Product case study · November 27, 2026
Ask Claude Code to stop sibling tasks when a batch fails
Build a local asyncio failure test, ask Claude Code to replace gather with TaskGroup, and verify sibling cleanup before the error reaches the caller.

For jobs that must succeed as one batch, make sibling cleanup part of the failure contract. TaskGroup gives that contract a clear boundary.
Your batch reports a failure, but another job is still running. If that job is writing a file or sending a request, the error message has arrived before the work has actually stopped.
This is a good repair to give Claude Code because “handle the exception” leaves the important question unanswered: what should happen to the other jobs? For a batch whose parts belong together, I want the caller to regain control only after unfinished siblings have been cancelled and their cleanup has finished.
Use Bash, Python 3.11 or newer, and an installed, signed-in Claude Code. This lab uses only local coroutines and fictional results. The Python baseline and reference repair were tested locally; the agent prompt is an authored exercise, not a recorded Claude session. Official sources were checked November 27, 2026.
Give the failure somewhere to hide
Create a disposable folder and a deliberately incomplete runner:
batch_lab=$(mktemp -d /tmp/claude-async-batch.XXXXXX)
cd "$batch_lab"
cat > batch.py <<'PY'
import asyncio
async def run_batch(jobs):
return await asyncio.gather(*(job() for job in jobs))
PY
Each job is a zero-argument async function. The runner calls them concurrently and returns their results in input order when all succeed.
Python documents that, with its default settings, gather propagates the first exception while other awaitables continue running. That behavior can be useful for independent work. It does not meet our batch policy.
Save this as test_batch.py:
import asyncio
import unittest
from batch import run_batch
class BatchTests(unittest.IsolatedAsyncioTestCase):
async def test_success_keeps_input_order(self):
second_finished = asyncio.Event()
async def first():
await second_finished.wait()
return "first"
async def second():
second_finished.set()
return "second"
self.assertEqual(await run_batch([first, second]),
["first", "second"])
async def test_empty_batch(self):
self.assertEqual(await run_batch([]), [])
async def test_failure_waits_for_sibling_cleanup(self):
started = asyncio.Event()
release = asyncio.Event()
cleaned = asyncio.Event()
effects = []
siblings = []
async def sibling():
siblings.append(asyncio.current_task())
started.set()
try:
await release.wait()
effects.append("work continued")
finally:
await asyncio.sleep(0)
cleaned.set()
async def broken():
await started.wait()
raise RuntimeError("fixture failure")
try:
with self.assertRaises(Exception) as caught:
await run_batch([sibling, broken])
self.assertTrue(cleaned.is_set(),
"runner returned before sibling cleanup")
self.assertEqual(effects, [])
self.assertIsInstance(caught.exception, ExceptionGroup)
self.assertEqual(len(caught.exception.exceptions), 1)
error = caught.exception.exceptions[0]
self.assertIsInstance(error, RuntimeError)
self.assertEqual(str(error), "fixture failure")
finally:
# Drain the deliberately broken baseline without leaking a task.
release.set()
await asyncio.gather(*siblings, return_exceptions=True)
Run:
python3 -m unittest -v test_batch
The baseline passes the success and empty-batch cases, then fails the cleanup assertion. The sibling is still waiting when run_batch raises. The test’s finally block releases and drains it so the exercise itself leaves no pending task behind.
The events matter: they establish that the sibling has started before the failure, without guessing how many milliseconds your laptop needs. Checking cleanup inside the running loop also avoids mistaking loop-shutdown cleanup for correct runner behavior.
Give Claude a complete contract
Start claude in the practice folder and paste:
Read batch.py and test_batch.py. Run the unchanged tests first.
Change only batch.py; do not install dependencies, commit or delegate.
Use Python 3.11+ asyncio.TaskGroup.
The input is a finite list of zero-argument async job functions.
Run them concurrently. On success return values in input order.
An empty list returns [].
If a job raises RuntimeError, cancel unfinished siblings and await
cleanup before propagating the TaskGroup's ExceptionGroup.
Do not swallow cancellation or turn errors into successful results.
Keep the tests unchanged. Run them again and report actual output.
Explain why this does not roll back effects completed before failure.
Anthropic’s common workflows describes giving Claude reproduction details and verifying fixes. Here, the acceptance test pins down when verification happens. Review the session’s permissions and proposed commands; the requested file boundary is an instruction, not a filesystem sandbox.
Compare the repair
A reference implementation is short:
import asyncio
async def run_batch(jobs):
async with asyncio.TaskGroup() as group:
tasks = [group.create_task(job()) for job in jobs]
return [task.result() for task in tasks]
This passed all three tests locally. Keeping task references in a list preserves input order even when completion order differs.
A task group’s exit waits for its tasks. If one fails with an exception other than CancelledError, it cancels the remaining tasks and waits for them before raising grouped failures. Python’s task-group reference documents the rules and special handling for KeyboardInterrupt and SystemExit.
The caller now receives an ExceptionGroup, rather than the baseline’s bare RuntimeError. That is an interface change worth reviewing. The test inspects the contained exception so a generic “something failed” result cannot hide a different bug. Existing callers that catch only RuntimeError need an explicit grouped-error handling policy.
Know what the passing test buys you
Cancellation is cooperative. A coroutine must reach a point where it can receive cancellation, and cleanup can take time. Keep resource cleanup in finally blocks; if you catch CancelledError, normally re-raise it after cleanup. A job that suppresses cancellation or blocks the event loop can prevent this boundary from finishing promptly.
Nor is a task group a transaction. An email already sent stays sent. A file already written stays written. This fixture proves that its waiting sibling is cancelled before it reaches its simulated effect; it does not prove rollback for external services.
After Claude finishes, rerun the unchanged suite yourself. If cleanup still fails, inspect whether tasks were created through the group or launched separately with asyncio.create_task. If results arrive in completion order, retain task references in input order. If TaskGroup is missing, check python3 --version and use Python 3.11 or newer.
I would use this contract for one report assembled from several dependent jobs. For independent jobs where partial results are useful, choose and test a different failure policy. The useful improvement is making that choice visible before an agent writes the code.
Sources
Checked November 27, 2026:
- Python: coroutines and tasks —
gather, task groups and cooperative cancellation. - Python: exception groups — grouped exceptions and their contained exceptions.
- Anthropic: common workflows — reproduction and verification prompts for Claude Code.
Put this to work
Why gather's first exception does not automatically stop its other jobs.
Try
Give Claude Code a batch runner and three fixed acceptance tests.
Prove it worked
Check cleanup at the error boundary, before the event loop shuts down.
Keep in view
- Expose a sibling coroutine still waiting after another job fails.
- Use TaskGroup to cancel and await unfinished siblings.
- Preserve successful result order and inspect grouped errors.