Reproducible CPU Lab · PYTHON

Structured concurrency

Companion Writing
Structured Concurrency for Model Workloads in Python →

Bound the queue and the number of tasks, preserve result identity, and make failures cancel the work they own. A standard-library asyncio lab.

Run from the repository root (the directory containing labs). After downloading the archive, extract it and run from the extracted root.

sh
python3 -m unittest discover -s labs/python/concurrency -p "test_*.py" -v
python3 labs/python/concurrency/workload.py

Go requires 1.24 or newer. Python requires 3.11 or newer. The two LLM labs additionally require CPU-capable PyTorch in labs/.venv; see the collection instructions.

Tests use deterministic substitutes or synthetic tensors. No paid API, cloud service, model-weight download, GPU, or external project checkout is required. A failed test is a correctness issue to investigate; raw timing changes alone do not fail the tests.

Read the source and tests together. The article's code excerpts are extracted from marked regions in these files during the website build.

Source & Verification Files

Primary implementation expanded · Click any file header to toggle
Implementationworkload.py
63 lines
/labs/python/concurrency/workload.pyRaw file ↓
python
"""Bound task creation as well as active work. Python 3.11+, standard library."""

from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Sequence
from typing import TypeVar

T = TypeVar("T")
R = TypeVar("R")


# region:workload
async def run_bounded(
    items: Sequence[T],
    work: Callable[[T], Awaitable[R]],
    *,
    concurrency: int = 4,
    queue_size: int = 4,
    timeout: float = 5.0,
) -> list[R]:
    if concurrency < 1 or queue_size < 1 or timeout <= 0:
        raise ValueError("concurrency, queue_size, and timeout must be positive")
    queue: asyncio.Queue[tuple[int, T] | None] = asyncio.Queue(queue_size)
    results: dict[int, R] = {}

    async def produce() -> None:
        for index, item in enumerate(items):
            await queue.put((index, item))
        for _ in range(concurrency):
            await queue.put(None)

    async def consume() -> None:
        while True:
            entry = await queue.get()
            try:
                if entry is None:
                    return
                index, item = entry
                results[index] = await work(item)
            finally:
                queue.task_done()

    async with asyncio.timeout(timeout):
        async with asyncio.TaskGroup() as group:
            group.create_task(produce(), name="lab-producer")
            for index in range(concurrency):
                group.create_task(consume(), name=f"lab-worker-{index}")
    return [results[index] for index in range(len(items))]


# endregion:workload


async def main() -> None:
    async def square(value: int) -> int:
        await asyncio.sleep(0)
        return value * value

    print(await run_bounded(list(range(8)), square, concurrency=2, queue_size=2))


if __name__ == "__main__":
    asyncio.run(main())
Verification Suitetest_workload.py
94 lines
/labs/python/concurrency/test_workload.pyRaw file ↓
python
import asyncio
import unittest
from workload import run_bounded


class WorkloadTests(unittest.IsolatedAsyncioTestCase):
    async def test_order_and_bound(self):
        active = peak = 0
        saturated = asyncio.Event()

        async def work(value):
            nonlocal active, peak
            active += 1
            peak = max(peak, active)
            if active == 3:
                saturated.set()
            await saturated.wait()
            await asyncio.sleep(0)
            active -= 1
            return value * 2

        self.assertEqual(
            await run_bounded(list(range(100)), work, concurrency=3, queue_size=2),
            list(range(0, 200, 2)),
        )
        self.assertEqual(peak, 3)
        self.assertEqual(active, 0)

    async def test_failure_cleans_blocked_producer_and_workers(self):
        active = 0

        async def work(value):
            nonlocal active
            active += 1
            try:
                if value == 1:
                    raise ValueError("injected failure")
                await asyncio.Event().wait()
            finally:
                active -= 1

        with self.assertRaises(ExceptionGroup):
            await run_bounded(list(range(100)), work, concurrency=2, queue_size=1)
        self.assertEqual(active, 0)
        self.assertFalse(
            [
                t
                for t in asyncio.all_tasks()
                if t.get_name().startswith("lab-") and not t.done()
            ]
        )

    async def test_timeout_and_external_cancellation(self):
        entered = asyncio.Event()
        exited = asyncio.Event()

        async def work(_):
            entered.set()
            try:
                await asyncio.Event().wait()
            finally:
                exited.set()

        with self.assertRaises(TimeoutError):
            await run_bounded([1], work, timeout=0.02)
        self.assertTrue(exited.is_set())
        entered.clear()
        exited.clear()
        task = asyncio.create_task(run_bounded([1, 2, 3], work, queue_size=1))
        await entered.wait()
        task.cancel()
        with self.assertRaises(asyncio.CancelledError):
            await task
        self.assertTrue(exited.is_set())
        self.assertFalse(
            [
                t
                for t in asyncio.all_tasks()
                if t.get_name().startswith("lab-") and not t.done()
            ]
        )

    async def test_empty_and_invalid(self):
        async def identity(value):
            return value

        self.assertEqual(await run_bounded([], identity), [])
        for kwargs in ({"concurrency": 0}, {"queue_size": 0}, {"timeout": 0}):
            with self.assertRaises(ValueError):
                await run_bounded([1], identity, **kwargs)


if __name__ == "__main__":
    unittest.main()