Search RU
Tasks / Concurrency / asyncio queue, cancellation and parallelism
Statement medium

asyncio queue, cancellation and parallelism

`process_batch(items, handler, *, workers=2, timeout=1.0)` processes a batch of
items with a pool of `workers` coroutines.

- `items` — a list of dicts `{"id": ..., "payload": ...}`; `id` is a non-empty
string, unique within the batch;
- `handler(payload)` — an async function;
- each item is processed with the `timeout`;
- no more than `workers` handlers run at the same time;
- result order does not matter, `timed_out` order follows `items`.

Return:

```python
{
"results": {id: result},
"errors": {id: "error text"},
"timed_out": [id, ...],
}
```

Rules:

- a handler exception goes to `errors`, the other items keep processing;
- a timeout goes to `timed_out`, and the handler **is cancelled**;
- when `process_batch` is cancelled from outside, all workers are cancelled and
do not stay in `asyncio.all_tasks()`;
- empty list — empty report;
- `workers < 1`, `timeout <= 0`, a duplicate `id` or an item without `payload` —
`ValueError`.

Run tests through `asyncio.run` inside sync functions: `pytest-asyncio` is not
installed.

Write tests for: a successful batch, the parallelism bound, one failing item,
a timeout with cancellation, external cancellation without orphans, empty input
and invalid arguments.

concurrencyasyncioqueuecancellationtimeout
test_solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

How do you prove the pool is actually parallel and not merely "async"?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts