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
Original file line number Diff line number Diff line change
Expand Up @@ -392,11 +392,35 @@ 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))
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, rows in zip(paths, file_rows, strict=True):
Expand Down
98 changes: 98 additions & 0 deletions tests/unit/datasets/test_anthropic_model_written_evals_dataset.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

import asyncio
from pathlib import Path
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,
Expand Down Expand Up @@ -288,6 +290,102 @@ 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)

@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()

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],
Expand Down
Loading