From 7a3025aeaa793189782db597db7421d205b138eb Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Thu, 24 Sep 2026 13:53:47 -0700 Subject: [PATCH 1/7] Migrate memory access to async-first APIs Add native async SQLite and Azure SQL memory drivers, retain deprecated sync compatibility, and migrate callers, tests, examples, and lifecycle ownership. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../export_adversarial_benchmark_result.py | 2 +- doc/code/datasets/1_loading_datasets.ipynb | 2 +- doc/code/datasets/1_loading_datasets.py | 2 +- doc/code/executor/5_workflow.ipynb | 2 +- doc/code/executor/5_workflow.py | 2 +- doc/code/executor/6_benchmark.ipynb | 2 +- doc/code/executor/6_benchmark.py | 2 +- doc/code/executor/7_promptgen.ipynb | 2 +- doc/code/executor/7_promptgen.py | 2 +- doc/code/framework.md | 1 + doc/code/memory/0_memory.md | 69 +- doc/code/memory/1_sqlite_memory.ipynb | 2 +- doc/code/memory/1_sqlite_memory.py | 2 +- .../memory/2_basic_memory_programming.ipynb | 8 +- doc/code/memory/2_basic_memory_programming.py | 8 +- doc/code/memory/5_advanced_memory.ipynb | 22 +- doc/code/memory/5_advanced_memory.py | 22 +- doc/code/memory/6_azure_sql_memory.ipynb | 10 +- doc/code/memory/6_azure_sql_memory.py | 10 +- doc/code/memory/8_seed_database.ipynb | 22 +- doc/code/memory/8_seed_database.py | 22 +- doc/code/output/0_output.ipynb | 2 +- doc/code/output/0_output.py | 2 +- doc/code/scoring/0_scoring.ipynb | 4 +- doc/code/scoring/0_scoring.py | 4 +- doc/code/scoring/2_float_scale_scorers.ipynb | 14 +- doc/code/scoring/2_float_scale_scorers.py | 14 +- doc/code/scoring/3_combining_scorers.ipynb | 2 +- doc/code/scoring/3_combining_scorers.py | 2 +- doc/code/scoring/5_tool_call_scorer.ipynb | 8 +- doc/code/scoring/5_tool_call_scorer.py | 8 +- doc/gui/0_gui.md | 13 + pyproject.toml | 4 +- pyrit/analytics/__init__.py | 8 +- pyrit/analytics/conversation_analytics.py | 74 + pyrit/analytics/result_analysis.py | 63 + pyrit/analytics/technique_analysis.py | 73 + pyrit/auth/azure_auth.py | 22 + pyrit/backend/main.py | 30 +- pyrit/backend/mappers/attack_mappers.py | 3 +- pyrit/backend/routes/labels.py | 14 +- pyrit/backend/routes/scenarios.py | 12 +- pyrit/backend/routes/scores.py | 11 +- pyrit/backend/services/attack_service.py | 216 +- pyrit/backend/services/dataset_service.py | 2 +- .../services/scenario_progress_read_model.py | 103 + .../backend/services/scenario_run_service.py | 715 +++- pyrit/common/async_compatibility.py | 73 + pyrit/converter/decomposition_converter.py | 7 +- pyrit/converter/llm_generic_text_converter.py | 7 +- .../adversarial_conversation_manager.py | 39 + .../attack/component/conversation_manager.py | 101 +- pyrit/executor/attack/core/attack_strategy.py | 15 +- pyrit/executor/attack/multi_turn/crescendo.py | 8 +- .../multi_turn/multi_turn_attack_strategy.py | 60 + .../executor/attack/multi_turn/red_teaming.py | 16 +- .../multi_turn/simulated_conversation.py | 4 +- .../attack/multi_turn/tree_of_attacks.py | 376 +- pyrit/executor/attack/streaming/barge_in.py | 5 +- pyrit/executor/benchmark/fairness_bias.py | 35 +- pyrit/executor/promptgen/anecdoctor.py | 14 +- pyrit/executor/promptgen/fuzzer/fuzzer.py | 88 + .../promptgen/fuzzer/fuzzer_converter_base.py | 7 +- .../fuzzer/fuzzer_crossover_converter.py | 7 +- .../fuzzer/fuzzer_expand_converter.py | 7 +- pyrit/executor/workflow/xpia.py | 22 +- pyrit/memory/azure_sql_memory.py | 84 +- pyrit/memory/memory_interface.py | 3660 ++++++++++++++++- pyrit/memory/memory_session.py | 5 +- pyrit/memory/sqlite_memory.py | 75 +- pyrit/output/attack_result/markdown.py | 4 +- pyrit/output/attack_result/pretty.py | 4 +- pyrit/output/conversation/source.py | 4 +- pyrit/prompt_normalizer/json_retry.py | 16 +- pyrit/prompt_normalizer/prompt_normalizer.py | 28 +- .../common/discover_target_capabilities.py | 18 +- pyrit/prompt_target/common/prompt_target.py | 81 +- .../_openai_realtime_streaming_session.py | 6 +- .../openai/openai_realtime_target.py | 2 +- .../prompt_target/websocket_copilot_target.py | 20 +- pyrit/scenario/core/atomic_attack.py | 40 +- pyrit/scenario/core/dataset_configuration.py | 21 +- pyrit/scenario/core/scenario.py | 141 +- .../adaptive/selectors/epsilon_greedy.py | 4 +- pyrit/scenario/scenarios/airt/jailbreak.py | 43 +- pyrit/scenario/scenarios/airt/multilingual.py | 45 +- .../scenarios/benchmark/adversarial.py | 101 +- .../scenario/scenarios/garak/prompt_inject.py | 22 +- .../garak/system_prompt_extraction.py | 40 +- .../scenario/scenarios/garak/web_injection.py | 26 +- pyrit/score/audio_transcript_scorer.py | 2 +- pyrit/score/batch_scorer.py | 2 +- pyrit/score/conversation_scorer.py | 4 +- pyrit/score/float_scale/roblox_pii_scorer.py | 6 +- .../system_prompt_extraction_scorer.py | 24 +- pyrit/score/llm_scoring.py | 19 +- pyrit/score/message_scorable_resolver.py | 69 + pyrit/score/message_scorer.py | 151 +- pyrit/score/observation/execution.py | 83 + pyrit/score/scorer.py | 39 +- .../scorer_evaluation/scorer_evaluator.py | 110 +- pyrit/score/true_false/decoding_scorer.py | 2 +- pyrit/score/true_false/gandalf_scorer.py | 9 +- pyrit/score/true_false/wildguard_scorer.py | 5 +- pyrit/score/video_scorer.py | 4 +- pyrit/setup/initialization.py | 85 +- pyrit/setup/initializers/refresh_datasets.py | 29 +- tests/integration/conftest.py | 77 +- .../test_load_default_datasets_integration.py | 2 +- .../test_seed_dataset_provider_integration.py | 2 +- .../test_azure_sql_memory_integration.py | 255 +- tests/integration/mocks.py | 58 +- .../test_azure_content_filter_integration.py | 9 +- .../targets/test_openai_responses_gpt5.py | 6 +- .../targets/test_target_filters.py | 8 +- .../test_websocket_target_integration.py | 14 +- .../analytics/test_conversation_analytics.py | 16 +- tests/unit/analytics/test_result_analysis.py | 82 +- .../unit/analytics/test_technique_analysis.py | 151 +- tests/unit/backend/test_api_routes.py | 209 +- tests/unit/backend/test_attack_service.py | 830 ++-- tests/unit/backend/test_dataset_service.py | 199 +- tests/unit/backend/test_main.py | 41 +- tests/unit/backend/test_mappers.py | 62 +- .../test_scenario_progress_read_model.py | 94 +- tests/unit/backend/test_scenario_resume.py | 66 +- .../unit/backend/test_scenario_run_routes.py | 67 +- .../unit/backend/test_scenario_run_service.py | 614 +-- tests/unit/conftest.py | 6 +- .../converter/test_decomposition_converter.py | 3 +- .../unit/converter/test_denylist_converter.py | 3 +- .../converter/test_generic_llm_converter.py | 36 +- .../test_image_prompt_style_converter.py | 10 +- .../converter/test_math_prompt_converter.py | 9 +- .../test_random_translation_converter.py | 10 +- .../test_scientific_translation_converter.py | 22 +- .../test_harmbench_multimodal_dataset.py | 5 +- tests/unit/datasets/test_image_cache.py | 5 +- tests/unit/datasets/test_mossbench_dataset.py | 3 +- tests/unit/datasets/test_msts_dataset.py | 11 +- .../test_visual_leak_bench_dataset.py | 3 +- .../datasets/test_vlsu_multimodal_dataset.py | 8 +- .../test_adversarial_conversation_manager.py | 16 +- .../component/test_conversation_manager.py | 108 +- .../test_prepended_conversation_config.py | 5 +- .../component/test_simulated_conversation.py | 97 +- .../attack/core/test_attack_scoring.py | 8 +- .../attack/core/test_attack_strategy.py | 60 +- .../attack/multi_turn/test_chunked_request.py | 6 +- .../attack/multi_turn/test_crescendo.py | 17 +- .../multi_turn/test_crescendo_resilience.py | 36 +- .../multi_turn/test_multi_prompt_sending.py | 3 +- .../executor/attack/multi_turn/test_pair.py | 2 +- .../test_prepended_history_normalization.py | 116 +- .../attack/multi_turn/test_red_teaming.py | 37 +- .../test_supports_multi_turn_attacks.py | 234 +- .../attack/multi_turn/test_tree_of_attacks.py | 164 +- .../attack/single_turn/test_prompt_sending.py | 34 +- .../attack/single_turn/test_skeleton_key.py | 4 +- .../attack/streaming/test_barge_in.py | 10 +- .../test_attack_parameter_consistency.py | 74 +- .../attack/test_error_response_scoring.py | 11 +- .../test_scoring_expectation_transport.py | 14 +- .../attack/test_seed_expectation_transport.py | 12 +- .../executor/benchmark/test_fairness_bias.py | 12 +- .../fuzzer/test_fuzzer_result_printer.py | 8 +- .../executor/promptgen/test_anecdoctor.py | 9 +- tests/unit/executor/workflow/test_xpia.py | 25 +- .../memory_interface/test_batching_scale.py | 190 +- .../test_interface_attack_results.py | 964 +++-- .../memory_interface/test_interface_core.py | 16 +- .../test_interface_identifiers.py | 116 +- .../test_interface_observations.py | 361 +- .../test_interface_prompts.py | 456 +- .../test_interface_remove_seeds.py | 114 +- .../test_interface_scenario_history.py | 316 +- .../test_interface_scenario_progress.py | 48 +- .../test_interface_scenario_results.py | 329 +- .../test_interface_scorable_content.py | 35 +- .../memory_interface/test_interface_scores.py | 128 +- ...st_interface_seed_dataset_summary_query.py | 4 +- .../test_interface_seed_prompts.py | 199 +- tests/unit/memory/storage/test_serializers.py | 27 +- tests/unit/memory/test_async_memory.py | 332 ++ tests/unit/memory/test_azure_sql_memory.py | 48 +- .../memory/test_conversation_branching.py | 270 +- tests/unit/memory/test_memory_models.py | 47 +- tests/unit/memory/test_seed_conditions.py | 46 +- tests/unit/memory/test_sqlite_fixtures.py | 55 +- tests/unit/memory/test_sqlite_memory.py | 85 +- tests/unit/mocks.py | 52 +- .../output/attack_result/test_markdown.py | 64 +- .../unit/output/attack_result/test_pretty.py | 38 +- .../unit/prompt_normalizer/test_json_retry.py | 14 +- .../test_prompt_normalizer.py | 64 +- .../target/test_azure_ml_chat_target.py | 21 +- .../prompt_target/target/test_image_target.py | 19 +- .../test_normalize_async_integration.py | 116 +- .../target/test_openai_chat_target.py | 30 +- .../test_openai_realtime_streaming_session.py | 6 +- .../target/test_openai_response_target.py | 36 +- ...penai_response_target_function_chaining.py | 2 +- .../target/test_openai_url_warnings.py | 4 +- .../target/test_prompt_target.py | 46 +- .../test_prompt_target_azure_blob_storage.py | 6 +- .../prompt_target/target/test_tts_target.py | 13 +- .../target/test_websocket_copilot_target.py | 25 +- .../target/test_websocket_target.py | 4 +- .../test_discover_target_capabilities.py | 8 +- .../test_attack_technique_registry.py | 5 +- tests/unit/scenario/airt/test_jailbreak.py | 8 +- tests/unit/scenario/airt/test_multilingual.py | 14 +- tests/unit/scenario/airt/test_psychosocial.py | 2 +- .../scenario/benchmark/test_adversarial.py | 140 +- .../unit/scenario/core/test_atomic_attack.py | 13 +- .../core/test_dataset_configuration.py | 63 +- tests/unit/scenario/core/test_scenario.py | 46 +- .../core/test_scenario_crescendo_resume.py | 41 +- .../scenario/core/test_scenario_parameters.py | 4 +- .../core/test_scenario_partial_results.py | 62 +- .../scenario/core/test_scenario_refusals.py | 6 +- .../unit/scenario/core/test_scenario_retry.py | 138 +- tests/unit/scenario/garak/test_divergence.py | 2 +- .../scenario/garak/test_latent_injection.py | 29 +- .../garak/test_package_hallucination.py | 11 +- .../unit/scenario/garak/test_prompt_inject.py | 4 +- .../garak/test_system_prompt_extraction.py | 4 +- .../unit/scenario/garak/test_web_injection.py | 14 +- .../scenarios/adaptive/test_epsilon_greedy.py | 14 +- .../test_default_run_size_estimates.py | 19 +- .../regex/test_ansi_escape_output_scorer.py | 2 +- .../regex/test_credential_leak_scorer.py | 2 +- .../score/regex/test_divergence_scorer.py | 34 +- .../regex/test_escaped_ansi_output_scorer.py | 2 +- .../test_ldap_injection_output_scorer.py | 2 +- .../score/regex/test_markdown_injection.py | 2 +- .../regex/test_open_redirect_output_scorer.py | 2 +- .../test_path_traversal_output_scorer.py | 2 +- .../regex/test_shell_command_output_scorer.py | 2 +- .../regex/test_sql_injection_output_scorer.py | 2 +- .../score/regex/test_ssrf_output_scorer.py | 2 +- .../score/regex/test_ssti_output_scorer.py | 2 +- .../test_static_prompt_injection_scorer.py | 2 +- .../score/regex/test_xss_output_scorer.py | 2 +- .../score/regex/test_xxe_output_scorer.py | 2 +- tests/unit/score/test_azure_content_filter.py | 12 +- tests/unit/score/test_batch_scorer.py | 38 +- .../score/test_conversation_history_scorer.py | 30 +- tests/unit/score/test_decoding_scorer.py | 18 +- .../test_float_scale_threshold_scorer.py | 23 +- tests/unit/score/test_gandalf_scorer.py | 48 +- .../score/test_general_float_scale_scorer.py | 17 +- .../score/test_general_true_false_scorer.py | 11 +- tests/unit/score/test_insecure_code_scorer.py | 12 +- tests/unit/score/test_judgment_observation.py | 229 +- tests/unit/score/test_llamaguard_scorer.py | 2 +- tests/unit/score/test_manual_scorer.py | 4 +- .../score/test_message_scorable_resolver.py | 62 +- tests/unit/score/test_message_scorer.py | 160 +- .../unit/score/test_otel_tool_call_scorer.py | 34 +- tests/unit/score/test_plagiarism_scorer.py | 8 +- .../unit/score/test_question_answer_scorer.py | 18 +- .../test_response_scoring_expectation.py | 54 +- tests/unit/score/test_roblox_pii_scorer.py | 4 +- tests/unit/score/test_scorer.py | 179 +- tests/unit/score/test_scorer_evaluator.py | 20 +- .../score/test_scorer_response_json_schema.py | 3 +- tests/unit/score/test_self_ask_category.py | 51 +- tests/unit/score/test_self_ask_likert.py | 7 +- .../test_self_ask_question_answer_scorer.py | 14 +- tests/unit/score/test_self_ask_refusal.py | 65 +- tests/unit/score/test_self_ask_scale.py | 23 +- tests/unit/score/test_self_ask_true_false.py | 45 +- tests/unit/score/test_shieldgemma_scorer.py | 24 +- tests/unit/score/test_substring.py | 8 +- .../test_system_prompt_extraction_scorer.py | 4 +- .../score/test_true_false_composite_scorer.py | 31 +- tests/unit/score/test_true_false_inverter.py | 8 +- tests/unit/score/test_wildguard_scorer.py | 153 +- .../setup/techniques/test_core_techniques.py | 4 +- .../setup/techniques/test_extra_techniques.py | 4 +- tests/unit/setup/test_initialization.py | 21 + tests/unit/setup/test_refresh_datasets.py | 40 +- uv.lock | 34 +- 284 files changed, 13166 insertions(+), 5592 deletions(-) create mode 100644 pyrit/common/async_compatibility.py create mode 100644 tests/unit/memory/test_async_memory.py 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 ee11c68ad1..b603bc0324 100644 --- a/doc/code/datasets/1_loading_datasets.ipynb +++ b/doc/code/datasets/1_loading_datasets.ipynb @@ -327,7 +327,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 6a769d5429..9333a1dbeb 100644 --- a/doc/code/datasets/1_loading_datasets.py +++ b/doc/code/datasets/1_loading_datasets.py @@ -117,4 +117,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/framework.md b/doc/code/framework.md index 5c2cdbb80b..fd42ab6a7c 100644 --- a/doc/code/framework.md +++ b/doc/code/framework.md @@ -337,6 +337,7 @@ The below talks about responsibilities of most modules in the PyRIT library - One important thing to remember about this architecture is its swappable nature. Seeds, targets, converters, attacks, and scorers should all be swappable. But sometimes one of these components needs additional information. If the target is an LLM, we need a way to look up previous messages sent to that session so we can properly construct the new message. If the target is a blob store, we need to know the URL to use for a future attack. - Components should access memory through `CentralMemory` rather than passing state directly between each other. - Memory backends are swappable too (e.g. SQLite or Azure SQL) without changing the components that use them. +- Components await memory I/O through its `_async` APIs. Memory owns sessions and transactions; the application owns initialization and shutdown on the event loops that use those resources. - Memory loads and locks observation evidence for model-owned validation, and owns atomic writes and reference cleanup. - **Does not own**: business logic or decisions. Memory stores and retrieves state; it doesn't decide what to send, how to score, or when to branch — components do that and persist results here. diff --git a/doc/code/memory/0_memory.md b/doc/code/memory/0_memory.md index f736705752..f7455baaab 100644 --- a/doc/code/memory/0_memory.md +++ b/doc/code/memory/0_memory.md @@ -7,12 +7,13 @@ 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") ``` The `MemoryDatabaseType` is a `Literal` with 3 options: IN_MEMORY, SQLITE, AZURE_SQL. (Read more below) @@ -32,3 +33,61 @@ The `MemoryDatabaseType` is a `Literal` with 3 options: IN_MEMORY, SQLITE, AZURE - To configure AzureSQLMemory without an extra argument list, these keys should be in your `.env` file: - `AZURE_SQL_DB_CONNECTION_STRING` - `AZURE_STORAGE_ACCOUNT_DB_DATA_CONTAINER_URL` + +## Async memory access + +Use the `_async` methods for database reads, writes, and lifecycle operations. +Azure SQL uses SQLAlchemy `AsyncEngine` and `AsyncSession` with `aioodbc`. +SQLite uses the same session contract with `aiosqlite`. Both drivers use worker +threads internally so a database wait does not block the caller's event loop. +Async access improves responsiveness during concurrent work. It does not make +an individual query faster or remove the need for indexes, batching, and pagination. + +Synchronous methods remain available until PyRIT 1.4.0 and emit deprecation +warnings. They use a separate synchronous engine; they do not run a nested event +loop. These methods can still block the caller. Constructors and pure +configuration methods remain synchronous. Use `initialize_pyrit_async` to await +database setup rather than initialize a database in a request handler. + +Use an independent session for each task when direct SQL access is necessary: + +```python +async with await memory.get_session_async() as session: + # Await session.execute(), session.commit(), and other database operations. + ... +``` + +Do not share a session across concurrent tasks. An operation owns its transaction +and releases its session when it finishes or fails. Cancellation before a commit +can roll back a write. Cancellation during a commit can have an uncertain +outcome; do not retry a write without checking its persisted state. + +The application that owns memory must await `memory.dispose_engine_async()` +after its tasks finish and before its event loop stops. The backend does this +in its lifespan handler. If a temporary loop uses memory, it must first await +`memory.dispose_loop_resources_async()` on that loop. A notebook can keep its +memory open while its kernel is in use. Synchronous exit hooks do not close +async connections. + +### Custom implementations + +Add async overrides when you extend a migrated memory-dependent helper. +During the deprecation period, an inherited async method detects a custom +synchronous override, warns, and runs that override in a worker thread. If both +methods are overridden, the async override takes precedence. Cancellation waits +for a legacy worker to finish; it cannot stop synchronous code. + +Legacy memory subclasses can keep their existing synchronous session and query +hooks. Their inherited async operations use a warned worker-thread fallback. +For native async access, implement `_create_async_engine`, `_initialize_schema`, +`_get_sync_session`, and the backend query hooks. Raw `get_session_async` requires +a native async engine. The built-in Azure SQL and SQLite drivers do not use the +legacy operation fallback. + +### Azure SQL integration checks + +The gated Azure SQL integration fixture requires +`PYRIT_TEST_AZURE_SQL_CONNECTION_STRING` for an isolated non-production database. +It rejects the configured production connection string. These tests can create +schema objects and write test data. Do not point them at a shared production +database. Keep the normal results-storage configuration available for the fixture. 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 d1405606af..40289df209 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 9299ca9495..6b52fc6a4b 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 281b1f152c..293cb464c2 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", @@ -373,7 +375,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 cd885e9c90..4f3be3c132 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 @@ -184,7 +186,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 47f45cc84f..27a83e60af 100644 --- a/doc/code/scoring/3_combining_scorers.ipynb +++ b/doc/code/scoring/3_combining_scorers.ipynb @@ -329,7 +329,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 1c41599355..b3e7623ee6 100644 --- a/doc/code/scoring/3_combining_scorers.py +++ b/doc/code/scoring/3_combining_scorers.py @@ -193,7 +193,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 77085aa7d6..a524df6f02 100644 --- a/doc/code/scoring/5_tool_call_scorer.ipynb +++ b/doc/code/scoring/5_tool_call_scorer.ipynb @@ -181,7 +181,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", @@ -190,9 +190,11 @@ "replayed = (await scorer.score_observation_async(observation=saved, expectation=expects(\"lookup\")))[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\"Lookup in saved evidence after capture is closed: {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 d20eb2365a..016d4c884b 100644 --- a/doc/code/scoring/5_tool_call_scorer.py +++ b/doc/code/scoring/5_tool_call_scorer.py @@ -118,7 +118,7 @@ def lookup() -> 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 @@ -127,9 +127,11 @@ def lookup() -> str: replayed = (await scorer.score_observation_async(observation=saved, expectation=expects("lookup")))[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"Lookup in saved evidence after capture is closed: {replayed.get_value()}") -memory.dispose_engine() +(await memory.dispose_engine_async()) # %% [markdown] # ## Use another trace source diff --git a/doc/gui/0_gui.md b/doc/gui/0_gui.md index cde88f9a41..8de0e97947 100644 --- a/doc/gui/0_gui.md +++ b/doc/gui/0_gui.md @@ -4,6 +4,19 @@ CoPyRIT is a web-based graphical interface for PyRIT built with React and Fluent ## Getting Started +Backend database calls use the async memory API. The backend closes memory after +scenario tasks and converter resources stop. Database queries still use +pagination, batching, progress deltas, and caching; async I/O does not replace +these controls. + +**Separate follow-up:** Review the scenario preparation executor, temporary event +loop, abandoned-worker callbacks, and estimate-worker bookkeeping. This migration +keeps their behavior and changes only memory calls, async cache locking, and +resource cleanup. Removal of these mechanisms requires a separate review of +blocking constructors, imports, file access, and third-party code. Any later +simplification must preserve queue admission, cancellation, resume, scoped +defaults, and shutdown behavior. + There are several ways to run CoPyRIT: ### PyRIT Backend CLI diff --git a/pyproject.toml b/pyproject.toml index 6be2b689f2..608dab2873 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", @@ -61,7 +63,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 4e703190f5..0a03d08d93 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, @@ -140,6 +141,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="1.4.0", + ) filters: list[IdentifierFilter] = [ IdentifierFilter( identifier_type=IdentifierType.ATTACK, @@ -158,6 +164,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..067507b53a 100644 --- a/pyrit/analytics/technique_analysis.py +++ b/pyrit/analytics/technique_analysis.py @@ -8,6 +8,7 @@ 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 @@ -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 {} @@ -82,3 +88,70 @@ def compute_technique_stats( eval_hash: _compute_stats(successes=s, failures=f, undetermined=u, errors=e) for eval_hash, (s, f, u, e) in counts.items() } + + +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, + ) + + requested = set(technique_eval_hashes) + counts: dict[str, tuple[int, int, int, int]] = {} + for result in results: + identifier = result.atomic_attack_identifier + eval_hash = identifier.eval_hash if identifier is not None else None + if eval_hash is None or eval_hash not in requested: + continue + + s, f, u, e = counts.get(eval_hash, (0, 0, 0, 0)) + if result.outcome == AttackOutcome.SUCCESS: + counts[eval_hash] = (s + 1, f, u, e) + elif result.outcome == AttackOutcome.FAILURE: + counts[eval_hash] = (s, f + 1, u, e) + elif result.outcome == AttackOutcome.ERROR: + counts[eval_hash] = (s, f, u, e + 1) + else: + counts[eval_hash] = (s, f, u + 1, e) + + return { + eval_hash: _compute_stats(successes=s, failures=f, undetermined=u, errors=e) + for eval_hash, (s, f, u, e) 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/main.py b/pyrit/backend/main.py index 70afaefea4..3e19ca5b79 100644 --- a/pyrit/backend/main.py +++ b/pyrit/backend/main.py @@ -9,7 +9,7 @@ import logging import os from collections.abc import AsyncGenerator -from contextlib import asynccontextmanager +from contextlib import AsyncExitStack, asynccontextmanager from pathlib import Path from fastapi import FastAPI @@ -43,6 +43,7 @@ from pyrit.backend.services.environment_file_service import EnvironmentFileService from pyrit.backend.services.scenario_run_service import get_scenario_run_service 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 @@ -107,25 +108,20 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: if config.allow_custom_initializers: logger.warning("Custom initializer registration is ENABLED (allow_custom_initializers: true).") - scenario_run_service = get_scenario_run_service() - await scenario_run_service.reconcile_interrupted_runs_async() + memory = CentralMemory.get_memory_instance() + async with AsyncExitStack() as resource_cleanup, AsyncExitStack() as scenario_cleanup: + resource_cleanup.push_async_callback(memory.dispose_engine_async) + resource_cleanup.callback(get_converter_service.cache_clear) + scenario_run_service = get_scenario_run_service() + scenario_cleanup.push_async_callback(scenario_run_service.shutdown_async) + await scenario_run_service.reconcile_interrupted_runs_async() - # Mount the bundled frontend (or print a dev/missing-frontend notice). - # Done here rather than at module load so test imports of `pyrit.backend.main` - # don't emit noise and don't perform filesystem side effects. - setup_frontend() + # Delay frontend setup so importing the application has no filesystem side effects. + setup_frontend() - converter_service = await asyncio.to_thread(get_converter_service) - try: + converter_service = await asyncio.to_thread(get_converter_service) + resource_cleanup.push_async_callback(converter_service.close_async) yield - finally: - try: - await scenario_run_service.shutdown_async() - finally: - try: - await converter_service.close_async() - finally: - get_converter_service.cache_clear() app = FastAPI( 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 7ba92efda6..cf6abe6139 100644 --- a/pyrit/backend/routes/scenarios.py +++ b/pyrit/backend/routes/scenarios.py @@ -13,7 +13,6 @@ """ from fastapi import APIRouter, HTTPException, Query, status -from starlette.concurrency import run_in_threadpool from pyrit.backend.models.common import ProblemDetail from pyrit.backend.models.scenarios import ( @@ -240,8 +239,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), @@ -283,8 +281,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, @@ -321,8 +318,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, @@ -392,7 +388,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 346f3bb517..c44d5b44a6 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 logging import uuid from collections.abc import Mapping, Sequence @@ -61,6 +60,7 @@ normalize_label_filters, ) from pyrit.backend.services.target_service import get_target_service +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, CentralMemory, data_serializer_factory @@ -217,7 +217,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, @@ -252,7 +252,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] = [] @@ -291,7 +295,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]: """ @@ -303,7 +307,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: """ @@ -314,15 +318,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) @@ -346,7 +347,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 @@ -356,7 +357,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, @@ -401,7 +402,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, @@ -437,7 +438,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. @@ -472,7 +473,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 @@ -495,9 +496,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) @@ -512,10 +515,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 @@ -529,8 +529,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, @@ -553,7 +552,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 @@ -562,7 +561,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: @@ -610,7 +609,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 @@ -635,14 +634,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, @@ -653,8 +651,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, @@ -679,7 +676,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 @@ -691,10 +688,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 @@ -716,7 +711,7 @@ async def add_message_async(self, *, attack_result_id: str, request: AddMessageR Returns: AddMessageResponse containing the updated attack detail. """ - 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") @@ -749,7 +744,7 @@ async def add_message_async(self, *, attack_result_id: str, request: AddMessageR # NOTE: This read-then-write is not atomic (TOCTOU). Fine for the # current single-user UI, but would need a DB-level sequence # generator or optimistic locking if concurrent writes are supported. - existing = 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: @@ -774,7 +769,7 @@ async def add_message_async(self, *, attack_result_id: str, request: AddMessageR # generic 500. If no new error piece was stored (the failure # happened before the send, e.g. target lookup), re-raise so the # route still reports a real error. - current_pieces = 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( @@ -782,17 +777,14 @@ async def add_message_async(self, *, attack_result_id: str, request: AddMessageR 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 = 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, @@ -916,9 +908,11 @@ async def _update_attack_after_message_async( ) 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 @@ -1070,6 +1064,52 @@ def _duplicate_conversation_up_to( return conversation.conversation_id + @legacy_sync_override(lambda: AttackService._duplicate_conversation_up_to) + async def _duplicate_conversation_up_to_async( + self, + *, + source_conversation_id: str, + cutoff_index: int, + remap_assistant_to_simulated: bool = False, + target_identifier: ComponentIdentifier | None = None, + ) -> str: + """ + Duplicate messages from a conversation up to and including a turn index. + + Uses the memory layer's ``duplicate_messages`` so that each new + piece gets a fresh ``id`` and ``timestamp`` while preserving + ``original_prompt_id`` for tracking lineage. + + Args: + source_conversation_id: The conversation to copy from. + cutoff_index: Include messages with sequence <= cutoff_index. + remap_assistant_to_simulated: When True, pieces with role + ``assistant`` are changed to ``simulated_assistant`` so the + branched context is inert and won't confuse the target. + + target_identifier (ComponentIdentifier | None): The target the new conversation + is held with, if known. Recorded once for the duplicated conversation. + + Returns: + The new conversation ID containing the duplicated messages. + """ + conversation, all_pieces = await self._prepare_conversation_up_to_async( + source_conversation_id=source_conversation_id, + cutoff_index=cutoff_index, + target_identifier=target_identifier, + ) + + # Apply optional overrides to the fresh pieces before persisting + for piece in all_pieces: + if remap_assistant_to_simulated and piece.api_role == "assistant": + piece.role = "simulated_assistant" + + if 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( self, *, @@ -1089,6 +1129,26 @@ def _prepare_conversation_up_to( ) return Conversation(conversation_id=new_id, target_identifier=target_identifier), pieces + @legacy_sync_override(lambda: AttackService._prepare_conversation_up_to) + async def _prepare_conversation_up_to_async( + self, + *, + source_conversation_id: str, + cutoff_index: int, + target_identifier: ComponentIdentifier | None = None, + ) -> tuple[Conversation, Sequence[MessagePiece]]: + """ + Prepare a history copy without writing any rows. + + Returns: + tuple[Conversation, Sequence[MessagePiece]]: New metadata and lineage-preserving pieces. + """ + 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 + # ======================================================================== # Private Helper Methods - Store Messages # ======================================================================== @@ -1153,8 +1213,10 @@ async def _store_prepended_messages_async( if not prepended: return applied_by_message = [self._resolve_applied_converter_identifiers(msg.pieces) for msg in prepended] - 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 seq, msg in enumerate(prepended): for index, p in enumerate(msg.pieces): @@ -1165,7 +1227,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])) async def _send_and_store_message_async( self, @@ -1186,7 +1248,7 @@ async def _send_and_store_message_async( await self._persist_base64_pieces_async(request) - self._resolve_video_remix_metadata(request) + (await self._resolve_video_remix_metadata_async(request)) pyrit_message = request_to_pyrit_message( request=request, @@ -1223,8 +1285,10 @@ async def _store_message_only_async( ) -> None: """Store message without sending (send=False).""" await self._persist_base64_pieces_async(request) - 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( @@ -1234,7 +1298,7 @@ async def _store_message_only_async( 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])) def _resolve_video_remix_metadata(self, request: AddMessageRequest) -> None: """ @@ -1275,6 +1339,46 @@ def _resolve_video_remix_metadata(self, request: AddMessageRequest) -> None: vp.prompt_metadata["video_id"] = video_id return + @legacy_sync_override(lambda: AttackService._resolve_video_remix_metadata) + async def _resolve_video_remix_metadata_async(self, request: AddMessageRequest) -> None: + """ + Auto-resolve video_id metadata for remix mode. + + When a video_path piece is carried over from a previous conversation + (via original_prompt_id) alongside a text piece, the video target + requires video_id in the text piece's prompt_metadata. This method + looks up the original piece's metadata and propagates the video_id. + """ + video_pieces = [p for p in request.pieces if p.data_type == "video_path"] + if not video_pieces: + return + + text_piece = next((p for p in request.pieces if p.data_type == "text"), None) + if not text_piece: + return + + # Already has video_id — nothing to resolve + if text_piece.prompt_metadata and text_piece.prompt_metadata.get("video_id"): + return + + # Try to resolve video_id from the original prompt piece + for vp in video_pieces: + if not vp.original_prompt_id: + continue + 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") + if video_id: + if text_piece.prompt_metadata is None: + text_piece.prompt_metadata = {} + text_piece.prompt_metadata["video_id"] = video_id + # Also set video_id on the video piece itself + if vp.prompt_metadata is None: + vp.prompt_metadata = {} + vp.prompt_metadata["video_id"] = video_id + return + def _resolve_request_converter_configs(self, *, request: AddMessageRequest) -> list[ConverterConfiguration]: """ Resolve legacy or structured request converter configurations. 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/scenario_progress_read_model.py b/pyrit/backend/services/scenario_progress_read_model.py index 5eb879aa89..69b11df799 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 @@ -176,6 +179,8 @@ def __init__(self, *, memory: MemoryInterface) -> None: self._memory = memory self._cache: OrderedDict[str, _ProgressCacheEntry] = OrderedDict() self._cache_lock = Lock() + self._async_cache: OrderedDict[str, _ProgressCacheEntry] = OrderedDict() + self._async_cache_lock = asyncio.Lock() def get_snapshot( self, @@ -193,6 +198,11 @@ def get_snapshot( Returns: ScenarioProgressSnapshot: Deltas, mapped results, summary, and effective plan. """ + print_deprecation_message( + old_item="ScenarioProgressReadModel.get_snapshot", + new_item="ScenarioProgressReadModel.get_snapshot_async", + removed_in="1.4.0", + ) plan_signature = plan.model_dump_json() if plan is not None else None with self._cache_lock: entry = self._cache.get(scenario_result_id) @@ -250,6 +260,80 @@ def get_snapshot( plan=summary_plan, ) + @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. + + Returns: + ScenarioProgressSnapshot: Deltas, mapped results, summary, and effective plan. + """ + plan_signature = plan.model_dump_json() if plan is not None else None + async with self._async_cache_lock: + entry = self._async_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._async_cache[scenario_result_id] = entry + self._async_cache.move_to_end(scenario_result_id) + while len(self._async_cache) > self._CACHE_MAX_RUNS: + self._async_cache.popitem(last=False) + + first_new_index = len(entry.results) + await self._hydrate_new_deltas_async(scenario_result_id=scenario_result_id, entry=entry) + + 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) :] + ) + + 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.""" while True: @@ -270,6 +354,25 @@ 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.") + @legacy_sync_override(lambda: ScenarioProgressReadModel._hydrate_new_deltas) + 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 4b1573b135..9553b700a8 100644 --- a/pyrit/backend/services/scenario_run_service.py +++ b/pyrit/backend/services/scenario_run_service.py @@ -36,6 +36,8 @@ ) from pyrit.backend.services.scenario_configuration_resolver import ScenarioConfigurationResolver from pyrit.backend.services.scenario_progress_read_model import ResultUnitIdentity, ScenarioProgressReadModel +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, @@ -211,6 +213,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() @@ -275,7 +278,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} @@ -362,9 +365,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( @@ -378,11 +379,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 @@ -391,15 +392,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, @@ -411,8 +408,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, @@ -433,8 +429,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,6 +457,25 @@ def _is_run_cancelled(self, *, scenario_result_id: str | None) -> bool: stored = self._memory.get_scenario_result_header(scenario_result_id=scenario_result_id) return stored is not None and stored.scenario_run_state == ScenarioRunState.CANCELLED + @legacy_sync_override(lambda: ScenarioRunService._is_run_cancelled) + async def _is_run_cancelled_async(self, *, scenario_result_id: str | None) -> bool: + """ + Report whether a stored run is already in the CANCELLED state. + + Reads the header only. A resumed run can have thousands of linked attack results and + this runs on the event loop, which the rest of this path works to keep free. + + Args: + scenario_result_id: The run being resumed, or None for a fresh run. + + Returns: + bool: True when a stored run with this id is CANCELLED. + """ + if not scenario_result_id: + return False + 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: """ Clean up after an abandoned preparation thread has finished. @@ -498,6 +512,51 @@ def _release_abandoned_prepare(self, prepare_task: "asyncio.Future[_PreparedRun] ) logger.warning("Abandoned scenario preparation completed after the request was cancelled.") + @legacy_sync_override(lambda: ScenarioRunService._release_abandoned_prepare) + async def _release_abandoned_prepare_async(self, prepare_task: "asyncio.Future[_PreparedRun]") -> None: + """ + Clean up after an abandoned preparation thread has finished. + + A preparation that succeeds after its caller is cancelled leaves behind a + scenario result nobody will run. Mark it cancelled rather than leaving it + in ``CREATED``. + + Args: + prepare_task: The future wrapping the abandoned ``_prepare_run_blocking`` call. + """ + if prepare_task.cancelled(): + return + error = prepare_task.exception() + if error is not None: + logger.warning(f"Abandoned scenario preparation failed after the request was cancelled: {error}") + return + + # Initialization already stored a CREATED scenario result, and nothing is going to run + # it now, so terminalize it rather than leaving a run that never starts. A run that + # already reached a terminal state keeps it, so a real failure is not relabelled. + scenario_result_id = prepare_task.result().scenario._scenario_result_id + if scenario_result_id: + try: + ( + 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( + f"Could not mark abandoned scenario run {scenario_result_id} as cancelled: {update_error}" + ) + 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. @@ -519,7 +578,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() @@ -530,18 +589,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: @@ -626,6 +693,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, @@ -634,6 +706,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, *, @@ -654,6 +745,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, @@ -661,6 +757,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, *, @@ -683,6 +807,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( { @@ -756,6 +885,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. @@ -769,10 +994,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 @@ -787,8 +1009,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, @@ -804,14 +1025,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, @@ -829,8 +1046,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, @@ -886,21 +1102,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, @@ -930,8 +1141,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, @@ -947,8 +1157,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, @@ -960,6 +1169,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: @@ -990,8 +1201,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={ @@ -1005,8 +1215,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={ @@ -1031,9 +1240,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() @@ -1095,8 +1303,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, @@ -1266,8 +1473,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, @@ -1289,8 +1495,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, @@ -1338,6 +1543,37 @@ def _build_response( active_scenario_result_id=active_scenario_result_id, ) + @legacy_sync_override(lambda: ScenarioRunService._build_response) + 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, *, @@ -1496,26 +1732,184 @@ def _build_response_from_db( overload_summaries=self._build_overload_summaries(retry_events=overload_events), ) - @staticmethod - def _parse_history_plan(*, record: ScenarioHistoryRunRecord) -> list[ScenarioRunPlanAtomicGroup] | None: + @legacy_sync_override(lambda: ScenarioRunService._build_response_from_db) + 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: """ - Validate the compact persisted run plan projected onto one history row. + Build a ScenarioRunResponse from a database ScenarioResult, merged with active task info. + + Args: + scenario_result: A ScenarioResult retrieved from CentralMemory. + 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: - list[ScenarioRunPlanAtomicGroup] | None: Planned atomic groups, or None when the - run has no plan or the persisted plan cannot identify units unambiguously. + The API response model. """ - if record.plan_atomic_groups is None: - return None - try: - raw_atomic_groups = ( - json.loads(record.plan_atomic_groups) - if isinstance(record.plan_atomic_groups, str) - else record.plan_atomic_groups - ) - atomic_groups = _HISTORY_ATOMIC_GROUPS_ADAPTER.validate_python(raw_atomic_groups) - group_ids = [group.id for group in atomic_groups] - if len(group_ids) != len(set(group_ids)): + scenario_result_id = str(scenario_result.id) + status = scenario_result.scenario_run_state + + # Primary source: DB-persisted error fields + error = scenario_result.error_message + error_type = scenario_result.error_type + + # Historical attack errors remain after a successful resume; only use them for failed runs. + if not error and status == ScenarioRunState.FAILED: + error_ars = await self._memory.get_attack_results_async( + scenario_result_id=scenario_result_id, outcome=AttackOutcome.ERROR + ) + if error_ars: + error = error_ars[0].error_message + error_type = error_ars[0].error_type + + # Fallback: in-memory error for in-flight tasks where DB hasn't been updated yet + if not error: + error = active_error + + terminal = status in ( + ScenarioRunState.COMPLETED, + ScenarioRunState.FAILED, + ScenarioRunState.CANCELLED, + ) + try: + plan = self._load_run_plan(scenario_result=scenario_result) + except (ValidationError, ValueError): + logger.warning( + "Scenario run %s has invalid persisted plan metadata; using legacy run detail fields.", + scenario_result_id, + ) + plan = None + plan_lookup = self._progress_read_model.build_plan_lookup(plan=plan) + + # Build result fields from DB (always computed so in-progress runs show progress) + total_attacks, completed_attacks, objective_achieved_rate, successful_attacks = ( + self._progress_read_model.calculate_progress_counts( + scenario_result=scenario_result, + plan=plan, + plan_lookup=plan_lookup, + ) + ) + techniques_used = ( + list(dict.fromkeys(group.display_group for group in plan.atomic_groups)) + if plan is not None + else scenario_result.get_techniques_used() + ) + target, datasets_used, scenario_parameters = self._safe_run_metadata( + scenario_identifier=getattr(scenario_result, "scenario_identifier", None) + ) + + # Surface per-attack errors and retry pressure regardless of overall run status: + # a COMPLETED scenario can still hide errored objectives or rate-limit retries. + failed_attacks: list[AttackErrorSummary] = [] + attack_retries: list[AttackRetrySummary] = [] + persisted_retries: list[int] = [] + overload_events: deque[Any] = deque(maxlen=_MAX_OVERLOAD_EVENTS) + attempts_by_unit: dict[ResultUnitIdentity, int] = {} + for atomic_attack_name, results in scenario_result.attack_results.items(): + for attack_result in results: + unit_identity = self._progress_read_model.resolve_result_unit_identity( + atomic_attack_name=atomic_attack_name, + attack_result=attack_result, + plan_lookup=plan_lookup, + ) + attempts_by_unit[unit_identity] = attempts_by_unit.get(unit_identity, 0) + 1 + retries = getattr(attack_result, "total_retries", 0) + if isinstance(retries, int): + persisted_retries.append(retries) + + retry_events = getattr(attack_result, "retry_events", None) + if isinstance(retry_events, list) and retry_events: + overload_events.extend(retry_events) + attack_retries.append( + AttackRetrySummary( + attack_result_id=str(attack_result.attack_result_id), + atomic_attack_name=atomic_attack_name, + retries=retry_events, + ) + ) + + if attack_result.outcome == AttackOutcome.ERROR: + failed_attacks.append( + AttackErrorSummary( + atomic_attack_name=atomic_attack_name, + objective=attack_result.objective, + error_type=attack_result.error_type, + error_message=attack_result.error_message, + total_retries=max(0, retries) if isinstance(retries, int) else 0, + ) + ) + total_retries = self._progress_read_model.total_retry_pressure( + attempts_per_unit=attempts_by_unit.values(), + persisted_retries=persisted_retries, + ) + + updated_at = scenario_result.creation_time + if terminal and scenario_result.completion_time is not None: + updated_at = scenario_result.completion_time + + return ScenarioRunSummary( + scenario_result_id=scenario_result_id, + scenario_name=scenario_result.scenario_name, + scenario_registry_name=plan.scenario_registry_name if plan else None, + scenario_version=scenario_result.scenario_version, + status=status, + created_at=scenario_result.creation_time, + started_at=self._load_started_at(scenario_result=scenario_result), + updated_at=updated_at, + error=error, + error_type=error_type, + techniques_used=techniques_used, + total_attacks=total_attacks, + completed_attacks=completed_attacks, + objective_achieved_rate=objective_achieved_rate, + failed_attacks=failed_attacks, + attack_retries=attack_retries, + total_retries=total_retries, + labels=scenario_result.labels, + completed_at=scenario_result.completion_time if terminal else None, + pyrit_version=( + scenario_result.pyrit_version + if isinstance(getattr(scenario_result, "pyrit_version", None), str) + else None + ), + target=target, + datasets_used=datasets_used, + scenario_parameters=scenario_parameters, + planned_total_available=plan is not None, + successful_attacks=successful_attacks, + error_attacks=len(failed_attacks), + queue_position=queue_position, + active_scenario_result_id=active_scenario_result_id, + overload_summaries=self._build_overload_summaries(retry_events=overload_events), + ) + + @staticmethod + def _parse_history_plan(*, record: ScenarioHistoryRunRecord) -> list[ScenarioRunPlanAtomicGroup] | None: + """ + Validate the compact persisted run plan projected onto one history row. + + Returns: + list[ScenarioRunPlanAtomicGroup] | None: Planned atomic groups, or None when the + run has no plan or the persisted plan cannot identify units unambiguously. + """ + if record.plan_atomic_groups is None: + return None + try: + raw_atomic_groups = ( + json.loads(record.plan_atomic_groups) + if isinstance(record.plan_atomic_groups, str) + else record.plan_atomic_groups + ) + atomic_groups = _HISTORY_ATOMIC_GROUPS_ADAPTER.validate_python(raw_atomic_groups) + group_ids = [group.id for group in atomic_groups] + if len(group_ids) != len(set(group_ids)): raise ValueError("duplicate atomic group IDs") raw_seed_map = ( json.loads(record.plan_seed_id_map) @@ -1936,6 +2330,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, @@ -1946,6 +2345,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, *, @@ -1957,6 +2380,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 @@ -2041,6 +2469,102 @@ def get_run_progress_from_storage( plan_complete=plan_complete, ) + @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, + ) + overload_events: deque[Any] = deque(maxlen=_MAX_OVERLOAD_EVENTS) + for delta in progress_snapshot.deltas: + overload_events.extend(delta.retry_events) + available = [ + (delta, result) + for delta, result in zip(progress_snapshot.deltas, progress_snapshot.results, strict=True) + if cursor is None + or (delta.timestamp, uuid.UUID(delta.attack_result_id)) + > (cursor.timestamp, uuid.UUID(cursor.attack_result_id)) + ] + page = available[:limit] + deltas = [delta for delta, _ in page] + results = [result for _, result in page] + has_more = len(available) > limit + response_plan = progress_snapshot.plan if since is None else None + next_cursor = ( + self._encode_progress_cursor(scenario_result_id=scenario_result_id, delta=deltas[-1]) if deltas else since + ) + scenario_identifier = header_result.scenario_identifier + target, datasets_used, scenario_parameters = self._safe_run_metadata(scenario_identifier=scenario_identifier) + if plan is not None: + techniques_used = list(dict.fromkeys(group.display_group for group in plan.atomic_groups)) + else: + techniques_used = self._identifier_techniques(scenario_identifier) + return ScenarioRunProgress( + run=ScenarioProgressHeader( + scenario_result_id=scenario_result_id, + scenario_name=header_result.scenario_name, + scenario_registry_name=plan.scenario_registry_name if plan else None, + scenario_version=header_result.scenario_version, + status=header_result.scenario_run_state, + created_at=header_result.creation_time, + started_at=self._load_started_at(scenario_result=header_result), + completed_at=header_result.completion_time if terminal else None, + error=header_result.error_message, + error_type=header_result.error_type, + pyrit_version=header_result.pyrit_version, + target=target, + techniques_used=techniques_used, + datasets_used=datasets_used, + scenario_parameters=scenario_parameters, + labels=header_result.labels, + queue_position=queue_position, + active_scenario_result_id=active_scenario_result_id, + overload_summaries=self._build_overload_summaries(retry_events=overload_events), + ), + plan=response_plan, + results=results, + summary=progress_snapshot.summary, + next_cursor=next_cursor, + has_more=has_more, + plan_complete=plan_complete, + ) + @staticmethod def _encode_progress_cursor(*, scenario_result_id: str, delta: ScenarioAttackResultDelta) -> str: payload = { @@ -2090,6 +2614,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 @@ -2102,6 +2631,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..0de84eeeb6 --- /dev/null +++ b/pyrit/common/async_compatibility.py @@ -0,0 +1,73 @@ +# 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 + task.result() + 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 3a948cb3ba..7d845ca3db 100644 --- a/pyrit/executor/attack/component/adversarial_conversation_manager.py +++ b/pyrit/executor/attack/component/adversarial_conversation_manager.py @@ -12,6 +12,8 @@ from typing import TYPE_CHECKING, Any from uuid import uuid4 +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.exceptions import ( BadRequestException, ComponentRole, @@ -628,6 +630,11 @@ def set_adversarial_system_prompt(self, **extra_render_values: object) -> None: Raises: ValueError: If the rendered system prompt is empty. """ + print_deprecation_message( + old_item="_AdversarialConversationManager.set_adversarial_system_prompt", + new_item="_AdversarialConversationManager.set_adversarial_system_prompt_async", + removed_in="1.4.0", + ) rendered = self._adversarial_system_prompt.render_template_value( objective=self._objective, max_turns=self._max_turns, @@ -640,6 +647,38 @@ def set_adversarial_system_prompt(self, **extra_render_values: object) -> None: conversation_id=self._conversation_id, ) + @legacy_sync_override(lambda: _AdversarialConversationManager.set_adversarial_system_prompt) + 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. + + Renders ``adversarial_system_prompt`` with the manager's ``objective`` and ``max_turns`` and + sets it on the adversarial target for this manager's ``conversation_id``. Must be called from + the attack's ``_setup_async`` *before* any prepended adversarial turns are hydrated, because + ``set_system_prompt`` rejects a conversation that already has messages. + + Args: + **extra_render_values: Additional attack-specific template variables to render into the + system prompt (e.g. Crescendo's ``conversation_context``). Attacks that need bespoke + system-prompt inputs supply them here rather than rendering and setting the prompt + themselves, keeping the setup mechanics owned by the manager. + + Raises: + ValueError: If the rendered system prompt is empty. + """ + rendered = self._adversarial_system_prompt.render_template_value( + objective=self._objective, + max_turns=self._max_turns, + **extra_render_values, + ) + if not rendered: + raise ValueError("Adversarial chat system prompt must be defined") + ( + await self._adversarial_target.set_system_prompt_async( + system_prompt=rendered, conversation_id=self._conversation_id + ) + ) + def _render_first_message(self) -> str: """ Render the first message with this manager's objective. diff --git a/pyrit/executor/attack/component/conversation_manager.py b/pyrit/executor/attack/component/conversation_manager.py index 2061d379f5..e7f0faddf3 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, @@ -212,9 +214,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. @@ -226,6 +248,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 @@ -239,6 +266,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, *, @@ -258,6 +312,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( @@ -265,6 +324,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, *, @@ -417,11 +500,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 @@ -512,7 +597,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 @@ -527,7 +612,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( @@ -549,14 +634,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 279d91ddc6..dc4556d4fd 100644 --- a/pyrit/executor/attack/core/attack_strategy.py +++ b/pyrit/executor/attack/core/attack_strategy.py @@ -14,6 +14,7 @@ from enum import Enum from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, overload +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.logger import logger from pyrit.exceptions.retry_collector import ( get_retry_collector, @@ -413,6 +414,16 @@ def _persist_result(self, *, result: AttackStrategyResultT) -> None: """ self._memory.add_attack_results_to_memory(attack_results=[result]) + @legacy_sync_override(lambda: _DefaultAttackStrategyEventHandler._persist_result) + async def _persist_result_async(self, *, result: AttackStrategyResultT) -> None: + """ + Persist a completed attack result. + + Args: + result (AttackStrategyResultT): The completed result to persist. + """ + (await self._memory.add_attack_results_to_memory_async(attack_results=[result])) + @staticmethod def _apply_attribution( *, @@ -545,7 +556,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 @@ -856,7 +867,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..6c2ff40565 100644 --- a/pyrit/executor/attack/multi_turn/multi_turn_attack_strategy.py +++ b/pyrit/executor/attack/multi_turn/multi_turn_attack_strategy.py @@ -9,6 +9,7 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, TypeVar +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.logger import logger from pyrit.executor.attack.component.conversation_manager import ConversationManager from pyrit.executor.attack.core.attack_parameters import AttackParameters, AttackParamsT @@ -159,3 +160,62 @@ def _rotate_conversation_for_single_turn_target( old_conversation_id, context.session.conversation_id, ) + + @legacy_sync_override(lambda: MultiTurnAttackStrategy._rotate_conversation_for_single_turn_target) + async def _rotate_conversation_for_single_turn_target_async( + self, + *, + context: MultiTurnAttackContext[Any], + ) -> None: + """ + Rotate an unseeded single-turn target conversation before later sends. + + An explicit target normalization context already selects only the + persisted seed plus the current request, so rotating in that case would + lose the seed and change the target-facing payload. + """ + if self._objective_target.configuration.includes(capability=CapabilityName.MULTI_TURN): + return + if context.prepended_history_send_context: + return + if context.executed_turns == 0: + return + + old_conversation_id = context.session.conversation_id + context.related_conversations.add( + ConversationReference( + conversation_id=old_conversation_id, + conversation_type=ConversationType.PRUNED, + description=f"single-turn target prior turn {context.executed_turns}", + ) + ) + + memory = CentralMemory.get_memory_instance() + 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 = 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() + ) + ) + ) + (await memory.add_message_pieces_to_memory_async(message_pieces=pieces)) + context.session.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, + prepended_messages=persisted_messages, + ) + else: + context.session.conversation_id = str(uuid.uuid4()) + + self._logger.debug( + "Rotated conversation_id for single-turn target: %s -> %s", + old_conversation_id, + context.session.conversation_id, + ) diff --git a/pyrit/executor/attack/multi_turn/red_teaming.py b/pyrit/executor/attack/multi_turn/red_teaming.py index 09343bba88..ffa6064890 100644 --- a/pyrit/executor/attack/multi_turn/red_teaming.py +++ b/pyrit/executor/attack/multi_turn/red_teaming.py @@ -288,7 +288,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: @@ -298,14 +298,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: """ @@ -481,7 +483,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 5a0c79a472..8ddeb74a6a 100644 --- a/pyrit/executor/attack/multi_turn/simulated_conversation.py +++ b/pyrit/executor/attack/multi_turn/simulated_conversation.py @@ -227,7 +227,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 @@ -326,7 +326,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 c4499d6f19..cf30784107 100644 --- a/pyrit/executor/attack/multi_turn/tree_of_attacks.py +++ b/pyrit/executor/attack/multi_turn/tree_of_attacks.py @@ -14,6 +14,8 @@ from treelib.tree import Tree from pyrit.common.apply_defaults import REQUIRED_VALUE, apply_defaults +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.common.path import EXECUTOR_SEED_PROMPT_PATH from pyrit.common.utils import combine_dict from pyrit.exceptions import ( @@ -527,7 +529,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_history_send_context = conversation_manager.create_prepended_history_send_context( target=self._objective_target, @@ -578,7 +580,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 @@ -674,7 +676,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 @@ -956,6 +958,11 @@ def duplicate(self) -> _TreeOfAttacksNode: of multiple attack variations from promising nodes. The tree expands by duplicating successful nodes and pruning unsuccessful ones. """ + print_deprecation_message( + old_item="_TreeOfAttacksNode.duplicate", + new_item="_TreeOfAttacksNode.duplicate_async", + removed_in="1.4.0", + ) source_messages = filter_non_replayable_messages( messages=list(self._memory.get_conversation_messages(conversation_id=self.objective_target_conversation_id)) ) @@ -1030,6 +1037,110 @@ def duplicate(self) -> _TreeOfAttacksNode: return duplicate_node + @legacy_sync_override(lambda: _TreeOfAttacksNode.duplicate) + async def duplicate_async(self) -> _TreeOfAttacksNode: + """ + Create a duplicate of this node for branching. + + This method implements the branching mechanism of the TAP algorithm by creating + a new node that inherits the current node's configuration and conversation history. + The duplicate serves as a child node that can explore variations of the attack path + while maintaining the context established by the parent. + + The duplication process preserves all configuration settings while creating new + identifiers and duplicating conversation histories. This allows the child node to + diverge from the parent's path while retaining the conversational context that + led to the branching point. + + Returns: + TreeOfAttacksNode: A new node instance that is a duplicate of this node, + ready to explore a new branch in the attack tree. + + Note: + Duplication is a key operation in the TAP algorithm, enabling the exploration + of multiple attack variations from promising nodes. The tree expands by + duplicating successful nodes and pruning unsuccessful ones. + """ + source_messages = filter_non_replayable_messages( + 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, + messages=source_messages, + ) + duplicate_node = _TreeOfAttacksNode( + objective_target=self._objective_target, + adversarial_chat=self._adversarial_chat, + adversarial_chat_seed_prompt=self._adversarial_chat_seed_prompt, + adversarial_chat_prompt_template=self._adversarial_chat_prompt_template, + adversarial_chat_system_seed_prompt=self._adversarial_chat_system_seed_prompt, + objective_scorer=self._objective_scorer, + on_topic_scorer=self._on_topic_scorer, + request_converters=self._request_converters, + response_converters=self._response_converters, + auxiliary_scorers=self._auxiliary_scorers, + attack_id=self._attack_id, + attack_strategy_name=self._attack_strategy_name, + modality_router=self._modality_router, + record_objective_conversation=self._record_objective_conversation, + use_score_as_feedback=self._use_score_as_feedback, + expectation=self._expectation, + memory_labels=self._memory_labels, + desired_response_prefix=self._desired_response_prefix, + parent_id=self.node_id, + prompt_normalizer=self._prompt_normalizer, + prepended_conversation_config=self._prepended_conversation_config, + ) + + 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( + await self._memory.get_conversation_messages_async( + conversation_id=duplicate_node.objective_target_conversation_id + ) + ) + ) + if self._prepended_history_send_context: + duplicate_node._prepended_history_send_context = ( + self._prepended_history_send_context.remap_for_duplicate_conversation( + conversation_id=duplicate_node.objective_target_conversation_id, + source_messages=source_messages, + duplicated_messages=duplicated_messages, + ) + ) + elif ( + duplicated_messages + and self._objective_target.configuration.includes(capability=CapabilityName.MULTI_TURN) + and not self._objective_target.configuration.includes(capability=CapabilityName.EDITABLE_HISTORY) + ): + duplicate_node._prepended_history_send_context = PrependedHistorySendContext( + conversation_id=duplicate_node.objective_target_conversation_id, + seed_message_ids=(), + replay_seed_each_send=False, + bootstrap_message_ids=tuple(message.get_piece().id for message in duplicated_messages), + ) + + duplicate_node.adversarial_chat_conversation_id = await self._memory.duplicate_conversation_async( + conversation_id=self.adversarial_chat_conversation_id + ) + + # Copy conversation context for adversarial chat system prompt + duplicate_node._conversation_context = self._conversation_context + duplicate_node.last_response = copy.deepcopy(self.last_response) + + # Copy visualization position so the clone starts from the same tree position + duplicate_node._vis_node_id = self._vis_node_id + + logger.debug(f"Node {self.node_id}: Created duplicate node {duplicate_node.node_id}") + + return duplicate_node + def _build_adversarial_manager(self) -> _AdversarialConversationManager: """ Build the adversarial-conversation manager that owns this node's adversarial chat. @@ -1170,7 +1281,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) @@ -1219,6 +1330,23 @@ def _is_first_turn(self) -> bool: target_messages = self._memory.get_conversation_messages(conversation_id=self.objective_target_conversation_id) return not target_messages + @legacy_sync_override(lambda: _TreeOfAttacksNode._is_first_turn) + async def _is_first_turn_async(self) -> bool: + """ + Check if this is the first turn of the conversation. + + This method determines whether the node is executing its initial attack turn by + examining the objective target conversation history. + + Returns: + bool: True if no messages exist in the objective target conversation (first turn), + False if the conversation already contains messages (subsequent turns). + """ + target_messages = await self._memory.get_conversation_messages_async( + conversation_id=self.objective_target_conversation_id + ) + return not target_messages + async def _generate_first_turn_prompt_async(self, objective: str) -> str: """ Generate the prompt for the first turn using the seed prompt. @@ -1246,9 +1374,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") @@ -1284,7 +1413,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"] @@ -1330,7 +1461,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" @@ -1914,13 +2045,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: """ @@ -1953,7 +2084,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: """ @@ -2082,6 +2213,35 @@ def _branch_existing_nodes(self, context: TAPAttackContext) -> None: context.nodes.extend(cloned_nodes) + @legacy_sync_override(lambda: TreeOfAttacksWithPruningAttack._branch_existing_nodes) + async def _branch_existing_nodes_async(self, context: TAPAttackContext) -> None: + """ + Branch existing nodes to create new exploration paths. + + Each existing node is branched according to the branching factor to explore variations. + The original node is retained, and (`branching_factor` - 1) duplicates are created, + resulting in branching_factor total paths from each parent node. Duplicated nodes + inherit the full conversation history from their parent. + + Args: + context (TAPAttackContext): The attack context containing the current state of nodes. + """ + cloned_nodes = [] + + for node in context.nodes: + for _ in range(self._configuration.branching_factor - 1): + 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( + conversation_id=cloned_node.adversarial_chat_conversation_id, + conversation_type=ConversationType.ADVERSARIAL, + ) + ) + cloned_nodes.append(cloned_node) + + context.nodes.extend(cloned_nodes) + async def _send_prompts_to_all_nodes_async(self, context: TAPAttackContext) -> None: """ Send prompts for all nodes in the current level. @@ -2395,6 +2555,29 @@ def _create_success_result(self, context: TAPAttackContext) -> TAPAttackResult: outcome_reason=outcome_reason, ) + @legacy_sync_override(lambda: TreeOfAttacksWithPruningAttack._create_success_result) + async def _create_success_result_async(self, context: TAPAttackContext) -> TAPAttackResult: + """ + Create a success result for the attack. + + Constructs a `TAPAttackResult` indicating successful objective achievement. + The outcome reason includes the achieved score and threshold for transparency. + Delegates to `_create_attack_result` for common result construction logic. + + Args: + context (TAPAttackContext): The attack context containing the final state + after execution, including best conversation ID and score. + + Returns: + TAPAttackResult: The success result indicating the attack achieved its objective. + """ + 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 await self._create_attack_result_async( + context=context, outcome=AttackOutcome.SUCCESS, outcome_reason=outcome_reason + ) + def _create_failure_result(self, context: TAPAttackContext) -> TAPAttackResult: """ Create a failure result for the attack. @@ -2429,6 +2612,39 @@ def _create_failure_result(self, context: TAPAttackContext) -> TAPAttackResult: outcome_reason=outcome_reason, ) + @legacy_sync_override(lambda: TreeOfAttacksWithPruningAttack._create_failure_result) + async def _create_failure_result_async(self, context: TAPAttackContext) -> TAPAttackResult: + """ + Create a failure result for the attack. + + Constructs a `TAPAttackResult` indicating the attack failed to achieve its objective + within the configured tree depth. The outcome reason includes the best score + achieved for diagnostic purposes. Delegates to `_create_attack_result` for common + result construction logic. + + Args: + context (TAPAttackContext): The attack context containing the final state + after execution, including best conversation ID and score. + + Returns: + TAPAttackResult: The failure result indicating the attack did not achieve its objective. + """ + best_score = context.best_objective_score + if best_score is not None and attack_outcome_from_score(best_score) is AttackOutcome.UNDETERMINED: + return await self._create_attack_result_async( + context=context, + outcome=AttackOutcome.UNDETERMINED, + outcome_reason=getattr(best_score, "score_rationale", None) + or "Objective scorer could not reach a verdict", + ) + + normalized_best = normalize_score_to_float(best_score) + outcome_reason = f"Did not achieve threshold score. Best score: {normalized_best:.2f}" + + return await self._create_attack_result_async( + context=context, outcome=AttackOutcome.FAILURE, outcome_reason=outcome_reason + ) + def _create_attack_result( self, *, @@ -2490,6 +2706,67 @@ def _create_attack_result( return result + @legacy_sync_override(lambda: TreeOfAttacksWithPruningAttack._create_attack_result) + async def _create_attack_result_async( + self, + *, + context: TAPAttackContext, + outcome: AttackOutcome, + outcome_reason: str, + ) -> TAPAttackResult: + """ + Create `TAPAttackResult` with common counting logic and metadata. + + Consolidates the result construction logic used by both success and failure cases. + Extracts the last response from the best conversation, compiles auxiliary scores + from the top node, calculates tree statistics, and populates all TAP-specific + metadata fields. + + Args: + context (TAPAttackContext): The attack context containing the final state + after execution, including best conversation ID, score, and tree visualization. + outcome (AttackOutcome): The attack outcome (`SUCCESS` or `FAILURE`). + outcome_reason (str): Human-readable explanation of the outcome. + + Returns: + TAPAttackResult: The constructed result containing all relevant information + about the attack execution, including conversation ID, objective, outcome, + outcome reason, executed turns, last response, last score, and additional metadata. + """ + 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 + auxiliary_scores_summary = self._get_auxiliary_scores_summary(context.nodes) + + # Calculate statistics from tree visualization + stats = self._calculate_tree_statistics(context.tree_visualization) + + # Create the result with basic information + result = TAPAttackResult( + atomic_attack_identifier=AtomicAttackIdentifier.build(attack_identifier=self.get_identifier()), + conversation_id=context.best_conversation_id or "", + objective=context.objective, + outcome=outcome, + outcome_reason=outcome_reason, + executed_turns=context.executed_turns, + last_response=last_response, + automated_score=context.best_objective_score, + related_conversations=context.related_conversations, + labels=context.memory_labels, + ) + + # Set attack-specific metadata using properties + result.tree_visualization = context.tree_visualization + result.nodes_explored = stats["nodes_explored"] + result.nodes_pruned = stats["nodes_pruned"] + result.max_depth_reached = context.executed_turns + result.auxiliary_scores_summary = auxiliary_scores_summary + result.best_adversarial_conversation_id = context.best_adversarial_conversation_id + + return result + def _get_result_response( self, *, @@ -2544,6 +2821,58 @@ def _get_result_response( return self._get_last_response_from_conversation(conversation_id) + @legacy_sync_override(lambda: TreeOfAttacksWithPruningAttack._get_result_response) + async def _get_result_response_async( + self, + *, + conversation_id: str | None, + score: Score | None, + ) -> MessagePiece | None: + """ + Resolve the response associated with TAP's already-selected score. + + This method does not compare scores or decide which node is best. The caller + supplies the conversation and score selected by `_update_best_performing_node`. + When a score exists, its message piece ID is used to find the corresponding + assistant response in that conversation, keeping `last_response` and + `last_score` aligned even when a later response was not scored. + + Duplicated TAP branches preserve lineage through `original_prompt_id`, and + memory may attach the score to that original ID rather than the branch-local + message ID. Matching either ID resolves the same logical response. If no score + exists, the final conversation message is returned only as an unscored + reporting fallback. + + Args: + conversation_id (str | None): The selected TAP conversation ID. + score (Score | None): The selected objective score. + + Returns: + MessagePiece | None: The response associated with the selected score, the + final unscored message when no score exists, or `None` when it cannot + be resolved. + """ + if not conversation_id: + return None + + if score: + message_piece_id = getattr(score, "message_piece_id", None) + if not message_piece_id: + return None + + responses = await self._memory.get_message_pieces_async(conversation_id=conversation_id, role="assistant") + return next( + ( + response + for response in responses + if str(response.id) == str(message_piece_id) + or str(response.original_prompt_id) == str(message_piece_id) + ), + None, + ) + + return await self._get_last_response_from_conversation_async(conversation_id) + def _get_last_response_from_conversation(self, conversation_id: str | None) -> MessagePiece | None: """ Retrieve the last response from a conversation. @@ -2566,6 +2895,29 @@ def _get_last_response_from_conversation(self, conversation_id: str | None) -> M responses = self._memory.get_message_pieces(conversation_id=conversation_id) return responses[-1] if responses else None + @legacy_sync_override(lambda: TreeOfAttacksWithPruningAttack._get_last_response_from_conversation) + async def _get_last_response_from_conversation_async(self, conversation_id: str | None) -> MessagePiece | None: + """ + Retrieve the last response from a conversation. + + Fetches all message pieces from memory for the given conversation ID + and returns the most recent one. This is typically used to extract the final + response from the best performing conversation for inclusion in the attack result. + + Args: + conversation_id (str | None): The conversation ID to retrieve from. May be + None if no successful conversations were found during the attack. + + Returns: + MessagePiece | None: The last response piece from the conversation, + or None if no conversation ID was provided or no responses exist. + """ + if not conversation_id: + return None + + 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]: """ Extract auxiliary scores from the best node if available. 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..4671c25d36 100644 --- a/pyrit/executor/benchmark/fairness_bias.py +++ b/pyrit/executor/benchmark/fairness_bias.py @@ -8,6 +8,7 @@ from dataclasses import dataclass, field from typing import Any, cast, overload +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.utils import get_kwarg_param from pyrit.executor.attack.core import ( AttackConverterConfig, @@ -184,7 +185,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) @@ -257,6 +258,38 @@ def _format_experiment_results( ), } + @legacy_sync_override(lambda: FairnessBiasBenchmark._format_experiment_results) + async def _format_experiment_results_async( + self, context: FairnessBiasBenchmarkContext, attack_result: AttackResult, experiment_num: int + ) -> dict[str, Any]: + """ + Format the experiment data into a dictionary. + + Args: + context (FairnessBiasBenchmarkContext): The benchmark context + attack_result (AttackResult): The result of benchmark attack + experiment_num (int): The current experiment number + + Returns: + Dict: dictionary with components from experiment parsed and formatted + """ + 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 { + "experiment_number": str(experiment_num + 1), + "subject": context.subject, + "story_type": context.story_type, + "generated_name": subject_name or "Not found", + "generated_content": response, + "score_category": attack_result.last_score.score_category if attack_result.last_score else "unknown", + "score_rationale": ( + attack_result.last_score.score_rationale if attack_result.last_score else "Scoring not available" + ), + } + def _format_story_prompt(self, *, subject: str, story_type: str) -> str: """ Format the story generation prompt. 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..07e0477849 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,56 @@ def _print_conversations(self, result: FuzzerResult) -> None: self._print_colored(f"{self._indent * 3} Score: {score_value} | {score.score_rationale}", Fore.CYAN) print() + @legacy_sync_override(lambda: FuzzerResultPrinter._print_conversations) + 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/azure_sql_memory.py b/pyrit/memory/azure_sql_memory.py index 651bfb76aa..6276d91b26 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,39 @@ 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__() + + 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 +153,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 +162,47 @@ 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 = params.pop("dsn").replace(";Trusted_Connection=Yes", "") + 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() + engine = self._async_engines.get(loop) + try: + if engine is not None: + await engine.dispose() + finally: + auth = self._async_auth.get(loop) + if auth is not None: + await auth.close_async() + del self._async_auth[loop] + # Retain loop ownership until both resources close successfully. + if engine is not None: + del self._async_engines[loop] @staticmethod def _resolve_sas_token(env_var_name: str, passed_value: str | None = None) -> str | None: @@ -194,7 +249,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 +553,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 +561,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 +574,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 +583,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 +596,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 +644,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 +890,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 d39adb7254..a2108fd2d7 100644 --- a/pyrit/memory/memory_interface.py +++ b/pyrit/memory/memory_interface.py @@ -10,21 +10,24 @@ import re 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 +from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, ParamSpec, TypeVar from urllib.parse import urlparse from sqlalchemy import MetaData, and_, case, exists, 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 +57,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 +100,7 @@ SeedGroup, SeedIdentifier, SeedObjective, + SeedPrompt, SeedType, TargetIdentifier, group_conversation_message_pieces_by_sequence, @@ -115,6 +119,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 +385,158 @@ 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._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() + ): + 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 without blocking the caller's event loop.""" + try: + await run_legacy_sync_async(self._initialize_schema) + except BaseException: + await self.dispose_engine_async() + raise + + 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. + """ + await self.dispose_loop_resources_async() + if self._async_engines: + raise RuntimeError("Close memory resources on their owning event loops before disposing memory.") + await run_legacy_sync_async(self._dispose_sync_engine) + + @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 +755,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 +812,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 +839,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 +879,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 +955,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 +993,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 +1013,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 +1027,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 +1046,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 +1198,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 +1244,7 @@ def get_target_identifiers( }, ) - def get_converter_identifiers( + def _execute_get_converter_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1128,7 +1283,7 @@ def get_converter_identifiers( }, ) - def get_scorer_identifiers( + def _execute_get_scorer_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1162,7 +1317,7 @@ def get_scorer_identifiers( }, ) - def get_scenario_identifiers( + def _execute_get_scenario_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1202,7 +1357,7 @@ def get_scenario_identifiers( }, ) - def get_seed_identifiers( + def _execute_get_seed_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1242,7 +1397,7 @@ def get_seed_identifiers( }, ) - def get_attack_identifiers( + def _execute_get_attack_identifiers( self, *, identifier_hashes: Sequence[str] | None = None, @@ -1282,7 +1437,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 +1465,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 +1527,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 +1723,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 +1742,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 +1751,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 +1779,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 +1805,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 +1866,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 +1875,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 +1892,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 +1915,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 +2014,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], @@ -1857,6 +2032,7 @@ def add_scores_to_memory( prepared_content_hashes={}, ) + @legacy_sync_override(lambda: MemoryInterface.add_scores_to_memory) async def add_scores_to_memory_async( self, *, @@ -1877,7 +2053,9 @@ async def add_scores_to_memory_async( ) ) if not media_scorables: - self.add_scores_to_memory(scores=scores, observations=observations) + await self._run_database_operation_async( + self._execute_add_scores_to_memory, scores=scores, observations=observations + ) return prepared_content = await asyncio.gather( @@ -1898,7 +2076,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, @@ -1971,7 +2150,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( @@ -2268,7 +2447,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. @@ -2292,7 +2473,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], @@ -2312,7 +2493,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], @@ -2345,7 +2526,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, @@ -2411,7 +2592,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, @@ -2450,7 +2631,7 @@ 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._execute_get_message_pieces( role=role, conversation_id=conversation_id, prompt_ids=prompt_ids, @@ -2495,7 +2676,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. @@ -2512,7 +2693,7 @@ 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._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: @@ -2536,7 +2717,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. @@ -2554,7 +2756,7 @@ 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._execute_get_conversation_messages(conversation_id=response.conversation_id) return conversation[response.sequence - 1] def _build_message_piece_identifier_conditions( @@ -2604,7 +2806,7 @@ def _build_message_piece_identifier_conditions( ) return conditions - def get_message_pieces( + def _execute_get_message_pieces( self, *, role: str | None = None, @@ -2703,7 +2905,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. @@ -2729,7 +2931,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. @@ -2743,18 +2945,18 @@ 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._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._execute_duplicate_messages(messages=messages) if all_pieces: - self.add_conversation_to_memory( + self._execute_add_conversation_to_memory( conversation=Conversation(conversation_id=new_conversation_id, target_identifier=source_target) ) - self.add_message_pieces_to_memory(message_pieces=all_pieces) + self._execute_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). @@ -2767,7 +2969,7 @@ 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._execute_get_conversation_messages(conversation_id=conversation_id) # remove the final turn from the conversation if len(messages) == 0: @@ -2785,16 +2987,16 @@ 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._execute_duplicate_messages(messages=messages_to_duplicate) if all_pieces: - self.add_conversation_to_memory( + self._execute_add_conversation_to_memory( conversation=Conversation(conversation_id=new_conversation_id, target_identifier=source_target) ) - self.add_message_pieces_to_memory(message_pieces=all_pieces) + self._execute_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. @@ -2804,27 +3006,29 @@ 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: - for piece in message_pieces: - 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 + ] 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._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. @@ -2832,7 +3036,7 @@ 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._execute_get_message_pieces(conversation_id=message_pieces[0].conversation_id) sequence = 0 @@ -2842,7 +3046,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. @@ -2893,7 +3099,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, @@ -2928,7 +3134,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: """ @@ -2941,7 +3147,7 @@ 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( + return self._execute_update_prompt_entries_by_conversation_id( conversation_id=conversation_id, update_fields={"prompt_metadata": prompt_metadata} ) @@ -2984,6 +3190,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. @@ -2997,6 +3216,19 @@ 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._dispose_sync_engine() + + def _dispose_sync_engine(self) -> None: """ Dispose the engine and clean up resources. """ @@ -3014,10 +3246,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, @@ -3116,7 +3348,7 @@ def _build_seed_filter_conditions( return conditions - def get_seeds( + def _execute_get_seeds( self, *, value: str | None = None, @@ -3195,7 +3427,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, @@ -3291,7 +3523,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) @@ -3302,7 +3534,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, @@ -3409,7 +3641,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) @@ -3499,8 +3731,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"]: @@ -3530,6 +3762,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 @@ -3663,7 +3899,7 @@ 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._execute_get_seeds(value_sha256=chunk, dataset_name=dataset_name): if not existing.value_sha256: continue conditions_key = self._seed_conditions_key(existing) @@ -3688,7 +3924,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. @@ -3766,7 +4002,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]] = {} @@ -3808,7 +4044,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. @@ -3891,7 +4127,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) @@ -3944,7 +4194,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, @@ -3992,7 +4242,7 @@ def get_seed_groups( Returns: Sequence[SeedGroup]: A list of `SeedGroup` objects that match the filtering criteria. """ - seeds = self.get_seeds( + seeds = self._execute_get_seeds( value=value, value_sha256=value_sha256, dataset_name=dataset_name, @@ -4014,7 +4264,7 @@ 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._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: @@ -4027,7 +4277,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. @@ -4036,7 +4286,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: @@ -4052,7 +4302,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, @@ -4082,7 +4332,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 @@ -4102,7 +4352,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. @@ -4113,7 +4363,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 @@ -4148,7 +4398,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. @@ -4183,7 +4433,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. @@ -4212,7 +4462,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, @@ -4741,7 +4991,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, @@ -4766,7 +5016,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)) @@ -4785,9 +5035,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) @@ -4804,7 +5054,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. @@ -4815,7 +5065,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( @@ -4833,7 +5083,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, @@ -4856,7 +5106,7 @@ def update_scenario_run_state( Raises: ValueError: If the scenario result is not found. """ - self.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, @@ -4864,7 +5114,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, @@ -4879,7 +5129,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: @@ -4902,7 +5152,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, @@ -4947,7 +5197,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( @@ -4962,7 +5212,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, @@ -4983,14 +5233,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, @@ -5002,7 +5252,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") @@ -5010,13 +5260,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], @@ -5043,7 +5293,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 ( [ @@ -5056,7 +5306,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 +5399,7 @@ def get_scenario_run_history_page( ScenarioResultEntry.timestamp.desc(), ScenarioResultEntry.id.desc(), ).limit(limit + 1) - with closing(self.get_session()) as session: + with closing(self._get_session()) as session: rows = session.execute(statement).all() page_rows = rows[:limit] @@ -5174,7 +5424,7 @@ def get_scenario_run_history_page( ) for row in page_rows ] - aggregates = self.get_scenario_history_aggregates( + 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 @@ -5182,7 +5432,7 @@ def get_scenario_run_history_page( ) return records, aggregates, len(rows) > limit - def get_scenario_history_aggregates( + def _execute_get_scenario_history_aggregates( self, *, scenario_result_ids: Sequence[str], @@ -5221,7 +5471,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() @@ -5449,10 +5699,10 @@ def _parse_scenario_started_at(*, raw_value: Any) -> datetime | None: return None return value if value.tzinfo is not None else None - 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)) @@ -5467,7 +5717,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, @@ -5534,7 +5784,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 @@ -5583,7 +5833,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, @@ -5832,6 +6082,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. @@ -5848,3 +6111,3124 @@ 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] = ()) -> 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) + + 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, + ) -> 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, + ) + + @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, + ) -> 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. + + 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, + ) + + 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, + ) -> 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, + ) + + @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, + ) -> 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. + + 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, + ) + + 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 + ] + 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 04421c09f3..e20868f7ab 100644 --- a/pyrit/memory/sqlite_memory.py +++ b/pyrit/memory/sqlite_memory.py @@ -9,14 +9,15 @@ 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, create_async_engine from sqlalchemy.orm import InstrumentedAttribute, sessionmaker from sqlalchemy.orm.session import Session -from sqlalchemy.pool import StaticPool +from sqlalchemy.pool import AsyncAdaptedQueuePool, StaticPool from sqlalchemy.sql.expression import TextClause from pyrit.common.path import DB_DATA_PATH @@ -32,6 +33,9 @@ from pyrit.memory.storage import DiskStorageIO from pyrit.models import ConversationStats +if TYPE_CHECKING: + from sqlalchemy.engine import Connection + logger = logging.getLogger(__name__) @@ -54,6 +58,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 +80,41 @@ 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._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 + + # Legacy sync sessions share a connection. Async sessions use a separate bounded + # pool on the same named database and must not acquire this thread-owned lock. self._connection_lock: threading.RLock | None = threading.RLock() if self.db_path == ":memory:" else 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() + + 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.update(poolclass=AsyncAdaptedQueuePool, pool_size=1, max_overflow=0) + return create_async_engine(f"sqlite+aiosqlite:///{database}", echo=self._verbose, **kwargs) + + 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 +127,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 +151,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: @@ -290,7 +317,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. @@ -332,7 +359,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. """ @@ -373,7 +400,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. @@ -381,7 +408,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", @@ -389,7 +416,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 @@ -398,7 +425,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 @@ -412,7 +439,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. @@ -461,7 +488,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 cc5b44c6ba..9c9e5792c7 100644 --- a/pyrit/prompt_normalizer/prompt_normalizer.py +++ b/pyrit/prompt_normalizer/prompt_normalizer.py @@ -119,8 +119,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: @@ -141,14 +143,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( @@ -165,7 +167,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], @@ -175,7 +177,7 @@ async def send_prompt_async( ) 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 @@ -192,7 +194,7 @@ async def send_prompt_async( error="empty", ) 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]) @@ -210,7 +212,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] @@ -414,7 +416,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, @@ -444,8 +446,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: @@ -458,7 +462,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 59050aac54..b05922b23b 100644 --- a/pyrit/prompt_target/common/discover_target_capabilities.py +++ b/pyrit/prompt_target/common/discover_target_capabilities.py @@ -327,10 +327,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 @@ -414,10 +416,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.", @@ -425,7 +429,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 diff --git a/pyrit/prompt_target/common/prompt_target.py b/pyrit/prompt_target/common/prompt_target.py index f28299bcc3..d70ecbcede 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 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 ( @@ -283,7 +285,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 @@ -337,6 +341,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. " @@ -360,6 +369,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. @@ -382,8 +449,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..3454fb49eb 100644 --- a/pyrit/prompt_target/websocket_copilot_target.py +++ b/pyrit/prompt_target/websocket_copilot_target.py @@ -19,6 +19,7 @@ ManualCopilotAuthenticator, ) from pyrit.common import get_mime_type +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.exceptions import ( EmptyResponseException, pyrit_target_retry, @@ -635,6 +636,23 @@ def _is_start_of_session(self, *, conversation_id: str) -> bool: conversation_history = self._memory.get_conversation_messages(conversation_id=conversation_id) return len(conversation_history) == 0 + @legacy_sync_override(lambda: WebSocketCopilotTarget._is_start_of_session) + async def _is_start_of_session_async(self, *, conversation_id: str) -> bool: + """ + Determine if this is the first message in a PyRIT conversation. + + Checks memory for existing conversation history to set the appropriate + flag for Copilot's server-side conversation initialization. + + Args: + conversation_id (str): The PyRIT conversation ID. + + Returns: + bool: True if no prior messages exist in this conversation, False otherwise. + """ + 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]: """ Generate consistent Copilot session_id and conversation_id for a PyRIT conversation. @@ -684,7 +702,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..a1ee8ccd52 100644 --- a/pyrit/scenario/core/atomic_attack.py +++ b/pyrit/scenario/core/atomic_attack.py @@ -18,6 +18,7 @@ import logging from typing import TYPE_CHECKING, Any +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.utils import to_sha256 from pyrit.executor.attack import AttackExecutor, AttackExecutorResult from pyrit.executor.attack.core.attack_result_attribution import AttackResultAttribution @@ -399,7 +400,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: @@ -453,3 +454,40 @@ def _enrich_atomic_attack_identifiers(self, *, results: AttackExecutorResult[Att "atomic_attack_identifier": identifier.model_dump(), }, ) + + @legacy_sync_override(lambda: AtomicAttack._enrich_atomic_attack_identifiers) + 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. + + Uses ``results.input_indices`` to map each completed result back to its + originating seed group by index, then rebuilds the atomic_attack_identifier + to include the seed identifiers and any technique seeds. The enriched + identifier is then flushed back to the corresponding ``AttackResultEntry`` row. + + Args: + results: The execution results to enrich. + """ + memory = CentralMemory.get_memory_instance() + + for result, idx in zip(results.completed_results, results.input_indices, strict=True): + if idx < len(self._seed_groups): + identifier = AtomicAttackIdentifier.build( + technique_identifier=self._attack_technique.get_identifier(), + seed_group=self._seed_groups[idx], + ) + + # Persist the enriched identifier back to the database. + # Stamp eval_hash so it lands in the stored JSON for DB-level filtering. + identifier = identifier.with_eval_hash(AtomicAttackEvaluationIdentifier(identifier).eval_hash) + + result.atomic_attack_identifier = identifier + + if result.attack_result_id: + ( + 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 8fb8ce704c..545ab3c616 100644 --- a/pyrit/scenario/core/scenario.py +++ b/pyrit/scenario/core/scenario.py @@ -20,11 +20,11 @@ from tqdm.auto import tqdm from pyrit.common import get_global_default_values +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.utils import to_sha256 from pyrit.exceptions import ScenarioPartialFailureException from pyrit.executor.attack import AttackExecutor, AttackExecutorResult from pyrit.memory import CentralMemory -from pyrit.memory.memory_models import ScenarioResultEntry from pyrit.models import ( SCENARIO_RUN_PLAN_METADATA_KEY, AttackOutcome, @@ -987,7 +987,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( @@ -1008,9 +1010,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 @@ -1035,7 +1039,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}") @@ -1364,6 +1368,61 @@ def _get_completed_objective_hashes_for_attack(self, *, atomic_attack: AtomicAtt return completed_hashes + @legacy_sync_override(lambda: Scenario._get_completed_objective_hashes_for_attack) + async def _get_completed_objective_hashes_for_attack_async(self, *, atomic_attack: AtomicAttack) -> set[str]: + """ + Return the set of ``objective_sha256`` values already completed (non-error) + for a specific atomic attack inside this scenario. + + Queries ``AttackResultEntry`` rows directly by ``attribution_parent_id`` — + which is stamped at write-time by the attack persistence path — so + results from an interrupted run are visible even though the + ``ScenarioResult.attack_results`` aggregate may not yet reflect them. + Identity is content-derived (``to_sha256(objective)``), so it stays + stable even if ``get_seed_groups()`` reorders or resamples between runs. + + Rows are matched on ``(parent_collection, parent_eval_hash)`` so that + two ``AtomicAttack`` instances sharing a name but using different + techniques (e.g. base64 vs hex encoders) never cross-pollinate their + completed-hash sets on resume. Rows persisted before + ``parent_eval_hash`` was introduced (or by callers that don't supply + one) match name-only as a backward-compatible fallback. + + Args: + atomic_attack (AtomicAttack): The live atomic attack whose + ``atomic_attack_name`` and technique identifier scope the query. + + Returns: + set[str]: ``objective_sha256`` hex strings for completed-without-error rows. + """ + if not self._scenario_result_id: + return set() + + atomic_attack_name = atomic_attack.atomic_attack_name + expected_eval_hash = atomic_attack.technique_eval_hash + + completed_hashes: set[str] = set() + try: + rows = await self._memory.get_attack_results_async(scenario_result_id=self._scenario_result_id) + for row in rows: + if row.outcome == AttackOutcome.ERROR: + continue + if row.attribution_data is None: + continue + if row.attribution_data.get("parent_collection") != atomic_attack_name: + continue + row_eval_hash = row.attribution_data.get("parent_eval_hash") + if row_eval_hash is not None and row_eval_hash != expected_eval_hash: + continue + if row.objective: + completed_hashes.add(to_sha256(row.objective)) + except Exception as e: + logger.warning( + f"Failed to retrieve completed objective hashes for atomic attack '{atomic_attack_name}': {str(e)}" + ) + + return completed_hashes + async def _get_remaining_atomic_attacks_async(self) -> list[AtomicAttack]: """ Get the list of atomic attacks that still have objectives to complete. @@ -1384,7 +1443,7 @@ async def _get_remaining_atomic_attacks_async(self) -> list[AtomicAttack]: remaining_attacks: list[AtomicAttack] = [] for atomic_attack in self._atomic_attacks: - completed_hashes = self._get_completed_objective_hashes_for_attack(atomic_attack=atomic_attack) + completed_hashes = await self._get_completed_objective_hashes_for_attack_async(atomic_attack=atomic_attack) if completed_hashes: original_count = len(atomic_attack.seed_groups) @@ -1528,7 +1587,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: @@ -1544,11 +1603,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}'") @@ -1557,7 +1618,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 @@ -1577,7 +1640,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 @@ -1610,20 +1673,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) @@ -1632,12 +1696,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") @@ -1666,13 +1732,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") @@ -1730,6 +1798,21 @@ def _mark_scenario_failed(self, *, scenario_result_id: str, error: BaseException error_type=type(error).__name__, ) + @legacy_sync_override(lambda: Scenario._mark_scenario_failed) + 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__)}" + ( + 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( self, *, 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..36298f242f 100644 --- a/pyrit/scenario/scenarios/airt/jailbreak.py +++ b/pyrit/scenario/scenarios/airt/jailbreak.py @@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, ClassVar from pyrit.common import apply_defaults +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.converter import TextJailbreakConverter from pyrit.datasets import TextJailBreak from pyrit.executor.attack.single_turn.prompt_sending import PromptSendingAttack @@ -310,6 +311,46 @@ def _resolve_templates(self) -> list[str]: return list(jailbreak_names) return TextJailBreak.get_jailbreak_templates(num_templates=num_jailbreaks or _DEFAULT_NUM_JAILBREAKS) + @legacy_sync_override(lambda: Jailbreak._resolve_templates) + async def _resolve_templates_async(self) -> list[str]: + """ + Resolve the jailbreak templates for this run, replaying the persisted set on resume. + + On a fresh run this reads the run parameters: an explicit ``jailbreak_names`` set or a random + ``num_jailbreaks`` sample (defaulting to a small random draw when neither is given). On resume + the originally chosen set is read back from the stored ``ScenarioResult`` metadata so a random + sample isn't redrawn (which would diverge from the persisted attacks). + + Returns: + list[str]: The jailbreak template file names to run. + + Raises: + ValueError: If both ``num_jailbreaks`` and ``jailbreak_names`` are provided, or if + ``jailbreak_names`` contains an unknown template. + """ + if self._scenario_result_id is not None: + 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: + return list(persisted) + + num_jailbreaks = self.params.get("num_jailbreaks") + jailbreak_names = self.params.get("jailbreak_names") + + if jailbreak_names and num_jailbreaks: + raise ValueError( + "Please provide only one of `num_jailbreaks` (random selection)" + " or `jailbreak_names` (specific selection)." + ) + if jailbreak_names: + available = set(TextJailBreak.get_jailbreak_templates()) + diff = set(jailbreak_names) - available + if diff: + raise ValueError(f"Error: could not find templates `{diff}`!") + return list(jailbreak_names) + return TextJailBreak.get_jailbreak_templates(num_templates=num_jailbreaks or _DEFAULT_NUM_JAILBREAKS) + def _build_initial_scenario_metadata(self) -> dict[str, Any]: """ Persist the resolved jailbreak templates alongside the base scenario metadata. @@ -464,7 +505,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/multilingual.py b/pyrit/scenario/scenarios/airt/multilingual.py index 189e39ee50..ac6062a4ed 100644 --- a/pyrit/scenario/scenarios/airt/multilingual.py +++ b/pyrit/scenario/scenarios/airt/multilingual.py @@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, Literal from pyrit.common import apply_defaults +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.path import DATASETS_PATH from pyrit.converter import RandomTranslationConverter, TranslationConverter from pyrit.executor.attack import PromptSendingAttack @@ -277,6 +278,48 @@ def _resolve_languages(self) -> list[str]: raise ValueError(f"num_languages must be between 1 and {len(self._default_languages)}.") return _normalize_languages(random.sample(self._default_languages, count)) + @legacy_sync_override(lambda: Multilingual._resolve_languages) + async def _resolve_languages_async(self) -> list[str]: + """ + Resolve the languages for this run, replaying the persisted set on resume. + + On a fresh run this reads the run parameters: an explicit ``languages`` set or a random + ``num_languages`` sample (defaulting to a small random draw when neither is given). On resume + the originally chosen set is read back from the stored ``ScenarioResult`` metadata so a random + sample isn't redrawn (which would diverge from the persisted attacks). + + Returns: + list[str]: The explicit or randomly sampled languages for this run. + + Raises: + ValueError: If both ``num_languages`` and ``languages`` are provided, + or if ``num_languages`` is out of bounds. + """ + if self._scenario_result_id is not None: + 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: + return _normalize_languages(list(persisted)) + + num_languages = self.params.get("num_languages") + languages = self.params.get("languages") + + if num_languages is not None and languages is not None: + raise ValueError( + "Please provide only one of `num_languages` (random selection) or `languages` (specific selection)." + ) + + if languages is not None: + if not languages: + raise ValueError("languages must contain at least one language.") + return _normalize_languages(languages) + + count = int(num_languages) if num_languages is not None else _DEFAULT_NUM_LANGUAGES + if count < 1 or count > len(self._default_languages): + raise ValueError(f"num_languages must be between 1 and {len(self._default_languages)}.") + return _normalize_languages(random.sample(self._default_languages, count)) + def _build_initial_scenario_metadata(self) -> dict[str, Any]: """ Persist the resolved languages alongside the base scenario metadata. @@ -306,7 +349,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 b0a7d05dd7..fd388196fb 100644 --- a/pyrit/scenario/scenarios/benchmark/adversarial.py +++ b/pyrit/scenario/scenarios/benchmark/adversarial.py @@ -10,8 +10,9 @@ from functools import cache from typing import TYPE_CHECKING, ClassVar -from pyrit.analytics import get_cached_results_for_technique +from pyrit.analytics import get_cached_results_for_technique, get_cached_results_for_technique_async from pyrit.common import apply_defaults +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.path import EXECUTOR_SEED_PROMPT_PATH from pyrit.models import ( AttackOutcome, @@ -414,7 +415,7 @@ async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list if not self._use_cached: return atomic_attacks - cached_attack_names = self._collect_cached_completion_pairs(atomic_attacks=atomic_attacks) + cached_attack_names = await self._collect_cached_completion_pairs_async(atomic_attacks=atomic_attacks) filtered = [c for c in atomic_attacks if c.atomic_attack_name not in cached_attack_names] skipped_attacks = [c for c in atomic_attacks if c.atomic_attack_name in cached_attack_names] if skipped_attacks: @@ -588,3 +589,99 @@ def _collect_cached_completion_pairs(self, *, atomic_attacks: list[AtomicAttack] self._cached_results_by_name[attack.atomic_attack_name] = attributed return cached_names + + @legacy_sync_override(lambda: AdversarialBenchmark._collect_cached_completion_pairs) + 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. + + Database queries are deduplicated by unique ``technique_eval_hash`` (one query per hash, + regardless of how many atomic attacks share that hash), then the skip eligibility + decision is applied per-atomic-attack using a Python-side filter on + ``attribution_data["parent_collection"]``. + + **Dataset-level scoping is implemented as a semantic Python filter, not a database query.** + ``get_cached_results_for_technique`` has no ``dataset`` parameter; it returns all results + for a given ``(technique_eval_hash × objective_target_eval_hash)`` pair regardless of which + dataset they came from. The scoping happens here: a retrieved result only counts toward the + skip decision for atomic-attack *X* if its ``attribution_data["parent_collection"]`` equals + ``X.atomic_attack_name``. This means two atomic attacks that share a technique+target hash + (e.g. the same red-teaming technique run against the same model for both ``harmbench`` and + ``advbench``) are cached independently: a harmbench result will never cause the advbench + slot to be skipped. + + A dataset slot is considered cached when the attribution-filtered result set contains at + least one ``AttackResult`` with outcome ``SUCCESS`` or ``FAILURE`` — + ``ERROR`` and ``UNDETERMINED`` outcomes are ignored so transient failures retry on the + next run. + + The objective-target eval hash is computed once from + ``self._objective_target_identifier`` (populated by the base + ``Scenario.initialize_async``) via + ``ObjectiveTargetEvaluationIdentifier``. + + As a side effect, populates ``self._cached_results_by_name`` with the + attribution-filtered ``AttackResult`` lists keyed by ``atomic_attack_name`` so that + ``_build_atomic_attacks_async`` can inject them into the final ``ScenarioResult`` + via ``run_async`` without re-filtering. + + Args: + atomic_attacks: The candidate atomic attacks built earlier in + ``_build_atomic_attacks_async``. + + Returns: + set[str]: ``atomic_attack_name`` values that have at least one qualifying cached + ``AttackResult``. Empty set when the scenario has no objective target identifier + or every analytics lookup fails (logged at warning level) — caching becomes a + no-op rather than blocking the run. + """ + cached_names: set[str] = set() + self._cached_results_by_name: dict[str, list[AttackResult]] = {} + + if self._objective_target_identifier is None: + return cached_names + + try: + objective_target_eval_hash = ObjectiveTargetEvaluationIdentifier( + self._objective_target_identifier + ).eval_hash + except Exception as exc: + logger.warning( + "skip_cached: failed to compute objective_target eval hash (%s); skipping cache filter.", + exc, + ) + return cached_names + + unique_technique_hashes = {c.technique_eval_hash for c in atomic_attacks if c.technique_eval_hash} + + # One DB query per unique hash (deduplication), results stored temporarily by hash. + raw_results_by_hash: dict[str, list[AttackResult]] = {} + for technique_eval_hash in unique_technique_hashes: + try: + 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, + ) + except Exception as exc: + logger.warning( + "skip_cached: analytics lookup failed for technique_eval_hash=%s (%s); not treating it as cached.", + technique_eval_hash, + exc, + ) + + # Per-attack attribution filter: only count results that were produced for this + # specific atomic_attack_name slot (dataset-level scoping via parent_collection). + for attack in atomic_attacks: + if not attack.technique_eval_hash or attack.technique_eval_hash not in raw_results_by_hash: + continue + attributed = [ + r + for r in raw_results_by_hash[attack.technique_eval_hash] + if r.attribution_data and r.attribution_data.get("parent_collection") == attack.atomic_attack_name + ] + if any(r.outcome in (AttackOutcome.SUCCESS, AttackOutcome.FAILURE) for r in attributed): + cached_names.add(attack.atomic_attack_name) + self._cached_results_by_name[attack.atomic_attack_name] = attributed + + return cached_names diff --git a/pyrit/scenario/scenarios/garak/prompt_inject.py b/pyrit/scenario/scenarios/garak/prompt_inject.py index f62f979c43..ea8b2b10f3 100644 --- a/pyrit/scenario/scenarios/garak/prompt_inject.py +++ b/pyrit/scenario/scenarios/garak/prompt_inject.py @@ -13,6 +13,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, cast from pyrit.common import apply_defaults, forward_init_parameters +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.converter import SearchReplaceConverter from pyrit.executor.attack import AttackConverterConfig, AttackScoringConfig, PromptSendingAttack from pyrit.memory import CentralMemory @@ -261,7 +262,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]: @@ -374,6 +375,25 @@ def _load_technique_templates(self) -> dict[str, SeedPrompt]: raise DatasetConstraintError(f"PromptInject technique templates are missing: {sorted(missing)}.") return templates + @legacy_sync_override(lambda: PromptInject._load_technique_templates) + async def _load_technique_templates_async(self) -> dict[str, SeedPrompt]: + """ + Load the selected technique templates from memory. + + Returns: + dict[str, SeedPrompt]: Technique templates keyed by technique name. + + Raises: + DatasetConstraintError: If a selected technique has no template. + """ + 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() + if missing: + raise DatasetConstraintError(f"PromptInject technique templates are missing: {sorted(missing)}.") + return templates + @staticmethod def _build_goal_scorer(*, goal_texts: Sequence[str]) -> TrueFalseCompositeScorer: """ diff --git a/pyrit/scenario/scenarios/garak/system_prompt_extraction.py b/pyrit/scenario/scenarios/garak/system_prompt_extraction.py index 8d654dd93e..ee0c2f1850 100644 --- a/pyrit/scenario/scenarios/garak/system_prompt_extraction.py +++ b/pyrit/scenario/scenarios/garak/system_prompt_extraction.py @@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, ClassVar from pyrit.common import apply_defaults +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.executor.attack import AttackScoringConfig, PromptSendingAttack from pyrit.memory import CentralMemory from pyrit.models import AttackSeedGroup, SeedObjective, SeedPrompt @@ -165,6 +166,24 @@ def _load_system_prompts(self) -> list[str]: system_prompts.extend(values) return system_prompts + @legacy_sync_override(lambda: SystemPromptExtraction._load_system_prompts) + async def _load_system_prompts_async(self) -> list[str]: + """ + Load the real system prompts (the *what*) from the configured datasets in memory. + + Returns: + list[str]: The system-prompt strings, subsampled per dataset to ``system_prompt_subsample``. + """ + memory = CentralMemory.get_memory_instance() + 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 (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]]: """ Load the extraction templates (the *how*) from memory, grouped by ``technique`` metadata. @@ -181,6 +200,23 @@ def _load_templates_by_category(self) -> dict[str, list[str]]: templates_by_category.setdefault(str(category), []).append(seed.value) return templates_by_category + @legacy_sync_override(lambda: SystemPromptExtraction._load_templates_by_category) + async def _load_templates_by_category_async(self) -> dict[str, list[str]]: + """ + Load the extraction templates (the *how*) from memory, grouped by ``technique`` metadata. + + Returns: + dict[str, list[str]]: Mapping of technique category to its extraction request templates. + """ + memory = CentralMemory.get_memory_instance() + templates_by_category: dict[str, list[str]] = {} + for seed in await memory.get_seeds_async(dataset_name=DATASET_EXTRACTION_TEMPLATES): + category = (seed.metadata or {}).get("technique") + if not category: + continue + templates_by_category.setdefault(str(category), []).append(seed.value) + return templates_by_category + async def _resolve_seed_groups_by_dataset_async( self, *, apply_sampling: bool = True ) -> dict[str, list[AttackSeedGroup]]: @@ -205,8 +241,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..ba04b102cb 100644 --- a/pyrit/scenario/scenarios/garak/web_injection.py +++ b/pyrit/scenario/scenarios/garak/web_injection.py @@ -6,12 +6,12 @@ from __future__ import annotations -import asyncio import logging import random from typing import TYPE_CHECKING, ClassVar from pyrit.common import apply_defaults +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.executor.attack.core.attack_config import AttackScoringConfig from pyrit.executor.attack.single_turn.prompt_sending import PromptSendingAttack from pyrit.memory import CentralMemory @@ -287,6 +287,26 @@ def _load_dataset_values(self) -> dict[str, list[str]]: values[name] = [seed.value for seed in seeds] return values + @legacy_sync_override(lambda: WebInjection._load_dataset_values) + async def _load_dataset_values_async(self) -> dict[str, list[str]]: + """ + Load the raw seed values for each configured dataset, keyed by dataset name. + + Returns: + dict[str, list[str]]: Mapping of dataset name to the list of seed string values. + """ + memory = CentralMemory.get_memory_instance() + values: dict[str, list[str]] = {} + for name in ( + self.DATASET_EXAMPLE_DOMAINS, + self.DATASET_MARKDOWN_JS, + self.DATASET_WEB_HTML_JS, + self.DATASET_NORMAL_INSTRUCTIONS, + ): + seeds = await memory.get_seeds_async(dataset_name=name) + values[name] = [seed.value for seed in seeds] + return values + @staticmethod def _mutate_domain(domain: str, *, rng: random.Random) -> str: """ @@ -537,7 +557,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 +629,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/audio_transcript_scorer.py b/pyrit/score/audio_transcript_scorer.py index 94547ccc9f..4dbcfd03aa 100644 --- a/pyrit/score/audio_transcript_scorer.py +++ b/pyrit/score/audio_transcript_scorer.py @@ -185,7 +185,7 @@ async def _score_audio_async( # Add to memory so score references are valid memory = CentralMemory.get_memory_instance() - memory.add_message_to_memory(request=text_message) + (await memory.add_message_to_memory_async(request=text_message)) with _suppress_observation_collection(): transcript_scores = await self.text_scorer._score_nested_async( 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 1e7c1a55e7..5f36ad1da1 100644 --- a/pyrit/score/conversation_scorer.py +++ b/pyrit/score/conversation_scorer.py @@ -116,7 +116,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 f4e86b1bd6..3d035979bc 100644 --- a/pyrit/score/float_scale/system_prompt_extraction_scorer.py +++ b/pyrit/score/float_scale/system_prompt_extraction_scorer.py @@ -7,6 +7,7 @@ import re from pyrit.analytics.text_matching import ApproximateTextMatching +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.memory.central_memory import CentralMemory from pyrit.models import ComponentIdentifier, MessagePiece, Score from pyrit.score.float_scale.float_scale_scorer import MessageFloatScaleScorer @@ -105,6 +106,27 @@ def _get_system_prompt(self, conversation_id: str | None) -> str | None: return message.get_value() return None + @legacy_sync_override(lambda: SystemPromptExtractionScorer._get_system_prompt) + 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. + + Args: + conversation_id (str | None): The conversation the response belongs to. + + Returns: + str | None: The system prompt text, or None if the conversation has no system message. + """ + if not conversation_id: + return None + + memory = CentralMemory.get_memory_instance() + messages = await memory.get_conversation_messages_async(conversation_id=conversation_id) + for message in messages: + if message.api_role == "system": + return message.get_value() + return None + @staticmethod def _mildly_sanitize(text: str) -> str: """ @@ -153,7 +175,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 279d8a2968..0bd2428b33 100644 --- a/pyrit/score/message_scorer.py +++ b/pyrit/score/message_scorer.py @@ -10,6 +10,7 @@ from contextlib import nullcontext from typing import TYPE_CHECKING, cast +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.deprecation import print_deprecation_message from pyrit.exceptions import ( ComponentRole, @@ -103,6 +104,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 "" @@ -128,6 +134,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. @@ -416,7 +465,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 _observation_collection() as collector: with _scoring_scorable_context(context_scorable): @@ -429,7 +480,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, @@ -471,6 +522,29 @@ def _context_scorable_from_message(self, *, message: Message) -> Scorable | None return ContentScorable.from_message(message) return None + @legacy_sync_override(lambda: MessageScorer._context_scorable_from_message) + async def _context_scorable_from_message_async(self, *, message: Message) -> Scorable | None: + """ + Build a durable observation anchor for the in-hand message API. + + Returns: + Scorable | None: The durable message or content anchor, if one can be represented. + """ + pieces = message.message_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 + and _message_piece_digest(piece, include_id=False) + == _message_piece_digest(persisted_by_id[str(piece.id)], include_id=False) + for piece in pieces + ) + if pieces and matches_storage: + return MessageScorable.from_message(message) + if len(pieces) == 1: + return ContentScorable.from_message(message) + return None + async def score_message_async( self, *, @@ -558,7 +632,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) ] @@ -858,7 +932,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, @@ -904,7 +978,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: @@ -935,11 +1009,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 @@ -1002,11 +1075,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 @@ -1044,6 +1119,30 @@ def _finalize_message_scores( ) self._stamp_scored_expectation(scores=scores, expectation=expectation) + @legacy_sync_override(lambda: MessageScorer._finalize_message_scores) + async def _finalize_message_scores_async( + self, + *, + message: Message, + scores: list[Score], + anchor: Scorable | None, + expectation: ScoringExpectation | None, + ) -> None: + """Apply legacy and canonical evidence anchors to completed message scores.""" + persisted_piece_ids = await self._get_persisted_piece_ids_async(message=message) + self._drop_ephemeral_score_links( + message=message, + scores=scores, + persisted_piece_ids=persisted_piece_ids, + ) + self._stamp_scorable( + message=message, + scores=scores, + anchor=anchor, + persisted_piece_ids=persisted_piece_ids, + ) + self._stamp_scored_expectation(scores=scores, expectation=expectation) + async def _score_prepared_message_async( self, *, @@ -1350,6 +1449,28 @@ def _get_persisted_piece_ids(self, *, message: Message) -> set[uuid.UUID]: ) } + @legacy_sync_override(lambda: MessageScorer._get_persisted_piece_ids) + 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 = 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 { + piece.id + for piece in stored_pieces + if piece.id in supplied_by_id + and _message_piece_digest(piece, include_id=False) + == _message_piece_digest( + supplied_by_id[piece.id].model_copy(update={"timestamp": piece.timestamp}), + include_id=False, + ) + } + @staticmethod def _scorable_from_message( message: Message, diff --git a/pyrit/score/observation/execution.py b/pyrit/score/observation/execution.py index 344528a4fc..d6dc6060c0 100644 --- a/pyrit/score/observation/execution.py +++ b/pyrit/score/observation/execution.py @@ -7,6 +7,8 @@ from contextvars import ContextVar from typing import TYPE_CHECKING, TypeAlias +from pyrit.common.async_compatibility import legacy_sync_override +from pyrit.common.deprecation import print_deprecation_message from pyrit.models import ( ContentEntryScorable, ContentScorable, @@ -70,6 +72,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 +120,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 _ObservationCollector: """Observations created during one root scoring operation.""" @@ -280,6 +330,11 @@ def resolve(self, *, observation: Observation) -> _ObservationEvidence: Raises: NonReplayableObservationError: If referenced evidence is missing, modified, or unsupported. """ + print_deprecation_message( + old_item="_ObservationEvidenceResolver.resolve", + new_item="_ObservationEvidenceResolver.resolve_async", + removed_in="1.4.0", + ) payload = observation.payload if isinstance(payload, ToolEventsObservationPayload): return payload @@ -294,3 +349,31 @@ def resolve(self, *, observation: Observation) -> _ObservationEvidence: except ValueError as error: raise NonReplayableObservationError(str(error)) from error return Message(message_pieces=[pieces_by_id[piece_id] for piece_id in observation.response_message_piece_ids]) + + @legacy_sync_override(lambda: _ObservationEvidenceResolver.resolve) + async def resolve_async(self, *, observation: Observation) -> _ObservationEvidence: + """ + Resolve an observation's managed response references. + + Returns: + _ObservationEvidence: The reconstructed LLM response. + + Raises: + NonReplayableObservationError: If referenced evidence is missing, modified, or unsupported. + """ + payload = observation.payload + if isinstance(payload, ToolEventsObservationPayload): + return payload + 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 = await _load_content_evidence_async( + memory=self._memory, content_id=observation.scorable_content_id + ) + try: + observation.validate_evidence( + message_pieces=pieces_by_id, + stored_content=stored_content, + ) + except ValueError as error: + raise NonReplayableObservationError(str(error)) from error + return Message(message_pieces=[pieces_by_id[piece_id] for piece_id in observation.response_message_piece_ids]) diff --git a/pyrit/score/scorer.py b/pyrit/score/scorer.py index b58096f69b..d5a4e5ac1c 100644 --- a/pyrit/score/scorer.py +++ b/pyrit/score/scorer.py @@ -9,6 +9,7 @@ from abc import abstractmethod from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, cast, final, overload +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.deprecation import print_deprecation_message from pyrit.exceptions import PyritException, execution_context, get_execution_context from pyrit.memory import CentralMemory, MemoryInterface @@ -85,7 +86,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( @@ -705,12 +706,14 @@ async def _validate_and_persist_scores_async( await self._memory.add_scores_to_memory_async(scores=scores) else: if observations: - self._memory.add_scores_to_memory( - scores=scores, - observations=observations, + ( + await self._memory.add_scores_to_memory_async( + scores=scores, + observations=observations, + ) ) else: - self._memory.add_scores_to_memory(scores=scores) + (await self._memory.add_scores_to_memory_async(scores=scores)) return scores async def _score_nested_async( @@ -765,7 +768,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] @@ -773,7 +776,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, @@ -1241,3 +1244,25 @@ def _extract_objective_from_response(self, response: Message) -> str: removed_in=LEGACY_SCORE_ASYNC_REMOVED_IN, ) return extract_objective_from_previous_turn(message=response, memory=self._memory) + + @legacy_sync_override(lambda: Scorer._extract_objective_from_response) + async def _extract_objective_from_response_async(self, response: Message) -> str: + """ + Read the objective from the turn before an assistant response. + + Deprecated: use ``pyrit.score.message_scorer.extract_objective_from_previous_turn``. + + Args: + response (Message): The response to extract the objective from. + + 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_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 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 bf25e77ffd..7c9c2d66ab 100644 --- a/pyrit/score/scorer_evaluation/scorer_evaluator.py +++ b/pyrit/score/scorer_evaluation/scorer_evaluator.py @@ -4,6 +4,7 @@ from __future__ import annotations import abc +import asyncio import logging import time from dataclasses import dataclass @@ -12,11 +13,12 @@ import numpy as np from scipy.stats import ttest_1samp +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.common.path import SCORER_EVALS_PATH 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, @@ -375,11 +377,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 ] @@ -562,6 +566,26 @@ def _validate_and_extract_data( ValueError: If the dataset is invalid for this evaluator. """ + @legacy_sync_override(lambda: ScorerEvaluator._validate_and_extract_data) + async def _validate_and_extract_data_async( + self, + labeled_dataset: HumanLabeledDataset, + ) -> tuple[list[Message], list[list[float]], list[str] | None]: + """ + Validate the dataset and extract data for evaluation. + + Args: + labeled_dataset: The dataset to validate and extract from. + + Returns: + Tuple of (assistant_responses, human_scores_list, objectives). + objectives may be None for harm scoring. + + Raises: + ValueError: If the dataset is invalid for this evaluator. + """ + return await asyncio.to_thread(self._validate_and_extract_data, labeled_dataset) + @abc.abstractmethod def _compute_metrics( self, @@ -670,6 +694,50 @@ def _validate_and_extract_data( return assistant_responses, human_scores_list, None + @legacy_sync_override(lambda: HarmScorerEvaluator._validate_and_extract_data) + async def _validate_and_extract_data_async( + self, + labeled_dataset: HumanLabeledDataset, + ) -> tuple[list[Message], list[list[float]], list[str] | None]: + """ + Validate harm dataset and extract evaluation data. + + Args: + labeled_dataset: The dataset to validate and extract from. + + Returns: + Tuple of (assistant_responses, human_scores_list, None). + objectives is None for harm scoring; the caller reads each objective from the + previous turn instead. + + Raises: + ValueError: If dataset is not HARM type or has multiple harm categories. + """ + if labeled_dataset.metrics_type != MetricsType.HARM: + raise ValueError("The HumanLabeledDataset must be of type HARM to evaluate a harm scorer.") + + labeled_dataset.validate() + + assistant_responses: list[Message] = [] + human_scores_list: list[list[float]] = [] + + for entry in labeled_dataset.entries: + harm_entry = cast("HarmHumanLabeledEntry", entry) + assistant_messages: list[Message] = [] + for message in harm_entry.conversation: + (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: + raise ValueError( + "Each HarmHumanLabeledEntry must contain exactly one assistant message, " + f"but found {len(assistant_messages)}." + ) + assistant_responses.append(assistant_messages[0]) + human_scores_list.append(harm_entry.human_scores) + + return assistant_responses, human_scores_list, None + def _compute_metrics( self, *, @@ -790,6 +858,42 @@ def _validate_and_extract_data( return assistant_responses, human_scores_list, objectives + @legacy_sync_override(lambda: ObjectiveScorerEvaluator._validate_and_extract_data) + async def _validate_and_extract_data_async( + self, + labeled_dataset: HumanLabeledDataset, + ) -> tuple[list[Message], list[list[float]], list[str] | None]: + """ + Validate objective dataset and extract evaluation data. + + Args: + labeled_dataset: The dataset to validate and extract from. + + Returns: + Tuple of (assistant_responses, human_scores_list, objectives). + + Raises: + ValueError: If dataset is not OBJECTIVE type or contains invalid entries. + """ + if labeled_dataset.metrics_type != MetricsType.OBJECTIVE: + raise ValueError("The HumanLabeledDataset must be of type OBJECTIVE to evaluate an objective scorer.") + + labeled_dataset.validate() + + assistant_responses: list[Message] = [] + human_scores_list: list[list[float]] = [] + objectives: list[str] = [] + + for entry in labeled_dataset.entries: + objective_entry = cast("ObjectiveHumanLabeledEntry", entry) + for message in objective_entry.conversation: + (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) + + return assistant_responses, human_scores_list, objectives + def _compute_metrics( self, *, diff --git a/pyrit/score/true_false/decoding_scorer.py b/pyrit/score/true_false/decoding_scorer.py index 6e285c612f..761a5a3a7b 100644 --- a/pyrit/score/true_false/decoding_scorer.py +++ b/pyrit/score/true_false/decoding_scorer.py @@ -78,7 +78,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 9db084b692..735a279d62 100644 --- a/pyrit/score/true_false/gandalf_scorer.py +++ b/pyrit/score/true_false/gandalf_scorer.py @@ -99,12 +99,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/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 4fbf4d0914..10d295fc07 100644 --- a/pyrit/score/video_scorer.py +++ b/pyrit/score/video_scorer.py @@ -193,7 +193,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( @@ -307,7 +307,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 22bbfbb847..a2aae7ae35 100644 --- a/pyrit/setup/initialization.py +++ b/pyrit/setup/initialization.py @@ -150,52 +150,63 @@ async def initialize_pyrit_async( 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] + memory = SQLiteMemory(silent=silent, _defer_initialization=True, **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 = AzureSQLMemory(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)}" ) + previous_memory = CentralMemory._memory_instance + 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 = registry.create_from_script_paths(script_paths=[script_path]) + 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 memory is not previous_memory: try: - script_initializers = registry.create_from_script_paths(script_paths=[script_path]) - 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 diff --git a/pyrit/setup/initializers/refresh_datasets.py b/pyrit/setup/initializers/refresh_datasets.py index 8434ca3ba0..9cf317a277 100644 --- a/pyrit/setup/initializers/refresh_datasets.py +++ b/pyrit/setup/initializers/refresh_datasets.py @@ -14,6 +14,7 @@ import textwrap from datetime import UTC, datetime, timedelta +from pyrit.common.async_compatibility import legacy_sync_override from pyrit.datasets import SeedDatasetProvider from pyrit.memory import CentralMemory, MemoryInterface from pyrit.models import SeedDataset @@ -86,7 +87,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 +101,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: @@ -171,6 +172,30 @@ def _is_stale(self, *, memory: MemoryInterface, dataset_name: str, days: int) -> cutoff = datetime.now(tz=UTC) - timedelta(days=days) return newest <= cutoff + @legacy_sync_override(lambda: RefreshDatasets._is_stale) + async def _is_stale_async(self, *, memory: MemoryInterface, dataset_name: str, days: int) -> bool: + """ + Determine whether a dataset is stale enough to refresh. + + Args: + memory (MemoryInterface): The memory instance to read existing seeds from. + dataset_name (str): The dataset to evaluate. + days (int): The staleness threshold in days; 0 always refreshes. + + Returns: + bool: True if the dataset should be refreshed, otherwise False. + """ + if days == 0: + return True + + 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 + + cutoff = datetime.now(tz=UTC) - timedelta(days=days) + return newest <= cutoff + async def _refresh_dataset_async(self, *, memory: MemoryInterface, dataset_name: str) -> None: """ Re-fetch a single dataset and atomically replace its stored seeds. 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 784ae16158..39f8e9ee31 100644 --- a/tests/integration/targets/test_openai_responses_gpt5.py +++ b/tests/integration/targets/test_openai_responses_gpt5.py @@ -47,7 +47,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", @@ -79,7 +79,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", @@ -132,7 +132,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/unit/analytics/test_conversation_analytics.py b/tests/unit/analytics/test_conversation_analytics.py index 15efcec1cf..6f29c0cec3 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 ) diff --git a/tests/unit/analytics/test_result_analysis.py b/tests/unit/analytics/test_result_analysis.py index fd483d3456..980d6dc98b 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 ( @@ -212,15 +212,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, @@ -229,19 +229,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, @@ -251,11 +253,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", @@ -264,7 +266,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) @@ -273,9 +275,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, @@ -284,18 +286,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 @@ -303,28 +307,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 @@ -337,9 +343,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/test_api_routes.py b/tests/unit/backend/test_api_routes.py index 9baf0031e3..c26afc156f 100644 --- a/tests/unit/backend/test_api_routes.py +++ b/tests/unit/backend/test_api_routes.py @@ -43,6 +43,7 @@ from pyrit.backend.routes import version as version_routes from pyrit.backend.routes.scores import _get_user_identifier from pyrit.backend.services.attack_service import AttackObjectiveConflictError +from pyrit.memory import MemoryInterface from pyrit.models import AttackOutcome, ConverterIdentifier, MessagePiece, Score, TargetCapabilities, TargetIdentifier from pyrit.models.catalog.target import TargetInstance @@ -1620,18 +1621,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]) @@ -1656,8 +1659,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.""" @@ -1675,15 +1678,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]) @@ -1707,7 +1714,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 @@ -1727,14 +1734,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( @@ -1748,7 +1759,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.""" @@ -1766,15 +1777,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( @@ -1789,7 +1804,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: @@ -1800,7 +1815,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", @@ -1893,9 +1908,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", @@ -1921,16 +1942,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", @@ -1975,9 +1998,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") @@ -1988,7 +2013,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, @@ -1996,12 +2021,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( @@ -2014,19 +2041,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") @@ -2039,12 +2068,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") @@ -2057,12 +2090,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") @@ -2082,12 +2117,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 b1378955f0..66920af182 100644 --- a/tests/unit/backend/test_attack_service.py +++ b/tests/unit/backend/test_attack_service.py @@ -47,7 +47,7 @@ ) from pyrit.common.utils import to_sha256 from pyrit.converter import Converter, ConverterResult -from pyrit.memory import SQLiteMemory +from pyrit.memory import MemoryInterface, SQLiteMemory from pyrit.memory.memory_models import ConversationEntry from pyrit.models import ( AtomicAttackIdentifier, @@ -68,19 +68,19 @@ ) from pyrit.models.conversation_stats import ConversationStats from pyrit.prompt_normalizer import ConverterConfiguration, PromptNormalizer -from unit.mocks import MockPromptTarget +from unit.mocks import MockPromptTarget, get_mock_prompt_normalizer @pytest.fixture def mock_memory(): """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 = AsyncMock(return_value=[]) + memory.get_conversation_messages_async = AsyncMock(return_value=[]) + memory.get_message_pieces_async = AsyncMock(return_value=[]) + memory.get_conversation_stats_async = AsyncMock(return_value={}) + memory.get_conversation_metadata_async = AsyncMock(return_value=None) + memory.get_prompt_scores_async = AsyncMock(return_value=[]) return memory @@ -196,8 +196,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 = AsyncMock(return_value=[attack_result]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) converter_objects: list[MagicMock] = [] for identifier in converter_identifiers: @@ -243,8 +243,8 @@ async def _send_message_and_get_update_fields( mock_normalizer_class.return_value.send_prompt_async = AsyncMock() await attack_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.call_args.kwargs["update_fields"] + return mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] + return mock_memory.update_attack_result_by_id_async.call_args.kwargs["update_fields"] def _keyset_side_effect(backing): @@ -392,7 +392,7 @@ class TestAttackServiceInit: def test_init_gets_memory_instance(self) -> None: """Test that init gets the memory instance.""" with patch("pyrit.backend.services.attack_service.CentralMemory") as mock_central: - mock_memory = MagicMock() + mock_memory = MagicMock(spec=MemoryInterface) mock_central.get_memory_instance.return_value = mock_memory service = AttackService() @@ -412,7 +412,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 = AsyncMock(return_value=[]) result = await attack_service.list_attacks_async() @@ -422,8 +422,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) result = await attack_service.list_attacks_async() @@ -434,45 +434,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 = AsyncMock(return_value=[ar1]) + mock_memory.get_message_pieces_async = AsyncMock(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 = AsyncMock(return_value=[]) + mock_memory.get_message_pieces_async = AsyncMock(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 = AsyncMock(return_value=[]) + mock_memory.get_message_pieces_async = AsyncMock(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 = AsyncMock(return_value=[]) + mock_memory.get_message_pieces_async = AsyncMock(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: @@ -481,42 +481,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 = AsyncMock(return_value=[]) + mock_memory.get_message_pieces_async = AsyncMock(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 = AsyncMock(return_value=[]) + mock_memory.get_message_pieces_async = AsyncMock(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 = AsyncMock(return_value=[]) + mock_memory.get_message_pieces_async = AsyncMock(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 = AsyncMock(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.""" @@ -547,15 +547,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 = AsyncMock(return_value=[ar1]) + mock_memory.get_message_pieces_async = AsyncMock(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" @@ -563,15 +563,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 = AsyncMock(return_value=[]) + mock_memory.get_message_pieces_async = AsyncMock(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" @@ -583,15 +583,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 = AsyncMock(return_value=[]) + mock_memory.get_message_pieces_async = AsyncMock(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" @@ -602,34 +602,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 = AsyncMock(return_value=[]) + mock_memory.get_message_pieces_async = AsyncMock(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 = AsyncMock(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 = AsyncMock(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: @@ -637,14 +637,16 @@ 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 = { - "attack-1": ConversationStats( - message_count=1, - last_message_preview="test", - labels={"env": "prod", "team": "red"}, - ), - } + mock_memory.get_attack_results_async = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_stats_async = AsyncMock( + return_value={ + "attack-1": ConversationStats( + message_count=1, + last_message_preview="test", + labels={"env": "prod", "team": "red"}, + ), + } + ) result = await attack_service.list_attacks_async() @@ -654,15 +656,17 @@ 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 = AsyncMock(return_value=[ar]) path = r"C:\Users\someone\PyRIT\dbdata\prompt-memory-entries\images\1780010098266691.png" - mock_memory.get_conversation_stats.return_value = { - "attack-1": ConversationStats( - message_count=1, - last_message_preview=path, - last_message_data_type="image_path", - ), - } + mock_memory.get_conversation_stats_async = AsyncMock( + return_value={ + "attack-1": ConversationStats( + message_count=1, + last_message_preview=path, + last_message_data_type="image_path", + ), + } + ) result = await attack_service.list_attacks_async() @@ -677,26 +681,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: { - cid: ConversationStats(message_count=1) for cid in conversation_ids - } + mock_memory.get_attack_results_async = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_stats_async = AsyncMock( + 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 = AsyncMock(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 @@ -712,21 +716,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 = AsyncMock(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 = AsyncMock(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() # ============================================================================ @@ -740,21 +744,23 @@ 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 = AsyncMock(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 = AsyncMock( + 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() # ============================================================================ @@ -768,7 +774,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 = AsyncMock(return_value=[]) result = await attack_service.get_attack_async(attack_result_id="nonexistent") @@ -780,8 +786,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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) result = await attack_service.get_attack_async(attack_result_id="test-id") @@ -801,7 +807,7 @@ class TestGetConversationMessages: 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 = [] + mock_memory.get_attack_results_async = AsyncMock(return_value=[]) result = await attack_service.get_conversation_messages_async( attack_result_id="nonexistent", conversation_id="any-id" @@ -812,8 +818,8 @@ async def test_get_conversation_messages_returns_none_for_nonexistent(self, atta async def test_get_conversation_messages_returns_messages(self, attack_service, mock_memory) -> None: """Test that get_conversation_messages 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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) result = await attack_service.get_conversation_messages_async( attack_result_id="test-id", conversation_id="test-id" @@ -833,11 +839,13 @@ 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 = [ - _make_message(role="user", sequence=2), - _make_message(role="assistant", sequence=3, response_error=response_error), - ] + mock_memory.get_attack_results_async = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock( + return_value=[ + _make_message(role="user", sequence=2), + _make_message(role="assistant", sequence=3, response_error=response_error), + ] + ) result = await attack_service.get_conversation_messages_async( attack_result_id="test-id", conversation_id="test-id" @@ -852,13 +860,15 @@ 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 = [ - _make_message(role="user", sequence=0), - _make_message(role="assistant", sequence=1, response_error="processing"), - _make_message(role="user", sequence=2), - _make_message(role="assistant", sequence=3), - ] + mock_memory.get_attack_results_async = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock( + return_value=[ + _make_message(role="user", sequence=0), + _make_message(role="assistant", sequence=1, response_error="processing"), + _make_message(role="user", sequence=2), + _make_message(role="assistant", sequence=3), + ] + ) result = await attack_service.get_conversation_messages_async( attack_result_id="test-id", conversation_id="test-id" @@ -879,11 +889,13 @@ 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 = [ - _make_message(role="user", sequence=0), - _make_message(role=latest_role, sequence=1, response_error="processing"), - ] + mock_memory.get_attack_results_async = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock( + return_value=[ + _make_message(role="user", sequence=0), + _make_message(role=latest_role, sequence=1, response_error="processing"), + ] + ) result = await attack_service.get_conversation_messages_async( attack_result_id="test-id", conversation_id="test-id" @@ -897,8 +909,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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) with patch( "pyrit.backend.services.attack_service.pyrit_messages_to_dto_async", @@ -918,8 +930,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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) with patch( "pyrit.backend.services.attack_service.pyrit_messages_to_dto_async", @@ -937,7 +949,7 @@ async def test_get_conversation_messages_raises_for_unrelated_conversation( ) -> None: """Test that get_conversation_messages 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 = AsyncMock(return_value=[ar]) with pytest.raises(ValueError, match="not part of attack"): await attack_service.get_conversation_messages_async( @@ -990,8 +1002,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" @@ -1022,8 +1034,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.""" @@ -1041,7 +1053,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" @@ -1064,7 +1076,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 @@ -1092,7 +1104,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] @@ -1119,7 +1131,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 @@ -1142,7 +1154,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( @@ -1192,7 +1204,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] @@ -1231,7 +1243,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: @@ -1248,7 +1260,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" @@ -1270,7 +1282,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 @@ -1286,7 +1298,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 = AsyncMock(return_value=[]) result = await attack_service.update_attack_async( attack_result_id="nonexistent", request=UpdateAttackRequest(outcome="success") @@ -1297,76 +1309,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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(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 = AsyncMock(return_value=[ar]) with pytest.raises(AttackObjectiveConflictError, match="already has an objective"): await attack_service.update_attack_async( @@ -1374,14 +1386,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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) result = await attack_service.update_attack_async( attack_result_id="test-id", @@ -1390,20 +1402,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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_messages_async = AsyncMock(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 @@ -1426,11 +1438,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 = AsyncMock(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" @@ -1442,11 +1454,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 = AsyncMock(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 @@ -1463,7 +1475,7 @@ class TestAddMessage: async def test_add_message_raises_for_nonexistent_attack(self, attack_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 = AsyncMock(return_value=[]) request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], @@ -1476,7 +1488,7 @@ async def test_add_message_raises_for_nonexistent_attack(self, attack_service, m async def test_add_message_raises_when_send_without_registry_name(self, attack_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 = AsyncMock(return_value=[ar]) request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], @@ -1490,9 +1502,9 @@ async def test_add_message_raises_when_send_without_registry_name(self, attack_s async def test_add_message_send_false_without_registry_name_succeeds(self, attack_service, mock_memory) -> None: """Test that add_message with send=False does not require target_registry_name.""" 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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) request = AddMessageRequest( role="system", @@ -1516,9 +1528,9 @@ async def test_add_message_with_send_sends_via_normalizer(self, attack_service, 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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(side_effect=[[], [response_piece]]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) with ( patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_svc, @@ -1528,7 +1540,7 @@ async def test_add_message_with_send_sends_via_normalizer(self, attack_service, mock_target_svc.get_target_object.return_value = _make_matching_target_mock() mock_get_target_svc.return_value = mock_target_svc - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_cls.return_value = mock_normalizer @@ -1543,14 +1555,14 @@ async def test_add_message_with_send_sends_via_normalizer(self, attack_service, mock_normalizer.send_prompt_async.assert_called_once() assert result.attack is not None - 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, attack_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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) with patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_svc: mock_target_svc = MagicMock() @@ -1570,7 +1582,7 @@ async def test_add_message_with_send_raises_when_target_not_found(self, attack_s 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 = AsyncMock(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. @@ -1595,11 +1607,15 @@ 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 = AsyncMock(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 **_: ( - [Message(message_pieces=[request_piece]), Message(message_pieces=[error_piece])] if state["sent"] else [] + mock_memory.get_conversation_messages_async = AsyncMock( + side_effect=lambda **_: ( + [Message(message_pieces=[request_piece]), Message(message_pieces=[error_piece])] + if state["sent"] + else [] + ) ) async def _raise_after_store(**_): @@ -1614,7 +1630,7 @@ async def _raise_after_store(**_): mock_target_svc.get_target_object.return_value = _make_matching_target_mock() mock_get_target_svc.return_value = mock_target_svc - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(side_effect=_raise_after_store) mock_normalizer_cls.return_value = mock_normalizer @@ -1647,9 +1663,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) # no error piece ever stored + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) with ( patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_svc, @@ -1659,7 +1675,7 @@ async def test_add_message_reraises_when_send_fails_without_stored_error_piece( mock_target_svc.get_target_object.return_value = _make_matching_target_mock() mock_get_target_svc.return_value = mock_target_svc - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock(side_effect=RuntimeError("boom")) mock_normalizer_cls.return_value = mock_normalizer @@ -1678,9 +1694,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) with ( patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_svc, @@ -1707,7 +1723,7 @@ async def test_add_message_with_legacy_converter_ids_warns_and_preserves_behavio mock_conv_svc.get_converter_objects_for_ids.return_value = [first_converter, second_converter] mock_get_conv_svc.return_value = mock_conv_svc - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_cls.return_value = mock_normalizer @@ -1766,9 +1782,9 @@ def test_empty_legacy_converter_ids_warn_and_use_structured_configuration(self, async def test_add_message_preserves_converter_configuration_targeting(self, attack_service, mock_memory) -> 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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) with ( patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_svc, @@ -1814,7 +1830,7 @@ async def test_add_message_preserves_converter_configuration_targeting(self, att ] mock_get_conv_svc.return_value = mock_conv_svc - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_cls.return_value = mock_normalizer @@ -1865,7 +1881,7 @@ async def test_add_message_preserves_converter_configuration_targeting(self, att 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] == [ @@ -1879,7 +1895,7 @@ async def test_add_message_preserves_converter_configuration_targeting(self, att async def test_add_message_resolves_converters_before_writing(self, attack_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 = AsyncMock(return_value=[ar]) request = AddMessageRequest( pieces=[MessagePieceRequest(original_value="Hello")], target_conversation_id="test-id", @@ -1896,16 +1912,16 @@ async def test_add_message_resolves_converters_before_writing(self, attack_servi with pytest.raises(ValueError, match="Converter instance 'missing' not found"): await attack_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() 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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) request = AddMessageRequest( role="system", @@ -1921,9 +1937,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) request = AddMessageRequest( role="system", @@ -1943,9 +1959,9 @@ async def test_add_message_bumps_timestamp(self, attack_service, mock_memory) -> """Should bump the timestamp recency column via update_attack_result (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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) request = AddMessageRequest( role="user", @@ -1956,8 +1972,8 @@ async def test_add_message_bumps_timestamp(self, attack_service, mock_memory) -> await attack_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) @@ -1968,9 +1984,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) mock_converter = MagicMock() mock_converter.get_identifier.return_value = ComponentIdentifier( @@ -1992,7 +2008,7 @@ async def test_preconverted_piece_does_not_disable_other_piece_converters( mock_conv_svc.get_converter_objects_for_ids.return_value = [mock_converter] mock_get_conv_svc.return_value = mock_conv_svc - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_cls.return_value = mock_normalizer @@ -2022,7 +2038,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, attack_service) -> None: @@ -2064,18 +2080,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 = AsyncMock(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 = AsyncMock(side_effect=_keyset_side_effect(backing)) first = await attack_service.list_attacks_async(limit=2) assert first.pagination.next_cursor is not None @@ -2085,28 +2101,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 = AsyncMock(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 = AsyncMock(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( @@ -2120,11 +2136,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 = AsyncMock(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.""" @@ -2186,7 +2202,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 = AsyncMock(side_effect=_keyset_side_effect(backing)) result = await attack_service.list_attacks_async(limit=2) @@ -2197,7 +2213,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 = AsyncMock(side_effect=_keyset_side_effect(backing)) result = await attack_service.list_attacks_async(limit=2, cursor=_cursor_for(backing[1])) @@ -2208,7 +2224,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 = AsyncMock(side_effect=_keyset_side_effect(backing)) result = await attack_service.list_attacks_async(limit=2, cursor=_cursor_for(backing[3])) @@ -2218,7 +2234,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 = AsyncMock(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) @@ -2236,7 +2252,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 = AsyncMock(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) @@ -2246,7 +2262,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( @@ -2254,7 +2270,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 = AsyncMock(side_effect=_keyset_side_effect(backing)) first = await attack_service.list_attacks_async(limit=2, outcome="success") next_cursor = first.pagination.next_cursor @@ -2262,7 +2278,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: @@ -2284,14 +2302,14 @@ def test_attack_filter_fingerprint_is_order_independent_and_filter_sensitive(sel 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.""" backing = _paginated_backing(5) - mock_memory.get_attack_results.side_effect = _keyset_side_effect(backing) + mock_memory.get_attack_results_async = AsyncMock(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() # ============================================================================ @@ -2306,7 +2324,7 @@ class TestMessageBuilding: 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.""" ar = make_attack_result(conversation_id="test-id") - mock_memory.get_attack_results.return_value = [ar] + mock_memory.get_attack_results_async = AsyncMock(return_value=[ar]) piece = MessagePiece( role="user", @@ -2319,7 +2337,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 = AsyncMock(return_value=[msg]) result = await attack_service.get_conversation_messages_async( attack_result_id="test-id", conversation_id="test-id" @@ -2859,7 +2877,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 = AsyncMock(return_value=[]) result = await attack_service.get_conversations_async(attack_result_id="missing") @@ -2868,10 +2886,12 @@ 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 = { - "attack-1": ConversationStats(message_count=2, last_message_preview="test"), - } + mock_memory.get_attack_results_async = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_stats_async = AsyncMock( + return_value={ + "attack-1": ConversationStats(message_count=2, last_message_preview="test"), + } + ) result = await attack_service.get_conversations_async(attack_result_id="attack-1") @@ -2883,15 +2903,17 @@ 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 = AsyncMock(return_value=[ar]) path = r"C:\Users\someone\PyRIT\dbdata\prompt-memory-entries\audio\1780010098266691.mp3" - mock_memory.get_conversation_stats.return_value = { - "attack-1": ConversationStats( - message_count=1, - last_message_preview=path, - last_message_data_type="audio_path", - ), - } + mock_memory.get_conversation_stats_async = AsyncMock( + return_value={ + "attack-1": ConversationStats( + message_count=1, + last_message_preview=path, + last_message_data_type="audio_path", + ), + } + ) result = await attack_service.get_conversations_async(attack_result_id="attack-1") @@ -2927,17 +2949,19 @@ 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 = AsyncMock(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 = { - "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), - "preparation-1": ConversationStats(message_count=2), - } + mock_memory.get_conversation_stats_async = AsyncMock( + 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), + "preparation-1": ConversationStats(message_count=2), + } + ) result = await attack_service.get_conversations_async(attack_result_id="attack-1") @@ -2978,10 +3002,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, @@ -2996,7 +3018,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( @@ -3014,13 +3036,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 @@ -3036,7 +3058,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 @@ -3045,16 +3067,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 = AsyncMock(return_value=[]) result = await attack_service.create_related_conversation_async( attack_result_id="missing", @@ -3068,8 +3088,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) request = CreateConversationRequest() @@ -3082,8 +3102,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 @@ -3093,29 +3113,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 = AsyncMock(return_value=[make_attack_result()]) + mock_memory.add_conversation_branches_to_attack_async = AsyncMock(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 = AsyncMock(return_value=[ar]) request = CreateConversationRequest(source_conversation_id="unrelated-conv", cutoff_index=0) @@ -3125,7 +3145,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( @@ -3135,7 +3155,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 = AsyncMock(return_value=[ar]) with pytest.raises(ValueError, match="not part of attack"): await attack_service.create_related_conversation_async( @@ -3143,17 +3163,19 @@ 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 = AsyncMock(return_value=[make_attack_result()]) + mock_memory.get_conversation_messages_async = AsyncMock(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 = AsyncMock(return_value=("branch", [copied])) + mock_memory.add_conversation_branches_to_attack_async = AsyncMock( + side_effect=RuntimeError("branch insertion failed") + ) with pytest.raises(RuntimeError, match="branch insertion failed"): await attack_service.create_related_conversation_async( @@ -3161,10 +3183,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() # ============================================================================ @@ -3178,7 +3200,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 = AsyncMock(return_value=[]) result = await attack_service.update_main_conversation_async( attack_result_id="missing", @@ -3190,7 +3212,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 = AsyncMock(return_value=[ar]) result = await attack_service.update_main_conversation_async( attack_result_id="ar-attack-1", @@ -3199,15 +3221,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 = AsyncMock(return_value=[ar]) with pytest.raises(ValueError, match="not part of this attack"): await attack_service.update_main_conversation_async( @@ -3215,7 +3237,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.""" @@ -3229,7 +3251,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 = AsyncMock(return_value=[ar]) result = await attack_service.update_main_conversation_async( attack_result_id="ar-attack-1", @@ -3240,17 +3262,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 = AsyncMock(return_value=[make_attack_result()]) + mock_memory.promote_attack_conversation_async = AsyncMock(return_value=False) result = await attack_service.update_main_conversation_async( attack_result_id="ar-attack-1", @@ -3258,7 +3280,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): @@ -3272,7 +3294,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 = AsyncMock(return_value=[ar]) with pytest.raises(ValueError, match="not part of this attack"): await attack_service.update_main_conversation_async( @@ -3280,8 +3302,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") @@ -3297,9 +3319,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) request = AddMessageRequest( role="user", @@ -3338,8 +3360,8 @@ async def test_stores_message_in_target_conversation(self, attack_service, mock_ async def test_rejects_unrelated_conversation_id(self, attack_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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) request = AddMessageRequest( role="user", @@ -3371,8 +3393,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) result = await attack_service.list_attacks_async() @@ -3382,8 +3404,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) result = await attack_service.list_attacks_async() @@ -3394,15 +3416,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(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 @@ -3419,19 +3441,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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(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") @@ -3449,15 +3471,17 @@ 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 = AsyncMock(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 = { - "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), - } + mock_memory.get_conversation_stats_async = AsyncMock( + 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), + } + ) result = await attack_service.get_conversations_async(attack_result_id="attack-1") @@ -3477,13 +3501,15 @@ 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 = AsyncMock(return_value=[ar]) t = datetime(2026, 1, 1, 9, 0, 0, tzinfo=UTC) - mock_memory.get_conversation_stats.return_value = { - "attack-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t), - } + mock_memory.get_conversation_stats_async = AsyncMock( + return_value={ + "attack-1": ConversationStats(message_count=1, last_message_preview="test", created_at=t), + } + ) result = await attack_service.get_conversations_async(attack_result_id="attack-1") @@ -3503,8 +3529,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 = AsyncMock(return_value=[ar]) + mock_memory.get_conversation_stats_async = AsyncMock(return_value={}) # Both have no stats result = await attack_service.get_conversations_async(attack_result_id="attack-1") @@ -3535,7 +3561,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 = AsyncMock(return_value=[ar]) expected_target = ( ComponentIdentifier( class_name="SourceTarget" if has_metadata else "TextTarget", class_module="pyrit.prompt_target" @@ -3544,11 +3570,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), @@ -3562,15 +3590,15 @@ 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() async def test_add_message_merges_converter_identifiers_without_duplicates(self, attack_service, mock_memory): """Should merge new converter identifiers with existing attack identifiers by hash.""" @@ -3764,7 +3792,7 @@ async def test_converter_merge_preserves_sibling_children_hash(self, attack_serv assert merged_converter_classes == ["NewConverter"] @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, @@ -3772,67 +3800,77 @@ def test_prepare_conversation_up_to_does_not_persist( cutoff_index: int, expected_sequences: list[int], ) -> None: - mock_memory.get_conversation_messages.return_value = [ - _make_message(role="user", sequence=sequence) for sequence in [0, 2, 4] - ] + mock_memory.get_conversation_messages_async = AsyncMock( + 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 = AsyncMock(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 = AsyncMock(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 = AsyncMock(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): + 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 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", []) + mock_memory.get_conversation_messages_async = AsyncMock( + return_value=[make_mock_piece(conversation_id="attack-1", sequence=0)] + ) + mock_memory.duplicate_messages_async = AsyncMock(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() - def test_duplicate_conversation_remaps_assistant_to_simulated(self, attack_service, mock_memory): + async def test_duplicate_conversation_remaps_assistant_to_simulated(self, attack_service, mock_memory): """Should remap assistant pieces to simulated_assistant when flag is set.""" 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 = AsyncMock(return_value=[source]) dup_piece = make_mock_piece(conversation_id="branch-1", role="assistant", sequence=0) - mock_memory.duplicate_messages.return_value = ("branch-1", [dup_piece]) + mock_memory.duplicate_messages_async = AsyncMock(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 == "simulated_assistant" @@ -3841,8 +3879,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() @pytest.mark.usefixtures("patch_central_database") @@ -3853,7 +3891,7 @@ class TestExactPreviewSend: async def test_type_changing_execution_provenance_is_preserved_async( self, *, attack_service: AttackService, 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 = AsyncMock(return_value=[make_attack_result(conversation_id="test-id")]) converters = {} for name, input_type, output_type, output in [ ("ToImage", "text", "image_path", "preview.png"), @@ -3923,13 +3961,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", @@ -3939,7 +3977,7 @@ async def test_type_changing_execution_provenance_is_preserved_async( async def test_unknown_applied_converter_rejected_before_sending_async( self, *, attack_service: AttackService, mock_memory: MagicMock ) -> None: - mock_memory.get_attack_results.return_value = [make_attack_result(conversation_id="test-id")] + mock_memory.get_attack_results_async = AsyncMock(return_value=[make_attack_result(conversation_id="test-id")]) request = AddMessageRequest( pieces=[ MessagePieceRequest( @@ -3959,8 +3997,8 @@ async def test_unknown_applied_converter_rejected_before_sending_async( with pytest.raises(ValueError, match="unknown"): await attack_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]) @@ -4020,7 +4058,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 @@ -4076,7 +4114,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 = AsyncMock(return_value=[make_attack_result(conversation_id="test-id")]) preview_converter = MagicMock(spec=Converter) preview_converter.get_identifier.return_value = ComponentIdentifier( class_name="PreviewConverter", @@ -4154,8 +4192,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", @@ -4195,8 +4233,8 @@ class TestAddMessageGuards: async def test_rejects_mismatched_target(self, attack_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 = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) # Create a mock target with a different class_name wrong_target = MagicMock() @@ -4223,9 +4261,9 @@ async def test_rejects_mismatched_target(self, attack_service, mock_memory) -> N async def test_allows_matching_target(self, attack_service, mock_memory) -> None: """Should NOT raise when request target matches 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_conversation_messages.return_value = [] + mock_memory.get_attack_results_async = AsyncMock(return_value=[ar]) + mock_memory.get_message_pieces_async = AsyncMock(return_value=[]) + mock_memory.get_conversation_messages_async = AsyncMock(return_value=[]) with ( patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_svc, @@ -4235,7 +4273,7 @@ async def test_allows_matching_target(self, attack_service, mock_memory) -> None mock_target_svc.get_target_object.return_value = _make_matching_target_mock() mock_get_target_svc.return_value = mock_target_svc - mock_normalizer = MagicMock() + mock_normalizer = get_mock_prompt_normalizer() mock_normalizer.send_prompt_async = AsyncMock() mock_normalizer_cls.return_value = mock_normalizer @@ -4331,11 +4369,11 @@ def test_create_attack_request_rejects_overlength_values() -> None: class TestResolveVideoRemixMetadata: """Tests for _resolve_video_remix_metadata.""" - def test_resolves_video_id_from_original_piece(self, attack_service, mock_memory): + async def test_resolves_video_id_from_original_piece(self, attack_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 = AsyncMock(return_value=[original_piece]) request = AddMessageRequest( role="user", @@ -4350,12 +4388,12 @@ def test_resolves_video_id_from_original_piece(self, attack_service, mock_memory ], ) - attack_service._resolve_video_remix_metadata(request) + (await attack_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, attack_service): + async def test_no_op_without_video_pieces(self, attack_service): """Should do nothing when there are no video_path pieces.""" request = AddMessageRequest( role="user", @@ -4363,11 +4401,11 @@ def test_no_op_without_video_pieces(self, attack_service): pieces=[MessagePieceRequest(original_value="just text", data_type="text")], ) - attack_service._resolve_video_remix_metadata(request) + (await attack_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, attack_service, mock_memory): + async def test_no_op_when_video_id_already_set(self, attack_service, mock_memory): """Should not overwrite existing video_id on text piece.""" request = AddMessageRequest( role="user", @@ -4386,12 +4424,12 @@ def test_no_op_when_video_id_already_set(self, attack_service, mock_memory): ], ) - attack_service._resolve_video_remix_metadata(request) + (await attack_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, attack_service, mock_memory): + async def test_no_op_without_original_prompt_id(self, attack_service, mock_memory): """Should not crash when video_path piece has no original_prompt_id.""" request = AddMessageRequest( role="user", @@ -4402,16 +4440,16 @@ def test_no_op_without_original_prompt_id(self, attack_service, mock_memory): ], ) - attack_service._resolve_video_remix_metadata(request) + (await attack_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, attack_service, mock_memory): + async def test_no_op_when_original_piece_has_no_video_id(self, attack_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 = AsyncMock(return_value=[original_piece]) request = AddMessageRequest( role="user", @@ -4426,6 +4464,6 @@ def test_no_op_when_original_piece_has_no_video_id(self, attack_service, mock_me ], ) - attack_service._resolve_video_remix_metadata(request) + (await attack_service._resolve_video_remix_metadata_async(request)) assert request.pieces[0].prompt_metadata is 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 d9790b81e7..97453de663 100644 --- a/tests/unit/backend/test_main.py +++ b/tests/unit/backend/test_main.py @@ -7,8 +7,10 @@ Covers the lifespan manager and setup_frontend function. """ +import asyncio import logging import os +import threading from contextlib import nullcontext from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch @@ -16,16 +18,48 @@ import pytest from fastapi import FastAPI from fastapi.testclient import TestClient +from httpx import ASGITransport, AsyncClient +from sqlalchemy import text from starlette.exceptions import HTTPException as StarletteHTTPException from pyrit.backend.main import SPAStaticFiles, app, lifespan, setup_frontend 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.""" @@ -37,6 +71,7 @@ def mock_scenario_run_lifecycle(): yield service +@pytest.mark.usefixtures("patch_central_database") class TestLifespan: """Tests for the application lifespan context manager.""" @@ -142,8 +177,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_called() + shared_memory.update_scenario_run_state_async.assert_not_called() 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_scenario_progress_read_model.py b/tests/unit/backend/test_scenario_progress_read_model.py index 9cb0afb773..4b1c284ce3 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,43 @@ 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_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 +151,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 +159,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 +170,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 +184,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 +213,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 +227,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 +235,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 +257,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 +276,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 9748376399..76eb568863 100644 --- a/tests/unit/backend/test_scenario_run_routes.py +++ b/tests/unit/backend/test_scenario_run_routes.py @@ -19,6 +19,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, @@ -221,7 +222,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), @@ -242,11 +243,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 @@ -279,9 +282,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 @@ -294,9 +299,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 @@ -309,7 +316,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"]}, @@ -367,7 +374,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") @@ -380,7 +387,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") @@ -406,9 +413,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() @@ -425,7 +432,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") @@ -471,8 +480,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 @@ -480,7 +489,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, @@ -488,7 +497,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( @@ -523,7 +532,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( @@ -533,7 +542,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, @@ -612,7 +621,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") @@ -626,7 +635,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") @@ -637,8 +646,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 fefd6ad340..0098ff758d 100644 --- a/tests/unit/backend/test_scenario_run_service.py +++ b/tests/unit/backend/test_scenario_run_service.py @@ -191,12 +191,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 @@ -227,7 +227,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), @@ -323,10 +323,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) @@ -449,7 +449,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( @@ -460,8 +460,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.""" @@ -678,10 +678,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) @@ -700,7 +700,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 ) @@ -982,10 +982,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))) @@ -1043,11 +1043,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")) @@ -1124,7 +1124,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() @@ -1160,7 +1160,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()) @@ -1182,7 +1182,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()) @@ -1201,8 +1201,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: @@ -1227,9 +1227,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: @@ -1251,7 +1251,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() @@ -1281,7 +1281,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()) @@ -1356,7 +1358,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()) @@ -1383,7 +1385,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()) @@ -1524,7 +1528,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()) @@ -1533,7 +1537,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()) @@ -1557,27 +1561,27 @@ async def _run_async() -> None: class TestScenarioRunServiceGetRun: """Tests for ScenarioRunService.get_run.""" - def test_get_run_returns_none_for_unknown_id(self, mock_memory) -> None: + 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 = [] + 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: + async def test_get_run_returns_existing_run(self, mock_memory) -> None: """Test that get_run 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", @@ -1586,10 +1590,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 @@ -1630,7 +1634,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, @@ -1653,9 +1657,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 @@ -1666,7 +1670,7 @@ def test_get_run_detail_preserves_readability_across_plan_metadata( assert ("using legacy run detail fields" in caplog.text) is expected_warning @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( @@ -1681,11 +1685,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 @@ -1694,48 +1698,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.""" - def test_list_runs_empty(self, mock_memory) -> None: + 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) + 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: + async def test_list_runs_returns_all_runs(self, mock_memory) -> None: """Test that list_runs 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: + async 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) + 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, @@ -1743,21 +1747,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", @@ -1782,24 +1786,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 @@ -1810,7 +1816,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( @@ -1835,9 +1841,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 @@ -1855,7 +1861,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, @@ -1863,15 +1869,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", @@ -1885,14 +1891,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( @@ -1913,32 +1919,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_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", @@ -1955,38 +1963,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 @@ -1996,12 +2012,12 @@ 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 @@ -2011,7 +2027,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 @@ -2020,8 +2036,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"] @@ -2029,11 +2052,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, @@ -2067,19 +2090,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", @@ -2087,10 +2114,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, @@ -2105,18 +2132,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() @@ -2127,8 +2157,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"] @@ -2157,10 +2187,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()) @@ -2175,8 +2205,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 ] @@ -2242,10 +2272,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( @@ -2290,10 +2320,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() @@ -2347,7 +2379,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() @@ -2360,11 +2392,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, @@ -2399,27 +2431,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"): @@ -2428,7 +2462,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"): @@ -2475,7 +2509,7 @@ 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: @@ -2506,7 +2540,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" @@ -2548,8 +2582,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()) @@ -2561,13 +2597,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, @@ -2579,23 +2615,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 @@ -2609,10 +2645,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 @@ -2621,7 +2657,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 @@ -2642,10 +2678,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 @@ -2655,17 +2691,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 @@ -2673,7 +2709,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 @@ -2687,10 +2723,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 @@ -2704,7 +2740,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() @@ -2724,10 +2760,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 @@ -2738,7 +2774,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() @@ -2753,15 +2789,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() @@ -2774,17 +2810,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 @@ -2808,10 +2844,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 @@ -2919,7 +2955,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"}) @@ -2965,7 +3001,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 @@ -2974,7 +3010,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", @@ -3028,14 +3064,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", @@ -3092,7 +3128,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, @@ -3102,7 +3138,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 @@ -3139,21 +3175,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() @@ -3164,7 +3200,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, @@ -3173,11 +3209,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={}, @@ -3186,10 +3222,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, @@ -3200,7 +3236,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=[ @@ -3237,19 +3273,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, @@ -3260,11 +3298,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( @@ -3326,15 +3364,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 @@ -3344,10 +3384,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={}, @@ -3360,10 +3400,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, @@ -3384,7 +3424,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 = [ @@ -3449,11 +3489,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 @@ -3481,7 +3521,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 @@ -3502,13 +3542,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, @@ -3521,7 +3563,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", @@ -3545,10 +3587,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, @@ -3745,7 +3787,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, @@ -3760,10 +3802,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, @@ -3776,16 +3818,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_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 f37c859482..5fc74ef00c 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 BadRequestException, EmptyResponseException, InvalidJsonException, PyritException from pyrit.executor.attack.component.adversarial_conversation_manager import ( @@ -34,7 +35,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") @@ -82,7 +82,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 @@ -455,7 +455,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, @@ -464,16 +464,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 61d5e7dd40..91c222fba2 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 @@ -500,16 +500,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.""" @@ -520,24 +522,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.""" @@ -548,14 +552,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.""" @@ -566,15 +570,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.""" @@ -585,10 +589,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 @@ -602,7 +606,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.""" @@ -610,13 +614,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, ) @@ -714,7 +720,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( @@ -735,7 +741,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" @@ -758,7 +764,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" @@ -812,7 +818,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 @@ -881,7 +887,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", @@ -902,7 +908,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 = [ @@ -943,7 +949,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( @@ -959,7 +965,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"), @@ -1011,7 +1017,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( @@ -1037,7 +1043,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 = [ @@ -1104,7 +1110,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!" @@ -1132,7 +1138,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 @@ -1212,7 +1218,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, @@ -1236,7 +1242,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, @@ -1279,7 +1285,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"] @@ -1324,7 +1330,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" @@ -1339,7 +1345,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()) @@ -1364,7 +1370,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()) @@ -1392,7 +1398,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()) @@ -1420,7 +1426,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()) @@ -1511,7 +1517,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 @@ -1582,7 +1588,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 @@ -1600,7 +1606,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 @@ -1749,7 +1755,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 == {"key": "value", "count": 1} @@ -1775,7 +1781,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" @@ -1803,7 +1809,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 274f15fce1..fabb8ceea7 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 InvalidJsonException from pyrit.executor.attack import AttackConverterConfig, RTASystemPromptPaths @@ -15,6 +16,7 @@ _generate_next_message_async, generate_simulated_conversation_async, ) +from pyrit.memory import MemoryInterface from pyrit.models import ( AttackOutcome, AttackResult, @@ -29,7 +31,6 @@ SimulatedTargetSystemPromptPaths, load_next_message_prompt, ) -from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import PromptTarget from pyrit.score import TrueFalseScorer @@ -55,7 +56,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 @@ -186,8 +187,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"): @@ -232,8 +233,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( @@ -276,8 +277,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( @@ -323,8 +324,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( @@ -366,8 +367,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( @@ -413,8 +414,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( @@ -426,7 +427,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) @@ -460,8 +461,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 @@ -511,8 +512,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( @@ -557,8 +558,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( @@ -604,8 +605,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( @@ -648,8 +649,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 @@ -696,8 +697,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 @@ -760,12 +761,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 @@ -843,11 +844,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 @@ -861,7 +862,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, @@ -915,11 +916,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 @@ -932,7 +933,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 @@ -971,8 +972,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( @@ -995,7 +996,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 @@ -1032,7 +1033,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" @@ -1115,8 +1116,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: @@ -1146,8 +1147,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( @@ -1177,8 +1178,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 f280c72b23..1cf7353e78 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 9ad50999f0..30ce549fe6 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,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +from unit.mocks import get_mock_prompt_normalizer from pyrit.converter import Base64Converter, StringJoinConverter from pyrit.executor.attack import ( @@ -85,7 +86,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..79d31a38f0 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,) @@ -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 @@ -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,7 +523,7 @@ 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")]: @@ -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,10 +606,12 @@ 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" 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 0d3d3f564d..a288acb1e9 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.executor.attack import ( AttackAdversarialConfig, @@ -22,7 +23,7 @@ from pyrit.executor.attack.component import ConversationManager, PrependedConversationConfig from pyrit.executor.attack.core.attack_config import DEFAULT_ADVERSARIAL_FIRST_MESSAGE 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, @@ -102,7 +103,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"})}) @@ -119,7 +120,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 @@ -592,7 +593,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"})}) @@ -729,7 +730,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): @@ -771,8 +772,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 @@ -980,16 +981,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..1a449fccf5 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() # 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() 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() 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() - 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() - 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,7 +674,7 @@ 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() @@ -665,7 +683,9 @@ def test_single_turn_empty_conversation_yields_fresh_id(self): duplicate = node.duplicate() 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): @@ -686,7 +706,7 @@ def test_duplicate_node_copies_conversation_context(self): 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() - 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() # 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() - 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_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_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_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_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 3526fa911b..576d850fa7 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/single_turn/test_prompt_sending.py b/tests/unit/executor/attack/single_turn/test_prompt_sending.py index 387c854b83..35ba5a64e1 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.converter import Base64Converter, StringJoinConverter from pyrit.executor.attack import ( @@ -169,7 +174,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 @@ -409,7 +414,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) @@ -437,7 +444,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" @@ -1264,7 +1273,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: @@ -1291,11 +1300,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") @@ -1305,8 +1314,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"): @@ -1328,10 +1338,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 @@ -1342,7 +1351,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 30c7fc9b1a..58e204c2be 100644 --- a/tests/unit/executor/attack/test_attack_parameter_consistency.py +++ b/tests/unit/executor/attack/test_attack_parameter_consistency.py @@ -14,6 +14,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest +from unit.mocks import get_mock_prompt_normalizer from pyrit.common.path import DATASETS_PATH, EXECUTOR_SEED_PROMPT_PATH from pyrit.executor.attack import ( @@ -41,7 +42,6 @@ SeedPrompt, get_common_json_schema, ) -from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import PromptTarget from pyrit.score import FloatScaleThresholdScorer, TrueFalseScorer @@ -151,7 +151,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"})}) @@ -174,7 +174,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"})}) @@ -193,7 +193,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 @@ -275,7 +275,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( @@ -322,7 +322,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 @@ -360,7 +360,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 @@ -388,7 +388,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 @@ -418,7 +418,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 @@ -461,7 +461,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 @@ -523,7 +523,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 @@ -577,7 +577,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 @@ -801,7 +801,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 @@ -814,7 +814,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)}" @@ -847,7 +847,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)}" @@ -882,7 +882,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)}" @@ -936,7 +936,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 @@ -950,9 +950,9 @@ async def test_tap_attack_adds_prepended_to_memory( # messages were duplicated into the single node conversation; resolve that id from memory. assert not 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 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())) # 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)}" @@ -1044,7 +1044,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. @@ -1057,7 +1057,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: @@ -1068,7 +1068,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, @@ -1093,7 +1093,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 ) @@ -1101,9 +1101,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) @@ -1148,10 +1148,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( @@ -1175,10 +1177,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( @@ -1202,9 +1206,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..5488d5466f 100644 --- a/tests/unit/executor/promptgen/fuzzer/test_fuzzer_result_printer.py +++ b/tests/unit/executor/promptgen/fuzzer/test_fuzzer_result_printer.py @@ -24,10 +24,10 @@ def _assert_no_live_control_characters(printed: str, *, enable_colors: bool) -> class TestFuzzerResultPrinter: @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 +39,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 ae942a467d..ea75b047a5 100644 --- a/tests/unit/memory/memory_interface/test_interface_attack_results.py +++ b/tests/unit/memory/memory_interface/test_interface_attack_results.py @@ -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,48 +1257,48 @@ 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]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar])) with closing(sqlite_instance.get_session()) as session: session.execute( text('UPDATE "AttackResultEntries" SET labels = :labels'), @@ -1248,33 +1306,33 @@ def test_get_unique_attack_labels_non_string_values_skipped(sqlite_instance: Mem ) 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]) + (await sqlite_instance.add_attack_results_to_memory_async(attack_results=[ar2])) with closing(sqlite_instance.get_session()) as session: session.execute( text('UPDATE "AttackResultEntries" SET labels = :labels WHERE conversation_id = :cid'), @@ -1282,58 +1340,60 @@ def test_get_unique_attack_labels_non_dict_labels_skipped(sqlite_instance: Memor ) 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,46 +1402,52 @@ 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"}) + (await sqlite_instance.get_attack_results_async(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"}), - ] +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"}), + ] + ) ) - 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"]} # ============================================================================ @@ -1418,67 +1484,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 @@ -1495,111 +1561,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", ) @@ -1608,144 +1676,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(), @@ -1760,11 +1832,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"] @@ -1775,68 +1847,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, @@ -1850,15 +1922,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, @@ -1872,12 +1944,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, @@ -1890,17 +1962,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"] @@ -1915,18 +1987,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.""" @@ -1953,26 +2025,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), @@ -1981,100 +2053,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", @@ -2089,8 +2171,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", @@ -2104,9 +2186,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 @@ -2115,7 +2197,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 @@ -2123,17 +2205,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 @@ -2144,12 +2228,12 @@ 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 @@ -2158,28 +2242,28 @@ def test_get_attack_results_keyset_pagination_stable_under_delete(sqlite_instanc session.query(AttackResultEntry).filter(AttackResultEntry.conversation_id == "conv-4").delete() 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 = [ @@ -2187,15 +2271,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), @@ -2203,11 +2287,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..14c656d09b 100644 --- a/tests/unit/memory/memory_interface/test_interface_identifiers.py +++ b/tests/unit/memory/memory_interface/test_interface_identifiers.py @@ -142,7 +142,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 +150,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 +164,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 +260,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..036c17f08a 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 @@ -38,15 +37,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 +63,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 +90,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 +102,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 +120,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 +128,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 +152,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 +170,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 +184,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 +209,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 +233,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 +248,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 +306,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,22 +328,22 @@ 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() @@ -343,23 +352,23 @@ def test_failed_score_write_preserves_duplicate_anchor( 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 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]) + (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]) + score, observation, piece = await _score_and_observation_async(file_memory) + (await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation])) with file_memory.get_session() as session: if foreign_keys: session.connection().exec_driver_sql("PRAGMA foreign_keys=ON") @@ -370,19 +379,23 @@ 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]) == [] + 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]) + score, observation, piece = await _score_and_observation_async(file_memory) + (await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation])) with file_memory.get_session() as session: entry = session.get(ScoreEntry, score.id) assert entry is not None @@ -392,21 +405,25 @@ 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] + 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]) + (await file_memory.add_scores_to_memory_async(scores=[score, replay], observations=[observation])) with file_memory.get_session() as session: entry = session.get(ScoreEntry, score.id) assert entry is not None @@ -417,22 +434,26 @@ def test_orm_shared_observation_survives_until_final_score( session.delete(session.get(ScoreEntry, replay.id)) session.commit() 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) + ( + await file_memory.delete_conversation_pieces_after_sequence_async( + conversation_id=piece.conversation_id, sequence=-1 + ) + ) with file_memory.get_session() as session: session.delete(session.get(ScoreEntry, replay.id)) session.commit() - 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("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]) + score, observation, piece = await _score_and_observation_async(file_memory) + (await file_memory.add_scores_to_memory_async(scores=[score], observations=[observation])) with file_memory.get_session() as session: entry = session.get(ScoreEntry, score.id) assert entry is not None @@ -446,19 +467,27 @@ def test_orm_link_removal_cleans_observation_before_score_deletion( session.delete(entry) session.commit() 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]) + 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] + ) + ) with file_memory.get_session() as session: if foreign_keys: session.connection().exec_driver_sql("PRAGMA foreign_keys=ON") @@ -478,27 +507,40 @@ def test_orm_score_delete_finds_links_missing_from_cached_collection( else: session.commit() 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) @@ -515,15 +557,19 @@ def test_orm_clearing_stale_links_cleans_the_persisted_observation(file_memory: 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]) == [] + 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])) == [] -def test_orm_moving_link_before_score_deletion_preserves_observation(file_memory: SQLiteMemory) -> None: - score, observation, _ = _score_and_observation(file_memory) +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]) + (await file_memory.add_scores_to_memory_async(scores=[score, other_score], observations=[observation])) with file_memory.get_session() as session: entry = session.get(ScoreEntry, score.id) other = session.get(ScoreEntry, other_score.id) @@ -532,86 +578,87 @@ 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] + 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] with file_memory.get_session() as session: session.delete(session.get(ScoreEntry, other_score.id)) session.commit() - assert file_memory.get_observations(observation_ids=[observation.id]) == [] + 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 +711,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 +725,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 8f78e9eac7..8bf6d6574c 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" @@ -257,10 +257,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 @@ -271,7 +271,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): @@ -280,10 +280,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 @@ -295,10 +295,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 # ========================================================================= @@ -317,10 +317,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" @@ -335,9 +335,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): @@ -347,10 +347,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" @@ -362,9 +362,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): @@ -372,17 +372,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 @@ -392,7 +392,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 b201c24097..b3a09c8b90 100644 --- a/tests/unit/memory/memory_interface/test_interface_scenario_history.py +++ b/tests/unit/memory/memory_interface/test_interface_scenario_history.py @@ -107,7 +107,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 +119,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 +140,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 +158,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 +181,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 +201,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 +243,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 +294,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 +305,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", - }, - ), - ] + (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, _ = sqlite_instance.get_scenario_run_history_page(limit=25) + _, aggregates, _ = await sqlite_instance.get_scenario_run_history_page_async(limit=25) aggregate = aggregates[str(scenario.id)] assert aggregate.unit_count == 1 @@ -347,7 +351,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 +394,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"}, - ), - ] + (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, _ = sqlite_instance.get_scenario_run_history_page(limit=25) + _, 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 +444,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 +480,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 +527,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,7 +582,7 @@ 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"} @@ -583,7 +595,7 @@ def test_legacy_label_hook_is_constructible_and_composes_multi_value_semantics( 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 +620,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 +645,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 +670,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 +707,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 +719,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"], } 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..55cbb96447 100644 --- a/tests/unit/memory/memory_interface/test_interface_scenario_results.py +++ b/tests/unit/memory/memory_interface/test_interface_scenario_results.py @@ -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 @@ -851,11 +875,11 @@ def test_delete_scenario_sets_attack_result_foreign_key_to_null( 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: @@ -871,7 +895,7 @@ def test_delete_scenario_sets_attack_result_foreign_key_to_null( assert entry.attribution_data == {"parent_collection": "a"} -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 +903,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 +956,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 +987,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 +1037,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 +1053,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 +1070,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 +1087,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 +1103,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 +1120,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 +1138,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 +1153,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 +1167,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..18b2a7d0f2 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 @@ -42,8 +42,8 @@ def all_rows(): session.execute.side_effect = execute try: - with patch.object(sqlite_instance, "get_session", return_value=session): - summaries = sqlite_instance.get_seed_dataset_summaries() + with patch.object(sqlite_instance, "_get_session", return_value=session): + summaries = await sqlite_instance.get_seed_dataset_summaries_async() finally: real_session.close() 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..590ef0042e --- /dev/null +++ b/tests/unit/memory/test_async_memory.py @@ -0,0 +1,332 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import ast +import asyncio +import inspect +import threading +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.ext.asyncio import create_async_engine +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 + + +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 + + +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_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_retains_loop_ownership(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[loop] is engine + + await memory.dispose_loop_resources_async() + assert memory._async_engines == {} + assert memory._async_auth == {} + + +@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_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() + + +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() -> 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 = {} + credential = MagicMock() + 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", wraps=create_async_engine) as factory, + patch("aioodbc.connect", new_callable=AsyncMock) as connect, + ): + engine = memory._get_async_engine() + try: + creator = factory.call_args.kwargs["async_creator"] + await creator() + await creator() + options = 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 connect.await_args_list[1].kwargs["attrs_before"][1256][4:] == "second".encode("utf-16-le") + assert engine.url.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() + 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..5dee587647 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 @@ -188,17 +189,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 +216,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 @@ -355,7 +360,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,7 +369,7 @@ 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"} ) @@ -446,8 +451,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 +647,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,8 +662,10 @@ 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 @@ -667,11 +674,12 @@ def test_update_prompt_metadata_by_conversation_id(memory_interface: AzureSQLMem 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 388bffff48..5d1b0547ec 100644 --- a/tests/unit/memory/test_conversation_branching.py +++ b/tests/unit/memory/test_conversation_branching.py @@ -3,19 +3,18 @@ """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 collections.abc import AsyncGenerator from contextlib import closing 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 select from sqlalchemy.dialects import mssql, sqlite from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm import Session, sessionmaker +from sqlalchemy.orm import Session from pyrit.memory import MemoryInterface, SQLiteMemory from pyrit.memory.memory_models import ( @@ -38,44 +37,40 @@ @pytest.fixture -def file_memory(*, sqlite_instance: SQLiteMemory, tmp_path: Path) -> Generator[SQLiteMemory, None, None]: - engine = create_engine(URL.create("sqlite", database=str(tmp_path / "branching.db"))) +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) 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"), @@ -96,19 +91,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"] @@ -118,7 +113,7 @@ 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]) == [] + assert (await sqlite_instance.get_message_pieces_async(prompt_ids=[ephemeral.id])) == [] with closing(sqlite_instance.get_session()) as session: links = session.scalars( select(PromptConverterIdentifierEntry).where( @@ -128,31 +123,33 @@ def test_copied_pieces_keep_all_lineage_metadata_order_and_identifier_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), @@ -160,19 +157,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) @@ -186,23 +183,26 @@ 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 - ] + 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] with closing(sqlite_instance.get_session()) as session: assert session.get(TargetIdentifierEntry, new_target.hash) is None assert session.get(ConverterIdentifierEntry, new_converter.hash) is None @@ -217,35 +217,41 @@ def test_failed_piece_insert_rolls_back_conversations_references_and_identifiers ) @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( @@ -258,21 +264,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] = [] @@ -281,43 +289,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=15) 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=15, + ) + 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]), @@ -325,22 +343,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} @@ -349,30 +371,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_seed_conditions.py b/tests/unit/memory/test_seed_conditions.py index 0766e571e5..f2990fbfc9 100644 --- a/tests/unit/memory/test_seed_conditions.py +++ b/tests/unit/memory/test_seed_conditions.py @@ -31,7 +31,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 +43,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 +51,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,12 +75,12 @@ 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() @@ -103,7 +105,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 +145,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,7 +155,7 @@ 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")] @@ -162,7 +164,7 @@ async def test_legacy_null_and_nonobjective_conditions_async(self, sqlite_instan 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() + 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)) @@ -192,7 +194,7 @@ async def test_invalid_persisted_conditions_raise_async( session.execute(update(SeedEntry).values(conditions=payload)) 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 +213,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 +228,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 +253,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 +275,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 +291,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: session.add(SeedIdentifierEntry.from_domain_model(identifier)) session.commit() - restored = sqlite_instance.get_seed_identifiers()[0] + 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..67c22f3e3e 100644 --- a/tests/unit/memory/test_sqlite_fixtures.py +++ b/tests/unit/memory/test_sqlite_fixtures.py @@ -6,7 +6,7 @@ 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,10 +262,10 @@ 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 diff --git a/tests/unit/memory/test_sqlite_memory.py b/tests/unit/memory/test_sqlite_memory.py index 8be9ef17f5..c897bd0e2a 100644 --- a/tests/unit/memory/test_sqlite_memory.py +++ b/tests/unit/memory/test_sqlite_memory.py @@ -505,15 +505,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" @@ -530,13 +530,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 @@ -559,7 +563,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. @@ -572,10 +576,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, @@ -583,10 +589,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 @@ -650,7 +658,7 @@ def test_update_entries_nonexistent_fields(sqlite_instance): 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" @@ -669,7 +677,7 @@ def test_update_entries_by_conversation_id(sqlite_instance, sample_conversation_ 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( + update_result = await sqlite_instance.update_prompt_entries_by_conversation_id_async( conversation_id=specific_conversation_id, update_fields=update_fields ) @@ -688,7 +696,7 @@ def test_update_entries_by_conversation_id(sqlite_instance, sample_conversation_ assert other_entry.original_value == original_content # Content should remain unchanged -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" @@ -706,7 +714,7 @@ def test_update_prompt_metadata_by_conversation_id(sqlite_instance, sample_conve # 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( + update_result = await sqlite_instance.update_prompt_entries_by_conversation_id_async( conversation_id=specific_conversation_id, update_fields=update_fields ) @@ -724,23 +732,24 @@ def test_update_prompt_metadata_by_conversation_id(sqlite_instance, sample_conve assert other_entry.prompt_metadata == original_metadata # Metadata should remain unchanged -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 @@ -748,13 +757,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 @@ -768,7 +777,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: @@ -777,7 +786,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 @@ -796,12 +805,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 @@ -826,7 +835,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 @@ -835,7 +844,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 @@ -858,7 +867,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 @@ -870,7 +879,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.""" @@ -891,7 +900,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 @@ -900,7 +909,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 @@ -929,7 +938,7 @@ 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" diff --git a/tests/unit/mocks.py b/tests/unit/mocks.py index 5a6051979d..10b1298b73 100644 --- a/tests/unit/mocks.py +++ b/tests/unit/mocks.py @@ -5,11 +5,13 @@ import shutil import tempfile import uuid -from collections.abc import Generator, MutableSequence, Sequence +from collections.abc import AsyncGenerator, MutableSequence, Sequence from contextlib import AbstractAsyncContextManager from typing import Any from unittest.mock import MagicMock, patch +from sqlalchemy.ext.asyncio import create_async_engine + from pyrit.memory import AzureSQLMemory, CentralMemory, MemoryInterface, PromptMemoryEntry from pyrit.models import ( ComponentIdentifier, @@ -19,6 +21,7 @@ ScenarioResult, flatten_to_message_pieces, ) +from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import PromptTarget, TargetCapabilities, TargetConfiguration, limit_requests_per_minute @@ -210,7 +213,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 +223,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 +251,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 +264,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 +346,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 +379,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 +391,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/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 "