Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions pyrit/backend/services/runtime_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
8 changes: 5 additions & 3 deletions pyrit/backend/services/scenario_run_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -1758,17 +1759,18 @@ 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:
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(e),
error_message=error_message,
error_type=type(e).__name__,
)
except Exception:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions pyrit/exceptions/exceptions_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,31 @@ 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, 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)}]"


def remove_start_md_json(response_msg: str) -> str:
"""
Check the message for supported start markers and remove them if present.
Expand Down
3 changes: 2 additions & 1 deletion pyrit/scenario/core/scenario.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__)}"
(
Expand Down
59 changes: 59 additions & 0 deletions tests/unit/backend/test_runtime_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions tests/unit/backend/test_scenario_run_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/datasets/test_anthropic_model_written_evals_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 37 additions & 0 deletions tests/unit/exceptions/test_exceptions_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
remove_end_md_json,
remove_markdown_json,
remove_start_md_json,
summarize_exception,
)


Expand Down Expand Up @@ -85,6 +86,42 @@ 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


@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."""

Expand Down
4 changes: 4 additions & 0 deletions tests/unit/scenario/core/test_scenario_partial_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -1151,6 +1151,10 @@ 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())
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()

Expand Down
Loading