From 0304227fc68706ebeb4d5a21dc20fe61fda04201 Mon Sep 17 00:00:00 2001 From: Muhammad Waqar Anwar Date: Thu, 5 Nov 2026 20:18:47 +0500 Subject: [PATCH 1/2] FIX: Preserve failures in exception group handling (P311-12) - Catch mixed BaseExceptionGroups from close_services_async in runtime shutdown and live apply, so memory is still disposed, earlier errors are kept, and apply records restart-required. - Add other concurrent Anthropic fetch failures as notes on the raised error instead of discarding them. - Include child failures in persisted scenario error messages. --- pyrit/backend/services/runtime_lifecycle.py | 7 ++- .../backend/services/scenario_run_service.py | 8 ++- .../anthropic_model_written_evals_dataset.py | 2 + pyrit/exceptions/exceptions_helpers.py | 22 +++++++ pyrit/scenario/core/scenario.py | 3 +- tests/unit/backend/test_runtime_lifecycle.py | 59 +++++++++++++++++++ .../unit/backend/test_scenario_run_service.py | 29 +++++++++ ...t_anthropic_model_written_evals_dataset.py | 24 ++++++++ .../exceptions/test_exceptions_helpers.py | 20 +++++++ .../core/test_scenario_partial_results.py | 2 + 10 files changed, 169 insertions(+), 7 deletions(-) diff --git a/pyrit/backend/services/runtime_lifecycle.py b/pyrit/backend/services/runtime_lifecycle.py index 9767c56749..4a1c93460d 100644 --- a/pyrit/backend/services/runtime_lifecycle.py +++ b/pyrit/backend/services/runtime_lifecycle.py @@ -220,7 +220,7 @@ async def _apply_async(self, *, version: str) -> None: await self._management_async(config) self.version = current_version self._publish(config) - except (Exception, asyncio.CancelledError) as error: + except (Exception, asyncio.CancelledError, BaseExceptionGroup) as error: logger.exception( "PyRIT live apply failed phase=%s generation=%s", "mutation" if mutated else "preflight", @@ -236,7 +236,8 @@ async def _apply_async(self, *, version: str) -> None: if mutated else "Configuration or memory settings are invalid. Memory changes require a restart." ) - if isinstance(error, asyncio.CancelledError): + # Only non-Exception errors can carry cancellation, including mixed exception groups. + if not isinstance(error, Exception): raise finally: logger.info("PyRIT apply outcome=%s generation=%s", self.outcome, self.generation) @@ -298,7 +299,7 @@ async def _shutdown_runtime_async(self) -> None: errors.append(error) try: await close_services_async() - except (Exception, asyncio.CancelledError) as error: + except (Exception, asyncio.CancelledError, BaseExceptionGroup) as error: errors.append(error) try: if get_analytics_service.cache_info().currsize: diff --git a/pyrit/backend/services/scenario_run_service.py b/pyrit/backend/services/scenario_run_service.py index 39dfcade98..b21ff17b33 100644 --- a/pyrit/backend/services/scenario_run_service.py +++ b/pyrit/backend/services/scenario_run_service.py @@ -50,6 +50,7 @@ ScenarioProgressSnapshot, ) from pyrit.common.async_compatibility import run_legacy_sync_async +from pyrit.exceptions.exceptions_helpers import summarize_exception from pyrit.executor.attack.core.attack_executor import ActiveAttackExecution from pyrit.memory import AttackResultKeysetCursor, CentralMemory, SQLiteMemory from pyrit.memory.memory_interface import ( @@ -1758,9 +1759,10 @@ async def _execute_run_async(self, *, scenario_result_id: str) -> None: logger.info("Scenario run %s stopped in state %s.", scenario_result_id, active.cancellation_state.value) except Exception as e: - active.error = str(e) + error_message = summarize_exception(e) + active.error = error_message active.cancellation_state = ScenarioRunState.FAILED - active.cancellation_reason = str(e) + active.cancellation_reason = error_message active.cancellation_error_type = type(e).__name__ active.retain_error_on_terminalization = True try: @@ -1768,7 +1770,7 @@ async def _execute_run_async(self, *, scenario_result_id: str) -> None: scenario_result_id=scenario_result_id, expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, scenario_run_state=ScenarioRunState.FAILED, - error_message=str(e), + error_message=error_message, error_type=type(e).__name__, ) except Exception: diff --git a/pyrit/datasets/seed_datasets/remote/anthropic_model_written_evals_dataset.py b/pyrit/datasets/seed_datasets/remote/anthropic_model_written_evals_dataset.py index 418a51ed0b..1e3511da15 100644 --- a/pyrit/datasets/seed_datasets/remote/anthropic_model_written_evals_dataset.py +++ b/pyrit/datasets/seed_datasets/remote/anthropic_model_written_evals_dataset.py @@ -414,6 +414,8 @@ async def fetch_files_async() -> list[list[dict[str, Any]]]: ) except ExceptionGroup as group: fetch_error = group.exceptions[0] + for other_error in group.exceptions[1:]: + fetch_error.add_note(f"Another file fetch also failed: {type(other_error).__name__}: {other_error}") if fetch_error is not None: # Preserve the original error without adding the group's exception context. raise fetch_error diff --git a/pyrit/exceptions/exceptions_helpers.py b/pyrit/exceptions/exceptions_helpers.py index 25e40ae176..441fca778f 100644 --- a/pyrit/exceptions/exceptions_helpers.py +++ b/pyrit/exceptions/exceptions_helpers.py @@ -73,6 +73,28 @@ def log_exception(retry_state: RetryCallState) -> None: collector.record(retry_state=retry_state) +def summarize_exception(error: BaseException) -> str: + """ + Describe an exception, including the child failures of exception groups. + + ``str()`` of an exception group only gives its message and child count. + + Args: + error: The exception to describe. + + Returns: + str: ``str(error)``, followed by each child's type and summary if ``error`` is a group. + """ + if not isinstance(error, BaseExceptionGroup): + return str(error) + children = [] + for child in error.exceptions: + child_summary = summarize_exception(child) + child_type = type(child).__name__ + children.append(f"{child_type}: {child_summary}" if child_summary else child_type) + return f"{error}: [{'; '.join(children)}]" + + def remove_start_md_json(response_msg: str) -> str: """ Check the message for supported start markers and remove them if present. diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py index 6c8281c9c2..7d4d8a90a6 100644 --- a/pyrit/scenario/core/scenario.py +++ b/pyrit/scenario/core/scenario.py @@ -24,6 +24,7 @@ from pyrit.common import default_values, get_global_default_values from pyrit.common.utils import to_sha256 from pyrit.exceptions import ScenarioPartialFailureException +from pyrit.exceptions.exceptions_helpers import summarize_exception from pyrit.executor.attack import AttackExecutor, AttackExecutorResult from pyrit.executor.attack.core.attack_executor import ActiveAttackExecution, _observe_interrupted_executions from pyrit.executor.attack.core.attack_preparation import AttackPreparationFailure @@ -1907,7 +1908,7 @@ def _partial_result_to_exception( 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) + error_message = summarize_exception(error) if error.__cause__ is not None: error_message = f"{error_message} Caused by {type(error.__cause__).__name__}: {str(error.__cause__)}" ( diff --git a/tests/unit/backend/test_runtime_lifecycle.py b/tests/unit/backend/test_runtime_lifecycle.py index 5bc4187327..f0884f7d66 100644 --- a/tests/unit/backend/test_runtime_lifecycle.py +++ b/tests/unit/backend/test_runtime_lifecycle.py @@ -219,6 +219,65 @@ async def test_shutdown_disposes_memory_after_services_even_on_failure( assert getattr(error, "__notes__", None) == expected +@pytest.mark.parametrize("scenario_fails", [False, True]) +async def test_shutdown_mixed_close_group_still_disposes_memory_and_reports_errors_async( + *, runtime: RuntimeLifecycle, scenario_fails: bool +) -> None: + memory = MagicMock(spec=MemoryInterface) + scenario_service = MagicMock(spec=ScenarioRunService) + scenario_error = RuntimeError("scenario shutdown failed") + if scenario_fails: + scenario_service.shutdown_async.side_effect = scenario_error + close_error = BaseExceptionGroup( + "Backend service closure failed.", [asyncio.CancelledError("cached close"), RuntimeError("analytics close")] + ) + with ( + patch.object(CentralMemory, "_memory_instance", memory), + patch.object(lifecycle_module, "peek_scenario_run_service", return_value=scenario_service), + patch.object(lifecycle_module, "close_services_async", AsyncMock(side_effect=close_error)), + pytest.raises(BaseExceptionGroup) as caught, + ): + await runtime.shutdown_async() + + if scenario_fails: + assert caught.value.exceptions == (scenario_error, close_error) + else: + assert caught.value is close_error + memory.dispose_engine_async.assert_awaited_once() + + +async def test_apply_mixed_close_group_requires_restart_and_propagates_cancellation_async( + runtime: RuntimeLifecycle, +) -> None: + close_error = BaseExceptionGroup( + "Backend service closure failed.", [asyncio.CancelledError("cached close"), RuntimeError("analytics close")] + ) + with ( + patch.object(lifecycle_module, "close_services_async", AsyncMock(side_effect=close_error)), + pytest.raises(BaseExceptionGroup) as caught, + ): + await apply_async(runtime) + + assert caught.value is close_error + assert runtime.state == "restart-required" + assert runtime.outcome == "restart-required" + config = await runtime._load_async() + config.apply_prepared_reinitialization_async.assert_not_awaited() + + +async def test_apply_close_group_without_cancellation_requires_restart_without_raising_async( + runtime: RuntimeLifecycle, +) -> None: + close_error = ExceptionGroup( + "Backend service closure failed.", [RuntimeError("cached close"), RuntimeError("analytics close")] + ) + with patch.object(lifecycle_module, "close_services_async", AsyncMock(side_effect=close_error)): + await apply_async(runtime) + + assert runtime.state == "restart-required" + assert runtime.outcome == "restart-required" + + async def test_shutdown_repeated_failure_preserves_original_error_async(runtime: RuntimeLifecycle) -> None: failure = RuntimeError("service shutdown failed") lifecycle_module.close_services_async.side_effect = failure diff --git a/tests/unit/backend/test_scenario_run_service.py b/tests/unit/backend/test_scenario_run_service.py index adfb156053..824fb3d8cb 100644 --- a/tests/unit/backend/test_scenario_run_service.py +++ b/tests/unit/backend/test_scenario_run_service.py @@ -3881,6 +3881,35 @@ async def _run() -> None: assert fetched is not None assert fetched.error == "scenario exploded" + async def test_execute_run_reports_every_failure_in_an_exception_group(self, mock_all_registries) -> None: + service = ScenarioRunService() + mock_instance = mock_all_registries["scenario_instance"] + release_execution = asyncio.Event() + + async def _run() -> None: + await release_execution.wait() + raise ExceptionGroup("Multiple failed", [ValueError("first boom"), RuntimeError("second boom")]) + + mock_instance.run_async = AsyncMock(side_effect=_run) + response = await service.start_run_async(request=_make_request()) + active = service._active_tasks.get(response.scenario_result_id) + assert active is not None + assert active.task is not None + release_execution.set() + await active.task + + expected = "Multiple failed (2 sub-exceptions): [ValueError: first boom; RuntimeError: second boom]" + assert active.error == expected + assert active.cancellation_reason == expected + assert active.cancellation_error_type == "ExceptionGroup" + mock_all_registries["memory"].try_update_scenario_run_state_async.assert_awaited_with( + scenario_result_id=response.scenario_result_id, + expected_states={ScenarioRunState.CREATED, ScenarioRunState.IN_PROGRESS}, + scenario_run_state=ScenarioRunState.FAILED, + error_message=expected, + error_type="ExceptionGroup", + ) + async def test_execute_run_retains_richer_terminal_error_from_scenario(self, mock_all_registries) -> None: service = ScenarioRunService() mock_instance = mock_all_registries["scenario_instance"] diff --git a/tests/unit/datasets/test_anthropic_model_written_evals_dataset.py b/tests/unit/datasets/test_anthropic_model_written_evals_dataset.py index 4d1d46381d..3cdb6ae9c7 100644 --- a/tests/unit/datasets/test_anthropic_model_written_evals_dataset.py +++ b/tests/unit/datasets/test_anthropic_model_written_evals_dataset.py @@ -315,8 +315,32 @@ async def fake_fetch(path: str, *, cache: bool) -> list[dict]: assert exc_info.value is error assert isinstance(exc_info.value.__cause__, OSError) + assert not hasattr(exc_info.value, "__notes__") assert sorted(cancelled) == sorted(path for path in _MANIFEST if path != failing_path) + async def test_concurrent_fetch_failures_keep_first_error_and_note_the_others(self) -> None: + loader = _AnthropicModelWrittenEvalsDataset() + errors = { + "persona/agreeableness.jsonl": RuntimeError("Status code: 503"), + "sycophancy/sycophancy_on_philpapers2020.jsonl": OSError("connection reset"), + } + + async def fake_fetch(path: str, *, cache: bool) -> list[dict]: + if path in errors: + raise errors[path] + await asyncio.Event().wait() + raise AssertionError("sibling fetch was not cancelled") + + with ( + patch.object(loader, "_fetch_file_async", side_effect=fake_fetch), + pytest.raises((RuntimeError, OSError)) as exc_info, + ): + await loader.fetch_dataset_async(cache=False) + + other = next(error for error in errors.values() if error is not exc_info.value) + assert exc_info.value in errors.values() + assert exc_info.value.__notes__ == [f"Another file fetch also failed: {type(other).__name__}: {other}"] + @pytest.mark.parametrize("categories", [None, [AnthropicModelWrittenEvalCategory.WINOGENERATED]]) async def test_fetch_failure_preserves_caller_cancellation_count( self, categories: list[AnthropicModelWrittenEvalCategory] | None diff --git a/tests/unit/exceptions/test_exceptions_helpers.py b/tests/unit/exceptions/test_exceptions_helpers.py index fb58c3935c..53fbf7b1b0 100644 --- a/tests/unit/exceptions/test_exceptions_helpers.py +++ b/tests/unit/exceptions/test_exceptions_helpers.py @@ -18,6 +18,7 @@ remove_end_md_json, remove_markdown_json, remove_start_md_json, + summarize_exception, ) @@ -85,6 +86,25 @@ def test_remove_markdown_json(input_str, expected_output): assert remove_markdown_json(input_str) == expected_output +@pytest.mark.parametrize( + "error, expected", + [ + (ValueError("plain failure"), "plain failure"), + (ValueError(), ""), + ( + ExceptionGroup("Both failed", [ValueError("first"), RuntimeError()]), + "Both failed (2 sub-exceptions): [ValueError: first; RuntimeError]", + ), + ( + ExceptionGroup("Outer", [ExceptionGroup("Inner", [KeyError("key")]), OSError("disk")]), + "Outer (2 sub-exceptions): [ExceptionGroup: Inner (1 sub-exception): [KeyError: 'key']; OSError: disk]", + ), + ], +) +def test_summarize_exception(error, expected): + assert summarize_exception(error) == expected + + class TestLogException: """Tests for the log_exception function with execution context.""" diff --git a/tests/unit/scenario/core/test_scenario_partial_results.py b/tests/unit/scenario/core/test_scenario_partial_results.py index a3a5ffdb62..32be1a751e 100644 --- a/tests/unit/scenario/core/test_scenario_partial_results.py +++ b/tests/unit/scenario/core/test_scenario_partial_results.py @@ -1151,6 +1151,8 @@ async def run_attack_c_async(*args, **kwargs) -> AttackExecutorResult[AttackResu )[0] assert failed_result.scenario_run_state == ScenarioRunState.FAILED assert failed_result.number_tries == 1 + assert failed_result.error_type == "ExceptionGroup" + assert all(str(error) in failed_result.error_message for error in partial_failures.values()) final_result = await scenario.run_async() From 0493265fde32641cc499582c088cf4a808ec7c79 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Thu, 5 Nov 2026 22:16:34 -0800 Subject: [PATCH 2/2] FIX: Preserve explicit causes in grouped failure summaries Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- pyrit/exceptions/exceptions_helpers.py | 5 ++++- .../unit/exceptions/test_exceptions_helpers.py | 17 +++++++++++++++++ .../core/test_scenario_partial_results.py | 2 ++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/pyrit/exceptions/exceptions_helpers.py b/pyrit/exceptions/exceptions_helpers.py index 441fca778f..35252783a0 100644 --- a/pyrit/exceptions/exceptions_helpers.py +++ b/pyrit/exceptions/exceptions_helpers.py @@ -83,13 +83,16 @@ def summarize_exception(error: BaseException) -> str: error: The exception to describe. Returns: - str: ``str(error)``, followed by each child's type and summary if ``error`` is a group. + str: ``str(error)``, followed by each child's type, summary, and direct explicit + cause if ``error`` is a group. Non-group errors are unchanged. """ if not isinstance(error, BaseExceptionGroup): return str(error) children = [] for child in error.exceptions: child_summary = summarize_exception(child) + if child.__cause__ is not None: + child_summary = f"{child_summary} Caused by {type(child.__cause__).__name__}: {child.__cause__}" child_type = type(child).__name__ children.append(f"{child_type}: {child_summary}" if child_summary else child_type) return f"{error}: [{'; '.join(children)}]" diff --git a/tests/unit/exceptions/test_exceptions_helpers.py b/tests/unit/exceptions/test_exceptions_helpers.py index 53fbf7b1b0..06ecfe6a83 100644 --- a/tests/unit/exceptions/test_exceptions_helpers.py +++ b/tests/unit/exceptions/test_exceptions_helpers.py @@ -105,6 +105,23 @@ def test_summarize_exception(error, expected): assert summarize_exception(error) == expected +@pytest.mark.parametrize("nested", [False, True]) +def test_summarize_exception_preserves_group_child_causes(*, nested: bool) -> None: + cause = RuntimeError("connection reset") + error = ValueError("fetch failed") + error.__cause__ = cause + group = ExceptionGroup("Fetches failed", [error, OSError("disk full")]) + if nested: + group = ExceptionGroup("Outer", [group]) + + summary = summarize_exception(group) + + assert "ValueError: fetch failed Caused by RuntimeError: connection reset" in summary + assert "OSError: disk full" in summary + assert summarize_exception(error) == "fetch failed" + assert error.__cause__ is cause + + class TestLogException: """Tests for the log_exception function with execution context.""" diff --git a/tests/unit/scenario/core/test_scenario_partial_results.py b/tests/unit/scenario/core/test_scenario_partial_results.py index 32be1a751e..ea2d4c84bf 100644 --- a/tests/unit/scenario/core/test_scenario_partial_results.py +++ b/tests/unit/scenario/core/test_scenario_partial_results.py @@ -1153,6 +1153,8 @@ async def run_attack_c_async(*args, **kwargs) -> AttackExecutorResult[AttackResu assert failed_result.number_tries == 1 assert failed_result.error_type == "ExceptionGroup" assert all(str(error) in failed_result.error_message for error in partial_failures.values()) + assert "Caused by RuntimeError: attack-a interrupted" in failed_result.error_message + assert "Caused by TimeoutError: attack-b timed out" in failed_result.error_message final_result = await scenario.run_async()