[ BENCHMARKS / v5.0 / TASKS / 173_taskgroup_cancel ]

asyncio TaskGroup structured cancellation in Python.

A structured-concurrency task group for asyncio, with a deadline and an explicit cancel, written without asyncio’s own TaskGroup and under a source lint.

Unit
173_taskgroup_cancel
Category
Concurrency & SystemsAsync patterns
Language
Python
Difficulty
Hard900 s wall clock (15 min)
Origin
New in v5
Ranked rows passed
1/7single seed each

The prompt

The agent receives exactly this text as its task, verbatim. The harness adds its own system prompt and, in some campaign arms, guidance of its own; the harness chapter describes those. The task’s setup also writes the files its working directory starts with (a worked sample, a repository or a service, where the prompt names them); they are not reproduced here.

Prompt · 173_taskgroup_cancel
Create /tmp/eval_tg173/tg.py (Python >= 3.11, standard library only) defining class TaskGroup: a structured-concurrency task group for asyncio with a deadline and an explicit cancel(). Do not use asyncio.TaskGroup or the asyncio.taskgroups module (the validator disables them). asyncio.timeout and every public Task/Future/loop API are allowed. The validator lints tg.py and rejects: imports other than asyncio, abc, collections, contextlib, enum, functools, heapq, itertools, math, time, typing, weakref and __future__; dynamic import, exec/eval/compile, gc, inspect, sys, type(), vars(), super() with arguments and dunder attribute access; private (_name) attributes of anything but self, and assigning attributes or items of anything but self or a local name (no patching asyncio, the loop or tasks). Here self means the first parameter of a plain method: class bodies hold only methods (undecorated or @property) and constants, a parameter or variable named self is refused elsewhere, and a class you define is used only by calling it. It also refuses a run that rebinds anything in asyncio or the event loop.

API
- TaskGroup(*, timeout=None): timeout is None or a positive number of seconds of event-loop time (loop.time()), counted from __aenter__.
- `async with TaskGroup(...) as g:` -- __aenter__ returns the group itself. The task that enters it is the group's parent. Entering the same group object a second time (even after it finished) raises RuntimeError.
- g.create_task(coro, *, name=None) -> asyncio.Task: runs coro as a child task with that name and returns the Task. It raises RuntimeError, after calling coro.close() so the coroutine never runs, if the group was never entered, is shutting down, or is finished. Finished = the exit has completed, or the exit has begun and no child is left. While the exit is waiting for children, a child may still add siblings (unless shutting down).
- g.cancel(): RuntimeError if never entered; does nothing if the group is shutting down or finished; otherwise triggers an internal shutdown.

Shutdown happens at most once, triggered by the first of:
 (1) a child finishing with an exception (a child that ends cancelled, by anyone, is not an error and triggers nothing);
 (2) the timeout expiring before the group is finished;
 (3) g.cancel();
 (4) the body of the `async with` exiting with an exception, including CancelledError;
 (5) the parent being cancelled while the exit waits for children.
Shutting down cancels every unfinished child, once (the group never cancels a child twice). For (1)-(3), internal shutdowns, the group also cancels its parent exactly once, so the body is interrupted at its current await, or the exit's wait is if the body already finished. The group must undo that request with Task.uncancel(): its own cancellation must never change the parent's cancelling() count, stay pending, or be seen outside the group (for example by an enclosing asyncio.timeout() or by code after the `async with`). Groups nest, in bodies and inside children; each group absorbs only the cancellations it requested itself.

Exit
The exit always waits until every child has finished, however many times the parent is cancelled meanwhile, and completes as soon as the last child finishes (in the same loop time; no polling). When it completes, the group leaves no callback scheduled on the loop. Child exceptions are collected in completion order (children that finish in the same loop tick may be in any order among themselves), including ones raised after shutdown began (e.g. by a child that raises while handling its cancellation). The first matching rule decides the outcome:
 A. Let E = the collected child exceptions, then the body's exception if it is not a CancelledError. If E is non-empty, raise ExceptionGroup('unhandled errors in a TaskGroup', E). If the parent still has a cancellation request from outside the group (parent.cancelling() > 0 once the group's own request is undone), that cancellation stays pending: the parent's next await raises CancelledError, and its cancelling() count is unchanged.
 B. Else, if a CancelledError reached the group (out of the body, or interrupting the exit's wait) and parent.cancelling() > 0 once the group's own request is undone: re-raise CancelledError.
 C. Else, if the shutdown was caused by the timeout: raise TimeoutError.
 D. Else exit normally; a CancelledError caused only by the group's own request is swallowed.
Children raise only Exception subclasses.

Example: in `async with TaskGroup() as g: g.create_task(crash()); g.create_task(slow()); await asyncio.sleep(5)`, where crash() sleeps 1 s then raises ValueError('x') and slow() sleeps 10 s: at loop time 1, slow() and the body are cancelled, and the `async with` raises ExceptionGroup('unhandled errors in a TaskGroup', [ValueError('x')]) at loop time 1. Afterwards the parent's cancelling() is 0.

Validation: a few hundred hidden, seeded scenarios. They use nested groups, timeouts, cancel(), external Task.cancel() of parents and children, asyncio.timeout() around groups, late create_task calls, and children that clean up, raise, or swallow on cancellation. They run on an event loop with a virtual clock: loop.time() jumps straight to the next scheduled timer whenever every task is blocked, so busy-waiting never advances time. Checked exactly: every event's (loop time, task name), the outcome of every group exit with the parent's cancelling() right after it, and that afterwards no task is left pending and no callback is left scheduled. Only a failing case's index is reported. Write your own tests.

What it tests and why it is in the suite

What it asks. A structured-concurrency task group for asyncio, with a deadline and an explicit cancel, written without asyncio’s own TaskGroup and under a source lint.

Why it is here. A new family. With the coroutine scheduler it covers Concurrency & Systems after the lock-free ring-buffer family (170) did not clear review.

In the suite README: evals/README.md:133 · evals/README.md:152

How it is graded

The validator holds its checks where the agent cannot read them, and runs them against what the agent left on disk once it stops. Its hidden cases are generated inside the validator from a seed; any worked sample the prompt names is only a sample, and no expected output for a hidden case is in the agent’s directory. Before any model ran it, the unit was proven: its reference solution passes, plausible wrong solutions fail for the reason declared in advance, an empty solution and a leak probe fail, and, where the unit is timed, a slow solution fails by the validator’s own limit. The family also went through up to three adversarial review rounds, in which an independent verifier tried to pass every unit without solving it.

Upstream: the prover’s controls · one unit’s life cycle · why v5 is built this way

How each ranked run did

One run per board row, the DGX Spark pair first, then the RTX 5090, then the gold standard. Each is a single seed: a pass or a fail on one unit is one draw, and a difference between two rows on one unit says little on its own. Claude Opus 5.5 is the unranked reference, in its own scaffold.

DGX Spark pair

One RTX 5090

Gold standard · unranked

  • Claude Opus 5.5Claude Code tools, no turn cap, 2× wallPassedPassed the validator.