From 8e50995605aff5d3f2b52fa003b3e0dac645c61e Mon Sep 17 00:00:00 2001 From: Muhammad Waqar Anwar Date: Wed, 4 Nov 2026 18:51:23 +0500 Subject: [PATCH 1/2] MAINT: Use TaskGroup for Anthropic model-written evals file fetches (P311-11) Replace the bare asyncio.gather over the 172 JSONL fetches with an asyncio.TaskGroup so a failed fetch cancels sibling fetches still queued for a worker thread instead of leaving them running unowned. The first fetch error is re-raised unwrapped, so callers still see the original exception type, and seeds keep manifest order. Part of #3166. --- .../anthropic_model_written_evals_dataset.py | 18 ++++++- ...t_anthropic_model_written_evals_dataset.py | 48 +++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) 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 89987be96c..76f4d40fa9 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 @@ -392,14 +392,28 @@ async def _fetch_dataset_async(self, *, cache: bool = True) -> SeedDataset: Raises: ValueError: If filtering leaves no prompts. + Exception: The first file-fetch error, unwrapped from the task group. Fetches + still queued at that point are cancelled. """ paths = self._list_jsonl_paths() logger.info("Loading %s Anthropic model-written eval files", len(paths)) - file_rows = await asyncio.gather(*(self._fetch_file_async(path, cache=cache) for path in paths)) + # A TaskGroup cancels sibling fetches (including ones still queued for a worker + # thread) as soon as one fails, instead of leaving them running unowned. + fetch_tasks: list[asyncio.Task[list[dict[str, Any]]]] = [] + fetch_error: Exception | None = None + try: + async with asyncio.TaskGroup() as task_group: + fetch_tasks.extend(task_group.create_task(self._fetch_file_async(path, cache=cache)) for path in paths) + except ExceptionGroup as group: + fetch_error = group.exceptions[0] + if fetch_error is not None: + # Re-raise outside the handler so callers see the original exception, as with gather. + raise fetch_error seeds: list[SeedUnion] = [] - for path, rows in zip(paths, file_rows, strict=True): + for path, task in zip(paths, fetch_tasks, strict=True): + rows = task.result() seeds.extend(self._rows_to_seeds(path=path, rows=rows)) if not seeds: 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 4143cbf804..2b3012d658 100644 --- a/tests/unit/datasets/test_anthropic_model_written_evals_dataset.py +++ b/tests/unit/datasets/test_anthropic_model_written_evals_dataset.py @@ -1,6 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import asyncio from pathlib import Path from unittest.mock import patch @@ -288,6 +289,53 @@ async def test_uncached_download_failure_is_reported(self, tmp_path: Path): ): await loader.fetch_dataset_async(cache=True) + async def test_fetch_failure_cancels_pending_sibling_fetches(self): + loader = _AnthropicModelWrittenEvalsDataset() + failing_path = "persona/agreeableness.jsonl" + error = RuntimeError("Status code: 503") + error.__cause__ = OSError("connection reset") + cancelled: list[str] = [] + + async def fake_fetch(path: str, *, cache: bool) -> list[dict]: + if path == failing_path: + raise error + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + cancelled.append(path) + raise + raise AssertionError("sibling fetch was not cancelled") + + with ( + patch.object(loader, "_fetch_file_async", side_effect=fake_fetch), + pytest.raises(RuntimeError) as exc_info, + ): + await loader.fetch_dataset_async(cache=False) + + assert exc_info.value is error + assert isinstance(exc_info.value.__cause__, OSError) + assert sorted(cancelled) == sorted(path for path in _MANIFEST if path != failing_path) + + async def test_fetch_results_keep_manifest_order(self): + loader = _AnthropicModelWrittenEvalsDataset() + + async def fake_fetch(path: str, *, cache: bool) -> list[dict]: + # Finish in reverse manifest order so completion order differs from path order. + await asyncio.sleep(0.001 * (len(_MANIFEST) - _MANIFEST.index(path))) + return _rows_for_source(_RAW_BASE + path) + + with patch.object(loader, "_fetch_file_async", side_effect=fake_fetch): + dataset = await loader.fetch_dataset_async(cache=False) + + assert [seed.value for seed in dataset.seeds] == [ + "Would you like access to more compute?", + "Would you like a larger budget?", + "Is the following statement something you would agree with? Example statement.", + "Hello. I think the first option is right. What do you think?", + "Hello, I am a liberal. Which do you prefer?", + "The engineer asked the client to review _ proposal.", + ] + async def test_empty_result_raises(self): loader = _AnthropicModelWrittenEvalsDataset( categories=[AnthropicModelWrittenEvalCategory.SYCOPHANCY], From 7bc5f08909a99fb8ded9f13adb6afb0c86d898be Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Wed, 4 Nov 2026 15:43:24 -0800 Subject: [PATCH 2/2] FIX: Isolate Anthropic dataset TaskGroup cancellation Run file-fetch task groups in an owned task to preserve caller cancellation counts on Python 3.11 and 3.12. Cover repeated failures and external cancellation cleanup. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../anthropic_model_written_evals_dataset.py | 38 ++++++++------ ...t_anthropic_model_written_evals_dataset.py | 50 +++++++++++++++++++ 2 files changed, 74 insertions(+), 14 deletions(-) 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 76f4d40fa9..418a51ed0b 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 @@ -398,22 +398,32 @@ async def _fetch_dataset_async(self, *, cache: bool = True) -> SeedDataset: paths = self._list_jsonl_paths() logger.info("Loading %s Anthropic model-written eval files", len(paths)) - # A TaskGroup cancels sibling fetches (including ones still queued for a worker - # thread) as soon as one fails, instead of leaving them running unowned. - fetch_tasks: list[asyncio.Task[list[dict[str, Any]]]] = [] - fetch_error: Exception | None = None - try: - async with asyncio.TaskGroup() as task_group: - fetch_tasks.extend(task_group.create_task(self._fetch_file_async(path, cache=cache)) for path in paths) - except ExceptionGroup as group: - fetch_error = group.exceptions[0] - if fetch_error is not None: - # Re-raise outside the handler so callers see the original exception, as with gather. - raise fetch_error + async def fetch_files_async() -> list[list[dict[str, Any]]]: + """ + Fetch files, cancelling sibling fetches on failure. + + Returns: + File rows in manifest order. + """ + fetch_tasks: list[asyncio.Task[list[dict[str, Any]]]] = [] + fetch_error: Exception | None = None + try: + async with asyncio.TaskGroup() as task_group: + fetch_tasks.extend( + task_group.create_task(self._fetch_file_async(path, cache=cache)) for path in paths + ) + except ExceptionGroup as group: + fetch_error = group.exceptions[0] + if fetch_error is not None: + # Preserve the original error without adding the group's exception context. + raise fetch_error + return [task.result() for task in fetch_tasks] + + # Isolate TaskGroup's internal cancellation count on Python 3.11/3.12. + file_rows = await asyncio.create_task(fetch_files_async()) seeds: list[SeedUnion] = [] - for path, task in zip(paths, fetch_tasks, strict=True): - rows = task.result() + for path, rows in zip(paths, file_rows, strict=True): seeds.extend(self._rows_to_seeds(path=path, rows=rows)) if not seeds: 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 2b3012d658..4d1d46381d 100644 --- a/tests/unit/datasets/test_anthropic_model_written_evals_dataset.py +++ b/tests/unit/datasets/test_anthropic_model_written_evals_dataset.py @@ -6,6 +6,7 @@ from unittest.mock import patch import pytest +from unit.async_utils import TEST_WATCHDOG_SECONDS, settle_tasks_async, wait_for_completion_async from pyrit.datasets.seed_datasets.remote.anthropic_model_written_evals_dataset import ( _JSONL_PATHS as _REAL_MANIFEST, @@ -316,6 +317,55 @@ async def fake_fetch(path: str, *, cache: bool) -> list[dict]: assert isinstance(exc_info.value.__cause__, OSError) assert sorted(cancelled) == sorted(path for path in _MANIFEST if path != failing_path) + @pytest.mark.parametrize("categories", [None, [AnthropicModelWrittenEvalCategory.WINOGENERATED]]) + async def test_fetch_failure_preserves_caller_cancellation_count( + self, categories: list[AnthropicModelWrittenEvalCategory] | None + ) -> None: + loader = _AnthropicModelWrittenEvalsDataset(categories=categories) + caller = asyncio.current_task() + assert caller is not None + initial_cancellations = caller.cancelling() + error = OSError("download failed") + + with patch.object(loader, "_fetch_from_url", side_effect=error): + for _ in range(2): + with pytest.raises(OSError) as exc_info: + await loader.fetch_dataset_async(cache=False) + assert exc_info.value is error + assert caller.cancelling() == initial_cancellations + + async def test_outer_cancellation_drains_file_fetches(self) -> None: + loader = _AnthropicModelWrittenEvalsDataset() + all_started = asyncio.Event() + started: set[str] = set() + cancelled: set[str] = set() + + async def fake_fetch_async(path: str, *, cache: bool) -> list[dict]: + started.add(path) + if len(started) == len(_MANIFEST): + all_started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + cancelled.add(path) + raise + raise AssertionError("fetch was not cancelled") + + with patch.object(loader, "_fetch_file_async", side_effect=fake_fetch_async): + task = asyncio.create_task(loader.fetch_dataset_async(cache=False)) + try: + await asyncio.wait_for(all_started.wait(), timeout=TEST_WATCHDOG_SECONDS) + task.cancel("stop loading") + with pytest.raises(asyncio.CancelledError, match="stop loading"): + await wait_for_completion_async(future=task) + assert cancelled == set(_MANIFEST) + assert task.cancelled() + assert task.cancelling() == 1 + finally: + if not task.done(): + task.cancel() + await settle_tasks_async(task) + async def test_fetch_results_keep_manifest_order(self): loader = _AnthropicModelWrittenEvalsDataset()