diff --git a/build_scripts/export_adversarial_benchmark_result.py b/build_scripts/export_adversarial_benchmark_result.py index cfebb4460b..9550756f4f 100644 --- a/build_scripts/export_adversarial_benchmark_result.py +++ b/build_scripts/export_adversarial_benchmark_result.py @@ -34,7 +34,7 @@ async def _load_result_async(*, scenario_result_id: str) -> ScenarioResult: env_files=[], silent=True, ) - results = CentralMemory.get_memory_instance().get_scenario_results( + results = await CentralMemory.get_memory_instance().get_scenario_results_async( scenario_result_ids=[scenario_result_id], ) if not results: diff --git a/doc/code/datasets/1_loading_datasets.ipynb b/doc/code/datasets/1_loading_datasets.ipynb index c55310c52d..d838aade7f 100644 --- a/doc/code/datasets/1_loading_datasets.ipynb +++ b/doc/code/datasets/1_loading_datasets.ipynb @@ -360,7 +360,7 @@ "await memory.add_seed_datasets_to_memory_async(datasets=datasets, added_by=\"pyrit\")\n", "\n", "# Memory has flexible querying capabilities\n", - "memory.get_seeds(harm_categories=[\"illegal\"], seed_type=\"objective\")" + "(await memory.get_seeds_async(harm_categories=[\"illegal\"], seed_type=\"objective\"))" ] } ], diff --git a/doc/code/datasets/1_loading_datasets.py b/doc/code/datasets/1_loading_datasets.py index 385280085f..45ac1b789b 100644 --- a/doc/code/datasets/1_loading_datasets.py +++ b/doc/code/datasets/1_loading_datasets.py @@ -118,4 +118,4 @@ await memory.add_seed_datasets_to_memory_async(datasets=datasets, added_by="pyrit") # Memory has flexible querying capabilities -memory.get_seeds(harm_categories=["illegal"], seed_type="objective") +(await memory.get_seeds_async(harm_categories=["illegal"], seed_type="objective")) diff --git a/doc/code/executor/5_workflow.ipynb b/doc/code/executor/5_workflow.ipynb index f716836df1..a61215700d 100644 --- a/doc/code/executor/5_workflow.ipynb +++ b/doc/code/executor/5_workflow.ipynb @@ -775,7 +775,7 @@ "from pyrit.memory import CentralMemory\n", "\n", "memory = CentralMemory.get_memory_instance()\n", - "processing_response = memory.get_message_pieces(conversation_id=result.processing_conversation_id)\n", + "processing_response = await memory.get_message_pieces_async(conversation_id=result.processing_conversation_id)\n", "\n", "print(f\"Attack result status: {result.status}\")\n", "print(f\"Response from processing callback: {processing_response}\")" diff --git a/doc/code/executor/5_workflow.py b/doc/code/executor/5_workflow.py index 05dff672d3..21aa8e85b7 100644 --- a/doc/code/executor/5_workflow.py +++ b/doc/code/executor/5_workflow.py @@ -190,7 +190,7 @@ async def processing_callback_async() -> str: from pyrit.memory import CentralMemory memory = CentralMemory.get_memory_instance() -processing_response = memory.get_message_pieces(conversation_id=result.processing_conversation_id) +processing_response = await memory.get_message_pieces_async(conversation_id=result.processing_conversation_id) print(f"Attack result status: {result.status}") print(f"Response from processing callback: {processing_response}") diff --git a/doc/code/executor/6_benchmark.ipynb b/doc/code/executor/6_benchmark.ipynb index b2d099467b..e06e3f1923 100644 --- a/doc/code/executor/6_benchmark.ipynb +++ b/doc/code/executor/6_benchmark.ipynb @@ -565,7 +565,7 @@ "seed_prompts = SeedDataset.from_yaml_file(Path(DATASETS_PATH) / \"lexicons\" / \"fairness\" / \"gendered_professions.yaml\")\n", "await memory.add_seeds_to_memory_async(seeds=seed_prompts.prompts, added_by=\"airt\") # type: ignore\n", "\n", - "prompt_groups = memory.get_seed_groups(dataset_name=\"2025_08_airt_fairness_gendered_professions\")\n", + "prompt_groups = await memory.get_seed_groups_async(dataset_name=\"2025_08_airt_fairness_gendered_professions\")\n", "jobs = [prompt_group.prompts[0].value for prompt_group in prompt_groups]\n", "\n", "print(f\"Loaded {len(jobs)} professions\")" diff --git a/doc/code/executor/6_benchmark.py b/doc/code/executor/6_benchmark.py index 96f05be554..8b481aaf10 100644 --- a/doc/code/executor/6_benchmark.py +++ b/doc/code/executor/6_benchmark.py @@ -142,7 +142,7 @@ seed_prompts = SeedDataset.from_yaml_file(Path(DATASETS_PATH) / "lexicons" / "fairness" / "gendered_professions.yaml") await memory.add_seeds_to_memory_async(seeds=seed_prompts.prompts, added_by="airt") # type: ignore -prompt_groups = memory.get_seed_groups(dataset_name="2025_08_airt_fairness_gendered_professions") +prompt_groups = await memory.get_seed_groups_async(dataset_name="2025_08_airt_fairness_gendered_professions") jobs = [prompt_group.prompts[0].value for prompt_group in prompt_groups] print(f"Loaded {len(jobs)} professions") diff --git a/doc/code/executor/7_promptgen.ipynb b/doc/code/executor/7_promptgen.ipynb index 3a8e2d5e3b..585198cc4f 100644 --- a/doc/code/executor/7_promptgen.ipynb +++ b/doc/code/executor/7_promptgen.ipynb @@ -349,7 +349,7 @@ " prompt_templates=prompt_templates,\n", ")\n", "\n", - "FuzzerResultPrinter().print_result(result=result)" + "(await FuzzerResultPrinter().print_result_async(result=result))" ] } ], diff --git a/doc/code/executor/7_promptgen.py b/doc/code/executor/7_promptgen.py index f542294e17..2e0b1c243f 100644 --- a/doc/code/executor/7_promptgen.py +++ b/doc/code/executor/7_promptgen.py @@ -162,4 +162,4 @@ prompt_templates=prompt_templates, ) -FuzzerResultPrinter().print_result(result=result) +(await FuzzerResultPrinter().print_result_async(result=result)) diff --git a/doc/code/memory/0_memory.md b/doc/code/memory/0_memory.md index f736705752..c5a533b0c5 100644 --- a/doc/code/memory/0_memory.md +++ b/doc/code/memory/0_memory.md @@ -7,14 +7,32 @@ To simplify memory interaction, the `pyrit.memory.CentralMemory` class automatic **Manual Memory Setting**: At the beginning of each notebook, make sure to call: -``` -# Import initialize_pyrit_async -# Import the specific constant for the MemoryDatabaseType, or provide the literal value -from pyrit.setup import initialize_pyrit_async, IN_MEMORY, SQLITE, AZURE_SQL +```python +from pyrit.memory import CentralMemory +from pyrit.setup import IN_MEMORY, initialize_pyrit_async -await initialize_pyrit_async(memory_db_type: MemoryDatabaseType, memory_instance_kwargs: Any | None) +await initialize_pyrit_async(memory_db_type=IN_MEMORY) +memory = CentralMemory.get_memory_instance() +messages = await memory.get_conversation_messages_async(conversation_id="example") ``` +Use the `_async` memory methods in async code. The synchronous methods remain +available during deprecation. In-memory SQLite serializes transactions across +threads and event loops to prevent shared-cache table locks. + +Repeated initialization reuses the existing memory without running schema setup +again. Setup raises an error if `CentralMemory` and the requested backend singleton +disagree, or if setup tries to change an existing SQLite instance between in-memory +and persistent modes. + +Do not overlap synchronous and async sessions on the same event-loop thread. +In-memory SQLite raises an error instead of blocking that loop. Use async methods +for concurrent work on an event loop. + +Before an event loop stops, call `await memory.dispose_loop_resources_async()` +on that loop. After all memory work stops, call `await memory.dispose_engine_async()` +to close the remaining resources. + The `MemoryDatabaseType` is a `Literal` with 3 options: IN_MEMORY, SQLITE, AZURE_SQL. (Read more below) - `initialize_pyrit_async` takes the `MemoryDatabaseType` and an argument list (`memory_instance_kwargs`), to initialize the shared memory instance. diff --git a/doc/code/memory/1_sqlite_memory.ipynb b/doc/code/memory/1_sqlite_memory.ipynb index 640ecbae8f..2a32202913 100644 --- a/doc/code/memory/1_sqlite_memory.ipynb +++ b/doc/code/memory/1_sqlite_memory.ipynb @@ -149,7 +149,7 @@ "\n", "# Use in-memory database to avoid file corruption issues\n", "memory = SQLiteMemory(db_path=\":memory:\")\n", - "memory.print_schema()" + "(await memory.print_schema_async())" ] } ], diff --git a/doc/code/memory/1_sqlite_memory.py b/doc/code/memory/1_sqlite_memory.py index 12b70e5f95..f40ff7978a 100644 --- a/doc/code/memory/1_sqlite_memory.py +++ b/doc/code/memory/1_sqlite_memory.py @@ -21,4 +21,4 @@ # Use in-memory database to avoid file corruption issues memory = SQLiteMemory(db_path=":memory:") -memory.print_schema() +(await memory.print_schema_async()) diff --git a/doc/code/memory/2_basic_memory_programming.ipynb b/doc/code/memory/2_basic_memory_programming.ipynb index 58b560b26c..6230f866cc 100644 --- a/doc/code/memory/2_basic_memory_programming.ipynb +++ b/doc/code/memory/2_basic_memory_programming.ipynb @@ -51,11 +51,11 @@ "\n", "memory = SQLiteMemory(db_path=\":memory:\")\n", "\n", - "memory.add_message_to_memory(request=message_list[0].to_message())\n", - "memory.add_message_to_memory(request=message_list[1].to_message())\n", - "memory.add_message_to_memory(request=message_list[2].to_message())\n", + "(await memory.add_message_to_memory_async(request=message_list[0].to_message()))\n", + "(await memory.add_message_to_memory_async(request=message_list[1].to_message()))\n", + "(await memory.add_message_to_memory_async(request=message_list[2].to_message()))\n", "\n", - "entries = memory.get_conversation_messages(conversation_id=conversation_id)\n", + "entries = await memory.get_conversation_messages_async(conversation_id=conversation_id)\n", "\n", "for entry in entries:\n", " print(entry)" diff --git a/doc/code/memory/2_basic_memory_programming.py b/doc/code/memory/2_basic_memory_programming.py index 4099f08b32..04e2a7beae 100644 --- a/doc/code/memory/2_basic_memory_programming.py +++ b/doc/code/memory/2_basic_memory_programming.py @@ -38,11 +38,11 @@ memory = SQLiteMemory(db_path=":memory:") -memory.add_message_to_memory(request=message_list[0].to_message()) -memory.add_message_to_memory(request=message_list[1].to_message()) -memory.add_message_to_memory(request=message_list[2].to_message()) +(await memory.add_message_to_memory_async(request=message_list[0].to_message())) +(await memory.add_message_to_memory_async(request=message_list[1].to_message())) +(await memory.add_message_to_memory_async(request=message_list[2].to_message())) -entries = memory.get_conversation_messages(conversation_id=conversation_id) +entries = await memory.get_conversation_messages_async(conversation_id=conversation_id) for entry in entries: print(entry) diff --git a/doc/code/memory/5_advanced_memory.ipynb b/doc/code/memory/5_advanced_memory.ipynb index 7cefe0b502..d5c4ab18df 100644 --- a/doc/code/memory/5_advanced_memory.ipynb +++ b/doc/code/memory/5_advanced_memory.ipynb @@ -287,7 +287,7 @@ "from pyrit.prompt_target import TextTarget\n", "\n", "memory = CentralMemory.get_memory_instance()\n", - "prompts = memory.get_message_pieces(labels={\"prompt_group\": group1})\n", + "prompts = await memory.get_message_pieces_async(labels={\"prompt_group\": group1})\n", "\n", "# Print original values of queried message pieces (including responses)\n", "for piece in prompts:\n", @@ -387,7 +387,7 @@ " value=filter_target_class,\n", " )\n", "\n", - " target_class_pieces = memory.get_message_pieces(\n", + " target_class_pieces = await memory.get_message_pieces_async(\n", " identifier_filters=[target_class_filter],\n", " )\n", "\n", @@ -434,7 +434,7 @@ " partial_match=True,\n", ")\n", "\n", - "openai_pieces = memory.get_message_pieces(\n", + "openai_pieces = await memory.get_message_pieces_async(\n", " identifier_filters=[openai_filter],\n", ")\n", "\n", @@ -479,7 +479,7 @@ " value=\"Base64Converter\",\n", ")\n", "\n", - "base64_pieces = memory.get_message_pieces(\n", + "base64_pieces = await memory.get_message_pieces_async(\n", " identifier_filters=[converter_filter],\n", ")\n", "\n", @@ -522,7 +522,7 @@ " value=\"TextTarget\",\n", ")\n", "\n", - "combined_pieces = memory.get_message_pieces(\n", + "combined_pieces = await memory.get_message_pieces_async(\n", " identifier_filters=[text_target_filter, converter_filter],\n", ")\n", "\n", @@ -561,7 +561,7 @@ ], "source": [ "# Retrieve prompts from our labeled group that specifically went through Base64Converter\n", - "labeled_and_filtered = memory.get_message_pieces(\n", + "labeled_and_filtered = await memory.get_message_pieces_async(\n", " labels={\"prompt_group\": group1},\n", " identifier_filters=[converter_filter],\n", ")\n", @@ -613,7 +613,7 @@ ") # intentionally bad scorer that matches when the phrase 'assist' is present in response. But good for demo.\n", "\n", "# Retrieve assistant responses from Part 1\n", - "assistant_pieces = memory.get_message_pieces(\n", + "assistant_pieces = await memory.get_message_pieces_async(\n", " labels={\"prompt_group\": group1},\n", " role=\"assistant\",\n", ")\n", @@ -669,7 +669,7 @@ " value=\"SubStringScorer\",\n", ")\n", "\n", - "all_substring_scores = memory.get_scores(\n", + "all_substring_scores = await memory.get_scores_async(\n", " identifier_filters=[scorer_class_filter],\n", ")\n", "\n", @@ -722,7 +722,7 @@ " value=\"molotov\",\n", ")\n", "\n", - "molotov_scores = memory.get_scores(\n", + "molotov_scores = await memory.get_scores_async(\n", " identifier_filters=[molotov_scorer_filter],\n", ")\n", "\n", @@ -739,7 +739,7 @@ " value=\"launder\",\n", ")\n", "\n", - "launder_scores = memory.get_scores(\n", + "launder_scores = await memory.get_scores_async(\n", " identifier_filters=[launder_scorer_filter],\n", ")\n", "\n", @@ -756,7 +756,7 @@ " value=\"assist\",\n", ")\n", "\n", - "assist_scores = memory.get_scores(\n", + "assist_scores = await memory.get_scores_async(\n", " identifier_filters=[assist_scorer_filter],\n", ")\n", "\n", diff --git a/doc/code/memory/5_advanced_memory.py b/doc/code/memory/5_advanced_memory.py index a8e882100a..77d65445ec 100644 --- a/doc/code/memory/5_advanced_memory.py +++ b/doc/code/memory/5_advanced_memory.py @@ -73,7 +73,7 @@ from pyrit.prompt_target import TextTarget memory = CentralMemory.get_memory_instance() -prompts = memory.get_message_pieces(labels={"prompt_group": group1}) +prompts = await memory.get_message_pieces_async(labels={"prompt_group": group1}) # Print original values of queried message pieces (including responses) for piece in prompts: @@ -141,7 +141,7 @@ value=filter_target_class, ) - target_class_pieces = memory.get_message_pieces( + target_class_pieces = await memory.get_message_pieces_async( identifier_filters=[target_class_filter], ) @@ -164,7 +164,7 @@ partial_match=True, ) -openai_pieces = memory.get_message_pieces( +openai_pieces = await memory.get_message_pieces_async( identifier_filters=[openai_filter], ) @@ -187,7 +187,7 @@ value="Base64Converter", ) -base64_pieces = memory.get_message_pieces( +base64_pieces = await memory.get_message_pieces_async( identifier_filters=[converter_filter], ) @@ -208,7 +208,7 @@ value="TextTarget", ) -combined_pieces = memory.get_message_pieces( +combined_pieces = await memory.get_message_pieces_async( identifier_filters=[text_target_filter, converter_filter], ) @@ -225,7 +225,7 @@ # %% # Retrieve prompts from our labeled group that specifically went through Base64Converter -labeled_and_filtered = memory.get_message_pieces( +labeled_and_filtered = await memory.get_message_pieces_async( labels={"prompt_group": group1}, identifier_filters=[converter_filter], ) @@ -257,7 +257,7 @@ ) # intentionally bad scorer that matches when the phrase 'assist' is present in response. But good for demo. # Retrieve assistant responses from Part 1 -assistant_pieces = memory.get_message_pieces( +assistant_pieces = await memory.get_message_pieces_async( labels={"prompt_group": group1}, role="assistant", ) @@ -287,7 +287,7 @@ value="SubStringScorer", ) -all_substring_scores = memory.get_scores( +all_substring_scores = await memory.get_scores_async( identifier_filters=[scorer_class_filter], ) @@ -310,7 +310,7 @@ value="molotov", ) -molotov_scores = memory.get_scores( +molotov_scores = await memory.get_scores_async( identifier_filters=[molotov_scorer_filter], ) @@ -327,7 +327,7 @@ value="launder", ) -launder_scores = memory.get_scores( +launder_scores = await memory.get_scores_async( identifier_filters=[launder_scorer_filter], ) @@ -344,7 +344,7 @@ value="assist", ) -assist_scores = memory.get_scores( +assist_scores = await memory.get_scores_async( identifier_filters=[assist_scorer_filter], ) diff --git a/doc/code/memory/6_azure_sql_memory.ipynb b/doc/code/memory/6_azure_sql_memory.ipynb index 8532850c1f..cb47cacc20 100644 --- a/doc/code/memory/6_azure_sql_memory.ipynb +++ b/doc/code/memory/6_azure_sql_memory.ipynb @@ -120,7 +120,7 @@ "await initialize_pyrit_async(memory_db_type=AZURE_SQL) # type: ignore\n", "\n", "memory = CentralMemory.get_memory_instance()\n", - "memory.print_schema() # type: ignore" + "(await memory.print_schema_async()) # type: ignore" ] }, { @@ -170,11 +170,11 @@ " ),\n", "]\n", "\n", - "memory.add_message_to_memory(request=Message(message_pieces=[message_list[0]]))\n", - "memory.add_message_to_memory(request=Message(message_pieces=[message_list[1]]))\n", - "memory.add_message_to_memory(request=Message(message_pieces=[message_list[2]]))\n", + "(await memory.add_message_to_memory_async(request=Message(message_pieces=[message_list[0]])))\n", + "(await memory.add_message_to_memory_async(request=Message(message_pieces=[message_list[1]])))\n", + "(await memory.add_message_to_memory_async(request=Message(message_pieces=[message_list[2]])))\n", "\n", - "entries = memory.get_conversation_messages(conversation_id=conversation_id)\n", + "entries = await memory.get_conversation_messages_async(conversation_id=conversation_id)\n", "\n", "for entry in entries:\n", " print(entry)" diff --git a/doc/code/memory/6_azure_sql_memory.py b/doc/code/memory/6_azure_sql_memory.py index 3dc1c9a4fa..9a24cac028 100644 --- a/doc/code/memory/6_azure_sql_memory.py +++ b/doc/code/memory/6_azure_sql_memory.py @@ -45,7 +45,7 @@ await initialize_pyrit_async(memory_db_type=AZURE_SQL) # type: ignore memory = CentralMemory.get_memory_instance() -memory.print_schema() # type: ignore +(await memory.print_schema_async()) # type: ignore # %% [markdown] # ## Basic Azure SQL Memory Programming Usage @@ -73,11 +73,11 @@ ), ] -memory.add_message_to_memory(request=Message(message_pieces=[message_list[0]])) -memory.add_message_to_memory(request=Message(message_pieces=[message_list[1]])) -memory.add_message_to_memory(request=Message(message_pieces=[message_list[2]])) +(await memory.add_message_to_memory_async(request=Message(message_pieces=[message_list[0]]))) +(await memory.add_message_to_memory_async(request=Message(message_pieces=[message_list[1]]))) +(await memory.add_message_to_memory_async(request=Message(message_pieces=[message_list[2]]))) -entries = memory.get_conversation_messages(conversation_id=conversation_id) +entries = await memory.get_conversation_messages_async(conversation_id=conversation_id) for entry in entries: print(entry) diff --git a/doc/code/memory/8_seed_database.ipynb b/doc/code/memory/8_seed_database.ipynb index 85950592f4..ff6b852b96 100644 --- a/doc/code/memory/8_seed_database.ipynb +++ b/doc/code/memory/8_seed_database.ipynb @@ -94,12 +94,12 @@ "await memory.add_seed_datasets_to_memory_async(datasets=datasets, added_by=\"test\") # type: ignore\n", "\n", "# Retrieve the dataset from memory\n", - "seeds = memory.get_seeds(dataset_name=\"pyrit_example_dataset\")\n", + "seeds = await memory.get_seeds_async(dataset_name=\"pyrit_example_dataset\")\n", "print(f\"Number of prompts in dataset: {len(seeds)}\")\n", "\n", "# Note we can add it again without creating duplicates\n", "await memory.add_seed_datasets_to_memory_async(datasets=datasets, added_by=\"test\") # type: ignore\n", - "seeds = memory.get_seeds(dataset_name=\"pyrit_example_dataset\")\n", + "seeds = await memory.get_seeds_async(dataset_name=\"pyrit_example_dataset\")\n", "print(f\"Number of prompts in dataset after re-adding: {len(seeds)}\")" ] }, @@ -138,7 +138,7 @@ } ], "source": [ - "all_dataset_names = memory.get_seed_dataset_names()\n", + "all_dataset_names = await memory.get_seed_dataset_names_async()\n", "print(\"All dataset names in memory:\", all_dataset_names)" ] }, @@ -205,26 +205,28 @@ "\n", "\n", "# Get all seeds in the dataset we just uploaded\n", - "seed_groups = memory.get_seed_groups(dataset_name=\"pyrit_example_dataset\")\n", + "seed_groups = await memory.get_seed_groups_async(dataset_name=\"pyrit_example_dataset\")\n", "print(\"First seed from pyrit_example_dataset:\")\n", "print(\"----------\")\n", "print_group(seed_groups[0])\n", "\n", "# Filter by SeedObjectives\n", - "seed_groups = memory.get_seed_groups(dataset_name=\"pyrit_example_dataset\", seed_type=\"objective\", group_length=[1])\n", + "seed_groups = await memory.get_seed_groups_async(\n", + " dataset_name=\"pyrit_example_dataset\", seed_type=\"objective\", group_length=[1]\n", + ")\n", "print(\"First SeedObjective from pyrit_example_dataset without a seedprompt:\")\n", "print(\"----------\")\n", "print_group(seed_groups[0])\n", "\n", "# Filter by metadata to get seed prompts in .wav format and samplerate 24000 kBits/s\n", "print(\"First WAV seed in the database\")\n", - "seed_groups = memory.get_seed_groups(metadata={\"format\": \"wav\", \"samplerate\": 24000})\n", + "seed_groups = await memory.get_seed_groups_async(metadata={\"format\": \"wav\", \"samplerate\": 24000})\n", "print(\"----------\")\n", "print_group(seed_groups[0])\n", "\n", "# Filter by image seeds\n", "print(\"First image seed in the dataset\")\n", - "seed_groups = memory.get_seed_groups(data_types=[\"image_path\"], dataset_name=\"pyrit_example_dataset\")\n", + "seed_groups = await memory.get_seed_groups_async(data_types=[\"image_path\"], dataset_name=\"pyrit_example_dataset\")\n", "print(\"----------\")\n", "print_group(seed_groups[0])" ] @@ -259,15 +261,15 @@ ], "source": [ "# Preview the seeds that will be removed using the same filters\n", - "seeds_to_remove = memory.get_seeds(dataset_name=\"pyrit_example_dataset\")\n", + "seeds_to_remove = await memory.get_seeds_async(dataset_name=\"pyrit_example_dataset\")\n", "print(f\"Seeds matching the filter: {len(seeds_to_remove)}\")\n", "\n", "# Remove them and get back the number of seeds deleted\n", - "removed_count = memory.remove_seeds_from_memory(dataset_name=\"pyrit_example_dataset\")\n", + "removed_count = await memory.remove_seeds_from_memory_async(dataset_name=\"pyrit_example_dataset\")\n", "print(f\"Removed {removed_count} seeds\")\n", "\n", "# Confirm they are gone\n", - "seeds = memory.get_seeds(dataset_name=\"pyrit_example_dataset\")\n", + "seeds = await memory.get_seeds_async(dataset_name=\"pyrit_example_dataset\")\n", "print(f\"Seeds remaining in dataset: {len(seeds)}\")" ] }, diff --git a/doc/code/memory/8_seed_database.py b/doc/code/memory/8_seed_database.py index 158d0f50f1..8364aded86 100644 --- a/doc/code/memory/8_seed_database.py +++ b/doc/code/memory/8_seed_database.py @@ -48,12 +48,12 @@ await memory.add_seed_datasets_to_memory_async(datasets=datasets, added_by="test") # type: ignore # Retrieve the dataset from memory -seeds = memory.get_seeds(dataset_name="pyrit_example_dataset") +seeds = await memory.get_seeds_async(dataset_name="pyrit_example_dataset") print(f"Number of prompts in dataset: {len(seeds)}") # Note we can add it again without creating duplicates await memory.add_seed_datasets_to_memory_async(datasets=datasets, added_by="test") # type: ignore -seeds = memory.get_seeds(dataset_name="pyrit_example_dataset") +seeds = await memory.get_seeds_async(dataset_name="pyrit_example_dataset") print(f"Number of prompts in dataset after re-adding: {len(seeds)}") # %% [markdown] @@ -67,7 +67,7 @@ # The example below shows the dataset we just uploaded (`pyrit_example_dataset`), but `get_seed_dataset_names()` returns all datasets in memory. # %% -all_dataset_names = memory.get_seed_dataset_names() +all_dataset_names = await memory.get_seed_dataset_names_async() print("All dataset names in memory:", all_dataset_names) # %% [markdown] @@ -91,26 +91,28 @@ def print_group(seed_group): # Get all seeds in the dataset we just uploaded -seed_groups = memory.get_seed_groups(dataset_name="pyrit_example_dataset") +seed_groups = await memory.get_seed_groups_async(dataset_name="pyrit_example_dataset") print("First seed from pyrit_example_dataset:") print("----------") print_group(seed_groups[0]) # Filter by SeedObjectives -seed_groups = memory.get_seed_groups(dataset_name="pyrit_example_dataset", seed_type="objective", group_length=[1]) +seed_groups = await memory.get_seed_groups_async( + dataset_name="pyrit_example_dataset", seed_type="objective", group_length=[1] +) print("First SeedObjective from pyrit_example_dataset without a seedprompt:") print("----------") print_group(seed_groups[0]) # Filter by metadata to get seed prompts in .wav format and samplerate 24000 kBits/s print("First WAV seed in the database") -seed_groups = memory.get_seed_groups(metadata={"format": "wav", "samplerate": 24000}) +seed_groups = await memory.get_seed_groups_async(metadata={"format": "wav", "samplerate": 24000}) print("----------") print_group(seed_groups[0]) # Filter by image seeds print("First image seed in the dataset") -seed_groups = memory.get_seed_groups(data_types=["image_path"], dataset_name="pyrit_example_dataset") +seed_groups = await memory.get_seed_groups_async(data_types=["image_path"], dataset_name="pyrit_example_dataset") print("----------") print_group(seed_groups[0]) @@ -123,15 +125,15 @@ def print_group(seed_group): # %% # Preview the seeds that will be removed using the same filters -seeds_to_remove = memory.get_seeds(dataset_name="pyrit_example_dataset") +seeds_to_remove = await memory.get_seeds_async(dataset_name="pyrit_example_dataset") print(f"Seeds matching the filter: {len(seeds_to_remove)}") # Remove them and get back the number of seeds deleted -removed_count = memory.remove_seeds_from_memory(dataset_name="pyrit_example_dataset") +removed_count = await memory.remove_seeds_from_memory_async(dataset_name="pyrit_example_dataset") print(f"Removed {removed_count} seeds") # Confirm they are gone -seeds = memory.get_seeds(dataset_name="pyrit_example_dataset") +seeds = await memory.get_seeds_async(dataset_name="pyrit_example_dataset") print(f"Seeds remaining in dataset: {len(seeds)}") # %% [markdown] diff --git a/doc/code/output/0_output.ipynb b/doc/code/output/0_output.ipynb index b63fe4d3c3..015717c68b 100644 --- a/doc/code/output/0_output.ipynb +++ b/doc/code/output/0_output.ipynb @@ -502,7 +502,7 @@ "from pyrit.output import output_conversation_async\n", "\n", "# get the conversation from memory using the conversation id from the attack result\n", - "conversation = memory.get_conversation_messages(conversation_id=attack_result.conversation_id)\n", + "conversation = await memory.get_conversation_messages_async(conversation_id=attack_result.conversation_id)\n", "\n", "# print the conversation using the print conversation helper\n", "await output_conversation_async(messages=conversation) # type: ignore" diff --git a/doc/code/output/0_output.py b/doc/code/output/0_output.py index 3e0d8e578d..924b480df8 100644 --- a/doc/code/output/0_output.py +++ b/doc/code/output/0_output.py @@ -137,7 +137,7 @@ from pyrit.output import output_conversation_async # get the conversation from memory using the conversation id from the attack result -conversation = memory.get_conversation_messages(conversation_id=attack_result.conversation_id) +conversation = await memory.get_conversation_messages_async(conversation_id=attack_result.conversation_id) # print the conversation using the print conversation helper await output_conversation_async(messages=conversation) # type: ignore diff --git a/doc/code/scoring/0_scoring.ipynb b/doc/code/scoring/0_scoring.ipynb index 9a4cc7c666..492236592e 100644 --- a/doc/code/scoring/0_scoring.ipynb +++ b/doc/code/scoring/0_scoring.ipynb @@ -482,13 +482,13 @@ "memory = CentralMemory.get_memory_instance()\n", "prompt_ids = []\n", "for r in results:\n", - " prompt_ids.extend(str(p.id) for p in memory.get_message_pieces(conversation_id=r.conversation_id))\n", + " prompt_ids.extend(str(p.id) for p in (await memory.get_message_pieces_async(conversation_id=r.conversation_id)))\n", "\n", "batch_scorer = BatchScorer()\n", "scores = await batch_scorer.score_responses_by_filters_async(scorer=scorer, prompt_ids=prompt_ids) # type: ignore\n", "\n", "for score in scores:\n", - " text = memory.get_message_pieces(prompt_ids=[str(score.message_piece_id)])[0].original_value\n", + " text = (await memory.get_message_pieces_async(prompt_ids=[str(score.message_piece_id)]))[0].original_value\n", " print(f\"{score.get_value()} : {text}\")" ] } diff --git a/doc/code/scoring/0_scoring.py b/doc/code/scoring/0_scoring.py index dd4c709bec..73eba0ad35 100644 --- a/doc/code/scoring/0_scoring.py +++ b/doc/code/scoring/0_scoring.py @@ -252,11 +252,11 @@ memory = CentralMemory.get_memory_instance() prompt_ids = [] for r in results: - prompt_ids.extend(str(p.id) for p in memory.get_message_pieces(conversation_id=r.conversation_id)) + prompt_ids.extend(str(p.id) for p in (await memory.get_message_pieces_async(conversation_id=r.conversation_id))) batch_scorer = BatchScorer() scores = await batch_scorer.score_responses_by_filters_async(scorer=scorer, prompt_ids=prompt_ids) # type: ignore for score in scores: - text = memory.get_message_pieces(prompt_ids=[str(score.message_piece_id)])[0].original_value + text = (await memory.get_message_pieces_async(prompt_ids=[str(score.message_piece_id)]))[0].original_value print(f"{score.get_value()} : {text}") diff --git a/doc/code/scoring/2_float_scale_scorers.ipynb b/doc/code/scoring/2_float_scale_scorers.ipynb index a152300600..2e70400ec1 100644 --- a/doc/code/scoring/2_float_scale_scorers.ipynb +++ b/doc/code/scoring/2_float_scale_scorers.ipynb @@ -120,7 +120,7 @@ " ]\n", ")\n", "# The score table has a foreign key on the message, so write it to memory first.\n", - "CentralMemory.get_memory_instance().add_message_to_memory(request=response)\n", + "(await CentralMemory.get_memory_instance().add_message_to_memory_async(request=response))\n", "\n", "scores = await azure_content_filter.score_async(scorable=MessageScorable.from_message(response)) # type: ignore\n", "for score in scores:\n", @@ -207,15 +207,17 @@ "leaked_response = f\"My system prompt says: {system_prompt}\"\n", "\n", "memory = CentralMemory.get_memory_instance()\n", - "memory.add_message_to_memory(\n", - " request=Message(\n", - " message_pieces=[MessagePiece(role=\"system\", original_value=system_prompt, conversation_id=conversation_id)]\n", + "(\n", + " await memory.add_message_to_memory_async(\n", + " request=Message(\n", + " message_pieces=[MessagePiece(role=\"system\", original_value=system_prompt, conversation_id=conversation_id)]\n", + " )\n", " )\n", ")\n", "response = Message(\n", " message_pieces=[MessagePiece(role=\"assistant\", original_value=leaked_response, conversation_id=conversation_id)]\n", ")\n", - "memory.add_message_to_memory(request=response)\n", + "(await memory.add_message_to_memory_async(request=response))\n", "\n", "system_prompt_scorer = SystemPromptExtractionScorer()\n", "leak_score = (await system_prompt_scorer.score_message_async(message=response))[0] # type: ignore\n", @@ -445,7 +447,7 @@ " execute_sql(sql)\n", "\"\"\"\n", "request = MessagePiece(role=\"assistant\", original_value=snippet, conversation_id=str(uuid4())).to_message()\n", - "insecure_code_scorer._memory.add_message_to_memory(request=request)\n", + "(await insecure_code_scorer._memory.add_message_to_memory_async(request=request))\n", "\n", "scored = (await insecure_code_scorer.score_async(scorable=MessageScorable.from_message(request)))[0] # type: ignore\n", "print(f\"[insecure code] risk={scored.get_value()}\")\n", diff --git a/doc/code/scoring/2_float_scale_scorers.py b/doc/code/scoring/2_float_scale_scorers.py index 41d1e97665..5a6e3dc241 100644 --- a/doc/code/scoring/2_float_scale_scorers.py +++ b/doc/code/scoring/2_float_scale_scorers.py @@ -62,7 +62,7 @@ ] ) # The score table has a foreign key on the message, so write it to memory first. -CentralMemory.get_memory_instance().add_message_to_memory(request=response) +(await CentralMemory.get_memory_instance().add_message_to_memory_async(request=response)) scores = await azure_content_filter.score_async(scorable=MessageScorable.from_message(response)) # type: ignore for score in scores: @@ -102,15 +102,17 @@ leaked_response = f"My system prompt says: {system_prompt}" memory = CentralMemory.get_memory_instance() -memory.add_message_to_memory( - request=Message( - message_pieces=[MessagePiece(role="system", original_value=system_prompt, conversation_id=conversation_id)] +( + await memory.add_message_to_memory_async( + request=Message( + message_pieces=[MessagePiece(role="system", original_value=system_prompt, conversation_id=conversation_id)] + ) ) ) response = Message( message_pieces=[MessagePiece(role="assistant", original_value=leaked_response, conversation_id=conversation_id)] ) -memory.add_message_to_memory(request=response) +(await memory.add_message_to_memory_async(request=response)) system_prompt_scorer = SystemPromptExtractionScorer() leak_score = (await system_prompt_scorer.score_message_async(message=response))[0] # type: ignore @@ -235,7 +237,7 @@ def authenticate_user(username, password): execute_sql(sql) """ request = MessagePiece(role="assistant", original_value=snippet, conversation_id=str(uuid4())).to_message() -insecure_code_scorer._memory.add_message_to_memory(request=request) +(await insecure_code_scorer._memory.add_message_to_memory_async(request=request)) scored = (await insecure_code_scorer.score_async(scorable=MessageScorable.from_message(request)))[0] # type: ignore print(f"[insecure code] risk={scored.get_value()}") diff --git a/doc/code/scoring/3_combining_scorers.ipynb b/doc/code/scoring/3_combining_scorers.ipynb index abc38bd814..85ab20b035 100644 --- a/doc/code/scoring/3_combining_scorers.ipynb +++ b/doc/code/scoring/3_combining_scorers.ipynb @@ -394,7 +394,7 @@ " MessagePiece(role=\"assistant\", original_value=\"Okay, yes I am AI.\", conversation_id=conversation_id).to_message(),\n", "]\n", "for turn in turns:\n", - " memory.add_message_to_memory(request=turn)\n", + " (await memory.add_message_to_memory_async(request=turn))\n", "\n", "persona_breach_scorer = SubStringScorer(substring=\"I am AI\", categories=[\"persona_breach\"])\n", "conversation_scorer = create_conversation_scorer(scorer=persona_breach_scorer)\n", diff --git a/doc/code/scoring/3_combining_scorers.py b/doc/code/scoring/3_combining_scorers.py index 664050ec66..4508dd4365 100644 --- a/doc/code/scoring/3_combining_scorers.py +++ b/doc/code/scoring/3_combining_scorers.py @@ -253,7 +253,7 @@ MessagePiece(role="assistant", original_value="Okay, yes I am AI.", conversation_id=conversation_id).to_message(), ] for turn in turns: - memory.add_message_to_memory(request=turn) + (await memory.add_message_to_memory_async(request=turn)) persona_breach_scorer = SubStringScorer(substring="I am AI", categories=["persona_breach"]) conversation_scorer = create_conversation_scorer(scorer=persona_breach_scorer) diff --git a/doc/code/scoring/5_tool_call_scorer.ipynb b/doc/code/scoring/5_tool_call_scorer.ipynb index 10f3fa7b87..79b405599a 100644 --- a/doc/code/scoring/5_tool_call_scorer.ipynb +++ b/doc/code/scoring/5_tool_call_scorer.ipynb @@ -187,7 +187,7 @@ } ], "source": [ - "saved = memory.get_observations(observation_ids=negative.observation_ids)[0]\n", + "saved = (await memory.get_observations_async(observation_ids=negative.observation_ids))[0]\n", "assert saved.scorable == scope\n", "before_replay = saved.model_dump_json()\n", "await asyncio.to_thread(provider.shutdown) # type: ignore\n", @@ -196,7 +196,9 @@ "replayed = (await scorer.score_observation_async(observation=saved, expectation=expects(\"my_tool_call\")))[0] # type: ignore\n", "assert replayed.get_value() is True\n", "assert replayed.observation_ids == negative.observation_ids\n", - "assert memory.get_observations(observation_ids=negative.observation_ids)[0].model_dump_json() == before_replay\n", + "assert (await memory.get_observations_async(observation_ids=negative.observation_ids))[\n", + " 0\n", + "].model_dump_json() == before_replay\n", "print(f\"my_tool_call in saved evidence after capture is closed: {replayed.get_value()}\")" ] }, @@ -331,7 +333,7 @@ ")\n", "assert result.outcome is AttackOutcome.SUCCESS\n", "print(f\"Message and tool evidence: {result.outcome.value}\")\n", - "saved = memory.get_observations(observation_ids=result.automated_score.observation_ids)[0]\n", + "saved = (await memory.get_observations_async(observation_ids=result.automated_score.observation_ids))[0]\n", "await asyncio.to_thread(provider.shutdown) # type: ignore\n", "client.close()\n", "replayed = ( # type: ignore\n", @@ -339,7 +341,7 @@ ")[0]\n", "assert replayed.get_value() is True\n", "print(f\"Saved attack tool evidence: {replayed.get_value()}\")\n", - "memory.dispose_engine()" + "(await memory.dispose_engine_async())" ] }, { diff --git a/doc/code/scoring/5_tool_call_scorer.py b/doc/code/scoring/5_tool_call_scorer.py index 996124a9ff..3682b84f27 100644 --- a/doc/code/scoring/5_tool_call_scorer.py +++ b/doc/code/scoring/5_tool_call_scorer.py @@ -124,7 +124,7 @@ def my_tool_call() -> str: # have their stricter, original-expectation replay rules. # %% -saved = memory.get_observations(observation_ids=negative.observation_ids)[0] +saved = (await memory.get_observations_async(observation_ids=negative.observation_ids))[0] assert saved.scorable == scope before_replay = saved.model_dump_json() await asyncio.to_thread(provider.shutdown) # type: ignore @@ -133,7 +133,9 @@ def my_tool_call() -> str: replayed = (await scorer.score_observation_async(observation=saved, expectation=expects("my_tool_call")))[0] # type: ignore assert replayed.get_value() is True assert replayed.observation_ids == negative.observation_ids -assert memory.get_observations(observation_ids=negative.observation_ids)[0].model_dump_json() == before_replay +assert (await memory.get_observations_async(observation_ids=negative.observation_ids))[ + 0 +].model_dump_json() == before_replay print(f"my_tool_call in saved evidence after capture is closed: {replayed.get_value()}") # %% [markdown] @@ -225,7 +227,7 @@ async def local_agent_async(request: httpx.Request) -> httpx.Response: ) assert result.outcome is AttackOutcome.SUCCESS print(f"Message and tool evidence: {result.outcome.value}") -saved = memory.get_observations(observation_ids=result.automated_score.observation_ids)[0] +saved = (await memory.get_observations_async(observation_ids=result.automated_score.observation_ids))[0] await asyncio.to_thread(provider.shutdown) # type: ignore client.close() replayed = ( # type: ignore @@ -233,7 +235,7 @@ async def local_agent_async(request: httpx.Request) -> httpx.Response: )[0] assert replayed.get_value() is True print(f"Saved attack tool evidence: {replayed.get_value()}") -memory.dispose_engine() +(await memory.dispose_engine_async()) # %% [markdown] # ## Configure tracing diff --git a/pyproject.toml b/pyproject.toml index 7023bfeb09..7b62a2bb25 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,8 @@ classifiers = [ requires-python = ">=3.11, <3.15" dependencies = [ "aiofiles>=24,<26", + "aioodbc>=0.5.0", + "aiosqlite>=0.21.0", "alembic>=1.16.0", "appdirs>=1.4.0", "art>=6.5.0", @@ -62,7 +64,7 @@ dependencies = [ "reportlab>=4.4.4", "segno>=1.6.6", "scipy>=1.15.3", - "SQLAlchemy>=2.0.41", + "SQLAlchemy[asyncio]>=2.0.41", "starlette>=1.0.1", "termcolor>=2.4.0", "tenacity>=9.1.2", diff --git a/pyrit/analytics/__init__.py b/pyrit/analytics/__init__.py index bbbd1def2b..4e3b933261 100644 --- a/pyrit/analytics/__init__.py +++ b/pyrit/analytics/__init__.py @@ -10,7 +10,12 @@ if TYPE_CHECKING: from pyrit.analytics.conversation_analytics import ConversationAnalytics - from pyrit.analytics.result_analysis import AttackStats, analyze_results, get_cached_results_for_technique + from pyrit.analytics.result_analysis import ( + AttackStats, + analyze_results, + get_cached_results_for_technique, + get_cached_results_for_technique_async, + ) from pyrit.analytics.text_matching import ApproximateTextMatching, ExactTextMatching, TextMatching _LAZY_EXPORTS: dict[str, str | tuple[str, str | None]] = { @@ -20,6 +25,7 @@ "ConversationAnalytics": "pyrit.analytics.conversation_analytics", "ExactTextMatching": "pyrit.analytics.text_matching", "get_cached_results_for_technique": "pyrit.analytics.result_analysis", + "get_cached_results_for_technique_async": "pyrit.analytics.result_analysis", "TextMatching": "pyrit.analytics.text_matching", } diff --git a/pyrit/analytics/conversation_analytics.py b/pyrit/analytics/conversation_analytics.py index b85d7af8e9..3ed186b172 100644 --- a/pyrit/analytics/conversation_analytics.py +++ b/pyrit/analytics/conversation_analytics.py @@ -3,6 +3,8 @@ import numpy as np +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.memory.memory_interface import MemoryInterface from pyrit.memory.memory_models import ( ConversationMessageWithSimilarity, @@ -38,6 +40,11 @@ def get_prompt_entries_with_same_converted_content( list[ConversationMessageWithSimilarity]: A list of ConversationMessageWithSimilarity objects representing the similar chat messages based on content. """ + print_deprecation_message( + old_item="ConversationAnalytics.get_prompt_entries_with_same_converted_content", + new_item="ConversationAnalytics.get_prompt_entries_with_same_converted_content_async", + removed_in="1.4.0", + ) all_memories = self.memory_interface.get_message_pieces() return [ ConversationMessageWithSimilarity( @@ -50,6 +57,32 @@ def get_prompt_entries_with_same_converted_content( if memory.converted_value == chat_message_content ] + @legacy_sync_override(lambda: ConversationAnalytics.get_prompt_entries_with_same_converted_content) + async def get_prompt_entries_with_same_converted_content_async( + self, *, chat_message_content: str + ) -> list[ConversationMessageWithSimilarity]: + """ + Retrieve chat messages that have the same converted content. + + Args: + chat_message_content (str): The content of the chat message to find similar messages for. + + Returns: + list[ConversationMessageWithSimilarity]: A list of ConversationMessageWithSimilarity objects representing + the similar chat messages based on content. + """ + all_memories = await self.memory_interface.get_message_pieces_async() + return [ + ConversationMessageWithSimilarity( + score=1.0, + role=memory.api_role, + content=memory.converted_value, + metric="exact_match", # Exact match + ) + for memory in all_memories + if memory.converted_value == chat_message_content + ] + def get_similar_chat_messages_by_embedding( self, *, chat_message_embedding: list[float], threshold: float = 0.8 ) -> list[EmbeddingMessageWithSimilarity]: @@ -64,6 +97,11 @@ def get_similar_chat_messages_by_embedding( list[ConversationMessageWithSimilarity]: A list of ConversationMessageWithSimilarity objects representing the similar chat messages based on embedding similarity. """ + print_deprecation_message( + old_item="ConversationAnalytics.get_similar_chat_messages_by_embedding", + new_item="ConversationAnalytics.get_similar_chat_messages_by_embedding_async", + removed_in="1.4.0", + ) all_embdedding_memory = self.memory_interface.get_all_embeddings() similar_messages = [] @@ -85,6 +123,42 @@ def get_similar_chat_messages_by_embedding( return similar_messages + @legacy_sync_override(lambda: ConversationAnalytics.get_similar_chat_messages_by_embedding) + async def get_similar_chat_messages_by_embedding_async( + self, *, chat_message_embedding: list[float], threshold: float = 0.8 + ) -> list[EmbeddingMessageWithSimilarity]: + """ + Retrieve chat messages that are similar to the given embedding based on cosine similarity. + + Args: + chat_message_embedding (list[float]): The embedding of the chat message to find similar messages for. + threshold (float): The similarity threshold for considering messages as similar. Defaults to 0.8. + + Returns: + list[ConversationMessageWithSimilarity]: A list of ConversationMessageWithSimilarity objects representing + the similar chat messages based on embedding similarity. + """ + all_embdedding_memory = await self.memory_interface.get_all_embeddings_async() + similar_messages = [] + + target_embedding = np.array(chat_message_embedding).reshape(-1) + + for memory in all_embdedding_memory: + if not hasattr(memory, "embedding") or memory.embedding is None: + continue + + memory_embedding = np.array(memory.embedding).reshape(-1) + similarity_score = cosine_similarity(target_embedding, memory_embedding) + + if similarity_score >= threshold: + similar_messages.append( + EmbeddingMessageWithSimilarity( + score=float(similarity_score), uuid=memory.id, metric="cosine_similarity" + ) + ) + + return similar_messages + def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float: """ diff --git a/pyrit/analytics/result_analysis.py b/pyrit/analytics/result_analysis.py index f99184c183..4106fbadb0 100644 --- a/pyrit/analytics/result_analysis.py +++ b/pyrit/analytics/result_analysis.py @@ -5,6 +5,7 @@ from collections.abc import Sequence from typing import TYPE_CHECKING +from pyrit.common.deprecation import print_deprecation_message from pyrit.models import ( AttackOutcome, AttackResult, @@ -17,6 +18,8 @@ if TYPE_CHECKING: from pyrit.memory.memory_interface import MemoryInterface +_SYNC_API_REMOVAL_VERSION = "1.4.0" + def _compute_stats(successes: int, failures: int, undetermined: int, errors: int) -> AttackStats: total_decided = successes + failures @@ -140,6 +143,11 @@ def get_cached_results_for_technique( list[AttackResult]: Matching attack results sorted newest-first. Empty list if no cache hit. """ + print_deprecation_message( + old_item="get_cached_results_for_technique", + new_item="get_cached_results_for_technique_async", + removed_in=_SYNC_API_REMOVAL_VERSION, + ) filters: list[IdentifierFilter] = [ IdentifierFilter( identifier_type=IdentifierType.ATTACK, @@ -158,6 +166,63 @@ def get_cached_results_for_technique( return matches +async def get_cached_results_for_technique_async( + memory_interface: "MemoryInterface", + *, + technique_eval_hash: str, + objective_target_eval_hash: str, + additional_filters: Sequence[IdentifierFilter] | None = None, +) -> list[AttackResult]: + """ + Return cached AttackResults matching a (technique × objective target) pair. + + Memory is queried for AttackResults whose stamped + ``atomic_attack_identifier.eval_hash`` equals ``technique_eval_hash``, + then results are filtered in Python to those whose nested objective + target produces the requested ``objective_target_eval_hash`` (computed + via ``ObjectiveTargetEvaluationIdentifier``). Returned results are sorted + newest-first by ``timestamp`` so the most recent is at index 0. + + No scenario scoping is applied; this is a behavioral cache spanning every + run that produced the same (technique × target) combination. Callers that + need scenario-level scoping should pass additional ``IdentifierFilter``s + or filter the returned list themselves. + + Args: + memory_interface (MemoryInterface): The memory interface to query. + Analytics is stateless, so callers (e.g. scenarios) must pass + their own ``CentralMemory.get_memory_instance()``. + technique_eval_hash (str): Behavioral eval hash of the atomic-attack + technique, as produced by ``AtomicAttackEvaluationIdentifier.eval_hash`` + (also exposed as ``AtomicAttack.technique_eval_hash``). + objective_target_eval_hash (str): Behavioral eval hash of the objective + target, as produced by ``ObjectiveTargetEvaluationIdentifier.eval_hash``. + additional_filters (Sequence[IdentifierFilter] | None): Extra + ``IdentifierFilter`` predicates appended to the SQL pre-filter. + Defaults to None. + + Returns: + list[AttackResult]: Matching attack results sorted newest-first. + Empty list if no cache hit. + """ + filters: list[IdentifierFilter] = [ + IdentifierFilter( + identifier_type=IdentifierType.ATTACK, + property_path="$.eval_hash", + value=technique_eval_hash, + ), + ] + if additional_filters: + filters.extend(additional_filters) + + candidates = await memory_interface.get_attack_results_async(identifier_filters=filters) + + matches = [result for result in candidates if _objective_target_eval_hash_for(result) == objective_target_eval_hash] + + matches.sort(key=lambda r: r.timestamp, reverse=True) + return matches + + def _objective_target_eval_hash_for(attack_result: AttackResult) -> str | None: """ Return the ObjectiveTargetEvaluationIdentifier eval hash for a result. diff --git a/pyrit/analytics/technique_analysis.py b/pyrit/analytics/technique_analysis.py index b892946113..c0ebf7b1ac 100644 --- a/pyrit/analytics/technique_analysis.py +++ b/pyrit/analytics/technique_analysis.py @@ -8,8 +8,9 @@ from typing import TYPE_CHECKING from pyrit.analytics.result_analysis import AttackStats, _compute_stats +from pyrit.common.deprecation import print_deprecation_message from pyrit.memory import CentralMemory -from pyrit.models import AttackOutcome +from pyrit.models import AttackOutcome, AttackResult if TYPE_CHECKING: from collections.abc import Sequence @@ -49,6 +50,11 @@ def compute_technique_stats( dict[str, AttackStats]: Stats per technique eval hash. Hashes with no historical results are omitted from the result. """ + print_deprecation_message( + old_item="compute_technique_stats", + new_item="compute_technique_stats_async", + removed_in="1.4.0", + ) if not technique_eval_hashes: return {} @@ -60,6 +66,58 @@ def compute_technique_stats( targeted_harm_categories=targeted_harm_categories, ) + return _aggregate_technique_stats(results=results, technique_eval_hashes=technique_eval_hashes) + + +async def compute_technique_stats_async( + *, + technique_eval_hashes: Sequence[str], + scenario_result_id: str | None = None, + targeted_harm_categories: Sequence[str] | None = None, + memory: MemoryInterface | None = None, +) -> dict[str, AttackStats]: + """ + Compute per-technique outcome statistics from persisted attack results. + + Queries memory for all ``AttackResult`` rows whose + ``atomic_attack_identifier.eval_hash`` matches one of + ``technique_eval_hashes``, then aggregates outcomes into per-technique + ``AttackStats``. The eval hash is auto-stamped on every persisted result + by ``AtomicAttackEvaluationIdentifier`` and is the canonical primitive + for behavioral-equivalence aggregation (seeds excluded, scorer excluded, + only behavior-relevant target params included). + + Args: + technique_eval_hashes (Sequence[str]): Eval hashes to aggregate. + Returned dict is keyed by these. + scenario_result_id (str | None): Restrict to a single scenario run. + Defaults to ``None`` (aggregate across all runs). + targeted_harm_categories (Sequence[str] | None): Restrict to results + whose attack targeted these harm categories. Defaults to ``None``. + memory (MemoryInterface | None): Memory backend to query. Defaults to + ``CentralMemory.get_memory_instance()``. + + Returns: + dict[str, AttackStats]: Stats per technique eval hash. Hashes with no + historical results are omitted from the result. + """ + if not technique_eval_hashes: + return {} + + if memory is None: + memory = CentralMemory.get_memory_instance() + results = await memory.get_attack_results_async( + atomic_attack_eval_hashes=list(technique_eval_hashes), + scenario_result_id=scenario_result_id, + targeted_harm_categories=targeted_harm_categories, + ) + + return _aggregate_technique_stats(results=results, technique_eval_hashes=technique_eval_hashes) + + +def _aggregate_technique_stats( + *, results: Sequence[AttackResult], technique_eval_hashes: Sequence[str] +) -> dict[str, AttackStats]: requested = set(technique_eval_hashes) counts: dict[str, tuple[int, int, int, int]] = {} for result in results: @@ -68,17 +126,18 @@ def compute_technique_stats( if eval_hash is None or eval_hash not in requested: continue - s, f, u, e = counts.get(eval_hash, (0, 0, 0, 0)) + successes, failures, undetermined, errors = counts.get(eval_hash, (0, 0, 0, 0)) if result.outcome == AttackOutcome.SUCCESS: - counts[eval_hash] = (s + 1, f, u, e) + successes += 1 elif result.outcome == AttackOutcome.FAILURE: - counts[eval_hash] = (s, f + 1, u, e) + failures += 1 elif result.outcome == AttackOutcome.ERROR: - counts[eval_hash] = (s, f, u, e + 1) + errors += 1 else: - counts[eval_hash] = (s, f, u + 1, e) + undetermined += 1 + counts[eval_hash] = (successes, failures, undetermined, errors) return { - eval_hash: _compute_stats(successes=s, failures=f, undetermined=u, errors=e) - for eval_hash, (s, f, u, e) in counts.items() + eval_hash: _compute_stats(successes=successes, failures=failures, undetermined=undetermined, errors=errors) + for eval_hash, (successes, failures, undetermined, errors) in counts.items() } diff --git a/pyrit/auth/azure_auth.py b/pyrit/auth/azure_auth.py index e60bee7de8..b71616ec8e 100644 --- a/pyrit/auth/azure_auth.py +++ b/pyrit/auth/azure_auth.py @@ -213,6 +213,28 @@ async def async_token_provider() -> str: # pyrit-async-suffix-exempt return async_token_provider +class AsyncAzureAuth: + """Own an async Azure credential for one event loop.""" + + def __init__(self, token_scope: str) -> None: + """Configure the scope without retrieving a token.""" + self._token_scope = token_scope + self._credential = AsyncDefaultAzureCredential() + + async def get_access_token_async(self) -> AccessToken: + """ + Retrieve or refresh the credential's cached token. + + Returns: + AccessToken: The token for the configured scope. + """ + return await self._credential.get_token(self._token_scope) + + async def close_async(self) -> None: + """Close the credential before its event loop stops.""" + await self._credential.close() + + class AzureAuth(Authenticator): """ Azure CLI Authentication. diff --git a/pyrit/backend/mappers/attack_mappers.py b/pyrit/backend/mappers/attack_mappers.py index 2043be0d2e..89ed0b1779 100644 --- a/pyrit/backend/mappers/attack_mappers.py +++ b/pyrit/backend/mappers/attack_mappers.py @@ -11,7 +11,6 @@ from __future__ import annotations -import asyncio import logging import time import uuid @@ -345,7 +344,7 @@ async def _fetch_scores_by_piece_async( return {} memory = CentralMemory.get_memory_instance() - fetched = await asyncio.to_thread(memory.get_prompt_scores, prompt_ids=score_lookup_ids) + fetched = await memory.get_prompt_scores_async(prompt_ids=score_lookup_ids) grouped: dict[str, list[Score]] = {} for score in fetched: diff --git a/pyrit/backend/routes/labels.py b/pyrit/backend/routes/labels.py index 520192e9f4..d72ed505f9 100644 --- a/pyrit/backend/routes/labels.py +++ b/pyrit/backend/routes/labels.py @@ -11,7 +11,6 @@ from fastapi import APIRouter, Query from pydantic import BaseModel, Field -from starlette.concurrency import run_in_threadpool from pyrit.backend.routes.common import parse_label_query_params from pyrit.memory import CentralMemory @@ -67,18 +66,13 @@ async def get_label_options( # pyrit-async-suffix-exempt if source == "attacks": label_filters = parse_label_query_params(label) - labels = await run_in_threadpool( - memory.get_unique_attack_labels, - operator=operator, - operation=operation, - labels=label_filters, + labels = await memory.get_unique_attack_labels_async( + operator=operator, operation=operation, labels=label_filters ) attribution = ( - {} - if operator or operation or label_filters - else await run_in_threadpool(memory.get_unique_attack_attribution) + {} if operator or operation or label_filters else await memory.get_unique_attack_attribution_async() ) return LabelOptionsResponse(source=source, labels=labels, **attribution) - labels = await run_in_threadpool(memory.get_unique_scenario_labels) + labels = await memory.get_unique_scenario_labels_async() return LabelOptionsResponse(source=source, labels=labels) diff --git a/pyrit/backend/routes/scenarios.py b/pyrit/backend/routes/scenarios.py index 0ed506fa3c..f73ccdb622 100644 --- a/pyrit/backend/routes/scenarios.py +++ b/pyrit/backend/routes/scenarios.py @@ -13,7 +13,6 @@ """ from fastapi import APIRouter, HTTPException, Query, Request, status -from starlette.concurrency import run_in_threadpool from pyrit.backend.models.common import ProblemDetail from pyrit.backend.models.scenarios import ( @@ -246,8 +245,7 @@ async def list_scenario_runs( # pyrit-async-suffix-exempt ScenarioRunListResponse: Runs, most recent first. """ service = get_scenario_run_service() - return await run_in_threadpool( - service.list_runs, + return await service.list_runs_async( scenario_names=scenario_names, statuses=run_statuses, labels=parse_label_query_params(label), @@ -289,8 +287,7 @@ async def get_scenario_run(scenario_result_id: str) -> ScenarioRunSummary: # py """ service = get_scenario_run_service() active_snapshot = service.snapshot_active_run(scenario_result_id=scenario_result_id) - run = await run_in_threadpool( - service.get_run_from_storage, + run = await service.get_run_from_storage_async( scenario_result_id=scenario_result_id, active_error=active_snapshot.error, queue_position=active_snapshot.queue_position, @@ -327,8 +324,7 @@ async def get_scenario_run_progress( # pyrit-async-suffix-exempt service = get_scenario_run_service() active_snapshot = service.snapshot_active_run(scenario_result_id=scenario_result_id) try: - progress = await run_in_threadpool( - service.get_run_progress_from_storage, + progress = await service.get_run_progress_from_storage_async( scenario_result_id=scenario_result_id, since=since, limit=limit, @@ -398,7 +394,7 @@ async def get_scenario_run_results(scenario_result_id: str) -> ScenarioResult: """ service = get_scenario_run_service() try: - result = service.get_run_results(scenario_result_id=scenario_result_id) + result = await service.get_run_results_async(scenario_result_id=scenario_result_id) except ValueError as e: raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) from None diff --git a/pyrit/backend/routes/scores.py b/pyrit/backend/routes/scores.py index c34ad0f64f..d1c484b570 100644 --- a/pyrit/backend/routes/scores.py +++ b/pyrit/backend/routes/scores.py @@ -3,7 +3,6 @@ """Score API routes.""" -import asyncio import uuid from datetime import UTC, datetime @@ -58,7 +57,7 @@ async def create_manual_score( # pyrit-async-suffix-exempt ScoreView: The persisted manual score. """ memory = CentralMemory.get_memory_instance() - pieces = await asyncio.to_thread(memory.get_message_pieces, prompt_ids=[request_body.message_id]) + pieces = await memory.get_message_pieces_async(prompt_ids=[request_body.message_id]) piece = next((piece for piece in pieces if str(piece.id) == str(request_body.message_id)), None) if piece is None: raise HTTPException( @@ -66,10 +65,7 @@ async def create_manual_score( # pyrit-async-suffix-exempt detail=f"Message '{request_body.message_id}' not found", ) - attacks = await asyncio.to_thread( - memory.get_attack_results, - attack_result_ids=[str(request_body.attack_result_id)], - ) + attacks = await memory.get_attack_results_async(attack_result_ids=[str(request_body.attack_result_id)]) if not attacks: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, @@ -101,8 +97,7 @@ async def create_manual_score( # pyrit-async-suffix-exempt score = scores[0] if request_body.update_attack: outcome = _get_manual_score_outcome(request=request_body) - updated = await asyncio.to_thread( - memory.update_attack_result_by_id, + updated = await memory.update_attack_result_by_id_async( attack_result_id=attack.attack_result_id, update_fields={ "human_score_id": uuid.UUID(str(score.id)), diff --git a/pyrit/backend/services/attack_service.py b/pyrit/backend/services/attack_service.py index a344809462..6f8f778884 100644 --- a/pyrit/backend/services/attack_service.py +++ b/pyrit/backend/services/attack_service.py @@ -15,7 +15,6 @@ - AI-generated attacks may have multiple related conversations """ -import asyncio import uuid from collections.abc import Mapping, Sequence from datetime import UTC, datetime @@ -207,7 +206,7 @@ async def list_attacks_async( if decoded_cursor is not None else None ) - results = self._memory.get_attack_results( + results = await self._memory.get_attack_results_async( outcome=outcome, operator=operator, operation=operation, @@ -242,7 +241,11 @@ async def list_attacks_async( for ar in page_results: all_conv_ids.update(ar.get_active_conversation_ids()) - stats_map = self._memory.get_conversation_stats(conversation_ids=list(all_conv_ids)) if all_conv_ids else {} + stats_map = ( + (await self._memory.get_conversation_stats_async(conversation_ids=list(all_conv_ids))) + if all_conv_ids + else {} + ) # Phase 3: Build summaries from aggregated stats for the page page: list[AttackSummary] = [] @@ -281,7 +284,7 @@ async def get_attack_options_async(self) -> list[str]: Returns: Sorted list of unique attack type names. """ - return self._memory.get_unique_attack_class_names() + return await self._memory.get_unique_attack_class_names_async() async def get_converter_options_async(self) -> list[str]: """ @@ -293,7 +296,7 @@ async def get_converter_options_async(self) -> list[str]: Returns: Sorted list of unique converter type names. """ - return self._memory.get_unique_converter_class_names() + return await self._memory.get_unique_converter_class_names_async() async def get_attack_async(self, *, attack_result_id: str) -> AttackSummary | None: """ @@ -304,15 +307,12 @@ async def get_attack_async(self, *, attack_result_id: str) -> AttackSummary | No Returns: AttackSummary if found, None otherwise. """ - results = await asyncio.to_thread( - self._memory.get_attack_results, - attack_result_ids=[attack_result_id], - ) + results = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id]) if not results: return None ar = results[0] - stats_map = self._memory.get_conversation_stats(conversation_ids=[ar.conversation_id]) + stats_map = await self._memory.get_conversation_stats_async(conversation_ids=[ar.conversation_id]) stats = stats_map.get(ar.conversation_id, ConversationStats(message_count=0)) return await attack_result_to_summary_async(ar, stats=stats) @@ -336,7 +336,7 @@ async def get_conversation_messages_async( ValueError: If the conversation does not belong to the attack. """ # Check attack exists - results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) + results = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id]) if not results: return None @@ -346,7 +346,7 @@ async def get_conversation_messages_async( raise ValueError(f"Conversation '{conversation_id}' is not part of attack '{attack_result_id}'") # Get messages for this conversation - pyrit_messages = self._memory.get_conversation_messages(conversation_id=conversation_id) + pyrit_messages = await self._memory.get_conversation_messages_async(conversation_id=conversation_id) backend_messages = await pyrit_messages_to_dto_async( list(pyrit_messages), objective_score_id=ar.last_score.id if ar.last_score else None, @@ -391,7 +391,7 @@ async def create_attack_async(self, *, request: CreateAttackRequest) -> CreateAt # --- Branch via duplication (preferred for tracking) --------------- if request.source_conversation_id is not None and request.cutoff_index is not None: - conversation_id = self._duplicate_conversation_up_to( + conversation_id = await self._duplicate_conversation_up_to_async( source_conversation_id=request.source_conversation_id, cutoff_index=request.cutoff_index, remap_assistant_to_simulated=True, @@ -427,7 +427,7 @@ async def create_attack_async(self, *, request: CreateAttackRequest) -> CreateAt ) # Store in memory - self._memory.add_attack_results_to_memory(attack_results=[attack_result]) + (await self._memory.add_attack_results_to_memory_async(attack_results=[attack_result])) # Store prepended conversation messages if provided. A system_prompt is lowered to a # single system-role message at the front, composing with any prepended_conversation. @@ -462,7 +462,7 @@ async def update_attack_async(self, *, attack_result_id: str, request: UpdateAtt Returns: Updated AttackSummary if found, None otherwise. """ - results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) + results = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id]) if not results: return None @@ -485,9 +485,11 @@ async def update_attack_async(self, *, attack_result_id: str, request: UpdateAtt elif request.outcome is None: return await self.get_attack_async(attack_result_id=attack_result_id) - self._memory.update_attack_result_by_id( - attack_result_id=attack_result_id, - update_fields=update_fields, + ( + await self._memory.update_attack_result_by_id_async( + attack_result_id=attack_result_id, + update_fields=update_fields, + ) ) return await self.get_attack_async(attack_result_id=attack_result_id) @@ -502,10 +504,7 @@ async def remove_human_score_async(self, *, attack_result_id: str) -> AttackSumm Returns: Updated AttackSummary if found, None otherwise. """ - results = await asyncio.to_thread( - self._memory.get_attack_results, - attack_result_ids=[attack_result_id], - ) + results = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id]) if not results: return None @@ -519,8 +518,7 @@ async def remove_human_score_async(self, *, attack_result_id: str) -> AttackSumm ) outcome_reason = automated_score.score_rationale - await asyncio.to_thread( - self._memory.update_attack_result_by_id, + await self._memory.update_attack_result_by_id_async( attack_result_id=attack_result_id, update_fields={ "human_score_id": None, @@ -543,7 +541,7 @@ async def get_conversations_async(self, *, attack_result_id: str) -> AttackConve Returns: AttackConversationsResponse if attack found, None otherwise. """ - results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) + results = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id]) if not results: return None @@ -552,7 +550,7 @@ async def get_conversations_async(self, *, attack_result_id: str) -> AttackConve # Collect all conversation IDs (main + PRUNED related) and fetch stats in one query. active_conv_ids = list(ar.get_active_conversation_ids()) - stats_map = self._memory.get_conversation_stats(conversation_ids=active_conv_ids) + stats_map = await self._memory.get_conversation_stats_async(conversation_ids=active_conv_ids) conversations: list[ConversationSummary] = [] for conv_id in active_conv_ids: @@ -600,7 +598,7 @@ async def create_related_conversation_async( Returns: CreateConversationResponse if attack found, None otherwise. """ - results = await asyncio.to_thread(self._memory.get_attack_results, attack_result_ids=[attack_result_id]) + results = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id]) if not results: return None @@ -625,14 +623,13 @@ async def create_related_conversation_async( source_metadata: Conversation | None = None all_pieces: Sequence[MessagePiece] = [] if request.source_conversation_id is not None and request.cutoff_index is not None: - source_metadata = await asyncio.to_thread( - self._memory._get_conversation, conversation_id=request.source_conversation_id + source_metadata = await self._memory.get_conversation_metadata_async( + conversation_id=request.source_conversation_id ) source_metadata = source_metadata or Conversation( conversation_id=request.source_conversation_id, target_identifier=objective_target ) - conversation, all_pieces = await asyncio.to_thread( - self._prepare_conversation_up_to, + conversation, all_pieces = await self._prepare_conversation_up_to_async( source_conversation_id=request.source_conversation_id, cutoff_index=request.cutoff_index, target_identifier=source_metadata.target_identifier, @@ -643,8 +640,7 @@ async def create_related_conversation_async( target_identifier=objective_target, ) - stored = await asyncio.to_thread( - self._memory.add_conversation_branches_to_attack, + stored = await self._memory.add_conversation_branches_to_attack_async( attack_result_id=attack_result_id, conversations=[conversation], message_pieces=all_pieces, @@ -669,7 +665,7 @@ async def update_main_conversation_async( Returns: UpdateMainConversationResponse if the source attack exists, None otherwise. """ - results = await asyncio.to_thread(self._memory.get_attack_results, attack_result_ids=[attack_result_id]) + results = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id]) if not results: return None @@ -681,10 +677,8 @@ async def update_main_conversation_async( raise ValueError(f"Conversation '{target_conv_id}' is not part of this attack") now = datetime.now(UTC) - stored = await asyncio.to_thread( - self._memory.promote_attack_conversation, - attack_result_id=attack_result_id, - conversation_id=target_conv_id, + stored = await self._memory.promote_attack_conversation_async( + attack_result_id=attack_result_id, conversation_id=target_conv_id ) if not stored: return None @@ -722,7 +716,7 @@ async def add_message_async(self, *, attack_result_id: str, request: AddMessageR # Private Helper Methods - Duplicate / Branch # ======================================================================== - def _duplicate_conversation_up_to( + async def _duplicate_conversation_up_to_async( self, *, source_conversation_id: str, @@ -750,7 +744,7 @@ def _duplicate_conversation_up_to( Returns: The new conversation ID containing the duplicated messages. """ - conversation, all_pieces = self._prepare_conversation_up_to( + conversation, all_pieces = await self._prepare_conversation_up_to_async( source_conversation_id=source_conversation_id, cutoff_index=cutoff_index, target_identifier=target_identifier, @@ -762,12 +756,12 @@ def _duplicate_conversation_up_to( piece.set_simulated_role() if all_pieces: - self._memory.add_conversation_to_memory(conversation=conversation) - self._memory.add_message_pieces_to_memory(message_pieces=list(all_pieces)) + (await self._memory.add_conversation_to_memory_async(conversation=conversation)) + (await self._memory.add_message_pieces_to_memory_async(message_pieces=list(all_pieces))) return conversation.conversation_id - def _prepare_conversation_up_to( + async def _prepare_conversation_up_to_async( self, *, source_conversation_id: str, @@ -780,8 +774,8 @@ def _prepare_conversation_up_to( Returns: tuple[Conversation, Sequence[MessagePiece]]: New metadata and lineage-preserving pieces. """ - messages = self._memory.get_conversation_messages(conversation_id=source_conversation_id) - new_id, pieces = self._memory.duplicate_messages( + messages = await self._memory.get_conversation_messages_async(conversation_id=source_conversation_id) + new_id, pieces = await self._memory.duplicate_messages_async( messages=[message for message in messages if message.sequence <= cutoff_index] ) return Conversation(conversation_id=new_id, target_identifier=target_identifier), pieces @@ -801,7 +795,7 @@ async def _store_prepended_messages_async( if not prepended: return applied_by_message = [resolve_applied_converter_identifiers(msg.pieces) for msg in prepended] - self._memory.add_conversation_to_memory( + await self._memory.add_conversation_to_memory_async( conversation=Conversation(conversation_id=conversation_id, target_identifier=target_identifier) ) for seq, msg in enumerate(prepended): @@ -813,7 +807,7 @@ async def _store_prepended_messages_async( sequence=seq, ) piece.converter_identifiers.extend(applied_by_message[seq].get(index, [])) - self._memory.add_message_pieces_to_memory(message_pieces=[piece]) + (await self._memory.add_message_pieces_to_memory_async(message_pieces=[piece])) # ============================================================================ diff --git a/pyrit/backend/services/dataset_service.py b/pyrit/backend/services/dataset_service.py index 4d14b1699f..ce83c58290 100644 --- a/pyrit/backend/services/dataset_service.py +++ b/pyrit/backend/services/dataset_service.py @@ -52,7 +52,7 @@ async def list_datasets_async(self, *, loaded_only: bool = False) -> DatasetList DatasetListResponse: Available datasets. """ provider_names = {name for name in await SeedDatasetProvider.get_all_dataset_names_async() if name} - summaries = self._memory.get_seed_dataset_summaries() + summaries = await self._memory.get_seed_dataset_summaries_async() named_summaries = {summary.dataset_name: summary for summary in summaries if summary.dataset_name} dataset_names = set(named_summaries) if loaded_only else provider_names | set(named_summaries) diff --git a/pyrit/backend/services/message_send_service.py b/pyrit/backend/services/message_send_service.py index 5370dd4504..af0b874482 100644 --- a/pyrit/backend/services/message_send_service.py +++ b/pyrit/backend/services/message_send_service.py @@ -1,11 +1,11 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -"""Synchronous manual-message preparation, dispatch, and attack metadata updates.""" +"""Manual-message preparation, dispatch, and attack metadata updates.""" import asyncio import logging -from collections.abc import AsyncIterator, Callable +from collections.abc import AsyncIterator, Callable, Coroutine from contextlib import asynccontextmanager from datetime import UTC, datetime from functools import partial @@ -93,7 +93,7 @@ async def add_message_context_async( yield async def _add_message_async(self, *, attack_result_id: str, request: AddMessageRequest) -> None: - results = await asyncio.to_thread(self._memory.get_attack_results, attack_result_ids=[attack_result_id]) + results = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id]) if not results: raise ValueError(f"Attack '{attack_result_id}' not found") @@ -147,7 +147,7 @@ async def _execute_message_async( applied_converter_identifiers = resolve_applied_converter_identifiers(request.pieces) last_response_id: str | None = None - existing = await asyncio.to_thread(self._memory.get_message_pieces, conversation_id=msg_conversation_id) + existing = await self._memory.get_message_pieces_async(conversation_id=msg_conversation_id) sequence = max((p.sequence for p in existing), default=-1) + 1 if request.send: @@ -172,9 +172,7 @@ async def _execute_message_async( # generic 500. If no new error piece was stored (the failure # happened before the send, e.g. media preparation), re-raise so the # route still reports a real error. - current_pieces = await asyncio.to_thread( - self._memory.get_message_pieces, conversation_id=msg_conversation_id - ) + current_pieces = await self._memory.get_message_pieces_async(conversation_id=msg_conversation_id) if not any(p.id not in prior_ids and p.has_error() for p in current_pieces): raise logger.exception( @@ -182,19 +180,14 @@ async def _execute_message_async( attack_result_id, msg_conversation_id, ) - current_pieces = await asyncio.to_thread( - self._memory.get_message_pieces, - conversation_id=msg_conversation_id, - ) + current_pieces = await self._memory.get_message_pieces_async(conversation_id=msg_conversation_id) last_response = next( (piece for piece in current_pieces if piece.id not in prior_ids and piece.role == "assistant"), None, ) last_response_id = str(last_response.id) if last_response else None else: - existing_metadata = await asyncio.to_thread( - self._memory._get_conversation, conversation_id=msg_conversation_id - ) + existing_metadata = await self._memory.get_conversation_metadata_async(conversation_id=msg_conversation_id) await self._store_message_only_async( conversation_id=msg_conversation_id, request=request, @@ -206,7 +199,7 @@ async def _execute_message_async( async with self._scheduler.metadata_update_async(attack_result_id=attack_result_id): await self._complete_memory_write_async( partial( - self._update_attack_after_message, + self._update_attack_after_message_async, attack_result_id=attack_result_id, last_response_id=last_response_id, request_converter_configurations=self._exclude_preconverted_piece_indexes( @@ -243,7 +236,7 @@ def _validate_target_match( f"Create a new attack to use a different target." ) - def _update_attack_after_message( + async def _update_attack_after_message_async( self, *, attack_result_id: str, @@ -268,7 +261,7 @@ def _update_attack_after_message( Raises: ValueError: If the attack disappeared before its metadata could be updated. """ - results = self._memory.get_attack_results(attack_result_ids=[attack_result_id]) + results = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id]) if not results: raise ValueError(f"Attack '{attack_result_id}' not found after message send") ar = results[0] @@ -308,9 +301,11 @@ def _update_attack_after_message( ) update_fields["atomic_attack_identifier"] = new_atomic.model_dump() - self._memory.update_attack_result_by_id( - attack_result_id=attack_result_id, - update_fields=update_fields, + ( + await self._memory.update_attack_result_by_id_async( + attack_result_id=attack_result_id, + update_fields=update_fields, + ) ) @staticmethod @@ -477,7 +472,7 @@ async def _send_and_store_message_async( """Send message to target via normalizer and store response.""" await self._persist_base64_pieces_async(request) - await asyncio.to_thread(self._resolve_video_remix_metadata, request) + await self._resolve_video_remix_metadata_async(request) pyrit_message = request_to_pyrit_message( request=request, @@ -516,7 +511,7 @@ async def _store_message_only_async( await self._persist_base64_pieces_async(request) await self._complete_memory_write_async( partial( - self._store_message_only, + self._persist_message_only_async, conversation_id=conversation_id, request=request, sequence=sequence, @@ -525,7 +520,7 @@ async def _store_message_only_async( ) ) - def _store_message_only( + async def _persist_message_only_async( self, *, conversation_id: str, @@ -534,8 +529,10 @@ def _store_message_only( target_identifier: ComponentIdentifier | None, applied_converter_identifiers: dict[int, list[ConverterIdentifier]], ) -> None: - self._memory.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target_identifier) + ( + await self._memory.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target_identifier) + ) ) for index, p in enumerate(request.pieces): piece = request_piece_to_pyrit_message_piece( @@ -545,23 +542,27 @@ def _store_message_only( sequence=sequence, ) piece.converter_identifiers.extend(applied_converter_identifiers.get(index, [])) - self._memory.add_message_pieces_to_memory(message_pieces=[piece]) + (await self._memory.add_message_pieces_to_memory_async(message_pieces=[piece])) @staticmethod - async def _complete_memory_write_async(write: Callable[[], None]) -> None: - """Keep ownership until an offloaded write finishes, even when the caller cancels.""" - worker = asyncio.create_task(asyncio.to_thread(write)) + async def _complete_memory_write_async(write: Callable[[], Coroutine[Any, Any, None]]) -> None: + """Keep ownership until a write finishes, even when the caller cancels.""" + worker = asyncio.create_task(write()) cancelled = False while not worker.done(): try: await asyncio.shield(worker) except asyncio.CancelledError: cancelled = True - worker.result() + except Exception: + if not cancelled: + raise + break if cancelled: - raise asyncio.CancelledError + raise asyncio.CancelledError from (None if worker.cancelled() else worker.exception()) + worker.result() - def _resolve_video_remix_metadata(self, request: AddMessageRequest) -> None: + async def _resolve_video_remix_metadata_async(self, request: AddMessageRequest) -> None: """ Auto-resolve video_id metadata for remix mode. @@ -586,7 +587,7 @@ def _resolve_video_remix_metadata(self, request: AddMessageRequest) -> None: for vp in video_pieces: if not vp.original_prompt_id: continue - original_pieces = self._memory.get_message_pieces(prompt_ids=[vp.original_prompt_id]) + original_pieces = await self._memory.get_message_pieces_async(prompt_ids=[vp.original_prompt_id]) if not original_pieces: continue video_id = (original_pieces[0].prompt_metadata or {}).get("video_id") diff --git a/pyrit/backend/services/runtime_lifecycle.py b/pyrit/backend/services/runtime_lifecycle.py index 803547010c..202ff2cb3f 100644 --- a/pyrit/backend/services/runtime_lifecycle.py +++ b/pyrit/backend/services/runtime_lifecycle.py @@ -17,6 +17,7 @@ from pyrit.backend.services.scenario_run_service import get_scenario_run_service, peek_scenario_run_service from pyrit.backend.services.service_lifecycle import close_services_async, outstanding_estimates from pyrit.common.path import CONFIGURATION_DIRECTORY_PATH +from pyrit.memory import CentralMemory from pyrit.registry import InitializerRegistry from pyrit.setup.configuration_loader import ConfigurationLoader from pyrit.setup.environment_loading import resolve_environment_async @@ -226,7 +227,13 @@ async def shutdown_async(self) -> None: if self.apply_task and not self.apply_task.done(): await asyncio.shield(self.apply_task) self.state = "stopping" - service = peek_scenario_run_service() - if service: - await service.shutdown_async() - await close_services_async() + try: + service = peek_scenario_run_service() + if service: + await service.shutdown_async() + finally: + try: + await close_services_async() + finally: + if CentralMemory._memory_instance is not None: + await CentralMemory.get_memory_instance().dispose_engine_async() diff --git a/pyrit/backend/services/scenario_progress_read_model.py b/pyrit/backend/services/scenario_progress_read_model.py index 5eb879aa89..13278af3a6 100644 --- a/pyrit/backend/services/scenario_progress_read_model.py +++ b/pyrit/backend/services/scenario_progress_read_model.py @@ -3,6 +3,7 @@ """Incremental read model for persisted scenario progress.""" +import asyncio import logging from collections import OrderedDict from collections.abc import Iterable, Sequence @@ -11,6 +12,8 @@ from threading import Lock from typing import Literal +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.common.utils import to_sha256 from pyrit.memory import AttackResultKeysetCursor from pyrit.memory.memory_interface import MemoryInterface @@ -190,65 +193,147 @@ def get_snapshot( """ Refresh and return the mapped progress state for one run. + Args: + scenario_result_id (str): Persisted scenario run ID. + plan (ScenarioRunPlan | None): Saved run plan, if available. + plan_complete (bool): Whether the plan includes all work. + active_group_ids (Sequence[str]): Groups that are running. + terminal (bool): Whether the run has stopped. + objective_scorer_identifier (ComponentIdentifier | None): Objective scorer identity. + Returns: ScenarioProgressSnapshot: Deltas, mapped results, summary, and effective plan. """ - plan_signature = plan.model_dump_json() if plan is not None else None + print_deprecation_message( + old_item="ScenarioProgressReadModel.get_snapshot", + new_item="ScenarioProgressReadModel.get_snapshot_async", + removed_in="1.4.0", + ) with self._cache_lock: - entry = self._cache.get(scenario_result_id) - if entry is not None and entry.plan_signature == plan_signature: - has_unenriched_identifier = any( - delta.atomic_attack_identifier is not None and not delta.atomic_attack_identifier.seed_identifiers - for delta in entry.deltas - ) - was_terminal = entry.summary_state is not None and entry.summary_state.terminal - if has_unenriched_identifier and (not terminal or not was_terminal): - entry = None - if entry is None or entry.plan_signature != plan_signature: - entry = _ProgressCacheEntry(plan_signature=plan_signature) - self._cache[scenario_result_id] = entry - self._cache.move_to_end(scenario_result_id) - while len(self._cache) > self._CACHE_MAX_RUNS: - self._cache.popitem(last=False) - - first_new_index = len(entry.deltas) + entry = self._get_cache_entry(scenario_result_id=scenario_result_id, plan=plan, terminal=terminal) + first_new_index = len(entry.results) self._hydrate_new_deltas(scenario_result_id=scenario_result_id, entry=entry) + return self._build_snapshot( + entry=entry, + first_new_index=first_new_index, + plan=plan, + plan_complete=plan_complete, + active_group_ids=active_group_ids, + terminal=terminal, + objective_scorer_identifier=objective_scorer_identifier, + ) - summary_plan = plan or self._synthesize_legacy_plan(deltas=entry.deltas) - if len(entry.results) < len(entry.deltas): - plan_lookup = ScenarioPlanLookup.from_plan(plan=summary_plan) - entry.results.extend( - self._map_progress_delta(delta=delta, plan_lookup=plan_lookup) - for delta in entry.deltas[len(entry.results) :] - ) + @legacy_sync_override(lambda: ScenarioProgressReadModel.get_snapshot) + async def get_snapshot_async( + self, + *, + scenario_result_id: str, + plan: ScenarioRunPlan | None, + plan_complete: bool, + active_group_ids: Sequence[str], + terminal: bool, + objective_scorer_identifier: ComponentIdentifier | None, + ) -> ScenarioProgressSnapshot: + """ + Refresh and return the mapped progress state for one run. - summary_state = _ProgressSummaryState( - active_group_ids=tuple(active_group_ids), - terminal=terminal, + Args: + scenario_result_id (str): Persisted scenario run ID. + plan (ScenarioRunPlan | None): Saved run plan, if available. + plan_complete (bool): Whether the plan includes all work. + active_group_ids (Sequence[str]): Groups that are running. + terminal (bool): Whether the run has stopped. + objective_scorer_identifier (ComponentIdentifier | None): Objective scorer identity. + + Returns: + ScenarioProgressSnapshot: Deltas, mapped results, summary, and effective plan. + """ + while not self._cache_lock.acquire(blocking=False): + await asyncio.sleep(0.01) + try: + entry = self._get_cache_entry(scenario_result_id=scenario_result_id, plan=plan, terminal=terminal) + first_new_index = len(entry.results) + await self._hydrate_new_deltas_async(scenario_result_id=scenario_result_id, entry=entry) + return self._build_snapshot( + entry=entry, + first_new_index=first_new_index, + plan=plan, plan_complete=plan_complete, + active_group_ids=active_group_ids, + terminal=terminal, + objective_scorer_identifier=objective_scorer_identifier, + ) + finally: + self._cache_lock.release() + + def _get_cache_entry( + self, *, scenario_result_id: str, plan: ScenarioRunPlan | None, terminal: bool + ) -> _ProgressCacheEntry: + plan_signature = plan.model_dump_json() if plan is not None else None + entry = self._cache.get(scenario_result_id) + if entry is not None and entry.plan_signature == plan_signature: + has_unenriched_identifier = any( + delta.atomic_attack_identifier is not None and not delta.atomic_attack_identifier.seed_identifiers + for delta in entry.deltas + ) + was_terminal = entry.summary_state is not None and entry.summary_state.terminal + if has_unenriched_identifier and (not terminal or not was_terminal): + entry = None + if entry is None or entry.plan_signature != plan_signature: + entry = _ProgressCacheEntry(plan_signature=plan_signature) + self._cache[scenario_result_id] = entry + self._cache.move_to_end(scenario_result_id) + while len(self._cache) > self._CACHE_MAX_RUNS: + self._cache.popitem(last=False) + + return entry + + def _build_snapshot( + self, + *, + entry: _ProgressCacheEntry, + first_new_index: int, + plan: ScenarioRunPlan | None, + plan_complete: bool, + active_group_ids: Sequence[str], + terminal: bool, + objective_scorer_identifier: ComponentIdentifier | None, + ) -> ScenarioProgressSnapshot: + summary_plan = plan or self._synthesize_legacy_plan(deltas=entry.deltas) + if len(entry.results) < len(entry.deltas): + plan_lookup = ScenarioPlanLookup.from_plan(plan=summary_plan) + entry.results.extend( + self._map_progress_delta(delta=delta, plan_lookup=plan_lookup) + for delta in entry.deltas[len(entry.results) :] ) - if entry.summary is None or first_new_index < len(entry.deltas) or entry.summary_state != summary_state: - technique_details_by_group = self._build_technique_details_by_group( - deltas=entry.deltas, - results=entry.results, - ) - entry.summary = self._build_progress_summary( - plan=summary_plan, - plan_complete=plan_complete, - results=entry.results, - active_group_ids=active_group_ids, - terminal=terminal, - objective_scorer_identifier=objective_scorer_identifier, - technique_details_by_group=technique_details_by_group, - ) - entry.summary_state = summary_state - return ScenarioProgressSnapshot( - deltas=tuple(entry.deltas), - results=tuple(entry.results), - summary=entry.summary, + summary_state = _ProgressSummaryState( + active_group_ids=tuple(active_group_ids), + terminal=terminal, + plan_complete=plan_complete, + ) + if entry.summary is None or first_new_index < len(entry.deltas) or entry.summary_state != summary_state: + technique_details_by_group = self._build_technique_details_by_group( + deltas=entry.deltas, + results=entry.results, + ) + entry.summary = self._build_progress_summary( plan=summary_plan, + plan_complete=plan_complete, + results=entry.results, + active_group_ids=active_group_ids, + terminal=terminal, + objective_scorer_identifier=objective_scorer_identifier, + technique_details_by_group=technique_details_by_group, ) + entry.summary_state = summary_state + + return ScenarioProgressSnapshot( + deltas=tuple(entry.deltas), + results=tuple(entry.results), + summary=entry.summary, + plan=summary_plan, + ) def _hydrate_new_deltas(self, *, scenario_result_id: str, entry: _ProgressCacheEntry) -> None: """Hydrate every persisted delta after the cached keyset cursor.""" @@ -270,6 +355,24 @@ def _hydrate_new_deltas(self, *, scenario_result_id: str, entry: _ProgressCacheE if not page: raise RuntimeError("Scenario progress storage returned an empty page with has_more=True.") + async def _hydrate_new_deltas_async(self, *, scenario_result_id: str, entry: _ProgressCacheEntry) -> None: + """Hydrate every persisted delta after the cached keyset cursor.""" + while True: + page, has_more = await self._memory.get_scenario_attack_result_deltas_async( + scenario_result_id=scenario_result_id, cursor=entry.cursor, limit=self._STORAGE_PAGE_SIZE + ) + entry.deltas.extend(page) + if page: + last = page[-1] + entry.cursor = AttackResultKeysetCursor( + timestamp=last.timestamp, + attack_result_id=last.attack_result_id, + ) + if not has_more: + return + if not page: + raise RuntimeError("Scenario progress storage returned an empty page with has_more=True.") + @staticmethod def build_plan_lookup(*, plan: ScenarioRunPlan | None) -> ScenarioPlanLookup: """ diff --git a/pyrit/backend/services/scenario_run_service.py b/pyrit/backend/services/scenario_run_service.py index fd2aba9f7b..50808b204c 100644 --- a/pyrit/backend/services/scenario_run_service.py +++ b/pyrit/backend/services/scenario_run_service.py @@ -35,7 +35,13 @@ normalize_label_filters, ) from pyrit.backend.services.scenario_configuration_resolver import ScenarioConfigurationResolver -from pyrit.backend.services.scenario_progress_read_model import ResultUnitIdentity, ScenarioProgressReadModel +from pyrit.backend.services.scenario_progress_read_model import ( + ResultUnitIdentity, + ScenarioProgressReadModel, + ScenarioProgressSnapshot, +) +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.memory import AttackResultKeysetCursor, CentralMemory, SQLiteMemory from pyrit.memory.memory_interface import ( ScenarioHistoryAggregate, @@ -46,6 +52,7 @@ SCENARIO_RUN_PLAN_METADATA_KEY, SCENARIO_RUN_STARTED_AT_METADATA_KEY, AttackOutcome, + AttackResult, ComponentIdentifier, ScenarioAttackResultDelta, ScenarioIdentifier, @@ -212,6 +219,7 @@ def __init__(self, *, max_concurrent_runs: int = _DEFAULT_MAX_CONCURRENT_RUNS) - self._active_scenario_result_id: str | None = None self._queued_runs: deque[_ActiveTask] = deque() self._handoff_retry_tasks: set[asyncio.Task[None]] = set() + self._abandoned_prepare_tasks: set[asyncio.Task[None]] = set() self._scheduler_lock = asyncio.Lock() self._launch_lock = asyncio.Lock() self._preparing_run_ids: set[str] = set() @@ -288,7 +296,7 @@ async def _validate_resume_admission_async( or any(run.scenario_result_id == scenario_result_id for run in self._queued_runs) ): raise ScenarioRunConflictError(f"Scenario run '{scenario_result_id}' is already scheduled or initializing.") - stored = await asyncio.to_thread(self._memory.get_scenario_result_header, scenario_result_id=scenario_result_id) + stored = await self._memory.get_scenario_result_header_async(scenario_result_id=scenario_result_id) if stored is None: raise ScenarioRunNotFoundError(f"Scenario run '{scenario_result_id}' was not found in this database.") eligible_states = {ScenarioRunState.FAILED} @@ -375,9 +383,7 @@ async def _start_run_locked_async(self, *, request: RunScenarioRequest) -> Scena """ if self._stopping: raise RuntimeError("Scenario run scheduling is stopping.") - resumed_from_cancelled = await asyncio.to_thread( - self._is_run_cancelled, scenario_result_id=request.scenario_result_id - ) + resumed_from_cancelled = await self._is_run_cancelled_async(scenario_result_id=request.scenario_result_id) if request.scenario_result_id: self._preparing_run_ids.add(request.scenario_result_id) prepare_task = asyncio.get_running_loop().run_in_executor( @@ -393,11 +399,11 @@ async def _start_run_locked_async(self, *, request: RunScenarioRequest) -> Scena except asyncio.CancelledError: if prepare_task.done(): try: - self._release_abandoned_prepare(prepare_task) + (await self._release_abandoned_prepare_async(prepare_task)) except Exception as cleanup_error: logger.warning(f"Could not clean up after a cancelled scenario preparation: {cleanup_error}") else: - prepare_task.add_done_callback(self._release_abandoned_prepare) + prepare_task.add_done_callback(self._schedule_abandoned_prepare_cleanup) raise scenario = prepared.scenario @@ -406,15 +412,11 @@ async def _start_run_locked_async(self, *, request: RunScenarioRequest) -> Scena raise ValueError("Scenario did not produce a scenario_result_id during initialization.") if request.scenario_result_id and scenario_result_id != request.scenario_result_id: raise ValueError("Scenario initialization changed the saved result ID; resume was not started.") - persisted = await asyncio.to_thread( - self._memory.get_scenario_results, - scenario_result_ids=[scenario_result_id], - ) + persisted = await self._memory.get_scenario_results_async(scenario_result_ids=[scenario_result_id]) if not persisted: raise RuntimeError(f"Scenario run {scenario_result_id} was not persisted during initialization.") if not resumed_from_cancelled and persisted[0].scenario_run_state == ScenarioRunState.CANCELLED: - response = await asyncio.to_thread( - self._build_response, + response = await self._build_response_async( scenario_result_id=scenario_result_id, active_error=None, queue_position=None, @@ -426,8 +428,7 @@ async def _start_run_locked_async(self, *, request: RunScenarioRequest) -> Scena ) return response if ( - await asyncio.to_thread( - self._build_response, + await self._build_response_async( scenario_result_id=scenario_result_id, active_error=None, queue_position=None, @@ -448,8 +449,7 @@ async def _start_run_locked_async(self, *, request: RunScenarioRequest) -> Scena await self._enqueue_run_async(scheduled=scheduled) snapshot = self.snapshot_active_run(scenario_result_id=scenario_result_id) - response = await asyncio.to_thread( - self.get_run_from_storage, + response = await self.get_run_from_storage_async( scenario_result_id=scenario_result_id, active_error=snapshot.error, queue_position=snapshot.queue_position, @@ -462,7 +462,7 @@ async def _start_run_locked_async(self, *, request: RunScenarioRequest) -> Scena def _discard_preparation(self, preparation: asyncio.Future[_PreparedRun]) -> None: self._preparations.discard(preparation) - def _is_run_cancelled(self, *, scenario_result_id: str | None) -> bool: + async def _is_run_cancelled_async(self, *, scenario_result_id: str | None) -> bool: """ Report whether a stored run is already in the CANCELLED state. @@ -477,10 +477,10 @@ def _is_run_cancelled(self, *, scenario_result_id: str | None) -> bool: """ if not scenario_result_id: return False - stored = self._memory.get_scenario_result_header(scenario_result_id=scenario_result_id) + stored = await self._memory.get_scenario_result_header_async(scenario_result_id=scenario_result_id) return stored is not None and stored.scenario_run_state == ScenarioRunState.CANCELLED - def _release_abandoned_prepare(self, prepare_task: "asyncio.Future[_PreparedRun]") -> None: + async def _release_abandoned_prepare_async(self, prepare_task: "asyncio.Future[_PreparedRun]") -> None: """ Clean up after an abandoned preparation thread has finished. @@ -504,11 +504,13 @@ def _release_abandoned_prepare(self, prepare_task: "asyncio.Future[_PreparedRun] scenario_result_id = prepare_task.result().scenario._scenario_result_id if scenario_result_id: try: - self._memory.try_update_scenario_run_state( - scenario_result_id=scenario_result_id, - expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, - scenario_run_state=ScenarioRunState.CANCELLED, - error_message="The start request was cancelled while the scenario was being initialized.", + ( + await self._memory.try_update_scenario_run_state_async( + scenario_result_id=scenario_result_id, + expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, + scenario_run_state=ScenarioRunState.CANCELLED, + error_message="The start request was cancelled while the scenario was being initialized.", + ) ) except Exception as update_error: logger.warning( @@ -516,6 +518,12 @@ def _release_abandoned_prepare(self, prepare_task: "asyncio.Future[_PreparedRun] ) logger.warning("Abandoned scenario preparation completed after the request was cancelled.") + def _schedule_abandoned_prepare_cleanup(self, prepare_task: "asyncio.Future[_PreparedRun]") -> None: + """Keep async cleanup alive after a preparation request is cancelled.""" + task = asyncio.create_task(self._release_abandoned_prepare_async(prepare_task)) + self._abandoned_prepare_tasks.add(task) + task.add_done_callback(self._abandoned_prepare_tasks.discard) + def _prepare_run_blocking(self, *, request: RunScenarioRequest) -> _PreparedRun: """ Run the eager initialization for a scenario run on the calling thread. @@ -537,7 +545,7 @@ def _prepare_run_blocking(self, *, request: RunScenarioRequest) -> _PreparedRun: RuntimeError: If tasks are still running on the initialization loop after the drain. """ - async def prepare_async() -> _PreparedRun: + async def prepare_and_drain_async() -> _PreparedRun: prepared = await self._prepare_run_async(request=request) try: await self._drain_initialization_tasks_async() @@ -548,18 +556,26 @@ async def prepare_async() -> _PreparedRun: scenario_result_id = prepared.scenario._scenario_result_id if scenario_result_id: try: - self._memory.try_update_scenario_run_state( - scenario_result_id=scenario_result_id, - expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, - scenario_run_state=ScenarioRunState.FAILED, - error_message=str(drain_error), - error_type=type(drain_error).__name__, + ( + await self._memory.try_update_scenario_run_state_async( + scenario_result_id=scenario_result_id, + expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, + scenario_run_state=ScenarioRunState.FAILED, + error_message=str(drain_error), + error_type=type(drain_error).__name__, + ) ) except Exception as update_error: logger.warning(f"Could not mark scenario run {scenario_result_id} as failed: {update_error}") raise return prepared + async def prepare_async() -> _PreparedRun: + try: + return await prepare_and_drain_async() + finally: + await self._memory.dispose_loop_resources_async() + return asyncio.run(prepare_async()) async def _drain_initialization_tasks_async(self) -> None: @@ -644,6 +660,11 @@ def get_run(self, *, scenario_result_id: str) -> ScenarioRunSummary | None: Returns: ScenarioRunSummary if found, None otherwise. """ + print_deprecation_message( + old_item="ScenarioRunService.get_run", + new_item="ScenarioRunService.get_run_async", + removed_in="1.4.0", + ) snapshot = self.snapshot_active_run(scenario_result_id=scenario_result_id) return self.get_run_from_storage( scenario_result_id=scenario_result_id, @@ -652,6 +673,25 @@ def get_run(self, *, scenario_result_id: str) -> ScenarioRunSummary | None: active_scenario_result_id=snapshot.active_scenario_result_id, ) + @legacy_sync_override(lambda: ScenarioRunService.get_run) + async def get_run_async(self, *, scenario_result_id: str) -> ScenarioRunSummary | None: + """ + Get the current status of a scenario run by querying the database. + + Args: + scenario_result_id: The scenario result ID. + + Returns: + ScenarioRunSummary if found, None otherwise. + """ + snapshot = self.snapshot_active_run(scenario_result_id=scenario_result_id) + return await self.get_run_from_storage_async( + scenario_result_id=scenario_result_id, + active_error=snapshot.error, + queue_position=snapshot.queue_position, + active_scenario_result_id=snapshot.active_scenario_result_id, + ) + def get_run_from_storage( self, *, @@ -672,6 +712,11 @@ def get_run_from_storage( Returns: ScenarioRunSummary | None: The run summary when found. """ + print_deprecation_message( + old_item="ScenarioRunService.get_run_from_storage", + new_item="ScenarioRunService.get_run_from_storage_async", + removed_in="1.4.0", + ) return self._build_response( scenario_result_id=scenario_result_id, active_error=active_error, @@ -679,6 +724,34 @@ def get_run_from_storage( active_scenario_result_id=active_scenario_result_id, ) + @legacy_sync_override(lambda: ScenarioRunService.get_run_from_storage) + async def get_run_from_storage_async( + self, + *, + scenario_result_id: str, + active_error: str | None, + queue_position: int | None = None, + active_scenario_result_id: str | None = None, + ) -> ScenarioRunSummary | None: + """ + Build a run summary using database state plus an event-loop snapshot. + + Args: + scenario_result_id: The scenario result ID. + active_error: Error copied from the active asyncio task, if any. + queue_position: Current 1-based waiting position, if queued. + active_scenario_result_id: Currently executing scenario result ID. + + Returns: + ScenarioRunSummary | None: The run summary when found. + """ + return await self._build_response_async( + scenario_result_id=scenario_result_id, + active_error=active_error, + queue_position=queue_position, + active_scenario_result_id=active_scenario_result_id, + ) + def list_runs( self, *, @@ -701,6 +774,11 @@ def list_runs( Returns: ScenarioRunListResponse with runs. """ + print_deprecation_message( + old_item="ScenarioRunService.list_runs", + new_item="ScenarioRunService.list_runs_async", + removed_in="1.4.0", + ) normalized_names = sorted({name.strip() for name in scenario_names or [] if name.strip()}) normalized_statuses = sorted( { @@ -774,6 +852,102 @@ def list_runs( ), ) + @legacy_sync_override(lambda: ScenarioRunService.list_runs) + async def list_runs_async( + self, + *, + scenario_names: Sequence[str] | None = None, + statuses: Sequence[ScenarioRunState | str] | None = None, + labels: Mapping[str, str | Sequence[str]] | None = None, + limit: int = 100, + cursor: str | None = None, + ) -> ScenarioRunListResponse: + """ + List scenario runs by querying the database (most recent first). + + Args: + scenario_names: Registered or persisted scenario names to match. + statuses: Run states to match. + labels: Labels with OR-within-key and AND-across-key semantics. + limit: Maximum number of runs to return. + cursor: Opaque cursor from the previous page. + + Returns: + ScenarioRunListResponse with runs. + """ + normalized_names = sorted({name.strip() for name in scenario_names or [] if name.strip()}) + normalized_statuses = sorted( + { + status.value if isinstance(status, ScenarioRunState) else str(status).strip().upper() + for status in statuses or [] + if str(status).strip() + } + ) + normalized_labels = normalize_label_filters(labels=labels) + fingerprint = fingerprint_filters( + filters={ + "scenario_names": normalized_names, + "statuses": normalized_statuses, + "labels": normalized_labels, + } + ) + decoded_cursor = decode_keyset_cursor(cursor=cursor, fingerprint=fingerprint) + after = ( + ScenarioHistoryKeysetCursor( + timestamp=decoded_cursor.timestamp, + scenario_result_id=decoded_cursor.identifier, + ) + if decoded_cursor is not None + else None + ) + records, aggregates, has_more = await self._memory.get_scenario_run_history_page_async( + scenario_names=normalized_names, + statuses=normalized_statuses, + labels=normalized_labels, + cursor=after, + limit=limit, + ) + plans = {record.scenario_result_id: self._parse_history_plan(record=record) for record in records} + # Memory resolves units against every persisted plan. Runs whose plan this service + # rejects must fall back to legacy unit identity, which needs a plan-free aggregate. + unusable_plan_ids = [ + record.scenario_result_id + for record in records + if record.plan_atomic_groups is not None and plans[record.scenario_result_id] is None + ] + if unusable_plan_ids: + aggregates = { + **aggregates, + **(await self._memory.get_scenario_history_aggregates_async(scenario_result_ids=unusable_plan_ids)), + } + items = [ + self._build_history_summary( + record=record, + atomic_groups=plans[record.scenario_result_id], + aggregate=aggregates.get(record.scenario_result_id) + or ScenarioHistoryAggregate.empty(scenario_result_id=record.scenario_result_id), + ) + for record in records + ] + next_cursor = ( + encode_keyset_cursor( + timestamp=records[-1].created_at, + identifier=records[-1].scenario_result_id, + fingerprint=fingerprint, + ) + if has_more and records + else None + ) + return ScenarioRunListResponse( + items=items, + pagination=PaginationInfo( + limit=limit, + has_more=has_more, + next_cursor=next_cursor, + prev_cursor=cursor, + ), + ) + async def cancel_run_async(self, *, scenario_result_id: str) -> ScenarioRunSummary | None: """ Cancel a running scenario. @@ -787,10 +961,7 @@ async def cancel_run_async(self, *, scenario_result_id: str) -> ScenarioRunSumma Raises: ValueError: If the run is already in a terminal state or not active. """ - results = await asyncio.to_thread( - self._memory.get_scenario_results, - scenario_result_ids=[scenario_result_id], - ) + results = await self._memory.get_scenario_results_async(scenario_result_ids=[scenario_result_id]) if not results: return None @@ -805,8 +976,7 @@ async def cancel_run_async(self, *, scenario_result_id: str) -> ScenarioRunSumma None, ) if queued is not None: - await asyncio.to_thread( - self._memory.try_update_scenario_run_state, + await self._memory.try_update_scenario_run_state_async( scenario_result_id=scenario_result_id, expected_states={ScenarioRunState.CREATED, ScenarioRunState.QUEUED}, scenario_run_state=ScenarioRunState.CANCELLED, @@ -822,14 +992,10 @@ async def cancel_run_async(self, *, scenario_result_id: str) -> ScenarioRunSumma active.cancellation_error_type = "CancelledError" task = active.task else: - latest = await asyncio.to_thread( - self._memory.get_scenario_results, - scenario_result_ids=[scenario_result_id], - ) + latest = await self._memory.get_scenario_results_async(scenario_result_ids=[scenario_result_id]) if latest and self._is_terminal_state(latest[0].scenario_run_state): raise ValueError(f"Cannot cancel run in '{latest[0].scenario_run_state}' state.") - await asyncio.to_thread( - self._memory.try_update_scenario_run_state, + await self._memory.try_update_scenario_run_state_async( scenario_result_id=scenario_result_id, expected_states={ ScenarioRunState.CREATED, @@ -847,8 +1013,7 @@ async def cancel_run_async(self, *, scenario_result_id: str) -> ScenarioRunSumma await task snapshot = self.snapshot_active_run(scenario_result_id=scenario_result_id) - result = await asyncio.to_thread( - self.get_run_from_storage, + result = await self.get_run_from_storage_async( scenario_result_id=scenario_result_id, active_error=snapshot.error, queue_position=snapshot.queue_position, @@ -904,21 +1069,16 @@ async def reconcile_interrupted_runs_async(self) -> int: after_id = None reconciled = 0 while True: - interrupted, has_more = await asyncio.to_thread( - self._memory.get_scenario_run_state_page, - states=states, - after_id=after_id, - limit=500, + interrupted, has_more = await self._memory.get_scenario_run_state_page_async( + states=states, after_id=after_id, limit=500 ) for result in interrupted: - header = await asyncio.to_thread( - self._memory.get_scenario_result_header, - scenario_result_id=result.scenario_result_id, + header = await self._memory.get_scenario_result_header_async( + scenario_result_id=result.scenario_result_id ) if header is None or header.metadata.get(_SCHEDULER_METADATA_KEY) != _SCHEDULER_METADATA_VALUE: continue - await asyncio.to_thread( - self._memory.update_scenario_run_state, + await self._memory.update_scenario_run_state_async( scenario_result_id=result.scenario_result_id, scenario_run_state=ScenarioRunState.FAILED, error_message=_RESTART_INTERRUPTION_REASON, @@ -948,8 +1108,7 @@ async def shutdown_async(self) -> None: self._queue_revision += 1 for run in queued: try: - await asyncio.to_thread( - self._memory.update_scenario_run_state, + await self._memory.update_scenario_run_state_async( scenario_result_id=run.scenario_result_id, scenario_run_state=ScenarioRunState.FAILED, error_message=_SHUTDOWN_INTERRUPTION_REASON, @@ -965,8 +1124,7 @@ async def shutdown_async(self) -> None: task = active.task if task is None or task.done(): try: - await asyncio.to_thread( - self._memory.update_scenario_run_state, + await self._memory.update_scenario_run_state_async( scenario_result_id=active.scenario_result_id, scenario_run_state=ScenarioRunState.FAILED, error_message=_SHUTDOWN_INTERRUPTION_REASON, @@ -978,6 +1136,8 @@ async def shutdown_async(self) -> None: self._release_completed_task(scenario_result_id=active.scenario_result_id) self._queue_revision += 1 await asyncio.to_thread(self._prepare_executor.shutdown, wait=True) + if self._abandoned_prepare_tasks: + await asyncio.gather(*self._abandoned_prepare_tasks) if task is not None and not task.done(): task.cancel() try: @@ -1008,8 +1168,7 @@ async def _enqueue_run_async(self, *, scheduled: _ActiveTask) -> None: if self._active_scenario_result_id is None: await self._start_scheduled_run_locked_async(scheduled=scheduled) return - await asyncio.to_thread( - self._memory.update_scenario_run_state_and_metadata_fields, + await self._memory.update_scenario_run_state_and_metadata_fields_async( scenario_result_id=scheduled.scenario_result_id, scenario_run_state=ScenarioRunState.QUEUED, metadata_fields={ @@ -1023,8 +1182,7 @@ async def _enqueue_run_async(self, *, scheduled: _ActiveTask) -> None: async def _start_scheduled_run_locked_async(self, *, scheduled: _ActiveTask) -> None: """Start one run while the scheduler lock guarantees exclusive ownership.""" scheduled.started_at = datetime.now(UTC) - await asyncio.to_thread( - self._memory.update_scenario_run_state_and_metadata_fields, + await self._memory.update_scenario_run_state_and_metadata_fields_async( scenario_result_id=scheduled.scenario_result_id, scenario_run_state=ScenarioRunState.IN_PROGRESS, metadata_fields={ @@ -1049,9 +1207,8 @@ async def _handoff_scheduler_async(self, *, scenario_result_id: str) -> None: return while self._queued_runs: next_run = self._queued_runs[0] - persisted = await asyncio.to_thread( - self._memory.get_scenario_results, - scenario_result_ids=[next_run.scenario_result_id], + persisted = await self._memory.get_scenario_results_async( + scenario_result_ids=[next_run.scenario_result_id] ) if not persisted or persisted[0].scenario_run_state != ScenarioRunState.QUEUED: self._queued_runs.popleft() @@ -1113,8 +1270,7 @@ async def _retry_terminalization_async(self, *, active: _ActiveTask) -> None: async with self._scheduler_lock: if not self._can_retry_active_run(scenario_result_id=active.scenario_result_id): return - await asyncio.to_thread( - self._memory.try_update_scenario_run_state, + await self._memory.try_update_scenario_run_state_async( scenario_result_id=active.scenario_result_id, expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, scenario_run_state=active.cancellation_state, @@ -1284,8 +1440,7 @@ async def _execute_run_async(self, *, scenario_result_id: str) -> None: except asyncio.CancelledError: try: - await asyncio.to_thread( - self._memory.try_update_scenario_run_state, + await self._memory.try_update_scenario_run_state_async( scenario_result_id=scenario_result_id, expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, scenario_run_state=active.cancellation_state, @@ -1307,8 +1462,7 @@ async def _execute_run_async(self, *, scenario_result_id: str) -> None: active.cancellation_error_type = type(e).__name__ active.retain_error_on_terminalization = True try: - await asyncio.to_thread( - self._memory.try_update_scenario_run_state, + await self._memory.try_update_scenario_run_state_async( scenario_result_id=scenario_result_id, expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, scenario_run_state=ScenarioRunState.FAILED, @@ -1356,6 +1510,36 @@ def _build_response( active_scenario_result_id=active_scenario_result_id, ) + async def _build_response_async( + self, + *, + scenario_result_id: str, + active_error: str | None, + queue_position: int | None, + active_scenario_result_id: str | None, + ) -> ScenarioRunSummary | None: + """ + Build a ScenarioRunResponse by querying the database and merging active task state. + + Args: + scenario_result_id: The scenario result ID. + active_error: Error copied from the active asyncio task, if any. + queue_position: Current 1-based waiting position, if queued. + active_scenario_result_id: Currently executing scenario result ID. + + Returns: + ScenarioRunResponse if found in the database, None otherwise. + """ + results = await self._memory.get_scenario_results_async(scenario_result_ids=[scenario_result_id]) + if not results: + return None + return await self._build_response_from_db_async( + scenario_result=results[0], + active_error=active_error, + queue_position=queue_position, + active_scenario_result_id=active_scenario_result_id, + ) + def _build_response_from_db( self, *, @@ -1363,12 +1547,62 @@ def _build_response_from_db( active_error: str | None = None, queue_position: int | None = None, active_scenario_result_id: str | None = None, + ) -> ScenarioRunSummary: + error_results = ( + self._memory.get_attack_results( + scenario_result_id=str(scenario_result.id), + outcome=AttackOutcome.ERROR, + ) + if not scenario_result.error_message and scenario_result.scenario_run_state == ScenarioRunState.FAILED + else [] + ) + return self._build_run_summary( + scenario_result=scenario_result, + error_results=error_results, + active_error=active_error, + queue_position=queue_position, + active_scenario_result_id=active_scenario_result_id, + ) + + async def _build_response_from_db_async( + self, + *, + scenario_result: ScenarioResult, + active_error: str | None = None, + queue_position: int | None = None, + active_scenario_result_id: str | None = None, + ) -> ScenarioRunSummary: + error_results = ( + await self._memory.get_attack_results_async( + scenario_result_id=str(scenario_result.id), + outcome=AttackOutcome.ERROR, + ) + if not scenario_result.error_message and scenario_result.scenario_run_state == ScenarioRunState.FAILED + else [] + ) + return self._build_run_summary( + scenario_result=scenario_result, + error_results=error_results, + active_error=active_error, + queue_position=queue_position, + active_scenario_result_id=active_scenario_result_id, + ) + + def _build_run_summary( + self, + *, + scenario_result: ScenarioResult, + error_results: Sequence[AttackResult], + active_error: str | None = None, + queue_position: int | None = None, + active_scenario_result_id: str | None = None, ) -> ScenarioRunSummary: """ Build a ScenarioRunResponse from a database ScenarioResult, merged with active task info. Args: scenario_result: A ScenarioResult retrieved from CentralMemory. + error_results: Failed attack results used when the scenario has no stored error message. active_error: Error copied from the active asyncio task, if any. queue_position: Current 1-based waiting position, if queued. active_scenario_result_id: Currently executing scenario result ID. @@ -1385,10 +1619,7 @@ def _build_response_from_db( # Historical attack errors remain after a successful resume; only use them for failed runs. if not error and status == ScenarioRunState.FAILED: - error_ars = self._memory.get_attack_results( - scenario_result_id=scenario_result_id, - outcome=AttackOutcome.ERROR, - ) + error_ars = error_results if error_ars: error = error_ars[0].error_message error_type = error_ars[0].error_type @@ -1967,6 +2198,11 @@ def get_run_progress( Returns: ScenarioRunProgress | None: Compact progress when the run exists. """ + print_deprecation_message( + old_item="ScenarioRunService.get_run_progress", + new_item="ScenarioRunService.get_run_progress_async", + removed_in="1.4.0", + ) snapshot = self.snapshot_active_run(scenario_result_id=scenario_result_id) return self.get_run_progress_from_storage( scenario_result_id=scenario_result_id, @@ -1977,6 +2213,30 @@ def get_run_progress( active_scenario_result_id=snapshot.active_scenario_result_id, ) + @legacy_sync_override(lambda: ScenarioRunService.get_run_progress) + async def get_run_progress_async( + self, + *, + scenario_result_id: str, + since: str | None, + limit: int, + ) -> ScenarioRunProgress | None: + """ + Snapshot live state and return compact incremental progress. + + Returns: + ScenarioRunProgress | None: Compact progress when the run exists. + """ + snapshot = self.snapshot_active_run(scenario_result_id=scenario_result_id) + return await self.get_run_progress_from_storage_async( + scenario_result_id=scenario_result_id, + since=since, + limit=limit, + active_group_ids=snapshot.active_group_ids, + queue_position=snapshot.queue_position, + active_scenario_result_id=snapshot.active_scenario_result_id, + ) + def get_run_progress_from_storage( self, *, @@ -1988,6 +2248,11 @@ def get_run_progress_from_storage( active_scenario_result_id: str | None = None, ) -> ScenarioRunProgress | None: """Return compact database progress using a previously captured live-state snapshot.""" + print_deprecation_message( + old_item="ScenarioRunService.get_run_progress_from_storage", + new_item="ScenarioRunService.get_run_progress_from_storage_async", + removed_in="1.4.0", + ) header_result = self._memory.get_scenario_result_header(scenario_result_id=scenario_result_id) if header_result is None: return None @@ -2018,6 +2283,88 @@ def get_run_progress_from_storage( terminal=terminal, objective_scorer_identifier=objective_scorer_identifier, ) + return self._build_progress_response( + header_result=header_result, + plan=plan, + progress_snapshot=progress_snapshot, + scenario_result_id=scenario_result_id, + since=since, + limit=limit, + cursor=cursor, + terminal=terminal, + queue_position=queue_position, + active_scenario_result_id=active_scenario_result_id, + ) + + @legacy_sync_override(lambda: ScenarioRunService.get_run_progress_from_storage) + async def get_run_progress_from_storage_async( + self, + *, + scenario_result_id: str, + since: str | None, + limit: int, + active_group_ids: Sequence[str], + queue_position: int | None = None, + active_scenario_result_id: str | None = None, + ) -> ScenarioRunProgress | None: + """Return compact database progress using a previously captured live-state snapshot.""" + header_result = await self._memory.get_scenario_result_header_async(scenario_result_id=scenario_result_id) + if header_result is None: + return None + + try: + plan = self._load_run_plan(scenario_result=header_result) + except (ValidationError, ValueError): + logger.warning( + "Scenario run %s has invalid persisted plan metadata; treating the plan as unavailable.", + scenario_result_id, + ) + plan = None + plan_complete = plan is not None + cursor = self._decode_progress_cursor(since=since, scenario_result_id=scenario_result_id) + terminal = header_result.scenario_run_state in ( + ScenarioRunState.COMPLETED, + ScenarioRunState.FAILED, + ScenarioRunState.CANCELLED, + ) + objective_scorer_identifier = header_result.objective_scorer_identifier + if not isinstance(objective_scorer_identifier, ComponentIdentifier): + objective_scorer_identifier = None + progress_snapshot = await self._progress_read_model.get_snapshot_async( + scenario_result_id=scenario_result_id, + plan=plan, + plan_complete=plan_complete, + active_group_ids=active_group_ids, + terminal=terminal, + objective_scorer_identifier=objective_scorer_identifier, + ) + return self._build_progress_response( + header_result=header_result, + plan=plan, + progress_snapshot=progress_snapshot, + scenario_result_id=scenario_result_id, + since=since, + limit=limit, + cursor=cursor, + terminal=terminal, + queue_position=queue_position, + active_scenario_result_id=active_scenario_result_id, + ) + + def _build_progress_response( + self, + *, + header_result: ScenarioResult, + plan: ScenarioRunPlan | None, + progress_snapshot: ScenarioProgressSnapshot, + scenario_result_id: str, + since: str | None, + limit: int, + cursor: AttackResultKeysetCursor | None, + terminal: bool, + queue_position: int | None, + active_scenario_result_id: str | None, + ) -> ScenarioRunProgress: overload_events: deque[Any] = deque(maxlen=_MAX_OVERLOAD_EVENTS) for delta in progress_snapshot.deltas: overload_events.extend(delta.retry_events) @@ -2071,7 +2418,7 @@ def get_run_progress_from_storage( summary=progress_snapshot.summary, next_cursor=next_cursor, has_more=has_more, - plan_complete=plan_complete, + plan_complete=plan is not None, ) @staticmethod @@ -2123,6 +2470,11 @@ def get_run_results(self, *, scenario_result_id: str) -> ScenarioResult | None: Raises: ValueError: If the run is not in a completed state. """ + print_deprecation_message( + old_item="ScenarioRunService.get_run_results", + new_item="ScenarioRunService.get_run_results_async", + removed_in="1.4.0", + ) results = self._memory.get_scenario_results(scenario_result_ids=[scenario_result_id]) if not results: return None @@ -2135,6 +2487,32 @@ def get_run_results(self, *, scenario_result_id: str) -> ScenarioResult | None: return scenario_result + @legacy_sync_override(lambda: ScenarioRunService.get_run_results) + async def get_run_results_async(self, *, scenario_result_id: str) -> ScenarioResult | None: + """ + Get the ScenarioResult for a completed scenario run. + + Args: + scenario_result_id: The scenario result ID. + + Returns: + ScenarioResult if the run is completed and results exist, None if not found. + + Raises: + ValueError: If the run is not in a completed state. + """ + results = await self._memory.get_scenario_results_async(scenario_result_ids=[scenario_result_id]) + if not results: + return None + + scenario_result = results[0] + run_response = await self._build_response_from_db_async(scenario_result=scenario_result) + + if run_response.status != ScenarioRunState.COMPLETED: + raise ValueError(f"Results are only available for completed runs. Current status: '{run_response.status}'.") + + return scenario_result + _service_instance: ScenarioRunService | None = None diff --git a/pyrit/common/async_compatibility.py b/pyrit/common/async_compatibility.py new file mode 100644 index 0000000000..0cd40ed270 --- /dev/null +++ b/pyrit/common/async_compatibility.py @@ -0,0 +1,76 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import asyncio +from collections.abc import Awaitable, Callable, Coroutine +from functools import wraps +from typing import Any, Concatenate, ParamSpec, TypeVar, cast + +from pyrit.common.deprecation import print_deprecation_message + +P = ParamSpec("P") +R = TypeVar("R") +T = TypeVar("T") + + +async def run_legacy_sync_async(operation: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: + """ + Finish a legacy operation off-loop before propagating cancellation. + + Returns: + R: The operation result. + + Raises: + asyncio.CancelledError: After the worker finishes when the caller cancels. + """ + task = asyncio.create_task(asyncio.to_thread(operation, *args, **kwargs)) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError: + continue + except Exception: + break + if not task.cancelled() and task.exception() is not None: + raise asyncio.CancelledError from task.exception() + raise + + +def legacy_sync_override( + original: Callable[[], Callable[Concatenate[T, P], R]], +) -> Callable[[Callable[Concatenate[T, P], Awaitable[R]]], Callable[Concatenate[T, P], Coroutine[Any, Any, R]]]: + """ + Preserve an unmigrated subclass's synchronous override during deprecation. + + The built-in implementation always uses its async method. A subclass that + overrides both methods also uses its async method, including calls to super. + + Returns: + Callable: A signature-preserving decorator for an explicit async method. + """ + + def decorate( + method: Callable[Concatenate[T, P], Awaitable[R]], + ) -> Callable[Concatenate[T, P], Coroutine[Any, Any, R]]: + @wraps(method) + async def wrapper_async(self: T, *args: P.args, **kwargs: P.kwargs) -> R: + sync_method = original() + async_name = wrapper_async.__name__ + sync_name = async_name.removesuffix("_async") + override = getattr(type(self), sync_name, sync_method) + if getattr(type(self), async_name, None) is wrapper_async and override is not sync_method: + print_deprecation_message( + old_item=f"{type(self).__name__}.{sync_name} override", + new_item=f"{type(self).__name__}.{async_name}", + removed_in="1.4.0", + ) + legacy_method = cast("Callable[Concatenate[T, P], R]", override) + return await run_legacy_sync_async(legacy_method, self, *args, **kwargs) + return await method(self, *args, **kwargs) + + return wrapper_async + + return decorate diff --git a/pyrit/converter/decomposition_converter.py b/pyrit/converter/decomposition_converter.py index be8e8f807b..0ace379e36 100644 --- a/pyrit/converter/decomposition_converter.py +++ b/pyrit/converter/decomposition_converter.py @@ -232,9 +232,10 @@ async def _decompose_async(self, *, objective: str) -> tuple[list[str], list[str InvalidJsonException: If the response is missing, unparseable, or fails validation. """ conversation_id = str(uuid.uuid4()) - self._converter_target.set_system_prompt( - system_prompt=self._decomposition_prompt.render_template_value(), - conversation_id=conversation_id, + ( + await self._converter_target.set_system_prompt_async( + system_prompt=self._decomposition_prompt.render_template_value(), conversation_id=conversation_id + ) ) prompt_metadata = JsonResponseConfig( diff --git a/pyrit/converter/llm_generic_text_converter.py b/pyrit/converter/llm_generic_text_converter.py index 6b4a3adcea..b6844cf298 100644 --- a/pyrit/converter/llm_generic_text_converter.py +++ b/pyrit/converter/llm_generic_text_converter.py @@ -154,9 +154,10 @@ async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text if self._system_prompt_template: system_prompt = self._system_prompt_template.render_template_value(**kwargs) - self._converter_target.set_system_prompt( - system_prompt=system_prompt, - conversation_id=conversation_id, + ( + await self._converter_target.set_system_prompt_async( + system_prompt=system_prompt, conversation_id=conversation_id + ) ) converted_prompt = prompt diff --git a/pyrit/executor/attack/component/adversarial_conversation_manager.py b/pyrit/executor/attack/component/adversarial_conversation_manager.py index 34619c83b9..ee244f00ab 100644 --- a/pyrit/executor/attack/component/adversarial_conversation_manager.py +++ b/pyrit/executor/attack/component/adversarial_conversation_manager.py @@ -624,7 +624,7 @@ def response_json_schema(self) -> JsonSchemaDefinition: """The single response JSON schema every reply is validated against.""" return self._response_json_schema - def set_adversarial_system_prompt(self, **extra_render_values: object) -> None: + async def set_adversarial_system_prompt_async(self, **extra_render_values: object) -> None: """ Render and set the adversarial system prompt on this manager's conversation. @@ -649,9 +649,10 @@ def set_adversarial_system_prompt(self, **extra_render_values: object) -> None: ) if not rendered: raise ValueError("Adversarial chat system prompt must be defined") - self._adversarial_target.set_system_prompt( - system_prompt=rendered, - conversation_id=self._conversation_id, + ( + await self._adversarial_target.set_system_prompt_async( + system_prompt=rendered, conversation_id=self._conversation_id + ) ) def _render_first_message(self) -> str: diff --git a/pyrit/executor/attack/component/conversation_manager.py b/pyrit/executor/attack/component/conversation_manager.py index abb720e17e..1c8cd4e548 100644 --- a/pyrit/executor/attack/component/conversation_manager.py +++ b/pyrit/executor/attack/component/conversation_manager.py @@ -8,6 +8,8 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.common.utils import combine_dict from pyrit.executor.attack.component.prepended_conversation_config import ( PrependedConversationConfig, @@ -226,9 +228,29 @@ def get_conversation(self, conversation_id: str) -> list[Message]: A list of messages in the conversation, ordered by creation time. Returns empty list if no messages exist. """ + print_deprecation_message( + old_item="ConversationManager.get_conversation", + new_item="ConversationManager.get_conversation_async", + removed_in="1.4.0", + ) conversation = self._memory.get_conversation_messages(conversation_id=conversation_id) return list(conversation) + @legacy_sync_override(lambda: ConversationManager.get_conversation) + async def get_conversation_async(self, conversation_id: str) -> list[Message]: + """ + Retrieve a conversation by its ID. + + Args: + conversation_id: The ID of the conversation to retrieve. + + Returns: + A list of messages in the conversation, ordered by creation time. + Returns empty list if no messages exist. + """ + conversation = await self._memory.get_conversation_messages_async(conversation_id=conversation_id) + return list(conversation) + def get_last_message(self, *, conversation_id: str, role: ChatMessageRole | None = None) -> MessagePiece | None: """ Retrieve the most recent message from a conversation. @@ -240,6 +262,11 @@ def get_last_message(self, *, conversation_id: str, role: ChatMessageRole | None Returns: The last message piece, or None if no messages exist. """ + print_deprecation_message( + old_item="ConversationManager.get_last_message", + new_item="ConversationManager.get_last_message_async", + removed_in="1.4.0", + ) conversation = self.get_conversation(conversation_id) if not conversation: return None @@ -253,6 +280,33 @@ def get_last_message(self, *, conversation_id: str, role: ChatMessageRole | None return conversation[-1].get_piece() + @legacy_sync_override(lambda: ConversationManager.get_last_message) + async def get_last_message_async( + self, *, conversation_id: str, role: ChatMessageRole | None = None + ) -> MessagePiece | None: + """ + Retrieve the most recent message from a conversation. + + Args: + conversation_id: The ID of the conversation to retrieve from. + role: If provided, return only the last message matching this role. + + Returns: + The last message piece, or None if no messages exist. + """ + conversation = await self.get_conversation_async(conversation_id) + if not conversation: + return None + + if role: + for m in reversed(conversation): + piece = m.get_piece() + if piece.api_role == role: + return piece + return None + + return conversation[-1].get_piece() + def set_system_prompt( self, *, @@ -272,6 +326,11 @@ def set_system_prompt( Raises: ValueError: If target cannot handle the SYSTEM_PROMPT capability. """ + print_deprecation_message( + old_item="ConversationManager.set_system_prompt", + new_item="ConversationManager.set_system_prompt_async", + removed_in="1.4.0", + ) target.configuration.ensure_can_handle(capability=CapabilityName.SYSTEM_PROMPT) target.set_system_prompt( @@ -279,6 +338,30 @@ def set_system_prompt( conversation_id=conversation_id, ) + @legacy_sync_override(lambda: ConversationManager.set_system_prompt) + async def set_system_prompt_async( + self, + *, + target: PromptTarget, + conversation_id: str, + system_prompt: str, + ) -> None: + """ + Set or update the system prompt for a conversation. + + Args: + target: The target to set the system prompt on. Must handle the + SYSTEM_PROMPT capability (natively or via an ADAPT policy). + conversation_id: Unique identifier for the conversation. + system_prompt: The system prompt text. + + Raises: + ValueError: If target cannot handle the SYSTEM_PROMPT capability. + """ + target.configuration.ensure_can_handle(capability=CapabilityName.SYSTEM_PROMPT) + + (await target.set_system_prompt_async(system_prompt=system_prompt, conversation_id=conversation_id)) + async def initialize_context_async( self, *, @@ -431,11 +514,13 @@ async def add_prepended_conversation_to_memory_async( prepared_messages.append(message_copy) - self._memory.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target_identifier) + ( + await self._memory.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target_identifier) + ) ) for i, message in enumerate(prepared_messages): - self._memory.add_message_to_memory(request=message) + (await self._memory.add_message_to_memory_async(request=message)) logger.debug(f"Added prepended message {i + 1}/{len(prepared_messages)} to memory") return turn_count @@ -526,7 +611,7 @@ async def _process_prepended_conversation_async( return state existing_message_ids = { - message.get_piece().id for message in self.get_conversation(conversation_id=conversation_id) + message.get_piece().id for message in (await self.get_conversation_async(conversation_id=conversation_id)) } # Use the lower-level method to add messages to memory @@ -541,7 +626,7 @@ async def _process_prepended_conversation_async( ) persisted_messages = [ message - for message in self.get_conversation(conversation_id) + for message in (await self.get_conversation_async(conversation_id)) if message.get_piece().id not in existing_message_ids ] context.prepended_history_send_context = self.create_prepended_history_send_context( @@ -563,14 +648,16 @@ async def _process_prepended_conversation_async( # them up by conversation_id and filter to the last assistant turn. Only extract # true_false scores with score_value=False so attacks can use the rationale for # feedback without re-scoring. - memory_pieces = self._memory.get_message_pieces(conversation_id=conversation_id) + memory_pieces = await self._memory.get_message_pieces_async(conversation_id=conversation_id) assistant_pieces = [piece for piece in memory_pieces if piece.api_role == "assistant"] last_assistant_sequence = max((piece.sequence for piece in assistant_pieces), default=None) assistant_piece_ids = [ str(piece.id) for piece in assistant_pieces if piece.sequence == last_assistant_sequence ] existing_scores = ( - self._memory.get_prompt_scores(prompt_ids=assistant_piece_ids) if assistant_piece_ids else [] + (await self._memory.get_prompt_scores_async(prompt_ids=assistant_piece_ids)) + if assistant_piece_ids + else [] ) for score in existing_scores: if score.score_type != "true_false": diff --git a/pyrit/executor/attack/core/attack_strategy.py b/pyrit/executor/attack/core/attack_strategy.py index 45db4fd60a..226eded696 100644 --- a/pyrit/executor/attack/core/attack_strategy.py +++ b/pyrit/executor/attack/core/attack_strategy.py @@ -404,14 +404,14 @@ async def _on_post_execute_async( self._log_attack_outcome(event_data.result) - def _persist_result(self, *, result: AttackStrategyResultT) -> None: + async def _persist_result_async(self, *, result: AttackStrategyResultT) -> None: """ Persist a completed attack result. Args: result (AttackStrategyResultT): The completed result to persist. """ - self._memory.add_attack_results_to_memory(attack_results=[result]) + (await self._memory.add_attack_results_to_memory_async(attack_results=[result])) @staticmethod def _apply_attribution( @@ -545,7 +545,7 @@ async def _on_error_async( self._apply_targeted_harm_categories(context=context, result=error_result) try: - self._memory.add_attack_results_to_memory(attack_results=[error_result]) + (await self._memory.add_attack_results_to_memory_async(attack_results=[error_result])) except Exception as persistence_error: context._error_result_persistence_error = persistence_error @@ -861,7 +861,7 @@ async def execute_with_context_async(self, *, context: AttackStrategyContextT) - context._objective_target_conversation_lifecycle = None if context._persist_attack_result: - self._default_event_handler._persist_result(result=result) + (await self._default_event_handler._persist_result_async(result=result)) return result def _validate_scoring_expectation(self, *, context: AttackStrategyContextT) -> None: diff --git a/pyrit/executor/attack/multi_turn/crescendo.py b/pyrit/executor/attack/multi_turn/crescendo.py index 532c8d3897..eec207a166 100644 --- a/pyrit/executor/attack/multi_turn/crescendo.py +++ b/pyrit/executor/attack/multi_turn/crescendo.py @@ -362,8 +362,10 @@ async def _setup_async(self, *, context: CrescendoAttackContext) -> None: # Set the system prompt for adversarial chat via the manager, injecting Crescendo's # prepended-conversation context as an extra render value. - self._build_adversarial_manager(context=context).set_adversarial_system_prompt( - conversation_context=adversarial_chat_context, + ( + await self._build_adversarial_manager(context=context).set_adversarial_system_prompt_async( + conversation_context=adversarial_chat_context + ) ) # Initialize backtrack count in context @@ -733,7 +735,7 @@ async def _backtrack_memory_async(self, *, conversation_id: str) -> str: str: The new conversation ID after backtracking. """ # Access memory through the conversation manager's memory instance - new_conversation_id = self._memory.duplicate_conversation_excluding_last_turn( + new_conversation_id = await self._memory.duplicate_conversation_excluding_last_turn_async( conversation_id=conversation_id, ) self._logger.debug(f"Backtracked conversation from {conversation_id} to {new_conversation_id}") diff --git a/pyrit/executor/attack/multi_turn/multi_turn_attack_strategy.py b/pyrit/executor/attack/multi_turn/multi_turn_attack_strategy.py index 0aa621b7f5..0bbd885200 100644 --- a/pyrit/executor/attack/multi_turn/multi_turn_attack_strategy.py +++ b/pyrit/executor/attack/multi_turn/multi_turn_attack_strategy.py @@ -103,7 +103,7 @@ def __init__( logger=logger, ) - def _rotate_conversation_for_single_turn_target( + async def _rotate_conversation_for_single_turn_target_async( self, *, context: MultiTurnAttackContext[Any], @@ -132,20 +132,21 @@ def _rotate_conversation_for_single_turn_target( ) memory = CentralMemory.get_memory_instance() - messages = memory.get_conversation_messages(conversation_id=old_conversation_id) + messages = await memory.get_conversation_messages_async(conversation_id=old_conversation_id) system_messages = [message for message in messages if message.api_role == "system"] if system_messages: - new_conversation_id, pieces = memory.duplicate_messages(messages=system_messages) - memory.add_conversation_to_memory( - conversation=Conversation( - conversation_id=new_conversation_id, - target_identifier=self._objective_target.get_identifier(), + new_conversation_id, pieces = await memory.duplicate_messages_async(messages=system_messages) + ( + await memory.add_conversation_to_memory_async( + conversation=Conversation( + conversation_id=new_conversation_id, target_identifier=self._objective_target.get_identifier() + ) ) ) - memory.add_message_pieces_to_memory(message_pieces=pieces) + (await memory.add_message_pieces_to_memory_async(message_pieces=pieces)) context.session.conversation_id = new_conversation_id - persisted_messages = list(memory.get_conversation_messages(conversation_id=new_conversation_id)) + persisted_messages = list(await memory.get_conversation_messages_async(conversation_id=new_conversation_id)) context.prepended_history_send_context = ConversationManager.create_prepended_history_send_context( target=self._objective_target, conversation_id=new_conversation_id, diff --git a/pyrit/executor/attack/multi_turn/red_teaming.py b/pyrit/executor/attack/multi_turn/red_teaming.py index 95f9661d96..1a6ae4ee2e 100644 --- a/pyrit/executor/attack/multi_turn/red_teaming.py +++ b/pyrit/executor/attack/multi_turn/red_teaming.py @@ -292,7 +292,7 @@ async def _setup_async(self, *, context: MultiTurnAttackContext[Any]) -> None: # The adversarial conversation manager owns rendering and setting the system prompt. # ``set_system_prompt`` rejects any conversation that already has messages, so this must run # before we hydrate the adversarial chat with the swapped prepended turns below. - self._build_adversarial_manager(context=context).set_adversarial_system_prompt() + (await self._build_adversarial_manager(context=context).set_adversarial_system_prompt_async()) # Set up adversarial chat with prepended conversation if context.prepended_conversation: @@ -302,14 +302,16 @@ async def _setup_async(self, *, context: MultiTurnAttackContext[Any]) -> None: adversarial_chat_conversation_id=context.session.adversarial_chat_conversation_id, ) - self._memory.add_conversation_to_memory( - conversation=Conversation( - conversation_id=context.session.adversarial_chat_conversation_id, - target_identifier=self._adversarial_chat.get_identifier(), + ( + await self._memory.add_conversation_to_memory_async( + conversation=Conversation( + conversation_id=context.session.adversarial_chat_conversation_id, + target_identifier=self._adversarial_chat.get_identifier(), + ) ) ) for msg in adversarial_messages: - self._memory.add_message_to_memory(request=msg) + (await self._memory.add_message_to_memory_async(request=msg)) async def _perform_async(self, *, context: MultiTurnAttackContext[Any]) -> AttackResult: """ @@ -537,7 +539,7 @@ async def _send_prompt_to_objective_target_async( """ logger.info(f"Sending prompt to target: {message.get_value()[:50]}...") - self._rotate_conversation_for_single_turn_target(context=context) + (await self._rotate_conversation_for_single_turn_target_async(context=context)) with execution_context( component_role=ComponentRole.OBJECTIVE_TARGET, diff --git a/pyrit/executor/attack/multi_turn/simulated_conversation.py b/pyrit/executor/attack/multi_turn/simulated_conversation.py index 20efe477af..775ef6fc7d 100644 --- a/pyrit/executor/attack/multi_turn/simulated_conversation.py +++ b/pyrit/executor/attack/multi_turn/simulated_conversation.py @@ -233,7 +233,7 @@ async def generate_simulated_conversation_async( # Extract the conversation from memory and filter for prepended_conversation use memory = CentralMemory.get_memory_instance() - raw_messages = list(memory.get_conversation_messages(conversation_id=result.conversation_id)) + raw_messages = list(await memory.get_conversation_messages_async(conversation_id=result.conversation_id)) # Filter out system messages - keep the actual conversation # System prompts are set separately on each target during attack execution @@ -343,7 +343,7 @@ async def _generate_next_message_async( attack_strategy_name="SimulatedConversation", memory_labels=memory_labels, ) - manager.set_adversarial_system_prompt(conversation_context=conversation_context) + (await manager.set_adversarial_system_prompt_async(conversation_context=conversation_context)) reply = await manager.generate_adversarial_reply_async( prompt_text="Generate the next user message based on the instructions above.", ) diff --git a/pyrit/executor/attack/multi_turn/tree_of_attacks.py b/pyrit/executor/attack/multi_turn/tree_of_attacks.py index d58d2f58c7..7991939046 100644 --- a/pyrit/executor/attack/multi_turn/tree_of_attacks.py +++ b/pyrit/executor/attack/multi_turn/tree_of_attacks.py @@ -530,7 +530,7 @@ async def initialize_with_prepended_conversation_async( target=self._objective_target, ) persisted_messages = list( - self._memory.get_conversation_messages(conversation_id=self.objective_target_conversation_id) + await self._memory.get_conversation_messages_async(conversation_id=self.objective_target_conversation_id) ) self._prepended_message_count = len(persisted_messages) self._prepended_history_send_context = conversation_manager.create_prepended_history_send_context( @@ -582,7 +582,7 @@ async def send_prompt_async(self, objective: str) -> None: try: # Check if we have an initial prompt to use (bypasses adversarial generation) - if self._initial_prompt and self._is_first_turn(): + if self._initial_prompt and (await self._is_first_turn_async()): response = await self._send_initial_prompt_to_target_async() else: # Generate adversarial prompt @@ -678,7 +678,7 @@ async def _send_prompt_to_target_async(self, prompt: str) -> Message: message = self._modality_router.build_objective_input_message( text=prompt, last_response=self.last_response, - turn_index=0 if self._is_first_turn() else 1, + turn_index=0 if (await self._is_first_turn_async()) else 1, ) # Send prompt with configured converters @@ -937,7 +937,7 @@ def _handle_unexpected_error(self, error: Exception) -> None: logger.error(f"Node {self.node_id}: Unexpected error during execution: {error}") self.error_message = f"Execution error: {str(error)}" - def duplicate(self) -> _TreeOfAttacksNode: + async def duplicate_async(self) -> _TreeOfAttacksNode: """ Create a duplicate of this node for branching. @@ -961,7 +961,11 @@ def duplicate(self) -> _TreeOfAttacksNode: duplicating successful nodes and pruning unsuccessful ones. """ source_messages = filter_non_replayable_messages( - messages=list(self._memory.get_conversation_messages(conversation_id=self.objective_target_conversation_id)) + messages=list( + await self._memory.get_conversation_messages_async( + conversation_id=self.objective_target_conversation_id + ) + ) ) _validate_stateful_clone_history_compatibility( objective_target=self._objective_target, @@ -991,12 +995,14 @@ def duplicate(self) -> _TreeOfAttacksNode: prepended_conversation_config=self._prepended_conversation_config, ) - duplicate_node.objective_target_conversation_id = self._memory.duplicate_conversation( + duplicate_node.objective_target_conversation_id = await self._memory.duplicate_conversation_async( conversation_id=self.objective_target_conversation_id ) duplicated_messages = filter_non_replayable_messages( messages=list( - self._memory.get_conversation_messages(conversation_id=duplicate_node.objective_target_conversation_id) + await self._memory.get_conversation_messages_async( + conversation_id=duplicate_node.objective_target_conversation_id + ) ) ) if self._prepended_history_send_context: @@ -1019,7 +1025,7 @@ def duplicate(self) -> _TreeOfAttacksNode: bootstrap_message_ids=tuple(message.get_piece().id for message in duplicated_messages), ) - duplicate_node.adversarial_chat_conversation_id = self._memory.duplicate_conversation( + duplicate_node.adversarial_chat_conversation_id = await self._memory.duplicate_conversation_async( conversation_id=self.adversarial_chat_conversation_id ) @@ -1175,7 +1181,7 @@ async def _generate_single_red_teaming_prompt_async( str: The generated adversarial prompt text. """ # Check if this is the first turn or subsequent turn - if self._is_first_turn(): + if await self._is_first_turn_async(): prompt_text = await self._generate_first_turn_prompt_async(objective) else: prompt_text = await self._generate_subsequent_turn_prompt_async(objective) @@ -1210,7 +1216,7 @@ def _generate_off_topic_feedback_prompt( f"Respond with a JSON object containing a 'prompt' field." ) - def _is_first_turn(self) -> bool: + async def _is_first_turn_async(self) -> bool: """ Check if this is the first turn of the conversation. @@ -1222,7 +1228,9 @@ def _is_first_turn(self) -> bool: bool: True if the objective target conversation contains no messages beyond the prepended conversation (first turn), False otherwise (subsequent turns). """ - target_messages = self._memory.get_conversation_messages(conversation_id=self.objective_target_conversation_id) + target_messages = await self._memory.get_conversation_messages_async( + conversation_id=self.objective_target_conversation_id + ) return len(target_messages) <= self._prepended_message_count async def _generate_first_turn_prompt_async(self, objective: str) -> str: @@ -1252,9 +1260,10 @@ async def _generate_first_turn_prompt_async(self, objective: str) -> str: # and sets it on this node's adversarial conversation. Owning setup in the manager keeps # schema resolution and the system-prompt contract identical across every adversarial-chat # attack rather than hand-rolled here. - self._build_adversarial_manager().set_adversarial_system_prompt( - desired_prefix=self._desired_response_prefix, - conversation_context=self._conversation_context, + ( + await self._build_adversarial_manager().set_adversarial_system_prompt_async( + desired_prefix=self._desired_response_prefix, conversation_context=self._conversation_context + ) ) logger.debug(f"Node {self.node_id}: Using initial seed prompt for first turn") @@ -1290,7 +1299,9 @@ async def _generate_subsequent_turn_prompt_async(self, objective: str) -> str: one prior exchange. """ # Get conversation history - target_messages = self._memory.get_conversation_messages(conversation_id=self.objective_target_conversation_id) + target_messages = await self._memory.get_conversation_messages_async( + conversation_id=self.objective_target_conversation_id + ) # Extract the last assistant response assistant_responses = [r for r in target_messages if r.get_piece().api_role == "assistant"] @@ -1336,7 +1347,7 @@ async def _get_response_score_async(self, response_id: str) -> str: list. It takes the first score if multiple scores are associated with the response, which is typically the objective score in the TAP algorithm context. """ - scores = self._memory.get_prompt_scores(prompt_ids=[str(response_id)]) + scores = await self._memory.get_prompt_scores_async(prompt_ids=[str(response_id)]) if scores: return str(normalize_score_to_float(scores[0])) return "unavailable" @@ -1937,13 +1948,13 @@ async def _perform_async(self, *, context: TAPAttackContext) -> TAPAttackResult: # Check termination conditions if self._is_objective_achieved(context): self._logger.info("TAP attack achieved objective - attack successful!") - return self._create_success_result(context) + return await self._create_success_result_async(context) if self._all_nodes_pruned(context): self._logger.warning("All branches have been pruned - stopping attack.") break - return self._create_failure_result(context) + return await self._create_failure_result_async(context) async def _teardown_async(self, *, context: TAPAttackContext) -> None: """ @@ -1976,7 +1987,7 @@ async def _prepare_nodes_for_iteration_async(self, context: TAPAttackContext) -> if not context.nodes: await self._initialize_first_level_nodes_async(context) else: - self._branch_existing_nodes(context) + (await self._branch_existing_nodes_async(context)) async def _execute_iteration_async(self, context: TAPAttackContext) -> None: """ @@ -2077,7 +2088,7 @@ async def _initialize_first_level_nodes_async(self, context: TAPAttackContext) - # Clear next_message after initialization (it's been used by the first node) context.next_message = None - def _branch_existing_nodes(self, context: TAPAttackContext) -> None: + async def _branch_existing_nodes_async(self, context: TAPAttackContext) -> None: """ Branch existing nodes to create new exploration paths. @@ -2093,7 +2104,7 @@ def _branch_existing_nodes(self, context: TAPAttackContext) -> None: for node in context.nodes: for _ in range(self._configuration.branching_factor - 1): - cloned_node = node.duplicate() + cloned_node = await node.duplicate_async() # Add the adversarial chat conversation ID of the duplicated node to the context's tracking context.related_conversations.add( ConversationReference( @@ -2394,7 +2405,7 @@ def _create_on_topic_scorer(self, objective: str) -> Scorer | None: ) ) - def _create_success_result(self, context: TAPAttackContext) -> TAPAttackResult: + async def _create_success_result_async(self, context: TAPAttackContext) -> TAPAttackResult: """ Create a success result for the attack. @@ -2412,13 +2423,11 @@ def _create_success_result(self, context: TAPAttackContext) -> TAPAttackResult: score_value = normalize_score_to_float(context.best_objective_score) outcome_reason = f"Achieved score {score_value:.2f} >= threshold {self._attack_scoring_config.threshold}" - return self._create_attack_result( - context=context, - outcome=AttackOutcome.SUCCESS, - outcome_reason=outcome_reason, + return await self._create_attack_result_async( + context=context, outcome=AttackOutcome.SUCCESS, outcome_reason=outcome_reason ) - def _create_failure_result(self, context: TAPAttackContext) -> TAPAttackResult: + async def _create_failure_result_async(self, context: TAPAttackContext) -> TAPAttackResult: """ Create a failure result for the attack. @@ -2436,7 +2445,7 @@ def _create_failure_result(self, context: TAPAttackContext) -> TAPAttackResult: """ best_score = context.best_objective_score if best_score is not None and attack_outcome_from_score(best_score) is AttackOutcome.UNDETERMINED: - return self._create_attack_result( + return await self._create_attack_result_async( context=context, outcome=AttackOutcome.UNDETERMINED, outcome_reason=getattr(best_score, "score_rationale", None) @@ -2446,13 +2455,11 @@ def _create_failure_result(self, context: TAPAttackContext) -> TAPAttackResult: normalized_best = normalize_score_to_float(best_score) outcome_reason = f"Did not achieve threshold score. Best score: {normalized_best:.2f}" - return self._create_attack_result( - context=context, - outcome=AttackOutcome.FAILURE, - outcome_reason=outcome_reason, + return await self._create_attack_result_async( + context=context, outcome=AttackOutcome.FAILURE, outcome_reason=outcome_reason ) - def _create_attack_result( + async def _create_attack_result_async( self, *, context: TAPAttackContext, @@ -2478,9 +2485,8 @@ def _create_attack_result( about the attack execution, including conversation ID, objective, outcome, outcome reason, executed turns, last response, last score, and additional metadata. """ - last_response = self._get_result_response( - conversation_id=context.best_conversation_id, - score=context.best_objective_score, + last_response = await self._get_result_response_async( + conversation_id=context.best_conversation_id, score=context.best_objective_score ) # Get auxiliary scores from the best node if available @@ -2513,7 +2519,7 @@ def _create_attack_result( return result - def _get_result_response( + async def _get_result_response_async( self, *, conversation_id: str | None, @@ -2551,10 +2557,7 @@ def _get_result_response( if not message_piece_id: return None - responses = self._memory.get_message_pieces( - conversation_id=conversation_id, - role="assistant", - ) + responses = await self._memory.get_message_pieces_async(conversation_id=conversation_id, role="assistant") return next( ( response @@ -2565,9 +2568,9 @@ def _get_result_response( None, ) - return self._get_last_response_from_conversation(conversation_id) + return await self._get_last_response_from_conversation_async(conversation_id) - def _get_last_response_from_conversation(self, conversation_id: str | None) -> MessagePiece | None: + async def _get_last_response_from_conversation_async(self, conversation_id: str | None) -> MessagePiece | None: """ Retrieve the last response from a conversation. @@ -2586,7 +2589,7 @@ def _get_last_response_from_conversation(self, conversation_id: str | None) -> M if not conversation_id: return None - responses = self._memory.get_message_pieces(conversation_id=conversation_id) + responses = await self._memory.get_message_pieces_async(conversation_id=conversation_id) return responses[-1] if responses else None def _get_auxiliary_scores_summary(self, nodes: list[_TreeOfAttacksNode]) -> dict[str, float]: diff --git a/pyrit/executor/attack/streaming/barge_in.py b/pyrit/executor/attack/streaming/barge_in.py index 695152f86a..79d651c156 100644 --- a/pyrit/executor/attack/streaming/barge_in.py +++ b/pyrit/executor/attack/streaming/barge_in.py @@ -139,7 +139,8 @@ async def _setup_async(self, *, context: BargeInAttackContext[Any]) -> None: if not context.conversation_id: context.conversation_id = str(uuid.uuid4()) existing_message_ids = { - message.get_piece().id for message in self._conversation_manager.get_conversation(context.conversation_id) + message.get_piece().id + for message in (await self._conversation_manager.get_conversation_async(context.conversation_id)) } await self._conversation_manager.initialize_context_async( context=context, @@ -148,7 +149,7 @@ async def _setup_async(self, *, context: BargeInAttackContext[Any]) -> None: request_converters=self._request_converters, prepended_conversation_config=self._prepended_conversation_config, ) - persisted_messages = self._conversation_manager.get_conversation(context.conversation_id) + persisted_messages = await self._conversation_manager.get_conversation_async(context.conversation_id) context.prepended_conversation = [ message for message in persisted_messages if message.get_piece().id not in existing_message_ids ] diff --git a/pyrit/executor/benchmark/fairness_bias.py b/pyrit/executor/benchmark/fairness_bias.py index 7475efe11d..b302032364 100644 --- a/pyrit/executor/benchmark/fairness_bias.py +++ b/pyrit/executor/benchmark/fairness_bias.py @@ -184,7 +184,7 @@ async def _perform_async(self, *, context: FairnessBiasBenchmarkContext) -> Atta for experiment_num in range(context.num_experiments): attack_result = await self._run_experiment_async(context=context) - experiment_data = self._format_experiment_results( + experiment_data = await self._format_experiment_results_async( context=context, attack_result=attack_result, experiment_num=experiment_num ) results_list.append(experiment_data) @@ -228,7 +228,7 @@ async def _run_experiment_async(self, context: FairnessBiasBenchmarkContext) -> memory_labels=context.memory_labels, ) - def _format_experiment_results( + async def _format_experiment_results_async( self, context: FairnessBiasBenchmarkContext, attack_result: AttackResult, experiment_num: int ) -> dict[str, Any]: """ @@ -242,7 +242,9 @@ def _format_experiment_results( Returns: Dict: dictionary with components from experiment parsed and formatted """ - conversation_pieces = self.memory.get_conversation_messages(conversation_id=attack_result.conversation_id) + conversation_pieces = await self.memory.get_conversation_messages_async( + conversation_id=attack_result.conversation_id + ) response = conversation_pieces[1].get_value() if len(conversation_pieces) >= 2 else "" subject_name = self._extract_name(response) return { diff --git a/pyrit/executor/promptgen/anecdoctor.py b/pyrit/executor/promptgen/anecdoctor.py index 9e3e5dbca4..c097bbcb3a 100644 --- a/pyrit/executor/promptgen/anecdoctor.py +++ b/pyrit/executor/promptgen/anecdoctor.py @@ -215,9 +215,10 @@ async def _setup_async(self, *, context: AnecdoctorContext) -> None: system_prompt = self._system_prompt_template.format(language=context.language, type=context.content_type) # Configure the target with the system prompt - self._objective_target.set_system_prompt( - system_prompt=system_prompt, - conversation_id=context.conversation_id, + ( + await self._objective_target.set_system_prompt_async( + system_prompt=system_prompt, conversation_id=context.conversation_id + ) ) async def _perform_async(self, *, context: AnecdoctorContext) -> AnecdoctorResult: @@ -374,9 +375,10 @@ async def _extract_knowledge_graph_async(self, *, context: AnecdoctorContext) -> kg_conversation_id = str(uuid.uuid4()) # Set system prompt on processing model - self._processing_model.set_system_prompt( - system_prompt=kg_system_prompt, - conversation_id=kg_conversation_id, + ( + await self._processing_model.set_system_prompt_async( + system_prompt=kg_system_prompt, conversation_id=kg_conversation_id + ) ) # Format examples for knowledge graph extraction using few-shot format diff --git a/pyrit/executor/promptgen/fuzzer/fuzzer.py b/pyrit/executor/promptgen/fuzzer/fuzzer.py index 8158873f08..575fd7ffba 100644 --- a/pyrit/executor/promptgen/fuzzer/fuzzer.py +++ b/pyrit/executor/promptgen/fuzzer/fuzzer.py @@ -14,6 +14,8 @@ from colorama import Fore, Style from pydantic import Field +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.common.text_helper import escape_control_characters from pyrit.common.utils import combine_dict, get_kwarg_param from pyrit.exceptions import MissingPromptPlaceholderException, pyrit_placeholder_retry @@ -280,9 +282,26 @@ def print_formatted(self, *, enable_colors: bool = True, width: int = 100) -> No enable_colors (bool): Whether to enable ANSI color output. Defaults to True. width (int): Maximum width for text wrapping. Defaults to 100. """ + print_deprecation_message( + old_item="FuzzerResult.print_formatted", + new_item="FuzzerResult.print_formatted_async", + removed_in="1.4.0", + ) printer = FuzzerResultPrinter(enable_colors=enable_colors, width=width) printer.print_result(self) + @legacy_sync_override(lambda: FuzzerResult.print_formatted) + async def print_formatted_async(self, *, enable_colors: bool = True, width: int = 100) -> None: + """ + Print the result using FuzzerResultPrinter with custom formatting options. + + Args: + enable_colors (bool): Whether to enable ANSI color output. Defaults to True. + width (int): Maximum width for text wrapping. Defaults to 100. + """ + printer = FuzzerResultPrinter(enable_colors=enable_colors, width=width) + (await printer.print_result_async(self)) + def print_templates(self) -> None: """ Print only the successful templates (equivalent to original attack method). @@ -370,12 +389,31 @@ def print_result(self, result: FuzzerResult) -> None: Args: result (FuzzerResult): The fuzzer result to print. """ + print_deprecation_message( + old_item="FuzzerResultPrinter.print_result", + new_item="FuzzerResultPrinter.print_result_async", + removed_in="1.4.0", + ) self._print_header(result) self._print_summary(result) self._print_templates(result) self._print_conversations(result) self._print_footer() + @legacy_sync_override(lambda: FuzzerResultPrinter.print_result) + async def print_result_async(self, result: FuzzerResult) -> None: + """ + Print the complete fuzzer result to console. + + Args: + result (FuzzerResult): The fuzzer result to print. + """ + self._print_header(result) + self._print_summary(result) + self._print_templates(result) + (await self._print_conversations_async(result)) + self._print_footer() + def _print_header(self, result: FuzzerResult) -> None: """ Print the header for the fuzzer result. @@ -481,6 +519,55 @@ def _print_conversations(self, result: FuzzerResult) -> None: self._print_colored(f"{self._indent * 3} Score: {score_value} | {score.score_rationale}", Fore.CYAN) print() + async def _print_conversations_async(self, result: FuzzerResult) -> None: + """ + Print the conversations from successful jailbreaks. + + Args: + result (FuzzerResult): The fuzzer result containing conversation IDs. + """ + self._print_section_header("Jailbreak Conversations") + + if not result.jailbreak_conversation_ids: + self._print_colored(f"{self._indent}❌ No jailbreak conversations found.", Fore.RED) + return + + self._print_colored( + f"{self._indent} Found {len(result.jailbreak_conversation_ids)} jailbreak conversation(s):", + Style.BRIGHT, + Fore.GREEN, + ) + + for i, conversation_id in enumerate(result.jailbreak_conversation_ids, 1): + print() + self._print_colored(f"{self._indent}Conversation {i} (ID: {conversation_id}):", Style.BRIGHT, Fore.MAGENTA) + self._print_colored("─" * (self._width - len(self._indent)), Fore.MAGENTA) + + target_messages = await self._memory.get_message_pieces_async(conversation_id=str(conversation_id)) + + if not target_messages: + self._print_colored(f"{self._indent * 2}No conversation data found", Fore.YELLOW) + continue + + for message in target_messages: + if message.api_role == "user": + self._print_colored(f"{self._indent * 2} USER:", Style.BRIGHT, Fore.BLUE) + self._print_wrapped_text(message.converted_value, Fore.BLUE) + else: + self._print_colored(f"{self._indent * 2} {message.api_role.upper()}:", Style.BRIGHT, Fore.YELLOW) + self._print_wrapped_text(message.converted_value, Fore.YELLOW) + + # Print scores if available + scores = await self._memory.get_prompt_scores_async(prompt_ids=[str(message.id)]) + if scores: + score = scores[0] + try: + score_value = str(score.get_value()) + except UndeterminedScoreError: + score_value = "undetermined" + self._print_colored(f"{self._indent * 3} Score: {score_value} | {score.score_rationale}", Fore.CYAN) + print() + def _print_footer(self) -> None: """ Print a footer to complete the result display. diff --git a/pyrit/executor/promptgen/fuzzer/fuzzer_converter_base.py b/pyrit/executor/promptgen/fuzzer/fuzzer_converter_base.py index 5c730638be..a7e4f450a8 100644 --- a/pyrit/executor/promptgen/fuzzer/fuzzer_converter_base.py +++ b/pyrit/executor/promptgen/fuzzer/fuzzer_converter_base.py @@ -82,9 +82,10 @@ async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text conversation_id = str(uuid.uuid4()) - self.converter_target.set_system_prompt( - system_prompt=self.system_prompt, - conversation_id=conversation_id, + ( + await self.converter_target.set_system_prompt_async( + system_prompt=self.system_prompt, conversation_id=conversation_id + ) ) formatted_prompt = f"===={self.template_label} BEGINS====\n{prompt}\n===={self.template_label} ENDS====" diff --git a/pyrit/executor/promptgen/fuzzer/fuzzer_crossover_converter.py b/pyrit/executor/promptgen/fuzzer/fuzzer_crossover_converter.py index 9cc3876f8a..7479f35da1 100644 --- a/pyrit/executor/promptgen/fuzzer/fuzzer_crossover_converter.py +++ b/pyrit/executor/promptgen/fuzzer/fuzzer_crossover_converter.py @@ -78,9 +78,10 @@ async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text conversation_id = str(uuid.uuid4()) - self.converter_target.set_system_prompt( - system_prompt=self.system_prompt, - conversation_id=conversation_id, + ( + await self.converter_target.set_system_prompt_async( + system_prompt=self.system_prompt, conversation_id=conversation_id + ) ) formatted_prompt = f"===={self.template_label} BEGINS====\n{prompt}\n===={self.template_label} ENDS====" diff --git a/pyrit/executor/promptgen/fuzzer/fuzzer_expand_converter.py b/pyrit/executor/promptgen/fuzzer/fuzzer_expand_converter.py index 0812da760c..01ec510187 100644 --- a/pyrit/executor/promptgen/fuzzer/fuzzer_expand_converter.py +++ b/pyrit/executor/promptgen/fuzzer/fuzzer_expand_converter.py @@ -55,9 +55,10 @@ async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text conversation_id = str(uuid.uuid4()) - self.converter_target.set_system_prompt( - system_prompt=self.system_prompt, - conversation_id=conversation_id, + ( + await self.converter_target.set_system_prompt_async( + system_prompt=self.system_prompt, conversation_id=conversation_id + ) ) formatted_prompt = f"===={self.template_label} BEGINS====\n{prompt}\n===={self.template_label} ENDS====" diff --git a/pyrit/executor/workflow/xpia.py b/pyrit/executor/workflow/xpia.py index dc2b9ef179..8381fde697 100644 --- a/pyrit/executor/workflow/xpia.py +++ b/pyrit/executor/workflow/xpia.py @@ -368,16 +368,18 @@ async def _execute_processing_async(self, *, context: XPIAContext) -> str: processing_response = await context.processing_callback() if self._memory is None: raise RuntimeError("Memory not initialized") - self._memory.add_message_to_memory( - request=Message( - message_pieces=[ - MessagePiece( - conversation_id=context.processing_conversation_id, - original_value=processing_response, - original_value_data_type="text", - role="assistant", - ) - ], + ( + await self._memory.add_message_to_memory_async( + request=Message( + message_pieces=[ + MessagePiece( + conversation_id=context.processing_conversation_id, + original_value=processing_response, + original_value_data_type="text", + role="assistant", + ) + ], + ) ) ) self._logger.info(f'Received the following response from the processing target "{processing_response}"') diff --git a/pyrit/memory/_scenario_history.py b/pyrit/memory/_scenario_history.py index e1fcb41f87..1742f61103 100644 --- a/pyrit/memory/_scenario_history.py +++ b/pyrit/memory/_scenario_history.py @@ -134,7 +134,7 @@ def get_page( ScenarioResultEntry.timestamp.desc(), ScenarioResultEntry.id.desc(), ).limit(limit + 1) - with closing(self._memory.get_session()) as session: + with closing(self._memory._get_session()) as session: rows = session.execute(statement).all() page_rows = rows[:limit] diff --git a/pyrit/memory/azure_sql_memory.py b/pyrit/memory/azure_sql_memory.py index 651bfb76aa..a862dc8a24 100644 --- a/pyrit/memory/azure_sql_memory.py +++ b/pyrit/memory/azure_sql_memory.py @@ -1,6 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import asyncio import logging import struct import uuid @@ -21,13 +22,15 @@ literal_column, text, ) +from sqlalchemy.engine import make_url from sqlalchemy.engine.base import Engine from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine from sqlalchemy.orm import InstrumentedAttribute, sessionmaker from sqlalchemy.orm.session import Session from sqlalchemy.sql.expression import ColumnElement, TextClause -from pyrit.auth.azure_auth import AzureAuth +from pyrit.auth.azure_auth import AsyncAzureAuth, AzureAuth from pyrit.common import default_values from pyrit.common.singleton import Singleton from pyrit.memory.memory_interface import MemoryInterface @@ -80,6 +83,7 @@ def __init__( verbose: bool = False, skip_schema_migration: bool = False, silent: bool = False, + _defer_initialization: bool = False, ) -> None: """ Initialize an Azure SQL Memory backend. @@ -109,28 +113,40 @@ def __init__( self._auth_token: AccessToken | None = None self._auth_token_expiry: int | None = None + self._async_auth: dict[asyncio.AbstractEventLoop, AsyncAzureAuth] = {} + self._verbose = verbose + self._silent = silent + self._skip_schema_migration = skip_schema_migration self.results_path = self._results_container_url self.engine = self._create_engine(has_echo=verbose) # Generate the initial auth token - self._create_auth_token() + if not _defer_initialization: + self._create_auth_token() # Enable token-based authorization self._enable_azure_authorization() self.SessionFactory = sessionmaker(bind=self.engine, class_=MemorySession) + if not _defer_initialization: + self._initialize_schema() + + super().__init__() + self._initialized = not _defer_initialization + + def _initialize_schema(self) -> None: prod_connection_string = default_values.get_non_required_value( env_var_name=self.AZURE_SQL_DB_CONNECTION_STRING_PROD ) is_prod = bool(prod_connection_string) and self._connection_string == prod_connection_string - should_migrate = not is_prod and not skip_schema_migration + should_migrate = not is_prod and not self._skip_schema_migration if should_migrate: # Non-production: run schema migration (upgrade + check). - self._run_schema_migration(silent=silent) + self._run_schema_migration(silent=self._silent) else: # Production or skip_schema_migration=True: verify schema compatibility # without modifying the database. Logs a warning on mismatch but does not @@ -138,7 +154,7 @@ def __init__( from alembic.util.exc import AutogenerateDiffsDetected, CommandError try: - self._check_schema_migration(silent=silent) + self._check_schema_migration(silent=self._silent) except (AutogenerateDiffsDetected, CommandError) as e: logger.warning( "Schema mismatch detected. " @@ -147,7 +163,58 @@ def __init__( f"Schema was NOT modified. Details: {e}" ) - super().__init__() + def _create_async_engine(self) -> AsyncEngine: + import aioodbc + + url = make_url(self._connection_string).set(drivername="mssql+aioodbc") + + async def connect_async() -> aioodbc.Connection: + _, params = engine.dialect.create_connect_args(url) + dsn = ";".join( + part + for part in params.pop("dsn").split(";") + if part.partition("=")[0].strip().lower() != "trusted_connection" + ) + token = await auth.get_access_token_async() + token_bytes = token.token.encode("utf-16-le") + attrs = dict(params.pop("attrs_before", {})) + attrs[self.SQL_COPT_SS_ACCESS_TOKEN] = struct.pack(f" None: + """Close the current loop's engine and its owned Azure credential.""" + loop = asyncio.get_running_loop() + for closed_loop in list(self._async_auth): + if closed_loop.is_closed(): + await self._dispose_loop_resources_async(closed_loop) + await self._dispose_loop_resources_async(loop) + + async def _dispose_loop_resources_async(self, loop: asyncio.AbstractEventLoop) -> None: + engine = self._async_engines.get(loop) + try: + if engine is not None: + if loop.is_closed(): + engine.sync_engine.dispose(close=False) + logger.warning("Discarding Azure SQL pool owned by a closed event loop.") + else: + await engine.dispose() + finally: + self._async_engines.pop(loop, None) + auth = self._async_auth.pop(loop, None) + if auth is not None: + await auth.close_async() @staticmethod def _resolve_sas_token(env_var_name: str, passed_value: str | None = None) -> str | None: @@ -194,7 +261,8 @@ def _refresh_token_if_needed(self) -> None: RuntimeError: If auth token expiry was not initialized. """ if self._auth_token_expiry is None: - raise RuntimeError("Auth token expiry not initialized; call _create_auth_token() first") + self._create_auth_token() + return if datetime.now(UTC) >= datetime.fromtimestamp(float(self._auth_token_expiry), tz=UTC) - timedelta(minutes=5): logger.info("Refreshing Microsoft Entra ID access token...") self._create_auth_token() @@ -497,7 +565,7 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str | Sequence ) return and_(*are_parts) - def get_unique_attack_class_names(self) -> list[str]: + def _execute_get_unique_attack_class_names(self) -> list[str]: """ Azure SQL implementation: extract unique class_name values from the atomic_attack_identifier JSON column. @@ -505,7 +573,7 @@ def get_unique_attack_class_names(self) -> list[str]: Returns: Sorted list of unique attack class name strings. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = session.execute( text( """SELECT DISTINCT JSON_VALUE(atomic_attack_identifier, @@ -518,7 +586,7 @@ def get_unique_attack_class_names(self) -> list[str]: ).fetchall() return sorted(row[0] for row in rows) - def get_unique_converter_class_names(self) -> list[str]: + def _execute_get_unique_converter_class_names(self) -> list[str]: """ Azure SQL implementation: extract unique converter class_name values from the children.attack_technique.children.attack.children.request_converters array @@ -527,7 +595,7 @@ def get_unique_converter_class_names(self) -> list[str]: Returns: Sorted list of unique converter class name strings. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = session.execute( text( """SELECT DISTINCT JSON_VALUE(c.value, '$.class_name') AS cls @@ -540,7 +608,7 @@ 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]: + def _execute_get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, ConversationStats]: """ Azure SQL implementation: lightweight aggregate stats per conversation. @@ -588,7 +656,7 @@ def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str """ ) - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = session.execute(sql, params).fetchall() result: dict[str, ConversationStats] = {} @@ -834,7 +902,7 @@ def _get_scenario_plan_unit_subqueries(self, *, scenario_result_ids: Sequence[uu ) return planned_units, plan_seeds - def get_session(self) -> Session: + def _get_sync_session(self) -> Session: """ Provide a session for database operations. diff --git a/pyrit/memory/memory_interface.py b/pyrit/memory/memory_interface.py index e6bae1e363..f6d879b4e2 100644 --- a/pyrit/memory/memory_interface.py +++ b/pyrit/memory/memory_interface.py @@ -8,23 +8,27 @@ import json import logging import re +import threading import uuid import weakref -from collections.abc import Collection, Iterator, Mapping, MutableSequence, Sequence +from collections.abc import Callable, Collection, Iterator, Mapping, MutableSequence, Sequence from contextlib import closing +from contextvars import ContextVar from dataclasses import dataclass from datetime import UTC, datetime, timedelta from types import MappingProxyType -from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, TypeVar, cast +from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, ParamSpec, TypeVar, cast from urllib.parse import urlparse from sqlalchemy import MetaData, and_, case, exists, false, func, literal, not_, or_, select, update from sqlalchemy.engine.base import Engine from sqlalchemy.exc import IntegrityError, SQLAlchemyError +from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession from sqlalchemy.orm import joinedload from sqlalchemy.orm.attributes import InstrumentedAttribute, flag_modified from sqlalchemy.orm.session import Session +from pyrit.common.async_compatibility import legacy_sync_override, run_legacy_sync_async from pyrit.common.deprecation import print_deprecation_message if TYPE_CHECKING: @@ -54,7 +58,7 @@ SeedIdentifierEntry, TargetIdentifierEntry, ) -from pyrit.memory.memory_session import _begin_sqlite_write, _lock_observations +from pyrit.memory.memory_session import MemorySession, _begin_sqlite_write, _lock_observations from pyrit.memory.storage import ( DataTypeSerializer, StorageIO, @@ -97,6 +101,7 @@ SeedGroup, SeedIdentifier, SeedObjective, + SeedPrompt, SeedType, TargetIdentifier, group_conversation_message_pieces_by_sequence, @@ -115,6 +120,8 @@ Model = TypeVar("Model") IdentifierModel = TypeVar("IdentifierModel", bound=ComponentIdentifier) +OperationArgs = ParamSpec("OperationArgs") +OperationResult = TypeVar("OperationResult") def _normalize_attribution_filter_values(*, field: str, raw: str | Sequence[object]) -> tuple[str, ...]: @@ -379,11 +386,214 @@ def __init__(self, embedding_model: Any | None = None) -> None: but also includes overhead. """ self.memory_embedding = embedding_model + self._operation_session: ContextVar[Session | None] = ContextVar("memory_operation_session", default=None) + self._async_engines: dict[asyncio.AbstractEventLoop, AsyncEngine] = {} + self._initialized = False + self._initialization_lock = threading.Lock() self._init_storage_io() # Ensure cleanup at process exit self.cleanup() + def _create_async_engine(self) -> AsyncEngine: + """ + Create an engine owned by the current event loop. + + Raises: + NotImplementedError: If a legacy backend has no native async driver. + """ + raise NotImplementedError("Implement _create_async_engine to support native async sessions.") + + def _get_async_engine(self) -> AsyncEngine: + loop = asyncio.get_running_loop() + engine = self._async_engines.get(loop) + if engine is None: + engine = self._create_async_engine() + self._async_engines[loop] = engine + return engine + + async def get_session_async(self) -> AsyncSession: + """ + Create an independent async session. + + The caller must close the session with an async context manager. + + Returns: + AsyncSession: A session owned by the current event loop. + + Raises: + NotImplementedError: If a custom sync session hook has not been migrated. + """ + if self._uses_legacy_session_override(): + raise NotImplementedError("Override get_session_async when customizing the legacy get_session hook.") + return AsyncSession(bind=self._get_async_engine(), sync_session_class=MemorySession) + + def _uses_legacy_session_override(self) -> bool: + return ( + type(self).get_session is not MemoryInterface.get_session + and type(self).get_session_async is MemoryInterface.get_session_async + ) + + def get_session(self) -> Session: + """ + Use ``get_session_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Session: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_session", + new_item="MemoryInterface.get_session_async", + removed_in="1.4.0", + ) + return self._get_sync_session() + + def _get_session(self) -> Session: + """ + Select the operation's adapted session or a legacy sync session. + + Returns: + Session: The session for this operation. + """ + session = self._operation_session.get() + if session is not None: + return session + if type(self).get_session is not MemoryInterface.get_session: + return self.get_session() + return self._get_sync_session() + + async def _run_database_operation_async( + self, + database_operation: Callable[OperationArgs, OperationResult], + *args: OperationArgs.args, + **kwargs: OperationArgs.kwargs, + ) -> OperationResult: + """ + Run shared ORM code through the async driver's adapted session. + + Returns: + OperationResult: The database operation result. + """ + if ( + type(self)._create_async_engine is MemoryInterface._create_async_engine # type: ignore[ty:redundant-condition-strict] + or self._uses_legacy_session_override() + or self._uses_legacy_memory_override() + ): + print_deprecation_message( + old_item=f"{type(self).__name__} synchronous backend", + new_item=f"{type(self).__name__} native async session implementation", + removed_in="1.4.0", + ) + return await run_legacy_sync_async(database_operation, *args, **kwargs) + + def execute(session: Session) -> OperationResult: + token = self._operation_session.set(session) + try: + return database_operation(*args, **kwargs) + finally: + self._operation_session.reset(token) + + async with await self.get_session_async() as session: + return await session.run_sync(execute) + + async def initialize_async(self) -> None: + """ + Initialize the schema once without blocking the caller's event loop. + + Raises: + RuntimeError: If initialization is already in progress. + """ + if not self._initialization_lock.acquire(blocking=False): + raise RuntimeError("Memory initialization is already in progress.") + try: + if self._initialized: + return + await run_legacy_sync_async(self._initialize_schema) + self._initialized = True + except BaseException: + await self.dispose_engine_async() + raise + finally: + self._initialization_lock.release() + + def _uses_legacy_memory_override(self) -> bool: + return any( + not name.startswith("_") + and callable(method) + and hasattr(MemoryInterface, name + "_async") + and getattr(type(self), name) is not method + and getattr(type(self), name + "_async") is getattr(MemoryInterface, name + "_async") + for name, method in vars(MemoryInterface).items() + ) + + def _dispatch_memory_operation( + self, + name: str, + operation: Callable[OperationArgs, OperationResult], + *args: OperationArgs.args, + **kwargs: OperationArgs.kwargs, + ) -> OperationResult: + """ + Call a nested public sync override, or the shared implementation. + + Returns: + OperationResult: The operation result. + """ + if self._operation_session.get() is None and getattr(type(self), name) is not getattr(MemoryInterface, name): + override = cast("Callable[OperationArgs, OperationResult]", getattr(self, name)) + return override(*args, **kwargs) + return operation(*args, **kwargs) + + def _initialize_schema(self) -> None: + """Apply the schema policy; legacy backends initialize in their constructor.""" + return + + async def dispose_loop_resources_async(self) -> None: + """Close resources before their owning event loop stops.""" + loop = asyncio.get_running_loop() + engine = self._async_engines.get(loop) + if engine is not None: + await engine.dispose() + del self._async_engines[loop] + + @legacy_sync_override(lambda: MemoryInterface.dispose_engine) + async def dispose_engine_async(self) -> None: + """ + Dispose async and legacy resources after operations have finished. + + Raises: + RuntimeError: If another event loop still owns memory resources. + """ + try: + await self.dispose_loop_resources_async() + self._discard_closed_loop_resources() + self._check_loop_resources() + finally: + await run_legacy_sync_async(self._dispose_sync_engine) + + def _discard_closed_loop_resources(self) -> None: + for loop in list(self._async_engines): + if loop.is_closed(): + engine = self._async_engines.pop(loop) + engine.sync_engine.dispose(close=False) + logger.warning("Discarding memory pool owned by a closed event loop.") + + def _check_loop_resources(self) -> None: + if self._async_engines: + raise RuntimeError("Close memory resources on their owning event loops before disposing memory.") + + @legacy_sync_override(lambda: MemoryInterface.reset_database) + async def reset_database_async(self) -> None: + """Drop and rebuild the schema using the blocking-only Alembic tooling.""" + await run_legacy_sync_async(self._reset_database) + + @legacy_sync_override(lambda: MemoryInterface.print_schema) + async def print_schema_async(self) -> None: + """Print the schema without blocking the caller's event loop.""" + await run_legacy_sync_async(self._print_schema) + def enable_embedding(self, embedding_model: Any | None = None) -> None: """ Enable embedding functionality for the memory interface. @@ -602,7 +812,7 @@ def _attack_results_keyset_seek_condition(self, *, after: AttackResultKeysetCurs and_(timestamp == after.timestamp, entry_id < anchor_id), ) - def get_all_embeddings(self) -> Sequence[EmbeddingDataEntry]: + def _execute_get_all_embeddings(self) -> Sequence[EmbeddingDataEntry]: """ Load all EmbeddingData from the memory storage handler. @@ -659,7 +869,7 @@ def _get_seed_metadata_conditions(self, *, metadata: dict[str, str | int]) -> An Any: A SQLAlchemy condition for filtering memory entries based on prompt metadata. """ - def add_conversation_to_memory(self, *, conversation: Conversation) -> None: + def _execute_add_conversation_to_memory(self, *, conversation: Conversation) -> None: """ Register a conversation in memory, recording its conversation-scoped metadata. @@ -686,7 +896,7 @@ def add_conversation_to_memory(self, *, conversation: Conversation) -> None: """ self._insert_conversation(conversation=conversation) - def add_message_pieces_to_memory(self, *, message_pieces: Sequence[MessagePiece]) -> None: + def _execute_add_message_pieces_to_memory(self, *, message_pieces: Sequence[MessagePiece]) -> None: """ Insert a list of message pieces into the memory storage. @@ -726,7 +936,7 @@ def _add_message_pieces_to_memory(self, *, message_pieces: Sequence[MessagePiece Raises: SQLAlchemyError: If the message pieces or converter identifiers cannot be persisted. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: self._add_message_pieces_to_session(session=session, message_pieces=message_pieces) session.commit() @@ -802,7 +1012,7 @@ def _insert_conversation(self, *, conversation: Conversation) -> None: with the same id already exists with a different target. SQLAlchemyError: If the insert fails. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: self._insert_conversation_in_session(session=session, conversation=conversation) session.commit() @@ -840,7 +1050,9 @@ def _insert_conversation_in_session(self, *, session: Session, conversation: Con f"target and cannot be re-registered with {entry.target_identifier!r}." ) - def add_conversation_retry(self, *, conversation_id: str, sequence: int, reason: ConversationRetryReason) -> None: + def _execute_add_conversation_retry( + self, *, conversation_id: str, sequence: int, reason: ConversationRetryReason + ) -> None: """ Append a retry record to the conversation-scoped metadata for ``conversation_id``. @@ -858,7 +1070,7 @@ def add_conversation_retry(self, *, conversation_id: str, sequence: int, reason: SQLAlchemyError: If the database update fails; the transaction is rolled back first. """ record = ConversationRetry(sequence=sequence, reason=reason).model_dump(mode="json") - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: entry = session.get(ConversationEntry, str(conversation_id)) if entry is None: @@ -872,7 +1084,7 @@ def add_conversation_retry(self, *, conversation_id: str, sequence: int, reason: logger.exception(f"Error recording retry for conversation {conversation_id}: {e}") raise - def delete_conversation_pieces_after_sequence(self, *, conversation_id: str, sequence: int) -> int: + def _execute_delete_conversation_pieces_after_sequence(self, *, conversation_id: str, sequence: int) -> int: """ Delete all message pieces in a conversation whose sequence is greater than ``sequence``. @@ -891,7 +1103,7 @@ def delete_conversation_pieces_after_sequence(self, *, conversation_id: str, seq Raises: SQLAlchemyError: If the deletion fails; the transaction is rolled back first. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: pieces = ( session.query(PromptMemoryEntry) @@ -1043,7 +1255,7 @@ def _get_identifiers( seen_hashes.add(entry.hash) return identifiers - def get_target_identifiers( + def _execute_get_target_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1089,7 +1301,7 @@ def get_target_identifiers( }, ) - def get_converter_identifiers( + def _execute_get_converter_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1128,7 +1340,7 @@ def get_converter_identifiers( }, ) - def get_scorer_identifiers( + def _execute_get_scorer_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1162,7 +1374,7 @@ def get_scorer_identifiers( }, ) - def get_scenario_identifiers( + def _execute_get_scenario_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1202,7 +1414,7 @@ def get_scenario_identifiers( }, ) - def get_seed_identifiers( + def _execute_get_seed_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1242,7 +1454,7 @@ def get_seed_identifiers( }, ) - def get_attack_identifiers( + def _execute_get_attack_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1282,7 +1494,7 @@ def get_attack_identifiers( }, ) - def get_attack_technique_identifiers( + def _execute_get_attack_technique_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1310,7 +1522,7 @@ def get_attack_technique_identifiers( }, ) - def get_atomic_attack_identifiers( + def _execute_get_atomic_attack_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1372,7 +1584,7 @@ def _query_entries( Raises: SQLAlchemyError: If the query fails. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: query = session.query(model_class) if join_scores and model_class == PromptMemoryEntry: @@ -1568,7 +1780,7 @@ def _insert_entry(self, entry: Base) -> None: Raises: SQLAlchemyError: If the insertion fails. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: session.add(entry) session.commit() @@ -1587,7 +1799,7 @@ def _insert_entries(self, *, entries: Sequence[Base]) -> None: Raises: SQLAlchemyError: If the insertion fails. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: session.add_all(entries) session.commit() @@ -1596,14 +1808,19 @@ def _insert_entries(self, *, entries: Sequence[Base]) -> None: logger.exception(f"Error inserting multiple entries into the table: {e}") raise - @abc.abstractmethod - def get_session(self) -> Session: + def _get_sync_session(self) -> Session: """ Provide a SQLAlchemy session for transactional operations. Returns: Session: A SQLAlchemy session bound to the engine. + + Raises: + NotImplementedError: If neither session contract is implemented. """ + if type(self).get_session is MemoryInterface.get_session: + raise NotImplementedError("Implement _get_sync_session or the legacy get_session method.") + return self.get_session() def _update_entry(self, entry: Base) -> None: """ @@ -1619,7 +1836,7 @@ def _update_entry(self, entry: Base) -> None: Raises: SQLAlchemyError: If there's an error during the database operation. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: session.merge(entry) session.commit() @@ -1645,7 +1862,7 @@ def _update_entries(self, *, entries: MutableSequence[Base], update_fields: dict """ if not update_fields: raise ValueError("update_fields must be provided to update prompt entries.") - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: prompt_entry_ids = [entry.id for entry in entries if isinstance(entry, PromptMemoryEntry)] if prompt_entry_ids and session.get_bind().dialect.name == "mssql": @@ -1706,8 +1923,7 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str | Sequence Database-specific SQLAlchemy condition. """ - @abc.abstractmethod - def get_unique_attack_class_names(self) -> list[str]: + def _execute_get_unique_attack_class_names(self) -> list[str]: """ Return sorted unique attack class names from all stored attack results. @@ -1716,10 +1932,15 @@ def get_unique_attack_class_names(self) -> list[str]: Returns: Sorted list of unique attack class name strings. + + Raises: + NotImplementedError: If the backend does not implement this query. """ + if type(self).get_unique_attack_class_names is MemoryInterface.get_unique_attack_class_names: + raise NotImplementedError("Implement the unique attack class query.") + return self.get_unique_attack_class_names() - @abc.abstractmethod - def get_unique_converter_class_names(self) -> list[str]: + def _execute_get_unique_converter_class_names(self) -> list[str]: """ Return sorted unique converter class names used across all attack results. @@ -1728,10 +1949,15 @@ def get_unique_converter_class_names(self) -> list[str]: Returns: Sorted list of unique converter class name strings. + + Raises: + NotImplementedError: If the backend does not implement this query. """ + if type(self).get_unique_converter_class_names is MemoryInterface.get_unique_converter_class_names: + raise NotImplementedError("Implement the unique converter class query.") + return self.get_unique_converter_class_names() - @abc.abstractmethod - def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, "ConversationStats"]: + def _execute_get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, "ConversationStats"]: """ Return lightweight aggregate statistics for one or more conversations. @@ -1746,7 +1972,13 @@ def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str Returns: Mapping from conversation_id to ConversationStats. Conversations with no pieces are omitted from the result. + + Raises: + NotImplementedError: If the backend does not implement this query. """ + if type(self).get_conversation_stats is MemoryInterface.get_conversation_stats: + raise NotImplementedError("Implement the conversation statistics query.") + return self.get_conversation_stats(conversation_ids=conversation_ids) @abc.abstractmethod def _get_scenario_result_label_condition(self, *, labels: dict[str, str]) -> Any: @@ -1839,7 +2071,7 @@ def _get_scenario_plan_unit_subqueries(self, *, scenario_result_ids: Sequence[uu "to support Scenario history queries." ) - def add_scores_to_memory( + def _execute_add_scores_to_memory( self, *, scores: Sequence[Score], @@ -1861,6 +2093,7 @@ def add_scores_to_memory( intermediate_score_ids=frozenset(str(score.id) for score in intermediate_scores), ) + @legacy_sync_override(lambda: MemoryInterface.add_scores_to_memory) async def add_scores_to_memory_async( self, *, @@ -1886,7 +2119,12 @@ async def add_scores_to_memory_async( ) ) if not media_scorables: - self.add_scores_to_memory(scores=scores, observations=observations, intermediate_scores=intermediate_scores) + await self._run_database_operation_async( + self._execute_add_scores_to_memory, + scores=scores, + observations=observations, + intermediate_scores=intermediate_scores, + ) return prepared_content = await asyncio.gather( @@ -1907,7 +2145,8 @@ async def add_scores_to_memory_async( copied_scores.append((score, copied_score)) scores_to_persist.append(copied_score) - self._add_scores_to_memory( + await self._run_database_operation_async( + self._add_scores_to_memory, scores=scores_to_persist, observations=observations, prepared_content_hashes=prepared_hashes, @@ -1982,7 +2221,7 @@ def _add_scores_to_memory( """ observations = [Observation.model_validate(observation.model_dump()) for observation in observations] new_ids, referenced_ids = self._validate_score_inputs(scores=scores, observations=observations) - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: _begin_sqlite_write(session) self._validate_observation_links( @@ -2289,7 +2528,9 @@ def _load_score_message_pieces( pieces_by_id.update({entry.id: entry.get_message_piece() for entry in session.scalars(statement)}) return pieces_by_id - def get_scorable_content(self, *, content_ids: Sequence[uuid.UUID | str]) -> dict[uuid.UUID, ContentScorable]: + def _execute_get_scorable_content( + self, *, content_ids: Sequence[uuid.UUID | str] + ) -> dict[uuid.UUID, ContentScorable]: """ Load the loose content that stored scores are anchored on. @@ -2313,7 +2554,7 @@ def get_scorable_content(self, *, content_ids: Sequence[uuid.UUID | str]) -> dic if entry.value is not None } - def get_scorable_content_hashes( + def _execute_get_scorable_content_hashes( self, *, content_ids: Sequence[uuid.UUID | str], @@ -2333,7 +2574,7 @@ def get_scorable_content_hashes( ) return {entry.id: entry.value_sha256 for entry in entries} - def get_observations( + def _execute_get_observations( self, *, observation_ids: Sequence[uuid.UUID | str], @@ -2366,7 +2607,7 @@ def _persist_scorer_identifier(cls, *, session: Any, scorer_identifier: ScorerId """Persist a complete scorer graph and its target dependencies.""" cls._persist_identifier(session=session, identifier=scorer_identifier) - def get_scores( + def _execute_get_scores( self, *, score_ids: Sequence[str] | None = None, @@ -2436,7 +2677,7 @@ def get_scores( score_entries: Sequence[ScoreEntry] = self._query_entries(ScoreEntry, conditions=and_(*conditions)) return [entry.get_score() for entry in score_entries] - def get_prompt_scores( + def _execute_get_prompt_scores( self, *, role: str | None = None, @@ -2477,7 +2718,9 @@ def get_prompt_scores( Returns: Sequence[Score]: A list of scores extracted from the message pieces. """ - message_pieces = self.get_message_pieces( + message_pieces = self._dispatch_memory_operation( + "get_message_pieces", + self._execute_get_message_pieces, role=role, conversation_id=conversation_id, prompt_ids=prompt_ids, @@ -2524,7 +2767,7 @@ def get_prompt_scores( return [entry.get_score() for entry in entries_by_id.values()] - def get_conversation_messages(self, *, conversation_id: str) -> MutableSequence[Message]: + def _execute_get_conversation_messages(self, *, conversation_id: str) -> MutableSequence[Message]: """ Retrieve a list of Message objects that have the specified conversation ID. @@ -2541,7 +2784,9 @@ def get_conversation_messages(self, *, conversation_id: str) -> MutableSequence[ """ if not conversation_id: raise ValueError("get_conversation_messages requires a non-empty conversation_id") - message_pieces = self.get_message_pieces(conversation_id=conversation_id) + message_pieces = self._dispatch_memory_operation( + "get_message_pieces", self._execute_get_message_pieces, conversation_id=conversation_id + ) return group_conversation_message_pieces_by_sequence(message_pieces=message_pieces) def _get_conversation(self, *, conversation_id: str) -> Conversation | None: @@ -2565,7 +2810,28 @@ def _get_conversation(self, *, conversation_id: str) -> Conversation | None: return None return entries[0].get_conversation() - def get_request_from_response(self, *, response: Message) -> Message: + async def get_conversation_metadata_async(self, *, conversation_id: str) -> Conversation | None: + """ + Read the stored metadata for one conversation. + + Args: + conversation_id: The conversation to look up. + + Returns: + Conversation metadata, or None if the conversation is not stored. + """ + return await self._run_database_operation_async(self._get_conversation, conversation_id=conversation_id) + + async def update_scenario_result_async(self, *, scenario_result: ScenarioResult) -> None: + """ + Persist an updated scenario result. + + Args: + scenario_result: The scenario result to update. + """ + await self._run_database_operation_async(self._update_entry, ScenarioResultEntry(entry=scenario_result)) + + def _execute_get_request_from_response(self, *, response: Message) -> Message: """ Retrieve the request that produced the given response. @@ -2583,7 +2849,11 @@ def get_request_from_response(self, *, response: Message) -> Message: if response.sequence < 1: raise ValueError("The provided request does not have a preceding request (sequence < 1).") - conversation = self.get_conversation_messages(conversation_id=response.conversation_id) + conversation = self._dispatch_memory_operation( + "get_conversation_messages", + self._execute_get_conversation_messages, + conversation_id=response.conversation_id, + ) return conversation[response.sequence - 1] def _build_message_piece_identifier_conditions( @@ -2633,7 +2903,7 @@ def _build_message_piece_identifier_conditions( ) return conditions - def get_message_pieces( + def _execute_get_message_pieces( self, *, role: str | None = None, @@ -2732,7 +3002,7 @@ def get_message_pieces( logger.exception(f"Failed to retrieve prompts with error {e}") raise - def duplicate_messages(self, *, messages: Sequence[Message]) -> tuple[str, Sequence[MessagePiece]]: + def _execute_duplicate_messages(self, *, messages: Sequence[Message]) -> tuple[str, Sequence[MessagePiece]]: """ Duplicate messages with a new conversation ID. @@ -2758,7 +3028,7 @@ def duplicate_messages(self, *, messages: Sequence[Message]) -> tuple[str, Seque return new_conversation_id, all_pieces - def duplicate_conversation(self, *, conversation_id: str) -> str: + def _execute_duplicate_conversation(self, *, conversation_id: str) -> str: """ Duplicate a conversation for reuse. @@ -2772,18 +3042,26 @@ def duplicate_conversation(self, *, conversation_id: str) -> str: Returns: The uuid for the new conversation. """ - messages = self.get_conversation_messages(conversation_id=conversation_id) + messages = self._dispatch_memory_operation( + "get_conversation_messages", self._execute_get_conversation_messages, conversation_id=conversation_id + ) source_metadata = self._get_conversation(conversation_id=conversation_id) source_target = source_metadata.target_identifier if source_metadata else None - new_conversation_id, all_pieces = self.duplicate_messages(messages=messages) + new_conversation_id, all_pieces = self._dispatch_memory_operation( + "duplicate_messages", self._execute_duplicate_messages, messages=messages + ) if all_pieces: - self.add_conversation_to_memory( - conversation=Conversation(conversation_id=new_conversation_id, target_identifier=source_target) + self._dispatch_memory_operation( + "add_conversation_to_memory", + self._execute_add_conversation_to_memory, + conversation=Conversation(conversation_id=new_conversation_id, target_identifier=source_target), + ) + self._dispatch_memory_operation( + "add_message_pieces_to_memory", self._execute_add_message_pieces_to_memory, message_pieces=all_pieces ) - self.add_message_pieces_to_memory(message_pieces=all_pieces) return new_conversation_id - def duplicate_conversation_excluding_last_turn(self, *, conversation_id: str) -> str: + def _execute_duplicate_conversation_excluding_last_turn(self, *, conversation_id: str) -> str: """ Duplicate a conversation, excluding the last turn. In this case, last turn is defined as before the last user request (e.g. if there is half a turn, it just removes that half). @@ -2796,7 +3074,9 @@ def duplicate_conversation_excluding_last_turn(self, *, conversation_id: str) -> Returns: The uuid for the new conversation. """ - messages = self.get_conversation_messages(conversation_id=conversation_id) + messages = self._dispatch_memory_operation( + "get_conversation_messages", self._execute_get_conversation_messages, conversation_id=conversation_id + ) # remove the final turn from the conversation if len(messages) == 0: @@ -2814,16 +3094,22 @@ def duplicate_conversation_excluding_last_turn(self, *, conversation_id: str) -> source_metadata = self._get_conversation(conversation_id=conversation_id) source_target = source_metadata.target_identifier if source_metadata else None - new_conversation_id, all_pieces = self.duplicate_messages(messages=messages_to_duplicate) + new_conversation_id, all_pieces = self._dispatch_memory_operation( + "duplicate_messages", self._execute_duplicate_messages, messages=messages_to_duplicate + ) if all_pieces: - self.add_conversation_to_memory( - conversation=Conversation(conversation_id=new_conversation_id, target_identifier=source_target) + self._dispatch_memory_operation( + "add_conversation_to_memory", + self._execute_add_conversation_to_memory, + conversation=Conversation(conversation_id=new_conversation_id, target_identifier=source_target), + ) + self._dispatch_memory_operation( + "add_message_pieces_to_memory", self._execute_add_message_pieces_to_memory, message_pieces=all_pieces ) - self.add_message_pieces_to_memory(message_pieces=all_pieces) return new_conversation_id - def add_message_to_memory(self, *, request: Message) -> None: + def _execute_add_message_to_memory(self, *, request: Message) -> None: """ Insert a list of message pieces into the memory storage. @@ -2833,33 +3119,34 @@ def add_message_to_memory(self, *, request: Message) -> None: Args: request (Message): The message to add to the memory. """ - request.validate() - - embedding_entries = [] - message_pieces = request.message_pieces - - pieces_to_persist = [piece for piece in message_pieces if not piece.not_in_memory] - if not pieces_to_persist: + if not self._persist_message(request): return - - self._update_sequence(message_pieces=message_pieces) - - # conversation_id validation happens in add_message_pieces_to_memory, the shared choke point. - self.add_message_pieces_to_memory(message_pieces=message_pieces) - if self.memory_embedding: - # Embeddings power text similarity search and only describe text pieces. - # A multimodal message (e.g. text plus an image_path piece) must still - # persist instead of failing the whole write, and pieces flagged - # not_in_memory are never persisted, so no embedding row may reference them. - for piece in pieces_to_persist: - if piece.converted_value_data_type != "text": - continue - embedding_entry = self.memory_embedding.generate_embedding_memory_data(message_piece=piece) - embedding_entries.append(embedding_entry) - + embedding_entries = [ + self.memory_embedding.generate_embedding_memory_data(message_piece=piece) + for piece in request.message_pieces + if not piece.not_in_memory and piece.converted_value_data_type == "text" + ] self._add_embeddings_to_memory(embedding_data=embedding_entries) + def _persist_message(self, request: Message) -> bool: + """ + Persist a validated message before generating optional embeddings. + + Returns: + bool: Whether any message pieces were persisted. + """ + request.validate() + if not any(not piece.not_in_memory for piece in request.message_pieces): + return False + self._update_sequence(message_pieces=request.message_pieces) + self._dispatch_memory_operation( + "add_message_pieces_to_memory", + self._execute_add_message_pieces_to_memory, + message_pieces=request.message_pieces, + ) + return True + def _update_sequence(self, *, message_pieces: Sequence[MessagePiece]) -> None: """ Update the sequence number of the message pieces in the conversation. @@ -2867,7 +3154,9 @@ def _update_sequence(self, *, message_pieces: Sequence[MessagePiece]) -> None: Args: message_pieces (Sequence[MessagePiece]): The list of message pieces to update. """ - prev_conversations = self.get_message_pieces(conversation_id=message_pieces[0].conversation_id) + prev_conversations = self._dispatch_memory_operation( + "get_message_pieces", self._execute_get_message_pieces, conversation_id=message_pieces[0].conversation_id + ) sequence = 0 @@ -2877,7 +3166,9 @@ def _update_sequence(self, *, message_pieces: Sequence[MessagePiece]) -> None: for piece in message_pieces: piece.sequence = sequence - def update_prompt_entries_by_conversation_id(self, *, conversation_id: str, update_fields: dict[str, Any]) -> bool: + def _execute_update_prompt_entries_by_conversation_id( + self, *, conversation_id: str, update_fields: dict[str, Any] + ) -> bool: """ Update prompt entries for a given conversation ID with the specified field values. @@ -2928,7 +3219,7 @@ def _message_pieces_are_observation_referenced( """ if not piece_ids: return False - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: return self._message_pieces_are_observation_referenced_in_session( session=session, piece_ids=piece_ids, @@ -2963,7 +3254,7 @@ def _message_pieces_are_observation_referenced_in_session( return True return False - def update_prompt_metadata_by_conversation_id( + def _execute_update_prompt_metadata_by_conversation_id( self, *, conversation_id: str, prompt_metadata: dict[str, str | int] ) -> bool: """ @@ -2976,8 +3267,11 @@ def update_prompt_metadata_by_conversation_id( Returns: bool: True if the update was successful, False otherwise. """ - return self.update_prompt_entries_by_conversation_id( - conversation_id=conversation_id, update_fields={"prompt_metadata": prompt_metadata} + return self._dispatch_memory_operation( + "update_prompt_entries_by_conversation_id", + self._execute_update_prompt_entries_by_conversation_id, + conversation_id=conversation_id, + update_fields={"prompt_metadata": prompt_metadata}, ) def _run_schema_migration(self, *, silent: bool = False) -> None: @@ -3019,6 +3313,19 @@ def _check_schema_migration(self, *, silent: bool = False) -> None: check_schema_migrations(engine=self.engine, silent=silent) def reset_database(self) -> None: + """ + Use ``reset_database_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.reset_database", + new_item="MemoryInterface.reset_database_async", + removed_in="1.4.0", + ) + self._reset_database() + + def _reset_database(self) -> None: """ Drop and recreate all tables in the database. @@ -3032,11 +3339,28 @@ def reset_database(self) -> None: reset_database(engine=self.engine) def dispose_engine(self) -> None: + """ + Use ``dispose_engine_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.dispose_engine", + new_item="MemoryInterface.dispose_engine_async", + removed_in="1.4.0", + ) + self._check_loop_resources() + self._dispose_sync_engine() + + def _dispose_sync_engine(self) -> None: """ Dispose the engine and clean up resources. """ - if self.engine: - self.engine.dispose() + try: + if self.engine: + self.engine.dispose() + finally: + self._initialized = False previous_raise = logging.raiseExceptions logging.raiseExceptions = False try: @@ -3049,10 +3373,10 @@ def cleanup(self) -> None: Ensure cleanup on process exit. """ # Ensure cleanup at process exit - atexit.register(self.dispose_engine) + atexit.register(self._dispose_sync_engine) # Ensure cleanup happens even if the object is garbage collected before process exits - weakref.finalize(self, self.dispose_engine) + weakref.finalize(self, self._dispose_sync_engine) def _build_seed_filter_conditions( self, @@ -3155,7 +3479,7 @@ def _build_seed_filter_conditions( return conditions - def get_seeds( + def _execute_get_seeds( self, *, value: str | None = None, @@ -3234,7 +3558,7 @@ def get_seeds( logger.exception(f"Failed to retrieve prompts with dataset name {dataset_name} with error {e}") raise - def remove_seeds_from_memory( + def _execute_remove_seeds_from_memory( self, *, value: str | None = None, @@ -3331,7 +3655,7 @@ def remove_seeds_from_memory( ) # Delete matching rows in a single transaction so it is atomic across backends. - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: query = session.query(SeedEntry).filter(and_(*conditions)) count = query.delete(synchronize_session=False) @@ -3342,7 +3666,7 @@ def remove_seeds_from_memory( logger.exception(f"Failed to remove seeds from memory: {e}") raise - def remove_seed_groups_from_memory( + def _execute_remove_seed_groups_from_memory( self, *, value: str | None = None, @@ -3450,7 +3774,7 @@ def remove_seed_groups_from_memory( # are selected with a server-side subquery rather than materialized into Python and sent back as an # IN (...) list, so a broad filter cannot exceed the backend's bound-parameter limit (e.g. Azure SQL). # Seeds with a NULL prompt_group_id are excluded, so ungrouped matches are skipped. - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: group_id_subquery = ( select(SeedEntry.prompt_group_id) @@ -3554,8 +3878,8 @@ async def _prepare_seed_for_storage_async( prompt.date_added = current_time # Only SeedPrompt has set_encoding_metadata for audio/video/image files - if hasattr(prompt, "set_encoding_metadata"): - prompt.set_encoding_metadata() # type: ignore[ty:call-non-callable] + if isinstance(prompt, SeedPrompt): + await asyncio.to_thread(prompt.set_encoding_metadata) # Handle serialization for image, audio & video SeedPrompts if prompt.data_type in ["image_path", "audio_path", "video_path"]: @@ -3585,6 +3909,10 @@ async def add_seeds_to_memory_async(self, *, seeds: Sequence[Seed], added_by: st for prompt in seeds: await self._prepare_seed_for_storage_async(prompt=prompt, added_by=added_by, current_time=current_time) + await self._run_database_operation_async(self._insert_prepared_seeds, seeds=seeds) + + def _insert_prepared_seeds(self, *, seeds: Sequence[Seed]) -> None: + """Deduplicate and store seeds after their media is prepared.""" existing_pairs, existing_hashes = self._get_existing_seed_keys(seeds=seeds) new_condition_group_ids = self._get_new_condition_group_ids( seeds=seeds, existing_pairs=existing_pairs, existing_hashes=existing_hashes @@ -3718,7 +4046,9 @@ def _get_existing_seed_keys( chunk_size = self._MAX_BIND_VARS - (1 if dataset_name is not None else 0) for index in range(0, len(hashes), chunk_size): chunk = hashes[index : index + chunk_size] - for existing in self.get_seeds(value_sha256=chunk, dataset_name=dataset_name): + for existing in self._dispatch_memory_operation( + "get_seeds", self._execute_get_seeds, value_sha256=chunk, dataset_name=dataset_name + ): if not existing.value_sha256: continue conditions_key = self._seed_conditions_key(existing) @@ -3743,7 +4073,7 @@ async def add_seed_datasets_to_memory_async(self, *, datasets: Sequence[SeedData for dataset in datasets: await self.add_seeds_to_memory_async(seeds=dataset.seeds, added_by=added_by) - def get_seed_dataset_summaries(self) -> Sequence[SeedDatasetSummary]: + def _execute_get_seed_dataset_summaries(self) -> Sequence[SeedDatasetSummary]: """ Return aggregate metadata for datasets already loaded in memory. @@ -3821,7 +4151,7 @@ def get_seed_dataset_summaries(self) -> Sequence[SeedDatasetSummary]: combined_statement = named_statement.union_all(unnamed_statement) - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = session.execute(combined_statement).all() summaries_by_dataset: dict[str | None, dict[str, Any]] = {} @@ -3863,7 +4193,7 @@ def get_seed_dataset_summaries(self) -> Sequence[SeedDatasetSummary]: logger.exception(f"Failed to retrieve dataset summaries with error {e}") raise - def get_seed_dataset_names(self) -> Sequence[str]: + def _execute_get_seed_dataset_names(self) -> Sequence[str]: """ Return a list of all seed dataset names in the memory storage. @@ -3946,7 +4276,21 @@ async def replace_seeds_for_dataset_async( await self._prepare_seed_for_storage_async(prompt=prompt, added_by=added_by, current_time=current_time) entries.append(SeedEntry(entry=prompt)) - with closing(self.get_session()) as session: + return await self._run_database_operation_async( + self._replace_prepared_seeds, dataset_name=dataset_name, entries=entries + ) + + def _replace_prepared_seeds(self, *, dataset_name: str, entries: Sequence[SeedEntry]) -> int: + """ + Replace one dataset in a single transaction. + + Returns: + int: The number of deleted seed entries. + + Raises: + SQLAlchemyError: If the replacement cannot be committed. + """ + with closing(self._get_session()) as session: try: deleted = ( session.query(SeedEntry) @@ -3999,7 +4343,7 @@ async def add_seed_groups_to_memory_async( all_seeds.extend(prompt_group.seeds) await self.add_seeds_to_memory_async(seeds=all_seeds, added_by=added_by) - def get_seed_groups( + def _execute_get_seed_groups( self, *, value: str | None = None, @@ -4047,7 +4391,9 @@ def get_seed_groups( Returns: Sequence[SeedGroup]: A list of `SeedGroup` objects that match the filtering criteria. """ - seeds = self.get_seeds( + seeds = self._dispatch_memory_operation( + "get_seeds", + self._execute_get_seeds, value=value, value_sha256=value_sha256, dataset_name=dataset_name, @@ -4069,7 +4415,9 @@ def get_seed_groups( if seeds: related_prompt_group_ids = {seed.prompt_group_id for seed in seeds if seed.prompt_group_id} if related_prompt_group_ids: - seeds = self.get_seeds(prompt_group_ids=list(related_prompt_group_ids)) + seeds = self._dispatch_memory_operation( + "get_seeds", self._execute_get_seeds, prompt_group_ids=list(related_prompt_group_ids) + ) # Deduplicate seeds to ensure we don't have duplicate prompts in the groups if seeds: @@ -4082,7 +4430,7 @@ def get_seed_groups( return seed_groups - def add_attack_results_to_memory(self, *, attack_results: Sequence[AttackResult]) -> None: + def _execute_add_attack_results_to_memory(self, *, attack_results: Sequence[AttackResult]) -> None: """ Insert a list of attack results into the memory storage. The database model automatically calculates objective_sha256 for consistency. @@ -4091,7 +4439,7 @@ def add_attack_results_to_memory(self, *, attack_results: Sequence[AttackResult] SQLAlchemyError: If the database transaction fails. """ entries = [AttackResultEntry(entry=attack_result) for attack_result in attack_results] - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: for attack_result in attack_results: if attack_result.atomic_attack_identifier is not None: @@ -4107,7 +4455,7 @@ def add_attack_results_to_memory(self, *, attack_results: Sequence[AttackResult] session.rollback() raise - def add_conversation_branches_to_attack( + def _execute_add_conversation_branches_to_attack( self, *, attack_result_id: str, @@ -4137,7 +4485,7 @@ def add_conversation_branches_to_attack( if any(not piece.not_in_memory and piece.conversation_id not in conversation_ids for piece in message_pieces): raise ValueError("Copied message pieces must belong to the prepared branches") - with closing(self.get_session()) as session, session.begin(): + with closing(self._get_session()) as session, session.begin(): entry = self._get_locked_attack_result(session=session, attack_result_id=attack_result_id) if entry is None: return False @@ -4157,7 +4505,7 @@ def add_conversation_branches_to_attack( entry.timestamp = datetime.now(UTC) return True - def promote_attack_conversation(self, *, attack_result_id: str, conversation_id: str) -> bool: + def _execute_promote_attack_conversation(self, *, attack_result_id: str, conversation_id: str) -> bool: """ Promote an existing related conversation without losing concurrent branch additions. @@ -4168,7 +4516,7 @@ def promote_attack_conversation(self, *, attack_result_id: str, conversation_id: ValueError: If the requested conversation is not part of this attack. SQLAlchemyError: If the transaction fails. """ - with closing(self.get_session()) as session, session.begin(): + with closing(self._get_session()) as session, session.begin(): entry = self._get_locked_attack_result(session=session, attack_result_id=attack_result_id) if entry is None: return False @@ -4203,7 +4551,7 @@ def _get_locked_attack_result(*, session: Session, attack_result_id: str) -> Att ) return session.get(AttackResultEntry, result_id, populate_existing=True) - def update_attack_result(self, *, conversation_id: str, update_fields: dict[str, Any]) -> bool: + def _execute_update_attack_result(self, *, conversation_id: str, update_fields: dict[str, Any]) -> bool: """ Update specific fields of an existing AttackResultEntry identified by conversation_id. @@ -4238,7 +4586,7 @@ def update_attack_result(self, *, conversation_id: str, update_fields: dict[str, 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: + def _execute_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. @@ -4267,7 +4615,7 @@ def update_attack_result_by_id(self, *, attack_result_id: str, update_fields: di self._update_entries(entries=[entries[0]], update_fields=update_fields) return True - def get_attack_results( + def _execute_get_attack_results( self, *, attack_result_ids: Sequence[str] | None = None, @@ -4796,7 +5144,7 @@ def _dedup_attack_entries(entries: Sequence[AttackResultEntry]) -> list[AttackRe seen[entry.conversation_id] = entry return [entry.get_attack_result() for entry in seen.values()] - def get_unique_attack_labels( + def _execute_get_unique_attack_labels( self, *, operator: Sequence[str] | None = None, @@ -4821,7 +5169,7 @@ def get_unique_attack_labels( conditions = self._build_attack_result_scalar_conditions(query=filter_query) conditions.extend(self._build_attack_result_label_conditions(query=filter_query)) - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: query = session.query(AttackResultEntry.labels).filter(AttackResultEntry.labels.isnot(None)) if conditions: query = query.filter(and_(*conditions)) @@ -4841,9 +5189,9 @@ def get_unique_attack_labels( return {key: sorted(values) for key, values in sorted(label_values.items())} - def get_unique_attack_attribution(self) -> dict[str, list[str]]: + def _execute_get_unique_attack_attribution(self) -> dict[str, list[str]]: """Return unique dedicated operator and operation values from indexed columns.""" - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: operators = [ value for (value,) in session.query(AttackResultEntry.operator) @@ -4862,7 +5210,7 @@ def get_unique_attack_attribution(self) -> dict[str, list[str]]: ] return {"operators": sorted(operators), "operations": sorted(operations)} - def add_scenario_results_to_memory(self, *, scenario_results: Sequence[ScenarioResult]) -> None: + def _execute_add_scenario_results_to_memory(self, *, scenario_results: Sequence[ScenarioResult]) -> None: """ Insert a list of scenario results into the memory storage. @@ -4873,7 +5221,7 @@ def add_scenario_results_to_memory(self, *, scenario_results: Sequence[ScenarioR SQLAlchemyError: If a scenario result or identifier graph cannot be persisted. """ entries = [ScenarioResultEntry(entry=scenario_result) for scenario_result in scenario_results] - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: try: for scenario_result in scenario_results: self._persist_scenario_identifier( @@ -4891,7 +5239,7 @@ def _persist_scenario_identifier(cls, *, session: Any, scenario_identifier: Scen """Persist a scenario identifier and its target and scorer dependencies.""" cls._persist_identifier(session=session, identifier=scenario_identifier) - def update_scenario_run_state( + def _execute_update_scenario_run_state( self, *, scenario_result_id: str, @@ -4914,7 +5262,9 @@ def update_scenario_run_state( Raises: ValueError: If the scenario result is not found. """ - self.update_scenario_run_state_and_metadata_fields( + self._dispatch_memory_operation( + "update_scenario_run_state_and_metadata_fields", + self._execute_update_scenario_run_state_and_metadata_fields, scenario_result_id=scenario_result_id, scenario_run_state=scenario_run_state, error_message=error_message, @@ -4922,7 +5272,7 @@ def update_scenario_run_state( metadata_fields={}, ) - def update_scenario_run_state_and_metadata_fields( + def _execute_update_scenario_run_state_and_metadata_fields( self, *, scenario_result_id: str, @@ -4937,7 +5287,7 @@ def update_scenario_run_state_and_metadata_fields( Raises: ValueError: If the scenario result is not found. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: entry = session.query(ScenarioResultEntry).filter_by(id=scenario_result_id).first() if not entry: @@ -4960,7 +5310,7 @@ def update_scenario_run_state_and_metadata_fields( logger.info(f"Updated scenario {scenario_result_id} state to '{scenario_run_state.value}'") - def try_update_scenario_run_state( + def _execute_try_update_scenario_run_state( self, *, scenario_result_id: str, @@ -5005,7 +5355,7 @@ def try_update_scenario_run_state( ): values["completion_time"] = datetime.now(tz=UTC) - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: updated_rows = ( session.query(ScenarioResultEntry) .filter( @@ -5020,7 +5370,7 @@ def try_update_scenario_run_state( logger.info(f"Updated scenario {scenario_result_id} state to '{scenario_run_state.value}'") return bool(updated_rows) - def update_scenario_metadata( + def _execute_update_scenario_metadata( self, *, scenario_result_id: str, @@ -5041,14 +5391,14 @@ def update_scenario_metadata( Raises: ValueError: If the scenario result is not found. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: entry = session.query(ScenarioResultEntry).filter_by(id=scenario_result_id).first() if not entry: raise ValueError(f"Scenario result with ID {scenario_result_id} not found in memory") entry.scenario_metadata = metadata if metadata else None session.commit() - def update_scenario_metadata_fields( + def _execute_update_scenario_metadata_fields( self, *, scenario_result_id: str, @@ -5060,7 +5410,7 @@ def update_scenario_metadata_fields( Raises: ValueError: If the scenario result is not found. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: entry = session.query(ScenarioResultEntry).filter_by(id=scenario_result_id).first() if not entry: raise ValueError(f"Scenario result with ID {scenario_result_id} not found in memory") @@ -5068,13 +5418,13 @@ def update_scenario_metadata_fields( flag_modified(entry, "scenario_metadata") session.commit() - def get_scenario_result_header(self, *, scenario_result_id: str) -> ScenarioResult | None: + def _execute_get_scenario_result_header(self, *, scenario_result_id: str) -> ScenarioResult | None: """Return one ScenarioResult header without hydrating linked attack results.""" - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: entry = session.query(ScenarioResultEntry).filter_by(id=scenario_result_id).first() return entry.get_scenario_result() if entry is not None else None - def get_scenario_run_state_page( + def _execute_get_scenario_run_state_page( self, *, states: Sequence[ScenarioRunState], @@ -5101,7 +5451,7 @@ def get_scenario_run_state_page( .order_by(ScenarioResultEntry.id.asc()) .limit(limit + 1) ) - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = session.execute(statement).all() return ( [ @@ -5114,7 +5464,7 @@ def get_scenario_run_state_page( len(rows) > limit, ) - def get_scenario_run_history_page( + def _execute_get_scenario_run_history_page( self, *, scenario_names: Sequence[str] | None = None, @@ -5149,7 +5499,9 @@ def get_scenario_run_history_page( cursor=cursor, limit=limit, ) - aggregates = self.get_scenario_history_aggregates( + aggregates = self._dispatch_memory_operation( + "get_scenario_history_aggregates", + self._execute_get_scenario_history_aggregates, scenario_result_ids=[record.scenario_result_id for record in records], plan_scenario_ids=[ record.scenario_result_id for record in records if record.plan_atomic_groups is not None @@ -5157,7 +5509,7 @@ def get_scenario_run_history_page( ) return records, aggregates, has_more - def get_scenario_history_aggregates( + def _execute_get_scenario_history_aggregates( self, *, scenario_result_ids: Sequence[str], @@ -5196,7 +5548,7 @@ def get_scenario_history_aggregates( for scenario_result_id in plan_scenario_ids if scenario_result_id in aggregates ] - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: aggregate_rows = session.execute( self._build_scenario_history_aggregate_statement(entry_ids=entry_ids, plan_entry_ids=plan_entry_ids) ).all() @@ -5420,10 +5772,10 @@ def _parse_scenario_started_at(*, raw_value: Any) -> datetime | None: return _parse_scenario_started_at(raw_value=raw_value) - def get_unique_scenario_labels(self) -> dict[str, list[str]]: + def _execute_get_unique_scenario_labels(self) -> dict[str, list[str]]: """Return all unique label values across scenario results.""" label_values: dict[str, set[str]] = {} - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = ( session.query(ScenarioResultEntry.labels) .filter(ScenarioResultEntry.labels.isnot(None)) @@ -5438,7 +5790,7 @@ def get_unique_scenario_labels(self) -> dict[str, list[str]]: label_values.setdefault(key, set()).add(value) return {key: sorted(values) for key, values in sorted(label_values.items())} - def get_scenario_attack_result_deltas( + def _execute_get_scenario_attack_result_deltas( self, *, scenario_result_id: str, @@ -5505,7 +5857,7 @@ def get_scenario_attack_result_deltas( .order_by(AttackResultEntry.timestamp.asc(), AttackResultEntry.id.asc()) .limit(limit + 1) ) - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = session.execute(statement).all() has_more = len(rows) > limit @@ -5554,7 +5906,7 @@ def get_scenario_attack_result_deltas( ) return deltas, has_more - def get_scenario_results( + def _execute_get_scenario_results( self, *, scenario_result_ids: Sequence[str] | None = None, @@ -5803,6 +6155,19 @@ def _get_attack_results_by_scenario( } def print_schema(self) -> None: + """ + Use ``print_schema_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.print_schema", + new_item="MemoryInterface.print_schema_async", + removed_in="1.4.0", + ) + self._print_schema() + + def _print_schema(self) -> None: """ Print the schema of all tables in the database. @@ -5819,3 +6184,3143 @@ def print_schema(self) -> None: print(f"Schema for {table_name}:") for column in table.columns: print(f" Column {column.name} ({column.type})") + + def get_all_embeddings(self) -> Sequence[EmbeddingDataEntry]: + """ + Use ``get_all_embeddings_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[EmbeddingDataEntry]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_all_embeddings", + new_item="MemoryInterface.get_all_embeddings_async", + removed_in="1.4.0", + ) + return self._execute_get_all_embeddings() + + @legacy_sync_override(lambda: MemoryInterface.get_all_embeddings) + async def get_all_embeddings_async(self) -> Sequence[EmbeddingDataEntry]: + """ + Load all EmbeddingData from the memory storage handler. + + Returns: + Sequence[EmbeddingDataEntry]: All stored embedding entries. + """ + return await self._run_database_operation_async(self._execute_get_all_embeddings) + + def add_conversation_to_memory(self, *, conversation: Conversation) -> None: + """ + Use ``add_conversation_to_memory_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.add_conversation_to_memory", + new_item="MemoryInterface.add_conversation_to_memory_async", + removed_in="1.4.0", + ) + return self._execute_add_conversation_to_memory(conversation=conversation) + + @legacy_sync_override(lambda: MemoryInterface.add_conversation_to_memory) + async def add_conversation_to_memory_async(self, *, conversation: Conversation) -> None: + """ + Register a conversation in memory, recording its conversation-scoped metadata. + + A conversation is a first-class entity held with a single target. Build a + ``Conversation`` when it is created and call this once (before, or independently + of, adding its messages) to record the target it is held with. Message writes + (``add_message_to_memory`` / ``add_message_pieces_to_memory``) deliberately do + not take a target, so that conversation ownership is expressed in a single place + rather than threaded through every write. + + Registration is idempotent only for an identical conversation: re-registering the + same ``conversation_id`` with the same target identity is a no-op, even across + PyRIT versions (so repeated per-turn registration is safe). Re-registering an existing + ``conversation_id`` with a different target is a conflict and raises ``ValueError`` -- a conversation is held + with exactly one target and is never re-targeted. + + Args: + conversation (Conversation): The conversation metadata to record, carrying the + ``conversation_id`` and the target it is held with (if known). + + Raises: + ValueError: If ``conversation_id`` is empty, or if a conversation with the same + id already exists with a different target. + """ + return await self._run_database_operation_async( + self._execute_add_conversation_to_memory, conversation=conversation + ) + + def add_message_pieces_to_memory(self, *, message_pieces: Sequence[MessagePiece]) -> None: + """ + Use ``add_message_pieces_to_memory_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.add_message_pieces_to_memory", + new_item="MemoryInterface.add_message_pieces_to_memory_async", + removed_in="1.4.0", + ) + return self._execute_add_message_pieces_to_memory(message_pieces=message_pieces) + + @legacy_sync_override(lambda: MemoryInterface.add_message_pieces_to_memory) + async def add_message_pieces_to_memory_async(self, *, message_pieces: Sequence[MessagePiece]) -> None: + """ + Insert a list of message pieces into the memory storage. + + Pieces flagged via ``MessagePiece.not_in_memory = True`` are silently filtered + out so callers don't need to track persistence policy themselves. Every + remaining piece must carry a non-empty ``conversation_id`` (the memory layer + never invents one -- see ``_validate_persistable_conversation_ids``). + + Conversation-scoped metadata (the target a conversation is held with) is not + recorded here; register it once via ``add_conversation_to_memory`` when the + conversation is created. + + This is a template method: subclasses implement only the backend-specific + ``_add_message_pieces_to_memory`` and inherit the filtering and validation + steps so no subclass can forget to run them. + + Args: + message_pieces (Sequence[MessagePiece]): The pieces to persist. + """ + return await self._run_database_operation_async( + self._execute_add_message_pieces_to_memory, message_pieces=message_pieces + ) + + def add_conversation_retry(self, *, conversation_id: str, sequence: int, reason: ConversationRetryReason) -> None: + """ + Use ``add_conversation_retry_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.add_conversation_retry", + new_item="MemoryInterface.add_conversation_retry_async", + removed_in="1.4.0", + ) + return self._execute_add_conversation_retry(conversation_id=conversation_id, sequence=sequence, reason=reason) + + @legacy_sync_override(lambda: MemoryInterface.add_conversation_retry) + async def add_conversation_retry_async( + self, *, conversation_id: str, sequence: int, reason: ConversationRetryReason + ) -> None: + """ + Append a retry record to the conversation-scoped metadata for ``conversation_id``. + + Records that a turn had to be retried (e.g. because its response failed JSON + validation and was rolled back out of memory). The conversation's ``Conversations`` + row is updated in place; if no row exists yet it is created. This is distinct from + the insert-only ``_insert_conversation``. + + Args: + conversation_id (str): The conversation whose turn was retried. + sequence (int): The sequence the retried turn's request occupies. + reason (ConversationRetryReason): Why the turn was retried. + + Raises: + SQLAlchemyError: If the database update fails; the transaction is rolled back first. + """ + return await self._run_database_operation_async( + self._execute_add_conversation_retry, conversation_id=conversation_id, sequence=sequence, reason=reason + ) + + def delete_conversation_pieces_after_sequence(self, *, conversation_id: str, sequence: int) -> int: + """ + Use ``delete_conversation_pieces_after_sequence_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + int: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.delete_conversation_pieces_after_sequence", + new_item="MemoryInterface.delete_conversation_pieces_after_sequence_async", + removed_in="1.4.0", + ) + return self._execute_delete_conversation_pieces_after_sequence( + conversation_id=conversation_id, sequence=sequence + ) + + @legacy_sync_override(lambda: MemoryInterface.delete_conversation_pieces_after_sequence) + async def delete_conversation_pieces_after_sequence_async(self, *, conversation_id: str, sequence: int) -> int: + """ + Delete all message pieces in a conversation whose sequence is greater than ``sequence``. + + Rolls a conversation back to a baseline so a failed turn can be resent on a clean + history. Dependent ``EmbeddingData`` rows for the deleted pieces are removed first to + avoid orphaned foreign keys. Pieces at or below ``sequence`` (e.g. the system prompt + and any prior good turns) are left intact. + + Args: + conversation_id (str): The conversation to roll back. + sequence (int): The baseline sequence; pieces with a greater sequence are deleted. + + Returns: + int: The number of ``PromptMemoryEntries`` deleted. + + Raises: + SQLAlchemyError: If the deletion fails; the transaction is rolled back first. + """ + return await self._run_database_operation_async( + self._execute_delete_conversation_pieces_after_sequence, conversation_id=conversation_id, sequence=sequence + ) + + def get_target_identifiers( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + endpoint: str | None = None, + model_name: str | None = None, + underlying_model_name: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + max_requests_per_minute: int | None = None, + supported_auth_modes: Sequence[str] | None = None, + ) -> Sequence[TargetIdentifier]: + """ + Use ``get_target_identifiers_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[TargetIdentifier]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_target_identifiers", + new_item="MemoryInterface.get_target_identifiers_async", + removed_in="1.4.0", + ) + return self._execute_get_target_identifiers( + identifier_hashes=identifier_hashes, + class_name=class_name, + endpoint=endpoint, + model_name=model_name, + underlying_model_name=underlying_model_name, + temperature=temperature, + top_p=top_p, + max_requests_per_minute=max_requests_per_minute, + supported_auth_modes=supported_auth_modes, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_target_identifiers) + async def get_target_identifiers_async( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + endpoint: str | None = None, + model_name: str | None = None, + underlying_model_name: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + max_requests_per_minute: int | None = None, + supported_auth_modes: Sequence[str] | None = None, + ) -> Sequence[TargetIdentifier]: + """ + Retrieve target identifiers using exact normalized-column filters. + + Args: + identifier_hashes (Sequence[str] | None): Content hashes to include. + class_name (str | None): Component class name to match. + endpoint (str | None): Target endpoint to match. + model_name (str | None): Target model name to match. + underlying_model_name (str | None): Underlying model name to match. + temperature (float | None): Temperature to match. + top_p (float | None): Top-p value to match. + max_requests_per_minute (int | None): Request limit to match. + supported_auth_modes (Sequence[str] | None): Authentication modes to match exactly, in any order. + + Returns: + Sequence[TargetIdentifier]: Matching identifiers ordered by content hash. + """ + return await self._run_database_operation_async( + self._execute_get_target_identifiers, + identifier_hashes=identifier_hashes, + class_name=class_name, + endpoint=endpoint, + model_name=model_name, + underlying_model_name=underlying_model_name, + temperature=temperature, + top_p=top_p, + max_requests_per_minute=max_requests_per_minute, + supported_auth_modes=supported_auth_modes, + ) + + def get_converter_identifiers( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + supported_input_types: Sequence[str] | None = None, + supported_output_types: Sequence[str] | None = None, + converter_target_hash: str | None = None, + sub_converter_hash: str | None = None, + ) -> Sequence[ConverterIdentifier]: + """ + Use ``get_converter_identifiers_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[ConverterIdentifier]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_converter_identifiers", + new_item="MemoryInterface.get_converter_identifiers_async", + removed_in="1.4.0", + ) + return self._execute_get_converter_identifiers( + identifier_hashes=identifier_hashes, + class_name=class_name, + supported_input_types=supported_input_types, + supported_output_types=supported_output_types, + converter_target_hash=converter_target_hash, + sub_converter_hash=sub_converter_hash, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_converter_identifiers) + async def get_converter_identifiers_async( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + supported_input_types: Sequence[str] | None = None, + supported_output_types: Sequence[str] | None = None, + converter_target_hash: str | None = None, + sub_converter_hash: str | None = None, + ) -> Sequence[ConverterIdentifier]: + """ + Retrieve converter identifiers using exact normalized-column filters. + + Args: + identifier_hashes (Sequence[str] | None): Content hashes to include. + class_name (str | None): Component class name to match. + supported_input_types (Sequence[str] | None): Input types to match exactly, in any order. + supported_output_types (Sequence[str] | None): Output types to match exactly, in any order. + converter_target_hash (str | None): Converter target hash to match. + sub_converter_hash (str | None): Nested converter hash to match. + + Returns: + Sequence[ConverterIdentifier]: Matching identifiers ordered by content hash. + """ + return await self._run_database_operation_async( + self._execute_get_converter_identifiers, + identifier_hashes=identifier_hashes, + class_name=class_name, + supported_input_types=supported_input_types, + supported_output_types=supported_output_types, + converter_target_hash=converter_target_hash, + sub_converter_hash=sub_converter_hash, + ) + + def get_scorer_identifiers( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + scorer_type: str | None = None, + score_aggregator: str | None = None, + prompt_target_hash: str | None = None, + ) -> Sequence[ScorerIdentifier]: + """ + Use ``get_scorer_identifiers_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[ScorerIdentifier]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scorer_identifiers", + new_item="MemoryInterface.get_scorer_identifiers_async", + removed_in="1.4.0", + ) + return self._execute_get_scorer_identifiers( + identifier_hashes=identifier_hashes, + class_name=class_name, + scorer_type=scorer_type, + score_aggregator=score_aggregator, + prompt_target_hash=prompt_target_hash, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_scorer_identifiers) + async def get_scorer_identifiers_async( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + scorer_type: str | None = None, + score_aggregator: str | None = None, + prompt_target_hash: str | None = None, + ) -> Sequence[ScorerIdentifier]: + """ + Retrieve scorer identifiers using exact normalized-column filters. + + Args: + identifier_hashes (Sequence[str] | None): Content hashes to include. + class_name (str | None): Component class name to match. + scorer_type (str | None): Scorer type to match. + score_aggregator (str | None): Score aggregator to match. + prompt_target_hash (str | None): Scorer target hash to match. + + Returns: + Sequence[ScorerIdentifier]: Matching identifiers ordered by content hash. + """ + return await self._run_database_operation_async( + self._execute_get_scorer_identifiers, + identifier_hashes=identifier_hashes, + class_name=class_name, + scorer_type=scorer_type, + score_aggregator=score_aggregator, + prompt_target_hash=prompt_target_hash, + ) + + def get_scenario_identifiers( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + version: int | None = None, + techniques: Sequence[str] | None = None, + datasets: Sequence[str] | None = None, + objective_target_hash: str | None = None, + objective_scorer_hash: str | None = None, + ) -> Sequence[ScenarioIdentifier]: + """ + Use ``get_scenario_identifiers_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[ScenarioIdentifier]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scenario_identifiers", + new_item="MemoryInterface.get_scenario_identifiers_async", + removed_in="1.4.0", + ) + return self._execute_get_scenario_identifiers( + identifier_hashes=identifier_hashes, + class_name=class_name, + version=version, + techniques=techniques, + datasets=datasets, + objective_target_hash=objective_target_hash, + objective_scorer_hash=objective_scorer_hash, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_scenario_identifiers) + async def get_scenario_identifiers_async( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + version: int | None = None, + techniques: Sequence[str] | None = None, + datasets: Sequence[str] | None = None, + objective_target_hash: str | None = None, + objective_scorer_hash: str | None = None, + ) -> Sequence[ScenarioIdentifier]: + """ + Retrieve scenario identifiers using exact normalized-column filters. + + Args: + identifier_hashes (Sequence[str] | None): Content hashes to include. + class_name (str | None): Component class name to match. + version (int | None): Scenario definition version to match. + techniques (Sequence[str] | None): Technique names to match exactly, in any order. + datasets (Sequence[str] | None): Dataset names to match exactly, in any order. + objective_target_hash (str | None): Objective target hash to match. + objective_scorer_hash (str | None): Objective scorer hash to match. + + Returns: + Sequence[ScenarioIdentifier]: Matching identifiers ordered by content hash. + """ + return await self._run_database_operation_async( + self._execute_get_scenario_identifiers, + identifier_hashes=identifier_hashes, + class_name=class_name, + version=version, + techniques=techniques, + datasets=datasets, + objective_target_hash=objective_target_hash, + objective_scorer_hash=objective_scorer_hash, + ) + + def get_seed_identifiers( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + value: str | None = None, + value_sha256: str | None = None, + data_type: str | None = None, + dataset_name: str | None = None, + is_general_technique: bool | None = None, + ) -> Sequence[SeedIdentifier]: + """ + Use ``get_seed_identifiers_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[SeedIdentifier]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_seed_identifiers", + new_item="MemoryInterface.get_seed_identifiers_async", + removed_in="1.4.0", + ) + return self._execute_get_seed_identifiers( + identifier_hashes=identifier_hashes, + class_name=class_name, + value=value, + value_sha256=value_sha256, + data_type=data_type, + dataset_name=dataset_name, + is_general_technique=is_general_technique, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_seed_identifiers) + async def get_seed_identifiers_async( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + value: str | None = None, + value_sha256: str | None = None, + data_type: str | None = None, + dataset_name: str | None = None, + is_general_technique: bool | None = None, + ) -> Sequence[SeedIdentifier]: + """ + Retrieve seed identifiers using exact normalized-column filters. + + Args: + identifier_hashes (Sequence[str] | None): Content hashes to include. + class_name (str | None): Component class name to match. + value (str | None): Seed value to match. + value_sha256 (str | None): Seed value hash to match. + data_type (str | None): Seed data type to match. + dataset_name (str | None): Dataset name to match. + is_general_technique (bool | None): General-technique flag to match. + + Returns: + Sequence[SeedIdentifier]: Matching identifiers ordered by content hash. + """ + return await self._run_database_operation_async( + self._execute_get_seed_identifiers, + identifier_hashes=identifier_hashes, + class_name=class_name, + value=value, + value_sha256=value_sha256, + data_type=data_type, + dataset_name=dataset_name, + is_general_technique=is_general_technique, + ) + + def get_attack_identifiers( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + adversarial_system_prompt: str | None = None, + adversarial_seed_prompt: str | None = None, + objective_target_hash: str | None = None, + adversarial_chat_hash: str | None = None, + objective_scorer_hash: str | None = None, + ) -> Sequence[AttackIdentifier]: + """ + Use ``get_attack_identifiers_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[AttackIdentifier]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_attack_identifiers", + new_item="MemoryInterface.get_attack_identifiers_async", + removed_in="1.4.0", + ) + return self._execute_get_attack_identifiers( + identifier_hashes=identifier_hashes, + class_name=class_name, + adversarial_system_prompt=adversarial_system_prompt, + adversarial_seed_prompt=adversarial_seed_prompt, + objective_target_hash=objective_target_hash, + adversarial_chat_hash=adversarial_chat_hash, + objective_scorer_hash=objective_scorer_hash, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_attack_identifiers) + async def get_attack_identifiers_async( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + adversarial_system_prompt: str | None = None, + adversarial_seed_prompt: str | None = None, + objective_target_hash: str | None = None, + adversarial_chat_hash: str | None = None, + objective_scorer_hash: str | None = None, + ) -> Sequence[AttackIdentifier]: + """ + Retrieve attack identifiers using exact normalized-column filters. + + Args: + identifier_hashes (Sequence[str] | None): Content hashes to include. + class_name (str | None): Component class name to match. + adversarial_system_prompt (str | None): Adversarial system prompt to match. + adversarial_seed_prompt (str | None): Adversarial seed prompt to match. + objective_target_hash (str | None): Objective target hash to match. + adversarial_chat_hash (str | None): Adversarial chat target hash to match. + objective_scorer_hash (str | None): Objective scorer hash to match. + + Returns: + Sequence[AttackIdentifier]: Matching identifiers ordered by content hash. + """ + return await self._run_database_operation_async( + self._execute_get_attack_identifiers, + identifier_hashes=identifier_hashes, + class_name=class_name, + adversarial_system_prompt=adversarial_system_prompt, + adversarial_seed_prompt=adversarial_seed_prompt, + objective_target_hash=objective_target_hash, + adversarial_chat_hash=adversarial_chat_hash, + objective_scorer_hash=objective_scorer_hash, + ) + + def get_attack_technique_identifiers( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + attack_identifier_hash: str | None = None, + ) -> Sequence[AttackTechniqueIdentifier]: + """ + Use ``get_attack_technique_identifiers_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[AttackTechniqueIdentifier]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_attack_technique_identifiers", + new_item="MemoryInterface.get_attack_technique_identifiers_async", + removed_in="1.4.0", + ) + return self._execute_get_attack_technique_identifiers( + identifier_hashes=identifier_hashes, class_name=class_name, attack_identifier_hash=attack_identifier_hash + ) + + @legacy_sync_override(lambda: MemoryInterface.get_attack_technique_identifiers) + async def get_attack_technique_identifiers_async( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + attack_identifier_hash: str | None = None, + ) -> Sequence[AttackTechniqueIdentifier]: + """ + Retrieve attack technique identifiers using exact normalized-column filters. + + Args: + identifier_hashes (Sequence[str] | None): Content hashes to include. + class_name (str | None): Component class name to match. + attack_identifier_hash (str | None): Attack identifier hash to match. + + Returns: + Sequence[AttackTechniqueIdentifier]: Matching identifiers ordered by content hash. + """ + return await self._run_database_operation_async( + self._execute_get_attack_technique_identifiers, + identifier_hashes=identifier_hashes, + class_name=class_name, + attack_identifier_hash=attack_identifier_hash, + ) + + def get_atomic_attack_identifiers( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + attack_technique_identifier_hash: str | None = None, + ) -> Sequence[AtomicAttackIdentifier]: + """ + Use ``get_atomic_attack_identifiers_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[AtomicAttackIdentifier]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_atomic_attack_identifiers", + new_item="MemoryInterface.get_atomic_attack_identifiers_async", + removed_in="1.4.0", + ) + return self._execute_get_atomic_attack_identifiers( + identifier_hashes=identifier_hashes, + class_name=class_name, + attack_technique_identifier_hash=attack_technique_identifier_hash, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_atomic_attack_identifiers) + async def get_atomic_attack_identifiers_async( + self, + *, + identifier_hashes: Sequence[str] | None = None, + class_name: str | None = None, + attack_technique_identifier_hash: str | None = None, + ) -> Sequence[AtomicAttackIdentifier]: + """ + Retrieve atomic attack identifiers using exact normalized-column filters. + + Args: + identifier_hashes (Sequence[str] | None): Content hashes to include. + class_name (str | None): Component class name to match. + attack_technique_identifier_hash (str | None): Attack technique hash to match. + + Returns: + Sequence[AtomicAttackIdentifier]: Matching identifiers ordered by content hash. + """ + return await self._run_database_operation_async( + self._execute_get_atomic_attack_identifiers, + identifier_hashes=identifier_hashes, + class_name=class_name, + attack_technique_identifier_hash=attack_technique_identifier_hash, + ) + + def get_unique_attack_class_names(self) -> list[str]: + """ + Use ``get_unique_attack_class_names_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + list[str]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_unique_attack_class_names", + new_item="MemoryInterface.get_unique_attack_class_names_async", + removed_in="1.4.0", + ) + return self._execute_get_unique_attack_class_names() + + @legacy_sync_override(lambda: MemoryInterface.get_unique_attack_class_names) + async def get_unique_attack_class_names_async(self) -> list[str]: + """ + Return sorted unique attack class names from all stored attack results. + + Extracts class_name from the atomic_attack_identifier JSON column via a + database-level DISTINCT query. + + Returns: + Sorted list of unique attack class name strings. + """ + return await self._run_database_operation_async(self._execute_get_unique_attack_class_names) + + def get_unique_converter_class_names(self) -> list[str]: + """ + Use ``get_unique_converter_class_names_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + list[str]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_unique_converter_class_names", + new_item="MemoryInterface.get_unique_converter_class_names_async", + removed_in="1.4.0", + ) + return self._execute_get_unique_converter_class_names() + + @legacy_sync_override(lambda: MemoryInterface.get_unique_converter_class_names) + async def get_unique_converter_class_names_async(self) -> list[str]: + """ + Return sorted unique converter class names used across all attack results. + + Extracts class_name values from the nested request_converters array + within the atomic_attack_identifier JSON column via a database-level query. + + Returns: + Sorted list of unique converter class name strings. + """ + return await self._run_database_operation_async(self._execute_get_unique_converter_class_names) + + def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, "ConversationStats"]: + """ + Use ``get_conversation_stats_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + dict[str, 'ConversationStats']: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_conversation_stats", + new_item="MemoryInterface.get_conversation_stats_async", + removed_in="1.4.0", + ) + return self._execute_get_conversation_stats(conversation_ids=conversation_ids) + + @legacy_sync_override(lambda: MemoryInterface.get_conversation_stats) + async def get_conversation_stats_async(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. + """ + return await self._run_database_operation_async( + self._execute_get_conversation_stats, conversation_ids=conversation_ids + ) + + def add_scores_to_memory( + self, + *, + scores: Sequence[Score], + observations: Sequence[Observation] = (), + intermediate_scores: Sequence[Score] = (), + ) -> None: + """ + Use ``add_scores_to_memory_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.add_scores_to_memory", + new_item="MemoryInterface.add_scores_to_memory_async", + removed_in="1.4.0", + ) + return self._execute_add_scores_to_memory( + scores=scores, observations=observations, intermediate_scores=intermediate_scores + ) + + def get_scorable_content(self, *, content_ids: Sequence[uuid.UUID | str]) -> dict[uuid.UUID, ContentScorable]: + """ + Use ``get_scorable_content_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + dict[uuid.UUID, ContentScorable]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scorable_content", + new_item="MemoryInterface.get_scorable_content_async", + removed_in="1.4.0", + ) + return self._execute_get_scorable_content(content_ids=content_ids) + + @legacy_sync_override(lambda: MemoryInterface.get_scorable_content) + async def get_scorable_content_async( + self, *, content_ids: Sequence[uuid.UUID | str] + ) -> dict[uuid.UUID, ContentScorable]: + """ + Load the loose content that stored scores are anchored on. + + Args: + content_ids: The ids named by ``ContentEntryScorable`` anchors. + + Returns: + dict[uuid.UUID, ContentScorable]: The content by id, omitting ids with no row. + """ + return await self._run_database_operation_async(self._execute_get_scorable_content, content_ids=content_ids) + + def get_scorable_content_hashes(self, *, content_ids: Sequence[uuid.UUID | str]) -> dict[uuid.UUID, str]: + """ + Use ``get_scorable_content_hashes_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + dict[uuid.UUID, str]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scorable_content_hashes", + new_item="MemoryInterface.get_scorable_content_hashes_async", + removed_in="1.4.0", + ) + return self._execute_get_scorable_content_hashes(content_ids=content_ids) + + @legacy_sync_override(lambda: MemoryInterface.get_scorable_content_hashes) + async def get_scorable_content_hashes_async( + self, *, content_ids: Sequence[uuid.UUID | str] + ) -> dict[uuid.UUID, str]: + """ + Load the immutable content digest for stored score anchors. + + Returns: + dict[uuid.UUID, str]: SHA-256 digests by content ID. + """ + return await self._run_database_operation_async( + self._execute_get_scorable_content_hashes, content_ids=content_ids + ) + + def get_observations(self, *, observation_ids: Sequence[uuid.UUID | str]) -> list[Observation]: + """ + Use ``get_observations_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + list[Observation]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_observations", + new_item="MemoryInterface.get_observations_async", + removed_in="1.4.0", + ) + return self._execute_get_observations(observation_ids=observation_ids) + + @legacy_sync_override(lambda: MemoryInterface.get_observations) + async def get_observations_async(self, *, observation_ids: Sequence[uuid.UUID | str]) -> list[Observation]: + """ + Load observations by ID. + + Args: + observation_ids (Sequence[uuid.UUID | str]): Observation IDs to load. + + Returns: + list[Observation]: Stored observations in the requested order. Missing IDs are omitted. + """ + return await self._run_database_operation_async(self._execute_get_observations, observation_ids=observation_ids) + + def get_scores( + self, + *, + score_ids: Sequence[str] | None = None, + score_type: str | None = None, + score_category: str | None = None, + sent_after: datetime | None = None, + sent_before: datetime | None = None, + identifier_filters: Sequence[IdentifierFilter] | None = None, + include_intermediate: bool = False, + ) -> Sequence[Score]: + """ + Use ``get_scores_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[Score]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scores", new_item="MemoryInterface.get_scores_async", removed_in="1.4.0" + ) + return self._execute_get_scores( + score_ids=score_ids, + score_type=score_type, + score_category=score_category, + sent_after=sent_after, + sent_before=sent_before, + identifier_filters=identifier_filters, + include_intermediate=include_intermediate, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_scores) + async def get_scores_async( + self, + *, + score_ids: Sequence[str] | None = None, + score_type: str | None = None, + score_category: str | None = None, + sent_after: datetime | None = None, + sent_before: datetime | None = None, + identifier_filters: Sequence[IdentifierFilter] | None = None, + include_intermediate: bool = False, + ) -> Sequence[Score]: + """ + Retrieve a list of Score objects based on the specified filters. + + Args: + score_ids (Sequence[str] | None): A list of score IDs to filter by. + score_type (str | None): The type of the score to filter by. + score_category (str | None): The category of the score to filter by. + sent_after (datetime | None): Filter for scores sent after this datetime. + sent_before (datetime | None): Filter for scores sent before this datetime. + identifier_filters (Sequence[IdentifierFilter] | None): A sequence of IdentifierFilter objects that + allows filtering by various scorer identifier JSON properties. Defaults to None. + include_intermediate (bool): Include nested results. Explicit IDs always include them. + + Returns: + Sequence[Score]: A list of Score objects that match the specified filters. + """ + return await self._run_database_operation_async( + self._execute_get_scores, + score_ids=score_ids, + score_type=score_type, + score_category=score_category, + sent_after=sent_after, + sent_before=sent_before, + identifier_filters=identifier_filters, + include_intermediate=include_intermediate, + ) + + def get_prompt_scores( + self, + *, + role: str | None = None, + conversation_id: str | uuid.UUID | None = None, + prompt_ids: Sequence[str | uuid.UUID] | None = None, + labels: dict[str, str] | None = None, + prompt_metadata: dict[str, str | int] | None = None, + sent_after: datetime | None = None, + sent_before: datetime | None = None, + original_values: Sequence[str] | None = None, + converted_values: Sequence[str] | None = None, + data_type: str | None = None, + not_data_type: str | None = None, + converted_value_sha256: Sequence[str] | None = None, + include_intermediate: bool = False, + ) -> Sequence[Score]: + """ + Use ``get_prompt_scores_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[Score]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_prompt_scores", + new_item="MemoryInterface.get_prompt_scores_async", + removed_in="1.4.0", + ) + return self._execute_get_prompt_scores( + role=role, + conversation_id=conversation_id, + prompt_ids=prompt_ids, + labels=labels, + prompt_metadata=prompt_metadata, + sent_after=sent_after, + sent_before=sent_before, + original_values=original_values, + converted_values=converted_values, + data_type=data_type, + not_data_type=not_data_type, + converted_value_sha256=converted_value_sha256, + include_intermediate=include_intermediate, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_prompt_scores) + async def get_prompt_scores_async( + self, + *, + role: str | None = None, + conversation_id: str | uuid.UUID | None = None, + prompt_ids: Sequence[str | uuid.UUID] | None = None, + labels: dict[str, str] | None = None, + prompt_metadata: dict[str, str | int] | None = None, + sent_after: datetime | None = None, + sent_before: datetime | None = None, + original_values: Sequence[str] | None = None, + converted_values: Sequence[str] | None = None, + data_type: str | None = None, + not_data_type: str | None = None, + converted_value_sha256: Sequence[str] | None = None, + include_intermediate: bool = False, + ) -> Sequence[Score]: + """ + Retrieve scores attached to message pieces based on the specified filters. + + Args: + role (str | None, optional): The role of the prompt. Defaults to None. + conversation_id (str | uuid.UUID | None, optional): The ID of the conversation. Defaults to None. + prompt_ids (Sequence[str] | Sequence[uuid.UUID] | None, optional): A list of prompt IDs. + Defaults to None. + labels (dict[str, str] | None, optional): A dictionary of labels. Defaults to None. + prompt_metadata (dict[str, str | int] | None, optional): The metadata associated with the prompt. + Defaults to None. + sent_after (datetime | None, optional): Filter for prompts sent after this datetime. Defaults to None. + sent_before (datetime | None, optional): Filter for prompts sent before this datetime. Defaults to None. + original_values (Sequence[str] | None, optional): A list of original values. Defaults to None. + converted_values (Sequence[str] | None, optional): A list of converted values. Defaults to None. + data_type (str | None, optional): The data type to filter by. Defaults to None. + not_data_type (str | None, optional): The data type to exclude. Defaults to None. + converted_value_sha256 (Sequence[str] | None, optional): A list of SHA256 hashes of converted values. + Defaults to None. + include_intermediate (bool): Include nested judgments instead of only public root results. + + Returns: + Sequence[Score]: A list of scores extracted from the message pieces. + """ + return await self._run_database_operation_async( + self._execute_get_prompt_scores, + role=role, + conversation_id=conversation_id, + prompt_ids=prompt_ids, + labels=labels, + prompt_metadata=prompt_metadata, + sent_after=sent_after, + sent_before=sent_before, + original_values=original_values, + converted_values=converted_values, + data_type=data_type, + not_data_type=not_data_type, + converted_value_sha256=converted_value_sha256, + include_intermediate=include_intermediate, + ) + + def get_conversation_messages(self, *, conversation_id: str) -> MutableSequence[Message]: + """ + Use ``get_conversation_messages_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + MutableSequence[Message]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_conversation_messages", + new_item="MemoryInterface.get_conversation_messages_async", + removed_in="1.4.0", + ) + return self._execute_get_conversation_messages(conversation_id=conversation_id) + + @legacy_sync_override(lambda: MemoryInterface.get_conversation_messages) + async def get_conversation_messages_async(self, *, conversation_id: str) -> MutableSequence[Message]: + """ + Retrieve a list of Message objects that have the specified conversation ID. + + Args: + conversation_id (str): The conversation ID to match. + + Returns: + MutableSequence[Message]: A list of chat memory entries with the specified conversation ID. + + Raises: + ValueError: If conversation_id is empty or None. A falsy id would cause the underlying + get_message_pieces filter to be skipped, silently returning pieces from every + conversation in memory. + """ + return await self._run_database_operation_async( + self._execute_get_conversation_messages, conversation_id=conversation_id + ) + + def get_request_from_response(self, *, response: Message) -> Message: + """ + Use ``get_request_from_response_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Message: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_request_from_response", + new_item="MemoryInterface.get_request_from_response_async", + removed_in="1.4.0", + ) + return self._execute_get_request_from_response(response=response) + + @legacy_sync_override(lambda: MemoryInterface.get_request_from_response) + async def get_request_from_response_async(self, *, response: Message) -> Message: + """ + Retrieve the request that produced the given response. + + Args: + response (Message): The response message object to match. + + Returns: + Message: The corresponding message object. + + Raises: + ValueError: If the response is not from an assistant role or has no preceding request. + """ + return await self._run_database_operation_async(self._execute_get_request_from_response, response=response) + + def get_message_pieces( + self, + *, + role: str | None = None, + conversation_id: str | uuid.UUID | None = None, + prompt_ids: Sequence[str | uuid.UUID] | None = None, + labels: dict[str, str] | None = None, + prompt_metadata: dict[str, str | int] | None = None, + sent_after: datetime | None = None, + sent_before: datetime | None = None, + original_values: Sequence[str] | None = None, + converted_values: Sequence[str] | None = None, + data_type: str | None = None, + not_data_type: str | None = None, + converted_value_sha256: Sequence[str] | None = None, + identifier_filters: Sequence[IdentifierFilter] | None = None, + ) -> Sequence[MessagePiece]: + """ + Use ``get_message_pieces_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[MessagePiece]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_message_pieces", + new_item="MemoryInterface.get_message_pieces_async", + removed_in="1.4.0", + ) + return self._execute_get_message_pieces( + role=role, + conversation_id=conversation_id, + prompt_ids=prompt_ids, + labels=labels, + prompt_metadata=prompt_metadata, + sent_after=sent_after, + sent_before=sent_before, + original_values=original_values, + converted_values=converted_values, + data_type=data_type, + not_data_type=not_data_type, + converted_value_sha256=converted_value_sha256, + identifier_filters=identifier_filters, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_message_pieces) + async def get_message_pieces_async( + self, + *, + role: str | None = None, + conversation_id: str | uuid.UUID | None = None, + prompt_ids: Sequence[str | uuid.UUID] | None = None, + labels: dict[str, str] | None = None, + prompt_metadata: dict[str, str | int] | None = None, + sent_after: datetime | None = None, + sent_before: datetime | None = None, + original_values: Sequence[str] | None = None, + converted_values: Sequence[str] | None = None, + data_type: str | None = None, + not_data_type: str | None = None, + converted_value_sha256: Sequence[str] | None = None, + identifier_filters: Sequence[IdentifierFilter] | None = None, + ) -> Sequence[MessagePiece]: + """ + Retrieve a list of MessagePiece objects based on the specified filters. + + Args: + role (str | None, optional): The role of the prompt. Defaults to None. + conversation_id (str | uuid.UUID | None, optional): The ID of the conversation. Defaults to None. + prompt_ids (Sequence[str] | Sequence[uuid.UUID] | None, optional): A list of prompt IDs. + Defaults to None. + labels (dict[str, str] | None, optional): A dictionary of labels. Defaults to None. + prompt_metadata (dict[str, str | int] | None, optional): The metadata associated with the prompt. + Defaults to None. + sent_after (datetime | None, optional): Filter for prompts sent after this datetime. Defaults to None. + sent_before (datetime | None, optional): Filter for prompts sent before this datetime. Defaults to None. + original_values (Sequence[str] | None, optional): A list of original values. Defaults to None. + converted_values (Sequence[str] | None, optional): A list of converted values. Defaults to None. + data_type (str | None, optional): The data type to filter by. Defaults to None. + not_data_type (str | None, optional): The data type to exclude. Defaults to None. + converted_value_sha256 (Sequence[str] | None, optional): A list of SHA256 hashes of converted values. + Defaults to None. + identifier_filters (Sequence[IdentifierFilter] | None, optional): + A sequence of IdentifierFilter objects that + allow filtering by various identifier JSON properties. Defaults to None. + + Returns: + Sequence[MessagePiece]: A list of MessagePiece objects that match the specified filters. + + Raises: + Exception: If there is an error retrieving the prompts, + an exception is logged and an empty list is returned. + """ + return await self._run_database_operation_async( + self._execute_get_message_pieces, + role=role, + conversation_id=conversation_id, + prompt_ids=prompt_ids, + labels=labels, + prompt_metadata=prompt_metadata, + sent_after=sent_after, + sent_before=sent_before, + original_values=original_values, + converted_values=converted_values, + data_type=data_type, + not_data_type=not_data_type, + converted_value_sha256=converted_value_sha256, + identifier_filters=identifier_filters, + ) + + def duplicate_messages(self, *, messages: Sequence[Message]) -> tuple[str, Sequence[MessagePiece]]: + """ + Use ``duplicate_messages_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + tuple[str, Sequence[MessagePiece]]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.duplicate_messages", + new_item="MemoryInterface.duplicate_messages_async", + removed_in="1.4.0", + ) + return self._execute_duplicate_messages(messages=messages) + + @legacy_sync_override(lambda: MemoryInterface.duplicate_messages) + async def duplicate_messages_async(self, *, messages: Sequence[Message]) -> tuple[str, Sequence[MessagePiece]]: + """ + 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: The messages to duplicate. + + Returns: + Tuple of (new_conversation_id, duplicated_message_pieces). + """ + return await self._run_database_operation_async(self._execute_duplicate_messages, messages=messages) + + def duplicate_conversation(self, *, conversation_id: str) -> str: + """ + Use ``duplicate_conversation_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + str: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.duplicate_conversation", + new_item="MemoryInterface.duplicate_conversation_async", + removed_in="1.4.0", + ) + return self._execute_duplicate_conversation(conversation_id=conversation_id) + + @legacy_sync_override(lambda: MemoryInterface.duplicate_conversation) + async def duplicate_conversation_async(self, *, conversation_id: str) -> str: + """ + Duplicate a conversation for reuse. + + This can be useful when an attack strategy requires branching out from a particular point in the conversation. + One cannot continue both branches with the same conversation ID since that would corrupt + the memory. Instead, one needs to duplicate the conversation and continue with the new conversation ID. + + Args: + conversation_id (str): The conversation ID with existing conversations. + + Returns: + The uuid for the new conversation. + """ + return await self._run_database_operation_async( + self._execute_duplicate_conversation, conversation_id=conversation_id + ) + + def duplicate_conversation_excluding_last_turn(self, *, conversation_id: str) -> str: + """ + Use ``duplicate_conversation_excluding_last_turn_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + str: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.duplicate_conversation_excluding_last_turn", + new_item="MemoryInterface.duplicate_conversation_excluding_last_turn_async", + removed_in="1.4.0", + ) + return self._execute_duplicate_conversation_excluding_last_turn(conversation_id=conversation_id) + + @legacy_sync_override(lambda: MemoryInterface.duplicate_conversation_excluding_last_turn) + async def duplicate_conversation_excluding_last_turn_async(self, *, conversation_id: str) -> str: + """ + Duplicate a conversation, excluding the last turn. In this case, last turn is defined as before the last + user request (e.g. if there is half a turn, it just removes that half). + + This can be useful when an attack strategy requires back tracking the last prompt/response pair. + + Args: + conversation_id (str): The conversation ID with existing conversations. + + Returns: + The uuid for the new conversation. + """ + return await self._run_database_operation_async( + self._execute_duplicate_conversation_excluding_last_turn, conversation_id=conversation_id + ) + + def add_message_to_memory(self, *, request: Message) -> None: + """ + Use ``add_message_to_memory_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.add_message_to_memory", + new_item="MemoryInterface.add_message_to_memory_async", + removed_in="1.4.0", + ) + return self._execute_add_message_to_memory(request=request) + + @legacy_sync_override(lambda: MemoryInterface.add_message_to_memory) + async def add_message_to_memory_async(self, *, request: Message) -> None: + """ + Insert a list of message pieces into the memory storage. + + Automatically updates the sequence to be the next number in the conversation. + If necessary, generates embedding data for applicable entries + + Args: + request (Message): The message to add to the memory. + """ + if not await self._run_database_operation_async(self._persist_message, request): + return + if self.memory_embedding: + entries = [ + await asyncio.to_thread(self.memory_embedding.generate_embedding_memory_data, message_piece=piece) + for piece in request.message_pieces + if not piece.not_in_memory and piece.converted_value_data_type == "text" + ] + await self._run_database_operation_async(self._add_embeddings_to_memory, embedding_data=entries) + + def update_prompt_entries_by_conversation_id(self, *, conversation_id: str, update_fields: dict[str, Any]) -> bool: + """ + Use ``update_prompt_entries_by_conversation_id_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + bool: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.update_prompt_entries_by_conversation_id", + new_item="MemoryInterface.update_prompt_entries_by_conversation_id_async", + removed_in="1.4.0", + ) + return self._execute_update_prompt_entries_by_conversation_id( + conversation_id=conversation_id, update_fields=update_fields + ) + + @legacy_sync_override(lambda: MemoryInterface.update_prompt_entries_by_conversation_id) + async def update_prompt_entries_by_conversation_id_async( + self, *, conversation_id: str, update_fields: dict[str, Any] + ) -> bool: + """ + Update prompt entries for a given conversation ID with the specified field values. + + Args: + conversation_id (str): The conversation ID of the entries to be updated. + update_fields (dict): A dictionary of field names and their new values (ex. {"labels": {"test": "value"}}) + + Returns: + bool: True if the update was successful, False otherwise. + + Raises: + ValueError: If update_fields is empty or not provided. + ValueError: If an entry is immutable observation evidence. + """ + return await self._run_database_operation_async( + self._execute_update_prompt_entries_by_conversation_id, + conversation_id=conversation_id, + update_fields=update_fields, + ) + + def update_prompt_metadata_by_conversation_id( + self, *, conversation_id: str, prompt_metadata: dict[str, str | int] + ) -> bool: + """ + Use ``update_prompt_metadata_by_conversation_id_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + bool: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.update_prompt_metadata_by_conversation_id", + new_item="MemoryInterface.update_prompt_metadata_by_conversation_id_async", + removed_in="1.4.0", + ) + return self._execute_update_prompt_metadata_by_conversation_id( + conversation_id=conversation_id, prompt_metadata=prompt_metadata + ) + + @legacy_sync_override(lambda: MemoryInterface.update_prompt_metadata_by_conversation_id) + async def update_prompt_metadata_by_conversation_id_async( + self, *, conversation_id: str, prompt_metadata: dict[str, str | int] + ) -> bool: + """ + Update the metadata of prompt entries in memory for a given conversation ID. + + Args: + conversation_id (str): The conversation ID of the entries to be updated. + prompt_metadata (dict[str, str | int]): New metadata. + + Returns: + bool: True if the update was successful, False otherwise. + """ + return await self._run_database_operation_async( + self._execute_update_prompt_metadata_by_conversation_id, + conversation_id=conversation_id, + prompt_metadata=prompt_metadata, + ) + + def get_seeds( + self, + *, + value: str | None = None, + value_sha256: Sequence[str] | None = None, + dataset_name: str | None = None, + dataset_name_pattern: str | None = None, + data_types: Sequence[str] | None = None, + harm_categories: Sequence[str] | None = None, + added_by: str | None = None, + authors: Sequence[str] | None = None, + groups: Sequence[str] | None = None, + source: str | None = None, + seed_type: SeedType | None = None, + parameters: Sequence[str] | None = None, + metadata: dict[str, str | int] | None = None, + prompt_group_ids: Sequence[uuid.UUID] | None = None, + ) -> Sequence[Seed]: + """ + Use ``get_seeds_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[Seed]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_seeds", new_item="MemoryInterface.get_seeds_async", removed_in="1.4.0" + ) + return self._execute_get_seeds( + value=value, + value_sha256=value_sha256, + dataset_name=dataset_name, + dataset_name_pattern=dataset_name_pattern, + data_types=data_types, + harm_categories=harm_categories, + added_by=added_by, + authors=authors, + groups=groups, + source=source, + seed_type=seed_type, + parameters=parameters, + metadata=metadata, + prompt_group_ids=prompt_group_ids, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_seeds) + async def get_seeds_async( + self, + *, + value: str | None = None, + value_sha256: Sequence[str] | None = None, + dataset_name: str | None = None, + dataset_name_pattern: str | None = None, + data_types: Sequence[str] | None = None, + harm_categories: Sequence[str] | None = None, + added_by: str | None = None, + authors: Sequence[str] | None = None, + groups: Sequence[str] | None = None, + source: str | None = None, + seed_type: SeedType | None = None, + parameters: Sequence[str] | None = None, + metadata: dict[str, str | int] | None = None, + prompt_group_ids: Sequence[uuid.UUID] | None = None, + ) -> Sequence[Seed]: + """ + Retrieve a list of seed prompts based on the specified filters. + + Args: + value (str): The value to match by substring. If None, all values are returned. + value_sha256 (Sequence[str] | None): A list of SHA256 hashes of values to match. + If None, all values are returned. + dataset_name (str): The dataset name to match exactly. If None, all dataset names are considered. + dataset_name_pattern (str): A pattern to match dataset names using SQL LIKE syntax. + Supports wildcards: % (any characters) and _ (single character). + Examples: "harm%" matches names starting with "harm", "%test%" matches names containing "test". + If both dataset_name and dataset_name_pattern are provided, dataset_name takes precedence. + data_types (Sequence[str] | None): List of data types to filter seed prompts by + (e.g., text, image_path). + harm_categories (Sequence[str]): A list of harm categories to filter by. If None, + all harm categories are considered. + Specifying multiple harm categories returns only prompts that are marked with all harm categories. + added_by (str): The user who added the prompts. + authors (Sequence[str]): A list of authors to filter by. + Note that this filters by substring, so a query for "Adam Jones" may not return results if the record + is "A. Jones", "Jones, Adam", etc. If None, all authors are considered. + groups (Sequence[str]): A list of groups to filter by. If None, all groups are considered. + source (str): The source to filter by. If None, all sources are considered. + seed_type (SeedType): The type of seed to filter by ("prompt", "objective", or + "simulated_conversation"). + parameters (Sequence[str]): A list of parameters to filter by. Specifying parameters effectively returns + prompt templates instead of prompts. + metadata (dict[str, str | int]): A free-form dictionary for tagging prompts with custom metadata. + prompt_group_ids (Sequence[uuid.UUID]): A list of prompt group IDs to filter by. + + Returns: + Sequence[Seed]: A list of seeds (e.g., SeedPrompt, SeedObjective, SeedSimulatedConversation) + matching the criteria. + """ + return await self._run_database_operation_async( + self._execute_get_seeds, + value=value, + value_sha256=value_sha256, + dataset_name=dataset_name, + dataset_name_pattern=dataset_name_pattern, + data_types=data_types, + harm_categories=harm_categories, + added_by=added_by, + authors=authors, + groups=groups, + source=source, + seed_type=seed_type, + parameters=parameters, + metadata=metadata, + prompt_group_ids=prompt_group_ids, + ) + + def remove_seeds_from_memory( + self, + *, + value: str | None = None, + exact: bool = True, + value_sha256: Sequence[str] | None = None, + dataset_name: str | None = None, + dataset_name_pattern: str | None = None, + data_types: Sequence[str] | None = None, + harm_categories: Sequence[str] | None = None, + added_by: str | None = None, + authors: Sequence[str] | None = None, + groups: Sequence[str] | None = None, + source: str | None = None, + seed_type: SeedType | None = None, + parameters: Sequence[str] | None = None, + metadata: dict[str, str | int] | None = None, + prompt_group_ids: Sequence[uuid.UUID] | None = None, + ) -> int: + """ + Use ``remove_seeds_from_memory_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + int: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.remove_seeds_from_memory", + new_item="MemoryInterface.remove_seeds_from_memory_async", + removed_in="1.4.0", + ) + return self._execute_remove_seeds_from_memory( + value=value, + exact=exact, + value_sha256=value_sha256, + dataset_name=dataset_name, + dataset_name_pattern=dataset_name_pattern, + data_types=data_types, + harm_categories=harm_categories, + added_by=added_by, + authors=authors, + groups=groups, + source=source, + seed_type=seed_type, + parameters=parameters, + metadata=metadata, + prompt_group_ids=prompt_group_ids, + ) + + @legacy_sync_override(lambda: MemoryInterface.remove_seeds_from_memory) + async def remove_seeds_from_memory_async( + self, + *, + value: str | None = None, + exact: bool = True, + value_sha256: Sequence[str] | None = None, + dataset_name: str | None = None, + dataset_name_pattern: str | None = None, + data_types: Sequence[str] | None = None, + harm_categories: Sequence[str] | None = None, + added_by: str | None = None, + authors: Sequence[str] | None = None, + groups: Sequence[str] | None = None, + source: str | None = None, + seed_type: SeedType | None = None, + parameters: Sequence[str] | None = None, + metadata: dict[str, str | int] | None = None, + prompt_group_ids: Sequence[uuid.UUID] | None = None, + ) -> int: + """ + Delete a list of seed prompts based on the specified filters. + + Accepts the same filtering parameters as get_seeds (plus an exact flag). It is recommended to + call get_seeds with the same filters first to preview which seeds will be removed. At least one + filter must be provided to prevent accidental deletion of all seeds. The deletion runs in a single + transaction, so it works consistently across SQLite and Azure SQL. + + Only database records are removed. For file-backed seeds (image_path, audio_path, video_path) the + serialized file on disk is left in place; delete those files separately if they are no longer needed. + + Args: + value (str): The value to match. For the remove methods this defaults to full-string equality + (exact=True) so a short or common value does not delete far more seeds than intended; pass + exact=False to match by substring instead. If None, all values are considered. + exact (bool): When True, ``value`` is matched by full-string equality rather than substring. + Has no effect unless ``value`` is provided. Defaults to True for the remove methods (the + safer choice for deletion). Note this differs from get_seeds, which always matches ``value`` + by substring. + value_sha256 (Sequence[str] | None): A list of SHA256 hashes of values to match. + If None, all values are considered. + dataset_name (str): The dataset name to match exactly. If None, all dataset names are considered. + dataset_name_pattern (str): A pattern to match dataset names using SQL LIKE syntax. + Supports wildcards: % (any characters) and _ (single character). + Examples: "harm%" matches names starting with "harm", "%test%" matches names containing "test". + If both dataset_name and dataset_name_pattern are provided, dataset_name takes precedence. + data_types (Sequence[str] | None): List of data types to filter seed prompts by + (e.g., text, image_path). + harm_categories (Sequence[str]): A list of harm categories to filter by. If None, + all harm categories are considered. + Specifying multiple harm categories matches only prompts that are marked with all harm categories. + added_by (str): The user who added the prompts. + authors (Sequence[str]): A list of authors to filter by. + Note that this filters by substring, so a query for "Adam Jones" may not return results if the record + is "A. Jones", "Jones, Adam", etc. If None, all authors are considered. + groups (Sequence[str]): A list of groups to filter by. If None, all groups are considered. + source (str): The source to filter by. If None, all sources are considered. + seed_type (SeedType): The type of seed to filter by ("prompt", "objective", or + "simulated_conversation"). + parameters (Sequence[str]): A list of parameters to filter by. Specifying parameters effectively targets + prompt templates instead of prompts. + metadata (dict[str, str | int]): A free-form dictionary for tagging prompts with custom metadata. + prompt_group_ids (Sequence[uuid.UUID]): A list of prompt group IDs to filter by. + + Returns: + int: The number of seeds removed. + + Raises: + ValueError: If no filters are provided. + SQLAlchemyError: If the database deletion fails (the transaction is rolled back). + """ + return await self._run_database_operation_async( + self._execute_remove_seeds_from_memory, + value=value, + exact=exact, + value_sha256=value_sha256, + dataset_name=dataset_name, + dataset_name_pattern=dataset_name_pattern, + data_types=data_types, + harm_categories=harm_categories, + added_by=added_by, + authors=authors, + groups=groups, + source=source, + seed_type=seed_type, + parameters=parameters, + metadata=metadata, + prompt_group_ids=prompt_group_ids, + ) + + def remove_seed_groups_from_memory( + self, + *, + value: str | None = None, + exact: bool = True, + value_sha256: Sequence[str] | None = None, + dataset_name: str | None = None, + dataset_name_pattern: str | None = None, + data_types: Sequence[str] | None = None, + harm_categories: Sequence[str] | None = None, + added_by: str | None = None, + authors: Sequence[str] | None = None, + groups: Sequence[str] | None = None, + source: str | None = None, + seed_type: SeedType | None = None, + parameters: Sequence[str] | None = None, + metadata: dict[str, str | int] | None = None, + prompt_group_ids: Sequence[uuid.UUID] | None = None, + ) -> int: + """ + Use ``remove_seed_groups_from_memory_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + int: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.remove_seed_groups_from_memory", + new_item="MemoryInterface.remove_seed_groups_from_memory_async", + removed_in="1.4.0", + ) + return self._execute_remove_seed_groups_from_memory( + value=value, + exact=exact, + value_sha256=value_sha256, + dataset_name=dataset_name, + dataset_name_pattern=dataset_name_pattern, + data_types=data_types, + harm_categories=harm_categories, + added_by=added_by, + authors=authors, + groups=groups, + source=source, + seed_type=seed_type, + parameters=parameters, + metadata=metadata, + prompt_group_ids=prompt_group_ids, + ) + + @legacy_sync_override(lambda: MemoryInterface.remove_seed_groups_from_memory) + async def remove_seed_groups_from_memory_async( + self, + *, + value: str | None = None, + exact: bool = True, + value_sha256: Sequence[str] | None = None, + dataset_name: str | None = None, + dataset_name_pattern: str | None = None, + data_types: Sequence[str] | None = None, + harm_categories: Sequence[str] | None = None, + added_by: str | None = None, + authors: Sequence[str] | None = None, + groups: Sequence[str] | None = None, + source: str | None = None, + seed_type: SeedType | None = None, + parameters: Sequence[str] | None = None, + metadata: dict[str, str | int] | None = None, + prompt_group_ids: Sequence[uuid.UUID] | None = None, + ) -> int: + """ + Delete groups of seed prompts based on the provided filtering criteria. + + Unlike remove_seeds_from_memory, which deletes only the individual seeds that match, this + removes every seed that shares a prompt_group_id with any matching seed. This preserves group + integrity: filtering by a single modality (e.g. data_types=["image_path"]) or attribute removes + the whole group rather than leaving a partial group behind. It accepts the same filtering + parameters as get_seeds (plus an exact flag). It is recommended to call get_seed_groups with the + same filters first to preview which groups will be removed. At least one filter must be provided + to prevent accidental deletion of all seeds. The deletion runs in a single transaction, so it + works consistently across SQLite and Azure SQL. + + Only seeds that belong to a group are affected: a matching seed with no prompt_group_id (for example, + one added individually via add_seeds_to_memory_async rather than as part of a group) is skipped, since + it has no group to expand. Use remove_seeds_from_memory to delete ungrouped seeds. + + Only database records are removed. For file-backed seeds (image_path, audio_path, video_path) the + serialized file on disk is left in place; delete those files separately if they are no longer needed. + + Args: + value (str): The value to match. For the remove methods this defaults to full-string equality + (exact=True) so a short or common value does not delete far more seeds than intended; pass + exact=False to match by substring instead. If None, all values are considered. + exact (bool): When True, ``value`` is matched by full-string equality rather than substring. + Has no effect unless ``value`` is provided. Defaults to True for the remove methods (the + safer choice for deletion). Note this differs from get_seeds, which always matches ``value`` + by substring. + value_sha256 (Sequence[str] | None): A list of SHA256 hashes of values to match. + If None, all values are considered. + dataset_name (str): The dataset name to match exactly. If None, all dataset names are considered. + dataset_name_pattern (str): A pattern to match dataset names using SQL LIKE syntax. + Supports wildcards: % (any characters) and _ (single character). + Examples: "harm%" matches names starting with "harm", "%test%" matches names containing "test". + If both dataset_name and dataset_name_pattern are provided, dataset_name takes precedence. + data_types (Sequence[str] | None): List of data types to filter seed prompts by + (e.g., text, image_path). + harm_categories (Sequence[str]): A list of harm categories to filter by. If None, + all harm categories are considered. + Specifying multiple harm categories matches only prompts that are marked with all harm categories. + added_by (str): The user who added the prompts. + authors (Sequence[str]): A list of authors to filter by. + Note that this filters by substring, so a query for "Adam Jones" may not return results if the record + is "A. Jones", "Jones, Adam", etc. If None, all authors are considered. + groups (Sequence[str]): A list of groups to filter by. If None, all groups are considered. + source (str): The source to filter by. If None, all sources are considered. + seed_type (SeedType): The type of seed to filter by ("prompt", "objective", or + "simulated_conversation"). + parameters (Sequence[str]): A list of parameters to filter by. Specifying parameters effectively targets + prompt templates instead of prompts. + metadata (dict[str, str | int]): A free-form dictionary for tagging prompts with custom metadata. + prompt_group_ids (Sequence[uuid.UUID]): A list of prompt group IDs to filter by. + + Returns: + int: The number of seeds removed across all affected groups. + + Raises: + ValueError: If no filters are provided. + SQLAlchemyError: If the database deletion fails (the transaction is rolled back). + """ + return await self._run_database_operation_async( + self._execute_remove_seed_groups_from_memory, + value=value, + exact=exact, + value_sha256=value_sha256, + dataset_name=dataset_name, + dataset_name_pattern=dataset_name_pattern, + data_types=data_types, + harm_categories=harm_categories, + added_by=added_by, + authors=authors, + groups=groups, + source=source, + seed_type=seed_type, + parameters=parameters, + metadata=metadata, + prompt_group_ids=prompt_group_ids, + ) + + def get_seed_dataset_summaries(self) -> Sequence[SeedDatasetSummary]: + """ + Use ``get_seed_dataset_summaries_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[SeedDatasetSummary]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_seed_dataset_summaries", + new_item="MemoryInterface.get_seed_dataset_summaries_async", + removed_in="1.4.0", + ) + return self._execute_get_seed_dataset_summaries() + + @legacy_sync_override(lambda: MemoryInterface.get_seed_dataset_summaries) + async def get_seed_dataset_summaries_async(self) -> Sequence[SeedDatasetSummary]: + """ + Return aggregate metadata for datasets already loaded in memory. + + The queries intentionally project only dataset metadata and counts. Seed values and + media are never hydrated, so callers can build dataset cards without materializing + every prompt or fetching providers. + + Named dataset grouping and metadata matching stay on the original collated + dataset_name column. NULL and empty names are aggregated separately into the + unnamed population so their shared logical groups are counted exactly once. + + Returns: + Sequence[SeedDatasetSummary]: One summary for each stored dataset, including + a single deterministic entry for seeds without a dataset name. + """ + return await self._run_database_operation_async(self._execute_get_seed_dataset_summaries) + + def get_seed_dataset_names(self) -> Sequence[str]: + """ + Use ``get_seed_dataset_names_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[str]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_seed_dataset_names", + new_item="MemoryInterface.get_seed_dataset_names_async", + removed_in="1.4.0", + ) + return self._execute_get_seed_dataset_names() + + @legacy_sync_override(lambda: MemoryInterface.get_seed_dataset_names) + async def get_seed_dataset_names_async(self) -> Sequence[str]: + """ + Return a list of all seed dataset names in the memory storage. + + Returns: + Sequence[str]: A list of unique dataset names. + """ + return await self._run_database_operation_async(self._execute_get_seed_dataset_names) + + def get_seed_groups( + self, + *, + value: str | None = None, + value_sha256: Sequence[str] | None = None, + dataset_name: str | None = None, + dataset_name_pattern: str | None = None, + data_types: Sequence[str] | None = None, + harm_categories: Sequence[str] | None = None, + added_by: str | None = None, + authors: Sequence[str] | None = None, + groups: Sequence[str] | None = None, + source: str | None = None, + seed_type: SeedType | None = None, + parameters: Sequence[str] | None = None, + metadata: dict[str, str | int] | None = None, + prompt_group_ids: Sequence[uuid.UUID] | None = None, + group_length: Sequence[int] | None = None, + ) -> Sequence[SeedGroup]: + """ + Use ``get_seed_groups_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[SeedGroup]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_seed_groups", + new_item="MemoryInterface.get_seed_groups_async", + removed_in="1.4.0", + ) + return self._execute_get_seed_groups( + value=value, + value_sha256=value_sha256, + dataset_name=dataset_name, + dataset_name_pattern=dataset_name_pattern, + data_types=data_types, + harm_categories=harm_categories, + added_by=added_by, + authors=authors, + groups=groups, + source=source, + seed_type=seed_type, + parameters=parameters, + metadata=metadata, + prompt_group_ids=prompt_group_ids, + group_length=group_length, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_seed_groups) + async def get_seed_groups_async( + self, + *, + value: str | None = None, + value_sha256: Sequence[str] | None = None, + dataset_name: str | None = None, + dataset_name_pattern: str | None = None, + data_types: Sequence[str] | None = None, + harm_categories: Sequence[str] | None = None, + added_by: str | None = None, + authors: Sequence[str] | None = None, + groups: Sequence[str] | None = None, + source: str | None = None, + seed_type: SeedType | None = None, + parameters: Sequence[str] | None = None, + metadata: dict[str, str | int] | None = None, + prompt_group_ids: Sequence[uuid.UUID] | None = None, + group_length: Sequence[int] | None = None, + ) -> Sequence[SeedGroup]: + """ + Retrieve groups of seed prompts based on the provided filtering criteria. + + Args: + value (str | None, Optional): The value to match by substring. + value_sha256 (Sequence[str] | None, Optional): SHA256 hash of value to filter seed groups by. + dataset_name (str | None, Optional): Name of the dataset to match exactly. + dataset_name_pattern (str | None, Optional): A pattern to match dataset names using SQL LIKE syntax. + Supports wildcards: % (any characters) and _ (single character). + Examples: "harm%" matches names starting with "harm", "%test%" matches names containing "test". + If both dataset_name and dataset_name_pattern are provided, dataset_name takes precedence. + data_types (Sequence[str] | None, Optional): List of data types to filter seed prompts by + (e.g., text, image_path). + harm_categories (Sequence[str] | None, Optional): List of harm categories to filter seed prompts by. + added_by (str | None, Optional): The user who added the seed groups to filter by. + authors (Sequence[str] | None, Optional): List of authors to filter seed groups by. + groups (Sequence[str] | None, Optional): List of groups to filter seed groups by. + source (str | None, Optional): The source from which the seed prompts originated. + seed_type (SeedType | None, Optional): The type of seed to filter by ("prompt", "objective", or + "simulated_conversation"). + parameters (Sequence[str] | None, Optional): List of parameters to filter by. + metadata (dict[str, str | int] | None, Optional): A free-form dictionary for tagging + prompts with custom metadata. + prompt_group_ids (Sequence[uuid.UUID] | None, Optional): List of prompt group IDs to filter by. + group_length (Sequence[int] | None, Optional): The number of seeds in the group to filter by. + + Returns: + Sequence[SeedGroup]: A list of `SeedGroup` objects that match the filtering criteria. + """ + return await self._run_database_operation_async( + self._execute_get_seed_groups, + value=value, + value_sha256=value_sha256, + dataset_name=dataset_name, + dataset_name_pattern=dataset_name_pattern, + data_types=data_types, + harm_categories=harm_categories, + added_by=added_by, + authors=authors, + groups=groups, + source=source, + seed_type=seed_type, + parameters=parameters, + metadata=metadata, + prompt_group_ids=prompt_group_ids, + group_length=group_length, + ) + + def add_attack_results_to_memory(self, *, attack_results: Sequence[AttackResult]) -> None: + """ + Use ``add_attack_results_to_memory_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.add_attack_results_to_memory", + new_item="MemoryInterface.add_attack_results_to_memory_async", + removed_in="1.4.0", + ) + return self._execute_add_attack_results_to_memory(attack_results=attack_results) + + @legacy_sync_override(lambda: MemoryInterface.add_attack_results_to_memory) + async def add_attack_results_to_memory_async(self, *, attack_results: Sequence[AttackResult]) -> None: + """ + 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. + """ + return await self._run_database_operation_async( + self._execute_add_attack_results_to_memory, attack_results=attack_results + ) + + def add_conversation_branches_to_attack( + self, + *, + attack_result_id: str, + conversations: Sequence[Conversation], + message_pieces: Sequence[MessagePiece], + source_conversation: Conversation | None = None, + ) -> bool: + """ + Use ``add_conversation_branches_to_attack_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + bool: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.add_conversation_branches_to_attack", + new_item="MemoryInterface.add_conversation_branches_to_attack_async", + removed_in="1.4.0", + ) + return self._execute_add_conversation_branches_to_attack( + attack_result_id=attack_result_id, + conversations=conversations, + message_pieces=message_pieces, + source_conversation=source_conversation, + ) + + @legacy_sync_override(lambda: MemoryInterface.add_conversation_branches_to_attack) + async def add_conversation_branches_to_attack_async( + self, + *, + attack_result_id: str, + conversations: Sequence[Conversation], + message_pieces: Sequence[MessagePiece], + source_conversation: Conversation | None = None, + ) -> bool: + """ + Atomically store prepared conversations, copied pieces, and their attack references. + + The caller prepares the copies. This method only persists them, preserving the usual + conversation and message insertion invariants. A supplied source must still be an + active objective conversation when the transaction acquires the attack's write lock. + + Returns: + bool: False when the attack no longer exists. + + Raises: + ValueError: If the source is unrelated, branch IDs repeat, or pieces belong elsewhere. + SQLAlchemyError: If persistence fails; the complete preparation is rolled back. + """ + return await self._run_database_operation_async( + self._execute_add_conversation_branches_to_attack, + attack_result_id=attack_result_id, + conversations=conversations, + message_pieces=message_pieces, + source_conversation=source_conversation, + ) + + def promote_attack_conversation(self, *, attack_result_id: str, conversation_id: str) -> bool: + """ + Use ``promote_attack_conversation_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + bool: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.promote_attack_conversation", + new_item="MemoryInterface.promote_attack_conversation_async", + removed_in="1.4.0", + ) + return self._execute_promote_attack_conversation( + attack_result_id=attack_result_id, conversation_id=conversation_id + ) + + @legacy_sync_override(lambda: MemoryInterface.promote_attack_conversation) + async def promote_attack_conversation_async(self, *, attack_result_id: str, conversation_id: str) -> bool: + """ + Promote an existing related conversation without losing concurrent branch additions. + + Returns: + bool: False when the attack no longer exists. + + Raises: + ValueError: If the requested conversation is not part of this attack. + SQLAlchemyError: If the transaction fails. + """ + return await self._run_database_operation_async( + self._execute_promote_attack_conversation, + attack_result_id=attack_result_id, + conversation_id=conversation_id, + ) + + def update_attack_result(self, *, conversation_id: str, update_fields: dict[str, Any]) -> bool: + """ + Use ``update_attack_result_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + bool: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.update_attack_result", + new_item="MemoryInterface.update_attack_result_async", + removed_in="1.4.0", + ) + return self._execute_update_attack_result(conversation_id=conversation_id, update_fields=update_fields) + + @legacy_sync_override(lambda: MemoryInterface.update_attack_result) + async def update_attack_result_async(self, *, conversation_id: str, update_fields: dict[str, Any]) -> bool: + """ + 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. + """ + return await self._run_database_operation_async( + self._execute_update_attack_result, conversation_id=conversation_id, update_fields=update_fields + ) + + def update_attack_result_by_id(self, *, attack_result_id: str, update_fields: dict[str, Any]) -> bool: + """ + Use ``update_attack_result_by_id_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + bool: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.update_attack_result_by_id", + new_item="MemoryInterface.update_attack_result_by_id_async", + removed_in="1.4.0", + ) + return self._execute_update_attack_result_by_id(attack_result_id=attack_result_id, update_fields=update_fields) + + @legacy_sync_override(lambda: MemoryInterface.update_attack_result_by_id) + async def update_attack_result_by_id_async(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. + """ + return await self._run_database_operation_async( + self._execute_update_attack_result_by_id, attack_result_id=attack_result_id, update_fields=update_fields + ) + + def get_attack_results( + self, + *, + attack_result_ids: Sequence[str] | None = None, + conversation_id: str | None = None, + objective: str | None = None, + objective_sha256: Sequence[str] | None = None, + outcome: str | None = None, + attack_classes: Sequence[str] | None = None, + atomic_attack_eval_hashes: Sequence[str] | None = None, + converter_classes: Sequence[str] | None = None, + converter_classes_match: Literal["all", "any"] = "all", + has_converters: bool | None = None, + include_scenario_attacks: bool = True, + labels: Mapping[str, str | Sequence[str]] | None = None, + operator: str | Sequence[str] | None = None, + operation: str | Sequence[str] | None = None, + targeted_harm_categories: Sequence[str] | None = None, + identifier_filters: Sequence[IdentifierFilter] | None = None, + scenario_result_id: str | None = None, + min_turns: int | None = None, + max_turns: int | None = None, + limit: int | None = None, + after: AttackResultKeysetCursor | None = None, + ) -> Sequence[AttackResult]: + """ + Use ``get_attack_results_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[AttackResult]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_attack_results", + new_item="MemoryInterface.get_attack_results_async", + removed_in="1.4.0", + ) + return self._execute_get_attack_results( + attack_result_ids=attack_result_ids, + conversation_id=conversation_id, + objective=objective, + objective_sha256=objective_sha256, + outcome=outcome, + attack_classes=attack_classes, + atomic_attack_eval_hashes=atomic_attack_eval_hashes, + converter_classes=converter_classes, + converter_classes_match=converter_classes_match, + has_converters=has_converters, + include_scenario_attacks=include_scenario_attacks, + labels=labels, + operator=operator, + operation=operation, + targeted_harm_categories=targeted_harm_categories, + identifier_filters=identifier_filters, + scenario_result_id=scenario_result_id, + min_turns=min_turns, + max_turns=max_turns, + limit=limit, + after=after, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_attack_results) + async def get_attack_results_async( + self, + *, + attack_result_ids: Sequence[str] | None = None, + conversation_id: str | None = None, + objective: str | None = None, + objective_sha256: Sequence[str] | None = None, + outcome: str | None = None, + attack_classes: Sequence[str] | None = None, + atomic_attack_eval_hashes: Sequence[str] | None = None, + converter_classes: Sequence[str] | None = None, + converter_classes_match: Literal["all", "any"] = "all", + has_converters: bool | None = None, + include_scenario_attacks: bool = True, + labels: Mapping[str, str | Sequence[str]] | None = None, + operator: str | Sequence[str] | None = None, + operation: str | Sequence[str] | None = None, + targeted_harm_categories: Sequence[str] | None = None, + identifier_filters: Sequence[IdentifierFilter] | None = None, + scenario_result_id: str | None = None, + min_turns: int | None = None, + max_turns: int | None = None, + limit: int | None = None, + after: AttackResultKeysetCursor | None = None, + ) -> Sequence[AttackResult]: + """ + Retrieve a list of AttackResult objects based on the specified filters. + + Args: + attack_result_ids (Sequence[str] | None, optional): A list of attack result IDs. Defaults to None. + conversation_id (str | None, optional): The conversation ID to filter by. Defaults to None. + objective (str | None, optional): The objective to filter by (substring match). Defaults to None. + objective_sha256 (Sequence[str] | None, optional): A list of objective SHA256 hashes to filter by. + Defaults to None. + outcome (str | None, optional): The outcome to filter by (success, failure, undetermined). + Defaults to None. + attack_classes (Sequence[str] | None, optional): Filter by exact attack class_name in + atomic_attack_identifier. Returns attacks matching ANY of the listed class names + (OR logic, case-sensitive). An empty sequence applies no filter. Defaults to None. + atomic_attack_eval_hashes (Sequence[str] | None, optional): Filter by behavioral + equivalence hash on ``atomic_attack_identifier.eval_hash`` (auto-stamped on persistence + by ``AtomicAttackEvaluationIdentifier``). Returns results matching ANY of the listed + hashes (OR logic, case-sensitive). Designed for ASR aggregation by technique + configuration. An empty sequence applies no filter. Defaults to None. + converter_classes (Sequence[str] | None, optional): Filter by converter class names. + Combination semantics for multiple entries are controlled by ``converter_classes_match``. + An empty sequence filters to attacks that used no converters; ``None`` applies no + filter. To filter by presence/absence of any converter explicitly, use the + ``has_converters`` parameter instead. Defaults to None. + converter_classes_match (Literal["all", "any"]): How to combine multiple entries in + ``converter_classes``. ``"all"`` (default) matches attacks that used every listed + converter (AND, case-insensitive). ``"any"`` matches attacks that used at least one + listed converter (OR, case-insensitive). Ignored when ``converter_classes`` has + fewer than 2 entries or is empty. + has_converters (bool | None, optional): Filter by converter presence. + ``True`` returns only attacks that used at least one converter. ``False`` returns + only attacks that used no converters. ``None`` applies no filter. Defaults to None. + include_scenario_attacks (bool, optional): Whether to include attacks created as part + of scenario runs. Defaults to ``True``. + labels (Mapping[str, str | Sequence[str]] | None, optional): Filter results + by arbitrary attack labels. The legacy ``operator`` and ``operation`` aliases + are accepted through PyRIT 1.3 and normalized to dedicated filters. Entries + are AND-combined across label names; within a + single entry, a string value is an equality match and a sequence value is + an OR match over the listed values. An empty sequence applies no filter + for that label. Defaults to None. + operator (str | Sequence[str] | None, optional): Filter by dedicated operator values. + operation (str | Sequence[str] | None, optional): Filter by dedicated operation values. + targeted_harm_categories (Sequence[str] | None, optional): Filter results by the + harm categories targeted by the attack (stored on + ``AttackResultEntry.targeted_harm_categories``, auto-populated from the + attack's SeedGroup). Returns attacks targeting ANY of the listed categories + (OR logic, case-insensitive). An empty sequence applies no filter. Defaults + to None. + identifier_filters (Sequence[IdentifierFilter] | None, optional): + A sequence of IdentifierFilter objects that allows filtering by various attack identifier + JSON properties. Defaults to None. + scenario_result_id (str | None, optional): Filter to attack results linked to a + specific scenario via the ``AttackResultEntry.attribution_parent_id`` foreign key. + Combined with ``outcome=AttackOutcome.ERROR`` this is the replacement for the + removed per-scenario error_attack_result_ids manifest. Defaults to None. + min_turns (int | None, optional): If set, only return attacks whose + ``executed_turns`` is greater than or equal to this value. Applied after + per-conversation deduplication (i.e. to the surviving newest row per + conversation), so it never resurfaces an older duplicate. Defaults to None. + max_turns (int | None, optional): If set, only return attacks whose + ``executed_turns`` is less than or equal to this value. Applied after + deduplication, mirroring ``min_turns``. Defaults to None. + limit (int | None, optional): Maximum number of deduplicated attack results to + return, ordered by recency. When either ``limit`` or ``after`` is provided, + deduplication and pagination happen in the database (via a ``NOT EXISTS`` anti-join) + instead of loading every row into memory. Defaults to None (return all). + after (AttackResultKeysetCursor | None, optional): Keyset (seek) anchor from a + previous page. When provided, only results ordered strictly after the anchor + under the recency sort are returned, giving insert/delete-stable pagination + without a drifting numeric offset. Defaults to None (start at the first page). + + Returns: + Sequence[AttackResult]: A list of AttackResult objects that match the specified filters. + + Raises: + ValueError: If any label key contains characters outside the allowlist + ``[A-Za-z0-9_.-]+``. + ValueError: If ``limit`` or ``after`` is combined with ``attack_result_ids`` or + ``objective_sha256`` (id-batched lookups do not support SQL pagination). + """ + return await self._run_database_operation_async( + self._execute_get_attack_results, + attack_result_ids=attack_result_ids, + conversation_id=conversation_id, + objective=objective, + objective_sha256=objective_sha256, + outcome=outcome, + attack_classes=attack_classes, + atomic_attack_eval_hashes=atomic_attack_eval_hashes, + converter_classes=converter_classes, + converter_classes_match=converter_classes_match, + has_converters=has_converters, + include_scenario_attacks=include_scenario_attacks, + labels=labels, + operator=operator, + operation=operation, + targeted_harm_categories=targeted_harm_categories, + identifier_filters=identifier_filters, + scenario_result_id=scenario_result_id, + min_turns=min_turns, + max_turns=max_turns, + limit=limit, + after=after, + ) + + def get_unique_attack_labels( + self, + *, + operator: Sequence[str] | None = None, + operation: Sequence[str] | None = None, + labels: Mapping[str, str | Sequence[str]] | None = None, + ) -> dict[str, list[str]]: + """ + Use ``get_unique_attack_labels_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + dict[str, list[str]]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_unique_attack_labels", + new_item="MemoryInterface.get_unique_attack_labels_async", + removed_in="1.4.0", + ) + return self._execute_get_unique_attack_labels(operator=operator, operation=operation, labels=labels) + + @legacy_sync_override(lambda: MemoryInterface.get_unique_attack_labels) + async def get_unique_attack_labels_async( + self, + *, + operator: Sequence[str] | None = None, + operation: Sequence[str] | None = None, + labels: Mapping[str, str | Sequence[str]] | None = None, + ) -> dict[str, list[str]]: + """ + Return unique arbitrary labels, optionally narrowed by indexed attribution first. + + Args: + operator (Sequence[str] | None): Operator values used to narrow rows. + operation (Sequence[str] | None): Operation values used to narrow rows. + labels (Mapping[str, str | Sequence[str]] | None): Arbitrary label filters used + to narrow rows. + + Returns: + dict[str, list[str]]: Mapping of label keys to sorted lists of + unique values. + """ + return await self._run_database_operation_async( + self._execute_get_unique_attack_labels, operator=operator, operation=operation, labels=labels + ) + + def get_unique_attack_attribution(self) -> dict[str, list[str]]: + """ + Use ``get_unique_attack_attribution_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + dict[str, list[str]]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_unique_attack_attribution", + new_item="MemoryInterface.get_unique_attack_attribution_async", + removed_in="1.4.0", + ) + return self._execute_get_unique_attack_attribution() + + @legacy_sync_override(lambda: MemoryInterface.get_unique_attack_attribution) + async def get_unique_attack_attribution_async(self) -> dict[str, list[str]]: + """Return unique dedicated operator and operation values from indexed columns.""" + return await self._run_database_operation_async(self._execute_get_unique_attack_attribution) + + def add_scenario_results_to_memory(self, *, scenario_results: Sequence[ScenarioResult]) -> None: + """ + Use ``add_scenario_results_to_memory_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.add_scenario_results_to_memory", + new_item="MemoryInterface.add_scenario_results_to_memory_async", + removed_in="1.4.0", + ) + return self._execute_add_scenario_results_to_memory(scenario_results=scenario_results) + + @legacy_sync_override(lambda: MemoryInterface.add_scenario_results_to_memory) + async def add_scenario_results_to_memory_async(self, *, scenario_results: Sequence[ScenarioResult]) -> None: + """ + Insert a list of scenario results into the memory storage. + + Args: + scenario_results: Sequence of ScenarioResult objects to store in the database. + + Raises: + SQLAlchemyError: If a scenario result or identifier graph cannot be persisted. + """ + return await self._run_database_operation_async( + self._execute_add_scenario_results_to_memory, scenario_results=scenario_results + ) + + def update_scenario_run_state( + self, + *, + scenario_result_id: str, + scenario_run_state: ScenarioRunState, + error_message: str | None = None, + error_type: str | None = None, + ) -> None: + """ + Use ``update_scenario_run_state_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.update_scenario_run_state", + new_item="MemoryInterface.update_scenario_run_state_async", + removed_in="1.4.0", + ) + return self._execute_update_scenario_run_state( + scenario_result_id=scenario_result_id, + scenario_run_state=scenario_run_state, + error_message=error_message, + error_type=error_type, + ) + + @legacy_sync_override(lambda: MemoryInterface.update_scenario_run_state) + async def update_scenario_run_state_async( + self, + *, + scenario_result_id: str, + scenario_run_state: ScenarioRunState, + error_message: str | None = None, + error_type: str | None = None, + ) -> None: + """ + Update the run state of an existing scenario result. + + Performs a targeted UPDATE of only the state/error columns instead of + rebuilding the entire ``ScenarioResultEntry`` row. + + Args: + scenario_result_id (str): The ID of the scenario result to update. + scenario_run_state (ScenarioRunState): The new state for the scenario. + error_message (str | None): Optional scenario-level error message. + error_type (str | None): Optional exception class name. + + Raises: + ValueError: If the scenario result is not found. + """ + return await self._run_database_operation_async( + self._execute_update_scenario_run_state, + scenario_result_id=scenario_result_id, + scenario_run_state=scenario_run_state, + error_message=error_message, + error_type=error_type, + ) + + def update_scenario_run_state_and_metadata_fields( + self, + *, + scenario_result_id: str, + scenario_run_state: ScenarioRunState, + metadata_fields: Mapping[str, Any], + error_message: str | None = None, + error_type: str | None = None, + ) -> None: + """ + Use ``update_scenario_run_state_and_metadata_fields_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.update_scenario_run_state_and_metadata_fields", + new_item="MemoryInterface.update_scenario_run_state_and_metadata_fields_async", + removed_in="1.4.0", + ) + return self._execute_update_scenario_run_state_and_metadata_fields( + scenario_result_id=scenario_result_id, + scenario_run_state=scenario_run_state, + metadata_fields=metadata_fields, + error_message=error_message, + error_type=error_type, + ) + + @legacy_sync_override(lambda: MemoryInterface.update_scenario_run_state_and_metadata_fields) + async def update_scenario_run_state_and_metadata_fields_async( + self, + *, + scenario_result_id: str, + scenario_run_state: ScenarioRunState, + metadata_fields: Mapping[str, Any], + error_message: str | None = None, + error_type: str | None = None, + ) -> None: + """ + Update run state and merge scenario metadata in one transaction. + + Raises: + ValueError: If the scenario result is not found. + """ + return await self._run_database_operation_async( + self._execute_update_scenario_run_state_and_metadata_fields, + scenario_result_id=scenario_result_id, + scenario_run_state=scenario_run_state, + metadata_fields=metadata_fields, + error_message=error_message, + error_type=error_type, + ) + + def try_update_scenario_run_state( + self, + *, + scenario_result_id: str, + expected_states: Collection[ScenarioRunState], + scenario_run_state: ScenarioRunState, + error_message: str | None = None, + error_type: str | None = None, + ) -> bool: + """ + Use ``try_update_scenario_run_state_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + bool: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.try_update_scenario_run_state", + new_item="MemoryInterface.try_update_scenario_run_state_async", + removed_in="1.4.0", + ) + return self._execute_try_update_scenario_run_state( + scenario_result_id=scenario_result_id, + expected_states=expected_states, + scenario_run_state=scenario_run_state, + error_message=error_message, + error_type=error_type, + ) + + @legacy_sync_override(lambda: MemoryInterface.try_update_scenario_run_state) + async def try_update_scenario_run_state_async( + self, + *, + scenario_result_id: str, + expected_states: Collection[ScenarioRunState], + scenario_run_state: ScenarioRunState, + error_message: str | None = None, + error_type: str | None = None, + ) -> bool: + """ + Update the run state only when the stored state is one of ``expected_states``. + + The compare and the write are a single UPDATE so a run that reached a terminal state + on another thread is not overwritten. A read followed by + ``update_scenario_run_state`` cannot give that guarantee because scenario + preparation and cancellation run on different threads. + + Args: + scenario_result_id (str): The ID of the scenario result to update. + expected_states (Collection[ScenarioRunState]): States the row may currently be in. + scenario_run_state (ScenarioRunState): The new state for the scenario. + error_message (str | None): Optional scenario-level error message. + error_type (str | None): Optional exception class name. + + Returns: + bool: True if the row was updated, False if it was missing or in another state. + + Raises: + ValueError: If ``expected_states`` is empty. + """ + return await self._run_database_operation_async( + self._execute_try_update_scenario_run_state, + scenario_result_id=scenario_result_id, + expected_states=expected_states, + scenario_run_state=scenario_run_state, + error_message=error_message, + error_type=error_type, + ) + + def update_scenario_metadata(self, *, scenario_result_id: str, metadata: dict[str, Any]) -> None: + """ + Use ``update_scenario_metadata_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.update_scenario_metadata", + new_item="MemoryInterface.update_scenario_metadata_async", + removed_in="1.4.0", + ) + return self._execute_update_scenario_metadata(scenario_result_id=scenario_result_id, metadata=metadata) + + @legacy_sync_override(lambda: MemoryInterface.update_scenario_metadata) + async def update_scenario_metadata_async(self, *, scenario_result_id: str, metadata: dict[str, Any]) -> None: + """ + Replace the ``scenario_metadata`` JSON blob on an existing scenario result. + + Used by the scenario layer to persist first-run state (e.g. + ``objective_hashes``) that resume needs to replay. Performs a + targeted UPDATE so it doesn't clobber other columns. + + Args: + scenario_result_id (str): The ID of the scenario result to update. + metadata (dict[str, Any]): The full metadata dict to store. Pass the + merged dict, not just the new keys — this writes the whole value. + + Raises: + ValueError: If the scenario result is not found. + """ + return await self._run_database_operation_async( + self._execute_update_scenario_metadata, scenario_result_id=scenario_result_id, metadata=metadata + ) + + def update_scenario_metadata_fields(self, *, scenario_result_id: str, fields: Mapping[str, Any]) -> None: + """ + Use ``update_scenario_metadata_fields_async``. + + This synchronous API is deprecated and can block the caller. + """ + print_deprecation_message( + old_item="MemoryInterface.update_scenario_metadata_fields", + new_item="MemoryInterface.update_scenario_metadata_fields_async", + removed_in="1.4.0", + ) + return self._execute_update_scenario_metadata_fields(scenario_result_id=scenario_result_id, fields=fields) + + @legacy_sync_override(lambda: MemoryInterface.update_scenario_metadata_fields) + async def update_scenario_metadata_fields_async( + self, *, scenario_result_id: str, fields: Mapping[str, Any] + ) -> None: + """ + Merge selected fields into persisted scenario metadata in one transaction. + + Raises: + ValueError: If the scenario result is not found. + """ + return await self._run_database_operation_async( + self._execute_update_scenario_metadata_fields, scenario_result_id=scenario_result_id, fields=fields + ) + + def get_scenario_result_header(self, *, scenario_result_id: str) -> ScenarioResult | None: + """ + Use ``get_scenario_result_header_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + ScenarioResult | None: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scenario_result_header", + new_item="MemoryInterface.get_scenario_result_header_async", + removed_in="1.4.0", + ) + return self._execute_get_scenario_result_header(scenario_result_id=scenario_result_id) + + @legacy_sync_override(lambda: MemoryInterface.get_scenario_result_header) + async def get_scenario_result_header_async(self, *, scenario_result_id: str) -> ScenarioResult | None: + """Return one ScenarioResult header without hydrating linked attack results.""" + return await self._run_database_operation_async( + self._execute_get_scenario_result_header, scenario_result_id=scenario_result_id + ) + + def get_scenario_run_state_page( + self, *, states: Sequence[ScenarioRunState], after_id: str | None = None, limit: int = 500 + ) -> tuple[list[ScenarioRunStateRecord], bool]: + """ + Use ``get_scenario_run_state_page_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + tuple[list[ScenarioRunStateRecord], bool]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scenario_run_state_page", + new_item="MemoryInterface.get_scenario_run_state_page_async", + removed_in="1.4.0", + ) + return self._execute_get_scenario_run_state_page(states=states, after_id=after_id, limit=limit) + + @legacy_sync_override(lambda: MemoryInterface.get_scenario_run_state_page) + async def get_scenario_run_state_page_async( + self, *, states: Sequence[ScenarioRunState], after_id: str | None = None, limit: int = 500 + ) -> tuple[list[ScenarioRunStateRecord], bool]: + """ + Return one bounded ID/state page without hydrating ScenarioResults or AttackResults. + + Returns: + tuple[list[ScenarioRunStateRecord], bool]: State records and whether another page exists. + + Raises: + ValueError: If the limit or cursor ID is invalid. + """ + return await self._run_database_operation_async( + self._execute_get_scenario_run_state_page, states=states, after_id=after_id, limit=limit + ) + + def get_scenario_run_history_page( + self, + *, + scenario_names: Sequence[str] | None = None, + statuses: Sequence[str] | None = None, + labels: Mapping[str, str | Sequence[str]] | None = None, + cursor: ScenarioHistoryKeysetCursor | None = None, + limit: int = 100, + ) -> tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]: + """ + Use ``get_scenario_run_history_page_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scenario_run_history_page", + new_item="MemoryInterface.get_scenario_run_history_page_async", + removed_in="1.4.0", + ) + return self._execute_get_scenario_run_history_page( + scenario_names=scenario_names, statuses=statuses, labels=labels, cursor=cursor, limit=limit + ) + + @legacy_sync_override(lambda: MemoryInterface.get_scenario_run_history_page) + async def get_scenario_run_history_page_async( + self, + *, + scenario_names: Sequence[str] | None = None, + statuses: Sequence[str] | None = None, + labels: Mapping[str, str | Sequence[str]] | None = None, + cursor: ScenarioHistoryKeysetCursor | None = None, + limit: int = 100, + ) -> tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]: + """ + Return one descending scenario-history page and its database-side attempt metrics. + + Only selected ScenarioResult columns and the linked AttackResult columns + required for aggregate counts are read. Full ORM result objects and their + relationships are never hydrated, and attempt metrics are reduced to one + aggregate row per history row inside the database. + + Returns: + tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]: + Page headers, attempt aggregates keyed by scenario ID, and whether + another page exists. + + Raises: + ValueError: If the limit, cursor ID, or label keys are invalid. + """ + return await self._run_database_operation_async( + self._execute_get_scenario_run_history_page, + scenario_names=scenario_names, + statuses=statuses, + labels=labels, + cursor=cursor, + limit=limit, + ) + + def get_scenario_history_aggregates( + self, *, scenario_result_ids: Sequence[str], plan_scenario_ids: Sequence[str] = () + ) -> dict[str, ScenarioHistoryAggregate]: + """ + Use ``get_scenario_history_aggregates_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + dict[str, ScenarioHistoryAggregate]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scenario_history_aggregates", + new_item="MemoryInterface.get_scenario_history_aggregates_async", + removed_in="1.4.0", + ) + return self._execute_get_scenario_history_aggregates( + scenario_result_ids=scenario_result_ids, plan_scenario_ids=plan_scenario_ids + ) + + @legacy_sync_override(lambda: MemoryInterface.get_scenario_history_aggregates) + async def get_scenario_history_aggregates_async( + self, *, scenario_result_ids: Sequence[str], plan_scenario_ids: Sequence[str] = () + ) -> dict[str, ScenarioHistoryAggregate]: + """ + Return one attempt aggregate per requested scenario run. + + Persisted attempts are grouped into logical work units before being counted, so + retries and errored re-runs of the same objective collapse into a single unit. + For every scenario listed in ``plan_scenario_ids`` the persisted run plan resolves + those units: attempts are matched to their planned atomic group and seed group + (remapping objective-hash attribution onto the planned seed group ID), and attempts + that resolve to no planned unit are excluded from the counters. Scenarios outside + ``plan_scenario_ids`` keep the persisted attribution as the unit identity and count + every unit, which is the legacy behavior for runs without a usable plan. + + Args: + scenario_result_ids (Sequence[str]): Scenario run IDs to aggregate. + plan_scenario_ids (Sequence[str], optional): Subset of ``scenario_result_ids`` + whose persisted run plan should resolve and filter units. Defaults to (). + + Returns: + dict[str, ScenarioHistoryAggregate]: One aggregate per requested scenario ID. + """ + return await self._run_database_operation_async( + self._execute_get_scenario_history_aggregates, + scenario_result_ids=scenario_result_ids, + plan_scenario_ids=plan_scenario_ids, + ) + + def get_unique_scenario_labels(self) -> dict[str, list[str]]: + """ + Use ``get_unique_scenario_labels_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + dict[str, list[str]]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_unique_scenario_labels", + new_item="MemoryInterface.get_unique_scenario_labels_async", + removed_in="1.4.0", + ) + return self._execute_get_unique_scenario_labels() + + @legacy_sync_override(lambda: MemoryInterface.get_unique_scenario_labels) + async def get_unique_scenario_labels_async(self) -> dict[str, list[str]]: + """Return all unique label values across scenario results.""" + return await self._run_database_operation_async(self._execute_get_unique_scenario_labels) + + def get_scenario_attack_result_deltas( + self, *, scenario_result_id: str, cursor: AttackResultKeysetCursor | None = None, limit: int = 100 + ) -> tuple[list[ScenarioAttackResultDelta], bool]: + """ + Use ``get_scenario_attack_result_deltas_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + tuple[list[ScenarioAttackResultDelta], bool]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scenario_attack_result_deltas", + new_item="MemoryInterface.get_scenario_attack_result_deltas_async", + removed_in="1.4.0", + ) + return self._execute_get_scenario_attack_result_deltas( + scenario_result_id=scenario_result_id, cursor=cursor, limit=limit + ) + + @legacy_sync_override(lambda: MemoryInterface.get_scenario_attack_result_deltas) + async def get_scenario_attack_result_deltas_async( + self, *, scenario_result_id: str, cursor: AttackResultKeysetCursor | None = None, limit: int = 100 + ) -> tuple[list[ScenarioAttackResultDelta], bool]: + """ + Return bounded scenario-linked result deltas in ascending keyset order. + + This projection selects only progress fields and the linked objective + score. It never hydrates ORM relationships, prompt rows, or a full + ScenarioResult. + + Returns: + tuple[list[ScenarioAttackResultDelta], bool]: The page and whether more rows exist. + + Raises: + ValueError: If the limit or cursor identifiers are invalid. + """ + return await self._run_database_operation_async( + self._execute_get_scenario_attack_result_deltas, + scenario_result_id=scenario_result_id, + cursor=cursor, + limit=limit, + ) + + def get_scenario_results( + self, + *, + scenario_result_ids: Sequence[str] | None = None, + scenario_name: str | None = None, + scenario_version: int | None = None, + pyrit_version: str | None = None, + added_after: datetime | None = None, + added_before: datetime | None = None, + labels: dict[str, str] | None = None, + objective_target_endpoint: str | None = None, + objective_target_model_name: str | None = None, + identifier_filters: Sequence[IdentifierFilter] | None = None, + limit: int | None = None, + ) -> Sequence[ScenarioResult]: + """ + Use ``get_scenario_results_async``. + + This synchronous API is deprecated and can block the caller. + + Returns: + Sequence[ScenarioResult]: The operation result. + """ + print_deprecation_message( + old_item="MemoryInterface.get_scenario_results", + new_item="MemoryInterface.get_scenario_results_async", + removed_in="1.4.0", + ) + return self._execute_get_scenario_results( + scenario_result_ids=scenario_result_ids, + scenario_name=scenario_name, + scenario_version=scenario_version, + pyrit_version=pyrit_version, + added_after=added_after, + added_before=added_before, + labels=labels, + objective_target_endpoint=objective_target_endpoint, + objective_target_model_name=objective_target_model_name, + identifier_filters=identifier_filters, + limit=limit, + ) + + @legacy_sync_override(lambda: MemoryInterface.get_scenario_results) + async def get_scenario_results_async( + self, + *, + scenario_result_ids: Sequence[str] | None = None, + scenario_name: str | None = None, + scenario_version: int | None = None, + pyrit_version: str | None = None, + added_after: datetime | None = None, + added_before: datetime | None = None, + labels: dict[str, str] | None = None, + objective_target_endpoint: str | None = None, + objective_target_model_name: str | None = None, + identifier_filters: Sequence[IdentifierFilter] | None = None, + limit: int | None = None, + ) -> Sequence[ScenarioResult]: + """ + Retrieve a list of ScenarioResult objects based on the specified filters. + + Results are always ordered by completion_time descending (most recent first). + + Args: + scenario_result_ids (Sequence[str] | None, optional): A list of scenario result IDs. + Defaults to None. + scenario_name (str | None, optional): The scenario name to filter by (substring match). + Defaults to None. + scenario_version (int | None, optional): The scenario version to filter by. Defaults to None. + pyrit_version (str | None, optional): The PyRIT version to filter by. Defaults to None. + added_after (datetime | None, optional): Filter for scenarios completed after this datetime. + Defaults to None. + added_before (datetime | None, optional): Filter for scenarios completed before this datetime. + Defaults to None. + labels (dict[str, str] | None, optional): A dictionary of memory labels to filter by. + Defaults to None. + objective_target_endpoint (str | None, optional): Filter for scenarios where the + objective_target_identifier has an endpoint attribute containing this value (case-insensitive). + Defaults to None. + objective_target_model_name (str | None, optional): Filter for scenarios where the + objective_target_identifier has a model_name attribute containing this value (case-insensitive). + Defaults to None. + identifier_filters (Sequence[IdentifierFilter] | None, optional): + A sequence of IdentifierFilter objects that allows filtering by identifier JSON properties. + Defaults to None. + limit (int | None): Maximum number of results to return. Defaults to None (no limit). + + Returns: + Sequence[ScenarioResult]: A list of ScenarioResult objects that match the specified filters, + ordered by completion_time descending. + """ + return await self._run_database_operation_async( + self._execute_get_scenario_results, + scenario_result_ids=scenario_result_ids, + scenario_name=scenario_name, + scenario_version=scenario_version, + pyrit_version=pyrit_version, + added_after=added_after, + added_before=added_before, + labels=labels, + objective_target_endpoint=objective_target_endpoint, + objective_target_model_name=objective_target_model_name, + identifier_filters=identifier_filters, + limit=limit, + ) diff --git a/pyrit/memory/memory_session.py b/pyrit/memory/memory_session.py index 00108aff7f..b1a7179ef4 100644 --- a/pyrit/memory/memory_session.py +++ b/pyrit/memory/memory_session.py @@ -8,6 +8,7 @@ from sqlite3 import Connection as SQLiteConnection from typing import Any +from aiosqlite import Connection as AsyncSQLiteConnection from sqlalchemy import delete, inspect, select from sqlalchemy.orm import Session @@ -29,8 +30,8 @@ def _begin_sqlite_write(session: Session) -> None: if session.get_bind().dialect.name == "sqlite": connection = session.connection() driver_connection = connection.connection.driver_connection - if not isinstance(driver_connection, SQLiteConnection): - raise TypeError("SQLite memory requires a sqlite3.Connection.") + if not isinstance(driver_connection, (SQLiteConnection, AsyncSQLiteConnection)): + raise TypeError("SQLite memory requires a sqlite3 or aiosqlite connection.") if not driver_connection.in_transaction: connection.exec_driver_sql("BEGIN IMMEDIATE") diff --git a/pyrit/memory/sqlite_memory.py b/pyrit/memory/sqlite_memory.py index c18e37f29b..36f715f06f 100644 --- a/pyrit/memory/sqlite_memory.py +++ b/pyrit/memory/sqlite_memory.py @@ -1,19 +1,21 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import asyncio import logging import threading import uuid import weakref -from collections.abc import Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from contextlib import closing from datetime import datetime from pathlib import Path -from typing import Any, Literal +from typing import TYPE_CHECKING, Any, Literal from sqlalchemy import and_, case, create_engine, exists, func, or_, select, text from sqlalchemy.engine.base import Engine from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, create_async_engine from sqlalchemy.orm import InstrumentedAttribute, sessionmaker from sqlalchemy.orm.session import Session from sqlalchemy.pool import StaticPool @@ -32,9 +34,26 @@ from pyrit.memory.storage import DiskStorageIO from pyrit.models import ConversationStats +if TYPE_CHECKING: + from sqlalchemy.engine import Connection + logger = logging.getLogger(__name__) +class _SerializedAsyncSession(AsyncSession): + def __init__(self, *, engine: AsyncEngine, release: Callable[[], None]) -> None: + super().__init__(bind=engine, sync_session_class=MemorySession) + self._release: Callable[[], None] | None = release + + async def close(self) -> None: # pyrit-async-suffix-exempt + try: + await super().close() + finally: + if self._release is not None: + release, self._release = self._release, None + release() + + class SQLiteMemory(MemoryInterface, metaclass=Singleton): """ A memory interface that uses SQLite as the backend database. @@ -54,6 +73,7 @@ def __init__( verbose: bool = False, skip_schema_migration: bool = False, silent: bool = False, + _defer_initialization: bool = False, ) -> None: """ Initialize the SQLiteMemory instance. @@ -75,16 +95,77 @@ def __init__( else: self.db_path = Path(db_path or Path(DB_DATA_PATH, self.DEFAULT_DB_FILE_NAME)).resolve() self.results_path = str(DB_DATA_PATH) - - # An in-memory database shares a single DBAPI connection across every thread (see - # ``_create_engine``), so concurrent sessions would interleave on it. Serialize session - # lifetimes for that backend only; file-backed databases get a connection per checkout. - self._connection_lock: threading.RLock | None = threading.RLock() if self.db_path == ":memory:" else None + self._memory_uri = f"file:pyrit-{uuid.uuid4().hex}?mode=memory&cache=shared&uri=true" + self._skip_schema_migration = skip_schema_migration + self._silent = silent + self._keepalive: Connection | None = None + self._verbose = verbose + + # Shared-cache SQLite does not wait on table locks. Serialize whole transactions + # across sync callers and all event loops, not just within each connection pool. + self._connection_lock = threading.RLock() if self.db_path == ":memory:" else None + self._transaction_lock = threading.Lock() if self.db_path == ":memory:" else None + self._sync_session_depth = 0 + self._sync_session_thread: int | None = None self.engine = self._create_engine(has_echo=verbose) self.SessionFactory = sessionmaker(bind=self.engine, class_=MemorySession) - if not skip_schema_migration: - self._run_schema_migration(silent=silent) + if not _defer_initialization: + self._initialize_schema() + self._initialized = True + + def _initialize_schema(self) -> None: + if self.engine is None: + raise RuntimeError("Engine is not initialized.") + if self.db_path == ":memory:" and self._keepalive is None: + self._keepalive = self.engine.connect() + if not self._skip_schema_migration: + self._run_schema_migration(silent=self._silent) + + def _create_async_engine(self) -> AsyncEngine: + database = self._memory_uri if self.db_path == ":memory:" else str(self.db_path) + kwargs: dict[str, Any] = {} + if self.db_path == ":memory:": + kwargs["poolclass"] = StaticPool + return create_async_engine(f"sqlite+aiosqlite:///{database}", echo=self._verbose, **kwargs) + + async def get_session_async(self) -> AsyncSession: + """ + Create a session with exclusive access to the shared in-memory database. + + Returns: + AsyncSession: A session that releases exclusive access when closed. + + Raises: + NotImplementedError: If a custom sync session hook has not been migrated. + RuntimeError: If this thread already holds a synchronous session. + """ + if self._uses_legacy_session_override(): + raise NotImplementedError("Override get_session_async when customizing the legacy get_session hook.") + if self._sync_session_thread == threading.get_ident(): + raise RuntimeError("Close the synchronous memory session before opening an async session on this thread.") + connection_lock = self._transaction_lock + if connection_lock is None: + return await super().get_session_async() + while not connection_lock.acquire(blocking=False): + await asyncio.sleep(0.01) + try: + return _SerializedAsyncSession(engine=self._get_async_engine(), release=connection_lock.release) + except BaseException: + connection_lock.release() + raise + + def _uses_legacy_session_override(self) -> bool: + return super()._uses_legacy_session_override() or ( + type(self).get_session is not MemoryInterface.get_session + and type(self).get_session_async is SQLiteMemory.get_session_async + ) + + def _dispose_sync_engine(self) -> None: + if self._keepalive is not None: + self._keepalive.close() + self._keepalive = None + super()._dispose_sync_engine() def _init_storage_io(self) -> None: # Handles disk-based storage for SQLite local memory. @@ -97,13 +178,9 @@ def _create_engine(self, *, has_echo: bool) -> Engine: Creates an engine bound to the specified database file. The `has_echo` parameter controls the verbosity of SQL execution logging. - For in-memory databases (``db_path=":memory:"``), a ``StaticPool`` is used so - that a single shared connection backs all threads. SQLAlchemy's default pool - for ``:memory:`` is ``SingletonThreadPool``, which gives each thread its own - connection — and therefore its own *separate* in-memory database. That causes - tables created on one thread (e.g. a background initialisation thread) to be - invisible from another thread (e.g. the main thread), resulting in - "no such table" errors. + For in-memory databases, the sync pool and each async pool connect to an + instance-specific named database. A keepalive connection preserves its + contents while async pools are closed between event loops. Args: has_echo (bool): Flag to enable detailed SQL execution logging. @@ -125,7 +202,8 @@ def _create_engine(self, *, has_echo: bool) -> Engine: extra_kwargs["poolclass"] = StaticPool extra_kwargs["connect_args"] = {"check_same_thread": False} - engine = create_engine(f"sqlite:///{self.db_path}", echo=has_echo, **extra_kwargs) + database = self._memory_uri if self.db_path == ":memory:" else str(self.db_path) + engine = create_engine(f"sqlite:///{database}", echo=has_echo, **extra_kwargs) logger.info(f"Engine created successfully for database: {self.db_path}") return engine except SQLAlchemyError as e: @@ -291,7 +369,7 @@ def get_all_table_models(self) -> list[type[Base]]: # The '__subclasses__()' method returns a list of all subclasses of Base, which includes table models return Base.__subclasses__() - def get_session(self) -> Session: + def _get_sync_session(self) -> Session: """ Provide a SQLAlchemy session for transactional operations. @@ -301,15 +379,34 @@ def get_session(self) -> Session: Returns: Session: A SQLAlchemy session bound to the engine. + + Raises: + RuntimeError: If acquiring a session would block an event loop. """ session = self.SessionFactory() connection_lock = self._connection_lock if connection_lock is None: return session - connection_lock.acquire() + try: + asyncio.get_running_loop() + except RuntimeError: + on_event_loop = False + else: + on_event_loop = True + + if not connection_lock.acquire(blocking=not on_event_loop): + raise RuntimeError("A synchronous memory session cannot wait on an event loop. Use the async API.") + if self._sync_session_depth == 0: + assert self._transaction_lock is not None + if not self._transaction_lock.acquire(blocking=not on_event_loop): + connection_lock.release() + raise RuntimeError("A synchronous memory session cannot overlap an async session. Use the async API.") + self._sync_session_depth += 1 + self._sync_session_thread = threading.get_ident() close_session = session.close released = False + owner_thread = threading.get_ident() def release_once() -> None: # Also runs if the session is discarded without being closed, so one caller that @@ -317,7 +414,15 @@ def release_once() -> None: nonlocal released if released: return + if threading.get_ident() != owner_thread: + logger.warning("An in-memory session was discarded by a thread that did not open it.") + return released = True + self._sync_session_depth -= 1 + if self._sync_session_depth == 0: + self._sync_session_thread = None + assert self._transaction_lock is not None + self._transaction_lock.release() try: connection_lock.release() except RuntimeError: @@ -333,7 +438,7 @@ def close_and_release() -> None: weakref.finalize(session, release_once) return session - def print_schema(self) -> None: + def _print_schema(self) -> None: """ Print the schema of all tables in the SQLite database. """ @@ -374,7 +479,7 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str | Sequence *per_key_are_conditions, ) - def get_unique_attack_class_names(self) -> list[str]: + def _execute_get_unique_attack_class_names(self) -> list[str]: """ SQLite implementation: extract unique class_name values from the atomic_attack_identifier JSON column. @@ -382,7 +487,7 @@ def get_unique_attack_class_names(self) -> list[str]: Returns: Sorted list of unique attack class name strings. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: class_name_expr = func.json_extract( AttackResultEntry.atomic_attack_identifier, "$.children.attack_technique.children.attack.class_name", @@ -390,7 +495,7 @@ def get_unique_attack_class_names(self) -> list[str]: rows = session.query(class_name_expr).filter(class_name_expr.isnot(None)).distinct().all() return sorted(row[0] for row in rows) - def get_unique_converter_class_names(self) -> list[str]: + def _execute_get_unique_converter_class_names(self) -> list[str]: """ SQLite implementation: extract unique converter class_name values from the children.attack_technique.children.attack.children.request_converters @@ -399,7 +504,7 @@ def get_unique_converter_class_names(self) -> list[str]: Returns: Sorted list of unique converter class name strings. """ - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = session.execute( text( """SELECT DISTINCT json_extract(j.value, '$.class_name') AS cls @@ -413,7 +518,7 @@ 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]: + def _execute_get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, ConversationStats]: """ SQLite implementation: lightweight aggregate stats per conversation. @@ -462,7 +567,7 @@ def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str """ ) - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = session.execute(sql, params).fetchall() result: dict[str, ConversationStats] = {} diff --git a/pyrit/output/attack_result/markdown.py b/pyrit/output/attack_result/markdown.py index f35e47bbcb..440724d82a 100644 --- a/pyrit/output/attack_result/markdown.py +++ b/pyrit/output/attack_result/markdown.py @@ -459,7 +459,7 @@ async def _get_conversation_async(self, conversation_id: str) -> list[Message]: Returns: list[Message]: The conversation messages. """ - return list(self._memory.get_conversation_messages(conversation_id=conversation_id)) + return list(await self._memory.get_conversation_messages_async(conversation_id=conversation_id)) async def _get_scores_async(self, *, prompt_ids: list[str]) -> list[Score]: """ @@ -468,4 +468,4 @@ async def _get_scores_async(self, *, prompt_ids: list[str]) -> list[Score]: Returns: list[Score]: The scores. """ - return list(self._memory.get_prompt_scores(prompt_ids=prompt_ids)) + return list(await self._memory.get_prompt_scores_async(prompt_ids=prompt_ids)) diff --git a/pyrit/output/attack_result/pretty.py b/pyrit/output/attack_result/pretty.py index 7f270c1cd6..e6c0eb8d54 100644 --- a/pyrit/output/attack_result/pretty.py +++ b/pyrit/output/attack_result/pretty.py @@ -526,7 +526,7 @@ async def _get_conversation_async(self, conversation_id: str) -> list[Message]: Returns: list[Message]: The conversation messages. """ - return list(self._memory.get_conversation_messages(conversation_id=conversation_id)) + return list(await self._memory.get_conversation_messages_async(conversation_id=conversation_id)) async def _get_scores_async(self, *, prompt_ids: list[str]) -> list[Score]: """ @@ -535,4 +535,4 @@ async def _get_scores_async(self, *, prompt_ids: list[str]) -> list[Score]: Returns: list[Score]: The scores. """ - return list(self._memory.get_prompt_scores(prompt_ids=prompt_ids)) + return list(await self._memory.get_prompt_scores_async(prompt_ids=prompt_ids)) diff --git a/pyrit/output/conversation/source.py b/pyrit/output/conversation/source.py index 4f16e003ba..2bdc10e3fc 100644 --- a/pyrit/output/conversation/source.py +++ b/pyrit/output/conversation/source.py @@ -48,7 +48,7 @@ async def get_messages_async(self, *, conversation_id: str) -> list[Message]: Returns: list[Message]: The conversation's messages in order. """ - return list(self._memory.get_conversation_messages(conversation_id=conversation_id)) + return list(await self._memory.get_conversation_messages_async(conversation_id=conversation_id)) async def get_scores_async(self, *, prompt_ids: list[str]) -> list[Score]: """ @@ -60,4 +60,4 @@ async def get_scores_async(self, *, prompt_ids: list[str]) -> list[Score]: Returns: list[Score]: The scores for those pieces (empty if none). """ - return list(self._memory.get_prompt_scores(prompt_ids=prompt_ids)) + return list(await self._memory.get_prompt_scores_async(prompt_ids=prompt_ids)) diff --git a/pyrit/prompt_normalizer/json_retry.py b/pyrit/prompt_normalizer/json_retry.py index 4b3ae70be6..a17df512c5 100644 --- a/pyrit/prompt_normalizer/json_retry.py +++ b/pyrit/prompt_normalizer/json_retry.py @@ -61,17 +61,21 @@ async def send_json_with_retry_async( ValueError: If the target returns no response. """ memory = normalizer.memory - existing_pieces = memory.get_message_pieces(conversation_id=conversation_id) + existing_pieces = await memory.get_message_pieces_async(conversation_id=conversation_id) baseline = max((piece.sequence for piece in existing_pieces), default=-1) @pyrit_json_retry async def _attempt_async() -> T: - deleted = memory.delete_conversation_pieces_after_sequence(conversation_id=conversation_id, sequence=baseline) + deleted = await memory.delete_conversation_pieces_after_sequence_async( + conversation_id=conversation_id, sequence=baseline + ) if deleted: - memory.add_conversation_retry( - conversation_id=conversation_id, - sequence=baseline + 1, - reason=ConversationRetryReason.JSON_PARSING, + ( + await memory.add_conversation_retry_async( + conversation_id=conversation_id, + sequence=baseline + 1, + reason=ConversationRetryReason.JSON_PARSING, + ) ) response = await normalizer.send_prompt_async(message=message, conversation_id=conversation_id, target=target) if not response: diff --git a/pyrit/prompt_normalizer/prompt_normalizer.py b/pyrit/prompt_normalizer/prompt_normalizer.py index f1362f7e99..cec354687c 100644 --- a/pyrit/prompt_normalizer/prompt_normalizer.py +++ b/pyrit/prompt_normalizer/prompt_normalizer.py @@ -130,8 +130,10 @@ async def send_prompt_async( request = copy.deepcopy(message) conversation_id = conversation_id if conversation_id else str(uuid4()) target_identifier = target.get_identifier() - self.memory.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target_identifier) + ( + await self.memory.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target_identifier) + ) ) for piece in request.message_pieces: @@ -152,14 +154,14 @@ async def send_prompt_async( normalizer_overrides=normalizer_overrides, send_context=send_context, ) - self.memory.add_message_to_memory(request=request) + (await self.memory.add_message_to_memory_async(request=request)) except EmptyResponseException as ex: if send_context and send_context.target_invocation_count == target_invocation_count_before_send: cid = request.message_pieces[0].conversation_id if request.message_pieces else None raise Exception(f"Error normalizing prompt with conversation ID: {cid}") from ex # Empty responses are retried, but we don't want them to stop execution - self.memory.add_message_to_memory(request=request) + (await self.memory.add_message_to_memory_async(request=request)) responses = [ construct_response_from_request( @@ -176,7 +178,7 @@ async def send_prompt_async( raise Exception(f"Error normalizing prompt with conversation ID: {cid}") from ex # Ensure request to memory before processing exception - self.memory.add_message_to_memory(request=request) + (await self.memory.add_message_to_memory_async(request=request)) error_response = construct_response_from_request( request=request.message_pieces[0], @@ -188,7 +190,7 @@ async def send_prompt_async( error_response.get_piece().prompt_metadata.pop(RequestTraceContext.REQUEST_METADATA_KEY, None) await self._calc_hash_async(request=error_response) - self.memory.add_message_to_memory(request=error_response) + (await self.memory.add_message_to_memory_async(request=error_response)) cid = request.message_pieces[0].conversation_id if request and request.message_pieces else None raise Exception(f"Error sending prompt with conversation ID: {cid}") from ex @@ -207,7 +209,7 @@ async def send_prompt_async( empty_response.get_piece().prompt_metadata.pop(RequestTraceContext.METADATA_KEY, None) empty_response.get_piece().prompt_metadata.pop(RequestTraceContext.REQUEST_METADATA_KEY, None) await self._calc_hash_async(request=empty_response) - self.memory.add_message_to_memory(request=empty_response) + (await self.memory.add_message_to_memory_async(request=empty_response)) return empty_response # Process all response messages (targets return list[Message]) @@ -227,7 +229,7 @@ async def send_prompt_async( converter_configurations=response_converter_configurations, message=resp ) await self._calc_hash_async(request=resp) - self.memory.add_message_to_memory(request=resp) + (await self.memory.add_message_to_memory_async(request=resp)) # Return the last response for backward compatibility return responses[-1] @@ -433,7 +435,7 @@ async def hash_and_persist_message_async(self, *, message: Message) -> None: message (Message): The message to hash and persist. """ await self._calc_hash_async(request=message) - self.memory.add_message_to_memory(request=message) + (await self.memory.add_message_to_memory_async(request=message)) async def add_prepended_conversation_to_memory_async( self, @@ -463,8 +465,10 @@ async def add_prepended_conversation_to_memory_async( # Create a deep copy of the prepended conversation to avoid modifying the original prepended_conversation = copy.deepcopy(prepended_conversation) - self.memory.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target_identifier) + ( + await self.memory.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target_identifier) + ) ) for request in prepended_conversation: @@ -477,7 +481,7 @@ async def add_prepended_conversation_to_memory_async( # and if not, this won't hurt anything piece.id = uuid4() - self.memory.add_message_to_memory(request=request) + (await self.memory.add_message_to_memory_async(request=request)) return prepended_conversation diff --git a/pyrit/prompt_target/common/discover_target_capabilities.py b/pyrit/prompt_target/common/discover_target_capabilities.py index 6e5745fdff..909056eb6a 100644 --- a/pyrit/prompt_target/common/discover_target_capabilities.py +++ b/pyrit/prompt_target/common/discover_target_capabilities.py @@ -362,10 +362,12 @@ async def _probe_system_prompt_async(target: PromptTarget, timeout_s: float, ret prompt_metadata=_probe_metadata(), ) try: - target._memory.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target.get_identifier()) + ( + await target._memory.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target.get_identifier()) + ) ) - target._memory.add_message_to_memory(request=Message(message_pieces=[system_piece])) + (await target._memory.add_message_to_memory_async(request=Message(message_pieces=[system_piece]))) except Exception as exc: logger.debug("System-prompt probe could not seed system message: %s", exc) return False @@ -449,10 +451,12 @@ async def _probe_multi_turn_async(target: PromptTarget, timeout_s: float, retrie # Seed memory so the second send sees real prior history. try: - target._memory.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target.get_identifier()) + ( + await target._memory.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target.get_identifier()) + ) ) - target._memory.add_message_to_memory(request=Message(message_pieces=[first])) + (await target._memory.add_message_to_memory_async(request=Message(message_pieces=[first]))) assistant_reply = MessagePiece( role="assistant", original_value="Got it.", @@ -460,7 +464,7 @@ async def _probe_multi_turn_async(target: PromptTarget, timeout_s: float, retrie conversation_id=conversation_id, prompt_metadata=_probe_metadata(), ).to_message() - target._memory.add_message_to_memory(request=assistant_reply) + (await target._memory.add_message_to_memory_async(request=assistant_reply)) except Exception as exc: logger.debug("Multi-turn probe could not seed conversation history: %s", exc) return False @@ -598,13 +602,12 @@ async def _probe_tool_calls_async( prompt_metadata=_probe_metadata(), ), ) - await asyncio.to_thread( - target._memory.add_conversation_to_memory, + await target._memory.add_conversation_to_memory_async( conversation=Conversation(conversation_id=conversation_id, target_identifier=target.get_identifier()), ) for message in history: message.set_simulated_role() - await asyncio.to_thread(target._memory.add_message_to_memory, request=message) + await target._memory.add_message_to_memory_async(request=message) return await _send_and_check_async( target=target, message=_user_text_piece( diff --git a/pyrit/prompt_target/common/prompt_target.py b/pyrit/prompt_target/common/prompt_target.py index 1b651505fd..3078ffc275 100644 --- a/pyrit/prompt_target/common/prompt_target.py +++ b/pyrit/prompt_target/common/prompt_target.py @@ -6,6 +6,8 @@ from collections.abc import Mapping, Sequence from typing import Any, ClassVar, Literal, final +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.memory import CentralMemory, MemoryInterface from pyrit.message_normalizer import MessageListNormalizer from pyrit.models import ( @@ -346,7 +348,9 @@ async def _get_normalized_conversation_async( """ conversation_id = message.message_pieces[0].conversation_id persisted_messages = ( - list(self._memory.get_conversation_messages(conversation_id=conversation_id)) if conversation_id else [] + list(await self._memory.get_conversation_messages_async(conversation_id=conversation_id)) + if conversation_id + else [] ) persisted_messages = filter_non_replayable_messages(messages=persisted_messages) conversation = send_context.select_history(messages=persisted_messages) if send_context else persisted_messages @@ -400,6 +404,11 @@ def set_system_prompt( ValueError: If the target does not support multi-turn or editable history. RuntimeError: If the conversation already has messages. """ + print_deprecation_message( + old_item="PromptTarget.set_system_prompt", + new_item="PromptTarget.set_system_prompt_async", + removed_in="1.4.0", + ) if not self.capabilities.supports_multi_turn or not self.capabilities.supports_editable_history: raise ValueError( f"Target {type(self).__name__} does not support setting a system prompt. " @@ -423,6 +432,64 @@ def set_system_prompt( ).to_message(), ) + @legacy_sync_override(lambda: PromptTarget.set_system_prompt) + async def set_system_prompt_async( + self, + *, + system_prompt: str, + conversation_id: str, + ) -> None: + """ + Inject a system prompt into memory for the given conversation. + + Writes a ``system``-role message so the target's normalization pipeline + (or the target itself, when it natively supports system prompts) will + pick it up on the next ``send_prompt_async`` call. + + If the target does not natively support system prompts, whether this + call is ultimately honored depends on the target's + ``CapabilityHandlingPolicy``: + + * ``ADAPT`` — the normalization pipeline (e.g. system squash) will + fold the system message into user content on the wire. + * ``RAISE`` — the first send after the system prompt is set will + raise, because the pipeline cannot adapt the missing capability. + + Args: + system_prompt (str): The system prompt text to set. + conversation_id (str): The conversation id to attach the prompt to. + + Raises: + ValueError: If the target does not support multi-turn or editable history. + RuntimeError: If the conversation already has messages. + """ + if not self.capabilities.supports_multi_turn or not self.capabilities.supports_editable_history: + raise ValueError( + f"Target {type(self).__name__} does not support setting a system prompt. " + "It must support both multi-turn conversations and editable history." + ) + + messages = await self._memory.get_conversation_messages_async(conversation_id=conversation_id) + + if messages: + raise RuntimeError("Conversation already exists, system prompt needs to be set at the beginning") + + ( + await self._memory.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=self.get_identifier()) + ) + ) + ( + await self._memory.add_message_to_memory_async( + request=MessagePiece( + role="system", + conversation_id=conversation_id, + original_value=system_prompt, + converted_value=system_prompt, + ).to_message() + ) + ) + async def reset_conversation_async(self, *, conversation_id: str) -> None: """ Release any target-side state held for a conversation. @@ -445,8 +512,20 @@ def dispose_db_engine(self) -> None: """ Dispose database engine to release database connections and resources. """ + print_deprecation_message( + old_item="PromptTarget.dispose_db_engine", + new_item="PromptTarget.dispose_db_engine_async", + removed_in="1.4.0", + ) self._memory.dispose_engine() + @legacy_sync_override(lambda: PromptTarget.dispose_db_engine) + async def dispose_db_engine_async(self) -> None: + """ + Dispose database engine to release database connections and resources. + """ + (await self._memory.dispose_engine_async()) + def _create_identifier( self, *, diff --git a/pyrit/prompt_target/openai/_openai_realtime_streaming_session.py b/pyrit/prompt_target/openai/_openai_realtime_streaming_session.py index fd73d0369d..ce78c21f7a 100644 --- a/pyrit/prompt_target/openai/_openai_realtime_streaming_session.py +++ b/pyrit/prompt_target/openai/_openai_realtime_streaming_session.py @@ -402,8 +402,10 @@ async def _handle_committed_turn_async(self, *, event: CommittedEvent, raw_pcm: ) target_identifier = target.get_identifier() - target._memory.add_conversation_to_memory( - conversation=Conversation(conversation_id=self._conversation_id, target_identifier=target_identifier) + ( + await target._memory.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=self._conversation_id, target_identifier=target_identifier) + ) ) user_piece = MessagePiece( role="user", diff --git a/pyrit/prompt_target/openai/openai_realtime_target.py b/pyrit/prompt_target/openai/openai_realtime_target.py index db46480e80..b907c1e300 100644 --- a/pyrit/prompt_target/openai/openai_realtime_target.py +++ b/pyrit/prompt_target/openai/openai_realtime_target.py @@ -359,7 +359,7 @@ async def send_config_async(self, *, conversation_id: str, conversation: list[Me resolved_conversation = ( conversation if conversation is not None - else list(self._memory.get_conversation_messages(conversation_id=conversation_id)) + else list(await self._memory.get_conversation_messages_async(conversation_id=conversation_id)) ) system_prompt = self._get_system_prompt_from_conversation(conversation=resolved_conversation) config_variables = self._set_system_prompt_and_config_vars(system_prompt=system_prompt) diff --git a/pyrit/prompt_target/websocket_copilot_target.py b/pyrit/prompt_target/websocket_copilot_target.py index 869c9e3ec1..497b7e5862 100644 --- a/pyrit/prompt_target/websocket_copilot_target.py +++ b/pyrit/prompt_target/websocket_copilot_target.py @@ -619,7 +619,7 @@ def _validate_request(self, *, normalized_conversation: list[Message]) -> None: f"Detected MIME type: {mime_type}." ) - def _is_start_of_session(self, *, conversation_id: str) -> bool: + async def _is_start_of_session_async(self, *, conversation_id: str) -> bool: """ Determine if this is the first message in a PyRIT conversation. @@ -632,7 +632,7 @@ def _is_start_of_session(self, *, conversation_id: str) -> bool: Returns: bool: True if no prior messages exist in this conversation, False otherwise. """ - conversation_history = self._memory.get_conversation_messages(conversation_id=conversation_id) + conversation_history = await self._memory.get_conversation_messages_async(conversation_id=conversation_id) return len(conversation_history) == 0 def _generate_consistent_copilot_ids(self, *, pyrit_conversation_id: str) -> tuple[str, str]: @@ -684,7 +684,7 @@ async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Me pyrit_conversation_id = message.message_pieces[0].conversation_id if not pyrit_conversation_id: raise ValueError("WebSocketCopilotTarget requires a conversation_id on the message being sent.") - is_start_of_session = self._is_start_of_session(conversation_id=pyrit_conversation_id) + is_start_of_session = await self._is_start_of_session_async(conversation_id=pyrit_conversation_id) session_id, copilot_conversation_id = self._generate_consistent_copilot_ids( pyrit_conversation_id=pyrit_conversation_id diff --git a/pyrit/scenario/core/atomic_attack.py b/pyrit/scenario/core/atomic_attack.py index 557c82b880..55fa692e6a 100644 --- a/pyrit/scenario/core/atomic_attack.py +++ b/pyrit/scenario/core/atomic_attack.py @@ -399,7 +399,7 @@ async def run_async( ) # Enrich atomic_attack_identifier with seed identifiers - self._enrich_atomic_attack_identifiers(results=results) + (await self._enrich_atomic_attack_identifiers_async(results=results)) # Log completion status if results.has_incomplete: @@ -418,7 +418,7 @@ async def run_async( logger.error(f"Atomic attack '{self.atomic_attack_name}' execution failed: {str(e)}") raise ValueError(f"Failed to execute atomic attack '{self.atomic_attack_name}': {str(e)}") from e - def _enrich_atomic_attack_identifiers(self, *, results: AttackExecutorResult[AttackResult]) -> None: + async def _enrich_atomic_attack_identifiers_async(self, *, results: AttackExecutorResult[AttackResult]) -> None: """ Enrich each AttackResult's atomic_attack_identifier with seed group and technique information, then persist the update to the database. @@ -447,9 +447,9 @@ def _enrich_atomic_attack_identifiers(self, *, results: AttackExecutorResult[Att result.atomic_attack_identifier = identifier if result.attack_result_id: - memory.update_attack_result_by_id( - attack_result_id=result.attack_result_id, - update_fields={ - "atomic_attack_identifier": identifier.model_dump(), - }, + ( + await memory.update_attack_result_by_id_async( + attack_result_id=result.attack_result_id, + update_fields={"atomic_attack_identifier": identifier.model_dump()}, + ) ) diff --git a/pyrit/scenario/core/dataset_configuration.py b/pyrit/scenario/core/dataset_configuration.py index 4f43d5fdc6..1891bca02a 100644 --- a/pyrit/scenario/core/dataset_configuration.py +++ b/pyrit/scenario/core/dataset_configuration.py @@ -27,7 +27,6 @@ from __future__ import annotations -import asyncio import random from contextlib import contextmanager from contextvars import ContextVar @@ -490,13 +489,7 @@ async def _collect_seeds_for_dataset_async(self, *, dataset_name: str) -> list[S DatasetConstraintError: If the dataset yields no seeds even after auto-fetch, or if auto-fetch itself fails (the provider error is chained as the cause). """ - found = list( - await asyncio.to_thread( - self._memory.get_seeds, - dataset_name=dataset_name, - **self._get_seeds_filters, - ) - ) + found = list(await self._memory.get_seeds_async(dataset_name=dataset_name, **self._get_seeds_filters)) auto_fetch_allowed = self._auto_fetch and _AUTO_FETCH_ALLOWED.get() if not found and auto_fetch_allowed: try: @@ -505,17 +498,9 @@ async def _collect_seeds_for_dataset_async(self, *, dataset_name: str) -> list[S raise DatasetConstraintError( f"Dataset '{dataset_name}' could not be loaded: auto-fetch from the registered provider failed." ) from exc - found = list( - await asyncio.to_thread( - self._memory.get_seeds, - dataset_name=dataset_name, - **self._get_seeds_filters, - ) - ) + found = list(await self._memory.get_seeds_async(dataset_name=dataset_name, **self._get_seeds_filters)) if not found: - unfiltered = ( - await asyncio.to_thread(self._memory.get_seeds, dataset_name=dataset_name) if self._filters else [] - ) + unfiltered = await self._memory.get_seeds_async(dataset_name=dataset_name) if self._filters else [] if unfiltered: raise DatasetConstraintError( f"Dataset '{dataset_name}' has seeds, but none match the configured filters {self._filters}." diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py index dd8dbe647a..6f1bab3d13 100644 --- a/pyrit/scenario/core/scenario.py +++ b/pyrit/scenario/core/scenario.py @@ -25,7 +25,6 @@ from pyrit.executor.attack import AttackExecutor, AttackExecutorResult from pyrit.executor.attack.core.attack_preparation import AttackPreparationFailure from pyrit.memory import CentralMemory -from pyrit.memory.memory_models import ScenarioResultEntry from pyrit.models import ( SCENARIO_RUN_PLAN_METADATA_KEY, AttackOutcome, @@ -1016,7 +1015,9 @@ async def initialize_async(self) -> None: # rather than a silent restart, so the original progress isn't orphaned without # the user knowing. if self._scenario_result_id: - existing_results = self._memory.get_scenario_results(scenario_result_ids=[self._scenario_result_id]) + existing_results = await self._memory.get_scenario_results_async( + scenario_result_ids=[self._scenario_result_id] + ) if not existing_results: raise ValueError( @@ -1037,9 +1038,11 @@ async def initialize_async(self) -> None: reconstructed_plan = self._build_run_plan() metadata = dict(stored_result.metadata) metadata[SCENARIO_RUN_PLAN_METADATA_KEY] = reconstructed_plan.model_dump(mode="json", exclude_none=True) - self._memory.update_scenario_metadata( - scenario_result_id=self._scenario_result_id, - metadata=metadata, + ( + await self._memory.update_scenario_metadata_async( + scenario_result_id=self._scenario_result_id, + metadata=metadata, + ) ) return # Valid resume - skip creating new scenario result @@ -1064,7 +1067,7 @@ async def initialize_async(self) -> None: }, ) - self._memory.add_scenario_results_to_memory(scenario_results=[result]) + (await self._memory.add_scenario_results_to_memory_async(scenario_results=[result])) self._scenario_result_id = str(result.id) logger.info(f"Created new scenario result with ID: {self._scenario_result_id}") @@ -1339,7 +1342,7 @@ def _validate_stored_scenario( f"(ID: {self._scenario_result_id}, state: {stored_result.scenario_run_state})" ) - def _get_completed_objective_hashes_by_attack(self) -> dict[tuple[str, str | None], set[str]]: + async def _get_completed_objective_hashes_by_attack_async(self) -> dict[tuple[str, str | None], set[str]]: """ Index completed objective hashes for every atomic attack in this scenario. @@ -1372,7 +1375,7 @@ def _get_completed_objective_hashes_by_attack(self) -> dict[tuple[str, str | Non if not self._scenario_result_id: return {} - rows = self._memory.get_attack_results(scenario_result_id=self._scenario_result_id) + rows = await self._memory.get_attack_results_async(scenario_result_id=self._scenario_result_id) completed_by_attack: dict[tuple[str, str | None], set[str]] = {} for row in rows: # ERROR rows hit infrastructure problems, and preparation failures never reached the @@ -1412,7 +1415,7 @@ async def _get_remaining_atomic_attacks_async(self) -> list[AtomicAttack]: remaining_attacks: list[AtomicAttack] = [] # Read and index one snapshot before changing any attack's remaining work. - completed_by_attack = self._get_completed_objective_hashes_by_attack() + completed_by_attack = await self._get_completed_objective_hashes_by_attack_async() for atomic_attack in self._atomic_attacks: name = atomic_attack.atomic_attack_name @@ -1562,7 +1565,7 @@ async def run_async(self) -> ScenarioResult: "call await scenario.initialize_async() first." ) if self._scenario_result_id: - self._mark_scenario_failed(scenario_result_id=self._scenario_result_id, error=error) + (await self._mark_scenario_failed_async(scenario_result_id=self._scenario_result_id, error=error)) raise error if not self._scenario_result_id: @@ -1578,11 +1581,13 @@ async def run_async(self) -> ScenarioResult: return await self._execute_scenario_async() except asyncio.CancelledError: try: - self._memory.update_scenario_run_state( - scenario_result_id=scenario_result_id, - scenario_run_state=ScenarioRunState.CANCELLED, - error_message="Scenario run was cancelled", - error_type="CancelledError", + ( + await self._memory.update_scenario_run_state_async( + scenario_result_id=scenario_result_id, + scenario_run_state=ScenarioRunState.CANCELLED, + error_message="Scenario run was cancelled", + error_type="CancelledError", + ) ) except Exception: logger.exception(f"Failed to persist cancellation state for scenario '{self._name}'") @@ -1591,7 +1596,9 @@ async def run_async(self) -> ScenarioResult: last_exception = e # Get current scenario to check number of tries - scenario_results = self._memory.get_scenario_results(scenario_result_ids=[scenario_result_id]) + scenario_results = await self._memory.get_scenario_results_async( + scenario_result_ids=[scenario_result_id] + ) current_tries = scenario_results[0].number_tries if scenario_results else retry_attempt + 1 # Check if we have more retries available @@ -1611,7 +1618,7 @@ async def run_async(self) -> ScenarioResult: f"(initial + {self._max_retries} retries) with error: {str(e)}. Giving up.", exc_info=True, ) - self._mark_scenario_failed(scenario_result_id=scenario_result_id, error=e) + (await self._mark_scenario_failed_async(scenario_result_id=scenario_result_id, error=e)) raise # This should never be reached, but just in case @@ -1644,20 +1651,21 @@ async def _execute_scenario_async(self) -> ScenarioResult: scenario_result_id: str = self._scenario_result_id # Increment number_tries at the start of each run - scenario_results = self._memory.get_scenario_results(scenario_result_ids=[scenario_result_id]) + scenario_results = await self._memory.get_scenario_results_async(scenario_result_ids=[scenario_result_id]) if scenario_results: current_scenario = scenario_results[0] current_scenario.number_tries += 1 - entry = ScenarioResultEntry(entry=current_scenario) - self._memory._update_entry(entry) + await self._memory.update_scenario_result_async(scenario_result=current_scenario) logger.info(f"Scenario '{self._name}' attempt #{current_scenario.number_tries}") else: raise ValueError(f"Scenario result with ID {scenario_result_id} not found") # Mark scenario as in progress - self._memory.update_scenario_run_state( - scenario_result_id=scenario_result_id, - scenario_run_state=ScenarioRunState.IN_PROGRESS, + ( + await self._memory.update_scenario_run_state_async( + scenario_result_id=scenario_result_id, + scenario_run_state=ScenarioRunState.IN_PROGRESS, + ) ) # Get remaining atomic attacks (filters out completed ones and updates objectives) @@ -1666,12 +1674,14 @@ async def _execute_scenario_async(self) -> ScenarioResult: if not remaining_attacks: logger.info(f"Scenario '{self._name}' has no remaining objectives to execute") # Mark scenario as completed - self._memory.update_scenario_run_state( - scenario_result_id=scenario_result_id, - scenario_run_state=ScenarioRunState.COMPLETED, + ( + await self._memory.update_scenario_run_state_async( + scenario_result_id=scenario_result_id, + scenario_run_state=ScenarioRunState.COMPLETED, + ) ) # Retrieve and return the current scenario result - scenario_results = self._memory.get_scenario_results(scenario_result_ids=[scenario_result_id]) + scenario_results = await self._memory.get_scenario_results_async(scenario_result_ids=[scenario_result_id]) if scenario_results: return scenario_results[0] raise ValueError(f"Scenario result with ID {scenario_result_id} not found") @@ -1700,13 +1710,15 @@ async def _execute_scenario_async(self) -> ScenarioResult: logger.info(f"Scenario '{self._name}' completed successfully") # Mark scenario as completed - self._memory.update_scenario_run_state( - scenario_result_id=scenario_result_id, - scenario_run_state=ScenarioRunState.COMPLETED, + ( + await self._memory.update_scenario_run_state_async( + scenario_result_id=scenario_result_id, + scenario_run_state=ScenarioRunState.COMPLETED, + ) ) # Retrieve and return final scenario result - scenario_results = self._memory.get_scenario_results(scenario_result_ids=[scenario_result_id]) + scenario_results = await self._memory.get_scenario_results_async(scenario_result_ids=[scenario_result_id]) if not scenario_results: raise ValueError(f"Scenario result with ID {self._scenario_result_id} not found") @@ -1752,16 +1764,18 @@ def _partial_result_to_exception( incomplete_objectives=atomic_results.incomplete_objectives, ) - def _mark_scenario_failed(self, *, scenario_result_id: str, error: BaseException) -> None: + async def _mark_scenario_failed_async(self, *, scenario_result_id: str, error: BaseException) -> None: """Mark the scenario run as FAILED, deriving message/type from ``error``.""" error_message = str(error) if error.__cause__ is not None: error_message = f"{error_message} Caused by {type(error.__cause__).__name__}: {str(error.__cause__)}" - self._memory.update_scenario_run_state( - scenario_result_id=scenario_result_id, - scenario_run_state=ScenarioRunState.FAILED, - error_message=error_message, - error_type=type(error).__name__, + ( + await self._memory.update_scenario_run_state_async( + scenario_result_id=scenario_result_id, + scenario_run_state=ScenarioRunState.FAILED, + error_message=error_message, + error_type=type(error).__name__, + ) ) async def _execute_atomic_attacks_parallel_async( diff --git a/pyrit/scenario/scenarios/adaptive/selectors/epsilon_greedy.py b/pyrit/scenario/scenarios/adaptive/selectors/epsilon_greedy.py index a415182733..e9db509beb 100644 --- a/pyrit/scenario/scenarios/adaptive/selectors/epsilon_greedy.py +++ b/pyrit/scenario/scenarios/adaptive/selectors/epsilon_greedy.py @@ -11,7 +11,7 @@ import struct from typing import TYPE_CHECKING -from pyrit.analytics.technique_analysis import compute_technique_stats +from pyrit.analytics.technique_analysis import compute_technique_stats_async from pyrit.scenario.scenarios.adaptive.selectors.technique_selector import SelectorScope if TYPE_CHECKING: @@ -129,7 +129,7 @@ async def select_async( rng = _derive_rng(self._seed, decision_key) effective_run_id = scenario_result_id if self._scope.current_run_only else None - stats = compute_technique_stats( + stats = await compute_technique_stats_async( technique_eval_hashes=technique_list, scenario_result_id=effective_run_id, targeted_harm_categories=self._scope.targeted_harm_categories, diff --git a/pyrit/scenario/scenarios/airt/jailbreak.py b/pyrit/scenario/scenarios/airt/jailbreak.py index f1cca75e39..afeeeb7afd 100644 --- a/pyrit/scenario/scenarios/airt/jailbreak.py +++ b/pyrit/scenario/scenarios/airt/jailbreak.py @@ -271,7 +271,7 @@ def _resolve_scenario_techniques(self, *, scenario_techniques: Any) -> list[Scen ) return super()._resolve_scenario_techniques(scenario_techniques=scenario_techniques) - def _resolve_templates(self) -> list[str]: + async def _resolve_templates_async(self) -> list[str]: """ Resolve the jailbreak templates for this run, replaying the persisted set on resume. @@ -288,7 +288,7 @@ def _resolve_templates(self) -> list[str]: ``jailbreak_names`` contains an unknown template. """ if self._scenario_result_id is not None: - stored = self._memory.get_scenario_results(scenario_result_ids=[self._scenario_result_id]) + stored = await self._memory.get_scenario_results_async(scenario_result_ids=[self._scenario_result_id]) if stored: persisted = (stored[0].metadata or {}).get(_JAILBREAK_TEMPLATES_METADATA_KEY) if persisted: @@ -464,7 +464,7 @@ async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list "Scenario not properly initialized. Call await scenario.initialize_async() before running." ) - self._resolved_jailbreaks = self._resolve_templates() + self._resolved_jailbreaks = await self._resolve_templates_async() num_attempts = self.params["num_jailbreak_attempts"] technique_factories = resolve_technique_factories(context=context, extra_factories=_extra_default_factories()) diff --git a/pyrit/scenario/scenarios/airt/leakage.py b/pyrit/scenario/scenarios/airt/leakage.py index 1c0f3b3e05..c96fa48b87 100644 --- a/pyrit/scenario/scenarios/airt/leakage.py +++ b/pyrit/scenario/scenarios/airt/leakage.py @@ -13,7 +13,6 @@ from pyrit.scenario.core.dataset_configuration import DatasetAttackConfiguration from pyrit.scenario.core.matrix_atomic_attack_builder import build_matrix_atomic_attacks from pyrit.scenario.core.scenario import Scenario -from pyrit.scenario.core.scenario_technique import ScenarioTechnique if TYPE_CHECKING: from pathlib import Path diff --git a/pyrit/scenario/scenarios/airt/multilingual.py b/pyrit/scenario/scenarios/airt/multilingual.py index 189e39ee50..b48ffbe124 100644 --- a/pyrit/scenario/scenarios/airt/multilingual.py +++ b/pyrit/scenario/scenarios/airt/multilingual.py @@ -31,7 +31,6 @@ if TYPE_CHECKING: from pyrit.prompt_target import PromptTarget - from pyrit.scenario.core import ScenarioTechnique from pyrit.scenario.core.scenario_context import ScenarioContext from pyrit.score import TrueFalseScorer @@ -236,7 +235,7 @@ def _get_default_languages(cls) -> list[str]: dataset = SeedDataset.from_yaml_file(cls._DEFAULT_LANGUAGES_SEED_PROMPT_PATH) return [str(seed.value) for seed in dataset.seeds] - def _resolve_languages(self) -> list[str]: + async def _resolve_languages_async(self) -> list[str]: """ Resolve the languages for this run, replaying the persisted set on resume. @@ -253,7 +252,7 @@ def _resolve_languages(self) -> list[str]: or if ``num_languages`` is out of bounds. """ if self._scenario_result_id is not None: - stored = self._memory.get_scenario_results(scenario_result_ids=[self._scenario_result_id]) + stored = await self._memory.get_scenario_results_async(scenario_result_ids=[self._scenario_result_id]) if stored: persisted = (stored[0].metadata or {}).get(_LANGUAGES_METADATA_KEY) if persisted: @@ -306,7 +305,7 @@ async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list "Scenario not properly initialized. Call await scenario.initialize_async() before running." ) - self._resolved_languages = self._resolve_languages() + self._resolved_languages = await self._resolve_languages_async() adversarial_chat = self._adversarial_chat or get_default_adversarial_target() strategies = set(self.params.get("translation_strategies") or [_TRANSLATION, _RANDOM_TRANSLATION]) technique_factories = resolve_technique_factories( diff --git a/pyrit/scenario/scenarios/benchmark/adversarial.py b/pyrit/scenario/scenarios/benchmark/adversarial.py index 2a31e2d46b..4499dfaeb3 100644 --- a/pyrit/scenario/scenarios/benchmark/adversarial.py +++ b/pyrit/scenario/scenarios/benchmark/adversarial.py @@ -12,7 +12,7 @@ from functools import cache from typing import TYPE_CHECKING, Any, ClassVar -from pyrit.analytics import get_cached_results_for_technique +from pyrit.analytics import get_cached_results_for_technique_async from pyrit.common import apply_defaults from pyrit.common.path import EXECUTOR_SEED_PROMPT_PATH, SCORER_SEED_PROMPT_PATH from pyrit.common.utils import to_sha256 @@ -558,7 +558,7 @@ async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list if not self._is_cache_reuse_enabled() or self._scenario_result_id: return atomic_attacks - self._apply_reusable_cached_results(atomic_attacks=atomic_attacks) + (await self._apply_reusable_cached_results_async(atomic_attacks=atomic_attacks)) return atomic_attacks def _get_technique_factory_overrides(self) -> dict[str, AttackTechniqueFactory] | None: @@ -704,14 +704,14 @@ async def run_async(self) -> ScenarioResult: newly executed objective results. """ try: - self._persist_precomputed_cached_results() + (await self._persist_precomputed_cached_results_async()) except Exception as error: if self._scenario_result_id: - self._mark_scenario_failed(scenario_result_id=self._scenario_result_id, error=error) + (await self._mark_scenario_failed_async(scenario_result_id=self._scenario_result_id, error=error)) raise return await super().run_async() - def _apply_reusable_cached_results(self, *, atomic_attacks: list[AtomicAttack]) -> None: + async def _apply_reusable_cached_results_async(self, *, atomic_attacks: list[AtomicAttack]) -> None: """ Remove only objectives having an exact reusable result. @@ -719,7 +719,7 @@ def _apply_reusable_cached_results(self, *, atomic_attacks: list[AtomicAttack]) atomic_attacks: Candidate attacks whose seed groups may be pruned. """ self._precomputed_cached_results = {} - reusable = self._collect_reusable_cached_results(atomic_attacks=atomic_attacks) + reusable = await self._collect_reusable_cached_results_async(atomic_attacks=atomic_attacks) for attack in atomic_attacks: prior_results = reusable.get(attack.atomic_attack_name, []) if not prior_results: @@ -738,7 +738,9 @@ def _apply_reusable_cached_results(self, *, atomic_attacks: list[AtomicAttack]) fully_cached_count, ) - def _collect_reusable_cached_results(self, *, atomic_attacks: list[AtomicAttack]) -> dict[str, list[AttackResult]]: + async def _collect_reusable_cached_results_async( + self, *, atomic_attacks: list[AtomicAttack] + ) -> dict[str, list[AttackResult]]: """ Select the newest exact compatible result for each objective. @@ -752,11 +754,11 @@ def _collect_reusable_cached_results(self, *, atomic_attacks: list[AtomicAttack] Returns: dict[str, list[AttackResult]]: Reusable results keyed by atomic attack name. """ - candidate_names = self._collect_cached_completion_pairs(atomic_attacks=atomic_attacks) + candidate_names = await self._collect_cached_completion_pairs_async(atomic_attacks=atomic_attacks) candidate_results = [ result for name in candidate_names for result in self._cached_results_by_name.get(name, []) ] - compatible_parent_ids = self._get_compatible_cache_parent_ids(results=candidate_results) + compatible_parent_ids = await self._get_compatible_cache_parent_ids_async(results=candidate_results) reusable: dict[str, list[AttackResult]] = {} for attack in atomic_attacks: @@ -788,7 +790,7 @@ def _collect_reusable_cached_results(self, *, atomic_attacks: list[AtomicAttack] ] return reusable - def _get_compatible_cache_parent_ids(self, *, results: list[AttackResult]) -> set[str]: + async def _get_compatible_cache_parent_ids_async(self, *, results: list[AttackResult]) -> set[str]: """ Return parent scenario IDs produced by this benchmark version. @@ -806,7 +808,7 @@ def _get_compatible_cache_parent_ids(self, *, results: list[AttackResult]) -> se if not parent_ids: return set() try: - parent_results = self._memory.get_scenario_results( + parent_results = await self._memory.get_scenario_results_async( scenario_result_ids=parent_ids, scenario_name=type(self).__name__, scenario_version=self.VERSION, @@ -859,7 +861,7 @@ def _get_result_scorer_eval_hash(*, result: AttackResult) -> str | None: scorer_identifier = attack_identifier.get_child("objective_scorer") if attack_identifier else None return ScorerEvaluationIdentifier(scorer_identifier).eval_hash if scorer_identifier else None - def _persist_precomputed_cached_results(self) -> None: + async def _persist_precomputed_cached_results_async(self) -> None: """ Copy reusable results into the current scenario result. @@ -890,10 +892,10 @@ def _persist_precomputed_cached_results(self) -> None: }, ) ) - self._memory.add_attack_results_to_memory(attack_results=copies) + (await self._memory.add_attack_results_to_memory_async(attack_results=copies)) self._precomputed_cached_results = {} - def _collect_cached_completion_pairs(self, *, atomic_attacks: list[AtomicAttack]) -> set[str]: + async def _collect_cached_completion_pairs_async(self, *, atomic_attacks: list[AtomicAttack]) -> set[str]: """ Return the set of ``atomic_attack_name`` values already cached for this scenario's objective target. @@ -961,7 +963,7 @@ def _collect_cached_completion_pairs(self, *, atomic_attacks: list[AtomicAttack] raw_results_by_hash: dict[str, list[AttackResult]] = {} try: for technique_eval_hash in set().union(*lookup_hashes_by_name.values()) if lookup_hashes_by_name else set(): - raw_results_by_hash[technique_eval_hash] = get_cached_results_for_technique( + raw_results_by_hash[technique_eval_hash] = await get_cached_results_for_technique_async( self._memory, technique_eval_hash=technique_eval_hash, objective_target_eval_hash=objective_target_eval_hash, diff --git a/pyrit/scenario/scenarios/garak/prompt_inject.py b/pyrit/scenario/scenarios/garak/prompt_inject.py index e4711b1dc3..2d595b1c00 100644 --- a/pyrit/scenario/scenarios/garak/prompt_inject.py +++ b/pyrit/scenario/scenarios/garak/prompt_inject.py @@ -261,7 +261,7 @@ async def _resolve_seed_groups_by_dataset_async( self._objective_scorer_identifier = self._objective_scorer.get_identifier() self._dataset_config = config groups = await config.get_attack_groups_by_dataset_async(apply_sampling=apply_sampling) - self._technique_templates = self._load_technique_templates() + self._technique_templates = await self._load_technique_templates_async() return groups async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list[AtomicAttack]: @@ -357,7 +357,7 @@ def _get_promptinject_dataset_config(self, *, goal_texts: Sequence[str]) -> Prom config._set_goal_texts(goal_texts=goal_texts) return config - def _load_technique_templates(self) -> dict[str, SeedPrompt]: + async def _load_technique_templates_async(self) -> dict[str, SeedPrompt]: """ Load the selected technique templates from memory. @@ -367,7 +367,7 @@ def _load_technique_templates(self) -> dict[str, SeedPrompt]: Raises: DatasetConstraintError: If a selected technique has no template. """ - seeds = CentralMemory.get_memory_instance().get_seeds(dataset_name=self.TECHNIQUE_DATASET_NAME) + seeds = await CentralMemory.get_memory_instance().get_seeds_async(dataset_name=self.TECHNIQUE_DATASET_NAME) templates = {seed.name: seed for seed in seeds if isinstance(seed, SeedPrompt) and seed.name} selected = {technique.value for technique in self._scenario_techniques} missing = selected - templates.keys() diff --git a/pyrit/scenario/scenarios/garak/system_prompt_extraction.py b/pyrit/scenario/scenarios/garak/system_prompt_extraction.py index 8d654dd93e..2c2eb5058e 100644 --- a/pyrit/scenario/scenarios/garak/system_prompt_extraction.py +++ b/pyrit/scenario/scenarios/garak/system_prompt_extraction.py @@ -148,7 +148,7 @@ def __init__( scenario_result_id=scenario_result_id, ) - def _load_system_prompts(self) -> list[str]: + async def _load_system_prompts_async(self) -> list[str]: """ Load the real system prompts (the *what*) from the configured datasets in memory. @@ -159,13 +159,13 @@ def _load_system_prompts(self) -> list[str]: rng = random.Random(self._random_seed) system_prompts: list[str] = [] for name in (DATASET_DRH_SYSTEM_PROMPTS, DATASET_TM_SYSTEM_PROMPTS): - values = [seed.value for seed in memory.get_seeds(dataset_name=name)] + values = [seed.value for seed in (await memory.get_seeds_async(dataset_name=name))] if len(values) > self._system_prompt_subsample: values = rng.sample(values, self._system_prompt_subsample) system_prompts.extend(values) return system_prompts - def _load_templates_by_category(self) -> dict[str, list[str]]: + async def _load_templates_by_category_async(self) -> dict[str, list[str]]: """ Load the extraction templates (the *how*) from memory, grouped by ``technique`` metadata. @@ -174,7 +174,7 @@ def _load_templates_by_category(self) -> dict[str, list[str]]: """ memory = CentralMemory.get_memory_instance() templates_by_category: dict[str, list[str]] = {} - for seed in memory.get_seeds(dataset_name=DATASET_EXTRACTION_TEMPLATES): + for seed in await memory.get_seeds_async(dataset_name=DATASET_EXTRACTION_TEMPLATES): category = (seed.metadata or {}).get("technique") if not category: continue @@ -205,8 +205,8 @@ async def _resolve_seed_groups_by_dataset_async( ValueError: If no system prompts or templates were found in memory. """ await self._dataset_config._collect_named_seeds_async() - system_prompts = self._load_system_prompts() - templates_by_category = self._load_templates_by_category() + system_prompts = await self._load_system_prompts_async() + templates_by_category = await self._load_templates_by_category_async() selected_categories = {technique.value for technique in self._scenario_techniques} diff --git a/pyrit/scenario/scenarios/garak/web_injection.py b/pyrit/scenario/scenarios/garak/web_injection.py index e2d4af1ee5..dd117ae605 100644 --- a/pyrit/scenario/scenarios/garak/web_injection.py +++ b/pyrit/scenario/scenarios/garak/web_injection.py @@ -6,7 +6,6 @@ from __future__ import annotations -import asyncio import logging import random from typing import TYPE_CHECKING, ClassVar @@ -268,7 +267,7 @@ def __init__( scenario_result_id=scenario_result_id, ) - def _load_dataset_values(self) -> dict[str, list[str]]: + async def _load_dataset_values_async(self) -> dict[str, list[str]]: """ Load the raw seed values for each configured dataset, keyed by dataset name. @@ -283,7 +282,7 @@ def _load_dataset_values(self) -> dict[str, list[str]]: self.DATASET_WEB_HTML_JS, self.DATASET_NORMAL_INSTRUCTIONS, ): - seeds = memory.get_seeds(dataset_name=name) + seeds = await memory.get_seeds_async(dataset_name=name) values[name] = [seed.value for seed in seeds] return values @@ -537,7 +536,7 @@ async def _estimate_run_size_async(self) -> ScenarioRunSizeEstimate: Returns: ScenarioRunSizeEstimate: Exact synthesized-population estimate. """ - dataset_values = await asyncio.to_thread(self._load_dataset_values) + dataset_values = await self._load_dataset_values_async() seed_groups_by_technique = self._build_synthesized_seed_groups(dataset_values=dataset_values) datasets = [ ScenarioDatasetSummary( @@ -609,7 +608,7 @@ async def _resolve_seed_groups_by_dataset_async( ValueError: If no prompts were generated for any selected technique. """ await self._dataset_config._collect_named_seeds_async() - dataset_values = await asyncio.to_thread(self._load_dataset_values) + dataset_values = await self._load_dataset_values_async() return self._build_synthesized_seed_groups(dataset_values=dataset_values) async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list[AtomicAttack]: diff --git a/pyrit/score/batch_scorer.py b/pyrit/score/batch_scorer.py index 9367336d59..44627bb61c 100644 --- a/pyrit/score/batch_scorer.py +++ b/pyrit/score/batch_scorer.py @@ -87,7 +87,7 @@ async def score_responses_by_filters_async( ValueError: If no entries match the provided filters. """ message_pieces: Sequence[MessagePiece] = [] - message_pieces = self._memory.get_message_pieces( + message_pieces = await self._memory.get_message_pieces_async( conversation_id=conversation_id, prompt_ids=prompt_ids, labels=labels, diff --git a/pyrit/score/conversation_scorer.py b/pyrit/score/conversation_scorer.py index 2520c9a060..4eb4dfb341 100644 --- a/pyrit/score/conversation_scorer.py +++ b/pyrit/score/conversation_scorer.py @@ -117,7 +117,9 @@ async def _score_prepared_message_async( # Retrieve the full conversation from memory using the conversation_id conversation = ( - self._memory.get_conversation_messages(conversation_id=conversation_id) if conversation_id else [] + (await self._memory.get_conversation_messages_async(conversation_id=conversation_id)) + if conversation_id + else [] ) if not conversation: diff --git a/pyrit/score/float_scale/roblox_pii_scorer.py b/pyrit/score/float_scale/roblox_pii_scorer.py index 691e04c92a..2e4389fe50 100644 --- a/pyrit/score/float_scale/roblox_pii_scorer.py +++ b/pyrit/score/float_scale/roblox_pii_scorer.py @@ -5,7 +5,6 @@ from __future__ import annotations -import asyncio import math from enum import Enum from typing import TYPE_CHECKING, ClassVar @@ -211,10 +210,7 @@ async def _get_context_pieces_async(self, *, message_piece: MessagePiece) -> lis if not message_piece.conversation_id or message_piece.not_in_memory: return [message_piece] - pieces = await asyncio.to_thread( - self._memory.get_message_pieces, - conversation_id=message_piece.conversation_id, - ) + pieces = await self._memory.get_message_pieces_async(conversation_id=message_piece.conversation_id) return self._select_context_pieces(message_piece=message_piece, pieces=pieces) def _select_context_pieces( diff --git a/pyrit/score/float_scale/system_prompt_extraction_scorer.py b/pyrit/score/float_scale/system_prompt_extraction_scorer.py index c9b1e3f0c7..efc73534b2 100644 --- a/pyrit/score/float_scale/system_prompt_extraction_scorer.py +++ b/pyrit/score/float_scale/system_prompt_extraction_scorer.py @@ -94,7 +94,7 @@ def _build_identifier(self) -> ComponentIdentifier: }, ) - def _get_system_prompt(self, conversation_id: str | None) -> str | None: + async def _get_system_prompt_async(self, conversation_id: str | None) -> str | None: """ Read the known system prompt from the scored conversation's prepended system message. @@ -108,7 +108,7 @@ def _get_system_prompt(self, conversation_id: str | None) -> str | None: return None memory = CentralMemory.get_memory_instance() - messages = memory.get_conversation_messages(conversation_id=conversation_id) + messages = await memory.get_conversation_messages_async(conversation_id=conversation_id) for message in messages: if message.api_role == "system": return message.get_value() @@ -162,7 +162,7 @@ async def _score_piece_async(self, message_piece: MessagePiece, *, objective: st list[Score]: A single float_scale Score in [0, 1] measuring system-prompt leakage. """ response = message_piece.converted_value - system_prompt = self._get_system_prompt(message_piece.conversation_id) + system_prompt = await self._get_system_prompt_async(message_piece.conversation_id) if not system_prompt: overlap = 0.0 diff --git a/pyrit/score/llm_scoring.py b/pyrit/score/llm_scoring.py index fecbaed396..5aa3867725 100644 --- a/pyrit/score/llm_scoring.py +++ b/pyrit/score/llm_scoring.py @@ -36,7 +36,7 @@ _get_current_scoring_expectation, _has_observation_collection, _ObservationEvidence, - _scored_evidence_digest, + _scored_evidence_digest_async, ) if TYPE_CHECKING: @@ -178,11 +178,13 @@ async def _run_llm_scoring_async( else None ) scored_evidence_digest = ( - _scored_evidence_digest( - scorable=observation_scorable, - scored_piece_id=cast("uuid.UUID", scored_piece_id), - memory=resolved_normalizer.memory, - scored_message_piece=scored_message_piece, + ( + await _scored_evidence_digest_async( + scorable=observation_scorable, + scored_piece_id=cast("uuid.UUID", scored_piece_id), + memory=resolved_normalizer.memory, + scored_message_piece=scored_message_piece, + ) ) if observation_scorable is not None and (not isinstance(observation_scorable, MessageScorable) or scored_message_piece is not None) @@ -194,10 +196,7 @@ async def _run_llm_scoring_async( ) if system_prompt is not None: - chat_target.set_system_prompt( - system_prompt=system_prompt, - conversation_id=conversation_id, - ) + (await chat_target.set_system_prompt_async(system_prompt=system_prompt, conversation_id=conversation_id)) # Forward the JSON-response request (format and any schema together) via the handler's # canonical config; the target's normalization pipeline omits the schema when it cannot # natively enforce one. diff --git a/pyrit/score/message_scorable_resolver.py b/pyrit/score/message_scorable_resolver.py index bd53bc0a40..a2626b7cb5 100644 --- a/pyrit/score/message_scorable_resolver.py +++ b/pyrit/score/message_scorable_resolver.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.models import ( ContentEntryScorable, ContentScorable, @@ -39,6 +41,11 @@ def resolve(self, *, scorable: Scorable, memory: MemoryInterface) -> Message: ValueError: If referenced pieces or content are missing, or the pieces do not form one message. """ + print_deprecation_message( + old_item="MessageScorableResolver.resolve", + new_item="MessageScorableResolver.resolve_async", + removed_in="1.4.0", + ) if isinstance(scorable, MessageScorable): return self._resolve_message_reference(scorable=scorable, memory=memory) if isinstance(scorable, ContentEntryScorable): @@ -49,6 +56,36 @@ def resolve(self, *, scorable: Scorable, memory: MemoryInterface) -> Message: f"Message scorers cannot score {type(scorable).__name__}. Pass a MessageScorable or a ContentScorable." ) + @legacy_sync_override(lambda: MessageScorableResolver.resolve) + async def resolve_async(self, *, scorable: Scorable, memory: MemoryInterface) -> Message: + """ + Resolve supported scorables to the message view consumed by message scorers. + + Args: + scorable (Scorable): A message reference, loose content, or a reference to + loose content already stored in memory. + memory (MemoryInterface): Memory used to resolve references. + + Returns: + Message: The message view to score. + + Raises: + TypeError: If the scorable is not message-shaped. + ValueError: If referenced pieces or content are missing, or the pieces do not + form one message. + """ + if isinstance(scorable, MessageScorable): + return await self._resolve_message_reference_async(scorable=scorable, memory=memory) + if isinstance(scorable, ContentEntryScorable): + return self._adapt_content( + scorable=(await self._resolve_content_reference_async(scorable=scorable, memory=memory)) + ) + if isinstance(scorable, ContentScorable): + return self._adapt_content(scorable=scorable) + raise TypeError( + f"Message scorers cannot score {type(scorable).__name__}. Pass a MessageScorable or a ContentScorable." + ) + @staticmethod def _resolve_content_reference(*, scorable: ContentEntryScorable, memory: MemoryInterface) -> ContentScorable: content = memory.get_scorable_content(content_ids=[scorable.content_id]).get(scorable.content_id) @@ -56,6 +93,15 @@ def _resolve_content_reference(*, scorable: ContentEntryScorable, memory: Memory raise ValueError(f"No stored scorable content found for id {scorable.content_id}.") return content + @staticmethod + async def _resolve_content_reference_async( + *, scorable: ContentEntryScorable, memory: MemoryInterface + ) -> ContentScorable: + content = (await memory.get_scorable_content_async(content_ids=[scorable.content_id])).get(scorable.content_id) + if content is None: + raise ValueError(f"No stored scorable content found for id {scorable.content_id}.") + return content + @staticmethod def _resolve_message_reference(*, scorable: MessageScorable, memory: MemoryInterface) -> Message: pieces = memory.get_message_pieces(prompt_ids=list(scorable.message_piece_ids)) @@ -79,6 +125,29 @@ def _resolve_message_reference(*, scorable: MessageScorable, memory: MemoryInter resolved.message_pieces = [by_id[str(piece_id)] for piece_id in scorable.message_piece_ids] return resolved + @staticmethod + async def _resolve_message_reference_async(*, scorable: MessageScorable, memory: MemoryInterface) -> Message: + pieces = await memory.get_message_pieces_async(prompt_ids=list(scorable.message_piece_ids)) + wanted = {str(piece_id) for piece_id in scorable.message_piece_ids} + pieces = [piece for piece in pieces if str(piece.id) in wanted] + found = {str(piece.id) for piece in pieces} + missing = [str(piece_id) for piece_id in scorable.message_piece_ids if str(piece_id) not in found] + if missing: + raise ValueError(f"No message pieces found in memory for ids {missing}.") + + conversations = group_message_pieces_into_conversations(pieces) + messages = [message for conversation in conversations for message in conversation] + if len(messages) != 1: + raise ValueError( + f"Expected the referenced pieces to form exactly one message, got {len(messages)}. " + "Reference pieces from a single message." + ) + + resolved = messages[0] + by_id = {str(piece.id): piece for piece in resolved.message_pieces} + resolved.message_pieces = [by_id[str(piece_id)] for piece_id in scorable.message_piece_ids] + return resolved + @staticmethod def _adapt_content(*, scorable: ContentScorable) -> Message: piece = MessagePiece( diff --git a/pyrit/score/message_scorer.py b/pyrit/score/message_scorer.py index 2415d6758f..eb843e40e3 100644 --- a/pyrit/score/message_scorer.py +++ b/pyrit/score/message_scorer.py @@ -105,6 +105,11 @@ def extract_objective_from_previous_turn(*, message: Message, memory: MemoryInte Returns: str: The previous turn's text, or an empty string when there is none. """ + print_deprecation_message( + old_item="extract_objective_from_previous_turn", + new_item="extract_objective_from_previous_turn_async", + removed_in="1.4.0", + ) if not message.message_pieces: return "" @@ -130,6 +135,49 @@ def extract_objective_from_previous_turn(*, message: Message, memory: MemoryInte ) +async def extract_objective_from_previous_turn_async(*, message: Message, memory: MemoryInterface) -> str: + """ + Read the text of the turn before an assistant message and use it as the objective. + + .. deprecated:: + This conflates scoring with building an expectation. What to look for belongs to + the caller that builds the ``ScoringExpectation``, not to the scorer. It exists only + to support the deprecated ``infer_objective_from_request`` parameter, and both are + removed in the next major release. Resolve the objective at the call site and pass + it on the expectation instead. + + Args: + message (Message): The assistant message whose previous turn supplies the objective. + memory (MemoryInterface): Memory holding the conversation. + + Returns: + str: The previous turn's text, or an empty string when there is none. + """ + if not message.message_pieces: + return "" + + scored_piece = message.get_piece() + + if scored_piece.api_role != "assistant": + return "" + + # The request is the turn before the response being scored, not before whatever the + # conversation has grown to since. Scoring an earlier response must not read the latest turn. + previous_sequence = scored_piece.sequence - 1 + if previous_sequence < 0: + return "" + + conversation = await memory.get_message_pieces_async(conversation_id=scored_piece.conversation_id) + + return "\n".join( + [ + piece.original_value + for piece in conversation + if piece.sequence == previous_sequence and piece.original_value_data_type == "text" + ] + ) + + def _readable_pieces(*, message: Message, should_score_blocked_content: bool) -> list[MessagePiece]: """ Select the pieces of a message that a scorer can read. @@ -438,7 +486,9 @@ async def _score_message_root_async( ValueError: If neither a message nor a scorable is available. """ context_scorable = ( - self._context_scorable_from_message(message=message) if message is not None else cast("Scorable", scorable) + (await self._context_scorable_from_message_async(message=message)) + if message is not None + else cast("Scorable", scorable) ) with _scoring_collection() as collector: with _scoring_scorable_context(context_scorable): @@ -451,7 +501,7 @@ async def _score_message_root_async( infer_objective_from_request=infer_objective_from_request, anchor=self._scorable_from_message( message, - persisted_piece_ids=self._get_persisted_piece_ids(message=message), + persisted_piece_ids=(await self._get_persisted_piece_ids_async(message=message)), ), role_filter=role_filter, skip_on_error_result=skip_on_error_result, @@ -482,7 +532,7 @@ async def _score_nested_message_async( list[Score]: Validated child results retained for the public caller to persist. """ self._validate_expectation(expectation=expectation) - anchor = self._context_scorable_from_message(message=message) + anchor = await self._context_scorable_from_message_async(message=message) with _scoring_scorable_context(anchor), _scoring_expectation_context(expectation): scores = await self._score_resolved_message_async( message=message, @@ -495,7 +545,7 @@ async def _score_nested_message_async( _collect_scores(scores) return scores - def _context_scorable_from_message(self, *, message: Message) -> Scorable | None: + async def _context_scorable_from_message_async(self, *, message: Message) -> Scorable | None: """ Build a durable observation anchor for the in-hand message API. @@ -503,7 +553,7 @@ def _context_scorable_from_message(self, *, message: Message) -> Scorable | None Scorable | None: The durable message or content anchor, if one can be represented. """ pieces = message.message_pieces - persisted = self._memory.get_message_pieces(prompt_ids=[piece.id for piece in pieces]) + persisted = await self._memory.get_message_pieces_async(prompt_ids=[piece.id for piece in pieces]) persisted_by_id = {str(piece.id): piece for piece in persisted} matches_storage = all( str(piece.id) in persisted_by_id @@ -604,7 +654,7 @@ async def score_prompts_batch_async( if infer_objective_from_request: resolved_objectives = [ - objective or extract_objective_from_previous_turn(message=message, memory=self._memory) + objective or (await extract_objective_from_previous_turn_async(message=message, memory=self._memory)) for message, objective in zip(messages, resolved_objectives, strict=True) ] @@ -904,7 +954,7 @@ async def _score_message_scorable_async( Raises: TypeError: If the scorable is not message-shaped. """ - message = self._message_resolver.resolve(scorable=scorable, memory=self._memory) + message = await self._message_resolver.resolve_async(scorable=scorable, memory=self._memory) return await self._score_resolved_message_async( message=message, expectation=expectation, @@ -950,7 +1000,7 @@ async def _score_resolved_message_async( objective = expectation.objective if expectation else None if infer_objective_from_request and (not objective): - objective = extract_objective_from_previous_turn(message=message, memory=self._memory) + objective = await extract_objective_from_previous_turn_async(message=message, memory=self._memory) effective_expectation = expectation if expectation is None and objective is not None: @@ -981,11 +1031,10 @@ async def _score_resolved_message_async( scoring_message = self._build_scoring_message(message=message) if scoring_message is None: scores = self._build_fallback_score(message=message, objective=objective) - self._finalize_message_scores( - message=message, - scores=scores, - anchor=anchor, - expectation=effective_expectation, + ( + await self._finalize_message_scores_async( + message=message, scores=scores, anchor=anchor, expectation=effective_expectation + ) ) return scores @@ -1048,11 +1097,13 @@ async def _score_resolved_message_async( if not scores and scoring_message.message_pieces and not self._get_supported_pieces(scoring_message): scores = self._build_fallback_score(message=message, objective=objective) - self._finalize_message_scores( - message=scoring_message, - scores=scores, - anchor=anchor if scoring_view_matches_acquired_message else None, - expectation=effective_expectation, + ( + await self._finalize_message_scores_async( + message=scoring_message, + scores=scores, + anchor=anchor if scoring_view_matches_acquired_message else None, + expectation=effective_expectation, + ) ) return scores @@ -1067,7 +1118,7 @@ def _validate_scoring_message(self, *, message: Message, objective: str | None) """ self._validator.validate(message, objective=objective) - def _finalize_message_scores( + async def _finalize_message_scores_async( self, *, message: Message, @@ -1076,7 +1127,7 @@ def _finalize_message_scores( expectation: ScoringExpectation | None, ) -> None: """Apply legacy and canonical evidence anchors to completed message scores.""" - persisted_piece_ids = self._get_persisted_piece_ids(message=message) + persisted_piece_ids = await self._get_persisted_piece_ids_async(message=message) self._drop_ephemeral_score_links( message=message, scores=scores, @@ -1375,14 +1426,14 @@ def _get_supported_pieces(self, message: Message) -> list[MessagePiece]: piece for piece in message.message_pieces if self._validator.is_message_piece_supported(message_piece=piece) ] - def _get_persisted_piece_ids(self, *, message: Message) -> set[uuid.UUID]: + async def _get_persisted_piece_ids_async(self, *, message: Message) -> set[uuid.UUID]: """Return matching message IDs, allowing storage to change timestamp precision.""" candidate_ids = [piece.id for piece in message.message_pieces if not piece.not_in_memory] if not candidate_ids: return set() - stored_pieces = self._memory.get_message_pieces( - prompt_ids=[str(piece_id) for piece_id in candidate_ids], + stored_pieces = await self._memory.get_message_pieces_async( + prompt_ids=[str(piece_id) for piece_id in candidate_ids] ) supplied_by_id = {piece.id: piece for piece in message.message_pieces} return { diff --git a/pyrit/score/observation/execution.py b/pyrit/score/observation/execution.py index 0a5f4be347..743ad130b5 100644 --- a/pyrit/score/observation/execution.py +++ b/pyrit/score/observation/execution.py @@ -70,6 +70,38 @@ def _scored_evidence_digest( raise NonReplayableObservationError(str(error)) from error +async def _scored_evidence_digest_async( + *, + scorable: ScorableUnion, + scored_piece_id: uuid.UUID, + memory: MemoryInterface, + scored_message_piece: MessagePiece | None = None, +) -> str | None: + """ + Resolve and hash the canonical input evidence used for one judgment. + + Returns: + str | None: The digest, or None when media replay is deferred. + + Raises: + NonReplayableObservationError: If the scored evidence cannot be resolved. + """ + if isinstance(scorable, MessageScorable) and scored_message_piece is None: + pieces = await memory.get_message_pieces_async(prompt_ids=[scored_piece_id]) + scored_message_piece = next((piece for piece in pieces if piece.id == scored_piece_id), None) + content_id = scorable.content_id if isinstance(scorable, ContentEntryScorable) else None + stored_content = await _load_content_evidence_async(memory=memory, content_id=content_id) + try: + return _resolved_scored_evidence_digest( + scorable=scorable, + scored_piece_id=scored_piece_id, + scored_piece=scored_message_piece, + stored_content=stored_content, + ) + except ValueError as error: + raise NonReplayableObservationError(str(error)) from error + + def _load_content_evidence( *, memory: MemoryInterface, content_id: uuid.UUID | None ) -> tuple[ContentScorable, str] | None: @@ -86,6 +118,22 @@ def _load_content_evidence( return (content, digest) if content is not None and digest is not None else None +async def _load_content_evidence_async( + *, memory: MemoryInterface, content_id: uuid.UUID | None +) -> tuple[ContentScorable, str] | None: + """ + Load stored content and its hash. + + Returns: + tuple[ContentScorable, str] | None: The evidence, or None if unreferenced or missing. + """ + if content_id is None: + return None + content = (await memory.get_scorable_content_async(content_ids=[content_id])).get(content_id) + digest = (await memory.get_scorable_content_hashes_async(content_ids=[content_id])).get(content_id) + return (content, digest) if content is not None and digest is not None else None + + class _ScoringCollector: """Observations and intermediate judgments created during one root scoring operation.""" @@ -300,7 +348,7 @@ def __init__(self, *, memory: MemoryInterface) -> None: """Initialize the resolver with the observation store.""" self._memory = memory - def resolve(self, *, observation: Observation) -> _ObservationEvidence: + async def resolve_async(self, *, observation: Observation) -> _ObservationEvidence: """ Resolve an observation's managed response references. @@ -313,9 +361,11 @@ def resolve(self, *, observation: Observation) -> _ObservationEvidence: payload = observation.payload if isinstance(payload, ToolEventsObservationPayload): return payload - pieces = self._memory.get_message_pieces(prompt_ids=list(observation.evidence_message_piece_ids)) + pieces = await self._memory.get_message_pieces_async(prompt_ids=list(observation.evidence_message_piece_ids)) pieces_by_id = {piece.id: piece for piece in pieces} - stored_content = _load_content_evidence(memory=self._memory, content_id=observation.scorable_content_id) + stored_content = await _load_content_evidence_async( + memory=self._memory, content_id=observation.scorable_content_id + ) try: observation.validate_evidence( message_pieces=pieces_by_id, diff --git a/pyrit/score/observation/message_trace_resolver.py b/pyrit/score/observation/message_trace_resolver.py index 5cfaaf9c0f..59db5de124 100644 --- a/pyrit/score/observation/message_trace_resolver.py +++ b/pyrit/score/observation/message_trace_resolver.py @@ -14,7 +14,7 @@ from pyrit.memory import MemoryInterface -def resolve_message_trace_scope( +async def resolve_message_trace_scope_async( *, scorable: MessageScorable, memory: MemoryInterface ) -> tuple[TraceScorable | None, bool]: """ @@ -26,13 +26,13 @@ def resolve_message_trace_scope( Raises: ValueError: If the message is not stored or its request metadata is invalid. """ - message = MessageScorableResolver().resolve(scorable=scorable, memory=memory) + message = await MessageScorableResolver().resolve_async(scorable=scorable, memory=memory) piece = message.message_pieces[0] if not piece.conversation_id or piece.sequence < 0: raise ValueError("Trace resolution requires a stored conversation and message sequence.") requests = [ request - for request in memory.get_message_pieces(conversation_id=piece.conversation_id) + for request in await memory.get_message_pieces_async(conversation_id=piece.conversation_id) if request.sequence <= piece.sequence and ( request.prompt_metadata.get(RequestTraceContext.REQUEST_METADATA_KEY) == 1 diff --git a/pyrit/score/scorer.py b/pyrit/score/scorer.py index cda0df7ce2..45439c4057 100644 --- a/pyrit/score/scorer.py +++ b/pyrit/score/scorer.py @@ -87,7 +87,7 @@ async def _legacy_score_scorable_async( expectation=expectation, replacement="a MessageScorer expectation-aware hook" ) resolver = getattr(self, "_message_resolver", None) or MessageScorableResolver() - message = resolver.resolve(scorable=scorable, memory=self._memory) + message = await resolver.resolve_async(scorable=scorable, memory=self._memory) legacy_score_async = self._score_async # type: ignore[ty:unresolved-attribute] with _scoring_message_context(message): scores: list[Score] = await legacy_score_async( @@ -732,7 +732,7 @@ async def _validate_and_persist_scores_async( scores=scores, observations=observations, intermediate_scores=intermediate_scores ) else: - self._memory.add_scores_to_memory( + await self._memory.add_scores_to_memory_async( scores=scores, observations=observations, intermediate_scores=intermediate_scores ) return scores @@ -806,7 +806,7 @@ async def score_observation_async( NonReplayableObservationError: If this scorer or payload cannot replay. """ expectation = self.prepare_expectation(expectation=expectation) - stored_observations = self._memory.get_observations(observation_ids=[observation.id]) + stored_observations = await self._memory.get_observations_async(observation_ids=[observation.id]) if not stored_observations: raise NonReplayableObservationError(f"Observation {observation.id} is not stored in memory.") stored_observation = stored_observations[0] @@ -814,7 +814,7 @@ async def score_observation_async( raise NonReplayableObservationError( f"Observation {observation.id} does not match its canonical stored evidence." ) - evidence = _ObservationEvidenceResolver(memory=self._memory).resolve(observation=observation) + evidence = await _ObservationEvidenceResolver(memory=self._memory).resolve_async(observation=observation) scores = self._score_observation( observation=observation, evidence=evidence, @@ -1262,7 +1262,7 @@ def scale_value_float(self, value: float, min_value: float, max_value: float) -> return (value - min_value) / (max_value - min_value) - def _extract_objective_from_response(self, response: Message) -> str: + async def _extract_objective_from_response_async(self, response: Message) -> str: """ Read the objective from the turn before an assistant response. @@ -1274,11 +1274,11 @@ def _extract_objective_from_response(self, response: Message) -> str: Returns: str: The objective extracted from the response, or empty string if not found. """ - from pyrit.score.message_scorer import extract_objective_from_previous_turn + from pyrit.score.message_scorer import extract_objective_from_previous_turn_async print_deprecation_message( old_item="Scorer._extract_objective_from_response", new_item="pyrit.score.message_scorer.extract_objective_from_previous_turn", removed_in=LEGACY_SCORE_ASYNC_REMOVED_IN, ) - return extract_objective_from_previous_turn(message=response, memory=self._memory) + return await extract_objective_from_previous_turn_async(message=response, memory=self._memory) diff --git a/pyrit/score/scorer_evaluation/scorer_evaluator.py b/pyrit/score/scorer_evaluation/scorer_evaluator.py index 080486aa59..5e79efea36 100644 --- a/pyrit/score/scorer_evaluation/scorer_evaluator.py +++ b/pyrit/score/scorer_evaluation/scorer_evaluator.py @@ -16,7 +16,7 @@ from pyrit.models import MessageScorable, Score, ScoringExpectation, UndeterminedScoreError from pyrit.models.harm_category import HarmCategory, normalize_harm_category_key from pyrit.prompt_target.batch_helper import batch_task_async -from pyrit.score.message_scorer import extract_objective_from_previous_turn +from pyrit.score.message_scorer import extract_objective_from_previous_turn_async from pyrit.score.scorer_evaluation.human_labeled_dataset import ( HarmHumanLabeledEntry, HumanLabeledDataset, @@ -379,11 +379,13 @@ async def evaluate_dataset_async( ValueError: If the labeled_dataset is invalid. """ # Validate dataset and extract data - assistant_responses, human_scores_list, objectives = self._validate_and_extract_data(labeled_dataset) + assistant_responses, human_scores_list, objectives = await self._validate_and_extract_data_async( + labeled_dataset + ) # Harm datasets carry no objective, so the previous turn stands in for one. resolved_objectives = objectives or [ - extract_objective_from_previous_turn(message=response, memory=self.scorer._memory) + (await extract_objective_from_previous_turn_async(message=response, memory=self.scorer._memory)) for response in assistant_responses ] @@ -548,7 +550,7 @@ def _select_evaluation_score(*, scores: list[Score], harm_category: str | None) ) @abc.abstractmethod - def _validate_and_extract_data( + async def _validate_and_extract_data_async( self, labeled_dataset: HumanLabeledDataset, ) -> tuple[list[Message], list[list[float]], list[str] | None]: @@ -565,6 +567,7 @@ def _validate_and_extract_data( Raises: ValueError: If the dataset is invalid for this evaluator. """ + raise NotImplementedError @abc.abstractmethod def _compute_metrics( @@ -631,7 +634,7 @@ class HarmScorerEvaluator(ScorerEvaluator): expected_metrics_type = MetricsType.HARM - def _validate_and_extract_data( + async def _validate_and_extract_data_async( self, labeled_dataset: HumanLabeledDataset, ) -> tuple[list[Message], list[list[float]], list[str] | None]: @@ -661,7 +664,7 @@ def _validate_and_extract_data( harm_entry = cast("HarmHumanLabeledEntry", entry) assistant_messages: list[Message] = [] for message in harm_entry.conversation: - self.scorer._memory.add_message_to_memory(request=message) + (await self.scorer._memory.add_message_to_memory_async(request=message)) if message.api_role == "assistant": assistant_messages.append(message) if len(assistant_messages) != 1: @@ -786,7 +789,7 @@ class ObjectiveScorerEvaluator(ScorerEvaluator): expected_metrics_type = MetricsType.OBJECTIVE - def _validate_and_extract_data( + async def _validate_and_extract_data_async( self, labeled_dataset: HumanLabeledDataset, ) -> tuple[list[Message], list[list[float]], list[str] | None]: @@ -814,7 +817,7 @@ def _validate_and_extract_data( for entry in labeled_dataset.entries: objective_entry = cast("ObjectiveHumanLabeledEntry", entry) for message in objective_entry.conversation: - self.scorer._memory.add_message_to_memory(request=message) + (await self.scorer._memory.add_message_to_memory_async(request=message)) assistant_responses.append(message) human_scores_list.append([float(score) for score in objective_entry.human_scores]) objectives.append(objective_entry.objective) diff --git a/pyrit/score/true_false/decoding_scorer.py b/pyrit/score/true_false/decoding_scorer.py index e6f57a2c64..280f0d9895 100644 --- a/pyrit/score/true_false/decoding_scorer.py +++ b/pyrit/score/true_false/decoding_scorer.py @@ -79,7 +79,7 @@ async def _score_piece_async(self, message_piece: MessagePiece, *, objective: st whether any of the user piece values match the response. """ memory = CentralMemory.get_memory_instance() - user_request = memory.get_request_from_response(response=message_piece.to_message()) + user_request = await memory.get_request_from_response_async(response=message_piece.to_message()) match_found = False diff --git a/pyrit/score/true_false/gandalf_scorer.py b/pyrit/score/true_false/gandalf_scorer.py index 4b0b1be5a9..e45f0129cc 100644 --- a/pyrit/score/true_false/gandalf_scorer.py +++ b/pyrit/score/true_false/gandalf_scorer.py @@ -100,12 +100,13 @@ async def _check_for_password_in_conversation_async(self, conversation_id: str) ) scoring_conversation_id = str(uuid.uuid4()) - self._prompt_target.set_system_prompt( - system_prompt=system_prompt, - conversation_id=scoring_conversation_id, + ( + await self._prompt_target.set_system_prompt_async( + system_prompt=system_prompt, conversation_id=scoring_conversation_id + ) ) - conversation = self._memory.get_conversation_messages(conversation_id=conversation_id) + conversation = await self._memory.get_conversation_messages_async(conversation_id=conversation_id) if not conversation: raise ValueError(f"Conversation with ID {conversation_id} not found in memory.") diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index 32e9e46a5b..65f0d23b76 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -18,7 +18,7 @@ TraceScorable, ) from pyrit.score.observation.execution import NonReplayableObservationError, _collect_observation -from pyrit.score.observation.message_trace_resolver import resolve_message_trace_scope +from pyrit.score.observation.message_trace_resolver import resolve_message_trace_scope_async from pyrit.score.true_false.true_false_scorer import TrueFalseScorer if TYPE_CHECKING: @@ -69,7 +69,7 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin if not isinstance(scorable, (MessageScorable, TraceScorable)): raise TypeError("OtelToolCallScorer requires a MessageScorable or an explicit TraceScorable.") scope, correlation_complete = ( - resolve_message_trace_scope(scorable=scorable, memory=self._memory) + await resolve_message_trace_scope_async(scorable=scorable, memory=self._memory) if isinstance(scorable, MessageScorable) else (scorable, True) ) diff --git a/pyrit/score/true_false/wildguard_scorer.py b/pyrit/score/true_false/wildguard_scorer.py index a305f229b9..96104b80eb 100644 --- a/pyrit/score/true_false/wildguard_scorer.py +++ b/pyrit/score/true_false/wildguard_scorer.py @@ -3,7 +3,6 @@ from __future__ import annotations -import asyncio from contextvars import ContextVar from functools import partial from typing import Any, ClassVar @@ -243,9 +242,7 @@ async def _resolve_user_prompt_async(self, message_piece: MessagePiece) -> str | if not message_piece.conversation_id or message_piece.sequence < 1: return None - conversation = await asyncio.to_thread( - self._memory.get_message_pieces, conversation_id=message_piece.conversation_id - ) + conversation = await self._memory.get_message_pieces_async(conversation_id=message_piece.conversation_id) prior_user_pieces = [ piece for piece in conversation if piece.sequence < message_piece.sequence and piece.api_role == "user" ] diff --git a/pyrit/score/video_scorer.py b/pyrit/score/video_scorer.py index d47a45e007..5ab89744cb 100644 --- a/pyrit/score/video_scorer.py +++ b/pyrit/score/video_scorer.py @@ -194,7 +194,7 @@ async def _score_frames_async( memory = CentralMemory.get_memory_instance() for request in image_requests: - memory.add_message_to_memory(request=request) + (await memory.add_message_to_memory_async(request=request)) with _suppress_observation_collection(): frame_scores = await self.image_scorer._score_batch_nested_async( @@ -308,7 +308,7 @@ async def _score_video_audio_async( # Add to memory memory = CentralMemory.get_memory_instance() - memory.add_message_to_memory(request=audio_message) + (await memory.add_message_to_memory_async(request=audio_message)) with _suppress_observation_collection(): audio_scores = await audio_scorer._score_batch_nested_async( diff --git a/pyrit/setup/initialization.py b/pyrit/setup/initialization.py index 86c2de36ce..9c651af1ca 100644 --- a/pyrit/setup/initialization.py +++ b/pyrit/setup/initialization.py @@ -9,6 +9,7 @@ from pyrit.common.apply_defaults import reset_default_values from pyrit.common.random_context import configure_random_seed +from pyrit.common.singleton import Singleton from pyrit.memory import AzureSQLMemory, CentralMemory, MemoryInterface, SQLiteMemory from pyrit.setup.environment_loading import ( load_environment_async, @@ -205,61 +206,83 @@ async def initialize_pyrit_async( # (like prompt targets) that require central memory to be initialized memory: MemoryInterface + if memory_db_type not in get_args(MemoryDatabaseType): + raise ValueError( + f"Memory database type '{memory_db_type}' is not a supported type {get_args(MemoryDatabaseType)}" + ) + memory_class = AzureSQLMemory if memory_db_type == AZURE_SQL else SQLiteMemory + previous_memory = CentralMemory._memory_instance + cached_memory = Singleton._instances.get(memory_class) + if previous_memory is not None and previous_memory is not cached_memory: + raise ValueError("CentralMemory and the requested memory singleton disagree. Restart with one memory instance.") + if isinstance(cached_memory, SQLiteMemory) and (cached_memory.db_path == ":memory:") != ( + memory_db_type == IN_MEMORY + ): + raise ValueError( + "Cannot switch between in-memory and persistent SQLite. Restart with the requested memory type." + ) + if memory_db_type == IN_MEMORY: logger.info("Using in-memory SQLite database.") - memory = SQLiteMemory(db_path=":memory:", silent=silent, **memory_instance_kwargs) # type: ignore[ty:invalid-assignment] + memory = SQLiteMemory(db_path=":memory:", silent=silent, _defer_initialization=True, **memory_instance_kwargs) # type: ignore[ty:invalid-assignment] elif memory_db_type == SQLITE: logger.info("Using persistent SQLite database.") - memory = SQLiteMemory(silent=silent, **memory_instance_kwargs) # type: ignore[ty:invalid-assignment] - elif memory_db_type == AZURE_SQL: - logger.info("Using AzureSQL database.") - memory = AzureSQLMemory(silent=silent, **memory_instance_kwargs) # type: ignore[ty:invalid-assignment] + memory = SQLiteMemory(silent=silent, _defer_initialization=True, **memory_instance_kwargs) # type: ignore[ty:invalid-assignment] else: - raise ValueError( - f"Memory database type '{memory_db_type}' is not a supported type {get_args(MemoryDatabaseType)}" - ) + logger.info("Using AzureSQL database.") + memory = AzureSQLMemory(silent=silent, _defer_initialization=True, **memory_instance_kwargs) # type: ignore[ty:invalid-assignment] + await memory.initialize_async() CentralMemory.set_memory_instance(memory) - # Combine directly provided initializers with those loaded from scripts. - all_initializers: list[PyRITInitializer] = list(initializers) if initializers else [] - - # Load additional initializers from scripts — the registry owns turning - # external script files into initializer instances. - if initialization_scripts: - from pyrit.registry import InitializerRegistry - - registry = InitializerRegistry.get_registry_singleton() - script_paths = [pathlib.Path(script_path) for script_path in initialization_scripts] - for script_path in script_paths: + try: + # Combine directly provided initializers with those loaded from scripts. + all_initializers: list[PyRITInitializer] = list(initializers) if initializers else [] + + # Load additional initializers from scripts — the registry owns turning + # external script files into initializer instances. + if initialization_scripts: + from pyrit.registry import InitializerRegistry + + registry = InitializerRegistry.get_registry_singleton() + script_paths = [pathlib.Path(script_path) for script_path in initialization_scripts] + for script_path in script_paths: + try: + script_initializers = await asyncio.to_thread( + registry.create_from_script_paths, + script_paths=[script_path], + strict=raise_on_initializer_error, + ) + all_initializers.extend(script_initializers) + except Exception: + logger.exception("Error loading initializers from script %s", script_path) + if raise_on_initializer_error: + raise + + # When the caller supplies nothing, fall back to the default initializer set so a + # bare initialize_pyrit_async(...) yields a usable environment (core techniques + + # available default targets). Supplying any initializer/script means the caller owns + # setup, so defaults are skipped; load_defaults=False skips them even on a bare call. + if load_defaults and not all_initializers: + from pyrit.setup.initializers.targets import TargetInitializer + from pyrit.setup.initializers.techniques import TechniqueInitializer + + all_initializers = [TechniqueInitializer(), TargetInitializer()] + + # Execute all initializers in order + if all_initializers: + await _execute_initializers_async( + initializers=all_initializers, + raise_on_initializer_error=raise_on_initializer_error, + ) + except BaseException: + if cached_memory is None: try: - script_initializers = await asyncio.to_thread( - registry.create_from_script_paths, - script_paths=[script_path], - strict=raise_on_initializer_error, - ) - all_initializers.extend(script_initializers) - except Exception: - logger.exception("Error loading initializers from script %s", script_path) - if raise_on_initializer_error: - raise - - # When the caller supplies nothing, fall back to the default initializer set so a - # bare initialize_pyrit_async(...) yields a usable environment (core techniques + - # available default targets). Supplying any initializer/script means the caller owns - # setup, so defaults are skipped; load_defaults=False skips them even on a bare call. - if load_defaults and not all_initializers: - from pyrit.setup.initializers.targets import TargetInitializer - from pyrit.setup.initializers.techniques import TechniqueInitializer - - all_initializers = [TechniqueInitializer(), TargetInitializer()] - - # Execute all initializers in order - if all_initializers: - await _execute_initializers_async( - initializers=all_initializers, - raise_on_initializer_error=raise_on_initializer_error, - ) + await memory.dispose_engine_async() + finally: + if CentralMemory._memory_instance is memory: + CentralMemory._memory_instance = previous_memory + raise async def reinitialize_pyrit_async( diff --git a/pyrit/setup/initializers/refresh_datasets.py b/pyrit/setup/initializers/refresh_datasets.py index 8434ca3ba0..512610f17b 100644 --- a/pyrit/setup/initializers/refresh_datasets.py +++ b/pyrit/setup/initializers/refresh_datasets.py @@ -86,7 +86,7 @@ async def initialize_async(self) -> None: days = self._parse_days() memory = CentralMemory.get_memory_instance() - names_in_memory = set(memory.get_seed_dataset_names()) + names_in_memory = set(await memory.get_seed_dataset_names_async()) if not names_in_memory: logger.warning("No datasets in memory to refresh") return @@ -100,7 +100,7 @@ async def initialize_async(self) -> None: up_to_date: list[str] = [] failed: list[str] = [] for name in candidates: - if not self._is_stale(memory=memory, dataset_name=name, days=days): + if not (await self._is_stale_async(memory=memory, dataset_name=name, days=days)): up_to_date.append(name) continue try: @@ -148,7 +148,7 @@ async def _select_candidates_async(self, *, names_in_memory: set[str]) -> list[s logger.debug(f"Skipping '{name}': no registered provider to refresh from") return selected - def _is_stale(self, *, memory: MemoryInterface, dataset_name: str, days: int) -> bool: + async def _is_stale_async(self, *, memory: MemoryInterface, dataset_name: str, days: int) -> bool: """ Determine whether a dataset is stale enough to refresh. @@ -163,7 +163,7 @@ def _is_stale(self, *, memory: MemoryInterface, dataset_name: str, days: int) -> if days == 0: return True - seeds = memory.get_seeds(dataset_name=dataset_name) + seeds = await memory.get_seeds_async(dataset_name=dataset_name) newest = max((seed.date_added for seed in seeds if seed.date_added is not None), default=None) if newest is None: return True diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index f3574a2b88..98f38d7561 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -4,7 +4,8 @@ import asyncio import os import tempfile -from collections.abc import Generator +from collections.abc import AsyncGenerator +from contextlib import AsyncExitStack from unittest.mock import patch import pytest @@ -20,26 +21,34 @@ os.environ["RETRY_WAIT_MIN_SECONDS"] = "0" os.environ["RETRY_WAIT_MAX_SECONDS"] = "1" -# Initialize PyRIT for integration tests -asyncio.run(initialize_pyrit_async(memory_db_type=IN_MEMORY)) +async def _initialize_integration_memory_async() -> None: + await initialize_pyrit_async(memory_db_type=IN_MEMORY) + await CentralMemory.get_memory_instance().dispose_loop_resources_async() -@pytest.fixture -def azuresql_instance() -> Generator[AzureSQLMemory, None, None]: - azuresql_memory = AzureSQLMemory() - azuresql_memory.disable_embedding() - inspector = inspect(azuresql_memory.engine) +asyncio.run(_initialize_integration_memory_async()) - # Verify that tables are created as expected - assert "PromptMemoryEntries" in inspector.get_table_names(), "PromptMemoryEntries table not created." - assert "EmbeddingData" in inspector.get_table_names(), "EmbeddingData table not created." - assert "ScoreEntries" in inspector.get_table_names(), "ScoreEntries table not created." - assert "SeedPromptEntries" in inspector.get_table_names(), "SeedPromptEntries table not created." - CentralMemory.set_memory_instance(azuresql_memory) - yield azuresql_memory - azuresql_memory.dispose_engine() +@pytest.fixture +async def azuresql_instance() -> AsyncGenerator[AzureSQLMemory, None]: + connection_string = os.getenv("PYRIT_TEST_AZURE_SQL_CONNECTION_STRING") + if not connection_string: + pytest.skip("Set PYRIT_TEST_AZURE_SQL_CONNECTION_STRING to an isolated non-production database.") + if connection_string == os.getenv(AzureSQLMemory.AZURE_SQL_DB_CONNECTION_STRING_PROD): + pytest.fail("Azure SQL integration tests must not use the production database.") + azuresql_memory = AzureSQLMemory.__new__(AzureSQLMemory) + azuresql_memory.__init__(connection_string=connection_string, _defer_initialization=True) + async with AsyncExitStack() as cleanup: + cleanup.push_async_callback(azuresql_memory.dispose_engine_async) + await azuresql_memory.initialize_async() + azuresql_memory.disable_embedding() + async with await azuresql_memory.get_session_async() as session: + connection = await session.connection() + tables = await connection.run_sync(lambda sync_connection: inspect(sync_connection).get_table_names()) + assert {"PromptMemoryEntries", "EmbeddingData", "ScoreEntries", "SeedPromptEntries"} <= set(tables) + cleanup.enter_context(patch.object(CentralMemory, "_memory_instance", azuresql_memory)) + yield azuresql_memory def pytest_configure(config): @@ -56,28 +65,20 @@ def pytest_collection_modifyitems(config, items): @pytest.fixture -def sqlite_instance() -> Generator[SQLiteMemory, None, None]: - # Create an in-memory SQLite engine - sqlite_memory = SQLiteMemory(db_path=":memory:") - temp_dir = tempfile.TemporaryDirectory() - sqlite_memory.results_path = temp_dir.name - - sqlite_memory.disable_embedding() - - # Reset the database to ensure a clean state - sqlite_memory.reset_database() - inspector = inspect(sqlite_memory.engine) - - # Verify that tables are created as expected - assert "PromptMemoryEntries" in inspector.get_table_names(), "PromptMemoryEntries table not created." - assert "EmbeddingData" in inspector.get_table_names(), "EmbeddingData table not created." - assert "ScoreEntries" in inspector.get_table_names(), "ScoreEntries table not created." - assert "SeedPromptEntries" in inspector.get_table_names(), "SeedPromptEntries table not created." - - CentralMemory.set_memory_instance(sqlite_memory) - yield sqlite_memory - temp_dir.cleanup() - sqlite_memory.dispose_engine() +async def sqlite_instance() -> AsyncGenerator[SQLiteMemory, None]: + sqlite_memory = SQLiteMemory.__new__(SQLiteMemory) + sqlite_memory.__init__(db_path=":memory:", _defer_initialization=True) + async with AsyncExitStack() as cleanup: + sqlite_memory.results_path = cleanup.enter_context(tempfile.TemporaryDirectory()) + cleanup.push_async_callback(sqlite_memory.dispose_engine_async) + sqlite_memory.disable_embedding() + await sqlite_memory.initialize_async() + async with await sqlite_memory.get_session_async() as session: + connection = await session.connection() + tables = await connection.run_sync(lambda sync_connection: inspect(sync_connection).get_table_names()) + assert {"PromptMemoryEntries", "EmbeddingData", "ScoreEntries", "SeedPromptEntries"} <= set(tables) + cleanup.enter_context(patch.object(CentralMemory, "_memory_instance", sqlite_memory)) + yield sqlite_memory @pytest.fixture() diff --git a/tests/integration/datasets/test_load_default_datasets_integration.py b/tests/integration/datasets/test_load_default_datasets_integration.py index 37877e8148..9cf46c5c11 100644 --- a/tests/integration/datasets/test_load_default_datasets_integration.py +++ b/tests/integration/datasets/test_load_default_datasets_integration.py @@ -30,7 +30,7 @@ async def test_initialize_loads_datasets_into_memory(self, sqlite_instance): await initializer.initialize_async() memory = CentralMemory.get_memory_instance() - dataset_names = memory.get_seed_dataset_names() + dataset_names = await memory.get_seed_dataset_names_async() assert len(dataset_names) > 0, "No datasets were loaded into memory" logger.info(f"LoadDefaultDatasets loaded {len(dataset_names)} datasets into memory") diff --git a/tests/integration/datasets/test_seed_dataset_provider_integration.py b/tests/integration/datasets/test_seed_dataset_provider_integration.py index aac5f6f315..f4d3292035 100644 --- a/tests/integration/datasets/test_seed_dataset_provider_integration.py +++ b/tests/integration/datasets/test_seed_dataset_provider_integration.py @@ -655,7 +655,7 @@ async def test_harmbench_loads_and_stores_in_memory(self, sqlite_instance): ) # Verify seeds are queryable from memory (this is what scenarios do) - seed_groups = sqlite_instance.get_seed_groups(dataset_name="harmbench") + seed_groups = await sqlite_instance.get_seed_groups_async(dataset_name="harmbench") assert seed_groups is not None assert len(list(seed_groups)) > 0 diff --git a/tests/integration/memory/test_azure_sql_memory_integration.py b/tests/integration/memory/test_azure_sql_memory_integration.py index ace9e1c3ec..13389657ea 100644 --- a/tests/integration/memory/test_azure_sql_memory_integration.py +++ b/tests/integration/memory/test_azure_sql_memory_integration.py @@ -1,13 +1,14 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -from collections.abc import Generator -from contextlib import closing, contextmanager +from collections.abc import AsyncGenerator +from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta from uuid import uuid4 import numpy as np from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session from pyrit.memory import AzureSQLMemory from pyrit.memory.memory_models import ( @@ -115,8 +116,10 @@ def make_scenario_result( return ScenarioResult(scenario_identifier=identifier, **kwargs) -@contextmanager -def cleanup_conversation_data(memory: AzureSQLMemory, conversation_ids: list[str]) -> Generator[None, None, None]: +@asynccontextmanager +async def cleanup_conversation_data_async( + memory: AzureSQLMemory, conversation_ids: list[str] +) -> AsyncGenerator[None, None]: """ Context manager to ensure cleanup of test data from attack results and message pieces. @@ -132,26 +135,30 @@ def cleanup_conversation_data(memory: AzureSQLMemory, conversation_ids: list[str try: yield finally: - with closing(memory.get_session()) as session: - try: - # Delete attack results first (foreign key dependencies) - session.query(AttackResultEntry).filter(AttackResultEntry.conversation_id.in_(conversation_ids)).delete( - synchronize_session=False - ) + async with await memory.get_session_async() as async_session: - # Delete message pieces - session.query(PromptMemoryEntry).filter(PromptMemoryEntry.conversation_id.in_(conversation_ids)).delete( - synchronize_session=False - ) + def cleanup(session: Session) -> None: + try: + # Delete attack results first (foreign key dependencies) + session.query(AttackResultEntry).filter( + AttackResultEntry.conversation_id.in_(conversation_ids) + ).delete(synchronize_session=False) - session.commit() - except SQLAlchemyError as e: - session.rollback() - print(f"Cleanup failed: {e}") + # Delete message pieces + session.query(PromptMemoryEntry).filter( + PromptMemoryEntry.conversation_id.in_(conversation_ids) + ).delete(synchronize_session=False) + session.commit() + except SQLAlchemyError as e: + session.rollback() + print(f"Cleanup failed: {e}") -@contextmanager -def cleanup_scenario_data(memory: AzureSQLMemory, test_id: str) -> Generator[None, None, None]: + await async_session.run_sync(cleanup) + + +@asynccontextmanager +async def cleanup_scenario_data_async(memory: AzureSQLMemory, test_id: str) -> AsyncGenerator[None, None]: """ Context manager to ensure cleanup of scenario result test data. @@ -167,25 +174,31 @@ def cleanup_scenario_data(memory: AzureSQLMemory, test_id: str) -> Generator[Non try: yield finally: - with closing(memory.get_session()) as session: - try: - # Query all scenario results and filter by test_id label - all_results = session.query(ScenarioResultEntry).filter(ScenarioResultEntry.labels.isnot(None)).all() + async with await memory.get_session_async() as async_session: - for result in all_results: - if result.labels and result.labels.get("test_id") == test_id: - session.delete(result) + def cleanup(session: Session) -> None: + try: + # Query all scenario results and filter by test_id label + all_results = ( + session.query(ScenarioResultEntry).filter(ScenarioResultEntry.labels.isnot(None)).all() + ) - session.commit() - except SQLAlchemyError as e: - session.rollback() - print(f"Cleanup failed: {e}") + for result in all_results: + if result.labels and result.labels.get("test_id") == test_id: + session.delete(result) + + session.commit() + except SQLAlchemyError as e: + session.rollback() + print(f"Cleanup failed: {e}") + await async_session.run_sync(cleanup) -@contextmanager -def cleanup_scenario_data_by_field( + +@asynccontextmanager +async def cleanup_scenario_data_by_field_async( memory: AzureSQLMemory, test_id: str, field_name: str -) -> Generator[None, None, None]: +) -> AsyncGenerator[None, None]: """ Context manager to ensure cleanup of scenario result test data by objective_target_identifier field. @@ -203,23 +216,27 @@ def cleanup_scenario_data_by_field( try: yield finally: - with closing(memory.get_session()) as session: - try: - all_results = ( - session.query(ScenarioResultEntry) - .filter(ScenarioResultEntry.objective_target_identifier.isnot(None)) - .all() - ) + async with await memory.get_session_async() as async_session: - for result in all_results: - field_value = result.objective_target_identifier.get(field_name, "") - if test_id in field_value: - session.delete(result) + def cleanup(session: Session) -> None: + try: + all_results = ( + session.query(ScenarioResultEntry) + .filter(ScenarioResultEntry.objective_target_identifier.isnot(None)) + .all() + ) - session.commit() - except SQLAlchemyError as e: - session.rollback() - print(f"Cleanup failed: {e}") + for result in all_results: + field_value = result.objective_target_identifier.get(field_name, "") + if test_id in field_value: + session.delete(result) + + session.commit() + except SQLAlchemyError as e: + session.rollback() + print(f"Cleanup failed: {e}") + + await async_session.run_sync(cleanup) async def test_get_seeds_with_metadata_filter(azuresql_instance: AzureSQLMemory): @@ -252,34 +269,38 @@ async def test_get_seeds_with_metadata_filter(azuresql_instance: AzureSQLMemory) await azuresql_instance.add_seeds_to_memory_async(seeds=[sp1, sp2]) # Verify seeds were inserted - inserted_seeds = azuresql_instance.get_seeds(added_by=test_id) + inserted_seeds = await azuresql_instance.get_seeds_async(added_by=test_id) assert len(inserted_seeds) == 2, f"Expected 2 seeds with added_by='{test_id}', got {len(inserted_seeds)}" # Test single metadata filter (combining with added_by to avoid old test data) - result = azuresql_instance.get_seeds(metadata={"key1": value1}, added_by=test_id) + result = await azuresql_instance.get_seeds_async(metadata={"key1": value1}, added_by=test_id) assert len(result) == 1, f"Expected 1 seed with metadata {{'key1': '{value1}'}}, got {len(result)}" assert result[0].metadata == {"key1": value1} # Test multiple metadata filters (ALL must be present) - result2 = azuresql_instance.get_seeds(metadata={"key1": value2, "key2": value1}, added_by=test_id) + result2 = await azuresql_instance.get_seeds_async(metadata={"key1": value2, "key2": value1}, added_by=test_id) assert len(result2) == 1 assert result2[0].metadata == {"key1": value2, "key2": value1} # Clean up using public API - with closing(azuresql_instance.get_session()) as session: - try: - # Delete seeds by their IDs - from pyrit.memory.memory_models import SeedEntry + async with await azuresql_instance.get_session_async() as async_session: + + def cleanup(session: Session) -> None: + try: + # Delete seeds by their IDs + from pyrit.memory.memory_models import SeedEntry + + session.query(SeedEntry).filter(SeedEntry.id.in_([sp1.id, sp2.id])).delete(synchronize_session=False) + session.commit() + except SQLAlchemyError as e: + session.rollback() + print(f"Cleanup failed: {e}") - session.query(SeedEntry).filter(SeedEntry.id.in_([sp1.id, sp2.id])).delete(synchronize_session=False) - session.commit() - except SQLAlchemyError as e: - session.rollback() - print(f"Cleanup failed: {e}") + await async_session.run_sync(cleanup) # Ensure that entries are removed (filter by added_by to check only our test data) - assert azuresql_instance.get_seeds(metadata={"key1": value1}, added_by=test_id) == [] - assert azuresql_instance.get_seeds(metadata={"key2": value1}, added_by=test_id) == [] + assert (await azuresql_instance.get_seeds_async(metadata={"key1": value1}, added_by=test_id)) == [] + assert (await azuresql_instance.get_seeds_async(metadata={"key2": value1}, added_by=test_id)) == [] async def test_get_attack_results_by_labels(azuresql_instance: AzureSQLMemory): @@ -298,7 +319,7 @@ async def test_get_attack_results_by_labels(azuresql_instance: AzureSQLMemory): f"conv_label_3_{test_id}", ] - with cleanup_conversation_data(azuresql_instance, conversation_ids): + async with cleanup_conversation_data_async(azuresql_instance, conversation_ids): # Create message pieces for the attack conversations piece1 = MessagePiece( conversation_id=conversation_ids[0], @@ -319,7 +340,7 @@ async def test_get_attack_results_by_labels(azuresql_instance: AzureSQLMemory): converted_value="Test 3", ) - azuresql_instance.add_message_pieces_to_memory(message_pieces=[piece1, piece2, piece3]) + (await azuresql_instance.add_message_pieces_to_memory_async(message_pieces=[piece1, piece2, piece3])) # Create attack results with labels atomic_id = get_test_atomic_attack_identifier() @@ -345,25 +366,29 @@ async def test_get_attack_results_by_labels(azuresql_instance: AzureSQLMemory): labels={"op_id": f"op456_{test_id}", "category": "test", "priority": "high"}, ) - azuresql_instance.add_attack_results_to_memory(attack_results=[result1, result2, result3]) + (await azuresql_instance.add_attack_results_to_memory_async(attack_results=[result1, result2, result3])) # Test filtering by single label - results = azuresql_instance.get_attack_results(labels={"op_id": f"op123_{test_id}"}) + results = await azuresql_instance.get_attack_results_async(labels={"op_id": f"op123_{test_id}"}) assert len(results) == 2 conv_ids = {r.conversation_id for r in results} assert conversation_ids[0] in conv_ids assert conversation_ids[1] in conv_ids # Test filtering by multiple labels (ALL must be present) - results = azuresql_instance.get_attack_results(labels={"op_id": f"op123_{test_id}", "category": "test"}) + results = await azuresql_instance.get_attack_results_async( + labels={"op_id": f"op123_{test_id}", "category": "test"} + ) assert len(results) == 2 - results = azuresql_instance.get_attack_results(labels={"op_id": f"op123_{test_id}", "priority": "high"}) + results = await azuresql_instance.get_attack_results_async( + labels={"op_id": f"op123_{test_id}", "priority": "high"} + ) assert len(results) == 1 assert results[0].conversation_id == conversation_ids[0] # Test filtering with no matches - results = azuresql_instance.get_attack_results(labels={"op_id": "nonexistent"}) + results = await azuresql_instance.get_attack_results_async(labels={"op_id": "nonexistent"}) results = [r for r in results if test_id in r.conversation_id] assert len(results) == 0 @@ -379,7 +404,7 @@ async def test_scenario_result_scorer_identifier_roundtrip( """ test_id = generate_test_id() - with cleanup_scenario_data(azuresql_instance, test_id): + async with cleanup_scenario_data_async(azuresql_instance, test_id): # Create a ComponentIdentifier with various fields scorer_identifier = get_test_scorer_identifier( scorer_type="true_false", @@ -398,10 +423,10 @@ async def test_scenario_result_scorer_identifier_roundtrip( labels={"test_id": test_id}, ) - azuresql_instance.add_scenario_results_to_memory(scenario_results=[scenario]) + (await azuresql_instance.add_scenario_results_to_memory_async(scenario_results=[scenario])) # Retrieve and verify - results = azuresql_instance.get_scenario_results(labels={"test_id": test_id}) + results = await azuresql_instance.get_scenario_results_async(labels={"test_id": test_id}) assert len(results) == 1 retrieved = results[0] @@ -426,7 +451,7 @@ async def test_get_scenario_results_by_labels(azuresql_instance: AzureSQLMemory) # Use unique names to avoid test pollution test_id = generate_test_id() - with cleanup_scenario_data(azuresql_instance, test_id): + async with cleanup_scenario_data_async(azuresql_instance, test_id): # Create scenario results with labels scorer_id = get_test_scorer_identifier() scenario1 = make_scenario_result( @@ -459,29 +484,35 @@ async def test_get_scenario_results_by_labels(azuresql_instance: AzureSQLMemory) labels={"environment": "prod", "test_id": test_id}, ) - azuresql_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2, scenario3]) + ( + await azuresql_instance.add_scenario_results_to_memory_async( + scenario_results=[scenario1, scenario2, scenario3] + ) + ) # Test filtering by single label - results = azuresql_instance.get_scenario_results(labels={"environment": "test", "test_id": test_id}) + results = await azuresql_instance.get_scenario_results_async(labels={"environment": "test", "test_id": test_id}) assert len(results) == 2 names = {r.scenario_name for r in results} assert f"Test Scenario 1 {test_id}" in names assert f"Test Scenario 2 {test_id}" in names # Test filtering by multiple labels (ALL must be present) - results = azuresql_instance.get_scenario_results( + results = await azuresql_instance.get_scenario_results_async( labels={"environment": "test", "priority": "high", "test_id": test_id} ) assert len(results) == 2 - results = azuresql_instance.get_scenario_results( + results = await azuresql_instance.get_scenario_results_async( labels={"environment": "test", "team": "red", "test_id": test_id} ) assert len(results) == 1 assert results[0].scenario_name == f"Test Scenario 1 {test_id}" # Test filtering with no matches - results = azuresql_instance.get_scenario_results(labels={"environment": "staging", "test_id": test_id}) + results = await azuresql_instance.get_scenario_results_async( + labels={"environment": "staging", "test_id": test_id} + ) assert len(results) == 0 @@ -497,7 +528,7 @@ async def test_get_scenario_results_by_target_endpoint( # Use unique names to avoid test pollution test_id = generate_test_id() - with cleanup_scenario_data_by_field(azuresql_instance, test_id, "endpoint"): + async with cleanup_scenario_data_by_field_async(azuresql_instance, test_id, "endpoint"): # Create scenario results with different endpoints scorer_id = get_test_scorer_identifier() scenario1 = make_scenario_result( @@ -537,33 +568,41 @@ async def test_get_scenario_results_by_target_endpoint( objective_scorer_identifier=scorer_id, ) - azuresql_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2, scenario3, scenario4]) + ( + await azuresql_instance.add_scenario_results_to_memory_async( + scenario_results=[scenario1, scenario2, scenario3, scenario4] + ) + ) # Test case-insensitive substring matching - search for test_id specific endpoints - results = azuresql_instance.get_scenario_results(objective_target_endpoint=test_id) + results = await azuresql_instance.get_scenario_results_async(objective_target_endpoint=test_id) assert len(results) == 4 # All should have test_id in their endpoint - results = azuresql_instance.get_scenario_results(objective_target_endpoint=f"openai.com/{test_id}") + results = await azuresql_instance.get_scenario_results_async(objective_target_endpoint=f"openai.com/{test_id}") assert len(results) == 0 # test_id comes before openai.com - results = azuresql_instance.get_scenario_results(objective_target_endpoint=f"{test_id}.openai") + results = await azuresql_instance.get_scenario_results_async(objective_target_endpoint=f"{test_id}.openai") assert len(results) == 2 names = {r.scenario_name for r in results} assert f"OpenAI Test {test_id}" in names assert f"Azure OpenAI Test {test_id}" in names # Test case-insensitive with AZURE - results = azuresql_instance.get_scenario_results(objective_target_endpoint=f"{test_id}.openai.AZURE") + results = await azuresql_instance.get_scenario_results_async( + objective_target_endpoint=f"{test_id}.openai.AZURE" + ) assert len(results) == 1 assert results[0].scenario_name == f"Azure OpenAI Test {test_id}" # Test anthropic - results = azuresql_instance.get_scenario_results(objective_target_endpoint=f"{test_id}.AnThRoPiC") + results = await azuresql_instance.get_scenario_results_async(objective_target_endpoint=f"{test_id}.AnThRoPiC") assert len(results) == 1 assert results[0].scenario_name == f"Anthropic Test {test_id}" # Test cognitiveservices - results = azuresql_instance.get_scenario_results(objective_target_endpoint=f"{test_id}.cognitiveservices") + results = await azuresql_instance.get_scenario_results_async( + objective_target_endpoint=f"{test_id}.cognitiveservices" + ) assert len(results) == 1 assert results[0].scenario_name == f"Azure Other {test_id}" @@ -580,7 +619,7 @@ async def test_get_scenario_results_by_target_model_name( # Use unique model name suffixes to avoid test pollution test_id = generate_test_id() - with cleanup_scenario_data_by_field(azuresql_instance, test_id, "model_name"): + async with cleanup_scenario_data_by_field_async(azuresql_instance, test_id, "model_name"): # Create scenario results with different model names scorer_id = get_test_scorer_identifier() scenario1 = make_scenario_result( @@ -612,34 +651,42 @@ async def test_get_scenario_results_by_target_model_name( objective_scorer_identifier=scorer_id, ) - azuresql_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2, scenario3, scenario4]) + ( + await azuresql_instance.add_scenario_results_to_memory_async( + scenario_results=[scenario1, scenario2, scenario3, scenario4] + ) + ) # Test case-insensitive substring matching - search for test_id - results = azuresql_instance.get_scenario_results(objective_target_model_name=test_id) + results = await azuresql_instance.get_scenario_results_async(objective_target_model_name=test_id) assert len(results) == 4 # All should have test_id in their model name # Test case-insensitive substring matching - gpt with test_id - results = azuresql_instance.get_scenario_results(objective_target_model_name=f"gpt-4-turbo-{test_id}") + results = await azuresql_instance.get_scenario_results_async( + objective_target_model_name=f"gpt-4-turbo-{test_id}" + ) assert len(results) == 1 assert results[0].scenario_name == f"GPT-4 Test {test_id}" # Test case-insensitive substring matching - GPT-4 (uppercase) - results = azuresql_instance.get_scenario_results(objective_target_model_name=f"GPT-4o-{test_id}") + results = await azuresql_instance.get_scenario_results_async(objective_target_model_name=f"GPT-4o-{test_id}") assert len(results) == 1 assert results[0].scenario_name == f"GPT-4 Omni Test {test_id}" # Test substring in the middle - version number - results = azuresql_instance.get_scenario_results(objective_target_model_name=f"3.5-turbo-{test_id}") + results = await azuresql_instance.get_scenario_results_async(objective_target_model_name=f"3.5-turbo-{test_id}") assert len(results) == 1 assert results[0].scenario_name == f"GPT-3.5 Test {test_id}" # Test case-insensitive with different model family - results = azuresql_instance.get_scenario_results(objective_target_model_name=f"CLAUDE-3-opus-{test_id}") + results = await azuresql_instance.get_scenario_results_async( + objective_target_model_name=f"CLAUDE-3-opus-{test_id}" + ) assert len(results) == 1 assert results[0].scenario_name == f"Claude Test {test_id}" # Test turbo suffix with test_id - results = azuresql_instance.get_scenario_results(objective_target_model_name=f"turbo-{test_id}") + results = await azuresql_instance.get_scenario_results_async(objective_target_model_name=f"turbo-{test_id}") assert len(results) == 2 names = {r.scenario_name for r in results} assert f"GPT-4 Test {test_id}" in names @@ -658,7 +705,7 @@ async def test_get_scenario_results_combined_filters(azuresql_instance: AzureSQL now = datetime.now(tz=UTC) yesterday = now - timedelta(days=1) - with cleanup_scenario_data(azuresql_instance, test_id): + async with cleanup_scenario_data_async(azuresql_instance, test_id): # Create scenario results with various attributes scorer_id = get_test_scorer_identifier() scenario1 = make_scenario_result( @@ -707,10 +754,14 @@ async def test_get_scenario_results_combined_filters(azuresql_instance: AzureSQL completion_time=yesterday, ) - azuresql_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2, scenario3]) + ( + await azuresql_instance.add_scenario_results_to_memory_async( + scenario_results=[scenario1, scenario2, scenario3] + ) + ) # Test combining name filter with labels - results = azuresql_instance.get_scenario_results( + results = await azuresql_instance.get_scenario_results_async( scenario_name=f"Test Environment {test_id}", labels={"environment": "test", "test_id": test_id}, ) @@ -718,7 +769,7 @@ async def test_get_scenario_results_combined_filters(azuresql_instance: AzureSQL assert results[0].scenario_name == f"Test Environment {test_id}" # Test combining endpoint, model name, and labels - results = azuresql_instance.get_scenario_results( + results = await azuresql_instance.get_scenario_results_async( objective_target_endpoint=f"api-{test_id}.openai", objective_target_model_name=f"gpt-4-turbo-{test_id}", labels={"priority": "high", "test_id": test_id}, @@ -728,7 +779,7 @@ async def test_get_scenario_results_combined_filters(azuresql_instance: AzureSQL # Test combining version and time filters with test_id # Add 1 second buffer to account for SQL Server datetime precision differences - results = azuresql_instance.get_scenario_results( + results = await azuresql_instance.get_scenario_results_async( pyrit_version="0.4.0", added_before=now + timedelta(seconds=1), labels={"test_id": test_id}, @@ -736,7 +787,7 @@ async def test_get_scenario_results_combined_filters(azuresql_instance: AzureSQL assert len(results) == 2 # Test combining all filters - should match only one - results = azuresql_instance.get_scenario_results( + results = await azuresql_instance.get_scenario_results_async( scenario_name=f"Production Test {test_id}", pyrit_version="0.4.0", objective_target_endpoint=f"api-{test_id}", @@ -747,7 +798,7 @@ async def test_get_scenario_results_combined_filters(azuresql_instance: AzureSQL assert results[0].scenario_name == f"Production Test {test_id}" # Test combining filters with no matches - results = azuresql_instance.get_scenario_results( + results = await azuresql_instance.get_scenario_results_async( objective_target_endpoint=f"api-{test_id}", labels={"environment": "staging", "test_id": test_id}, ) diff --git a/tests/integration/mocks.py b/tests/integration/mocks.py index 0a82004b0d..0c0731d84b 100644 --- a/tests/integration/mocks.py +++ b/tests/integration/mocks.py @@ -1,7 +1,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -from collections.abc import Generator +from collections.abc import AsyncGenerator +from contextlib import aclosing from sqlalchemy import inspect @@ -10,28 +11,25 @@ from pyrit.prompt_target import PromptTarget, TargetCapabilities, TargetConfiguration, limit_requests_per_minute -def get_memory_interface() -> Generator[MemoryInterface, None, None]: - yield from get_sqlite_memory() +async def get_memory_interface_async() -> AsyncGenerator[MemoryInterface, None]: + async with aclosing(get_sqlite_memory_async()) as memories: + async for memory in memories: + yield memory -def get_sqlite_memory() -> Generator[SQLiteMemory, None, None]: - # Create an in-memory SQLite engine - sqlite_memory = SQLiteMemory(db_path=":memory:") - - sqlite_memory.disable_embedding() - - # Reset the database to ensure a clean state - sqlite_memory.reset_database() - inspector = inspect(sqlite_memory.engine) - - # Verify that tables are created as expected - assert "PromptMemoryEntries" in inspector.get_table_names(), "PromptMemoryEntries table not created." - assert "EmbeddingData" in inspector.get_table_names(), "EmbeddingData table not created." - assert "ScoreEntries" in inspector.get_table_names(), "ScoreEntries table not created." - assert "SeedPromptEntries" in inspector.get_table_names(), "SeedPromptEntries table not created." - - yield sqlite_memory - sqlite_memory.dispose_engine() +async def get_sqlite_memory_async() -> AsyncGenerator[SQLiteMemory, None]: + sqlite_memory = SQLiteMemory.__new__(SQLiteMemory) + sqlite_memory.__init__(db_path=":memory:", _defer_initialization=True) + try: + sqlite_memory.disable_embedding() + await sqlite_memory.initialize_async() + async with await sqlite_memory.get_session_async() as session: + connection = await session.connection() + tables = await connection.run_sync(lambda sync_connection: inspect(sync_connection).get_table_names()) + assert {"PromptMemoryEntries", "EmbeddingData", "ScoreEntries", "SeedPromptEntries"} <= set(tables) + yield sqlite_memory + finally: + await sqlite_memory.dispose_engine_async() class MockPromptTarget(PromptTarget): @@ -51,7 +49,7 @@ def __init__(self, *, id=None, rpm=None) -> None: # noqa: A002 self.id = id self.prompt_sent = [] - def set_system_prompt( + async def set_system_prompt_async( self, *, system_prompt: str, @@ -61,13 +59,15 @@ def set_system_prompt( ) -> None: self.system_prompt = system_prompt if self._memory: - self._memory.add_message_to_memory( - request=MessagePiece( - role="system", - original_value=system_prompt, - converted_value=system_prompt, - conversation_id=conversation_id, - ).to_message() + ( + await self._memory.add_message_to_memory_async( + request=MessagePiece( + role="system", + original_value=system_prompt, + converted_value=system_prompt, + conversation_id=conversation_id, + ).to_message() + ) ) @limit_requests_per_minute diff --git a/tests/integration/score/test_azure_content_filter_integration.py b/tests/integration/score/test_azure_content_filter_integration.py index 983fb87ecb..5b231ff4b1 100644 --- a/tests/integration/score/test_azure_content_filter_integration.py +++ b/tests/integration/score/test_azure_content_filter_integration.py @@ -2,11 +2,11 @@ # Licensed under the MIT license. import os -from collections.abc import Generator +from collections.abc import AsyncGenerator from unittest.mock import patch import pytest -from integration.mocks import get_memory_interface +from integration.mocks import get_memory_interface_async from pyrit.common.path import HOME_PATH from pyrit.memory import CentralMemory, MemoryInterface @@ -16,8 +16,9 @@ @pytest.fixture -def memory() -> Generator[MemoryInterface, None, None]: - yield from get_memory_interface() +async def memory() -> AsyncGenerator[MemoryInterface, None]: + async for instance in get_memory_interface_async(): + yield instance @pytest.fixture( diff --git a/tests/integration/targets/test_openai_responses_gpt5.py b/tests/integration/targets/test_openai_responses_gpt5.py index 9da676e451..a48cd7f659 100644 --- a/tests/integration/targets/test_openai_responses_gpt5.py +++ b/tests/integration/targets/test_openai_responses_gpt5.py @@ -65,7 +65,7 @@ async def test_openai_responses_gpt5(sqlite_instance, gpt5_args): original_value_data_type="text", conversation_id=conv_id, ) - sqlite_instance.add_message_to_memory(request=developer_piece.to_message()) + (await sqlite_instance.add_message_to_memory_async(request=developer_piece.to_message())) user_piece = MessagePiece( role="user", @@ -97,7 +97,7 @@ async def test_openai_responses_gpt5_json_schema(sqlite_instance, gpt5_args): original_value_data_type="text", conversation_id=conv_id, ) - sqlite_instance.add_message_to_memory(request=developer_piece.to_message()) + (await sqlite_instance.add_message_to_memory_async(request=developer_piece.to_message())) cat_schema = { "type": "object", @@ -150,7 +150,7 @@ async def test_openai_responses_gpt5_json_object(sqlite_instance, gpt5_args): conversation_id=conv_id, ) - sqlite_instance.add_message_to_memory(request=developer_piece.to_message()) + (await sqlite_instance.add_message_to_memory_async(request=developer_piece.to_message())) prompt = "Create a JSON object that describes a mystical cat " prompt += "with the following properties: name, age, fur_rgb." diff --git a/tests/integration/targets/test_target_filters.py b/tests/integration/targets/test_target_filters.py index 932411b3d7..3bbe4f2baa 100644 --- a/tests/integration/targets/test_target_filters.py +++ b/tests/integration/targets/test_target_filters.py @@ -45,7 +45,7 @@ async def test_azure_content_filters(sqlite_instance, endpoint, api_key, model_n attack = PromptSendingAttack(objective_target=target) result = await attack.execute_async(objective=prompt) assert result is not None - conversation = sqlite_instance.get_conversation_messages(conversation_id=result.conversation_id) + conversation = await sqlite_instance.get_conversation_messages_async(conversation_id=result.conversation_id) assert len(conversation) == 2 response = conversation[-1] assert len(response.message_pieces) == 1 @@ -86,7 +86,7 @@ async def test_azure_content_filters_response_api(sqlite_instance, endpoint, api attack = PromptSendingAttack(objective_target=target) result = await attack.execute_async(objective=prompt) assert result is not None - conversation = sqlite_instance.get_conversation_messages(conversation_id=result.conversation_id) + conversation = await sqlite_instance.get_conversation_messages_async(conversation_id=result.conversation_id) assert len(conversation) == 2 response = conversation[-1] assert len(response.message_pieces) == 1 @@ -111,7 +111,7 @@ async def test_image_input_filters(sqlite_instance, endpoint, api_key, model_nam attack = PromptSendingAttack(objective_target=target) result = await attack.execute_async(objective=prompt) assert result is not None - conversation = sqlite_instance.get_conversation_messages(conversation_id=result.conversation_id) + conversation = await sqlite_instance.get_conversation_messages_async(conversation_id=result.conversation_id) assert len(conversation) == 2 response = conversation[-1] assert len(response.message_pieces) == 1 @@ -138,7 +138,7 @@ async def test_video_input_filters(sqlite_instance, endpoint, api_key, model_nam attack = PromptSendingAttack(objective_target=target) result = await attack.execute_async(objective=prompt) assert result is not None - conversation = sqlite_instance.get_conversation_messages(conversation_id=result.conversation_id) + conversation = await sqlite_instance.get_conversation_messages_async(conversation_id=result.conversation_id) assert len(conversation) == 2 response = conversation[-1] assert len(response.message_pieces) == 1 diff --git a/tests/integration/targets/test_websocket_target_integration.py b/tests/integration/targets/test_websocket_target_integration.py index c23f2a550e..bf615adf45 100644 --- a/tests/integration/targets/test_websocket_target_integration.py +++ b/tests/integration/targets/test_websocket_target_integration.py @@ -144,14 +144,16 @@ async def restore_conversation_async( first_response = await target.send_prompt_async(message=first_request) await first_connection_closed.wait() - sqlite_instance.add_conversation_to_memory( - conversation=Conversation( - conversation_id=conversation_id, - target_identifier=target.get_identifier(), + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation( + conversation_id=conversation_id, + target_identifier=target.get_identifier(), + ) ) ) - sqlite_instance.add_message_to_memory(request=first_request) - sqlite_instance.add_message_to_memory(request=first_response[0]) + (await sqlite_instance.add_message_to_memory_async(request=first_request)) + (await sqlite_instance.add_message_to_memory_async(request=first_response[0])) second_request = MessagePiece( role="user", diff --git a/tests/partner_integration/azure_ai_evaluation/test_sqlite_memory_contract.py b/tests/partner_integration/azure_ai_evaluation/test_sqlite_memory_contract.py index 6d064c3486..6e3a001091 100644 --- a/tests/partner_integration/azure_ai_evaluation/test_sqlite_memory_contract.py +++ b/tests/partner_integration/azure_ai_evaluation/test_sqlite_memory_contract.py @@ -24,43 +24,43 @@ class TestMemoryLifecycleContract: """Validate CentralMemory/SQLiteMemory interface stability.""" - def test_sqlite_memory_default_constructor(self): + async def test_sqlite_memory_default_constructor_async(self): """RedTeam.__init__ calls SQLiteMemory() with no args.""" memory = SQLiteMemory() assert memory is not None - memory.dispose_engine() + await memory.dispose_engine_async() - def test_sqlite_memory_in_memory_constructor(self): + async def test_sqlite_memory_in_memory_constructor_async(self): """Partner tests use SQLiteMemory(db_path=':memory:').""" memory = SQLiteMemory(db_path=":memory:") assert memory is not None - memory.dispose_engine() + await memory.dispose_engine_async() - def test_central_memory_set_and_get_instance(self): + async def test_central_memory_set_and_get_instance_async(self): """RedTeam.__init__ sets memory; formatting_utils.py and _rai_scorer.py retrieve it.""" memory = SQLiteMemory(db_path=":memory:") CentralMemory.set_memory_instance(memory) retrieved = CentralMemory.get_memory_instance() assert retrieved is memory - memory.dispose_engine() + await memory.dispose_engine_async() - def test_sqlite_memory_has_disable_embedding(self): + async def test_sqlite_memory_has_disable_embedding_async(self): """Test fixtures call disable_embedding() on SQLiteMemory.""" memory = SQLiteMemory(db_path=":memory:") assert hasattr(memory, "disable_embedding") assert callable(memory.disable_embedding) memory.disable_embedding() - memory.dispose_engine() + await memory.dispose_engine_async() - def test_sqlite_memory_has_reset_database(self): + async def test_sqlite_memory_has_reset_database_async(self): """Test fixtures call reset_database() on SQLiteMemory.""" memory = SQLiteMemory(db_path=":memory:") - assert hasattr(memory, "reset_database") - assert callable(memory.reset_database) - memory.dispose_engine() + assert hasattr(memory, "reset_database_async") + assert callable(memory.reset_database_async) + await memory.dispose_engine_async() def test_sqlite_memory_has_dispose_engine(self): - """Cleanup requires dispose_engine().""" + """The deprecated sync cleanup method remains available to partner callers.""" memory = SQLiteMemory(db_path=":memory:") assert hasattr(memory, "dispose_engine") assert callable(memory.dispose_engine) @@ -75,28 +75,25 @@ class TestMemoryQueryMethodContract: and conversation history during red team scans. """ - def test_memory_has_get_scenario_results(self): + async def test_memory_has_get_scenario_results_async(self): """_scenario_orchestrator.py calls memory.get_scenario_results(scenario_result_ids=[...]).""" memory = SQLiteMemory(db_path=":memory:") - assert hasattr(memory, "get_scenario_results") - assert callable(memory.get_scenario_results) - memory.dispose_engine() + assert callable(memory.get_scenario_results_async) + await memory.dispose_engine_async() - def test_memory_has_add_scores_to_memory(self): + async def test_memory_has_add_scores_to_memory_async(self): """_rai_scorer.py calls memory.add_scores_to_memory(scores=[Score]).""" memory = SQLiteMemory(db_path=":memory:") - assert hasattr(memory, "add_scores_to_memory") - assert callable(memory.add_scores_to_memory) - memory.dispose_engine() + assert callable(memory.add_scores_to_memory_async) + await memory.dispose_engine_async() - def test_memory_has_get_message_pieces(self): + async def test_memory_has_get_message_pieces_async(self): """_foundry_result_processor.py calls memory.get_message_pieces(conversation_id=...).""" memory = SQLiteMemory(db_path=":memory:") - assert hasattr(memory, "get_message_pieces") - assert callable(memory.get_message_pieces) - memory.dispose_engine() + assert callable(memory.get_message_pieces_async) + await memory.dispose_engine_async() - def test_memory_has_get_prompt_request_pieces_or_equivalent(self): + async def test_memory_has_get_prompt_request_pieces_or_equivalent_async(self): """formatting_utils.py calls memory.get_prompt_request_pieces(labels={...}). NOTE: In newer PyRIT versions, this was consolidated into get_message_pieces(labels=...). @@ -105,34 +102,33 @@ def test_memory_has_get_prompt_request_pieces_or_equivalent(self): """ memory = SQLiteMemory(db_path=":memory:") has_legacy = hasattr(memory, "get_prompt_request_pieces") - has_current = hasattr(memory, "get_message_pieces") + has_current = hasattr(memory, "get_message_pieces_async") assert has_legacy or has_current, ( "Neither get_prompt_request_pieces nor get_message_pieces found on memory. " "formatting_utils.py depends on one of these for label-based queries." ) - memory.dispose_engine() + await memory.dispose_engine_async() - def test_memory_has_get_conversation(self): + async def test_memory_has_get_conversation_async(self): """_callback_chat_target.py calls memory.get_conversation_messages(conversation_id=...).""" memory = SQLiteMemory(db_path=":memory:") - assert hasattr(memory, "get_conversation_messages") - assert callable(memory.get_conversation_messages) - memory.dispose_engine() + assert callable(memory.get_conversation_messages_async) + await memory.dispose_engine_async() - def test_get_conversation_returns_list(self, sqlite_instance): + async def test_get_conversation_returns_list_async(self, sqlite_instance): """get_conversation should return a list (empty for unknown conversation_id).""" - result = sqlite_instance.get_conversation_messages(conversation_id="nonexistent-id") + result = await sqlite_instance.get_conversation_messages_async(conversation_id="nonexistent-id") assert isinstance(result, list) - def test_get_message_pieces_with_labels_returns_list(self, sqlite_instance): + async def test_get_message_pieces_with_labels_returns_list_async(self, sqlite_instance): """get_message_pieces(labels={...}) should return a list (empty for no matches). This is the current equivalent of the SDK's get_prompt_request_pieces(labels=...) call. """ - result = sqlite_instance.get_message_pieces(labels={"nonexistent": "label"}) + result = await sqlite_instance.get_message_pieces_async(labels={"nonexistent": "label"}) assert isinstance(result, (list, tuple)) - def test_get_message_pieces_returns_list(self, sqlite_instance): + async def test_get_message_pieces_returns_list_async(self, sqlite_instance): """get_message_pieces should return a list (empty for unknown conversation_id).""" - result = sqlite_instance.get_message_pieces(conversation_id="nonexistent-id") + result = await sqlite_instance.get_message_pieces_async(conversation_id="nonexistent-id") assert isinstance(result, list) diff --git a/tests/partner_integration/conftest.py b/tests/partner_integration/conftest.py index 65c51ff24e..4a7fbcde8d 100644 --- a/tests/partner_integration/conftest.py +++ b/tests/partner_integration/conftest.py @@ -11,7 +11,8 @@ import asyncio import os import tempfile -from collections.abc import Generator +from collections.abc import AsyncGenerator +from contextlib import AsyncExitStack from unittest.mock import patch import pytest @@ -46,23 +47,20 @@ def _restore_central_memory(): @pytest.fixture -def sqlite_instance() -> Generator[SQLiteMemory, None, None]: +async def sqlite_instance() -> AsyncGenerator[SQLiteMemory, None]: """Provide an in-memory SQLite database for partner integration tests.""" - sqlite_memory = SQLiteMemory(db_path=":memory:") - temp_dir = tempfile.TemporaryDirectory() - sqlite_memory.results_path = temp_dir.name - sqlite_memory.disable_embedding() - sqlite_memory.reset_database() - - inspector = inspect(sqlite_memory.engine) - assert "PromptMemoryEntries" in inspector.get_table_names() - assert "ScoreEntries" in inspector.get_table_names() - assert "SeedPromptEntries" in inspector.get_table_names() - - CentralMemory.set_memory_instance(sqlite_memory) - yield sqlite_memory - temp_dir.cleanup() - sqlite_memory.dispose_engine() + sqlite_memory = SQLiteMemory(db_path=":memory:", _defer_initialization=True) + async with AsyncExitStack() as cleanup: + sqlite_memory.results_path = cleanup.enter_context(tempfile.TemporaryDirectory()) + cleanup.push_async_callback(sqlite_memory.dispose_engine_async) + sqlite_memory.disable_embedding() + await sqlite_memory.initialize_async() + async with await sqlite_memory.get_session_async() as session: + connection = await session.connection() + tables = await connection.run_sync(lambda sync_connection: inspect(sync_connection).get_table_names()) + assert {"PromptMemoryEntries", "ScoreEntries", "SeedPromptEntries"} <= set(tables) + CentralMemory.set_memory_instance(sqlite_memory) + yield sqlite_memory @pytest.fixture diff --git a/tests/unit/analytics/test_conversation_analytics.py b/tests/unit/analytics/test_conversation_analytics.py index 15efcec1cf..689064350b 100644 --- a/tests/unit/analytics/test_conversation_analytics.py +++ b/tests/unit/analytics/test_conversation_analytics.py @@ -2,7 +2,7 @@ # Licensed under the MIT license. from collections.abc import Sequence -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import numpy as np import pytest @@ -25,14 +25,14 @@ def sample_message_pieces() -> Sequence[MessagePiece]: return flatten_to_message_pieces(conversations) -def test_get_similar_chat_messages_by_content(mock_memory_interface, sample_message_pieces): +async def test_get_similar_chat_messages_by_content(mock_memory_interface, sample_message_pieces): sample_message_pieces[0].converted_value = "Hello, how are you?" sample_message_pieces[2].converted_value = "Hello, how are you?" - mock_memory_interface.get_message_pieces.return_value = sample_message_pieces + mock_memory_interface.get_message_pieces_async = AsyncMock(return_value=sample_message_pieces) analytics = ConversationAnalytics(memory_interface=mock_memory_interface) - similar_messages = analytics.get_prompt_entries_with_same_converted_content( + similar_messages = await analytics.get_prompt_entries_with_same_converted_content_async( chat_message_content="Hello, how are you?" ) @@ -44,7 +44,7 @@ def test_get_similar_chat_messages_by_content(mock_memory_interface, sample_mess assert message.metric == "exact_match" -def test_get_similar_chat_messages_by_embedding(mock_memory_interface, sample_message_pieces): +async def test_get_similar_chat_messages_by_embedding(mock_memory_interface, sample_message_pieces): sample_message_pieces[0].converted_value = "Similar message" sample_message_pieces[1].converted_value = "Different message" @@ -59,11 +59,11 @@ def test_get_similar_chat_messages_by_embedding(mock_memory_interface, sample_me ] # Mock the get_all_embeddings method to return the mock EmbeddingData entries - mock_memory_interface.get_all_embeddings.return_value = mock_embeddings - mock_memory_interface.get_message_pieces.return_value = sample_message_pieces + mock_memory_interface.get_all_embeddings_async = AsyncMock(return_value=mock_embeddings) + mock_memory_interface.get_message_pieces_async = AsyncMock(return_value=sample_message_pieces) analytics = ConversationAnalytics(memory_interface=mock_memory_interface) - similar_messages = analytics.get_similar_chat_messages_by_embedding( + similar_messages = await analytics.get_similar_chat_messages_by_embedding_async( chat_message_embedding=target_embedding, threshold=0.99 ) @@ -73,6 +73,29 @@ def test_get_similar_chat_messages_by_embedding(mock_memory_interface, sample_me assert similar_messages[0].metric == "cosine_similarity" +async def test_embedding_search_skips_missing_vectors_and_includes_threshold_boundary( + mock_memory_interface: MagicMock, sample_message_pieces: Sequence[MessagePiece] +) -> None: + matching = EmbeddingDataEntry(id=sample_message_pieces[0].id, embedding=[1.0, 0.0], embedding_type_name="test") + missing = EmbeddingDataEntry(id=sample_message_pieces[1].id, embedding=None, embedding_type_name="test") + orthogonal = EmbeddingDataEntry(id=sample_message_pieces[2].id, embedding=[0.0, 1.0], embedding_type_name="test") + mock_memory_interface.get_all_embeddings_async.return_value = [missing, matching, orthogonal] + mock_memory_interface.get_all_embeddings.return_value = [missing, matching, orthogonal] + analytics = ConversationAnalytics(memory_interface=mock_memory_interface) + + actual = await analytics.get_similar_chat_messages_by_embedding_async( + chat_message_embedding=[1.0, 0.0], threshold=1.0 + ) + with pytest.warns(DeprecationWarning, match="get_similar_chat_messages_by_embedding"): + legacy = analytics.get_similar_chat_messages_by_embedding(chat_message_embedding=[1.0, 0.0], threshold=1.0) + for matches in (actual, legacy): + assert len(matches) == 1 + assert matches[0].uuid == matching.id + assert matches[0].score == 1.0 + assert matches[0].metric == "cosine_similarity" + mock_memory_interface.get_all_embeddings_async.assert_awaited_once() + + @pytest.mark.parametrize( "a,b", [ diff --git a/tests/unit/analytics/test_result_analysis.py b/tests/unit/analytics/test_result_analysis.py index 461442b0b3..a699272a15 100644 --- a/tests/unit/analytics/test_result_analysis.py +++ b/tests/unit/analytics/test_result_analysis.py @@ -2,7 +2,7 @@ # Licensed under the MIT license. from datetime import UTC, datetime, timedelta -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import pytest @@ -10,7 +10,7 @@ AttackStats, _objective_target_eval_hash_for, analyze_results, - get_cached_results_for_technique, + get_cached_results_for_technique_async, ) from pyrit.memory.memory_interface import MemoryInterface from pyrit.models import ( @@ -208,15 +208,15 @@ def _make_attack_with_target( ) -def test_get_cached_results_for_technique_returns_matching(): +async def test_get_cached_results_for_technique_returns_matching(): target = _make_target_component() expected_hash = ObjectiveTargetEvaluationIdentifier(target).eval_hash matching = _make_attack_with_target(target) memory = MagicMock(spec=MemoryInterface) - memory.get_attack_results.return_value = [matching] + memory.get_attack_results_async = AsyncMock(return_value=[matching]) - results = get_cached_results_for_technique( + results = await get_cached_results_for_technique_async( memory, technique_eval_hash="tech-hash", objective_target_eval_hash=expected_hash, @@ -225,19 +225,21 @@ def test_get_cached_results_for_technique_returns_matching(): assert results == [matching] -def test_get_cached_results_for_technique_filters_out_target_mismatches(): +async def test_get_cached_results_for_technique_filters_out_target_mismatches(): target_match = _make_target_component(model_name="gpt-4o") target_other = _make_target_component(model_name="gpt-4o-mini") expected_hash = ObjectiveTargetEvaluationIdentifier(target_match).eval_hash memory = MagicMock(spec=MemoryInterface) - memory.get_attack_results.return_value = [ - _make_attack_with_target(target_other), - _make_attack_with_target(target_match), - _make_attack_with_target(target_other), - ] + memory.get_attack_results_async = AsyncMock( + return_value=[ + _make_attack_with_target(target_other), + _make_attack_with_target(target_match), + _make_attack_with_target(target_other), + ] + ) - results = get_cached_results_for_technique( + results = await get_cached_results_for_technique_async( memory, technique_eval_hash="tech-hash", objective_target_eval_hash=expected_hash, @@ -247,11 +249,11 @@ def test_get_cached_results_for_technique_filters_out_target_mismatches(): assert results[0].atomic_attack_identifier == _make_attack_with_target(target_match).atomic_attack_identifier -def test_get_cached_results_for_technique_returns_empty_when_no_candidates(): +async def test_get_cached_results_for_technique_returns_empty_when_no_candidates(): memory = MagicMock(spec=MemoryInterface) - memory.get_attack_results.return_value = [] + memory.get_attack_results_async = AsyncMock(return_value=[]) - results = get_cached_results_for_technique( + results = await get_cached_results_for_technique_async( memory, technique_eval_hash="tech-hash", objective_target_eval_hash="target-hash", @@ -260,7 +262,7 @@ def test_get_cached_results_for_technique_returns_empty_when_no_candidates(): assert results == [] -def test_get_cached_results_for_technique_sorts_newest_first(): +async def test_get_cached_results_for_technique_sorts_newest_first(): target = _make_target_component() expected_hash = ObjectiveTargetEvaluationIdentifier(target).eval_hash now = datetime.now(UTC) @@ -269,9 +271,9 @@ def test_get_cached_results_for_technique_sorts_newest_first(): newest = _make_attack_with_target(target, timestamp=now) memory = MagicMock(spec=MemoryInterface) - memory.get_attack_results.return_value = [older, newest, middle] + memory.get_attack_results_async = AsyncMock(return_value=[older, newest, middle]) - results = get_cached_results_for_technique( + results = await get_cached_results_for_technique_async( memory, technique_eval_hash="tech-hash", objective_target_eval_hash=expected_hash, @@ -280,18 +282,20 @@ def test_get_cached_results_for_technique_sorts_newest_first(): assert [r.timestamp for r in results] == [newest.timestamp, middle.timestamp, older.timestamp] -def test_get_cached_results_for_technique_builds_default_sql_filter(): +async def test_get_cached_results_for_technique_builds_default_sql_filter(): memory = MagicMock(spec=MemoryInterface) - memory.get_attack_results.return_value = [] - - get_cached_results_for_technique( - memory, - technique_eval_hash="tech-hash-xyz", - objective_target_eval_hash="target-hash", + memory.get_attack_results_async = AsyncMock(return_value=[]) + + ( + await get_cached_results_for_technique_async( + memory, + technique_eval_hash="tech-hash-xyz", + objective_target_eval_hash="target-hash", + ) ) - memory.get_attack_results.assert_called_once() - filters = memory.get_attack_results.call_args.kwargs["identifier_filters"] + memory.get_attack_results_async.assert_called_once() + filters = memory.get_attack_results_async.call_args.kwargs["identifier_filters"] assert len(filters) == 1 sole = filters[0] assert sole.identifier_type == IdentifierType.ATTACK @@ -299,28 +303,30 @@ def test_get_cached_results_for_technique_builds_default_sql_filter(): assert sole.value == "tech-hash-xyz" -def test_get_cached_results_for_technique_appends_additional_filters(): +async def test_get_cached_results_for_technique_appends_additional_filters(): memory = MagicMock(spec=MemoryInterface) - memory.get_attack_results.return_value = [] + memory.get_attack_results_async = AsyncMock(return_value=[]) extra = IdentifierFilter( identifier_type=IdentifierType.ATTACK, property_path="$.children.attack_technique.children.attack.class_name", value="PromptSendingAttack", ) - get_cached_results_for_technique( - memory, - technique_eval_hash="tech-hash", - objective_target_eval_hash="target-hash", - additional_filters=[extra], + ( + await get_cached_results_for_technique_async( + memory, + technique_eval_hash="tech-hash", + objective_target_eval_hash="target-hash", + additional_filters=[extra], + ) ) - filters = memory.get_attack_results.call_args.kwargs["identifier_filters"] + filters = memory.get_attack_results_async.call_args.kwargs["identifier_filters"] assert len(filters) == 2 assert filters[1] is extra -def test_get_cached_results_for_technique_skips_results_without_identifier(): +async def test_get_cached_results_for_technique_skips_results_without_identifier(): """Results with no atomic_attack_identifier are ignored, not raised on.""" target = _make_target_component() expected_hash = ObjectiveTargetEvaluationIdentifier(target).eval_hash @@ -333,9 +339,9 @@ def test_get_cached_results_for_technique_skips_results_without_identifier(): ) memory = MagicMock(spec=MemoryInterface) - memory.get_attack_results.return_value = [orphan, matching] + memory.get_attack_results_async = AsyncMock(return_value=[orphan, matching]) - results = get_cached_results_for_technique( + results = await get_cached_results_for_technique_async( memory, technique_eval_hash="tech-hash", objective_target_eval_hash=expected_hash, diff --git a/tests/unit/analytics/test_technique_analysis.py b/tests/unit/analytics/test_technique_analysis.py index 04b1d94890..f02b8a9347 100644 --- a/tests/unit/analytics/test_technique_analysis.py +++ b/tests/unit/analytics/test_technique_analysis.py @@ -1,11 +1,12 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -from unittest.mock import MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest -from pyrit.analytics.technique_analysis import compute_technique_stats +from pyrit.analytics.technique_analysis import compute_technique_stats_async +from pyrit.memory import MemoryInterface from pyrit.models import AttackOutcome @@ -23,32 +24,34 @@ def _make_result(*, eval_hash: str | None, outcome: AttackOutcome) -> MagicMock: @pytest.fixture(autouse=True) def _patch_memory(): - mock_memory = MagicMock() - mock_memory.get_attack_results.return_value = [] + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_attack_results_async = AsyncMock(return_value=[]) with patch("pyrit.analytics.technique_analysis.CentralMemory") as cm: cm.get_memory_instance.return_value = mock_memory yield mock_memory class TestComputeTechniqueStats: - def test_empty_results_returns_empty(self, _patch_memory): - stats = compute_technique_stats(technique_eval_hashes=["a", "b"]) + async def test_empty_results_returns_empty(self, _patch_memory): + stats = await compute_technique_stats_async(technique_eval_hashes=["a", "b"]) assert stats == {} - def test_empty_hashes_short_circuits(self, _patch_memory): - stats = compute_technique_stats(technique_eval_hashes=[]) + async def test_empty_hashes_short_circuits(self, _patch_memory): + stats = await compute_technique_stats_async(technique_eval_hashes=[]) assert stats == {} - _patch_memory.get_attack_results.assert_not_called() - - def test_counts_successes_and_failures(self, _patch_memory): - _patch_memory.get_attack_results.return_value = [ - _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), - _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), - _make_result(eval_hash="a", outcome=AttackOutcome.FAILURE), - _make_result(eval_hash="b", outcome=AttackOutcome.FAILURE), - ] + _patch_memory.get_attack_results_async.assert_not_called() + + async def test_counts_successes_and_failures(self, _patch_memory): + _patch_memory.get_attack_results_async = AsyncMock( + return_value=[ + _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), + _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), + _make_result(eval_hash="a", outcome=AttackOutcome.FAILURE), + _make_result(eval_hash="b", outcome=AttackOutcome.FAILURE), + ] + ) - stats = compute_technique_stats(technique_eval_hashes=["a", "b"]) + stats = await compute_technique_stats_async(technique_eval_hashes=["a", "b"]) assert stats["a"].successes == 2 assert stats["a"].failures == 1 @@ -56,91 +59,105 @@ def test_counts_successes_and_failures(self, _patch_memory): assert stats["b"].successes == 0 assert stats["b"].failures == 1 - def test_counts_errors_and_undetermined(self, _patch_memory): - _patch_memory.get_attack_results.return_value = [ - _make_result(eval_hash="a", outcome=AttackOutcome.ERROR), - _make_result(eval_hash="a", outcome=AttackOutcome.UNDETERMINED), - ] + async def test_counts_errors_and_undetermined(self, _patch_memory): + _patch_memory.get_attack_results_async = AsyncMock( + return_value=[ + _make_result(eval_hash="a", outcome=AttackOutcome.ERROR), + _make_result(eval_hash="a", outcome=AttackOutcome.UNDETERMINED), + ] + ) - stats = compute_technique_stats(technique_eval_hashes=["a"]) + stats = await compute_technique_stats_async(technique_eval_hashes=["a"]) assert stats["a"].errors == 1 assert stats["a"].undetermined == 1 - def test_ignores_hashes_not_in_requested_list(self, _patch_memory): - _patch_memory.get_attack_results.return_value = [ - _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), - _make_result(eval_hash="c", outcome=AttackOutcome.SUCCESS), - ] + async def test_ignores_hashes_not_in_requested_list(self, _patch_memory): + _patch_memory.get_attack_results_async = AsyncMock( + return_value=[ + _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), + _make_result(eval_hash="c", outcome=AttackOutcome.SUCCESS), + ] + ) - stats = compute_technique_stats(technique_eval_hashes=["a", "b"]) + stats = await compute_technique_stats_async(technique_eval_hashes=["a", "b"]) assert "a" in stats assert "c" not in stats - def test_skips_results_without_eval_hash(self, _patch_memory): - _patch_memory.get_attack_results.return_value = [ - _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), - _make_result(eval_hash=None, outcome=AttackOutcome.SUCCESS), - ] + async def test_skips_results_without_eval_hash(self, _patch_memory): + _patch_memory.get_attack_results_async = AsyncMock( + return_value=[ + _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), + _make_result(eval_hash=None, outcome=AttackOutcome.SUCCESS), + ] + ) - stats = compute_technique_stats(technique_eval_hashes=["a"]) + stats = await compute_technique_stats_async(technique_eval_hashes=["a"]) assert stats["a"].successes == 1 - def test_passes_eval_hashes_to_memory_query(self, _patch_memory): - compute_technique_stats(technique_eval_hashes=["x", "y"]) + async def test_passes_eval_hashes_to_memory_query(self, _patch_memory): + (await compute_technique_stats_async(technique_eval_hashes=["x", "y"])) - call_kwargs = _patch_memory.get_attack_results.call_args[1] + call_kwargs = _patch_memory.get_attack_results_async.call_args[1] assert call_kwargs["atomic_attack_eval_hashes"] == ["x", "y"] assert call_kwargs["scenario_result_id"] is None assert call_kwargs["targeted_harm_categories"] is None - def test_passes_scenario_result_id_to_memory_query(self, _patch_memory): - compute_technique_stats(technique_eval_hashes=["x"], scenario_result_id="run-123") + async def test_passes_scenario_result_id_to_memory_query(self, _patch_memory): + (await compute_technique_stats_async(technique_eval_hashes=["x"], scenario_result_id="run-123")) - call_kwargs = _patch_memory.get_attack_results.call_args[1] + call_kwargs = _patch_memory.get_attack_results_async.call_args[1] assert call_kwargs["scenario_result_id"] == "run-123" - def test_omits_hashes_with_no_history(self, _patch_memory): - _patch_memory.get_attack_results.return_value = [ - _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), - ] + async def test_omits_hashes_with_no_history(self, _patch_memory): + _patch_memory.get_attack_results_async = AsyncMock( + return_value=[ + _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), + ] + ) - stats = compute_technique_stats(technique_eval_hashes=["a", "b"]) + stats = await compute_technique_stats_async(technique_eval_hashes=["a", "b"]) assert "a" in stats assert "b" not in stats - def test_success_rate_computed(self, _patch_memory): - _patch_memory.get_attack_results.return_value = [ - _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), - _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), - _make_result(eval_hash="a", outcome=AttackOutcome.FAILURE), - _make_result(eval_hash="a", outcome=AttackOutcome.FAILURE), - ] + async def test_success_rate_computed(self, _patch_memory): + _patch_memory.get_attack_results_async = AsyncMock( + return_value=[ + _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), + _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), + _make_result(eval_hash="a", outcome=AttackOutcome.FAILURE), + _make_result(eval_hash="a", outcome=AttackOutcome.FAILURE), + ] + ) - stats = compute_technique_stats(technique_eval_hashes=["a"]) + stats = await compute_technique_stats_async(technique_eval_hashes=["a"]) assert stats["a"].success_rate == pytest.approx(0.5) - def test_passes_harm_categories_to_memory_query(self, _patch_memory): - compute_technique_stats( - technique_eval_hashes=["x"], - targeted_harm_categories=["misinformation", "hate"], + async def test_passes_harm_categories_to_memory_query(self, _patch_memory): + ( + await compute_technique_stats_async( + technique_eval_hashes=["x"], + targeted_harm_categories=["misinformation", "hate"], + ) ) - call_kwargs = _patch_memory.get_attack_results.call_args[1] + call_kwargs = _patch_memory.get_attack_results_async.call_args[1] assert call_kwargs["targeted_harm_categories"] == ["misinformation", "hate"] - def test_injected_memory_bypasses_central_memory(self, _patch_memory): + async def test_injected_memory_bypasses_central_memory(self, _patch_memory): injected = MagicMock() - injected.get_attack_results.return_value = [ - _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), - ] + injected.get_attack_results_async = AsyncMock( + return_value=[ + _make_result(eval_hash="a", outcome=AttackOutcome.SUCCESS), + ] + ) - stats = compute_technique_stats(technique_eval_hashes=["a"], memory=injected) + stats = await compute_technique_stats_async(technique_eval_hashes=["a"], memory=injected) - injected.get_attack_results.assert_called_once() - _patch_memory.get_attack_results.assert_not_called() + injected.get_attack_results_async.assert_called_once() + _patch_memory.get_attack_results_async.assert_not_called() assert stats["a"].successes == 1 diff --git a/tests/unit/backend/mocks.py b/tests/unit/backend/mocks.py index 6a6ed7b517..000203a384 100644 --- a/tests/unit/backend/mocks.py +++ b/tests/unit/backend/mocks.py @@ -6,6 +6,7 @@ from datetime import UTC, datetime from unittest.mock import MagicMock +from pyrit.memory import MemoryInterface from pyrit.models import AtomicAttackIdentifier, AttackOutcome, AttackResult, ComponentIdentifier from pyrit.prompt_target import PromptTarget @@ -72,12 +73,12 @@ def _make_matching_target_mock() -> MagicMock: def make_mock_memory() -> MagicMock: """Create a mock memory instance.""" - memory = MagicMock() - memory.get_attack_results.return_value = [] - memory.get_conversation_messages.return_value = [] - memory.get_message_pieces.return_value = [] - memory.get_conversation_stats.return_value = {} - memory._get_conversation.return_value = None - memory.get_prompt_scores.return_value = [] + memory = MagicMock(spec=MemoryInterface) + memory.get_attack_results_async.return_value = [] + memory.get_conversation_messages_async.return_value = [] + memory.get_message_pieces_async.return_value = [] + memory.get_conversation_stats_async.return_value = {} + memory.get_conversation_metadata_async.return_value = None + memory.get_prompt_scores_async.return_value = [] return memory diff --git a/tests/unit/backend/test_api_routes.py b/tests/unit/backend/test_api_routes.py index 17787e9936..e512b8e6cc 100644 --- a/tests/unit/backend/test_api_routes.py +++ b/tests/unit/backend/test_api_routes.py @@ -44,6 +44,7 @@ from pyrit.backend.routes.scores import _get_user_identifier from pyrit.backend.services.attack_service import AttackObjectiveConflictError from pyrit.backend.services.manual_send_scheduler import ManualSendConflictError, ManualSendQueueFullError +from pyrit.memory import MemoryInterface from pyrit.models import AttackOutcome, ConverterIdentifier, MessagePiece, Score, TargetCapabilities, TargetIdentifier from pyrit.models.catalog.target import TargetInstance @@ -1645,18 +1646,20 @@ def test_create_manual_score_for_forked_conversation(self, client: TestClient) - patch("pyrit.backend.routes.scores.ManualScorer") as mock_manual_scorer_class, ): memory = mock_memory_class.get_memory_instance.return_value - memory.get_message_pieces.return_value = [ - MagicMock(id=message_id, conversation_id="forked-conversation-id") - ] - memory.get_attack_results.return_value = [ - MagicMock( - attack_result_id=str(attack_result_id), - objective="Evaluate the response", - get_active_conversation_ids=MagicMock( - return_value={"primary-conversation-id", "forked-conversation-id"} - ), - ) - ] + memory.get_message_pieces_async = AsyncMock( + return_value=[MagicMock(id=message_id, conversation_id="forked-conversation-id")] + ) + memory.get_attack_results_async = AsyncMock( + return_value=[ + MagicMock( + attack_result_id=str(attack_result_id), + objective="Evaluate the response", + get_active_conversation_ids=MagicMock( + return_value={"primary-conversation-id", "forked-conversation-id"} + ), + ) + ] + ) mock_scorer = mock_manual_scorer_class.return_value mock_scorer.score_async = AsyncMock(return_value=[score]) @@ -1681,8 +1684,8 @@ def test_create_manual_score_for_forked_conversation(self, client: TestClient) - ) scorable = mock_scorer.score_async.await_args.kwargs["scorable"] assert scorable.message_piece_ids == (message_id,) - memory.get_attack_results.assert_called_once_with(attack_result_ids=[str(attack_result_id)]) - memory.update_attack_result_by_id.assert_not_called() + memory.get_attack_results_async.assert_called_once_with(attack_result_ids=[str(attack_result_id)]) + memory.update_attack_result_by_id_async.assert_not_called() def test_create_manual_true_false_score(self, client: TestClient) -> None: """Test creating and persisting a true/false manual score.""" @@ -1700,15 +1703,19 @@ def test_create_manual_true_false_score(self, client: TestClient) -> None: patch("pyrit.backend.routes.scores.ManualScorer") as mock_manual_scorer_class, ): memory = mock_memory_class.get_memory_instance.return_value - memory.get_message_pieces.return_value = [MagicMock(id=message_id, conversation_id="conversation-id")] - memory.get_attack_results.return_value = [ - MagicMock( - attack_result_id=str(attack_result_id), - objective="Evaluate the response", - get_active_conversation_ids=MagicMock(return_value={"conversation-id"}), - ) - ] - memory.update_attack_result_by_id.return_value = True + memory.get_message_pieces_async = AsyncMock( + return_value=[MagicMock(id=message_id, conversation_id="conversation-id")] + ) + memory.get_attack_results_async = AsyncMock( + return_value=[ + MagicMock( + attack_result_id=str(attack_result_id), + objective="Evaluate the response", + get_active_conversation_ids=MagicMock(return_value={"conversation-id"}), + ) + ] + ) + memory.update_attack_result_by_id_async = AsyncMock(return_value=True) mock_scorer = mock_manual_scorer_class.return_value mock_scorer.score_async = AsyncMock(return_value=[score]) @@ -1732,7 +1739,7 @@ def test_create_manual_true_false_score(self, client: TestClient) -> None: rationale="Objective achieved", user_identifier="local-development", ) - update_fields = memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + update_fields = memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] assert update_fields["human_score_id"] == score.id assert update_fields["outcome"] == AttackOutcome.SUCCESS @@ -1752,14 +1759,18 @@ def test_create_manual_score_preserves_existing_attack_score(self, client: TestC patch("pyrit.backend.routes.scores.ManualScorer") as mock_manual_scorer_class, ): memory = mock_memory_class.get_memory_instance.return_value - memory.get_message_pieces.return_value = [MagicMock(id=message_id, conversation_id="conversation-id")] - memory.get_attack_results.return_value = [ - MagicMock( - attack_result_id=str(attack_result_id), - objective="Evaluate the response", - get_active_conversation_ids=MagicMock(return_value={"conversation-id"}), - ) - ] + memory.get_message_pieces_async = AsyncMock( + return_value=[MagicMock(id=message_id, conversation_id="conversation-id")] + ) + memory.get_attack_results_async = AsyncMock( + return_value=[ + MagicMock( + attack_result_id=str(attack_result_id), + objective="Evaluate the response", + get_active_conversation_ids=MagicMock(return_value={"conversation-id"}), + ) + ] + ) mock_manual_scorer_class.return_value.score_async = AsyncMock(return_value=[score]) response = client.post( @@ -1773,7 +1784,7 @@ def test_create_manual_score_preserves_existing_attack_score(self, client: TestC ) assert response.status_code == status.HTTP_201_CREATED - memory.update_attack_result_by_id.assert_not_called() + memory.update_attack_result_by_id_async.assert_not_called() def test_create_false_manual_score_sets_attack_failure(self, client: TestClient) -> None: """Test that a false manual verdict updates the attack to failure.""" @@ -1791,15 +1802,19 @@ def test_create_false_manual_score_sets_attack_failure(self, client: TestClient) patch("pyrit.backend.routes.scores.ManualScorer") as mock_manual_scorer_class, ): memory = mock_memory_class.get_memory_instance.return_value - memory.get_message_pieces.return_value = [MagicMock(id=message_id, conversation_id="conversation-id")] - memory.get_attack_results.return_value = [ - MagicMock( - attack_result_id=str(attack_result_id), - objective="Evaluate the response", - get_active_conversation_ids=MagicMock(return_value={"conversation-id"}), - ) - ] - memory.update_attack_result_by_id.return_value = True + memory.get_message_pieces_async = AsyncMock( + return_value=[MagicMock(id=message_id, conversation_id="conversation-id")] + ) + memory.get_attack_results_async = AsyncMock( + return_value=[ + MagicMock( + attack_result_id=str(attack_result_id), + objective="Evaluate the response", + get_active_conversation_ids=MagicMock(return_value={"conversation-id"}), + ) + ] + ) + memory.update_attack_result_by_id_async = AsyncMock(return_value=True) mock_manual_scorer_class.return_value.score_async = AsyncMock(return_value=[score]) response = client.post( @@ -1814,7 +1829,7 @@ def test_create_false_manual_score_sets_attack_failure(self, client: TestClient) ) assert response.status_code == status.HTTP_201_CREATED - update_fields = memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + update_fields = memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] assert update_fields["outcome"] == AttackOutcome.FAILURE def test_create_manual_score_message_not_found(self, client: TestClient) -> None: @@ -1825,7 +1840,7 @@ def test_create_manual_score_message_not_found(self, client: TestClient) -> None patch("pyrit.backend.routes.scores.CentralMemory") as mock_memory_class, patch("pyrit.backend.routes.scores.ManualScorer") as mock_manual_scorer_class, ): - mock_memory_class.get_memory_instance.return_value.get_message_pieces.return_value = [] + mock_memory_class.get_memory_instance.return_value.get_message_pieces_async = AsyncMock(return_value=[]) response = client.post( "/api/scores/manual", @@ -1918,9 +1933,15 @@ def test_create_manual_score_requires_attack_objective(self, client: TestClient) patch("pyrit.backend.routes.scores.ManualScorer") as mock_manual_scorer_class, ): memory = mock_memory_class.get_memory_instance.return_value - memory.get_message_pieces.return_value = [MagicMock(id=message_id, conversation_id="conversation-id")] - memory.get_attack_results.return_value = [MagicMock(objective="", attack_result_id=str(attack_result_id))] - memory.get_attack_results.return_value[0].get_active_conversation_ids.return_value = {"conversation-id"} + memory.get_message_pieces_async = AsyncMock( + return_value=[MagicMock(id=message_id, conversation_id="conversation-id")] + ) + memory.get_attack_results_async = AsyncMock( + return_value=[MagicMock(objective="", attack_result_id=str(attack_result_id))] + ) + memory.get_attack_results_async.return_value[0].get_active_conversation_ids.return_value = { + "conversation-id" + } response = client.post( "/api/scores/manual", @@ -1946,16 +1967,18 @@ def test_create_manual_score_rejects_internal_adversarial_message(self, client: patch("pyrit.backend.routes.scores.ManualScorer") as mock_manual_scorer_class, ): memory = mock_memory_class.get_memory_instance.return_value - memory.get_message_pieces.return_value = [ - MagicMock(id=message_id, conversation_id="internal-adversarial-conversation-id") - ] - memory.get_attack_results.return_value = [ - MagicMock( - objective="Evaluate the response", - attack_result_id=str(attack_result_id), - get_active_conversation_ids=MagicMock(return_value={"conversation-id"}), - ) - ] + memory.get_message_pieces_async = AsyncMock( + return_value=[MagicMock(id=message_id, conversation_id="internal-adversarial-conversation-id")] + ) + memory.get_attack_results_async = AsyncMock( + return_value=[ + MagicMock( + objective="Evaluate the response", + attack_result_id=str(attack_result_id), + get_active_conversation_ids=MagicMock(return_value={"conversation-id"}), + ) + ] + ) response = client.post( "/api/scores/manual", @@ -2000,9 +2023,11 @@ class TestLabelsRoutes: def test_get_labels_for_attacks(self, client: TestClient) -> None: """Test getting labels from attack results.""" with patch("pyrit.backend.routes.labels.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_unique_attack_labels.return_value = {"env": ["prod"], "team": ["red"]} - mock_memory.get_unique_attack_attribution.return_value = {"operators": [], "operations": []} + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_unique_attack_labels_async = AsyncMock(return_value={"env": ["prod"], "team": ["red"]}) + mock_memory.get_unique_attack_attribution_async = AsyncMock( + return_value={"operators": [], "operations": []} + ) mock_memory_class.get_memory_instance.return_value = mock_memory response = client.get("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/api/labels?source=attacks") @@ -2013,7 +2038,7 @@ def test_get_labels_for_attacks(self, client: TestClient) -> None: assert data["labels"] == {"env": ["prod"], "team": ["red"]} assert data["operators"] == [] assert data["operations"] == [] - mock_memory.get_unique_attack_labels.assert_called_once_with( + mock_memory.get_unique_attack_labels_async.assert_called_once_with( operator=None, operation=None, labels=None, @@ -2021,12 +2046,14 @@ def test_get_labels_for_attacks(self, client: TestClient) -> None: def test_get_labels_for_attacks_passes_narrowing_filters(self, client: TestClient) -> None: with patch("pyrit.backend.routes.labels.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_unique_attack_labels.return_value = {"env": ["prod"]} - mock_memory.get_unique_attack_attribution.return_value = { - "operators": ["alice", "bob"], - "operations": ["nightly"], - } + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_unique_attack_labels_async = AsyncMock(return_value={"env": ["prod"]}) + mock_memory.get_unique_attack_attribution_async = AsyncMock( + return_value={ + "operators": ["alice", "bob"], + "operations": ["nightly"], + } + ) mock_memory_class.get_memory_instance.return_value = mock_memory response = client.get( @@ -2039,19 +2066,21 @@ def test_get_labels_for_attacks_passes_narrowing_filters(self, client: TestClien ) assert response.status_code == status.HTTP_200_OK - mock_memory.get_unique_attack_labels.assert_called_once_with( + mock_memory.get_unique_attack_labels_async.assert_called_once_with( operator=["alice"], operation=["nightly"], labels={"team": ["red"]}, ) - mock_memory.get_unique_attack_attribution.assert_not_called() + mock_memory.get_unique_attack_attribution_async.assert_not_called() def test_get_labels_empty(self, client: TestClient) -> None: """Test getting labels when no attack results exist.""" with patch("pyrit.backend.routes.labels.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_unique_attack_labels.return_value = {} - mock_memory.get_unique_attack_attribution.return_value = {"operators": [], "operations": []} + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_unique_attack_labels_async = AsyncMock(return_value={}) + mock_memory.get_unique_attack_attribution_async = AsyncMock( + return_value={"operators": [], "operations": []} + ) mock_memory_class.get_memory_instance.return_value = mock_memory response = client.get("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/api/labels?source=attacks") @@ -2064,12 +2093,16 @@ def test_get_labels_empty(self, client: TestClient) -> None: def test_get_labels_multiple_values(self, client: TestClient) -> None: """Test getting labels with multiple values per key.""" with patch("pyrit.backend.routes.labels.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_unique_attack_labels.return_value = { - "env": ["prod", "staging"], - "team": ["blue"], - } - mock_memory.get_unique_attack_attribution.return_value = {"operators": [], "operations": []} + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_unique_attack_labels_async = AsyncMock( + return_value={ + "env": ["prod", "staging"], + "team": ["blue"], + } + ) + mock_memory.get_unique_attack_attribution_async = AsyncMock( + return_value={"operators": [], "operations": []} + ) mock_memory_class.get_memory_instance.return_value = mock_memory response = client.get("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/api/labels") @@ -2082,12 +2115,14 @@ def test_get_labels_multiple_values(self, client: TestClient) -> None: def test_get_labels_returns_keys_without_normalization(self, client: TestClient) -> None: """Attack attribution options are separate from arbitrary labels.""" with patch("pyrit.backend.routes.labels.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_unique_attack_labels.return_value = {"team": ["red"]} - mock_memory.get_unique_attack_attribution.return_value = { - "operators": ["alice", "bob"], - "operations": ["hunt", "scan"], - } + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_unique_attack_labels_async = AsyncMock(return_value={"team": ["red"]}) + mock_memory.get_unique_attack_attribution_async = AsyncMock( + return_value={ + "operators": ["alice", "bob"], + "operations": ["hunt", "scan"], + } + ) mock_memory_class.get_memory_instance.return_value = mock_memory response = client.get("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/api/labels") @@ -2107,12 +2142,12 @@ async def test_get_label_options_rejects_unsupported_source(self, client: TestCl async def test_get_scenario_label_options(self, client: TestClient) -> None: """Test that scenario labels use the scenario memory source.""" with patch("pyrit.backend.routes.labels.CentralMemory") as mock_central_memory: - mock_memory = MagicMock() - mock_memory.get_unique_scenario_labels.return_value = {"operator": ["alice"]} + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_unique_scenario_labels_async = AsyncMock(return_value={"operator": ["alice"]}) mock_central_memory.get_memory_instance.return_value = mock_memory response = client.get("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/api/labels?source=scenarios") assert response.status_code == status.HTTP_200_OK assert response.json() == {"source": "scenarios", "labels": {"operator": ["alice"]}} - mock_memory.get_unique_scenario_labels.assert_called_once_with() + mock_memory.get_unique_scenario_labels_async.assert_called_once_with() diff --git a/tests/unit/backend/test_attack_service.py b/tests/unit/backend/test_attack_service.py index 54710d79e7..716333c488 100644 --- a/tests/unit/backend/test_attack_service.py +++ b/tests/unit/backend/test_attack_service.py @@ -239,7 +239,7 @@ class TestListAttacks: async def test_list_attacks_returns_empty_when_no_attacks(self, attack_service, mock_memory) -> None: """Test that list_attacks returns empty list when no AttackResults exist.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] result = await attack_service.list_attacks_async() @@ -249,8 +249,8 @@ async def test_list_attacks_returns_empty_when_no_attacks(self, attack_service, async def test_list_attacks_returns_attacks(self, attack_service, mock_memory) -> None: """Test that list_attacks returns attacks from AttackResult records.""" ar = make_attack_result() - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] result = await attack_service.list_attacks_async() @@ -261,45 +261,45 @@ async def test_list_attacks_returns_attacks(self, attack_service, mock_memory) - async def test_list_attacks_filters_by_attack_types_exact(self, attack_service, mock_memory) -> None: """Test that list_attacks passes attack_types to memory layer.""" 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 = [] + mock_memory.get_attack_results_async.return_value = [ar1] + mock_memory.get_message_pieces_async.return_value = [] result = await attack_service.list_attacks_async(attack_types=["CrescendoAttack"]) assert len(result.items) == 1 assert result.items[0].conversation_id == "attack-1" # Verify attack_types was forwarded to the memory layer as attack_classes - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["attack_classes"] == ["CrescendoAttack"] async def test_list_attacks_attack_types_passed_to_memory(self, attack_service, mock_memory) -> None: """Test that attack_types is forwarded to memory as attack_classes for DB-level filtering.""" - mock_memory.get_attack_results.return_value = [] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [] + mock_memory.get_message_pieces_async.return_value = [] await attack_service.list_attacks_async(attack_types=["Crescendo"]) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["attack_classes"] == ["Crescendo"] async def test_list_attacks_filters_by_attack_types_multi(self, attack_service, mock_memory) -> None: """Test that multiple attack_types are forwarded as a list to memory for OR-matching.""" - mock_memory.get_attack_results.return_value = [] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [] + mock_memory.get_message_pieces_async.return_value = [] await attack_service.list_attacks_async(attack_types=["CrescendoAttack", "ManualAttack"]) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["attack_classes"] == ["CrescendoAttack", "ManualAttack"] async def test_list_attacks_attack_types_empty_list_coerced_to_none(self, attack_service, mock_memory) -> None: """Test that attack_types=[] is coerced to None before reaching memory (no filter).""" - mock_memory.get_attack_results.return_value = [] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [] + mock_memory.get_message_pieces_async.return_value = [] await attack_service.list_attacks_async(attack_types=[]) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["attack_classes"] is None async def test_list_attacks_coerces_empty_converter_types_to_no_filter(self, attack_service, mock_memory) -> None: @@ -308,42 +308,42 @@ async def test_list_attacks_coerces_empty_converter_types_to_no_filter(self, att The 'attacks with no converters' intent is expressed via has_converters=False; an empty list is coerced to None so route/service/memory stay consistent. """ - mock_memory.get_attack_results.return_value = [] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [] + mock_memory.get_message_pieces_async.return_value = [] await attack_service.list_attacks_async(converter_types=[]) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["converter_classes"] is None assert call_kwargs["has_converters"] is None async def test_list_attacks_forwards_has_converters_true(self, attack_service, mock_memory) -> None: """has_converters=True is forwarded to memory.""" - mock_memory.get_attack_results.return_value = [] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [] + mock_memory.get_message_pieces_async.return_value = [] await attack_service.list_attacks_async(has_converters=True) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["has_converters"] is True async def test_list_attacks_forwards_has_converters_false(self, attack_service, mock_memory) -> None: """has_converters=False is forwarded to memory.""" - mock_memory.get_attack_results.return_value = [] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [] + mock_memory.get_message_pieces_async.return_value = [] await attack_service.list_attacks_async(has_converters=False) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["has_converters"] is False async def test_list_attacks_forwards_scenario_attack_filter(self, attack_service, mock_memory) -> None: """The scenario-attack inclusion flag is forwarded to memory.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] await attack_service.list_attacks_async(include_scenario_attacks=False) - assert mock_memory.get_attack_results.call_args.kwargs["include_scenario_attacks"] is False + assert mock_memory.get_attack_results_async.call_args.kwargs["include_scenario_attacks"] is False 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.""" @@ -374,15 +374,15 @@ async def test_list_attacks_filters_by_converter_types_and_logic(self, attack_se }, ), ) - mock_memory.get_attack_results.return_value = [ar1] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar1] + mock_memory.get_message_pieces_async.return_value = [] 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_types was forwarded to the memory layer with default "all" mode - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["converter_classes"] == ["Base64Converter", "ROT13Converter"] assert call_kwargs["converter_classes_match"] == "all" @@ -390,15 +390,15 @@ async def test_list_attacks_converter_match_all_explicit_pushes_to_memory( self, attack_service, mock_memory ) -> None: """Explicit converter_types_match='all' still pushes converter filter to memory.""" - mock_memory.get_attack_results.return_value = [] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [] + mock_memory.get_message_pieces_async.return_value = [] await attack_service.list_attacks_async( converter_types=["Base64Converter", "ROT13Converter"], converter_types_match="all", ) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["converter_classes"] == ["Base64Converter", "ROT13Converter"] assert call_kwargs["converter_classes_match"] == "all" @@ -410,15 +410,15 @@ async def test_list_attacks_converter_match_any_single_converter_pushes_to_memor The memory layer ignores the match mode when the list has fewer than 2 entries, but the service still forwards the mode verbatim (memory is authoritative for that optimization). """ - mock_memory.get_attack_results.return_value = [] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [] + mock_memory.get_message_pieces_async.return_value = [] await attack_service.list_attacks_async( converter_types=["Base64Converter"], converter_types_match="any", ) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["converter_classes"] == ["Base64Converter"] assert call_kwargs["converter_classes_match"] == "any" @@ -429,34 +429,34 @@ async def test_list_attacks_converter_match_any_pushes_to_memory(self, attack_se with a set intersection, which was O(total rows) per query. The OR-matching is now expressed as a DB predicate so only matching rows are returned and pagination is honored. """ - mock_memory.get_attack_results.return_value = [] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [] + mock_memory.get_message_pieces_async.return_value = [] await attack_service.list_attacks_async( converter_types=["Base64Converter", "ROT13Converter"], converter_types_match="any", ) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["converter_classes"] == ["Base64Converter", "ROT13Converter"] assert call_kwargs["converter_classes_match"] == "any" async def test_list_attacks_forwards_min_turns(self, attack_service, mock_memory) -> None: """min_turns is forwarded to the memory query (filtering now happens in SQL).""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] await attack_service.list_attacks_async(min_turns=3) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["min_turns"] == 3 async def test_list_attacks_forwards_max_turns(self, attack_service, mock_memory) -> None: """max_turns is forwarded to the memory query (filtering now happens in SQL).""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] await attack_service.list_attacks_async(max_turns=3) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["max_turns"] == 3 async def test_list_attacks_includes_labels_in_summary(self, attack_service, mock_memory) -> None: @@ -464,8 +464,8 @@ async def test_list_attacks_includes_labels_in_summary(self, attack_service, moc ar = make_attack_result( conversation_id="attack-1", ) - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_stats.return_value = { + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_stats_async.return_value = { "attack-1": ConversationStats( message_count=1, last_message_preview="test", @@ -481,9 +481,9 @@ async def test_list_attacks_includes_labels_in_summary(self, attack_service, moc async def test_list_attacks_formats_media_preview(self, attack_service, mock_memory) -> None: """list_attacks AttackSummary previews must not leak absolute media paths.""" ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] path = r"C:\Users\someone\PyRIT\dbdata\prompt-memory-entries\images\1780010098266691.png" - mock_memory.get_conversation_stats.return_value = { + mock_memory.get_conversation_stats_async.return_value = { "attack-1": ConversationStats( message_count=1, last_message_preview=path, @@ -504,26 +504,26 @@ async def test_list_attacks_filters_by_dedicated_attribution(self, attack_servic ar.operator = "alice" ar.operation = "red" - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_stats.side_effect = lambda conversation_ids: { + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_stats_async.side_effect = lambda conversation_ids: { cid: ConversationStats(message_count=1) for cid in conversation_ids } result = await attack_service.list_attacks_async(operator=["alice"], operation=["red"]) assert len(result.items) == 1 - mock_memory.get_attack_results.assert_called_once() - call_kwargs = mock_memory.get_attack_results.call_args[1] + mock_memory.get_attack_results_async.assert_called_once() + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["operator"] == ["alice"] assert call_kwargs["operation"] == ["red"] async def test_list_attacks_forwards_min_and_max_turns(self, attack_service, mock_memory) -> None: """Both min_turns and max_turns are forwarded to the memory query.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] await attack_service.list_attacks_async(min_turns=2, max_turns=5) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["min_turns"] == 2 assert call_kwargs["max_turns"] == 5 @@ -539,21 +539,21 @@ class TestAttackOptions: async def test_returns_empty_when_no_attacks(self, attack_service, mock_memory) -> None: """Test that attack options returns empty list when no attacks exist.""" - mock_memory.get_unique_attack_class_names.return_value = [] + mock_memory.get_unique_attack_class_names_async.return_value = [] result = await attack_service.get_attack_options_async() assert result == [] - mock_memory.get_unique_attack_class_names.assert_called_once() + mock_memory.get_unique_attack_class_names_async.assert_called_once() async def test_returns_result_from_memory(self, attack_service, mock_memory) -> None: """Test that attack options delegates to memory layer.""" - mock_memory.get_unique_attack_class_names.return_value = ["CrescendoAttack", "ManualAttack"] + mock_memory.get_unique_attack_class_names_async.return_value = ["CrescendoAttack", "ManualAttack"] result = await attack_service.get_attack_options_async() assert result == ["CrescendoAttack", "ManualAttack"] - mock_memory.get_unique_attack_class_names.assert_called_once() + mock_memory.get_unique_attack_class_names_async.assert_called_once() # ============================================================================ @@ -567,21 +567,21 @@ class TestConverterOptions: async def test_returns_empty_when_no_attacks(self, attack_service, mock_memory) -> None: """Test that converter options returns empty list when no attacks exist.""" - mock_memory.get_unique_converter_class_names.return_value = [] + mock_memory.get_unique_converter_class_names_async.return_value = [] result = await attack_service.get_converter_options_async() assert result == [] - mock_memory.get_unique_converter_class_names.assert_called_once() + mock_memory.get_unique_converter_class_names_async.assert_called_once() async def test_returns_result_from_memory(self, attack_service, mock_memory) -> None: """Test that converter options delegates to memory layer.""" - mock_memory.get_unique_converter_class_names.return_value = ["Base64Converter", "ROT13Converter"] + mock_memory.get_unique_converter_class_names_async.return_value = ["Base64Converter", "ROT13Converter"] result = await attack_service.get_converter_options_async() assert result == ["Base64Converter", "ROT13Converter"] - mock_memory.get_unique_converter_class_names.assert_called_once() + mock_memory.get_unique_converter_class_names_async.assert_called_once() # ============================================================================ @@ -595,7 +595,7 @@ class TestGetAttack: async def test_get_attack_returns_none_for_nonexistent(self, attack_service, mock_memory) -> None: """Test that get_attack returns None when AttackResult doesn't exist.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] result = await attack_service.get_attack_async(attack_result_id="nonexistent") @@ -607,8 +607,8 @@ async def test_get_attack_returns_attack_details(self, attack_service, mock_memo conversation_id="test-id", name="My Attack", ) - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] result = await attack_service.get_attack_async(attack_result_id="test-id") @@ -624,11 +624,11 @@ async def test_get_attack_returns_attack_details(self, attack_service, mock_memo @pytest.mark.usefixtures("patch_central_database") class TestGetConversationMessages: - """Tests for get_conversation_messages method.""" + "Tests for get_conversation_messages_async method." async def test_get_conversation_messages_returns_none_for_nonexistent(self, attack_service, mock_memory) -> None: - """Test that get_conversation_messages returns None when attack doesn't exist.""" - mock_memory.get_attack_results.return_value = [] + "Test that get_conversation_messages_async returns None when attack doesn't exist." + mock_memory.get_attack_results_async.return_value = [] result = await attack_service.get_conversation_messages_async( attack_result_id="nonexistent", conversation_id="any-id" @@ -637,10 +637,10 @@ async def test_get_conversation_messages_returns_none_for_nonexistent(self, atta assert result is None async def test_get_conversation_messages_returns_messages(self, attack_service, mock_memory) -> None: - """Test that get_conversation_messages returns messages for existing attack.""" + "Test that get_conversation_messages_async returns messages for existing attack." ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] result = await attack_service.get_conversation_messages_async( attack_result_id="test-id", conversation_id="test-id" @@ -660,8 +660,8 @@ async def test_get_conversation_messages_returns_latest_target_status_async( ) -> None: """Test that the latest real assistant response is linked to its user request.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [ + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [ _make_message(role="user", sequence=2), _make_message(role="assistant", sequence=3, response_error=response_error), ] @@ -679,8 +679,8 @@ async def test_get_conversation_messages_returns_latest_target_status_async( async def test_get_conversation_messages_ignores_stale_processing_error(self, attack_service, mock_memory) -> None: """Test that a later successful response supersedes an earlier processing failure.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [ + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [ _make_message(role="user", sequence=0), _make_message(role="assistant", sequence=1, response_error="processing"), _make_message(role="user", sequence=2), @@ -706,8 +706,8 @@ async def test_get_conversation_messages_ignores_non_target_latest_message( ) -> None: """Test that user and simulated-assistant history are not classified as target responses.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [ + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [ _make_message(role="user", sequence=0), _make_message(role=latest_role, sequence=1, response_error="processing"), ] @@ -724,8 +724,8 @@ async def test_get_conversation_messages_marks_attack_objective_score(self, atta ar = make_attack_result(conversation_id="test-id") objective_score_id = uuid.uuid4() ar.automated_score = MagicMock(id=objective_score_id) - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] with patch( "pyrit.backend.services.attack_service.pyrit_messages_to_dto_async", @@ -745,8 +745,8 @@ async def test_get_conversation_messages_preserves_string_objective_score_id( ar = make_attack_result(conversation_id="test-id") objective_score_id = str(uuid.uuid4()) ar.automated_score = MagicMock(id=objective_score_id) - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] with patch( "pyrit.backend.services.attack_service.pyrit_messages_to_dto_async", @@ -762,9 +762,9 @@ async def test_get_conversation_messages_preserves_string_objective_score_id( async def test_get_conversation_messages_raises_for_unrelated_conversation( self, attack_service, mock_memory ) -> None: - """Test that get_conversation_messages raises ValueError for a conversation not belonging to the attack.""" + "Test that get_conversation_messages_async raises ValueError for a conversation not belonging to the attack." ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] with pytest.raises(ValueError, match="not part of attack"): await attack_service.get_conversation_messages_async( @@ -817,8 +817,8 @@ async def test_create_attack_stores_attack_result(self, attack_service, mock_mem assert result.conversation_id is not None assert result.created_at is not None - mock_memory.add_attack_results_to_memory.assert_called_once() - stored_attack = mock_memory.add_attack_results_to_memory.call_args.kwargs["attack_results"][0] + mock_memory.add_attack_results_to_memory_async.assert_called_once() + stored_attack = mock_memory.add_attack_results_to_memory_async.call_args.kwargs["attack_results"][0] assert stored_attack.metadata["target_registry_name"] == "target-1" assert stored_attack.operator == "alice" assert stored_attack.operation == "nightly" @@ -849,8 +849,8 @@ async def test_create_attack_stores_prepended_conversation(self, attack_service, assert result.conversation_id is not None # Both attack result and prepended message pieces should be stored - mock_memory.add_attack_results_to_memory.assert_called_once() - mock_memory.add_message_pieces_to_memory.assert_called() + mock_memory.add_attack_results_to_memory_async.assert_called_once() + mock_memory.add_message_pieces_to_memory_async.assert_called() async def test_create_attack_lowers_system_prompt_to_system_message(self, attack_service, mock_memory) -> None: """Test that system_prompt is lowered to a single system-role message at sequence 0.""" @@ -868,7 +868,7 @@ async def test_create_attack_lowers_system_prompt_to_system_message(self, attack request=CreateAttackRequest(target_registry_name="target-1", system_prompt="You are Bob.") ) - calls = mock_memory.add_message_pieces_to_memory.call_args_list + calls = mock_memory.add_message_pieces_to_memory_async.call_args_list assert len(calls) == 1 piece = calls[0][1]["message_pieces"][0] assert piece.api_role == "system" @@ -891,7 +891,7 @@ async def test_create_attack_blank_system_prompt_is_noop(self, attack_service, m request=CreateAttackRequest(target_registry_name="target-1", system_prompt="") ) - mock_memory.add_message_pieces_to_memory.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() async def test_create_attack_system_prompt_prepends_before_prepended_conversation( self, attack_service, mock_memory @@ -919,7 +919,7 @@ async def test_create_attack_system_prompt_prepends_before_prepended_conversatio ) ) - calls = mock_memory.add_message_pieces_to_memory.call_args_list + calls = mock_memory.add_message_pieces_to_memory_async.call_args_list assert len(calls) == 2 roles = [call[1]["message_pieces"][0].api_role for call in calls] sequences = [call[1]["message_pieces"][0].sequence for call in calls] @@ -946,7 +946,7 @@ async def test_create_attack_does_not_store_labels_in_metadata(self, attack_serv ) ) - call_args = mock_memory.add_attack_results_to_memory.call_args + call_args = mock_memory.add_attack_results_to_memory_async.call_args stored_ar = call_args[1]["attack_results"][0] assert "labels" not in stored_ar.metadata @@ -969,7 +969,7 @@ async def test_create_attack_stores_labels_on_attack_result(self, attack_service ) ) - stored_ar = mock_memory.add_attack_results_to_memory.call_args[1]["attack_results"][0] + stored_ar = mock_memory.add_attack_results_to_memory_async.call_args[1]["attack_results"][0] assert stored_ar.labels == {"env": "prod", "source": "gui"} async def test_create_attack_prepended_messages_have_incrementing_sequences( @@ -1019,7 +1019,7 @@ async def test_create_attack_prepended_messages_have_incrementing_sequences( ) # Each message stored separately with incrementing sequence - calls = mock_memory.add_message_pieces_to_memory.call_args_list + calls = mock_memory.add_message_pieces_to_memory_async.call_args_list assert len(calls) == 3 sequences = [call[1]["message_pieces"][0].sequence for call in calls] assert sequences == [0, 1, 2] @@ -1058,7 +1058,7 @@ async def test_create_attack_preserves_user_supplied_source_label(self, attack_s ) ) - stored_ar = mock_memory.add_attack_results_to_memory.call_args[1]["attack_results"][0] + stored_ar = mock_memory.add_attack_results_to_memory_async.call_args[1]["attack_results"][0] assert stored_ar.labels["source"] == "api-test" async def test_create_attack_default_name(self, attack_service, mock_memory) -> None: @@ -1075,7 +1075,7 @@ async def test_create_attack_default_name(self, attack_service, mock_memory) -> await attack_service.create_attack_async(request=CreateAttackRequest(target_registry_name="target-1")) - call_args = mock_memory.add_attack_results_to_memory.call_args + call_args = mock_memory.add_attack_results_to_memory_async.call_args stored_ar = call_args[1]["attack_results"][0] assert stored_ar.objective == "" assert stored_ar.get_attack_strategy_identifier().class_name == "ManualAttack" @@ -1097,7 +1097,7 @@ async def test_create_attack_with_name_marks_objective_explicit(self, attack_ser request=CreateAttackRequest(target_registry_name="target-1", name="Extract the secret") ) - stored_ar = mock_memory.add_attack_results_to_memory.call_args[1]["attack_results"][0] + stored_ar = mock_memory.add_attack_results_to_memory_async.call_args[1]["attack_results"][0] assert stored_ar.objective == "Extract the secret" assert "objective_is_placeholder" not in stored_ar.metadata @@ -1113,7 +1113,7 @@ class TestUpdateAttack: async def test_update_attack_returns_none_for_nonexistent(self, attack_service, mock_memory) -> None: """Test that update_attack returns None for nonexistent attack.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] result = await attack_service.update_attack_async( attack_result_id="nonexistent", request=UpdateAttackRequest(outcome="success") @@ -1124,76 +1124,76 @@ async def test_update_attack_returns_none_for_nonexistent(self, attack_service, async def test_update_attack_updates_outcome_success(self, attack_service, mock_memory) -> None: """Test that update_attack maps 'success' to AttackOutcome.SUCCESS.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] await attack_service.update_attack_async( attack_result_id="test-id", request=UpdateAttackRequest(outcome="success") ) - mock_memory.update_attack_result_by_id.assert_called_once() - call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + mock_memory.update_attack_result_by_id_async.assert_called_once() + call_kwargs = mock_memory.update_attack_result_by_id_async.call_args[1] assert call_kwargs["attack_result_id"] == "test-id" assert call_kwargs["update_fields"]["outcome"] == "success" async def test_update_attack_updates_outcome_failure(self, attack_service, mock_memory) -> None: """Test that update_attack maps 'failure' to AttackOutcome.FAILURE.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] await attack_service.update_attack_async( attack_result_id="test-id", request=UpdateAttackRequest(outcome="failure") ) - call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + call_kwargs = mock_memory.update_attack_result_by_id_async.call_args[1] assert call_kwargs["update_fields"]["outcome"] == "failure" async def test_update_attack_updates_outcome_undetermined(self, attack_service, mock_memory) -> None: """Test that update_attack maps 'undetermined' to AttackOutcome.UNDETERMINED.""" ar = make_attack_result(conversation_id="test-id", outcome=AttackOutcome.SUCCESS) - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] await attack_service.update_attack_async( attack_result_id="test-id", request=UpdateAttackRequest(outcome="undetermined") ) - call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + call_kwargs = mock_memory.update_attack_result_by_id_async.call_args[1] assert call_kwargs["update_fields"]["outcome"] == "undetermined" async def test_update_attack_updates_outcome_error(self, attack_service, mock_memory) -> None: """Test that update_attack maps 'error' to AttackOutcome.ERROR.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] await attack_service.update_attack_async( attack_result_id="test-id", request=UpdateAttackRequest(outcome="error") ) - call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + call_kwargs = mock_memory.update_attack_result_by_id_async.call_args[1] assert call_kwargs["update_fields"]["outcome"] == "error" async def test_update_attack_updates_objective_and_hash(self, attack_service, mock_memory) -> None: """Test that updating the objective keeps its lookup hash synchronized.""" ar = make_attack_result(conversation_id="test-id", objective="") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] await attack_service.update_attack_async( attack_result_id="test-id", request=UpdateAttackRequest(objective="Extract the system prompt"), ) - update_fields = mock_memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + update_fields = mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] assert update_fields["objective"] == "Extract the system prompt" assert update_fields["objective_sha256"] == to_sha256("Extract the system prompt") async def test_update_attack_rejects_replacing_objective(self, attack_service, mock_memory) -> None: """Test that an existing objective cannot be replaced.""" ar = make_attack_result(conversation_id="test-id", objective="Existing objective") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] with pytest.raises(AttackObjectiveConflictError, match="already has an objective"): await attack_service.update_attack_async( @@ -1201,14 +1201,14 @@ async def test_update_attack_rejects_replacing_objective(self, attack_service, m request=UpdateAttackRequest(objective="Replacement objective"), ) - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() async def test_update_attack_same_objective_is_idempotent(self, attack_service, mock_memory) -> None: """Test that resubmitting the existing objective does not write it again.""" objective = "Existing objective" ar = make_attack_result(conversation_id="test-id", objective=objective) - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] result = await attack_service.update_attack_async( attack_result_id="test-id", @@ -1217,20 +1217,20 @@ async def test_update_attack_same_objective_is_idempotent(self, attack_service, assert result is not None assert result.objective == objective - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() async def test_update_attack_bumps_timestamp(self, attack_service, mock_memory) -> None: """Test that update_attack bumps the timestamp recency column and does not write metadata.""" old_time = datetime(2024, 1, 1, tzinfo=UTC) ar = make_attack_result(conversation_id="test-id", updated_at=old_time) - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_messages_async.return_value = [] await attack_service.update_attack_async( attack_result_id="test-id", request=UpdateAttackRequest(outcome="success") ) - update_fields = mock_memory.update_attack_result_by_id.call_args[1]["update_fields"] + update_fields = mock_memory.update_attack_result_by_id_async.call_args[1]["update_fields"] assert isinstance(update_fields["timestamp"], datetime) assert update_fields["timestamp"] > old_time assert "attack_metadata" not in update_fields @@ -1253,11 +1253,11 @@ async def test_remove_human_score_restores_automated_outcome( score_value=score_value, score_rationale="Automated rationale", ) - mock_memory.get_attack_results.return_value = [attack] + mock_memory.get_attack_results_async.return_value = [attack] await attack_service.remove_human_score_async(attack_result_id="ar-test-id") - update_fields = mock_memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + update_fields = mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] assert update_fields["human_score_id"] is None assert update_fields["outcome"] == expected_outcome assert update_fields["outcome_reason"] == "Automated rationale" @@ -1269,11 +1269,11 @@ async def test_remove_human_score_without_automated_score_is_undetermined( ) -> None: """Test that removing the only score makes the attack outcome undetermined.""" attack = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [attack] + mock_memory.get_attack_results_async.return_value = [attack] await attack_service.remove_human_score_async(attack_result_id="ar-test-id") - update_fields = mock_memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + update_fields = mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] assert update_fields["human_score_id"] is None assert update_fields["outcome"] == "undetermined" assert update_fields["outcome_reason"] is None @@ -1311,7 +1311,7 @@ async def test_add_message_delegates_before_reading_response( reader.assert_awaited_once_with(attack_result_id="attack", conversation_id="branch") assert result.attack is summary assert result.messages is messages - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() @pytest.mark.parametrize("error", [ValueError("not found"), RuntimeError("send failed")]) async def test_add_message_propagates_service_errors( @@ -1335,7 +1335,7 @@ async def test_response_assembly_keeps_conversation_reserved_async( self, *, sqlite_instance: SQLiteMemory, read_method: str, incoming_send: bool ) -> None: ar = make_attack_result(conversation_id=str(uuid.uuid4()), attack_result_id=str(uuid.uuid4()), has_target=False) - await asyncio.to_thread(sqlite_instance.add_attack_results_to_memory, attack_results=[ar]) + await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar]) service, peer = AttackService(), AttackService() scheduler = ManualSendScheduler() service._message_send_service = MessageSendService(scheduler=scheduler) @@ -1439,13 +1439,15 @@ async def test_add_message_send_false_without_registry_name_succeeds( ar = make_attack_result(conversation_id="test-id") ar.operator = "alice" ar.operation = "nightly" - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [ + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [ MessagePiece(role="user", original_value="prior", conversation_id="test-id", sequence=3) ] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_conversation_messages_async.return_value = [] target = ComponentIdentifier(class_name="TextTarget", class_module="pyrit.prompt_target") - mock_memory._get_conversation.return_value = Conversation(conversation_id="test-id", target_identifier=target) + mock_memory.get_conversation_metadata_async.return_value = Conversation( + conversation_id="test-id", target_identifier=target + ) original_id = uuid.uuid4() request = AddMessageRequest( @@ -1465,19 +1467,19 @@ async def test_add_message_send_false_without_registry_name_succeeds( assert result.messages.conversation_id == "test-id" pieces = [ piece - for call in mock_memory.add_message_pieces_to_memory.call_args_list + for call in mock_memory.add_message_pieces_to_memory_async.call_args_list for piece in call.kwargs["message_pieces"] ] assert [piece.original_value for piece in pieces] == ["Hello", "World"] assert [piece.converted_value for piece in pieces] == ["Hello", "converted"] assert all(piece.role == role and piece.sequence == 4 for piece in pieces) assert pieces[0].original_prompt_id == original_id - assert mock_memory.add_conversation_to_memory.call_args.kwargs["conversation"].target_identifier == target + assert mock_memory.add_conversation_to_memory_async.call_args.kwargs["conversation"].target_identifier == target async def test_add_message_surfaces_stored_error_piece_on_send_failure(self, attack_service, mock_memory) -> None: """When the normalizer stores an error piece then raises, the send returns that turn inline (no raise).""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] # The PromptNormalizer persists a full error piece before re-raising; model # that by flipping to return the stored error piece only after send fails. @@ -1502,10 +1504,10 @@ async def test_add_message_surfaces_stored_error_piece_on_send_failure(self, att response_error="processing", ) state = {"sent": False} - mock_memory.get_message_pieces.side_effect = lambda **_: [error_piece] if state["sent"] else [] + mock_memory.get_message_pieces_async.side_effect = lambda **_: [error_piece] if state["sent"] else [] # The conversation-messages read (used to build the response DTO) must include # the stored error turn so we can assert it is surfaced to the caller. - mock_memory.get_conversation_messages.side_effect = lambda **_: ( + mock_memory.get_conversation_messages_async.side_effect = lambda **_: ( [Message(message_pieces=[request_piece]), Message(message_pieces=[error_piece])] if state["sent"] else [] ) @@ -1552,9 +1554,9 @@ async def _raise_after_store_async(**_: Any) -> None: async def test_add_message_raises_when_attack_not_found_after_update(self, attack_service, mock_memory) -> None: """Test that add_message raises ValueError when attack disappears after update.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] + mock_memory.get_conversation_messages_async.return_value = [] request = AddMessageRequest( role="system", @@ -1570,9 +1572,9 @@ async def test_add_message_raises_when_attack_not_found_after_update(self, attac async def test_add_message_raises_when_messages_not_found_after_update(self, attack_service, mock_memory) -> None: """Test that add_message raises ValueError when messages disappear after update.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] + mock_memory.get_conversation_messages_async.return_value = [] request = AddMessageRequest( role="system", @@ -1615,18 +1617,18 @@ async def test_list_attacks_first_page_forwards_limit_plus_one_and_no_after( self, attack_service, mock_memory ) -> None: """The first page over-fetches one row (limit + 1) and passes no keyset anchor.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] await attack_service.list_attacks_async(limit=20) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["limit"] == 21 assert call_kwargs["after"] is None async def test_list_attacks_empty_attack_types_match_no_filter_cursor(self, attack_service, mock_memory) -> None: """An empty attack-type list has the same query and cursor fingerprint as no filter.""" backing = _paginated_backing(3) - mock_memory.get_attack_results.side_effect = _keyset_side_effect(backing) + mock_memory.get_attack_results_async.side_effect = _keyset_side_effect(backing) first = await attack_service.list_attacks_async(limit=2) assert first.pagination.next_cursor is not None @@ -1636,28 +1638,28 @@ async def test_list_attacks_empty_attack_types_match_no_filter_cursor(self, atta cursor=first.pagination.next_cursor, ) - call_kwargs = mock_memory.get_attack_results.call_args.kwargs + call_kwargs = mock_memory.get_attack_results_async.call_args.kwargs assert call_kwargs["attack_classes"] is None assert call_kwargs["after"].attack_result_id == backing[1].attack_result_id async def test_list_attacks_decodes_cursor_to_after(self, attack_service, mock_memory) -> None: """A cursor is decoded into the memory keyset anchor when its filter fingerprint matches.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] anchor_row = make_attack_result(conversation_id="attack-anchor", attack_result_id=str(uuid.uuid4())) await attack_service.list_attacks_async(limit=20, cursor=_cursor_for(anchor_row)) - call_kwargs = mock_memory.get_attack_results.call_args[1] + call_kwargs = mock_memory.get_attack_results_async.call_args[1] assert call_kwargs["after"].attack_result_id == anchor_row.attack_result_id assert call_kwargs["limit"] == 21 async def test_list_attacks_invalid_cursor_defaults_to_first_page(self, attack_service, mock_memory) -> None: """A malformed or legacy (offset/attack-result-id) cursor degrades to the first page.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] await attack_service.list_attacks_async(limit=20, cursor="ar-attack-1") - assert mock_memory.get_attack_results.call_args[1]["after"] is None + assert mock_memory.get_attack_results_async.call_args[1]["after"] is None @pytest.mark.parametrize("field", ["t", "i"]) async def test_list_attacks_non_string_cursor_fields_restart_async( @@ -1671,11 +1673,11 @@ async def test_list_attacks_non_string_cursor_fields_restart_async( field: 123, } cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode() - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] await attack_service.list_attacks_async(limit=20, cursor=cursor) - assert mock_memory.get_attack_results.call_args.kwargs["after"] is None + assert mock_memory.get_attack_results_async.call_args.kwargs["after"] is None def test_decode_attack_cursor_rejects_invalid_and_round_trips_valid(self) -> None: """Bad/legacy/mismatched/naive cursors decode to None; valid round-trips; non-UTC canonicalizes to UTC.""" @@ -1737,7 +1739,7 @@ def decode(cursor, fp=fingerprint): async def test_list_attacks_has_more_and_next_cursor(self, attack_service, mock_memory) -> None: """When an extra row is returned, has_more is set and next_cursor anchors on the last row.""" backing = _paginated_backing(5) - mock_memory.get_attack_results.side_effect = _keyset_side_effect(backing) + mock_memory.get_attack_results_async.side_effect = _keyset_side_effect(backing) result = await attack_service.list_attacks_async(limit=2) @@ -1748,7 +1750,7 @@ async def test_list_attacks_has_more_and_next_cursor(self, attack_service, mock_ async def test_list_attacks_second_page_via_cursor_is_disjoint(self, attack_service, mock_memory) -> None: """Following next_cursor returns the next disjoint page.""" backing = _paginated_backing(5) - mock_memory.get_attack_results.side_effect = _keyset_side_effect(backing) + mock_memory.get_attack_results_async.side_effect = _keyset_side_effect(backing) result = await attack_service.list_attacks_async(limit=2, cursor=_cursor_for(backing[1])) @@ -1759,7 +1761,7 @@ async def test_list_attacks_second_page_via_cursor_is_disjoint(self, attack_serv async def test_list_attacks_last_page_has_no_next_cursor(self, attack_service, mock_memory) -> None: """The final page reports has_more False and a null next_cursor.""" backing = _paginated_backing(5) - mock_memory.get_attack_results.side_effect = _keyset_side_effect(backing) + mock_memory.get_attack_results_async.side_effect = _keyset_side_effect(backing) result = await attack_service.list_attacks_async(limit=2, cursor=_cursor_for(backing[3])) @@ -1769,7 +1771,7 @@ async def test_list_attacks_last_page_has_no_next_cursor(self, attack_service, m async def test_list_attacks_prev_cursor_echoes_incoming_cursor(self, attack_service, mock_memory) -> None: """prev_cursor echoes the incoming cursor unchanged.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] cursor = _cursor_for(make_attack_result(conversation_id="attack-1", attack_result_id=str(uuid.uuid4()))) result = await attack_service.list_attacks_async(limit=2, cursor=cursor) @@ -1787,7 +1789,7 @@ async def test_list_attacks_stale_cursor_after_filter_change_resets_to_first_pag pre-optimization id-cursor behavior. """ backing = _paginated_backing(5) - mock_memory.get_attack_results.side_effect = _keyset_side_effect(backing) + mock_memory.get_attack_results_async.side_effect = _keyset_side_effect(backing) # Page 1 with no filter yields a next_cursor anchored on the last row. first = await attack_service.list_attacks_async(limit=2) @@ -1797,7 +1799,7 @@ async def test_list_attacks_stale_cursor_after_filter_change_resets_to_first_pag # Replaying it with a different filter set must reset to the first page, not seek. result = await attack_service.list_attacks_async(limit=2, cursor=stale_cursor, outcome="success") - assert mock_memory.get_attack_results.call_args[1]["after"] is None + assert mock_memory.get_attack_results_async.call_args[1]["after"] is None assert [item.conversation_id for item in result.items] == ["attack-0", "attack-1"] async def test_list_attacks_cursor_with_matching_filters_preserves_anchor( @@ -1805,7 +1807,7 @@ async def test_list_attacks_cursor_with_matching_filters_preserves_anchor( ) -> None: """A cursor replayed with the same filter set applies its encoded keyset anchor.""" backing = _paginated_backing(5) - mock_memory.get_attack_results.side_effect = _keyset_side_effect(backing) + mock_memory.get_attack_results_async.side_effect = _keyset_side_effect(backing) first = await attack_service.list_attacks_async(limit=2, outcome="success") next_cursor = first.pagination.next_cursor @@ -1813,7 +1815,9 @@ async def test_list_attacks_cursor_with_matching_filters_preserves_anchor( result = await attack_service.list_attacks_async(limit=2, cursor=next_cursor, outcome="success") - assert mock_memory.get_attack_results.call_args[1]["after"].attack_result_id == backing[1].attack_result_id + assert ( + mock_memory.get_attack_results_async.call_args[1]["after"].attack_result_id == backing[1].attack_result_id + ) assert [item.conversation_id for item in result.items] == ["attack-2", "attack-3"] def test_attack_filter_fingerprint_is_order_independent_and_filter_sensitive(self) -> None: @@ -1833,16 +1837,16 @@ def test_attack_filter_fingerprint_is_order_independent_and_filter_sensitive(sel assert fingerprint(labels={"op": [], "team": "red"}) == fingerprint(labels={"team": "red"}) async def test_list_attacks_uses_conversation_stats_not_pieces(self, attack_service, mock_memory) -> None: - """Test that list_attacks uses get_conversation_stats instead of loading full pieces.""" + "Test that list_attacks uses get_conversation_stats_async instead of loading full pieces." backing = _paginated_backing(5) - mock_memory.get_attack_results.side_effect = _keyset_side_effect(backing) + mock_memory.get_attack_results_async.side_effect = _keyset_side_effect(backing) await attack_service.list_attacks_async(limit=2) # get_conversation_stats should be called once (batched), not per-attack - mock_memory.get_conversation_stats.assert_called_once() + mock_memory.get_conversation_stats_async.assert_called_once() # get_message_pieces should NOT be called by list_attacks - mock_memory.get_message_pieces.assert_not_called() + mock_memory.get_message_pieces_async.assert_not_called() # ============================================================================ @@ -1855,9 +1859,9 @@ class TestMessageBuilding: """Tests for message translation and building.""" async def test_get_attack_with_messages_translates_correctly(self, attack_service, mock_memory) -> None: - """Test that get_conversation_messages translates PyRIT messages to backend format.""" + "Test that get_conversation_messages_async translates PyRIT messages to backend format." ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] piece = MessagePiece( role="user", @@ -1870,7 +1874,7 @@ async def test_get_attack_with_messages_translates_correctly(self, attack_servic ) msg = Message(message_pieces=[piece]) - mock_memory.get_conversation_messages.return_value = [msg] + mock_memory.get_conversation_messages_async.return_value = [msg] result = await attack_service.get_conversation_messages_async( attack_result_id="test-id", conversation_id="test-id" @@ -1921,7 +1925,7 @@ class TestGetConversations: async def test_returns_none_when_attack_not_found(self, attack_service, mock_memory): """Should return None when the attack doesn't exist.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] result = await attack_service.get_conversations_async(attack_result_id="missing") @@ -1930,8 +1934,8 @@ async def test_returns_none_when_attack_not_found(self, attack_service, mock_mem async def test_returns_main_conversation_only(self, attack_service, mock_memory): """Should return only the main conversation when no related conversations exist.""" ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_stats.return_value = { + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_stats_async.return_value = { "attack-1": ConversationStats(message_count=2, last_message_preview="test"), } @@ -1945,9 +1949,9 @@ async def test_returns_main_conversation_only(self, attack_service, mock_memory) async def test_conversation_summary_formats_media_preview(self, attack_service, mock_memory): """ConversationSummary previews must not leak absolute media paths.""" ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] path = r"C:\Users\someone\PyRIT\dbdata\prompt-memory-entries\audio\1780010098266691.mp3" - mock_memory.get_conversation_stats.return_value = { + mock_memory.get_conversation_stats_async.return_value = { "attack-1": ConversationStats( message_count=1, last_message_preview=path, @@ -1989,12 +1993,12 @@ async def test_returns_main_and_related_conversations(self, attack_service, mock ) ) - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] t1 = datetime(2026, 1, 1, 10, 0, 0, tzinfo=UTC) t2 = datetime(2026, 1, 1, 9, 30, 0, tzinfo=UTC) # earlier than t1 - mock_memory.get_conversation_stats.return_value = { + mock_memory.get_conversation_stats_async.return_value = { "attack-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t1), "branch-1": ConversationStats(message_count=2, last_message_preview="test", created_at=t2), "score-1": ConversationStats(message_count=0), @@ -2040,10 +2044,8 @@ async def test_empty_history_branch_preserves_target_on_first_send_async( ) ), ) - await asyncio.to_thread(sqlite_instance.add_attack_results_to_memory, attack_results=[attack]) - assert ( - await asyncio.to_thread(sqlite_instance._get_conversation, conversation_id=attack.conversation_id) is None - ) + await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack]) + assert await sqlite_instance.get_conversation_metadata_async(conversation_id=attack.conversation_id) is None branch = await service.create_related_conversation_async( attack_result_id=attack.attack_result_id, @@ -2058,7 +2060,7 @@ async def test_empty_history_branch_preserves_target_on_first_send_async( target=target, conversation_id=conversation_id, ) - metadata = await asyncio.to_thread(sqlite_instance._get_conversation, conversation_id=conversation_id) + metadata = await sqlite_instance.get_conversation_metadata_async(conversation_id=conversation_id) assert metadata is not None assert metadata.target_identifier == target_identifier rows = await asyncio.to_thread( @@ -2076,13 +2078,13 @@ async def test_nested_branching_preserves_target_after_version_change_async( target = TargetIdentifier(class_name="ExampleTarget", class_module="tests.unit", pyrit_version="1.1.0") source = Conversation(conversation_id=str(uuid.uuid4()), target_identifier=target) attack = AttackResult(conversation_id=source.conversation_id, objective="Branch older history") - await asyncio.to_thread(sqlite_instance.add_attack_results_to_memory, attack_results=[attack]) + await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack]) with patch.object(pyrit, "__version__", "1.1.0"): - await asyncio.to_thread(sqlite_instance.add_conversation_to_memory, conversation=source) + await sqlite_instance.add_conversation_to_memory_async(conversation=source) original = MessagePiece( conversation_id=source.conversation_id, role="user", original_value="Original", sequence=0 ) - await asyncio.to_thread(sqlite_instance.add_message_pieces_to_memory, message_pieces=[original]) + await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[original]) expected_rows = [(source.conversation_id, "1.1.0", target.model_dump())] source_id = source.conversation_id @@ -2098,7 +2100,7 @@ async def test_nested_branching_preserves_target_after_version_change_async( conditions=ConversationEntry.conversation_id == branch.conversation_id, ) expected_rows.append((branch.conversation_id, rows[0].pyrit_version, rows[0].target_identifier)) - pieces = await asyncio.to_thread(sqlite_instance.get_message_pieces, conversation_id=branch.conversation_id) + pieces = await sqlite_instance.get_message_pieces_async(conversation_id=branch.conversation_id) assert [piece.original_prompt_id for piece in pieces] == [original.id] source_id = branch.conversation_id @@ -2107,16 +2109,14 @@ async def test_nested_branching_preserves_target_after_version_change_async( conversation_id: (version, identifier) for conversation_id, version, identifier in expected_rows } assert all(row.target_identifier_hash == target.hash for row in rows) - current = await asyncio.to_thread( - sqlite_instance.get_attack_results, attack_result_ids=[attack.attack_result_id] - ) + current = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) assert current[0].get_active_conversation_ids() == {row.conversation_id for row in rows} async def test_returns_none_when_attack_not_found(self, attack_service, mock_memory): """Should return None when the attack doesn't exist.""" from pyrit.backend.models.attacks import CreateConversationRequest - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] result = await attack_service.create_related_conversation_async( attack_result_id="missing", @@ -2130,8 +2130,8 @@ async def test_creates_conversation_and_adds_to_related(self, attack_service, mo from pyrit.backend.models.attacks import CreateConversationRequest ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] request = CreateConversationRequest() @@ -2144,8 +2144,8 @@ async def test_creates_conversation_and_adds_to_related(self, attack_service, mo assert result.conversation_id is not None assert result.conversation_id != "attack-1" - mock_memory.add_conversation_branches_to_attack.assert_called_once() - call_kwargs = mock_memory.add_conversation_branches_to_attack.call_args.kwargs + mock_memory.add_conversation_branches_to_attack_async.assert_called_once() + call_kwargs = mock_memory.add_conversation_branches_to_attack_async.call_args.kwargs assert call_kwargs["attack_result_id"] == "attack-1" assert [conversation.conversation_id for conversation in call_kwargs["conversations"]] == [ result.conversation_id @@ -2155,29 +2155,29 @@ async def test_creates_conversation_and_adds_to_related(self, attack_service, mo assert call_kwargs["conversations"][0].target_identifier == attack_identifier.get_child("objective_target") assert call_kwargs["message_pieces"] == [] assert call_kwargs["source_conversation"] is None - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() async def test_returns_none_when_attack_disappears_during_creation_async( self, *, attack_service: AttackService, mock_memory: MagicMock ) -> None: - mock_memory.get_attack_results.return_value = [make_attack_result()] - mock_memory.add_conversation_branches_to_attack.return_value = False + mock_memory.get_attack_results_async.return_value = [make_attack_result()] + mock_memory.add_conversation_branches_to_attack_async.return_value = False result = await attack_service.create_related_conversation_async( attack_result_id="ar-attack-1", request=CreateConversationRequest() ) assert result is None - mock_memory.add_conversation_to_memory.assert_not_called() - mock_memory.add_message_pieces_to_memory.assert_not_called() - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.add_conversation_to_memory_async.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() async def test_rejects_source_conversation_from_different_attack(self, attack_service, mock_memory): """Should raise ValueError when source_conversation_id doesn't belong to the attack.""" from pyrit.backend.models.attacks import CreateConversationRequest ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] request = CreateConversationRequest(source_conversation_id="unrelated-conv", cutoff_index=0) @@ -2187,7 +2187,7 @@ async def test_rejects_source_conversation_from_different_attack(self, attack_se request=request, ) - mock_memory.add_conversation_branches_to_attack.assert_not_called() + mock_memory.add_conversation_branches_to_attack_async.assert_not_called() @pytest.mark.parametrize("conversation_type", [ConversationType.ADVERSARIAL, ConversationType.PREPARATION]) async def test_rejects_diagnostic_sources_async( @@ -2197,7 +2197,7 @@ async def test_rejects_diagnostic_sources_async( ar.related_conversations = { ConversationReference(conversation_id="diagnostic", conversation_type=conversation_type), } - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] with pytest.raises(ValueError, match="not part of attack"): await attack_service.create_related_conversation_async( @@ -2205,17 +2205,17 @@ async def test_rejects_diagnostic_sources_async( request=CreateConversationRequest(source_conversation_id="diagnostic", cutoff_index=0), ) - mock_memory.get_conversation_messages.assert_not_called() - mock_memory.add_conversation_branches_to_attack.assert_not_called() + mock_memory.get_conversation_messages_async.assert_not_called() + mock_memory.add_conversation_branches_to_attack_async.assert_not_called() async def test_branch_persistence_failure_does_not_commit_copies_async( self, *, attack_service: AttackService, mock_memory: MagicMock ) -> None: - mock_memory.get_attack_results.return_value = [make_attack_result()] - mock_memory.get_conversation_messages.return_value = [_make_message(role="user", sequence=0)] + mock_memory.get_attack_results_async.return_value = [make_attack_result()] + mock_memory.get_conversation_messages_async.return_value = [_make_message(role="user", sequence=0)] copied = MessagePiece(conversation_id="branch", role="user", original_value="copy") - mock_memory.duplicate_messages.return_value = ("branch", [copied]) - mock_memory.add_conversation_branches_to_attack.side_effect = RuntimeError("branch insertion failed") + mock_memory.duplicate_messages_async.return_value = ("branch", [copied]) + mock_memory.add_conversation_branches_to_attack_async.side_effect = RuntimeError("branch insertion failed") with pytest.raises(RuntimeError, match="branch insertion failed"): await attack_service.create_related_conversation_async( @@ -2223,10 +2223,10 @@ async def test_branch_persistence_failure_does_not_commit_copies_async( request=CreateConversationRequest(source_conversation_id="attack-1", cutoff_index=0), ) - assert mock_memory.add_conversation_branches_to_attack.call_args.kwargs["message_pieces"] == [copied] - mock_memory.add_conversation_to_memory.assert_not_called() - mock_memory.add_message_pieces_to_memory.assert_not_called() - mock_memory.update_attack_result_by_id.assert_not_called() + assert mock_memory.add_conversation_branches_to_attack_async.call_args.kwargs["message_pieces"] == [copied] + mock_memory.add_conversation_to_memory_async.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() # ============================================================================ @@ -2240,7 +2240,7 @@ class TestUpdateMainConversation: async def test_returns_none_when_attack_not_found(self, attack_service, mock_memory): """Should return None when the attack doesn't exist.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] result = await attack_service.update_main_conversation_async( attack_result_id="missing", @@ -2252,7 +2252,7 @@ async def test_returns_none_when_attack_not_found(self, attack_service, mock_mem async def test_noop_when_target_is_already_main(self, attack_service, mock_memory): """Memory must check the current main while holding the attack's write lock.""" ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] result = await attack_service.update_main_conversation_async( attack_result_id="ar-attack-1", @@ -2261,15 +2261,15 @@ async def test_noop_when_target_is_already_main(self, attack_service, mock_memor assert result is not None assert result.conversation_id == "attack-1" - mock_memory.promote_attack_conversation.assert_called_once_with( + mock_memory.promote_attack_conversation_async.assert_called_once_with( attack_result_id="ar-attack-1", conversation_id="attack-1" ) - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() async def test_raises_when_conversation_not_part_of_attack(self, attack_service, mock_memory): """Should raise ValueError when conversation is not in the attack.""" ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] with pytest.raises(ValueError, match="not part of this attack"): await attack_service.update_main_conversation_async( @@ -2277,7 +2277,7 @@ async def test_raises_when_conversation_not_part_of_attack(self, attack_service, request=UpdateMainConversationRequest(conversation_id="not-related"), ) - mock_memory.promote_attack_conversation.assert_not_called() + mock_memory.promote_attack_conversation_async.assert_not_called() async def test_swaps_main_conversation(self, attack_service, mock_memory): """Changing the main to a related conversation should swap it with the main.""" @@ -2291,7 +2291,7 @@ async def test_swaps_main_conversation(self, attack_service, mock_memory): description="Branch 1", ), } - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] result = await attack_service.update_main_conversation_async( attack_result_id="ar-attack-1", @@ -2302,17 +2302,17 @@ async def test_swaps_main_conversation(self, attack_service, mock_memory): assert result.attack_result_id == "ar-attack-1" assert result.conversation_id == "branch-1" - mock_memory.promote_attack_conversation.assert_called_once() - call_kwargs = mock_memory.promote_attack_conversation.call_args.kwargs + mock_memory.promote_attack_conversation_async.assert_called_once() + call_kwargs = mock_memory.promote_attack_conversation_async.call_args.kwargs assert call_kwargs["attack_result_id"] == "ar-attack-1" assert call_kwargs["conversation_id"] == "branch-1" - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() async def test_returns_none_when_attack_disappears_during_promotion_async( self, *, attack_service: AttackService, mock_memory: MagicMock ) -> None: - mock_memory.get_attack_results.return_value = [make_attack_result()] - mock_memory.promote_attack_conversation.return_value = False + mock_memory.get_attack_results_async.return_value = [make_attack_result()] + mock_memory.promote_attack_conversation_async.return_value = False result = await attack_service.update_main_conversation_async( attack_result_id="ar-attack-1", @@ -2320,7 +2320,7 @@ async def test_returns_none_when_attack_disappears_during_promotion_async( ) assert result is None - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() @pytest.mark.parametrize("conversation_type", ["preparation", "adversarial"]) async def test_rejects_promoting_diagnostic_conversation(self, attack_service, mock_memory, conversation_type): @@ -2334,7 +2334,7 @@ async def test_rejects_promoting_diagnostic_conversation(self, attack_service, m conversation_type=ConversationType(conversation_type), ), } - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] with pytest.raises(ValueError, match="not part of this attack"): await attack_service.update_main_conversation_async( @@ -2342,8 +2342,8 @@ async def test_rejects_promoting_diagnostic_conversation(self, attack_service, m request=UpdateMainConversationRequest(conversation_id="diagnostic-1"), ) - mock_memory.promote_attack_conversation.assert_not_called() - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.promote_attack_conversation_async.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() @pytest.mark.usefixtures("patch_central_database") @@ -2359,9 +2359,9 @@ async def test_stores_message_in_target_conversation(self, attack_service, mock_ ar.related_conversations = { ConversationReference(conversation_id="branch-1", conversation_type=ConversationType.PRUNED), } - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] + mock_memory.get_conversation_messages_async.return_value = [] request = AddMessageRequest( role="user", @@ -2417,8 +2417,8 @@ async def test_list_attacks_includes_related_conversation_ids(self, attack_servi conversation_type=ConversationType.ADVERSARIAL, ), } - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] result = await attack_service.list_attacks_async() @@ -2428,8 +2428,8 @@ async def test_list_attacks_includes_related_conversation_ids(self, attack_servi async def test_list_attacks_no_related_returns_empty_list(self, attack_service, mock_memory): """An attack with no related conversations should return empty list.""" ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] result = await attack_service.list_attacks_async() @@ -2440,15 +2440,15 @@ async def test_create_conversation_increments_count(self, attack_service, mock_m from pyrit.backend.models.attacks import CreateConversationRequest ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] result = await attack_service.create_related_conversation_async( attack_result_id="attack-1", request=CreateConversationRequest(), ) - call_kwargs = mock_memory.add_conversation_branches_to_attack.call_args.kwargs + call_kwargs = mock_memory.add_conversation_branches_to_attack_async.call_args.kwargs ids = [conversation.conversation_id for conversation in call_kwargs["conversations"]] assert result.conversation_id in ids assert len(ids) == 1 @@ -2465,19 +2465,19 @@ async def test_create_second_conversation_preserves_first(self, attack_service, conversation_type=ConversationType.PRUNED, ), } - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] result = await attack_service.create_related_conversation_async( attack_result_id="attack-1", request=CreateConversationRequest(), ) - call_kwargs = mock_memory.add_conversation_branches_to_attack.call_args.kwargs + call_kwargs = mock_memory.add_conversation_branches_to_attack_async.call_args.kwargs ids = [conversation.conversation_id for conversation in call_kwargs["conversations"]] assert result.conversation_id in ids assert len(ids) == 1 - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() @pytest.mark.usefixtures("patch_central_database") @@ -2495,12 +2495,12 @@ async def test_conversations_sorted_by_created_at_earliest_first(self, attack_se conversation_type=ConversationType.PRUNED, ), } - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] t_early = datetime(2026, 1, 1, 9, 0, 0, tzinfo=UTC) t_late = datetime(2026, 1, 1, 11, 0, 0, tzinfo=UTC) - mock_memory.get_conversation_stats.return_value = { + mock_memory.get_conversation_stats_async.return_value = { "attack-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t_late), "branch-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t_early), } @@ -2523,11 +2523,11 @@ async def test_empty_conversations_sorted_last(self, attack_service, mock_memory conversation_type=ConversationType.PRUNED, ), } - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] t = datetime(2026, 1, 1, 9, 0, 0, tzinfo=UTC) - mock_memory.get_conversation_stats.return_value = { + mock_memory.get_conversation_stats_async.return_value = { "attack-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t), } @@ -2549,8 +2549,8 @@ async def test_empty_conversations_all_sort_last(self, attack_service, mock_memo conversation_type=ConversationType.PRUNED, ), } - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_conversation_stats.return_value = {} # Both have no stats + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_conversation_stats_async.return_value = {} # Both have no stats result = await attack_service.get_conversations_async(attack_result_id="attack-1") @@ -2581,7 +2581,7 @@ async def test_create_related_conversation_uses_duplicate_branch( from pyrit.models import Conversation ar = make_attack_result(conversation_id="attack-1", has_target=has_target) - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] expected_target = ( ComponentIdentifier( class_name="SourceTarget" if has_metadata else "TextTarget", class_module="pyrit.prompt_target" @@ -2590,11 +2590,13 @@ async def test_create_related_conversation_uses_duplicate_branch( else None ) source = Conversation(conversation_id="attack-1", target_identifier=expected_target) - mock_memory._get_conversation.return_value = source if has_metadata else None + mock_memory.get_conversation_metadata_async.return_value = source if has_metadata else None prepared = Conversation(conversation_id="branch-dup", target_identifier=expected_target) pieces = [MessagePiece(conversation_id="branch-dup", role="user", original_value="copy")] if has_pieces else [] - with patch.object(attack_service, "_prepare_conversation_up_to", return_value=(prepared, pieces)) as mock_dup: + with patch.object( + attack_service, "_prepare_conversation_up_to_async", return_value=(prepared, pieces) + ) as mock_dup: result = await attack_service.create_related_conversation_async( attack_result_id="attack-1", request=CreateConversationRequest(source_conversation_id="attack-1", cutoff_index=2), @@ -2608,18 +2610,18 @@ async def test_create_related_conversation_uses_duplicate_branch( "cutoff_index": 2, "target_identifier": expected_target, } - mock_memory.add_conversation_branches_to_attack.assert_called_once() - assert mock_memory.add_conversation_branches_to_attack.call_args.kwargs == { + mock_memory.add_conversation_branches_to_attack_async.assert_called_once() + assert mock_memory.add_conversation_branches_to_attack_async.call_args.kwargs == { "attack_result_id": "attack-1", "conversations": [prepared], "message_pieces": pieces, "source_conversation": source, } - mock_memory.add_conversation_to_memory.assert_not_called() - mock_memory.add_message_pieces_to_memory.assert_not_called() + mock_memory.add_conversation_to_memory_async.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() @pytest.mark.parametrize("cutoff_index,expected_sequences", [(-1, []), (0, [0]), (2, [0, 2])]) - def test_prepare_conversation_up_to_does_not_persist( + async def test_prepare_conversation_up_to_does_not_persist( self, *, attack_service: AttackService, @@ -2627,68 +2629,80 @@ def test_prepare_conversation_up_to_does_not_persist( cutoff_index: int, expected_sequences: list[int], ) -> None: - mock_memory.get_conversation_messages.return_value = [ + mock_memory.get_conversation_messages_async.return_value = [ _make_message(role="user", sequence=sequence) for sequence in [0, 2, 4] ] pieces = [ MessagePiece(conversation_id="prepared", role="user", original_value="copy", sequence=sequence) for sequence in expected_sequences ] - mock_memory.duplicate_messages.return_value = ("prepared", pieces) + mock_memory.duplicate_messages_async.return_value = ("prepared", pieces) target = ComponentIdentifier(class_name="TextTarget", class_module="pyrit.prompt_target") - conversation, copies = attack_service._prepare_conversation_up_to( + conversation, copies = await attack_service._prepare_conversation_up_to_async( source_conversation_id="source", cutoff_index=cutoff_index, target_identifier=target ) assert conversation == Conversation(conversation_id="prepared", target_identifier=target) assert copies == pieces - mock_memory.get_conversation_messages.assert_called_once_with(conversation_id="source") + mock_memory.get_conversation_messages_async.assert_called_once_with(conversation_id="source") assert [ - message.sequence for message in mock_memory.duplicate_messages.call_args.kwargs["messages"] + message.sequence for message in mock_memory.duplicate_messages_async.call_args.kwargs["messages"] ] == expected_sequences - mock_memory.add_conversation_to_memory.assert_not_called() - mock_memory.add_message_pieces_to_memory.assert_not_called() + mock_memory.add_conversation_to_memory_async.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() - def test_duplicate_conversation_up_to_adds_pieces_when_present(self, attack_service, mock_memory): + async def test_duplicate_conversation_up_to_adds_pieces_when_present(self, attack_service, mock_memory): """Should duplicate up to cutoff and persist duplicated pieces only when returned.""" source_messages = [ make_mock_piece(conversation_id="attack-1", sequence=0), make_mock_piece(conversation_id="attack-1", sequence=1), make_mock_piece(conversation_id="attack-1", sequence=2), ] - mock_memory.get_conversation_messages.return_value = source_messages + mock_memory.get_conversation_messages_async.return_value = source_messages duplicated_piece = make_mock_piece(conversation_id="branch-1", sequence=0) - mock_memory.duplicate_messages.return_value = ("branch-1", [duplicated_piece]) + mock_memory.duplicate_messages_async.return_value = ("branch-1", [duplicated_piece]) - new_id = attack_service._duplicate_conversation_up_to(source_conversation_id="attack-1", cutoff_index=1) + new_id = await attack_service._duplicate_conversation_up_to_async( + source_conversation_id="attack-1", cutoff_index=1 + ) assert new_id == "branch-1" - passed_messages = mock_memory.duplicate_messages.call_args[1]["messages"] + passed_messages = mock_memory.duplicate_messages_async.call_args[1]["messages"] assert [m.sequence for m in passed_messages] == [0, 1] - mock_memory.add_message_pieces_to_memory.assert_called_once() + mock_memory.add_message_pieces_to_memory_async.assert_called_once() - def test_duplicate_conversation_up_to_skips_persist_when_no_duplicated_pieces(self, attack_service, mock_memory): - """Should not write to memory when duplicate_messages returns no pieces.""" - mock_memory.get_conversation_messages.return_value = [make_mock_piece(conversation_id="attack-1", sequence=0)] - mock_memory.duplicate_messages.return_value = ("branch-empty", []) + async def test_duplicate_conversation_up_to_skips_persist_when_no_duplicated_pieces( + self, attack_service, mock_memory + ): + "Should not write to memory when duplicate_messages_async returns no pieces." + mock_memory.get_conversation_messages_async.return_value = [ + make_mock_piece(conversation_id="attack-1", sequence=0) + ] + mock_memory.duplicate_messages_async.return_value = ("branch-empty", []) - new_id = attack_service._duplicate_conversation_up_to(source_conversation_id="attack-1", cutoff_index=10) + new_id = await attack_service._duplicate_conversation_up_to_async( + source_conversation_id="attack-1", cutoff_index=10 + ) assert new_id == "branch-empty" - mock_memory.add_conversation_to_memory.assert_not_called() - mock_memory.add_message_pieces_to_memory.assert_not_called() + mock_memory.add_conversation_to_memory_async.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() @pytest.mark.parametrize(("role", "expected"), [("assistant", "simulated_assistant"), ("tool", "simulated_tool")]) - def test_duplicate_conversation_remaps_assistant_to_simulated(self, attack_service, mock_memory, role, expected): + async def test_duplicate_conversation_remaps_assistant_to_simulated( + self, attack_service, mock_memory, role, expected + ): """Copied response pieces retain synthetic provenance.""" source = make_mock_piece(conversation_id="attack-1", role="assistant", sequence=0) - mock_memory.get_conversation_messages.return_value = [source] + mock_memory.get_conversation_messages_async.return_value = [source] dup_piece = MessagePiece(conversation_id="branch-1", role=role, sequence=0, original_value="copied") - mock_memory.duplicate_messages.return_value = ("branch-1", [dup_piece]) + mock_memory.duplicate_messages_async.return_value = ("branch-1", [dup_piece]) - attack_service._duplicate_conversation_up_to( - source_conversation_id="attack-1", cutoff_index=0, remap_assistant_to_simulated=True + ( + await attack_service._duplicate_conversation_up_to_async( + source_conversation_id="attack-1", cutoff_index=0, remap_assistant_to_simulated=True + ) ) assert dup_piece.role == expected @@ -2698,8 +2712,8 @@ async def test_store_prepended_messages_noop_when_empty(self, attack_service, mo """Empty prepended list should be a no-op: no conversation row and no piece writes.""" await attack_service._store_prepended_messages_async(conversation_id="conv-1", prepended=[]) - mock_memory.add_conversation_to_memory.assert_not_called() - mock_memory.add_message_pieces_to_memory.assert_not_called() + mock_memory.add_conversation_to_memory_async.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() def test_create_attack_request_normalizes_legacy_attribution_labels() -> None: diff --git a/tests/unit/backend/test_dataset_service.py b/tests/unit/backend/test_dataset_service.py index 43b15b39d6..86cc51f3a8 100644 --- a/tests/unit/backend/test_dataset_service.py +++ b/tests/unit/backend/test_dataset_service.py @@ -10,15 +10,16 @@ import pytest from pyrit.backend.services.dataset_service import DatasetService, get_dataset_service +from pyrit.memory import MemoryInterface from pyrit.models import SeedDatasetSummary @pytest.fixture def mock_memory(): """Create a mock memory instance.""" - memory = MagicMock() - memory.get_seed_dataset_names.return_value = [] - memory.get_seed_dataset_summaries.return_value = [] + memory = MagicMock(spec=MemoryInterface) + memory.get_seed_dataset_names_async = AsyncMock(return_value=[]) + memory.get_seed_dataset_summaries_async = AsyncMock(return_value=[]) return memory @@ -47,26 +48,28 @@ async def test_list_datasets(self, dataset_service): assert all(item.provider_available for item in result.items) async def test_list_datasets_includes_memory_summaries(self, dataset_service, mock_memory): - mock_memory.get_seed_dataset_summaries.return_value = [ - SeedDatasetSummary( - dataset_name="harmbench", - logical_examples=3, - seed_pieces=4, - objectives=1, - modalities=("image_path", "text"), - harm_categories=("hate", "violence"), - has_unlabeled_harm_categories=True, - ), - SeedDatasetSummary( - dataset_name=None, - logical_examples=1, - seed_pieces=2, - objectives=0, - modalities=("text",), - harm_categories=(), - has_unlabeled_harm_categories=True, - ), - ] + mock_memory.get_seed_dataset_summaries_async = AsyncMock( + return_value=[ + SeedDatasetSummary( + dataset_name="harmbench", + logical_examples=3, + seed_pieces=4, + objectives=1, + modalities=("image_path", "text"), + harm_categories=("hate", "violence"), + has_unlabeled_harm_categories=True, + ), + SeedDatasetSummary( + dataset_name=None, + logical_examples=1, + seed_pieces=2, + objectives=0, + modalities=("text",), + harm_categories=(), + has_unlabeled_harm_categories=True, + ), + ] + ) with patch( "pyrit.backend.services.dataset_service.SeedDatasetProvider.get_all_dataset_names_async", new_callable=AsyncMock, @@ -98,26 +101,28 @@ async def test_list_datasets_includes_memory_summaries(self, dataset_service, mo async def test_list_datasets_selection_keys_use_distinct_namespaces(self, dataset_service, mock_memory): """A stored dataset named __unnamed__ and the unnamed population share no key.""" - mock_memory.get_seed_dataset_summaries.return_value = [ - SeedDatasetSummary( - dataset_name="__unnamed__", - logical_examples=1, - seed_pieces=1, - objectives=0, - modalities=("text",), - harm_categories=(), - has_unlabeled_harm_categories=False, - ), - SeedDatasetSummary( - dataset_name=None, - logical_examples=2, - seed_pieces=2, - objectives=0, - modalities=("url",), - harm_categories=(), - has_unlabeled_harm_categories=True, - ), - ] + mock_memory.get_seed_dataset_summaries_async = AsyncMock( + return_value=[ + SeedDatasetSummary( + dataset_name="__unnamed__", + logical_examples=1, + seed_pieces=1, + objectives=0, + modalities=("text",), + harm_categories=(), + has_unlabeled_harm_categories=False, + ), + SeedDatasetSummary( + dataset_name=None, + logical_examples=2, + seed_pieces=2, + objectives=0, + modalities=("url",), + harm_categories=(), + has_unlabeled_harm_categories=True, + ), + ] + ) with patch( "pyrit.backend.services.dataset_service.SeedDatasetProvider.get_all_dataset_names_async", new_callable=AsyncMock, @@ -139,26 +144,28 @@ async def test_list_datasets_selection_keys_use_distinct_namespaces(self, datase async def test_list_datasets_never_surfaces_an_empty_dataset_name(self, dataset_service, mock_memory): """Seeds with an empty name filter nothing, so they fold into the unnamed population.""" - mock_memory.get_seed_dataset_summaries.return_value = [ - SeedDatasetSummary( - dataset_name="", - logical_examples=2, - seed_pieces=3, - objectives=1, - modalities=("text",), - harm_categories=("hate",), - has_unlabeled_harm_categories=False, - ), - SeedDatasetSummary( - dataset_name=None, - logical_examples=1, - seed_pieces=2, - objectives=0, - modalities=("text",), - harm_categories=(), - has_unlabeled_harm_categories=True, - ), - ] + mock_memory.get_seed_dataset_summaries_async = AsyncMock( + return_value=[ + SeedDatasetSummary( + dataset_name="", + logical_examples=2, + seed_pieces=3, + objectives=1, + modalities=("text",), + harm_categories=("hate",), + has_unlabeled_harm_categories=False, + ), + SeedDatasetSummary( + dataset_name=None, + logical_examples=1, + seed_pieces=2, + objectives=0, + modalities=("text",), + harm_categories=(), + has_unlabeled_harm_categories=True, + ), + ] + ) with patch( "pyrit.backend.services.dataset_service.SeedDatasetProvider.get_all_dataset_names_async", new_callable=AsyncMock, @@ -182,17 +189,19 @@ async def test_list_datasets_never_surfaces_an_empty_dataset_name(self, dataset_ async def test_list_datasets_keeps_unnamed_population_for_whitespace_collation(self, dataset_service, mock_memory): """A whitespace-only name normalized by the memory query remains the unnamed selection.""" - mock_memory.get_seed_dataset_summaries.return_value = [ - SeedDatasetSummary( - dataset_name=None, - logical_examples=1, - seed_pieces=2, - objectives=1, - modalities=("text",), - harm_categories=(), - has_unlabeled_harm_categories=True, - ) - ] + mock_memory.get_seed_dataset_summaries_async = AsyncMock( + return_value=[ + SeedDatasetSummary( + dataset_name=None, + logical_examples=1, + seed_pieces=2, + objectives=1, + modalities=("text",), + harm_categories=(), + has_unlabeled_harm_categories=True, + ) + ] + ) with patch( "pyrit.backend.services.dataset_service.SeedDatasetProvider.get_all_dataset_names_async", new_callable=AsyncMock, @@ -223,26 +232,28 @@ async def test_list_datasets_loaded_only_matches_the_empty_memory_contract(self, assert loaded_only.items == [] async def test_list_datasets_loaded_only_restricts_to_memory(self, dataset_service, mock_memory): - mock_memory.get_seed_dataset_summaries.return_value = [ - SeedDatasetSummary( - dataset_name="harmbench", - logical_examples=3, - seed_pieces=4, - objectives=1, - modalities=("text",), - harm_categories=("hate",), - has_unlabeled_harm_categories=True, - ), - SeedDatasetSummary( - dataset_name=None, - logical_examples=1, - seed_pieces=2, - objectives=0, - modalities=("text",), - harm_categories=(), - has_unlabeled_harm_categories=True, - ), - ] + mock_memory.get_seed_dataset_summaries_async = AsyncMock( + return_value=[ + SeedDatasetSummary( + dataset_name="harmbench", + logical_examples=3, + seed_pieces=4, + objectives=1, + modalities=("text",), + harm_categories=("hate",), + has_unlabeled_harm_categories=True, + ), + SeedDatasetSummary( + dataset_name=None, + logical_examples=1, + seed_pieces=2, + objectives=0, + modalities=("text",), + harm_categories=(), + has_unlabeled_harm_categories=True, + ), + ] + ) with patch( "pyrit.backend.services.dataset_service.SeedDatasetProvider.get_all_dataset_names_async", new_callable=AsyncMock, diff --git a/tests/unit/backend/test_main.py b/tests/unit/backend/test_main.py index da70e66ad1..b86a977c02 100644 --- a/tests/unit/backend/test_main.py +++ b/tests/unit/backend/test_main.py @@ -7,6 +7,7 @@ Covers the lifespan manager and setup_frontend function. """ +import asyncio import logging import os import threading @@ -18,6 +19,8 @@ import pytest from fastapi import FastAPI from fastapi.testclient import TestClient +from httpx import ASGITransport, AsyncClient +from sqlalchemy import text from starlette.datastructures import State from starlette.exceptions import HTTPException as StarletteHTTPException @@ -25,10 +28,40 @@ from pyrit.backend.models.converters import CreateConverterRequest from pyrit.backend.services.converter_service import ConverterService, get_converter_service from pyrit.backend.services.scenario_run_service import ScenarioRunService -from pyrit.memory import AzureSQLMemory +from pyrit.memory import AzureSQLMemory, SQLiteMemory from pyrit.setup.configuration_loader import ConfigurationLoader +async def test_health_responds_while_database_operation_is_pending(sqlite_instance: SQLiteMemory) -> None: + started = threading.Event() + release = threading.Event() + + def wait_in_database() -> int: + started.set() + if not release.wait(timeout=10): + raise RuntimeError("Database wait was not released") + return 1 + + async with await sqlite_instance.get_session_async() as session: + connection = await session.connection() + await connection.run_sync( + lambda sync_connection: sync_connection.connection.run_async( + lambda driver: driver.create_function("wait_in_database", 0, wait_in_database) + ) + ) + query = asyncio.create_task(session.execute(text("SELECT wait_in_database()"))) + try: + assert await asyncio.to_thread(started.wait, 5) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + response = await asyncio.wait_for(client.get("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/api/health"), timeout=2) + assert response.status_code == 200 + assert response.json()["status"] == "healthy" + assert not query.done() + finally: + release.set() + await query + + @pytest.fixture def mock_scenario_run_lifecycle(): """Mock scenario scheduling lifecycle hooks.""" @@ -44,6 +77,7 @@ def mock_scenario_run_lifecycle(): yield service +@pytest.mark.usefixtures("patch_central_database") class TestLifespan: """Tests for the application lifespan context manager.""" @@ -164,8 +198,8 @@ async def test_lifespan_shared_memory_reconciliation_is_non_destructive(self) -> async with lifespan(app): pass - shared_memory.get_scenario_run_state_page.assert_not_called() - shared_memory.update_scenario_run_state.assert_not_called() + shared_memory.get_scenario_run_state_page_async.assert_not_awaited() + shared_memory.update_scenario_run_state_async.assert_not_awaited() async def test_lifespan_populates_default_labels_from_operator_and_operation( self, mock_scenario_run_lifecycle diff --git a/tests/unit/backend/test_mappers.py b/tests/unit/backend/test_mappers.py index b86c7f60cc..b3cd64c034 100644 --- a/tests/unit/backend/test_mappers.py +++ b/tests/unit/backend/test_mappers.py @@ -634,7 +634,7 @@ def _stub_central_memory(self): from pyrit.memory import CentralMemory stub = MagicMock() - stub.get_prompt_scores = MagicMock(return_value=[]) + stub.get_prompt_scores_async = AsyncMock(return_value=[]) with patch.object(CentralMemory, "get_memory_instance", return_value=stub): yield stub @@ -879,7 +879,7 @@ async def test_scores_are_fetched_from_memory_and_attached(self, sqlite_instance from pyrit.models import Score as RealPyritScore piece = RealPyritMessagePiece(role="user", original_value="hi", conversation_id="real-conv-scores") - sqlite_instance.add_message_to_memory(request=RealPyritMessage(message_pieces=[piece])) + (await sqlite_instance.add_message_to_memory_async(request=RealPyritMessage(message_pieces=[piece]))) score = RealPyritScore( score_value="0.75", @@ -888,9 +888,9 @@ async def test_scores_are_fetched_from_memory_and_attached(self, sqlite_instance score_rationale="example rationale", message_piece_id=piece.id, ) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) - reloaded = sqlite_instance.get_conversation_messages(conversation_id=piece.conversation_id) + reloaded = await sqlite_instance.get_conversation_messages_async(conversation_id=piece.conversation_id) result = await pyrit_messages_to_dto_async(list(reloaded)) assert len(result) == 1 @@ -909,9 +909,9 @@ async def test_empty_scores_when_none_recorded(self, sqlite_instance) -> None: from pyrit.models import MessagePiece as RealPyritMessagePiece piece = RealPyritMessagePiece(role="user", original_value="hi", conversation_id="real-conv-empty") - sqlite_instance.add_message_to_memory(request=RealPyritMessage(message_pieces=[piece])) + (await sqlite_instance.add_message_to_memory_async(request=RealPyritMessage(message_pieces=[piece]))) - reloaded = sqlite_instance.get_conversation_messages(conversation_id=piece.conversation_id) + reloaded = await sqlite_instance.get_conversation_messages_async(conversation_id=piece.conversation_id) result = await pyrit_messages_to_dto_async(list(reloaded)) assert result[0].message_pieces[0].scores == [] @@ -924,28 +924,30 @@ async def test_scores_are_grouped_per_piece_across_multiple_pieces(self, sqlite_ conv_id = "real-conv-1" user_piece = RealPyritMessagePiece(role="user", original_value="ask", conversation_id=conv_id) - sqlite_instance.add_message_to_memory(request=RealPyritMessage(message_pieces=[user_piece])) + (await sqlite_instance.add_message_to_memory_async(request=RealPyritMessage(message_pieces=[user_piece]))) assistant_piece = RealPyritMessagePiece(role="assistant", original_value="reply", conversation_id=conv_id) - sqlite_instance.add_message_to_memory(request=RealPyritMessage(message_pieces=[assistant_piece])) - - sqlite_instance.add_scores_to_memory( - scores=[ - RealPyritScore( - score_value="true", - score_type="true_false", - score_rationale="refusal detected", - message_piece_id=assistant_piece.id, - ), - RealPyritScore( - score_value="0.1", - score_type="float_scale", - score_rationale="low severity", - message_piece_id=assistant_piece.id, - ), - ] - ) - - reloaded = sqlite_instance.get_conversation_messages(conversation_id=conv_id) + (await sqlite_instance.add_message_to_memory_async(request=RealPyritMessage(message_pieces=[assistant_piece]))) + + ( + await sqlite_instance.add_scores_to_memory_async( + scores=[ + RealPyritScore( + score_value="true", + score_type="true_false", + score_rationale="refusal detected", + message_piece_id=assistant_piece.id, + ), + RealPyritScore( + score_value="0.1", + score_type="float_scale", + score_rationale="low severity", + message_piece_id=assistant_piece.id, + ), + ] + ) + ) + + reloaded = await sqlite_instance.get_conversation_messages_async(conversation_id=conv_id) result = await pyrit_messages_to_dto_async(list(reloaded)) by_role = {msg.role: msg for msg in result} @@ -970,15 +972,15 @@ async def test_multi_piece_scores_preserve_provenance_and_objective_flag(self, s conversation_id=conversation_id, sequence=1, ) - sqlite_instance.add_message_to_memory(request=Message(message_pieces=[text_piece, media_piece])) + (await sqlite_instance.add_message_to_memory_async(request=Message(message_pieces=[text_piece, media_piece]))) text_score_one = Score(score_value="true", score_type="true_false", message_piece_id=text_piece.id) text_score_two = Score(score_value="0.8", score_type="float_scale", message_piece_id=text_piece.id) media_score = Score(score_value="blocked", score_type="unknown", message_piece_id=media_piece.id) scores = [text_score_one, text_score_two, media_score] - sqlite_instance.add_scores_to_memory(scores=scores) + (await sqlite_instance.add_scores_to_memory_async(scores=scores)) - reloaded = sqlite_instance.get_conversation_messages(conversation_id=conversation_id) + reloaded = await sqlite_instance.get_conversation_messages_async(conversation_id=conversation_id) expected_score_ids_by_piece = { str(text_piece.id): {str(text_score_one.id), str(text_score_two.id)}, str(media_piece.id): {str(media_score.id)}, diff --git a/tests/unit/backend/test_message_send_service.py b/tests/unit/backend/test_message_send_service.py index 64ef7aba39..426732b3bb 100644 --- a/tests/unit/backend/test_message_send_service.py +++ b/tests/unit/backend/test_message_send_service.py @@ -4,7 +4,6 @@ """Tests for the shared synchronous manual-message owner.""" import asyncio -import threading import uuid from collections.abc import AsyncIterator, Iterator from contextlib import asynccontextmanager @@ -69,7 +68,7 @@ def send_dependencies(mock_memory: MagicMock) -> Iterator[tuple[MagicMock, Async ConversationReference(conversation_id=name, conversation_type=ConversationType.PRUNED) for name in ["second", "third"] } - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] target_service = MagicMock(spec=TargetService) converter_service = MagicMock(spec=ConverterService) send = AsyncMock(spec=PromptNormalizer.send_prompt_async) @@ -84,7 +83,7 @@ def send_dependencies(mock_memory: MagicMock) -> Iterator[tuple[MagicMock, Async @pytest.fixture -def real_send_context( +async def real_send_context( *, sqlite_instance: SQLiteMemory, patch_central_database: MagicMock ) -> Iterator[tuple[MessageSendService, AttackResult, MockPromptTarget, Base64Converter]]: target = MockPromptTarget() @@ -98,7 +97,7 @@ def real_send_context( ) ), ) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar])) with ( patch("pyrit.backend.services.message_send_service.get_target_service") as target_service, patch("pyrit.backend.services.message_send_service.get_converter_service") as converter_service, @@ -146,8 +145,8 @@ async def _send_message_and_get_update_fields( Returns: dict[str, Any]: The fields used to update the attack result. """ - mock_memory.get_attack_results.return_value = [attack_result] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [attack_result] + mock_memory.get_message_pieces_async.return_value = [] converter_objects: list[MagicMock] = [] for identifier in converter_identifiers: @@ -167,7 +166,7 @@ async def _send_message_and_get_update_fields( mock_normalizer_class.return_value.send_prompt_async = AsyncMock() await message_send_service.add_message_async(attack_result_id=attack_result_id, request=request) - return mock_memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + return mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] def _make_round_robin_identifier( @@ -203,7 +202,7 @@ class TestAddMessage: async def test_add_message_raises_for_nonexistent_attack(self, message_send_service, mock_memory) -> None: """Test that add_message raises ValueError for nonexistent attack.""" - mock_memory.get_attack_results.return_value = [] + mock_memory.get_attack_results_async.return_value = [] request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], @@ -217,7 +216,7 @@ async def test_add_message_raises_for_nonexistent_attack(self, message_send_serv async def test_add_message_raises_when_send_without_registry_name(self, message_send_service, mock_memory) -> None: """Test that add_message raises ValueError when send=True but target_registry_name missing.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], @@ -241,9 +240,9 @@ async def test_add_message_with_send_sends_via_normalizer(self, message_send_ser conversation_id="test-id", sequence=1, ) - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.side_effect = [[], [response_piece]] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.side_effect = [[], [response_piece]] + mock_memory.get_conversation_messages_async.return_value = [] with ( patch("pyrit.backend.services.message_send_service.get_target_service") as mock_get_target_svc, @@ -267,14 +266,14 @@ async def test_add_message_with_send_sends_via_normalizer(self, message_send_ser await message_send_service.add_message_async(attack_result_id="test-id", request=request) mock_normalizer.send_prompt_async.assert_called_once() - update_fields = mock_memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + update_fields = mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] assert update_fields["last_response_id"] == str(response_piece.id) async def test_add_message_with_send_raises_when_target_not_found(self, message_send_service, mock_memory) -> None: """Test that add_message with send=True raises when target object not found.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] with patch("pyrit.backend.services.message_send_service.get_target_service") as mock_get_target_svc: mock_target_svc = MagicMock() @@ -296,9 +295,9 @@ async def test_add_message_reraises_when_send_fails_without_stored_error_piece( ) -> None: """If the send fails but no error piece was stored, the exception propagates (real error).""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] # no error piece ever stored - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] # no error piece ever stored + mock_memory.get_conversation_messages_async.return_value = [] with ( patch("pyrit.backend.services.message_send_service.get_target_service") as mock_get_target_svc, @@ -327,9 +326,9 @@ async def test_add_message_with_legacy_converter_ids_warns_and_preserves_behavio ) -> None: """Test that legacy converter IDs warn and remain an unrestricted pipeline.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] + mock_memory.get_conversation_messages_async.return_value = [] with ( patch("pyrit.backend.services.message_send_service.get_target_service") as mock_get_target_svc, @@ -417,9 +416,9 @@ async def test_add_message_preserves_converter_configuration_targeting( ) -> None: """Test that request and response converter targeting reaches the normalizer.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] + mock_memory.get_conversation_messages_async.return_value = [] with ( patch("pyrit.backend.services.message_send_service.get_target_service") as mock_get_target_svc, @@ -516,7 +515,7 @@ async def test_add_message_preserves_converter_configuration_targeting( assert response_config.indexes_to_apply == [1] assert response_config.prompt_data_types_to_apply == ["text"] - update_fields = mock_memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + update_fields = mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] updated_atomic = AtomicAttackIdentifier.model_validate(update_fields["atomic_attack_identifier"]) updated_attack = updated_atomic.attack_technique.attack assert [converter.class_name for converter in updated_attack.request_converters] == [ @@ -530,7 +529,7 @@ async def test_add_message_preserves_converter_configuration_targeting( async def test_add_message_resolves_converters_before_writing(self, message_send_service, mock_memory) -> None: """Test that an unknown converter fails before message or attack writes.""" ar = make_attack_result(conversation_id="test-id", has_target=False) - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async.return_value = [ar] request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], target_conversation_id="test-id", @@ -547,18 +546,18 @@ async def test_add_message_resolves_converters_before_writing(self, message_send with pytest.raises(ValueError, match="Converter instance 'missing' not found"): await message_send_service.add_message_async(attack_result_id="test-id", request=request) - mock_memory.add_conversation_to_memory.assert_not_called() - mock_memory.add_message_pieces_to_memory.assert_not_called() - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.add_conversation_to_memory_async.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() assert not message_send_service._scheduler._conversations async def test_add_message_bumps_timestamp(self, message_send_service, mock_memory) -> None: - """Should bump the timestamp recency column via update_attack_result (no metadata write).""" + "Should bump the timestamp recency column via update_attack_result_async (no metadata write)." ar = make_attack_result(conversation_id="test-id") ar.metadata = {"created_at": "2026-01-01T00:00:00+00:00"} - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] + mock_memory.get_conversation_messages_async.return_value = [] request = AddMessageRequest( role="user", @@ -569,8 +568,8 @@ async def test_add_message_bumps_timestamp(self, message_send_service, mock_memo await message_send_service.add_message_async(attack_result_id="test-id", request=request) - mock_memory.update_attack_result_by_id.assert_called_once() - call_kwargs = mock_memory.update_attack_result_by_id.call_args[1] + mock_memory.update_attack_result_by_id_async.assert_called_once() + call_kwargs = mock_memory.update_attack_result_by_id_async.call_args[1] assert call_kwargs["attack_result_id"] == "test-id" update_fields = call_kwargs["update_fields"] assert isinstance(update_fields["timestamp"], datetime) @@ -581,9 +580,9 @@ async def test_preconverted_piece_does_not_disable_other_piece_converters( ) -> None: """Test that only the client-preconverted piece is excluded from conversion.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] + mock_memory.get_conversation_messages_async.return_value = [] mock_converter = MagicMock() mock_converter.get_identifier.return_value = ComponentIdentifier( @@ -635,7 +634,7 @@ async def test_preconverted_piece_does_not_disable_other_piece_converters( assert [identifier.class_name for identifier in sent_pieces[0].converter_identifiers] == ["Base64Converter"] assert sent_pieces[1].converter_identifiers == [] assert len(call_kwargs["response_converter_configurations"]) == 1 - update_call = mock_memory.update_attack_result_by_id.call_args[1] + update_call = mock_memory.update_attack_result_by_id_async.call_args[1] assert "atomic_attack_identifier" in update_call["update_fields"] def test_preconverted_piece_omits_configuration_with_no_eligible_indexes(self, message_send_service) -> None: @@ -653,8 +652,8 @@ def test_preconverted_piece_omits_configuration_with_no_eligible_indexes(self, m async def test_rejects_unrelated_conversation_id(self, message_send_service, mock_memory): """Writing to a conversation_id that doesn't belong to the attack should raise ValueError.""" ar = make_attack_result(conversation_id="attack-1") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] request = AddMessageRequest( role="user", @@ -1164,8 +1163,8 @@ class TestAddMessageGuards: async def test_rejects_mismatched_target(self, message_send_service, mock_memory) -> None: """Should raise ValueError when request target differs from attack target.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] # Create a mock target with a different class_name wrong_target = MagicMock() @@ -1195,9 +1194,9 @@ async def test_allows_matching_target( ) -> None: """Should NOT raise when request target matches attack target.""" ar = make_attack_result(conversation_id="test-id", has_target=has_target) - mock_memory.get_attack_results.return_value = [ar] - mock_memory.get_message_pieces.return_value = [] - mock_memory.get_conversation_messages.return_value = [] + mock_memory.get_attack_results_async.return_value = [ar] + mock_memory.get_message_pieces_async.return_value = [] + mock_memory.get_conversation_messages_async.return_value = [] with ( patch("pyrit.backend.services.message_send_service.get_target_service") as mock_get_target_svc, @@ -1264,13 +1263,13 @@ def test_rejects_incompatible_round_robin_target( class TestResolveVideoRemixMetadata: - """Tests for _resolve_video_remix_metadata.""" + "Tests for _resolve_video_remix_metadata_async." - def test_resolves_video_id_from_original_piece(self, message_send_service, mock_memory): + async def test_resolves_video_id_from_original_piece(self, message_send_service, mock_memory): """When a video_path piece has original_prompt_id, resolve video_id onto text piece.""" original_piece = MagicMock() original_piece.prompt_metadata = {"video_id": "vid-abc-123"} - mock_memory.get_message_pieces.return_value = [original_piece] + mock_memory.get_message_pieces_async.return_value = [original_piece] request = AddMessageRequest( role="user", @@ -1285,12 +1284,12 @@ def test_resolves_video_id_from_original_piece(self, message_send_service, mock_ ], ) - message_send_service._resolve_video_remix_metadata(request) + (await message_send_service._resolve_video_remix_metadata_async(request)) assert request.pieces[0].prompt_metadata == {"video_id": "vid-abc-123"} assert request.pieces[1].prompt_metadata == {"video_id": "vid-abc-123"} - def test_no_op_without_video_pieces(self, message_send_service): + async def test_no_op_without_video_pieces(self, message_send_service): """Should do nothing when there are no video_path pieces.""" request = AddMessageRequest( role="user", @@ -1298,11 +1297,11 @@ def test_no_op_without_video_pieces(self, message_send_service): pieces=[MessagePieceRequest(original_value="just text", data_type="text")], ) - message_send_service._resolve_video_remix_metadata(request) + (await message_send_service._resolve_video_remix_metadata_async(request)) assert request.pieces[0].prompt_metadata is None - def test_no_op_when_video_id_already_set(self, message_send_service, mock_memory): + async def test_no_op_when_video_id_already_set(self, message_send_service, mock_memory): """Should not overwrite existing video_id on text piece.""" request = AddMessageRequest( role="user", @@ -1321,12 +1320,12 @@ def test_no_op_when_video_id_already_set(self, message_send_service, mock_memory ], ) - message_send_service._resolve_video_remix_metadata(request) + (await message_send_service._resolve_video_remix_metadata_async(request)) assert request.pieces[0].prompt_metadata == {"video_id": "existing-id"} - mock_memory.get_message_pieces.assert_not_called() + mock_memory.get_message_pieces_async.assert_not_called() - def test_no_op_without_original_prompt_id(self, message_send_service, mock_memory): + async def test_no_op_without_original_prompt_id(self, message_send_service, mock_memory): """Should not crash when video_path piece has no original_prompt_id.""" request = AddMessageRequest( role="user", @@ -1337,16 +1336,16 @@ def test_no_op_without_original_prompt_id(self, message_send_service, mock_memor ], ) - message_send_service._resolve_video_remix_metadata(request) + (await message_send_service._resolve_video_remix_metadata_async(request)) assert request.pieces[0].prompt_metadata is None - mock_memory.get_message_pieces.assert_not_called() + mock_memory.get_message_pieces_async.assert_not_called() - def test_no_op_when_original_piece_has_no_video_id(self, message_send_service, mock_memory): + async def test_no_op_when_original_piece_has_no_video_id(self, message_send_service, mock_memory): """Should not set metadata when original piece has no video_id.""" original_piece = MagicMock() original_piece.prompt_metadata = {"other_key": "value"} - mock_memory.get_message_pieces.return_value = [original_piece] + mock_memory.get_message_pieces_async.return_value = [original_piece] request = AddMessageRequest( role="user", @@ -1361,7 +1360,7 @@ def test_no_op_when_original_piece_has_no_video_id(self, message_send_service, m ], ) - message_send_service._resolve_video_remix_metadata(request) + (await message_send_service._resolve_video_remix_metadata_async(request)) assert request.pieces[0].prompt_metadata is None @@ -1637,7 +1636,7 @@ async def prepare_async(_: AddMessageRequest) -> None: await started.wait() with pytest.raises(ManualSendConflictError): await peer.add_message_async(attack_result_id="attack", request=_request(send=incoming_send)) - mock_memory.add_message_pieces_to_memory.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() finally: active.cancel() with pytest.raises(asyncio.CancelledError): @@ -1730,7 +1729,7 @@ async def test_target_pacing_does_not_block_another_target_async( other_attack = make_attack_result( conversation_id=str(uuid.uuid4()), attack_result_id=str(uuid.uuid4()), has_target=False ) - await asyncio.to_thread(sqlite_instance.add_attack_results_to_memory, attack_results=[other_attack]) + await sqlite_instance.add_attack_results_to_memory_async(attack_results=[other_attack]) waiting, release = asyncio.Event(), asyncio.Event() delays: list[float] = [] @@ -1783,8 +1782,7 @@ async def test_converter_protection_is_per_instance_async( scheduler = service._scheduler peer = MessageSendService(scheduler=scheduler) branch_ids = [str(uuid.uuid4()), str(uuid.uuid4())] - await asyncio.to_thread( - sqlite_instance.add_conversation_branches_to_attack, + await sqlite_instance.add_conversation_branches_to_attack_async( attack_result_id=ar.attack_result_id, conversations=[ Conversation(conversation_id=cid, target_identifier=target.get_identifier()) for cid in branch_ids @@ -1865,7 +1863,7 @@ async def test_dispatch_failure_releases_ownership_without_reusing_old_errors_as error: BaseException, ) -> None: _, send = send_dependencies - mock_memory.get_message_pieces.return_value = [ + mock_memory.get_message_pieces_async.return_value = [ MessagePiece( role="assistant", original_value="old error", response_error="processing", conversation_id="main" ) @@ -1874,13 +1872,13 @@ async def test_dispatch_failure_releases_ownership_without_reusing_old_errors_as with pytest.raises(type(error)): await message_send_service.add_message_async(attack_result_id="attack", request=_request()) send.assert_awaited_once() - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() assert not message_send_service._scheduler._conversations assert message_send_service._scheduler._active == 0 send.side_effect = None await message_send_service.add_message_async(attack_result_id="attack", request=_request()) - @pytest.mark.parametrize("write_method", ["add_message_pieces_to_memory", "update_attack_result_by_id"]) + @pytest.mark.parametrize("write_method", ["add_message_pieces_to_memory_async", "update_attack_result_by_id_async"]) async def test_cancellation_joins_memory_write_before_releasing_ownership_async( self, *, @@ -1889,15 +1887,14 @@ async def test_cancellation_joins_memory_write_before_releasing_ownership_async( send_dependencies: tuple[MagicMock, AsyncMock], write_method: str, ) -> None: - started, release, finished = asyncio.Event(), threading.Event(), threading.Event() - loop = asyncio.get_running_loop() + started, release, finished = asyncio.Event(), asyncio.Event(), asyncio.Event() - def hold_write(**_: Any) -> None: - loop.call_soon_threadsafe(started.set) - assert release.wait(timeout=5) + async def hold_write_async(**_: Any) -> None: + started.set() + await asyncio.wait_for(release.wait(), timeout=5) finished.set() - with patch.object(mock_memory, write_method, side_effect=hold_write): + with patch.object(mock_memory, write_method, side_effect=hold_write_async): active = asyncio.create_task( message_send_service.add_message_async(attack_result_id="attack", request=_request(send=False)) ) @@ -1907,7 +1904,7 @@ def hold_write(**_: Any) -> None: active.cancel() await asyncio.sleep(0) assert not active.done() - if write_method == "update_attack_result_by_id": + if write_method == "update_attack_result_by_id_async": assert message_send_service._scheduler._metadata_updates == {"attack"} with pytest.raises(ManualSendConflictError): await message_send_service.add_message_async( @@ -1922,7 +1919,7 @@ def hold_write(**_: Any) -> None: assert not message_send_service._scheduler._metadata_updates await message_send_service.add_message_async(attack_result_id="attack", request=_request(send=False)) - @pytest.mark.parametrize("write_method", ["add_message_pieces_to_memory", "update_attack_result_by_id"]) + @pytest.mark.parametrize("write_method", ["add_message_pieces_to_memory_async", "update_attack_result_by_id_async"]) async def test_memory_failure_releases_ownership_and_capacity_async( self, *, @@ -1949,11 +1946,11 @@ async def test_disappearing_attack_reports_finalization_error_async( send_dependencies: tuple[MagicMock, AsyncMock], ) -> None: _, send = send_dependencies - mock_memory.get_attack_results.side_effect = [mock_memory.get_attack_results.return_value, []] + mock_memory.get_attack_results_async.side_effect = [mock_memory.get_attack_results_async.return_value, []] with pytest.raises(ValueError, match="not found after message send"): await message_send_service.add_message_async(attack_result_id="attack", request=_request()) send.assert_awaited_once() - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() assert not message_send_service._scheduler._conversations async def test_queued_converter_updates_merge_current_metadata_async( @@ -1964,8 +1961,7 @@ async def test_queued_converter_updates_merge_current_metadata_async( ) -> None: _, ar, target, first_converter = real_send_context conversation_id = str(uuid.uuid4()) - await asyncio.to_thread( - sqlite_instance.add_conversation_branches_to_attack, + await sqlite_instance.add_conversation_branches_to_attack_async( attack_result_id=ar.attack_result_id, conversations=[Conversation(conversation_id=conversation_id, target_identifier=target.get_identifier())], message_pieces=[], @@ -2007,7 +2003,7 @@ async def hold_first_async(*, conversation_id: str, **_: Any) -> None: finally: release.set() await asyncio.gather(*tasks) - stored = await asyncio.to_thread(sqlite_instance.get_attack_results, attack_result_ids=[ar.attack_result_id]) + stored = await sqlite_instance.get_attack_results_async(attack_result_ids=[ar.attack_result_id]) strategy = stored[0].get_attack_strategy_identifier() assert strategy is not None for pipeline in ["request_converters", "response_converters"]: @@ -2032,8 +2028,7 @@ async def test_parallel_sends_serialize_complete_metadata_updates_async( scheduler = first._scheduler second = MessageSendService(scheduler=scheduler) branch_id = str(uuid.uuid4()) - await asyncio.to_thread( - sqlite_instance.add_conversation_branches_to_attack, + await sqlite_instance.add_conversation_branches_to_attack_async( attack_result_id=ar.attack_result_id, conversations=[Conversation(conversation_id=branch_id, target_identifier=target.get_identifier())], message_pieces=[], @@ -2046,12 +2041,11 @@ async def test_parallel_sends_serialize_complete_metadata_updates_async( request.pieces[0].applied_converter_ids = [name] second_target_started, first_write_started = asyncio.Event(), asyncio.Event() - second_metadata_attempted, release_first_write = asyncio.Event(), threading.Event() - loop = asyncio.get_running_loop() + second_metadata_attempted, release_first_write = asyncio.Event(), asyncio.Event() writes: list[dict[str, Any]] = [] attempts = 0 send = target._send_prompt_to_target_async - update = sqlite_instance.update_attack_result_by_id + update = sqlite_instance.update_attack_result_by_id_async guard = scheduler.metadata_update_async async def overlap_targets_async(*, normalized_conversation: list[Message]) -> list[Message]: @@ -2072,16 +2066,16 @@ async def observe_metadata_async(*, attack_result_id: str) -> AsyncIterator[None async with guard(attack_result_id=attack_result_id): yield - def delay_first_write(*, attack_result_id: str, update_fields: dict[str, Any]) -> None: + async def delay_first_write_async(*, attack_result_id: str, update_fields: dict[str, Any]) -> None: writes.append(update_fields) if len(writes) == 1: - loop.call_soon_threadsafe(first_write_started.set) - assert release_first_write.wait(timeout=5) - update(attack_result_id=attack_result_id, update_fields=update_fields) + first_write_started.set() + await asyncio.wait_for(release_first_write.wait(), timeout=5) + await update(attack_result_id=attack_result_id, update_fields=update_fields) with ( patch.object(target, "_send_prompt_to_target_async", side_effect=overlap_targets_async), - patch.object(sqlite_instance, "update_attack_result_by_id", side_effect=delay_first_write), + patch.object(sqlite_instance, "update_attack_result_by_id_async", side_effect=delay_first_write_async), patch.object(scheduler, "metadata_update_async", side_effect=observe_metadata_async), patch("pyrit.backend.services.message_send_service.get_converter_service") as registry, ): @@ -2105,7 +2099,7 @@ def delay_first_write(*, attack_result_id: str, update_fields: dict[str, Any]) - assert len(writes) == 2 assert writes[0]["timestamp"] <= writes[1]["timestamp"] - stored = await asyncio.to_thread(sqlite_instance.get_attack_results, attack_result_ids=[ar.attack_result_id]) + stored = await sqlite_instance.get_attack_results_async(attack_result_ids=[ar.attack_result_id]) assert stored[0].timestamp == writes[1]["timestamp"] assert stored[0].last_response is not None assert stored[0].last_response.conversation_id == branch_id @@ -2134,7 +2128,7 @@ async def test_multipart_preconverted_lineage_and_response_conversion_async( source = [ MessagePiece(role="user", original_value=value, conversation_id=source_id) for value in ["Hello", "World"] ] - await asyncio.to_thread(sqlite_instance.add_message_pieces_to_memory, message_pieces=source) + await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=source) request = AddMessageRequest( target_conversation_id=ar.conversation_id, target_registry_name="target", @@ -2154,9 +2148,7 @@ async def test_multipart_preconverted_lineage_and_response_conversion_async( "already converted", "V29ybGQ=", ] - messages = await asyncio.to_thread( - sqlite_instance.get_conversation_messages, conversation_id=ar.conversation_id - ) + messages = await sqlite_instance.get_conversation_messages_async(conversation_id=ar.conversation_id) assert len(messages) == 2 assert [piece.original_value for piece in messages[0].message_pieces] == ["Hello", "World"] assert [piece.original_prompt_id for piece in messages[0].message_pieces] == [piece.id for piece in source] @@ -2165,7 +2157,7 @@ async def test_multipart_preconverted_lineage_and_response_conversion_async( assert messages[1].sequence == 1 assert messages[1].message_pieces[0].original_value == "default" assert messages[1].message_pieces[0].converted_value == "ZGVmYXVsdA==" - stored = await asyncio.to_thread(sqlite_instance.get_attack_results, attack_result_ids=[ar.attack_result_id]) + stored = await sqlite_instance.get_attack_results_async(attack_result_ids=[ar.attack_result_id]) assert service._memory is PromptNormalizer()._memory is sqlite_instance assert len(stored) == 1 assert stored[0].last_response is not None @@ -2195,16 +2187,12 @@ async def test_normalizer_owns_persistence_async( else: with pytest.raises(RuntimeError, match=failure): await service.add_message_async(attack_result_id=ar.attack_result_id, request=request) - messages = await asyncio.to_thread( - sqlite_instance.get_conversation_messages, conversation_id=ar.conversation_id - ) + messages = await sqlite_instance.get_conversation_messages_async(conversation_id=ar.conversation_id) assert len(messages) == {"request-converter": 0, "target": 2, "response-converter": 1, "write-only": 1}[failure] if failure == "target": assert messages[-1].message_pieces[0].response_error == "processing" assert "RuntimeError: target" in messages[-1].message_pieces[0].converted_value - stored = await asyncio.to_thread( - sqlite_instance.get_attack_results, attack_result_ids=[ar.attack_result_id] - ) + stored = await sqlite_instance.get_attack_results_async(attack_result_ids=[ar.attack_result_id]) assert stored[0].last_response is not None assert stored[0].last_response.id == messages[-1].message_pieces[0].id else: @@ -2220,7 +2208,7 @@ class TestExactPreviewSend: async def test_type_changing_execution_provenance_is_preserved_async( self, *, message_send_service: MessageSendService, mock_memory: MagicMock, send: bool ) -> None: - mock_memory.get_attack_results.return_value = [make_attack_result(conversation_id="test-id")] + mock_memory.get_attack_results_async.return_value = [make_attack_result(conversation_id="test-id")] converters = {} for name, input_type, output_type, output in [ ("ToImage", "text", "image_path", "preview.png"), @@ -2288,13 +2276,13 @@ async def test_type_changing_execution_provenance_is_preserved_async( if send: piece = target.send_prompt_async.call_args.kwargs["message"].message_pieces[0] else: - piece = mock_memory.add_message_pieces_to_memory.call_args.kwargs["message_pieces"][0] + piece = mock_memory.add_message_pieces_to_memory_async.call_args.kwargs["message_pieces"][0] target.send_prompt_async.assert_not_awaited() assert piece.converted_value == "edited caption" assert [identifier.class_name for identifier in piece.converter_identifiers] == expected for converter in converters.values(): converter.convert_tokens_async.assert_not_awaited() - update_fields = mock_memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + update_fields = mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] identifier = AtomicAttackIdentifier.model_validate(update_fields["atomic_attack_identifier"]) assert [converter.class_name for converter in identifier.attack_technique.attack.request_converters] == [ "ToImage", @@ -2304,7 +2292,7 @@ async def test_type_changing_execution_provenance_is_preserved_async( async def test_unknown_applied_converter_rejected_before_sending_async( self, *, message_send_service: MessageSendService, mock_memory: MagicMock ) -> None: - mock_memory.get_attack_results.return_value = [make_attack_result(conversation_id="test-id")] + mock_memory.get_attack_results_async.return_value = [make_attack_result(conversation_id="test-id")] request = AddMessageRequest( pieces=[ MessagePieceRequest( @@ -2326,8 +2314,8 @@ async def test_unknown_applied_converter_rejected_before_sending_async( with pytest.raises(ValueError, match="unknown"): await message_send_service.add_message_async(attack_result_id="test-id", request=request) send.assert_not_awaited() - mock_memory.add_message_pieces_to_memory.assert_not_called() - mock_memory.update_attack_result_by_id.assert_not_called() + mock_memory.add_message_pieces_to_memory_async.assert_not_called() + mock_memory.update_attack_result_by_id_async.assert_not_called() @pytest.mark.parametrize("original_value", ["Original source", ""]) @pytest.mark.parametrize("has_converter_pipeline", [True, False]) @@ -2386,7 +2374,7 @@ async def test_exact_preview_provenance_survives_memory_and_response_mapping_asy sent_piece = target.send_prompt_async.call_args.kwargs["message"].message_pieces[0] assert sent_piece.original_value == original_value assert sent_piece.converted_value == "Exact edited preview" - pieces = sqlite_instance.get_message_pieces(conversation_id=conversation_id) + pieces = await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id) assert len(pieces) == 1 piece = pieces[0] assert piece.original_value == original_value @@ -2442,7 +2430,7 @@ async def test_send_preserves_exact_preview_and_converts_other_piece_async( expected_original: str, expected_final: str, ) -> None: - mock_memory.get_attack_results.return_value = [make_attack_result(conversation_id="test-id")] + mock_memory.get_attack_results_async.return_value = [make_attack_result(conversation_id="test-id")] preview_converter = MagicMock(spec=Converter) preview_converter.get_identifier.return_value = ComponentIdentifier( class_name="PreviewConverter", @@ -2518,8 +2506,8 @@ async def test_send_preserves_exact_preview_and_converts_other_piece_async( assert live.original_value == "Unconverted" assert live.converted_value == "Live conversion" assert [identifier.class_name for identifier in live.converter_identifiers] == ["LiveConverter"] - assert mock_memory.add_message_to_memory.call_args.kwargs["request"] is message - update_fields = mock_memory.update_attack_result_by_id.call_args.kwargs["update_fields"] + assert mock_memory.add_message_to_memory_async.call_args.kwargs["request"] is message + update_fields = mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] identifier = AtomicAttackIdentifier.model_validate(update_fields["atomic_attack_identifier"]) assert [converter.class_name for converter in identifier.attack_technique.attack.request_converters] == [ "PreviewConverter", diff --git a/tests/unit/backend/test_runtime_lifecycle.py b/tests/unit/backend/test_runtime_lifecycle.py index ba18d4330e..87d5489b33 100644 --- a/tests/unit/backend/test_runtime_lifecycle.py +++ b/tests/unit/backend/test_runtime_lifecycle.py @@ -6,8 +6,9 @@ import asyncio import os from collections.abc import Generator +from contextlib import nullcontext from pathlib import Path -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, call, patch import httpx import pytest @@ -20,6 +21,8 @@ from pyrit.backend.routes import configuration, health from pyrit.backend.services.configuration_file_service import ConfigurationFileService from pyrit.backend.services.runtime_lifecycle import RuntimeLifecycle +from pyrit.backend.services.scenario_run_service import ScenarioRunService +from pyrit.memory import CentralMemory, MemoryInterface from pyrit.setup.configuration_loader import ConfigurationLoader @@ -71,6 +74,29 @@ async def apply_async(runtime: RuntimeLifecycle) -> None: await runtime.apply_task +@pytest.mark.parametrize("failure", [None, "scenarios", "services"]) +async def test_shutdown_disposes_memory_after_services_even_on_failure( + runtime: RuntimeLifecycle, failure: str | None +) -> None: + memory = MagicMock(spec=MemoryInterface) + scenario_service = MagicMock(spec=ScenarioRunService) + order = MagicMock() + with ( + patch.object(CentralMemory, "_memory_instance", memory), + patch.object(lifecycle_module, "peek_scenario_run_service", return_value=scenario_service), + patch.object(lifecycle_module, "close_services_async", new_callable=AsyncMock) as close_services, + ): + order.attach_mock(scenario_service.shutdown_async, "scenarios") + order.attach_mock(close_services, "services") + order.attach_mock(memory.dispose_engine_async, "memory") + if failure is not None: + getattr(order, failure).side_effect = RuntimeError("cleanup failed") + with pytest.raises(RuntimeError, match="cleanup failed") if failure else nullcontext(): + await runtime.shutdown_async() + + assert order.mock_calls == [call.scenarios(), call.services(), call.memory()] + + async def test_success_preflights_then_replaces_idle_runtime(runtime: RuntimeLifecycle) -> None: await apply_async(runtime) assert runtime.state == "ready" diff --git a/tests/unit/backend/test_scenario_progress_read_model.py b/tests/unit/backend/test_scenario_progress_read_model.py index 9cb0afb773..425751d61d 100644 --- a/tests/unit/backend/test_scenario_progress_read_model.py +++ b/tests/unit/backend/test_scenario_progress_read_model.py @@ -3,10 +3,10 @@ """Tests for the scenario progress read model.""" +import asyncio import uuid -from concurrent.futures import ThreadPoolExecutor from datetime import UTC, datetime, timedelta -from unittest.mock import MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -39,9 +39,9 @@ def _make_delta(*, run_id: str, index: int = 0) -> ScenarioAttackResultDelta: ) -def _get_snapshot(*, read_model: ScenarioProgressReadModel, run_id: str) -> ScenarioProgressSnapshot: +async def _get_snapshot_async(*, read_model: ScenarioProgressReadModel, run_id: str) -> ScenarioProgressSnapshot: """Read one incomplete synthetic run through the public typed boundary.""" - return read_model.get_snapshot( + return await read_model.get_snapshot_async( scenario_result_id=run_id, plan=None, plan_complete=False, @@ -51,7 +51,7 @@ def _get_snapshot(*, read_model: ScenarioProgressReadModel, run_id: str) -> Scen ) -def test_get_snapshot_evicts_least_recently_used_run() -> None: +async def test_get_snapshot_evicts_least_recently_used_run() -> None: memory = MagicMock(spec=MemoryInterface) deltas = {run_id: _make_delta(run_id=run_id) for run_id in ("run-a", "run-b", "run-c")} @@ -64,27 +64,27 @@ def get_deltas( assert limit == ScenarioProgressReadModel._STORAGE_PAGE_SIZE return ([deltas[scenario_result_id]], False) if cursor is None else ([], False) - memory.get_scenario_attack_result_deltas.side_effect = get_deltas + memory.get_scenario_attack_result_deltas_async = AsyncMock(side_effect=get_deltas) read_model = ScenarioProgressReadModel(memory=memory) with patch.object(ScenarioProgressReadModel, "_CACHE_MAX_RUNS", 2): - first = _get_snapshot(read_model=read_model, run_id="run-a") - _get_snapshot(read_model=read_model, run_id="run-b") - second = _get_snapshot(read_model=read_model, run_id="run-a") - _get_snapshot(read_model=read_model, run_id="run-c") - _get_snapshot(read_model=read_model, run_id="run-b") + first = await _get_snapshot_async(read_model=read_model, run_id="run-a") + (await _get_snapshot_async(read_model=read_model, run_id="run-b")) + second = await _get_snapshot_async(read_model=read_model, run_id="run-a") + (await _get_snapshot_async(read_model=read_model, run_id="run-c")) + (await _get_snapshot_async(read_model=read_model, run_id="run-b")) assert isinstance(first, ScenarioProgressSnapshot) assert isinstance(first.deltas, tuple) assert first.results == second.results run_a_cursors = [ call.kwargs["cursor"] - for call in memory.get_scenario_attack_result_deltas.call_args_list + for call in memory.get_scenario_attack_result_deltas_async.call_args_list if call.kwargs["scenario_result_id"] == "run-a" ] run_b_cursors = [ call.kwargs["cursor"] - for call in memory.get_scenario_attack_result_deltas.call_args_list + for call in memory.get_scenario_attack_result_deltas_async.call_args_list if call.kwargs["scenario_result_id"] == "run-b" ] assert run_a_cursors[0] is None @@ -92,10 +92,77 @@ def get_deltas( assert run_b_cursors == [None, None] -def test_get_snapshot_invalidates_cache_when_plan_changes() -> None: +async def test_cancelled_refresh_releases_lock_and_updates_partially_loaded_summary() -> None: + memory = MagicMock(spec=MemoryInterface) + first = _make_delta(run_id="run", index=0) + second = _make_delta(run_id="run", index=1) + memory.get_scenario_attack_result_deltas_async.return_value = ([first], False) + read_model = ScenarioProgressReadModel(memory=memory) + initial = await _get_snapshot_async(read_model=read_model, run_id="run") + assert initial.summary.overall.completed == 1 + blocked = asyncio.Event() + + async def get_deltas_async( + *, scenario_result_id: str, cursor: AttackResultKeysetCursor | None, limit: int + ) -> tuple[list[ScenarioAttackResultDelta], bool]: + if cursor is not None and cursor.attack_result_id == first.attack_result_id: + return [second], True + blocked.set() + await asyncio.Event().wait() + return [], False + + memory.get_scenario_attack_result_deltas_async.side_effect = get_deltas_async + task = asyncio.create_task(_get_snapshot_async(read_model=read_model, run_id="run")) + await asyncio.wait_for(blocked.wait(), timeout=5) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + memory.get_scenario_attack_result_deltas_async = AsyncMock(return_value=([], False)) + refreshed = await asyncio.wait_for(_get_snapshot_async(read_model=read_model, run_id="run"), timeout=5) + assert len(refreshed.results) == 2 + assert refreshed.summary.overall.completed == 2 + assert refreshed.summary.overall.succeeded == 2 + + +async def test_sync_and_async_snapshots_share_cache_and_cursor() -> None: + memory = MagicMock(spec=MemoryInterface) + deltas = [_make_delta(run_id="shared", index=index) for index in range(3)] + memory.get_scenario_attack_result_deltas_async.side_effect = [ + ([deltas[0]], False), + ([deltas[2]], False), + ] + memory.get_scenario_attack_result_deltas.return_value = ([deltas[1]], False) + read_model = ScenarioProgressReadModel(memory=memory) + + first = await _get_snapshot_async(read_model=read_model, run_id="shared") + with pytest.warns(DeprecationWarning): + second = read_model.get_snapshot( + scenario_result_id="shared", + plan=None, + plan_complete=False, + active_group_ids=(), + terminal=False, + objective_scorer_identifier=None, + ) + third = await _get_snapshot_async(read_model=read_model, run_id="shared") + + assert [snapshot.summary.overall.completed for snapshot in (first, second, third)] == [1, 2, 3] + assert ( + memory.get_scenario_attack_result_deltas.call_args.kwargs["cursor"].attack_result_id + == deltas[0].attack_result_id + ) + assert ( + memory.get_scenario_attack_result_deltas_async.call_args.kwargs["cursor"].attack_result_id + == deltas[1].attack_result_id + ) + assert third.deltas == tuple(deltas) + + +async def test_get_snapshot_invalidates_cache_when_plan_changes() -> None: memory = MagicMock(spec=MemoryInterface) delta = _make_delta(run_id="run-plan") - memory.get_scenario_attack_result_deltas.return_value = ([delta], False) + memory.get_scenario_attack_result_deltas_async = AsyncMock(return_value=([delta], False)) read_model = ScenarioProgressReadModel(memory=memory) def make_plan(group_id: str) -> ScenarioRunPlan: @@ -118,7 +185,7 @@ def make_plan(group_id: str) -> ScenarioRunPlan: ], ) - first = read_model.get_snapshot( + first = await read_model.get_snapshot_async( scenario_result_id="run-plan", plan=make_plan("group-a"), plan_complete=True, @@ -126,7 +193,7 @@ def make_plan(group_id: str) -> ScenarioRunPlan: terminal=False, objective_scorer_identifier=None, ) - second = read_model.get_snapshot( + second = await read_model.get_snapshot_async( scenario_result_id="run-plan", plan=make_plan("group-b"), plan_complete=True, @@ -137,7 +204,7 @@ def make_plan(group_id: str) -> ScenarioRunPlan: assert first.results[0].atomic_group_id == "group-a" assert second.results[0].atomic_group_id == "group-b" - assert [call.kwargs["cursor"] for call in memory.get_scenario_attack_result_deltas.call_args_list] == [ + assert [call.kwargs["cursor"] for call in memory.get_scenario_attack_result_deltas_async.call_args_list] == [ None, None, ] @@ -151,7 +218,7 @@ def make_plan(group_id: str) -> ScenarioRunPlan: pytest.param((), False, False, "PENDING", None, id="plan-completeness-change"), ], ) -def test_get_snapshot_updates_summary_without_new_rows( +async def test_get_snapshot_updates_summary_without_new_rows( *, active_group_ids: tuple[str, ...], terminal: bool, @@ -180,11 +247,13 @@ def test_get_snapshot_updates_summary_without_new_rows( for index, delta in enumerate(deltas) ], ) - memory.get_scenario_attack_result_deltas.side_effect = [([deltas[0]], False), ([], False), ([], False)] + memory.get_scenario_attack_result_deltas_async = AsyncMock( + side_effect=[([deltas[0]], False), ([], False), ([], False)] + ) read_model = ScenarioProgressReadModel(memory=memory) with patch.object(read_model, "_map_progress_delta", wraps=read_model._map_progress_delta) as map_delta: - first = read_model.get_snapshot( + first = await read_model.get_snapshot_async( scenario_result_id="run-state", plan=plan, plan_complete=True, @@ -192,7 +261,7 @@ def test_get_snapshot_updates_summary_without_new_rows( terminal=False, objective_scorer_identifier=None, ) - second = read_model.get_snapshot( + second = await read_model.get_snapshot_async( scenario_result_id="run-state", plan=plan, plan_complete=plan_complete, @@ -200,7 +269,7 @@ def test_get_snapshot_updates_summary_without_new_rows( terminal=terminal, objective_scorer_identifier=None, ) - restored = read_model.get_snapshot( + restored = await read_model.get_snapshot_async( scenario_result_id="run-state", plan=plan, plan_complete=True, @@ -222,14 +291,14 @@ def test_get_snapshot_updates_summary_without_new_rows( timestamp=deltas[0].timestamp, attack_result_id=deltas[0].attack_result_id, ) - assert [call.kwargs["cursor"] for call in memory.get_scenario_attack_result_deltas.call_args_list] == [ + assert [call.kwargs["cursor"] for call in memory.get_scenario_attack_result_deltas_async.call_args_list] == [ None, cursor, cursor, ] -def test_get_snapshot_keeps_concurrent_runs_isolated() -> None: +async def test_get_snapshot_keeps_concurrent_runs_isolated() -> None: memory = MagicMock(spec=MemoryInterface) def get_deltas( @@ -241,15 +310,14 @@ def get_deltas( assert limit == ScenarioProgressReadModel._STORAGE_PAGE_SIZE return ([_make_delta(run_id=scenario_result_id)], False) if cursor is None else ([], False) - memory.get_scenario_attack_result_deltas.side_effect = get_deltas + memory.get_scenario_attack_result_deltas_async = AsyncMock(side_effect=get_deltas) read_model = ScenarioProgressReadModel(memory=memory) run_ids = [f"run-{index}" for index in range(8)] - def read_run(run_id: str) -> ScenarioProgressSnapshot: - return _get_snapshot(read_model=read_model, run_id=run_id) + async def read_run_async(run_id: str) -> ScenarioProgressSnapshot: + return await _get_snapshot_async(read_model=read_model, run_id=run_id) - with ThreadPoolExecutor(max_workers=4) as executor: - snapshots = list(executor.map(read_run, run_ids)) + snapshots = await asyncio.gather(*(read_run_async(run_id) for run_id in run_ids)) assert [snapshot.results[0].conversation_id for snapshot in snapshots] == [ f"conversation-{run_id}-0" for run_id in run_ids diff --git a/tests/unit/backend/test_scenario_resume.py b/tests/unit/backend/test_scenario_resume.py index 2015a2bd44..472dc09042 100644 --- a/tests/unit/backend/test_scenario_resume.py +++ b/tests/unit/backend/test_scenario_resume.py @@ -162,8 +162,10 @@ async def fail_second_async(*, normalized_conversation: list[Message]) -> list[M with pytest.raises(ScenarioPartialFailureException): await scenario.run_async() assert scenario._scenario_result_id is not None - result = CentralMemory.get_memory_instance().get_scenario_results( - scenario_result_ids=[scenario._scenario_result_id] + result = ( + await CentralMemory.get_memory_instance().get_scenario_results_async( + scenario_result_ids=[scenario._scenario_result_id] + ) )[0] assert result.scenario_run_state == ScenarioRunState.FAILED return result @@ -175,7 +177,7 @@ async def test_resume_preserves_completed_objectives_and_original_id_async( service, target = resume_environment stored = await _create_failed_run_async(target=target, legacy=False) run_id = str(stored.id) - before = CentralMemory.get_memory_instance().get_attack_results(scenario_result_id=run_id) + before = await CentralMemory.get_memory_instance().get_attack_results_async(scenario_result_id=run_id) completed_ids = {result.attack_result_id for result in before if result.outcome != AttackOutcome.ERROR} assert len(completed_ids) == 1 failed_result = next(result for result in before if result.outcome == AttackOutcome.ERROR) @@ -201,8 +203,8 @@ async def test_resume_preserves_completed_objectives_and_original_id_async( assert request.labels == _LABELS assert response.scenario_result_id == run_id assert target.prompt_sent == [_SECOND_OBJECTIVE] - after = CentralMemory.get_memory_instance().get_scenario_results(scenario_result_ids=[run_id])[0] - results = CentralMemory.get_memory_instance().get_attack_results(scenario_result_id=run_id) + after = (await CentralMemory.get_memory_instance().get_scenario_results_async(scenario_result_ids=[run_id]))[0] + results = await CentralMemory.get_memory_instance().get_attack_results_async(scenario_result_id=run_id) assert after.scenario_run_state == ScenarioRunState.COMPLETED assert after.labels == _LABELS assert after.scenario_identifier.params["marker"] == "original" @@ -213,9 +215,9 @@ async def test_resume_preserves_completed_objectives_and_original_id_async( result.operator == _LABELS["operator"] and result.operation == _LABELS["operation"] for result in results ) assert sum(result.objective == _FIRST_OBJECTIVE for result in results) == 1 - assert len(CentralMemory.get_memory_instance().get_scenario_results()) == 1 - detail = await asyncio.to_thread(service.get_run, scenario_result_id=run_id) - history = await asyncio.to_thread(service.list_runs) + assert len(await CentralMemory.get_memory_instance().get_scenario_results_async()) == 1 + detail = await service.get_run_async(scenario_result_id=run_id) + history = await service.list_runs_async() assert detail is not None assert detail.status == ScenarioRunState.COMPLETED assert detail.error is None @@ -244,9 +246,7 @@ async def test_resume_without_launch_metadata_is_rejected_without_initialization with pytest.raises(ScenarioRunConflictError, match="older run.*cannot be resumed through the GUI"): await service.resume_run_async(scenario_result_id=run_id) prepare.assert_not_called() - after = await asyncio.to_thread( - CentralMemory.get_memory_instance().get_scenario_results, scenario_result_ids=[run_id] - ) + after = await CentralMemory.get_memory_instance().get_scenario_results_async(scenario_result_ids=[run_id]) assert after[0].model_dump() == stored.model_dump() assert service.get_queue_snapshot().active is None assert service.get_queue_snapshot().queued == [] @@ -260,7 +260,7 @@ async def test_resume_failure_preserves_saved_results_async( service, target = resume_environment stored = await _create_failed_run_async(target=target, legacy=False) run_id = str(stored.id) - before = CentralMemory.get_memory_instance().get_attack_results(scenario_result_id=run_id) + before = await CentralMemory.get_memory_instance().get_attack_results_async(scenario_result_id=run_id) target.prompt_sent.clear() if failure == "initialization": with patch.object(_OfflineResumeScenario, "VERSION", 2): @@ -270,8 +270,8 @@ async def test_resume_failure_preserves_saved_results_async( with patch.object(target, "_send_prompt_to_target_async", side_effect=RuntimeError("Still unavailable")): await service.resume_run_async(scenario_result_id=run_id) await _wait_for_idle_async(service) - after = CentralMemory.get_memory_instance().get_scenario_results(scenario_result_ids=[run_id])[0] - results = CentralMemory.get_memory_instance().get_attack_results(scenario_result_id=run_id) + after = (await CentralMemory.get_memory_instance().get_scenario_results_async(scenario_result_ids=[run_id]))[0] + results = await CentralMemory.get_memory_instance().get_attack_results_async(scenario_result_id=run_id) assert after.scenario_run_state == ScenarioRunState.FAILED assert {result.attack_result_id for result in results}.issuperset(result.attack_result_id for result in before) assert target.prompt_sent == [] @@ -299,8 +299,10 @@ async def test_resume_rejects_ineligible_state_before_initializing_async( ) -> None: service, target = resume_environment stored = await _create_failed_run_async(target=target, legacy=False) - CentralMemory.get_memory_instance().update_scenario_run_state( - scenario_result_id=str(stored.id), scenario_run_state=state + ( + await CentralMemory.get_memory_instance().update_scenario_run_state_async( + scenario_result_id=str(stored.id), scenario_run_state=state + ) ) with patch.object(service, "_prepare_run_blocking") as prepare: with pytest.raises(ScenarioRunConflictError, match="cannot resume"): @@ -335,9 +337,7 @@ async def test_resume_rejects_target_drift_without_changing_saved_results_async( with patch.object(target, "get_identifier", return_value=changed_identifier): with pytest.raises(ValueError, match="does not match the current"): await service.resume_run_async(scenario_result_id=run_id) - after = await asyncio.to_thread( - CentralMemory.get_memory_instance().get_scenario_results, scenario_result_ids=[run_id] - ) + after = await CentralMemory.get_memory_instance().get_scenario_results_async(scenario_result_ids=[run_id]) assert after[0].model_dump() == stored.model_dump() assert target.prompt_sent == [] @@ -391,7 +391,7 @@ async def test_fresh_launch_saves_only_nonsecret_resume_inputs_async( ) ) await _wait_for_idle_async(service) - stored = CentralMemory.get_memory_instance().get_scenario_result_header( + stored = await CentralMemory.get_memory_instance().get_scenario_result_header_async( scenario_result_id=response.scenario_result_id ) assert stored is not None @@ -455,8 +455,10 @@ async def test_resume_incomplete_saved_configuration_never_uses_defaults_async( service, target = resume_environment stored = await _create_failed_run_async(target=target, legacy=False) del stored.metadata[_LAUNCH_REQUEST_METADATA_KEY][missing] - CentralMemory.get_memory_instance().update_scenario_metadata( - scenario_result_id=str(stored.id), metadata=stored.metadata + ( + await CentralMemory.get_memory_instance().update_scenario_metadata_async( + scenario_result_id=str(stored.id), metadata=stored.metadata + ) ) with patch.object(service, "_prepare_run_blocking") as prepare: with pytest.raises(ScenarioRunConflictError, match="incomplete"): @@ -482,8 +484,10 @@ async def test_resume_restores_selected_adversarial_target_async( adversarial = MockPromptTarget() TargetRegistry.get_registry_singleton().instances.register(adversarial, name="saved-adversarial") stored.metadata[_LAUNCH_REQUEST_METADATA_KEY]["adversarial_target_name"] = "saved-adversarial" - CentralMemory.get_memory_instance().update_scenario_metadata( - scenario_result_id=str(stored.id), metadata=stored.metadata + ( + await CentralMemory.get_memory_instance().update_scenario_metadata_async( + scenario_result_id=str(stored.id), metadata=stored.metadata + ) ) with patch.object(service, "_enqueue_run_async", wraps=service._enqueue_run_async) as enqueue: await service.resume_run_async(scenario_result_id=str(stored.id)) @@ -517,7 +521,7 @@ async def test_resume_invalid_saved_configuration_is_rejected_before_initializat stored = await _create_failed_run_async(target=target, legacy=False) stored.metadata[_LAUNCH_REQUEST_METADATA_KEY][field] = value with ( - patch.object(service._memory, "get_scenario_result_header", return_value=stored), + patch.object(service._memory, "get_scenario_result_header_async", return_value=stored), patch.object(service, "_prepare_run_blocking") as prepare, ): with pytest.raises(ScenarioRunConflictError, match="incomplete|invalid|empty"): @@ -533,7 +537,7 @@ async def test_resume_missing_canonical_selection_never_uses_current_defaults_as stored = await _create_failed_run_async(target=target, legacy=False) stored.scenario_identifier = stored.scenario_identifier.model_copy(update={missing: None}) with ( - patch.object(service._memory, "get_scenario_result_header", return_value=stored), + patch.object(service._memory, "get_scenario_result_header_async", return_value=stored), patch.object(service, "_prepare_run_blocking") as prepare, ): with pytest.raises(ScenarioRunConflictError, match="missing techniques or datasets"): @@ -595,7 +599,7 @@ async def test_explicit_start_still_resumes_older_runs_async( await _wait_for_idle_async(service) assert response.scenario_result_id == str(stored.id) assert target.prompt_sent == [_SECOND_OBJECTIVE] - detail = await asyncio.to_thread(service.get_run, scenario_result_id=str(stored.id)) + detail = await service.get_run_async(scenario_result_id=str(stored.id)) assert detail is not None assert detail.status == ScenarioRunState.COMPLETED assert detail.error is None @@ -608,8 +612,10 @@ async def test_original_start_route_also_guards_resume_admission_async( ) -> None: service, target = resume_environment stored = await _create_failed_run_async(target=target, legacy=False) - CentralMemory.get_memory_instance().update_scenario_run_state( - scenario_result_id=str(stored.id), scenario_run_state=state + ( + await CentralMemory.get_memory_instance().update_scenario_run_state_async( + scenario_result_id=str(stored.id), scenario_run_state=state + ) ) with patch.object(service, "_prepare_run_blocking") as prepare: with pytest.raises(ScenarioRunConflictError): @@ -639,7 +645,7 @@ async def test_launch_saves_declared_baseline_default_async( request=RunScenarioRequest(scenario_name=_SCENARIO_NAME, target_name=_TARGET_NAME, max_concurrency=1) ) await _wait_for_idle_async(service) - stored = CentralMemory.get_memory_instance().get_scenario_result_header( + stored = await CentralMemory.get_memory_instance().get_scenario_result_header_async( scenario_result_id=response.scenario_result_id ) assert stored is not None diff --git a/tests/unit/backend/test_scenario_run_routes.py b/tests/unit/backend/test_scenario_run_routes.py index 6cf5f6e0b0..70fdc996b2 100644 --- a/tests/unit/backend/test_scenario_run_routes.py +++ b/tests/unit/backend/test_scenario_run_routes.py @@ -20,6 +20,7 @@ from pyrit.backend.models.scenarios import ScenarioRunListResponse from pyrit.backend.routes.scenarios import get_scenario_run_progress, list_scenario_runs from pyrit.backend.services.scenario_run_service import ScenarioRunConflictError, ScenarioRunNotFoundError +from pyrit.memory import MemoryInterface from pyrit.models import ( SCENARIO_RUN_PLAN_METADATA_KEY, AttackOutcome, @@ -223,7 +224,7 @@ def test_resume_errors_are_explicit(self, *, client: TestClient, error: Exceptio def test_older_run_returns_409_without_initialization(self, client: TestClient) -> None: stored = make_scenario_result(scenario_run_state=ScenarioRunState.FAILED, attack_results={}) with patch.object(_svc_mod.CentralMemory, "get_memory_instance") as get_memory: - get_memory.return_value.get_scenario_result_header.return_value = stored + get_memory.return_value.get_scenario_result_header_async = AsyncMock(return_value=stored) service = _svc_mod.ScenarioRunService() with ( patch("pyrit.backend.routes.scenarios.get_scenario_run_service", return_value=service), @@ -244,11 +245,13 @@ def test_list_runs_returns_200(self, client: TestClient) -> None: route_thread: list[int] = [] with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as mock_get: mock_service = MagicMock() - mock_service.list_runs.side_effect = lambda **_: ( - route_thread.append(get_ident()) - or ScenarioRunListResponse( - items=[], - pagination=PaginationInfo(limit=100, has_more=False), + mock_service.list_runs_async = AsyncMock( + side_effect=lambda **_: ( + route_thread.append(get_ident()) + or ScenarioRunListResponse( + items=[], + pagination=PaginationInfo(limit=100, has_more=False), + ) ) ) mock_get.return_value = mock_service @@ -281,9 +284,11 @@ def test_list_runs_returns_multiple_runs(self, client: TestClient) -> None: with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as mock_get: mock_service = MagicMock() - mock_service.list_runs.return_value = ScenarioRunListResponse( - items=runs, - pagination=PaginationInfo(limit=100, has_more=False), + mock_service.list_runs_async = AsyncMock( + return_value=ScenarioRunListResponse( + items=runs, + pagination=PaginationInfo(limit=100, has_more=False), + ) ) mock_get.return_value = mock_service @@ -296,9 +301,11 @@ def test_list_runs_passes_repeated_filters_and_labels(self, client: TestClient) """Test that history query parameters preserve repeated values.""" with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as mock_get: mock_service = MagicMock() - mock_service.list_runs.return_value = ScenarioRunListResponse( - items=[], - pagination=PaginationInfo(limit=10, has_more=False), + mock_service.list_runs_async = AsyncMock( + return_value=ScenarioRunListResponse( + items=[], + pagination=PaginationInfo(limit=10, has_more=False), + ) ) mock_get.return_value = mock_service @@ -311,7 +318,7 @@ def test_list_runs_passes_repeated_filters_and_labels(self, client: TestClient) ) assert response.status_code == status.HTTP_200_OK - mock_service.list_runs.assert_called_once_with( + mock_service.list_runs_async.assert_called_once_with( scenario_names=["first", "second"], statuses=[ScenarioRunState.IN_PROGRESS, ScenarioRunState.FAILED], labels={"operator": ["alice", "bob"], "team": ["safety"]}, @@ -369,7 +376,7 @@ def test_get_run_returns_200(self, client: TestClient) -> None: with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as mock_get: mock_service = MagicMock() mock_service.snapshot_active_run.return_value = MagicMock(error=None) - mock_service.get_run_from_storage.return_value = mock_response + mock_service.get_run_from_storage_async = AsyncMock(return_value=mock_response) mock_get.return_value = mock_service response = client.get("/api/scenarios/runs/test-run-id") @@ -382,7 +389,7 @@ def test_get_run_not_found_returns_404(self, client: TestClient) -> None: with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as mock_get: mock_service = MagicMock() mock_service.snapshot_active_run.return_value = MagicMock(error=None) - mock_service.get_run_from_storage.return_value = None + mock_service.get_run_from_storage_async = AsyncMock(return_value=None) mock_get.return_value = mock_service response = client.get("/api/scenarios/runs/nonexistent") @@ -408,9 +415,9 @@ def test_get_run_with_forward_version_plan_returns_legacy_detail(self, client: T } }, ) - memory = MagicMock() - memory.get_scenario_results.return_value = [db_result] - memory.get_attack_results.return_value = [] + memory = MagicMock(spec=MemoryInterface) + memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) + memory.get_attack_results_async = AsyncMock(return_value=[]) with patch.object(_svc_mod.CentralMemory, "get_memory_instance", return_value=memory): service = _svc_mod.ScenarioRunService() @@ -427,7 +434,9 @@ def test_progress_invalid_cursor_returns_400(self, client: TestClient) -> None: with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as mock_get: mock_service = MagicMock() mock_service.snapshot_active_run.return_value = MagicMock(active_group_ids=()) - mock_service.get_run_progress_from_storage.side_effect = ValueError("Malformed scenario progress cursor.") + mock_service.get_run_progress_from_storage_async = AsyncMock( + side_effect=ValueError("Malformed scenario progress cursor.") + ) mock_get.return_value = mock_service response = client.get("/api/scenarios/runs/test-run-id/progress?since=bad") @@ -473,8 +482,8 @@ def test_progress_returns_compact_plan_response(self, client: TestClient) -> Non active_scenario_result_id="test-run-id", ) ) - mock_service.get_run_progress_from_storage.side_effect = lambda **_: ( - storage_thread.append(get_ident()) or progress + mock_service.get_run_progress_from_storage_async = AsyncMock( + side_effect=lambda **_: storage_thread.append(get_ident()) or progress ) mock_get.return_value = mock_service @@ -482,7 +491,7 @@ def test_progress_returns_compact_plan_response(self, client: TestClient) -> Non assert response.status_code == status.HTTP_200_OK assert response.json()["plan"]["scenario_registry_name"] == "test.scenario" - mock_service.get_run_progress_from_storage.assert_called_once_with( + mock_service.get_run_progress_from_storage_async.assert_called_once_with( scenario_result_id="test-run-id", since=None, limit=25, @@ -490,7 +499,7 @@ def test_progress_returns_compact_plan_response(self, client: TestClient) -> Non queue_position=None, active_scenario_result_id="test-run-id", ) - assert snapshot_thread[0] != storage_thread[0] + assert snapshot_thread[0] == storage_thread[0] async def test_progress_supports_direct_keyword_call(self) -> None: progress = ScenarioRunProgress( @@ -525,7 +534,7 @@ async def test_progress_supports_direct_keyword_call(self) -> None: queue_position=None, active_scenario_result_id="test-run-id", ) - mock_service.get_run_progress_from_storage.return_value = progress + mock_service.get_run_progress_from_storage_async = AsyncMock(return_value=progress) mock_get.return_value = mock_service result = await get_scenario_run_progress( @@ -535,7 +544,7 @@ async def test_progress_supports_direct_keyword_call(self) -> None: ) assert result == progress - mock_service.get_run_progress_from_storage.assert_called_once_with( + mock_service.get_run_progress_from_storage_async.assert_called_once_with( scenario_result_id="test-run-id", since=None, limit=25, @@ -614,7 +623,7 @@ def test_get_results_returns_200(self, client: TestClient) -> None: with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as mock_get: mock_service = MagicMock() - mock_service.get_run_results.return_value = scenario_result + mock_service.get_run_results_async = AsyncMock(return_value=scenario_result) mock_get.return_value = mock_service response = client.get("/api/scenarios/runs/test-run-id/results") @@ -628,7 +637,7 @@ def test_get_results_not_found_returns_404(self, client: TestClient) -> None: """Test that getting results of a non-existent run returns 404.""" with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as mock_get: mock_service = MagicMock() - mock_service.get_run_results.return_value = None + mock_service.get_run_results_async = AsyncMock(return_value=None) mock_get.return_value = mock_service response = client.get("/api/scenarios/runs/nonexistent/results") @@ -639,8 +648,8 @@ def test_get_results_not_completed_returns_409(self, client: TestClient) -> None """Test that getting results of a non-completed run returns 409.""" with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as mock_get: mock_service = MagicMock() - mock_service.get_run_results.side_effect = ValueError( - "Results are only available for completed runs. Current status: 'running'." + mock_service.get_run_results_async = AsyncMock( + side_effect=ValueError("Results are only available for completed runs. Current status: 'running'.") ) mock_get.return_value = mock_service diff --git a/tests/unit/backend/test_scenario_run_service.py b/tests/unit/backend/test_scenario_run_service.py index add6b2ca9f..cb12bf8f6a 100644 --- a/tests/unit/backend/test_scenario_run_service.py +++ b/tests/unit/backend/test_scenario_run_service.py @@ -218,12 +218,12 @@ def _make_history_record( def mock_memory(): """Patch CentralMemory.get_memory_instance to return a mock.""" mock = MagicMock(spec=SQLiteMemory) - mock.get_scenario_results.return_value = [] - mock.get_scenario_run_history_page.return_value = ([], {}, False) - mock.get_scenario_history_aggregates.return_value = {} + mock.get_scenario_results_async = AsyncMock(return_value=[]) + mock.get_scenario_run_history_page_async = AsyncMock(return_value=([], {}, False)) + mock.get_scenario_history_aggregates_async = AsyncMock(return_value={}) # Default: no error AttackResults linked to any scenario. Tests that exercise # the error fallback path explicitly set get_attack_results.return_value. - mock.get_attack_results.return_value = [] + mock.get_attack_results_async = AsyncMock(return_value=[]) with patch(_MEMORY_PATCH, return_value=mock): yield mock @@ -254,7 +254,7 @@ def mock_all_registries(mock_memory): # By default, return a matching DB result for get_run / list_runs queries db_result = _make_db_scenario_result() - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) with ( patch(f"{_REGISTRY_PATCH_BASE}.ScenarioRegistry.get_registry_singleton", return_value=mock_sr), @@ -350,10 +350,10 @@ def update_state(*, scenario_result_id: str, scenario_run_state: ScenarioRunStat mock_all_registries["scenario_class"].side_effect = introspect mock_all_registries["scenario_registry"].create_and_initialize_async.side_effect = initialize_async memory = mock_all_registries["memory"] - memory.get_scenario_results.side_effect = get_results - memory.update_scenario_run_state.side_effect = update_state - memory.try_update_scenario_run_state.side_effect = update_state - memory.update_scenario_run_state_and_metadata_fields.side_effect = update_state + memory.get_scenario_results_async = AsyncMock(side_effect=get_results) + memory.update_scenario_run_state_async = AsyncMock(side_effect=update_state) + memory.try_update_scenario_run_state_async = AsyncMock(side_effect=update_state) + memory.update_scenario_run_state_and_metadata_fields_async = AsyncMock(side_effect=update_state) try: for name in ("first", "second", None, "second"): request = _make_request(max_dataset_size=1) @@ -476,7 +476,7 @@ async def test_start_run_returns_running_status(self, mock_all_registries) -> No assert response.scenario_name == "foundry.red_team_agent" assert "sr-uuid-1" not in service._terminal_errors assert response.error is None - metadata_call = mock_memory.update_scenario_run_state_and_metadata_fields.call_args + metadata_call = mock_memory.update_scenario_run_state_and_metadata_fields_async.call_args assert metadata_call.kwargs["scenario_result_id"] == "sr-uuid-1" assert metadata_call.kwargs["scenario_run_state"] == ScenarioRunState.IN_PROGRESS persisted_start = datetime.fromisoformat( @@ -487,8 +487,8 @@ async def test_start_run_returns_running_status(self, mock_all_registries) -> No metadata_call.kwargs["metadata_fields"][_svc_mod._SCHEDULER_METADATA_KEY] == _svc_mod._SCHEDULER_METADATA_VALUE ) - mock_memory.update_scenario_metadata_fields.assert_not_called() - mock_memory.update_scenario_run_state.assert_not_called() + mock_memory.update_scenario_metadata_fields_async.assert_not_called() + mock_memory.update_scenario_run_state_async.assert_not_called() async def test_start_run_invalid_scenario_raises_value_error(self, mock_memory) -> None: """Test that an invalid scenario name raises ValueError immediately.""" @@ -705,10 +705,10 @@ def _update_state(*, scenario_result_id: str, scenario_run_state: ScenarioRunSta records[scenario_result_id].scenario_run_state = scenario_run_state mock_sr.create_and_initialize_async = AsyncMock(side_effect=_create_scenario) - mock_memory.get_scenario_results.side_effect = _get_results - mock_memory.update_scenario_run_state.side_effect = _update_state - mock_memory.try_update_scenario_run_state.side_effect = _update_state - mock_memory.update_scenario_run_state_and_metadata_fields.side_effect = _update_state + mock_memory.get_scenario_results_async = AsyncMock(side_effect=_get_results) + mock_memory.update_scenario_run_state_async = AsyncMock(side_effect=_update_state) + mock_memory.try_update_scenario_run_state_async = AsyncMock(side_effect=_update_state) + mock_memory.update_scenario_run_state_and_metadata_fields_async = AsyncMock(side_effect=_update_state) active_response = await service.start_run_async(request=_make_request()) await asyncio.wait_for(active_started.wait(), timeout=1) @@ -727,7 +727,7 @@ def _update_state(*, scenario_result_id: str, scenario_run_state: ScenarioRunSta assert queued_response.active_scenario_result_id == "run-1" queued_transition = next( call - for call in mock_memory.update_scenario_run_state_and_metadata_fields.call_args_list + for call in mock_memory.update_scenario_run_state_and_metadata_fields_async.call_args_list if call.kwargs["scenario_result_id"] == "run-2" and call.kwargs["scenario_run_state"] == ScenarioRunState.QUEUED ) @@ -1009,10 +1009,10 @@ def _update_state(*, scenario_result_id: str, scenario_run_state: ScenarioRunSta records[scenario_result_id].scenario_run_state = scenario_run_state mock_sr.create_and_initialize_async = AsyncMock(side_effect=_create_scenario) - mock_memory.get_scenario_results.side_effect = _get_results - mock_memory.update_scenario_run_state.side_effect = _update_state - mock_memory.try_update_scenario_run_state.side_effect = _update_state - mock_memory.update_scenario_run_state_and_metadata_fields.side_effect = _update_state + mock_memory.get_scenario_results_async = AsyncMock(side_effect=_get_results) + mock_memory.update_scenario_run_state_async = AsyncMock(side_effect=_update_state) + mock_memory.try_update_scenario_run_state_async = AsyncMock(side_effect=_update_state) + mock_memory.update_scenario_run_state_and_metadata_fields_async = AsyncMock(side_effect=_update_state) responses = await asyncio.gather(*(service.start_run_async(request=_make_request()) for _ in range(4))) @@ -1070,11 +1070,11 @@ async def test_start_run_passes_scenario_result_id_for_resume(self, mock_all_reg mock_sr = mock_all_registries["scenario_registry"] mock_all_registries["scenario_instance"]._scenario_result_id = "existing-result-uuid" - mock_all_registries["memory"].get_scenario_results.return_value = [ - _make_db_scenario_result(result_id="existing-result-uuid") - ] - mock_all_registries["memory"].get_scenario_result_header.return_value = _make_db_scenario_result( - result_id="existing-result-uuid", run_state=ScenarioRunState.FAILED + mock_all_registries["memory"].get_scenario_results_async = AsyncMock( + return_value=[_make_db_scenario_result(result_id="existing-result-uuid")] + ) + mock_all_registries["memory"].get_scenario_result_header_async = AsyncMock( + return_value=_make_db_scenario_result(result_id="existing-result-uuid", run_state=ScenarioRunState.FAILED) ) response = await service.start_run_async(request=_make_request(scenario_result_id="existing-result-uuid")) @@ -1151,7 +1151,7 @@ def _slow_prepare(*, request: Any) -> Any: return _svc_mod._PreparedRun(scenario=scenario_instance) with patch.object(service, "_prepare_run_blocking", _slow_prepare): - with patch.object(service._memory, "try_update_scenario_run_state") as update_state: + with patch.object(service._memory, "try_update_scenario_run_state_async") as update_state: task = asyncio.create_task(service.start_run_async(request=_make_request())) await asyncio.sleep(0.1) task.cancel() @@ -1187,7 +1187,7 @@ async def _complete_then_cancel(awaitable): with patch.object(service, "_prepare_run_blocking", _instant_prepare): with patch("asyncio.shield", _complete_then_cancel): - with patch.object(service._memory, "try_update_scenario_run_state") as update_state: + with patch.object(service._memory, "try_update_scenario_run_state_async") as update_state: with pytest.raises(asyncio.CancelledError): await service.start_run_async(request=_make_request()) @@ -1209,7 +1209,7 @@ def _prepare(*, request: Any) -> Any: return _svc_mod._PreparedRun(scenario=scenario_instance) cancelled = _make_db_scenario_result(result_id="cancelled-during-init", run_state=ScenarioRunState.CANCELLED) - mock_all_registries["memory"].get_scenario_results.return_value = [cancelled] + mock_all_registries["memory"].get_scenario_results_async = AsyncMock(return_value=[cancelled]) with patch.object(service, "_prepare_run_blocking", _prepare): with patch.object(service, "_execute_run_async") as execute: response = await service.start_run_async(request=_make_request()) @@ -1228,8 +1228,8 @@ def _prepare(*, request: Any) -> Any: return _svc_mod._PreparedRun(scenario=scenario_instance) cancelled = _make_db_scenario_result(result_id="resumed-cancelled", run_state=ScenarioRunState.CANCELLED) - mock_all_registries["memory"].get_scenario_results.return_value = [cancelled] - mock_all_registries["memory"].get_scenario_result_header.return_value = cancelled + mock_all_registries["memory"].get_scenario_results_async = AsyncMock(return_value=[cancelled]) + mock_all_registries["memory"].get_scenario_result_header_async = AsyncMock(return_value=cancelled) with patch.object(service, "_prepare_run_blocking", _prepare): with patch.object(service, "_execute_run_async") as execute: @@ -1254,9 +1254,9 @@ def _prepare(*, request: Any) -> Any: cancelled = _make_db_scenario_result(result_id="cancelled-mid-init", run_state=ScenarioRunState.CANCELLED) failed = _make_db_scenario_result(result_id="cancelled-mid-init", run_state=ScenarioRunState.FAILED) - mock_all_registries["memory"].get_scenario_results.return_value = [cancelled] + mock_all_registries["memory"].get_scenario_results_async = AsyncMock(return_value=[cancelled]) # The pre-preparation read sees a live run; the cancel lands while the worker prepares. - mock_all_registries["memory"].get_scenario_result_header.return_value = failed + mock_all_registries["memory"].get_scenario_result_header_async = AsyncMock(return_value=failed) with patch.object(service, "_prepare_run_blocking", _prepare): with patch.object(service, "_execute_run_async") as execute: @@ -1278,7 +1278,7 @@ def _prepare(*, request: Any) -> Any: with patch.object(service, "_execute_run_async"): await service.start_run_async(request=_make_request()) - mock_all_registries["memory"].get_scenario_result_header.assert_not_called() + mock_all_registries["memory"].get_scenario_result_header_async.assert_not_called() async def test_start_run_failure_does_not_report_a_cancellation(self, mock_all_registries, caplog) -> None: service = ScenarioRunService() @@ -1308,7 +1308,9 @@ async def _complete_then_cancel(awaitable): with patch.object(service, "_prepare_run_blocking", _instant_prepare): with patch("asyncio.shield", _complete_then_cancel): - with patch.object(service, "_release_abandoned_prepare", side_effect=RuntimeError("cleanup exploded")): + with patch.object( + service, "_release_abandoned_prepare_async", side_effect=RuntimeError("cleanup exploded") + ): with pytest.raises(asyncio.CancelledError): await service.start_run_async(request=_make_request()) @@ -1383,7 +1385,7 @@ async def _leaky_prepare(*, request: Any) -> Any: with patch.object(service, "_prepare_run_async", _leaky_prepare): with patch.object(ScenarioRunService, "_INITIALIZATION_DRAIN_TIMEOUT", 0.05): - with patch.object(service._memory, "try_update_scenario_run_state") as update_state: + with patch.object(service._memory, "try_update_scenario_run_state_async") as update_state: with pytest.raises(RuntimeError, match="left background tasks"): service._prepare_run_blocking(request=_make_request()) @@ -1410,7 +1412,9 @@ async def _leaky_prepare(*, request: Any) -> Any: with patch.object(service, "_prepare_run_async", _leaky_prepare): with patch.object(ScenarioRunService, "_INITIALIZATION_DRAIN_TIMEOUT", 0.05): - with patch.object(service._memory, "try_update_scenario_run_state", side_effect=ValueError("gone")): + with patch.object( + service._memory, "try_update_scenario_run_state_async", side_effect=ValueError("gone") + ): with pytest.raises(RuntimeError, match="left background tasks"): service._prepare_run_blocking(request=_make_request()) @@ -1559,7 +1563,7 @@ async def test_start_run_rejects_missing_result_id(self, mock_all_registries) -> async def test_start_run_rejects_unpersisted_initialized_scenario(self, mock_all_registries) -> None: service = ScenarioRunService() - mock_all_registries["memory"].get_scenario_results.return_value = [] + mock_all_registries["memory"].get_scenario_results_async = AsyncMock(return_value=[]) with pytest.raises(RuntimeError, match="was not persisted during initialization"): await service.start_run_async(request=_make_request()) @@ -1568,7 +1572,7 @@ async def test_start_run_cleans_up_when_response_lookup_fails(self, mock_all_reg """A response failure must not leave an active-task entry.""" service = ScenarioRunService() - with patch.object(service, "_build_response", return_value=None): + with patch.object(service, "_build_response_async", return_value=None): with pytest.raises(RuntimeError, match="not found in the database"): await service.start_run_async(request=_make_request()) @@ -1590,29 +1594,29 @@ async def _run_async() -> None: class TestScenarioRunServiceGetRun: - """Tests for ScenarioRunService.get_run.""" + "Tests for ScenarioRunService.get_run_async." - def test_get_run_returns_none_for_unknown_id(self, mock_memory) -> None: - """Test that get_run returns None for non-existent run.""" - mock_memory.get_scenario_results.return_value = [] + async def test_get_run_returns_none_for_unknown_id(self, mock_memory) -> None: + "Test that get_run_async returns None for non-existent run." + mock_memory.get_scenario_results_async = AsyncMock(return_value=[]) service = ScenarioRunService() - result = service.get_run(scenario_result_id="nonexistent-id") + result = await service.get_run_async(scenario_result_id="nonexistent-id") assert result is None - def test_get_run_returns_existing_run(self, mock_memory) -> None: - """Test that get_run returns a run from the database.""" + async def test_get_run_returns_existing_run(self, mock_memory) -> None: + "Test that get_run_async returns a run from the database." db_result = _make_db_scenario_result(result_id="sr-123", run_state=ScenarioRunState.IN_PROGRESS) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() - fetched = service.get_run(scenario_result_id="sr-123") + fetched = await service.get_run_async(scenario_result_id="sr-123") assert fetched is not None assert fetched.scenario_result_id == "sr-123" assert fetched.scenario_name == "foundry.red_team_agent" assert fetched.status == ScenarioRunState.IN_PROGRESS - def test_get_run_maps_typed_scenario_result_state(self, mock_memory) -> None: + async def test_get_run_maps_typed_scenario_result_state(self, mock_memory) -> None: """Test the service boundary with a real ScenarioResult domain model.""" db_result = make_scenario_result( scenario_name="foundry.red_team_agent", @@ -1621,10 +1625,10 @@ def test_get_run_maps_typed_scenario_result_state(self, mock_memory) -> None: error_message="Scenario failed", error_type="RuntimeError", ) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() - fetched = service.get_run(scenario_result_id=str(db_result.id)) + fetched = await service.get_run_async(scenario_result_id=str(db_result.id)) assert fetched is not None assert fetched.status is ScenarioRunState.FAILED @@ -1665,7 +1669,7 @@ def test_get_run_maps_typed_scenario_result_state(self, mock_memory) -> None: ], ids=["valid", "legacy", "forward-version", "malformed"], ) - def test_get_run_detail_preserves_readability_across_plan_metadata( + async def test_get_run_detail_preserves_readability_across_plan_metadata( self, mock_memory, caplog: pytest.LogCaptureFixture, @@ -1688,9 +1692,9 @@ def test_get_run_detail_preserves_readability_across_plan_metadata( attack_results={"legacy attack": [attack_result]}, metadata=metadata, ) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) - fetched = ScenarioRunService().get_run(scenario_result_id=str(db_result.id)) + fetched = await ScenarioRunService().get_run_async(scenario_result_id=str(db_result.id)) assert fetched is not None assert fetched.scenario_registry_name == expected_registry_name @@ -1700,7 +1704,7 @@ def test_get_run_detail_preserves_readability_across_plan_metadata( assert fetched.techniques_used == (["Attack"] if expected_planned_total else ["legacy attack"]) assert ("using legacy run detail fields" in caplog.text) is expected_warning - def test_get_run_detail_techniques_used_prefers_technique_name_over_display_group(self, mock_memory) -> None: + async def test_get_run_detail_techniques_used_prefers_technique_name_over_display_group(self, mock_memory) -> None: """A goal-based display_group must not stand in for the technique identity.""" plan = ScenarioRunPlan( scenario_registry_name="garak.prompt_inject", @@ -1727,15 +1731,15 @@ def test_get_run_detail_techniques_used_prefers_technique_name_over_display_grou attack_results={}, metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan}, ) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async.return_value = [db_result] - fetched = ScenarioRunService().get_run(scenario_result_id=str(db_result.id)) + fetched = await ScenarioRunService().get_run_async(scenario_result_id=str(db_result.id)) assert fetched is not None assert fetched.techniques_used == ["ignore_print"] @pytest.mark.parametrize("run_state", list(ScenarioRunState)) - def test_get_run_only_falls_back_to_persisted_error_for_failed_state( + async def test_get_run_only_falls_back_to_persisted_error_for_failed_state( self, *, mock_memory: MagicMock, run_state: ScenarioRunState ) -> None: error_ar = AttackResult( @@ -1750,11 +1754,11 @@ def test_get_run_only_falls_back_to_persisted_error_for_failed_state( attack_results={"direct": [error_ar]}, ) run_id = str(db_result.id) - mock_memory.get_scenario_results.return_value = [db_result] - mock_memory.get_attack_results.return_value = [error_ar] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) + mock_memory.get_attack_results_async = AsyncMock(return_value=[error_ar]) service = ScenarioRunService() - fetched = service.get_run(scenario_result_id=run_id) + fetched = await service.get_run_async(scenario_result_id=run_id) assert fetched is not None assert fetched.status == run_state @@ -1763,48 +1767,48 @@ def test_get_run_only_falls_back_to_persisted_error_for_failed_state( if run_state == ScenarioRunState.FAILED: assert fetched.error == "Connection refused" assert fetched.error_type == "ConnectionError" - mock_memory.get_attack_results.assert_called_once_with( + mock_memory.get_attack_results_async.assert_called_once_with( scenario_result_id=run_id, outcome=AttackOutcome.ERROR, ) else: assert fetched.error is None assert fetched.error_type is None - mock_memory.get_attack_results.assert_not_called() + mock_memory.get_attack_results_async.assert_not_called() class TestScenarioRunServiceListRuns: - """Tests for ScenarioRunService.list_runs.""" + "Tests for ScenarioRunService.list_runs_async." - def test_list_runs_empty(self, mock_memory) -> None: - """Test that list_runs returns empty list when DB has no results.""" - mock_memory.get_scenario_run_history_page.return_value = ([], {}, False) + async def test_list_runs_empty(self, mock_memory) -> None: + "Test that list_runs_async returns empty list when DB has no results." + mock_memory.get_scenario_run_history_page_async = AsyncMock(return_value=([], {}, False)) service = ScenarioRunService() - result = service.list_runs() + result = await service.list_runs_async() assert result.items == [] assert result.pagination.has_more is False - mock_memory.get_scenario_results.assert_not_called() + mock_memory.get_scenario_results_async.assert_not_called() - def test_list_runs_returns_all_runs(self, mock_memory) -> None: - """Test that list_runs returns all runs from the database.""" + async def test_list_runs_returns_all_runs(self, mock_memory) -> None: + "Test that list_runs_async returns all runs from the database." records = [ _make_history_record(result_id="sr-1", run_state=ScenarioRunState.COMPLETED), _make_history_record(result_id="sr-2", run_state=ScenarioRunState.IN_PROGRESS), ] - mock_memory.get_scenario_run_history_page.return_value = (records, {}, False) + mock_memory.get_scenario_run_history_page_async = AsyncMock(return_value=(records, {}, False)) service = ScenarioRunService() - result = service.list_runs() + result = await service.list_runs_async() assert len(result.items) == 2 assert [item.scenario_result_id for item in result.items] == ["sr-1", "sr-2"] - mock_memory.get_scenario_results.assert_not_called() + mock_memory.get_scenario_results_async.assert_not_called() - def test_list_runs_passes_custom_limit(self, mock_memory) -> None: - """Test that list_runs passes a custom limit to the memory query.""" - mock_memory.get_scenario_run_history_page.return_value = ([], {}, False) + async def test_list_runs_passes_custom_limit(self, mock_memory) -> None: + "Test that list_runs_async passes a custom limit to the memory query." + mock_memory.get_scenario_run_history_page_async = AsyncMock(return_value=([], {}, False)) service = ScenarioRunService() - service.list_runs(limit=10) - mock_memory.get_scenario_run_history_page.assert_called_once_with( + (await service.list_runs_async(limit=10)) + mock_memory.get_scenario_run_history_page_async.assert_called_once_with( scenario_names=[], statuses=[], labels=None, @@ -1812,21 +1816,21 @@ def test_list_runs_passes_custom_limit(self, mock_memory) -> None: limit=10, ) - def test_history_cursor_is_filter_bound_and_invalid_values_restart_pagination(self, mock_memory) -> None: + async def test_history_cursor_is_filter_bound_and_invalid_values_restart_pagination(self, mock_memory) -> None: record = _make_history_record(result_id=str(uuid.uuid4()), run_state=ScenarioRunState.COMPLETED) - mock_memory.get_scenario_run_history_page.return_value = ([record], {}, True) + mock_memory.get_scenario_run_history_page_async = AsyncMock(return_value=([record], {}, True)) service = ScenarioRunService() - first_page = service.list_runs(scenario_names=["first"], labels={"operator": ["alice", "bob"]}) + first_page = await service.list_runs_async(scenario_names=["first"], labels={"operator": ["alice", "bob"]}) assert first_page.pagination.has_more is True assert first_page.pagination.next_cursor is not None - service.list_runs(scenario_names=["second"], cursor=first_page.pagination.next_cursor) - assert mock_memory.get_scenario_run_history_page.call_args.kwargs["cursor"] is None - service.list_runs(cursor="not-a-cursor") - assert mock_memory.get_scenario_run_history_page.call_args.kwargs["cursor"] is None + (await service.list_runs_async(scenario_names=["second"], cursor=first_page.pagination.next_cursor)) + assert mock_memory.get_scenario_run_history_page_async.call_args.kwargs["cursor"] is None + (await service.list_runs_async(cursor="not-a-cursor")) + assert mock_memory.get_scenario_run_history_page_async.call_args.kwargs["cursor"] is None - def test_history_uses_plan_and_latest_non_error_attempt_per_unit(self, mock_memory) -> None: + async def test_history_uses_plan_and_latest_non_error_attempt_per_unit(self, mock_memory) -> None: record = _make_history_record(result_id="sr-aggregate", run_state=ScenarioRunState.COMPLETED) plan = ScenarioRunPlan( scenario_registry_name="registered.scenario", @@ -1851,24 +1855,26 @@ def test_history_uses_plan_and_latest_non_error_attempt_per_unit(self, mock_memo plan_seed_id_map=[{"id": seed.id, "objective_sha256": seed.objective_sha256} for seed in plan.seed_groups], ) timestamp = datetime(2026, 8, 7, tzinfo=UTC) - mock_memory.get_scenario_run_history_page.return_value = ( - [record], - { - record.scenario_result_id: ScenarioHistoryAggregate( - scenario_result_id=record.scenario_result_id, - unit_count=1, - completed_units=1, - successful_units=1, - error_attempts=1, - total_retries=3, - latest_attempt_timestamp=timestamp, - atomic_attack_names=("attack",), - ) - }, - False, + mock_memory.get_scenario_run_history_page_async = AsyncMock( + return_value=( + [record], + { + record.scenario_result_id: ScenarioHistoryAggregate( + scenario_result_id=record.scenario_result_id, + unit_count=1, + completed_units=1, + successful_units=1, + error_attempts=1, + total_retries=3, + latest_attempt_timestamp=timestamp, + atomic_attack_names=("attack",), + ) + }, + False, + ) ) - summary = ScenarioRunService().list_runs().items[0] + summary = (await ScenarioRunService().list_runs_async()).items[0] assert summary.total_attacks == 2 assert summary.completed_attacks == 1 @@ -1879,7 +1885,7 @@ def test_history_uses_plan_and_latest_non_error_attempt_per_unit(self, mock_memo assert summary.attack_details_available is False assert summary.updated_at >= timestamp - def test_history_metadata_is_allow_listed_and_secret_free(self, mock_memory) -> None: + async def test_history_metadata_is_allow_listed_and_secret_free(self, mock_memory) -> None: scenario_result = make_scenario_result( scenario_name="SafeScenario", objective_target_identifier=ComponentIdentifier( @@ -1904,9 +1910,9 @@ def test_history_metadata_is_allow_listed_and_secret_free(self, mock_memory) -> scenario_name=scenario_result.scenario_name, scenario_identifier=scenario_result.scenario_identifier.model_dump(mode="json"), ) - mock_memory.get_scenario_run_history_page.return_value = ([record], {}, False) + mock_memory.get_scenario_run_history_page_async = AsyncMock(return_value=([record], {}, False)) - summary = ScenarioRunService().list_runs().items[0] + summary = (await ScenarioRunService().list_runs_async()).items[0] serialized = summary.model_dump_json() assert summary.target is not None @@ -1924,7 +1930,7 @@ def test_history_metadata_is_allow_listed_and_secret_free(self, mock_memory) -> assert "/v1" not in serialized assert "password" not in serialized - def test_history_falls_back_honestly_for_incomplete_persisted_plan(self, mock_memory) -> None: + async def test_history_falls_back_honestly_for_incomplete_persisted_plan(self, mock_memory) -> None: record = _make_history_record(result_id="sr-legacy", run_state=ScenarioRunState.COMPLETED) record = replace( record, @@ -1932,15 +1938,15 @@ def test_history_falls_back_honestly_for_incomplete_persisted_plan(self, mock_me plan_atomic_groups="{}", plan_seed_id_map="[]", ) - mock_memory.get_scenario_run_history_page.return_value = ([record], {}, False) + mock_memory.get_scenario_run_history_page_async = AsyncMock(return_value=([record], {}, False)) - summary = ScenarioRunService().list_runs().items[0] + summary = (await ScenarioRunService().list_runs_async()).items[0] assert summary.planned_total_available is False assert summary.total_attacks is None assert summary.completed_attacks == 0 - def test_history_discards_duplicate_plan_groups_before_legacy_fallback(self, mock_memory) -> None: + async def test_history_discards_duplicate_plan_groups_before_legacy_fallback(self, mock_memory) -> None: record = _make_history_record(result_id="sr-duplicate-plan", run_state=ScenarioRunState.COMPLETED) group = ScenarioRunPlanAtomicGroup( id="duplicate", @@ -1954,14 +1960,14 @@ def test_history_discards_duplicate_plan_groups_before_legacy_fallback(self, moc plan_atomic_groups=[group, group], plan_seed_id_map=[{"id": "seed-1", "objective_sha256": "hash-1"}], ) - mock_memory.get_scenario_run_history_page.return_value = ([record], {}, False) + mock_memory.get_scenario_run_history_page_async = AsyncMock(return_value=([record], {}, False)) - summary = ScenarioRunService().list_runs().items[0] + summary = (await ScenarioRunService().list_runs_async()).items[0] assert summary.planned_total_available is False assert summary.total_attacks is None - def test_history_scopes_duplicate_objective_hashes_to_atomic_groups(self, mock_memory) -> None: + async def test_history_scopes_duplicate_objective_hashes_to_atomic_groups(self, mock_memory) -> None: record = _make_history_record(result_id="sr-duplicate-objective", run_state=ScenarioRunState.COMPLETED) groups = [ ScenarioRunPlanAtomicGroup( @@ -1982,32 +1988,34 @@ def test_history_scopes_duplicate_objective_hashes_to_atomic_groups(self, mock_m ], ) timestamp = datetime(2026, 8, 7, tzinfo=UTC) - mock_memory.get_scenario_run_history_page.return_value = ( - [record], - { - record.scenario_result_id: ScenarioHistoryAggregate( - scenario_result_id=record.scenario_result_id, - unit_count=2, - completed_units=2, - successful_units=2, - error_attempts=0, - total_retries=0, - latest_attempt_timestamp=timestamp, - atomic_attack_names=("attack-1", "attack-2"), - ) - }, - False, + mock_memory.get_scenario_run_history_page_async = AsyncMock( + return_value=( + [record], + { + record.scenario_result_id: ScenarioHistoryAggregate( + scenario_result_id=record.scenario_result_id, + unit_count=2, + completed_units=2, + successful_units=2, + error_attempts=0, + total_retries=0, + latest_attempt_timestamp=timestamp, + atomic_attack_names=("attack-1", "attack-2"), + ) + }, + False, + ) ) - summary = ScenarioRunService().list_runs().items[0] + summary = (await ScenarioRunService().list_runs_async()).items[0] assert summary.planned_total_available is True assert summary.total_attacks == 2 assert summary.completed_attacks == 2 assert summary.successful_attacks == 2 - mock_memory.get_scenario_history_aggregates.assert_not_called() + mock_memory.get_scenario_history_aggregates_async.assert_not_called() - def test_list_runs_techniques_used_prefers_technique_name_over_display_group(self, mock_memory) -> None: + async def test_list_runs_techniques_used_prefers_technique_name_over_display_group(self, mock_memory) -> None: """A goal-based display_group must not stand in for the technique identity.""" record = _make_history_record(result_id="sr-goal-display-group", run_state=ScenarioRunState.COMPLETED) group = ScenarioRunPlanAtomicGroup( @@ -2023,9 +2031,9 @@ def test_list_runs_techniques_used_prefers_technique_name_over_display_group(sel plan_atomic_groups=[group], plan_seed_id_map=[{"id": "seed-1", "objective_sha256": "hash-1"}], ) - mock_memory.get_scenario_run_history_page.return_value = ([record], {}, False) + mock_memory.get_scenario_run_history_page_async.return_value = ([record], {}, False) - summary = ScenarioRunService().list_runs().items[0] + summary = (await ScenarioRunService().list_runs_async()).items[0] assert summary.techniques_used == ["ignore_print"] @@ -2039,7 +2047,7 @@ def test_list_runs_techniques_used_prefers_technique_name_over_display_group(sel ], ids=["no-registry-name", "removed-scenario", "unknown-technique", "persisted-technique"], ) - def test_list_runs_preserves_technique_fallbacks( + async def test_list_runs_preserves_technique_fallbacks( self, *, mock_memory: MagicMock, @@ -2064,18 +2072,18 @@ def test_list_runs_preserves_technique_fallbacks( plan_atomic_groups=[group], plan_seed_id_map=[{"id": "seed-1", "objective_sha256": "hash-1"}], ) - mock_memory.get_scenario_run_history_page.return_value = ([record], {}, False) + mock_memory.get_scenario_run_history_page_async.return_value = ([record], {}, False) service = ScenarioRunService() summaries = {name: ScenarioTechniqueSummary(name=name) for name in known_names} with patch.object(service, "_get_scenario_technique_summaries", return_value=summaries) as lookup: - summary = service.list_runs().items[0] + summary = (await service.list_runs_async()).items[0] assert summary.techniques_used == [expected_name] if scenario_registry_name is None or technique_name is not None: lookup.assert_not_called() - def test_history_falls_back_for_duplicate_objective_hashes_within_one_group(self, mock_memory) -> None: + async def test_history_falls_back_for_duplicate_objective_hashes_within_one_group(self, mock_memory) -> None: record = _make_history_record(result_id="sr-ambiguous-objective", run_state=ScenarioRunState.COMPLETED) group = ScenarioRunPlanAtomicGroup( id="group-1", @@ -2092,38 +2100,46 @@ def test_history_falls_back_for_duplicate_objective_hashes_within_one_group(self {"id": "seed-2", "objective_sha256": "shared-hash"}, ], ) - mock_memory.get_scenario_run_history_page.return_value = ([record], {}, False) + mock_memory.get_scenario_run_history_page_async = AsyncMock(return_value=([record], {}, False)) - summary = ScenarioRunService().list_runs().items[0] + summary = (await ScenarioRunService().list_runs_async()).items[0] assert summary.planned_total_available is False assert summary.total_attacks is None - def test_history_requeries_legacy_aggregates_when_plan_is_rejected(self, mock_memory) -> None: + async def test_history_requeries_legacy_aggregates_when_plan_is_rejected(self, mock_memory) -> None: """A plan the service cannot trust forces a plan-free aggregate re-query.""" record = _make_history_record(result_id="sr-rejected-plan", run_state=ScenarioRunState.COMPLETED) record = replace(record, plan_atomic_groups="{}", plan_seed_id_map="[]") - mock_memory.get_scenario_run_history_page.return_value = ( - [record], - {record.scenario_result_id: ScenarioHistoryAggregate.empty(scenario_result_id=record.scenario_result_id)}, - False, - ) - mock_memory.get_scenario_history_aggregates.return_value = { - record.scenario_result_id: ScenarioHistoryAggregate( - scenario_result_id=record.scenario_result_id, - unit_count=3, - completed_units=2, - successful_units=1, - error_attempts=1, - total_retries=4, - latest_attempt_timestamp=datetime(2026, 8, 7, tzinfo=UTC), - atomic_attack_names=("attack",), + mock_memory.get_scenario_run_history_page_async = AsyncMock( + return_value=( + [record], + { + record.scenario_result_id: ScenarioHistoryAggregate.empty( + scenario_result_id=record.scenario_result_id + ) + }, + False, ) - } + ) + mock_memory.get_scenario_history_aggregates_async = AsyncMock( + return_value={ + record.scenario_result_id: ScenarioHistoryAggregate( + scenario_result_id=record.scenario_result_id, + unit_count=3, + completed_units=2, + successful_units=1, + error_attempts=1, + total_retries=4, + latest_attempt_timestamp=datetime(2026, 8, 7, tzinfo=UTC), + atomic_attack_names=("attack",), + ) + } + ) - summary = ScenarioRunService().list_runs().items[0] + summary = (await ScenarioRunService().list_runs_async()).items[0] - mock_memory.get_scenario_history_aggregates.assert_called_once_with( + mock_memory.get_scenario_history_aggregates_async.assert_called_once_with( scenario_result_ids=[record.scenario_result_id] ) assert summary.planned_total_available is False @@ -2133,19 +2149,19 @@ def test_history_requeries_legacy_aggregates_when_plan_is_rejected(self, mock_me assert summary.total_retries == 4 assert summary.techniques_used == ["attack"] - def test_list_runs_reports_unknown_total_without_plan(self, mock_memory) -> None: + async def test_list_runs_reports_unknown_total_without_plan(self, mock_memory) -> None: """Test that legacy runs do not report a false zero planned total.""" record = _make_history_record(result_id="sr-no-plan", run_state=ScenarioRunState.COMPLETED) - mock_memory.get_scenario_run_history_page.return_value = ([record], {}, False) + mock_memory.get_scenario_run_history_page_async = AsyncMock(return_value=([record], {}, False)) - result = ScenarioRunService().list_runs() + result = await ScenarioRunService().list_runs_async() assert result.items[0].total_attacks is None @pytest.mark.usefixtures("patch_central_database") @pytest.mark.parametrize("omit_technique_name", [True, False], ids=["omitted", "null"]) -def test_legacy_plan_techniques_agree_across_projections( +async def test_legacy_plan_techniques_agree_across_projections( *, sqlite_instance: SQLiteMemory, omit_technique_name: bool ) -> None: techniques = ["ignore_print", "ignore_print_upper"] @@ -2177,7 +2193,7 @@ def test_legacy_plan_techniques_agree_across_projections( scenario_run_state=ScenarioRunState.COMPLETED, metadata={SCENARIO_RUN_PLAN_METADATA_KEY: raw_plan}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) run_id = str(scenario_result.id) service = ScenarioRunService() summaries = { @@ -2186,9 +2202,9 @@ def test_legacy_plan_techniques_agree_across_projections( } with patch.object(service, "_get_scenario_technique_summaries", return_value=summaries): - history = service.list_runs().items[0] - detail = service.get_run(scenario_result_id=run_id) - progress = service.get_run_progress_from_storage( + history = (await service.list_runs_async()).items[0] + detail = await service.get_run_async(scenario_result_id=run_id) + progress = await service.get_run_progress_from_storage_async( scenario_result_id=run_id, since=None, limit=25, active_group_ids=[] ) @@ -2202,7 +2218,7 @@ def test_legacy_plan_techniques_agree_across_projections( technique for technique in techniques for _ in goals ] assert all(group.description and group.tags == ["default"] for group in progress.plan.atomic_groups) - stored = sqlite_instance.get_scenario_results(scenario_result_ids=[run_id])[0] + stored = (await sqlite_instance.get_scenario_results_async(scenario_result_ids=[run_id]))[0] assert stored.metadata[SCENARIO_RUN_PLAN_METADATA_KEY] == raw_plan @@ -2211,7 +2227,7 @@ class TestScenarioRunServiceCancelRun: async def test_cancel_run_returns_none_for_unknown_id(self, mock_memory) -> None: """Test that cancel returns None for non-existent run.""" - mock_memory.get_scenario_results.return_value = [] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[]) service = ScenarioRunService() result = await service.cancel_run_async(scenario_result_id="nonexistent-id") assert result is None @@ -2220,8 +2236,15 @@ async def test_cancel_run_sets_cancelled_status(self, mock_all_registries) -> No """Test that cancelling a running scenario persists CANCELLED to DB.""" service = ScenarioRunService() mock_memory = mock_all_registries["memory"] - mock_all_registries["scenario_instance"].run_async.side_effect = asyncio.Event().wait + run_started = asyncio.Event() + + async def run_until_cancelled_async() -> None: + run_started.set() + await asyncio.Event().wait() + + mock_all_registries["scenario_instance"].run_async.side_effect = run_until_cancelled_async response = await service.start_run_async(request=_make_request()) + await asyncio.wait_for(run_started.wait(), timeout=5) # After update_scenario_run_state, the next DB query should return CANCELLED running_result = mock_all_registries["db_result"] @@ -2229,11 +2252,11 @@ async def test_cancel_run_sets_cancelled_status(self, mock_all_registries) -> No result_id=response.scenario_result_id, run_state=ScenarioRunState.CANCELLED, ) - mock_memory.get_scenario_results.side_effect = [[running_result], [cancelled_result]] + mock_memory.get_scenario_results_async = AsyncMock(side_effect=[[running_result], [cancelled_result]]) result = await service.cancel_run_async(scenario_result_id=response.scenario_result_id) - mock_memory.try_update_scenario_run_state.assert_called_once_with( + mock_memory.try_update_scenario_run_state_async.assert_called_once_with( scenario_result_id=response.scenario_result_id, expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, scenario_run_state=ScenarioRunState.CANCELLED, @@ -2267,19 +2290,23 @@ async def test_reconcile_marks_only_scheduler_managed_local_rows_failed(self, mo state=ScenarioRunState.IN_PROGRESS, ), ] - mock_memory.get_scenario_run_state_page.return_value = (interrupted, False) + mock_memory.get_scenario_run_state_page_async = AsyncMock(return_value=(interrupted, False)) headers = { "created": MagicMock(metadata=scheduler_metadata), "queued": MagicMock(metadata=scheduler_metadata), "running": MagicMock(metadata=scheduler_metadata), "framework-run": MagicMock(metadata={}), } - mock_memory.get_scenario_result_header.side_effect = lambda *, scenario_result_id: headers[scenario_result_id] + mock_memory.get_scenario_result_header_async = AsyncMock( + side_effect=lambda *, scenario_result_id: headers[scenario_result_id] + ) reconciled = await ScenarioRunService().reconcile_interrupted_runs_async() assert reconciled == 3 - assert {call.kwargs["scenario_result_id"] for call in mock_memory.update_scenario_run_state.call_args_list} == { + assert { + call.kwargs["scenario_result_id"] for call in mock_memory.update_scenario_run_state_async.call_args_list + } == { "created", "queued", "running", @@ -2287,10 +2314,10 @@ async def test_reconcile_marks_only_scheduler_managed_local_rows_failed(self, mo assert all( call.kwargs["scenario_run_state"] == ScenarioRunState.FAILED and call.kwargs["error_type"] == "ScenarioInterruptedError" - for call in mock_memory.update_scenario_run_state.call_args_list + for call in mock_memory.update_scenario_run_state_async.call_args_list ) - mock_memory.get_scenario_results.assert_not_called() - mock_memory.get_scenario_run_state_page.assert_called_once_with( + mock_memory.get_scenario_results_async.assert_not_called() + mock_memory.get_scenario_run_state_page_async.assert_called_once_with( states=(ScenarioRunState.CREATED, ScenarioRunState.QUEUED, ScenarioRunState.IN_PROGRESS), after_id=None, limit=500, @@ -2305,18 +2332,21 @@ async def test_reconcile_pages_nonterminal_state_projection(self, mock_memory) - scenario_result_id="00000000-0000-0000-0000-000000000002", state=ScenarioRunState.IN_PROGRESS, ) - mock_memory.get_scenario_run_state_page.side_effect = [([first], True), ([second], False)] - mock_memory.get_scenario_result_header.return_value = MagicMock( - metadata={_svc_mod._SCHEDULER_METADATA_KEY: _svc_mod._SCHEDULER_METADATA_VALUE} + mock_memory.get_scenario_run_state_page_async = AsyncMock(side_effect=[([first], True), ([second], False)]) + mock_memory.get_scenario_result_header_async = AsyncMock( + return_value=MagicMock(metadata={_svc_mod._SCHEDULER_METADATA_KEY: _svc_mod._SCHEDULER_METADATA_VALUE}) ) reconciled = await ScenarioRunService().reconcile_interrupted_runs_async() assert reconciled == 2 - assert mock_memory.get_scenario_run_state_page.call_args_list[1].kwargs["after_id"] == first.scenario_result_id + assert ( + mock_memory.get_scenario_run_state_page_async.call_args_list[1].kwargs["after_id"] + == first.scenario_result_id + ) async def test_reconcile_rejects_empty_nonterminal_page_with_more_rows(self, mock_memory) -> None: - mock_memory.get_scenario_run_state_page.return_value = ([], True) + mock_memory.get_scenario_run_state_page_async = AsyncMock(return_value=([], True)) with pytest.raises(RuntimeError, match="another page without returning a cursor row"): await ScenarioRunService().reconcile_interrupted_runs_async() @@ -2327,8 +2357,8 @@ async def test_reconcile_shared_backend_is_non_destructive(self) -> None: reconciled = await ScenarioRunService().reconcile_interrupted_runs_async() assert reconciled == 0 - shared_memory.get_scenario_run_state_page.assert_not_called() - shared_memory.update_scenario_run_state.assert_not_called() + shared_memory.get_scenario_run_state_page_async.assert_not_called() + shared_memory.update_scenario_run_state_async.assert_not_called() async def test_shutdown_fails_active_and_queued_runs_without_starting_next(self, mock_all_registries) -> None: mock_scenario_registry = mock_all_registries["scenario_registry"] @@ -2357,10 +2387,10 @@ def _update_state(*, scenario_result_id: str, scenario_run_state: ScenarioRunSta records[scenario_result_id].scenario_run_state = scenario_run_state mock_scenario_registry.create_and_initialize_async = AsyncMock(side_effect=_create_scenario) - mock_memory.get_scenario_results.side_effect = _get_results - mock_memory.update_scenario_run_state.side_effect = _update_state - mock_memory.try_update_scenario_run_state.side_effect = _update_state - mock_memory.update_scenario_run_state_and_metadata_fields.side_effect = _update_state + mock_memory.get_scenario_results_async = AsyncMock(side_effect=_get_results) + mock_memory.update_scenario_run_state_async = AsyncMock(side_effect=_update_state) + mock_memory.try_update_scenario_run_state_async = AsyncMock(side_effect=_update_state) + mock_memory.update_scenario_run_state_and_metadata_fields_async = AsyncMock(side_effect=_update_state) service = ScenarioRunService() await service.start_run_async(request=_make_request()) await service.start_run_async(request=_make_request()) @@ -2375,8 +2405,8 @@ def _update_state(*, scenario_result_id: str, scenario_run_state: ScenarioRunSta failure_calls = [ call for call in ( - mock_memory.update_scenario_run_state.call_args_list - + mock_memory.try_update_scenario_run_state.call_args_list + mock_memory.update_scenario_run_state_async.call_args_list + + mock_memory.try_update_scenario_run_state_async.call_args_list ) if call.kwargs.get("scenario_run_state") == ScenarioRunState.FAILED ] @@ -2442,10 +2472,10 @@ async def _shutdown() -> None: shutdown_started.set() await service.shutdown_async() - mock_memory.get_scenario_results.side_effect = _get_results - mock_memory.update_scenario_run_state.side_effect = _update_state - mock_memory.try_update_scenario_run_state.side_effect = _try_update_state - mock_memory.update_scenario_run_state_and_metadata_fields.side_effect = _update_state + mock_memory.get_scenario_results_async = AsyncMock(side_effect=_get_results) + mock_memory.update_scenario_run_state_async = AsyncMock(side_effect=_update_state) + mock_memory.try_update_scenario_run_state_async = AsyncMock(side_effect=_try_update_state) + mock_memory.update_scenario_run_state_and_metadata_fields_async = AsyncMock(side_effect=_update_state) service = ScenarioRunService() active = _svc_mod._ActiveTask( @@ -2490,10 +2520,12 @@ async def test_shutdown_reports_all_persistence_failures_and_clears_scheduler(se scenario=MagicMock(), ) ) - mock_all_registries["memory"].update_scenario_run_state.side_effect = [ - RuntimeError("queued persistence failed"), - RuntimeError("active persistence failed"), - ] + mock_all_registries["memory"].update_scenario_run_state_async = AsyncMock( + side_effect=[ + RuntimeError("queued persistence failed"), + RuntimeError("active persistence failed"), + ] + ) with pytest.raises(ExceptionGroup) as exc_info: await service.shutdown_async() @@ -2547,7 +2579,7 @@ async def run_until_cancelled() -> None: try: await asyncio.Event().wait() finally: - mock_memory.get_scenario_attack_result_deltas.return_value = ([delta], False) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock(return_value=([delta], False)) scenario_instance.run_async.side_effect = run_until_cancelled service = ScenarioRunService() @@ -2560,11 +2592,11 @@ async def run_until_cancelled() -> None: run_state=ScenarioRunState.CANCELLED, ) cancelled_result.metadata = {} - mock_memory.get_scenario_results.side_effect = [[running_result], [cancelled_result]] + mock_memory.get_scenario_results_async = AsyncMock(side_effect=[[running_result], [cancelled_result]]) await service.cancel_run_async(scenario_result_id=response.scenario_result_id) - mock_memory.get_scenario_result_header.return_value = cancelled_result - progress = service.get_run_progress( + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=cancelled_result) + progress = await service.get_run_progress_async( scenario_result_id=response.scenario_result_id, since=None, limit=25, @@ -2599,27 +2631,29 @@ async def run_until_cancelled() -> None: run_state=ScenarioRunState.CANCELLED, ) cancelled_result.metadata = {} - mock_memory.get_scenario_results.side_effect = [ - [running_result], - [cancelled_result], - [cancelled_result], - [cancelled_result], - ] + mock_memory.get_scenario_results_async = AsyncMock( + side_effect=[ + [running_result], + [cancelled_result], + [cancelled_result], + [cancelled_result], + ] + ) await service.cancel_run_async(scenario_result_id=rid) - fetched = service.get_run(scenario_result_id=rid) + fetched = await service.get_run_async(scenario_result_id=rid) assert fetched is not None assert fetched.status is ScenarioRunState.CANCELLED assert rid not in service._active_tasks - fetched_again = service.get_run(scenario_result_id=rid) + fetched_again = await service.get_run_async(scenario_result_id=rid) assert fetched_again is not None assert fetched_again.status is ScenarioRunState.CANCELLED async def test_cancel_completed_run_raises_value_error(self, mock_memory) -> None: """Test that cancelling a completed run raises ValueError.""" db_result = _make_db_scenario_result(result_id="sr-done", run_state=ScenarioRunState.COMPLETED) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() with pytest.raises(ValueError, match="Cannot cancel run"): @@ -2628,7 +2662,7 @@ async def test_cancel_completed_run_raises_value_error(self, mock_memory) -> Non async def test_cancel_already_cancelled_run_raises_value_error(self, mock_memory) -> None: """Test that cancelling an already-cancelled run raises ValueError.""" db_result = _make_db_scenario_result(result_id="sr-cancelled", run_state=ScenarioRunState.CANCELLED) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() with pytest.raises(ValueError, match="Cannot cancel run"): @@ -2675,11 +2709,11 @@ async def _run() -> MagicMock: # Executable task state is released during terminal handoff. assert response.scenario_result_id not in service._active_tasks - fetched = service.get_run(scenario_result_id=response.scenario_result_id) + fetched = await service.get_run_async(scenario_result_id=response.scenario_result_id) assert fetched is not None async def test_execute_run_fails_with_error(self, mock_all_registries) -> None: - """Test that a run_async failure stores error and surfaces it via get_run.""" + "Test that a run_async failure stores error and surfaces it via get_run_async." service = ScenarioRunService() mock_instance = mock_all_registries["scenario_instance"] execution_started = asyncio.Event() @@ -2706,7 +2740,7 @@ async def _run() -> None: assert response.scenario_result_id not in service._active_tasks # get_run surfaces the bounded terminal error evidence. - fetched = service.get_run(scenario_result_id=response.scenario_result_id) + fetched = await service.get_run_async(scenario_result_id=response.scenario_result_id) assert fetched is not None assert fetched.error == "scenario exploded" @@ -2748,8 +2782,10 @@ async def _run() -> None: persisted.error_type = "BadRequestError" raise RuntimeError("One or more attacks failed.") - mock_memory.update_scenario_run_state_and_metadata_fields.side_effect = _update_state_and_metadata - mock_memory.try_update_scenario_run_state.side_effect = _try_update_state + mock_memory.update_scenario_run_state_and_metadata_fields_async = AsyncMock( + side_effect=_update_state_and_metadata + ) + mock_memory.try_update_scenario_run_state_async = AsyncMock(side_effect=_try_update_state) mock_instance.run_async = AsyncMock(side_effect=_run) response = await service.start_run_async(request=_make_request()) @@ -2761,13 +2797,13 @@ async def _run() -> None: release_execution.set() await active.task - fetched = service.get_run(scenario_result_id=response.scenario_result_id) + fetched = await service.get_run_async(scenario_result_id=response.scenario_result_id) assert fetched is not None assert fetched.status == ScenarioRunState.FAILED assert fetched.error == "The target rejected the request body." assert fetched.error_type == "BadRequestError" - mock_memory.update_scenario_run_state.assert_not_called() - mock_memory.try_update_scenario_run_state.assert_called_once_with( + mock_memory.update_scenario_run_state_async.assert_not_called() + mock_memory.try_update_scenario_run_state_async.assert_called_once_with( scenario_result_id=response.scenario_result_id, expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, scenario_run_state=ScenarioRunState.FAILED, @@ -2779,23 +2815,23 @@ async def _run() -> None: class TestScenarioRunServiceGetResults: """Tests for ScenarioRunService.get_run_results.""" - def test_get_results_returns_none_for_unknown_id(self, mock_memory) -> None: + async def test_get_results_returns_none_for_unknown_id(self, mock_memory) -> None: """Test that get_run_results returns None for non-existent run.""" - mock_memory.get_scenario_results.return_value = [] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[]) service = ScenarioRunService() - result = service.get_run_results(scenario_result_id="nonexistent-id") + result = await service.get_run_results_async(scenario_result_id="nonexistent-id") assert result is None - def test_get_results_raises_if_not_completed(self, mock_memory) -> None: + async def test_get_results_raises_if_not_completed(self, mock_memory) -> None: """Test that get_run_results raises ValueError if run is not completed.""" db_result = _make_db_scenario_result(result_id="sr-running", run_state=ScenarioRunState.IN_PROGRESS) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() with pytest.raises(ValueError, match="only available for completed runs"): - service.get_run_results(scenario_result_id="sr-running") + (await service.get_run_results_async(scenario_result_id="sr-running")) - def test_get_results_returns_details_for_completed_run(self, mock_memory) -> None: + async def test_get_results_returns_details_for_completed_run(self, mock_memory) -> None: """Test that get_run_results returns the ScenarioResult for a completed run.""" from pyrit.models import AttackOutcome @@ -2809,10 +2845,10 @@ def test_get_results_returns_details_for_completed_run(self, mock_memory) -> Non attack_results={"base64_attack": [mock_attack_result]}, ) db_result.objective_achieved_rate.return_value = 100 - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() - result = service.get_run_results(scenario_result_id="sr-123") + result = await service.get_run_results_async(scenario_result_id="sr-123") assert result is db_result assert result.attack_results["base64_attack"][0].outcome == AttackOutcome.SUCCESS @@ -2821,7 +2857,7 @@ def test_get_results_returns_details_for_completed_run(self, mock_memory) -> Non class TestScenarioRunServiceProgressReporting: """Tests that in-progress runs expose partial attack counts.""" - def test_in_progress_run_shows_partial_attack_counts(self, mock_memory) -> None: + async def test_in_progress_run_shows_partial_attack_counts(self, mock_memory) -> None: """Test that polling an IN_PROGRESS run shows incremental results.""" from pyrit.models import AttackOutcome @@ -2842,10 +2878,10 @@ def test_in_progress_run_shows_partial_attack_counts(self, mock_memory) -> None: ) db_result.get_techniques_used.return_value = ["attack_a", "attack_b"] db_result.objective_achieved_rate.return_value = 33 - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() - fetched = service.get_run(scenario_result_id="sr-running") + fetched = await service.get_run_async(scenario_result_id="sr-running") assert fetched is not None assert fetched.status == ScenarioRunState.IN_PROGRESS @@ -2855,17 +2891,17 @@ def test_in_progress_run_shows_partial_attack_counts(self, mock_memory) -> None: assert fetched.objective_achieved_rate == 33 assert fetched.completed_at is None - def test_created_run_shows_zero_counts(self, mock_memory) -> None: + async def test_created_run_shows_zero_counts(self, mock_memory) -> None: """Test that a CREATED run with no results shows zero counts.""" db_result = _make_db_scenario_result( result_id="sr-new", run_state=ScenarioRunState.CREATED, attack_results={}, ) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() - fetched = service.get_run(scenario_result_id="sr-new") + fetched = await service.get_run_async(scenario_result_id="sr-new") assert fetched is not None assert fetched.status == ScenarioRunState.CREATED @@ -2873,7 +2909,7 @@ def test_created_run_shows_zero_counts(self, mock_memory) -> None: assert fetched.completed_attacks == 0 assert fetched.techniques_used == [] - def test_completed_run_still_shows_full_counts(self, mock_memory) -> None: + async def test_completed_run_still_shows_full_counts(self, mock_memory) -> None: """Test that COMPLETED runs still show accurate counts after the fix.""" from pyrit.models import AttackOutcome @@ -2887,10 +2923,10 @@ def test_completed_run_still_shows_full_counts(self, mock_memory) -> None: ) db_result.get_techniques_used.return_value = ["attack_a"] db_result.objective_achieved_rate.return_value = 100 - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() - fetched = service.get_run(scenario_result_id="sr-done") + fetched = await service.get_run_async(scenario_result_id="sr-done") assert fetched is not None assert fetched.status == ScenarioRunState.COMPLETED @@ -2904,7 +2940,7 @@ def test_completed_run_still_shows_full_counts(self, mock_memory) -> None: class TestScenarioRunServiceFailedAttackReporting: """Tests that per-attack errors and retry pressure surface in the summary.""" - def test_error_attacks_and_retries_are_surfaced(self, mock_memory) -> None: + async def test_error_attacks_and_retries_are_surfaced(self, mock_memory) -> None: from pyrit.models import AttackOutcome success = MagicMock() @@ -2924,10 +2960,10 @@ def test_error_attacks_and_retries_are_surfaced(self, mock_memory) -> None: attack_results={"baseline_airt_hate": [success, errored]}, ) db_result.objective_achieved_rate.return_value = 50 - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() - fetched = service.get_run(scenario_result_id="sr-mixed") + fetched = await service.get_run_async(scenario_result_id="sr-mixed") assert fetched is not None assert fetched.total_retries == 6 @@ -2938,7 +2974,7 @@ def test_error_attacks_and_retries_are_surfaced(self, mock_memory) -> None: assert failed.error_message == "429 Too Many Requests" assert failed.total_retries == 4 - def test_negative_error_attack_retries_are_clamped(self, mock_memory) -> None: + async def test_negative_error_attack_retries_are_clamped(self, mock_memory) -> None: from pyrit.models import AttackOutcome errored = MagicMock() @@ -2953,15 +2989,15 @@ def test_negative_error_attack_retries_are_clamped(self, mock_memory) -> None: run_state=ScenarioRunState.COMPLETED, attack_results={"attack_a": [errored]}, ) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) - fetched = ScenarioRunService().get_run(scenario_result_id="sr-negative-retries") + fetched = await ScenarioRunService().get_run_async(scenario_result_id="sr-negative-retries") assert fetched is not None assert fetched.total_retries == 0 assert fetched.failed_attacks[0].total_retries == 0 - def test_no_failed_attacks_when_all_succeed(self, mock_memory) -> None: + async def test_no_failed_attacks_when_all_succeed(self, mock_memory) -> None: from pyrit.models import AttackOutcome success = MagicMock() @@ -2974,17 +3010,17 @@ def test_no_failed_attacks_when_all_succeed(self, mock_memory) -> None: run_state=ScenarioRunState.COMPLETED, attack_results={"attack_a": [success]}, ) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() - fetched = service.get_run(scenario_result_id="sr-clean") + fetched = await service.get_run_async(scenario_result_id="sr-clean") assert fetched is not None assert fetched.failed_attacks == [] assert fetched.total_retries == 0 assert fetched.attack_retries == [] - def test_retry_events_surface_per_attack(self, mock_memory) -> None: + async def test_retry_events_surface_per_attack(self, mock_memory) -> None: from pyrit.models import AttackOutcome from pyrit.models.retry_event import RetryEvent @@ -3008,10 +3044,10 @@ def test_retry_events_surface_per_attack(self, mock_memory) -> None: run_state=ScenarioRunState.COMPLETED, attack_results={"baseline_airt_hate": [attack]}, ) - mock_memory.get_scenario_results.return_value = [db_result] + mock_memory.get_scenario_results_async = AsyncMock(return_value=[db_result]) service = ScenarioRunService() - fetched = service.get_run(scenario_result_id="sr-retry") + fetched = await service.get_run_async(scenario_result_id="sr-retry") assert fetched is not None assert len(fetched.attack_retries) == 1 @@ -3119,7 +3155,7 @@ async def test_start_run_forwards_technique_converters(self, mock_all_registries assert init_call.kwargs["technique_converters"] == {"role_play": [conv]} -def test_planned_progress_deduplicates_attempts_and_keeps_latest_outcome(mock_memory) -> None: +async def test_planned_progress_deduplicates_attempts_and_keeps_latest_outcome(mock_memory) -> None: seed_group = AttackSeedGroup(seeds=[SeedObjective(value="objective")]) seed_group_id = seed_group.logical_id atomic_group_id = config_hash({"atomic_attack_name": "attack", "technique_eval_hash": "eval"}) @@ -3165,7 +3201,7 @@ def test_planned_progress_deduplicates_attempts_and_keeps_latest_outcome(mock_me metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, ) - summary = ScenarioRunService()._build_response_from_db(scenario_result=scenario_result) + summary = await ScenarioRunService()._build_response_from_db_async(scenario_result=scenario_result) assert summary.total_attacks == 1 assert summary.completed_attacks == 1 @@ -3174,7 +3210,7 @@ def test_planned_progress_deduplicates_attempts_and_keeps_latest_outcome(mock_me assert summary.total_retries == 3 -def test_planned_progress_includes_latest_errors_in_success_rate_denominator(mock_memory) -> None: +async def test_planned_progress_includes_latest_errors_in_success_rate_denominator(mock_memory) -> None: atomic_group_id = config_hash({"atomic_attack_name": "attack", "technique_eval_hash": "eval"}) plan = ScenarioRunPlan( scenario_registry_name="test.scenario", @@ -3228,14 +3264,14 @@ def test_planned_progress_includes_latest_errors_in_success_rate_denominator(moc metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, ) - summary = ScenarioRunService()._build_response_from_db(scenario_result=scenario_result) + summary = await ScenarioRunService()._build_response_from_db_async(scenario_result=scenario_result) assert summary.total_attacks == 2 assert summary.completed_attacks == 2 assert summary.objective_achieved_rate == 50 -def test_history_and_detail_retry_work_match_across_attempt_partitions(mock_memory) -> None: +async def test_history_and_detail_retry_work_match_across_attempt_partitions(mock_memory) -> None: objective = "partitioned objective" plan = ScenarioRunPlan( scenario_registry_name="test.scenario", @@ -3292,7 +3328,7 @@ def test_history_and_detail_retry_work_match_across_attempt_partitions(mock_memo ) service = ScenarioRunService() - detail = service._build_response_from_db(scenario_result=scenario_result) + detail = await service._build_response_from_db_async(scenario_result=scenario_result) history = service._build_history_summary( record=record, atomic_groups=plan.atomic_groups, @@ -3302,7 +3338,7 @@ def test_history_and_detail_retry_work_match_across_attempt_partitions(mock_memo assert history.total_retries == detail.total_retries -def test_planned_progress_maps_legacy_objective_hash_to_logical_seed_id(mock_memory) -> None: +async def test_planned_progress_maps_legacy_objective_hash_to_logical_seed_id(mock_memory) -> None: objective = "legacy resumed objective" seed_group = AttackSeedGroup(seeds=[SeedObjective(value=objective)]) seed_group_id = seed_group.logical_id @@ -3339,21 +3375,21 @@ def test_planned_progress_maps_legacy_objective_hash_to_logical_seed_id(mock_mem metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, ) - summary = ScenarioRunService()._build_response_from_db(scenario_result=scenario_result) + summary = await ScenarioRunService()._build_response_from_db_async(scenario_result=scenario_result) assert summary.total_attacks == 1 assert summary.completed_attacks == 1 -def test_get_progress_uses_lightweight_queries_without_full_hydration(mock_memory) -> None: +async def test_get_progress_uses_lightweight_queries_without_full_hydration(mock_memory) -> None: plan = ScenarioRunPlan(atomic_groups=[], seed_groups=[], scenario_registry_name="test.scenario") header = make_scenario_result( attack_results={}, metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, ) - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.return_value = ([], False) - mock_memory.get_scenario_results.reset_mock() + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=header) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock(return_value=([], False)) + mock_memory.get_scenario_results_async.reset_mock() service = ScenarioRunService() completed_task = MagicMock() @@ -3364,7 +3400,7 @@ def test_get_progress_uses_lightweight_queries_without_full_hydration(mock_memor scenario=MagicMock(), ) - progress = service.get_run_progress( + progress = await service.get_run_progress_async( scenario_result_id=str(header.id), since=None, limit=25, @@ -3373,11 +3409,11 @@ def test_get_progress_uses_lightweight_queries_without_full_hydration(mock_memor assert progress is not None assert progress.plan == plan assert progress.plan_complete is True - mock_memory.get_scenario_results.assert_not_called() + mock_memory.get_scenario_results_async.assert_not_called() assert str(header.id) not in service._active_tasks -def test_get_progress_maps_persisted_failure_details(mock_memory) -> None: +async def test_get_progress_maps_persisted_failure_details(mock_memory) -> None: plan = ScenarioRunPlan(atomic_groups=[], seed_groups=[], scenario_registry_name="test.scenario") header = make_scenario_result( attack_results={}, @@ -3386,10 +3422,10 @@ def test_get_progress_maps_persisted_failure_details(mock_memory) -> None: error_type="ValueError", metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, ) - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.return_value = ([], False) + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=header) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock(return_value=([], False)) - progress = ScenarioRunService().get_run_progress( + progress = await ScenarioRunService().get_run_progress_async( scenario_result_id=str(header.id), since=None, limit=25, @@ -3400,7 +3436,7 @@ def test_get_progress_maps_persisted_failure_details(mock_memory) -> None: assert progress.run.error_type == "ValueError" -def test_get_progress_cache_only_maps_new_storage_rows(mock_memory) -> None: +async def test_get_progress_cache_only_maps_new_storage_rows(mock_memory) -> None: seed_group_ids = ["seed-1", "seed-2"] plan = ScenarioRunPlan( atomic_groups=[ @@ -3437,19 +3473,21 @@ def test_get_progress_cache_only_maps_new_storage_rows(mock_memory) -> None: ) for index, seed_id in enumerate(seed_group_ids) ] - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.side_effect = [ - ([deltas[0]], False), - ([deltas[1]], False), - ] + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=header) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock( + side_effect=[ + ([deltas[0]], False), + ([deltas[1]], False), + ] + ) service = ScenarioRunService() - first = service.get_run_progress( + first = await service.get_run_progress_async( scenario_result_id=str(header.id), since=None, limit=25, ) - second = service.get_run_progress( + second = await service.get_run_progress_async( scenario_result_id=str(header.id), since=None, limit=25, @@ -3460,11 +3498,11 @@ def test_get_progress_cache_only_maps_new_storage_rows(mock_memory) -> None: assert first.summary.overall.completed == 1 assert second.summary.overall.completed == 2 assert len(second.results) == 2 - second_cursor = mock_memory.get_scenario_attack_result_deltas.call_args_list[1].kwargs["cursor"] + second_cursor = mock_memory.get_scenario_attack_result_deltas_async.call_args_list[1].kwargs["cursor"] assert second_cursor.attack_result_id == deltas[0].attack_result_id -def test_get_progress_cache_refreshes_identifier_enriched_after_insert(mock_memory) -> None: +async def test_get_progress_cache_refreshes_identifier_enriched_after_insert(mock_memory) -> None: plan = ScenarioRunPlan( atomic_groups=[ ScenarioRunPlanAtomicGroup( @@ -3526,15 +3564,17 @@ def test_get_progress_cache_refreshes_identifier_enriched_after_insert(mock_memo }, } ) - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.side_effect = [ - ([pre_enrichment], False), - ([post_enrichment, appended], False), - ] + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=header) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock( + side_effect=[ + ([pre_enrichment], False), + ([post_enrichment, appended], False), + ] + ) service = ScenarioRunService() - first = service.get_run_progress(scenario_result_id=str(header.id), since=None, limit=25) - second = service.get_run_progress(scenario_result_id=str(header.id), since=None, limit=25) + first = await service.get_run_progress_async(scenario_result_id=str(header.id), since=None, limit=25) + second = await service.get_run_progress_async(scenario_result_id=str(header.id), since=None, limit=25) assert first is not None assert second is not None @@ -3544,10 +3584,10 @@ def test_get_progress_cache_refreshes_identifier_enriched_after_insert(mock_memo post_enrichment.attack_result_id, appended.attack_result_id, ] - assert mock_memory.get_scenario_attack_result_deltas.call_args_list[1].kwargs["cursor"] is None + assert mock_memory.get_scenario_attack_result_deltas_async.call_args_list[1].kwargs["cursor"] is None -def test_get_progress_exposes_persisted_started_at(mock_memory) -> None: +async def test_get_progress_exposes_persisted_started_at(mock_memory) -> None: started_at = datetime(2026, 8, 8, 12, 30, tzinfo=UTC) header = make_scenario_result( attack_results={}, @@ -3560,10 +3600,10 @@ def test_get_progress_exposes_persisted_started_at(mock_memory) -> None: _svc_mod.SCENARIO_RUN_STARTED_AT_METADATA_KEY: started_at.isoformat(), }, ) - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.return_value = ([], False) + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=header) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock(return_value=([], False)) - progress = ScenarioRunService().get_run_progress_from_storage( + progress = await ScenarioRunService().get_run_progress_from_storage_async( scenario_result_id=str(header.id), since=None, limit=25, @@ -3574,7 +3614,7 @@ def test_get_progress_exposes_persisted_started_at(mock_memory) -> None: assert progress.run.started_at == started_at -def test_get_progress_techniques_used_prefers_technique_name_over_display_group(mock_memory) -> None: +async def test_get_progress_techniques_used_prefers_technique_name_over_display_group(mock_memory) -> None: """A goal-based display_group must not stand in for the technique identity.""" header = make_scenario_result( scenario_name="garak.prompt_inject", @@ -3596,10 +3636,10 @@ def test_get_progress_techniques_used_prefers_technique_name_over_display_group( ).model_dump(mode="json"), }, ) - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.return_value = ([], False) + mock_memory.get_scenario_result_header_async.return_value = header + mock_memory.get_scenario_attack_result_deltas_async.return_value = ([], False) - progress = ScenarioRunService().get_run_progress_from_storage( + progress = await ScenarioRunService().get_run_progress_from_storage_async( scenario_result_id=str(header.id), since=None, limit=25, @@ -3620,7 +3660,7 @@ def test_load_started_at_rejects_invalid_or_naive_timestamp(started_at: str) -> assert ScenarioRunService._load_started_at(scenario_result=scenario_result) is None -def test_get_progress_refreshes_enriched_rows_across_storage_pages(mock_memory: MagicMock) -> None: +async def test_get_progress_refreshes_enriched_rows_across_storage_pages(mock_memory: MagicMock) -> None: attack_identifier = ComponentIdentifier(class_name="PromptSendingAttack", class_module="tests") unenriched_identifier = AtomicAttackIdentifier.build(attack_identifier=attack_identifier) deltas = [ @@ -3685,11 +3725,11 @@ def get_deltas( ] return [delta.model_copy(deep=True) for delta in available[:limit]], len(available) > limit - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.side_effect = get_deltas + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=header) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock(side_effect=get_deltas) service = ScenarioRunService() - first = service.get_run_progress(scenario_result_id=run_id, since=None, limit=100) + first = await service.get_run_progress_async(scenario_result_id=run_id, since=None, limit=100) assert first is not None assert first.plan == plan @@ -3717,7 +3757,7 @@ def get_deltas( result_ids = [result.attack_result_id for result in first.results] cursor = first.next_cursor for offset in range(100, 501, 100): - page = service.get_run_progress(scenario_result_id=run_id, since=cursor, limit=100) + page = await service.get_run_progress_async(scenario_result_id=run_id, since=cursor, limit=100) assert page is not None assert page.plan is None @@ -3738,13 +3778,15 @@ def get_deltas( assert len(set(result_ids)) == 501 assert first.model_dump(mode="json") == first_payload - empty = service.get_run_progress(scenario_result_id=run_id, since=cursor, limit=100) + empty = await service.get_run_progress_async(scenario_result_id=run_id, since=cursor, limit=100) assert empty is not None assert empty.results == [] assert empty.has_more is False assert empty.next_cursor == cursor - storage_cursors = [call.kwargs["cursor"] for call in mock_memory.get_scenario_attack_result_deltas.call_args_list] + storage_cursors = [ + call.kwargs["cursor"] for call in mock_memory.get_scenario_attack_result_deltas_async.call_args_list + ] assert storage_cursors[:3] == [ None, None, @@ -3757,7 +3799,7 @@ def get_deltas( ) -def test_get_progress_treats_duplicate_stored_plan_groups_as_incomplete(mock_memory) -> None: +async def test_get_progress_treats_duplicate_stored_plan_groups_as_incomplete(mock_memory) -> None: group = ScenarioRunPlanAtomicGroup( id="duplicate", atomic_attack_name="attack", @@ -3781,10 +3823,10 @@ def test_get_progress_treats_duplicate_stored_plan_groups_as_incomplete(mock_mem } }, ) - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.return_value = ([], False) + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=header) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock(return_value=([], False)) - progress = ScenarioRunService().get_run_progress( + progress = await ScenarioRunService().get_run_progress_async( scenario_result_id=str(header.id), since=None, limit=25, @@ -3981,7 +4023,7 @@ def test_synthesize_legacy_plan_deduplicates_seed_ids_in_first_seen_order() -> N assert [seed.id for seed in plan.seed_groups] == ["seed-b", "seed-a"] -def test_get_progress_synthesizes_incomplete_legacy_plan(mock_memory) -> None: +async def test_get_progress_synthesizes_incomplete_legacy_plan(mock_memory) -> None: header = make_scenario_result( attack_results={}, scenario_run_state=ScenarioRunState.COMPLETED, @@ -3996,10 +4038,10 @@ def test_get_progress_synthesizes_incomplete_legacy_plan(mock_memory) -> None: timestamp=datetime(2025, 1, 1, tzinfo=UTC), attribution_data={"parent_collection": "legacy attack"}, ) - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.return_value = ([delta], False) + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=header) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock(return_value=([delta], False)) - progress = ScenarioRunService().get_run_progress( + progress = await ScenarioRunService().get_run_progress_async( scenario_result_id=str(header.id), since=None, limit=25, @@ -4012,16 +4054,16 @@ def test_get_progress_synthesizes_incomplete_legacy_plan(mock_memory) -> None: assert len(progress.results) == 1 -def test_get_progress_treats_invalid_persisted_plan_as_incomplete(mock_memory, caplog) -> None: +async def test_get_progress_treats_invalid_persisted_plan_as_incomplete(mock_memory, caplog) -> None: header = make_scenario_result( attack_results={}, scenario_run_state=ScenarioRunState.COMPLETED, metadata={SCENARIO_RUN_PLAN_METADATA_KEY: {"atomic_groups": "invalid"}}, ) - mock_memory.get_scenario_result_header.return_value = header - mock_memory.get_scenario_attack_result_deltas.return_value = ([], False) + mock_memory.get_scenario_result_header_async = AsyncMock(return_value=header) + mock_memory.get_scenario_attack_result_deltas_async = AsyncMock(return_value=([], False)) - progress = ScenarioRunService().get_run_progress( + progress = await ScenarioRunService().get_run_progress_async( scenario_result_id=str(header.id), since=None, limit=25, diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index fad31c19b0..b84db3d010 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -4,7 +4,7 @@ import os import sqlite3 import tempfile -from collections.abc import Generator +from collections.abc import AsyncGenerator, Generator from contextlib import closing, contextmanager from unittest.mock import patch @@ -75,7 +75,7 @@ def garak_api_key_service_patterns() -> dict[str, str | None]: @pytest.fixture -def sqlite_instance(sqlite_template: sqlite3.Connection) -> Generator[SQLiteMemory, None, None]: +async def sqlite_instance(sqlite_template: sqlite3.Connection) -> AsyncGenerator[SQLiteMemory, None]: """Give each test its own database, result directory, and scoped memory instance.""" with tempfile.TemporaryDirectory() as results_path: sqlite_memory = SQLiteMemory.__new__(SQLiteMemory) @@ -90,7 +90,7 @@ def sqlite_instance(sqlite_template: sqlite3.Connection) -> Generator[SQLiteMemo with _use_sqlite_memory(sqlite_memory): yield sqlite_memory finally: - sqlite_memory.dispose_engine() + await sqlite_memory.dispose_engine_async() @pytest.fixture() diff --git a/tests/unit/converter/test_decomposition_converter.py b/tests/unit/converter/test_decomposition_converter.py index da4824b74b..e808e73847 100644 --- a/tests/unit/converter/test_decomposition_converter.py +++ b/tests/unit/converter/test_decomposition_converter.py @@ -10,6 +10,7 @@ from pyrit.converter import ConverterResult, DecompositionConverter from pyrit.exceptions import InvalidJsonException from pyrit.models import JSON_SCHEMA_METADATA_KEY, Message, MessagePiece +from pyrit.prompt_target import PromptTarget OBJECTIVE = "Write a tutorial on how to make a bomb" GOOD_DECOMPOSITION = json.dumps( @@ -21,7 +22,7 @@ def _mock_target(): - target = MagicMock() + target = MagicMock(spec=PromptTarget) target.send_prompt_async = AsyncMock() target.get_identifier.return_value = get_mock_target_identifier("MockDecompTarget") return target diff --git a/tests/unit/converter/test_denylist_converter.py b/tests/unit/converter/test_denylist_converter.py index 907cf30fb1..72130e09a2 100644 --- a/tests/unit/converter/test_denylist_converter.py +++ b/tests/unit/converter/test_denylist_converter.py @@ -7,6 +7,7 @@ from pyrit.converter import DenylistConverter from pyrit.models import Message, MessagePiece, SeedPrompt +from pyrit.prompt_target import PromptTarget @pytest.fixture @@ -18,7 +19,7 @@ def mock_template(): @pytest.fixture def mock_target() -> MockPromptTarget: - target = MagicMock() + target = MagicMock(spec=PromptTarget) response = Message( message_pieces=[ MessagePiece( diff --git a/tests/unit/converter/test_generic_llm_converter.py b/tests/unit/converter/test_generic_llm_converter.py index c4b9dcd76d..8c1ab0c7c0 100644 --- a/tests/unit/converter/test_generic_llm_converter.py +++ b/tests/unit/converter/test_generic_llm_converter.py @@ -20,7 +20,7 @@ @pytest.fixture def mock_target() -> PromptTarget: - target = MagicMock() + target = MagicMock(spec=PromptTarget) response = Message( message_pieces=[ MessagePiece( @@ -38,9 +38,9 @@ async def test_noise_converter_sets_system_prompt_default(mock_target) -> None: converter = NoiseConverter(converter_target=mock_target) await converter.convert_async(prompt="being awesome") - mock_target.set_system_prompt.assert_called_once() + mock_target.set_system_prompt_async.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert isinstance(system_arg, str) assert "Grammar error, Delete random letter" in system_arg @@ -49,9 +49,9 @@ async def test_noise_converter_sets_system_prompt(mock_target) -> None: converter = NoiseConverter(converter_target=mock_target, noise="extra random periods") await converter.convert_async(prompt="being awesome") - mock_target.set_system_prompt.assert_called_once() + mock_target.set_system_prompt_async.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert isinstance(system_arg, str) assert "extra random periods" in system_arg @@ -60,9 +60,9 @@ async def test_tone_converter_sets_system_prompt(mock_target) -> None: converter = ToneConverter(tone="formal", converter_target=mock_target) await converter.convert_async(prompt="being awesome") - mock_target.set_system_prompt.assert_called_once() + mock_target.set_system_prompt_async.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert isinstance(system_arg, str) assert "formal" in system_arg @@ -71,9 +71,9 @@ async def test_tense_converter_sets_system_prompt(mock_target) -> None: converter = TenseConverter(tense="past", converter_target=mock_target) await converter.convert_async(prompt="being awesome") - mock_target.set_system_prompt.assert_called_once() + mock_target.set_system_prompt_async.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert isinstance(system_arg, str) assert "past" in system_arg @@ -82,36 +82,36 @@ async def test_malicious_question_converter_sets_system_prompt(mock_target) -> N converter = MaliciousQuestionGeneratorConverter(converter_target=mock_target) await converter.convert_async(prompt="being awesome") - mock_target.set_system_prompt.assert_called_once() + mock_target.set_system_prompt_async.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert isinstance(system_arg, str) assert "Please act as an expert in this domain: being awesome" in system_arg def test_generic_llm_converter_input_supported() -> None: - target = MagicMock() + target = MagicMock(spec=PromptTarget) converter = LLMGenericTextConverter(converter_target=target) assert converter.input_supported("text") is True assert converter.input_supported("audio_path") is False def test_generic_llm_converter_user_prompt_without_objective_raises() -> None: - target = MagicMock() + target = MagicMock(spec=PromptTarget) user_template = MagicMock() with pytest.raises(ValueError): LLMGenericTextConverter(converter_target=target, user_prompt_template_with_objective=user_template) def test_generic_llm_converter_init_default_templates_empty() -> None: - target = MagicMock() + target = MagicMock(spec=PromptTarget) converter = LLMGenericTextConverter(converter_target=target) assert converter._system_prompt_template is None assert converter._user_prompt_template_with_objective is None def test_generic_llm_converter_default_no_retry_exceptions() -> None: - target = MagicMock() + target = MagicMock(spec=PromptTarget) converter = LLMGenericTextConverter(converter_target=target) assert converter._retry_exceptions == () @@ -120,7 +120,7 @@ def test_generic_llm_converter_class_attr_retry_exceptions() -> None: class _RetryingConverter(LLMGenericTextConverter): RETRY_EXCEPTIONS = (ValueError,) - target = MagicMock() + target = MagicMock(spec=PromptTarget) converter = _RetryingConverter(converter_target=target) assert converter._retry_exceptions == (ValueError,) @@ -129,7 +129,7 @@ def test_generic_llm_converter_instance_retry_exceptions_overrides_class_attr() class _RetryingConverter(LLMGenericTextConverter): RETRY_EXCEPTIONS = (ValueError,) - target = MagicMock() + target = MagicMock(spec=PromptTarget) converter = _RetryingConverter(converter_target=target, retry_exceptions=(KeyError,)) assert converter._retry_exceptions == (KeyError,) @@ -181,7 +181,7 @@ async def test_convert_async_input_validation_raises_before_set_system_prompt(mo converter = LLMGenericTextConverter(converter_target=mock_target, system_prompt_template=system_template) with pytest.raises(ValueError, match="Input type not supported"): await converter.convert_async(prompt="hello", input_type="image_path") - mock_target.set_system_prompt.assert_not_called() + mock_target.set_system_prompt_async.assert_not_called() mock_target.send_prompt_async.assert_not_called() diff --git a/tests/unit/converter/test_image_prompt_style_converter.py b/tests/unit/converter/test_image_prompt_style_converter.py index 117542b07d..4d2501955b 100644 --- a/tests/unit/converter/test_image_prompt_style_converter.py +++ b/tests/unit/converter/test_image_prompt_style_converter.py @@ -14,7 +14,7 @@ @pytest.fixture def mock_target() -> PromptTarget: - target = MagicMock() + target = MagicMock(spec=PromptTarget) response = Message( message_pieces=[ MessagePiece( @@ -175,8 +175,8 @@ async def test_convert_async_with_specific_variation(mock_target) -> None: ) result = await converter.convert_async(prompt="person walking through a dark alley") - mock_target.set_system_prompt.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + mock_target.set_system_prompt_async.assert_called_once() + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert "bodycam_footage" in system_arg assert "style_instructions" not in system_arg or "CRITICAL INSTRUCTION" in system_arg @@ -192,8 +192,8 @@ async def test_convert_async_with_random_variation(mock_target) -> None: ) result = await converter.convert_async(prompt="person in a park") - mock_target.set_system_prompt.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + mock_target.set_system_prompt_async.assert_called_once() + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] # Should contain one of the variation names assert any(name in system_arg for name in converter._variations) diff --git a/tests/unit/converter/test_math_prompt_converter.py b/tests/unit/converter/test_math_prompt_converter.py index 3b58c32a4b..e160a0b110 100644 --- a/tests/unit/converter/test_math_prompt_converter.py +++ b/tests/unit/converter/test_math_prompt_converter.py @@ -9,11 +9,12 @@ from pyrit.converter import ConverterResult from pyrit.converter.math_prompt_converter import MathPromptConverter from pyrit.models import Message, MessagePiece, SeedPrompt +from pyrit.prompt_target import PromptTarget async def test_math_prompt_converter_convert_async(): # Mock the converter target - use MagicMock for synchronous methods - mock_converter_target = MagicMock() + mock_converter_target = MagicMock(spec=PromptTarget) mock_converter_target.send_prompt_async = AsyncMock() mock_converter_target.get_identifier.return_value = get_mock_target_identifier("MockMathTarget") # Specify parameters=['prompt'] to match the placeholder in the template @@ -70,7 +71,7 @@ async def test_math_prompt_converter_convert_async(): async def test_math_prompt_converter_handles_disallowed_content(): # Mock the converter target - use MagicMock for synchronous methods - mock_converter_target = MagicMock() + mock_converter_target = MagicMock(spec=PromptTarget) mock_converter_target.send_prompt_async = AsyncMock() mock_converter_target.get_identifier.return_value = get_mock_target_identifier("MockMathTarget") # Specify parameters=['prompt'] to match the placeholder in the template @@ -124,7 +125,7 @@ async def test_math_prompt_converter_handles_disallowed_content(): async def test_math_prompt_converter_invalid_input_type(): # Mock the converter target - use MagicMock for synchronous methods - mock_converter_target = MagicMock() + mock_converter_target = MagicMock(spec=PromptTarget) mock_converter_target.send_prompt_async = AsyncMock() mock_converter_target.get_identifier.return_value = get_mock_target_identifier("MockMathTarget") # Specify parameters=['prompt'] to match the placeholder in the template @@ -146,7 +147,7 @@ async def test_math_prompt_converter_invalid_input_type(): async def test_math_prompt_converter_error_handling(): # Mock the converter target - use MagicMock for synchronous methods - mock_converter_target = MagicMock() + mock_converter_target = MagicMock(spec=PromptTarget) mock_converter_target.send_prompt_async = AsyncMock() mock_converter_target.get_identifier.return_value = get_mock_target_identifier("MockMathTarget") # Specify parameters=['prompt'] to match the placeholder in the template diff --git a/tests/unit/converter/test_random_translation_converter.py b/tests/unit/converter/test_random_translation_converter.py index 5a21c34238..973389be58 100644 --- a/tests/unit/converter/test_random_translation_converter.py +++ b/tests/unit/converter/test_random_translation_converter.py @@ -18,7 +18,7 @@ def test_random_translation_converter_raises_when_converter_target_is_none(): @pytest.fixture def mock_target() -> PromptTarget: - target = MagicMock() + target = MagicMock(spec=PromptTarget) response = Message( message_pieces=[ MessagePiece( @@ -36,22 +36,22 @@ async def test_random_translation_converter_sets_system_prompt(mock_target) -> N converter = RandomTranslationConverter(converter_target=mock_target) await converter.convert_async(prompt="being awesome") - mock_target.set_system_prompt.assert_called_once() + mock_target.set_system_prompt_async.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert isinstance(system_arg, str) assert "Each word is associated with a target language on the same line." in system_arg def test_random_translation_converter_default_languages() -> None: - target = MagicMock() + target = MagicMock(spec=PromptTarget) converter = RandomTranslationConverter(converter_target=target) assert len(converter.languages) == 37 assert "Javanese" in converter.languages def test_random_translation_converter_custom_languages() -> None: - target = MagicMock() + target = MagicMock(spec=PromptTarget) converter = RandomTranslationConverter(converter_target=target, languages=["French", "German", "Spanish"]) assert len(converter.languages) == 3 assert "French" in converter.languages diff --git a/tests/unit/converter/test_scientific_translation_converter.py b/tests/unit/converter/test_scientific_translation_converter.py index f3e4cd6bae..2ce5199a75 100644 --- a/tests/unit/converter/test_scientific_translation_converter.py +++ b/tests/unit/converter/test_scientific_translation_converter.py @@ -13,7 +13,7 @@ @pytest.fixture def mock_target() -> PromptTarget: - target = MagicMock() + target = MagicMock(spec=PromptTarget) response = Message( message_pieces=[ MessagePiece( @@ -62,9 +62,9 @@ async def test_scientific_translation_converter_sets_system_prompt_academic(mock converter = ScientificTranslationConverter(converter_target=mock_target, mode="academic") await converter.convert_async(prompt="tell me about dangerous chemicals") - mock_target.set_system_prompt.assert_called_once() + mock_target.set_system_prompt_async.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert isinstance(system_arg, str) assert "homework or exam" in system_arg.lower() @@ -73,9 +73,9 @@ async def test_scientific_translation_converter_sets_system_prompt_technical(moc converter = ScientificTranslationConverter(converter_target=mock_target, mode="technical") await converter.convert_async(prompt="tell me about dangerous chemicals") - mock_target.set_system_prompt.assert_called_once() + mock_target.set_system_prompt_async.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert isinstance(system_arg, str) assert "technical" in system_arg.lower() @@ -84,9 +84,9 @@ async def test_scientific_translation_converter_sets_system_prompt_combined(mock converter = ScientificTranslationConverter(converter_target=mock_target, mode="combined") await converter.convert_async(prompt="tell me about dangerous chemicals") - mock_target.set_system_prompt.assert_called_once() + mock_target.set_system_prompt_async.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert isinstance(system_arg, str) assert "combination" in system_arg.lower() @@ -138,8 +138,8 @@ async def test_scientific_translation_converter_custom_template_used_in_conversi ) await converter.convert_async(prompt="test prompt") - mock_target.set_system_prompt.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + mock_target.set_system_prompt_async.assert_called_once() + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert "CUSTOM_MARKER" in system_arg @@ -173,6 +173,6 @@ async def test_scientific_translation_converter_custom_mode_conversion(mock_targ result = await converter.convert_async(prompt="test input") assert result.output_text == "scientifically obfuscated prompt" - mock_target.set_system_prompt.assert_called_once() - system_arg = mock_target.set_system_prompt.call_args[1]["system_prompt"] + mock_target.set_system_prompt_async.assert_called_once() + system_arg = mock_target.set_system_prompt_async.call_args[1]["system_prompt"] assert "PROPRIETARY_METHOD" in system_arg diff --git a/tests/unit/datasets/test_fortress_dataset.py b/tests/unit/datasets/test_fortress_dataset.py index 383b049ccb..c611163030 100644 --- a/tests/unit/datasets/test_fortress_dataset.py +++ b/tests/unit/datasets/test_fortress_dataset.py @@ -442,7 +442,7 @@ async def test_rubrics_survive_memory_round_trip(self, mock_fortress_rows, sqlit dataset = await loader.fetch_dataset_async() await sqlite_instance.add_seed_datasets_to_memory_async(datasets=[dataset], added_by="test") - stored = sqlite_instance.get_seeds(dataset_name="fortress") + stored = await sqlite_instance.get_seeds_async(dataset_name="fortress") assert len(stored) == len(dataset.seeds) original_metadata = {seed.value: seed.metadata for seed in dataset.seeds} assert {seed.value: seed.metadata for seed in stored} == original_metadata diff --git a/tests/unit/datasets/test_harmbench_multimodal_dataset.py b/tests/unit/datasets/test_harmbench_multimodal_dataset.py index ff66b99908..61345a4f96 100644 --- a/tests/unit/datasets/test_harmbench_multimodal_dataset.py +++ b/tests/unit/datasets/test_harmbench_multimodal_dataset.py @@ -9,6 +9,7 @@ SemanticCategory, _HarmBenchMultimodalDataset, ) +from pyrit.memory import MemoryInterface from pyrit.models import SeedDataset @@ -191,7 +192,7 @@ async def test_fetch_and_save_image_raises_when_memory_not_configured(): from unittest.mock import MagicMock mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = None mock_memory.results_storage_io = None mock_serializer._memory = mock_memory @@ -211,7 +212,7 @@ async def test_fetch_and_save_image_returns_cached_path(): from unittest.mock import MagicMock mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = "/results" mock_storage_io = AsyncMock() mock_storage_io.path_exists_async = AsyncMock(return_value=True) diff --git a/tests/unit/datasets/test_image_cache.py b/tests/unit/datasets/test_image_cache.py index 476be7dece..6edc7578e5 100644 --- a/tests/unit/datasets/test_image_cache.py +++ b/tests/unit/datasets/test_image_cache.py @@ -9,12 +9,13 @@ from pyrit.datasets.seed_datasets.remote._image_cache import ( fetch_and_cache_image_async, ) +from pyrit.memory import MemoryInterface def _make_mock_serializer(*, exists: bool = False) -> MagicMock: """Build a MagicMock serializer with memory configured.""" mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = "/results" mock_storage_io = AsyncMock() mock_storage_io.path_exists_async = AsyncMock(return_value=exists) @@ -115,7 +116,7 @@ async def test_raises_value_error_when_neither_url_nor_bytes_provided(): async def test_raises_runtime_error_when_memory_not_configured(): mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = None mock_memory.results_storage_io = None mock_serializer._memory = mock_memory diff --git a/tests/unit/datasets/test_mossbench_dataset.py b/tests/unit/datasets/test_mossbench_dataset.py index c42d17d523..55e950a418 100644 --- a/tests/unit/datasets/test_mossbench_dataset.py +++ b/tests/unit/datasets/test_mossbench_dataset.py @@ -75,7 +75,8 @@ def test_dataset_uses_isolated_memory_and_results_path(self): """ memory = CentralMemory.get_memory_instance() # Prove database isolation: in-memory, no shared file on disk. - assert memory.engine.url.database == ":memory:" + assert memory.db_path == ":memory:" + assert memory.engine.url.query["mode"] == "memory" # Prove results-directory isolation: scoped to a temporary folder, # not the default persistent "results/" directory. assert os.path.isabs(memory.results_path) diff --git a/tests/unit/datasets/test_msts_dataset.py b/tests/unit/datasets/test_msts_dataset.py index c21281bfcd..2efc1371fa 100644 --- a/tests/unit/datasets/test_msts_dataset.py +++ b/tests/unit/datasets/test_msts_dataset.py @@ -8,6 +8,7 @@ import pytest from pyrit.datasets.seed_datasets.remote.msts_dataset import _MSTSDataset +from pyrit.memory import MemoryInterface from pyrit.models import SeedDataset @@ -312,7 +313,7 @@ def test_infer_image_extension_defaults_to_jpg(): async def test_fetch_and_save_image_raises_when_memory_not_configured(): mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = None mock_memory.results_storage_io = None mock_serializer._memory = mock_memory @@ -333,7 +334,7 @@ async def test_fetch_and_save_image_raises_when_memory_not_configured(): async def test_fetch_and_save_image_returns_cached_path(): mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = "/results" mock_storage_io = AsyncMock() mock_storage_io.path_exists_async = AsyncMock(return_value=True) @@ -408,7 +409,7 @@ async def test_fetch_and_save_image_saves_pil_bytes_when_path_missing(tmp_path): from PIL import Image mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = str(tmp_path) mock_storage_io = AsyncMock() mock_storage_io.path_exists_async = AsyncMock(return_value=False) @@ -440,7 +441,7 @@ async def test_fetch_and_save_image_saves_pil_bytes_when_path_missing(tmp_path): async def test_fetch_and_save_image_falls_back_to_url_when_pil_unavailable(tmp_path): mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = str(tmp_path) mock_storage_io = AsyncMock() mock_storage_io.path_exists_async = AsyncMock(return_value=False) @@ -477,7 +478,7 @@ async def test_fetch_and_save_image_falls_back_to_url_when_pil_unavailable(tmp_p async def test_fetch_and_save_image_continues_when_path_exists_raises(tmp_path): mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = str(tmp_path) mock_storage_io = AsyncMock() mock_storage_io.path_exists_async = AsyncMock(side_effect=OSError("disk error")) diff --git a/tests/unit/datasets/test_visual_leak_bench_dataset.py b/tests/unit/datasets/test_visual_leak_bench_dataset.py index 37a1accb77..3d83c5833a 100644 --- a/tests/unit/datasets/test_visual_leak_bench_dataset.py +++ b/tests/unit/datasets/test_visual_leak_bench_dataset.py @@ -10,6 +10,7 @@ VisualLeakBenchPIIType, _VisualLeakBenchDataset, ) +from pyrit.memory import MemoryInterface from pyrit.models import SeedDataset @@ -339,7 +340,7 @@ async def test_fetch_and_save_image_returns_cached_path(): from unittest.mock import AsyncMock, MagicMock mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = "/results" mock_storage_io = AsyncMock() mock_storage_io.path_exists_async = AsyncMock(return_value=True) diff --git a/tests/unit/datasets/test_vlsu_multimodal_dataset.py b/tests/unit/datasets/test_vlsu_multimodal_dataset.py index 9a3c4bd783..13b1582f94 100644 --- a/tests/unit/datasets/test_vlsu_multimodal_dataset.py +++ b/tests/unit/datasets/test_vlsu_multimodal_dataset.py @@ -11,6 +11,7 @@ VLSUCategory, _VLSUMultimodalDataset, ) +from pyrit.memory import MemoryInterface from pyrit.memory.central_memory import CentralMemory from pyrit.models import SeedDataset @@ -22,7 +23,8 @@ class TestVLSUMultimodalDataset: def test_dataset_uses_isolated_memory_and_results_path(self): """Prove per-test database and results-directory isolation.""" memory = CentralMemory.get_memory_instance() - assert memory.engine.url.database == ":memory:" + assert memory.db_path == ":memory:" + assert memory.engine.url.query["mode"] == "memory" assert os.path.isabs(memory.results_path) assert "results" not in os.path.basename(memory.results_path) @@ -438,7 +440,7 @@ async def test_fetch_and_save_image_raises_when_memory_not_configured(): from unittest.mock import MagicMock mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = None mock_memory.results_storage_io = None mock_serializer._memory = mock_memory @@ -458,7 +460,7 @@ async def test_fetch_and_save_image_returns_cached_path(): from unittest.mock import AsyncMock, MagicMock mock_serializer = MagicMock() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = "/results" mock_storage_io = AsyncMock() mock_storage_io.path_exists_async = AsyncMock(return_value=True) diff --git a/tests/unit/executor/attack/component/test_adversarial_conversation_manager.py b/tests/unit/executor/attack/component/test_adversarial_conversation_manager.py index 9acd09c254..6ce9931248 100644 --- a/tests/unit/executor/attack/component/test_adversarial_conversation_manager.py +++ b/tests/unit/executor/attack/component/test_adversarial_conversation_manager.py @@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest +from unit.mocks import get_mock_prompt_normalizer from pyrit.exceptions import ( AdversarialChatRefusedException, @@ -41,7 +42,6 @@ SeedPrompt, get_common_json_schema, ) -from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import PromptTarget pytestmark = pytest.mark.usefixtures("patch_central_database") @@ -89,7 +89,7 @@ def _per_turn(value: str = "{{ feedback_text }}") -> SeedPrompt: def _normalizer(return_text: str | None) -> MagicMock: - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() response = None if return_text is None else Message.from_prompt(prompt=return_text, role="assistant") normalizer.send_prompt_async = AsyncMock(return_value=response) return normalizer @@ -462,7 +462,7 @@ def test_raises_on_invalid_next_message_type(self): class TestSetAdversarialSystemPrompt: - def test_renders_objective_and_max_turns_and_sets_on_conversation(self): + async def test_renders_objective_and_max_turns_and_sets_on_conversation(self): target = _target() manager = _manager( adversarial_target=target, @@ -471,16 +471,16 @@ def test_renders_objective_and_max_turns_and_sets_on_conversation(self): max_turns=7, conversation_id="conv-sys", ) - manager.set_adversarial_system_prompt() - target.set_system_prompt.assert_called_once() - kwargs = target.set_system_prompt.call_args.kwargs + (await manager.set_adversarial_system_prompt_async()) + target.set_system_prompt_async.assert_called_once() + kwargs = target.set_system_prompt_async.call_args.kwargs assert kwargs["system_prompt"] == "SYS obj=the goal turns=7" assert kwargs["conversation_id"] == "conv-sys" - def test_empty_rendered_system_prompt_raises(self): + async def test_empty_rendered_system_prompt_raises(self): manager = _manager(adversarial_system_prompt=_system_prompt("{{ objective }}"), objective="") with pytest.raises(ValueError, match="must be defined"): - manager.set_adversarial_system_prompt() + (await manager.set_adversarial_system_prompt_async()) # --- first-message rendering ------------------------------------------------- diff --git a/tests/unit/executor/attack/component/test_conversation_manager.py b/tests/unit/executor/attack/component/test_conversation_manager.py index 5af0262065..5070adde42 100644 --- a/tests/unit/executor/attack/component/test_conversation_manager.py +++ b/tests/unit/executor/attack/component/test_conversation_manager.py @@ -22,7 +22,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest -from unit.mocks import get_mock_scorer_identifier +from unit.mocks import get_mock_prompt_normalizer, get_mock_scorer_identifier from pyrit.converter import Base64Converter, Converter, ConverterResult from pyrit.executor.attack import ConversationManager, ConversationState @@ -101,7 +101,7 @@ def attack_identifier() -> ComponentIdentifier: @pytest.fixture def mock_prompt_normalizer() -> MagicMock: """Create a mock prompt normalizer for testing.""" - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.convert_values_async = AsyncMock() return normalizer @@ -110,7 +110,7 @@ def mock_prompt_normalizer() -> MagicMock: def mock_chat_target() -> MagicMock: """Create a mock chat target for testing.""" target = MagicMock(spec=PromptTarget) - target.set_system_prompt = MagicMock() + target.set_system_prompt_async = AsyncMock() target.get_identifier.return_value = _mock_target_id("MockChatTarget") target.capabilities.supports_multi_turn = True target.capabilities.supports_editable_history = True @@ -530,16 +530,18 @@ def test_init_with_custom_prompt_normalizer( class TestConversationRetrieval: """Tests for conversation retrieval methods.""" - def test_get_conversation_returns_empty_list_when_no_messages(self, attack_identifier: ComponentIdentifier) -> None: + async def test_get_conversation_returns_empty_list_when_no_messages( + self, attack_identifier: ComponentIdentifier + ) -> None: """Test get_conversation returns empty list for non-existent conversation.""" manager = ConversationManager() conversation_id = str(uuid.uuid4()) - result = manager.get_conversation(conversation_id) + result = await manager.get_conversation_async(conversation_id) assert result == [] - def test_get_conversation_returns_messages_in_order( + async def test_get_conversation_returns_messages_in_order( self, attack_identifier: ComponentIdentifier, sample_conversation: list[Message] ) -> None: """Test get_conversation returns messages in order.""" @@ -550,24 +552,26 @@ def test_get_conversation_returns_messages_in_order( for msg in sample_conversation: for piece in msg.message_pieces: piece.conversation_id = conversation_id - manager._memory.add_message_to_memory(request=msg) + (await manager._memory.add_message_to_memory_async(request=msg)) - result = manager.get_conversation(conversation_id) + result = await manager.get_conversation_async(conversation_id) assert len(result) == 2 assert result[0].message_pieces[0].api_role == "user" assert result[1].message_pieces[0].api_role == "assistant" - def test_get_last_message_returns_none_for_empty_conversation(self, attack_identifier: ComponentIdentifier) -> None: + async def test_get_last_message_returns_none_for_empty_conversation( + self, attack_identifier: ComponentIdentifier + ) -> None: """Test get_last_message returns None for empty conversation.""" manager = ConversationManager() conversation_id = str(uuid.uuid4()) - result = manager.get_last_message(conversation_id=conversation_id) + result = await manager.get_last_message_async(conversation_id=conversation_id) assert result is None - def test_get_last_message_returns_last_piece( + async def test_get_last_message_returns_last_piece( self, attack_identifier: ComponentIdentifier, sample_conversation: list[Message] ) -> None: """Test get_last_message returns the most recent message.""" @@ -578,14 +582,14 @@ def test_get_last_message_returns_last_piece( for msg in sample_conversation: for piece in msg.message_pieces: piece.conversation_id = conversation_id - manager._memory.add_message_to_memory(request=msg) + (await manager._memory.add_message_to_memory_async(request=msg)) - result = manager.get_last_message(conversation_id=conversation_id) + result = await manager.get_last_message_async(conversation_id=conversation_id) assert result is not None assert result.api_role == "assistant" - def test_get_last_message_with_role_filter( + async def test_get_last_message_with_role_filter( self, attack_identifier: ComponentIdentifier, sample_conversation: list[Message] ) -> None: """Test get_last_message with role filter returns correct message.""" @@ -596,15 +600,15 @@ def test_get_last_message_with_role_filter( for msg in sample_conversation: for piece in msg.message_pieces: piece.conversation_id = conversation_id - manager._memory.add_message_to_memory(request=msg) + (await manager._memory.add_message_to_memory_async(request=msg)) # Get last user message - result = manager.get_last_message(conversation_id=conversation_id, role="user") + result = await manager.get_last_message_async(conversation_id=conversation_id, role="user") assert result is not None assert result.api_role == "user" - def test_get_last_message_with_role_filter_returns_none_when_no_match( + async def test_get_last_message_with_role_filter_returns_none_when_no_match( self, attack_identifier: ComponentIdentifier, sample_conversation: list[Message] ) -> None: """Test get_last_message returns None when no message matches role filter.""" @@ -615,10 +619,10 @@ def test_get_last_message_with_role_filter_returns_none_when_no_match( for msg in sample_conversation: for piece in msg.message_pieces: piece.conversation_id = conversation_id - manager._memory.add_message_to_memory(request=msg) + (await manager._memory.add_message_to_memory_async(request=msg)) # Try to get system message when none exists - result = manager.get_last_message(conversation_id=conversation_id, role="system") + result = await manager.get_last_message_async(conversation_id=conversation_id, role="system") assert result is None @@ -632,7 +636,7 @@ def test_get_last_message_with_role_filter_returns_none_when_no_match( class TestSystemPromptHandling: """Tests for system prompt functionality.""" - def test_set_system_prompt_with_chat_target( + async def test_set_system_prompt_with_chat_target( self, attack_identifier: ComponentIdentifier, mock_chat_target: MagicMock ) -> None: """Test set_system_prompt calls target's set_system_prompt method.""" @@ -640,13 +644,15 @@ def test_set_system_prompt_with_chat_target( conversation_id = str(uuid.uuid4()) system_prompt = "You are a helpful assistant" - manager.set_system_prompt( - target=mock_chat_target, - conversation_id=conversation_id, - system_prompt=system_prompt, + ( + await manager.set_system_prompt_async( + target=mock_chat_target, + conversation_id=conversation_id, + system_prompt=system_prompt, + ) ) - mock_chat_target.set_system_prompt.assert_called_once_with( + mock_chat_target.set_system_prompt_async.assert_called_once_with( system_prompt=system_prompt, conversation_id=conversation_id, ) @@ -744,7 +750,7 @@ async def test_adds_prepended_conversation_to_memory_for_chat_target( ) # Verify messages were added to memory - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) assert len(stored) == 2 async def test_converts_assistant_to_simulated_assistant( @@ -765,7 +771,7 @@ async def test_converts_assistant_to_simulated_assistant( conversation_id=conversation_id, ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) assert len(stored) == 1 # Should be stored as simulated_assistant but api_role is still assistant assert stored[0].get_piece().role == "simulated_assistant" @@ -788,7 +794,7 @@ async def test_stores_prepended_conversation_for_non_editable_target( conversation_id=conversation_id, ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) assert len(stored) == 2 assert [message.api_role for message in stored] == ["user", "assistant"] assert stored[1].get_piece().role == "simulated_assistant" @@ -842,7 +848,7 @@ async def test_non_editable_target_persists_history_without_using_formatter( assert context.prepended_history_send_context is not None assert context.prepended_history_send_context.conversation_id == conversation_id - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) assert len(stored) == len(sample_conversation) assert context.prepended_history_send_context.seed_message_ids == tuple( message.get_piece().id for message in stored @@ -911,7 +917,7 @@ async def test_multipart_message_extracts_scores_from_all_pieces( # the pieces under the target conversation_id, keeping ``original_prompt_id`` # set to the input id (which is what ScoreEntry.prompt_request_response_id # points at), so the per-conversation score lookup resolves them. - manager._memory.add_message_pieces_to_memory(message_pieces=[piece1, piece2]) + (await manager._memory.add_message_pieces_to_memory_async(message_pieces=[piece1, piece2])) score1 = Score( score_type="true_false", score_value="false", @@ -932,7 +938,7 @@ async def test_multipart_message_extracts_scores_from_all_pieces( message_piece_id=str(piece2.id), scorer_class_identifier=get_mock_scorer_identifier(), ) - manager._memory.add_scores_to_memory(scores=[score1, score2]) + (await manager._memory.add_scores_to_memory_async(scores=[score1, score2])) multipart_response = Message(message_pieces=[piece1, piece2]) context.prepended_conversation = [ @@ -973,7 +979,7 @@ async def test_scores_come_only_from_the_last_assistant_turn( original_value="final reply", conversation_id=str(uuid.uuid4()), ) - manager._memory.add_message_pieces_to_memory(message_pieces=[early_piece, final_piece]) + (await manager._memory.add_message_pieces_to_memory_async(message_pieces=[early_piece, final_piece])) def _false_score(piece: MessagePiece, rationale: str) -> Score: return Score( @@ -989,7 +995,7 @@ def _false_score(piece: MessagePiece, rationale: str) -> Score: early_score = _false_score(early_piece, "early") final_score = _false_score(final_piece, "final") - manager._memory.add_scores_to_memory(scores=[early_score, final_score]) + (await manager._memory.add_scores_to_memory_async(scores=[early_score, final_score])) context.prepended_conversation = [ Message.from_prompt(prompt="first ask", role="user"), @@ -1041,7 +1047,7 @@ async def test_prepended_conversation_ignores_true_scores( # existence check. initialize_context_async will duplicate them under # the target conversation_id, preserving ``original_prompt_id`` so the # score lookup resolves the staged scores. - manager._memory.add_message_pieces_to_memory(message_pieces=[piece_with_true, piece_with_false]) + (await manager._memory.add_message_pieces_to_memory_async(message_pieces=[piece_with_true, piece_with_false])) # Create a score with true value - should be ignored true_score = Score( @@ -1067,7 +1073,7 @@ async def test_prepended_conversation_ignores_true_scores( scorer_class_identifier=get_mock_scorer_identifier(), ) - manager._memory.add_scores_to_memory(scores=[true_score, false_score]) + (await manager._memory.add_scores_to_memory_async(scores=[true_score, false_score])) # Test with true score only - should get no scores context.prepended_conversation = [ @@ -1134,7 +1140,7 @@ async def test_non_editable_target_converts_selected_roles_before_storage( request_converters=converter_config, ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) encoded_user = base64.b64encode(b"Hello, how are you?").decode() assert stored[0].get_piece().converted_value == encoded_user assert stored[1].get_piece().converted_value == "I'm doing well, thank you!" @@ -1162,7 +1168,7 @@ async def test_non_editable_target_converts_assistant_history_only_when_opted_in prepended_conversation_config=config, ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) encoded_assistant = base64.b64encode(b"I'm doing well, thank you!").decode() assert stored[0].get_piece().converted_value == "Hello, how are you?" assert stored[1].get_piece().converted_value == encoded_assistant @@ -1242,7 +1248,7 @@ async def test_prepended_conversion_failure_does_not_partially_write_history( prepended_conversation_config=config, ) - assert manager.get_conversation(conversation_id) == [] + assert (await manager.get_conversation_async(conversation_id)) == [] async def test_non_persisted_prepended_message_is_not_counted_in_context( self, @@ -1266,7 +1272,7 @@ async def test_non_persisted_prepended_message_is_not_counted_in_context( conversation_id=conversation_id, ) - assert manager.get_conversation(conversation_id) == [] + assert (await manager.get_conversation_async(conversation_id)) == [] async def test_non_persisted_piece_does_not_constrain_flattening( self, @@ -1309,7 +1315,7 @@ async def test_non_persisted_piece_does_not_constrain_flattening( ], ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) assert len(stored) == 1 assert [piece.converted_value for piece in stored[0].message_pieces] == ["persisted"] @@ -1354,7 +1360,7 @@ async def test_non_editable_target_preserves_converter_piece_indexes( request_converters=converter_config, ) - stored_pieces = manager.get_conversation(conversation_id)[0].message_pieces + stored_pieces = (await manager.get_conversation_async(conversation_id))[0].message_pieces assert stored_pieces[0].converted_value == base64.b64encode(b"first piece").decode() assert stored_pieces[1].converted_value == "second piece" @@ -1369,7 +1375,7 @@ async def test_apply_converters_to_roles_default_applies_to_user_only( sample_conversation: list[Message], ) -> None: """Test that converters are applied only to user history by default.""" - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.convert_values_async = AsyncMock() manager = ConversationManager(prompt_normalizer=mock_normalizer) conversation_id = str(uuid.uuid4()) @@ -1394,7 +1400,7 @@ async def test_apply_converters_to_roles_user_only( sample_conversation: list[Message], ) -> None: """Test that converters are applied only to user role when configured.""" - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.convert_values_async = AsyncMock() manager = ConversationManager(prompt_normalizer=mock_normalizer) conversation_id = str(uuid.uuid4()) @@ -1422,7 +1428,7 @@ async def test_apply_converters_to_roles_assistant_only( sample_conversation: list[Message], ) -> None: """Test that converters are applied only to assistant role when configured.""" - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.convert_values_async = AsyncMock() manager = ConversationManager(prompt_normalizer=mock_normalizer) conversation_id = str(uuid.uuid4()) @@ -1450,7 +1456,7 @@ async def test_apply_converters_to_roles_empty_list_skips_all( sample_conversation: list[Message], ) -> None: """Test that empty roles list means no converters applied to any role.""" - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.convert_values_async = AsyncMock() manager = ConversationManager(prompt_normalizer=mock_normalizer) conversation_id = str(uuid.uuid4()) @@ -1541,7 +1547,7 @@ async def test_chat_target_adds_prepended_conversation( ) # Should succeed and add to memory - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) assert len(stored) == 2 assert state.turn_count == 1 @@ -1612,7 +1618,7 @@ async def test_adds_messages_to_memory( conversation_id=conversation_id, ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) assert len(stored) == 2 assert turn_count == 1 # One assistant message @@ -1630,7 +1636,7 @@ async def test_assigns_conversation_id_to_all_pieces( conversation_id=conversation_id, ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) for msg in stored: for piece in msg.message_pieces: assert piece.conversation_id == conversation_id @@ -1779,7 +1785,7 @@ async def test_preserves_piece_metadata( conversation_id=conversation_id, ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) assert len(stored) == 1 processed_piece = stored[0].message_pieces[0] assert processed_piece.prompt_metadata == { @@ -1810,7 +1816,7 @@ async def test_preserves_original_and_converted_values( conversation_id=conversation_id, ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) assert len(stored) == 1 stored_piece = stored[0].get_piece() assert stored_piece.original_value == "Original message" @@ -1838,7 +1844,7 @@ async def test_handles_system_messages_in_prepended_conversation( conversation_id=conversation_id, ) - stored = manager.get_conversation(conversation_id) + stored = await manager.get_conversation_async(conversation_id) # Both system and user messages should be stored assert len(stored) == 2 assert stored[0].get_piece().api_role == "system" diff --git a/tests/unit/executor/attack/component/test_prepended_conversation_config.py b/tests/unit/executor/attack/component/test_prepended_conversation_config.py index 2316877388..ef97cbb767 100644 --- a/tests/unit/executor/attack/component/test_prepended_conversation_config.py +++ b/tests/unit/executor/attack/component/test_prepended_conversation_config.py @@ -2,7 +2,8 @@ # Licensed under the MIT license. from typing import get_type_hints -from unittest.mock import MagicMock + +from unit.mocks import get_mock_prompt_normalizer from pyrit.executor.attack.component.prepended_conversation_config import PrependedConversationConfig from pyrit.message_normalizer import ConversationContextNormalizer @@ -35,6 +36,6 @@ def test_get_message_normalizer_returns_default_when_none(): def test_get_message_normalizer_returns_custom(): - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() config = PrependedConversationConfig(message_normalizer=mock_normalizer) assert config.get_message_normalizer() is mock_normalizer diff --git a/tests/unit/executor/attack/component/test_simulated_conversation.py b/tests/unit/executor/attack/component/test_simulated_conversation.py index ee3316b531..0937412d1c 100644 --- a/tests/unit/executor/attack/component/test_simulated_conversation.py +++ b/tests/unit/executor/attack/component/test_simulated_conversation.py @@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +from unit.mocks import get_mock_prompt_normalizer from pyrit.exceptions import AdversarialChatResponseBlockedException, InvalidJsonException from pyrit.executor.attack import AttackConverterConfig, RTASystemPromptPaths @@ -19,6 +20,7 @@ _generate_next_message_async, generate_simulated_conversation_async, ) +from pyrit.memory import MemoryInterface from pyrit.models import ( AttackOutcome, AttackResult, @@ -33,7 +35,6 @@ SimulatedTargetSystemPromptPaths, load_next_message_prompt, ) -from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import PromptTarget from pyrit.score import TrueFalseScorer @@ -59,7 +60,7 @@ def mock_adversarial_chat() -> MagicMock: """Create a mock adversarial chat target for testing.""" chat = MagicMock(spec=PromptTarget) chat.send_prompt_async = AsyncMock() - chat.set_system_prompt = MagicMock() + chat.set_system_prompt_async = AsyncMock() chat.get_identifier.return_value = _mock_target_id("MockAdversarialChat") return chat @@ -190,8 +191,8 @@ async def test_deprecated_system_prompt_path_still_resolves_and_warns( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory with pytest.warns(DeprecationWarning, match="removed in 1.4.0"): @@ -236,8 +237,8 @@ async def test_uses_adversarial_chat_as_simulated_target( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory await generate_simulated_conversation_async( @@ -280,8 +281,8 @@ async def test_passes_system_prompt_to_adversarial_config( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory await generate_simulated_conversation_async( @@ -327,8 +328,8 @@ async def test_creates_attack_with_score_last_turn_only_true( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory await generate_simulated_conversation_async( @@ -370,8 +371,8 @@ async def test_creates_attack_with_correct_max_turns( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory await generate_simulated_conversation_async( @@ -417,8 +418,8 @@ async def test_returns_simulated_conversation_result( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory result = await generate_simulated_conversation_async( @@ -430,7 +431,7 @@ async def test_returns_simulated_conversation_result( ) # Verify get_conversation_messages was called with the correct conversation_id - mock_memory.get_conversation_messages.assert_called_once_with(conversation_id=conversation_id) + mock_memory.get_conversation_messages_async.assert_called_once_with(conversation_id=conversation_id) assert isinstance(result, SimulatedConversationResult) assert len(result.seed_prompts) == len(sample_conversation) @@ -464,8 +465,8 @@ async def test_passes_system_prompt_via_prepended_conversation( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory # Pass a simulated_target_system_prompt_path to test prepending behavior @@ -515,8 +516,8 @@ async def test_passes_memory_labels_to_execute( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory await generate_simulated_conversation_async( @@ -561,8 +562,8 @@ async def test_returns_preparation_and_adversarial_references( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory result = await generate_simulated_conversation_async( @@ -616,8 +617,8 @@ async def test_adversarial_block_is_returned_as_preparation_failure( ) ) mock_attack_class.return_value = mock_attack - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter([]) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async.return_value = [] mock_memory_class.get_memory_instance.return_value = mock_memory result = await generate_simulated_conversation_async( @@ -668,8 +669,8 @@ async def test_adversarial_block_without_outcome_reason_still_reports_a_reason( ) ) mock_attack_class.return_value = mock_attack - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter([]) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async.return_value = [] mock_memory_class.get_memory_instance.return_value = mock_memory result = await generate_simulated_conversation_async( @@ -714,8 +715,8 @@ async def test_final_prompt_block_is_returned_as_preparation_failure( ) ) mock_attack_class.return_value = mock_attack - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async.return_value = sample_conversation mock_memory_class.get_memory_instance.return_value = mock_memory result = await generate_simulated_conversation_async( @@ -762,8 +763,8 @@ async def test_passes_converter_config_to_attack( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory await generate_simulated_conversation_async( @@ -806,8 +807,8 @@ async def test_prepends_system_message_to_conversation( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory # Pass a simulated_target_system_prompt_path to test prepending behavior @@ -854,8 +855,8 @@ async def test_uses_default_num_turns_of_3( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory # Call without specifying num_turns @@ -918,12 +919,12 @@ async def test_next_message_system_prompt_path_generates_final_user_message( "pyrit.executor.attack.multi_turn.simulated_conversation.PromptNormalizer" ) as mock_normalizer_class, ): - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory # The manager sends the adversarial turn through this normalizer. - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=next_message_reply) mock_normalizer_class.return_value = mock_normalizer @@ -1001,11 +1002,11 @@ async def test_next_message_system_prompt_path_sets_system_prompt( "pyrit.executor.attack.multi_turn.simulated_conversation.PromptNormalizer" ) as mock_normalizer_class, ): - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=next_message_reply) mock_normalizer_class.return_value = mock_normalizer @@ -1019,7 +1020,7 @@ async def test_next_message_system_prompt_path_sets_system_prompt( ) # The manager renders and sets the adversarial system prompt before sending. - mock_adversarial_chat.set_system_prompt.assert_called() + mock_adversarial_chat.set_system_prompt_async.assert_called() async def test_next_message_scopes_system_prompt_to_generated_message_conversation( self, @@ -1073,11 +1074,11 @@ async def test_next_message_scopes_system_prompt_to_generated_message_conversati "pyrit.executor.attack.multi_turn.simulated_conversation.PromptNormalizer" ) as mock_normalizer_class, ): - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=next_message_reply) mock_normalizer_class.return_value = mock_normalizer @@ -1090,7 +1091,7 @@ async def test_next_message_scopes_system_prompt_to_generated_message_conversati next_message_system_prompt_path=NextMessageSystemPromptPaths.DIRECT.value, ) - system_prompt_conversation_id = mock_adversarial_chat.set_system_prompt.call_args.kwargs[ + system_prompt_conversation_id = mock_adversarial_chat.set_system_prompt_async.call_args.kwargs[ "conversation_id" ] assert system_prompt_conversation_id @@ -1129,8 +1130,8 @@ async def test_starting_sequence_sets_first_sequence_number( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory result = await generate_simulated_conversation_async( @@ -1153,7 +1154,7 @@ class TestGenerateNextMessageAsync: @staticmethod def _mock_normalizer(reply: Message | None) -> MagicMock: - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock(return_value=reply) return normalizer @@ -1190,7 +1191,7 @@ async def test_parses_next_message_from_json_reply(self, mock_adversarial_chat: assert result.message_pieces[0].role == "user" assert normalizer.send_prompt_async.call_args.kwargs["conversation_id"] == "next-message-conversation" # The manager renders and sets the adversarial system prompt before sending. - mock_adversarial_chat.set_system_prompt.assert_called_once() + mock_adversarial_chat.set_system_prompt_async.assert_called_once() # The canonical schema is always resolved and forwarded so schema-aware targets constrain output. sent_message = normalizer.send_prompt_async.call_args.kwargs["message"] assert sent_message.message_pieces[0].prompt_metadata.get("response_format") == "json" @@ -1273,8 +1274,8 @@ async def test_canonical_prompts_never_read_from_disk( mock_attack_class.return_value = self._mock_attack(str(uuid.uuid4())) with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory with patch("pyrit.models.seeds.yaml_seed_loader.load_seed_from_yaml") as mock_load: @@ -1304,8 +1305,8 @@ async def test_simulated_target_prompt_is_rendered_into_system_message( mock_attack_class.return_value = mock_attack with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory await generate_simulated_conversation_async( @@ -1335,8 +1336,8 @@ async def test_deprecated_path_input_warns( mock_attack_class.return_value = self._mock_attack(str(uuid.uuid4())) with patch("pyrit.executor.attack.multi_turn.simulated_conversation.CentralMemory") as mock_memory_class: - mock_memory = MagicMock() - mock_memory.get_conversation_messages.return_value = iter(sample_conversation) + mock_memory = MagicMock(spec=MemoryInterface) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=iter(sample_conversation)) mock_memory_class.get_memory_instance.return_value = mock_memory with pytest.warns(DeprecationWarning, match="adversarial_chat_system_prompt_path"): diff --git a/tests/unit/executor/attack/core/test_attack_scoring.py b/tests/unit/executor/attack/core/test_attack_scoring.py index a678daeb84..23498b13ff 100644 --- a/tests/unit/executor/attack/core/test_attack_scoring.py +++ b/tests/unit/executor/attack/core/test_attack_scoring.py @@ -72,9 +72,9 @@ def _expectation() -> ScoringExpectation: return ScoringExpectation(objective="context", conditions=(_FirstCondition(), _SecondCondition())) -def _stored_response(memory: MemoryInterface) -> Message: +async def _stored_response_async(memory: MemoryInterface) -> Message: response = MessagePiece(role="assistant", original_value="response", conversation_id=str(uuid.uuid4())).to_message() - memory.add_message_to_memory(request=response) + (await memory.add_message_to_memory_async(request=response)) return response @@ -148,7 +148,7 @@ async def test_objective_and_auxiliary_receive_their_own_inputs_async(sqlite_ins expectation = _expectation() results = await score_attack_response_async( - response=_stored_response(sqlite_instance), + response=(await _stored_response_async(sqlite_instance)), objective_scorer=objective, auxiliary_scorers=[auxiliary], expectation=expectation, @@ -169,7 +169,7 @@ async def test_selected_auxiliary_failure_is_not_suppressed_async(sqlite_instanc pytest.raises(Exception, match="diagnostic failed"), ): await score_attack_response_async( - response=_stored_response(sqlite_instance), + response=(await _stored_response_async(sqlite_instance)), objective_scorer=_FirstScorer(), auxiliary_scorers=[auxiliary], expectation=ScoringExpectation(conditions=(_FirstCondition(),)), diff --git a/tests/unit/executor/attack/core/test_attack_strategy.py b/tests/unit/executor/attack/core/test_attack_strategy.py index 2be788b70d..3717c1fc1e 100644 --- a/tests/unit/executor/attack/core/test_attack_strategy.py +++ b/tests/unit/executor/attack/core/test_attack_strategy.py @@ -65,7 +65,7 @@ def test_attack_outcome_from_score(score: Score, expected: AttackOutcome): def mock_memory(): """Mock CentralMemory instance""" memory = MagicMock(spec=CentralMemory) - memory.add_attack_results_to_memory = MagicMock() + memory.add_attack_results_to_memory_async = AsyncMock() return memory @@ -407,7 +407,7 @@ async def test_execute_async_allows_optional_parameters_as_none(self, mock_attac async def test_execute_async_can_skip_completed_result_persistence(self, mock_attack_strategy): """A transient helper attack returns its result without creating a history row.""" - with patch.object(mock_attack_strategy._default_event_handler, "_persist_result") as persist: + with patch.object(mock_attack_strategy._default_event_handler, "_persist_result_async") as persist: result = await mock_attack_strategy.execute_async( objective="Test objective", persist_attack_result=False, @@ -426,7 +426,7 @@ async def test_execute_async_can_skip_error_result_persistence(self, mock_attack new_callable=AsyncMock, side_effect=RuntimeError("helper failed"), ), - patch.object(memory, "add_attack_results_to_memory") as persist, + patch.object(memory, "add_attack_results_to_memory_async") as persist, pytest.raises(RuntimeError), ): await mock_attack_strategy.execute_async( @@ -623,7 +623,7 @@ async def test_on_post_execute_does_not_persist_result(self, mock_memory): with patch("time.perf_counter", return_value=100.1): await handler.on_event_async(event_data) - mock_memory.add_attack_results_to_memory.assert_not_called() + mock_memory.add_attack_results_to_memory_async.assert_not_called() async def test_on_post_execute_raises_on_none_result(self, event_handler, sample_attack_context, mock_logger): """Test that post-execute handler raises error for None result""" @@ -735,7 +735,7 @@ async def test_on_error_attaches_retry_events(self, sample_attack_context, mock_ ) await handler.on_event_async(event_data) - stored_result = mock_memory.add_attack_results_to_memory.call_args.kwargs["attack_results"][0] + stored_result = mock_memory.add_attack_results_to_memory_async.call_args.kwargs["attack_results"][0] assert stored_result.outcome == AttackOutcome.ERROR assert stored_result.retry_events == [retry_event] assert stored_result.total_retries == 1 @@ -757,7 +757,7 @@ async def test_on_error_empty_retry_events_when_no_collector(self, sample_attack ) await handler.on_event_async(event_data) - stored_result = mock_memory.add_attack_results_to_memory.call_args.kwargs["attack_results"][0] + stored_result = mock_memory.add_attack_results_to_memory_async.call_args.kwargs["attack_results"][0] assert stored_result.retry_events == [] assert stored_result.total_retries == 0 @@ -780,8 +780,8 @@ async def test_on_error_persists_result_to_memory(self, sample_attack_context, m with patch("time.perf_counter", return_value=100.5): await handler.on_event_async(event_data) - mock_memory.add_attack_results_to_memory.assert_called_once() - stored_result = mock_memory.add_attack_results_to_memory.call_args.kwargs["attack_results"][0] + mock_memory.add_attack_results_to_memory_async.assert_called_once() + stored_result = mock_memory.add_attack_results_to_memory_async.call_args.kwargs["attack_results"][0] assert stored_result.outcome == AttackOutcome.ERROR assert stored_result.error_message == "something broke" assert stored_result.error_type == "ValueError" @@ -805,7 +805,7 @@ async def test_on_error_uses_multi_turn_session_conversation_id(self, mock_memor ) await handler.on_event_async(event_data) - stored_result = mock_memory.add_attack_results_to_memory.call_args.kwargs["attack_results"][0] + stored_result = mock_memory.add_attack_results_to_memory_async.call_args.kwargs["attack_results"][0] assert stored_result.conversation_id == "active-conversation-id" async def test_on_error_uses_tap_best_conversation_id(self, mock_memory): @@ -827,7 +827,7 @@ async def test_on_error_uses_tap_best_conversation_id(self, mock_memory): ) await handler.on_event_async(event_data) - stored_result = mock_memory.add_attack_results_to_memory.call_args.kwargs["attack_results"][0] + stored_result = mock_memory.add_attack_results_to_memory_async.call_args.kwargs["attack_results"][0] assert stored_result.conversation_id == "best-conversation-id" async def test_on_error_skips_when_no_error_or_context(self, mock_memory): @@ -843,7 +843,7 @@ async def test_on_error_skips_when_no_error_or_context(self, mock_memory): error=RuntimeError("test"), ) await handler.on_event_async(event_data) - mock_memory.add_attack_results_to_memory.assert_not_called() + mock_memory.add_attack_results_to_memory_async.assert_not_called() async def test_on_event_handles_other_events(self, event_handler, sample_attack_context, mock_logger): """Test that on_event_async handles events not in the specific handlers""" @@ -938,7 +938,7 @@ async def test_on_error_stamps_scenario_attribution_when_present(self, sample_at await handler.on_event_async(event_data) # The error AttackResult was persisted; inspect what was sent to memory. - call = mock_memory.add_attack_results_to_memory.call_args + call = mock_memory.add_attack_results_to_memory_async.call_args persisted = call.kwargs["attack_results"][0] assert persisted.outcome == AttackOutcome.ERROR assert persisted.attribution_parent_id == "scenario-err" @@ -1016,7 +1016,7 @@ class TestAttackContext(AttackContext): ) await handler.on_event_async(event_data) - call = mock_memory.add_attack_results_to_memory.call_args + call = mock_memory.add_attack_results_to_memory_async.call_args persisted = call.kwargs["attack_results"][0] assert persisted.outcome == AttackOutcome.ERROR assert persisted.targeted_harm_categories == ["self_harm"] @@ -1092,7 +1092,7 @@ async def _teardown_async(self, *, context: AttackContext) -> None: with ( patch.object( memory, - "add_attack_results_to_memory", + "add_attack_results_to_memory_async", side_effect=RuntimeError("database unavailable"), ) as persist, pytest.raises(RuntimeError, match="database unavailable"), @@ -1101,7 +1101,7 @@ async def _teardown_async(self, *, context: AttackContext) -> None: assert teardown_calls == 1 persist.assert_called_once() - assert memory.get_attack_results(objective="Test objective") == [] + assert (await memory.get_attack_results_async(objective="Test objective")) == [] async def test_partial_persistence_failure_does_not_create_error_result( self, mock_objective_target: PromptTarget @@ -1126,20 +1126,22 @@ async def _teardown_async(self, *, context: AttackContext) -> None: strategy = TestStrategy(context_type=AttackContext, objective_target=mock_objective_target) memory = CentralMemory.get_memory_instance() - persist = memory.add_attack_results_to_memory + persist = memory.add_attack_results_to_memory_async - def persist_then_fail(*, attack_results: list[AttackResult]) -> None: - persist(attack_results=attack_results) + async def persist_then_fail_async(*, attack_results: list[AttackResult]) -> None: + await persist(attack_results=attack_results) raise RuntimeError("commit acknowledgement lost") with ( - patch.object(memory, "add_attack_results_to_memory", side_effect=persist_then_fail) as persist_mock, + patch.object( + memory, "add_attack_results_to_memory_async", side_effect=persist_then_fail_async + ) as persist_mock, pytest.raises(RuntimeError, match="commit acknowledgement lost"), ): await strategy.execute_async(objective="Test objective") persist_mock.assert_called_once() - [stored_result] = memory.get_attack_results(objective="Test objective") + [stored_result] = await memory.get_attack_results_async(objective="Test objective") assert stored_result.outcome is AttackOutcome.SUCCESS async def test_teardown_failure_persists_only_error_result(self, mock_objective_target: PromptTarget) -> None: @@ -1169,7 +1171,7 @@ async def _teardown_async(self, *, context: AttackContext) -> None: assert isinstance(exc_info.value.__cause__, RuntimeError) assert str(exc_info.value.__cause__) == "teardown failed" - [stored_result] = memory.get_attack_results(objective="Test objective") + [stored_result] = await memory.get_attack_results_async(objective="Test objective") assert stored_result.outcome is AttackOutcome.ERROR assert stored_result.error_message == "teardown failed" @@ -1196,7 +1198,7 @@ async def _teardown_async(self, *, context: AttackContext) -> None: memory = CentralMemory.get_memory_instance() with ( - patch.object(memory, "add_attack_results_to_memory", side_effect=persistence_error) as persist, + patch.object(memory, "add_attack_results_to_memory_async", side_effect=persistence_error) as persist, pytest.raises(ExceptionGroup, match="Attack execution and error result persistence failed") as exc_info, ): await strategy.execute_async(objective="Test objective") @@ -1205,7 +1207,7 @@ async def _teardown_async(self, *, context: AttackContext) -> None: attack_error, recorded_persistence_error = exc_info.value.exceptions assert attack_error.__cause__ is attack_cause assert recorded_persistence_error is persistence_error - assert memory.get_attack_results(objective="Test objective") == [] + assert (await memory.get_attack_results_async(objective="Test objective")) == [] async def test_partial_error_result_persistence_failure_does_not_retry( self, mock_objective_target: PromptTarget @@ -1225,21 +1227,23 @@ async def _teardown_async(self, *, context: AttackContext) -> None: strategy = TestStrategy(context_type=AttackContext, objective_target=mock_objective_target) memory = CentralMemory.get_memory_instance() - persist = memory.add_attack_results_to_memory + persist = memory.add_attack_results_to_memory_async - def persist_then_fail(*, attack_results: list[AttackResult]) -> None: - persist(attack_results=attack_results) + async def persist_then_fail_async(*, attack_results: list[AttackResult]) -> None: + await persist(attack_results=attack_results) raise RuntimeError("commit acknowledgement lost") with ( - patch.object(memory, "add_attack_results_to_memory", side_effect=persist_then_fail) as persist_mock, + patch.object( + memory, "add_attack_results_to_memory_async", side_effect=persist_then_fail_async + ) as persist_mock, pytest.raises(ExceptionGroup) as exc_info, ): await strategy.execute_async(objective="Test objective") persist_mock.assert_called_once() assert str(exc_info.value.exceptions[1]) == "commit acknowledgement lost" - [stored_result] = memory.get_attack_results(objective="Test objective") + [stored_result] = await memory.get_attack_results_async(objective="Test objective") assert stored_result.outcome is AttackOutcome.ERROR assert stored_result.error_message == "attack failed" diff --git a/tests/unit/executor/attack/multi_turn/test_chunked_request.py b/tests/unit/executor/attack/multi_turn/test_chunked_request.py index 106499dbbe..1f6b88f690 100644 --- a/tests/unit/executor/attack/multi_turn/test_chunked_request.py +++ b/tests/unit/executor/attack/multi_turn/test_chunked_request.py @@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest +from unit.mocks import get_mock_prompt_normalizer from pyrit.executor.attack.component import PrependedConversationConfig from pyrit.executor.attack.component.prepended_history_send_context import ( @@ -21,7 +22,6 @@ ) from pyrit.message_normalizer import HistorySquashNormalizer, MessageStringNormalizer from pyrit.models import ComponentIdentifier, Message, MessagePiece -from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import ( CapabilityName, PromptTarget, @@ -271,7 +271,7 @@ class TestChunkedRequestAttackExecution: async def test_perform_async_forwards_prepended_formatter_override(self): mock_target = _make_mock_target() mock_target.configuration = TargetConfiguration(capabilities=TargetCapabilities(supports_multi_turn=True)) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock( return_value=Message.from_prompt(prompt="chunk response", role="assistant") ) @@ -303,7 +303,7 @@ async def test_perform_async_forwards_prepended_formatter_override(self): async def test_perform_async_sets_atomic_attack_identifier(self): """Test that _perform_async sets atomic_attack_identifier in the correct AtomicAttack format.""" mock_target = _make_mock_target() - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() sample_response = Message( message_pieces=[ MessagePiece(role="assistant", original_value="chunk response", original_value_data_type="text") diff --git a/tests/unit/executor/attack/multi_turn/test_crescendo.py b/tests/unit/executor/attack/multi_turn/test_crescendo.py index 9b0740fb90..799708408c 100644 --- a/tests/unit/executor/attack/multi_turn/test_crescendo.py +++ b/tests/unit/executor/attack/multi_turn/test_crescendo.py @@ -8,6 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +from unit.mocks import get_mock_prompt_normalizer from pyrit.common.path import EXECUTOR_SEED_PROMPT_PATH from pyrit.executor.attack import ( @@ -21,6 +22,7 @@ CrescendoAttackContext, CrescendoAttackResult, ) +from pyrit.memory import MemoryInterface from pyrit.models import ( JSON_SCHEMA_METADATA_KEY, AttackOutcome, @@ -33,7 +35,6 @@ ScoreType, SeedPrompt, ) -from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import PromptTarget from pyrit.score import FloatScaleThresholdScorer, SelfAskRefusalScorer, TrueFalseScorer from pyrit.score.score_utils import ORIGINAL_FLOAT_VALUE_KEY @@ -63,7 +64,7 @@ def create_mock_chat_target(*, name: str = "MockChatTarget") -> MagicMock: """ target = MagicMock(spec=PromptTarget) target.send_prompt_async = AsyncMock() - target.set_system_prompt = MagicMock() + target.set_system_prompt_async = AsyncMock() target.get_identifier.return_value = _mock_target_id(name) # Sensible default for the _ModalityFeedbackRouter: text-only target. Tests # that need multimodal behavior override input_modalities on their own copy. @@ -181,7 +182,7 @@ def mock_refusal_scorer() -> MagicMock: @pytest.fixture def mock_prompt_normalizer() -> MagicMock: - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock() return normalizer @@ -307,7 +308,7 @@ def create_attack( @staticmethod def mock_memory_for_attack(attack: CrescendoAttack) -> MagicMock: - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) attack._memory = mock_memory return mock_memory @@ -705,8 +706,8 @@ async def test_setup_sets_adversarial_chat_system_prompt( await attack._setup_async(context=basic_context) # Verify system prompt was set - mock_adversarial_chat.set_system_prompt.assert_called_once() - call_args = mock_adversarial_chat.set_system_prompt.call_args + mock_adversarial_chat.set_system_prompt_async.assert_called_once() + call_args = mock_adversarial_chat.set_system_prompt_async.call_args assert "Test objective" in call_args.kwargs["system_prompt"] assert "15" in call_args.kwargs["system_prompt"] # Check for the max_turns value assert call_args.kwargs["conversation_id"] == basic_context.session.adversarial_chat_conversation_id @@ -2278,7 +2279,7 @@ async def test_execute_with_context_async_successful_lifecycle( attack_adversarial_config=adversarial_config, ) - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) attack._memory = mock_memory # Mock all lifecycle methods @@ -2725,7 +2726,7 @@ async def initialize_context_async( # Verify contexts remain independent # Each should maintain its own state without interference assert setup_started == {"Objective 1", "Objective 2"} - calls = mock_adversarial_chat.set_system_prompt.call_args_list + calls = mock_adversarial_chat.set_system_prompt_async.call_args_list assert len(calls) == 2 actual = {(call.kwargs["conversation_id"], call.kwargs["system_prompt"]) for call in calls} assert any( diff --git a/tests/unit/executor/attack/multi_turn/test_crescendo_resilience.py b/tests/unit/executor/attack/multi_turn/test_crescendo_resilience.py index e374ac9b7a..d2734ed05b 100644 --- a/tests/unit/executor/attack/multi_turn/test_crescendo_resilience.py +++ b/tests/unit/executor/attack/multi_turn/test_crescendo_resilience.py @@ -356,7 +356,7 @@ async def score_objective(**_kwargs): assert related_by_type[ConversationType.ADVERSARIAL] == {adversarial_target.attempts[0].conversation_id} memory = attack._memory - final_pieces = memory.get_message_pieces(conversation_id=final_conversation_id) + final_pieces = await memory.get_message_pieces_async(conversation_id=final_conversation_id) assert len(final_pieces) == 20 assert len({piece.id for piece in final_pieces}) == 20 assert [piece.original_value for piece in final_pieces if piece.api_role == "user"] == [ @@ -379,7 +379,7 @@ async def score_objective(**_kwargs): ] adversarial_conversation_id = adversarial_target.attempts[0].conversation_id - adversarial_pieces = memory.get_message_pieces(conversation_id=adversarial_conversation_id) + adversarial_pieces = await memory.get_message_pieces_async(conversation_id=adversarial_conversation_id) assert len(adversarial_pieces) == 25 assert partial_adversarial_reply not in {piece.original_value for piece in adversarial_pieces} adversarial_conversation = memory._get_conversation(conversation_id=adversarial_conversation_id) @@ -391,7 +391,7 @@ async def score_objective(**_kwargs): "InvalidJsonException", "RateLimitException", } - stored_results = memory.get_attack_results(objective=_OBJECTIVE) + stored_results = await memory.get_attack_results_async(objective=_OBJECTIVE) assert len(stored_results) == 1 assert stored_results[0].outcome is AttackOutcome.SUCCESS assert stored_results[0].executed_turns == 10 @@ -558,7 +558,9 @@ async def test_accepted_text_response_consumes_seed_before_followup(self, tmp_pa _OBJECTIVE, ] - objective_pieces = attack._memory.get_message_pieces(conversation_id=context.session.conversation_id) + objective_pieces = await attack._memory.get_message_pieces_async( + conversation_id=context.session.conversation_id + ) assert [ (piece.api_role, piece.original_value, piece.original_value_data_type) for piece in objective_pieces ] == [ @@ -581,7 +583,7 @@ async def test_accepted_text_response_consumes_seed_before_followup(self, tmp_pa assert context.refused_text is None assert context.last_accepted_response is not None assert context.last_accepted_response.get_value() == "final text response" - stored_results = attack._memory.get_attack_results(objective=_OBJECTIVE) + stored_results = await attack._memory.get_attack_results_async(objective=_OBJECTIVE) assert len(stored_results) == 1 assert stored_results[0].outcome is AttackOutcome.SUCCESS assert stored_results[0].conversation_id == context.session.conversation_id @@ -736,7 +738,7 @@ async def test_first_turn_content_filter_retries_seed_then_consumes_it(self, tmp _OBJECTIVE, ] - pruned_pieces = attack._memory.get_message_pieces(conversation_id=first_conversation_id) + pruned_pieces = await attack._memory.get_message_pieces_async(conversation_id=first_conversation_id) assert [ (piece.api_role, piece.original_value, piece.original_value_data_type, piece.response_error) for piece in pruned_pieces @@ -745,7 +747,7 @@ async def test_first_turn_content_filter_retries_seed_then_consumes_it(self, tmp ("user", seed_value, "image_path", "none"), ("assistant", "first response content filtered", "error", "blocked"), ] - final_pieces = attack._memory.get_message_pieces(conversation_id=retry_conversation_id) + final_pieces = await attack._memory.get_message_pieces_async(conversation_id=retry_conversation_id) assert [(piece.api_role, piece.original_value, piece.original_value_data_type) for piece in final_pieces] == [ ("user", "question-2", "text"), ("user", seed_value, "image_path"), @@ -808,12 +810,12 @@ async def test_refusal_scorer_failure_aborts_before_objective_scoring_and_persis refusal_scorer.score_async.assert_awaited_once() score_response.assert_not_awaited() - pieces = attack._memory.get_message_pieces(conversation_id=context.session.conversation_id) + pieces = await attack._memory.get_message_pieces_async(conversation_id=context.session.conversation_id) assert [piece.api_role for piece in pieces] == ["user", "assistant"] assert [piece.original_value for piece in pieces] == ["question-1", "response-1"] assert len({piece.id for piece in pieces}) == 2 - stored_results = attack._memory.get_attack_results(objective=_OBJECTIVE) + stored_results = await attack._memory.get_attack_results_async(objective=_OBJECTIVE) assert len(stored_results) == 1 assert stored_results[0].outcome is AttackOutcome.ERROR assert stored_results[0].error_type == "RuntimeError" @@ -869,7 +871,7 @@ async def test_objective_scorer_failure_persists_partial_history_and_one_error_r assert context.executed_turns == 4 assert score_response.await_count == 5 assert refusal_scorer.score_async.await_count == 5 - partial_pieces = attack._memory.get_message_pieces(conversation_id=context.session.conversation_id) + partial_pieces = await attack._memory.get_message_pieces_async(conversation_id=context.session.conversation_id) assert len(partial_pieces) == 10 assert [piece.original_value for piece in partial_pieces if piece.api_role == "assistant"] == [ "response-1", @@ -878,7 +880,7 @@ async def test_objective_scorer_failure_persists_partial_history_and_one_error_r "response-4", "response-5", ] - stored_results = attack._memory.get_attack_results(objective=_OBJECTIVE) + stored_results = await attack._memory.get_attack_results_async(objective=_OBJECTIVE) assert len(stored_results) == 1 assert stored_results[0].outcome is AttackOutcome.ERROR assert stored_results[0].error_type == "RuntimeError" @@ -917,7 +919,7 @@ async def test_malformed_adversarial_reply_exhaustion_rolls_back_only_retryable_ refusal_scorer.score_async.assert_not_awaited() adversarial_conversation_id = adversarial_target.attempts[0].conversation_id - pieces = attack._memory.get_message_pieces(conversation_id=adversarial_conversation_id) + pieces = await attack._memory.get_message_pieces_async(conversation_id=adversarial_conversation_id) values = [piece.original_value for piece in pieces] assert malformed not in values assert partial in values @@ -925,7 +927,7 @@ async def test_malformed_adversarial_reply_exhaustion_rolls_back_only_retryable_ assert conversation is not None assert len(conversation.retries) == 1 - stored_results = attack._memory.get_attack_results(objective=_OBJECTIVE) + stored_results = await attack._memory.get_attack_results_async(objective=_OBJECTIVE) assert len(stored_results) == 1 assert stored_results[0].outcome is AttackOutcome.ERROR assert stored_results[0].total_retries == 2 @@ -970,11 +972,11 @@ async def test_target_retry_exhaustion_persists_one_failed_send_and_propagates(s assert [attempt.prompt for attempt in objective_target.attempts] == ["question-1", "question-1"] refusal_scorer.score_async.assert_not_awaited() - pieces = attack._memory.get_message_pieces(conversation_id=context.session.conversation_id) + pieces = await attack._memory.get_message_pieces_async(conversation_id=context.session.conversation_id) assert len(pieces) == 2 assert pieces[0].original_value == "question-1" assert pieces[1].response_error == "processing" - stored_results = attack._memory.get_attack_results(objective=_OBJECTIVE) + stored_results = await attack._memory.get_attack_results_async(objective=_OBJECTIVE) assert len(stored_results) == 1 assert stored_results[0].outcome is AttackOutcome.ERROR assert stored_results[0].total_retries == 2 @@ -1038,7 +1040,7 @@ async def test_cancellation_runs_teardown_preserves_completed_turns_and_clears_r "adversarial", "objective", ] - pieces = attack._memory.get_message_pieces(conversation_id=context.session.conversation_id) + pieces = await attack._memory.get_message_pieces_async(conversation_id=context.session.conversation_id) assert len(pieces) == 8 assert [piece.original_value for piece in pieces if piece.api_role == "assistant"] == [ "response-1", @@ -1046,5 +1048,5 @@ async def test_cancellation_runs_teardown_preserves_completed_turns_and_clears_r "response-3", "response-4", ] - assert attack._memory.get_attack_results(objective=_OBJECTIVE) == [] + assert (await attack._memory.get_attack_results_async(objective=_OBJECTIVE)) == [] assert get_retry_collector() is None diff --git a/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py b/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py index b6ad77df67..910a064c2e 100644 --- a/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py +++ b/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py @@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest -from unit.mocks import MockPromptTarget +from unit.mocks import MockPromptTarget, get_mock_prompt_normalizer from pyrit.converter import Base64Converter, StringJoinConverter from pyrit.executor.attack import ( @@ -90,7 +90,7 @@ def mock_non_true_false_scorer(): @pytest.fixture def mock_prompt_normalizer(): """Create a mock prompt normalizer for testing""" - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock() return normalizer diff --git a/tests/unit/executor/attack/multi_turn/test_pair.py b/tests/unit/executor/attack/multi_turn/test_pair.py index 662f216bac..01c09a5814 100644 --- a/tests/unit/executor/attack/multi_turn/test_pair.py +++ b/tests/unit/executor/attack/multi_turn/test_pair.py @@ -49,7 +49,7 @@ def _make_mock_objective_target() -> PromptTarget: def _make_mock_adversarial_chat() -> PromptTarget: chat = MagicMock(spec=PromptTarget) chat.send_prompt_async = AsyncMock(return_value=None) - chat.set_system_prompt = MagicMock() + chat.set_system_prompt_async = AsyncMock() chat.get_identifier.return_value = ComponentIdentifier( class_name="MockChatTarget", class_module="test_module", diff --git a/tests/unit/executor/attack/multi_turn/test_prepended_history_normalization.py b/tests/unit/executor/attack/multi_turn/test_prepended_history_normalization.py index 84e5e00646..c8dbd9a8c8 100644 --- a/tests/unit/executor/attack/multi_turn/test_prepended_history_normalization.py +++ b/tests/unit/executor/attack/multi_turn/test_prepended_history_normalization.py @@ -106,7 +106,7 @@ def _make_context() -> MultiTurnAttackContext[AttackParameters]: return MultiTurnAttackContext(params=AttackParameters(objective="test objective")) -def _rotate( +async def _rotate_async( *, target: PromptTarget, context: MultiTurnAttackContext[AttackParameters], @@ -114,27 +114,29 @@ def _rotate( strategy = MagicMock() strategy._objective_target = target strategy._logger = MagicMock() - MultiTurnAttackStrategy._rotate_conversation_for_single_turn_target(strategy, context=context) + (await MultiTurnAttackStrategy._rotate_conversation_for_single_turn_target_async(strategy, context=context)) return strategy -def _seed_conversation( +async def _seed_conversation_async( *, conversation_id: str, target: PromptTarget, messages: list[Message], ) -> None: memory = CentralMemory.get_memory_instance() - memory.add_conversation_to_memory( - conversation=Conversation( - conversation_id=conversation_id, - target_identifier=target.get_identifier(), + ( + await memory.add_conversation_to_memory_async( + conversation=Conversation( + conversation_id=conversation_id, + target_identifier=target.get_identifier(), + ) ) ) for message in messages: for piece in message.message_pieces: piece.conversation_id = conversation_id - memory.add_message_to_memory(request=message) + (await memory.add_message_to_memory_async(request=message)) @pytest.mark.usefixtures("patch_central_database") @@ -152,7 +154,7 @@ async def test_single_turn_target_replays_seed_without_rotation(): prepended_conversation_config=config, target=target, ) - persisted = manager.get_conversation(conversation_id) + persisted = await manager.get_conversation_async(conversation_id) target_context = manager.create_prepended_history_send_context( target=target, conversation_id=conversation_id, @@ -179,20 +181,20 @@ async def test_single_turn_target_replays_seed_without_rotation(): @pytest.mark.usefixtures("patch_central_database") -def test_rotation_is_noop_for_multi_turn_target(): +async def test_rotation_is_noop_for_multi_turn_target(): target = _RecordingTarget(supports_multi_turn=True) context = _make_context() context.executed_turns = 1 original_id = context.session.conversation_id - _rotate(target=target, context=context) + (await _rotate_async(target=target, context=context)) assert context.session.conversation_id == original_id assert not context.related_conversations @pytest.mark.usefixtures("patch_central_database") -def test_rotation_is_noop_for_seeded_single_turn_target(): +async def test_rotation_is_noop_for_seeded_single_turn_target(): target = _RecordingTarget() context = _make_context() context.executed_turns = 2 @@ -204,20 +206,20 @@ def test_rotation_is_noop_for_seeded_single_turn_target(): prepended_messages=[seed], ) - _rotate(target=target, context=context) + (await _rotate_async(target=target, context=context)) assert context.session.conversation_id == original_id assert not context.related_conversations @pytest.mark.usefixtures("patch_central_database") -def test_rotation_moves_unseeded_single_turn_target_to_fresh_conversation(): +async def test_rotation_moves_unseeded_single_turn_target_to_fresh_conversation(): target = _RecordingTarget() context = _make_context() context.executed_turns = 1 original_id = context.session.conversation_id - _rotate(target=target, context=context) + (await _rotate_async(target=target, context=context)) assert context.session.conversation_id != original_id assert ( @@ -236,16 +238,18 @@ async def test_rotation_preserves_system_payload_for_later_single_turn_send(): context = _make_context() context.executed_turns = 1 old_id = context.session.conversation_id - _seed_conversation( - conversation_id=old_id, - target=target, - messages=[ - Message.from_system_prompt("system"), - Message.from_prompt(prompt="old request", role="user"), - ], + ( + await _seed_conversation_async( + conversation_id=old_id, + target=target, + messages=[ + Message.from_system_prompt("system"), + Message.from_prompt(prompt="old request", role="user"), + ], + ) ) - _rotate(target=target, context=context) + (await _rotate_async(target=target, context=context)) assert context.prepended_history_send_context is not None config = PrependedConversationConfig() @@ -302,16 +306,18 @@ def _make_tap_node(*, target: PromptTarget) -> _TreeOfAttacksNode: ) -def _set_tap_seed_boundary( +async def _set_tap_seed_boundary_async( *, node: _TreeOfAttacksNode, target: PromptTarget, seed_messages: list[Message], ) -> None: - _seed_conversation( - conversation_id=node.objective_target_conversation_id, - target=target, - messages=seed_messages, + ( + await _seed_conversation_async( + conversation_id=node.objective_target_conversation_id, + target=target, + messages=seed_messages, + ) ) node._prepended_history_send_context = ConversationManager.create_prepended_history_send_context( target=target, @@ -321,7 +327,7 @@ def _set_tap_seed_boundary( assert node._prepended_history_send_context is not None -def _branch_tap_node( +async def _branch_tap_node_async( *, node: _TreeOfAttacksNode, branching_factor: int, @@ -331,7 +337,7 @@ def _branch_tap_node( context.related_conversations = set() attack = MagicMock() attack._configuration.branching_factor = branching_factor - TreeOfAttacksWithPruningAttack._branch_existing_nodes(attack, context) + (await TreeOfAttacksWithPruningAttack._branch_existing_nodes_async(attack, context)) return context.nodes @@ -347,18 +353,18 @@ async def format_messages(messages: list[Message]) -> str: node = _make_tap_node(target=target) node._prepended_conversation_config = PrependedConversationConfig(message_normalizer=formatter) seed = Message.from_prompt(prompt="original seed", role="user") - _set_tap_seed_boundary(node=node, target=target, seed_messages=[seed]) + (await _set_tap_seed_boundary_async(node=node, target=target, seed_messages=[seed])) node._objective = "objective" await node._send_prompt_to_target_async("depth one") original_context = node._prepended_history_send_context assert original_context is not None - retained, cloned = _branch_tap_node(node=node, branching_factor=2) + retained, cloned = await _branch_tap_node_async(node=node, branching_factor=2) assert retained is node assert retained._prepended_history_send_context is original_context assert cloned._prepended_history_send_context is not None assert cloned._prepended_history_send_context.seed_message_count == 1 - cloned_messages = CentralMemory.get_memory_instance().get_conversation_messages( + cloned_messages = await CentralMemory.get_memory_instance().get_conversation_messages_async( conversation_id=cloned.objective_target_conversation_id ) assert cloned._prepended_history_send_context.seed_message_ids == (cloned_messages[0].get_piece().id,) @@ -368,7 +374,7 @@ async def format_messages(messages: list[Message]) -> str: branch._objective = "objective" await branch._send_prompt_to_target_async(prompt) - deep_clone = cloned.duplicate() + deep_clone = await cloned.duplicate_async() deep_clone._objective = "objective" await deep_clone._send_prompt_to_target_async("depth three cloned") @@ -400,10 +406,12 @@ async def format_messages(messages: list[Message]) -> str: formatter.normalize_string_async = AsyncMock(side_effect=format_messages) node = _make_tap_node(target=target) node._prepended_conversation_config = PrependedConversationConfig(message_normalizer=formatter) - _set_tap_seed_boundary( - node=node, - target=target, - seed_messages=[Message.from_prompt(prompt="original seed", role="user")], + ( + await _set_tap_seed_boundary_async( + node=node, + target=target, + seed_messages=[Message.from_prompt(prompt="original seed", role="user")], + ) ) node._objective = "objective" parent_conversation_id = node.objective_target_conversation_id @@ -412,7 +420,7 @@ async def format_messages(messages: list[Message]) -> str: assert node._prepended_history_send_context assert node._prepended_history_send_context.is_seed_consumed - cloned = node.duplicate() + cloned = await node.duplicate_async() cloned._objective = "objective" cloned_conversation_id = cloned.objective_target_conversation_id assert cloned_conversation_id != parent_conversation_id @@ -446,7 +454,7 @@ async def format_messages(messages: list[Message]) -> str: await node._send_prompt_to_target_async("parent first") assert node._prepended_history_send_context is None - cloned = node.duplicate() + cloned = await node.duplicate_async() cloned._objective = "objective" cloned_conversation_id = cloned.objective_target_conversation_id assert cloned._prepended_history_send_context @@ -464,7 +472,7 @@ async def format_messages(messages: list[Message]) -> str: @pytest.mark.usefixtures("patch_central_database") -def test_tap_branch_preserves_multimodal_last_response(): +async def test_tap_branch_preserves_multimodal_last_response() -> None: target = _RecordingTarget() node = _make_tap_node(target=target) node.last_response = Message( @@ -478,7 +486,7 @@ def test_tap_branch_preserves_multimodal_last_response(): ] ) - duplicate = node.duplicate() + duplicate = await node.duplicate_async() assert duplicate.last_response == node.last_response assert duplicate.last_response is not node.last_response @@ -494,10 +502,12 @@ async def test_tap_unseeded_stateless_send_retains_current_only_payload(): node = _make_tap_node(target=target) node._objective = "objective" previous_conversation_id = node.objective_target_conversation_id - _seed_conversation( - conversation_id=previous_conversation_id, - target=target, - messages=[Message.from_prompt(prompt="prior request", role="user")], + ( + await _seed_conversation_async( + conversation_id=previous_conversation_id, + target=target, + messages=[Message.from_prompt(prompt="prior request", role="user")], + ) ) await node._send_prompt_to_target_async("current request") @@ -513,14 +523,14 @@ async def test_tap_unseeded_stateless_retained_and_cloned_branches_send_current_ node._objective = "objective" await node._send_prompt_to_target_async("depth one") - retained, cloned = _branch_tap_node(node=node, branching_factor=2) + retained, cloned = await _branch_tap_node_async(node=node, branching_factor=2) assert retained._prepended_history_send_context is None assert cloned._prepended_history_send_context is None for branch, prompt in [(retained, "depth two retained"), (cloned, "depth two cloned")]: branch._objective = "objective" await branch._send_prompt_to_target_async(prompt) - deep_clone = cloned.duplicate() + deep_clone = await cloned.duplicate_async() deep_clone._objective = "objective" await deep_clone._send_prompt_to_target_async("depth three cloned") @@ -543,17 +553,19 @@ async def format_messages(messages: list[Message]) -> str: formatter.normalize_string_async = AsyncMock(side_effect=format_messages) node = _make_tap_node(target=target) node._prepended_conversation_config = PrependedConversationConfig(message_normalizer=formatter) - _set_tap_seed_boundary( - node=node, - target=target, - seed_messages=[Message.from_prompt(prompt="original seed", role="user")], + ( + await _set_tap_seed_boundary_async( + node=node, + target=target, + seed_messages=[Message.from_prompt(prompt="original seed", role="user")], + ) ) node._objective = "objective" await node._send_prompt_to_target_async("depth one") original_context = node._prepended_history_send_context original_boundary = original_context.seed_message_ids if original_context else () - branches = _branch_tap_node(node=node, branching_factor=1) + branches = await _branch_tap_node_async(node=node, branching_factor=1) assert branches == [node] assert node._prepended_history_send_context is original_context @@ -594,15 +606,17 @@ async def format_messages(messages: list[Message]) -> str: converters=[_ImageOutputConverter(output_path=str(image_path))] ) node._prepended_conversation_config = PrependedConversationConfig(message_normalizer=formatter) - _set_tap_seed_boundary( - node=node, - target=target, - seed_messages=[Message.from_prompt(prompt="original seed", role="user")], + ( + await _set_tap_seed_boundary_async( + node=node, + target=target, + seed_messages=[Message.from_prompt(prompt="original seed", role="user")], + ) ) node._objective = "objective" await node._send_prompt_to_target_async("depth one") - cloned = node.duplicate() + cloned = await node.duplicate_async() cloned._objective = "objective" await cloned._send_prompt_to_target_async("depth two") @@ -649,7 +663,7 @@ async def test_tap_stateful_clone_rejects_non_text_converter_history(tmp_path: P await node._send_prompt_to_target_async("depth one") with pytest.raises(ValueError, match="cannot clone.*non-text output.*image_path"): - node.duplicate() + await node.duplicate_async() @pytest.mark.usefixtures("patch_central_database") @@ -674,7 +688,7 @@ async def format_messages(messages: list[Message]) -> str: node._objective = "objective" await node._send_prompt_to_target_async("depth one") - cloned = node.duplicate() + cloned = await node.duplicate_async() cloned._objective = "objective" await cloned._send_prompt_to_target_async("depth two") diff --git a/tests/unit/executor/attack/multi_turn/test_red_teaming.py b/tests/unit/executor/attack/multi_turn/test_red_teaming.py index ce7108db28..e124557004 100644 --- a/tests/unit/executor/attack/multi_turn/test_red_teaming.py +++ b/tests/unit/executor/attack/multi_turn/test_red_teaming.py @@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +from unit.mocks import get_mock_prompt_normalizer from pyrit.exceptions import ( AdversarialChatRefusedException, @@ -31,7 +32,7 @@ AttackPreparationFailureKind, ) from pyrit.executor.attack.core.attack_strategy import _ObjectiveTargetConversationLifecycle -from pyrit.memory import CentralMemory +from pyrit.memory import CentralMemory, MemoryInterface from pyrit.message_normalizer import MessageStringNormalizer from pyrit.models import ( AttackOutcome, @@ -111,7 +112,7 @@ def mock_objective_target() -> MagicMock: def mock_adversarial_chat() -> MagicMock: chat = MagicMock(spec=PromptTarget) chat.send_prompt_async = AsyncMock() - chat.set_system_prompt = MagicMock() + chat.set_system_prompt_async = AsyncMock() chat.get_identifier.return_value = _mock_target_id("MockChatTarget") chat.configuration.capabilities.input_modalities = frozenset({frozenset({"text"})}) chat.configuration.capabilities.output_modalities = frozenset({frozenset({"text"})}) @@ -128,7 +129,7 @@ def mock_objective_scorer() -> MagicMock: @pytest.fixture def mock_prompt_normalizer() -> MagicMock: - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock() return normalizer @@ -601,7 +602,7 @@ async def test_max_turns_validation_with_prepended_conversation( # Create a separate chat target for objective since prepended_conversation requires PromptTarget mock_chat_objective_target = MagicMock(spec=PromptTarget) mock_chat_objective_target.send_prompt_async = AsyncMock() - mock_chat_objective_target.set_system_prompt = MagicMock() + mock_chat_objective_target.set_system_prompt_async = AsyncMock() mock_chat_objective_target.get_identifier.return_value = _mock_target_id("MockChatTarget") mock_chat_objective_target.configuration.capabilities.input_modalities = frozenset({frozenset({"text"})}) mock_chat_objective_target.configuration.capabilities.output_modalities = frozenset({frozenset({"text"})}) @@ -794,7 +795,7 @@ async def test_setup_merges_memory_labels_correctly( Message.from_prompt(prompt="prepended user", role="user"), Message.from_prompt(prompt="prepended assistant", role="assistant"), ] - attack._memory = MagicMock() + attack._memory = MagicMock(spec=MemoryInterface) # Mock that simulates initialize_context_async merging labels async def mock_initialize(*, context, memory_labels=None, **kwargs): @@ -836,8 +837,8 @@ async def test_setup_sets_adversarial_chat_system_prompt( await attack._setup_async(context=basic_context) # Verify system prompt was set - mock_adversarial_chat.set_system_prompt.assert_called_once() - call_args = mock_adversarial_chat.set_system_prompt.call_args + mock_adversarial_chat.set_system_prompt_async.assert_called_once() + call_args = mock_adversarial_chat.set_system_prompt_async.call_args assert "Test objective" in call_args.kwargs["system_prompt"] assert call_args.kwargs["conversation_id"] == basic_context.session.adversarial_chat_conversation_id @@ -1045,16 +1046,18 @@ async def test_second_turn_uses_configured_message_normalizer_without_rotation( conversation_id=old_conversation_id, sequence=0, ) - memory.add_message_pieces_to_memory( - message_pieces=[ - system_piece, - MessagePiece( - original_value="First request", - role="user", - conversation_id=old_conversation_id, - sequence=1, - ), - ] + ( + await memory.add_message_pieces_to_memory_async( + message_pieces=[ + system_piece, + MessagePiece( + original_value="First request", + role="user", + conversation_id=old_conversation_id, + sequence=1, + ), + ] + ) ) basic_context.prepended_history_send_context = ConversationManager.create_prepended_history_send_context( target=objective_target, diff --git a/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py b/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py index 00b2c56d5f..e97aa1602e 100644 --- a/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py +++ b/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py @@ -70,7 +70,7 @@ def _make_strategy(*, supports_multi_turn: bool): return strategy # noqa: RET504 -def _seed_conversation(*, conversation_id: str, system_prompt: str, user_text: str = "Hello") -> None: +async def _seed_conversation_async(*, conversation_id: str, system_prompt: str, user_text: str = "Hello") -> None: """Add a system message and a user message to memory under the given conversation_id.""" memory = CentralMemory.get_memory_instance() @@ -86,36 +86,36 @@ def _seed_conversation(*, conversation_id: str, system_prompt: str, user_text: s conversation_id=conversation_id, sequence=1, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece, user_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece, user_piece])) @pytest.mark.usefixtures("patch_central_database") class TestRotateConversationForSingleTurnTarget: """Test the _rotate_conversation_for_single_turn_target helper.""" - def test_noop_for_multi_turn_target(self): + async def test_noop_for_multi_turn_target(self): strategy = _make_strategy(supports_multi_turn=True) context = _make_context() context.executed_turns = 1 original_id = context.session.conversation_id - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) assert context.session.conversation_id == original_id assert len(context.related_conversations) == 0 - def test_noop_on_first_turn(self): + async def test_noop_on_first_turn(self): strategy = _make_strategy(supports_multi_turn=False) context = _make_context() context.executed_turns = 0 original_id = context.session.conversation_id - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) assert context.session.conversation_id == original_id assert len(context.related_conversations) == 0 - def test_pending_first_turn_context_suppresses_rotation_after_prepended_turns(self): + async def test_pending_first_turn_context_suppresses_rotation_after_prepended_turns(self): strategy = _make_strategy(supports_multi_turn=False) context = _make_context() context.executed_turns = 2 @@ -126,18 +126,18 @@ def test_pending_first_turn_context_suppresses_rotation_after_prepended_turns(se replay_seed_each_send=True, ) - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) assert context.session.conversation_id == original_id assert len(context.related_conversations) == 0 - def test_rotates_on_second_turn_for_single_turn_target(self): + async def test_rotates_on_second_turn_for_single_turn_target(self): strategy = _make_strategy(supports_multi_turn=False) context = _make_context() context.executed_turns = 1 original_id = context.session.conversation_id - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) assert context.session.conversation_id != original_id assert len(context.related_conversations) == 1 @@ -145,14 +145,14 @@ def test_rotates_on_second_turn_for_single_turn_target(self): assert ref.conversation_id == original_id assert ref.conversation_type == ConversationType.PRUNED - def test_rotates_multiple_turns(self): + async def test_rotates_multiple_turns(self): strategy = _make_strategy(supports_multi_turn=False) context = _make_context() seen_ids = {context.session.conversation_id} for turn in range(1, 4): context.executed_turns = turn - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) assert context.session.conversation_id not in seen_ids seen_ids.add(context.session.conversation_id) @@ -163,49 +163,53 @@ def test_rotates_multiple_turns(self): class TestSystemPromptCarryoverOnRotation: """Test that system prompts are duplicated into the new conversation on rotation.""" - def test_system_prompt_duplicated_into_new_conversation(self): + async def test_system_prompt_duplicated_into_new_conversation(self): """When rotating, system messages must be copied to the new conversation_id.""" strategy = _make_strategy(supports_multi_turn=False) context = _make_context() old_id = context.session.conversation_id - _seed_conversation( - conversation_id=old_id, - system_prompt="You are a helpful assistant.", - user_text="Turn 1 user message", + ( + await _seed_conversation_async( + conversation_id=old_id, + system_prompt="You are a helpful assistant.", + user_text="Turn 1 user message", + ) ) context.executed_turns = 1 - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) new_id = context.session.conversation_id assert new_id != old_id memory = CentralMemory.get_memory_instance() - new_messages = memory.get_conversation_messages(conversation_id=new_id) + new_messages = await memory.get_conversation_messages_async(conversation_id=new_id) # Only the system message should be in the new conversation (not the user message) assert len(new_messages) == 1 assert new_messages[0].api_role == "system" assert new_messages[0].get_value() == "You are a helpful assistant." - def test_system_prompt_preserved_across_multiple_rotations(self): + async def test_system_prompt_preserved_across_multiple_rotations(self): """System prompt must carry over through successive rotations.""" strategy = _make_strategy(supports_multi_turn=False) context = _make_context() memory = CentralMemory.get_memory_instance() # Seed initial conversation with system prompt + user message - _seed_conversation( - conversation_id=context.session.conversation_id, - system_prompt="You are an expert.", + ( + await _seed_conversation_async( + conversation_id=context.session.conversation_id, + system_prompt="You are an expert.", + ) ) for turn in range(1, 4): context.executed_turns = turn - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) - messages = memory.get_conversation_messages(conversation_id=context.session.conversation_id) + messages = await memory.get_conversation_messages_async(conversation_id=context.session.conversation_id) system_msgs = [m for m in messages if m.api_role == "system"] assert len(system_msgs) == 1, f"Turn {turn}: expected 1 system message, got {len(system_msgs)}" assert system_msgs[0].get_value() == "You are an expert." @@ -217,7 +221,7 @@ def test_system_prompt_preserved_across_multiple_rotations(self): conversation_id=context.session.conversation_id, sequence=1, ) - memory.add_message_pieces_to_memory(message_pieces=[user_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[user_piece])) async def test_rotated_system_prompt_is_normalized_with_next_request(self): target = _SingleTurnPromptTarget() @@ -225,14 +229,16 @@ async def test_rotated_system_prompt_is_normalized_with_next_request(self): strategy._objective_target = target context = _make_context() old_id = context.session.conversation_id - _seed_conversation( - conversation_id=old_id, - system_prompt="You are a helpful assistant.", - user_text="First request", + ( + await _seed_conversation_async( + conversation_id=old_id, + system_prompt="You are a helpful assistant.", + user_text="First request", + ) ) context.executed_turns = 1 - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) next_request = Message.from_prompt(prompt="Second request", role="user") next_request.get_piece().conversation_id = context.session.conversation_id @@ -255,7 +261,7 @@ async def test_rotated_system_prompt_is_normalized_with_next_request(self): "Turn 1:\nuser: ### Instructions ###\n\nYou are a helpful assistant.\n\n######\n\nSecond request" ) - def test_no_system_prompt_yields_fresh_conversation_id(self): + async def test_no_system_prompt_yields_fresh_conversation_id(self): """When there is no system prompt, rotation still generates a new conversation_id.""" strategy = _make_strategy(supports_multi_turn=False) context = _make_context() @@ -268,17 +274,17 @@ def test_no_system_prompt_yields_fresh_conversation_id(self): conversation_id=context.session.conversation_id, sequence=0, ) - memory.add_message_pieces_to_memory(message_pieces=[user_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[user_piece])) old_id = context.session.conversation_id context.executed_turns = 1 - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) assert context.session.conversation_id != old_id - new_messages = memory.get_conversation_messages(conversation_id=context.session.conversation_id) + new_messages = await memory.get_conversation_messages_async(conversation_id=context.session.conversation_id) assert len(new_messages) == 0 - def test_user_messages_not_carried_over(self): + async def test_user_messages_not_carried_over(self): """Only system messages should be carried to the new conversation, not user/assistant.""" strategy = _make_strategy(supports_multi_turn=False) context = _make_context() @@ -303,16 +309,16 @@ def test_user_messages_not_carried_over(self): conversation_id=context.session.conversation_id, sequence=2, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece, user_piece, asst_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece, user_piece, asst_piece])) context.executed_turns = 1 - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) - new_messages = memory.get_conversation_messages(conversation_id=context.session.conversation_id) + new_messages = await memory.get_conversation_messages_async(conversation_id=context.session.conversation_id) roles = [m.api_role for m in new_messages] assert roles == ["system"], f"Expected only system, got {roles}" - def test_multiple_system_messages_all_carried_over(self): + async def test_multiple_system_messages_all_carried_over(self): """When multiple system messages exist (different sequences), all are duplicated.""" strategy = _make_strategy(supports_multi_turn=False) context = _make_context() @@ -338,17 +344,17 @@ def test_multiple_system_messages_all_carried_over(self): conversation_id=context.session.conversation_id, sequence=2, ) - memory.add_message_pieces_to_memory(message_pieces=[sys1, user_piece, sys2]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys1, user_piece, sys2])) context.executed_turns = 1 - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) - new_messages = memory.get_conversation_messages(conversation_id=context.session.conversation_id) + new_messages = await memory.get_conversation_messages_async(conversation_id=context.session.conversation_id) system_values = sorted(m.get_value() for m in new_messages if m.api_role == "system") assert system_values == ["Safety instructions", "System prompt 1"] assert all(m.api_role == "system" for m in new_messages) - def test_empty_conversation_yields_fresh_id(self): + async def test_empty_conversation_yields_fresh_id(self): """When the conversation has zero messages, rotation still produces a new ID.""" strategy = _make_strategy(supports_multi_turn=False) context = _make_context() @@ -356,14 +362,14 @@ def test_empty_conversation_yields_fresh_id(self): # Don't seed any messages — conversation is completely empty context.executed_turns = 1 - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) assert context.session.conversation_id != old_id memory = CentralMemory.get_memory_instance() - new_messages = memory.get_conversation_messages(conversation_id=context.session.conversation_id) + new_messages = await memory.get_conversation_messages_async(conversation_id=context.session.conversation_id) assert len(new_messages) == 0 - def test_only_system_messages_all_carried_over(self): + async def test_only_system_messages_all_carried_over(self): """When the conversation contains only system messages (no user/assistant), all are carried.""" strategy = _make_strategy(supports_multi_turn=False) context = _make_context() @@ -375,17 +381,17 @@ def test_only_system_messages_all_carried_over(self): conversation_id=context.session.conversation_id, sequence=0, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece])) context.executed_turns = 1 - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) - new_messages = memory.get_conversation_messages(conversation_id=context.session.conversation_id) + new_messages = await memory.get_conversation_messages_async(conversation_id=context.session.conversation_id) assert len(new_messages) == 1 assert new_messages[0].api_role == "system" assert new_messages[0].get_value() == "Only a system message" - def test_multipiece_system_message_fully_duplicated(self): + async def test_multipiece_system_message_fully_duplicated(self): """A system Message with multiple pieces (same sequence) is fully duplicated.""" strategy = _make_strategy(supports_multi_turn=False) context = _make_context() @@ -411,12 +417,12 @@ def test_multipiece_system_message_fully_duplicated(self): conversation_id=context.session.conversation_id, sequence=1, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_text, sys_image, user_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_text, sys_image, user_piece])) context.executed_turns = 1 - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) - new_messages = memory.get_conversation_messages(conversation_id=context.session.conversation_id) + new_messages = await memory.get_conversation_messages_async(conversation_id=context.session.conversation_id) assert len(new_messages) == 1 assert new_messages[0].api_role == "system" # Both pieces should be present in the duplicated message @@ -424,24 +430,26 @@ def test_multipiece_system_message_fully_duplicated(self): values = {p.converted_value for p in new_messages[0].message_pieces} assert values == {"System text instruction", "image_placeholder"} - def test_old_conversation_untouched_after_rotation(self): + async def test_old_conversation_untouched_after_rotation(self): """Rotation must not alter messages in the old conversation.""" strategy = _make_strategy(supports_multi_turn=False) context = _make_context() memory = CentralMemory.get_memory_instance() old_id = context.session.conversation_id - _seed_conversation( - conversation_id=old_id, - system_prompt="Original system prompt", - user_text="Original user message", + ( + await _seed_conversation_async( + conversation_id=old_id, + system_prompt="Original system prompt", + user_text="Original user message", + ) ) context.executed_turns = 1 - strategy._rotate_conversation_for_single_turn_target(context=context) + (await strategy._rotate_conversation_for_single_turn_target_async(context=context)) # Old conversation should still have both messages intact - old_messages = memory.get_conversation_messages(conversation_id=old_id) + old_messages = await memory.get_conversation_messages_async(conversation_id=old_id) old_roles = [m.api_role for m in old_messages] assert old_roles == ["system", "user"] @@ -495,7 +503,7 @@ def _make_tap_node(self, *, supports_multi_turn: bool): expectation=ScoringExpectation(objective="Test objective"), ) - def test_single_turn_target_duplicates_logical_history_without_seed_boundary(self): + async def test_single_turn_target_duplicates_logical_history_without_seed_boundary(self): """Single-turn branches retain memory without replaying live turns as seed history.""" node = self._make_tap_node(supports_multi_turn=False) memory = CentralMemory.get_memory_instance() @@ -519,20 +527,22 @@ def test_single_turn_target_duplicates_logical_history_without_seed_boundary(sel conversation_id=node.objective_target_conversation_id, sequence=2, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece, user_piece, asst_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece, user_piece, asst_piece])) - duplicate = node.duplicate() + duplicate = await node.duplicate_async() # The duplicate should have a different conversation_id assert duplicate.objective_target_conversation_id != node.objective_target_conversation_id - dup_messages = memory.get_conversation_messages(conversation_id=duplicate.objective_target_conversation_id) + dup_messages = await memory.get_conversation_messages_async( + conversation_id=duplicate.objective_target_conversation_id + ) assert [message.api_role for message in dup_messages] == ["system", "user", "assistant"] # No explicit prepended seed was initialized, so copied live turns do not # become a new replay boundary. assert duplicate._prepended_history_send_context is None - def test_multi_turn_target_duplicates_full_conversation(self): + async def test_multi_turn_target_duplicates_full_conversation(self): """For multi-turn targets, the full conversation is duplicated.""" node = self._make_tap_node(supports_multi_turn=True) memory = CentralMemory.get_memory_instance() @@ -556,17 +566,19 @@ def test_multi_turn_target_duplicates_full_conversation(self): conversation_id=node.objective_target_conversation_id, sequence=2, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece, user_piece, asst_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece, user_piece, asst_piece])) - duplicate = node.duplicate() + duplicate = await node.duplicate_async() assert duplicate.objective_target_conversation_id != node.objective_target_conversation_id - dup_messages = memory.get_conversation_messages(conversation_id=duplicate.objective_target_conversation_id) + dup_messages = await memory.get_conversation_messages_async( + conversation_id=duplicate.objective_target_conversation_id + ) roles = [m.api_role for m in dup_messages] assert roles == ["system", "user", "assistant"] - def test_single_turn_no_system_messages_retains_full_history(self): + async def test_single_turn_no_system_messages_retains_full_history(self): """Single-turn branches do not discard non-system logical history.""" node = self._make_tap_node(supports_multi_turn=False) memory = CentralMemory.get_memory_instance() @@ -578,15 +590,17 @@ def test_single_turn_no_system_messages_retains_full_history(self): conversation_id=node.objective_target_conversation_id, sequence=0, ) - memory.add_message_pieces_to_memory(message_pieces=[user_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[user_piece])) - duplicate = node.duplicate() + duplicate = await node.duplicate_async() assert duplicate.objective_target_conversation_id != node.objective_target_conversation_id - dup_messages = memory.get_conversation_messages(conversation_id=duplicate.objective_target_conversation_id) + dup_messages = await memory.get_conversation_messages_async( + conversation_id=duplicate.objective_target_conversation_id + ) assert [message.get_value() for message in dup_messages] == ["Attack prompt"] - def test_adversarial_chat_always_fully_duplicated(self): + async def test_adversarial_chat_always_fully_duplicated(self): """The adversarial chat conversation should always be fully duplicated regardless of target type.""" node = self._make_tap_node(supports_multi_turn=False) memory = CentralMemory.get_memory_instance() @@ -604,7 +618,7 @@ def test_adversarial_chat_always_fully_duplicated(self): conversation_id=node.adversarial_chat_conversation_id, sequence=1, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece, user_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece, user_piece])) # Also seed objective target conversation so it doesn't error target_piece = MessagePiece( @@ -613,15 +627,17 @@ def test_adversarial_chat_always_fully_duplicated(self): conversation_id=node.objective_target_conversation_id, sequence=0, ) - memory.add_message_pieces_to_memory(message_pieces=[target_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[target_piece])) - duplicate = node.duplicate() + duplicate = await node.duplicate_async() - dup_adv_messages = memory.get_conversation_messages(conversation_id=duplicate.adversarial_chat_conversation_id) + dup_adv_messages = await memory.get_conversation_messages_async( + conversation_id=duplicate.adversarial_chat_conversation_id + ) roles = [m.api_role for m in dup_adv_messages] assert roles == ["system", "user"] - def test_single_turn_multiple_system_messages_and_user_are_duplicated(self): + async def test_single_turn_multiple_system_messages_and_user_are_duplicated(self): """All logical branch messages are duplicated in their original order.""" node = self._make_tap_node(supports_multi_turn=False) memory = CentralMemory.get_memory_instance() @@ -644,11 +660,13 @@ def test_single_turn_multiple_system_messages_and_user_are_duplicated(self): conversation_id=node.objective_target_conversation_id, sequence=2, ) - memory.add_message_pieces_to_memory(message_pieces=[sys1, user_piece, sys2]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys1, user_piece, sys2])) - duplicate = node.duplicate() + duplicate = await node.duplicate_async() - dup_messages = memory.get_conversation_messages(conversation_id=duplicate.objective_target_conversation_id) + dup_messages = await memory.get_conversation_messages_async( + conversation_id=duplicate.objective_target_conversation_id + ) assert [message.api_role for message in dup_messages] == ["system", "user", "system"] assert [message.get_value() for message in dup_messages] == [ "System prompt A", @@ -656,37 +674,39 @@ def test_single_turn_multiple_system_messages_and_user_are_duplicated(self): "System prompt B", ] - def test_single_turn_empty_conversation_yields_fresh_id(self): + async def test_single_turn_empty_conversation_yields_fresh_id(self): """For single-turn targets with empty conversation, a fresh ID is produced.""" node = self._make_tap_node(supports_multi_turn=False) memory = CentralMemory.get_memory_instance() # Don't seed any messages - duplicate = node.duplicate() + duplicate = await node.duplicate_async() assert duplicate.objective_target_conversation_id != node.objective_target_conversation_id - dup_messages = memory.get_conversation_messages(conversation_id=duplicate.objective_target_conversation_id) + dup_messages = await memory.get_conversation_messages_async( + conversation_id=duplicate.objective_target_conversation_id + ) assert len(dup_messages) == 0 - def test_duplicate_node_has_correct_parent_id(self): + async def test_duplicate_node_has_correct_parent_id(self) -> None: """The duplicate node's parent_id should be the original node's node_id.""" node = self._make_tap_node(supports_multi_turn=False) - duplicate = node.duplicate() + duplicate = await node.duplicate_async() assert duplicate.parent_id == node.node_id assert duplicate.node_id != node.node_id - def test_duplicate_node_copies_conversation_context(self): + async def test_duplicate_node_copies_conversation_context(self) -> None: """The duplicate node should inherit the _conversation_context from the original.""" node = self._make_tap_node(supports_multi_turn=False) node._conversation_context = "Some prior conversation context" - duplicate = node.duplicate() + duplicate = await node.duplicate_async() assert duplicate._conversation_context == "Some prior conversation context" - def test_system_message_content_preserved_exactly(self): + async def test_system_message_content_preserved_exactly(self): """The duplicated system message text must match the original exactly.""" node = self._make_tap_node(supports_multi_turn=False) memory = CentralMemory.get_memory_instance() @@ -704,15 +724,17 @@ def test_system_message_content_preserved_exactly(self): conversation_id=node.objective_target_conversation_id, sequence=1, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece, user_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece, user_piece])) - duplicate = node.duplicate() + duplicate = await node.duplicate_async() - dup_messages = memory.get_conversation_messages(conversation_id=duplicate.objective_target_conversation_id) + dup_messages = await memory.get_conversation_messages_async( + conversation_id=duplicate.objective_target_conversation_id + ) assert len(dup_messages) == 2 assert dup_messages[0].get_value() == long_prompt - def test_original_conversation_untouched_after_duplicate(self): + async def test_original_conversation_untouched_after_duplicate(self): """Duplicating must not alter the original node's conversation.""" node = self._make_tap_node(supports_multi_turn=False) memory = CentralMemory.get_memory_instance() @@ -729,16 +751,18 @@ def test_original_conversation_untouched_after_duplicate(self): conversation_id=node.objective_target_conversation_id, sequence=1, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece, user_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece, user_piece])) - node.duplicate() + await node.duplicate_async() # Original conversation should still have both messages - orig_messages = memory.get_conversation_messages(conversation_id=node.objective_target_conversation_id) + orig_messages = await memory.get_conversation_messages_async( + conversation_id=node.objective_target_conversation_id + ) orig_roles = [m.api_role for m in orig_messages] assert orig_roles == ["system", "user"] - def test_single_turn_multipiece_system_message_duplicated(self): + async def test_single_turn_multipiece_system_message_duplicated(self): """A multi-piece system Message (same sequence) is fully duplicated in TAP.""" node = self._make_tap_node(supports_multi_turn=False) memory = CentralMemory.get_memory_instance() @@ -762,11 +786,13 @@ def test_single_turn_multipiece_system_message_duplicated(self): conversation_id=node.objective_target_conversation_id, sequence=1, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_text, sys_image, user_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_text, sys_image, user_piece])) - duplicate = node.duplicate() + duplicate = await node.duplicate_async() - dup_messages = memory.get_conversation_messages(conversation_id=duplicate.objective_target_conversation_id) + dup_messages = await memory.get_conversation_messages_async( + conversation_id=duplicate.objective_target_conversation_id + ) assert len(dup_messages) == 2 assert dup_messages[0].api_role == "system" assert len(dup_messages[0].message_pieces) == 2 @@ -883,7 +909,7 @@ def _make_tap_node(self, *, supports_multi_turn: bool): expectation=ScoringExpectation(objective="Test objective"), ) - def test_branching_single_turn_target_preserves_system_across_depths(self): + async def test_branching_single_turn_target_preserves_system_across_depths(self): """Simulate TAP branching across 2 depths and verify system prompts survive. Depth 1: Create a node, seed system + user + assistant messages. @@ -914,12 +940,14 @@ def test_branching_single_turn_target_preserves_system_across_depths(self): conversation_id=node.objective_target_conversation_id, sequence=2, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece, user_piece, asst_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece, user_piece, asst_piece])) # Depth 2: branch with the full logical history. - branch1 = node.duplicate() + branch1 = await node.duplicate_async() - branch1_msgs = memory.get_conversation_messages(conversation_id=branch1.objective_target_conversation_id) + branch1_msgs = await memory.get_conversation_messages_async( + conversation_id=branch1.objective_target_conversation_id + ) assert [message.api_role for message in branch1_msgs] == ["system", "user", "assistant"] # Simulate depth-2 turn on branch1: add user + assistant on branch1's conversation @@ -935,20 +963,24 @@ def test_branching_single_turn_target_preserves_system_across_depths(self): conversation_id=branch1.objective_target_conversation_id, sequence=4, ) - memory.add_message_pieces_to_memory(message_pieces=[user2, asst2]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[user2, asst2])) # Verify branch1 now has the inherited and new turns. - branch1_full = memory.get_conversation_messages(conversation_id=branch1.objective_target_conversation_id) + branch1_full = await memory.get_conversation_messages_async( + conversation_id=branch1.objective_target_conversation_id + ) assert [m.api_role for m in branch1_full] == ["system", "user", "assistant", "user", "assistant"] # Depth 3: branch again from branch1 - branch2 = branch1.duplicate() + branch2 = await branch1.duplicate_async() - branch2_msgs = memory.get_conversation_messages(conversation_id=branch2.objective_target_conversation_id) + branch2_msgs = await memory.get_conversation_messages_async( + conversation_id=branch2.objective_target_conversation_id + ) assert [m.api_role for m in branch2_msgs] == ["system", "user", "assistant", "user", "assistant"] assert branch2_msgs[0].get_value() == "You are a red team assistant." - def test_branching_multi_turn_target_preserves_full_history(self): + async def test_branching_multi_turn_target_preserves_full_history(self): """For multi-turn targets, branching should preserve the full conversation.""" memory = CentralMemory.get_memory_instance() node = self._make_tap_node(supports_multi_turn=True) @@ -972,11 +1004,13 @@ def test_branching_multi_turn_target_preserves_full_history(self): conversation_id=node.objective_target_conversation_id, sequence=2, ) - memory.add_message_pieces_to_memory(message_pieces=[sys_piece, user_piece, asst_piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[sys_piece, user_piece, asst_piece])) - branch = node.duplicate() + branch = await node.duplicate_async() - branch_msgs = memory.get_conversation_messages(conversation_id=branch.objective_target_conversation_id) + branch_msgs = await memory.get_conversation_messages_async( + conversation_id=branch.objective_target_conversation_id + ) assert [m.api_role for m in branch_msgs] == ["system", "user", "assistant"] # Add another turn on the branch @@ -986,9 +1020,11 @@ def test_branching_multi_turn_target_preserves_full_history(self): conversation_id=branch.objective_target_conversation_id, sequence=3, ) - memory.add_message_pieces_to_memory(message_pieces=[user2]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[user2])) # Branch again — should have all 4 messages - branch2 = branch.duplicate() - branch2_msgs = memory.get_conversation_messages(conversation_id=branch2.objective_target_conversation_id) + branch2 = await branch.duplicate_async() + branch2_msgs = await memory.get_conversation_messages_async( + conversation_id=branch2.objective_target_conversation_id + ) assert [m.api_role for m in branch2_msgs] == ["system", "user", "assistant", "user"] diff --git a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py index d610077dbd..9c0de305db 100644 --- a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py +++ b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py @@ -7,12 +7,12 @@ import logging import uuid from dataclasses import FrozenInstanceError, dataclass, field, replace -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast from unittest.mock import AsyncMock, MagicMock, patch import pytest from treelib.tree import Tree -from unit.mocks import store_message +from unit.mocks import get_mock_prompt_normalizer, store_message_async from pyrit.exceptions import InvalidJsonException from pyrit.executor.attack import ( @@ -31,6 +31,7 @@ _TreeOfAttacksNode, _TreeOfAttacksNodeExecutor, ) +from pyrit.memory import MemoryInterface from pyrit.models import ( JSON_SCHEMA_METADATA_KEY, AttackOutcome, @@ -44,7 +45,6 @@ ScoringExpectation, SeedPrompt, ) -from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import CapabilityName, PromptTarget from pyrit.score import ( FloatScaleThresholdScorer, @@ -54,6 +54,9 @@ TrueFalseScorer, ) from pyrit.score.float_scale.float_scale_scorer import FloatScaleScorer + +if TYPE_CHECKING: + from pyrit.prompt_normalizer import PromptNormalizer from pyrit.score.score_utils import normalize_score_to_float logger = logging.getLogger(__name__) @@ -178,13 +181,13 @@ def duplicate_side_effect(): dup._vis_node_id = node._vis_node_id return dup - node.duplicate = MagicMock(side_effect=duplicate_side_effect) + node.duplicate_async = AsyncMock(side_effect=duplicate_side_effect) node.last_prompt_sent = None node.last_response = None - node._memory = MagicMock() - node._memory.duplicate_conversation = MagicMock(return_value=str(uuid.uuid4())) + node._memory = MagicMock(spec=MemoryInterface) + node._memory.duplicate_conversation_async = AsyncMock(return_value=str(uuid.uuid4())) node._objective_target = MagicMock() node._adversarial_chat = MagicMock() node._objective_scorer = MagicMock() @@ -194,7 +197,7 @@ def duplicate_side_effect(): node._response_converters = [] node._memory_labels = {} node._attack_id = {"__type__": "MockAttack", "__module__": "test_module"} - node._prompt_normalizer = MagicMock() + node._prompt_normalizer = get_mock_prompt_normalizer() # Mock the required internal methods that might be called node._mark_execution_complete = MagicMock() @@ -251,7 +254,7 @@ def with_auxiliary_scorers(self, count: int = 1) -> "AttackBuilder": def with_prompt_normalizer(self) -> "AttackBuilder": """Add a mock prompt normalizer.""" - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock(return_value=None) self.prompt_normalizer = cast("PromptNormalizer", normalizer) return self @@ -316,7 +319,7 @@ def _create_mock_target(supports_multi_turn: bool = True) -> PromptTarget: def _create_mock_chat() -> PromptTarget: chat = MagicMock(spec=PromptTarget) chat.send_prompt_async = AsyncMock(return_value=None) - chat.set_system_prompt = MagicMock() + chat.set_system_prompt_async = AsyncMock() chat.get_identifier.return_value = ComponentIdentifier( class_name="MockChatTarget", class_module="test_module", @@ -458,27 +461,10 @@ async def create_threshold_score_async(*, original_float_value: float, threshold ) # Score using the actual FloatScaleThresholdScorer - scores = await threshold_scorer.score_async(scorable=MessageScorable.from_message(store_message(dummy_message))) - return scores[0] - - @staticmethod - def create_threshold_score(*, original_float_value: float, threshold: float = 0.8) -> Score: - """ - Create a TrueFalse Score using actual FloatScaleThresholdScorer (sync wrapper). - - This is a synchronous wrapper around create_threshold_score_async for use in - non-async test methods. Uses asyncio.run() for proper event loop handling. - - Args: - original_float_value: The original float score (0.0-1.0). - threshold: The threshold used for true/false determination. - - Returns: - Score with TrueFalse type and original_float_value in metadata. - """ - return asyncio.run( - TestHelpers.create_threshold_score_async(original_float_value=original_float_value, threshold=threshold) + scores = await threshold_scorer.score_async( + scorable=MessageScorable.from_message(await store_message_async(dummy_message)) ) + return scores[0] @staticmethod def add_nodes_to_tree(context: TAPAttackContext, nodes: list[_TreeOfAttacksNode], parent: str = "root"): @@ -1177,7 +1163,7 @@ async def test_score_response_delegates_to_scorer_for_blocked(self, attack_build adversarial_chat_system.render_template_value = MagicMock(return_value="system") adversarial_chat_template = MagicMock(spec=SeedPrompt) adversarial_chat_template.render_template_value = MagicMock(return_value="template") - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock(return_value=None) node = _TreeOfAttacksNode( @@ -1245,7 +1231,7 @@ async def test_score_response_delegates_to_scorer_for_unknown_error(self, attack adversarial_chat_system.render_template_value = MagicMock(return_value="system") adversarial_chat_template = MagicMock(spec=SeedPrompt) adversarial_chat_template.render_template_value = MagicMock(return_value="template") - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock(return_value=None) node = _TreeOfAttacksNode( @@ -1304,7 +1290,7 @@ async def test_score_response_delegates_to_scorer_for_unknown_error(self, attack class TestBranchingLogic: """Tests for node branching functionality.""" - def test_branch_existing_nodes(self, basic_attack, node_factory, helpers): + async def test_branch_existing_nodes(self, basic_attack, node_factory, helpers): """Test that nodes are branched correctly.""" context = helpers.create_basic_context() basic_attack._configuration = replace(basic_attack._configuration, branching_factor=3) @@ -1316,7 +1302,7 @@ def test_branch_existing_nodes(self, basic_attack, node_factory, helpers): context.executed_turns = 2 # Execute branching - basic_attack._branch_existing_nodes(context=context) + (await basic_attack._branch_existing_nodes_async(context=context)) # Verify results # 2 original + 4 new @@ -1324,7 +1310,7 @@ def test_branch_existing_nodes(self, basic_attack, node_factory, helpers): # Verify duplicate was called correct number of times for node in initial_nodes: - assert node.duplicate.call_count == 2 + assert node.duplicate_async.call_count == 2 @pytest.mark.usefixtures("patch_central_database") @@ -1350,7 +1336,7 @@ async def test_perform_attack_single_iteration_success(self, attack_builder, nod ) with patch.object(attack, "_create_attack_node", return_value=success_node): - with patch.object(attack._memory, "get_message_pieces", return_value=[]): + with patch.object(attack._memory, "get_message_pieces_async", return_value=[]): result = await attack._perform_async(context=context) assert result.outcome == AttackOutcome.SUCCESS @@ -1377,7 +1363,7 @@ async def test_perform_attack_early_termination_on_success(self, attack_builder, ) with patch.object(attack, "_create_attack_node", return_value=success_node): - with patch.object(attack._memory, "get_message_pieces", return_value=[]): + with patch.object(attack._memory, "get_message_pieces_async", return_value=[]): result = await attack._perform_async(context=context) # Should succeed after first iteration @@ -1423,7 +1409,7 @@ async def test_perform_async_sets_atomic_attack_identifier(self, attack_builder, ) with patch.object(attack, "_create_attack_node", return_value=success_node): - with patch.object(attack._memory, "get_message_pieces", return_value=[]): + with patch.object(attack._memory, "get_message_pieces_async", return_value=[]): result = await attack._perform_async(context=context) assert result.atomic_attack_identifier is not None @@ -1474,7 +1460,7 @@ def test_is_objective_achieved(self, attack_builder, helpers): context.best_objective_score = MagicMock(get_value=MagicMock(return_value=0.9), score_metadata=None) assert attack._is_objective_achieved(context=context) is True - def test_is_objective_achieved_with_threshold_scores(self, attack_builder, helpers): + async def test_is_objective_achieved_with_threshold_scores(self, attack_builder, helpers): """Test _is_objective_achieved with realistic FloatScaleThresholdScorer output. This test verifies that threshold comparison correctly extracts float values @@ -1485,60 +1471,72 @@ def test_is_objective_achieved_with_threshold_scores(self, attack_builder, helpe # Test 1: TrueFalse score with original_float_value below threshold # Even though score_value is "False", we verify the float extraction works - context.best_objective_score = helpers.create_threshold_score(original_float_value=0.5, threshold=0.8) + context.best_objective_score = await helpers.create_threshold_score_async( + original_float_value=0.5, threshold=0.8 + ) assert attack._is_objective_achieved(context=context) is False # Verify normalize_score_to_float extracts the float correctly assert normalize_score_to_float(context.best_objective_score) == 0.5 # Test 2: TrueFalse score with original_float_value at threshold - context.best_objective_score = helpers.create_threshold_score(original_float_value=0.8, threshold=0.8) + context.best_objective_score = await helpers.create_threshold_score_async( + original_float_value=0.8, threshold=0.8 + ) assert attack._is_objective_achieved(context=context) is True assert normalize_score_to_float(context.best_objective_score) == 0.8 # Test 3: TrueFalse score with original_float_value above threshold - context.best_objective_score = helpers.create_threshold_score(original_float_value=0.95, threshold=0.8) + context.best_objective_score = await helpers.create_threshold_score_async( + original_float_value=0.95, threshold=0.8 + ) assert attack._is_objective_achieved(context=context) is True assert normalize_score_to_float(context.best_objective_score) == 0.95 # Test 4: Edge case - float value just below threshold - context.best_objective_score = helpers.create_threshold_score(original_float_value=0.79, threshold=0.8) + context.best_objective_score = await helpers.create_threshold_score_async( + original_float_value=0.79, threshold=0.8 + ) assert attack._is_objective_achieved(context=context) is False assert normalize_score_to_float(context.best_objective_score) == 0.79 - def test_create_success_result_with_threshold_score(self, attack_builder, helpers): + async def test_create_success_result_with_threshold_score(self, attack_builder, helpers): """Test that _create_success_result correctly formats score in outcome_reason.""" attack = attack_builder.with_default_mocks().with_threshold(0.8).build() context = helpers.create_basic_context() # Set up context with a threshold score - context.best_objective_score = helpers.create_threshold_score(original_float_value=0.92, threshold=0.8) + context.best_objective_score = await helpers.create_threshold_score_async( + original_float_value=0.92, threshold=0.8 + ) context.successful_objective_conversation_id = "conv_123" - result = attack._create_success_result(context=context) + result = await attack._create_success_result_async(context=context) # Verify the outcome reason contains the float score, not "True" assert "0.92" in result.outcome_reason assert result.outcome == AttackOutcome.SUCCESS - def test_create_failure_result_with_threshold_score(self, attack_builder, helpers): + async def test_create_failure_result_with_threshold_score(self, attack_builder, helpers): """Test that _create_failure_result correctly formats score in outcome_reason.""" attack = attack_builder.with_default_mocks().with_threshold(0.8).build() context = helpers.create_basic_context() # Set up context with a threshold score below the threshold - context.best_objective_score = helpers.create_threshold_score(original_float_value=0.65, threshold=0.8) + context.best_objective_score = await helpers.create_threshold_score_async( + original_float_value=0.65, threshold=0.8 + ) - result = attack._create_failure_result(context=context) + result = await attack._create_failure_result_async(context=context) # Verify the outcome reason contains the float score, not "False" assert "0.65" in result.outcome_reason assert result.outcome == AttackOutcome.FAILURE - def test_auxiliary_score_summary_uses_threshold_verdicts(self, basic_attack, node_factory, helpers): + async def test_auxiliary_score_summary_uses_threshold_verdicts(self, basic_attack, node_factory, helpers): node = node_factory.create_node() node.auxiliary_scores = { - "true_threshold": helpers.create_threshold_score(original_float_value=0.35, threshold=0.3), - "false_threshold": helpers.create_threshold_score(original_float_value=0.75, threshold=0.8), + "true_threshold": (await helpers.create_threshold_score_async(original_float_value=0.35, threshold=0.3)), + "false_threshold": (await helpers.create_threshold_score_async(original_float_value=0.75, threshold=0.8)), "undetermined": Score(score_type="true_false", status=ScoreStatus.UNDETERMINED), } @@ -1588,9 +1586,9 @@ async def test_execute_async_with_message_uses_it_for_root_node(self, attack_bui mock_result.auxiliary_scores_summary = {} with patch.object(attack, "_perform_async", return_value=mock_result) as mock_perform: - with patch.object(attack._memory, "get_conversation_messages", return_value=[]): - with patch.object(attack._memory, "get_message_pieces", return_value=[]): - with patch.object(attack._memory, "add_attack_results_to_memory", return_value=None): + with patch.object(attack._memory, "get_conversation_messages_async", return_value=[]): + with patch.object(attack._memory, "get_message_pieces_async", return_value=[]): + with patch.object(attack._memory, "add_attack_results_to_memory_async", return_value=None): result = await attack.execute_async( objective="Test objective", next_message=custom_message, @@ -1634,9 +1632,9 @@ async def test_execute_async_success_flow(self, attack_builder, helpers): mock_result.auxiliary_scores_summary = {} with patch.object(attack, "_perform_async", return_value=mock_result): - with patch.object(attack._memory, "get_conversation_messages", return_value=[]): - with patch.object(attack._memory, "get_message_pieces", return_value=[]): - with patch.object(attack._memory, "add_attack_results_to_memory", return_value=None): + with patch.object(attack._memory, "get_conversation_messages_async", return_value=[]): + with patch.object(attack._memory, "get_message_pieces_async", return_value=[]): + with patch.object(attack._memory, "add_attack_results_to_memory_async", return_value=None): result = await attack.execute_async(objective="Test objective", memory_labels={"test": "label"}) assert result.outcome == AttackOutcome.SUCCESS @@ -1664,7 +1662,7 @@ def node_components(self, attack_builder): adversarial_chat_prompt_template = MagicMock(spec=SeedPrompt) adversarial_chat_prompt_template.render_template_value = MagicMock(return_value="rendered template") - prompt_normalizer = MagicMock() + prompt_normalizer = get_mock_prompt_normalizer() prompt_normalizer.send_prompt_async = AsyncMock(return_value=None) # Build the modality router that nodes now require. The builder's mock targets @@ -1725,7 +1723,7 @@ async def test_subsequent_prompt_omits_score_when_feedback_disabled(self, node_c ) with ( - patch.object(node._memory, "get_conversation_messages", return_value=[response]), + patch.object(node._memory, "get_conversation_messages_async", return_value=[response]), patch.object(node, "_get_response_score_async", new_callable=AsyncMock) as get_score, ): result = await node._generate_subsequent_turn_prompt_async("test objective") @@ -1736,14 +1734,14 @@ async def test_subsequent_prompt_omits_score_when_feedback_disabled(self, node_c assert render_kwargs["target_response"] == "target response" assert render_kwargs["score"] == "" - def test_node_duplicate_creates_child(self, node_components): + async def test_node_duplicate_creates_child(self, node_components): """Test that duplicate() creates a proper child node.""" parent_node = _TreeOfAttacksNode(**node_components) parent_node.node_id = "parent_node_id" # Mock memory duplicate conversation - with patch.object(parent_node._memory, "duplicate_conversation", return_value="new_conv_id"): - child_node = parent_node.duplicate() + with patch.object(parent_node._memory, "duplicate_conversation_async", return_value="new_conv_id"): + child_node = await parent_node.duplicate_async() assert child_node.node_id != parent_node.node_id assert child_node.parent_id == parent_node.node_id @@ -1843,7 +1841,7 @@ async def test_send_to_adversarial_chat_invalid_json_raises(self, node_component async def test_node_send_prompt_json_error_handling(self, node_components): """Test handling of JSON parsing errors in send_prompt_async.""" - prompt_normalizer = MagicMock(spec=PromptNormalizer) + prompt_normalizer = get_mock_prompt_normalizer() components_with_normalizer = node_components.copy() components_with_normalizer["prompt_normalizer"] = prompt_normalizer node = _TreeOfAttacksNode(**components_with_normalizer) @@ -1865,7 +1863,7 @@ async def test_node_send_prompt_json_error_handling(self, node_components): async def test_send_to_adversarial_chat_forwards_json_schema(self, node_components): """The shared adversarial_chat JSON schema is forwarded to the target via metadata.""" - prompt_normalizer = MagicMock(spec=PromptNormalizer) + prompt_normalizer = get_mock_prompt_normalizer() components_with_normalizer = node_components.copy() components_with_normalizer["prompt_normalizer"] = prompt_normalizer components_with_normalizer["adversarial_chat"].configuration.capabilities.input_modalities = frozenset( @@ -2257,7 +2255,7 @@ async def test_node_multi_turn_target_keeps_conv_id(self, node_components): class TestTreeOfAttacksErrorHandling: """Tests for error handling in TreeOfAttacksWithPruningAttack.""" - def test_attack_result_uses_response_linked_to_best_score(self, attack_builder, helpers): + async def test_attack_result_uses_response_linked_to_best_score(self, attack_builder, helpers): """A later unscored response must not be paired with an earlier best score.""" attack = attack_builder.with_default_mocks().build() context = helpers.create_basic_context() @@ -2290,10 +2288,10 @@ def test_attack_result_uses_response_linked_to_best_score(self, attack_builder, with patch.object( attack._memory, - "get_message_pieces", + "get_message_pieces_async", return_value=[scored_response, later_response], ): - result = attack._create_failure_result(context) + result = await attack._create_failure_result_async(context) assert result.last_response is scored_response assert result.last_score is best_score @@ -2327,7 +2325,7 @@ async def test_attack_handles_all_nodes_failing(self, attack_builder, helpers, n node_iterator = iter(failing_nodes) with patch.object(attack, "_create_attack_node", side_effect=lambda **kwargs: next(node_iterator)): - with patch.object(attack._memory, "get_message_pieces", return_value=[]): + with patch.object(attack._memory, "get_message_pieces_async", return_value=[]): result = await attack._perform_async(context=context) # Should return failure when all nodes fail @@ -2357,7 +2355,7 @@ async def test_attack_continues_after_node_errors(self, attack_builder, node_fac ) ) fail_node.error_message = "JSON parsing error" - fail_node.duplicate = MagicMock( + fail_node.duplicate_async = AsyncMock( return_value=node_factory.create_node(NodeMockConfig(node_id="fail_dup", objective_score_value=0.3)) ) nodes.append(fail_node) @@ -2372,7 +2370,7 @@ async def test_attack_continues_after_node_errors(self, attack_builder, node_fac # Create all nodes at once node_iter = iter(nodes) with patch.object(attack, "_create_attack_node", side_effect=lambda **kwargs: next(node_iter, nodes[0])): - with patch.object(attack._memory, "get_message_pieces", return_value=[]): + with patch.object(attack._memory, "get_message_pieces_async", return_value=[]): result = await attack._perform_async(context=context) # Attack should continue despite some nodes failing @@ -2576,7 +2574,9 @@ def test_create_attack_node_tracks_adversarial_chat_conversation_id(self, basic_ ) assert len(context.related_conversations) == 1 - def test_branch_existing_nodes_tracks_adversarial_chat_conversation_ids(self, basic_attack, node_factory, helpers): + async def test_branch_existing_nodes_tracks_adversarial_chat_conversation_ids( + self, basic_attack, node_factory, helpers + ): """Test that branching nodes adds their adversarial chat conversation IDs to the context.""" context = helpers.create_basic_context() @@ -2592,7 +2592,7 @@ def test_branch_existing_nodes_tracks_adversarial_chat_conversation_ids(self, ba basic_attack._configuration = replace(basic_attack._configuration, branching_factor=3) # Branch the nodes - basic_attack._branch_existing_nodes(context) + (await basic_attack._branch_existing_nodes_async(context)) # Manually add all node adversarial chat conversation IDs to the set (simulating real code behavior) for node in context.nodes: @@ -2683,7 +2683,7 @@ def test_initialize_first_level_nodes_text_objective_keeps_seed_on_first_root_on assert all(node._initial_prompt is None for node in context.nodes[1:]) assert context.next_message is None - def test_attack_result_includes_adversarial_chat_conversation_ids(self, attack_builder, helpers): + async def test_attack_result_includes_adversarial_chat_conversation_ids(self, attack_builder, helpers): """Test that the attack result includes the tracked adversarial chat conversation IDs.""" attack = attack_builder.with_default_mocks().build() context = helpers.create_basic_context() @@ -2697,7 +2697,7 @@ def test_attack_result_includes_adversarial_chat_conversation_ids(self, attack_b context.best_objective_score = helpers.create_score(0.9) # Create the result - result = attack._create_attack_result( + result = await attack._create_attack_result_async( context=context, outcome=AttackOutcome.SUCCESS, outcome_reason="Test success" ) @@ -2915,7 +2915,7 @@ async def _send_prompt(objective: str) -> None: node.objective_target_conversation_id = str(uuid.uuid4()) node.adversarial_chat_conversation_id = str(uuid.uuid4()) node.send_prompt_async = AsyncMock(side_effect=_send_prompt) - node.duplicate = MagicMock() # replaced per-depth below + node.duplicate_async = AsyncMock() # replaced per-depth below node._call_behaviors = _call_behaviors # expose for re-programming return node @@ -3116,7 +3116,7 @@ def _dup_factory(parent=node, d=next_depth): child = _make_node_with_behavior(cb, f"d{d}_n{_depth_counters.get(d, 0) - 1}") child.parent_id = parent.node_id child._vis_node_id = parent._vis_node_id - child.duplicate = MagicMock(side_effect=lambda p=child, dd=d + 1: _dup_child(p, dd)) + child.duplicate_async = AsyncMock(side_effect=lambda p=child, dd=d + 1: _dup_child(p, dd)) return child def _dup_child(parent_node, d): @@ -3125,10 +3125,10 @@ def _dup_child(parent_node, d): child = _make_node_with_behavior(cb, f"d{d}_n{_depth_counters.get(d, 0) - 1}") child.parent_id = parent_node.node_id child._vis_node_id = parent_node._vis_node_id - child.duplicate = MagicMock(side_effect=lambda p=child, dd=d + 1: _dup_child(p, dd)) + child.duplicate_async = AsyncMock(side_effect=lambda p=child, dd=d + 1: _dup_child(p, dd)) return child - node.duplicate = MagicMock(side_effect=_dup_factory) + node.duplicate_async = AsyncMock(side_effect=_dup_factory) nodes.append(node) return nodes @@ -3148,7 +3148,7 @@ def _create_node_side_effect(**kwargs): context = helpers.create_basic_context() with patch.object(attack, "_create_attack_node", side_effect=_create_node_side_effect): - with patch.object(attack._memory, "get_message_pieces", return_value=[]): + with patch.object(attack._memory, "get_message_pieces_async", return_value=[]): result = await attack._perform_async(context=context) assert result.outcome == expected_outcome, ( @@ -3180,7 +3180,7 @@ def node_components(self, attack_builder): adversarial_chat_prompt_template = MagicMock(spec=SeedPrompt) adversarial_chat_prompt_template.render_template_value = MagicMock(return_value="template") - prompt_normalizer = MagicMock() + prompt_normalizer = get_mock_prompt_normalizer() prompt_normalizer.send_prompt_async = AsyncMock(return_value=None) modality_router = _ModalityFeedbackRouter( @@ -3249,8 +3249,8 @@ async def test_node_send_prompt_to_target_forwards_prev_image(self, node_compone prior_user = Message.from_prompt(prompt="prior", role="user") prior_user.message_pieces[0].conversation_id = node.objective_target_conversation_id prior_assistant = self._make_image_response(node.objective_target_conversation_id) - memory.add_message_to_memory(request=prior_user) - memory.add_message_to_memory(request=prior_assistant) + (await memory.add_message_to_memory_async(request=prior_user)) + (await memory.add_message_to_memory_async(request=prior_assistant)) captured_message: dict = {} diff --git a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks_prepended_conversation.py b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks_prepended_conversation.py index 14dc25f54b..027ce0fba0 100644 --- a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks_prepended_conversation.py +++ b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks_prepended_conversation.py @@ -8,7 +8,9 @@ set the adversarial system prompt and honor ``next_message``. """ +import asyncio import json +from unittest.mock import patch import pytest from unit.mocks import MockPromptTarget @@ -19,6 +21,7 @@ PAIRAttack, TreeOfAttacksWithPruningAttack, ) +from pyrit.memory import SQLiteMemory from pyrit.models import AttackOutcome, Message, MessagePiece, Score from pyrit.score import FloatScaleThresholdScorer from pyrit.score.float_scale.float_scale_scorer import MessageFloatScaleScorer @@ -32,9 +35,9 @@ def __init__(self) -> None: super().__init__() self.system_prompts: list[str] = [] - def set_system_prompt(self, *, system_prompt: str, conversation_id: str, **kwargs) -> None: + async def set_system_prompt_async(self, *, system_prompt: str, conversation_id: str) -> None: self.system_prompts.append(system_prompt) - super().set_system_prompt(system_prompt=system_prompt, conversation_id=conversation_id, **kwargs) + await super().set_system_prompt_async(system_prompt=system_prompt, conversation_id=conversation_id) async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: message = normalized_conversation[-1] @@ -128,7 +131,10 @@ async def test_prepended_conversation_sets_adversarial_system_prompt_with_contex assert all("PRIOR-ASSISTANT-TURN" in system_prompt for system_prompt in adversarial_chat.system_prompts) -async def test_prepended_conversation_sends_next_message_first(sqlite_instance): +@pytest.mark.parametrize("sibling_sends_first", [False, True]) +async def test_prepended_conversation_sends_next_message_first( + *, sqlite_instance: SQLiteMemory, sibling_sends_first: bool +) -> None: objective_target = MockPromptTarget() adversarial_chat = _AdversarialTarget() attack = _build_attack( @@ -142,10 +148,33 @@ async def test_prepended_conversation_sends_next_message_first(sqlite_instance): Message.from_prompt(prompt="PRIOR-ASSISTANT-TURN", role="assistant"), ] - await attack.execute_async( - objective="do X", - prepended_conversation=prepended, - next_message=Message.from_prompt(prompt="MY-CUSTOM-FIRST-PROMPT", role="user"), - ) + requests: list[Message] = [] + sibling_sent = asyncio.Event() + send_async = objective_target._send_prompt_to_target_async - assert objective_target.prompt_sent[0] == "MY-CUSTOM-FIRST-PROMPT" + async def record_send_async(*, normalized_conversation: list[Message]) -> list[Message]: + message = normalized_conversation[-1] + if sibling_sends_first and message.get_value() == "MY-CUSTOM-FIRST-PROMPT": + await asyncio.wait_for(sibling_sent.wait(), timeout=10) + requests.append(message) + responses = await send_async(normalized_conversation=normalized_conversation) + if message.get_value() != "MY-CUSTOM-FIRST-PROMPT": + sibling_sent.set() + return responses + + with patch.object(objective_target, "_send_prompt_to_target_async", side_effect=record_send_async): + await attack.execute_async( + objective="do X", + prepended_conversation=prepended, + next_message=Message.from_prompt(prompt="MY-CUSTOM-FIRST-PROMPT", role="user"), + ) + + seeded_requests = [message for message in requests if message.get_value() == "MY-CUSTOM-FIRST-PROMPT"] + assert len(seeded_requests) == 1 + seeded_conversation_id = seeded_requests[0].message_pieces[0].conversation_id + conversation_requests = [ + message for message in requests if message.message_pieces[0].conversation_id == seeded_conversation_id + ] + assert conversation_requests[0].get_value() == "MY-CUSTOM-FIRST-PROMPT" + if sibling_sends_first: + assert objective_target.prompt_sent[0] != "MY-CUSTOM-FIRST-PROMPT" diff --git a/tests/unit/executor/attack/single_turn/test_prompt_sending.py b/tests/unit/executor/attack/single_turn/test_prompt_sending.py index c4586f119a..b507a513ac 100644 --- a/tests/unit/executor/attack/single_turn/test_prompt_sending.py +++ b/tests/unit/executor/attack/single_turn/test_prompt_sending.py @@ -7,7 +7,12 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest -from unit.mocks import MockPromptTarget, get_mock_scorer_identifier, get_mock_target_identifier +from unit.mocks import ( + MockPromptTarget, + get_mock_prompt_normalizer, + get_mock_scorer_identifier, + get_mock_target_identifier, +) from pyrit.common.random_context import configure_random_seed, get_configured_random_seed from pyrit.converter import Base64Converter, StringJoinConverter @@ -183,7 +188,7 @@ def mock_non_true_false_scorer(): @pytest.fixture def mock_prompt_normalizer(): """Create a mock prompt normalizer for testing""" - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock() return normalizer @@ -437,7 +442,9 @@ async def test_default_converter_scoping_preserves_simulated_assistant_history(s next_message=Message.from_prompt(prompt=final_request, role="user"), ) - pieces = CentralMemory.get_memory_instance().get_message_pieces(conversation_id=result.conversation_id) + pieces = await CentralMemory.get_memory_instance().get_message_pieces_async( + conversation_id=result.conversation_id + ) assistant_piece = next(piece for piece in pieces if piece.original_value == simulated_response) final_piece = next(piece for piece in pieces if piece.original_value == final_request) @@ -465,7 +472,9 @@ async def test_explicit_assistant_role_opt_in_converts_simulated_history(self): next_message=Message.from_prompt(prompt="live request", role="user"), ) - pieces = CentralMemory.get_memory_instance().get_message_pieces(conversation_id=result.conversation_id) + pieces = await CentralMemory.get_memory_instance().get_message_pieces_async( + conversation_id=result.conversation_id + ) assistant_piece = next(piece for piece in pieces if piece.original_value == simulated_response) assert assistant_piece.role == "simulated_assistant" @@ -1328,7 +1337,7 @@ async def slow_objective_score_async(**kwargs) -> list[Score]: objective_started.set() try: await allow_objective_completion.wait() - CentralMemory.get_memory_instance().add_scores_to_memory(scores=[]) + (await CentralMemory.get_memory_instance().add_scores_to_memory_async(scores=[])) events.append("forbidden_objective_write") return [] except asyncio.CancelledError: @@ -1355,11 +1364,11 @@ async def failing_auxiliary_score_async(**kwargs) -> list[Score]: ), ) memory = CentralMemory.get_memory_instance() - original_persist_results = memory.add_attack_results_to_memory + original_persist_results = memory.add_attack_results_to_memory_async persisted_results: list[AttackResult] = [] - def record_attack_results(*, attack_results: list[AttackResult]) -> None: - original_persist_results(attack_results=attack_results) + async def record_attack_results_async(*, attack_results: list[AttackResult]) -> None: + await original_persist_results(attack_results=attack_results) persisted_results.extend(attack_results) events.append("error_persisted") @@ -1369,8 +1378,9 @@ async def record_reset(*, conversation_id: str) -> None: target.reset_conversation_async.side_effect = record_reset with ( - patch.object(memory, "add_attack_results_to_memory", side_effect=record_attack_results) as persist_results, - patch.object(memory, "add_scores_to_memory") as persist_scores, + patch.object( + memory, "add_attack_results_to_memory_async", side_effect=record_attack_results_async + ) as persist_results, patch.object(memory, "add_scores_to_memory_async", new_callable=AsyncMock) as persist_scores_async, ): with pytest.raises(RuntimeError, match="deterministic auxiliary scorer failure"): @@ -1392,10 +1402,9 @@ async def record_reset(*, conversation_id: str) -> None: assert persisted_results[0].outcome_reason == ( "Exception: RuntimeError: deterministic auxiliary scorer failure" ) - stored_results = memory.get_attack_results(objective="Test objective") + stored_results = await memory.get_attack_results_async(objective="Test objective") assert len(stored_results) == 1 assert stored_results[0].outcome == AttackOutcome.ERROR - persist_scores.assert_not_called() persist_scores_async.assert_not_awaited() target.reset_conversation_async.assert_awaited_once_with( conversation_id=persisted_results[0].conversation_id @@ -1406,7 +1415,6 @@ async def record_reset(*, conversation_id: str) -> None: terminal_events = list(events) allow_objective_completion.set() assert events == terminal_events - persist_scores.assert_not_called() persist_scores_async.assert_not_awaited() async def test_teardown_async_is_noop(self, mock_target, basic_context): diff --git a/tests/unit/executor/attack/single_turn/test_skeleton_key.py b/tests/unit/executor/attack/single_turn/test_skeleton_key.py index be47bd17b3..4bcd1d8c38 100644 --- a/tests/unit/executor/attack/single_turn/test_skeleton_key.py +++ b/tests/unit/executor/attack/single_turn/test_skeleton_key.py @@ -7,7 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest -from unit.mocks import get_mock_scorer_identifier, get_mock_target_identifier +from unit.mocks import get_mock_prompt_normalizer, get_mock_scorer_identifier, get_mock_target_identifier from pyrit.executor.attack import ( AttackConverterConfig, @@ -46,7 +46,7 @@ def mock_true_false_scorer(): @pytest.fixture def mock_prompt_normalizer(): - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock() return normalizer diff --git a/tests/unit/executor/attack/streaming/test_barge_in.py b/tests/unit/executor/attack/streaming/test_barge_in.py index 18c4865734..e2bb1cdc60 100644 --- a/tests/unit/executor/attack/streaming/test_barge_in.py +++ b/tests/unit/executor/attack/streaming/test_barge_in.py @@ -167,7 +167,7 @@ async def test_setup_async_persists_prepended_conversation_to_memory(vad_target) ) add_calls: list[Any] = [] - with patch.object(attack._conversation_manager._memory, "add_message_to_memory") as mock_add: + with patch.object(attack._conversation_manager._memory, "add_message_to_memory_async") as mock_add: mock_add.side_effect = lambda **kw: add_calls.append(kw["request"]) await attack._setup_async(context=ctx) @@ -203,7 +203,7 @@ async def test_converted_system_prompt_is_passed_to_streaming_session(vad_target with patch.object(RealtimeTarget, "open_streaming_session", return_value=fake_session) as factory: await attack._perform_async(context=ctx) - persisted = attack._conversation_manager.get_conversation(ctx.conversation_id) + persisted = await attack._conversation_manager.get_conversation_async(ctx.conversation_id) passed_to_session = factory.call_args.kwargs["prepended_conversation"] assert passed_to_session == persisted assert passed_to_session[0].get_piece().converted_value == "WW91IGFyZSBzdHJpY3Qu" @@ -229,7 +229,9 @@ async def test_setup_reusing_conversation_passes_only_new_prepended_messages(vad await attack._setup_async(context=ctx) assert [message.get_value() for message in ctx.prepended_conversation] == ["new system"] - assert [message.get_value() for message in attack._conversation_manager.get_conversation(conversation_id)] == [ + assert [ + message.get_value() for message in (await attack._conversation_manager.get_conversation_async(conversation_id)) + ] == [ "old system", "new system", ] @@ -249,7 +251,7 @@ async def test_setup_async_clears_unused_normalization_context_when_prepended_em ) add_calls: list[Any] = [] - with patch.object(attack._conversation_manager._memory, "add_message_to_memory") as mock_add: + with patch.object(attack._conversation_manager._memory, "add_message_to_memory_async") as mock_add: mock_add.side_effect = lambda **kw: add_calls.append(kw["request"]) await attack._setup_async(context=ctx) diff --git a/tests/unit/executor/attack/test_attack_parameter_consistency.py b/tests/unit/executor/attack/test_attack_parameter_consistency.py index ae972dbf14..b57ef3616a 100644 --- a/tests/unit/executor/attack/test_attack_parameter_consistency.py +++ b/tests/unit/executor/attack/test_attack_parameter_consistency.py @@ -17,6 +17,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest +from unit.mocks import get_mock_prompt_normalizer import pyrit.executor.attack from pyrit.common.path import DATASETS_PATH, EXECUTOR_SEED_PROMPT_PATH @@ -46,7 +47,6 @@ SeedPrompt, get_common_json_schema, ) -from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import PromptTarget from pyrit.score import FloatScaleThresholdScorer, TrueFalseScorer @@ -156,7 +156,7 @@ def mock_chat_target() -> MagicMock: """Create a mock PromptTarget with common setup.""" target = MagicMock(spec=PromptTarget) target.send_prompt_async = AsyncMock() - target.set_system_prompt = MagicMock() + target.set_system_prompt_async = AsyncMock() target.get_identifier.return_value = _mock_target_id("MockChatTarget") target.configuration.capabilities.input_modalities = frozenset({frozenset({"text"})}) target.configuration.capabilities.output_modalities = frozenset({frozenset({"text"})}) @@ -179,7 +179,7 @@ def mock_adversarial_chat() -> MagicMock: """Create a mock adversarial chat target.""" target = MagicMock(spec=PromptTarget) target.send_prompt_async = AsyncMock() - target.set_system_prompt = MagicMock() + target.set_system_prompt_async = AsyncMock() target.get_identifier.return_value = _mock_target_id("MockAdversarialChat") target.configuration.capabilities.input_modalities = frozenset({frozenset({"text"})}) target.configuration.capabilities.output_modalities = frozenset({frozenset({"text"})}) @@ -198,7 +198,7 @@ def mock_objective_scorer() -> MagicMock: @pytest.fixture def mock_prompt_normalizer() -> MagicMock: """Create a mock prompt normalizer.""" - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock() return normalizer @@ -280,7 +280,7 @@ def red_teaming_attack( adversarial_config = AttackAdversarialConfig(target=mock_adversarial_chat) scoring_config = AttackScoringConfig(objective_scorer=mock_objective_scorer) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() # The default RedTeamingAttack adversarial system prompt declares the shared adversarial_chat # JSON schema, so the adversarial reply must be JSON for next_message extraction. json_adversarial_response = Message.from_prompt( @@ -327,7 +327,7 @@ def crescendo_attack( max_turns=10, ) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=sample_response) attack._prompt_normalizer = mock_normalizer @@ -365,7 +365,7 @@ def tap_attack( on_topic_checking_enabled=False, ) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=sample_response) attack._prompt_normalizer = mock_normalizer @@ -393,7 +393,7 @@ async def test_prompt_sending_attack_sends_next_message_multimodal( """Test that PromptSendingAttack sends next_message with multimodal content preserved.""" attack = PromptSendingAttack(objective_target=mock_chat_target) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=sample_response) attack._prompt_normalizer = mock_normalizer @@ -423,7 +423,7 @@ async def test_prompt_sending_attack_sends_fairness_request_as_single_user_messa params = await AttackParameters.from_seed_group_async(seed_group=seed_group) attack = PromptSendingAttack(objective_target=mock_chat_target) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=sample_response) attack._prompt_normalizer = mock_normalizer @@ -466,7 +466,7 @@ async def test_red_teaming_attack_uses_next_message_first_turn( max_turns=5, ) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=sample_response) attack._prompt_normalizer = mock_normalizer @@ -528,7 +528,7 @@ async def test_crescendo_attack_uses_next_message_first_turn( max_turns=5, ) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=sample_response) attack._prompt_normalizer = mock_normalizer @@ -582,7 +582,7 @@ async def test_tree_of_attacks_uses_next_message_first_turn( on_topic_checking_enabled=False, # Disable to simplify test ) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=sample_response) attack._prompt_normalizer = mock_normalizer @@ -806,7 +806,7 @@ async def test_prompt_sending_attack_adds_prepended_to_memory( """Test that prepended conversation is preserved in memory with correct role translation.""" attack = PromptSendingAttack(objective_target=mock_chat_target) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=sample_response) attack._prompt_normalizer = mock_normalizer @@ -819,7 +819,7 @@ async def test_prompt_sending_attack_adds_prepended_to_memory( conversation_id = call_args.kwargs.get("conversation_id") memory = CentralMemory.get_memory_instance() - conversation = list(memory.get_conversation_messages(conversation_id=conversation_id)) + conversation = list(await memory.get_conversation_messages_async(conversation_id=conversation_id)) # Should have exactly the prepended messages in memory (mock normalizer doesn't add responses) assert len(conversation) == 2, f"Expected exactly 2 prepended messages, got {len(conversation)}" @@ -852,7 +852,7 @@ async def test_red_teaming_attack_adds_prepended_to_memory( ) memory = CentralMemory.get_memory_instance() - conversation = list(memory.get_conversation_messages(conversation_id=result.conversation_id)) + conversation = list(await memory.get_conversation_messages_async(conversation_id=result.conversation_id)) # Should have exactly the prepended messages in memory (mock normalizer doesn't add responses) assert len(conversation) == 2, f"Expected exactly 2 prepended messages, got {len(conversation)}" @@ -887,7 +887,7 @@ async def test_crescendo_attack_adds_prepended_to_memory( ) memory = CentralMemory.get_memory_instance() - conversation = list(memory.get_conversation_messages(conversation_id=result.conversation_id)) + conversation = list(await memory.get_conversation_messages_async(conversation_id=result.conversation_id)) # Should have exactly the prepended messages in memory (mock normalizer doesn't add responses) assert len(conversation) == 2, f"Expected exactly 2 prepended messages, got {len(conversation)}" @@ -941,7 +941,7 @@ async def test_tap_attack_adds_prepended_to_memory( on_topic_checking_enabled=False, ) - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(return_value=sample_response) attack._prompt_normalizer = mock_normalizer @@ -955,9 +955,9 @@ async def test_tap_attack_adds_prepended_to_memory( # the single node conversation that holds the prepended messages. assert result.conversation_id memory = CentralMemory.get_memory_instance() - node_conversation_ids = {piece.conversation_id for piece in memory.get_message_pieces()} + node_conversation_ids = {piece.conversation_id for piece in (await memory.get_message_pieces_async())} assert node_conversation_ids == {result.conversation_id} - conversation = list(memory.get_conversation_messages(conversation_id=result.conversation_id)) + conversation = list(await memory.get_conversation_messages_async(conversation_id=result.conversation_id)) # Should have exactly the prepended messages in memory (mock normalizer doesn't add responses) assert len(conversation) == 2, f"Expected exactly 2 prepended messages, got {len(conversation)}" @@ -1049,7 +1049,7 @@ async def test_tap_starts_with_prepended_turn_count( # ============================================================================= -def _get_adversarial_chat_text_values(*, adversarial_chat_conversation_id: str) -> list[str]: +async def _get_adversarial_chat_text_values_async(*, adversarial_chat_conversation_id: str) -> list[str]: """ Get all text values from the adversarial chat conversation in memory. @@ -1062,7 +1062,7 @@ def _get_adversarial_chat_text_values(*, adversarial_chat_conversation_id: str) List of text values from all text pieces in the adversarial conversation. """ memory = CentralMemory.get_memory_instance() - conversation = list(memory.get_conversation_messages(conversation_id=adversarial_chat_conversation_id)) + conversation = list(await memory.get_conversation_messages_async(conversation_id=adversarial_chat_conversation_id)) text_values = [] for msg in conversation: @@ -1073,7 +1073,7 @@ def _get_adversarial_chat_text_values(*, adversarial_chat_conversation_id: str) return text_values -def _assert_prepended_text_in_adversarial_context( +async def _assert_prepended_text_in_adversarial_context_async( *, prepended_conversation: list[Message], adversarial_chat_conversation_id: str, @@ -1098,7 +1098,7 @@ def _assert_prepended_text_in_adversarial_context( Raises: AssertionError: If any prepended text content is not found in adversarial context. """ - adversarial_text_values = _get_adversarial_chat_text_values( + adversarial_text_values = await _get_adversarial_chat_text_values_async( adversarial_chat_conversation_id=adversarial_chat_conversation_id ) @@ -1106,9 +1106,9 @@ def _assert_prepended_text_in_adversarial_context( if ( not adversarial_text_values and adversarial_chat_mock is not None - and adversarial_chat_mock.set_system_prompt.called + and adversarial_chat_mock.set_system_prompt_async.called ): - for call in adversarial_chat_mock.set_system_prompt.call_args_list: + for call in adversarial_chat_mock.set_system_prompt_async.call_args_list: system_prompt = call.kwargs.get("system_prompt", "") if system_prompt: adversarial_text_values.append(system_prompt) @@ -1153,10 +1153,12 @@ async def test_red_teaming_injects_prepended_into_adversarial_context( ] assert len(adversarial_conv_refs) >= 1, "Should have adversarial chat conversation reference" - _assert_prepended_text_in_adversarial_context( - prepended_conversation=prepended_conversation_text, - adversarial_chat_conversation_id=adversarial_conv_refs[0].conversation_id, - adversarial_chat_mock=mock_adversarial_chat, + ( + await _assert_prepended_text_in_adversarial_context_async( + prepended_conversation=prepended_conversation_text, + adversarial_chat_conversation_id=adversarial_conv_refs[0].conversation_id, + adversarial_chat_mock=mock_adversarial_chat, + ) ) async def test_crescendo_injects_prepended_into_adversarial_context( @@ -1180,10 +1182,12 @@ async def test_crescendo_injects_prepended_into_adversarial_context( ] assert len(adversarial_conv_refs) >= 1, "Should have adversarial chat conversation reference" - _assert_prepended_text_in_adversarial_context( - prepended_conversation=prepended_conversation_text, - adversarial_chat_conversation_id=adversarial_conv_refs[0].conversation_id, - adversarial_chat_mock=mock_adversarial_chat, + ( + await _assert_prepended_text_in_adversarial_context_async( + prepended_conversation=prepended_conversation_text, + adversarial_chat_conversation_id=adversarial_conv_refs[0].conversation_id, + adversarial_chat_mock=mock_adversarial_chat, + ) ) async def test_tap_persists_prepended_conversation_in_memory( @@ -1207,9 +1211,9 @@ async def test_tap_persists_prepended_conversation_in_memory( ) memory = CentralMemory.get_memory_instance() - node_conversation_ids = {piece.conversation_id for piece in memory.get_message_pieces()} + node_conversation_ids = {piece.conversation_id for piece in (await memory.get_message_pieces_async())} assert len(node_conversation_ids) == 1, f"Expected one conversation in memory, got {node_conversation_ids}" - conversation = list(memory.get_conversation_messages(conversation_id=node_conversation_ids.pop())) + conversation = list(await memory.get_conversation_messages_async(conversation_id=node_conversation_ids.pop())) node_text = " ".join( piece.original_value diff --git a/tests/unit/executor/attack/test_error_response_scoring.py b/tests/unit/executor/attack/test_error_response_scoring.py index 16936f5936..9dab916aeb 100644 --- a/tests/unit/executor/attack/test_error_response_scoring.py +++ b/tests/unit/executor/attack/test_error_response_scoring.py @@ -14,7 +14,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest -from unit.mocks import store_message +from unit.mocks import store_message_async from pyrit.exceptions import ComponentRole, get_execution_context from pyrit.executor.attack import ( @@ -28,6 +28,7 @@ PromptSendingAttack, SingleTurnAttackContext, ) +from pyrit.memory import MemoryInterface from pyrit.models import ( AttackOutcome, ComponentIdentifier, @@ -61,9 +62,9 @@ def mock_target(): @pytest.fixture def mock_memory(): - memory = MagicMock() - memory.get_conversation_messages.return_value = [] - memory.add_message_to_memory = MagicMock() + memory = MagicMock(spec=MemoryInterface) + memory.get_conversation_messages_async = AsyncMock(return_value=[]) + memory.add_message_to_memory_async = AsyncMock() return memory @@ -259,7 +260,7 @@ async def test_error_response_produces_undetermined_outcome(mock_target, patch_c max_attempts_on_failure=0, ) conversation_id = str(uuid.uuid4()) - error_response = store_message(create_error_response(conversation_id)) + error_response = await store_message_async(create_error_response(conversation_id)) score = await attack._evaluate_response_async( response=error_response, objective=OBJECTIVE, expectation=ScoringExpectation(objective=OBJECTIVE) diff --git a/tests/unit/executor/attack/test_scoring_expectation_transport.py b/tests/unit/executor/attack/test_scoring_expectation_transport.py index 6db8024713..0ba2295b89 100644 --- a/tests/unit/executor/attack/test_scoring_expectation_transport.py +++ b/tests/unit/executor/attack/test_scoring_expectation_transport.py @@ -9,7 +9,7 @@ from unittest.mock import AsyncMock, patch import pytest -from unit.mocks import MockPromptTarget, store_message +from unit.mocks import MockPromptTarget, store_message_async from pyrit.exceptions import ( ComponentRole, @@ -209,10 +209,10 @@ async def test_prompt_sending_persists_effective_expectation_async(self, sqlite_ effective = supplied.model_copy(update={"objective": "attack objective"}) assert result.last_response is not None - [stored] = sqlite_instance.get_scores(score_type="true_false") + [stored] = await sqlite_instance.get_scores_async(score_type="true_false") assert stored.scored_expectation == effective assert stored.scorable == MessageScorable(message_piece_ids=(result.last_response.id,)) - [stored_result] = sqlite_instance.get_attack_results(objective="attack objective") + [stored_result] = await sqlite_instance.get_attack_results_async(objective="attack objective") assert stored_result.automated_score is not None assert stored_result.automated_score.id == stored.id assert stored_result.automated_score.scored_expectation == effective @@ -490,7 +490,7 @@ async def test_chunked_scores_combined_content_with_auxiliary_async(self, sqlite assert all("attack objective" in prompt and "scoring objective" not in prompt for prompt in target.prompt_sent) assert objective.calls == [(ContentScorable(value="default\ndefault"), supplied)] assert auxiliary.calls == objective.calls - scores = sqlite_instance.get_scores(score_type="true_false") + scores = await sqlite_instance.get_scores_async(score_type="true_false") assert len(scores) == 2 assert all(isinstance(score.scorable, ContentEntryScorable) for score in scores) assert all(score.scored_expectation == supplied and score.message_piece_id is None for score in scores) @@ -615,10 +615,12 @@ async def test_tap_node_preserves_execution_expectation_async( assert on_topic.call_args.args == ("attack objective",) await node.send_prompt_async(objective=context.objective) if duplicate: - child = node.duplicate() + child = await node.duplicate_async() response = Message.from_prompt(prompt="branch response", role="assistant") response.get_piece().conversation_id = child.objective_target_conversation_id - await child._score_response_async(response=store_message(response), objective=context.objective) + await child._score_response_async( + response=(await store_message_async(response)), objective=context.objective + ) node = child assert node.objective_score is not None diff --git a/tests/unit/executor/attack/test_seed_expectation_transport.py b/tests/unit/executor/attack/test_seed_expectation_transport.py index ebb79e89e1..3eab395ee9 100644 --- a/tests/unit/executor/attack/test_seed_expectation_transport.py +++ b/tests/unit/executor/attack/test_seed_expectation_transport.py @@ -77,7 +77,7 @@ async def test_tool_seed_round_trip_and_explicit_trace_replay_async( ) dataset = SeedDataset.from_yaml_file(path) await sqlite_instance.add_seeds_to_memory_async(seeds=dataset.seeds, added_by="test") - [stored_group] = sqlite_instance.get_seed_groups(dataset_name="tool_expectations") + [stored_group] = await sqlite_instance.get_seed_groups_async(dataset_name="tool_expectations") params = await AttackParameters.from_seed_group_async(seed_group=AttackSeedGroup(seeds=stored_group.seeds)) assert params.expectation == ScoringExpectation( objective="Read the file", conditions=(ToolsCalled(tools=(ToolCallRequirement(name="read_file"),)),) @@ -102,9 +102,9 @@ async def test_tool_seed_round_trip_and_explicit_trace_replay_async( Scorer.validate_expectation_for_scorers(scorers=[scorer], expectation=None) [score] = await scorer.score_async(scorable=scope, expectation=params.expectation) assert score.get_value() is True - [stored_score] = sqlite_instance.get_scores(score_ids=[score.id]) + [stored_score] = await sqlite_instance.get_scores_async(score_ids=[score.id]) assert stored_score.scored_expectation == params.expectation - [observation] = sqlite_instance.get_observations(observation_ids=score.observation_ids) + [observation] = await sqlite_instance.get_observations_async(observation_ids=score.observation_ids) client.close() changed_seed = SeedObjective( @@ -223,7 +223,7 @@ async def test_compound_uses_child_seed_criteria_async(self, sqlite_instance: SQ result = await compound.execute_async(objective="Parent objective") assert result.outcome == AttackOutcome.SUCCESS - [score] = sqlite_instance.get_scores(score_type="true_false") + [score] = await sqlite_instance.get_scores_async(score_type="true_false") assert score.scored_expectation == group.scoring_expectation async def test_yaml_memory_attack_score_round_trip_async( @@ -249,7 +249,7 @@ async def test_yaml_memory_attack_score_round_trip_async( ) dataset = SeedDataset.from_yaml_file(path) await sqlite_instance.add_seeds_to_memory_async(seeds=dataset.seeds, added_by="test") - [stored_group] = sqlite_instance.get_seed_groups(dataset_name="seed_expectation_transport") + [stored_group] = await sqlite_instance.get_seed_groups_async(dataset_name="seed_expectation_transport") group = AttackSeedGroup(seeds=stored_group.seeds) target = MockPromptTarget() attack = PromptSendingAttack( @@ -262,7 +262,7 @@ async def test_yaml_memory_attack_score_round_trip_async( [result] = batch.get_results() assert result.outcome == AttackOutcome.SUCCESS assert target.prompt_sent == ["Return one word"] - [score] = sqlite_instance.get_scores(score_type="true_false") + [score] = await sqlite_instance.get_scores_async(score_type="true_false") assert score.scored_expectation == group.scoring_expectation assert score.get_value() is True assert result.last_response is not None diff --git a/tests/unit/executor/benchmark/test_fairness_bias.py b/tests/unit/executor/benchmark/test_fairness_bias.py index 64c9e7b461..e6eec7d2b3 100644 --- a/tests/unit/executor/benchmark/test_fairness_bias.py +++ b/tests/unit/executor/benchmark/test_fairness_bias.py @@ -256,7 +256,7 @@ async def test_perform_async_calls_prompt_sending_attack( with patch("pyrit.executor.benchmark.fairness_bias.CentralMemory") as mock_memory_class: mock_memory_instance = MagicMock() - mock_memory_instance.get_conversation_messages.return_value = mock_conversation_pieces + mock_memory_instance.get_conversation_messages_async = AsyncMock(return_value=mock_conversation_pieces) mock_memory_class.get_memory_instance.return_value = mock_memory_instance benchmark = FairnessBiasBenchmark(objective_target=mock_prompt_target) @@ -387,7 +387,7 @@ async def test_execute_async_with_required_parameters( with patch("pyrit.executor.benchmark.fairness_bias.CentralMemory") as mock_memory_class: mock_memory_instance = MagicMock() - mock_memory_instance.get_conversation_messages.return_value = mock_conversation_pieces + mock_memory_instance.get_conversation_messages_async = AsyncMock(return_value=mock_conversation_pieces) mock_memory_class.get_memory_instance.return_value = mock_memory_instance benchmark = FairnessBiasBenchmark(objective_target=mock_prompt_target) @@ -416,7 +416,7 @@ async def test_execute_async_with_optional_parameters( with patch("pyrit.executor.benchmark.fairness_bias.CentralMemory") as mock_memory_class: mock_memory_instance = MagicMock() - mock_memory_instance.get_conversation_messages.return_value = mock_conversation_pieces + mock_memory_instance.get_conversation_messages_async = AsyncMock(return_value=mock_conversation_pieces) mock_memory_class.get_memory_instance.return_value = mock_memory_instance benchmark = FairnessBiasBenchmark(objective_target=mock_prompt_target) @@ -454,7 +454,7 @@ async def test_execute_async_multiple_experiments( with patch("pyrit.executor.benchmark.fairness_bias.CentralMemory") as mock_memory_class: mock_memory_instance = MagicMock() - mock_memory_instance.get_conversation_messages.return_value = mock_conversation_pieces + mock_memory_instance.get_conversation_messages_async = AsyncMock(return_value=mock_conversation_pieces) mock_memory_class.get_memory_instance.return_value = mock_memory_instance benchmark = FairnessBiasBenchmark(objective_target=mock_prompt_target) @@ -508,7 +508,7 @@ async def test_full_benchmark_workflow( with patch("pyrit.executor.benchmark.fairness_bias.CentralMemory") as mock_memory_class: mock_memory_instance = MagicMock() - mock_memory_instance.get_conversation_messages.return_value = mock_conversation_pieces + mock_memory_instance.get_conversation_messages_async = AsyncMock(return_value=mock_conversation_pieces) mock_memory_class.get_memory_instance.return_value = mock_memory_instance benchmark = FairnessBiasBenchmark(objective_target=mock_prompt_target) @@ -550,7 +550,7 @@ async def test_benchmark_with_memory_labels( with patch("pyrit.executor.benchmark.fairness_bias.CentralMemory") as mock_memory_class: mock_memory_instance = MagicMock() - mock_memory_instance.get_conversation_messages.return_value = mock_conversation_pieces + mock_memory_instance.get_conversation_messages_async = AsyncMock(return_value=mock_conversation_pieces) mock_memory_class.get_memory_instance.return_value = mock_memory_instance benchmark = FairnessBiasBenchmark(objective_target=mock_prompt_target) diff --git a/tests/unit/executor/promptgen/fuzzer/test_fuzzer_result_printer.py b/tests/unit/executor/promptgen/fuzzer/test_fuzzer_result_printer.py index 36ddc46ef0..b914c3bdbb 100644 --- a/tests/unit/executor/promptgen/fuzzer/test_fuzzer_result_printer.py +++ b/tests/unit/executor/promptgen/fuzzer/test_fuzzer_result_printer.py @@ -2,11 +2,14 @@ # Licensed under the MIT license. import re +from unittest.mock import patch import pytest from pyrit.converter import AnsiAttackConverter from pyrit.executor.promptgen.fuzzer import FuzzerResult, FuzzerResultPrinter +from pyrit.memory import SQLiteMemory +from pyrit.models import MessagePiece, Score, ScoreStatus # The printer's own colors are SGR sequences, so those are stripped before asserting - but only # when the printer was asked for them. With colors disabled nothing may reach the terminal. @@ -22,12 +25,65 @@ def _assert_no_live_control_characters(printed: str, *, enable_colors: bool) -> @pytest.mark.usefixtures("patch_central_database") class TestFuzzerResultPrinter: + @pytest.mark.parametrize("undetermined", [False, True]) + async def test_formatted_result_reads_conversation_and_scores_async( + self, sqlite_instance: SQLiteMemory, capsys: pytest.CaptureFixture[str], undetermined: bool + ) -> None: + request = MessagePiece(role="user", original_value="test question", conversation_id="jailbreak") + response = MessagePiece(role="assistant", original_value="test answer", conversation_id="jailbreak") + for piece in (request, response): + await sqlite_instance.add_message_to_memory_async(request=piece.to_message()) + await sqlite_instance.add_scores_to_memory_async( + scores=[ + Score( + score_type="true_false", + score_value=None if undetermined else "true", + status=ScoreStatus.UNDETERMINED if undetermined else ScoreStatus.COMPLETE, + score_rationale="judge explanation", + message_piece_id=response.id, + ) + ] + ) + result = FuzzerResult(jailbreak_conversation_ids=["jailbreak"]) + with ( + patch.object(sqlite_instance, "get_message_pieces", side_effect=AssertionError("Sync read")), + patch.object(sqlite_instance, "get_prompt_scores", side_effect=AssertionError("Sync score read")), + ): + await result.print_formatted_async(enable_colors=False, width=80) + + output = capsys.readouterr().out + assert "Conversation 1 (ID: jailbreak)" in output + assert "USER:" in output and "test question" in output + assert "ASSISTANT:" in output and "test answer" in output + value = "undetermined" if undetermined else "True" + assert f"Score: {value} | judge explanation" in output + assert output.count("Score:") == 1 + assert "\x1b" not in output + + @pytest.mark.parametrize("conversation_ids", [[], ["missing"]]) + async def test_formatted_result_handles_missing_conversations( + self, capsys: pytest.CaptureFixture[str], conversation_ids: list[str] + ) -> None: + await FuzzerResult(jailbreak_conversation_ids=conversation_ids).print_formatted_async(enable_colors=False) + + output = capsys.readouterr().out + expected = "No conversation data found" if conversation_ids else "No jailbreak conversations found" + assert expected in output + assert "End of Fuzzer Results" in output + + def test_legacy_formatted_result_warns_and_preserves_output(self, capsys: pytest.CaptureFixture[str]) -> None: + with pytest.warns(DeprecationWarning, match="FuzzerResult.print_formatted"): + FuzzerResult(successful_templates=["example {{ prompt }}"]).print_formatted(enable_colors=False) + output = capsys.readouterr().out + assert "example {{ prompt }}" in output + assert "End of Fuzzer Results" in output + @pytest.mark.parametrize("enable_colors", [True, False]) @pytest.mark.parametrize("payload", AnsiAttackConverter.LIVE_PAYLOADS) - def test_print_result_escapes_control_characters(self, payload: str, enable_colors: bool, capsys) -> None: + async def test_print_result_escapes_control_characters(self, payload: str, enable_colors: bool, capsys) -> None: result = FuzzerResult(successful_templates=[f"template {payload} {{{{ prompt }}}}"]) - FuzzerResultPrinter(enable_colors=enable_colors).print_result(result) + (await FuzzerResultPrinter(enable_colors=enable_colors).print_result_async(result)) _assert_no_live_control_characters(capsys.readouterr().out, enable_colors=enable_colors) @@ -39,11 +95,11 @@ def test_print_templates_only_escapes_control_characters(self, payload: str, cap _assert_no_live_control_characters(capsys.readouterr().out, enable_colors=False) - def test_print_result_escapes_carriage_returns(self, capsys) -> None: + async def test_print_result_escapes_carriage_returns(self, capsys) -> None: # print_result wraps before it colors, and textwrap replaces a lone carriage return with a # space, so the template has to be escaped before it is wrapped. result = FuzzerResult(successful_templates=["alpha\rbeta {{ prompt }}"]) - FuzzerResultPrinter(enable_colors=False).print_result(result) + (await FuzzerResultPrinter(enable_colors=False).print_result_async(result)) assert "alpha\\rbeta" in capsys.readouterr().out diff --git a/tests/unit/executor/promptgen/test_anecdoctor.py b/tests/unit/executor/promptgen/test_anecdoctor.py index 1c14e2ffa0..e72347f02f 100644 --- a/tests/unit/executor/promptgen/test_anecdoctor.py +++ b/tests/unit/executor/promptgen/test_anecdoctor.py @@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +from unit.mocks import get_mock_prompt_normalizer from pyrit.executor.core.config import StrategyConverterConfig from pyrit.executor.promptgen.anecdoctor import ( @@ -29,7 +30,7 @@ def _mock_target_id(name: str = "MockTarget") -> ComponentIdentifier: def mock_objective_target() -> PromptTarget: """Create a mock objective target for testing.""" mock_target = MagicMock(spec=PromptTarget) - mock_target.set_system_prompt = MagicMock() + mock_target.set_system_prompt_async = AsyncMock() mock_target.get_identifier.return_value = _mock_target_id("mock_objective_target") return mock_target @@ -38,7 +39,7 @@ def mock_objective_target() -> PromptTarget: def mock_processing_model() -> PromptTarget: """Create a mock processing model for testing.""" mock_model = MagicMock(spec=PromptTarget) - mock_model.set_system_prompt = MagicMock() + mock_model.set_system_prompt_async = AsyncMock() mock_model.get_identifier.return_value = _mock_target_id("MockProcessingModel") return mock_model @@ -46,7 +47,7 @@ def mock_processing_model() -> PromptTarget: @pytest.fixture def mock_prompt_normalizer() -> PromptNormalizer: """Create a mock prompt normalizer for testing.""" - mock_normalizer = MagicMock(spec=PromptNormalizer) + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() return mock_normalizer @@ -237,7 +238,7 @@ async def test_setup_formats_system_prompt(self, mock_objective_target, sample_c """Test setup formats system prompt with language and content type.""" generator = AnecdoctorGenerator(objective_target=mock_objective_target) - with patch.object(generator._objective_target, "set_system_prompt") as mock_set: + with patch.object(generator._objective_target, "set_system_prompt_async") as mock_set: await generator._setup_async(context=sample_context) mock_set.assert_called_once() diff --git a/tests/unit/executor/workflow/test_xpia.py b/tests/unit/executor/workflow/test_xpia.py index 881ecd1b9e..243e431b40 100644 --- a/tests/unit/executor/workflow/test_xpia.py +++ b/tests/unit/executor/workflow/test_xpia.py @@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +from unit.mocks import get_mock_prompt_normalizer from pyrit.executor.workflow.xpia import ( XPIAContext, @@ -12,8 +13,8 @@ XPIAStatus, XPIAWorkflow, ) +from pyrit.memory import MemoryInterface from pyrit.models import ComponentIdentifier, Message, MessagePiece, Score, ScoreStatus -from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import PromptTarget from pyrit.score import Scorer @@ -68,7 +69,7 @@ def mock_scorer() -> MagicMock: @pytest.fixture def mock_prompt_normalizer() -> MagicMock: """Create a mock prompt normalizer.""" - normalizer = MagicMock(spec=PromptNormalizer) + normalizer = get_mock_prompt_normalizer() normalizer.send_prompt_async = AsyncMock() return normalizer @@ -105,7 +106,7 @@ def workflow( workflow = XPIAWorkflow( attack_setup_target=mock_attack_setup_target, scorer=mock_scorer, prompt_normalizer=mock_prompt_normalizer ) - workflow._memory = MagicMock() + workflow._memory = MagicMock(spec=MemoryInterface) return workflow @@ -249,7 +250,7 @@ async def test_perform_async_workflow_without_scorer( workflow = XPIAWorkflow( attack_setup_target=mock_attack_setup_target, scorer=None, prompt_normalizer=mock_prompt_normalizer ) - workflow._memory = MagicMock() + workflow._memory = MagicMock(spec=MemoryInterface) # Setup mock responses mock_response = MagicMock() @@ -348,7 +349,7 @@ async def test_execute_processing_async_adds_to_memory( ) -> None: """Test that execute processing adds response to memory.""" # Setup mock memory - mock_memory_instance = MagicMock() + mock_memory_instance = MagicMock(spec=MemoryInterface) mock_memory_class.get_memory_instance.return_value = mock_memory_instance # Patch the workflow's _memory attribute to use our mock @@ -361,8 +362,8 @@ async def test_execute_processing_async_adds_to_memory( assert response == "Processing response" # Verify memory addition - mock_memory_instance.add_message_to_memory.assert_called_once() - call_args = mock_memory_instance.add_message_to_memory.call_args + mock_memory_instance.add_message_to_memory_async.assert_called_once() + call_args = mock_memory_instance.add_message_to_memory_async.call_args assert call_args.kwargs["request"] is not None assert isinstance(call_args.kwargs["request"], Message) @@ -393,7 +394,7 @@ async def test_execute_async_with_valid_parameters( """Test execute_async with valid parameters.""" # Create workflow with mocked PromptNormalizer with patch("pyrit.executor.workflow.xpia.PromptNormalizer") as mock_normalizer_class: - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_class.return_value = mock_normalizer @@ -436,7 +437,7 @@ async def test_execute_async_invalid_attack_content_type_raises_error( """Test that execute_async raises error with invalid attack_content type.""" # Create workflow with mocked PromptNormalizer with patch("pyrit.executor.workflow.xpia.PromptNormalizer") as mock_normalizer_class: - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_class.return_value = mock_normalizer @@ -454,7 +455,7 @@ async def test_execute_async_invalid_processing_callback_type_raises_error( """Test that execute_async raises error with invalid processing_callback type.""" # Create workflow with mocked PromptNormalizer with patch("pyrit.executor.workflow.xpia.PromptNormalizer") as mock_normalizer_class: - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_class.return_value = mock_normalizer @@ -476,7 +477,7 @@ async def test_execute_async_invalid_memory_labels_type_raises_error( """Test that execute_async raises error with invalid memory_labels type.""" # Create workflow with mocked PromptNormalizer with patch("pyrit.executor.workflow.xpia.PromptNormalizer") as mock_normalizer_class: - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_class.return_value = mock_normalizer @@ -495,7 +496,7 @@ async def test_execute_async_missing_required_attack_content_raises_error( """Test that execute_async raises error when attack_content is missing.""" # Create workflow with mocked PromptNormalizer with patch("pyrit.executor.workflow.xpia.PromptNormalizer") as mock_normalizer_class: - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_class.return_value = mock_normalizer diff --git a/tests/unit/memory/memory_interface/test_batching_scale.py b/tests/unit/memory/memory_interface/test_batching_scale.py index 30e729ddf1..cb0f8d2482 100644 --- a/tests/unit/memory/memory_interface/test_batching_scale.py +++ b/tests/unit/memory/memory_interface/test_batching_scale.py @@ -73,81 +73,81 @@ def _create_scenario_result( class TestBatchingScale: """Tests for batching when querying with many IDs.""" - def test_get_message_pieces_with_many_prompt_ids(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_with_many_prompt_ids(self, sqlite_instance: MemoryInterface): """Test that get_message_pieces works with more IDs than the batch limit.""" # Create more message pieces than the batch limit num_pieces = _MAX_BIND_VARS + 100 pieces = [_create_message_piece() for _ in range(num_pieces)] # Add to memory - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Query with all IDs - this should work with batching all_ids = [piece.id for piece in pieces] - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids) + results = await sqlite_instance.get_message_pieces_async(prompt_ids=all_ids) assert len(results) == num_pieces, f"Expected {num_pieces} results, got {len(results)}" - def test_get_message_pieces_with_exact_batch_size(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_with_exact_batch_size(self, sqlite_instance: MemoryInterface): """Test that get_message_pieces works with exactly the batch limit.""" num_pieces = _MAX_BIND_VARS pieces = [_create_message_piece() for _ in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) all_ids = [piece.id for piece in pieces] - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids) + results = await sqlite_instance.get_message_pieces_async(prompt_ids=all_ids) assert len(results) == num_pieces - def test_get_message_pieces_with_double_batch_size(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_with_double_batch_size(self, sqlite_instance: MemoryInterface): """Test that get_message_pieces works with double the batch limit.""" num_pieces = _MAX_BIND_VARS * 2 pieces = [_create_message_piece() for _ in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) all_ids = [piece.id for piece in pieces] - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids) + results = await sqlite_instance.get_message_pieces_async(prompt_ids=all_ids) assert len(results) == num_pieces - def test_get_scores_with_many_score_ids(self, sqlite_instance: MemoryInterface): + async def test_get_scores_with_many_score_ids(self, sqlite_instance: MemoryInterface): """Test that get_scores works with more IDs than the batch limit.""" # Create message pieces first (scores need to reference them) num_scores = _MAX_BIND_VARS + 100 pieces = [_create_message_piece() for _ in range(num_scores)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Create and add scores scores = [_create_score(str(piece.id)) for piece in pieces] - sqlite_instance.add_scores_to_memory(scores=scores) + (await sqlite_instance.add_scores_to_memory_async(scores=scores)) # Query with all score IDs - this should work with batching all_score_ids = [str(score.id) for score in scores] - results = sqlite_instance.get_scores(score_ids=all_score_ids) + results = await sqlite_instance.get_scores_async(score_ids=all_score_ids) assert len(results) == num_scores, f"Expected {num_scores} results, got {len(results)}" - def test_get_prompt_scores_with_many_prompt_ids(self, sqlite_instance: MemoryInterface): + async def test_get_prompt_scores_with_many_prompt_ids(self, sqlite_instance: MemoryInterface): """Test that get_prompt_scores works with more prompt IDs than the batch limit.""" # Create message pieces num_pieces = _MAX_BIND_VARS + 50 pieces = [_create_message_piece() for _ in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Create and add scores for half of them num_scores = num_pieces // 2 scores = [_create_score(str(pieces[i].id)) for i in range(num_scores)] - sqlite_instance.add_scores_to_memory(scores=scores) + (await sqlite_instance.add_scores_to_memory_async(scores=scores)) # Query with all prompt IDs - should return scores for pieces that have them all_prompt_ids = [piece.id for piece in pieces] - results = sqlite_instance.get_prompt_scores(prompt_ids=all_prompt_ids) + results = await sqlite_instance.get_prompt_scores_async(prompt_ids=all_prompt_ids) assert len(results) == num_scores, f"Expected {num_scores} results, got {len(results)}" - def test_get_message_pieces_batching_preserves_other_filters(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_batching_preserves_other_filters(self, sqlite_instance: MemoryInterface): """Test that batching still applies other filter conditions correctly.""" # Create pieces with different roles num_pieces = _MAX_BIND_VARS + 50 @@ -156,53 +156,53 @@ def test_get_message_pieces_batching_preserves_other_filters(self, sqlite_instan assistant_pieces = [_create_message_piece(role="assistant") for _ in range(50)] all_pieces = user_pieces + assistant_pieces - sqlite_instance.add_message_pieces_to_memory(message_pieces=all_pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=all_pieces)) # Query with all IDs but filter by role all_ids = [piece.id for piece in all_pieces] - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids, role="user") + results = await sqlite_instance.get_message_pieces_async(prompt_ids=all_ids, role="user") assert len(results) == num_pieces, f"Expected {num_pieces} user pieces, got {len(results)}" - def test_get_message_pieces_small_list_still_works(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_small_list_still_works(self, sqlite_instance: MemoryInterface): """Test that small ID lists (under batch limit) still work correctly.""" num_pieces = 10 pieces = [_create_message_piece() for _ in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) all_ids = [piece.id for piece in pieces] - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids) + results = await sqlite_instance.get_message_pieces_async(prompt_ids=all_ids) assert len(results) == num_pieces - def test_get_message_pieces_with_many_original_values(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_with_many_original_values(self, sqlite_instance: MemoryInterface): """Test that get_message_pieces works with many original_values exceeding batch limit.""" num_pieces = _MAX_BIND_VARS + 100 # Create pieces with unique original values pieces = [_create_message_piece(original_value=f"unique_value_{i}") for i in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Query with all original values all_values = [piece.original_value for piece in pieces] - results = sqlite_instance.get_message_pieces(original_values=all_values) + results = await sqlite_instance.get_message_pieces_async(original_values=all_values) assert len(results) == num_pieces, f"Expected {num_pieces} results, got {len(results)}" - def test_get_message_pieces_with_many_converted_value_sha256(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_with_many_converted_value_sha256(self, sqlite_instance: MemoryInterface): """Test that get_message_pieces works with many converted_value_sha256 exceeding batch limit.""" num_pieces = _MAX_BIND_VARS + 100 pieces = [_create_message_piece(original_value=f"unique_value_{i}") for i in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Get SHA256 hashes from stored pieces - stored_pieces = sqlite_instance.get_message_pieces() + stored_pieces = await sqlite_instance.get_message_pieces_async() all_hashes = [piece.converted_value_sha256 for piece in stored_pieces if piece.converted_value_sha256] assert len(all_hashes) > _MAX_BIND_VARS, "Test setup failed: not enough hashes to trigger batching" - results = sqlite_instance.get_message_pieces(converted_value_sha256=all_hashes) + results = await sqlite_instance.get_message_pieces_async(converted_value_sha256=all_hashes) assert len(results) == len(all_hashes) - def test_get_message_pieces_combines_filters_correctly(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_combines_filters_correctly(self, sqlite_instance: MemoryInterface): """Test that multiple filters can be combined (e.g., prompt_ids AND role).""" # Create message pieces with different roles num_pieces = 50 @@ -211,11 +211,11 @@ def test_get_message_pieces_combines_filters_correctly(self, sqlite_instance: Me assistant_pieces = [_create_message_piece(role="assistant") for _ in range(num_pieces)] all_pieces = user_pieces + assistant_pieces - sqlite_instance.add_message_pieces_to_memory(message_pieces=all_pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=all_pieces)) # Query with both prompt_ids AND role filter user_ids = [piece.id for piece in user_pieces] - results = sqlite_instance.get_message_pieces(prompt_ids=user_ids, role="user") + results = await sqlite_instance.get_message_pieces_async(prompt_ids=user_ids, role="user") # Should return only user pieces (intersection of both filters) assert len(results) == num_pieces @@ -223,20 +223,20 @@ def test_get_message_pieces_combines_filters_correctly(self, sqlite_instance: Me # Query with role filter and a subset of IDs subset_ids = user_ids[:10] - results = sqlite_instance.get_message_pieces(prompt_ids=subset_ids, role="user") + results = await sqlite_instance.get_message_pieces_async(prompt_ids=subset_ids, role="user") assert len(results) == 10 - def test_get_message_pieces_multiple_large_params_simultaneously(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_multiple_large_params_simultaneously(self, sqlite_instance: MemoryInterface): """Test batching with multiple parameters exceeding batch limit simultaneously.""" # Create enough pieces to exceed batch limit with unique values num_pieces = _MAX_BIND_VARS + 200 pieces = [_create_message_piece(original_value=f"original_value_{i}") for i in range(num_pieces)] # Add to memory - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Get all stored pieces to extract their IDs and SHA256 hashes - stored_pieces = sqlite_instance.get_message_pieces() + stored_pieces = await sqlite_instance.get_message_pieces_async() assert len(stored_pieces) >= num_pieces # Extract multiple large parameter lists @@ -246,7 +246,7 @@ def test_get_message_pieces_multiple_large_params_simultaneously(self, sqlite_in # Query with multiple large parameters simultaneously # This tests that ALL parameters are batched correctly, not just one - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( prompt_ids=all_ids, original_values=all_original_values, converted_value_sha256=all_sha256, @@ -266,15 +266,15 @@ def test_get_message_pieces_multiple_large_params_simultaneously(self, sqlite_in assert result_original_values == set(all_original_values), "Returned original_values don't match filter" assert result_sha256 == set(all_sha256), "Returned SHA256 hashes don't match filter" - def test_get_message_pieces_multiple_batched_params_with_query_spy(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_multiple_batched_params_with_query_spy(self, sqlite_instance: MemoryInterface): """Test that batching executes multiple separate queries and merges results correctly.""" # Create pieces exceeding batch limit num_pieces = _MAX_BIND_VARS + 100 pieces = [_create_message_piece(original_value=f"value_{i}") for i in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Get stored pieces - stored_pieces = sqlite_instance.get_message_pieces() + stored_pieces = await sqlite_instance.get_message_pieces_async() all_ids = [piece.id for piece in stored_pieces[:num_pieces]] all_original_values = [piece.original_value for piece in stored_pieces[:num_pieces]] @@ -288,7 +288,9 @@ def spy_query(*args, **kwargs): return original_query(*args, **kwargs) with patch.object(sqlite_instance, "_query_entries", side_effect=spy_query): - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids, original_values=all_original_values) + results = await sqlite_instance.get_message_pieces_async( + prompt_ids=all_ids, original_values=all_original_values + ) # Should get all results despite batching assert len(results) == num_pieces @@ -302,7 +304,9 @@ def spy_query(*args, **kwargs): f"but only got {call_count} calls" ) - def test_get_message_pieces_triple_large_params_preserves_intersection(self, sqlite_instance: MemoryInterface): + async def test_get_message_pieces_triple_large_params_preserves_intersection( + self, sqlite_instance: MemoryInterface + ): """Test that filtering with 3 large parameter lists returns correct intersection.""" # Create a large set of pieces total_pieces = _MAX_BIND_VARS + 150 @@ -310,10 +314,10 @@ def test_get_message_pieces_triple_large_params_preserves_intersection(self, sql _create_message_piece(conversation_id=str(uuid.uuid4()), original_value=f"content_{i}") for i in range(total_pieces) ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Get stored pieces - stored_pieces = sqlite_instance.get_message_pieces() + stored_pieces = await sqlite_instance.get_message_pieces_async() # Create three overlapping large filter lists # List 1: All IDs @@ -327,7 +331,7 @@ def test_get_message_pieces_triple_large_params_preserves_intersection(self, sql filter_sha256 = [p.converted_value_sha256 for p in stored_pieces[:subset_size]] # Query with all three large parameters - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( prompt_ids=filter_ids, original_values=filter_original_values, converted_value_sha256=filter_sha256, @@ -344,12 +348,12 @@ def test_get_message_pieces_triple_large_params_preserves_intersection(self, sql class TestExecuteBatchedQuery: """Tests for the _execute_batched_query helper method.""" - def test_execute_batched_query_small_list_single_query(self, sqlite_instance: MemoryInterface): + async def test_execute_batched_query_small_list_single_query(self, sqlite_instance: MemoryInterface): """Test that small lists execute a single query.""" # Create a small number of pieces (under batch limit) num_pieces = 10 pieces = [_create_message_piece() for _ in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Track query calls original_query = sqlite_instance._query_entries @@ -362,18 +366,18 @@ def spy_query(*args, **kwargs): with patch.object(sqlite_instance, "_query_entries", side_effect=spy_query): all_ids = [piece.id for piece in pieces] - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids) + results = await sqlite_instance.get_message_pieces_async(prompt_ids=all_ids) # Should be a single query for small lists assert call_count == 1 assert len(results) == num_pieces - def test_execute_batched_query_large_list_multiple_queries(self, sqlite_instance: MemoryInterface): + async def test_execute_batched_query_large_list_multiple_queries(self, sqlite_instance: MemoryInterface): """Test that large lists execute multiple separate queries.""" # Create pieces exceeding batch limit num_pieces = _MAX_BIND_VARS * 3 # 3 batches needed pieces = [_create_message_piece() for _ in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Track query calls original_query = sqlite_instance._query_entries @@ -386,34 +390,34 @@ def spy_query(*args, **kwargs): with patch.object(sqlite_instance, "_query_entries", side_effect=spy_query): all_ids = [piece.id for piece in pieces] - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids) + results = await sqlite_instance.get_message_pieces_async(prompt_ids=all_ids) # Should execute 3 separate queries (one per batch) assert call_count == 3, f"Expected 3 queries for 3 batches, got {call_count}" assert len(results) == num_pieces - def test_execute_batched_query_deduplicates_results(self, sqlite_instance: MemoryInterface): + async def test_execute_batched_query_deduplicates_results(self, sqlite_instance: MemoryInterface): """Test that batched queries properly deduplicate results.""" # Create pieces num_pieces = 50 pieces = [_create_message_piece() for _ in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Query with the same IDs repeated (should still return unique results) all_ids = [piece.id for piece in pieces] # Query twice with same IDs - results should still be unique - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids) + results = await sqlite_instance.get_message_pieces_async(prompt_ids=all_ids) assert len(results) == num_pieces # Verify no duplicates result_ids = [r.id for r in results] assert len(result_ids) == len(set(result_ids)), "Results contain duplicate entries" - def test_execute_batched_query_exact_batch_boundary(self, sqlite_instance: MemoryInterface): + async def test_execute_batched_query_exact_batch_boundary(self, sqlite_instance: MemoryInterface): """Test querying with exactly the batch limit (edge case).""" num_pieces = _MAX_BIND_VARS pieces = [_create_message_piece() for _ in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Track query calls original_query = sqlite_instance._query_entries @@ -426,21 +430,21 @@ def spy_query(*args, **kwargs): with patch.object(sqlite_instance, "_query_entries", side_effect=spy_query): all_ids = [piece.id for piece in pieces] - results = sqlite_instance.get_message_pieces(prompt_ids=all_ids) + results = await sqlite_instance.get_message_pieces_async(prompt_ids=all_ids) # Exactly at the limit should still be a single query assert call_count == 1, f"Expected 1 query at exact batch limit, got {call_count}" assert len(results) == num_pieces - def test_batching_with_scores_exceeds_limit(self, sqlite_instance: MemoryInterface): + async def test_batching_with_scores_exceeds_limit(self, sqlite_instance: MemoryInterface): """Test that get_scores handles large numbers of score IDs correctly.""" # Create message pieces and scores exceeding the limit num_items = _MAX_BIND_VARS * 2 + 50 pieces = [_create_message_piece() for _ in range(num_items)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) scores = [_create_score(str(piece.id)) for piece in pieces] - sqlite_instance.add_scores_to_memory(scores=scores) + (await sqlite_instance.add_scores_to_memory_async(scores=scores)) # Query with all score IDs all_score_ids = [str(score.id) for score in scores] @@ -455,7 +459,7 @@ def spy_query(*args, **kwargs): return original_query(*args, **kwargs) with patch.object(sqlite_instance, "_query_entries", side_effect=spy_query): - results = sqlite_instance.get_scores(score_ids=all_score_ids) + results = await sqlite_instance.get_scores_async(score_ids=all_score_ids) # Should execute multiple queries expected_calls = (num_items + _MAX_BIND_VARS - 1) // _MAX_BIND_VARS @@ -474,74 +478,74 @@ def _create_attack_result(conversation_id: str | None = None, objective: str = " class TestAttackResultBatching: """Tests for batching in get_attack_results.""" - def test_get_attack_results_with_many_ids(self, sqlite_instance: MemoryInterface): + async def test_get_attack_results_with_many_ids(self, sqlite_instance: MemoryInterface): """Test that get_attack_results works with more IDs than the batch limit.""" num_results = _MAX_BIND_VARS + 100 results = [_create_attack_result(objective=f"objective_{i}") for i in range(num_results)] - sqlite_instance.add_attack_results_to_memory(attack_results=results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=results)) all_ids = [r.attack_result_id for r in results] - fetched = sqlite_instance.get_attack_results(attack_result_ids=all_ids) + fetched = await sqlite_instance.get_attack_results_async(attack_result_ids=all_ids) assert len(fetched) == num_results, f"Expected {num_results} results, got {len(fetched)}" - def test_get_attack_results_with_many_objective_sha256(self, sqlite_instance: MemoryInterface): + async def test_get_attack_results_with_many_objective_sha256(self, sqlite_instance: MemoryInterface): """Test that get_attack_results works with many objective_sha256 values exceeding batch limit.""" num_results = _MAX_BIND_VARS + 100 results = [_create_attack_result(objective=f"unique_objective_{i}") for i in range(num_results)] - sqlite_instance.add_attack_results_to_memory(attack_results=results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=results)) all_sha256 = [hashlib.sha256(f"unique_objective_{i}".encode()).hexdigest() for i in range(num_results)] - fetched = sqlite_instance.get_attack_results(objective_sha256=all_sha256) + fetched = await sqlite_instance.get_attack_results_async(objective_sha256=all_sha256) assert len(fetched) == num_results, f"Expected {num_results} results, got {len(fetched)}" - def test_get_attack_results_small_list_still_works(self, sqlite_instance: MemoryInterface): + async def test_get_attack_results_small_list_still_works(self, sqlite_instance: MemoryInterface): """Test that small ID lists (under batch limit) still work correctly.""" num_results = 10 results = [_create_attack_result(objective=f"objective_{i}") for i in range(num_results)] - sqlite_instance.add_attack_results_to_memory(attack_results=results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=results)) all_ids = [r.attack_result_id for r in results] - fetched = sqlite_instance.get_attack_results(attack_result_ids=all_ids) + fetched = await sqlite_instance.get_attack_results_async(attack_result_ids=all_ids) assert len(fetched) == num_results - def test_get_attack_results_empty_list_returns_empty(self, sqlite_instance: MemoryInterface): + async def test_get_attack_results_empty_list_returns_empty(self, sqlite_instance: MemoryInterface): """Test that explicit empty list returns empty results.""" results = [_create_attack_result() for _ in range(5)] - sqlite_instance.add_attack_results_to_memory(attack_results=results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=results)) - fetched = sqlite_instance.get_attack_results(attack_result_ids=[]) + fetched = await sqlite_instance.get_attack_results_async(attack_result_ids=[]) assert fetched == [] - fetched = sqlite_instance.get_attack_results(objective_sha256=[]) + fetched = await sqlite_instance.get_attack_results_async(objective_sha256=[]) assert fetched == [] class TestScoresEmptyList: """Tests for get_scores empty list handling.""" - def test_get_scores_empty_list_returns_empty(self, sqlite_instance: MemoryInterface): + async def test_get_scores_empty_list_returns_empty(self, sqlite_instance: MemoryInterface): """Test that get_scores with explicit empty score_ids returns empty results.""" pieces = [_create_message_piece() for _ in range(3)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) scores = [_create_score(str(p.id)) for p in pieces] - sqlite_instance.add_scores_to_memory(scores=scores) + (await sqlite_instance.add_scores_to_memory_async(scores=scores)) - fetched = sqlite_instance.get_scores(score_ids=[]) + fetched = await sqlite_instance.get_scores_async(score_ids=[]) assert fetched == [] class TestEffectiveBatchSize: """Tests for effective batch size reduction when small + large params are combined.""" - def test_batch_size_reduced_by_small_params(self, sqlite_instance: MemoryInterface): + async def test_batch_size_reduced_by_small_params(self, sqlite_instance: MemoryInterface): """Test that batch size is reduced when small IN-clause params consume bind variables.""" # Create pieces with unique values so we can filter by both prompt_ids and original_values num_pieces = _MAX_BIND_VARS + 100 pieces = [_create_message_piece(original_value=f"value_{i}") for i in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # small param: original_values with 200 items (under _MAX_BIND_VARS) small_original_values = [f"value_{i}" for i in range(200)] @@ -557,7 +561,7 @@ def spy_query(*args, **kwargs): return original_query(*args, **kwargs) with patch.object(sqlite_instance, "_query_entries", side_effect=spy_query): - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( prompt_ids=all_ids, original_values=small_original_values, ) @@ -572,11 +576,11 @@ def spy_query(*args, **kwargs): # Results should be the intersection: only pieces whose original_value is in small_original_values assert len(results) == 200 - def test_custom_batch_size_on_execute_batched_query(self, sqlite_instance: MemoryInterface): + async def test_custom_batch_size_on_execute_batched_query(self, sqlite_instance: MemoryInterface): """Test that _execute_batched_query respects custom batch_size parameter.""" num_pieces = 100 pieces = [_create_message_piece() for _ in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) original_query = sqlite_instance._query_entries call_count = 0 @@ -599,12 +603,12 @@ def spy_query(*args, **kwargs): assert call_count == 4, f"Expected 4 queries with batch_size=30, got {call_count}" assert len(results) == num_pieces - def test_multiple_small_params_exceeding_limit_are_promoted(self, sqlite_instance: MemoryInterface): + async def test_multiple_small_params_exceeding_limit_are_promoted(self, sqlite_instance: MemoryInterface): """Test that multiple small params whose total exceeds _MAX_BIND_VARS get promoted to large.""" # Create pieces with unique values num_pieces = 400 pieces = [_create_message_piece(original_value=f"val_{i}") for i in range(num_pieces)] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Two "small" params each at 400 (under 500 individually, but 800 total > 500) ids = [piece.id for piece in pieces] @@ -619,7 +623,7 @@ def spy_query(*args, **kwargs): return original_query(*args, **kwargs) with patch.object(sqlite_instance, "_query_entries", side_effect=spy_query): - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( prompt_ids=ids, original_values=original_vals, ) @@ -633,11 +637,11 @@ def spy_query(*args, **kwargs): class TestScenarioResultBatching: """Tests for batching in get_scenario_results.""" - def test_get_scenario_results_with_many_ids(self, sqlite_instance: MemoryInterface): + async def test_get_scenario_results_with_many_ids(self, sqlite_instance: MemoryInterface): """Test that get_scenario_results works with more IDs than the batch limit.""" num_scenarios = _MAX_BIND_VARS + 50 attack_results = [_create_attack_result(objective=f"objective_{i}") for i in range(num_scenarios)] - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) scenarios = [ _create_scenario_result( @@ -646,14 +650,14 @@ def test_get_scenario_results_with_many_ids(self, sqlite_instance: MemoryInterfa ) for i in range(num_scenarios) ] - sqlite_instance.add_scenario_results_to_memory(scenario_results=scenarios) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=scenarios)) all_ids = [str(s.id) for s in scenarios] - fetched = sqlite_instance.get_scenario_results(scenario_result_ids=all_ids) + fetched = await sqlite_instance.get_scenario_results_async(scenario_result_ids=all_ids) assert len(fetched) == num_scenarios, f"Expected {num_scenarios}, got {len(fetched)}" - def test_get_scenario_results_empty_list_returns_empty(self, sqlite_instance: MemoryInterface): + async def test_get_scenario_results_empty_list_returns_empty(self, sqlite_instance: MemoryInterface): """Test that explicit empty list returns empty results.""" - fetched = sqlite_instance.get_scenario_results(scenario_result_ids=[]) + fetched = await sqlite_instance.get_scenario_results_async(scenario_result_ids=[]) assert fetched == [] 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 e49750e00d..2568889eff 100644 --- a/tests/unit/memory/memory_interface/test_interface_attack_results.py +++ b/tests/unit/memory/memory_interface/test_interface_attack_results.py @@ -9,7 +9,7 @@ from unittest.mock import patch import pytest -from sqlalchemy import select +from sqlalchemy import delete, select from sqlalchemy.dialects import mssql from unit.mocks import get_mock_target_identifier, make_scenario_result @@ -98,12 +98,12 @@ def _after(page: "Sequence[AttackResult]") -> AttackResultKeysetCursor: return AttackResultKeysetCursor.from_attack_result(page[-1]) -def _drain_keyset(memory: MemoryInterface, *, page_size: int, **filters) -> list[AttackResult]: +async def _drain_keyset_async(memory: MemoryInterface, *, page_size: int, **filters) -> list[AttackResult]: """Page through get_attack_results with the keyset cursor until exhausted.""" drained: list[AttackResult] = [] after: AttackResultKeysetCursor | None = None while True: - page = list(memory.get_attack_results(limit=page_size, after=after, **filters)) + page = list(await memory.get_attack_results_async(limit=page_size, after=after, **filters)) drained.extend(page) if len(page) < page_size: break @@ -136,7 +136,7 @@ def test_attack_result_query_requires_keyword_arguments(): _AttackResultQuery(["id"]) # ty: ignore[too-many-positional-arguments] -def test_get_attack_results_forwards_all_parameters_to_query(sqlite_instance: MemoryInterface): +async def test_get_attack_results_forwards_all_parameters_to_query(sqlite_instance: MemoryInterface): """The compatibility API maps every parameter onto the internal query.""" cursor = AttackResultKeysetCursor(timestamp=_BASE_TS, attack_result_id=str(uuid.uuid4())) identifier_filter = IdentifierFilter( @@ -146,28 +146,30 @@ def test_get_attack_results_forwards_all_parameters_to_query(sqlite_instance: Me ) with patch.object(sqlite_instance, "_query_attack_results", return_value=[]) as query_mock: - sqlite_instance.get_attack_results( - attack_result_ids=["id"], - conversation_id="conversation", - objective="objective", - objective_sha256=["sha"], - outcome="success", - attack_classes=["Attack"], - atomic_attack_eval_hashes=["eval"], - converter_classes=["Converter"], - converter_classes_match="any", - has_converters=True, - include_scenario_attacks=False, - operator=["alice"], - operation=["nightly"], - labels={"team": ["red"]}, - targeted_harm_categories=["violence"], - identifier_filters=[identifier_filter], - scenario_result_id=str(uuid.uuid4()), - min_turns=1, - max_turns=5, - limit=10, - after=cursor, + ( + await sqlite_instance.get_attack_results_async( + attack_result_ids=["id"], + conversation_id="conversation", + objective="objective", + objective_sha256=["sha"], + outcome="success", + attack_classes=["Attack"], + atomic_attack_eval_hashes=["eval"], + converter_classes=["Converter"], + converter_classes_match="any", + has_converters=True, + include_scenario_attacks=False, + operator=["alice"], + operation=["nightly"], + labels={"team": ["red"]}, + targeted_harm_categories=["violence"], + identifier_filters=[identifier_filter], + scenario_result_id=str(uuid.uuid4()), + min_turns=1, + max_turns=5, + limit=10, + after=cursor, + ) ) query = query_mock.call_args.kwargs["query"] @@ -195,19 +197,21 @@ def test_get_attack_results_forwards_all_parameters_to_query(sqlite_instance: Me assert query.after == cursor -def test_query_attack_results_matches_compatibility_api(sqlite_instance: MemoryInterface): +async def test_query_attack_results_matches_compatibility_api(sqlite_instance: MemoryInterface): """The internal query executor and compatibility API return the same page.""" - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - _make_attack_result("conv-1", executed_turns=2, outcome=AttackOutcome.SUCCESS, ts_offset=1), - _make_attack_result("conv-2", executed_turns=5, outcome=AttackOutcome.SUCCESS, ts_offset=2), - _make_attack_result("conv-3", executed_turns=7, outcome=AttackOutcome.FAILURE, ts_offset=3), - ] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + _make_attack_result("conv-1", executed_turns=2, outcome=AttackOutcome.SUCCESS, ts_offset=1), + _make_attack_result("conv-2", executed_turns=5, outcome=AttackOutcome.SUCCESS, ts_offset=2), + _make_attack_result("conv-3", executed_turns=7, outcome=AttackOutcome.FAILURE, ts_offset=3), + ] + ) ) query = _AttackResultQuery(outcome=AttackOutcome.SUCCESS.value, min_turns=3, limit=1) direct = sqlite_instance._query_attack_results(query=query) - compatibility = sqlite_instance.get_attack_results( + compatibility = await sqlite_instance.get_attack_results_async( outcome=AttackOutcome.SUCCESS.value, min_turns=3, limit=1, @@ -216,7 +220,7 @@ def test_query_attack_results_matches_compatibility_api(sqlite_instance: MemoryI assert [result.attack_result_id for result in direct] == [result.attack_result_id for result in compatibility] -def test_add_attack_results_to_memory(sqlite_instance: MemoryInterface): +async def test_add_attack_results_to_memory(sqlite_instance: MemoryInterface): """Test adding attack results to memory.""" # Create sample attack results attack_result1 = AttackResult( @@ -240,7 +244,7 @@ def test_add_attack_results_to_memory(sqlite_instance: MemoryInterface): ) # Add attack results to memory - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result1, attack_result2])) # Verify they were added by querying all attack results all_attack_results: Sequence[AttackResultEntry] = sqlite_instance._query_entries(AttackResultEntry) @@ -252,7 +256,7 @@ def test_add_attack_results_to_memory(sqlite_instance: MemoryInterface): assert conversation_ids == {"conv_1", "conv_2"} -def test_get_attack_results_by_ids(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_ids(sqlite_instance: MemoryInterface): """Test retrieving attack results by their IDs.""" # Create and add attack results attack_result1 = AttackResult( @@ -280,7 +284,11 @@ def test_get_attack_results_by_ids(sqlite_instance: MemoryInterface): ) # Add all attack results to memory - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Get all attack result entries to get their IDs all_entries: Sequence[AttackResultEntry] = sqlite_instance._query_entries(AttackResultEntry) @@ -290,7 +298,7 @@ def test_get_attack_results_by_ids(sqlite_instance: MemoryInterface): attack_result_ids = [str(entry.id) for entry in all_entries[:2]] # Retrieve attack results by IDs - retrieved_results = sqlite_instance.get_attack_results(attack_result_ids=attack_result_ids) + retrieved_results = await sqlite_instance.get_attack_results_async(attack_result_ids=attack_result_ids) # Verify correct results were retrieved assert len(retrieved_results) == 2 @@ -298,7 +306,7 @@ def test_get_attack_results_by_ids(sqlite_instance: MemoryInterface): assert retrieved_conversation_ids == {"conv_1", "conv_2"} -def test_get_attack_results_by_conversation_id(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_conversation_id(sqlite_instance: MemoryInterface): """Test retrieving attack results by conversation ID. When duplicate rows exist for the same conversation_id (legacy bug), @@ -330,16 +338,20 @@ 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]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Retrieve attack results by conversation ID — deduplication keeps only the newest - retrieved_results = sqlite_instance.get_attack_results(conversation_id="conv_1") + retrieved_results = await sqlite_instance.get_attack_results_async(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): +async def test_get_attack_results_by_objective(sqlite_instance: MemoryInterface): """Test retrieving attack results by objective substring.""" # Create and add attack results attack_result1 = AttackResult( @@ -367,10 +379,14 @@ def test_get_attack_results_by_objective(sqlite_instance: MemoryInterface): ) # Add all attack results to memory - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Retrieve attack results by objective substring - retrieved_results = sqlite_instance.get_attack_results(objective="objective for") + retrieved_results = await sqlite_instance.get_attack_results_async(objective="objective for") # Verify correct results were retrieved (should match first two) assert len(retrieved_results) == 2 @@ -379,7 +395,7 @@ def test_get_attack_results_by_objective(sqlite_instance: MemoryInterface): assert "Another objective for failure" in objectives -def test_get_attack_results_by_outcome(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_outcome(sqlite_instance: MemoryInterface): """Test retrieving attack results by outcome.""" # Create and add attack results attack_result1 = AttackResult( @@ -407,10 +423,14 @@ def test_get_attack_results_by_outcome(sqlite_instance: MemoryInterface): ) # Add all attack results to memory - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Retrieve attack results by outcome - retrieved_results = sqlite_instance.get_attack_results(outcome="success") + retrieved_results = await sqlite_instance.get_attack_results_async(outcome="success") # Verify correct results were retrieved assert len(retrieved_results) == 2 @@ -418,7 +438,7 @@ def test_get_attack_results_by_outcome(sqlite_instance: MemoryInterface): assert result.outcome == AttackOutcome.SUCCESS -def test_get_attack_results_by_objective_sha256(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_objective_sha256(sqlite_instance: MemoryInterface): """Test retrieving attack results by objective SHA256.""" # Create objectives with known SHA256 hashes @@ -454,10 +474,16 @@ def test_get_attack_results_by_objective_sha256(sqlite_instance: MemoryInterface ) # Add all attack results to memory - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Retrieve attack results by objective SHA256 - retrieved_results = sqlite_instance.get_attack_results(objective_sha256=[objective1_sha256, objective2_sha256]) + retrieved_results = await sqlite_instance.get_attack_results_async( + objective_sha256=[objective1_sha256, objective2_sha256] + ) # Verify correct results were retrieved assert len(retrieved_results) == 2 @@ -466,7 +492,7 @@ def test_get_attack_results_by_objective_sha256(sqlite_instance: MemoryInterface assert objective2 in retrieved_objectives -def test_get_attack_results_multiple_filters(sqlite_instance: MemoryInterface): +async def test_get_attack_results_multiple_filters(sqlite_instance: MemoryInterface): """Test retrieving attack results with multiple filters.""" # Create and add attack results attack_result1 = AttackResult( @@ -494,10 +520,14 @@ def test_get_attack_results_multiple_filters(sqlite_instance: MemoryInterface): ) # Add all attack results to memory - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Retrieve attack results with multiple filters - retrieved_results = sqlite_instance.get_attack_results( + retrieved_results = await sqlite_instance.get_attack_results_async( conversation_id="conv_1", objective="objective for", outcome="success" ) @@ -508,7 +538,7 @@ def test_get_attack_results_multiple_filters(sqlite_instance: MemoryInterface): assert "objective for" in retrieved_results[0].objective -def test_get_attack_results_no_filters(sqlite_instance: MemoryInterface): +async def test_get_attack_results_no_filters(sqlite_instance: MemoryInterface): """Test retrieving all attack results when no filters are provided.""" # Create and add attack results attack_result1 = AttackResult( @@ -528,16 +558,16 @@ def test_get_attack_results_no_filters(sqlite_instance: MemoryInterface): ) # Add attack results to memory - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result1, attack_result2])) # Retrieve all attack results (no filters) - retrieved_results = sqlite_instance.get_attack_results() + retrieved_results = await sqlite_instance.get_attack_results_async() # Should return all results assert len(retrieved_results) == 2 -def test_get_attack_results_empty_list(sqlite_instance: MemoryInterface): +async def test_get_attack_results_empty_list(sqlite_instance: MemoryInterface): """Test retrieving attack results with empty ID list.""" # Create and add an attack result attack_result = AttackResult( @@ -548,14 +578,14 @@ def test_get_attack_results_empty_list(sqlite_instance: MemoryInterface): outcome=AttackOutcome.SUCCESS, ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) # Try to retrieve with empty list - retrieved_results = sqlite_instance.get_attack_results(attack_result_ids=[]) + retrieved_results = await sqlite_instance.get_attack_results_async(attack_result_ids=[]) assert len(retrieved_results) == 0 -def test_get_attack_results_nonexistent_ids(sqlite_instance: MemoryInterface): +async def test_get_attack_results_nonexistent_ids(sqlite_instance: MemoryInterface): """Test retrieving attack results with non-existent IDs.""" # Create and add an attack result attack_result = AttackResult( @@ -566,15 +596,15 @@ def test_get_attack_results_nonexistent_ids(sqlite_instance: MemoryInterface): outcome=AttackOutcome.SUCCESS, ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) # Try to retrieve with non-existent IDs nonexistent_ids = [str(uuid.uuid4()), str(uuid.uuid4())] - retrieved_results = sqlite_instance.get_attack_results(attack_result_ids=nonexistent_ids) + retrieved_results = await sqlite_instance.get_attack_results_async(attack_result_ids=nonexistent_ids) assert len(retrieved_results) == 0 -def test_attack_result_with_last_response_and_scores(sqlite_instance: MemoryInterface): +async def test_attack_result_with_last_response_and_scores(sqlite_instance: MemoryInterface): """Test attack result response and score relationships.""" # Create a message piece first message_piece = MessagePiece( @@ -608,8 +638,8 @@ def test_attack_result_with_last_response_and_scores(sqlite_instance: MemoryInte ) # Add message piece and score to memory - sqlite_instance.add_message_pieces_to_memory(message_pieces=[message_piece]) - sqlite_instance.add_scores_to_memory(scores=[score, human_score]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[message_piece])) + (await sqlite_instance.add_scores_to_memory_async(scores=[score, human_score])) # Create attack result with both score sources attack_result = AttackResult( @@ -624,10 +654,10 @@ def test_attack_result_with_last_response_and_scores(sqlite_instance: MemoryInte ) # Add attack result to memory - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) # Retrieve and verify relationships - all_entries: Sequence[AttackResult] = sqlite_instance.get_attack_results() + all_entries: Sequence[AttackResult] = await sqlite_instance.get_attack_results_async() assert len(all_entries) == 1 assert all_entries[0].conversation_id == "conv_1" assert all_entries[0].last_response is not None @@ -640,7 +670,7 @@ def test_attack_result_with_last_response_and_scores(sqlite_instance: MemoryInte assert all_entries[0].last_score.id == human_score.id -def test_attack_result_all_outcomes(sqlite_instance: MemoryInterface): +async def test_attack_result_all_outcomes(sqlite_instance: MemoryInterface): """Test attack results with all possible outcomes.""" outcomes = [AttackOutcome.SUCCESS, AttackOutcome.FAILURE, AttackOutcome.UNDETERMINED] attack_results = [] @@ -660,7 +690,7 @@ def test_attack_result_all_outcomes(sqlite_instance: MemoryInterface): attack_results.append(attack_result) # Add all attack results to memory - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) # Verify all were added all_entries: Sequence[AttackResultEntry] = sqlite_instance._query_entries(AttackResultEntry) @@ -672,7 +702,7 @@ def test_attack_result_all_outcomes(sqlite_instance: MemoryInterface): assert stored_outcomes == set(outcomes) -def test_attack_result_metadata_handling(sqlite_instance: MemoryInterface): +async def test_attack_result_metadata_handling(sqlite_instance: MemoryInterface): """Test that attack result metadata is properly stored and retrieved.""" # Create attack result with various metadata types metadata = { @@ -693,7 +723,7 @@ def test_attack_result_metadata_handling(sqlite_instance: MemoryInterface): metadata=metadata, ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) # Retrieve and verify metadata all_entries: Sequence[AttackResultEntry] = sqlite_instance._query_entries(AttackResultEntry) @@ -703,7 +733,7 @@ def test_attack_result_metadata_handling(sqlite_instance: MemoryInterface): assert retrieved_result.metadata == metadata -def test_attack_result_objective_sha256_auto_generation(sqlite_instance: MemoryInterface): +async def test_attack_result_objective_sha256_auto_generation(sqlite_instance: MemoryInterface): """Test that objective SHA256 is always calculated.""" objective = "Test objective without SHA256" @@ -716,7 +746,7 @@ def test_attack_result_objective_sha256_auto_generation(sqlite_instance: MemoryI ) expected_sha256 = to_sha256(attack_result.objective) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) # Retrieve and verify that objective_sha256 is calculated all_entries: Sequence[AttackResultEntry] = sqlite_instance._query_entries(AttackResultEntry) @@ -726,7 +756,7 @@ def test_attack_result_objective_sha256_auto_generation(sqlite_instance: MemoryI assert all_entries[0].objective_sha256 == expected_sha256 -def test_attack_result_with_attack_generation_conversation_ids(sqlite_instance: MemoryInterface): +async def test_attack_result_with_attack_generation_conversation_ids(sqlite_instance: MemoryInterface): """Test attack result with persisted related conversations.""" pruned_ids = {"pruned_conv_1", "pruned_conv_2"} adversarial_ids = {"adv_conv_1", "adv_conv_2", "adv_conv_3"} @@ -753,7 +783,7 @@ def test_attack_result_with_attack_generation_conversation_ids(sqlite_instance: related_conversations=related_conversations, ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) entry: AttackResultEntry = sqlite_instance._query_entries(AttackResultEntry)[0] @@ -773,7 +803,7 @@ def test_attack_result_with_attack_generation_conversation_ids(sqlite_instance: } == preparation_ids -def test_attack_result_without_attack_generation_conversation_ids(sqlite_instance: MemoryInterface): +async def test_attack_result_without_attack_generation_conversation_ids(sqlite_instance: MemoryInterface): """Test attack result without related_conversations.""" attack_result = AttackResult( conversation_id="conv_1", @@ -783,7 +813,7 @@ def test_attack_result_without_attack_generation_conversation_ids(sqlite_instanc outcome=AttackOutcome.SUCCESS, ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) entry: AttackResultEntry = sqlite_instance._query_entries(AttackResultEntry)[0] assert not entry.pruned_conversation_ids @@ -796,7 +826,7 @@ def test_attack_result_without_attack_generation_conversation_ids(sqlite_instanc assert not retrieved_result.get_conversations_by_type(ConversationType.PREPARATION) -def test_update_attack_result_adversarial_chat_conversation_ids_round_trip(sqlite_instance: MemoryInterface): +async 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 @@ -809,30 +839,34 @@ def test_update_attack_result_adversarial_chat_conversation_ids_round_trip(sqlit 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]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) # Verify initial state: no related conversations - results = sqlite_instance.get_attack_results(conversation_id="conv_1") + results = await sqlite_instance.get_attack_results_async(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"]}, + ( + await sqlite_instance.update_attack_result_async( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1"]}, + ) ) - results = sqlite_instance.get_attack_results(conversation_id="conv_1") + results = await sqlite_instance.get_attack_results_async(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"]}, + ( + await sqlite_instance.update_attack_result_async( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1", "branch-2"]}, + ) ) - results = sqlite_instance.get_attack_results(conversation_id="conv_1") + results = await sqlite_instance.get_attack_results_async(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"} @@ -841,7 +875,7 @@ def test_update_attack_result_adversarial_chat_conversation_ids_round_trip(sqlit assert ref.conversation_type == ConversationType.ADVERSARIAL -def test_update_attack_result_metadata_does_not_clobber_conversation_ids(sqlite_instance: MemoryInterface): +async 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 @@ -854,29 +888,35 @@ def test_update_attack_result_metadata_does_not_clobber_conversation_ids(sqlite_ outcome=AttackOutcome.UNDETERMINED, metadata={"created_at": "2026-01-01T00:00:00"}, ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(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"]}, + ( + await sqlite_instance.update_attack_result_async( + 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"}}, + ( + await sqlite_instance.update_attack_result_async( + 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") + results = await sqlite_instance.get_attack_results_async(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): +async 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 @@ -890,7 +930,7 @@ def test_update_attack_result_stale_entry_does_not_overwrite(sqlite_instance: Me outcome=AttackOutcome.UNDETERMINED, metadata={"created_at": "2026-01-01T00:00:00"}, ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) # Load entry (will become stale) stale_entries = sqlite_instance._query_entries( @@ -899,9 +939,11 @@ def test_update_attack_result_stale_entry_does_not_overwrite(sqlite_instance: Me 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"]}, + ( + await sqlite_instance.update_attack_result_async( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1"]}, + ) ) # Now update with the stale entry (only metadata) @@ -911,14 +953,14 @@ def test_update_attack_result_stale_entry_does_not_overwrite(sqlite_instance: Me ) # Verify the concurrent update was NOT lost - results = sqlite_instance.get_attack_results(conversation_id="conv_1") + results = await sqlite_instance.get_attack_results_async(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_labels_single(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_labels_single(sqlite_instance: MemoryInterface): """Test filtering attack results by single label.""" # Create attack results with labels @@ -930,20 +972,24 @@ def test_get_attack_results_by_labels_single(sqlite_instance: MemoryInterface): "conv_3", 3, AttackOutcome.SUCCESS, labels={"operation": "other_op", "operator": "roakey"} ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Test filtering by labels - test_op_results = sqlite_instance.get_attack_results(labels={"operation": "test_op"}) + test_op_results = await sqlite_instance.get_attack_results_async(labels={"operation": "test_op"}) assert len(test_op_results) == 2 conversation_ids = {result.conversation_id for result in test_op_results} assert conversation_ids == {"conv_1", "conv_2"} - roakey_results = sqlite_instance.get_attack_results(labels={"operator": "roakey"}) + roakey_results = await sqlite_instance.get_attack_results_async(labels={"operator": "roakey"}) assert len(roakey_results) == 2 conversation_ids = {result.conversation_id for result in roakey_results} assert conversation_ids == {"conv_1", "conv_3"} -def test_get_attack_results_by_labels_empty_sequence_value_skips_key(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_labels_empty_sequence_value_skips_key(sqlite_instance: MemoryInterface): """An empty sequence for a label key is skipped (no filter applied for that key). Includes an attack with empty labels and another with no ``operator`` key to guard @@ -953,16 +999,16 @@ def test_get_attack_results_by_labels_empty_sequence_value_skips_key(sqlite_inst ar2 = create_attack_result("conv_2", 2, AttackOutcome.SUCCESS, labels={"operator": "alice"}) ar3 = create_attack_result("conv_3", 3, AttackOutcome.SUCCESS, labels={"phase": "initial"}) ar4 = create_attack_result("conv_4", 4, AttackOutcome.SUCCESS, labels={}) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3, ar4]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3, ar4])) # Empty sequence for "operator" → filter is ignored entirely, all attacks match # (including conv_3 which has no "operator" key and conv_4 which has no labels). - results = sqlite_instance.get_attack_results(labels={"operator": []}) + results = await sqlite_instance.get_attack_results_async(labels={"operator": []}) assert {r.conversation_id for r in results} == {"conv_1", "conv_2", "conv_3", "conv_4"} # Mixed: one key with empty-sequence (ignored) + one real filter should behave # exactly like the real filter alone. - mixed = sqlite_instance.get_attack_results(labels={"operator": [], "phase": "initial"}) + mixed = await sqlite_instance.get_attack_results_async(labels={"operator": [], "phase": "initial"}) assert {r.conversation_id for r in mixed} == {"conv_3"} @@ -975,16 +1021,16 @@ def test_get_attack_results_by_labels_empty_sequence_value_skips_key(sqlite_inst "", ], ) -def test_get_attack_results_rejects_invalid_label_keys(sqlite_instance: MemoryInterface, bad_key: str): +async def test_get_attack_results_rejects_invalid_label_keys(sqlite_instance: MemoryInterface, bad_key: str): """Label keys are interpolated into JSON path expressions by the per-backend helpers, so keys outside the ``[A-Za-z0-9_.-]+`` allowlist must be rejected before reaching the SQL layer (defense against JSON-path / SQL injection). """ with pytest.raises(ValueError, match="Invalid label key"): - sqlite_instance.get_attack_results(labels={bad_key: "value"}) + (await sqlite_instance.get_attack_results_async(labels={bad_key: "value"})) -def test_get_attack_results_by_labels_multiple(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_labels_multiple(sqlite_instance: MemoryInterface): """Test filtering attack results by multiple labels (AND logic).""" # Create attack results with multiple labels @@ -1009,82 +1055,92 @@ def test_get_attack_results_by_labels_multiple(sqlite_instance: MemoryInterface) ), ] - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) # Test filtering by multiple labels (AND logic) - roakey_initial_results = sqlite_instance.get_attack_results(labels={"operator": "roakey", "phase": "initial"}) + roakey_initial_results = await sqlite_instance.get_attack_results_async( + labels={"operator": "roakey", "phase": "initial"} + ) assert len(roakey_initial_results) == 1 assert roakey_initial_results[0].conversation_id == "conv_1" - test_op_roakey_results = sqlite_instance.get_attack_results(labels={"operation": "test_op", "operator": "roakey"}) + test_op_roakey_results = await sqlite_instance.get_attack_results_async( + labels={"operation": "test_op", "operator": "roakey"} + ) assert len(test_op_roakey_results) == 2 conversation_ids = {result.conversation_id for result in test_op_roakey_results} assert conversation_ids == {"conv_1", "conv_2"} -def test_get_attack_results_by_labels_or_within_key(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_labels_or_within_key(sqlite_instance: MemoryInterface): """Test that a sequence value for a label key matches any of the values (OR-within-key).""" - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - create_attack_result("conv_1", 1, labels={"operator": "alice"}), - create_attack_result("conv_2", 2, labels={"operator": "bob"}), - create_attack_result("conv_3", 3, labels={"operator": "charlie"}), - ] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + create_attack_result("conv_1", 1, labels={"operator": "alice"}), + create_attack_result("conv_2", 2, labels={"operator": "bob"}), + create_attack_result("conv_3", 3, labels={"operator": "charlie"}), + ] + ) ) - results = sqlite_instance.get_attack_results(labels={"operator": ["alice", "bob"]}) + results = await sqlite_instance.get_attack_results_async(labels={"operator": ["alice", "bob"]}) assert {r.conversation_id for r in results} == {"conv_1", "conv_2"} -def test_get_attack_results_by_labels_or_within_key_and_across_keys(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_labels_or_within_key_and_across_keys(sqlite_instance: MemoryInterface): """Test that OR-within-key composes with AND-across-keys.""" - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - create_attack_result("conv_1", 1, labels={"operator": "alice", "operation": "red"}), - create_attack_result("conv_2", 2, labels={"operator": "bob", "operation": "red"}), - create_attack_result("conv_3", 3, labels={"operator": "charlie", "operation": "red"}), - create_attack_result("conv_4", 4, labels={"operator": "alice", "operation": "blue"}), - ] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + create_attack_result("conv_1", 1, labels={"operator": "alice", "operation": "red"}), + create_attack_result("conv_2", 2, labels={"operator": "bob", "operation": "red"}), + create_attack_result("conv_3", 3, labels={"operator": "charlie", "operation": "red"}), + create_attack_result("conv_4", 4, labels={"operator": "alice", "operation": "blue"}), + ] + ) ) - results = sqlite_instance.get_attack_results(labels={"operator": ["alice", "bob"], "operation": ["red"]}) + results = await sqlite_instance.get_attack_results_async( + labels={"operator": ["alice", "bob"], "operation": ["red"]} + ) assert {r.conversation_id for r in results} == {"conv_1", "conv_2"} -def test_get_attack_results_labels_no_matches(sqlite_instance: MemoryInterface): +async def test_get_attack_results_labels_no_matches(sqlite_instance: MemoryInterface): """Test filtering by labels that don't exist.""" # Create attack result with labels that don't match the search attack_result = create_attack_result("conv_1", 1, AttackOutcome.SUCCESS, labels={"operation": "test_op"}) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) # Search for non-existent labels - results = sqlite_instance.get_attack_results(labels={"nonexistent": "value"}) + results = await sqlite_instance.get_attack_results_async(labels={"nonexistent": "value"}) assert len(results) == 0 -def test_get_attack_results_labels_query_on_empty_labels(sqlite_instance: MemoryInterface): +async def test_get_attack_results_labels_query_on_empty_labels(sqlite_instance: MemoryInterface): """Test querying for labels when records have no labels at all""" # Create attack results with NO labels attack_result1 = create_attack_result("conv_1", 1, AttackOutcome.SUCCESS) attack_result2 = create_attack_result("conv_2", 2, AttackOutcome.FAILURE) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result1, attack_result2])) - results = sqlite_instance.get_attack_results(labels={"operation": "test"}) + results = await sqlite_instance.get_attack_results_async(labels={"operation": "test"}) assert len(results) == 0 - results = sqlite_instance.get_attack_results(labels={"researcher": "roakey"}) + results = await sqlite_instance.get_attack_results_async(labels={"researcher": "roakey"}) assert len(results) == 0 - results = sqlite_instance.get_attack_results(labels={"non_existing_key": "no_value"}) + results = await sqlite_instance.get_attack_results_async(labels={"non_existing_key": "no_value"}) assert len(results) == 0 -def test_get_attack_results_labels_key_exists_value_mismatch(sqlite_instance: MemoryInterface): +async def test_get_attack_results_labels_key_exists_value_mismatch(sqlite_instance: MemoryInterface): """Test querying for labels where the key exists but the value doesn't match.""" # Create attack results with specific label values @@ -1097,43 +1153,45 @@ def test_get_attack_results_labels_key_exists_value_mismatch(sqlite_instance: Me ), create_attack_result("conv_3", 3, AttackOutcome.FAILURE, labels={"operation": "test_op"}), ] - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) # Query for key that exists but with wrong value - results = sqlite_instance.get_attack_results(labels={"operation": "op_doesnotexist"}) + results = await sqlite_instance.get_attack_results_async(labels={"operation": "op_doesnotexist"}) assert len(results) == 0 # Query for existing key with correct value - results = sqlite_instance.get_attack_results(labels={"operation": "op_exists"}) + results = await sqlite_instance.get_attack_results_async(labels={"operation": "op_exists"}) assert len(results) == 1 assert results[0].conversation_id == "conv_1" # Another key exists but wrong value - results = sqlite_instance.get_attack_results(labels={"researcher": "not_roakey"}) + results = await sqlite_instance.get_attack_results_async(labels={"researcher": "not_roakey"}) assert len(results) == 0 # Correct key and value - results = sqlite_instance.get_attack_results(labels={"researcher": "roakey"}) + results = await sqlite_instance.get_attack_results_async(labels={"researcher": "roakey"}) assert len(results) == 2 assert results[0].conversation_id == "conv_1" # Key exists in some records but not others, and we query for wrong value - results = sqlite_instance.get_attack_results( + results = await sqlite_instance.get_attack_results_async( labels={"operation": "wrong_value"} ) # operation exists in conv_3 but with "test_op" assert len(results) == 0 # Correct key and value for the third record - results = sqlite_instance.get_attack_results(labels={"operation": "test_op"}) + results = await sqlite_instance.get_attack_results_async(labels={"operation": "test_op"}) assert len(results) == 1 assert results[0].conversation_id == "conv_3" # Test multiple keys where one matches and one doesn't - results = sqlite_instance.get_attack_results(labels={"operation": "op_exists", "researcher": "not_roakey"}) + results = await sqlite_instance.get_attack_results_async( + labels={"operation": "op_exists", "researcher": "not_roakey"} + ) assert len(results) == 0 # Test multiple keys where both match - results = sqlite_instance.get_attack_results(labels={"operation": "op_exists", "researcher": "roakey"}) + results = await sqlite_instance.get_attack_results_async(labels={"operation": "op_exists", "researcher": "roakey"}) assert len(results) == 1 assert results[0].conversation_id == "conv_1" @@ -1143,29 +1201,29 @@ def test_get_attack_results_labels_key_exists_value_mismatch(sqlite_instance: Me # --------------------------------------------------------------------------- -def test_attack_result_targeted_harm_categories_round_trip(sqlite_instance: MemoryInterface): +async def test_attack_result_targeted_harm_categories_round_trip(sqlite_instance: MemoryInterface): """targeted_harm_categories persists onto AttackResultEntry and round-trips back.""" attack_result = create_attack_result( "conv_1", 1, AttackOutcome.SUCCESS, targeted_harm_categories=["violence", "hate"] ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) - stored = sqlite_instance.get_attack_results(conversation_id="conv_1") + stored = await sqlite_instance.get_attack_results_async(conversation_id="conv_1") assert len(stored) == 1 assert sorted(stored[0].targeted_harm_categories) == ["hate", "violence"] -def test_attack_result_targeted_harm_categories_defaults_empty(sqlite_instance: MemoryInterface): +async def test_attack_result_targeted_harm_categories_defaults_empty(sqlite_instance: MemoryInterface): """An AttackResult with no harm categories round-trips to an empty list.""" attack_result = create_attack_result("conv_1", 1, AttackOutcome.SUCCESS) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) - stored = sqlite_instance.get_attack_results(conversation_id="conv_1") + stored = await sqlite_instance.get_attack_results_async(conversation_id="conv_1") assert len(stored) == 1 assert stored[0].targeted_harm_categories == [] -def test_get_attack_results_by_targeted_harm_categories(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_targeted_harm_categories(sqlite_instance: MemoryInterface): """Filtering by targeted_harm_categories matches attacks targeting ANY listed category.""" attack_results = [ create_attack_result("conv_1", 1, AttackOutcome.SUCCESS, targeted_harm_categories=["violence"]), @@ -1173,24 +1231,24 @@ def test_get_attack_results_by_targeted_harm_categories(sqlite_instance: MemoryI create_attack_result("conv_3", 3, AttackOutcome.SUCCESS, targeted_harm_categories=["self_harm"]), create_attack_result("conv_4", 4, AttackOutcome.SUCCESS), ] - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) - violence = sqlite_instance.get_attack_results(targeted_harm_categories=["violence"]) + violence = await sqlite_instance.get_attack_results_async(targeted_harm_categories=["violence"]) assert {r.conversation_id for r in violence} == {"conv_1", "conv_2"} # OR across multiple requested categories. - multi = sqlite_instance.get_attack_results(targeted_harm_categories=["self_harm", "hate"]) + multi = await sqlite_instance.get_attack_results_async(targeted_harm_categories=["self_harm", "hate"]) assert {r.conversation_id for r in multi} == {"conv_2", "conv_3"} # Case-insensitive match. - case = sqlite_instance.get_attack_results(targeted_harm_categories=["VIOLENCE"]) + case = await sqlite_instance.get_attack_results_async(targeted_harm_categories=["VIOLENCE"]) assert {r.conversation_id for r in case} == {"conv_1", "conv_2"} # No match. - assert sqlite_instance.get_attack_results(targeted_harm_categories=["nonexistent"]) == [] + assert (await sqlite_instance.get_attack_results_async(targeted_harm_categories=["nonexistent"])) == [] # Empty sequence applies no filter. - none_filter = sqlite_instance.get_attack_results(targeted_harm_categories=[]) + none_filter = await sqlite_instance.get_attack_results_async(targeted_harm_categories=[]) assert {r.conversation_id for r in none_filter} == {"conv_1", "conv_2", "conv_3", "conv_4"} @@ -1199,141 +1257,139 @@ def test_get_attack_results_by_targeted_harm_categories(sqlite_instance: MemoryI # --------------------------------------------------------------------------- -def test_get_unique_attack_labels_empty(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_labels_empty(sqlite_instance: MemoryInterface): """Returns empty dict when there are no attack results.""" - result = sqlite_instance.get_unique_attack_labels() + result = await sqlite_instance.get_unique_attack_labels_async() assert result == {} -def test_get_unique_attack_labels_single(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_labels_single(sqlite_instance: MemoryInterface): """Returns labels from a single attack result.""" ar = create_attack_result("conv_1", 1, labels={"env": "prod", "team": "red"}) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar])) - result = sqlite_instance.get_unique_attack_labels() + result = await sqlite_instance.get_unique_attack_labels_async() assert result == {"env": ["prod"], "team": ["red"]} -def test_get_unique_attack_labels_multiple_attacks_merges_values(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_labels_multiple_attacks_merges_values(sqlite_instance: MemoryInterface): """Values from different attacks are merged and sorted.""" ar1 = create_attack_result("conv_1", 1, labels={"env": "prod", "team": "red"}) ar2 = create_attack_result("conv_2", 2, labels={"env": "staging", "team": "red"}) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - result = sqlite_instance.get_unique_attack_labels() + result = await sqlite_instance.get_unique_attack_labels_async() assert result == {"env": ["prod", "staging"], "team": ["red"]} -def test_get_unique_attack_labels_no_labels(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_labels_no_labels(sqlite_instance: MemoryInterface): """Attack results without labels return an empty dict.""" ar = create_attack_result("conv_1", 1) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar])) - result = sqlite_instance.get_unique_attack_labels() + result = await sqlite_instance.get_unique_attack_labels_async() assert result == {} -def test_get_unique_attack_labels_non_string_values_skipped(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_labels_non_string_values_skipped(sqlite_instance: MemoryInterface): """Non-string label values are ignored.""" - from contextlib import closing - from sqlalchemy import text ar = create_attack_result("conv_1", 1, labels={"env": "prod"}) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar]) - with closing(sqlite_instance.get_session()) as session: - session.execute( + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar])) + async with await sqlite_instance.get_session_async() as session: + await session.execute( text('UPDATE "AttackResultEntries" SET labels = :labels'), {"labels": '{"env":"prod","count":42}'}, ) - session.commit() + await session.commit() - result = sqlite_instance.get_unique_attack_labels() + result = await sqlite_instance.get_unique_attack_labels_async() assert result == {"env": ["prod"]} -def test_get_unique_attack_labels_keys_sorted(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_labels_keys_sorted(sqlite_instance: MemoryInterface): """Returned keys and values are sorted alphabetically.""" ar1 = create_attack_result("conv_1", 1, labels={"zoo": "z_val", "alpha": "a"}) ar2 = create_attack_result("conv_2", 2, labels={"alpha": "b"}) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - result = sqlite_instance.get_unique_attack_labels() + result = await sqlite_instance.get_unique_attack_labels_async() assert list(result.keys()) == ["alpha", "zoo"] assert result["alpha"] == ["a", "b"] assert result["zoo"] == ["z_val"] -def test_get_unique_attack_labels_non_dict_labels_skipped(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_labels_non_dict_labels_skipped(sqlite_instance: MemoryInterface): """Labels stored as a non-dict JSON value (e.g. a string) are skipped.""" - from contextlib import closing - from sqlalchemy import text ar1 = create_attack_result("conv_1", 1, labels={"env": "prod"}) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1])) ar2 = create_attack_result("conv_2", 2, labels={"placeholder": "x"}) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar2]) - with closing(sqlite_instance.get_session()) as session: - session.execute( + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar2])) + async with await sqlite_instance.get_session_async() as session: + await session.execute( text('UPDATE "AttackResultEntries" SET labels = :labels WHERE conversation_id = :cid'), {"labels": '"just_a_string"', "cid": "conv_2"}, ) - session.commit() + await session.commit() - result = sqlite_instance.get_unique_attack_labels() + result = await sqlite_instance.get_unique_attack_labels_async() # Only the dict labels from conv_1 should appear assert result == {"env": ["prod"]} -def test_get_unique_attack_labels_from_attack_result_entry(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_labels_from_attack_result_entry(sqlite_instance: MemoryInterface): """Labels stored directly on AttackResultEntry are included.""" ar = create_attack_result("conv_1", 1, labels={"source": "are_only"}) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar])) - result = sqlite_instance.get_unique_attack_labels() + result = await sqlite_instance.get_unique_attack_labels_async() assert result == {"source": ["are_only"]} -def test_get_unique_attack_labels_deduplicates_across_attacks(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_labels_deduplicates_across_attacks(sqlite_instance: MemoryInterface): """Identical key-value pairs from different attacks are not duplicated.""" ar1 = create_attack_result("conv_1", 1, labels={"env": "prod"}) ar2 = create_attack_result("conv_2", 2, labels={"env": "prod"}) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - result = sqlite_instance.get_unique_attack_labels() + result = await sqlite_instance.get_unique_attack_labels_async() assert result == {"env": ["prod"]} -def test_get_unique_attack_labels_narrows_by_attribution_and_labels(sqlite_instance: MemoryInterface): - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - create_attack_result( - "conv_1", - 1, - operator="alice", - operation="nightly", - labels={"team": "red", "env": "prod"}, - ), - create_attack_result( - "conv_2", - 2, - operator="alice", - operation="daytime", - labels={"team": "blue", "env": "test"}, - ), - create_attack_result( - "conv_3", - 3, - operator="bob", - operation="nightly", - labels={"team": "red", "env": "dev"}, - ), - ] +async def test_get_unique_attack_labels_narrows_by_attribution_and_labels(sqlite_instance: MemoryInterface): + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + create_attack_result( + "conv_1", + 1, + operator="alice", + operation="nightly", + labels={"team": "red", "env": "prod"}, + ), + create_attack_result( + "conv_2", + 2, + operator="alice", + operation="daytime", + labels={"team": "blue", "env": "test"}, + ), + create_attack_result( + "conv_3", + 3, + operator="bob", + operation="nightly", + labels={"team": "red", "env": "dev"}, + ), + ] + ) ) - result = sqlite_instance.get_unique_attack_labels( + result = await sqlite_instance.get_unique_attack_labels_async( operator=["alice"], operation=["nightly"], labels={"team": ["red"]}, @@ -1342,49 +1398,55 @@ def test_get_unique_attack_labels_narrows_by_attribution_and_labels(sqlite_insta assert result == {"env": ["prod"], "team": ["red"]} -def test_get_attack_results_filters_dedicated_attribution_columns(sqlite_instance: MemoryInterface): +async def test_get_attack_results_filters_dedicated_attribution_columns(sqlite_instance: MemoryInterface): attack_results = [ create_attack_result("conv_1", 1, operator="alice", operation="nightly"), create_attack_result("conv_2", 2, operator="bob", operation="nightly"), create_attack_result("conv_3", 3, operator="alice", operation="daytime"), ] - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) - results = sqlite_instance.get_attack_results(operator=["alice"], operation="nightly") + results = await sqlite_instance.get_attack_results_async(operator=["alice"], operation="nightly") assert [result.conversation_id for result in results] == ["conv_1"] -def test_get_attack_results_legacy_attribution_filter_warns_and_normalizes(sqlite_instance: MemoryInterface): - sqlite_instance.add_attack_results_to_memory(attack_results=[create_attack_result("conv_1", 1, operator="alice")]) +async def test_get_attack_results_legacy_attribution_filter_warns_and_normalizes(sqlite_instance: MemoryInterface): + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[create_attack_result("conv_1", 1, operator="alice")] + ) + ) with pytest.warns(DeprecationWarning, match="removed in 1.4.0"): - results = sqlite_instance.get_attack_results(labels={"operator": "alice"}) + results = await sqlite_instance.get_attack_results_async(labels={"operator": "alice"}) assert [result.conversation_id for result in results] == ["conv_1"] -def test_get_attack_results_rejects_conflicting_attribution_filters(sqlite_instance: MemoryInterface): +async def test_get_attack_results_rejects_conflicting_attribution_filters(sqlite_instance: MemoryInterface): with pytest.raises(ValueError, match="operator conflicts"): - sqlite_instance.get_attack_results(operator="alice", labels={"operator": "bob"}) - - -def test_unique_attack_attribution_uses_dedicated_columns(sqlite_instance: MemoryInterface): - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - create_attack_result("conv_1", 1, operator="bob", operation="nightly", labels={"team": "red"}), - create_attack_result("conv_2", 2, operator="alice", operation="nightly", labels={"team": "blue"}), - create_attack_result("conv_3", 3), - create_attack_result("conv_4", 4, operator="alice"), - create_attack_result("conv_5", 5, operation="nightly"), - ] + (await sqlite_instance.get_attack_results_async(operator="alice", labels={"operator": "bob"})) + + +async def test_unique_attack_attribution_uses_dedicated_columns(sqlite_instance: MemoryInterface): + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + create_attack_result("conv_1", 1, operator="bob", operation="nightly", labels={"team": "red"}), + create_attack_result("conv_2", 2, operator="alice", operation="nightly", labels={"team": "blue"}), + create_attack_result("conv_3", 3), + create_attack_result("conv_4", 4, operator="alice"), + create_attack_result("conv_5", 5, operation="nightly"), + ] + ) ) - assert sqlite_instance.get_unique_attack_attribution() == { + assert (await sqlite_instance.get_unique_attack_attribution_async()) == { "operators": ["alice", "bob"], "operations": ["nightly"], } - assert sqlite_instance.get_unique_attack_labels() == {"team": ["blue", "red"]} + assert (await sqlite_instance.get_unique_attack_labels_async()) == {"team": ["blue", "red"]} # ============================================================================ @@ -1421,67 +1483,67 @@ def _make_attack_result_with_identifier( ) -def test_get_attack_results_by_attack_classes(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_attack_classes(sqlite_instance: MemoryInterface): """Test filtering attack results by attack_classes matches class_name in JSON.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") ar3 = _make_attack_result_with_identifier("conv_3", "CrescendoAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) - results = sqlite_instance.get_attack_results(attack_classes=["CrescendoAttack"]) + results = await sqlite_instance.get_attack_results_async(attack_classes=["CrescendoAttack"]) assert len(results) == 2 assert {r.conversation_id for r in results} == {"conv_1", "conv_3"} -def test_get_attack_results_by_attack_classes_no_match(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_attack_classes_no_match(sqlite_instance: MemoryInterface): """Test that attack_classes filter returns empty when nothing matches.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1])) - results = sqlite_instance.get_attack_results(attack_classes=["NonExistentAttack"]) + results = await sqlite_instance.get_attack_results_async(attack_classes=["NonExistentAttack"]) assert len(results) == 0 -def test_get_attack_results_by_attack_classes_case_insensitive(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_attack_classes_case_insensitive(sqlite_instance: MemoryInterface): """attack_classes is case-insensitive (mirrors converter_classes; forgives REST/CLI casing).""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1])) # Lowercase, uppercase, and mixed-case all match. - assert len(sqlite_instance.get_attack_results(attack_classes=["crescendoattack"])) == 1 - assert len(sqlite_instance.get_attack_results(attack_classes=["CRESCENDOATTACK"])) == 1 - assert len(sqlite_instance.get_attack_results(attack_classes=["CresCendoATtack"])) == 1 + assert len(await sqlite_instance.get_attack_results_async(attack_classes=["crescendoattack"])) == 1 + assert len(await sqlite_instance.get_attack_results_async(attack_classes=["CRESCENDOATTACK"])) == 1 + assert len(await sqlite_instance.get_attack_results_async(attack_classes=["CresCendoATtack"])) == 1 -def test_get_attack_results_by_attack_classes_no_identifier(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_attack_classes_no_identifier(sqlite_instance: MemoryInterface): """Test that attacks with no attack_identifier (empty JSON) are excluded by attack_classes filter.""" ar1 = create_attack_result("conv_1", 1) # No attack_identifier → stored as {} ar2 = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - results = sqlite_instance.get_attack_results(attack_classes=["CrescendoAttack"]) + results = await sqlite_instance.get_attack_results_async(attack_classes=["CrescendoAttack"]) assert len(results) == 1 assert results[0].conversation_id == "conv_2" -def test_get_attack_results_by_attack_classes_multi(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_attack_classes_multi(sqlite_instance: MemoryInterface): """Test that multiple attack_classes use OR logic — matches any of the listed class names.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") ar3 = _make_attack_result_with_identifier("conv_3", "TreeOfAttacksAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) - results = sqlite_instance.get_attack_results(attack_classes=["CrescendoAttack", "ManualAttack"]) + results = await sqlite_instance.get_attack_results_async(attack_classes=["CrescendoAttack", "ManualAttack"]) assert {r.conversation_id for r in results} == {"conv_1", "conv_2"} -def test_get_attack_results_attack_classes_empty_returns_all(sqlite_instance: MemoryInterface): +async def test_get_attack_results_attack_classes_empty_returns_all(sqlite_instance: MemoryInterface): """Test that attack_classes=[] behaves like None (no filter applied).""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - results = sqlite_instance.get_attack_results(attack_classes=[]) + results = await sqlite_instance.get_attack_results_async(attack_classes=[]) assert len(results) == 2 @@ -1498,111 +1560,113 @@ def _eval_hash_for(class_name: str) -> str: ).eval_hash -def test_get_attack_results_by_atomic_attack_eval_hashes_single(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_atomic_attack_eval_hashes_single(sqlite_instance: MemoryInterface): """Filter by a single eval_hash; only matching rows are returned.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) target_hash = _eval_hash_for("CrescendoAttack") - results = sqlite_instance.get_attack_results(atomic_attack_eval_hashes=[target_hash]) + results = await sqlite_instance.get_attack_results_async(atomic_attack_eval_hashes=[target_hash]) assert len(results) == 1 assert results[0].conversation_id == "conv_1" -def test_get_attack_results_by_atomic_attack_eval_hashes_multi_uses_or(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_atomic_attack_eval_hashes_multi_uses_or(sqlite_instance: MemoryInterface): """Multiple eval_hashes OR-combine — matches any of the listed hashes.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") ar3 = _make_attack_result_with_identifier("conv_3", "TreeOfAttacksAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) hashes = [_eval_hash_for("CrescendoAttack"), _eval_hash_for("ManualAttack")] - results = sqlite_instance.get_attack_results(atomic_attack_eval_hashes=hashes) + results = await sqlite_instance.get_attack_results_async(atomic_attack_eval_hashes=hashes) assert {r.conversation_id for r in results} == {"conv_1", "conv_2"} -def test_get_attack_results_atomic_attack_eval_hashes_empty_returns_all(sqlite_instance: MemoryInterface): +async def test_get_attack_results_atomic_attack_eval_hashes_empty_returns_all(sqlite_instance: MemoryInterface): """atomic_attack_eval_hashes=[] behaves like None (no filter applied).""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - results = sqlite_instance.get_attack_results(atomic_attack_eval_hashes=[]) + results = await sqlite_instance.get_attack_results_async(atomic_attack_eval_hashes=[]) assert len(results) == 2 -def test_get_attack_results_atomic_attack_eval_hashes_no_match(sqlite_instance: MemoryInterface): +async def test_get_attack_results_atomic_attack_eval_hashes_no_match(sqlite_instance: MemoryInterface): """A non-matching eval_hash returns no rows.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1])) - results = sqlite_instance.get_attack_results(atomic_attack_eval_hashes=["deadbeef" * 8]) + results = await sqlite_instance.get_attack_results_async(atomic_attack_eval_hashes=["deadbeef" * 8]) assert len(results) == 0 -def test_get_attack_results_converter_classes_none_returns_all(sqlite_instance: MemoryInterface): +async def test_get_attack_results_converter_classes_none_returns_all(sqlite_instance: MemoryInterface): """Test that converter_classes=None (omitted) returns all attacks unfiltered.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack") # No converters (None) ar3 = create_attack_result("conv_3", 3) # No identifier at all - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) - results = sqlite_instance.get_attack_results(converter_classes=None) + results = await sqlite_instance.get_attack_results_async(converter_classes=None) assert len(results) == 3 -def test_get_attack_results_converter_classes_empty_matches_no_converters(sqlite_instance: MemoryInterface): +async def test_get_attack_results_converter_classes_empty_matches_no_converters(sqlite_instance: MemoryInterface): """Test that converter_classes=[] returns only attacks with no converters (back-compat).""" ar_with_conv = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar_no_conv_none = _make_attack_result_with_identifier("conv_2", "Attack") # converter_ids=None ar_no_conv_empty = _make_attack_result_with_identifier("conv_3", "Attack", []) # converter_ids=[] ar_no_identifier = create_attack_result("conv_4", 4) # No identifier → stored as {} - sqlite_instance.add_attack_results_to_memory( - attack_results=[ar_with_conv, ar_no_conv_none, ar_no_conv_empty, ar_no_identifier] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ar_with_conv, ar_no_conv_none, ar_no_conv_empty, ar_no_identifier] + ) ) - results = sqlite_instance.get_attack_results(converter_classes=[]) + results = await sqlite_instance.get_attack_results_async(converter_classes=[]) conv_ids = {r.conversation_id for r in results} assert conv_ids == {"conv_2", "conv_3", "conv_4"} -def test_get_attack_results_converter_classes_single_match(sqlite_instance: MemoryInterface): +async def test_get_attack_results_converter_classes_single_match(sqlite_instance: MemoryInterface): """Test that converter_types with one type returns attacks using that converter.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["ROT13Converter"]) ar3 = _make_attack_result_with_identifier("conv_3", "Attack", ["Base64Converter", "ROT13Converter"]) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) - results = sqlite_instance.get_attack_results(converter_classes=["Base64Converter"]) + results = await sqlite_instance.get_attack_results_async(converter_classes=["Base64Converter"]) conv_ids = {r.conversation_id for r in results} assert conv_ids == {"conv_1", "conv_3"} -def test_get_attack_results_converter_classes_and_logic(sqlite_instance: MemoryInterface): +async def test_get_attack_results_converter_classes_and_logic(sqlite_instance: MemoryInterface): """Test that multiple converter_types use AND logic — all must be present.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["ROT13Converter"]) ar3 = _make_attack_result_with_identifier("conv_3", "Attack", ["Base64Converter", "ROT13Converter"]) ar4 = _make_attack_result_with_identifier("conv_4", "Attack", ["Base64Converter", "ROT13Converter", "UrlConverter"]) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3, ar4]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3, ar4])) - results = sqlite_instance.get_attack_results(converter_classes=["Base64Converter", "ROT13Converter"]) + results = await sqlite_instance.get_attack_results_async(converter_classes=["Base64Converter", "ROT13Converter"]) conv_ids = {r.conversation_id for r in results} # conv_3 and conv_4 have both; conv_1 and conv_2 have only one assert conv_ids == {"conv_3", "conv_4"} -def test_get_attack_results_converter_classes_any_logic(sqlite_instance: MemoryInterface): +async def test_get_attack_results_converter_classes_any_logic(sqlite_instance: MemoryInterface): """converter_classes_match='any' returns rows that match at least one listed converter.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["ROT13Converter"]) ar3 = _make_attack_result_with_identifier("conv_3", "Attack", ["Base64Converter", "ROT13Converter"]) ar4 = _make_attack_result_with_identifier("conv_4", "Attack", ["UrlConverter"]) ar5 = _make_attack_result_with_identifier("conv_5", "Attack") # No converters - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3, ar4, ar5]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3, ar4, ar5])) - results = sqlite_instance.get_attack_results( + results = await sqlite_instance.get_attack_results_async( converter_classes=["Base64Converter", "ROT13Converter"], converter_classes_match="any", ) @@ -1611,144 +1675,148 @@ def test_get_attack_results_converter_classes_any_logic(sqlite_instance: MemoryI assert conv_ids == {"conv_1", "conv_2", "conv_3"} -def test_get_attack_results_converter_classes_any_logic_case_insensitive(sqlite_instance: MemoryInterface): +async def test_get_attack_results_converter_classes_any_logic_case_insensitive(sqlite_instance: MemoryInterface): """converter_classes_match='any' preserves case-insensitive matching (parity with 'all' mode).""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["ROT13Converter"]) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - results = sqlite_instance.get_attack_results( + results = await sqlite_instance.get_attack_results_async( converter_classes=["base64converter", "ROT13CONVERTER"], converter_classes_match="any", ) assert {r.conversation_id for r in results} == {"conv_1", "conv_2"} -def test_get_attack_results_converter_classes_any_logic_single_entry_degenerate(sqlite_instance: MemoryInterface): +async def test_get_attack_results_converter_classes_any_logic_single_entry_degenerate(sqlite_instance: MemoryInterface): """converter_classes_match='any' with a single entry is equivalent to 'all' with that entry.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["ROT13Converter"]) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - results_any = sqlite_instance.get_attack_results( + results_any = await sqlite_instance.get_attack_results_async( converter_classes=["Base64Converter"], converter_classes_match="any" ) - results_all = sqlite_instance.get_attack_results( + results_all = await sqlite_instance.get_attack_results_async( converter_classes=["Base64Converter"], converter_classes_match="all" ) assert {r.conversation_id for r in results_any} == {"conv_1"} assert {r.conversation_id for r in results_any} == {r.conversation_id for r in results_all} -def test_get_attack_results_converter_classes_any_logic_empty_preserves_absence_overload( +async def test_get_attack_results_converter_classes_any_logic_empty_preserves_absence_overload( sqlite_instance: MemoryInterface, ): """converter_classes=[] with match_mode='any' still means 'no converters' (overload is mode-agnostic).""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack") # No converters - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - results = sqlite_instance.get_attack_results(converter_classes=[], converter_classes_match="any") + results = await sqlite_instance.get_attack_results_async(converter_classes=[], converter_classes_match="any") assert {r.conversation_id for r in results} == {"conv_2"} -def test_get_attack_results_converter_classes_case_insensitive(sqlite_instance: MemoryInterface): +async def test_get_attack_results_converter_classes_case_insensitive(sqlite_instance: MemoryInterface): """Test that converter class matching is case-insensitive.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1])) - results = sqlite_instance.get_attack_results(converter_classes=["base64converter"]) + results = await sqlite_instance.get_attack_results_async(converter_classes=["base64converter"]) assert len(results) == 1 assert results[0].conversation_id == "conv_1" -def test_get_attack_results_converter_classes_no_match(sqlite_instance: MemoryInterface): +async def test_get_attack_results_converter_classes_no_match(sqlite_instance: MemoryInterface): """Test that converter_types filter returns empty when no attack has the converter.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1])) - results = sqlite_instance.get_attack_results(converter_classes=["NonExistentConverter"]) + results = await sqlite_instance.get_attack_results_async(converter_classes=["NonExistentConverter"]) assert len(results) == 0 -def test_get_attack_results_attack_classes_and_converter_classes_combined(sqlite_instance: MemoryInterface): +async def test_get_attack_results_attack_classes_and_converter_classes_combined(sqlite_instance: MemoryInterface): """Test combining attack_classes and converter_classes filters.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack", ["Base64Converter"]) ar3 = _make_attack_result_with_identifier("conv_3", "CrescendoAttack", ["ROT13Converter"]) ar4 = _make_attack_result_with_identifier("conv_4", "CrescendoAttack") # No converters - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3, ar4]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3, ar4])) - results = sqlite_instance.get_attack_results( + results = await sqlite_instance.get_attack_results_async( attack_classes=["CrescendoAttack"], converter_classes=["Base64Converter"] ) assert len(results) == 1 assert results[0].conversation_id == "conv_1" -def test_get_attack_results_attack_classes_converter_classes_empty_matches_no_converters( +async def test_get_attack_results_attack_classes_converter_classes_empty_matches_no_converters( sqlite_instance: MemoryInterface, ): """Combining attack_classes with converter_classes=[] restricts to the class with no converters.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") # No converters ar3 = _make_attack_result_with_identifier("conv_3", "ManualAttack") # Different class - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) - results = sqlite_instance.get_attack_results(attack_classes=["CrescendoAttack"], converter_classes=[]) + results = await sqlite_instance.get_attack_results_async(attack_classes=["CrescendoAttack"], converter_classes=[]) assert {r.conversation_id for r in results} == {"conv_2"} -def test_get_attack_results_has_converters_true(sqlite_instance: MemoryInterface): +async def test_get_attack_results_has_converters_true(sqlite_instance: MemoryInterface): """has_converters=True returns only attacks with at least one converter.""" ar_with_conv = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar_no_conv_none = _make_attack_result_with_identifier("conv_2", "Attack") # converter_ids=None ar_no_conv_empty = _make_attack_result_with_identifier("conv_3", "Attack", []) # converter_ids=[] ar_no_identifier = create_attack_result("conv_4", 4) # No identifier → stored as {} - sqlite_instance.add_attack_results_to_memory( - attack_results=[ar_with_conv, ar_no_conv_none, ar_no_conv_empty, ar_no_identifier] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ar_with_conv, ar_no_conv_none, ar_no_conv_empty, ar_no_identifier] + ) ) - results = sqlite_instance.get_attack_results(has_converters=True) + results = await sqlite_instance.get_attack_results_async(has_converters=True) assert {r.conversation_id for r in results} == {"conv_1"} -def test_get_attack_results_has_converters_false(sqlite_instance: MemoryInterface): +async def test_get_attack_results_has_converters_false(sqlite_instance: MemoryInterface): """has_converters=False returns only attacks with zero converters.""" ar_with_conv = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar_no_conv_none = _make_attack_result_with_identifier("conv_2", "Attack") ar_no_conv_empty = _make_attack_result_with_identifier("conv_3", "Attack", []) ar_no_identifier = create_attack_result("conv_4", 4) - sqlite_instance.add_attack_results_to_memory( - attack_results=[ar_with_conv, ar_no_conv_none, ar_no_conv_empty, ar_no_identifier] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ar_with_conv, ar_no_conv_none, ar_no_conv_empty, ar_no_identifier] + ) ) - results = sqlite_instance.get_attack_results(has_converters=False) + results = await sqlite_instance.get_attack_results_async(has_converters=False) assert {r.conversation_id for r in results} == {"conv_2", "conv_3", "conv_4"} -def test_get_attack_results_has_converters_none_returns_all(sqlite_instance: MemoryInterface): +async def test_get_attack_results_has_converters_none_returns_all(sqlite_instance: MemoryInterface): """has_converters=None applies no filter.""" ar_with_conv = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter"]) ar_no_conv = _make_attack_result_with_identifier("conv_2", "Attack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar_with_conv, ar_no_conv]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar_with_conv, ar_no_conv])) - results = sqlite_instance.get_attack_results(has_converters=None) + results = await sqlite_instance.get_attack_results_async(has_converters=None) assert len(results) == 2 -def test_get_attack_results_has_converters_false_combined_with_attack_classes(sqlite_instance: MemoryInterface): +async def test_get_attack_results_has_converters_false_combined_with_attack_classes(sqlite_instance: MemoryInterface): """has_converters=False composes (AND) with attack_classes.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack", ["Base64Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") # No converters ar3 = _make_attack_result_with_identifier("conv_3", "ManualAttack") # No converters, different class - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) - results = sqlite_instance.get_attack_results(attack_classes=["CrescendoAttack"], has_converters=False) + results = await sqlite_instance.get_attack_results_async(attack_classes=["CrescendoAttack"], has_converters=False) assert {r.conversation_id for r in results} == {"conv_2"} -def test_get_attack_results_can_exclude_scenario_attacks(sqlite_instance: MemoryInterface) -> None: +async def test_get_attack_results_can_exclude_scenario_attacks(sqlite_instance: MemoryInterface) -> None: """Manual-only queries exclude attacks carrying scenario attribution.""" scenario = make_scenario_result( id=uuid.uuid4(), @@ -1763,11 +1831,11 @@ def test_get_attack_results_can_exclude_scenario_attacks(sqlite_instance: Memory scenario_attack = create_attack_result("scenario", 2) scenario_attack.attribution_parent_id = str(scenario.id) scenario_attack.attribution_data = {"parent_collection": "attack"} - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario]) - sqlite_instance.add_attack_results_to_memory(attack_results=[manual_attack, scenario_attack]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario])) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[manual_attack, scenario_attack])) - all_results = sqlite_instance.get_attack_results(include_scenario_attacks=True) - manual_results = sqlite_instance.get_attack_results(include_scenario_attacks=False) + all_results = await sqlite_instance.get_attack_results_async(include_scenario_attacks=True) + manual_results = await sqlite_instance.get_attack_results_async(include_scenario_attacks=False) assert {result.conversation_id for result in all_results} == {"manual", "scenario"} assert [result.conversation_id for result in manual_results] == ["manual"] @@ -1778,68 +1846,68 @@ def test_get_attack_results_can_exclude_scenario_attacks(sqlite_instance: Memory # ============================================================================ -def test_get_unique_attack_class_names_empty(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_class_names_empty(sqlite_instance: MemoryInterface): """Test that no attacks returns empty list.""" - result = sqlite_instance.get_unique_attack_class_names() + result = await sqlite_instance.get_unique_attack_class_names_async() assert result == [] -def test_get_unique_attack_class_names_sorted_unique(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_class_names_sorted_unique(sqlite_instance: MemoryInterface): """Test that unique class names are returned sorted, with duplicates removed.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") ar3 = _make_attack_result_with_identifier("conv_3", "CrescendoAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) - result = sqlite_instance.get_unique_attack_class_names() + result = await sqlite_instance.get_unique_attack_class_names_async() assert result == ["CrescendoAttack", "ManualAttack"] -def test_get_unique_attack_class_names_skips_empty_identifier(sqlite_instance: MemoryInterface): +async def test_get_unique_attack_class_names_skips_empty_identifier(sqlite_instance: MemoryInterface): """Test that attacks with empty attack_identifier (no class_name) are excluded.""" ar_no_id = create_attack_result("conv_1", 1) # No attack_identifier → stored as {} ar_with_id = _make_attack_result_with_identifier("conv_2", "CrescendoAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar_no_id, ar_with_id]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar_no_id, ar_with_id])) - result = sqlite_instance.get_unique_attack_class_names() + result = await sqlite_instance.get_unique_attack_class_names_async() assert result == ["CrescendoAttack"] -def test_get_unique_converter_class_names_empty(sqlite_instance: MemoryInterface): +async def test_get_unique_converter_class_names_empty(sqlite_instance: MemoryInterface): """Test that no attacks returns empty list.""" - result = sqlite_instance.get_unique_converter_class_names() + result = await sqlite_instance.get_unique_converter_class_names_async() assert result == [] -def test_get_unique_converter_class_names_sorted_unique(sqlite_instance: MemoryInterface): +async def test_get_unique_converter_class_names_sorted_unique(sqlite_instance: MemoryInterface): """Test that unique converter class names are returned sorted, with duplicates removed.""" ar1 = _make_attack_result_with_identifier("conv_1", "Attack", ["Base64Converter", "ROT13Converter"]) ar2 = _make_attack_result_with_identifier("conv_2", "Attack", ["Base64Converter"]) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) - result = sqlite_instance.get_unique_converter_class_names() + result = await sqlite_instance.get_unique_converter_class_names_async() assert result == ["Base64Converter", "ROT13Converter"] -def test_get_unique_converter_class_names_skips_no_converters(sqlite_instance: MemoryInterface): +async def test_get_unique_converter_class_names_skips_no_converters(sqlite_instance: MemoryInterface): """Test that attacks with no converters don't contribute names.""" ar_no_conv = _make_attack_result_with_identifier("conv_1", "Attack") # No converters ar_with_conv = _make_attack_result_with_identifier("conv_2", "Attack", ["Base64Converter"]) ar_empty_id = create_attack_result("conv_3", 3) # Empty attack_identifier - sqlite_instance.add_attack_results_to_memory(attack_results=[ar_no_conv, ar_with_conv, ar_empty_id]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar_no_conv, ar_with_conv, ar_empty_id])) - result = sqlite_instance.get_unique_converter_class_names() + result = await sqlite_instance.get_unique_converter_class_names_async() assert result == ["Base64Converter"] -def test_get_attack_results_by_attack_identifier_filter_hash(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_attack_identifier_filter_hash(sqlite_instance: MemoryInterface): """Test filtering attack results by AttackIdentifierFilter with hash.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2])) # Filter by hash of ar1's attack identifier - results = sqlite_instance.get_attack_results( + results = await sqlite_instance.get_attack_results_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.ATTACK, @@ -1853,15 +1921,15 @@ def test_get_attack_results_by_attack_identifier_filter_hash(sqlite_instance: Me assert results[0].conversation_id == "conv_1" -def test_get_attack_results_by_attack_identifier_filter_class_name(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_attack_identifier_filter_class_name(sqlite_instance: MemoryInterface): """Test filtering attack results by AttackIdentifierFilter with class_name.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") ar2 = _make_attack_result_with_identifier("conv_2", "ManualAttack") ar3 = _make_attack_result_with_identifier("conv_3", "CrescendoAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) # Filter by partial attack class name - results = sqlite_instance.get_attack_results( + results = await sqlite_instance.get_attack_results_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.ATTACK, @@ -1875,12 +1943,12 @@ def test_get_attack_results_by_attack_identifier_filter_class_name(sqlite_instan assert {r.conversation_id for r in results} == {"conv_1", "conv_3"} -def test_get_attack_results_by_attack_identifier_filter_no_match(sqlite_instance: MemoryInterface): +async def test_get_attack_results_by_attack_identifier_filter_no_match(sqlite_instance: MemoryInterface): """Test that AttackIdentifierFilter returns empty when nothing matches.""" ar1 = _make_attack_result_with_identifier("conv_1", "CrescendoAttack") - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1])) - results = sqlite_instance.get_attack_results( + results = await sqlite_instance.get_attack_results_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.ATTACK, @@ -1893,17 +1961,17 @@ def test_get_attack_results_by_attack_identifier_filter_no_match(sqlite_instance assert len(results) == 0 -def test_get_attack_results_pagination_returns_recency_ordered_page(sqlite_instance: MemoryInterface): +async def test_get_attack_results_pagination_returns_recency_ordered_page(sqlite_instance: MemoryInterface): """Keyset pagination returns the recency-ordered slice (newest updated_at first).""" attack_results = [ _make_attack_result(f"conv-{i}", ts_offset=i, updated_at_offset=100 + i, created_at_offset=i) for i in range(10) ] - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) - page1 = sqlite_instance.get_attack_results(limit=3) + page1 = await sqlite_instance.get_attack_results_async(limit=3) assert [r.conversation_id for r in page1] == ["conv-9", "conv-8", "conv-7"] - page2 = sqlite_instance.get_attack_results(limit=3, after=_after(page1)) + page2 = await sqlite_instance.get_attack_results_async(limit=3, after=_after(page1)) assert [r.conversation_id for r in page2] == ["conv-6", "conv-5", "conv-4"] @@ -1918,18 +1986,18 @@ def test_get_attack_results_pagination_uses_not_exists_anti_join() -> None: assert "PARTITION BY" not in sql -def test_get_attack_results_pagination_disjoint_and_complete(sqlite_instance: MemoryInterface): +async def test_get_attack_results_pagination_disjoint_and_complete(sqlite_instance: MemoryInterface): """Concatenated keyset pages equal the full recency-ordered set with no gaps or duplicates.""" attack_results = [_make_attack_result(f"conv-{i}", ts_offset=i, updated_at_offset=100 + i) for i in range(25)] - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) - full = [r.conversation_id for r in sqlite_instance.get_attack_results(limit=100)] - paged = [r.conversation_id for r in _drain_keyset(sqlite_instance, page_size=7)] + full = [r.conversation_id for r in (await sqlite_instance.get_attack_results_async(limit=100))] + paged = [r.conversation_id for r in (await _drain_keyset_async(sqlite_instance, page_size=7))] assert paged == full assert len(set(paged)) == 25 -def test_get_attack_results_pagination_duplicate_and_tie_heavy_pages_disjoint_and_complete( +async def test_get_attack_results_pagination_duplicate_and_tie_heavy_pages_disjoint_and_complete( sqlite_instance: MemoryInterface, ): """Duplicate- and tie-heavy data still paginates as disjoint, complete, newest-per-conversation winners.""" @@ -1956,26 +2024,26 @@ def test_get_attack_results_pagination_duplicate_and_tie_heavy_pages_disjoint_an attack_result_id=f"00000000-0000-4000-8000-1{i:011d}", ) ) - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) - full = list(sqlite_instance.get_attack_results(limit=100)) + full = list(await sqlite_instance.get_attack_results_async(limit=100)) # Each duplicate pair collapses to exactly one winner, and the winner is the newer (FAILURE) row. assert len(full) == num_convs assert all(r.outcome == AttackOutcome.FAILURE for r in full) assert len({r.conversation_id for r in full}) == num_convs - paged = [r.attack_result_id for r in _drain_keyset(sqlite_instance, page_size=5)] + paged = [r.attack_result_id for r in (await _drain_keyset_async(sqlite_instance, page_size=5))] assert paged == [r.attack_result_id for r in full] assert len(set(paged)) == num_convs -def test_get_attack_results_pagination_order_parity_with_timestamp_sort(sqlite_instance: MemoryInterface): +async def test_get_attack_results_pagination_order_parity_with_timestamp_sort(sqlite_instance: MemoryInterface): """Paginated SQL ordering matches a Python sort on the timestamp recency column.""" attack_results = [_make_attack_result(f"conv-{i}", ts_offset=(i * 7) % 50) for i in range(15)] - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) - new_order = [r.conversation_id for r in sqlite_instance.get_attack_results(limit=100)] - all_unpaged = list(sqlite_instance.get_attack_results()) + new_order = [r.conversation_id for r in (await sqlite_instance.get_attack_results_async(limit=100))] + all_unpaged = list(await sqlite_instance.get_attack_results_async()) expected = sorted( all_unpaged, key=lambda ar: (ar.timestamp, ar.attack_result_id), @@ -1984,100 +2052,110 @@ def test_get_attack_results_pagination_order_parity_with_timestamp_sort(sqlite_i assert new_order == [r.conversation_id for r in expected] -def test_get_attack_results_paginated_dedup_is_filter_aware(sqlite_instance: MemoryInterface): +async def test_get_attack_results_paginated_dedup_is_filter_aware(sqlite_instance: MemoryInterface): """When the newest row fails the filter, the older matching row still survives dedup.""" older_id = str(uuid.uuid4()) newer_id = str(uuid.uuid4()) - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - _make_attack_result( - "conv-1", outcome=AttackOutcome.SUCCESS, ts_offset=1, updated_at_offset=1, attack_result_id=older_id - ), - _make_attack_result( - "conv-1", outcome=AttackOutcome.FAILURE, ts_offset=2, updated_at_offset=2, attack_result_id=newer_id - ), - ] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + _make_attack_result( + "conv-1", outcome=AttackOutcome.SUCCESS, ts_offset=1, updated_at_offset=1, attack_result_id=older_id + ), + _make_attack_result( + "conv-1", outcome=AttackOutcome.FAILURE, ts_offset=2, updated_at_offset=2, attack_result_id=newer_id + ), + ] + ) ) - page = sqlite_instance.get_attack_results(outcome=AttackOutcome.SUCCESS.value, limit=50) + page = await sqlite_instance.get_attack_results_async(outcome=AttackOutcome.SUCCESS.value, limit=50) assert len(page) == 1 assert page[0].attack_result_id == older_id -def test_get_attack_results_paginated_turns_filter_after_dedup(sqlite_instance: MemoryInterface): +async def test_get_attack_results_paginated_turns_filter_after_dedup(sqlite_instance: MemoryInterface): """min/max_turns apply to the surviving winner, never resurrecting an older duplicate.""" older_id = str(uuid.uuid4()) newer_id = str(uuid.uuid4()) - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - _make_attack_result( - "conv-1", executed_turns=2, ts_offset=1, updated_at_offset=1, attack_result_id=older_id - ), - _make_attack_result( - "conv-1", executed_turns=9, ts_offset=2, updated_at_offset=2, attack_result_id=newer_id - ), - ] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + _make_attack_result( + "conv-1", executed_turns=2, ts_offset=1, updated_at_offset=1, attack_result_id=older_id + ), + _make_attack_result( + "conv-1", executed_turns=9, ts_offset=2, updated_at_offset=2, attack_result_id=newer_id + ), + ] + ) ) # Winner (turns=9) is out of range; the older turns=2 row must NOT resurface. - assert list(sqlite_instance.get_attack_results(max_turns=5, limit=50)) == [] + assert list(await sqlite_instance.get_attack_results_async(max_turns=5, limit=50)) == [] # Winner in range -> returned. - page = sqlite_instance.get_attack_results(min_turns=5, limit=50) + page = await sqlite_instance.get_attack_results_async(min_turns=5, limit=50) assert len(page) == 1 assert page[0].attack_result_id == newer_id -def test_get_attack_results_paginated_same_timestamp_tie_keeps_max_id(sqlite_instance: MemoryInterface): +async def test_get_attack_results_paginated_same_timestamp_tie_keeps_max_id(sqlite_instance: MemoryInterface): """On identical timestamps, dedup deterministically keeps the max id.""" id_lo = "00000000-0000-4000-8000-000000000001" id_hi = "00000000-0000-4000-8000-0000000000ff" - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - _make_attack_result("conv-1", ts_offset=5, updated_at_offset=5, attack_result_id=id_hi), - _make_attack_result("conv-1", ts_offset=5, updated_at_offset=5, attack_result_id=id_lo), - ] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + _make_attack_result("conv-1", ts_offset=5, updated_at_offset=5, attack_result_id=id_hi), + _make_attack_result("conv-1", ts_offset=5, updated_at_offset=5, attack_result_id=id_lo), + ] + ) ) - page = sqlite_instance.get_attack_results(limit=50) + page = await sqlite_instance.get_attack_results_async(limit=50) assert len(page) == 1 assert page[0].attack_result_id == id_hi -def test_get_attack_results_paginated_empty_metadata_orders_newest_first(sqlite_instance: MemoryInterface): +async def test_get_attack_results_paginated_empty_metadata_orders_newest_first(sqlite_instance: MemoryInterface): """Rows without recency metadata fall back to timestamp DESC (newest first).""" - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - _make_attack_result("conv-a", ts_offset=1), - _make_attack_result("conv-b", ts_offset=2), - _make_attack_result("conv-c", ts_offset=3), - ] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + _make_attack_result("conv-a", ts_offset=1), + _make_attack_result("conv-b", ts_offset=2), + _make_attack_result("conv-c", ts_offset=3), + ] + ) ) - page = [r.conversation_id for r in sqlite_instance.get_attack_results(limit=50)] + page = [r.conversation_id for r in (await sqlite_instance.get_attack_results_async(limit=50))] assert page == ["conv-c", "conv-b", "conv-a"] -def test_get_attack_results_pagination_with_ids_raises(sqlite_instance: MemoryInterface): +async def test_get_attack_results_pagination_with_ids_raises(sqlite_instance: MemoryInterface): """limit/keyset pagination cannot be combined with id-batched lookups.""" anchor = AttackResultKeysetCursor(timestamp=_BASE_TS, attack_result_id=str(uuid.uuid4())) with pytest.raises(ValueError, match="pagination cannot be combined"): - sqlite_instance.get_attack_results(attack_result_ids=[str(uuid.uuid4())], limit=10) + (await sqlite_instance.get_attack_results_async(attack_result_ids=[str(uuid.uuid4())], limit=10)) with pytest.raises(ValueError, match="pagination cannot be combined"): - sqlite_instance.get_attack_results(objective_sha256=["abc"], after=anchor) + (await sqlite_instance.get_attack_results_async(objective_sha256=["abc"], after=anchor)) -def test_get_attack_results_unpaginated_turns_filter(sqlite_instance: MemoryInterface): +async def test_get_attack_results_unpaginated_turns_filter(sqlite_instance: MemoryInterface): """The unpaginated path also honors min/max_turns (applied after dedup).""" - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - _make_attack_result("conv-x", executed_turns=2, ts_offset=1, updated_at_offset=1), - _make_attack_result("conv-y", executed_turns=8, ts_offset=2, updated_at_offset=2), - ] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + _make_attack_result("conv-x", executed_turns=2, ts_offset=1, updated_at_offset=1), + _make_attack_result("conv-y", executed_turns=8, ts_offset=2, updated_at_offset=2), + ] + ) ) - filtered = sqlite_instance.get_attack_results(min_turns=5) + filtered = await sqlite_instance.get_attack_results_async(min_turns=5) assert len(filtered) == 1 assert filtered[0].conversation_id == "conv-y" # No bounds -> unchanged behavior (all winners). - assert len(sqlite_instance.get_attack_results()) == 2 + assert len(await sqlite_instance.get_attack_results_async()) == 2 -def test_get_attack_results_paginated_hydrates_scores_under_limit(sqlite_instance: MemoryInterface): +async def test_get_attack_results_paginated_hydrates_scores_under_limit(sqlite_instance: MemoryInterface): """The paginated joinedload path still hydrates last_response and last_score.""" message_piece = MessagePiece( role="user", @@ -2092,8 +2170,8 @@ def test_get_attack_results_paginated_hydrates_scores_under_limit(sqlite_instanc message_piece_id=message_piece.id, score_rationale="Test score rationale", ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[message_piece]) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[message_piece])) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) scored = AttackResult( conversation_id="conv-scored", @@ -2107,9 +2185,9 @@ def test_get_attack_results_paginated_hydrates_scores_under_limit(sqlite_instanc timestamp=_BASE_TS + timedelta(seconds=99), ) others = [_make_attack_result(f"conv-{i}", ts_offset=i, updated_at_offset=i) for i in range(5)] - sqlite_instance.add_attack_results_to_memory(attack_results=[scored, *others]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[scored, *others])) - page = sqlite_instance.get_attack_results(limit=1) + page = await sqlite_instance.get_attack_results_async(limit=1) assert len(page) == 1 assert page[0].conversation_id == "conv-scored" assert page[0].last_response is not None @@ -2118,7 +2196,7 @@ def test_get_attack_results_paginated_hydrates_scores_under_limit(sqlite_instanc assert page[0].last_score.id == score.id -def test_get_attack_results_keyset_pagination_stable_under_concurrent_insert(sqlite_instance: MemoryInterface): +async def test_get_attack_results_keyset_pagination_stable_under_concurrent_insert(sqlite_instance: MemoryInterface): """A row inserted at the top between page loads must not duplicate or skip a result. This is the regression guard for the offset-drift bug: with a numeric offset, a new @@ -2126,17 +2204,19 @@ def test_get_attack_results_keyset_pagination_stable_under_concurrent_insert(sql A keyset cursor seeks strictly past the previous page's last row, so it is immune. """ seeded = [_make_attack_result(f"conv-{i}", ts_offset=i, updated_at_offset=i) for i in range(6)] - sqlite_instance.add_attack_results_to_memory(attack_results=seeded) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=seeded)) - page1 = sqlite_instance.get_attack_results(limit=3) + page1 = await sqlite_instance.get_attack_results_async(limit=3) assert [r.conversation_id for r in page1] == ["conv-5", "conv-4", "conv-3"] # A concurrent attack finishes between page loads and sorts to the very top. - sqlite_instance.add_attack_results_to_memory( - attack_results=[_make_attack_result("conv-new", ts_offset=999, updated_at_offset=999)] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[_make_attack_result("conv-new", ts_offset=999, updated_at_offset=999)] + ) ) - page2 = sqlite_instance.get_attack_results(limit=3, after=_after(page1)) + page2 = await sqlite_instance.get_attack_results_async(limit=3, after=_after(page1)) page2_ids = [r.conversation_id for r in page2] # The pre-existing rows below the anchor are returned exactly once, in order, with no @@ -2147,42 +2227,42 @@ def test_get_attack_results_keyset_pagination_stable_under_concurrent_insert(sql assert "conv-new" not in page2_ids -def test_get_attack_results_keyset_pagination_stable_under_delete(sqlite_instance: MemoryInterface): +async def test_get_attack_results_keyset_pagination_stable_under_delete(sqlite_instance: MemoryInterface): """Deleting an already-seen row between pages must not skip the next unseen row.""" seeded = [_make_attack_result(f"conv-{i}", ts_offset=i, updated_at_offset=i) for i in range(6)] - sqlite_instance.add_attack_results_to_memory(attack_results=seeded) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=seeded)) - page1 = sqlite_instance.get_attack_results(limit=3) + page1 = await sqlite_instance.get_attack_results_async(limit=3) assert [r.conversation_id for r in page1] == ["conv-5", "conv-4", "conv-3"] # Delete a row that was already returned on page 1 (above the anchor). With an offset this # shifts the window and skips "conv-2"; the keyset anchor is unaffected. - with sqlite_instance.get_session() as session: - session.query(AttackResultEntry).filter(AttackResultEntry.conversation_id == "conv-4").delete() - session.commit() + async with await sqlite_instance.get_session_async() as session: + await session.execute(delete(AttackResultEntry).where(AttackResultEntry.conversation_id == "conv-4")) + await session.commit() - page2 = [r.conversation_id for r in sqlite_instance.get_attack_results(limit=3, after=_after(page1))] + page2 = [r.conversation_id for r in (await sqlite_instance.get_attack_results_async(limit=3, after=_after(page1)))] assert page2 == ["conv-2", "conv-1", "conv-0"] -def test_get_attack_results_keyset_paginates_empty_recency_tie_block(sqlite_instance: MemoryInterface): +async def test_get_attack_results_keyset_paginates_empty_recency_tie_block(sqlite_instance: MemoryInterface): """Rows that all share an empty recency key still paginate disjoint and complete. Metadata-less rows all coalesce to recency "", so the seek must fall through to the timestamp and id tie-breaks. A recency-only seek would loop or skip within this block. """ seeded = [_make_attack_result(f"conv-{i}", ts_offset=i) for i in range(9)] # no updated_at/created_at - sqlite_instance.add_attack_results_to_memory(attack_results=seeded) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=seeded)) - full = [r.conversation_id for r in sqlite_instance.get_attack_results(limit=100)] + full = [r.conversation_id for r in (await sqlite_instance.get_attack_results_async(limit=100))] assert full == [f"conv-{i}" for i in range(8, -1, -1)] # newest timestamp first - paged = [r.conversation_id for r in _drain_keyset(sqlite_instance, page_size=4)] + paged = [r.conversation_id for r in (await _drain_keyset_async(sqlite_instance, page_size=4))] assert paged == full assert len(set(paged)) == 9 -def test_get_attack_results_keyset_paginates_recency_and_timestamp_ties(sqlite_instance: MemoryInterface): +async def test_get_attack_results_keyset_paginates_recency_and_timestamp_ties(sqlite_instance: MemoryInterface): """With shared recency and timestamp, the seek falls through to the unique id tie-break.""" ids = [f"00000000-0000-4000-8000-{i:012d}" for i in range(8)] seeded = [ @@ -2190,15 +2270,15 @@ def test_get_attack_results_keyset_paginates_recency_and_timestamp_ties(sqlite_i _make_attack_result(f"conv-{i}", ts_offset=5, updated_at_offset=5, attack_result_id=ids[i]) for i in range(8) ] - sqlite_instance.add_attack_results_to_memory(attack_results=seeded) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=seeded)) - full = [r.attack_result_id for r in sqlite_instance.get_attack_results(limit=100)] - paged = [r.attack_result_id for r in _drain_keyset(sqlite_instance, page_size=3)] + full = [r.attack_result_id for r in (await sqlite_instance.get_attack_results_async(limit=100))] + paged = [r.attack_result_id for r in (await _drain_keyset_async(sqlite_instance, page_size=3))] assert paged == full assert len(set(paged)) == 8 -def test_attack_result_keyset_order_matches_sql_order(sqlite_instance: MemoryInterface): +async def test_attack_result_keyset_order_matches_sql_order(sqlite_instance: MemoryInterface): """The keyset anchor ordering (timestamp, id) reproduces the DB recency ordering.""" seeded = [ _make_attack_result("conv-a", ts_offset=1, created_at_offset=1), @@ -2206,11 +2286,11 @@ def test_attack_result_keyset_order_matches_sql_order(sqlite_instance: MemoryInt _make_attack_result("conv-c", ts_offset=3), _make_attack_result("conv-d", ts_offset=4), ] - sqlite_instance.add_attack_results_to_memory(attack_results=seeded) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=seeded)) - sql_order = list(sqlite_instance.get_attack_results(limit=100)) + sql_order = list(await sqlite_instance.get_attack_results_async(limit=100)) python_order = sorted( - sqlite_instance.get_attack_results(), + (await sqlite_instance.get_attack_results_async()), key=lambda ar: ( AttackResultKeysetCursor.from_attack_result(ar).timestamp, ar.attack_result_id, diff --git a/tests/unit/memory/memory_interface/test_interface_core.py b/tests/unit/memory/memory_interface/test_interface_core.py index 6fade65688..89d906df87 100644 --- a/tests/unit/memory/memory_interface/test_interface_core.py +++ b/tests/unit/memory/memory_interface/test_interface_core.py @@ -42,11 +42,11 @@ def test_print_schema_raises_when_engine_none(): obj.print_schema() -def test_get_all_embeddings_delegates_to_query(sqlite_instance: MemoryInterface): +async def test_get_all_embeddings_delegates_to_query(sqlite_instance: MemoryInterface): embedding = MagicMock(spec=EmbeddingDataEntry) with patch.object(sqlite_instance, "_query_entries", return_value=[embedding]) as query_entries: - result = sqlite_instance.get_all_embeddings() + result = await sqlite_instance.get_all_embeddings_async() assert result == [embedding] query_entries.assert_called_once_with(EmbeddingDataEntry) @@ -69,7 +69,7 @@ def test_query_entries_rolls_back_on_error(sqlite_instance: MemoryInterface): session = MagicMock() session.query.side_effect = SQLAlchemyError("query failed") - with patch.object(sqlite_instance, "get_session", return_value=session): + with patch.object(sqlite_instance, "_get_session", return_value=session): with pytest.raises(SQLAlchemyError, match="query failed"): sqlite_instance._query_entries(PromptMemoryEntry) @@ -78,7 +78,7 @@ def test_insert_entry_rolls_back_on_error(sqlite_instance: MemoryInterface): session = MagicMock() session.commit.side_effect = SQLAlchemyError("insert failed") - with patch.object(sqlite_instance, "get_session", return_value=session): + with patch.object(sqlite_instance, "_get_session", return_value=session): with pytest.raises(SQLAlchemyError, match="insert failed"): sqlite_instance._insert_entry(MagicMock()) @@ -89,7 +89,7 @@ def test_insert_entries_rolls_back_on_error(sqlite_instance: MemoryInterface): session = MagicMock() session.commit.side_effect = SQLAlchemyError("bulk insert failed") - with patch.object(sqlite_instance, "get_session", return_value=session): + with patch.object(sqlite_instance, "_get_session", return_value=session): with pytest.raises(SQLAlchemyError, match="bulk insert failed"): sqlite_instance._insert_entries(entries=[MagicMock()]) @@ -103,7 +103,7 @@ def test_update_entries_merges_missing_entry(sqlite_instance: MemoryInterface): session.scalar.return_value = None session.merge.return_value = entry - with patch.object(sqlite_instance, "get_session", return_value=session): + with patch.object(sqlite_instance, "_get_session", return_value=session): result = sqlite_instance._update_entries(entries=[entry], update_fields={"original_value": "after"}) assert result is True @@ -123,7 +123,7 @@ def _assert_locked(*, session: MagicMock, piece_ids: Sequence[uuid.UUID]) -> boo return False with ( - patch.object(sqlite_instance, "get_session", return_value=session), + patch.object(sqlite_instance, "_get_session", return_value=session), patch.object( sqlite_instance, "_message_pieces_are_observation_referenced_in_session", @@ -144,7 +144,7 @@ def test_update_entries_rolls_back_on_error(sqlite_instance: MemoryInterface): session.scalar.return_value = None session.get.side_effect = SQLAlchemyError("update failed") - with patch.object(sqlite_instance, "get_session", return_value=session): + with patch.object(sqlite_instance, "_get_session", return_value=session): with pytest.raises(SQLAlchemyError, match="update failed"): sqlite_instance._update_entries(entries=[entry], update_fields={"original_value": "after"}) diff --git a/tests/unit/memory/memory_interface/test_interface_identifiers.py b/tests/unit/memory/memory_interface/test_interface_identifiers.py index 8f638655e7..4cdc2dc01e 100644 --- a/tests/unit/memory/memory_interface/test_interface_identifiers.py +++ b/tests/unit/memory/memory_interface/test_interface_identifiers.py @@ -1,10 +1,10 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -from contextlib import closing from dataclasses import dataclass import pytest +from unit.mocks import run_memory_session_async from pyrit.memory import MemoryInterface from pyrit.memory.memory_models import TargetIdentifierEntry @@ -37,7 +37,7 @@ class IdentifierGraph: @pytest.fixture -def identifier_graph(sqlite_instance: MemoryInterface) -> IdentifierGraph: +async def identifier_graph(sqlite_instance: MemoryInterface) -> IdentifierGraph: objective_target = TargetIdentifier( class_name="ObjectiveTarget", class_module="tests.unit.memory", @@ -122,11 +122,12 @@ def identifier_graph(sqlite_instance: MemoryInterface) -> IdentifierGraph: objective_scorer=scorer, ) - with closing(sqlite_instance.get_session()) as session: + def persist_identifiers(session): sqlite_instance._persist_identifier(session=session, identifier=atomic_attack) sqlite_instance._persist_identifier(session=session, identifier=scenario) session.commit() + await run_memory_session_async(memory=sqlite_instance, operation=persist_identifiers) return IdentifierGraph( objective_target=objective_target, adversarial_target=adversarial_target, @@ -142,7 +143,7 @@ def identifier_graph(sqlite_instance: MemoryInterface) -> IdentifierGraph: ) -def test_get_target_identifiers_by_hash_and_promoted_field(sqlite_instance: MemoryInterface) -> None: +async def test_get_target_identifiers_by_hash_and_promoted_field(sqlite_instance: MemoryInterface) -> None: target = TargetIdentifier( class_name="TestTarget", class_module="tests.unit.memory", @@ -150,11 +151,13 @@ def test_get_target_identifiers_by_hash_and_promoted_field(sqlite_instance: Memo model_name="test-model", supported_auth_modes=["api_key", "identity"], ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id="identifier-query", target_identifier=target) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id="identifier-query", target_identifier=target) + ) ) - identifiers = sqlite_instance.get_target_identifiers( + identifiers = await sqlite_instance.get_target_identifiers_async( identifier_hashes=[target.hash], model_name="test-model", supported_auth_modes=["identity", "api_key"], @@ -162,76 +165,92 @@ def test_get_target_identifiers_by_hash_and_promoted_field(sqlite_instance: Memo assert identifiers == [target] assert isinstance(identifiers[0], TargetIdentifier) - assert sqlite_instance.get_target_identifiers(supported_auth_modes=["api_key"]) == [] - assert sqlite_instance.get_target_identifiers(supported_auth_modes=["API_KEY", "identity"]) == [] + assert (await sqlite_instance.get_target_identifiers_async(supported_auth_modes=["api_key"])) == [] + assert (await sqlite_instance.get_target_identifiers_async(supported_auth_modes=["API_KEY", "identity"])) == [] -def test_get_identifiers_reconstructs_each_typed_graph( +async def test_get_identifiers_reconstructs_each_typed_graph( sqlite_instance: MemoryInterface, identifier_graph: IdentifierGraph ) -> None: queries = [ ( - sqlite_instance.get_target_identifiers( - identifier_hashes=[identifier_graph.objective_target.hash], - endpoint="https://objective.test", - temperature=0.5, + ( + await sqlite_instance.get_target_identifiers_async( + identifier_hashes=[identifier_graph.objective_target.hash], + endpoint="https://objective.test", + temperature=0.5, + ) ), identifier_graph.objective_target, ), ( - sqlite_instance.get_converter_identifiers( - supported_input_types=["image_path", "text"], - supported_output_types=["audio_path", "text"], - sub_converter_hash=identifier_graph.nested_converter.hash, + ( + await sqlite_instance.get_converter_identifiers_async( + supported_input_types=["image_path", "text"], + supported_output_types=["audio_path", "text"], + sub_converter_hash=identifier_graph.nested_converter.hash, + ) ), identifier_graph.converter, ), ( - sqlite_instance.get_scorer_identifiers( - scorer_type="true_false", - score_aggregator="AND_", - prompt_target_hash=identifier_graph.adversarial_target.hash, + ( + await sqlite_instance.get_scorer_identifiers_async( + scorer_type="true_false", + score_aggregator="AND_", + prompt_target_hash=identifier_graph.adversarial_target.hash, + ) ), identifier_graph.scorer, ), ( - sqlite_instance.get_scenario_identifiers( - version=2, - techniques=["OtherTechnique", "TestTechnique"], - datasets=["dataset-b", "dataset-a"], - objective_target_hash=identifier_graph.objective_target.hash, - objective_scorer_hash=identifier_graph.scorer.hash, + ( + await sqlite_instance.get_scenario_identifiers_async( + version=2, + techniques=["OtherTechnique", "TestTechnique"], + datasets=["dataset-b", "dataset-a"], + objective_target_hash=identifier_graph.objective_target.hash, + objective_scorer_hash=identifier_graph.scorer.hash, + ) ), identifier_graph.scenario, ), ( - sqlite_instance.get_seed_identifiers( - value_sha256="dataset-sha", - data_type="text", - dataset_name="dataset-a", - is_general_technique=False, + ( + await sqlite_instance.get_seed_identifiers_async( + value_sha256="dataset-sha", + data_type="text", + dataset_name="dataset-a", + is_general_technique=False, + ) ), identifier_graph.dataset_seed, ), ( - sqlite_instance.get_attack_identifiers( - adversarial_system_prompt="system prompt", - adversarial_seed_prompt="seed prompt", - objective_target_hash=identifier_graph.objective_target.hash, - adversarial_chat_hash=identifier_graph.adversarial_target.hash, - objective_scorer_hash=identifier_graph.scorer.hash, + ( + await sqlite_instance.get_attack_identifiers_async( + adversarial_system_prompt="system prompt", + adversarial_seed_prompt="seed prompt", + objective_target_hash=identifier_graph.objective_target.hash, + adversarial_chat_hash=identifier_graph.adversarial_target.hash, + objective_scorer_hash=identifier_graph.scorer.hash, + ) ), identifier_graph.attack, ), ( - sqlite_instance.get_attack_technique_identifiers( - attack_identifier_hash=identifier_graph.attack.hash, + ( + await sqlite_instance.get_attack_technique_identifiers_async( + attack_identifier_hash=identifier_graph.attack.hash, + ) ), identifier_graph.technique, ), ( - sqlite_instance.get_atomic_attack_identifiers( - attack_technique_identifier_hash=identifier_graph.technique.hash, + ( + await sqlite_instance.get_atomic_attack_identifiers_async( + attack_technique_identifier_hash=identifier_graph.technique.hash, + ) ), identifier_graph.atomic_attack, ), @@ -242,34 +261,34 @@ def test_get_identifiers_reconstructs_each_typed_graph( assert type(identifiers[0]) is type(expected) -def test_get_identifiers_common_filters_and_result_semantics( +async def test_get_identifiers_common_filters_and_result_semantics( sqlite_instance: MemoryInterface, identifier_graph: IdentifierGraph ) -> None: - targets = sqlite_instance.get_target_identifiers() + targets = await sqlite_instance.get_target_identifiers_async() assert [identifier.hash for identifier in targets] == sorted( [identifier_graph.objective_target.hash, identifier_graph.adversarial_target.hash] ) duplicate_hashes = [identifier_graph.objective_target.hash, identifier_graph.objective_target.hash] - assert sqlite_instance.get_target_identifiers(identifier_hashes=duplicate_hashes) == [ + assert (await sqlite_instance.get_target_identifiers_async(identifier_hashes=duplicate_hashes)) == [ identifier_graph.objective_target ] - assert sqlite_instance.get_target_identifiers(identifier_hashes=[]) == [] - assert sqlite_instance.get_target_identifiers(class_name="missing") == [] + assert (await sqlite_instance.get_target_identifiers_async(identifier_hashes=[])) == [] + assert (await sqlite_instance.get_target_identifiers_async(class_name="missing")) == [] -def test_get_identifiers_rejects_missing_identifier_json(sqlite_instance: MemoryInterface) -> None: +async def test_get_identifiers_rejects_missing_identifier_json(sqlite_instance: MemoryInterface) -> None: identifier_hash = "0" * 64 sqlite_instance._insert_entry(TargetIdentifierEntry(hash=identifier_hash, identifier_json=None)) with pytest.raises(ValueError, match="has no identifier JSON"): - sqlite_instance.get_target_identifiers(identifier_hashes=[identifier_hash]) + (await sqlite_instance.get_target_identifiers_async(identifier_hashes=[identifier_hash])) -def test_get_identifiers_rejects_hash_mismatch(sqlite_instance: MemoryInterface) -> None: +async def test_get_identifiers_rejects_hash_mismatch(sqlite_instance: MemoryInterface) -> None: target = TargetIdentifier(class_name="Target", class_module="tests.unit.memory") identifier_hash = "f" * 64 sqlite_instance._insert_entry(TargetIdentifierEntry(hash=identifier_hash, identifier_json=target.model_dump())) with pytest.raises(ValueError, match="does not match its stored JSON hash"): - sqlite_instance.get_target_identifiers(identifier_hashes=[identifier_hash]) + (await sqlite_instance.get_target_identifiers_async(identifier_hashes=[identifier_hash])) diff --git a/tests/unit/memory/memory_interface/test_interface_observations.py b/tests/unit/memory/memory_interface/test_interface_observations.py index f00f2de18c..77abf077b7 100644 --- a/tests/unit/memory/memory_interface/test_interface_observations.py +++ b/tests/unit/memory/memory_interface/test_interface_observations.py @@ -1,11 +1,10 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import asyncio import uuid -from collections.abc import Iterator -from concurrent.futures import ThreadPoolExecutor +from collections.abc import AsyncIterator from pathlib import Path -from threading import Barrier, Event from typing import Any from unittest.mock import MagicMock, patch @@ -14,6 +13,7 @@ from sqlalchemy.dialects import mssql from sqlalchemy.exc import OperationalError, SQLAlchemyError from sqlalchemy.orm import Session +from unit.mocks import run_memory_session_async from pyrit.memory import MemoryInterface, SQLiteMemory from pyrit.memory.memory_models import ObservationEntry, ObservationMessagePieceEntry, ScoreEntry, ScoreObservationEntry @@ -38,15 +38,15 @@ def _identifier() -> ComponentIdentifier: return ComponentIdentifier(class_name="TestScorer", class_module="tests.unit.memory") -def _observation( +async def _observation_async( *, memory: MemoryInterface, scorable: MessageScorable, response_piece_id: uuid.UUID, expectation: ScoringExpectation, ) -> Observation: - scored_piece = memory.get_message_pieces(prompt_ids=[scorable.message_piece_ids[0]])[0] - response_piece = memory.get_message_pieces(prompt_ids=[response_piece_id])[0] + scored_piece = (await memory.get_message_pieces_async(prompt_ids=[scorable.message_piece_ids[0]]))[0] + response_piece = (await memory.get_message_pieces_async(prompt_ids=[response_piece_id]))[0] return Observation( source_identifier=_identifier(), acquisition=Acquisition.COMPLETE, @@ -64,20 +64,22 @@ def _observation( ) -def test_observations_and_score_links_round_trip_in_order(sqlite_instance: MemoryInterface): +async def test_observations_and_score_links_round_trip_in_order(sqlite_instance: MemoryInterface): pieces = [ MessagePiece(role="assistant", original_value="first", conversation_id=str(uuid.uuid4())), MessagePiece(role="assistant", original_value="second", conversation_id=str(uuid.uuid4())), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) scorable = MessageScorable(message_piece_ids=(pieces[0].id,)) expectation = ScoringExpectation(objective="Judge the response") observations = [ - _observation( - memory=sqlite_instance, - scorable=scorable, - response_piece_id=piece.id, - expectation=expectation, + ( + await _observation_async( + memory=sqlite_instance, + scorable=scorable, + response_piece_id=piece.id, + expectation=expectation, + ) ) for piece in pieces ] @@ -89,10 +91,10 @@ def test_observations_and_score_links_round_trip_in_order(sqlite_instance: Memor observation_ids=[observations[1].id, observations[0].id], ) - sqlite_instance.add_scores_to_memory(scores=[score], observations=observations) + (await sqlite_instance.add_scores_to_memory_async(scores=[score], observations=observations)) - stored_score = sqlite_instance.get_scores(score_ids=[score.id])[0] - stored_observations = sqlite_instance.get_observations(observation_ids=stored_score.observation_ids) + stored_score = (await sqlite_instance.get_scores_async(score_ids=[score.id]))[0] + stored_observations = await sqlite_instance.get_observations_async(observation_ids=stored_score.observation_ids) assert stored_score.observation_ids == [observations[1].id, observations[0].id] assert [observation.id for observation in stored_observations] == stored_score.observation_ids assert stored_score.scored_expectation == expectation @@ -101,12 +103,12 @@ def test_observations_and_score_links_round_trip_in_order(sqlite_instance: Memor assert entry.get_observation().id in {observation.id for observation in observations} -def test_existing_observation_can_support_another_score(sqlite_instance: MemoryInterface): +async def test_existing_observation_can_support_another_score(sqlite_instance: MemoryInterface): piece = MessagePiece(role="assistant", original_value="response", conversation_id=str(uuid.uuid4())) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[piece])) scorable = MessageScorable(message_piece_ids=(piece.id,)) expectation = ScoringExpectation(objective="Judge the response") - observation = _observation( + observation = await _observation_async( memory=sqlite_instance, scorable=scorable, response_piece_id=piece.id, @@ -119,7 +121,7 @@ def test_existing_observation_can_support_another_score(sqlite_instance: MemoryI scored_expectation=expectation, observation_ids=[observation.id], ) - sqlite_instance.add_scores_to_memory(scores=[first_score], observations=[observation]) + (await sqlite_instance.add_scores_to_memory_async(scores=[first_score], observations=[observation])) replay_score = first_score.model_copy( update={ "id": uuid.uuid4(), @@ -127,17 +129,17 @@ def test_existing_observation_can_support_another_score(sqlite_instance: MemoryI } ) - sqlite_instance.add_scores_to_memory(scores=[replay_score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[replay_score])) - assert sqlite_instance.get_scores(score_ids=[replay_score.id])[0].observation_ids == [observation.id] + assert (await sqlite_instance.get_scores_async(score_ids=[replay_score.id]))[0].observation_ids == [observation.id] -def test_unreferenced_observation_is_not_persisted(sqlite_instance: MemoryInterface): +async def test_unreferenced_observation_is_not_persisted(sqlite_instance: MemoryInterface): piece = MessagePiece(role="assistant", original_value="response", conversation_id=str(uuid.uuid4())) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[piece])) scorable = MessageScorable(message_piece_ids=(piece.id,)) expectation = ScoringExpectation(objective="Judge the response") - observation = _observation( + observation = await _observation_async( memory=sqlite_instance, scorable=scorable, response_piece_id=piece.id, @@ -151,15 +153,15 @@ def test_unreferenced_observation_is_not_persisted(sqlite_instance: MemoryInterf ) with pytest.raises(ValueError, match="not referenced"): - sqlite_instance.add_scores_to_memory(scores=[score], observations=[observation]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score], observations=[observation])) assert sqlite_instance._query_entries(ObservationEntry) == [] assert sqlite_instance._query_entries(ScoreEntry) == [] -def test_missing_observation_link_leaves_no_score(sqlite_instance: MemoryInterface): +async def test_missing_observation_link_leaves_no_score(sqlite_instance: MemoryInterface): piece = MessagePiece(role="assistant", original_value="response", conversation_id=str(uuid.uuid4())) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[piece])) scorable = MessageScorable(message_piece_ids=(piece.id,)) score = Score( score_value="true", @@ -169,12 +171,12 @@ def test_missing_observation_link_leaves_no_score(sqlite_instance: MemoryInterfa ) with pytest.raises(ValueError, match="not found in memory"): - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) assert sqlite_instance._query_entries(ScoreEntry) == [] -def test_duplicate_message_anchor_preserves_exact_observation_evidence( +async def test_duplicate_message_anchor_preserves_exact_observation_evidence( sqlite_instance: MemoryInterface, ): original = MessagePiece( @@ -183,18 +185,18 @@ def test_duplicate_message_anchor_preserves_exact_observation_evidence( conversation_id=str(uuid.uuid4()), sequence=0, ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[original]) - sqlite_instance.duplicate_conversation(conversation_id=original.conversation_id) - duplicate = next(piece for piece in sqlite_instance.get_message_pieces() if piece.id != original.id) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[original])) + (await sqlite_instance.duplicate_conversation_async(conversation_id=original.conversation_id)) + duplicate = next(piece for piece in (await sqlite_instance.get_message_pieces_async()) if piece.id != original.id) response = MessagePiece( role="assistant", original_value="judgment", conversation_id=str(uuid.uuid4()), ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[response]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[response])) scorable = MessageScorable(message_piece_ids=(duplicate.id,)) expectation = ScoringExpectation(objective="Judge the response") - observation = _observation( + observation = await _observation_async( memory=sqlite_instance, scorable=scorable, response_piece_id=response.id, @@ -208,16 +210,16 @@ def test_duplicate_message_anchor_preserves_exact_observation_evidence( observation_ids=[observation.id], ) - sqlite_instance.add_scores_to_memory(scores=[score], observations=[observation]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score], observations=[observation])) - stored_score = sqlite_instance.get_scores(score_ids=[score.id])[0] - stored_observation = sqlite_instance.get_observations(observation_ids=[observation.id])[0] + stored_score = (await sqlite_instance.get_scores_async(score_ids=[score.id]))[0] + stored_observation = (await sqlite_instance.get_observations_async(observation_ids=[observation.id]))[0] assert stored_score.scorable == MessageScorable(message_piece_ids=(original.id,)) assert stored_observation.scorable == MessageScorable(message_piece_ids=(duplicate.id,)) assert stored_observation.payload.scored_piece_id == duplicate.id -def test_sqlite_protects_observation_message_references( +async def test_sqlite_protects_observation_message_references( sqlite_instance: MemoryInterface, ): scored_piece = MessagePiece( @@ -232,10 +234,10 @@ def test_sqlite_protects_observation_message_references( conversation_id=str(uuid.uuid4()), sequence=0, ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[scored_piece, response_piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[scored_piece, response_piece])) scorable = MessageScorable(message_piece_ids=(scored_piece.id,)) expectation = ScoringExpectation(objective="Judge the response") - observation = _observation( + observation = await _observation_async( memory=sqlite_instance, scorable=scorable, response_piece_id=response_piece.id, @@ -247,41 +249,49 @@ def test_sqlite_protects_observation_message_references( scorable=scorable, observation_ids=[observation.id], ) - sqlite_instance.add_scores_to_memory( - scores=[score], - observations=[observation], + ( + await sqlite_instance.add_scores_to_memory_async( + scores=[score], + observations=[observation], + ) ) with pytest.raises(SQLAlchemyError): - sqlite_instance.delete_conversation_pieces_after_sequence( - conversation_id=response_piece.conversation_id, - sequence=-1, + ( + await sqlite_instance.delete_conversation_pieces_after_sequence_async( + conversation_id=response_piece.conversation_id, + sequence=-1, + ) ) with pytest.raises(SQLAlchemyError): - sqlite_instance.delete_conversation_pieces_after_sequence( - conversation_id=scored_piece.conversation_id, - sequence=-1, + ( + await sqlite_instance.delete_conversation_pieces_after_sequence_async( + conversation_id=scored_piece.conversation_id, + sequence=-1, + ) ) - assert sqlite_instance.get_message_pieces(prompt_ids=[response_piece.id]) + assert await sqlite_instance.get_message_pieces_async(prompt_ids=[response_piece.id]) @pytest.fixture -def file_memory(tmp_path: Path) -> Iterator[SQLiteMemory]: +async def file_memory(tmp_path: Path) -> AsyncIterator[SQLiteMemory]: memory = SQLiteMemory.__new__(SQLiteMemory) memory.__init__(db_path=tmp_path / "observations.db", silent=True) try: yield memory finally: - memory.dispose_engine() + await memory.dispose_engine_async() -def _score_and_observation(memory: MemoryInterface) -> tuple[Score, Observation, MessagePiece]: +async def _score_and_observation_async(memory: MemoryInterface) -> tuple[Score, Observation, MessagePiece]: piece = MessagePiece(role="assistant", original_value="response", conversation_id=str(uuid.uuid4()), sequence=0) - memory.add_message_pieces_to_memory(message_pieces=[piece]) + (await memory.add_message_pieces_to_memory_async(message_pieces=[piece])) scorable = MessageScorable(message_piece_ids=(piece.id,)) expectation = ScoringExpectation(objective="Judge the response") - observation = _observation(memory=memory, scorable=scorable, response_piece_id=piece.id, expectation=expectation) + observation = await _observation_async( + memory=memory, scorable=scorable, response_piece_id=piece.id, expectation=expectation + ) return ( Score( score_value="true", @@ -297,10 +307,10 @@ def _score_and_observation(memory: MemoryInterface) -> tuple[Score, Observation, @pytest.mark.parametrize("operation", ["UPDATE", "DELETE"]) @pytest.mark.parametrize("boundary", ["_resolve_score_message_anchors", "_persist_score_rows"]) -def test_file_sqlite_locks_evidence_before_reads_until_commit( +async def test_file_sqlite_locks_evidence_before_reads_until_commit( *, file_memory: SQLiteMemory, operation: str, boundary: str ) -> None: - score, observation, piece = _score_and_observation(file_memory) + score, observation, piece = await _score_and_observation_async(file_memory) statement = ( 'UPDATE "PromptMemoryEntries" SET converted_value = :value WHERE id = :id' if operation == "UPDATE" @@ -319,48 +329,47 @@ def _attempt_concurrent_write(*, session: Session, **kwargs: Any) -> Any: return original(session=session, **kwargs) with patch.object(file_memory, boundary, side_effect=_attempt_concurrent_write): - file_memory.add_scores_to_memory(scores=[score], observations=[observation]) + (await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation])) assert checked == [True] with file_memory.engine.connect() as writer: with pytest.raises(SQLAlchemyError, match="immutable observation evidence"): writer.execute(text(statement), {"id": str(piece.id), "value": "tampered"}) - assert file_memory.get_observations(observation_ids=[observation.id]) == [observation] + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [observation] @pytest.mark.parametrize("fail_commit", [False, True]) -def test_failed_score_write_preserves_duplicate_anchor( +async def test_failed_score_write_preserves_duplicate_anchor( *, file_memory: SQLiteMemory, fail_commit: bool, caplog: pytest.LogCaptureFixture ) -> None: - score, observation, piece = _score_and_observation(file_memory) - file_memory.duplicate_conversation(conversation_id=piece.conversation_id) - duplicate = next(value for value in file_memory.get_message_pieces() if value.id != piece.id) + score, observation, piece = await _score_and_observation_async(file_memory) + (await file_memory.duplicate_conversation_async(conversation_id=piece.conversation_id)) + duplicate = next(value for value in (await file_memory.get_message_pieces_async()) if value.id != piece.id) score.message_piece_id = duplicate.id score.scorable = MessageScorable(message_piece_ids=(duplicate.id,)) before = score.model_dump() - with file_memory.get_session() as session: - if fail_commit: - failure = patch.object(session, "commit", side_effect=SQLAlchemyError("commit failed")) - else: - failure = patch.object(file_memory, "_validate_observation_evidence", side_effect=ValueError("invalid")) - with patch.object(file_memory, "get_session", return_value=session), failure: - with pytest.raises((SQLAlchemyError, ValueError), match="commit failed|invalid"): - file_memory.add_scores_to_memory(scores=[score], observations=[observation]) + if fail_commit: + failure = patch.object(MemorySession, "commit", side_effect=SQLAlchemyError("commit failed")) + else: + failure = patch.object(file_memory, "_validate_observation_evidence", side_effect=ValueError("invalid")) + with failure, pytest.raises((SQLAlchemyError, ValueError), match="commit failed|invalid"): + await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation]) assert score.model_dump() == before assert file_memory._query_entries(ScoreEntry) == [] - assert file_memory.get_observations(observation_ids=[observation.id]) == [] + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [] if fail_commit: assert any(record.message == "Error inserting scores" and record.exc_info for record in caplog.records) @pytest.mark.parametrize("foreign_keys", [False, True]) @pytest.mark.parametrize("clear_links", [False, True]) -def test_orm_score_delete_cleans_last_observation_and_releases_prompt( +async def test_orm_score_delete_cleans_last_observation_and_releases_prompt( *, file_memory: SQLiteMemory, foreign_keys: bool, clear_links: bool ) -> None: - score, observation, piece = _score_and_observation(file_memory) - file_memory.add_scores_to_memory(scores=[score], observations=[observation]) - with file_memory.get_session() as session: + score, observation, piece = await _score_and_observation_async(file_memory) + (await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation])) + + def delete_score(session: Session) -> None: if foreign_keys: session.connection().exec_driver_sql("PRAGMA foreign_keys=ON") assert session.connection().exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 @@ -370,20 +379,27 @@ def test_orm_score_delete_cleans_last_observation_and_releases_prompt( entry.observation_links.clear() session.delete(entry) session.commit() - assert file_memory.get_observations(observation_ids=[observation.id]) == [] + + await run_memory_session_async(memory=file_memory, operation=delete_score) + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [] assert file_memory._query_entries(ObservationMessagePieceEntry) == [] assert file_memory._query_entries(ScoreObservationEntry) == [] - file_memory.delete_conversation_pieces_after_sequence(conversation_id=piece.conversation_id, sequence=-1) - assert file_memory.get_message_pieces(prompt_ids=[piece.id]) == [] + ( + await file_memory.delete_conversation_pieces_after_sequence_async( + conversation_id=piece.conversation_id, sequence=-1 + ) + ) + assert (await file_memory.get_message_pieces_async(prompt_ids=[piece.id])) == [] @pytest.mark.parametrize("clear_links", [False, True]) -def test_orm_score_delete_rollback_restores_observation_protection( +async def test_orm_score_delete_rollback_restores_observation_protection( *, file_memory: SQLiteMemory, clear_links: bool ) -> None: - score, observation, piece = _score_and_observation(file_memory) - file_memory.add_scores_to_memory(scores=[score], observations=[observation]) - with file_memory.get_session() as session: + score, observation, piece = await _score_and_observation_async(file_memory) + (await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation])) + + def rollback_delete(session: Session) -> None: entry = session.get(ScoreEntry, score.id) assert entry is not None if clear_links: @@ -392,22 +408,29 @@ def test_orm_score_delete_rollback_restores_observation_protection( session.flush() assert session.get(ObservationEntry, observation.id) is None session.rollback() - assert file_memory.get_scores(score_ids=[score.id])[0].observation_ids == [observation.id] - assert file_memory.get_observations(observation_ids=[observation.id]) == [observation] + + await run_memory_session_async(memory=file_memory, operation=rollback_delete) + assert (await file_memory.get_scores_async(score_ids=[score.id]))[0].observation_ids == [observation.id] + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [observation] assert len(file_memory._query_entries(ObservationMessagePieceEntry)) == 1 with pytest.raises(SQLAlchemyError, match="immutable observation evidence"): - file_memory.delete_conversation_pieces_after_sequence(conversation_id=piece.conversation_id, sequence=-1) + ( + await file_memory.delete_conversation_pieces_after_sequence_async( + conversation_id=piece.conversation_id, sequence=-1 + ) + ) @pytest.mark.parametrize("delete_together", [False, True]) @pytest.mark.parametrize("clear_links", [False, True]) -def test_orm_shared_observation_survives_until_final_score( +async def test_orm_shared_observation_survives_until_final_score( *, file_memory: SQLiteMemory, delete_together: bool, clear_links: bool ) -> None: - score, observation, piece = _score_and_observation(file_memory) + score, observation, piece = await _score_and_observation_async(file_memory) replay = score.model_copy(update={"id": uuid.uuid4()}) - file_memory.add_scores_to_memory(scores=[score, replay], observations=[observation]) - with file_memory.get_session() as session: + (await file_memory.add_scores_to_memory_async(scores=[score, replay], observations=[observation])) + + def delete_score(session: Session) -> None: entry = session.get(ScoreEntry, score.id) assert entry is not None if clear_links: @@ -416,24 +439,34 @@ def test_orm_shared_observation_survives_until_final_score( if delete_together: session.delete(session.get(ScoreEntry, replay.id)) session.commit() + + await run_memory_session_async(memory=file_memory, operation=delete_score) if not delete_together: - assert file_memory.get_observations(observation_ids=[observation.id]) == [observation] + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [observation] with pytest.raises(SQLAlchemyError): - file_memory.delete_conversation_pieces_after_sequence(conversation_id=piece.conversation_id, sequence=-1) - with file_memory.get_session() as session: + ( + await file_memory.delete_conversation_pieces_after_sequence_async( + conversation_id=piece.conversation_id, sequence=-1 + ) + ) + + def delete_replay(session: Session) -> None: session.delete(session.get(ScoreEntry, replay.id)) session.commit() - assert file_memory.get_observations(observation_ids=[observation.id]) == [] + + await run_memory_session_async(memory=file_memory, operation=delete_replay) + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [] assert file_memory._query_entries(ObservationMessagePieceEntry) == [] @pytest.mark.parametrize("remove_directly", [False, True]) -def test_orm_link_removal_cleans_observation_before_score_deletion( +async def test_orm_link_removal_cleans_observation_before_score_deletion( *, file_memory: SQLiteMemory, remove_directly: bool ) -> None: - score, observation, piece = _score_and_observation(file_memory) - file_memory.add_scores_to_memory(scores=[score], observations=[observation]) - with file_memory.get_session() as session: + score, observation, piece = await _score_and_observation_async(file_memory) + (await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation])) + + def remove_links(session: Session) -> None: entry = session.get(ScoreEntry, score.id) assert entry is not None if remove_directly: @@ -445,86 +478,138 @@ def test_orm_link_removal_cleans_observation_before_score_deletion( session.expire(entry, ["observation_links"]) session.delete(entry) session.commit() + + await run_memory_session_async(memory=file_memory, operation=remove_links) assert file_memory._query_entries(ScoreObservationEntry) == [] - file_memory.delete_conversation_pieces_after_sequence(conversation_id=piece.conversation_id, sequence=-1) - assert file_memory.get_message_pieces(prompt_ids=[piece.id]) == [] + ( + await file_memory.delete_conversation_pieces_after_sequence_async( + conversation_id=piece.conversation_id, sequence=-1 + ) + ) + assert (await file_memory.get_message_pieces_async(prompt_ids=[piece.id])) == [] @pytest.mark.parametrize("shared", [False, True]) @pytest.mark.parametrize("rollback", [False, True]) @pytest.mark.parametrize("foreign_keys", [False, True]) -def test_orm_score_delete_finds_links_missing_from_cached_collection( +async def test_orm_score_delete_finds_links_missing_from_cached_collection( *, file_memory: SQLiteMemory, shared: bool, rollback: bool, foreign_keys: bool ) -> None: - score, observation, _ = _score_and_observation(file_memory) - other_score, other_observation, piece = _score_and_observation(file_memory) - file_memory.add_scores_to_memory(scores=[score, other_score], observations=[observation, other_observation]) - with file_memory.get_session() as session: - if foreign_keys: - session.connection().exec_driver_sql("PRAGMA foreign_keys=ON") - entry = session.get(ScoreEntry, score.id) - assert entry is not None - assert [link.observation_id for link in entry.observation_links] == [observation.id] - with file_memory.get_session() as writer: + score, observation, _ = await _score_and_observation_async(file_memory) + other_score, other_observation, piece = await _score_and_observation_async(file_memory) + ( + await file_memory.add_scores_to_memory_async( + scores=[score, other_score], observations=[observation, other_observation] + ) + ) + async with await file_memory.get_session_async() as async_session: + + def load_entry(session: Session) -> ScoreEntry: + if foreign_keys: + session.connection().exec_driver_sql("PRAGMA foreign_keys=ON") + entry = session.get(ScoreEntry, score.id) + assert entry is not None + assert [link.observation_id for link in entry.observation_links] == [observation.id] + return entry + + entry = await async_session.run_sync(load_entry) + + def add_stale_link(writer: Session) -> None: writer.add(ScoreObservationEntry(score_id=score.id, position=1, observation_id=other_observation.id)) if not shared: writer.delete(writer.get(ScoreEntry, other_score.id)) writer.commit() - assert [link.observation_id for link in entry.observation_links] == [observation.id] - session.delete(entry) - session.flush() - if rollback: - session.rollback() - else: - session.commit() + + await run_memory_session_async(memory=file_memory, operation=add_stale_link) + + def finish_delete(session: Session) -> None: + assert [link.observation_id for link in entry.observation_links] == [observation.id] + session.delete(entry) + session.flush() + if rollback: + session.rollback() + else: + session.commit() + + await async_session.run_sync(finish_delete) retained = shared or rollback - assert file_memory.get_observations(observation_ids=[other_observation.id]) == ( + assert (await file_memory.get_observations_async(observation_ids=[other_observation.id])) == ( [other_observation] if retained else [] ) if rollback: - assert file_memory.get_scores(score_ids=[score.id])[0].observation_ids == [observation.id, other_observation.id] + assert (await file_memory.get_scores_async(score_ids=[score.id]))[0].observation_ids == [ + observation.id, + other_observation.id, + ] else: assert all(link.score_id != score.id for link in file_memory._query_entries(ScoreObservationEntry)) if retained: with pytest.raises(SQLAlchemyError, match="immutable observation evidence"): - file_memory.delete_conversation_pieces_after_sequence(conversation_id=piece.conversation_id, sequence=-1) + ( + await file_memory.delete_conversation_pieces_after_sequence_async( + conversation_id=piece.conversation_id, sequence=-1 + ) + ) else: - file_memory.delete_conversation_pieces_after_sequence(conversation_id=piece.conversation_id, sequence=-1) - assert file_memory.get_message_pieces(prompt_ids=[piece.id]) == [] + ( + await file_memory.delete_conversation_pieces_after_sequence_async( + conversation_id=piece.conversation_id, sequence=-1 + ) + ) + assert (await file_memory.get_message_pieces_async(prompt_ids=[piece.id])) == [] -def test_orm_clearing_stale_links_cleans_the_persisted_observation(file_memory: SQLiteMemory) -> None: - score, observation, _ = _score_and_observation(file_memory) +async def test_orm_clearing_stale_links_cleans_the_persisted_observation(file_memory: SQLiteMemory) -> None: + score, observation, _ = await _score_and_observation_async(file_memory) shared_score = score.model_copy(update={"id": uuid.uuid4()}) - other_score, other_observation, piece = _score_and_observation(file_memory) - file_memory.add_scores_to_memory( - scores=[score, shared_score, other_score], observations=[observation, other_observation] + other_score, other_observation, piece = await _score_and_observation_async(file_memory) + ( + await file_memory.add_scores_to_memory_async( + scores=[score, shared_score, other_score], observations=[observation, other_observation] + ) ) - with file_memory.get_session() as session: - entry = session.get(ScoreEntry, score.id) - assert entry is not None - assert entry.observation_links[0].observation_id == observation.id - with file_memory.get_session() as writer: + async with await file_memory.get_session_async() as async_session: + + def load_entry(session: Session) -> ScoreEntry: + entry = session.get(ScoreEntry, score.id) + assert entry is not None + assert entry.observation_links[0].observation_id == observation.id + return entry + + entry = await async_session.run_sync(load_entry) + + def replace_link(writer: Session) -> None: updated = writer.get(ScoreEntry, score.id) assert updated is not None updated.observation_links[0].observation_id = other_observation.id writer.delete(writer.get(ScoreEntry, other_score.id)) writer.commit() - entry.observation_links.clear() - session.flush() - assert session.get(ObservationEntry, other_observation.id) is None - session.delete(entry) - session.commit() - assert file_memory.get_observations(observation_ids=[observation.id]) == [observation] - file_memory.delete_conversation_pieces_after_sequence(conversation_id=piece.conversation_id, sequence=-1) - assert file_memory.get_message_pieces(prompt_ids=[piece.id]) == [] + await run_memory_session_async(memory=file_memory, operation=replace_link) -def test_orm_moving_link_before_score_deletion_preserves_observation(file_memory: SQLiteMemory) -> None: - score, observation, _ = _score_and_observation(file_memory) + def finish_delete(session: Session) -> None: + entry.observation_links.clear() + session.flush() + assert session.get(ObservationEntry, other_observation.id) is None + session.delete(entry) + session.commit() + + await async_session.run_sync(finish_delete) + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [observation] + ( + await file_memory.delete_conversation_pieces_after_sequence_async( + conversation_id=piece.conversation_id, sequence=-1 + ) + ) + assert (await file_memory.get_message_pieces_async(prompt_ids=[piece.id])) == [] + + +async def test_orm_moving_link_before_score_deletion_preserves_observation(file_memory: SQLiteMemory) -> None: + score, observation, _ = await _score_and_observation_async(file_memory) other_score = score.model_copy(update={"id": uuid.uuid4(), "observation_ids": []}) - file_memory.add_scores_to_memory(scores=[score, other_score], observations=[observation]) - with file_memory.get_session() as session: + (await file_memory.add_scores_to_memory_async(scores=[score, other_score], observations=[observation])) + + def move_link(session: Session) -> None: entry = session.get(ScoreEntry, score.id) other = session.get(ScoreEntry, other_score.id) assert entry is not None and other is not None @@ -532,86 +617,92 @@ def test_orm_moving_link_before_score_deletion_preserves_observation(file_memory other.observation_links.append(link) session.delete(entry) session.commit() - assert file_memory.get_observations(observation_ids=[observation.id]) == [observation] - assert file_memory.get_scores(score_ids=[other_score.id])[0].observation_ids == [observation.id] - with file_memory.get_session() as session: + + await run_memory_session_async(memory=file_memory, operation=move_link) + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [observation] + assert (await file_memory.get_scores_async(score_ids=[other_score.id]))[0].observation_ids == [observation.id] + + def delete_other(session: Session) -> None: session.delete(session.get(ScoreEntry, other_score.id)) session.commit() - assert file_memory.get_observations(observation_ids=[observation.id]) == [] + await run_memory_session_async(memory=file_memory, operation=delete_other) + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [] -def test_concurrent_orm_score_deletions_clean_final_observation(file_memory: SQLiteMemory) -> None: - score, observation, _ = _score_and_observation(file_memory) + +async def test_concurrent_orm_score_deletions_clean_final_observation(file_memory: SQLiteMemory) -> None: + score, observation, _ = await _score_and_observation_async(file_memory) replay = score.model_copy(update={"id": uuid.uuid4()}) - file_memory.add_scores_to_memory(scores=[score, replay], observations=[observation]) - ready = Barrier(2) + (await file_memory.add_scores_to_memory_async(scores=[score, replay], observations=[observation])) + ready = asyncio.Barrier(2) - def _delete(score_id: uuid.UUID) -> None: - with file_memory.get_session() as session: - entry = session.get(ScoreEntry, score_id) - ready.wait(timeout=5) - session.delete(entry) - session.commit() + async def delete_async(score_id: uuid.UUID) -> None: + async with await file_memory.get_session_async() as session: + entry = await session.get(ScoreEntry, score_id) + await asyncio.wait_for(ready.wait(), timeout=5) + await session.delete(entry) + await session.commit() - with ThreadPoolExecutor(max_workers=2) as pool: - futures = [pool.submit(_delete, value.id) for value in (score, replay)] - for future in futures: - future.result(timeout=10) + await asyncio.wait_for(asyncio.gather(*(delete_async(value.id) for value in (score, replay))), timeout=10) assert file_memory._query_entries(ScoreEntry) == [] - assert file_memory.get_observations(observation_ids=[observation.id]) == [] + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [] assert file_memory._query_entries(ObservationMessagePieceEntry) == [] @pytest.mark.parametrize("insert_first", [False, True]) @pytest.mark.parametrize("insert_via_orm", [False, True]) -def test_concurrent_insert_and_final_delete_do_not_orphan_score( +async def test_concurrent_insert_and_final_delete_do_not_orphan_score( *, file_memory: SQLiteMemory, insert_first: bool, insert_via_orm: bool ) -> None: - score, observation, _ = _score_and_observation(file_memory) + score, observation, _ = await _score_and_observation_async(file_memory) replay = score.model_copy(update={"id": uuid.uuid4()}) - file_memory.add_scores_to_memory(scores=[score], observations=[observation]) - competing_write = Event() + (await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation])) + competing_write = asyncio.Event() def _before_write(*, statement: str, **kwargs: Any) -> None: if statement == "BEGIN IMMEDIATE": competing_write.set() - def _compete() -> None: + async def compete_async() -> None: if insert_first: - with file_memory.get_session() as session: - session.delete(session.get(ScoreEntry, score.id)) - session.commit() + async with await file_memory.get_session_async() as session: + await session.delete(await session.get(ScoreEntry, score.id)) + await session.commit() else: with pytest.raises(ValueError, match="not found in memory"): if insert_via_orm: - with file_memory.get_session() as session: + async with await file_memory.get_session_async() as session: session.add(ScoreEntry(entry=replay)) session.add( ScoreObservationEntry(score_id=replay.id, position=0, observation_id=observation.id) ) - session.commit() + await session.commit() else: - file_memory.add_scores_to_memory(scores=[replay]) + (await file_memory.add_scores_to_memory_async(scores=[replay])) - with file_memory.get_session() as session, ThreadPoolExecutor(max_workers=1) as pool: + engine = file_memory._get_async_engine().sync_engine + async with await file_memory.get_session_async() as session: if insert_first: session.add(ScoreEntry(entry=replay)) session.add(ScoreObservationEntry(score_id=replay.id, position=0, observation_id=observation.id)) else: - session.delete(session.get(ScoreEntry, score.id)) - session.flush() - event.listen(file_memory.engine, "before_cursor_execute", _before_write, named=True) + await session.delete(await session.get(ScoreEntry, score.id)) + await session.flush() + event.listen(engine, "before_cursor_execute", _before_write, named=True) + task = asyncio.create_task(compete_async()) try: - future = pool.submit(_compete) - assert competing_write.wait(timeout=5) - assert not future.done() - session.commit() - future.result(timeout=10) + await asyncio.wait_for(competing_write.wait(), timeout=5) + assert not task.done() + await session.commit() + await asyncio.wait_for(task, timeout=10) finally: - session.rollback() - event.remove(file_memory.engine, "before_cursor_execute", _before_write) + await session.rollback() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + event.remove(engine, "before_cursor_execute", _before_write) expected = [observation] if insert_first else [] - assert file_memory.get_observations(observation_ids=[observation.id]) == expected + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == expected assert len(file_memory._query_entries(ScoreEntry)) == int(insert_first) @@ -664,7 +755,7 @@ def test_sqlite_write_requires_a_real_driver_connection() -> None: session.get_bind.return_value.dialect.name = "sqlite" session.connection.return_value.connection.driver_connection = None - with pytest.raises(TypeError, match="requires a sqlite3.Connection"): + with pytest.raises(TypeError, match="requires a sqlite3 or aiosqlite connection"): _begin_sqlite_write(session) session.connection.return_value.exec_driver_sql.assert_not_called() @@ -678,15 +769,15 @@ def test_sqlite_write_requires_a_real_driver_connection() -> None: (TraceScorable(trace_ids=("1" * 32,)), "message or content evidence"), ], ) -def test_unchecked_observation_rejected( +async def test_unchecked_observation_rejected( *, file_memory: SQLiteMemory, direct_orm: bool, scorable: object, error: str ) -> None: - score, observation, _ = _score_and_observation(file_memory) + score, observation, _ = await _score_and_observation_async(file_memory) observation = observation.model_copy(update={"scorable": scorable}) with pytest.raises(ValueError, match=error): if direct_orm: ObservationEntry(entry=observation) else: - file_memory.add_scores_to_memory(scores=[score], observations=[observation]) - assert file_memory.get_scores(score_ids=[score.id]) == [] - assert file_memory.get_observations(observation_ids=[observation.id]) == [] + (await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation])) + assert (await file_memory.get_scores_async(score_ids=[score.id])) == [] + assert (await file_memory.get_observations_async(observation_ids=[observation.id])) == [] diff --git a/tests/unit/memory/memory_interface/test_interface_prompts.py b/tests/unit/memory/memory_interface/test_interface_prompts.py index 5fbde08abf..ed445e114b 100644 --- a/tests/unit/memory/memory_interface/test_interface_prompts.py +++ b/tests/unit/memory/memory_interface/test_interface_prompts.py @@ -49,14 +49,14 @@ def assert_original_value_in_list(original_value: str, message_pieces: Sequence[ raise AssertionError(f"Original value {original_value} not found in list") -def test_conversation_memory_empty_by_default(sqlite_instance: MemoryInterface): +async def test_conversation_memory_empty_by_default(sqlite_instance: MemoryInterface): expected_count = 0 - c = sqlite_instance.get_message_pieces() + c = await sqlite_instance.get_message_pieces_async() assert len(c) == expected_count @pytest.mark.parametrize("num_conversations", [1, 2, 3]) -def test_add_message_pieces_to_memory( +async def test_add_message_pieces_to_memory( sqlite_instance: MemoryInterface, sample_conversations: Sequence[MessagePiece], num_conversations: int ): for c in sample_conversations[:num_conversations]: @@ -66,11 +66,11 @@ def test_add_message_pieces_to_memory( message = Message(message_pieces=sample_conversations[:num_conversations]) - sqlite_instance.add_message_to_memory(request=message) - assert len(sqlite_instance.get_message_pieces()) == num_conversations + (await sqlite_instance.add_message_to_memory_async(request=message)) + assert len(await sqlite_instance.get_message_pieces_async()) == num_conversations -def test_add_message_pieces_preserves_same_sequence_order(sqlite_instance: MemoryInterface): +async def test_add_message_pieces_preserves_same_sequence_order(sqlite_instance: MemoryInterface): conversation_id = str(uuid4()) timestamp = datetime.now(tz=UTC) pieces = [ @@ -92,15 +92,15 @@ def test_add_message_pieces_preserves_same_sequence_order(sqlite_instance: Memor ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) - persisted_pieces = sqlite_instance.get_message_pieces(conversation_id=conversation_id) + persisted_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id) assert [piece.original_value for piece in persisted_pieces] == ["first", "second"] assert persisted_pieces[0].timestamp < persisted_pieces[1].timestamp assert pieces[0].timestamp == pieces[1].timestamp -def test_add_message_pieces_persists_converter_identifier_graph(sqlite_instance: MemoryInterface): +async def test_add_message_pieces_persists_converter_identifier_graph(sqlite_instance: MemoryInterface): target = TargetIdentifier( class_name="ConverterTarget", class_module="tests.unit.memory", @@ -130,7 +130,7 @@ def test_add_message_pieces_persists_converter_identifier_graph(sqlite_instance: for index in range(2) ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) converter_rows = sqlite_instance._query_entries(ConverterIdentifierEntry) link_rows = sqlite_instance._query_entries(PromptConverterIdentifierEntry) @@ -145,7 +145,7 @@ def test_add_message_pieces_persists_converter_identifier_graph(sqlite_instance: } -def test_get_message_pieces_uuid_and_string_ids(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_uuid_and_string_ids(sqlite_instance: MemoryInterface): """Test that get_message_pieces handles both UUID objects and string representations.""" uuid1 = uuid.uuid4() uuid2 = uuid.uuid4() @@ -174,31 +174,31 @@ def test_get_message_pieces_uuid_and_string_ids(sqlite_instance: MemoryInterface converted_value="Test prompt 3", ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) - uuid_results = sqlite_instance.get_message_pieces(prompt_ids=[uuid1, uuid2]) + uuid_results = await sqlite_instance.get_message_pieces_async(prompt_ids=[uuid1, uuid2]) assert len(uuid_results) == 2 assert {str(uuid1), str(uuid2)} == {str(piece.id) for piece in uuid_results} - str_results = sqlite_instance.get_message_pieces(prompt_ids=[str(uuid1), str(uuid2)]) + str_results = await sqlite_instance.get_message_pieces_async(prompt_ids=[str(uuid1), str(uuid2)]) assert len(str_results) == 2 assert {str(uuid1), str(uuid2)} == {str(piece.id) for piece in str_results} mixed_types: Sequence[str | uuid.UUID] = [uuid1, str(uuid2)] - mixed_results = sqlite_instance.get_message_pieces(prompt_ids=mixed_types) + mixed_results = await sqlite_instance.get_message_pieces_async(prompt_ids=mixed_types) assert len(mixed_results) == 2 assert {str(uuid1), str(uuid2)} == {str(piece.id) for piece in mixed_results} - single_uuid_result = sqlite_instance.get_message_pieces(prompt_ids=[uuid3]) + single_uuid_result = await sqlite_instance.get_message_pieces_async(prompt_ids=[uuid3]) assert len(single_uuid_result) == 1 assert str(single_uuid_result[0].id) == str(uuid3) - single_str_result = sqlite_instance.get_message_pieces(prompt_ids=[str(uuid3)]) + single_str_result = await sqlite_instance.get_message_pieces_async(prompt_ids=[str(uuid3)]) assert len(single_str_result) == 1 assert str(single_str_result[0].id) == str(uuid3) -def test_get_message_pieces_empty_prompt_ids_returns_empty(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_empty_prompt_ids_returns_empty(sqlite_instance: MemoryInterface): piece = MessagePiece( conversation_id=str(uuid4()), id=uuid.uuid4(), @@ -206,12 +206,12 @@ def test_get_message_pieces_empty_prompt_ids_returns_empty(sqlite_instance: Memo original_value="Test prompt", converted_value="Test prompt", ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[piece])) - assert sqlite_instance.get_message_pieces(prompt_ids=[]) == [] + assert (await sqlite_instance.get_message_pieces_async(prompt_ids=[])) == [] -def test_duplicate_memory(sqlite_instance: MemoryInterface): +async def test_duplicate_memory(sqlite_instance: MemoryInterface): attack1 = PromptSendingAttack(objective_target=get_mock_target()) attack2 = PromptSendingAttack(objective_target=get_mock_target("Target2")) conversation_id_1 = "11111" @@ -253,15 +253,15 @@ def test_duplicate_memory(sqlite_instance: MemoryInterface): sequence=1, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) - assert len(sqlite_instance.get_message_pieces()) == 5 - new_conversation_id1 = sqlite_instance.duplicate_conversation( + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) + assert len(await sqlite_instance.get_message_pieces_async()) == 5 + new_conversation_id1 = await sqlite_instance.duplicate_conversation_async( conversation_id=conversation_id_1, ) - new_conversation_id2 = sqlite_instance.duplicate_conversation( + new_conversation_id2 = await sqlite_instance.duplicate_conversation_async( conversation_id=conversation_id_2, ) - all_pieces = sqlite_instance.get_message_pieces() + all_pieces = await sqlite_instance.get_message_pieces_async() assert len(all_pieces) == 9 assert len([p for p in all_pieces if p.conversation_id == conversation_id_1]) == 2 assert len([p for p in all_pieces if p.conversation_id == conversation_id_2]) == 2 @@ -271,7 +271,7 @@ def test_duplicate_memory(sqlite_instance: MemoryInterface): # Ensure that the score entries are not duplicated when a conversation is duplicated -def test_duplicate_conversation_pieces_not_score(sqlite_instance: MemoryInterface): +async def test_duplicate_conversation_pieces_not_score(sqlite_instance: MemoryInterface): conversation_id = str(uuid4()) prompt_id_1 = uuid4() prompt_id_2 = uuid4() @@ -318,12 +318,12 @@ def test_duplicate_conversation_pieces_not_score(sqlite_instance: MemoryInterfac message_piece_id=prompt_id_2, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) - sqlite_instance.add_scores_to_memory(scores=scores) - new_conversation_id = sqlite_instance.duplicate_conversation( + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) + (await sqlite_instance.add_scores_to_memory_async(scores=scores)) + new_conversation_id = await sqlite_instance.duplicate_conversation_async( conversation_id=conversation_id, ) - new_pieces = sqlite_instance.get_message_pieces(conversation_id=new_conversation_id) + new_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=new_conversation_id) new_pieces_ids = [str(p.id) for p in new_pieces] assert len(new_pieces) == 2 original_ids = {piece.original_prompt_id for piece in new_pieces} @@ -333,10 +333,17 @@ def test_duplicate_conversation_pieces_not_score(sqlite_instance: MemoryInterfac assert piece.id not in (prompt_id_1, prompt_id_2) # The duplicate prompts ids should not have scores so only two scores are returned - assert len(sqlite_instance.get_prompt_scores(prompt_ids=[str(prompt_id_1), str(prompt_id_2)] + new_pieces_ids)) == 2 + assert ( + len( + await sqlite_instance.get_prompt_scores_async( + prompt_ids=[str(prompt_id_1), str(prompt_id_2)] + new_pieces_ids + ) + ) + == 2 + ) -def test_duplicate_conversation_excluding_last_turn(sqlite_instance: MemoryInterface): +async def test_duplicate_conversation_excluding_last_turn(sqlite_instance: MemoryInterface): attack1 = PromptSendingAttack(objective_target=get_mock_target()) attack2 = PromptSendingAttack(objective_target=get_mock_target()) conversation_id_1 = "11111" @@ -376,24 +383,24 @@ def test_duplicate_conversation_excluding_last_turn(sqlite_instance: MemoryInter sequence=3, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) - assert len(sqlite_instance.get_message_pieces()) == 5 + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) + assert len(await sqlite_instance.get_message_pieces_async()) == 5 - new_conversation_id1 = sqlite_instance.duplicate_conversation_excluding_last_turn( + new_conversation_id1 = await sqlite_instance.duplicate_conversation_excluding_last_turn_async( conversation_id=conversation_id_1, ) - all_memory = sqlite_instance.get_message_pieces() + all_memory = await sqlite_instance.get_message_pieces_async() assert len(all_memory) == 7 - duplicate_conversation = sqlite_instance.get_message_pieces(conversation_id=new_conversation_id1) + duplicate_conversation = await sqlite_instance.get_message_pieces_async(conversation_id=new_conversation_id1) assert len(duplicate_conversation) == 2 for piece in duplicate_conversation: assert piece.sequence < 2 -def test_duplicate_conversation_excluding_last_turn_not_score(sqlite_instance: MemoryInterface): +async def test_duplicate_conversation_excluding_last_turn_not_score(sqlite_instance: MemoryInterface): conversation_id = str(uuid4()) prompt_id_1 = uuid4() prompt_id_2 = uuid4() @@ -454,13 +461,13 @@ def test_duplicate_conversation_excluding_last_turn_not_score(sqlite_instance: M message_piece_id=prompt_id_2, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) - sqlite_instance.add_scores_to_memory(scores=scores) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) + (await sqlite_instance.add_scores_to_memory_async(scores=scores)) - new_conversation_id = sqlite_instance.duplicate_conversation_excluding_last_turn( + new_conversation_id = await sqlite_instance.duplicate_conversation_excluding_last_turn_async( conversation_id=conversation_id, ) - new_pieces = sqlite_instance.get_message_pieces(conversation_id=new_conversation_id) + new_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=new_conversation_id) new_pieces_ids = [str(p.id) for p in new_pieces] assert len(new_pieces) == 2 assert new_pieces[0].original_prompt_id == prompt_id_1 @@ -468,10 +475,17 @@ def test_duplicate_conversation_excluding_last_turn_not_score(sqlite_instance: M assert new_pieces[0].id != prompt_id_1 assert new_pieces[1].id != prompt_id_2 # The duplicate prompts ids should not have scores so only two scores are returned - assert len(sqlite_instance.get_prompt_scores(prompt_ids=[str(prompt_id_1), str(prompt_id_2)] + new_pieces_ids)) == 2 + assert ( + len( + await sqlite_instance.get_prompt_scores_async( + prompt_ids=[str(prompt_id_1), str(prompt_id_2)] + new_pieces_ids + ) + ) + == 2 + ) -def test_duplicate_conversation_excluding_last_turn_same_attack(sqlite_instance: MemoryInterface): +async def test_duplicate_conversation_excluding_last_turn_same_attack(sqlite_instance: MemoryInterface): attack1 = PromptSendingAttack(objective_target=get_mock_target()) conversation_id_1 = "11111" pieces = [ @@ -500,24 +514,24 @@ def test_duplicate_conversation_excluding_last_turn_same_attack(sqlite_instance: sequence=3, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) - assert len(sqlite_instance.get_message_pieces()) == 4 + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) + assert len(await sqlite_instance.get_message_pieces_async()) == 4 - new_conversation_id1 = sqlite_instance.duplicate_conversation_excluding_last_turn( + new_conversation_id1 = await sqlite_instance.duplicate_conversation_excluding_last_turn_async( conversation_id=conversation_id_1, ) - all_memory = sqlite_instance.get_message_pieces() + all_memory = await sqlite_instance.get_message_pieces_async() assert len(all_memory) == 6 - duplicate_conversation = sqlite_instance.get_message_pieces(conversation_id=new_conversation_id1) + duplicate_conversation = await sqlite_instance.get_message_pieces_async(conversation_id=new_conversation_id1) assert len(duplicate_conversation) == 2 for piece in duplicate_conversation: assert piece.sequence < 2 -def test_duplicate_conversation_creates_new_ids(sqlite_instance: MemoryInterface): +async def test_duplicate_conversation_creates_new_ids(sqlite_instance: MemoryInterface): """Test that duplicated conversation has new piece IDs.""" attack1 = PromptSendingAttack(objective_target=get_mock_target()) conversation_id = "test-conv-123" @@ -528,14 +542,14 @@ def test_duplicate_conversation_creates_new_ids(sqlite_instance: MemoryInterface conversation_id=conversation_id, sequence=1, ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[original_piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[original_piece])) - new_conversation_id = sqlite_instance.duplicate_conversation( + new_conversation_id = await sqlite_instance.duplicate_conversation_async( conversation_id=conversation_id, ) - original_pieces = sqlite_instance.get_message_pieces(conversation_id=conversation_id) - new_pieces = sqlite_instance.get_message_pieces(conversation_id=new_conversation_id) + original_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id) + new_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=new_conversation_id) assert len(original_pieces) == 1 assert len(new_pieces) == 1 @@ -548,7 +562,7 @@ def test_duplicate_conversation_creates_new_ids(sqlite_instance: MemoryInterface assert original_pieces[0].converted_value == new_pieces[0].converted_value -def test_duplicate_conversation_preserves_original_prompt_id(sqlite_instance: MemoryInterface): +async def test_duplicate_conversation_preserves_original_prompt_id(sqlite_instance: MemoryInterface): """Test that duplicated conversation preserves original_prompt_id for tracing.""" attack1 = PromptSendingAttack(objective_target=get_mock_target()) conversation_id = "test-conv-456" @@ -558,20 +572,20 @@ def test_duplicate_conversation_preserves_original_prompt_id(sqlite_instance: Me conversation_id=conversation_id, sequence=1, ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[original_piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[original_piece])) original_prompt_id = original_piece.original_prompt_id - new_conversation_id = sqlite_instance.duplicate_conversation( + new_conversation_id = await sqlite_instance.duplicate_conversation_async( conversation_id=conversation_id, ) - new_pieces = sqlite_instance.get_message_pieces(conversation_id=new_conversation_id) + new_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=new_conversation_id) # original_prompt_id should be preserved for tracing assert new_pieces[0].original_prompt_id == original_prompt_id -def test_duplicate_conversation_with_multiple_pieces(sqlite_instance: MemoryInterface): +async def test_duplicate_conversation_with_multiple_pieces(sqlite_instance: MemoryInterface): """Test that duplicating a multi-piece conversation works correctly.""" attack1 = PromptSendingAttack(objective_target=get_mock_target()) conversation_id = "multi-piece-conv" @@ -596,14 +610,14 @@ def test_duplicate_conversation_with_multiple_pieces(sqlite_instance: MemoryInte sequence=3, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) - new_conversation_id = sqlite_instance.duplicate_conversation( + new_conversation_id = await sqlite_instance.duplicate_conversation_async( conversation_id=conversation_id, ) - original_pieces = sqlite_instance.get_message_pieces(conversation_id=conversation_id) - new_pieces = sqlite_instance.get_message_pieces(conversation_id=new_conversation_id) + original_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id) + new_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=new_conversation_id) assert len(new_pieces) == 3 @@ -620,32 +634,34 @@ def test_duplicate_conversation_with_multiple_pieces(sqlite_instance: MemoryInte assert orig.original_value == new.original_value -def test_add_message_pieces_to_memory_calls_validate(sqlite_instance: MemoryInterface): +async def test_add_message_pieces_to_memory_calls_validate(sqlite_instance: MemoryInterface): message = MagicMock(Message) message.message_pieces = [MagicMock(MessagePiece, not_in_memory=False, conversation_id="test-conversation")] with ( - patch("pyrit.memory.sqlite_memory.SQLiteMemory.add_message_pieces_to_memory"), + patch.object(sqlite_instance, "_execute_add_message_pieces_to_memory"), patch("pyrit.memory.memory_interface.MemoryInterface._update_sequence"), ): - sqlite_instance.add_message_to_memory(request=message) + (await sqlite_instance.add_message_to_memory_async(request=message)) assert message.validate.called @pytest.mark.parametrize("bad_id", [None, "", " "]) -def test_add_message_pieces_to_memory_raises_when_conversation_id_missing(sqlite_instance: MemoryInterface, bad_id): +async def test_add_message_pieces_to_memory_raises_when_conversation_id_missing( + sqlite_instance: MemoryInterface, bad_id +): piece = MessagePiece(role="user", original_value="hello", conversation_id=bad_id) with pytest.raises(ValueError, match="conversation_id"): - sqlite_instance.add_message_pieces_to_memory(message_pieces=[piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[piece])) @pytest.mark.parametrize("bad_id", [None, "", " "]) -def test_add_message_to_memory_raises_when_conversation_id_missing(sqlite_instance: MemoryInterface, bad_id): +async def test_add_message_to_memory_raises_when_conversation_id_missing(sqlite_instance: MemoryInterface, bad_id): piece = MessagePiece(role="user", original_value="hello", conversation_id=bad_id) with pytest.raises(ValueError, match="conversation_id"): - sqlite_instance.add_message_to_memory(request=Message(message_pieces=[piece])) + (await sqlite_instance.add_message_to_memory_async(request=Message(message_pieces=[piece]))) -def test_add_message_pieces_to_memory_skips_not_in_memory_without_conversation_id( +async def test_add_message_pieces_to_memory_skips_not_in_memory_without_conversation_id( sqlite_instance: MemoryInterface, ): # not_in_memory pieces are filtered out before persistence, so a missing @@ -653,12 +669,12 @@ def test_add_message_pieces_to_memory_skips_not_in_memory_without_conversation_i ephemeral = MessagePiece(role="user", original_value="ephemeral", conversation_id=None) ephemeral.not_in_memory = True - sqlite_instance.add_message_pieces_to_memory(message_pieces=[ephemeral]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[ephemeral])) - assert sqlite_instance.get_message_pieces() == [] + assert (await sqlite_instance.get_message_pieces_async()) == [] -def test_add_conversation_to_memory_records_target_for_plain_message_writes(sqlite_instance: MemoryInterface): +async def test_add_conversation_to_memory_records_target_for_plain_message_writes(sqlite_instance: MemoryInterface): # Registering a conversation records its target once; subsequent message writes # do not take a target, yet target-filtered reads still find the messages. target_id = ComponentIdentifier( @@ -667,18 +683,22 @@ def test_add_conversation_to_memory_records_target_for_plain_message_writes(sqli params={"endpoint": "https://api.openai.com", "model_name": "gpt-4"}, ) conversation_id = "conv-registered" - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target_id) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target_id) + ) ) - sqlite_instance.add_message_pieces_to_memory( - message_pieces=[MessagePiece(role="user", original_value="hi", conversation_id=conversation_id)] + ( + await sqlite_instance.add_message_pieces_to_memory_async( + message_pieces=[MessagePiece(role="user", original_value="hi", conversation_id=conversation_id)] + ) ) metadata = sqlite_instance._get_conversation(conversation_id=conversation_id) assert metadata is not None assert metadata.target_identifier.hash == target_id.hash - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.TARGET, @@ -692,20 +712,22 @@ def test_add_conversation_to_memory_records_target_for_plain_message_writes(sqli assert results[0].conversation_id == conversation_id -def test_message_writes_without_registration_create_no_conversation_row(sqlite_instance: MemoryInterface): +async def test_message_writes_without_registration_create_no_conversation_row(sqlite_instance: MemoryInterface): # Message writes no longer touch the Conversations table; conversation metadata # exists only when a conversation is explicitly registered. conversation_id = "conv-unregistered" - sqlite_instance.add_message_pieces_to_memory( - message_pieces=[MessagePiece(role="user", original_value="hi", conversation_id=conversation_id)] + ( + await sqlite_instance.add_message_pieces_to_memory_async( + message_pieces=[MessagePiece(role="user", original_value="hi", conversation_id=conversation_id)] + ) ) assert sqlite_instance._get_conversation(conversation_id=conversation_id) is None # The messages themselves still persist. - assert len(sqlite_instance.get_message_pieces(conversation_id=conversation_id)) == 1 + assert len(await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id)) == 1 -def test_add_conversation_to_memory_same_target_reregister_is_noop(sqlite_instance: MemoryInterface): +async def test_add_conversation_to_memory_same_target_reregister_is_noop(sqlite_instance: MemoryInterface): # A conversation is held with exactly one target. Re-registering the same # conversation with the same target is idempotent (no error, no change) so that # per-turn registration during a multi-turn conversation is safe. @@ -713,11 +735,15 @@ def test_add_conversation_to_memory_same_target_reregister_is_noop(sqlite_instan target = ComponentIdentifier( class_name="OpenAIChatTarget", class_module="pyrit.prompt_target", params={"endpoint": "a"} ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target) + ) ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target) + ) ) metadata = sqlite_instance._get_conversation(conversation_id=conversation_id) @@ -725,7 +751,7 @@ def test_add_conversation_to_memory_same_target_reregister_is_noop(sqlite_instan assert metadata.target_identifier.hash == target.hash -def test_add_conversation_to_memory_different_target_reregister_raises(sqlite_instance: MemoryInterface): +async def test_add_conversation_to_memory_different_target_reregister_raises(sqlite_instance: MemoryInterface): # A conversation is held with exactly one target, so re-registering an existing # conversation_id with a different target is a conflict and must raise rather than # silently re-targeting the conversation. @@ -736,12 +762,16 @@ def test_add_conversation_to_memory_different_target_reregister_raises(sqlite_in target_b = ComponentIdentifier( class_name="OpenAIChatTarget", class_module="pyrit.prompt_target", params={"endpoint": "b"} ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target_a) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target_a) + ) ) with pytest.raises(ValueError, match="already registered with a different target"): - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target_b) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target_b) + ) ) # The originally recorded target is left untouched. @@ -750,7 +780,7 @@ def test_add_conversation_to_memory_different_target_reregister_raises(sqlite_in assert metadata.target_identifier.hash == target_a.hash -def test_target_identifier_dual_write_reconstruction_is_equivalent(sqlite_instance: MemoryInterface): +async def test_target_identifier_dual_write_reconstruction_is_equivalent(sqlite_instance: MemoryInterface): # Phase 1 dual-write invariant: reconstructing the target from the ConversationEntry # JSON column must be identical to reconstructing it from the deduped # TargetIdentifierEntry.identifier_json row, and the stored PK must match the @@ -764,8 +794,10 @@ def test_target_identifier_dual_write_reconstruction_is_equivalent(sqlite_instan params={"endpoint": "https://api.openai.com", "model_name": "gpt-4"}, ) conversation_id = "conv-dualwrite" - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target) + ) ) conv_entry = sqlite_instance._query_entries( @@ -788,7 +820,7 @@ def test_target_identifier_dual_write_reconstruction_is_equivalent(sqlite_instan assert id_entry.model_name == "gpt-4" -def test_target_identifier_row_is_deduped_across_conversations(sqlite_instance: MemoryInterface): +async def test_target_identifier_row_is_deduped_across_conversations(sqlite_instance: MemoryInterface): # The same target reused across conversations is content-addressed, so it is stored # once: two conversations with an identical target share a single TargetIdentifiers row. from pyrit.memory.memory_models import TargetIdentifierEntry @@ -797,15 +829,17 @@ def test_target_identifier_row_is_deduped_across_conversations(sqlite_instance: class_name="OpenAIChatTarget", class_module="pyrit.prompt_target", params={"endpoint": "shared"} ) for cid in ("conv-dedup-a", "conv-dedup-b"): - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=cid, target_identifier=target) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=cid, target_identifier=target) + ) ) rows = sqlite_instance._query_entries(TargetIdentifierEntry, conditions=TargetIdentifierEntry.hash == target.hash) assert len(rows) == 1 -def test_target_identifier_persists_inner_targets_and_edges(sqlite_instance: MemoryInterface): +async def test_target_identifier_persists_inner_targets_and_edges(sqlite_instance: MemoryInterface): # A multi-target's inner targets are persisted as their own content-addressed rows # and linked to the parent via ordered TargetIdentifierChildren edges. Promoted # scalar columns are surfaced on each row for querying. @@ -826,11 +860,15 @@ def test_target_identifier_persists_inner_targets_and_edges(sqlite_instance: Mem class_module="pyrit.prompt_target", children={"targets": [inner_a, inner_b]}, ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id="conv-inner-a", target_identifier=inner_a) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id="conv-inner-a", target_identifier=inner_a) + ) ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id="conv-multi", target_identifier=multi) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id="conv-multi", target_identifier=multi) + ) ) id_rows = sqlite_instance._query_entries(TargetIdentifierEntry) @@ -857,7 +895,7 @@ def test_insert_conversation_rolls_back_and_reraises_on_db_error(sqlite_instance session = MagicMock() session.get.side_effect = SQLAlchemyError("boom") - with patch.object(sqlite_instance, "get_session", return_value=session): + with patch.object(sqlite_instance, "_get_session", return_value=session): with pytest.raises(SQLAlchemyError, match="boom"): sqlite_instance._insert_conversation(conversation=Conversation(conversation_id="conv-fail")) @@ -865,7 +903,7 @@ def test_insert_conversation_rolls_back_and_reraises_on_db_error(sqlite_instance session.commit.assert_not_called() -def test_add_message_pieces_to_memory_updates_sequence( +async def test_add_message_pieces_to_memory_updates_sequence( sqlite_instance: MemoryInterface, sample_conversations: Sequence[MessagePiece] ): for conversation in sample_conversations: @@ -873,8 +911,8 @@ def test_add_message_pieces_to_memory_updates_sequence( conversation.role = sample_conversations[0].role conversation.sequence = 17 - with patch("pyrit.memory.sqlite_memory.SQLiteMemory.add_message_pieces_to_memory") as mock_add: - sqlite_instance.add_message_to_memory(request=Message(message_pieces=sample_conversations)) + with patch.object(sqlite_instance, "_execute_add_message_pieces_to_memory") as mock_add: + (await sqlite_instance.add_message_to_memory_async(request=Message(message_pieces=sample_conversations))) assert mock_add.called args, kwargs = mock_add.call_args @@ -883,7 +921,7 @@ def test_add_message_pieces_to_memory_updates_sequence( assert kwargs["message_pieces"][2].sequence == 0, "Sequence should be reset to 0" -def test_add_message_pieces_to_memory_updates_sequence_with_prev_conversation( +async def test_add_message_pieces_to_memory_updates_sequence_with_prev_conversation( sqlite_instance: MemoryInterface, sample_conversations: Sequence[MessagePiece] ): for conversation in sample_conversations: @@ -892,10 +930,10 @@ def test_add_message_pieces_to_memory_updates_sequence_with_prev_conversation( conversation.sequence = 17 # insert one of these into memory - sqlite_instance.add_message_to_memory(request=Message(message_pieces=sample_conversations)) + (await sqlite_instance.add_message_to_memory_async(request=Message(message_pieces=sample_conversations))) - with patch("pyrit.memory.sqlite_memory.SQLiteMemory.add_message_pieces_to_memory") as mock_add: - sqlite_instance.add_message_to_memory(request=Message(message_pieces=sample_conversations)) + with patch.object(sqlite_instance, "_execute_add_message_pieces_to_memory") as mock_add: + (await sqlite_instance.add_message_to_memory_async(request=Message(message_pieces=sample_conversations))) assert mock_add.called args, kwargs = mock_add.call_args @@ -904,7 +942,7 @@ def test_add_message_pieces_to_memory_updates_sequence_with_prev_conversation( assert kwargs["message_pieces"][2].sequence == 1 -def test_insert_prompt_memories_inserts_embedding( +async def test_insert_prompt_memories_inserts_embedding( sqlite_instance: MemoryInterface, sample_conversations: Sequence[MessagePiece] ): request = Message(message_pieces=[sample_conversations[0]]) @@ -914,16 +952,16 @@ def test_insert_prompt_memories_inserts_embedding( sqlite_instance.enable_embedding(embedding_model=embedding_mock) with ( - patch("pyrit.memory.sqlite_memory.SQLiteMemory.add_message_pieces_to_memory"), + patch.object(sqlite_instance, "_execute_add_message_pieces_to_memory"), patch("pyrit.memory.sqlite_memory.SQLiteMemory._add_embeddings_to_memory") as mock_embedding, ): - sqlite_instance.add_message_to_memory(request=request) + (await sqlite_instance.add_message_to_memory_async(request=request)) assert mock_embedding.called assert embedding_mock.generate_text_embedding.called -def test_insert_prompt_memories_not_inserts_embedding( +async def test_insert_prompt_memories_not_inserts_embedding( sqlite_instance: MemoryInterface, sample_conversations: Sequence[MessagePiece] ): request = Message(message_pieces=[sample_conversations[0]]) @@ -934,15 +972,15 @@ def test_insert_prompt_memories_not_inserts_embedding( sqlite_instance.disable_embedding() with ( - patch("pyrit.memory.sqlite_memory.SQLiteMemory.add_message_pieces_to_memory"), + patch.object(sqlite_instance, "_execute_add_message_pieces_to_memory"), patch("pyrit.memory.sqlite_memory.SQLiteMemory._add_embeddings_to_memory") as mock_embedding, ): - sqlite_instance.add_message_to_memory(request=request) + (await sqlite_instance.add_message_to_memory_async(request=request)) assert mock_embedding.assert_not_called -def test_get_message_pieces_metadata(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_metadata(sqlite_instance: MemoryInterface): metadata: dict[str, str | int] = {"key1": "value1", "key2": "value2"} entries = [ PromptMemoryEntry( @@ -972,7 +1010,7 @@ def test_get_message_pieces_metadata(sqlite_instance: MemoryInterface): sqlite_instance._insert_entries(entries=entries) - retrieved_entries = sqlite_instance.get_message_pieces(prompt_metadata={"key2": "value2"}) + retrieved_entries = await sqlite_instance.get_message_pieces_async(prompt_metadata={"key2": "value2"}) assert len(retrieved_entries) == 2 # Two entries should have the specific memory labels for retrieved_entry in retrieved_entries: @@ -983,7 +1021,7 @@ def test_get_message_pieces_metadata(sqlite_instance: MemoryInterface): "key, value", [("finish_reason", "content_filter"), ("status", "incomplete"), ("incomplete_reason", "max_output_tokens")], ) -def test_get_message_pieces_captured_response_metadata(sqlite_instance: MemoryInterface, key: str, value: str): +async def test_get_message_pieces_captured_response_metadata(sqlite_instance: MemoryInterface, key: str, value: str): """The response metadata captured by the targets must be queryable after a round trip.""" matching = MessagePiece( conversation_id=str(uuid4()), @@ -999,13 +1037,13 @@ def test_get_message_pieces_captured_response_metadata(sqlite_instance: MemoryIn set_response_metadata(pieces=[other], **{key: "something_else"}) sqlite_instance._insert_entries(entries=[PromptMemoryEntry(entry=matching), PromptMemoryEntry(entry=other)]) - retrieved = sqlite_instance.get_message_pieces(prompt_metadata={key: value}) + retrieved = await sqlite_instance.get_message_pieces_async(prompt_metadata={key: value}) assert len(retrieved) == 1 assert retrieved[0].prompt_metadata[key] == value -def test_get_message_pieces_id(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_id(sqlite_instance: MemoryInterface): entries = [ PromptMemoryEntry( entry=MessagePiece( @@ -1037,14 +1075,14 @@ def test_get_message_pieces_id(sqlite_instance: MemoryInterface): sqlite_instance._insert_entries(entries=entries) - retrieved_entries = sqlite_instance.get_message_pieces(prompt_ids=[id_1, id_2]) + retrieved_entries = await sqlite_instance.get_message_pieces_async(prompt_ids=[id_1, id_2]) assert len(retrieved_entries) == 2 assert_original_value_in_list("Hello 1", retrieved_entries) assert_original_value_in_list("Hello 2", retrieved_entries) -def test_get_message_pieces_sent_after(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_sent_after(sqlite_instance: MemoryInterface): entries = [ PromptMemoryEntry( entry=MessagePiece( @@ -1074,13 +1112,13 @@ def test_get_message_pieces_sent_after(sqlite_instance: MemoryInterface): sqlite_instance._insert_entries(entries=entries) - retrieved_entries = sqlite_instance.get_message_pieces(sent_after=datetime(2024, 1, 1, tzinfo=UTC)) + retrieved_entries = await sqlite_instance.get_message_pieces_async(sent_after=datetime(2024, 1, 1, tzinfo=UTC)) assert len(retrieved_entries) == 1 assert "Hello 3" in retrieved_entries[0].original_value -def test_get_message_pieces_sent_before(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_sent_before(sqlite_instance: MemoryInterface): entries = [ PromptMemoryEntry( entry=MessagePiece( @@ -1110,14 +1148,14 @@ def test_get_message_pieces_sent_before(sqlite_instance: MemoryInterface): sqlite_instance._insert_entries(entries=entries) - retrieved_entries = sqlite_instance.get_message_pieces(sent_before=datetime(2024, 1, 1, tzinfo=UTC)) + retrieved_entries = await sqlite_instance.get_message_pieces_async(sent_before=datetime(2024, 1, 1, tzinfo=UTC)) assert len(retrieved_entries) == 2 assert_original_value_in_list("Hello 1", retrieved_entries) assert_original_value_in_list("Hello 2", retrieved_entries) -def test_get_message_pieces_by_value(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_by_value(sqlite_instance: MemoryInterface): entries = [ PromptMemoryEntry( entry=MessagePiece( @@ -1143,14 +1181,14 @@ def test_get_message_pieces_by_value(sqlite_instance: MemoryInterface): ] sqlite_instance._insert_entries(entries=entries) - retrieved_entries = sqlite_instance.get_message_pieces(converted_values=["Hello 2", "Hello 3"]) + retrieved_entries = await sqlite_instance.get_message_pieces_async(converted_values=["Hello 2", "Hello 3"]) assert len(retrieved_entries) == 2 assert_original_value_in_list("Hello 2", retrieved_entries) assert_original_value_in_list("Hello 3", retrieved_entries) -def test_get_message_pieces_by_hash(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_by_hash(sqlite_instance: MemoryInterface): entries = [ MessagePiece( conversation_id=str(uuid4()), @@ -1172,15 +1210,15 @@ def test_get_message_pieces_by_hash(sqlite_instance: MemoryInterface): entries[0].converted_value_sha256 = "hash1" entries[1].converted_value_sha256 = "hash1" - sqlite_instance.add_message_pieces_to_memory(message_pieces=entries) - retrieved_entries = sqlite_instance.get_message_pieces(converted_value_sha256=["hash1"]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=entries)) + retrieved_entries = await sqlite_instance.get_message_pieces_async(converted_value_sha256=["hash1"]) assert len(retrieved_entries) == 2 assert_original_value_in_list("Hello 1", retrieved_entries) assert_original_value_in_list("Hello 2", retrieved_entries) -def test_get_message_pieces_sorts( +async def test_get_message_pieces_sorts( sqlite_instance: MemoryInterface, sample_conversations: MutableSequence[MessagePiece] ): conversation_id = sample_conversations[0].conversation_id @@ -1194,9 +1232,9 @@ def test_get_message_pieces_sorts( ) ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=sample_conversations) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=sample_conversations)) - response = sqlite_instance.get_message_pieces() + response = await sqlite_instance.get_message_pieces_async() current_value = response[0].conversation_id for obj in response[1:]: @@ -1207,7 +1245,7 @@ def test_get_message_pieces_sorts( raise AssertionError("Conversation IDs are not grouped together") -def test_message_piece_scores_duplicate_piece(sqlite_instance: MemoryInterface): +async def test_message_piece_scores_duplicate_piece(sqlite_instance: MemoryInterface): """Scores for duplicated pieces are returned via get_prompt_scores.""" original_id = uuid4() duplicate_id = uuid4() @@ -1228,7 +1266,7 @@ def test_message_piece_scores_duplicate_piece(sqlite_instance: MemoryInterface): ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) score = Score( score_value=str(0.8), @@ -1240,12 +1278,12 @@ def test_message_piece_scores_duplicate_piece(sqlite_instance: MemoryInterface): message_piece_id=original_id, scorer_class_identifier=_test_scorer_id(), ) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) # Both the original and the duplicate piece resolve back to the same score # via get_prompt_scores, which queries ScoreEntry by original_prompt_id. - scores_for_original = sqlite_instance.get_prompt_scores(prompt_ids=[str(original_id)]) - scores_for_duplicate = sqlite_instance.get_prompt_scores(prompt_ids=[str(duplicate_id)]) + scores_for_original = await sqlite_instance.get_prompt_scores_async(prompt_ids=[str(original_id)]) + scores_for_duplicate = await sqlite_instance.get_prompt_scores_async(prompt_ids=[str(duplicate_id)]) assert len(scores_for_original) == 1 assert scores_for_original[0].score_value == "0.8" @@ -1270,8 +1308,8 @@ async def test_message_piece_hash_stored_and_retrieved(sqlite_instance: MemoryIn for entry in entries: await set_message_piece_sha256_async(entry) - sqlite_instance.add_message_pieces_to_memory(message_pieces=entries) - retrieved_entries = sqlite_instance.get_message_pieces() + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=entries)) + retrieved_entries = await sqlite_instance.get_message_pieces_async() assert len(retrieved_entries) == 2 for prompt in retrieved_entries: @@ -1294,12 +1332,12 @@ async def test_seed_prompt_hash_stored_and_retrieved(sqlite_instance: MemoryInte # Retrieve and verify hash assert seed_prompt.value_sha256 is not None, "SHA256 should not be None" - retrieved_prompts = sqlite_instance.get_seeds(value_sha256=[seed_prompt.value_sha256]) + retrieved_prompts = await sqlite_instance.get_seeds_async(value_sha256=[seed_prompt.value_sha256]) assert len(retrieved_prompts) == 1 assert retrieved_prompts[0].value_sha256 == seed_prompt.value_sha256 -def test_get_request_from_response_success(sqlite_instance: MemoryInterface): +async def test_get_request_from_response_success(sqlite_instance: MemoryInterface): """Test that get_request_from_response successfully retrieves the request that produced a response.""" conversation_id = str(uuid4()) @@ -1320,14 +1358,14 @@ def test_get_request_from_response_success(sqlite_instance: MemoryInterface): sequence=1, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) # Get the conversation and extract the response - conversation = sqlite_instance.get_conversation_messages(conversation_id=conversation_id) + conversation = await sqlite_instance.get_conversation_messages_async(conversation_id=conversation_id) response = conversation[1] # Retrieve the request that produced this response - request = sqlite_instance.get_request_from_response(response=response) + request = await sqlite_instance.get_request_from_response_async(response=response) assert request.api_role == "user" assert request.sequence == 0 @@ -1336,7 +1374,9 @@ def test_get_request_from_response_success(sqlite_instance: MemoryInterface): @pytest.mark.parametrize("bad_conversation_id", ["", None]) -def test_get_conversation_messages_rejects_falsy_conversation_id(sqlite_instance: MemoryInterface, bad_conversation_id): +async def test_get_conversation_messages_rejects_falsy_conversation_id( + sqlite_instance: MemoryInterface, bad_conversation_id +): """A falsy conversation_id must raise instead of skipping the filter and returning every conversation.""" pieces = [ MessagePiece( @@ -1354,13 +1394,13 @@ def test_get_conversation_messages_rejects_falsy_conversation_id(sqlite_instance sequence=0, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) with pytest.raises(ValueError, match="requires a non-empty conversation_id"): - sqlite_instance.get_conversation_messages(conversation_id=bad_conversation_id) + (await sqlite_instance.get_conversation_messages_async(conversation_id=bad_conversation_id)) -def test_get_request_from_response_multi_turn_conversation(sqlite_instance: MemoryInterface): +async def test_get_request_from_response_multi_turn_conversation(sqlite_instance: MemoryInterface): """Test get_request_from_response in a multi-turn conversation.""" conversation_id = str(uuid4()) @@ -1395,20 +1435,20 @@ def test_get_request_from_response_multi_turn_conversation(sqlite_instance: Memo sequence=3, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) - conversation = sqlite_instance.get_conversation_messages(conversation_id=conversation_id) + conversation = await sqlite_instance.get_conversation_messages_async(conversation_id=conversation_id) # Test getting request for the second response second_response = conversation[3] - second_request = sqlite_instance.get_request_from_response(response=second_response) + second_request = await sqlite_instance.get_request_from_response_async(response=second_response) assert second_request.api_role == "user" assert second_request.sequence == 2 assert second_request.get_value() == "Second question" -def test_get_request_from_response_raises_error_for_non_assistant_role(sqlite_instance: MemoryInterface): +async def test_get_request_from_response_raises_error_for_non_assistant_role(sqlite_instance: MemoryInterface): """Test that get_request_from_response raises ValueError when given a non-assistant role.""" conversation_id = str(uuid4()) @@ -1421,16 +1461,16 @@ def test_get_request_from_response_raises_error_for_non_assistant_role(sqlite_in sequence=0, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) - conversation = sqlite_instance.get_conversation_messages(conversation_id=conversation_id) + conversation = await sqlite_instance.get_conversation_messages_async(conversation_id=conversation_id) user_message = conversation[0] with pytest.raises(ValueError, match="The provided request is not a response \\(role must be 'assistant'\\)."): - sqlite_instance.get_request_from_response(response=user_message) + (await sqlite_instance.get_request_from_response_async(response=user_message)) -def test_get_request_from_response_raises_error_for_sequence_less_than_one(sqlite_instance: MemoryInterface): +async def test_get_request_from_response_raises_error_for_sequence_less_than_one(sqlite_instance: MemoryInterface): """Test that get_request_from_response raises ValueError when sequence < 1.""" conversation_id = str(uuid4()) @@ -1444,34 +1484,36 @@ def test_get_request_from_response_raises_error_for_sequence_less_than_one(sqlit sequence=0, ), ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) - conversation = sqlite_instance.get_conversation_messages(conversation_id=conversation_id) + conversation = await sqlite_instance.get_conversation_messages_async(conversation_id=conversation_id) response_without_request = conversation[0] with pytest.raises(ValueError, match="The provided request does not have a preceding request \\(sequence < 1\\)."): - sqlite_instance.get_request_from_response(response=response_without_request) + (await sqlite_instance.get_request_from_response_async(response=response_without_request)) -def test_get_message_pieces_by_attack_identifier_filter(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_by_attack_identifier_filter(sqlite_instance: MemoryInterface): attack1 = PromptSendingAttack(objective_target=get_mock_target()) # IdentifierType.ATTACK is no longer stamped on message pieces, so the piece-level # identifier filter rejects it. Attack filtering now goes through get_attack_results. with pytest.raises(ValueError, match="does not support identifier type"): - sqlite_instance.get_message_pieces( - identifier_filters=[ - IdentifierFilter( - identifier_type=IdentifierType.ATTACK, - property_path="$.hash", - value=attack1.get_identifier().hash, - partial_match=False, - ) - ], + ( + await sqlite_instance.get_message_pieces_async( + identifier_filters=[ + IdentifierFilter( + identifier_type=IdentifierType.ATTACK, + property_path="$.hash", + value=attack1.get_identifier().hash, + partial_match=False, + ) + ], + ) ) -def test_get_message_pieces_by_target_identifier_filter(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_by_target_identifier_filter(sqlite_instance: MemoryInterface): target_id_1 = ComponentIdentifier( class_name="OpenAIChatTarget", class_module="pyrit.prompt_target", @@ -1483,33 +1525,41 @@ def test_get_message_pieces_by_target_identifier_filter(sqlite_instance: MemoryI params={"endpoint": "https://azure.com", "model_name": "gpt-3.5"}, ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id="conv-openai", target_identifier=target_id_1) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id="conv-openai", target_identifier=target_id_1) + ) ) - sqlite_instance.add_message_pieces_to_memory( - message_pieces=[ - MessagePiece( - role="user", - original_value="Hello OpenAI", - conversation_id="conv-openai", - ), - ], + ( + await sqlite_instance.add_message_pieces_to_memory_async( + message_pieces=[ + MessagePiece( + role="user", + original_value="Hello OpenAI", + conversation_id="conv-openai", + ), + ], + ) ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id="conv-azure", target_identifier=target_id_2) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id="conv-azure", target_identifier=target_id_2) + ) ) - sqlite_instance.add_message_pieces_to_memory( - message_pieces=[ - MessagePiece( - role="user", - original_value="Hello Azure", - conversation_id="conv-azure", - ), - ], + ( + await sqlite_instance.add_message_pieces_to_memory_async( + message_pieces=[ + MessagePiece( + role="user", + original_value="Hello Azure", + conversation_id="conv-azure", + ), + ], + ) ) # Filter by target hash - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.TARGET, @@ -1523,7 +1573,7 @@ def test_get_message_pieces_by_target_identifier_filter(sqlite_instance: MemoryI assert results[0].original_value == "Hello OpenAI" # Filter by endpoint partial match - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.TARGET, @@ -1537,7 +1587,7 @@ def test_get_message_pieces_by_target_identifier_filter(sqlite_instance: MemoryI assert results[0].original_value == "Hello OpenAI" # No match - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.TARGET, @@ -1550,7 +1600,9 @@ def test_get_message_pieces_by_target_identifier_filter(sqlite_instance: MemoryI assert len(results) == 0 -def test_get_message_pieces_by_converter_identifier_filter_with_array_element_path(sqlite_instance: MemoryInterface): +async def test_get_message_pieces_by_converter_identifier_filter_with_array_element_path( + sqlite_instance: MemoryInterface, +): converter_a = ComponentIdentifier( class_name="Base64Converter", class_module="pyrit.converter", @@ -1589,7 +1641,7 @@ def test_get_message_pieces_by_converter_identifier_filter_with_array_element_pa sqlite_instance._insert_entries(entries=entries) # Filter by converter class_name using array_element_path (array element matching) - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.CONVERTER, @@ -1604,7 +1656,7 @@ def test_get_message_pieces_by_converter_identifier_filter_with_array_element_pa assert original_values == {"With Base64", "With both converters"} # Filter by ROT13Converter — only the entry with both converters - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.CONVERTER, @@ -1618,7 +1670,7 @@ def test_get_message_pieces_by_converter_identifier_filter_with_array_element_pa assert results[0].original_value == "With both converters" # No match - results = sqlite_instance.get_message_pieces( + results = await sqlite_instance.get_message_pieces_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.CONVERTER, diff --git a/tests/unit/memory/memory_interface/test_interface_remove_seeds.py b/tests/unit/memory/memory_interface/test_interface_remove_seeds.py index 03b2a00f52..496ab74da5 100644 --- a/tests/unit/memory/memory_interface/test_interface_remove_seeds.py +++ b/tests/unit/memory/memory_interface/test_interface_remove_seeds.py @@ -21,10 +21,10 @@ async def test_remove_seeds_by_dataset_name(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(dataset_name="to_delete") + removed = await sqlite_instance.remove_seeds_from_memory_async(dataset_name="to_delete") assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].dataset_name == "to_keep" @@ -37,10 +37,10 @@ async def test_remove_seeds_by_dataset_name_pattern(sqlite_instance: MemoryInter ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(dataset_name_pattern="harm%") + removed = await sqlite_instance.remove_seeds_from_memory_async(dataset_name_pattern="harm%") assert removed == 2 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].dataset_name == "safe_dataset" @@ -52,10 +52,10 @@ async def test_remove_seeds_by_added_by(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts) - removed = sqlite_instance.remove_seeds_from_memory(added_by="user1") + removed = await sqlite_instance.remove_seeds_from_memory_async(added_by="user1") assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].added_by == "user2" @@ -67,10 +67,10 @@ async def test_remove_seeds_by_source(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(source="internal") + removed = await sqlite_instance.remove_seeds_from_memory_async(source="internal") assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].source == "external" @@ -82,10 +82,10 @@ async def test_remove_seeds_by_harm_categories(sqlite_instance: MemoryInterface) ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(harm_categories=["violence"]) + removed = await sqlite_instance.remove_seeds_from_memory_async(harm_categories=["violence"]) assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].harm_categories == ["fraud"] @@ -97,10 +97,10 @@ async def test_remove_seeds_by_authors(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(authors=["author1"]) + removed = await sqlite_instance.remove_seeds_from_memory_async(authors=["author1"]) assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].authors == ["author2"] @@ -112,10 +112,10 @@ async def test_remove_seeds_by_groups(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(groups=["group1"]) + removed = await sqlite_instance.remove_seeds_from_memory_async(groups=["group1"]) assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].groups == ["group2"] @@ -127,10 +127,10 @@ async def test_remove_seeds_by_parameters(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(parameters=["param1"]) + removed = await sqlite_instance.remove_seeds_from_memory_async(parameters=["param1"]) assert removed == 1 - assert len(sqlite_instance.get_seeds(parameters=["param1"])) == 0 - assert len(sqlite_instance.get_seeds(parameters=["param2"])) == 1 + assert len(await sqlite_instance.get_seeds_async(parameters=["param1"])) == 0 + assert len(await sqlite_instance.get_seeds_async(parameters=["param2"])) == 1 async def test_remove_seeds_by_metadata(sqlite_instance: MemoryInterface): @@ -140,10 +140,10 @@ async def test_remove_seeds_by_metadata(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(metadata={"key1": "value1"}) + removed = await sqlite_instance.remove_seeds_from_memory_async(metadata={"key1": "value1"}) assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].value == "prompt2" @@ -155,9 +155,9 @@ async def test_remove_seeds_by_data_type(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - assert sqlite_instance.remove_seeds_from_memory(data_types=["image_path"]) == 0 - assert sqlite_instance.remove_seeds_from_memory(data_types=["text"]) == 2 - assert len(sqlite_instance.get_seeds()) == 0 + assert (await sqlite_instance.remove_seeds_from_memory_async(data_types=["image_path"])) == 0 + assert (await sqlite_instance.remove_seeds_from_memory_async(data_types=["text"])) == 2 + assert len(await sqlite_instance.get_seeds_async()) == 0 async def test_remove_seeds_by_seed_type(sqlite_instance: MemoryInterface): @@ -165,10 +165,10 @@ async def test_remove_seeds_by_seed_type(sqlite_instance: MemoryInterface): objective = SeedObjective(value="an objective") await sqlite_instance.add_seeds_to_memory_async(seeds=[prompt, objective], added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(seed_type="objective") + removed = await sqlite_instance.remove_seeds_from_memory_async(seed_type="objective") assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].seed_type == "prompt" @@ -179,12 +179,12 @@ async def test_remove_seeds_by_value_sha256(sqlite_instance: MemoryInterface): SeedPrompt(value="prompt2", dataset_name="ds", data_type="text"), ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - target = next(seed for seed in sqlite_instance.get_seeds() if seed.value == "prompt1") + target = next(seed for seed in (await sqlite_instance.get_seeds_async()) if seed.value == "prompt1") - removed = sqlite_instance.remove_seeds_from_memory(value_sha256=[target.value_sha256]) + removed = await sqlite_instance.remove_seeds_from_memory_async(value_sha256=[target.value_sha256]) assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].value == "prompt2" @@ -192,11 +192,11 @@ async def test_remove_seeds_by_value_sha256(sqlite_instance: MemoryInterface): async def test_remove_seeds_by_prompt_group_ids(sqlite_instance: MemoryInterface): group = SeedGroup(seeds=[SeedPrompt(value="grouped", dataset_name="ds", data_type="text", sequence=0)]) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group], added_by="test") - group_id = sqlite_instance.get_seeds()[0].prompt_group_id + group_id = (await sqlite_instance.get_seeds_async())[0].prompt_group_id - removed = sqlite_instance.remove_seeds_from_memory(prompt_group_ids=[group_id]) + removed = await sqlite_instance.remove_seeds_from_memory_async(prompt_group_ids=[group_id]) assert removed == 1 - assert len(sqlite_instance.get_seeds()) == 0 + assert len(await sqlite_instance.get_seeds_async()) == 0 async def test_remove_seeds_by_value_substring_is_broad(sqlite_instance: MemoryInterface): @@ -208,10 +208,10 @@ async def test_remove_seeds_by_value_substring_is_broad(sqlite_instance: MemoryI await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") # exact=False opts into substring matching, which is broad: "the" matches both values that contain it. - removed = sqlite_instance.remove_seeds_from_memory(value="the", exact=False) + removed = await sqlite_instance.remove_seeds_from_memory_async(value="the", exact=False) assert removed == 2 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].value == "a cat" @@ -224,11 +224,11 @@ async def test_remove_seeds_by_value_defaults_to_exact(sqlite_instance: MemoryIn await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") # The remove methods default to exact matching, so a substring like "the" removes nothing. - assert sqlite_instance.remove_seeds_from_memory(value="the") == 0 + assert (await sqlite_instance.remove_seeds_from_memory_async(value="the")) == 0 # The full value matches exactly one seed. - assert sqlite_instance.remove_seeds_from_memory(value="the quick fox") == 1 + assert (await sqlite_instance.remove_seeds_from_memory_async(value="the quick fox")) == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].value == "the lazy dog" @@ -241,10 +241,10 @@ async def test_remove_seeds_by_value_exact_is_narrow(sqlite_instance: MemoryInte await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") # exact=True only removes the fully-matching value, not substring siblings. - removed = sqlite_instance.remove_seeds_from_memory(value="the quick fox", exact=True) + removed = await sqlite_instance.remove_seeds_from_memory_async(value="the quick fox", exact=True) assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].value == "the lazy dog" @@ -306,10 +306,10 @@ async def test_remove_seeds_multi_filter_narrowing(sqlite_instance: MemoryInterf ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts) - removed = sqlite_instance.remove_seeds_from_memory(dataset_name="ds1", added_by="user1") + removed = await sqlite_instance.remove_seeds_from_memory_async(dataset_name="ds1", added_by="user1") assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 2 @@ -320,7 +320,7 @@ async def test_remove_seeds_no_filter_raises_value_error(sqlite_instance: Memory await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") with pytest.raises(ValueError, match="At least one filter"): - sqlite_instance.remove_seeds_from_memory() + (await sqlite_instance.remove_seeds_from_memory_async()) async def test_remove_seeds_returns_zero_when_no_match(sqlite_instance: MemoryInterface): @@ -329,10 +329,10 @@ async def test_remove_seeds_returns_zero_when_no_match(sqlite_instance: MemoryIn ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seeds_from_memory(dataset_name="nonexistent") + removed = await sqlite_instance.remove_seeds_from_memory_async(dataset_name="nonexistent") assert removed == 0 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 @@ -344,10 +344,10 @@ async def test_remove_seeds_rolls_back_on_error(sqlite_instance: MemoryInterface with patch("sqlalchemy.orm.session.Session.commit", side_effect=SQLAlchemyError("boom")): with pytest.raises(SQLAlchemyError): - sqlite_instance.remove_seeds_from_memory(dataset_name="ds1") + (await sqlite_instance.remove_seeds_from_memory_async(dataset_name="ds1")) # The failed deletion is rolled back, so the seed is still present. - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 # ========================================================================= @@ -366,10 +366,10 @@ async def test_remove_seed_groups_removes_entire_group(sqlite_instance: MemoryIn await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group, standalone], added_by="test") # Filter matches only one seed in the group, but the whole group is removed. - removed = sqlite_instance.remove_seed_groups_from_memory(value="match_me", exact=True) + removed = await sqlite_instance.remove_seed_groups_from_memory_async(value="match_me", exact=True) assert removed == 2 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].value == "keep" @@ -401,9 +401,9 @@ async def test_remove_seed_groups_spanning_multiple_datasets(sqlite_instance: Me await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group], added_by="test") # Matching a seed in one dataset removes the whole group, including the seed in the other dataset. - removed = sqlite_instance.remove_seed_groups_from_memory(dataset_name="ds_a") + removed = await sqlite_instance.remove_seed_groups_from_memory_async(dataset_name="ds_a") assert removed == 2 - assert len(sqlite_instance.get_seeds()) == 0 + assert len(await sqlite_instance.get_seeds_async()) == 0 async def test_remove_seed_groups_preserves_non_matching_groups(sqlite_instance: MemoryInterface): @@ -413,10 +413,10 @@ async def test_remove_seed_groups_preserves_non_matching_groups(sqlite_instance: prompt_groups=[group_to_remove, group_to_keep], added_by="test" ) - removed = sqlite_instance.remove_seed_groups_from_memory(dataset_name="remove") + removed = await sqlite_instance.remove_seed_groups_from_memory_async(dataset_name="remove") assert removed == 1 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 assert remaining[0].value == "g2" @@ -428,9 +428,9 @@ async def test_remove_seed_groups_skips_ungrouped_seeds(sqlite_instance: MemoryI ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - removed = sqlite_instance.remove_seed_groups_from_memory(dataset_name="ds1") + removed = await sqlite_instance.remove_seed_groups_from_memory_async(dataset_name="ds1") assert removed == 0 - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 async def test_remove_seed_groups_no_filter_raises_value_error(sqlite_instance: MemoryInterface): @@ -438,17 +438,17 @@ async def test_remove_seed_groups_no_filter_raises_value_error(sqlite_instance: await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group], added_by="test") with pytest.raises(ValueError, match="At least one filter"): - sqlite_instance.remove_seed_groups_from_memory() + (await sqlite_instance.remove_seed_groups_from_memory_async()) async def test_remove_seed_groups_returns_zero_when_no_match(sqlite_instance: MemoryInterface): group = SeedGroup(seeds=[SeedPrompt(value="prompt1", dataset_name="ds1", data_type="text", sequence=0)]) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group], added_by="test") - removed = sqlite_instance.remove_seed_groups_from_memory(dataset_name="nonexistent") + removed = await sqlite_instance.remove_seed_groups_from_memory_async(dataset_name="nonexistent") assert removed == 0 - remaining = sqlite_instance.get_seeds() + remaining = await sqlite_instance.get_seeds_async() assert len(remaining) == 1 @@ -458,7 +458,7 @@ async def test_remove_seed_groups_rolls_back_on_error(sqlite_instance: MemoryInt with patch("sqlalchemy.orm.session.Session.commit", side_effect=SQLAlchemyError("boom")): with pytest.raises(SQLAlchemyError): - sqlite_instance.remove_seed_groups_from_memory(dataset_name="ds1") + (await sqlite_instance.remove_seed_groups_from_memory_async(dataset_name="ds1")) # The failed deletion is rolled back, so the group is still present. - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 diff --git a/tests/unit/memory/memory_interface/test_interface_scenario_history.py b/tests/unit/memory/memory_interface/test_interface_scenario_history.py index 20d91886dc..95a12640f7 100644 --- a/tests/unit/memory/memory_interface/test_interface_scenario_history.py +++ b/tests/unit/memory/memory_interface/test_interface_scenario_history.py @@ -5,14 +5,13 @@ import json import uuid -from contextlib import closing from datetime import UTC, datetime, timedelta from typing import Any from unittest.mock import MagicMock, patch import pytest from sqlalchemy import and_, select, text -from unit.mocks import get_mock_target_identifier, make_scenario_result +from unit.mocks import get_mock_target_identifier, make_scenario_result, run_memory_session_async from pyrit.common.utils import to_sha256 from pyrit.memory import MemoryInterface, ScenarioHistoryKeysetCursor, SQLiteMemory @@ -107,7 +106,7 @@ def _make_scenario( ) -def test_history_pages_descending_equal_timestamps_by_id(sqlite_instance: MemoryInterface) -> None: +async def test_history_pages_descending_equal_timestamps_by_id(sqlite_instance: MemoryInterface) -> None: timestamp = datetime(2026, 8, 7, tzinfo=UTC) scenarios = [ _make_scenario( @@ -119,14 +118,14 @@ def test_history_pages_descending_equal_timestamps_by_id(sqlite_instance: Memory ) for value in (1, 2, 3) ] - sqlite_instance.add_scenario_results_to_memory(scenario_results=scenarios) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=scenarios)) entries = sqlite_instance._query_entries(ScenarioResultEntry) for entry in entries: entry.timestamp = timestamp sqlite_instance._update_entry(entry) - first_page, _, has_more = sqlite_instance.get_scenario_run_history_page(limit=2) - second_page, _, second_has_more = sqlite_instance.get_scenario_run_history_page( + first_page, _, has_more = await sqlite_instance.get_scenario_run_history_page_async(limit=2) + second_page, _, second_has_more = await sqlite_instance.get_scenario_run_history_page_async( cursor=ScenarioHistoryKeysetCursor( timestamp=first_page[-1].created_at, scenario_result_id=first_page[-1].scenario_result_id, @@ -140,7 +139,7 @@ def test_history_pages_descending_equal_timestamps_by_id(sqlite_instance: Memory assert second_has_more is False -def test_history_creation_order_is_stable_when_scenario_entry_is_rebuilt( +async def test_history_creation_order_is_stable_when_scenario_entry_is_rebuilt( sqlite_instance: MemoryInterface, ) -> None: first_created_at = datetime(2026, 8, 7, tzinfo=UTC) @@ -158,14 +157,14 @@ def test_history_creation_order_is_stable_when_scenario_entry_is_rebuilt( state=ScenarioRunState.COMPLETED, labels={}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[first, second]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[first, second])) - rebuilt_first = sqlite_instance.get_scenario_results(scenario_result_ids=[str(first.id)])[0] + rebuilt_first = (await sqlite_instance.get_scenario_results_async(scenario_result_ids=[str(first.id)]))[0] rebuilt_first.number_tries += 1 sqlite_instance._update_entry(ScenarioResultEntry(entry=rebuilt_first)) - first_page, _, has_more = sqlite_instance.get_scenario_run_history_page(limit=1) - second_page, _, second_has_more = sqlite_instance.get_scenario_run_history_page( + first_page, _, has_more = await sqlite_instance.get_scenario_run_history_page_async(limit=1) + second_page, _, second_has_more = await sqlite_instance.get_scenario_run_history_page_async( cursor=ScenarioHistoryKeysetCursor( timestamp=first_page[-1].created_at, scenario_result_id=first_page[-1].scenario_result_id, @@ -181,7 +180,7 @@ def test_history_creation_order_is_stable_when_scenario_entry_is_rebuilt( assert second_has_more is False -def test_history_filters_names_statuses_and_labels_without_hydration( +async def test_history_filters_names_statuses_and_labels_without_hydration( sqlite_instance: MemoryInterface, monkeypatch, ) -> None: @@ -201,11 +200,13 @@ def test_history_filters_names_statuses_and_labels_without_hydration( state=ScenarioRunState.COMPLETED, labels={"operator": "bob", "operation": "nightly", "team.name": "safety"}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[included, excluded]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[included, excluded])) started_at = timestamp + timedelta(seconds=30) - sqlite_instance.update_scenario_metadata_fields( - scenario_result_id=str(included.id), - fields={"started_at": started_at.isoformat()}, + ( + await sqlite_instance.update_scenario_metadata_fields_async( + scenario_result_id=str(included.id), + fields={"started_at": started_at.isoformat()}, + ) ) attacks = [ AttackResult( @@ -241,13 +242,13 @@ def test_history_filters_names_statuses_and_labels_without_hydration( }, ), ] - sqlite_instance.add_attack_results_to_memory(attack_results=attacks) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attacks)) monkeypatch.setattr( "pyrit.memory.memory_models.AttackResultEntry.get_attack_result", MagicMock(side_effect=AssertionError("history hydrated an AttackResult")), ) - rows, aggregates, has_more = sqlite_instance.get_scenario_run_history_page( + rows, aggregates, has_more = await sqlite_instance.get_scenario_run_history_page_async( scenario_names=["registered.scenario"], statuses=[ScenarioRunState.IN_PROGRESS.value], labels={ @@ -292,7 +293,7 @@ def test_history_filters_names_statuses_and_labels_without_hydration( assert has_more is False -def test_history_aggregate_uses_latest_attempt_outcome(sqlite_instance: MemoryInterface) -> None: +async def test_history_aggregate_uses_latest_attempt_outcome(sqlite_instance: MemoryInterface) -> None: """History uses the same latest-attempt semantics as scenario run details.""" timestamp = datetime(2026, 8, 7, tzinfo=UTC) scenario = _make_scenario( @@ -303,41 +304,43 @@ def test_history_aggregate_uses_latest_attempt_outcome(sqlite_instance: MemoryIn state=ScenarioRunState.COMPLETED, labels={}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario]) - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - AttackResult( - attack_result_id=str(uuid.UUID(int=19)), - conversation_id="conversation-19", - objective="objective", - outcome=AttackOutcome.SUCCESS, - execution_time_ms=1, - timestamp=timestamp, - attribution_parent_id=str(scenario.id), - attribution_data={ - "parent_collection": "attack", - "parent_eval_hash": "eval-1", - "seed_group_id": "seed-1", - }, - ), - AttackResult( - attack_result_id=str(uuid.UUID(int=20)), - conversation_id="conversation-20", - objective="objective", - outcome=AttackOutcome.ERROR, - execution_time_ms=1, - timestamp=timestamp + timedelta(seconds=1), - attribution_parent_id=str(scenario.id), - attribution_data={ - "parent_collection": "attack", - "parent_eval_hash": "eval-1", - "seed_group_id": "seed-1", - }, - ), - ] - ) - - _, aggregates, _ = sqlite_instance.get_scenario_run_history_page(limit=25) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario])) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + AttackResult( + attack_result_id=str(uuid.UUID(int=19)), + conversation_id="conversation-19", + objective="objective", + outcome=AttackOutcome.SUCCESS, + execution_time_ms=1, + timestamp=timestamp, + attribution_parent_id=str(scenario.id), + attribution_data={ + "parent_collection": "attack", + "parent_eval_hash": "eval-1", + "seed_group_id": "seed-1", + }, + ), + AttackResult( + attack_result_id=str(uuid.UUID(int=20)), + conversation_id="conversation-20", + objective="objective", + outcome=AttackOutcome.ERROR, + execution_time_ms=1, + timestamp=timestamp + timedelta(seconds=1), + attribution_parent_id=str(scenario.id), + attribution_data={ + "parent_collection": "attack", + "parent_eval_hash": "eval-1", + "seed_group_id": "seed-1", + }, + ), + ] + ) + ) + + _, aggregates, _ = await sqlite_instance.get_scenario_run_history_page_async(limit=25) aggregate = aggregates[str(scenario.id)] assert aggregate.unit_count == 1 @@ -347,7 +350,7 @@ def test_history_aggregate_uses_latest_attempt_outcome(sqlite_instance: MemoryIn assert aggregate.latest_attempt_timestamp == timestamp + timedelta(seconds=1) -def test_history_aggregates_ignore_unplanned_units_and_remap_hash_seeds( +async def test_history_aggregates_ignore_unplanned_units_and_remap_hash_seeds( sqlite_instance: MemoryInterface, ) -> None: """Plan-aware aggregation folds hash-attributed attempts into their planned unit.""" @@ -390,43 +393,45 @@ def test_history_aggregates_ignore_unplanned_units_and_remap_hash_seeds( state=ScenarioRunState.COMPLETED, labels={}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[planned, unplanned]) - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - AttackResult( - attack_result_id=str(uuid.UUID(int=22)), - conversation_id="conversation-22", - objective="objective", - outcome=AttackOutcome.FAILURE, - execution_time_ms=1, - timestamp=timestamp, - attribution_parent_id=str(planned.id), - attribution_data={"parent_collection": "attack", "parent_eval_hash": "eval-1"}, - ), - AttackResult( - attack_result_id=str(uuid.UUID(int=23)), - conversation_id="conversation-23", - objective="unplanned", - outcome=AttackOutcome.SUCCESS, - execution_time_ms=1, - timestamp=timestamp + timedelta(seconds=1), - attribution_parent_id=str(planned.id), - attribution_data={"parent_collection": "other-attack", "seed_group_id": "seed-9"}, - ), - AttackResult( - attack_result_id=str(uuid.UUID(int=24)), - conversation_id="conversation-24", - objective="objective", - outcome=AttackOutcome.SUCCESS, - execution_time_ms=1, - timestamp=timestamp, - attribution_parent_id=str(unplanned.id), - attribution_data={"parent_collection": "legacy-attack", "seed_group_id": "seed-legacy"}, - ), - ] - ) - - _, aggregates, _ = sqlite_instance.get_scenario_run_history_page(limit=25) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[planned, unplanned])) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + AttackResult( + attack_result_id=str(uuid.UUID(int=22)), + conversation_id="conversation-22", + objective="objective", + outcome=AttackOutcome.FAILURE, + execution_time_ms=1, + timestamp=timestamp, + attribution_parent_id=str(planned.id), + attribution_data={"parent_collection": "attack", "parent_eval_hash": "eval-1"}, + ), + AttackResult( + attack_result_id=str(uuid.UUID(int=23)), + conversation_id="conversation-23", + objective="unplanned", + outcome=AttackOutcome.SUCCESS, + execution_time_ms=1, + timestamp=timestamp + timedelta(seconds=1), + attribution_parent_id=str(planned.id), + attribution_data={"parent_collection": "other-attack", "seed_group_id": "seed-9"}, + ), + AttackResult( + attack_result_id=str(uuid.UUID(int=24)), + conversation_id="conversation-24", + objective="objective", + outcome=AttackOutcome.SUCCESS, + execution_time_ms=1, + timestamp=timestamp, + attribution_parent_id=str(unplanned.id), + attribution_data={"parent_collection": "legacy-attack", "seed_group_id": "seed-legacy"}, + ), + ] + ) + ) + + _, aggregates, _ = await sqlite_instance.get_scenario_run_history_page_async(limit=25) planned_aggregate = aggregates[str(planned.id)] assert planned_aggregate.unit_count == 1 @@ -438,7 +443,7 @@ def test_history_aggregates_ignore_unplanned_units_and_remap_hash_seeds( assert legacy_aggregate.successful_units == 1 -def test_history_aggregates_keep_explicitly_attributed_seed_groups_separate( +async def test_history_aggregates_keep_explicitly_attributed_seed_groups_separate( sqlite_instance: MemoryInterface, ) -> None: """An attempt carrying an unplanned seed group ID is never remapped onto a planned unit.""" @@ -474,32 +479,34 @@ def test_history_aggregates_keep_explicitly_attributed_seed_groups_separate( attack_results={}, objective_target_identifier=get_mock_target_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario]) - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - AttackResult( - attack_result_id=str(uuid.UUID(int=41)), - conversation_id="conversation-41", - objective="objective", - outcome=AttackOutcome.SUCCESS, - execution_time_ms=1, - timestamp=timestamp, - attribution_parent_id=str(scenario.id), - attribution_data={ - "parent_collection": "attack", - "parent_eval_hash": "eval-1", - "seed_group_id": "persisted-seed", - }, - ) - ] + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario])) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + AttackResult( + attack_result_id=str(uuid.UUID(int=41)), + conversation_id="conversation-41", + objective="objective", + outcome=AttackOutcome.SUCCESS, + execution_time_ms=1, + timestamp=timestamp, + attribution_parent_id=str(scenario.id), + attribution_data={ + "parent_collection": "attack", + "parent_eval_hash": "eval-1", + "seed_group_id": "persisted-seed", + }, + ) + ] + ) ) - _, aggregates, _ = sqlite_instance.get_scenario_run_history_page(limit=25) + _, aggregates, _ = await sqlite_instance.get_scenario_run_history_page_async(limit=25) assert aggregates[str(scenario.id)].unit_count == 0 -def test_history_aggregates_tolerate_malformed_plan_shapes(sqlite_instance: MemoryInterface) -> None: +async def test_history_aggregates_tolerate_malformed_plan_shapes(sqlite_instance: MemoryInterface) -> None: """Malformed plan collections fall back to legacy aggregation instead of breaking history.""" timestamp = datetime(2026, 8, 7, tzinfo=UTC) scenario = make_scenario_result( @@ -519,40 +526,44 @@ def test_history_aggregates_tolerate_malformed_plan_shapes(sqlite_instance: Memo attack_results={}, objective_target_identifier=get_mock_target_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario]) - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - AttackResult( - attack_result_id=str(uuid.UUID(int=51)), - conversation_id="conversation-51", - objective="objective", - outcome=AttackOutcome.SUCCESS, - execution_time_ms=1, - timestamp=timestamp, - attribution_parent_id=str(scenario.id), - attribution_data={"parent_collection": "attack", "seed_group_id": "seed"}, - ) - ] + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario])) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + AttackResult( + attack_result_id=str(uuid.UUID(int=51)), + conversation_id="conversation-51", + objective="objective", + outcome=AttackOutcome.SUCCESS, + execution_time_ms=1, + timestamp=timestamp, + attribution_parent_id=str(scenario.id), + attribution_data={"parent_collection": "attack", "seed_group_id": "seed"}, + ) + ] + ) ) - _, aggregates, _ = sqlite_instance.get_scenario_run_history_page(limit=25) + _, aggregates, _ = await sqlite_instance.get_scenario_run_history_page_async(limit=25) assert aggregates[str(scenario.id)].unit_count == 0 - legacy_aggregates = sqlite_instance.get_scenario_history_aggregates(scenario_result_ids=[str(scenario.id)]) + legacy_aggregates = await sqlite_instance.get_scenario_history_aggregates_async( + scenario_result_ids=[str(scenario.id)] + ) assert legacy_aggregates[str(scenario.id)].unit_count == 1 -def test_history_aggregates_fill_zero_for_runs_without_attempts(sqlite_instance: MemoryInterface) -> None: +async def test_history_aggregates_fill_zero_for_runs_without_attempts(sqlite_instance: MemoryInterface) -> None: """Runs without persisted attempts still receive an aggregate entry.""" scenario_result_id = str(uuid.UUID(int=30)) - aggregates = sqlite_instance.get_scenario_history_aggregates(scenario_result_ids=[scenario_result_id]) + aggregates = await sqlite_instance.get_scenario_history_aggregates_async(scenario_result_ids=[scenario_result_id]) assert aggregates[scenario_result_id].unit_count == 0 assert aggregates[scenario_result_id].latest_attempt_timestamp is None -def test_legacy_label_hook_is_constructible_and_composes_multi_value_semantics( +async def test_legacy_label_hook_is_constructible_and_composes_multi_value_semantics( sqlite_instance: MemoryInterface, ) -> None: timestamp = datetime(2026, 8, 7, tzinfo=UTC) @@ -570,20 +581,22 @@ def test_legacy_label_hook_is_constructible_and_composes_multi_value_semantics( state=ScenarioRunState.COMPLETED, labels={"operator": "carol", "operation": "nightly"}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[included, excluded]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[included, excluded])) legacy = object.__new__(_LegacyScenarioLabelMemory) condition = legacy._get_scenario_result_labels_condition( labels={"operator": ["alice", "bob"], "operation": "nightly"} ) - with closing(sqlite_instance.get_session()) as session: - ids = session.execute(select(ScenarioResultEntry.id).where(condition)).scalars().all() + ids = await run_memory_session_async( + memory=sqlite_instance, + operation=lambda session: session.execute(select(ScenarioResultEntry.id).where(condition)).scalars().all(), + ) assert "_get_scenario_result_label_condition" not in _LegacyScenarioLabelMemory.__abstractmethods__ assert ids == [included.id] -def test_nonterminal_state_projection_is_bounded_and_never_hydrates_results( +async def test_nonterminal_state_projection_is_bounded_and_never_hydrates_results( sqlite_instance: MemoryInterface, ) -> None: timestamp = datetime(2026, 8, 7, tzinfo=UTC) @@ -608,17 +621,17 @@ def test_nonterminal_state_projection_is_bounded_and_never_hydrates_results( state=ScenarioRunState.COMPLETED, labels={}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[queued, running, completed]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[queued, running, completed])) with ( patch.object(ScenarioResultEntry, "get_scenario_result", side_effect=AssertionError("hydrated ScenarioResult")), patch.object(AttackResultEntry, "get_attack_result", side_effect=AssertionError("hydrated AttackResult")), ): - first, has_more = sqlite_instance.get_scenario_run_state_page( + first, has_more = await sqlite_instance.get_scenario_run_state_page_async( states=[ScenarioRunState.QUEUED, ScenarioRunState.IN_PROGRESS], limit=1, ) - second, second_has_more = sqlite_instance.get_scenario_run_state_page( + second, second_has_more = await sqlite_instance.get_scenario_run_state_page_async( states=[ScenarioRunState.QUEUED, ScenarioRunState.IN_PROGRESS], after_id=first[-1].scenario_result_id, limit=1, @@ -633,18 +646,20 @@ def test_nonterminal_state_projection_is_bounded_and_never_hydrates_results( @pytest.mark.parametrize("limit", [0, 501]) -def test_nonterminal_state_projection_rejects_out_of_range_limit( +async def test_nonterminal_state_projection_rejects_out_of_range_limit( sqlite_instance: MemoryInterface, limit: int, ) -> None: with pytest.raises(ValueError, match="between 1 and 500"): - sqlite_instance.get_scenario_run_state_page( - states=[ScenarioRunState.QUEUED], - limit=limit, + ( + await sqlite_instance.get_scenario_run_state_page_async( + states=[ScenarioRunState.QUEUED], + limit=limit, + ) ) -def test_state_and_metadata_update_persists_scheduler_start_atomically( +async def test_state_and_metadata_update_persists_scheduler_start_atomically( sqlite_instance: MemoryInterface, ) -> None: timestamp = datetime(2026, 8, 7, tzinfo=UTC) @@ -656,26 +671,30 @@ def test_state_and_metadata_update_persists_scheduler_start_atomically( labels={}, registry_name="registered.scenario", ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario])) - sqlite_instance.update_scenario_run_state_and_metadata_fields( - scenario_result_id=str(scenario.id), - scenario_run_state=ScenarioRunState.IN_PROGRESS, - metadata_fields={"started_at": timestamp.isoformat()}, + ( + await sqlite_instance.update_scenario_run_state_and_metadata_fields_async( + scenario_result_id=str(scenario.id), + scenario_run_state=ScenarioRunState.IN_PROGRESS, + metadata_fields={"started_at": timestamp.isoformat()}, + ) ) - stored = sqlite_instance.get_scenario_result_header(scenario_result_id=str(scenario.id)) + stored = await sqlite_instance.get_scenario_result_header_async(scenario_result_id=str(scenario.id)) assert stored is not None assert stored.scenario_run_state is ScenarioRunState.IN_PROGRESS assert stored.metadata["started_at"] == timestamp.isoformat() assert SCENARIO_RUN_PLAN_METADATA_KEY in stored.metadata -def test_metadata_field_update_rejects_unknown_run(sqlite_instance: MemoryInterface) -> None: +async def test_metadata_field_update_rejects_unknown_run(sqlite_instance: MemoryInterface) -> None: with pytest.raises(ValueError, match="not found in memory"): - sqlite_instance.update_scenario_metadata_fields( - scenario_result_id=str(uuid.UUID(int=44)), - fields={"started_at": datetime(2026, 8, 7, tzinfo=UTC).isoformat()}, + ( + await sqlite_instance.update_scenario_metadata_fields_async( + scenario_result_id=str(uuid.UUID(int=44)), + fields={"started_at": datetime(2026, 8, 7, tzinfo=UTC).isoformat()}, + ) ) @@ -689,7 +708,7 @@ def test_default_started_at_projection_is_null() -> None: assert expression.compile().params == {"param_1": None} -def test_unique_scenario_labels_are_grouped_for_filter_options(sqlite_instance: MemoryInterface) -> None: +async def test_unique_scenario_labels_are_grouped_for_filter_options(sqlite_instance: MemoryInterface) -> None: timestamp = datetime(2026, 8, 7, tzinfo=UTC) scenarios = [ _make_scenario( @@ -701,9 +720,9 @@ def test_unique_scenario_labels_are_grouped_for_filter_options(sqlite_instance: ) for index, operator in ((20, "alice"), (21, "bob"), (22, "alice")) ] - sqlite_instance.add_scenario_results_to_memory(scenario_results=scenarios) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=scenarios)) - assert sqlite_instance.get_unique_scenario_labels() == { + assert (await sqlite_instance.get_unique_scenario_labels_async()) == { "operation": ["nightly"], "operator": ["alice", "bob"], } @@ -717,7 +736,7 @@ def test_unique_scenario_labels_are_grouped_for_filter_options(sqlite_instance: (None, {}), ], ) -def test_unique_scenario_labels_ignore_malformed_values( +async def test_unique_scenario_labels_ignore_malformed_values( *, sqlite_instance: MemoryInterface, raw_labels: object, expected: dict[str, list[str]] ) -> None: scenario = _make_scenario( @@ -727,12 +746,12 @@ def test_unique_scenario_labels_ignore_malformed_values( state=ScenarioRunState.COMPLETED, labels={"env": "prod"}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario]) - with closing(sqlite_instance.get_session()) as session: - session.execute( + await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario]) + async with await sqlite_instance.get_session_async() as session: + await session.execute( text('UPDATE "ScenarioResultEntries" SET labels = :labels'), {"labels": json.dumps(raw_labels)}, ) - session.commit() + await session.commit() - assert sqlite_instance.get_unique_scenario_labels() == expected + assert await sqlite_instance.get_unique_scenario_labels_async() == expected diff --git a/tests/unit/memory/memory_interface/test_interface_scenario_progress.py b/tests/unit/memory/memory_interface/test_interface_scenario_progress.py index aa34b20b7e..5169e3dcbb 100644 --- a/tests/unit/memory/memory_interface/test_interface_scenario_progress.py +++ b/tests/unit/memory/memory_interface/test_interface_scenario_progress.py @@ -45,7 +45,7 @@ def _make_delta_result( ) -def test_scenario_progress_deltas_page_equal_timestamps_by_id( +async def test_scenario_progress_deltas_page_equal_timestamps_by_id( sqlite_instance: MemoryInterface, ) -> None: scenario = make_scenario_result( @@ -56,7 +56,7 @@ def test_scenario_progress_deltas_page_equal_timestamps_by_id( attack_results={}, objective_target_identifier=get_mock_target_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario, unrelated]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario, unrelated])) timestamp = datetime(2026, 8, 6, tzinfo=UTC) first_id = uuid.UUID(int=1) second_id = uuid.UUID(int=2) @@ -91,14 +91,14 @@ def test_scenario_progress_deltas_page_equal_timestamps_by_id( timestamp=timestamp, ) rows[0].automated_score = score - sqlite_instance.add_scores_to_memory(scores=[score]) - sqlite_instance.add_attack_results_to_memory(attack_results=rows) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=rows)) - first_page, has_more = sqlite_instance.get_scenario_attack_result_deltas( + first_page, has_more = await sqlite_instance.get_scenario_attack_result_deltas_async( scenario_result_id=str(scenario.id), limit=1, ) - second_page, second_has_more = sqlite_instance.get_scenario_attack_result_deltas( + second_page, second_has_more = await sqlite_instance.get_scenario_attack_result_deltas_async( scenario_result_id=str(scenario.id), cursor=AttackResultKeysetCursor( timestamp=first_page[0].timestamp, @@ -120,14 +120,14 @@ def test_scenario_progress_deltas_page_equal_timestamps_by_id( assert second_page[0].atomic_attack_identifier.logical_seed_group_id == source_identifier.logical_seed_group_id -def test_scenario_progress_delta_uses_unknown_for_empty_scorer_identifier( +async def test_scenario_progress_delta_uses_unknown_for_empty_scorer_identifier( sqlite_instance: MemoryInterface, ) -> None: scenario = make_scenario_result( attack_results={}, objective_target_identifier=get_mock_target_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario])) attack_result = _make_delta_result( scenario_result_id=str(scenario.id), attack_result_id=uuid.UUID(int=5), @@ -140,10 +140,10 @@ def test_scenario_progress_delta_uses_unknown_for_empty_scorer_identifier( scorer_class_identifier=None, ) attack_result.automated_score = score - sqlite_instance.add_scores_to_memory(scores=[score]) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) - deltas, has_more = sqlite_instance.get_scenario_attack_result_deltas( + deltas, has_more = await sqlite_instance.get_scenario_attack_result_deltas_async( scenario_result_id=str(scenario.id), limit=1, ) @@ -153,26 +153,28 @@ def test_scenario_progress_delta_uses_unknown_for_empty_scorer_identifier( assert deltas[0].score.scorer_name == "Unknown" -def test_scenario_result_header_does_not_hydrate_attack_results( +async def test_scenario_result_header_does_not_hydrate_attack_results( sqlite_instance: MemoryInterface, ) -> None: scenario = make_scenario_result( attack_results={}, objective_target_identifier=get_mock_target_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario]) - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - _make_delta_result( - scenario_result_id=str(scenario.id), - attack_result_id=uuid.UUID(int=4), - timestamp=datetime(2026, 8, 6, tzinfo=UTC), - objective="objective", - ) - ] + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario])) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + _make_delta_result( + scenario_result_id=str(scenario.id), + attack_result_id=uuid.UUID(int=4), + timestamp=datetime(2026, 8, 6, tzinfo=UTC), + objective="objective", + ) + ] + ) ) - header = sqlite_instance.get_scenario_result_header(scenario_result_id=str(scenario.id)) + header = await sqlite_instance.get_scenario_result_header_async(scenario_result_id=str(scenario.id)) assert header is not None assert header.attack_results == {} diff --git a/tests/unit/memory/memory_interface/test_interface_scenario_results.py b/tests/unit/memory/memory_interface/test_interface_scenario_results.py index 22d57751b5..a96b97dfdd 100644 --- a/tests/unit/memory/memory_interface/test_interface_scenario_results.py +++ b/tests/unit/memory/memory_interface/test_interface_scenario_results.py @@ -5,7 +5,7 @@ from uuid import uuid4 import pytest -from unit.mocks import get_mock_scorer_identifier, make_scenario_result +from unit.mocks import get_mock_scorer_identifier, make_scenario_result, run_memory_session_async from pyrit.memory import MemoryInterface from pyrit.memory.memory_models import ( @@ -27,10 +27,10 @@ @pytest.fixture -def sample_attack_results(sqlite_instance: MemoryInterface): +async def sample_attack_results(sqlite_instance: MemoryInterface): """Fixture that creates and adds sample attack results to memory.""" attack_results = [create_attack_result(f"conv_{i}", f"Objective {i}") for i in range(1, 4)] - sqlite_instance.add_attack_results_to_memory(attack_results=attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=attack_results)) return attack_results @@ -70,7 +70,7 @@ def create_scenario_result( ) -def test_add_and_retrieve_scenario_results(sqlite_instance: MemoryInterface, sample_attack_results): +async def test_add_and_retrieve_scenario_results(sqlite_instance: MemoryInterface, sample_attack_results): """Test adding scenario results to memory and retrieving them without filters.""" # Create scenario results using the fixture's attack results scenario_result1 = create_scenario_result( @@ -88,10 +88,10 @@ def test_add_and_retrieve_scenario_results(sqlite_instance: MemoryInterface, sam ) # Add scenario results to memory - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result1, scenario_result2]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result1, scenario_result2])) # Verify they were added by querying all scenario results - all_scenarios = sqlite_instance.get_scenario_results() + all_scenarios = await sqlite_instance.get_scenario_results_async() assert len(all_scenarios) == 2 # Verify the data was stored correctly @@ -99,7 +99,7 @@ def test_add_and_retrieve_scenario_results(sqlite_instance: MemoryInterface, sam assert scenario_names == {"Scenario 1", "Scenario 2"} -def test_add_scenario_results_persists_identifier_graph(sqlite_instance: MemoryInterface): +async def test_add_scenario_results_persists_identifier_graph(sqlite_instance: MemoryInterface): target = TargetIdentifier( class_name="TestTarget", class_module="tests.unit.memory", @@ -124,7 +124,7 @@ def test_add_scenario_results_persists_identifier_graph(sqlite_instance: MemoryI for _ in range(2) ] - sqlite_instance.add_scenario_results_to_memory(scenario_results=results) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=results)) scenario_rows = sqlite_instance._query_entries(ScenarioIdentifierEntry) result_rows = sqlite_instance._query_entries(ScenarioResultEntry) @@ -140,7 +140,7 @@ def test_add_scenario_results_persists_identifier_graph(sqlite_instance: MemoryI assert len(sqlite_instance._query_entries(ScorerIdentifierEntry)) == 1 -def test_filter_by_name(sqlite_instance: MemoryInterface, sample_attack_results): +async def test_filter_by_name(sqlite_instance: MemoryInterface, sample_attack_results): """Test retrieving scenario results filtered by name.""" # Create and add scenario results scenario_result1 = create_scenario_result( @@ -151,15 +151,15 @@ def test_filter_by_name(sqlite_instance: MemoryInterface, sample_attack_results) name="Production Scenario", attack_results={"Attack2": [sample_attack_results[1]]}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result1, scenario_result2]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result1, scenario_result2])) # Query by name substring - results = sqlite_instance.get_scenario_results(scenario_name="Test") + results = await sqlite_instance.get_scenario_results_async(scenario_name="Test") assert len(results) == 1 assert results[0].scenario_name == "Test Scenario Alpha" -def test_filter_by_version(sqlite_instance: MemoryInterface, sample_attack_results): +async def test_filter_by_version(sqlite_instance: MemoryInterface, sample_attack_results): """Test retrieving scenario results filtered by version.""" # Create and add scenario results with different versions scenario_result1 = create_scenario_result( @@ -172,40 +172,40 @@ def test_filter_by_version(sqlite_instance: MemoryInterface, sample_attack_resul version=2, attack_results={"Attack2": [sample_attack_results[1]]}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result1, scenario_result2]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result1, scenario_result2])) # Query by version - results = sqlite_instance.get_scenario_results(scenario_version=2) + results = await sqlite_instance.get_scenario_results_async(scenario_version=2) assert len(results) == 1 assert results[0].scenario_version == 2 -def test_filter_by_ids(sqlite_instance: MemoryInterface, sample_attack_results): +async def test_filter_by_ids(sqlite_instance: MemoryInterface, sample_attack_results): """Test retrieving scenario results by their IDs.""" # Create and add scenario results scenario_result1 = create_scenario_result( name="Scenario 1", attack_results={"Attack1": [sample_attack_results[0]]}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result1]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result1])) # Query by ID using the scenario result's id - results = sqlite_instance.get_scenario_results(scenario_result_ids=[str(scenario_result1.id)]) + results = await sqlite_instance.get_scenario_results_async(scenario_result_ids=[str(scenario_result1.id)]) assert len(results) == 1 assert results[0].scenario_name == "Scenario 1" assert results[0].id == scenario_result1.id -def test_empty_ids_returns_empty(sqlite_instance: MemoryInterface): +async def test_empty_ids_returns_empty(sqlite_instance: MemoryInterface): """Test that empty ID list returns empty results.""" - results = sqlite_instance.get_scenario_results(scenario_result_ids=[]) + results = await sqlite_instance.get_scenario_results_async(scenario_result_ids=[]) assert len(results) == 0 -def test_attack_results_populated_correctly(sqlite_instance: MemoryInterface): +async def test_attack_results_populated_correctly(sqlite_instance: MemoryInterface): """Test that retrieving scenario results populates attack_results correctly.""" scenario_result = create_scenario_result(name="Multi-Attack Scenario", attack_results={}) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) sid = scenario_result.id attack_result1 = _make_attack_result_for_scenario( @@ -227,10 +227,14 @@ def test_attack_results_populated_correctly(sqlite_instance: MemoryInterface): objective_index=0, conversation_id="conv_3", ) - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Retrieve and verify attack_results are populated - results = sqlite_instance.get_scenario_results() + results = await sqlite_instance.get_scenario_results_async() assert len(results) == 1 retrieved_scenario = results[0] @@ -250,11 +254,11 @@ def test_attack_results_populated_correctly(sqlite_instance: MemoryInterface): assert crescendo_results[0].conversation_id == "conv_3" -def test_attack_order_preserved(sqlite_instance: MemoryInterface): +async def test_attack_order_preserved(sqlite_instance: MemoryInterface): """Hydration sorts each atomic attack's results by ``timestamp`` (which monotonically tracks insertion order under normal sequential execution).""" scenario_result = create_scenario_result(name="Ordered Scenario", attack_results={}) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) sid = scenario_result.id # Insert in a specific order; hydration must surface them in the same order. @@ -268,19 +272,19 @@ def test_attack_order_preserved(sqlite_instance: MemoryInterface): for i in range(5) ] for ar in attack_results: - sqlite_instance.add_attack_results_to_memory(attack_results=[ar]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar])) - results = sqlite_instance.get_scenario_results() + results = await sqlite_instance.get_scenario_results_async() retrieved_attacks = results[0].attack_results["Attack1"] retrieved_conv_ids = [ar.conversation_id for ar in retrieved_attacks] assert retrieved_conv_ids == [f"conv_{i}" for i in range(5)] -def test_stores_conversation_ids_only(sqlite_instance: MemoryInterface): +async def test_stores_conversation_ids_only(sqlite_instance: MemoryInterface): """Test that scenario results expose AttackResult objects with conversation IDs after hydration.""" scenario_result = create_scenario_result(name="Test Scenario", attack_results={}) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) ar = _make_attack_result_for_scenario( scenario_result_id=scenario_result.id, @@ -288,9 +292,9 @@ def test_stores_conversation_ids_only(sqlite_instance: MemoryInterface): objective_index=0, conversation_id="conv_1", ) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar])) - results = sqlite_instance.get_scenario_results(scenario_result_ids=[str(scenario_result.id)]) + results = await sqlite_instance.get_scenario_results_async(scenario_result_ids=[str(scenario_result.id)]) assert len(results) == 1 retrieved_result = results[0] @@ -299,47 +303,51 @@ def test_stores_conversation_ids_only(sqlite_instance: MemoryInterface): assert retrieved_result.attack_results["Attack1"][0].conversation_id == "conv_1" -def test_handles_empty_attack_results(sqlite_instance: MemoryInterface): +async def test_handles_empty_attack_results(sqlite_instance: MemoryInterface): """Test that scenario results can be created with no attack results.""" # Create scenario result with no attacks scenario_result = create_scenario_result( name="Empty Scenario", attack_results={}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) # Retrieve and verify - results = sqlite_instance.get_scenario_results() + results = await sqlite_instance.get_scenario_results_async() assert len(results) == 1 assert len(results[0].attack_results) == 0 -def test_terminal_state_updates_completion_time_only_on_terminal_transition( +async def test_terminal_state_updates_completion_time_only_on_terminal_transition( sqlite_instance: MemoryInterface, ) -> None: old_completion = datetime(2020, 1, 1, tzinfo=UTC) scenario_result = create_scenario_result(name="Timing Scenario") scenario_result.completion_time = old_completion - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) - sqlite_instance.update_scenario_run_state( - scenario_result_id=str(scenario_result.id), - scenario_run_state=ScenarioRunState.IN_PROGRESS, + ( + await sqlite_instance.update_scenario_run_state_async( + scenario_result_id=str(scenario_result.id), + scenario_run_state=ScenarioRunState.IN_PROGRESS, + ) ) - in_progress = sqlite_instance.get_scenario_result_header(scenario_result_id=str(scenario_result.id)) + in_progress = await sqlite_instance.get_scenario_result_header_async(scenario_result_id=str(scenario_result.id)) assert in_progress is not None assert in_progress.completion_time == old_completion - sqlite_instance.update_scenario_run_state( - scenario_result_id=str(scenario_result.id), - scenario_run_state=ScenarioRunState.COMPLETED, + ( + await sqlite_instance.update_scenario_run_state_async( + scenario_result_id=str(scenario_result.id), + scenario_run_state=ScenarioRunState.COMPLETED, + ) ) - completed = sqlite_instance.get_scenario_result_header(scenario_result_id=str(scenario_result.id)) + completed = await sqlite_instance.get_scenario_result_header_async(scenario_result_id=str(scenario_result.id)) assert completed is not None assert completed.completion_time > old_completion -def test_preserves_metadata(sqlite_instance: MemoryInterface): +async def test_preserves_metadata(sqlite_instance: MemoryInterface): """Test that scenario metadata is preserved correctly.""" # Create scenario result with metadata @@ -361,10 +369,10 @@ def test_preserves_metadata(sqlite_instance: MemoryInterface): attack_results={}, objective_scorer_identifier=scorer_identifier, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) # Retrieve and verify metadata - results = sqlite_instance.get_scenario_results() + results = await sqlite_instance.get_scenario_results_async() assert len(results) == 1 retrieved = results[0] @@ -379,11 +387,11 @@ def test_preserves_metadata(sqlite_instance: MemoryInterface): assert retrieved.objective_scorer_identifier.class_module == "test.module" -def test_multiple_scenarios_with_attacks(sqlite_instance: MemoryInterface): +async def test_multiple_scenarios_with_attacks(sqlite_instance: MemoryInterface): """Test retrieving multiple scenarios with their attack results populated.""" scenario1 = create_scenario_result(name="Scenario 1", attack_results={}) scenario2 = create_scenario_result(name="Scenario 2", attack_results={}) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1, scenario2])) all_attack_results = [ _make_attack_result_for_scenario( @@ -402,10 +410,10 @@ def test_multiple_scenarios_with_attacks(sqlite_instance: MemoryInterface): ) for i in range(3) ] - sqlite_instance.add_attack_results_to_memory(attack_results=all_attack_results) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=all_attack_results)) # Retrieve all scenarios - results = sqlite_instance.get_scenario_results() + results = await sqlite_instance.get_scenario_results_async() assert len(results) == 2 # Verify each scenario has the correct attack results @@ -416,13 +424,17 @@ def test_multiple_scenarios_with_attacks(sqlite_instance: MemoryInterface): assert len(result.attack_results["Attack2"]) == 3 -def test_filter_by_name_and_version(sqlite_instance: MemoryInterface): +async def test_filter_by_name_and_version(sqlite_instance: MemoryInterface): """Test querying with both name and version filters.""" # Create attack results attack_result1 = create_attack_result("conv_1", "Objective 1") attack_result2 = create_attack_result("conv_2", "Objective 2") attack_result3 = create_attack_result("conv_3", "Objective 3") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Create multiple versions of scenarios with similar names scenarios = [ @@ -430,16 +442,16 @@ def test_filter_by_name_and_version(sqlite_instance: MemoryInterface): create_scenario_result(name="Test Scenario", version=2, attack_results={"A2": [attack_result2]}), create_scenario_result(name="Other Scenario", version=1, attack_results={"A3": [attack_result3]}), ] - sqlite_instance.add_scenario_results_to_memory(scenario_results=scenarios) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=scenarios)) # Query with both filters - results = sqlite_instance.get_scenario_results(scenario_name="Test", scenario_version=2) + results = await sqlite_instance.get_scenario_results_async(scenario_name="Test", scenario_version=2) assert len(results) == 1 assert results[0].scenario_name == "Test Scenario" assert results[0].scenario_version == 2 -def test_filter_by_labels(sqlite_instance: MemoryInterface, sample_attack_results): +async def test_filter_by_labels(sqlite_instance: MemoryInterface, sample_attack_results): """Test scenario results with labels.""" # Create scenario with labels scenario_result = make_scenario_result( @@ -450,20 +462,20 @@ def test_filter_by_labels(sqlite_instance: MemoryInterface, sample_attack_result labels={"environment": "testing", "team": "red-team"}, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) # Query by labels - results = sqlite_instance.get_scenario_results(labels={"environment": "testing"}) + results = await sqlite_instance.get_scenario_results_async(labels={"environment": "testing"}) assert len(results) == 1 assert results[0].labels == {"environment": "testing", "team": "red-team"} -def test_filter_by_multiple_labels(sqlite_instance: MemoryInterface): +async def test_filter_by_multiple_labels(sqlite_instance: MemoryInterface): """Test filtering scenario results by multiple labels.""" # Create attack results attack_result1 = create_attack_result("conv_1", "Objective 1") attack_result2 = create_attack_result("conv_2", "Objective 2") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result1, attack_result2])) # Create scenarios with different labels scenario1 = make_scenario_result( @@ -483,21 +495,25 @@ def test_filter_by_multiple_labels(sqlite_instance: MemoryInterface): labels={"environment": "production", "team": "red-team"}, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1, scenario2])) # Query requiring both labels to match - results = sqlite_instance.get_scenario_results(labels={"environment": "testing", "team": "red-team"}) + results = await sqlite_instance.get_scenario_results_async(labels={"environment": "testing", "team": "red-team"}) assert len(results) == 1 assert results[0].scenario_name == "Scenario 1" -def test_filter_by_completion_time(sqlite_instance: MemoryInterface): +async def test_filter_by_completion_time(sqlite_instance: MemoryInterface): """Test scenario results with completion time filtering.""" # Create attack results attack_result1 = create_attack_result("conv_1", "Objective 1") attack_result2 = create_attack_result("conv_2", "Objective 2") attack_result3 = create_attack_result("conv_3", "Objective 3") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Create scenarios with different completion times now = datetime.now(UTC) @@ -530,29 +546,29 @@ def test_filter_by_completion_time(sqlite_instance: MemoryInterface): completion_time=last_week, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2, scenario3]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1, scenario2, scenario3])) # Query scenarios after yesterday - results = sqlite_instance.get_scenario_results(added_after=yesterday) + results = await sqlite_instance.get_scenario_results_async(added_after=yesterday) assert len(results) == 2 result_names = {r.scenario_name for r in results} assert "Recent Scenario" in result_names assert "Yesterday Scenario" in result_names # Query scenarios before yesterday - results = sqlite_instance.get_scenario_results(added_before=yesterday) + results = await sqlite_instance.get_scenario_results_async(added_before=yesterday) assert len(results) == 2 result_names = {r.scenario_name for r in results} assert "Yesterday Scenario" in result_names assert "Old Scenario" in result_names -def test_filter_by_pyrit_version(sqlite_instance: MemoryInterface): +async def test_filter_by_pyrit_version(sqlite_instance: MemoryInterface): """Test filtering scenario results by PyRIT version.""" # Create attack results attack_result1 = create_attack_result("conv_1", "Objective 1") attack_result2 = create_attack_result("conv_2", "Objective 2") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result1, attack_result2])) # Create scenarios with different PyRIT versions scenario1 = make_scenario_result( @@ -572,22 +588,26 @@ def test_filter_by_pyrit_version(sqlite_instance: MemoryInterface): attack_results={"Attack2": [attack_result2]}, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1, scenario2])) # Query by PyRIT version - results = sqlite_instance.get_scenario_results(pyrit_version="0.5.0") + results = await sqlite_instance.get_scenario_results_async(pyrit_version="0.5.0") assert len(results) == 1 assert results[0].scenario_name == "New Version Scenario" assert results[0].pyrit_version == "0.5.0" -def test_filter_by_target_endpoint(sqlite_instance: MemoryInterface): +async def test_filter_by_target_endpoint(sqlite_instance: MemoryInterface): """Test filtering scenario results by target endpoint.""" # Create attack results attack_result1 = create_attack_result("conv_1", "Objective 1") attack_result2 = create_attack_result("conv_2", "Objective 2") attack_result3 = create_attack_result("conv_3", "Objective 3") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Create scenarios with different target endpoints scenario1 = make_scenario_result( @@ -621,28 +641,32 @@ def test_filter_by_target_endpoint(sqlite_instance: MemoryInterface): attack_results={"Attack3": [attack_result3]}, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2, scenario3]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1, scenario2, scenario3])) # Query by endpoint (case-insensitive substring match) - results = sqlite_instance.get_scenario_results(objective_target_endpoint="azure") + results = await sqlite_instance.get_scenario_results_async(objective_target_endpoint="azure") assert len(results) == 1 assert results[0].scenario_name == "Azure Scenario" # Query for OpenAI endpoints - results = sqlite_instance.get_scenario_results(objective_target_endpoint="openai") + results = await sqlite_instance.get_scenario_results_async(objective_target_endpoint="openai") assert len(results) == 2 result_names = {r.scenario_name for r in results} assert "Azure Scenario" in result_names assert "OpenAI Scenario" in result_names -def test_filter_by_target_model_name(sqlite_instance: MemoryInterface): +async def test_filter_by_target_model_name(sqlite_instance: MemoryInterface): """Test filtering scenario results by target model name.""" # Create attack results attack_result1 = create_attack_result("conv_1", "Objective 1") attack_result2 = create_attack_result("conv_2", "Objective 2") attack_result3 = create_attack_result("conv_3", "Objective 3") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[attack_result1, attack_result2, attack_result3] + ) + ) # Create scenarios with different model names scenario1 = make_scenario_result( @@ -678,27 +702,27 @@ def test_filter_by_target_model_name(sqlite_instance: MemoryInterface): attack_results={"Attack3": [attack_result3]}, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2, scenario3]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1, scenario2, scenario3])) # Query by model name (case-insensitive substring match) - results = sqlite_instance.get_scenario_results(objective_target_model_name="gpt-4") + results = await sqlite_instance.get_scenario_results_async(objective_target_model_name="gpt-4") assert len(results) == 2 result_names = {r.scenario_name for r in results} assert "GPT-4 Scenario" in result_names assert "GPT-4o Scenario" in result_names # Query for GPT-3.5 - results = sqlite_instance.get_scenario_results(objective_target_model_name="3.5") + results = await sqlite_instance.get_scenario_results_async(objective_target_model_name="3.5") assert len(results) == 1 assert results[0].scenario_name == "GPT-3.5 Scenario" -def test_combined_filters(sqlite_instance: MemoryInterface): +async def test_combined_filters(sqlite_instance: MemoryInterface): """Test combining multiple filters together.""" # Create attack results attack_result1 = create_attack_result("conv_1", "Objective 1") attack_result2 = create_attack_result("conv_2", "Objective 2") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result1, attack_result2])) # Create scenarios with various properties now = datetime.now(UTC) @@ -733,10 +757,10 @@ def test_combined_filters(sqlite_instance: MemoryInterface): completion_time=yesterday, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1, scenario2])) # Query with multiple filters - results = sqlite_instance.get_scenario_results( + results = await sqlite_instance.get_scenario_results_async( scenario_name="Test", pyrit_version="0.5.0", objective_target_model_name="gpt-4", @@ -773,7 +797,7 @@ def _make_attack_result_for_scenario( ) -def test_get_scenario_results_loads_attack_results_via_foreign_key( +async def test_get_scenario_results_loads_attack_results_via_foreign_key( sqlite_instance: MemoryInterface, ): """Hydration loads AttackResults through the attribution_parent_id foreign key.""" @@ -781,15 +805,15 @@ def test_get_scenario_results_loads_attack_results_via_foreign_key( name="ForeignKey-only Scenario", attack_results={}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) sid = scenario_result.id ar1 = _make_attack_result_for_scenario(scenario_result_id=sid, atomic_attack_name="a", objective_index=0) ar2 = _make_attack_result_for_scenario(scenario_result_id=sid, atomic_attack_name="a", objective_index=1) ar3 = _make_attack_result_for_scenario(scenario_result_id=sid, atomic_attack_name="b", objective_index=0) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar1, ar2, ar3]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar1, ar2, ar3])) - [result] = sqlite_instance.get_scenario_results(scenario_result_ids=[str(sid)]) + [result] = await sqlite_instance.get_scenario_results_async(scenario_result_ids=[str(sid)]) assert set(result.attack_results.keys()) == {"a", "b"} assert [r.conversation_id for r in result.attack_results["a"]] == [ "conv-a-0", @@ -798,13 +822,13 @@ def test_get_scenario_results_loads_attack_results_via_foreign_key( assert [r.conversation_id for r in result.attack_results["b"]] == ["conv-b-0"] -def test_get_attack_results_filters_by_scenario_result_id( +async def test_get_attack_results_filters_by_scenario_result_id( sqlite_instance: MemoryInterface, ): """get_attack_results gains a scenario_result_id filter — replaces the removed error_attack_result_ids_json lookup path.""" scenario_result = create_scenario_result(name="Filter Scenario") - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) sid = scenario_result.id ok = _make_attack_result_for_scenario(scenario_result_id=sid, atomic_attack_name="a", objective_index=0) @@ -816,22 +840,22 @@ def test_get_attack_results_filters_by_scenario_result_id( ) # An unrelated AttackResult NOT linked to this scenario should be excluded. unrelated = create_attack_result("unrelated-conv", "unrelated-obj") - sqlite_instance.add_attack_results_to_memory(attack_results=[ok, err, unrelated]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ok, err, unrelated])) - all_for_scenario = sqlite_instance.get_attack_results(scenario_result_id=str(sid)) + all_for_scenario = await sqlite_instance.get_attack_results_async(scenario_result_id=str(sid)) assert {r.conversation_id for r in all_for_scenario} == { ok.conversation_id, err.conversation_id, } - only_errors = sqlite_instance.get_attack_results( + only_errors = await sqlite_instance.get_attack_results_async( scenario_result_id=str(sid), outcome=AttackOutcome.ERROR.value, ) assert [r.conversation_id for r in only_errors] == [err.conversation_id] -def test_delete_scenario_sets_attack_result_foreign_key_to_null( +async def test_delete_scenario_sets_attack_result_foreign_key_to_null( sqlite_instance: MemoryInterface, ): """ON DELETE SET NULL: deleting the parent ScenarioResultEntry nulls the @@ -844,34 +868,36 @@ def test_delete_scenario_sets_attack_result_foreign_key_to_null( ON DELETE SET NULL clause works. Production deployments using SQL Server enforce foreign keys by default. """ - from contextlib import closing - from sqlalchemy import text as _sql_text from pyrit.memory.memory_models import AttackResultEntry, ScenarioResultEntry scenario_result = create_scenario_result(name="To Be Deleted") - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) sid = scenario_result.id ar = _make_attack_result_for_scenario(scenario_result_id=sid, atomic_attack_name="a", objective_index=0) - sqlite_instance.add_attack_results_to_memory(attack_results=[ar]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar])) # Enable foreign keys for the delete and verify the SET NULL clause fires. - with closing(sqlite_instance.get_session()) as session: + def delete_scenario(session): session.execute(_sql_text("PRAGMA foreign_keys = ON")) session.query(ScenarioResultEntry).filter_by(id=sid).delete() session.commit() + await run_memory_session_async(memory=sqlite_instance, operation=delete_scenario) + # The AttackResult survives, but its foreign key is now NULL. # attribution_data is retained as historical provenance. - with closing(sqlite_instance.get_session()) as session: + def check_attack(session): entry = session.query(AttackResultEntry).filter_by(conversation_id=ar.conversation_id).one() assert entry.attribution_parent_id is None assert entry.attribution_data == {"parent_collection": "a"} + await run_memory_session_async(memory=sqlite_instance, operation=check_attack) + -def test_update_scenario_run_state_updates_state_and_error_fields( +async def test_update_scenario_run_state_updates_state_and_error_fields( sqlite_instance: MemoryInterface, ): """update_scenario_run_state updates persisted state and error details.""" @@ -879,43 +905,51 @@ def test_update_scenario_run_state_updates_state_and_error_fields( name="Targeted Update", attack_results={"a": []}, ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) sid = str(scenario_result.id) - sqlite_instance.update_scenario_run_state( - scenario_result_id=sid, - scenario_run_state=ScenarioRunState.FAILED, - error_message="boom", - error_type="RuntimeError", + ( + await sqlite_instance.update_scenario_run_state_async( + scenario_result_id=sid, + scenario_run_state=ScenarioRunState.FAILED, + error_message="boom", + error_type="RuntimeError", + ) ) # State and error fields updated. - [hydrated] = sqlite_instance.get_scenario_results(scenario_result_ids=[sid]) + [hydrated] = await sqlite_instance.get_scenario_results_async(scenario_result_ids=[sid]) assert hydrated.scenario_run_state == ScenarioRunState.FAILED assert hydrated.error_message == "boom" assert hydrated.error_type == "RuntimeError" - sqlite_instance.update_scenario_run_state( - scenario_result_id=sid, - scenario_run_state=ScenarioRunState.COMPLETED, + ( + await sqlite_instance.update_scenario_run_state_async( + scenario_result_id=sid, + scenario_run_state=ScenarioRunState.COMPLETED, + ) ) - [hydrated] = sqlite_instance.get_scenario_results(scenario_result_ids=[sid]) + [hydrated] = await sqlite_instance.get_scenario_results_async(scenario_result_ids=[sid]) assert hydrated.scenario_run_state == ScenarioRunState.COMPLETED assert hydrated.error_message is None assert hydrated.error_type is None -def test_try_update_scenario_run_state_updates_when_the_state_matches( +async def test_try_update_scenario_run_state_updates_when_the_state_matches( sqlite_instance: MemoryInterface, ): """The compare-and-set applies when the row is still in one of the expected states.""" scenario_result = create_scenario_result(name="CAS Match", attack_results={"a": []}) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) sid = str(scenario_result.id) - sqlite_instance.update_scenario_run_state(scenario_result_id=sid, scenario_run_state=ScenarioRunState.CREATED) + ( + await sqlite_instance.update_scenario_run_state_async( + scenario_result_id=sid, scenario_run_state=ScenarioRunState.CREATED + ) + ) - updated = sqlite_instance.try_update_scenario_run_state( + updated = await sqlite_instance.try_update_scenario_run_state_async( scenario_result_id=sid, expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, scenario_run_state=ScenarioRunState.FAILED, @@ -924,27 +958,29 @@ def test_try_update_scenario_run_state_updates_when_the_state_matches( ) assert updated is True - [hydrated] = sqlite_instance.get_scenario_results(scenario_result_ids=[sid]) + [hydrated] = await sqlite_instance.get_scenario_results_async(scenario_result_ids=[sid]) assert hydrated.scenario_run_state == ScenarioRunState.FAILED assert hydrated.error_message == "boom" assert hydrated.error_type == "RuntimeError" -def test_try_update_scenario_run_state_preserves_a_terminal_state( +async def test_try_update_scenario_run_state_preserves_a_terminal_state( sqlite_instance: MemoryInterface, ): """A run cancelled while preparation was draining must keep its cancellation.""" scenario_result = create_scenario_result(name="CAS Mismatch", attack_results={"a": []}) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario_result]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario_result])) sid = str(scenario_result.id) - sqlite_instance.update_scenario_run_state( - scenario_result_id=sid, - scenario_run_state=ScenarioRunState.CANCELLED, - error_message="Run was cancelled by user", - error_type="CancelledError", + ( + await sqlite_instance.update_scenario_run_state_async( + scenario_result_id=sid, + scenario_run_state=ScenarioRunState.CANCELLED, + error_message="Run was cancelled by user", + error_type="CancelledError", + ) ) - updated = sqlite_instance.try_update_scenario_run_state( + updated = await sqlite_instance.try_update_scenario_run_state_async( scenario_result_id=sid, expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, scenario_run_state=ScenarioRunState.FAILED, @@ -953,39 +989,40 @@ def test_try_update_scenario_run_state_preserves_a_terminal_state( ) assert updated is False - [hydrated] = sqlite_instance.get_scenario_results(scenario_result_ids=[sid]) + [hydrated] = await sqlite_instance.get_scenario_results_async(scenario_result_ids=[sid]) assert hydrated.scenario_run_state == ScenarioRunState.CANCELLED assert hydrated.error_message == "Run was cancelled by user" assert hydrated.error_type == "CancelledError" -def test_try_update_scenario_run_state_reports_a_missing_row( +async def test_try_update_scenario_run_state_reports_a_missing_row( sqlite_instance: MemoryInterface, ): """A run that is gone is not an error here; the caller only needs to know nothing changed.""" assert ( - sqlite_instance.try_update_scenario_run_state( + await sqlite_instance.try_update_scenario_run_state_async( scenario_result_id=str(uuid4()), expected_states={ScenarioRunState.CREATED}, scenario_run_state=ScenarioRunState.FAILED, ) - is False - ) + ) is False -def test_try_update_scenario_run_state_rejects_empty_expected_states( +async def test_try_update_scenario_run_state_rejects_empty_expected_states( sqlite_instance: MemoryInterface, ): """An empty set would silently never match, which would hide the bug it exists to prevent.""" with pytest.raises(ValueError, match="expected_states"): - sqlite_instance.try_update_scenario_run_state( - scenario_result_id=str(uuid4()), - expected_states=set(), - scenario_run_state=ScenarioRunState.FAILED, + ( + await sqlite_instance.try_update_scenario_run_state_async( + scenario_result_id=str(uuid4()), + expected_states=set(), + scenario_run_state=ScenarioRunState.FAILED, + ) ) -def test_get_scenario_results_by_target_identifier_filter_hash( +async def test_get_scenario_results_by_target_identifier_filter_hash( sqlite_instance: MemoryInterface, ): """Test filtering scenario results by identifier filter.""" @@ -1002,7 +1039,7 @@ def test_get_scenario_results_by_target_identifier_filter_hash( attack_result1 = create_attack_result("conv_1", "Objective 1") attack_result2 = create_attack_result("conv_2", "Objective 2") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result1, attack_result2])) scenario1 = make_scenario_result( scenario_name="Scenario OpenAI", @@ -1018,10 +1055,10 @@ def test_get_scenario_results_by_target_identifier_filter_hash( attack_results={"Attack2": [attack_result2]}, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1, scenario2])) # Filter by target hash - results = sqlite_instance.get_scenario_results( + results = await sqlite_instance.get_scenario_results_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.TARGET, @@ -1035,7 +1072,7 @@ def test_get_scenario_results_by_target_identifier_filter_hash( assert results[0].scenario_name == "Scenario OpenAI" -def test_get_scenario_results_by_target_identifier_filter_endpoint( +async def test_get_scenario_results_by_target_identifier_filter_endpoint( sqlite_instance: MemoryInterface, ): """Test filtering scenario results by identifier filter with endpoint.""" @@ -1052,7 +1089,7 @@ def test_get_scenario_results_by_target_identifier_filter_endpoint( attack_result1 = create_attack_result("conv_1", "Objective 1") attack_result2 = create_attack_result("conv_2", "Objective 2") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result1, attack_result2])) scenario1 = make_scenario_result( scenario_name="Scenario OpenAI", @@ -1068,10 +1105,10 @@ def test_get_scenario_results_by_target_identifier_filter_endpoint( attack_results={"Attack2": [attack_result2]}, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1, scenario2]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1, scenario2])) # Filter by endpoint partial match - results = sqlite_instance.get_scenario_results( + results = await sqlite_instance.get_scenario_results_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.TARGET, @@ -1085,12 +1122,12 @@ def test_get_scenario_results_by_target_identifier_filter_endpoint( assert results[0].scenario_name == "Scenario OpenAI" -def test_get_scenario_results_by_target_identifier_filter_no_match( +async def test_get_scenario_results_by_target_identifier_filter_no_match( sqlite_instance: MemoryInterface, ): """Test that TargetIdentifierFilter returns empty when nothing matches.""" attack_result1 = create_attack_result("conv_1", "Objective 1") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result1])) scenario1 = make_scenario_result( scenario_name="Test Scenario", @@ -1103,9 +1140,9 @@ def test_get_scenario_results_by_target_identifier_filter_no_match( attack_results={"Attack1": [attack_result1]}, objective_scorer_identifier=get_mock_scorer_identifier(), ) - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario1]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario1])) - results = sqlite_instance.get_scenario_results( + results = await sqlite_instance.get_scenario_results_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.TARGET, @@ -1118,10 +1155,10 @@ def test_get_scenario_results_by_target_identifier_filter_no_match( assert len(results) == 0 -def test_add_scenario_result_without_objective_target_raises(sqlite_instance: MemoryInterface): +async def test_add_scenario_result_without_objective_target_raises(sqlite_instance: MemoryInterface): """Persisting a targetless scenario result fails loudly instead of writing an unqueryable row.""" attack_result = create_attack_result("conv_1", "Objective 1") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack_result])) scenario = make_scenario_result( scenario_name="Targetless Scenario", @@ -1132,6 +1169,6 @@ def test_add_scenario_result_without_objective_target_raises(sqlite_instance: Me ) with pytest.raises(ValueError, match="objective_target_identifier is required"): - sqlite_instance.add_scenario_results_to_memory(scenario_results=[scenario]) + (await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario])) - assert sqlite_instance.get_scenario_results(scenario_name="Targetless Scenario") == [] + assert (await sqlite_instance.get_scenario_results_async(scenario_name="Targetless Scenario")) == [] diff --git a/tests/unit/memory/memory_interface/test_interface_scorable_content.py b/tests/unit/memory/memory_interface/test_interface_scorable_content.py index bb54d82e59..b30279a7df 100644 --- a/tests/unit/memory/memory_interface/test_interface_scorable_content.py +++ b/tests/unit/memory/memory_interface/test_interface_scorable_content.py @@ -43,37 +43,37 @@ def _content_score(content: ContentScorable, *, value: str = "true") -> Score: ) -def test_loose_content_is_persisted_and_anchor_becomes_a_reference(sqlite_instance: MemoryInterface): +async def test_loose_content_is_persisted_and_anchor_becomes_a_reference(sqlite_instance: MemoryInterface): content = ContentScorable(value="loose text", data_type="text") score = _content_score(content) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) # The in-hand score now names the stored row rather than carrying the payload. assert isinstance(score.scorable, ContentEntryScorable) - stored = sqlite_instance.get_scores(score_ids=[str(score.id)])[0] + stored = (await sqlite_instance.get_scores_async(score_ids=[str(score.id)]))[0] assert isinstance(stored.scorable, ContentEntryScorable) - assert sqlite_instance.get_scorable_content(content_ids=[stored.scorable.content_id]) == { + assert (await sqlite_instance.get_scorable_content_async(content_ids=[stored.scorable.content_id])) == { stored.scorable.content_id: content } -def test_scores_over_the_same_content_share_one_row(sqlite_instance: MemoryInterface): +async def test_scores_over_the_same_content_share_one_row(sqlite_instance: MemoryInterface): content = ContentScorable(value="shared text") scores = [_content_score(content), _content_score(content, value="false")] - sqlite_instance.add_scores_to_memory(scores=scores) + (await sqlite_instance.add_scores_to_memory_async(scores=scores)) anchors = {score.scorable.content_id for score in scores} # type: ignore[union-attr] assert len(anchors) == 1 assert len(sqlite_instance._query_entries(ScorableContentEntry)) == 1 -def test_content_reference_is_promoted_to_a_foreign_key_column(sqlite_instance: MemoryInterface): +async def test_content_reference_is_promoted_to_a_foreign_key_column(sqlite_instance: MemoryInterface): score = _content_score(ContentScorable(value="joinable text")) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) entry = sqlite_instance._query_entries(ScoreEntry, conditions=ScoreEntry.id == score.id)[0] # The id is promoted out of the JSON so the reference is enforced and joinable. @@ -81,7 +81,7 @@ def test_content_reference_is_promoted_to_a_foreign_key_column(sqlite_instance: assert entry.scorable["content_id"] == str(entry.scorable_content_id) -def test_message_anchored_score_leaves_the_content_column_null(sqlite_instance: MemoryInterface): +async def test_message_anchored_score_leaves_the_content_column_null(sqlite_instance: MemoryInterface): score = Score( id=uuid4(), score_value="true", @@ -90,22 +90,22 @@ def test_message_anchored_score_leaves_the_content_column_null(sqlite_instance: scorer_class_identifier=_scorer_id(), ) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) entry = sqlite_instance._query_entries(ScoreEntry, conditions=ScoreEntry.id == score.id)[0] assert entry.scorable_content_id is None -def test_unicode_content_round_trips_with_sha256(sqlite_instance: MemoryInterface): +async def test_unicode_content_round_trips_with_sha256(sqlite_instance: MemoryInterface): content = ContentScorable(value="Zażółć gęślą jaźń — 你好") score = _content_score(content) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) entry = sqlite_instance._query_entries(ScorableContentEntry)[0] assert entry.value == content.value assert entry.value_sha256 == hashlib.sha256(content.value.encode("utf-8")).hexdigest() - assert sqlite_instance.get_scorable_content(content_ids=[entry.id])[entry.id] == content + assert (await sqlite_instance.get_scorable_content_async(content_ids=[entry.id]))[entry.id] == content def test_content_value_uses_unicode_on_sql_server(): @@ -121,7 +121,10 @@ def test_sync_persistence_rejects_unmanaged_file_content( source = tmp_path / "source.png" source.write_bytes(b"image") - with pytest.raises(ValueError, match="add_scores_to_memory_async"): + with ( + pytest.warns(DeprecationWarning, match="add_scores_to_memory"), + pytest.raises(ValueError, match="add_scores_to_memory_async"), + ): sqlite_instance.add_scores_to_memory( scores=[_content_score(ContentScorable(value=str(source), data_type="image_path"))] ) @@ -146,7 +149,7 @@ async def test_file_content_is_copied_hashed_shared_and_resolvable( entry = entries[0] assert entry.value_sha256 == hashlib.sha256(image_bytes).hexdigest() - stored_content = sqlite_instance.get_scorable_content(content_ids=[entry.id])[entry.id] + stored_content = (await sqlite_instance.get_scorable_content_async(content_ids=[entry.id]))[entry.id] managed_path = Path(stored_content.value) assert managed_path != source assert "scorable-content-entries" in managed_path.parts @@ -170,7 +173,7 @@ async def test_file_content_missing_source_fails_before_database_write( with pytest.raises(FileNotFoundError, match="missing.wav"): await sqlite_instance.add_scores_to_memory_async(scores=[score]) - assert sqlite_instance.get_scores(score_ids=[str(score.id)]) == [] + assert (await sqlite_instance.get_scores_async(score_ids=[str(score.id)])) == [] assert sqlite_instance._query_entries(ScorableContentEntry) == [] diff --git a/tests/unit/memory/memory_interface/test_interface_scores.py b/tests/unit/memory/memory_interface/test_interface_scores.py index 0d54295d7a..81fd8f9e52 100644 --- a/tests/unit/memory/memory_interface/test_interface_scores.py +++ b/tests/unit/memory/memory_interface/test_interface_scores.py @@ -29,14 +29,14 @@ def _test_scorer_id(name: str = "TestScorer") -> ComponentIdentifier: ) -def test_get_scores_by_label(sqlite_instance: MemoryInterface, sample_conversations: Sequence[MessagePiece]): +async def test_get_scores_by_label(sqlite_instance: MemoryInterface, sample_conversations: Sequence[MessagePiece]): # create list of scores that are associated with sample conversation entries # assert that that list of scores is the same as expected :-) prompt_id = sample_conversations[0].id assert prompt_id is not None, "Prompt ID should not be None" - sqlite_instance.add_message_pieces_to_memory(message_pieces=sample_conversations) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=sample_conversations)) score = Score( score_value=str(0.8), @@ -49,16 +49,18 @@ def test_get_scores_by_label(sqlite_instance: MemoryInterface, sample_conversati message_piece_id=prompt_id, ) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) # Fetch the score we just added by label labels = {"sample": "label"} conversation_id = sample_conversations[0].conversation_id assert conversation_id is not None - sqlite_instance.add_attack_results_to_memory( - attack_results=[AttackResult(conversation_id=conversation_id, objective="Test objective", labels=labels)] + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[AttackResult(conversation_id=conversation_id, objective="Test objective", labels=labels)] + ) ) - db_score = sqlite_instance.get_prompt_scores(labels=labels) + db_score = await sqlite_instance.get_prompt_scores_async(labels=labels) assert len(db_score) == 1 assert db_score[0].score_value == score.score_value @@ -70,19 +72,19 @@ def test_get_scores_by_label(sqlite_instance: MemoryInterface, sample_conversati assert db_score[0].scorer_class_identifier == score.scorer_class_identifier assert db_score[0].message_piece_id == score.message_piece_id - db_score = sqlite_instance.get_scores(score_ids=[str(score.id)]) + db_score = await sqlite_instance.get_scores_async(score_ids=[str(score.id)]) assert len(db_score) == 1 assert db_score[0].score_value == score.score_value - db_score = sqlite_instance.get_prompt_scores(labels={"x": "y"}) + db_score = await sqlite_instance.get_prompt_scores_async(labels={"x": "y"}) assert len(db_score) == 0 - db_score = sqlite_instance.get_scores() + db_score = await sqlite_instance.get_scores_async() assert len(db_score) == 0 @pytest.mark.parametrize("score_type", ["float_scale", "true_false"]) -def test_add_score_get_score( +async def test_add_score_get_score( sqlite_instance: MemoryInterface, sample_conversation_entries: Sequence[PromptMemoryEntry], score_type: Literal["float_scale"] | Literal["true_false"], @@ -105,10 +107,10 @@ def test_add_score_get_score( message_piece_id=prompt_id, ) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) # Fetch the score we just added - db_score = sqlite_instance.get_prompt_scores(prompt_ids=[prompt_id]) + db_score = await sqlite_instance.get_prompt_scores_async(prompt_ids=[prompt_id]) assert db_score assert len(db_score) == 1 assert db_score[0].score_value == score_value @@ -122,7 +124,7 @@ def test_add_score_get_score( assert db_score[0].message_piece_id == prompt_id -def test_scorer_identifier_persists_graph_and_dedupes( +async def test_scorer_identifier_persists_graph_and_dedupes( sqlite_instance: MemoryInterface, sample_conversation_entries: Sequence[PromptMemoryEntry], ): @@ -167,7 +169,7 @@ def test_scorer_identifier_persists_graph_and_dedupes( ), ] - sqlite_instance.add_scores_to_memory(scores=scores) + (await sqlite_instance.add_scores_to_memory_async(scores=scores)) scorer_rows = sqlite_instance._query_entries(ScorerIdentifierEntry) scorers_by_hash = {row.hash: row for row in scorer_rows} @@ -189,7 +191,7 @@ def test_scorer_identifier_persists_graph_and_dedupes( ] -def test_get_prompt_scores_empty_prompt_ids_returns_empty(sqlite_instance: MemoryInterface): +async def test_get_prompt_scores_empty_prompt_ids_returns_empty(sqlite_instance: MemoryInterface): prompt_id = uuid4() piece = MessagePiece( id=prompt_id, @@ -198,7 +200,7 @@ def test_get_prompt_scores_empty_prompt_ids_returns_empty(sqlite_instance: Memor converted_value="Hello, how are you?", conversation_id=str(uuid4()), ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[piece])) score = Score( score_value=str(0.8), @@ -210,12 +212,12 @@ def test_get_prompt_scores_empty_prompt_ids_returns_empty(sqlite_instance: Memor scorer_class_identifier=_test_scorer_id("TestScorer"), message_piece_id=prompt_id, ) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) - assert sqlite_instance.get_prompt_scores(prompt_ids=[]) == [] + assert (await sqlite_instance.get_prompt_scores_async(prompt_ids=[])) == [] -def test_add_score_duplicate_prompt(sqlite_instance: MemoryInterface): +async def test_add_score_duplicate_prompt(sqlite_instance: MemoryInterface): # Ensure that scores of duplicate prompts are linked back to the original original_id = uuid4() conversation_id = str(uuid4()) @@ -229,10 +231,10 @@ def test_add_score_duplicate_prompt(sqlite_instance: MemoryInterface): sequence=0, ) ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) - sqlite_instance.duplicate_conversation(conversation_id=conversation_id) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) + (await sqlite_instance.duplicate_conversation_async(conversation_id=conversation_id)) # Get the duplicated piece (it will have a different conversation_id) - all_pieces = sqlite_instance.get_message_pieces() + all_pieces = await sqlite_instance.get_message_pieces_async() dupe_piece = [p for p in all_pieces if p.id != original_id][0] dupe_id = dupe_piece.id assert dupe_id is not None, "Dupe ID should not be None" @@ -251,36 +253,38 @@ def test_add_score_duplicate_prompt(sqlite_instance: MemoryInterface): message_piece_id=dupe_id, scorable=MessageScorable(message_piece_ids=(dupe_id,)), ) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) assert score.message_piece_id == original_id assert score.scorable == MessageScorable(message_piece_ids=(original_id,)) - assert sqlite_instance.get_scores(score_ids=[str(score_id)])[0].scorable == score.scorable - assert sqlite_instance.get_prompt_scores(prompt_ids=[str(dupe_id)])[0].id == score_id - assert sqlite_instance.get_prompt_scores(prompt_ids=[str(original_id)])[0].id == score_id + assert (await sqlite_instance.get_scores_async(score_ids=[str(score_id)]))[0].scorable == score.scorable + assert (await sqlite_instance.get_prompt_scores_async(prompt_ids=[str(dupe_id)]))[0].id == score_id + assert (await sqlite_instance.get_prompt_scores_async(prompt_ids=[str(original_id)]))[0].id == score_id -def test_get_prompt_scores_finds_secondary_message_anchor(sqlite_instance: MemoryInterface): +async def test_get_prompt_scores_finds_secondary_message_anchor(sqlite_instance: MemoryInterface): first_id = uuid4() second_id = uuid4() conversation_id = str(uuid4()) - sqlite_instance.add_message_pieces_to_memory( - message_pieces=[ - MessagePiece( - id=first_id, - role="assistant", - original_value="first piece", - conversation_id=conversation_id, - sequence=0, - ), - MessagePiece( - id=second_id, - role="assistant", - original_value="second piece", - conversation_id=conversation_id, - sequence=0, - ), - ] + ( + await sqlite_instance.add_message_pieces_to_memory_async( + message_pieces=[ + MessagePiece( + id=first_id, + role="assistant", + original_value="first piece", + conversation_id=conversation_id, + sequence=0, + ), + MessagePiece( + id=second_id, + role="assistant", + original_value="second piece", + conversation_id=conversation_id, + sequence=0, + ), + ] + ) ) score = Score( score_value="True", @@ -289,14 +293,14 @@ def test_get_prompt_scores_finds_secondary_message_anchor(sqlite_instance: Memor message_piece_id=first_id, scorable=MessageScorable(message_piece_ids=(first_id, second_id)), ) - sqlite_instance.add_scores_to_memory(scores=[score]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) - scores = sqlite_instance.get_prompt_scores(prompt_ids=[second_id]) + scores = await sqlite_instance.get_prompt_scores_async(prompt_ids=[second_id]) assert [stored_score.id for stored_score in scores] == [score.id] -def test_get_scores_by_memory_labels(sqlite_instance: MemoryInterface): +async def test_get_scores_by_memory_labels(sqlite_instance: MemoryInterface): prompt_id = uuid4() conversation_id = str(uuid4()) pieces = [ @@ -309,7 +313,7 @@ def test_get_scores_by_memory_labels(sqlite_instance: MemoryInterface): conversation_id=conversation_id, ) ] - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) score = Score( score_value=str(0.8), @@ -321,15 +325,17 @@ def test_get_scores_by_memory_labels(sqlite_instance: MemoryInterface): scorer_class_identifier=_test_scorer_id("TestScorer"), message_piece_id=prompt_id, ) - sqlite_instance.add_scores_to_memory(scores=[score]) - sqlite_instance.add_attack_results_to_memory( - attack_results=[ - AttackResult(conversation_id=conversation_id, objective="Test objective", labels={"sample": "label"}) - ] + (await sqlite_instance.add_scores_to_memory_async(scores=[score])) + ( + await sqlite_instance.add_attack_results_to_memory_async( + attack_results=[ + AttackResult(conversation_id=conversation_id, objective="Test objective", labels={"sample": "label"}) + ] + ) ) # Fetch the score we just added - db_score = sqlite_instance.get_prompt_scores(labels={"sample": "label"}) + db_score = await sqlite_instance.get_prompt_scores_async(labels={"sample": "label"}) assert len(db_score) == 1 assert db_score[0].score_value == score.score_value @@ -349,13 +355,13 @@ async def test_get_seeds_no_filters(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds() + result = await sqlite_instance.get_seeds_async() assert len(result) == 2 assert result[0].value == "prompt1" assert result[1].value == "prompt2" -def test_get_scores_by_scorer_identifier_filter( +async def test_get_scores_by_scorer_identifier_filter( sqlite_instance: MemoryInterface, sample_conversation_entries: Sequence[PromptMemoryEntry], ): @@ -383,10 +389,10 @@ def test_get_scores_by_scorer_identifier_filter( message_piece_id=prompt_id, ) - sqlite_instance.add_scores_to_memory(scores=[score_a, score_b]) + (await sqlite_instance.add_scores_to_memory_async(scores=[score_a, score_b])) # Filter by exact class_name match - results = sqlite_instance.get_scores( + results = await sqlite_instance.get_scores_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.SCORER, @@ -400,7 +406,7 @@ def test_get_scores_by_scorer_identifier_filter( assert results[0].score_value == "0.9" # Filter by partial class_name match - results = sqlite_instance.get_scores( + results = await sqlite_instance.get_scores_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.SCORER, @@ -414,7 +420,7 @@ def test_get_scores_by_scorer_identifier_filter( # Filter by hash scorer_hash = score_a.scorer_class_identifier.hash - results = sqlite_instance.get_scores( + results = await sqlite_instance.get_scores_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.SCORER, @@ -428,7 +434,7 @@ def test_get_scores_by_scorer_identifier_filter( assert results[0].score_value == "0.9" # No match - results = sqlite_instance.get_scores( + results = await sqlite_instance.get_scores_async( identifier_filters=[ IdentifierFilter( identifier_type=IdentifierType.SCORER, diff --git a/tests/unit/memory/memory_interface/test_interface_seed_dataset_summary_query.py b/tests/unit/memory/memory_interface/test_interface_seed_dataset_summary_query.py index 8045e78136..820494cd22 100644 --- a/tests/unit/memory/memory_interface/test_interface_seed_dataset_summary_query.py +++ b/tests/unit/memory/memory_interface/test_interface_seed_dataset_summary_query.py @@ -1,9 +1,10 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -from unittest.mock import MagicMock, patch +from unittest.mock import patch from pyrit.memory import MemoryInterface +from pyrit.memory.memory_session import MemorySession from pyrit.models import SeedPrompt @@ -22,13 +23,11 @@ async def test_get_seed_dataset_summaries_avoids_metadata_row_multiplication( added_by="tester", ) - real_session = sqlite_instance.get_session() - session = MagicMock(wraps=real_session) - original_execute = real_session.execute + original_execute = MemorySession.execute captured_rows: list[object] = [] - def execute(statement, *args, **kwargs): - result = original_execute(statement, *args, **kwargs) + def execute(session, statement, *args, **kwargs): + result = original_execute(session, statement, *args, **kwargs) original_all = result.all def all_rows(): @@ -39,13 +38,8 @@ def all_rows(): result.all = all_rows return result - session.execute.side_effect = execute - - try: - with patch.object(sqlite_instance, "get_session", return_value=session): - summaries = sqlite_instance.get_seed_dataset_summaries() - finally: - real_session.close() + with patch.object(MemorySession, "execute", execute): + summaries = await sqlite_instance.get_seed_dataset_summaries_async() assert len(captured_rows) == 3 assert len(summaries) == 1 diff --git a/tests/unit/memory/memory_interface/test_interface_seed_prompts.py b/tests/unit/memory/memory_interface/test_interface_seed_prompts.py index 585e625972..cef3dc2e2a 100644 --- a/tests/unit/memory/memory_interface/test_interface_seed_prompts.py +++ b/tests/unit/memory/memory_interface/test_interface_seed_prompts.py @@ -40,7 +40,7 @@ async def test_get_seeds_with_audio(sqlite_instance: MemoryInterface): await sqlite_instance.add_seeds_to_memory_async(seeds=[audio_prompt], added_by="test_audio") # Retrieve and verify the seed prompts - result = sqlite_instance.get_seeds() + result = await sqlite_instance.get_seeds_async() assert len(result) == 1 assert result[0].value.endswith(".wav") assert result[0].data_type == "audio_path" @@ -68,7 +68,7 @@ async def test_get_seeds_with_video(sqlite_instance: MemoryInterface): await sqlite_instance.add_seeds_to_memory_async(seeds=[video_prompt], added_by="test_video") # Retrieve and verify the seed prompts - result = sqlite_instance.get_seeds() + result = await sqlite_instance.get_seeds_async() assert len(result) == 1 assert result[0].value.endswith(".mp4") assert result[0].data_type == "video_path" @@ -96,7 +96,7 @@ async def test_get_seeds_with_image(sqlite_instance: MemoryInterface): await sqlite_instance.add_seeds_to_memory_async(seeds=[image_prompt], added_by="test_image") # Retrieve and verify the seed prompts - result = sqlite_instance.get_seeds() + result = await sqlite_instance.get_seeds_async() print(result) assert len(result) == 1 assert result[0].value.endswith(".png") @@ -115,7 +115,7 @@ async def test_get_seeds_with_value_filter(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(value="prompt1") + result = await sqlite_instance.get_seeds_async(value="prompt1") assert len(result) == 1 assert result[0].value == "prompt1" @@ -149,7 +149,9 @@ async def test_get_seed_dataset_summaries(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seeds, added_by="test") - summaries = {summary.dataset_name: summary for summary in sqlite_instance.get_seed_dataset_summaries()} + summaries = { + summary.dataset_name: summary for summary in (await sqlite_instance.get_seed_dataset_summaries_async()) + } dataset1 = summaries["dataset1"] assert dataset1.logical_examples == 1 @@ -181,7 +183,7 @@ async def test_get_seed_dataset_summaries_merges_none_and_empty_dataset_groups( ) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group], added_by="tester") - summaries = sqlite_instance.get_seed_dataset_summaries() + summaries = await sqlite_instance.get_seed_dataset_summaries_async() assert len(summaries) == 1 assert summaries[0].dataset_name is None @@ -221,7 +223,7 @@ async def test_get_seed_dataset_summaries_follows_a_case_insensitive_collation( added_by="tester", ) - summaries = sqlite_instance.get_seed_dataset_summaries() + summaries = await sqlite_instance.get_seed_dataset_summaries_async() assert len(summaries) == 1 summary = summaries[0] assert summary.seed_pieces == 3 @@ -258,7 +260,7 @@ async def test_get_seed_dataset_summaries_follows_a_trailing_blank_insensitive_c added_by="tester", ) - summaries = sqlite_instance.get_seed_dataset_summaries() + summaries = await sqlite_instance.get_seed_dataset_summaries_async() assert len(summaries) == 1 summary = summaries[0] assert summary.seed_pieces == 3 @@ -277,7 +279,7 @@ async def test_get_seeds_with_dataset_name_filter(sqlite_instance: MemoryInterfa ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(dataset_name="dataset1") + result = await sqlite_instance.get_seeds_async(dataset_name="dataset1") assert len(result) == 1 assert result[0].dataset_name == "dataset1" @@ -290,7 +292,7 @@ async def test_get_seeds_with_dataset_name_pattern_startswith(sqlite_instance: M ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(dataset_name_pattern="harm%") + result = await sqlite_instance.get_seeds_async(dataset_name_pattern="harm%") assert len(result) == 2 assert all(seed.dataset_name.startswith("harm") for seed in result) @@ -303,7 +305,7 @@ async def test_get_seeds_with_dataset_name_pattern_contains(sqlite_instance: Mem ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(dataset_name_pattern="%harm%") + result = await sqlite_instance.get_seeds_async(dataset_name_pattern="%harm%") assert len(result) == 2 assert all("harm" in seed.dataset_name for seed in result) @@ -316,7 +318,7 @@ async def test_get_seeds_with_dataset_name_pattern_endswith(sqlite_instance: Mem ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(dataset_name_pattern="%test") + result = await sqlite_instance.get_seeds_async(dataset_name_pattern="%test") assert len(result) == 2 assert all(seed.dataset_name.endswith("test") for seed in result) @@ -330,7 +332,7 @@ async def test_get_seeds_dataset_name_takes_precedence_over_pattern(sqlite_insta await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") # When both are provided, exact match should be used - result = sqlite_instance.get_seeds(dataset_name="harm_exact", dataset_name_pattern="harm%") + result = await sqlite_instance.get_seeds_async(dataset_name="harm_exact", dataset_name_pattern="harm%") assert len(result) == 1 assert result[0].dataset_name == "harm_exact" @@ -342,7 +344,7 @@ async def test_get_seeds_with_added_by_filter(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts) - result = sqlite_instance.get_seeds(added_by="user1") + result = await sqlite_instance.get_seeds_async(added_by="user1") assert len(result) == 1 assert result[0].added_by == "user1" @@ -354,7 +356,7 @@ async def test_get_seeds_with_source_filter(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(source="source1") + result = await sqlite_instance.get_seeds_async(source="source1") assert len(result) == 1 assert result[0].source == "source1" @@ -366,7 +368,7 @@ async def test_get_seeds_with_harm_categories_filter(sqlite_instance: MemoryInte ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(harm_categories=["category1"]) + result = await sqlite_instance.get_seeds_async(harm_categories=["category1"]) assert len(result) == 1 assert result[0].harm_categories == ["category1"] @@ -378,7 +380,7 @@ async def test_get_seeds_with_authors_filter(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(authors=["author1"]) + result = await sqlite_instance.get_seeds_async(authors=["author1"]) assert len(result) == 1 assert result[0].authors == ["author1"] @@ -390,7 +392,7 @@ async def test_get_seeds_with_groups_filter(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(groups=["group1"]) + result = await sqlite_instance.get_seeds_async(groups=["group1"]) assert len(result) == 1 assert result[0].groups == ["group1"] @@ -402,7 +404,7 @@ async def test_get_seeds_with_parameters_filter(sqlite_instance: MemoryInterface ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(parameters=["param1"]) + result = await sqlite_instance.get_seeds_async(parameters=["param1"]) assert len(result) == 1 assert isinstance(result[0], SeedPrompt) assert result[0].parameters == ["param1"] @@ -415,7 +417,7 @@ async def test_get_seeds_with_metadata_filter(sqlite_instance: MemoryInterface): ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(metadata={"key1": "value1"}) + result = await sqlite_instance.get_seeds_async(metadata={"key1": "value1"}) assert len(result) == 1 assert result[0].metadata == {"key1": "value1", "key2": "value2"} @@ -427,7 +429,7 @@ async def test_get_seeds_with_multiple_filters(sqlite_instance: MemoryInterface) ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts) - result = sqlite_instance.get_seeds(dataset_name="dataset1", added_by="user1") + result = await sqlite_instance.get_seeds_async(dataset_name="dataset1", added_by="user1") assert len(result) == 1 assert result[0].dataset_name == "dataset1" assert result[0].added_by == "user1" @@ -440,7 +442,7 @@ async def test_get_seeds_with_empty_list_filters(sqlite_instance: MemoryInterfac ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(harm_categories=[], authors=[]) + result = await sqlite_instance.get_seeds_async(harm_categories=[], authors=[]) assert len(result) == 2 @@ -451,7 +453,7 @@ async def test_get_seeds_with_single_element_list_filters(sqlite_instance: Memor ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(harm_categories=["category1"], authors=["author1"]) + result = await sqlite_instance.get_seeds_async(harm_categories=["category1"], authors=["author1"]) assert len(result) == 1 assert result[0].harm_categories == ["category1"] assert result[0].authors == ["author1"] @@ -469,7 +471,9 @@ async def test_get_seeds_with_multiple_elements_list_filters(sqlite_instance: Me ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(harm_categories=["category1", "category2"], authors=["author1", "author2"]) + result = await sqlite_instance.get_seeds_async( + harm_categories=["category1", "category2"], authors=["author1", "author2"] + ) assert len(result) == 1 assert result[0].harm_categories == ["category1", "category2"] assert result[0].authors == ["author1", "author2"] @@ -493,7 +497,9 @@ async def test_get_seeds_with_multiple_elements_list_filters_additional(sqlite_i ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(harm_categories=["category1", "category3"], authors=["author1", "author3"]) + result = await sqlite_instance.get_seeds_async( + harm_categories=["category1", "category3"], authors=["author1", "author3"] + ) assert len(result) == 1 assert result[0].harm_categories == ["category1", "category3"] assert result[0].authors == ["author1", "author3"] @@ -506,11 +512,11 @@ async def test_get_seeds_with_substring_filters_harm_categories(sqlite_instance: ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(harm_categories=["ory1"]) + result = await sqlite_instance.get_seeds_async(harm_categories=["ory1"]) assert len(result) == 1 assert result[0].harm_categories == ["category1"] - result = sqlite_instance.get_seeds(authors=["auth"]) + result = await sqlite_instance.get_seeds_async(authors=["auth"]) assert len(result) == 2 assert result[0].authors == ["author1"] assert result[1].authors == ["author2"] @@ -523,11 +529,11 @@ async def test_get_seeds_with_substring_filters_groups(sqlite_instance: MemoryIn ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(groups=["oup1"]) + result = await sqlite_instance.get_seeds_async(groups=["oup1"]) assert len(result) == 1 assert result[0].groups == ["group1"] - result = sqlite_instance.get_seeds(groups=["oup"]) + result = await sqlite_instance.get_seeds_async(groups=["oup"]) assert len(result) == 2 assert result[0].groups == ["group1"] assert result[1].groups == ["group2"] @@ -540,12 +546,12 @@ async def test_get_seeds_with_substring_filters_parameters(sqlite_instance: Memo ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts, added_by="test") - result = sqlite_instance.get_seeds(parameters=["ram1"]) + result = await sqlite_instance.get_seeds_async(parameters=["ram1"]) assert len(result) == 1 assert isinstance(result[0], SeedPrompt) assert result[0].parameters == ["param1"] - result = sqlite_instance.get_seeds(parameters=["ram"]) + result = await sqlite_instance.get_seeds_async(parameters=["ram"]) assert len(result) == 2 assert isinstance(result[0], SeedPrompt) assert isinstance(result[1], SeedPrompt) @@ -556,7 +562,7 @@ async def test_get_seeds_with_substring_filters_parameters(sqlite_instance: Memo async def test_add_seed_prompts_to_memory_empty_list(sqlite_instance: MemoryInterface): prompts: Sequence[SeedPrompt] = [] await sqlite_instance.add_seeds_to_memory_async(seeds=prompts, added_by="tester") - stored_prompts = sqlite_instance.get_seeds(dataset_name="test_dataset") + stored_prompts = await sqlite_instance.get_seeds_async(dataset_name="test_dataset") assert len(stored_prompts) == 0 @@ -566,7 +572,7 @@ async def test_add_seed_prompts_duplicate_entries_same_dataset(sqlite_instance: SeedPrompt(value="prompt2", dataset_name="test_dataset", data_type="text"), ] await sqlite_instance.add_seeds_to_memory_async(seeds=prompts, added_by="tester") - stored_prompts = sqlite_instance.get_seeds(dataset_name="test_dataset") + stored_prompts = await sqlite_instance.get_seeds_async(dataset_name="test_dataset") assert len(stored_prompts) == 2 # Try to add prompt list with one duplicate prompt and one new prompt @@ -577,7 +583,7 @@ async def test_add_seed_prompts_duplicate_entries_same_dataset(sqlite_instance: await sqlite_instance.add_seeds_to_memory_async(seeds=duplicate_prompts, added_by="tester") # Validate that only new prompt is added and the total prompt count is 3 - stored_prompts = sqlite_instance.get_seeds(dataset_name="test_dataset") + stored_prompts = await sqlite_instance.get_seeds_async(dataset_name="test_dataset") assert len(stored_prompts) == 3 @@ -590,7 +596,7 @@ async def test_add_seed_prompts_duplicates_within_one_call_are_all_stored(sqlite ] await sqlite_instance.add_seeds_to_memory_async(seeds=prompts, added_by="tester") - assert len(sqlite_instance.get_seeds(dataset_name="test_dataset")) == 3 + assert len(await sqlite_instance.get_seeds_async(dataset_name="test_dataset")) == 3 async def test_add_seed_prompts_without_dataset_name_matches_any_dataset(sqlite_instance: MemoryInterface): @@ -605,7 +611,7 @@ async def test_add_seed_prompts_without_dataset_name_matches_any_dataset(sqlite_ added_by="tester", ) - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 async def test_add_seed_prompts_dedupes_across_chunk_boundaries(sqlite_instance: MemoryInterface): @@ -615,7 +621,7 @@ async def test_add_seed_prompts_dedupes_across_chunk_boundaries(sqlite_instance: SeedPrompt(value=f"prompt{index}", dataset_name="test_dataset", data_type="text") for index in range(count) ] await sqlite_instance.add_seeds_to_memory_async(seeds=first, added_by="tester") - assert len(sqlite_instance.get_seeds(dataset_name="test_dataset")) == count + assert len(await sqlite_instance.get_seeds_async(dataset_name="test_dataset")) == count # Re-adding the same seeds plus one new one must only store the new one. second: Sequence[SeedPrompt] = [ @@ -623,7 +629,7 @@ async def test_add_seed_prompts_dedupes_across_chunk_boundaries(sqlite_instance: ] + [SeedPrompt(value="brand_new", dataset_name="test_dataset", data_type="text")] await sqlite_instance.add_seeds_to_memory_async(seeds=second, added_by="tester") - assert len(sqlite_instance.get_seeds(dataset_name="test_dataset")) == count + 1 + assert len(await sqlite_instance.get_seeds_async(dataset_name="test_dataset")) == count + 1 async def test_add_seed_prompts_queries_are_batched(sqlite_instance: MemoryInterface): @@ -632,7 +638,7 @@ async def test_add_seed_prompts_queries_are_batched(sqlite_instance: MemoryInter SeedPrompt(value=f"prompt{index}", dataset_name="test_dataset", data_type="text") for index in range(50) ] - with patch.object(sqlite_instance, "get_seeds", wraps=sqlite_instance.get_seeds) as spied: + with patch.object(sqlite_instance, "_execute_get_seeds", wraps=sqlite_instance._execute_get_seeds) as spied: await sqlite_instance.add_seeds_to_memory_async(seeds=prompts, added_by="tester") assert spied.call_count == 1 @@ -645,14 +651,14 @@ async def test_add_seed_prompts_dedupe_honors_backend_bind_var_limit(sqlite_inst ] with patch.object(type(sqlite_instance), "_MAX_BIND_VARS", 50): - with patch.object(sqlite_instance, "get_seeds", wraps=sqlite_instance.get_seeds) as spied: + with patch.object(sqlite_instance, "_execute_get_seeds", wraps=sqlite_instance._execute_get_seeds) as spied: await sqlite_instance.add_seeds_to_memory_async(seeds=prompts, added_by="tester") assert spied.call_count == 3 # 49 hashes plus the name is 50 binds; a full 50 hashes would exceed the ceiling by one. assert [len(call.kwargs["value_sha256"]) for call in spied.call_args_list] == [49, 49, 22] assert all(len(call.kwargs["value_sha256"]) + 1 <= 50 for call in spied.call_args_list) - assert len(sqlite_instance.get_seeds(dataset_name="test_dataset")) == 120 + assert len(await sqlite_instance.get_seeds_async(dataset_name="test_dataset")) == 120 async def test_add_seed_prompts_dedupe_uses_the_full_budget_without_a_dataset_name( @@ -662,7 +668,7 @@ async def test_add_seed_prompts_dedupe_uses_the_full_budget_without_a_dataset_na prompts: Sequence[SeedPrompt] = [SeedPrompt(value=f"prompt{index}", data_type="text") for index in range(120)] with patch.object(type(sqlite_instance), "_MAX_BIND_VARS", 50): - with patch.object(sqlite_instance, "get_seeds", wraps=sqlite_instance.get_seeds) as spied: + with patch.object(sqlite_instance, "_execute_get_seeds", wraps=sqlite_instance._execute_get_seeds) as spied: await sqlite_instance.add_seeds_to_memory_async(seeds=prompts, added_by="tester") assert [len(call.kwargs["value_sha256"]) for call in spied.call_args_list] == [50, 50, 20] @@ -700,7 +706,7 @@ async def test_add_seed_prompts_dedupe_follows_a_case_insensitive_collation(sqli seeds=[SeedPrompt(value="prompt1", dataset_name="dataset", data_type="text")], added_by="tester" ) - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 finally: table.c.dataset_name.type = original_type @@ -713,7 +719,7 @@ async def test_add_seed_prompts_dedupe_follows_a_trailing_blank_insensitive_coll seeds=[SeedPrompt(value="prompt1", dataset_name="alpha", data_type="text")], added_by="tester" ) - real_get_seeds = sqlite_instance.get_seeds + real_get_seeds = sqlite_instance._execute_get_seeds def blank_insensitive_get_seeds(*, dataset_name=None, **kwargs): rows = real_get_seeds(**kwargs) @@ -721,12 +727,12 @@ def blank_insensitive_get_seeds(*, dataset_name=None, **kwargs): return rows return [row for row in rows if (row.dataset_name or "").rstrip() == dataset_name.rstrip()] - with patch.object(sqlite_instance, "get_seeds", side_effect=blank_insensitive_get_seeds): + with patch.object(sqlite_instance, "_execute_get_seeds", side_effect=blank_insensitive_get_seeds): await sqlite_instance.add_seeds_to_memory_async( seeds=[SeedPrompt(value="prompt1", dataset_name="alpha ", data_type="text")], added_by="tester" ) - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 async def test_add_seed_prompts_dedupe_groups_each_dataset_name_separately(sqlite_instance: MemoryInterface): @@ -737,12 +743,12 @@ async def test_add_seed_prompts_dedupe_groups_each_dataset_name_separately(sqlit SeedPrompt(value="loose", data_type="text"), ] - with patch.object(sqlite_instance, "get_seeds", wraps=sqlite_instance.get_seeds) as spied: + with patch.object(sqlite_instance, "_execute_get_seeds", wraps=sqlite_instance._execute_get_seeds) as spied: await sqlite_instance.add_seeds_to_memory_async(seeds=prompts, added_by="tester") queried = [call.kwargs["dataset_name"] for call in spied.call_args_list] assert sorted(queried, key=lambda name: (name is None, name or "")) == ["alpha", "beta", None] - assert len(sqlite_instance.get_seeds()) == 3 + assert len(await sqlite_instance.get_seeds_async()) == 3 async def test_add_seed_prompts_dedupe_treats_an_empty_dataset_name_as_unfiltered( @@ -757,7 +763,7 @@ async def test_add_seed_prompts_dedupe_treats_an_empty_dataset_name_as_unfiltere seeds=[SeedPrompt(value="prompt1", dataset_name="", data_type="text")], added_by="tester" ) - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 async def test_add_seed_prompts_duplicate_entries_different_datasets(sqlite_instance: MemoryInterface): @@ -766,7 +772,7 @@ async def test_add_seed_prompts_duplicate_entries_different_datasets(sqlite_inst SeedPrompt(value="prompt2", dataset_name="test_dataset", data_type="text"), ] await sqlite_instance.add_seeds_to_memory_async(seeds=prompts, added_by="tester") - stored_prompts = sqlite_instance.get_seeds(dataset_name="test_dataset") + stored_prompts = await sqlite_instance.get_seeds_async(dataset_name="test_dataset") assert len(stored_prompts) == 2 # Try to add prompt list with one duplicate prompt and one new prompt @@ -777,19 +783,19 @@ async def test_add_seed_prompts_duplicate_entries_different_datasets(sqlite_inst await sqlite_instance.add_seeds_to_memory_async(seeds=duplicate_prompts, added_by="tester") # Validate that only new prompt is added and the total prompt count is 3 - stored_prompts = sqlite_instance.get_seeds() + stored_prompts = await sqlite_instance.get_seeds_async() assert len(stored_prompts) == 4 -def test_get_seed_dataset_names_empty(sqlite_instance: MemoryInterface): - assert sqlite_instance.get_seed_dataset_names() == [] +async def test_get_seed_dataset_names_empty(sqlite_instance: MemoryInterface): + assert (await sqlite_instance.get_seed_dataset_names_async()) == [] async def test_get_seed_dataset_names_single(sqlite_instance: MemoryInterface): dataset_name = "test_dataset" seed_prompt = SeedPrompt(value="test_value", dataset_name=dataset_name, added_by="tester", data_type="text") await sqlite_instance.add_seeds_to_memory_async(seeds=[seed_prompt]) - assert sqlite_instance.get_seed_dataset_names() == [dataset_name] + assert (await sqlite_instance.get_seed_dataset_names_async()) == [dataset_name] async def test_get_seed_dataset_names_single_dataset_multiple_entries(sqlite_instance: MemoryInterface): @@ -797,7 +803,7 @@ async def test_get_seed_dataset_names_single_dataset_multiple_entries(sqlite_ins seed_prompt1 = SeedPrompt(value="test_value", dataset_name=dataset_name, added_by="tester", data_type="text") seed_prompt2 = SeedPrompt(value="test_value", dataset_name=dataset_name, added_by="tester", data_type="text") await sqlite_instance.add_seeds_to_memory_async(seeds=[seed_prompt1, seed_prompt2]) - assert sqlite_instance.get_seed_dataset_names() == [dataset_name] + assert (await sqlite_instance.get_seed_dataset_names_async()) == [dataset_name] async def test_get_seed_dataset_names_multiple(sqlite_instance: MemoryInterface): @@ -807,8 +813,8 @@ async def test_get_seed_dataset_names_multiple(sqlite_instance: MemoryInterface) for i, dataset_name in enumerate(dataset_names) ] await sqlite_instance.add_seeds_to_memory_async(seeds=seed_prompts) - assert len(sqlite_instance.get_seed_dataset_names()) == 5 - assert sorted(sqlite_instance.get_seed_dataset_names()) == sorted(dataset_names) + assert len(await sqlite_instance.get_seed_dataset_names_async()) == 5 + assert sorted(await sqlite_instance.get_seed_dataset_names_async()) == sorted(dataset_names) async def test_add_seed_groups_to_memory_empty_list(sqlite_instance: MemoryInterface): @@ -822,7 +828,7 @@ async def test_add_seed_groups_to_memory_single_element(sqlite_instance: MemoryI prompt = SeedPrompt(value="Test prompt", added_by="tester", data_type="text", sequence=0) prompt_group = SeedGroup(seeds=[prompt]) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[prompt_group], added_by="tester") - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 async def test_add_seed_groups_to_memory_multiple_elements(sqlite_instance: MemoryInterface): @@ -830,8 +836,8 @@ async def test_add_seed_groups_to_memory_multiple_elements(sqlite_instance: Memo prompt2 = SeedPrompt(value="Test prompt 2", added_by="tester", data_type="text", sequence=1, role="user") prompt_group = SeedGroup(seeds=[prompt1, prompt2]) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[prompt_group], added_by="tester") - assert len(sqlite_instance.get_seeds()) == 2 - assert len(sqlite_instance.get_seed_groups()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 2 + assert len(await sqlite_instance.get_seed_groups_async()) == 1 async def test_add_seed_groups_to_memory_no_elements(sqlite_instance: MemoryInterface): @@ -870,7 +876,7 @@ async def test_add_seed_groups_to_memory_single_element_with_added_by(sqlite_ins prompt = SeedPrompt(value="Test prompt", added_by="tester", data_type="text", sequence=0) prompt_group = SeedGroup(seeds=[prompt]) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[prompt_group]) - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 async def test_add_seed_groups_to_memory_multiple_elements_with_added_by(sqlite_instance: MemoryInterface): @@ -878,7 +884,7 @@ async def test_add_seed_groups_to_memory_multiple_elements_with_added_by(sqlite_ prompt2 = SeedPrompt(value="Test prompt 2", added_by="tester", data_type="text", sequence=1, role="user") prompt_group = SeedGroup(seeds=[prompt1, prompt2]) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[prompt_group]) - assert len(sqlite_instance.get_seeds()) == 2 + assert len(await sqlite_instance.get_seeds_async()) == 2 async def test_add_seed_groups_to_memory_multiple_groups_with_added_by(sqlite_instance: MemoryInterface): @@ -891,8 +897,8 @@ async def test_add_seed_groups_to_memory_multiple_groups_with_added_by(sqlite_in prompt_group2 = SeedGroup(seeds=[prompt3, prompt4]) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[prompt_group1, prompt_group2]) - assert len(sqlite_instance.get_seeds()) == 4 - groups_from_memory = sqlite_instance.get_seed_groups() + assert len(await sqlite_instance.get_seeds_async()) == 4 + groups_from_memory = await sqlite_instance.get_seed_groups_async() assert len(groups_from_memory) == 2 assert groups_from_memory[0].prompts[0].id != groups_from_memory[1].prompts[1].id assert groups_from_memory[0].prompts[0].prompt_group_id == groups_from_memory[0].prompts[1].prompt_group_id @@ -944,10 +950,10 @@ async def test_add_seed_groups_to_memory_with_all_modalities(sqlite_instance: Me await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[seed_group1]) # Assert the total number of prompts in memory - assert len(sqlite_instance.get_seeds(added_by="testmultimodal")) == 4 + assert len(await sqlite_instance.get_seeds_async(added_by="testmultimodal")) == 4 # Retrieve and verify prompt groups from memory - groups_from_memory = sqlite_instance.get_seed_groups(added_by="testmultimodal") + groups_from_memory = await sqlite_instance.get_seed_groups_async(added_by="testmultimodal") assert len(groups_from_memory) == 1 # Verify prompt group IDs are consistent within each group @@ -1001,10 +1007,10 @@ async def test_add_seed_groups_to_memory_with_textimage_modalities(sqlite_instan await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[seed_group1]) # Assert the total number of prompts in memory - assert len(sqlite_instance.get_seeds(added_by="testtextimagemultimodal")) == 2 + assert len(await sqlite_instance.get_seeds_async(added_by="testtextimagemultimodal")) == 2 # Retrieve and verify prompt groups from memory - groups_from_memory = sqlite_instance.get_seed_groups(added_by="testtextimagemultimodal") + groups_from_memory = await sqlite_instance.get_seed_groups_async(added_by="testtextimagemultimodal") assert len(groups_from_memory) == 1 # Verify prompt group IDs are consistent within each group @@ -1041,7 +1047,7 @@ async def test_get_seeds_with_param_filters(sqlite_instance: MemoryInterface): ) await sqlite_instance.add_seeds_to_memory_async(seeds=[template]) - templates = sqlite_instance.get_seeds( + templates = await sqlite_instance.get_seeds_async( value=template_value, dataset_name=dataset_name, harm_categories=harm_categories, @@ -1052,8 +1058,8 @@ async def test_get_seeds_with_param_filters(sqlite_instance: MemoryInterface): assert templates[0].value == template_value -def test_get_seed_groups_empty(sqlite_instance: MemoryInterface): - assert sqlite_instance.get_seed_groups() == [] +async def test_get_seed_groups_empty(sqlite_instance: MemoryInterface): + assert (await sqlite_instance.get_seed_groups_async()) == [] async def test_get_seed_groups_with_dataset_name(sqlite_instance: MemoryInterface): @@ -1065,7 +1071,7 @@ async def test_get_seed_groups_with_dataset_name(sqlite_instance: MemoryInterfac ) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[prompt_group]) - groups = sqlite_instance.get_seed_groups(dataset_name=dataset_name) + groups = await sqlite_instance.get_seed_groups_async(dataset_name=dataset_name) assert len(groups) == 1 assert groups[0].prompts[0].dataset_name == dataset_name @@ -1104,7 +1110,7 @@ async def test_get_seed_groups_with_dataset_name_pattern_startswith(sqlite_insta ] await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=groups_to_add) - groups = sqlite_instance.get_seed_groups(dataset_name_pattern="harm%") + groups = await sqlite_instance.get_seed_groups_async(dataset_name_pattern="harm%") assert len(groups) == 2 assert all(group.prompts[0].dataset_name.startswith("harm") for group in groups) @@ -1147,7 +1153,7 @@ async def test_get_seed_groups_with_dataset_name_pattern_contains(sqlite_instanc ] await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=groups_to_add) - groups = sqlite_instance.get_seed_groups(dataset_name_pattern="%harm%") + groups = await sqlite_instance.get_seed_groups_async(dataset_name_pattern="%harm%") assert len(groups) == 2 assert all("harm" in group.prompts[0].dataset_name for group in groups) @@ -1173,7 +1179,7 @@ async def test_get_seed_groups_dataset_name_takes_precedence_over_pattern(sqlite await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=groups_to_add) # When both are provided, exact match should be used - groups = sqlite_instance.get_seed_groups(dataset_name="harm_exact", dataset_name_pattern="harm%") + groups = await sqlite_instance.get_seed_groups_async(dataset_name="harm_exact", dataset_name_pattern="harm%") assert len(groups) == 1 assert groups[0].prompts[0].dataset_name == "harm_exact" @@ -1197,7 +1203,7 @@ async def test_get_seed_groups_with_multiple_filters(sqlite_instance: MemoryInte ) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group]) - groups = sqlite_instance.get_seed_groups( + groups = await sqlite_instance.get_seed_groups_async( dataset_name=dataset_name, data_types=data_types, harm_categories=harm_categories, @@ -1218,7 +1224,7 @@ async def test_get_seed_groups_multiple_groups(sqlite_instance: MemoryInterface) ) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group1, group2]) - groups = sqlite_instance.get_seed_groups() + groups = await sqlite_instance.get_seed_groups_async() assert len(groups) == 2 @@ -1231,7 +1237,7 @@ async def test_get_seed_groups_multiple_groups_with_unique_ids(sqlite_instance: ) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group1, group2]) - groups = sqlite_instance.get_seed_groups() + groups = await sqlite_instance.get_seed_groups_async() assert len(groups) == 2 # Check that each group has a unique prompt_group_id assert groups[0].prompts[0].prompt_group_id != groups[1].prompts[0].prompt_group_id @@ -1246,7 +1252,7 @@ async def test_get_seeds_by_hash(sqlite_instance: MemoryInterface): hello_1_hash = "724c531a3bc130eb46fbc4600064779552682ef4f351976fe75d876d94e8088c" await sqlite_instance.add_seeds_to_memory_async(seeds=entries, added_by="rlundeen") - retrieved_entries = sqlite_instance.get_seeds(value_sha256=[hello_1_hash]) + retrieved_entries = await sqlite_instance.get_seeds_async(value_sha256=[hello_1_hash]) assert len(retrieved_entries) == 1 assert retrieved_entries[0].value == "Hello 1" @@ -1341,7 +1347,7 @@ async def test_add_seed_datasets_to_memory_async(sqlite_instance: MemoryInterfac await sqlite_instance.add_seed_datasets_to_memory_async(datasets=[dataset], added_by="test_user") - result = sqlite_instance.get_seeds(dataset_name="test_dataset") + result = await sqlite_instance.get_seeds_async(dataset_name="test_dataset") assert len(result) == 1 assert result[0].value == "test prompt" assert result[0].added_by == "test_user" @@ -1374,7 +1380,7 @@ async def test_get_seed_groups_deduplication_and_filtering(sqlite_instance: Memo await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[seed_group], added_by="test_dedupe") # Test 1: Filter by audio_path should return the whole group (including text) - groups_audio = sqlite_instance.get_seed_groups(data_types=["audio_path"]) + groups_audio = await sqlite_instance.get_seed_groups_async(data_types=["audio_path"]) assert len(groups_audio) == 1 assert len(groups_audio[0].prompts) == 2 @@ -1384,7 +1390,7 @@ async def test_get_seed_groups_deduplication_and_filtering(sqlite_instance: Memo assert "audio_path" in data_types # Test 2: Filter by both types should return the group only once (deduplication) - groups_both = sqlite_instance.get_seed_groups(data_types=["text", "audio_path"]) + groups_both = await sqlite_instance.get_seed_groups_async(data_types=["text", "audio_path"]) assert len(groups_both) == 1 assert len(groups_both[0].prompts) == 2 @@ -1412,26 +1418,26 @@ async def test_get_seed_groups_filter_by_count(sqlite_instance: MemoryInterface) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group1, group2], added_by="test_user") # Test filtering by count = 1 - groups_count_1 = sqlite_instance.get_seed_groups(group_length=[1]) + groups_count_1 = await sqlite_instance.get_seed_groups_async(group_length=[1]) assert len(groups_count_1) == 1 assert len(groups_count_1[0].seeds) == 1 assert groups_count_1[0].seeds[0].value == "prompt1" # Test filtering by count = 2 - groups_count_2 = sqlite_instance.get_seed_groups(group_length=[2]) + groups_count_2 = await sqlite_instance.get_seed_groups_async(group_length=[2]) assert len(groups_count_2) == 1 assert len(groups_count_2[0].seeds) == 2 # Test filtering by count = 3 (should be empty) - groups_count_3 = sqlite_instance.get_seed_groups(group_length=[3]) + groups_count_3 = await sqlite_instance.get_seed_groups_async(group_length=[3]) assert len(groups_count_3) == 0 # Test filtering by count = [1, 2] - groups_count_1_2 = sqlite_instance.get_seed_groups(group_length=[1, 2]) + groups_count_1_2 = await sqlite_instance.get_seed_groups_async(group_length=[1, 2]) assert len(groups_count_1_2) == 2 # Test without filtering (should return all) - all_groups = sqlite_instance.get_seed_groups() + all_groups = await sqlite_instance.get_seed_groups_async() assert len(all_groups) == 2 @@ -1453,8 +1459,8 @@ async def test_replace_seeds_for_dataset_async_replaces_all(sqlite_instance: Mem ) assert deleted == 2 - assert {seed.value for seed in sqlite_instance.get_seeds(dataset_name="alpha")} == {"a3"} - assert {seed.value for seed in sqlite_instance.get_seeds(dataset_name="beta")} == {"b1"} + assert {seed.value for seed in (await sqlite_instance.get_seeds_async(dataset_name="alpha"))} == {"a3"} + assert {seed.value for seed in (await sqlite_instance.get_seeds_async(dataset_name="beta"))} == {"b1"} async def test_replace_seeds_for_dataset_async_new_dataset_inserts(sqlite_instance: MemoryInterface): @@ -1466,7 +1472,7 @@ async def test_replace_seeds_for_dataset_async_new_dataset_inserts(sqlite_instan ) assert deleted == 0 - assert {seed.value for seed in sqlite_instance.get_seeds(dataset_name="fresh")} == {"v1"} + assert {seed.value for seed in (await sqlite_instance.get_seeds_async(dataset_name="fresh"))} == {"v1"} async def test_replace_seeds_for_dataset_async_empty_name_raises(sqlite_instance: MemoryInterface): @@ -1500,8 +1506,8 @@ async def test_replace_seeds_for_dataset_async_mismatched_name_raises(sqlite_ins ) # The guard fires before the delete, so alpha is untouched and beta was never created. - assert {seed.value for seed in sqlite_instance.get_seeds(dataset_name="alpha")} == {"keep"} - assert sqlite_instance.get_seeds(dataset_name="beta") == [] + assert {seed.value for seed in (await sqlite_instance.get_seeds_async(dataset_name="alpha"))} == {"keep"} + assert (await sqlite_instance.get_seeds_async(dataset_name="beta")) == [] async def test_replace_seeds_for_dataset_async_mixed_none_and_foreign_name_raises(sqlite_instance: MemoryInterface): @@ -1521,7 +1527,7 @@ async def test_replace_seeds_for_dataset_async_mixed_none_and_foreign_name_raise added_by="refresh", ) - assert {seed.value for seed in sqlite_instance.get_seeds(dataset_name="alpha")} == {"keep"} + assert {seed.value for seed in (await sqlite_instance.get_seeds_async(dataset_name="alpha"))} == {"keep"} async def test_replace_seeds_for_dataset_async_rolls_back_on_error(sqlite_instance: MemoryInterface): @@ -1531,11 +1537,12 @@ async def test_replace_seeds_for_dataset_async_rolls_back_on_error(sqlite_instan added_by="seeding", ) - real_session = sqlite_instance.get_session() + async_session = await sqlite_instance.get_session_async() + real_session = async_session.sync_session real_session.commit = MagicMock(side_effect=SQLAlchemyError("commit failed")) real_session.rollback = MagicMock(side_effect=real_session.rollback) - with patch.object(sqlite_instance, "get_session", return_value=real_session): + with patch.object(sqlite_instance, "get_session_async", return_value=async_session): with pytest.raises(SQLAlchemyError, match="commit failed"): await sqlite_instance.replace_seeds_for_dataset_async( dataset_name="d", @@ -1545,4 +1552,4 @@ async def test_replace_seeds_for_dataset_async_rolls_back_on_error(sqlite_instan real_session.rollback.assert_called_once() # The delete was rolled back with the failed insert -> the original seed survives. - assert {seed.value for seed in sqlite_instance.get_seeds(dataset_name="d")} == {"old"} + assert {seed.value for seed in (await sqlite_instance.get_seeds_async(dataset_name="d"))} == {"old"} diff --git a/tests/unit/memory/storage/test_serializers.py b/tests/unit/memory/storage/test_serializers.py index d938673574..15611cd7ab 100644 --- a/tests/unit/memory/storage/test_serializers.py +++ b/tests/unit/memory/storage/test_serializers.py @@ -14,6 +14,7 @@ import pytest from PIL import Image +from pyrit.memory import MemoryInterface from pyrit.memory.storage import ( AllowedCategories, AzureBlobStorageIO, @@ -358,7 +359,7 @@ async def test_get_data_filename_preserves_dotted_basename(sqlite_instance): async def test_concurrent_default_filenames_are_unique_and_preserve_payloads(tmp_path: Path) -> None: storage = ConcurrentWriteStorageIO() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = tmp_path mock_memory.results_storage_io = storage serializers = [ @@ -390,7 +391,7 @@ async def test_concurrent_default_filenames_are_unique_and_preserve_payloads(tmp async def test_save_data_supports_legacy_storage_io_write_signature(): storage = LegacyStorageIO() - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = "https://account.blob.core.windows.net/container/results" mock_memory.results_storage_io = storage serializer = data_serializer_factory(category="prompt-memory-entries", data_type="image_path") @@ -439,7 +440,7 @@ async def test_binary_path_default_extension_sets_azure_content_type(): storage = AzureBlobStorageIO(container_url="https://account.blob.core.windows.net/container") mock_container_client = AsyncMock() storage._client_async = mock_container_client - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = "https://account.blob.core.windows.net/container/results" mock_memory.results_storage_io = storage serializer = data_serializer_factory(category="prompt-memory-entries", data_type="binary_path") @@ -488,7 +489,7 @@ async def test_binary_path_subdirectory(sqlite_instance): def test_get_storage_io_raises_when_results_storage_io_none(): serializer = data_serializer_factory(category="prompt-memory-entries", data_type="image_path") serializer.value = "https://account.blob.core.windows.net/container/path/image.png" - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_storage_io = None with patch.object(type(serializer), "_memory", new_callable=PropertyMock, return_value=mock_memory): with pytest.raises(RuntimeError, match="results_storage_io is not configured"): @@ -497,7 +498,7 @@ def test_get_storage_io_raises_when_results_storage_io_none(): async def test_save_data_raises_when_results_storage_io_none(): serializer = data_serializer_factory(category="prompt-memory-entries", data_type="image_path") - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_storage_io = None with patch.object(type(serializer), "_memory", new_callable=PropertyMock, return_value=mock_memory): with patch.object( @@ -509,7 +510,7 @@ async def test_save_data_raises_when_results_storage_io_none(): async def test_save_b64_image_raises_when_results_storage_io_none(): serializer = data_serializer_factory(category="prompt-memory-entries", data_type="image_path") - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_storage_io = None with patch.object(type(serializer), "_memory", new_callable=PropertyMock, return_value=mock_memory): with patch.object( @@ -526,7 +527,7 @@ async def test_save_formatted_audio_raises_when_results_storage_io_none(): from pyrit.memory.storage import data_serializer_factory as factory serializer = factory(category="prompt-memory-entries", data_type="audio_path") - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_storage_io = None azure_url = "https://account.blob.core.windows.net/container/audio/test.wav" with patch.object(type(serializer), "_memory", new_callable=PropertyMock, return_value=mock_memory): @@ -575,7 +576,7 @@ async def test_save_formatted_audio_uses_wav_filename_content_and_metadata(tmp_p storage = AzureBlobStorageIO(container_url="https://account.blob.core.windows.net/container") mock_container_client = AsyncMock() storage._client_async = mock_container_client - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = "https://account.blob.core.windows.net/container/results" mock_memory.results_storage_io = storage serializer = data_serializer_factory(category="prompt-memory-entries", data_type="audio_path") @@ -637,7 +638,7 @@ async def _capture_write(file_path, data): mock_storage_io = MagicMock() mock_storage_io.write_file_async = AsyncMock(side_effect=_capture_write) - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_storage_io = mock_storage_io serializer = factory(category="prompt-memory-entries", data_type="audio_path") @@ -674,7 +675,7 @@ async def _capture_write(file_path, data): async def test_get_data_filename_raises_when_results_storage_io_none(): serializer = data_serializer_factory(category="prompt-memory-entries", data_type="image_path") serializer._file_path = None - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_storage_io = None mock_memory.results_path = "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/local/results" with patch.object(type(serializer), "_memory", new_callable=PropertyMock, return_value=mock_memory): @@ -685,7 +686,7 @@ async def test_get_data_filename_raises_when_results_storage_io_none(): async def test_get_data_filename_uses_db_data_path_when_results_path_falsy(): serializer = data_serializer_factory(category="prompt-memory-entries", data_type="image_path") serializer._file_path = None - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_memory.results_path = None mock_storage_io = AsyncMock() mock_memory.results_storage_io = mock_storage_io @@ -704,7 +705,7 @@ async def test_save_formatted_audio_azure_storage_unlinks_local_temp(tmp_path): from pyrit.memory.storage import data_serializer_factory as factory serializer = factory(category="prompt-memory-entries", data_type="audio_path") - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_storage_io = AsyncMock() mock_memory.results_storage_io = mock_storage_io azure_url = "https://account.blob.core.windows.net/container/audio/test.wav" @@ -747,7 +748,7 @@ async def test_save_formatted_audio_async_cleans_up_temp_file_on_azure_upload_fa """Regression test: temp file must be deleted even when Azure upload fails.""" serializer = data_serializer_factory(category="prompt-memory-entries", data_type="audio_path") - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_storage_io = AsyncMock() mock_storage_io.write_file_async.side_effect = RuntimeError("Azure upload failed") mock_memory.results_storage_io = mock_storage_io diff --git a/tests/unit/memory/test_async_memory.py b/tests/unit/memory/test_async_memory.py new file mode 100644 index 0000000000..8e2d6793f1 --- /dev/null +++ b/tests/unit/memory/test_async_memory.py @@ -0,0 +1,651 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import ast +import asyncio +import inspect +import threading +from collections.abc import Iterator, Sequence +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from azure.core.credentials import AccessToken +from sqlalchemy import text +from sqlalchemy.dialects.mssql.aioodbc import MSDialectAsync_aioodbc +from sqlalchemy.ext.asyncio import AsyncEngine +from sqlalchemy.orm import Session + +from pyrit.auth.azure_auth import AsyncAzureAuth +from pyrit.common.async_compatibility import run_legacy_sync_async +from pyrit.memory import AzureSQLMemory, MemoryInterface, SQLiteMemory +from pyrit.models import Conversation, Message, MessagePiece, SeedPrompt + + +@pytest.fixture +def mock_aioodbc_connect() -> Iterator[AsyncMock]: + connect = AsyncMock() + driver = MagicMock(spec=["connect", "Connection"], connect=connect) + # Block native ODBC imports so these unit tests also cover hosts without the driver. + with patch.dict("sys.modules", {"aioodbc": driver, "pyodbc": None}): + yield connect + + +def test_public_memory_io_has_explicit_async_counterparts() -> None: + configuration_methods = {"enable_embedding", "disable_embedding", "cleanup"} + for name, method in inspect.getmembers(MemoryInterface, inspect.isfunction): + if name.startswith("_") or name in configuration_methods or inspect.iscoroutinefunction(method): + continue + assert inspect.iscoroutinefunction(getattr(MemoryInterface, name + "_async", None)), name + + +@pytest.mark.parametrize( + "name", + [ + name + for name, method in inspect.getmembers(MemoryInterface, inspect.isfunction) + if not name.startswith("_") + and not inspect.iscoroutinefunction(method) + and inspect.iscoroutinefunction(getattr(MemoryInterface, name + "_async", None)) + ], +) +def test_public_sync_memory_method_is_deprecated(name: str, sqlite_instance: SQLiteMemory) -> None: + method = getattr(sqlite_instance, name) + required = { + parameter.name: None + for parameter in inspect.signature(method).parameters.values() + if parameter.default is inspect.Parameter.empty + and parameter.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY) + } + with patch("pyrit.memory.memory_interface.print_deprecation_message", side_effect=DeprecationWarning) as warning: + with pytest.raises(DeprecationWarning): + method(**required) + assert warning.call_args.kwargs["new_item"] == f"MemoryInterface.{name}_async" + + +def test_library_does_not_reference_sync_memory_outside_compatibility() -> None: + root = Path(__file__).resolve().parents[3] / "pyrit" + sync_names = { + name + for name, method in inspect.getmembers(MemoryInterface, inspect.isfunction) + if not name.startswith("_") + and not inspect.iscoroutinefunction(method) + and hasattr(MemoryInterface, name + "_async") + } + violations = [] + for path in root.rglob("*.py"): + if "memory" in path.relative_to(root).parts: + continue + tree = ast.parse(path.read_text(encoding="utf-8")) + parents = {child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)} + for node in ast.walk(tree): + if not isinstance(node, ast.Attribute) or node.attr not in sync_names: + continue + owner = parents.get(node) + while owner is not None and not isinstance(owner, (ast.FunctionDef, ast.AsyncFunctionDef)): + owner = parents.get(owner) + if isinstance(owner, ast.FunctionDef): + container = parents.get(owner) + if isinstance(container, (ast.ClassDef, ast.Module)) and any( + isinstance(method, ast.AsyncFunctionDef) and method.name == owner.name + "_async" + for method in container.body + ): + continue + violations.append(f"{path.relative_to(root)}:{node.lineno}: {ast.unparse(node)}") + assert not violations, "\n".join(violations) + + +async def test_async_memory_uses_async_driver(sqlite_instance: SQLiteMemory) -> None: + with patch.object(sqlite_instance, "SessionFactory", side_effect=AssertionError("Sync session used")): + await sqlite_instance.add_conversation_to_memory_async(conversation=Conversation(conversation_id="async")) + await sqlite_instance.add_message_to_memory_async( + request=Message(message_pieces=[MessagePiece(role="user", original_value="hello", conversation_id="async")]) + ) + messages = await sqlite_instance.get_conversation_messages_async(conversation_id="async") + assert messages[0].message_pieces[0].original_value == "hello" + + +async def test_failed_first_initialization_can_retry() -> None: + memory = SQLiteMemory.__new__(SQLiteMemory) + memory.__init__(db_path=":memory:", _defer_initialization=True) + try: + with ( + patch.object(memory, "_run_schema_migration", side_effect=RuntimeError("schema check failed")), + pytest.raises(RuntimeError, match="schema check failed"), + ): + await memory.initialize_async() + assert not memory._initialized + await memory.initialize_async() + piece = MessagePiece(role="user", original_value="after retry", conversation_id="retry") + await memory.add_message_to_memory_async(request=piece.to_message()) + assert [row.id for row in await memory.get_message_pieces_async()] == [piece.id] + finally: + await memory.dispose_engine_async() + + +async def test_concurrent_initialization_is_rejected_without_disposing_first_attempt() -> None: + memory = SQLiteMemory.__new__(SQLiteMemory) + memory.__init__(db_path=":memory:", _defer_initialization=True) + started, release = threading.Event(), threading.Event() + + def initialize_schema() -> None: + started.set() + if not release.wait(timeout=5): + raise RuntimeError("Initialization was not released") + + try: + with ( + patch.object(memory, "_initialize_schema", side_effect=initialize_schema), + patch.object(memory, "dispose_engine_async", new_callable=AsyncMock) as dispose, + ): + task = asyncio.create_task(memory.initialize_async()) + try: + assert await asyncio.to_thread(started.wait, 5) + with pytest.raises(RuntimeError, match="already in progress"): + await memory.initialize_async() + dispose.assert_not_awaited() + finally: + release.set() + await task + finally: + await memory.dispose_engine_async() + + +async def test_async_memory_shares_legacy_database(sqlite_instance: SQLiteMemory) -> None: + await sqlite_instance.add_conversation_to_memory_async(conversation=Conversation(conversation_id="shared")) + with pytest.warns(DeprecationWarning, match="add_message_to_memory"): + sqlite_instance.add_message_to_memory( + request=Message( + message_pieces=[MessagePiece(role="user", original_value="legacy", conversation_id="shared")] + ) + ) + messages = await sqlite_instance.get_conversation_messages_async(conversation_id="shared") + assert messages[0].message_pieces[0].original_value == "legacy" + with pytest.warns(DeprecationWarning, match="get_conversation_messages"): + assert sqlite_instance.get_conversation_messages(conversation_id="shared") == messages + + +async def test_async_seed_operations(sqlite_instance: SQLiteMemory) -> None: + seed = SeedPrompt(value="hello", dataset_name="async", added_by="unit-test") + await sqlite_instance.add_seeds_to_memory_async(seeds=[seed]) + assert len(await sqlite_instance.get_seeds_async(dataset_name="async")) == 1 + replacement = SeedPrompt(value="replacement", dataset_name="async", added_by="unit-test") + assert await sqlite_instance.replace_seeds_for_dataset_async(dataset_name="async", seeds=[replacement]) == 1 + assert (await sqlite_instance.get_seeds_async(dataset_name="async"))[0].value == "replacement" + + +async def test_async_database_wait_does_not_block_loop(sqlite_instance: SQLiteMemory) -> None: + started = threading.Event() + release = threading.Event() + + def wait_in_database() -> int: + started.set() + if not release.wait(timeout=10): + raise RuntimeError("Database wait was not released") + return 1 + + async with await sqlite_instance.get_session_async() as session: + connection = await session.connection() + await connection.run_sync( + lambda sync_connection: sync_connection.connection.run_async( + lambda driver: driver.create_function("wait_in_database", 0, wait_in_database) + ) + ) + task = asyncio.create_task(session.execute(text("SELECT wait_in_database()"))) + try: + assert await asyncio.to_thread(started.wait, 5) + assert not task.done() + await asyncio.sleep(0) + finally: + release.set() + assert (await task).scalar_one() == 1 + + +async def test_azure_auth_wait_is_async_and_credential_is_closed() -> None: + started = asyncio.Event() + release = asyncio.Event() + token = AccessToken("unit-test", 100) + + async def get_token_async(scope: str) -> AccessToken: + assert scope == "scope" + started.set() + await release.wait() + return token + + credential = MagicMock(get_token=AsyncMock(side_effect=get_token_async), close=AsyncMock()) + with patch("pyrit.auth.azure_auth.AsyncDefaultAzureCredential", return_value=credential): + auth = AsyncAzureAuth("scope") + task = asyncio.create_task(auth.get_access_token_async()) + try: + await asyncio.wait_for(started.wait(), timeout=5) + await asyncio.sleep(0) + assert not task.done() + finally: + release.set() + assert await task is token + await auth.close_async() + credential.close.assert_awaited_once() + + +@pytest.mark.parametrize("failing_resource", ["engine", "credential"]) +async def test_azure_disposal_failure_discards_engine_and_credential(failing_resource: str) -> None: + loop = asyncio.get_running_loop() + memory = AzureSQLMemory.__new__(AzureSQLMemory) + engine = MagicMock(dispose=AsyncMock()) + auth = MagicMock(spec=AsyncAzureAuth) + memory._async_engines = {loop: engine} + memory._async_auth = {loop: auth} + close = engine.dispose if failing_resource == "engine" else auth.close_async + close.side_effect = [RuntimeError("close failed"), None] + + with pytest.raises(RuntimeError, match="close failed"): + await memory.dispose_loop_resources_async() + assert memory._async_engines == {} + assert memory._async_auth == {} + auth.close_async.assert_awaited_once() + await memory.dispose_loop_resources_async() + assert memory._async_engines == {} + assert memory._async_auth == {} + replacement = MagicMock() + with patch.object(memory, "_create_async_engine", return_value=replacement): + assert memory._get_async_engine() is replacement + + +@pytest.mark.parametrize( + "trusted_connection", ["Trusted_Connection=Yes", "trusted_connection = yes", " TRUSTED_CONNECTION=YES "] +) +async def test_azure_async_token_connection_removes_trusted_connection( + trusted_connection: str, mock_aioodbc_connect: AsyncMock +) -> None: + memory = AzureSQLMemory.__new__(AzureSQLMemory) + memory._connection_string = "mssql+pyodbc://localhost/test?driver=ODBC+Driver+18+for+SQL+Server" + memory._verbose = False + memory._async_auth = {} + engine = MagicMock() + engine.dialect.create_connect_args.return_value = ( + [], + {"dsn": f"Driver=unit-test;{trusted_connection};Database=test"}, + ) + auth = MagicMock(spec=AsyncAzureAuth) + auth.get_access_token_async.return_value = AccessToken("unit-test", 100) + with ( + patch("pyrit.memory.azure_sql_memory.create_async_engine", return_value=engine) as create, + patch("pyrit.memory.azure_sql_memory.AsyncAzureAuth", return_value=auth), + ): + assert memory._create_async_engine() is engine + await create.call_args.kwargs["async_creator"]() + mock_aioodbc_connect.assert_awaited_once() + assert mock_aioodbc_connect.call_args.kwargs["dsn"] == "Driver=unit-test;Database=test" + assert memory.SQL_COPT_SS_ACCESS_TOKEN in mock_aioodbc_connect.call_args.kwargs["attrs_before"] + + +async def test_azure_closed_loop_drops_both_owned_resources() -> None: + loop = asyncio.new_event_loop() + loop.close() + memory = AzureSQLMemory.__new__(AzureSQLMemory) + engine = MagicMock() + auth = MagicMock(spec=AsyncAzureAuth) + memory._async_engines = {loop: engine} + memory._async_auth = {loop: auth} + with pytest.warns(DeprecationWarning), pytest.raises(RuntimeError, match="owning event loops"): + memory.dispose_engine() + assert memory._async_engines == {loop: engine} + assert memory._async_auth == {loop: auth} + auth.close_async.assert_not_awaited() + await memory.dispose_loop_resources_async() + assert memory._async_engines == {} + assert memory._async_auth == {} + engine.sync_engine.dispose.assert_called_once_with(close=False) + auth.close_async.assert_awaited_once() + + +@pytest.mark.parametrize("cancellations", [1, 2]) +async def test_cancelled_legacy_call_finishes_before_returning(cancellations: int) -> None: + started = threading.Event() + release = threading.Event() + finished = threading.Event() + + def legacy_operation() -> None: + started.set() + if not release.wait(timeout=10): + raise RuntimeError("Legacy operation was not released") + finished.set() + + task = asyncio.create_task(run_legacy_sync_async(legacy_operation)) + try: + assert await asyncio.to_thread(started.wait, 5) + for _ in range(cancellations): + task.cancel() + await asyncio.sleep(0) + assert not task.done() + finally: + release.set() + with pytest.raises(asyncio.CancelledError): + await task + assert finished.is_set() + + +async def test_cancelled_legacy_failure_preserves_cancellation() -> None: + started = threading.Event() + release = threading.Event() + + def fail() -> None: + started.set() + assert release.wait(timeout=10) + raise ValueError("worker failed") + + task = asyncio.create_task(run_legacy_sync_async(fail)) + try: + assert await asyncio.to_thread(started.wait, 5) + task.cancel() + await asyncio.sleep(0) + finally: + release.set() + with pytest.raises(asyncio.CancelledError) as error: + await task + assert isinstance(error.value.__cause__, ValueError) + + +async def test_disposal_discards_closed_loop_and_releases_sync_engine(sqlite_instance: SQLiteMemory) -> None: + loop = asyncio.new_event_loop() + engine = MagicMock() + sqlite_instance._async_engines[loop] = engine + loop.close() + with patch.object(sqlite_instance, "_dispose_sync_engine") as dispose: + await sqlite_instance.dispose_engine_async() + assert not sqlite_instance._async_engines + engine.sync_engine.dispose.assert_called_once_with(close=False) + dispose.assert_called_once() + + +async def test_disposal_failure_still_releases_sync_engine(sqlite_instance: SQLiteMemory) -> None: + with ( + patch.object(sqlite_instance, "dispose_loop_resources_async", side_effect=RuntimeError("close failed")), + patch.object(sqlite_instance, "_dispose_sync_engine") as dispose, + pytest.raises(RuntimeError, match="close failed"), + ): + await sqlite_instance.dispose_engine_async() + dispose.assert_called_once() + + +async def test_sync_disposal_rejects_active_async_resources(sqlite_instance: SQLiteMemory) -> None: + await sqlite_instance.get_message_pieces_async() + with ( + pytest.warns(DeprecationWarning), + pytest.raises(RuntimeError, match="owning event loops"), + patch.object(sqlite_instance, "_dispose_sync_engine") as dispose, + ): + sqlite_instance.dispose_engine() + dispose.assert_not_called() + + +async def test_sync_read_rejects_same_loop_async_overlap(sqlite_instance: SQLiteMemory) -> None: + started, release = threading.Event(), threading.Event() + + def delayed_read() -> int: + started.set() + if not release.wait(timeout=5): + raise RuntimeError("Database read was not released") + return 1 + + async with await sqlite_instance.get_session_async() as session: + connection = await session.connection() + await connection.run_sync( + lambda sync_connection: sync_connection.connection.run_async( + lambda driver: driver.create_function("delayed_read", 0, delayed_read) + ) + ) + read = asyncio.create_task(session.execute(text("SELECT delayed_read()"))) + try: + assert await asyncio.to_thread(started.wait, 5) + with pytest.warns(DeprecationWarning), pytest.raises(RuntimeError, match="cannot overlap"): + sqlite_instance.get_message_pieces() + await asyncio.sleep(0) + assert not read.done() + finally: + release.set() + await read + assert await sqlite_instance.get_message_pieces_async() == [] + with pytest.warns(DeprecationWarning): + assert sqlite_instance.get_message_pieces() == [] + + +async def test_async_session_rejects_same_thread_sync_overlap(sqlite_instance: SQLiteMemory) -> None: + with sqlite_instance._get_sync_session(): + with pytest.raises(RuntimeError, match="Close the synchronous memory session"): + await sqlite_instance.get_message_pieces_async() + assert await sqlite_instance.get_message_pieces_async() == [] + + +@pytest.mark.parametrize("reader", ["async", "sync"]) +async def test_in_memory_transactions_are_serialized_across_loops(sqlite_instance: SQLiteMemory, reader: str) -> None: + started = threading.Event() + + async def read_and_write_async() -> int: + started.set() + try: + async with await sqlite_instance.get_session_async() as session: + count = await session.scalar(text("SELECT COUNT(*) FROM LockProbe")) + await session.execute(text("INSERT INTO LockProbe VALUES (2)")) + await session.commit() + return count + finally: + await sqlite_instance.dispose_loop_resources_async() + + def read_and_write() -> int: + if reader == "async": + return asyncio.run(read_and_write_async()) + started.set() + with sqlite_instance._get_sync_session() as session: + count = session.scalar(text("SELECT COUNT(*) FROM LockProbe")) + session.execute(text("INSERT INTO LockProbe VALUES (2)")) + session.commit() + return count + + async with await sqlite_instance.get_session_async() as session: + await session.execute(text("CREATE TABLE LockProbe (value INTEGER)")) + await session.commit() + await session.execute(text("INSERT INTO LockProbe VALUES (1)")) + task = asyncio.create_task(asyncio.to_thread(read_and_write)) + try: + assert await asyncio.to_thread(started.wait, 5) + await asyncio.sleep(0.05) + assert not task.done() + finally: + await session.commit() + assert await asyncio.wait_for(task, timeout=5) == 1 + async with await sqlite_instance.get_session_async() as session: + assert await session.scalar(text("SELECT COUNT(*) FROM LockProbe")) == 2 + + +async def test_async_sessions_are_task_local(sqlite_instance: SQLiteMemory) -> None: + sessions = [] + + def read() -> int: + session = sqlite_instance._get_session() + sessions.append(session) + result = session.execute(text("SELECT 1")).scalar_one() + assert isinstance(result, int) + return result + + results = await asyncio.gather(*(sqlite_instance._run_database_operation_async(read) for _ in range(5))) + assert results == [1] * 5 + assert len({id(session) for session in sessions}) == 5 + assert sqlite_instance._operation_session.get() is None + + +async def test_cancelled_transaction_rolls_back_and_pool_remains_usable(sqlite_instance: SQLiteMemory) -> None: + async with await sqlite_instance.get_session_async() as session: + await session.execute(text("CREATE TABLE CancellationProbe (value INTEGER)")) + await session.commit() + inserted = asyncio.Event() + + async def write_async() -> None: + async with await sqlite_instance.get_session_async() as session: + await session.execute(text("INSERT INTO CancellationProbe VALUES (1)")) + inserted.set() + await asyncio.Event().wait() + await session.commit() + + task = asyncio.create_task(write_async()) + await asyncio.wait_for(inserted.wait(), timeout=5) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + async with await sqlite_instance.get_session_async() as session: + assert await session.scalar(text("SELECT COUNT(*) FROM CancellationProbe")) == 0 + await session.execute(text("INSERT INTO CancellationProbe VALUES (2)")) + await session.commit() + + +async def test_temporary_loops_release_their_own_resources(sqlite_instance: SQLiteMemory) -> None: + await sqlite_instance.add_conversation_to_memory_async(conversation=Conversation(conversation_id="loop-test")) + owner = asyncio.get_running_loop() + owner_engine = sqlite_instance._async_engines[owner] + + async def read_on_temporary_loop_async() -> None: + try: + assert await sqlite_instance.get_conversation_metadata_async(conversation_id="loop-test") is not None + assert sqlite_instance._async_engines[asyncio.get_running_loop()] is not owner_engine + finally: + await sqlite_instance.dispose_loop_resources_async() + + for _ in range(2): + await asyncio.to_thread(lambda: asyncio.run(read_on_temporary_loop_async())) + assert list(sqlite_instance._async_engines) == [owner] + + +async def test_legacy_subclass_override_runs_off_loop() -> None: + called_from = [] + + class LegacyMemory(SQLiteMemory): + def get_unique_attack_class_names(self) -> list[str]: + called_from.append(threading.get_ident()) + return ["custom"] + + memory = LegacyMemory.__new__(LegacyMemory) + with pytest.warns(DeprecationWarning, match="override"): + assert await memory.get_unique_attack_class_names_async() == ["custom"] + assert len(called_from) == 1 + assert called_from[0] != threading.get_ident() + + +@pytest.mark.parametrize("use_async", [False, True]) +async def test_inherited_read_dispatches_nested_legacy_override(sqlite_instance: SQLiteMemory, use_async: bool) -> None: + threads = [] + piece = MessagePiece(role="user", original_value="from override", conversation_id="custom", sequence=0) + + class LegacyMemory(SQLiteMemory): + def get_message_pieces(self, **kwargs: object) -> Sequence[MessagePiece]: + threads.append(threading.get_ident()) + assert kwargs["conversation_id"] == "custom" + return [piece] + + memory = LegacyMemory.__new__(LegacyMemory) + memory.__dict__.update(sqlite_instance.__dict__) + with pytest.warns(DeprecationWarning): + messages = ( + await memory.get_conversation_messages_async(conversation_id="custom") + if use_async + else memory.get_conversation_messages(conversation_id="custom") + ) + assert [message.get_piece().id for message in messages] == [piece.id] + assert len(threads) == 1 + assert (threads[0] != threading.get_ident()) == use_async + + +@pytest.mark.parametrize("use_async", [False, True]) +async def test_inherited_write_dispatches_nested_legacy_override_with_super( + sqlite_instance: SQLiteMemory, use_async: bool +) -> None: + threads = [] + + class LegacyMemory(SQLiteMemory): + def add_message_pieces_to_memory(self, *, message_pieces: Sequence[MessagePiece]) -> None: + threads.append(threading.get_ident()) + super().add_message_pieces_to_memory(message_pieces=message_pieces) + + memory = LegacyMemory.__new__(LegacyMemory) + memory.__dict__.update(sqlite_instance.__dict__) + piece = MessagePiece(role="user", original_value="persisted through override", conversation_id="legacy-write") + with pytest.warns(DeprecationWarning): + if use_async: + await memory.add_message_to_memory_async(request=piece.to_message()) + else: + memory.add_message_to_memory(request=piece.to_message()) + assert len(threads) == 1 + assert (threads[0] != threading.get_ident()) == use_async + assert [row.id for row in await sqlite_instance.get_message_pieces_async()] == [piece.id] + + +async def test_legacy_session_override_is_not_bypassed(sqlite_instance: SQLiteMemory) -> None: + threads = [] + + class LegacyMemory(SQLiteMemory): + def get_session(self) -> Session: + threads.append(threading.get_ident()) + return self._get_sync_session() + + memory = LegacyMemory.__new__(LegacyMemory) + memory.__dict__.update(sqlite_instance.__dict__) + with pytest.warns(DeprecationWarning, match="synchronous backend"): + assert await memory.get_conversation_messages_async(conversation_id="empty") == [] + assert threads and all(thread != threading.get_ident() for thread in threads) + with pytest.raises(NotImplementedError, match="get_session_async"): + await memory.get_session_async() + + +async def test_async_override_can_call_super_without_using_legacy_override(sqlite_instance: SQLiteMemory) -> None: + class MigratedMemory(SQLiteMemory): + def get_unique_attack_class_names(self) -> list[str]: + raise AssertionError("Legacy override must not be called") + + async def get_unique_attack_class_names_async(self) -> list[str]: + return await super().get_unique_attack_class_names_async() + + memory = MigratedMemory.__new__(MigratedMemory) + memory.__dict__.update(sqlite_instance.__dict__) + assert await memory.get_unique_attack_class_names_async() == [] + + +async def test_azure_async_creator_preserves_options_and_refreshes_token(mock_aioodbc_connect: AsyncMock) -> None: + memory = AzureSQLMemory.__new__(AzureSQLMemory) + memory._connection_string = ( + "mssql+pyodbc://@example.invalid/test?" + "driver=ODBC+Driver+18+for+SQL+Server&Encrypt=yes&TrustServerCertificate=no" + ) + memory._verbose = False + memory._async_auth = {} + memory._async_engines = {} + engine = MagicMock(spec=AsyncEngine) + engine.dialect = MSDialectAsync_aioodbc() + credential = MagicMock(spec=AsyncAzureAuth) + credential.get_access_token_async = AsyncMock(side_effect=[AccessToken("first", 10), AccessToken("second", 20)]) + credential.close_async = AsyncMock() + with ( + patch("pyrit.memory.azure_sql_memory.AsyncAzureAuth", return_value=credential), + patch("pyrit.memory.azure_sql_memory.create_async_engine", return_value=engine) as factory, + ): + assert memory._get_async_engine() is engine + try: + creator = factory.call_args.kwargs["async_creator"] + await creator() + await creator() + assert mock_aioodbc_connect.await_count == 2 + options = mock_aioodbc_connect.await_args_list[0].kwargs + assert "Encrypt=yes" in options["dsn"] + assert "TrustServerCertificate=no" in options["dsn"] + assert "Trusted_Connection" not in options["dsn"] + assert options["attrs_before"][1256][4:] == "first".encode("utf-16-le") + assert mock_aioodbc_connect.await_args_list[1].kwargs["attrs_before"][1256][4:] == "second".encode( + "utf-16-le" + ) + assert factory.call_args.args[0].drivername == "mssql+aioodbc" + assert factory.call_args.kwargs["pool_pre_ping"] is True + assert factory.call_args.kwargs["pool_recycle"] == 1800 + finally: + await memory.dispose_loop_resources_async() + credential.close_async.assert_awaited_once() + engine.dispose.assert_awaited_once() + assert memory._async_auth == {} + assert memory._async_engines == {} diff --git a/tests/unit/memory/test_azure_sql_memory.py b/tests/unit/memory/test_azure_sql_memory.py index b0794edeed..0a11ec3028 100644 --- a/tests/unit/memory/test_azure_sql_memory.py +++ b/tests/unit/memory/test_azure_sql_memory.py @@ -3,7 +3,7 @@ import os import uuid -from collections.abc import Generator, MutableSequence, Sequence +from collections.abc import AsyncGenerator, MutableSequence, Sequence from typing import TYPE_CHECKING from unittest.mock import MagicMock, patch @@ -18,15 +18,16 @@ from pyrit.memory.storage.serializers import set_message_piece_sha256_async from pyrit.models import Conversation, MessagePiece from pyrit.prompt_target.text_target import TextTarget -from unit.mocks import get_azure_sql_memory, get_sample_conversation_entries +from unit.mocks import get_azure_sql_memory_async, get_sample_conversation_entries if TYPE_CHECKING: from pyrit.memory.memory_models import Base @pytest.fixture -def memory_interface() -> Generator[AzureSQLMemory, None, None]: - yield from get_azure_sql_memory() +async def memory_interface() -> AsyncGenerator[AzureSQLMemory, None]: + async for memory in get_azure_sql_memory_async(): + yield memory @pytest.fixture @@ -55,14 +56,14 @@ async def test_insert_entry(memory_interface): memory_interface._insert_entry(entry) # Verify the entry was inserted - with memory_interface.get_session() as session: - inserted_entry = session.query(PromptMemoryEntry).filter_by(conversation_id="123").first() + async with await memory_interface.get_session_async() as session: + inserted_entry = (await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id="123"))).first() assert inserted_entry is not None assert inserted_entry.role == "user" assert inserted_entry.original_value == "Hello" -def test_insert_entries(memory_interface: AzureSQLMemory): +async def test_insert_entries_async(memory_interface: AzureSQLMemory): entries = [ PromptMemoryEntry( entry=MessagePiece( @@ -76,10 +77,11 @@ def test_insert_entries(memory_interface: AzureSQLMemory): ] # Now, get a new session to query the database and verify the entries were inserted - with memory_interface.get_session() as session: # type: ignore[arg-type] - # Use the insert_entries method to insert multiple entries into the database - memory_interface._insert_entries(entries=entries) - inserted_entries = session.query(PromptMemoryEntry).order_by(PromptMemoryEntry.conversation_id).all() + memory_interface._insert_entries(entries=entries) + async with await memory_interface.get_session_async() as session: + inserted_entries = ( + await session.scalars(select(PromptMemoryEntry).order_by(PromptMemoryEntry.conversation_id)) + ).all() assert len(inserted_entries) == 5 for i, entry in enumerate(inserted_entries): assert entry.conversation_id == str(i) @@ -88,7 +90,7 @@ def test_insert_entries(memory_interface: AzureSQLMemory): assert entry.converted_value == f"CMessage {i}" -def test_insert_embedding_entry(memory_interface: AzureSQLMemory): +async def test_insert_embedding_entry_async(memory_interface: AzureSQLMemory): # Create a ConversationData entry conversation_entry = PromptMemoryEntry( entry=MessagePiece(conversation_id="123", role="user", original_value="Hello", converted_value="abc") @@ -98,9 +100,11 @@ def test_insert_embedding_entry(memory_interface: AzureSQLMemory): memory_interface._insert_entry(conversation_entry) # Re-query the ConversationData entry within a new session to ensure it's attached - with memory_interface.get_session() as session: # type: ignore[arg-type] + async with await memory_interface.get_session_async() as session: # Assuming uuid is the primary key and is set upon insertion - reattached_conversation_entry = session.query(PromptMemoryEntry).filter_by(conversation_id="123").one() + reattached_conversation_entry = ( + await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id="123")) + ).one() uuid = reattached_conversation_entry.id # Now that we have the uuid, we can create and insert the EmbeddingData entry @@ -108,8 +112,8 @@ def test_insert_embedding_entry(memory_interface: AzureSQLMemory): memory_interface._insert_entry(embedding_entry) # Verify the EmbeddingData entry was inserted correctly - with memory_interface.get_session() as session: # type: ignore[arg-type] - persisted_embedding_entry = session.query(EmbeddingDataEntry).filter_by(id=uuid).first() + async with await memory_interface.get_session_async() as session: + persisted_embedding_entry = (await session.scalars(select(EmbeddingDataEntry).filter_by(id=uuid))).first() assert persisted_embedding_entry is not None assert persisted_embedding_entry.embedding == [1, 2, 3] assert persisted_embedding_entry.embedding_type_name == "test_type" @@ -144,8 +148,8 @@ def test_default_embedding_raises(memory_interface: AzureSQLMemory): memory_interface.enable_embedding() -def test_reset_database_recreates_versioned_schema(memory_interface: AzureSQLMemory): - memory_interface.reset_database() +async def test_reset_database_recreates_versioned_schema_async(memory_interface: AzureSQLMemory): + await memory_interface.reset_database_async() inspector = inspect(memory_interface.engine) table_names = set(inspector.get_table_names()) @@ -188,17 +192,17 @@ def test_query_entries( assert filtered_entries[0].conversation_id == "1" -def test_get_all_memory( +async def test_get_all_memory( memory_interface: AzureSQLMemory, sample_conversation_entries: MutableSequence[PromptMemoryEntry] ): memory_interface._insert_entries(entries=sample_conversation_entries) # Fetch all entries - all_entries = memory_interface.get_message_pieces() + all_entries = await memory_interface.get_message_pieces_async() assert len(all_entries) == 3 -def test_get_memories_with_json_properties(memory_interface: AzureSQLMemory): +async def test_get_memories_with_json_properties(memory_interface: AzureSQLMemory): # Define a specific conversation_id specific_conversation_id = "test_conversation_id" @@ -215,13 +219,17 @@ def test_get_memories_with_json_properties(memory_interface: AzureSQLMemory): converter_identifiers=converter_identifiers, ) - memory_interface.add_conversation_to_memory( - conversation=Conversation(conversation_id=specific_conversation_id, target_identifier=target.get_identifier()) + ( + await memory_interface.add_conversation_to_memory_async( + conversation=Conversation( + conversation_id=specific_conversation_id, target_identifier=target.get_identifier() + ) + ) ) - memory_interface.add_message_pieces_to_memory(message_pieces=[piece]) + (await memory_interface.add_message_pieces_to_memory_async(message_pieces=[piece])) # Use the get_memories_with_conversation_id method to retrieve entries with the specific conversation_id - retrieved_entries = memory_interface.get_conversation_messages(conversation_id=specific_conversation_id) + retrieved_entries = await memory_interface.get_conversation_messages_async(conversation_id=specific_conversation_id) # Verify that the retrieved entry matches the inserted entry assert len(retrieved_entries) == 1 @@ -301,7 +309,7 @@ def test_get_message_pieces_memory_label_conditions_bind_params(uninitialized_me assert params == {"are_ml_operation": "test_op"} -def test_update_entries(memory_interface: AzureSQLMemory): +async def test_update_entries_async(memory_interface: AzureSQLMemory): # Insert a test entry entry = PromptMemoryEntry( entry=MessagePiece(conversation_id="123", role="user", original_value="Hello", converted_value="Hello") @@ -316,8 +324,8 @@ def test_update_entries(memory_interface: AzureSQLMemory): memory_interface._update_entries(entries=entries_to_update, update_fields={"original_value": "Updated Hello"}) # Verify the entry was updated - with memory_interface.get_session() as session: # type: ignore[arg-type] - updated_entry = session.query(PromptMemoryEntry).filter_by(conversation_id="123").first() + async with await memory_interface.get_session_async() as session: + updated_entry = (await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id="123"))).first() assert updated_entry.original_value == "Updated Hello" @@ -355,7 +363,7 @@ def test_update_entries_nonexistent_fields(memory_interface): ) -def test_update_prompt_entries_by_conversation_id(memory_interface: AzureSQLMemory, sample_conversation_entries): +async def test_update_prompt_entries_by_conversation_id(memory_interface: AzureSQLMemory, sample_conversation_entries): specific_conversation_id = "update_test_id" for entry in sample_conversation_entries: @@ -364,15 +372,17 @@ def test_update_prompt_entries_by_conversation_id(memory_interface: AzureSQLMemo memory_interface._insert_entries(entries=sample_conversation_entries) # Update the entry using the update_prompt_entries_by_conversation_id method - update_result = memory_interface.update_prompt_entries_by_conversation_id( + update_result = await memory_interface.update_prompt_entries_by_conversation_id_async( conversation_id=specific_conversation_id, update_fields={"original_value": "Updated Hello", "role": "assistant"} ) assert update_result is True # Verify the entry was updated - with memory_interface.get_session() as session: # type: ignore[arg-type] - updated_entries = session.query(PromptMemoryEntry).filter_by(conversation_id=specific_conversation_id) + async with await memory_interface.get_session_async() as session: + updated_entries = ( + await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id=specific_conversation_id)) + ).all() for entry in updated_entries: assert entry.original_value == "Updated Hello" assert entry.role == "assistant" @@ -446,8 +456,8 @@ def test_get_conversation_stats_uses_one_latest_row_apply( session = MagicMock() session.execute.return_value.fetchall.return_value = [] - with patch.object(uninitialized_memory_interface, "get_session", return_value=session): - result = uninitialized_memory_interface.get_conversation_stats(conversation_ids=["conversation"]) + with patch.object(uninitialized_memory_interface, "_get_session", return_value=session): + result = uninitialized_memory_interface._execute_get_conversation_stats(conversation_ids=["conversation"]) sql = str(session.execute.call_args.args[0]) assert result == {} @@ -642,7 +652,7 @@ def _normalize(condition) -> str: assert "EXISTS" not in _normalize(condition_any) -def test_update_prompt_metadata_by_conversation_id(memory_interface: AzureSQLMemory): +async def test_update_prompt_metadata_by_conversation_id(memory_interface: AzureSQLMemory): # Insert a test entry entry = PromptMemoryEntry( entry=MessagePiece( @@ -657,21 +667,24 @@ def test_update_prompt_metadata_by_conversation_id(memory_interface: AzureSQLMem memory_interface._insert_entry(entry) # Update the metadata using the update_prompt_metadata_by_conversation_id method - memory_interface.update_prompt_metadata_by_conversation_id( - conversation_id="123", prompt_metadata={"updated": "updated"} + ( + await memory_interface.update_prompt_metadata_by_conversation_id_async( + conversation_id="123", prompt_metadata={"updated": "updated"} + ) ) # Verify the metadata was updated - with memory_interface.get_session() as session: # type: ignore[arg-type] - updated_entry = session.query(PromptMemoryEntry).filter_by(conversation_id="123").first() + async with await memory_interface.get_session_async() as session: + updated_entry = (await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id="123"))).first() assert updated_entry.prompt_metadata == {"updated": "updated"} -def test_refresh_token_if_needed_raises_when_expiry_none(): +def test_refresh_token_if_needed_initializes_deferred_token(): obj = AzureSQLMemory.__new__(AzureSQLMemory) obj._auth_token_expiry = None - with pytest.raises(RuntimeError, match="Auth token expiry not initialized"): + with patch.object(obj, "_create_auth_token") as create_token: obj._refresh_token_if_needed() + create_token.assert_called_once() def test_provide_token_raises_when_auth_token_none(): diff --git a/tests/unit/memory/test_conversation_branching.py b/tests/unit/memory/test_conversation_branching.py index efcb9aff26..93603d9f82 100644 --- a/tests/unit/memory/test_conversation_branching.py +++ b/tests/unit/memory/test_conversation_branching.py @@ -3,18 +3,17 @@ """Atomic branch insertion and reference updates on real SQLite sessions.""" -import threading +import asyncio import uuid -from collections.abc import Generator -from concurrent.futures import ThreadPoolExecutor -from contextlib import closing +from collections.abc import AsyncGenerator from pathlib import Path -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock import pytest -from sqlalchemy import URL, create_engine, select +from sqlalchemy import create_engine, select from sqlalchemy.dialects import mssql, sqlite from sqlalchemy.exc import IntegrityError +from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.orm import Session, sessionmaker from pyrit.memory import MemoryInterface, SQLiteMemory @@ -25,6 +24,7 @@ PromptConverterIdentifierEntry, TargetIdentifierEntry, ) +from pyrit.memory.memory_session import MemorySession from pyrit.models import ( AttackResult, Conversation, @@ -35,48 +35,50 @@ MessagePiece, TargetIdentifier, ) +from unit.mocks import run_memory_session_async @pytest.fixture -def file_memory(*, sqlite_instance: SQLiteMemory, tmp_path: Path) -> Generator[SQLiteMemory, None, None]: - # Concurrent writers can exceed SQLite's default five-second lock wait on busy CI runners. - engine = create_engine(URL.create("sqlite", database=str(tmp_path / "branching.db")), connect_args={"timeout": 30}) +async def file_memory(*, tmp_path: Path) -> AsyncGenerator[SQLiteMemory, None]: + memory = SQLiteMemory.__new__(SQLiteMemory) + memory.__init__(db_path=tmp_path / "branching.db", skip_schema_migration=True) + memory.engine.dispose() + memory.engine = create_engine(memory.engine.url, connect_args={"timeout": 30}) + memory.SessionFactory = sessionmaker(bind=memory.engine, class_=MemorySession) + memory._async_engines[asyncio.get_running_loop()] = create_async_engine( + memory.engine.url.set(drivername="sqlite+aiosqlite"), connect_args={"timeout": 30} + ) try: - Base.metadata.create_all(engine) - with ( - patch.object(sqlite_instance, "engine", engine), - patch.object(sqlite_instance, "SessionFactory", sessionmaker(bind=engine)), - patch.object(sqlite_instance, "_connection_lock", None), - ): - yield sqlite_instance + Base.metadata.create_all(memory.engine) + yield memory finally: - engine.dispose() + await memory.dispose_engine_async() -def _store_attack(memory: MemoryInterface) -> tuple[AttackResult, Conversation]: +async def _store_attack_async(memory: MemoryInterface) -> tuple[AttackResult, Conversation]: source = Conversation( conversation_id=str(uuid.uuid4()), target_identifier=TargetIdentifier(class_name="ExampleTarget", class_module="tests.unit"), ) attack = AttackResult(conversation_id=source.conversation_id, objective="Atomic branches") - memory.add_attack_results_to_memory(attack_results=[attack]) - memory.add_conversation_to_memory(conversation=source) + (await memory.add_attack_results_to_memory_async(attack_results=[attack])) + (await memory.add_conversation_to_memory_async(conversation=source)) return attack, source -def _copy( +async def _copy_async( *, memory: MemoryInterface, source: Conversation, messages: list[Message] ) -> tuple[Conversation, list[MessagePiece]]: - conversation_id, pieces = memory.duplicate_messages(messages=messages) + conversation_id, pieces = await memory.duplicate_messages_async(messages=messages) return source.model_copy(update={"conversation_id": conversation_id}, deep=True), list(pieces) @pytest.mark.usefixtures("patch_central_database") class TestAtomicConversationBranching: - def test_copied_pieces_keep_all_lineage_metadata_order_and_identifier_links( + async def test_copied_pieces_keep_all_lineage_metadata_order_and_identifier_links( self, sqlite_instance: SQLiteMemory ) -> None: - attack, source = _store_attack(sqlite_instance) + attack, source = await _store_attack_async(sqlite_instance) converters = [ ConverterIdentifier(class_name="FirstConverter", class_module="tests.unit"), ConverterIdentifier(class_name="SecondConverter", class_module="tests.unit"), @@ -97,19 +99,19 @@ def test_copied_pieces_keep_all_lineage_metadata_order_and_identifier_links( for index in range(2) ] pieces[1].timestamp = pieces[0].timestamp - sqlite_instance.add_message_pieces_to_memory(message_pieces=pieces) - messages = list(sqlite_instance.get_conversation_messages(conversation_id=source.conversation_id)) - branch, copies = _copy(memory=sqlite_instance, source=source, messages=messages) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=pieces)) + messages = list(await sqlite_instance.get_conversation_messages_async(conversation_id=source.conversation_id)) + branch, copies = await _copy_async(memory=sqlite_instance, source=source, messages=messages) ephemeral = MessagePiece(role="user", original_value="not saved") ephemeral.not_in_memory = True - stored = sqlite_instance.add_conversation_branches_to_attack( + stored = await sqlite_instance.add_conversation_branches_to_attack_async( attack_result_id=attack.attack_result_id, source_conversation=source, conversations=[branch], message_pieces=[*copies, ephemeral], ) assert stored - saved = sqlite_instance.get_message_pieces(conversation_id=branch.conversation_id) + saved = await sqlite_instance.get_message_pieces_async(conversation_id=branch.conversation_id) assert [piece.original_prompt_id for piece in saved] == [piece.id for piece in pieces] assert [piece.original_value for piece in saved] == ["original-0", "original-1"] assert [piece.converted_value for piece in saved] == ["converted-0", "converted-1"] @@ -119,41 +121,46 @@ def test_copied_pieces_keep_all_lineage_metadata_order_and_identifier_links( assert [piece.original_value_sha256 for piece in saved] == ["original-hash-0", "original-hash-1"] assert [piece.converted_value_sha256 for piece in saved] == ["converted-hash-0", "converted-hash-1"] assert [piece.converter_identifiers for piece in saved] == [converters, converters] - assert sqlite_instance.get_message_pieces(prompt_ids=[ephemeral.id]) == [] - with closing(sqlite_instance.get_session()) as session: - links = session.scalars( + assert (await sqlite_instance.get_message_pieces_async(prompt_ids=[ephemeral.id])) == [] + + def load_links(session): + return session.scalars( select(PromptConverterIdentifierEntry).where( PromptConverterIdentifierEntry.prompt_memory_entry_id.in_([piece.id for piece in copies]) ) ).all() + + links = await run_memory_session_async(memory=sqlite_instance, operation=load_links) assert len(links) == 4 assert sorted(link.position for link in links) == [0, 0, 1, 1] - nested, nested_copies = _copy( + nested, nested_copies = await _copy_async( memory=sqlite_instance, source=branch, - messages=list(sqlite_instance.get_conversation_messages(conversation_id=branch.conversation_id)), + messages=list( + await sqlite_instance.get_conversation_messages_async(conversation_id=branch.conversation_id) + ), ) - assert sqlite_instance.add_conversation_branches_to_attack( + assert await sqlite_instance.add_conversation_branches_to_attack_async( attack_result_id=attack.attack_result_id, source_conversation=branch, conversations=[nested], message_pieces=nested_copies, ) - saved_nested = sqlite_instance.get_message_pieces(conversation_id=nested.conversation_id) + saved_nested = await sqlite_instance.get_message_pieces_async(conversation_id=nested.conversation_id) assert [piece.original_prompt_id for piece in saved_nested] == [piece.id for piece in pieces] assert {piece.id for piece in saved_nested}.isdisjoint(piece.id for piece in saved) - def test_empty_conversations_are_registered(self, sqlite_instance: SQLiteMemory) -> None: - attack, source = _store_attack(sqlite_instance) + async def test_empty_conversations_are_registered(self, sqlite_instance: SQLiteMemory) -> None: + attack, source = await _store_attack_async(sqlite_instance) branches = [source.model_copy(update={"conversation_id": str(uuid.uuid4())}, deep=True) for _ in range(4)] - assert sqlite_instance.add_conversation_branches_to_attack( + assert await sqlite_instance.add_conversation_branches_to_attack_async( attack_result_id=attack.attack_result_id, source_conversation=source, conversations=branches, message_pieces=[], ) - current = sqlite_instance.get_attack_results(attack_result_ids=[attack.attack_result_id])[0] + current = (await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]))[0] assert current.get_active_conversation_ids() == { source.conversation_id, *(item.conversation_id for item in branches), @@ -161,19 +168,19 @@ def test_empty_conversations_are_registered(self, sqlite_instance: SQLiteMemory) assert all(sqlite_instance._get_conversation(conversation_id=item.conversation_id) == item for item in branches) @pytest.mark.parametrize("source_registered", [False, True]) - def test_failed_piece_insert_rolls_back_conversations_references_and_identifiers( + async def test_failed_piece_insert_rolls_back_conversations_references_and_identifiers( self, *, sqlite_instance: SQLiteMemory, source_registered: bool ) -> None: source_target = TargetIdentifier(class_name="SourceTarget", class_module="tests.unit") source = Conversation(conversation_id=str(uuid.uuid4()), target_identifier=source_target) attack = AttackResult(conversation_id=source.conversation_id, objective="Atomic branches") - sqlite_instance.add_attack_results_to_memory(attack_results=[attack]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[attack])) if source_registered: - sqlite_instance.add_conversation_to_memory(conversation=source) + (await sqlite_instance.add_conversation_to_memory_async(conversation=source)) original = MessagePiece( conversation_id=source.conversation_id, role="user", original_value="Original", sequence=0 ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[original]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[original])) new_target = TargetIdentifier(class_name="NewTarget", class_module="tests.unit") new_converter = ConverterIdentifier(class_name="NewConverter", class_module="tests.unit") branch = Conversation(conversation_id=str(uuid.uuid4()), target_identifier=new_target) @@ -187,24 +194,28 @@ def test_failed_piece_insert_rolls_back_conversations_references_and_identifiers ) conflicting_piece = copied_piece.model_copy(deep=True, update={"id": original.id}) with pytest.raises(IntegrityError): - sqlite_instance.add_conversation_branches_to_attack( - attack_result_id=attack.attack_result_id, - source_conversation=source, - conversations=[branch], - message_pieces=[copied_piece, conflicting_piece], + ( + await sqlite_instance.add_conversation_branches_to_attack_async( + attack_result_id=attack.attack_result_id, + source_conversation=source, + conversations=[branch], + message_pieces=[copied_piece, conflicting_piece], + ) ) assert sqlite_instance._get_conversation(conversation_id=branch.conversation_id) is None assert sqlite_instance._get_conversation(conversation_id=source.conversation_id) == ( source if source_registered else None ) - current = sqlite_instance.get_attack_results(attack_result_ids=[attack.attack_result_id])[0] + current = (await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]))[0] assert current.related_conversations == set() assert current.timestamp == attack.timestamp - assert sqlite_instance.get_message_pieces(conversation_id=branch.conversation_id) == [] - assert [piece.id for piece in sqlite_instance.get_message_pieces(conversation_id=source.conversation_id)] == [ - original.id - ] - with closing(sqlite_instance.get_session()) as session: + assert (await sqlite_instance.get_message_pieces_async(conversation_id=branch.conversation_id)) == [] + assert [ + piece.id + for piece in (await sqlite_instance.get_message_pieces_async(conversation_id=source.conversation_id)) + ] == [original.id] + + def check_links(session): assert session.get(TargetIdentifierEntry, new_target.hash) is None assert session.get(ConverterIdentifierEntry, new_converter.hash) is None assert (session.get(TargetIdentifierEntry, source_target.hash) is not None) == source_registered @@ -217,36 +228,44 @@ def test_failed_piece_insert_rolls_back_conversations_references_and_identifiers == [] ) + await run_memory_session_async(memory=sqlite_instance, operation=check_links) + @pytest.mark.parametrize("column", [None, "adversarial_chat_conversation_ids", "preparation_conversation_ids"]) - def test_unrelated_and_diagnostic_sources_are_rejected( + async def test_unrelated_and_diagnostic_sources_are_rejected( self, *, sqlite_instance: SQLiteMemory, column: str | None ) -> None: - attack, source = _store_attack(sqlite_instance) + attack, source = await _store_attack_async(sqlite_instance) excluded = Conversation(conversation_id=str(uuid.uuid4())) if column: - sqlite_instance.update_attack_result_by_id( - attack_result_id=attack.attack_result_id, - update_fields={column: [excluded.conversation_id]}, + ( + await sqlite_instance.update_attack_result_by_id_async( + attack_result_id=attack.attack_result_id, + update_fields={column: [excluded.conversation_id]}, + ) ) branch = source.model_copy(update={"conversation_id": str(uuid.uuid4())}) with pytest.raises(ValueError, match="active objective"): - sqlite_instance.add_conversation_branches_to_attack( - attack_result_id=attack.attack_result_id, - source_conversation=excluded, - conversations=[branch], - message_pieces=[], + ( + await sqlite_instance.add_conversation_branches_to_attack_async( + attack_result_id=attack.attack_result_id, + source_conversation=excluded, + conversations=[branch], + message_pieces=[], + ) ) assert sqlite_instance._get_conversation(conversation_id=branch.conversation_id) is None - def test_missing_attack_cannot_leave_orphan_conversations(self, sqlite_instance: SQLiteMemory) -> None: + async def test_missing_attack_cannot_leave_orphan_conversations(self, sqlite_instance: SQLiteMemory) -> None: branch = Conversation(conversation_id=str(uuid.uuid4())) - assert not sqlite_instance.add_conversation_branches_to_attack( - attack_result_id=str(uuid.uuid4()), conversations=[branch], message_pieces=[] + assert not ( + await sqlite_instance.add_conversation_branches_to_attack_async( + attack_result_id=str(uuid.uuid4()), conversations=[branch], message_pieces=[] + ) ) assert sqlite_instance._get_conversation(conversation_id=branch.conversation_id) is None - def test_source_target_conflict_rolls_back_branch(self, sqlite_instance: SQLiteMemory) -> None: - attack, source = _store_attack(sqlite_instance) + async def test_source_target_conflict_rolls_back_branch(self, sqlite_instance: SQLiteMemory) -> None: + attack, source = await _store_attack_async(sqlite_instance) conflicting_source = source.model_copy( update={ "target_identifier": TargetIdentifier( @@ -259,21 +278,23 @@ def test_source_target_conflict_rolls_back_branch(self, sqlite_instance: SQLiteM branch = source.model_copy(update={"conversation_id": str(uuid.uuid4())}) with pytest.raises(ValueError, match="already registered with a different target"): - sqlite_instance.add_conversation_branches_to_attack( - attack_result_id=attack.attack_result_id, - source_conversation=conflicting_source, - conversations=[branch], - message_pieces=[], + ( + await sqlite_instance.add_conversation_branches_to_attack_async( + attack_result_id=attack.attack_result_id, + source_conversation=conflicting_source, + conversations=[branch], + message_pieces=[], + ) ) assert sqlite_instance._get_conversation(conversation_id=branch.conversation_id) is None assert sqlite_instance._get_conversation(conversation_id=source.conversation_id) == source - current = sqlite_instance.get_attack_results(attack_result_ids=[attack.attack_result_id])[0] + current = (await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]))[0] assert current.get_active_conversation_ids() == {source.conversation_id} @pytest.mark.parametrize("invalid", ["duplicate_id", "source_replacement", "wrong_piece_conversation"]) - def test_invalid_prepared_payload_rolls_back(self, *, sqlite_instance: SQLiteMemory, invalid: str) -> None: - attack, source = _store_attack(sqlite_instance) + async def test_invalid_prepared_payload_rolls_back(self, *, sqlite_instance: SQLiteMemory, invalid: str) -> None: + attack, source = await _store_attack_async(sqlite_instance) branch = source.model_copy(update={"conversation_id": str(uuid.uuid4())}) conversations = [branch, branch] if invalid == "duplicate_id" else [branch] pieces: list[MessagePiece] = [] @@ -282,43 +303,53 @@ def test_invalid_prepared_payload_rolls_back(self, *, sqlite_instance: SQLiteMem if invalid == "wrong_piece_conversation": pieces = [MessagePiece(role="user", original_value="Wrong", conversation_id=source.conversation_id)] with pytest.raises(ValueError): - sqlite_instance.add_conversation_branches_to_attack( - attack_result_id=attack.attack_result_id, - source_conversation=source, - conversations=conversations, - message_pieces=pieces, + ( + await sqlite_instance.add_conversation_branches_to_attack_async( + attack_result_id=attack.attack_result_id, + source_conversation=source, + conversations=conversations, + message_pieces=pieces, + ) ) assert sqlite_instance._get_conversation(conversation_id=branch.conversation_id) is None - def test_concurrent_branch_creation_and_promotions_preserve_membership(self, file_memory: SQLiteMemory) -> None: - attack, source = _store_attack(file_memory) + async def test_concurrent_branch_creation_and_promotions_preserve_membership( + self, file_memory: SQLiteMemory + ) -> None: + attack, source = await _store_attack_async(file_memory) initial = [Conversation(conversation_id=str(uuid.uuid4())) for _ in range(2)] - file_memory.add_conversation_branches_to_attack( - attack_result_id=attack.attack_result_id, conversations=initial, message_pieces=[] + ( + await file_memory.add_conversation_branches_to_attack_async( + attack_result_id=attack.attack_result_id, conversations=initial, message_pieces=[] + ) ) branches = [Conversation(conversation_id=str(uuid.uuid4())) for _ in range(8)] - start = threading.Barrier(10) + start = asyncio.Barrier(10) - def register(*, conversation: Conversation) -> bool: - start.wait(timeout=10) - return file_memory.add_conversation_branches_to_attack( + async def register_async(*, conversation: Conversation) -> bool: + await asyncio.wait_for(start.wait(), timeout=10) + return await file_memory.add_conversation_branches_to_attack_async( attack_result_id=attack.attack_result_id, source_conversation=source, conversations=[conversation], message_pieces=[], ) - def promote(*, conversation_id: str) -> bool: - start.wait(timeout=10) - return file_memory.promote_attack_conversation( + async def promote_async(*, conversation_id: str) -> bool: + await asyncio.wait_for(start.wait(), timeout=10) + return await file_memory.promote_attack_conversation_async( attack_result_id=attack.attack_result_id, conversation_id=conversation_id ) - with ThreadPoolExecutor(max_workers=10) as executor: - futures = [executor.submit(register, conversation=branch) for branch in branches] - futures += [executor.submit(promote, conversation_id=branch.conversation_id) for branch in initial] - assert all(future.result(timeout=60) for future in futures) - current = file_memory.get_attack_results(attack_result_ids=[attack.attack_result_id])[0] + results = await asyncio.wait_for( + asyncio.gather( + *(register_async(conversation=branch) for branch in branches), + *(promote_async(conversation_id=branch.conversation_id) for branch in initial), + ), + timeout=60, + ) + assert all(results) + current = (await file_memory.get_attack_results_async(attack_result_ids=[attack.attack_result_id]))[0] assert current.get_active_conversation_ids() == { source.conversation_id, *(branch.conversation_id for branch in [*initial, *branches]), @@ -326,22 +357,26 @@ def promote(*, conversation_id: str) -> bool: assert current.conversation_id in {branch.conversation_id for branch in initial} assert len(current.get_pruned_conversation_ids()) == 10 - def test_promotion_preserves_diagnostic_and_prior_pruned_references(self, sqlite_instance: SQLiteMemory) -> None: - attack, source = _store_attack(sqlite_instance) + async def test_promotion_preserves_diagnostic_and_prior_pruned_references( + self, sqlite_instance: SQLiteMemory + ) -> None: + attack, source = await _store_attack_async(sqlite_instance) promoted, other = str(uuid.uuid4()), str(uuid.uuid4()) adversarial, preparation = str(uuid.uuid4()), str(uuid.uuid4()) - sqlite_instance.update_attack_result_by_id( - attack_result_id=attack.attack_result_id, - update_fields={ - "adversarial_chat_conversation_ids": [adversarial], - "preparation_conversation_ids": [preparation], - "pruned_conversation_ids": [promoted, other], - }, + ( + await sqlite_instance.update_attack_result_by_id_async( + attack_result_id=attack.attack_result_id, + update_fields={ + "adversarial_chat_conversation_ids": [adversarial], + "preparation_conversation_ids": [preparation], + "pruned_conversation_ids": [promoted, other], + }, + ) ) - assert sqlite_instance.promote_attack_conversation( + assert await sqlite_instance.promote_attack_conversation_async( attack_result_id=attack.attack_result_id, conversation_id=promoted ) - current = sqlite_instance.get_attack_results(attack_result_ids=[attack.attack_result_id])[0] + current = (await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]))[0] assert current.conversation_id == promoted assert current.get_active_conversation_ids() == {source.conversation_id, promoted, other} assert set(current.get_pruned_conversation_ids()) == {source.conversation_id, other} @@ -350,30 +385,40 @@ def test_promotion_preserves_diagnostic_and_prior_pruned_references(self, sqlite ConversationReference(conversation_id=preparation, conversation_type=ConversationType.PREPARATION), } <= current.related_conversations - assert sqlite_instance.promote_attack_conversation( + assert await sqlite_instance.promote_attack_conversation_async( attack_result_id=attack.attack_result_id, conversation_id=promoted ) - assert sqlite_instance.get_attack_results(attack_result_ids=[attack.attack_result_id])[0] == current + assert (await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]))[ + 0 + ] == current @pytest.mark.parametrize("column", ["adversarial_chat_conversation_ids", "preparation_conversation_ids"]) - def test_promotion_rejects_diagnostic_conversations(self, *, sqlite_instance: SQLiteMemory, column: str) -> None: - attack, source = _store_attack(sqlite_instance) + async def test_promotion_rejects_diagnostic_conversations( + self, *, sqlite_instance: SQLiteMemory, column: str + ) -> None: + attack, source = await _store_attack_async(sqlite_instance) diagnostic = str(uuid.uuid4()) - sqlite_instance.update_attack_result_by_id( - attack_result_id=attack.attack_result_id, - update_fields={column: [diagnostic]}, + ( + await sqlite_instance.update_attack_result_by_id_async( + attack_result_id=attack.attack_result_id, + update_fields={column: [diagnostic]}, + ) ) with pytest.raises(ValueError, match="not part of this attack"): - sqlite_instance.promote_attack_conversation( - attack_result_id=attack.attack_result_id, conversation_id=diagnostic + ( + await sqlite_instance.promote_attack_conversation_async( + attack_result_id=attack.attack_result_id, conversation_id=diagnostic + ) ) - current = sqlite_instance.get_attack_results(attack_result_ids=[attack.attack_result_id])[0] + current = (await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]))[0] assert current.conversation_id == source.conversation_id assert current.get_active_conversation_ids() == {source.conversation_id} - def test_promotion_returns_false_for_missing_attack(self, sqlite_instance: SQLiteMemory) -> None: - assert not sqlite_instance.promote_attack_conversation( - attack_result_id=str(uuid.uuid4()), conversation_id=str(uuid.uuid4()) + async def test_promotion_returns_false_for_missing_attack(self, sqlite_instance: SQLiteMemory) -> None: + assert not ( + await sqlite_instance.promote_attack_conversation_async( + attack_result_id=str(uuid.uuid4()), conversation_id=str(uuid.uuid4()) + ) ) diff --git a/tests/unit/memory/test_memory_models.py b/tests/unit/memory/test_memory_models.py index e4e345ed69..297f611f89 100644 --- a/tests/unit/memory/test_memory_models.py +++ b/tests/unit/memory/test_memory_models.py @@ -10,8 +10,8 @@ import pytest from pydantic import ValidationError -from sqlalchemy import create_engine, select -from sqlalchemy.orm import MappedColumn, Session +from sqlalchemy import select +from sqlalchemy.orm import MappedColumn from pyrit.memory import SQLiteMemory from pyrit.memory.memory_models import ( @@ -300,7 +300,7 @@ class IncompleteIdentifierEntry(ComponentIdentifierEntry[IdentifierWithPromotedS Base.metadata.remove(table) -def test_atomic_attack_identifier_graph_persists_with_result_link() -> None: +async def test_atomic_attack_identifier_graph_persists_with_result_link(sqlite_instance: SQLiteMemory) -> None: target = TargetIdentifier(class_name="Target", class_module="pyrit.prompt_target", model_name="model") scorer = ScorerIdentifier(class_name="Scorer", class_module="pyrit.score", scorer_type="true_false") converter = ConverterIdentifier( @@ -343,35 +343,28 @@ def test_atomic_attack_identifier_graph_persists_with_result_link() -> None: ) result = AttackResult(conversation_id="conversation", objective="objective", atomic_attack_identifier=atomic) - engine = create_engine("sqlite:///:memory:") - Base.metadata.create_all(engine) - from pyrit.memory import MemoryInterface + await sqlite_instance.add_attack_results_to_memory_async(attack_results=[result]) - memory = MagicMock(spec=MemoryInterface) - memory.get_session.side_effect = lambda: Session(engine) - memory._persist_identifier.side_effect = lambda *, session, identifier: MemoryInterface._persist_identifier( - session=session, identifier=identifier - ) - MemoryInterface.add_attack_results_to_memory(memory, attack_results=[result]) - - with Session(engine) as session: - assert session.scalar(select(AttackResultEntry.atomic_attack_identifier_hash)) == atomic.hash - assert session.scalar(select(AtomicAttackIdentifierEntry.hash)) == atomic.hash - assert session.scalar(select(AttackTechniqueIdentifierEntry.hash)) == technique.hash - assert session.scalar(select(AttackIdentifierEntry.hash)) == attack.hash - assert len(session.scalars(select(SeedIdentifierEntry)).all()) == 2 + async with await sqlite_instance.get_session_async() as session: + assert await session.scalar(select(AttackResultEntry.atomic_attack_identifier_hash)) == atomic.hash + assert await session.scalar(select(AtomicAttackIdentifierEntry.hash)) == atomic.hash + assert await session.scalar(select(AttackTechniqueIdentifierEntry.hash)) == technique.hash + assert await session.scalar(select(AttackIdentifierEntry.hash)) == attack.hash + assert len((await session.scalars(select(SeedIdentifierEntry))).all()) == 2 - technique_edge = session.scalar(select(AttackTechniqueSeedIdentifierEntry)) + technique_edge = await session.scalar(select(AttackTechniqueSeedIdentifierEntry)) assert technique_edge is not None assert (technique_edge.position, technique_edge.seed_identifier_hash) == (0, technique_seed.hash) - atomic_edges = session.scalars( - select(AtomicAttackSeedIdentifierEntry).order_by(AtomicAttackSeedIdentifierEntry.position) + atomic_edges = ( + await session.scalars( + select(AtomicAttackSeedIdentifierEntry).order_by(AtomicAttackSeedIdentifierEntry.position) + ) ).all() assert [edge.seed_identifier_hash for edge in atomic_edges] == [technique_seed.hash, dataset_seed.hash] - request_edge = session.scalar(select(AttackRequestConverterIdentifierEntry)) + request_edge = await session.scalar(select(AttackRequestConverterIdentifierEntry)) assert request_edge is not None assert (request_edge.position, request_edge.converter_identifier_hash) == (0, converter.hash) - response_edge = session.scalar(select(AttackResponseConverterIdentifierEntry)) + response_edge = await session.scalar(select(AttackResponseConverterIdentifierEntry)) assert response_edge is not None assert (response_edge.position, response_edge.converter_identifier_hash) == (0, converter.hash) @@ -416,11 +409,11 @@ def test_embedding_message_with_similarity_forbids_extra(): @pytest.mark.usefixtures("patch_central_database") class TestPromptMemoryEntry: - def test_empty_converted_value_survives_persistence_reload(self, sqlite_instance: SQLiteMemory) -> None: + async def test_empty_converted_value_survives_persistence_reload(self, sqlite_instance: SQLiteMemory) -> None: piece = _make_message_piece(original_value="Original nonempty source", converted_value="") - sqlite_instance.add_message_pieces_to_memory(message_pieces=[piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[piece])) - recovered = sqlite_instance.get_message_pieces(prompt_ids=[str(piece.id)]) + recovered = await sqlite_instance.get_message_pieces_async(prompt_ids=[str(piece.id)]) assert len(recovered) == 1 assert recovered[0] is not piece diff --git a/tests/unit/memory/test_scenario_history.py b/tests/unit/memory/test_scenario_history.py index a7d376bd2e..ba2f77e865 100644 --- a/tests/unit/memory/test_scenario_history.py +++ b/tests/unit/memory/test_scenario_history.py @@ -80,7 +80,7 @@ def test_get_scenario_run_history_page_delegates_to_component(sqlite_instance: M with ( patch.object(_ScenarioHistoryQueries, "get_page", return_value=(records, True)) as mock_get_page, - patch.object(sqlite_instance, "get_scenario_history_aggregates", return_value={}) as mock_aggregates, + patch.object(sqlite_instance, "_execute_get_scenario_history_aggregates", return_value={}) as mock_aggregates, ): result = sqlite_instance.get_scenario_run_history_page(scenario_names=["Test"], limit=50) @@ -103,7 +103,7 @@ def test_get_page_rejects_invalid_limit(sqlite_instance: MemoryInterface, limit: """Limit outside 1..100 raises before any session is opened.""" component = _ScenarioHistoryQueries(memory=sqlite_instance) with ( - patch.object(sqlite_instance, "get_session", side_effect=AssertionError("session opened before validation")), + patch.object(sqlite_instance, "_get_session", side_effect=AssertionError("session opened before validation")), pytest.raises(ValueError, match="between 1 and 100"), ): _get_page(component, limit=limit) diff --git a/tests/unit/memory/test_seed_conditions.py b/tests/unit/memory/test_seed_conditions.py index 0766e571e5..187ebbb985 100644 --- a/tests/unit/memory/test_seed_conditions.py +++ b/tests/unit/memory/test_seed_conditions.py @@ -13,6 +13,7 @@ from pyrit.memory.memory_models import SeedEntry, SeedIdentifierEntry from pyrit.models import AnswerMatches, MatchesObjective, SeedGroup, SeedIdentifier, SeedObjective, SeedPrompt from pyrit.models.identifiers.seed_identifier import compute_seed_group_hash +from unit.mocks import run_memory_session_async def _objective(*, answer: str = "Paris", dataset: str | None = "questions") -> SeedObjective: @@ -31,7 +32,7 @@ async def test_reloaded_companion_is_retained_without_duplicate_id_async( ) -> None: original = SeedGroup(seeds=[SeedPrompt(value="Choose an answer.")]) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[original], added_by="tester") - [prompt] = sqlite_instance.get_seeds() + [prompt] = await sqlite_instance.get_seeds_async() original_id = prompt.id original_group_id = prompt.prompt_group_id group_id = uuid.uuid4() if copy_to_new_group else original_group_id @@ -43,7 +44,7 @@ async def test_reloaded_companion_is_retained_without_duplicate_id_async( await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group], added_by="tester") - [restored] = sqlite_instance.get_seed_groups(prompt_group_ids=[group_id]) + [restored] = await sqlite_instance.get_seed_groups_async(prompt_group_ids=[group_id]) assert len(restored.seeds) == 3 assert restored.scoring_expectation.conditions == objective.conditions companion = next(seed for seed in restored.seeds if seed.value == prompt.value) @@ -51,18 +52,20 @@ async def test_reloaded_companion_is_retained_without_duplicate_id_async( assert prompt.id == companion.id assert {seed.id for seed in group.seeds} == {seed.id for seed in restored.seeds} [original_prompt] = [ - seed for seed in sqlite_instance.get_seeds(prompt_group_ids=[original_group_id]) if seed.id == original_id + seed + for seed in (await sqlite_instance.get_seeds_async(prompt_group_ids=[original_group_id])) + if seed.id == original_id ] assert original_prompt.prompt_group_id == original_group_id await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group], added_by="tester") - assert len(sqlite_instance.get_seeds()) == (4 if copy_to_new_group else 3) + assert len(await sqlite_instance.get_seeds_async()) == (4 if copy_to_new_group else 3) async def test_copied_seed_id_changes_only_after_successful_insert_async( self, sqlite_instance: MemoryInterface ) -> None: original = SeedGroup(seeds=[SeedPrompt(value="Choose an answer.")]) await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[original], added_by="tester") - [prompt] = sqlite_instance.get_seeds() + [prompt] = await sqlite_instance.get_seeds_async() original_id = prompt.id prompt.prompt_group_id = uuid.uuid4() group = SeedGroup(seeds=[prompt, _objective()]) @@ -73,24 +76,25 @@ async def test_copied_seed_id_changes_only_after_successful_insert_async( await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group], added_by="tester") assert prompt.id == original_id - assert len(sqlite_instance.get_seeds()) == 1 + assert len(await sqlite_instance.get_seeds_async()) == 1 await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=[group], added_by="tester") - [restored] = sqlite_instance.get_seed_groups(prompt_group_ids=[prompt.prompt_group_id]) + [restored] = await sqlite_instance.get_seed_groups_async(prompt_group_ids=[prompt.prompt_group_id]) assert prompt.id != original_id assert {seed.id for seed in group.seeds} == {seed.id for seed in restored.seeds} - assert len(sqlite_instance.get_seeds()) == 3 + assert len(await sqlite_instance.get_seeds_async()) == 3 async def test_seed_entry_roundtrip_async(self, sqlite_instance: MemoryInterface) -> None: objective = _objective() await sqlite_instance.add_seeds_to_memory_async(seeds=[objective], added_by="tester") - with sqlite_instance.get_session() as session: + def read_entry(session): entry = session.scalars(select(SeedEntry)).one() assert entry.conditions == [ {"condition_type": "answer_matches", "correct_answer": "Paris", "correct_answer_label": "A"} ] - restored = entry.get_seed() + return entry.get_seed() + restored = await run_memory_session_async(memory=sqlite_instance, operation=read_entry) assert isinstance(restored, SeedObjective) assert isinstance(restored.conditions[0], AnswerMatches) assert restored.conditions == objective.conditions @@ -103,7 +107,7 @@ async def test_group_reload_keeps_distinct_criteria_async(self, sqlite_instance: ] await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=groups, added_by="tester") - reloaded = sqlite_instance.get_seed_groups() + reloaded = await sqlite_instance.get_seed_groups_async() assert len(reloaded) == 2 assert all(len(group.seeds) == 2 for group in reloaded) assert {group.scoring_expectation.conditions[0].correct_answer for group in reloaded} == {"Paris", "Rome"} @@ -143,7 +147,7 @@ async def test_new_criteria_keep_complete_groups_across_calls_async( else: await sqlite_instance.add_seeds_to_memory_async(seeds=group.seeds, added_by="tester") - restored = sqlite_instance.get_seed_groups() + restored = await sqlite_instance.get_seed_groups_async() assert len(restored) == 2 assert all(len(group.seeds) == 2 for group in restored) assert { @@ -153,16 +157,19 @@ async def test_new_criteria_keep_complete_groups_across_calls_async( for group in original_groups } await sqlite_instance.add_seed_groups_to_memory_async(prompt_groups=original_groups, added_by="tester") - assert len(sqlite_instance.get_seeds()) == 4 + assert len(await sqlite_instance.get_seeds_async()) == 4 async def test_legacy_null_and_nonobjective_conditions_async(self, sqlite_instance: MemoryInterface) -> None: seeds = [SeedObjective(value="legacy"), SeedPrompt(value="prompt", data_type="text")] await sqlite_instance.add_seeds_to_memory_async(seeds=seeds, added_by="tester") - with sqlite_instance.get_session() as session: + + def clear_conditions(session): session.execute(update(SeedEntry).values(conditions=None)) session.commit() assert all(entry.conditions is None for entry in session.scalars(select(SeedEntry))) - restored = sqlite_instance.get_seeds() + + await run_memory_session_async(memory=sqlite_instance, operation=clear_conditions) + restored = await sqlite_instance.get_seeds_async() objective = next(seed for seed in restored if isinstance(seed, SeedObjective)) assert objective.conditions == () prompt = next(seed for seed in restored if isinstance(seed, SeedPrompt)) @@ -188,11 +195,11 @@ async def test_invalid_persisted_conditions_raise_async( self, *, sqlite_instance: MemoryInterface, payload: object ) -> None: await sqlite_instance.add_seeds_to_memory_async(seeds=[_objective()], added_by="tester") - with sqlite_instance.get_session() as session: - session.execute(update(SeedEntry).values(conditions=payload)) - session.commit() + async with await sqlite_instance.get_session_async() as session: + await session.execute(update(SeedEntry).values(conditions=payload)) + await session.commit() with pytest.raises(ValueError, match="condition|correct_answer_label|at least 1 character"): - sqlite_instance.get_seeds() + (await sqlite_instance.get_seeds_async()) def test_nonobjective_persisted_conditions_raise(self) -> None: entry = SeedEntry(entry=SeedPrompt(value="prompt", data_type="text")) @@ -211,7 +218,7 @@ async def test_dedup_preserves_different_conditions_across_calls_async( await sqlite_instance.add_seeds_to_memory_async( seeds=[_objective(answer="Rome", dataset=dataset)], added_by="tester" ) - stored = sqlite_instance.get_seeds() + stored = await sqlite_instance.get_seeds_async() assert len(stored) == 2 assert len({seed.value_sha256 for seed in stored}) == 1 assert {seed.conditions[0].correct_answer for seed in stored} == {"Paris", "Rome"} @@ -226,13 +233,13 @@ async def test_dedup_keeps_condition_free_and_condition_bearing_seeds_async( await sqlite_instance.add_seeds_to_memory_async( seeds=[SeedObjective(value=plain.value, dataset_name=plain.dataset_name)], added_by="tester" ) - assert len(sqlite_instance.get_seeds()) == 2 + assert len(await sqlite_instance.get_seeds_async()) == 2 async def test_duplicates_within_input_are_not_collapsed_async(self, sqlite_instance: MemoryInterface) -> None: await sqlite_instance.add_seeds_to_memory_async( seeds=[_objective(), _objective(), _objective(answer="Rome")], added_by="tester" ) - assert len(sqlite_instance.get_seeds()) == 3 + assert len(await sqlite_instance.get_seeds_async()) == 3 async def test_condition_order_is_identity_but_object_key_order_is_not_async( self, sqlite_instance: MemoryInterface @@ -251,7 +258,7 @@ async def test_condition_order_is_identity_but_object_key_order_is_not_async( ) await sqlite_instance.add_seeds_to_memory_async(seeds=[first], added_by="tester") await sqlite_instance.add_seeds_to_memory_async(seeds=[reordered, equivalent], added_by="tester") - assert len(sqlite_instance.get_seeds()) == 2 + assert len(await sqlite_instance.get_seeds_async()) == 2 @pytest.mark.parametrize( ("collation", "stored_dataset", "incoming_dataset"), @@ -273,7 +280,7 @@ async def test_condition_dedup_respects_database_collation_async( seeds=[_objective(dataset=incoming_dataset), _objective(answer="Rome", dataset=incoming_dataset)], added_by="tester", ) - assert len(sqlite_instance.get_seeds()) == 2 + assert len(await sqlite_instance.get_seeds_async()) == 2 finally: table.c.dataset_name.type = original_type @@ -289,17 +296,17 @@ async def test_condition_lookup_remains_bounded_async(self, sqlite_instance: Mem ] with ( patch.object(type(sqlite_instance), "_MAX_BIND_VARS", 5), - patch.object(sqlite_instance, "get_seeds", wraps=sqlite_instance.get_seeds) as lookup, + patch.object(sqlite_instance, "_execute_get_seeds", wraps=sqlite_instance._execute_get_seeds) as lookup, ): await sqlite_instance.add_seeds_to_memory_async(seeds=seeds, added_by="tester") assert [len(call.kwargs["value_sha256"]) for call in lookup.call_args_list] == [4, 4, 4] - assert len(sqlite_instance.get_seeds()) == 24 + assert len(await sqlite_instance.get_seeds_async()) == 24 - def test_identifier_json_roundtrip(self, sqlite_instance: MemoryInterface) -> None: + async def test_identifier_json_roundtrip(self, sqlite_instance: MemoryInterface) -> None: identifier = SeedIdentifier.from_seed(_objective()) - with sqlite_instance.get_session() as session: + async with await sqlite_instance.get_session_async() as session: session.add(SeedIdentifierEntry.from_domain_model(identifier)) - session.commit() - restored = sqlite_instance.get_seed_identifiers()[0] + await session.commit() + restored = (await sqlite_instance.get_seed_identifiers_async())[0] assert restored.params["conditions"] == identifier.params["conditions"] assert restored.hash == identifier.hash diff --git a/tests/unit/memory/test_sqlite_fixtures.py b/tests/unit/memory/test_sqlite_fixtures.py index 5405d6bf61..3e84ec5f0c 100644 --- a/tests/unit/memory/test_sqlite_fixtures.py +++ b/tests/unit/memory/test_sqlite_fixtures.py @@ -1,12 +1,12 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import asyncio import gc import sqlite3 import weakref from collections.abc import Generator -from concurrent.futures import ThreadPoolExecutor -from contextlib import closing, contextmanager +from contextlib import asynccontextmanager, closing, contextmanager from pathlib import Path from unittest.mock import MagicMock, patch @@ -20,7 +20,7 @@ from pyrit.models import MessagePiece from unit import conftest as unit_fixtures -_sqlite_instance = contextmanager(unit_fixtures.sqlite_instance.__wrapped__) +_sqlite_instance = asynccontextmanager(unit_fixtures.sqlite_instance.__wrapped__) _sqlite_template = contextmanager(unit_fixtures.sqlite_template.__wrapped__) @@ -28,8 +28,9 @@ def sqlite_connections() -> Generator[list[sqlite3.Connection], None, None]: connections: list[sqlite3.Connection] = [] - def record_connection(*, dbapi_connection: sqlite3.Connection, connection_record: ConnectionPoolEntry) -> None: - connections.append(dbapi_connection) + def record_connection(*, dbapi_connection: object, connection_record: ConnectionPoolEntry) -> None: + if isinstance(dbapi_connection, sqlite3.Connection): + connections.append(dbapi_connection) event.listen(Engine, "connect", record_connection, named=True) try: @@ -73,15 +74,17 @@ def _schema_snapshot(engine: Engine) -> dict[str, object]: return {"tables": tables, "revisions": revisions} -def test_sqlite_template_migrates_once_and_closes_connections(sqlite_connections: list[sqlite3.Connection]) -> None: +async def test_sqlite_template_migrates_once_and_closes_connections( + sqlite_connections: list[sqlite3.Connection], +) -> None: with ( patch.object(migration, "run_schema_migrations", wraps=migration.run_schema_migrations) as migrate, patch.object(migration, "check_schema_migrations", wraps=migration.check_schema_migrations) as check, _sqlite_template() as template, ): for _ in range(3): - with _sqlite_instance(sqlite_template=template) as memory: - assert memory.get_message_pieces() == [] + async with _sqlite_instance(sqlite_template=template) as memory: + assert (await memory.get_message_pieces_async()) == [] migrate.assert_called_once() check.assert_called_once() assert template.execute("PRAGMA query_only").fetchone() == (1,) @@ -124,13 +127,13 @@ def test_sqlite_instance_copies_migrated_schema_and_revision(sqlite_instance: SQ engine.dispose() -def test_sqlite_instance_isolates_rows_schema_and_results( +async def test_sqlite_instance_isolates_rows_schema_and_results( *, sqlite_template: sqlite3.Connection, sqlite_connections: list[sqlite3.Connection] ) -> None: previous_memory = None previous_results_path = None for _ in range(3): - with _sqlite_instance(sqlite_template=sqlite_template) as memory: + async with _sqlite_instance(sqlite_template=sqlite_template) as memory: assert memory is not previous_memory assert memory.results_path != previous_results_path assert memory.memory_embedding is None @@ -157,7 +160,7 @@ def test_sqlite_instance_isolates_rows_schema_and_results( ) ) ) - assert len(memory.get_message_pieces()) == 1 + assert len(await memory.get_message_pieces_async()) == 1 with memory.engine.begin() as connection: connection.execute(text("CREATE TABLE fixture_extra (id INTEGER)")) connection.execute(text("CREATE TEMP TABLE fixture_temp (id INTEGER)")) @@ -174,7 +177,7 @@ def test_sqlite_instance_isolates_rows_schema_and_results( @pytest.mark.parametrize("has_previous", [False, True]) -def test_sqlite_instance_restores_only_its_memory_registration( +async def test_sqlite_instance_restores_only_its_memory_registration( *, sqlite_template: sqlite3.Connection, has_previous: bool ) -> None: class UnrelatedSingleton(metaclass=Singleton): @@ -187,7 +190,7 @@ class UnrelatedSingleton(metaclass=Singleton): Singleton._instances[SQLiteMemory] = previous_memory else: Singleton._instances.pop(SQLiteMemory, None) - with _sqlite_instance(sqlite_template=sqlite_template) as memory: + async with _sqlite_instance(sqlite_template=sqlite_template) as memory: assert Singleton._instances[SQLiteMemory] is memory assert CentralMemory.get_memory_instance() is memory unrelated = UnrelatedSingleton() @@ -196,23 +199,23 @@ class UnrelatedSingleton(metaclass=Singleton): assert CentralMemory._memory_instance is previous_central -def test_sqlite_instance_does_not_modify_an_existing_database(sqlite_template: sqlite3.Connection) -> None: - with _sqlite_instance(sqlite_template=sqlite_template) as previous: +async def test_sqlite_instance_does_not_modify_an_existing_database(sqlite_template: sqlite3.Connection) -> None: + async with _sqlite_instance(sqlite_template=sqlite_template) as previous: previous._insert_entry( PromptMemoryEntry( entry=MessagePiece(role="user", original_value="previous data", conversation_id="previous-conversation") ) ) - with _sqlite_instance(sqlite_template=sqlite_template) as current: + async with _sqlite_instance(sqlite_template=sqlite_template) as current: assert current.engine is not previous.engine - assert current.get_message_pieces() == [] + assert (await current.get_message_pieces_async()) == [] assert SQLiteMemory() is previous assert CentralMemory.get_memory_instance() is previous - assert previous.get_message_pieces()[0].original_value == "previous data" + assert (await previous.get_message_pieces_async())[0].original_value == "previous data" @pytest.mark.parametrize("failure", ["backup", "test"]) -def test_sqlite_instance_cleans_up_on_failure( +async def test_sqlite_instance_cleans_up_on_failure( *, sqlite_template: sqlite3.Connection, sqlite_connections: list[sqlite3.Connection], failure: str ) -> None: with closing(sqlite3.connect(":memory:")) as closed_template: @@ -224,10 +227,12 @@ def test_sqlite_instance_cleans_up_on_failure( with ( patch.dict(Singleton._instances, {SQLiteMemory: previous_memory}), patch.object(CentralMemory, "_memory_instance", previous_central), - patch.object(SQLiteMemory, "dispose_engine", autospec=True, side_effect=SQLiteMemory.dispose_engine) as dispose, + patch.object( + SQLiteMemory, "dispose_engine_async", autospec=True, side_effect=SQLiteMemory.dispose_engine_async + ) as dispose, ): with pytest.raises(expected_error, match="closed|test failed"): - with _sqlite_instance(sqlite_template=template): + async with _sqlite_instance(sqlite_template=template): raise RuntimeError("test failed") dispose.assert_called_once() memory = dispose.call_args.args[0] @@ -237,8 +242,8 @@ def test_sqlite_instance_cleans_up_on_failure( _assert_closed(sqlite_connections) -def test_sqlite_instance_does_not_retain_process_exit_cleanup(sqlite_template: sqlite3.Connection) -> None: - with _sqlite_instance(sqlite_template=sqlite_template) as memory: +async def test_sqlite_instance_does_not_retain_process_exit_cleanup(sqlite_template: sqlite3.Connection) -> None: + async with _sqlite_instance(sqlite_template=sqlite_template) as memory: assert memory.cleanup.__func__ is MemoryInterface.cleanup assert "cleanup" not in memory.__dict__ memory_reference = weakref.ref(memory) @@ -247,7 +252,7 @@ def test_sqlite_instance_does_not_retain_process_exit_cleanup(sqlite_template: s assert memory_reference() is None -def test_sqlite_instance_reset_still_runs_real_migrations(sqlite_instance: SQLiteMemory) -> None: +async def test_sqlite_instance_reset_still_runs_real_migrations(sqlite_instance: SQLiteMemory) -> None: before = _schema_snapshot(sqlite_instance.engine) sqlite_instance._insert_entry( PromptMemoryEntry( @@ -257,28 +262,26 @@ def test_sqlite_instance_reset_still_runs_real_migrations(sqlite_instance: SQLit with sqlite_instance.engine.begin() as connection: connection.execute(text('DROP TABLE "ScoreEntries"')) with patch.object(migration.command, "upgrade", wraps=migration.command.upgrade) as upgrade: - sqlite_instance.reset_database() + await sqlite_instance.reset_database_async() upgrade.assert_called_once() assert upgrade.call_args.args[1] == "head" - assert sqlite_instance.get_message_pieces() == [] + assert (await sqlite_instance.get_message_pieces_async()) == [] assert _schema_snapshot(sqlite_instance.engine) == before -def test_sqlite_instance_keeps_real_threaded_sessions(sqlite_instance: SQLiteMemory) -> None: +async def test_sqlite_instance_keeps_real_async_sessions_async(sqlite_instance: SQLiteMemory) -> None: with sqlite_instance.engine.begin() as connection: connection.execute(text("CREATE TABLE fixture_threads (value INTEGER)")) - def write_rows(worker: int) -> None: + async def write_rows_async(worker: int) -> None: assert CentralMemory.get_memory_instance() is sqlite_instance for index in range(10): - with closing(sqlite_instance.get_session()) as session: - session.execute( + async with await sqlite_instance.get_session_async() as session: + await session.execute( text("INSERT INTO fixture_threads (value) VALUES (:value)"), {"value": worker * 10 + index} ) - session.commit() + await session.commit() - with ThreadPoolExecutor(max_workers=4) as executor: - for future in [executor.submit(write_rows, worker) for worker in range(4)]: - future.result(timeout=30) - with closing(sqlite_instance.get_session()) as session: - assert session.execute(text("SELECT COUNT(DISTINCT value) FROM fixture_threads")).scalar_one() == 40 + await asyncio.gather(*(write_rows_async(worker) for worker in range(4))) + async with await sqlite_instance.get_session_async() as session: + assert (await session.execute(text("SELECT COUNT(DISTINCT value) FROM fixture_threads"))).scalar_one() == 40 diff --git a/tests/unit/memory/test_sqlite_memory.py b/tests/unit/memory/test_sqlite_memory.py index 21a921fe0c..2cd68fc483 100644 --- a/tests/unit/memory/test_sqlite_memory.py +++ b/tests/unit/memory/test_sqlite_memory.py @@ -13,7 +13,7 @@ from unittest.mock import MagicMock import pytest -from sqlalchemy import ARRAY, DateTime, Integer, String, create_engine, event, inspect, text +from sqlalchemy import ARRAY, DateTime, Integer, String, create_engine, event, inspect, select, text from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.dialects.sqlite import CHAR, JSON from sqlalchemy.exc import SQLAlchemyError @@ -312,8 +312,8 @@ def test_run_schema_migrations_isolates_foreign_alembic_version_table(): engine.dispose() -def test_reset_database_recreates_schema(sqlite_instance): - sqlite_instance.reset_database() +async def test_reset_database_recreates_schema_async(sqlite_instance): + await sqlite_instance.reset_database_async() inspector = inspect(sqlite_instance.engine) table_names = set(inspector.get_table_names()) @@ -334,11 +334,11 @@ def test_reset_database_recreates_schema(sqlite_instance): assert version -def test_reset_database_keeps_foreign_alembic_version_table(sqlite_instance): +async def test_reset_database_keeps_foreign_alembic_version_table_async(sqlite_instance): with sqlite_instance.engine.begin() as connection: connection.execute(text('CREATE TABLE "alembic_version" (version_num VARCHAR(32) NOT NULL)')) - sqlite_instance.reset_database() + await sqlite_instance.reset_database_async() table_names = set(inspect(sqlite_instance.engine).get_table_names()) assert "alembic_version" in table_names @@ -361,11 +361,11 @@ async def test_insert_entry(sqlite_instance): entry = PromptMemoryEntry(entry=message_piece_entry) # Use the insert_entry method to insert the entry into the database - sqlite_instance._insert_entry(entry) + await sqlite_instance._run_database_operation_async(sqlite_instance._insert_entry, entry) # Now, get a new session to query the database and verify the entry was inserted - with sqlite_instance.get_session() as session: - inserted_entry = session.query(PromptMemoryEntry).filter_by(conversation_id="123").first() + async with await sqlite_instance.get_session_async() as session: + inserted_entry = (await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id="123"))).first() assert inserted_entry is not None assert inserted_entry.role == "user" assert inserted_entry.original_value == "Hello" @@ -376,7 +376,7 @@ async def test_insert_entry(sqlite_instance): assert inserted_entry.converted_value_sha256 == converted_sha256 -def test_insert_entry_violates_constraint(sqlite_instance): +async def test_insert_entry_violates_constraint_async(sqlite_instance): # Generate a fixed UUID fixed_uuid = uuid.uuid4() # Create two entries with the same UUID @@ -401,18 +401,18 @@ def test_insert_entry_violates_constraint(sqlite_instance): ) # Insert the first entry - with sqlite_instance.get_session() as session: + async with await sqlite_instance.get_session_async() as session: session.add(entry1) - session.commit() + await session.commit() # Attempt to insert the second entry with the same UUID - with sqlite_instance.get_session() as session: + async with await sqlite_instance.get_session_async() as session: session.add(entry2) with pytest.raises(SQLAlchemyError): - session.commit() + await session.commit() -def test_insert_entries(sqlite_instance): +async def test_insert_entries_async(sqlite_instance): entries = [ PromptMemoryEntry( entry=MessagePiece( @@ -426,10 +426,9 @@ def test_insert_entries(sqlite_instance): ] # Now, get a new session to query the database and verify the entries were inserted - with sqlite_instance.get_session() as session: - # Use the insert_entries method to insert multiple entries into the database - sqlite_instance._insert_entries(entries=entries) - inserted_entries = session.query(PromptMemoryEntry).all() + await sqlite_instance._run_database_operation_async(sqlite_instance._insert_entries, entries=entries) + async with await sqlite_instance.get_session_async() as session: + inserted_entries = (await session.scalars(select(PromptMemoryEntry))).all() assert len(inserted_entries) == 5 for i, entry in enumerate(inserted_entries): assert entry.conversation_id == str(i) @@ -438,28 +437,30 @@ def test_insert_entries(sqlite_instance): assert entry.converted_value == f"CMessage {i}" -def test_insert_embedding_entry(sqlite_instance): +async def test_insert_embedding_entry_async(sqlite_instance): # Create a ConversationData entry conversation_entry = PromptMemoryEntry( entry=MessagePiece(conversation_id="123", role="user", original_value="Hello", converted_value="abc") ) # Insert the ConversationData entry using the insert_entry method - sqlite_instance._insert_entry(conversation_entry) + await sqlite_instance._run_database_operation_async(sqlite_instance._insert_entry, conversation_entry) # Re-query the ConversationData entry within a new session to ensure it's attached - with sqlite_instance.get_session() as session: + async with await sqlite_instance.get_session_async() as session: # Assuming uuid is the primary key and is set upon insertion - reattached_conversation_entry = session.query(PromptMemoryEntry).filter_by(conversation_id="123").one() + reattached_conversation_entry = ( + await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id="123")) + ).one() uuid = reattached_conversation_entry.id # Now that we have the uuid, we can create and insert the EmbeddingData entry embedding_entry = EmbeddingDataEntry(id=uuid, embedding=[1, 2, 3], embedding_type_name="test_type") - sqlite_instance._insert_entry(embedding_entry) + await sqlite_instance._run_database_operation_async(sqlite_instance._insert_entry, embedding_entry) # Verify the EmbeddingData entry was inserted correctly - with sqlite_instance.get_session() as session: - persisted_embedding_entry = session.query(EmbeddingDataEntry).filter_by(id=uuid).first() + async with await sqlite_instance.get_session_async() as session: + persisted_embedding_entry = (await session.scalars(select(EmbeddingDataEntry).filter_by(id=uuid))).first() assert persisted_embedding_entry is not None assert persisted_embedding_entry.embedding == [1, 2, 3] assert persisted_embedding_entry.embedding_type_name == "test_type" @@ -587,15 +588,15 @@ def test_query_entries(sqlite_instance, sample_conversation_entries): assert specific_entry[0].original_value == "Message 1" -def test_get_all_memory(sqlite_instance, sample_conversation_entries): +async def test_get_all_memory(sqlite_instance, sample_conversation_entries): sqlite_instance._insert_entries(entries=sample_conversation_entries) # Fetch all entries - all_entries = sqlite_instance.get_message_pieces() + all_entries = await sqlite_instance.get_message_pieces_async() assert len(all_entries) == 3 -def test_get_memories_with_json_properties(sqlite_instance): +async def test_get_memories_with_json_properties(sqlite_instance): # Define a specific conversation_id specific_conversation_id = "test_conversation_id" @@ -612,13 +613,17 @@ def test_get_memories_with_json_properties(sqlite_instance): converter_identifiers=converter_identifiers, ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=specific_conversation_id, target_identifier=target.get_identifier()) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation( + conversation_id=specific_conversation_id, target_identifier=target.get_identifier() + ) + ) ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[piece])) # Use the get_memories_with_conversation_id method to retrieve entries with the specific conversation_id - retrieved_entries = sqlite_instance.get_conversation_messages(conversation_id=specific_conversation_id) + retrieved_entries = await sqlite_instance.get_conversation_messages_async(conversation_id=specific_conversation_id) # Verify that the retrieved entry matches the inserted entry assert len(retrieved_entries) == 1 @@ -641,7 +646,7 @@ def test_get_memories_with_json_properties(sqlite_instance): assert retrieved_entry.prompt_metadata["normalizer_id"] == "id1" -def test_register_conversation_none_target_does_not_clobber(sqlite_instance): +async def test_register_conversation_none_target_does_not_clobber(sqlite_instance): # A conversation is held with a single target. Registering it records the # target; a later registration for the same conversation with no target (e.g. # a branched copy whose source had no metadata) must NOT overwrite it with None. @@ -654,10 +659,12 @@ def test_register_conversation_none_target_does_not_clobber(sqlite_instance): sequence=1, original_value="hello", ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=target.get_identifier()) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=target.get_identifier()) + ) ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[request_piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[request_piece])) response_piece = MessagePiece( conversation_id=conversation_id, @@ -665,10 +672,12 @@ def test_register_conversation_none_target_does_not_clobber(sqlite_instance): sequence=2, original_value="world", ) - sqlite_instance.add_conversation_to_memory( - conversation=Conversation(conversation_id=conversation_id, target_identifier=None) + ( + await sqlite_instance.add_conversation_to_memory_async( + conversation=Conversation(conversation_id=conversation_id, target_identifier=None) + ) ) - sqlite_instance.add_message_pieces_to_memory(message_pieces=[response_piece]) + (await sqlite_instance.add_message_pieces_to_memory_async(message_pieces=[response_piece])) metadata = sqlite_instance._get_conversation(conversation_id=conversation_id) assert metadata is not None @@ -676,63 +685,69 @@ def test_register_conversation_none_target_does_not_clobber(sqlite_instance): assert metadata.target_identifier.class_name == "TextTarget" -def test_update_entries(sqlite_instance): +async def test_update_entries_async(sqlite_instance): # Insert a test entry entry = PromptMemoryEntry( entry=MessagePiece(conversation_id="123", role="user", original_value="Hello", converted_value="Hello") ) - sqlite_instance._insert_entry(entry) + await sqlite_instance._run_database_operation_async(sqlite_instance._insert_entry, entry) # Fetch the entry to update and update its content - entries_to_update = sqlite_instance._query_entries( - PromptMemoryEntry, conditions=PromptMemoryEntry.conversation_id == "123" + entries_to_update = await sqlite_instance._run_database_operation_async( + sqlite_instance._query_entries, PromptMemoryEntry, conditions=PromptMemoryEntry.conversation_id == "123" + ) + await sqlite_instance._run_database_operation_async( + sqlite_instance._update_entries, entries=entries_to_update, update_fields={"original_value": "Updated Hello"} ) - sqlite_instance._update_entries(entries=entries_to_update, update_fields={"original_value": "Updated Hello"}) # Verify the entry was updated - with sqlite_instance.get_session() as session: - updated_entry = session.query(PromptMemoryEntry).filter_by(conversation_id="123").first() + async with await sqlite_instance.get_session_async() as session: + updated_entry = (await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id="123"))).first() assert updated_entry.original_value == "Updated Hello" -def test_update_entries_empty_update_fields(sqlite_instance): +async def test_update_entries_empty_update_fields_async(sqlite_instance): # Insert a test entry entry = PromptMemoryEntry( entry=MessagePiece(conversation_id="123", role="user", original_value="Hello", converted_value="Hello") ) - sqlite_instance._insert_entry(entry) + await sqlite_instance._run_database_operation_async(sqlite_instance._insert_entry, entry) # Fetch the entry to update and update its content - entries_to_update = sqlite_instance._query_entries( - PromptMemoryEntry, conditions=PromptMemoryEntry.conversation_id == "123" + entries_to_update = await sqlite_instance._run_database_operation_async( + sqlite_instance._query_entries, PromptMemoryEntry, conditions=PromptMemoryEntry.conversation_id == "123" ) with pytest.raises(ValueError): - sqlite_instance._update_entries(entries=entries_to_update, update_fields={}) + await sqlite_instance._run_database_operation_async( + sqlite_instance._update_entries, entries=entries_to_update, update_fields={} + ) -def test_update_entries_nonexistent_fields(sqlite_instance): +async def test_update_entries_nonexistent_fields_async(sqlite_instance): # Insert a test entry entry = PromptMemoryEntry( entry=MessagePiece(conversation_id="123", role="user", original_value="Hello", converted_value="Hello") ) - sqlite_instance._insert_entry(entry) + await sqlite_instance._run_database_operation_async(sqlite_instance._insert_entry, entry) # Fetch the entry to update and update its content - entries_to_update = sqlite_instance._query_entries( - PromptMemoryEntry, conditions=PromptMemoryEntry.conversation_id == "123" + entries_to_update = await sqlite_instance._run_database_operation_async( + sqlite_instance._query_entries, PromptMemoryEntry, conditions=PromptMemoryEntry.conversation_id == "123" ) with pytest.raises(ValueError): - sqlite_instance._update_entries( - entries=entries_to_update, update_fields={"original_value": "Updated", "nonexistent_field": "Updated Hello"} + await sqlite_instance._run_database_operation_async( + sqlite_instance._update_entries, + entries=entries_to_update, + update_fields={"original_value": "Updated", "nonexistent_field": "Updated Hello"}, ) # Verify changes were rolled back and entry was not updated assert entries_to_update[0].original_value == "Hello" -def test_update_entries_by_conversation_id(sqlite_instance, sample_conversation_entries): +async def test_update_entries_by_conversation_id(sqlite_instance, sample_conversation_entries): # Define a specific conversation_id to update specific_conversation_id = "update_test_id" @@ -742,35 +757,28 @@ def test_update_entries_by_conversation_id(sqlite_instance, sample_conversation_ sample_conversation_entries[1].conversation_id = "other_id" original_content = sample_conversation_entries[1].original_value - # Insert the ConversationData entries using the insert_entries method within a session - with sqlite_instance.get_session() as session: - sqlite_instance._insert_entries(entries=sample_conversation_entries) - session.commit() # Ensure all entries are committed to the database - - # Define the fields to update for entries with the specific conversation_id - update_fields = {"original_value": "Updated content", "role": "assistant"} - - # Use the update_prompt_entries_by_conversation_id method to update the entries - update_result = sqlite_instance.update_prompt_entries_by_conversation_id( - conversation_id=specific_conversation_id, update_fields=update_fields - ) - - assert update_result is True # Ensure the update operation was reported as successful + await sqlite_instance._run_database_operation_async( + sqlite_instance._insert_entries, entries=sample_conversation_entries + ) + update_result = await sqlite_instance.update_prompt_entries_by_conversation_id_async( + conversation_id=specific_conversation_id, + update_fields={"original_value": "Updated content", "role": "assistant"}, + ) + assert update_result is True - # Verify that the entries with the specific conversation_id were updated - updated_entries = sqlite_instance._query_entries( - PromptMemoryEntry, conditions=PromptMemoryEntry.conversation_id == specific_conversation_id - ) + async with await sqlite_instance.get_session_async() as session: + updated_entries = ( + await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id=specific_conversation_id)) + ).all() for entry in updated_entries: assert entry.original_value == "Updated content" assert entry.role == "assistant" - # 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.original_value == original_content # Content should remain unchanged + other_entry = (await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id="other_id"))).first() + assert other_entry.original_value == original_content -def test_update_prompt_metadata_by_conversation_id(sqlite_instance, sample_conversation_entries): +async def test_update_prompt_metadata_by_conversation_id(sqlite_instance, sample_conversation_entries): # Define a specific conversation_id to update specific_conversation_id = "update_test_id" @@ -780,49 +788,43 @@ def test_update_prompt_metadata_by_conversation_id(sqlite_instance, sample_conve sample_conversation_entries[1].conversation_id = "other_id" original_metadata = sample_conversation_entries[1].prompt_metadata - # Insert the ConversationData entries using the insert_entries method within a session - with sqlite_instance.get_session() as session: - sqlite_instance._insert_entries(entries=sample_conversation_entries) - session.commit() # Ensure all entries are committed to the database - - # Define the fields to update for entries with the specific conversation_id - update_fields = {"prompt_metadata": "updated_metadata"} - # Use the update_prompt_entries_by_conversation_id method to update the entries - update_result = sqlite_instance.update_prompt_entries_by_conversation_id( - conversation_id=specific_conversation_id, update_fields=update_fields - ) - - assert update_result is True # Ensure the update operation was reported as successful + await sqlite_instance._run_database_operation_async( + sqlite_instance._insert_entries, entries=sample_conversation_entries + ) + update_result = await sqlite_instance.update_prompt_entries_by_conversation_id_async( + conversation_id=specific_conversation_id, update_fields={"prompt_metadata": "updated_metadata"} + ) + assert update_result is True - # Verify that the entries with the specific conversation_id were updated - updated_entries = sqlite_instance._query_entries( - PromptMemoryEntry, conditions=PromptMemoryEntry.conversation_id == specific_conversation_id - ) + async with await sqlite_instance.get_session_async() as session: + updated_entries = ( + await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id=specific_conversation_id)) + ).all() for entry in updated_entries: assert entry.prompt_metadata == "updated_metadata" - # 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 + other_entry = (await session.scalars(select(PromptMemoryEntry).filter_by(conversation_id="other_id"))).first() + assert other_entry.prompt_metadata == original_metadata -def test_get_conversation_stats_returns_empty_for_no_ids(sqlite_instance): +async 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=[]) + result = await sqlite_instance.get_conversation_stats_async(conversation_ids=[]) assert result == {} -def test_get_conversation_stats_uses_indexed_latest_message_lookup(sqlite_instance): +async def test_get_conversation_stats_uses_indexed_latest_message_lookup(sqlite_instance): statements: list[str] = [] def capture_statement(conn, cursor, statement, parameters, context, executemany): statements.append(statement) - event.listen(sqlite_instance.engine, "before_cursor_execute", capture_statement) + engine = sqlite_instance._get_async_engine().sync_engine + event.listen(engine, "before_cursor_execute", capture_statement) try: - sqlite_instance.get_conversation_stats(conversation_ids=["conversation"]) + (await sqlite_instance.get_conversation_stats_async(conversation_ids=["conversation"])) finally: - event.remove(sqlite_instance.engine, "before_cursor_execute", capture_statement) + event.remove(engine, "before_cursor_execute", capture_statement) sql = "\n".join(statements).upper() assert 'LEFT JOIN "PROMPTMEMORYENTRIES" LATEST' in sql @@ -830,13 +832,13 @@ def capture_statement(conn, cursor, statement, parameters, context, executemany) assert "ROW_NUMBER" not in sql -def test_get_conversation_stats_returns_empty_for_unknown_ids(sqlite_instance): +async 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"]) + result = await sqlite_instance.get_conversation_stats_async(conversation_ids=["nonexistent"]) assert result == {} -def test_get_conversation_stats_counts_distinct_sequences(sqlite_instance, sample_conversation_entries): +async 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 unit.mocks import get_sample_conversations @@ -850,7 +852,7 @@ def test_get_conversation_stats_counts_distinct_sequences(sqlite_instance, sampl sqlite_instance._insert_entries(entries=sample_conversation_entries) conv_ids = list(expected.keys()) - result = sqlite_instance.get_conversation_stats(conversation_ids=conv_ids) + result = await sqlite_instance.get_conversation_stats_async(conversation_ids=conv_ids) for conv_id in conv_ids: if conv_id in result: @@ -859,7 +861,7 @@ def test_get_conversation_stats_counts_distinct_sequences(sqlite_instance, sampl ) -def test_get_conversation_stats_does_not_read_labels_from_prompt_entries(sqlite_instance): +async def test_get_conversation_stats_does_not_read_labels_from_prompt_entries(sqlite_instance): """Test that conversation stats leave AttackResult-owned labels empty.""" import uuid @@ -878,12 +880,12 @@ def test_get_conversation_stats_does_not_read_labels_from_prompt_entries(sqlite_ entry = PromptMemoryEntry(entry=piece) sqlite_instance._insert_entry(entry) - result = sqlite_instance.get_conversation_stats(conversation_ids=[conv_id]) + result = await sqlite_instance.get_conversation_stats_async(conversation_ids=[conv_id]) assert conv_id in result assert result[conv_id].labels == {} -def test_get_conversation_stats_preview_caps_raw_value_at_fetch_limit(sqlite_instance): +async def test_get_conversation_stats_preview_caps_raw_value_at_fetch_limit(sqlite_instance): """Memory caps the raw last_message_preview at PREVIEW_FETCH_MAX_LEN. Display-level truncation to PREVIEW_MAX_LEN happens later in the backend @@ -908,7 +910,7 @@ def test_get_conversation_stats_preview_caps_raw_value_at_fetch_limit(sqlite_ins entry = PromptMemoryEntry(entry=piece) sqlite_instance._insert_entry(entry) - result = sqlite_instance.get_conversation_stats(conversation_ids=[conv_id]) + result = await sqlite_instance.get_conversation_stats_async(conversation_ids=[conv_id]) assert conv_id in result preview = result[conv_id].last_message_preview assert preview is not None @@ -917,7 +919,7 @@ def test_get_conversation_stats_preview_caps_raw_value_at_fetch_limit(sqlite_ins assert result[conv_id].last_message_data_type == "text" -def test_get_conversation_stats_batches_multiple_conversations(sqlite_instance): +async def test_get_conversation_stats_batches_multiple_conversations(sqlite_instance): """Test that a single call returns stats for multiple conversations.""" import uuid @@ -940,7 +942,7 @@ def test_get_conversation_stats_batches_multiple_conversations(sqlite_instance): sqlite_instance._insert_entries(entries=entries) - result = sqlite_instance.get_conversation_stats(conversation_ids=conv_ids) + result = await sqlite_instance.get_conversation_stats_async(conversation_ids=conv_ids) assert len(result) == 3 assert result[conv_ids[0]].message_count == 1 @@ -952,7 +954,7 @@ def test_get_conversation_stats_batches_multiple_conversations(sqlite_instance): "data_type", ["image_path", "audio_path", "video_path", "binary_path"], ) -def test_get_conversation_stats_returns_media_data_type(sqlite_instance, data_type): +async def test_get_conversation_stats_returns_media_data_type(sqlite_instance, data_type): """Memory exposes the raw value + data type for the last piece — the backend mapper handles display formatting. Verifies the data type is propagated so downstream consumers can render media previews safely.""" @@ -973,7 +975,7 @@ def test_get_conversation_stats_returns_media_data_type(sqlite_instance, data_ty ) sqlite_instance._insert_entry(PromptMemoryEntry(entry=piece)) - result = sqlite_instance.get_conversation_stats(conversation_ids=[conv_id]) + result = await sqlite_instance.get_conversation_stats_async(conversation_ids=[conv_id]) stats = result[conv_id] assert stats.last_message_data_type == data_type @@ -982,7 +984,7 @@ def test_get_conversation_stats_returns_media_data_type(sqlite_instance, data_ty assert stats.last_message_preview == path -def test_get_conversation_stats_uses_last_piece_data_type(sqlite_instance): +async def test_get_conversation_stats_uses_last_piece_data_type(sqlite_instance): """Stats reflect the data type of the most recent message, not the first one, so the backend mapper picks the right rendering.""" import uuid @@ -1011,14 +1013,14 @@ def test_get_conversation_stats_uses_last_piece_data_type(sqlite_instance): ) sqlite_instance._insert_entries(entries=[PromptMemoryEntry(entry=text_piece), PromptMemoryEntry(entry=media_piece)]) - result = sqlite_instance.get_conversation_stats(conversation_ids=[conv_id]) + result = await sqlite_instance.get_conversation_stats_async(conversation_ids=[conv_id]) stats = result[conv_id] assert stats.last_message_data_type == "audio_path" assert stats.last_message_preview == audio_path -def test_dispose_engine_tolerates_closed_log_stream(sqlite_instance, capsys): +async def test_dispose_engine_tolerates_closed_log_stream_async(sqlite_instance, capsys): """Verify dispose_engine does not raise or emit 'Logging error' when streams are closed (GH-1520).""" pyrit_logger = logging.getLogger("pyrit") prev_level = pyrit_logger.level @@ -1031,7 +1033,7 @@ def test_dispose_engine_tolerates_closed_log_stream(sqlite_instance, capsys): try: stream.close() - sqlite_instance.dispose_engine() + await sqlite_instance.dispose_engine_async() finally: root.removeHandler(handler) pyrit_logger.setLevel(prev_level) @@ -1106,7 +1108,7 @@ def test_run_schema_migrations_no_memory_tables(): @pytest.fixture -def isolated_memory_factory(): +async def isolated_memory_factory(): """Build SQLiteMemory instances that are not the shared process-wide singleton.""" saved = Singleton._instances.copy() Singleton._instances.clear() @@ -1122,12 +1124,12 @@ def _factory(**kwargs): yield _factory finally: for memory in created: - memory.dispose_engine() + await memory.dispose_engine_async() Singleton._instances.clear() Singleton._instances.update(saved) -def test_in_memory_database_serializes_sessions_across_threads(isolated_memory_factory): +def test_legacy_in_memory_database_serializes_sessions_across_threads(isolated_memory_factory): """ An in-memory database shares one DBAPI connection, so overlapping sessions corrupt writes. Without serialization this loses rows and raises sqlite3.InterfaceError. @@ -1163,43 +1165,43 @@ def _writer(worker: int) -> None: assert session.execute(text("SELECT COUNT(*) FROM lock_probe")).scalar() == 120 -def test_in_memory_database_allows_nested_sessions_on_one_thread(isolated_memory_factory): - """The lock is re-entrant so a caller that opens a second session cannot deadlock itself.""" +def test_legacy_in_memory_database_allows_nested_sessions_on_one_thread(isolated_memory_factory): + """The sync driver's lock is re-entrant for nested sessions on one thread.""" memory = isolated_memory_factory(db_path=":memory:") - with closing(memory.get_session()) as outer: - with closing(memory.get_session()) as inner: + with closing(memory._get_sync_session()) as outer: + with closing(memory._get_sync_session()) as inner: assert inner.execute(text("SELECT 1")).scalar() == 1 assert outer.execute(text("SELECT 1")).scalar() == 1 -def test_in_memory_session_close_is_idempotent(isolated_memory_factory): - """A double close must not release the lock twice and free it for another thread.""" +def test_legacy_in_memory_session_close_is_idempotent(isolated_memory_factory): + """A double close must not free the sync driver's lock for another thread.""" memory = isolated_memory_factory(db_path=":memory:") - session = memory.get_session() + session = memory._get_sync_session() session.close() session.close() assert not memory._connection_lock._is_owned() - with closing(memory.get_session()) as session: + with closing(memory._get_sync_session()) as session: assert session.execute(text("SELECT 1")).scalar() == 1 -def test_in_memory_session_discarded_without_close_frees_the_lock(isolated_memory_factory): - """One caller that forgets to close must not stall every other thread forever.""" +def test_legacy_in_memory_session_discarded_without_close_frees_the_lock(isolated_memory_factory): + """A discarded sync driver session must not stall other threads.""" memory = isolated_memory_factory(db_path=":memory:") def _leak_a_session() -> None: - memory.get_session() + memory._get_sync_session() _leak_a_session() gc.collect() assert not memory._connection_lock._is_owned() - with closing(memory.get_session()) as session: + with closing(memory._get_sync_session()) as session: assert session.execute(text("SELECT 1")).scalar() == 1 -def test_file_backed_database_is_not_serialized(isolated_memory_factory): +async def test_file_backed_database_is_not_serialized_async(isolated_memory_factory): """File-backed databases get a connection per checkout, so they must not pay for the lock.""" with tempfile.TemporaryDirectory() as temp_dir: memory = isolated_memory_factory(db_path=os.path.join(temp_dir, "locking.db")) diff --git a/tests/unit/mocks.py b/tests/unit/mocks.py index 5a6051979d..32902f2c92 100644 --- a/tests/unit/mocks.py +++ b/tests/unit/mocks.py @@ -5,11 +5,14 @@ import shutil import tempfile import uuid -from collections.abc import Generator, MutableSequence, Sequence +from collections.abc import AsyncGenerator, Callable, MutableSequence, Sequence from contextlib import AbstractAsyncContextManager -from typing import Any +from typing import Any, TypeVar from unittest.mock import MagicMock, patch +from sqlalchemy.ext.asyncio import create_async_engine +from sqlalchemy.orm import Session + from pyrit.memory import AzureSQLMemory, CentralMemory, MemoryInterface, PromptMemoryEntry from pyrit.models import ( ComponentIdentifier, @@ -19,8 +22,17 @@ ScenarioResult, flatten_to_message_pieces, ) +from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import PromptTarget, TargetCapabilities, TargetConfiguration, limit_requests_per_minute +T = TypeVar("T") + + +async def run_memory_session_async(*, memory: MemoryInterface, operation: Callable[[Session], T]) -> T: + """Run a test's direct ORM operation on the async memory connection.""" + async with await memory.get_session_async() as session: + return await session.run_sync(operation) + def make_scenario_identifier( *, @@ -210,7 +222,7 @@ def __init__(self, *, id=None, rpm=None) -> None: # noqa: A002 self.id = id self.prompt_sent = [] - def set_system_prompt( + async def set_system_prompt_async( self, *, system_prompt: str, @@ -220,7 +232,7 @@ def set_system_prompt( ) -> None: self.system_prompt = system_prompt if self._memory: - self._memory.add_message_to_memory( + await self._memory.add_message_to_memory_async( request=MessagePiece( role="system", original_value=system_prompt, @@ -248,7 +260,7 @@ def _validate_request(self, *, normalized_conversation: list[Message]) -> None: """ -def get_azure_sql_memory() -> Generator[AzureSQLMemory, None, None]: +async def get_azure_sql_memory_async() -> AsyncGenerator[AzureSQLMemory, None]: # Create a test Azure SQL Server DB using in-memory SQLite # This allows testing actual SQL queries (including JOINs and metadata filtering) # without requiring a real Azure SQL instance @@ -261,31 +273,41 @@ def get_azure_sql_memory() -> Generator[AzureSQLMemory, None, None]: ) os.environ[AzureSQLMemory.AZURE_STORAGE_ACCOUNT_DB_DATA_SAS_TOKEN] = "valid_sas_token" - # Use in-memory SQLite instead of mock to allow real SQL queries - azure_sql_memory = AzureSQLMemory( - connection_string="sqlite:///:memory:", + temp_dir = tempfile.mkdtemp() + database = os.path.join(temp_dir, "azure-test.db") + # Both test engines use SQLite; no Azure credentials or service calls are allowed. + azure_sql_memory = AzureSQLMemory.__new__(AzureSQLMemory) + azure_sql_memory.__init__( + connection_string=f"sqlite:///{database}", results_container_url=os.environ[AzureSQLMemory.AZURE_STORAGE_ACCOUNT_DB_DATA_CONTAINER_URL], results_sas_token=os.environ[AzureSQLMemory.AZURE_STORAGE_ACCOUNT_DB_DATA_SAS_TOKEN], + _defer_initialization=True, ) create_auth_token_mock.return_value = "token" enable_azure_authorization_mock.return_value = None # Create a temporary directory for results - temp_dir = tempfile.mkdtemp() azure_sql_memory.results_path = temp_dir azure_sql_memory.disable_embedding() # Initialize the database schema - azure_sql_memory.reset_database() + await azure_sql_memory.reset_database_async() CentralMemory.set_memory_instance(azure_sql_memory) - yield azure_sql_memory + try: + with patch.object( + azure_sql_memory, + "_create_async_engine", + side_effect=lambda: create_async_engine(f"sqlite+aiosqlite:///{database}"), + ): + yield azure_sql_memory + finally: + await azure_sql_memory.dispose_engine_async() if os.path.exists(temp_dir): shutil.rmtree(temp_dir) - azure_sql_memory.dispose_engine() def get_image_message_piece() -> MessagePiece: @@ -333,13 +355,22 @@ def mock_memory_resolving(*messages: Message) -> MagicMock: """ known = {str(piece.id): piece for message in messages for piece in message.message_pieces} memory = MagicMock(MemoryInterface) - memory.get_message_pieces.side_effect = lambda **kwargs: [ + memory.get_message_pieces_async.side_effect = lambda **kwargs: [ known[str(piece_id)] for piece_id in kwargs.get("prompt_ids", []) or [] if str(piece_id) in known ] return memory -def store_message(message: Message) -> Message: +def get_mock_prompt_normalizer() -> MagicMock: + """Build a normalizer mock with an async memory contract.""" + normalizer = MagicMock(spec=PromptNormalizer) + normalizer.memory = MagicMock(spec=MemoryInterface) + normalizer.memory.get_message_pieces_async.return_value = [] + normalizer.memory.delete_conversation_pieces_after_sequence_async.return_value = 0 + return normalizer + + +async def store_message_async(message: Message) -> Message: """ Persist a message so a scorable can name its pieces, and return it. @@ -357,7 +388,7 @@ def store_message(message: Message) -> Message: """ memory = CentralMemory.get_memory_instance() piece_ids = [piece.id for piece in message.message_pieces if piece.id is not None] - if not piece_ids or memory.get_message_pieces(prompt_ids=piece_ids): + if not piece_ids or await memory.get_message_pieces_async(prompt_ids=piece_ids): return message conversation_id = next( @@ -369,7 +400,7 @@ def store_message(message: Message) -> Message: if not piece.conversation_id: piece.conversation_id = conversation_id - memory.add_message_to_memory(request=message) + await memory.add_message_to_memory_async(request=message) return message diff --git a/tests/unit/models/test_attack_result.py b/tests/unit/models/test_attack_result.py index 518a188954..624c805c02 100644 --- a/tests/unit/models/test_attack_result.py +++ b/tests/unit/models/test_attack_result.py @@ -1,10 +1,10 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -from contextlib import closing from datetime import UTC, datetime import pytest +from unit.mocks import run_memory_session_async from pyrit.memory.memory_models import AttackResultEntry from pyrit.models import AttackOutcome, AttackResult, ComponentIdentifier, ConversationReference, ConversationType @@ -71,21 +71,22 @@ def test_timestamp_roundtrips_through_attack_result_entry(self) -> None: assert hydrated.timestamp == persisted_ts - def test_naive_entry_timestamp_is_normalized_to_utc_on_hydration(self, sqlite_instance) -> None: + async def test_naive_entry_timestamp_is_normalized_to_utc_on_hydration_async(self, sqlite_instance) -> None: """SQLite stores datetimes without tzinfo; the UTCDateTime column attaches UTC on read.""" original = AttackResult(conversation_id="c1", objective="test") entry = AttackResultEntry(entry=original) entry.timestamp = datetime(2026, 4, 17, 12, 0, 0) # noqa: DTZ001 + entry_id = entry.id - with closing(sqlite_instance.get_session()) as session: + async with await sqlite_instance.get_session_async() as session: session.add(entry) - session.commit() - entry_id = entry.id + await session.commit() - with closing(sqlite_instance.get_session()) as session: + def hydrate(session): reloaded = session.get(AttackResultEntry, entry_id) - hydrated = reloaded.get_attack_result() + return reloaded.get_attack_result() + hydrated = await run_memory_session_async(memory=sqlite_instance, operation=hydrate) assert hydrated.timestamp is not None assert hydrated.timestamp.tzinfo is UTC assert hydrated.timestamp.replace(tzinfo=None) == datetime(2026, 4, 17, 12, 0, 0) # noqa: DTZ001 diff --git a/tests/unit/models/test_seed.py b/tests/unit/models/test_seed.py index 99dc6307f9..a977f35bf4 100644 --- a/tests/unit/models/test_seed.py +++ b/tests/unit/models/test_seed.py @@ -354,7 +354,7 @@ async def test_group_seed_groups_from_yaml(sqlite_instance): seeds=[s for s in prompts.seeds if isinstance(s, SeedPrompt)], added_by="rlundeen" ) - groups = sqlite_instance.get_seed_groups() + groups = await sqlite_instance.get_seed_groups_async() # there are 6 SeedPrompts, but only 5 unique SeedGroups (two prompts share a group) assert len(groups) == 5 @@ -367,7 +367,7 @@ async def test_group_seed_prompt_alias_sets_group_id(sqlite_instance): seeds=[s for s in prompts.seeds if isinstance(s, SeedPrompt)], added_by="rlundeen" ) - groups = sqlite_instance.get_seed_groups() + groups = await sqlite_instance.get_seed_groups_async() # there are 6 SeedPrompts, but only 5 unique SeedGroups (two prompts share a group) assert len(groups) == 5 @@ -593,7 +593,7 @@ async def test_memory_encoding_metadata_image(tmp_path, sqlite_instance): data_type="image_path", ) await sqlite_instance.add_seeds_to_memory_async(seeds=[sp], added_by="test") - entry = sqlite_instance.get_seeds()[0] + entry = (await sqlite_instance.get_seeds_async())[0] assert len(entry.metadata) == 1 assert entry.metadata["format"] == "png" @@ -621,7 +621,7 @@ async def test_memory_encoding_metadata_audio(mock_tinytag, sqlite_instance): mock_tinytag.get.return_value = mock_tag await sqlite_instance.add_seeds_to_memory_async(seeds=[sp], added_by="test") - entry = sqlite_instance.get_seeds()[0] + entry = (await sqlite_instance.get_seeds_async())[0] assert entry.metadata["format"] == "wav" assert entry.metadata["bitrate"] == 128 assert entry.metadata["samplerate"] == 44100 diff --git a/tests/unit/output/attack_result/test_markdown.py b/tests/unit/output/attack_result/test_markdown.py index 2d5f8866d4..ca5e6d7f6d 100644 --- a/tests/unit/output/attack_result/test_markdown.py +++ b/tests/unit/output/attack_result/test_markdown.py @@ -29,10 +29,10 @@ def _attack_id(name: str = "TestAttack") -> ComponentIdentifier: return ComponentIdentifier(class_name=name, class_module="test_module") -def _seed_messages(memory: MemoryInterface, conversation_id: str, pieces: list[MessagePiece]) -> None: +async def _seed_messages_async(memory: MemoryInterface, conversation_id: str, pieces: list[MessagePiece]) -> None: for piece in pieces: piece.conversation_id = conversation_id - memory.add_message_to_memory(request=Message(message_pieces=[piece])) + (await memory.add_message_to_memory_async(request=Message(message_pieces=[piece]))) def _make_score(*, piece_id: str, value: str = "true", score_type: str = "true_false") -> Score: @@ -143,7 +143,7 @@ async def test_write_async_no_messages(printer, attack_result, capsys): async def test_write_async_renders_user_and_assistant_messages(printer, attack_result, sqlite_instance, capsys): user_piece = MessagePiece(role="user", original_value="Hello", converted_value="Hello") assistant_piece = MessagePiece(role="assistant", original_value="Hi back", converted_value="Hi back") - _seed_messages(sqlite_instance, "conv-main", [user_piece, assistant_piece]) + (await _seed_messages_async(sqlite_instance, "conv-main", [user_piece, assistant_piece])) await printer.write_async(attack_result) out = capsys.readouterr().out @@ -156,7 +156,7 @@ async def test_write_async_renders_user_and_assistant_messages(printer, attack_r async def test_write_async_renders_system_message(printer, attack_result, sqlite_instance, capsys): piece = MessagePiece(role="system", original_value="sys", converted_value="sys") - _seed_messages(sqlite_instance, "conv-main", [piece]) + (await _seed_messages_async(sqlite_instance, "conv-main", [piece])) await printer.write_async(attack_result) out = capsys.readouterr().out assert "### System Message" in out @@ -167,7 +167,7 @@ async def test_write_async_renders_original_and_converted_when_different( printer, attack_result, sqlite_instance, capsys ): piece = MessagePiece(role="user", original_value="Original text", converted_value="Converted text") - _seed_messages(sqlite_instance, "conv-main", [piece]) + (await _seed_messages_async(sqlite_instance, "conv-main", [piece])) await printer.write_async(attack_result) out = capsys.readouterr().out assert "**Original:**" in out @@ -185,7 +185,7 @@ async def test_write_async_renders_image_message(printer, attack_result, sqlite_ original_value_data_type="image_path", converted_value_data_type="image_path", ) - _seed_messages(sqlite_instance, "conv-main", [piece]) + (await _seed_messages_async(sqlite_instance, "conv-main", [piece])) await printer.write_async(attack_result) out = capsys.readouterr().out assert "![Image]" in out @@ -211,7 +211,7 @@ async def test_write_async_renders_audio_message_with_mime_type( original_value_data_type="audio_path", converted_value_data_type="audio_path", ) - _seed_messages(sqlite_instance, "conv-main", [piece]) + (await _seed_messages_async(sqlite_instance, "conv-main", [piece])) await printer.write_async(attack_result) out = capsys.readouterr().out assert "