Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

fix(runner): carry the GPU assignment into subprocess mode, and stop serializing every GPU (#2390)

Sai Nithin Goud Kurremula40b1c2bd336c
diff --git a/docs/src/content/docs/programming_guide/function.mdx b/docs/src/content/docs/programming_guide/function.mdx
index 664ef01b..5b672370 100644
--- a/docs/src/content/docs/programming_guide/function.mdx
+++ b/docs/src/content/docs/programming_guide/function.mdx
@@ -1134,7 +1134,7 @@ Common use cases:
### Runner
-The `runner` <Lang only="python">parameter</Lang><Lang only="rust">argument</Lang> allows functions to execute in a specific context, such as a dedicated GPU runner that serializes GPU workloads.
+The `runner` <Lang only="python">parameter</Lang><Lang only="rust">argument</Lang> allows functions to execute in a specific context, such as the GPU runner, which limits how many calls share each GPU.
<Lang only="python">
@@ -1149,7 +1149,7 @@ Like batching, a runner requires an async interface, so it is always set with `@
```python
@coco.fn.as_async(runner=coco.GPU)
def gpu_inference(data: bytes) -> bytes:
- # Runs with GPU serialization
+ # Runs on the GPU runner
return model.predict(data)
# External usage: async
@@ -1184,10 +1184,23 @@ let result = whole_gpu(&ctx, item).await?;
The `coco.GPU` runner:
-- By default, runs in-process with all functions sharing a queue for serial execution
-- Sync functions run on a dedicated GPU thread to avoid blocking the event loop
+- Takes a whole GPU per call by default; `coco.GPU(0.5)` asks for half of one, so two such calls can share a card. Inside the function, `coco.current_gpu()` returns the id of the GPU the call was given
+- Runs in-process by default. The GPU pool decides how many calls run at once: one at a time on a single GPU at the default fraction, more with several GPUs or a smaller fraction. Batched functions on the same runner also share one batch queue, so their batches follow the [`max_in_flight`](#batching) rule as well
+- Sync functions run on a dedicated GPU thread to avoid blocking the event loop. The thread cannot be interrupted, so a cancelled call keeps its GPU until the thread finishes
- Set the environment variable `COCOINDEX_RUN_GPU_IN_SUBPROCESS=1` to run in a subprocess for GPU memory isolation
+:::caution[Subprocess mode]
+`coco.current_gpu()` reports the same assignment inside the subprocess as it does in-process.
+
+Each GPU gets its own workers. A call runs on an idle worker of its GPU, and a new worker starts only when all of that GPU's workers are busy, up to a cap; workers stay resident for the life of the process. Each is a separate interpreter with its own CUDA context, costing hundreds of MB of device memory before your model allocates anything, and with its own copy of any model your function caches and its own allocator cache. A fractional runner like `coco.GPU(0.25)`, which lets four calls share a card, can therefore end up with four of each on that card.
+
+`CUDA_VISIBLE_DEVICES` is not set per worker, so `cuda:{coco.current_gpu()}` names the same device as it does in-process, and a function that ignores `coco.current_gpu()` can still reach a GPU it was not assigned.
+
+Cancelling a call returns right away, but its GPU is not released until the worker finishes. A worker that has already started cannot be interrupted, so the capacity stays held; otherwise the next call would be admitted onto a card that is still busy. A worker that is still running also keeps the process from exiting until it finishes.
+
+A call whose worker dies fails with `BrokenProcessPool` and is not retried: the component fails, nothing is written or memoized for it, and the next `app.update()` retries it cleanly. Calls on other workers keep running. If a worker dies while idle, the next call on that GPU goes to another worker, unless it reaches the dead one in the moment before the death is noticed, in which case that call fails too.
+:::
+
</Lang>
<Lang only="rust">
@@ -1232,7 +1245,7 @@ You can combine batching with a runner:
```python
@coco.fn.as_async(batching=True, max_batch_size=16, runner=coco.GPU)
def batch_gpu_embed(texts: list[str]) -> list[list[float]]:
- # Batched execution with GPU serialization
+ # Batched execution on the GPU runner
return gpu_model.encode(texts)
# External usage: async
diff --git a/python/cocoindex/_internal/runner.py b/python/cocoindex/_internal/runner.py
index 1a7c44ac..99bfd7fc 100644
--- a/python/cocoindex/_internal/runner.py
+++ b/python/cocoindex/_internal/runner.py
@@ -16,12 +16,11 @@ import os
import pickle
import threading
import multiprocessing as mp
-import warnings
from abc import ABC, abstractmethod
from concurrent.futures import Future, ProcessPoolExecutor, ThreadPoolExecutor
from concurrent.futures.process import BrokenProcessPool
from contextvars import Context, ContextVar
-from typing import Any, Callable, Coroutine, TypeVar, ParamSpec
+from typing import Any, Callable, Coroutine, NamedTuple, TypeVar, ParamSpec
from . import core
@@ -92,39 +91,78 @@ class Runner(ABC):
# ============================================================================
_WATCHDOG_INTERVAL_SECONDS = 10.0
-_pool_lock = threading.Lock()
-_pool: ProcessPoolExecutor | None = None
-
-
-def _get_pool() -> ProcessPoolExecutor:
- """Get or create the singleton subprocess pool."""
- global _pool
- with _pool_lock:
- if _pool is None:
- _pool = ProcessPoolExecutor(
- max_workers=1,
- initializer=_subprocess_init,
- initargs=(os.getpid(),),
- mp_context=mp.get_context("spawn"),
- )
- return _pool
+# Ceiling on subprocess workers per GPU. `GPUPool` decides how many calls run at once,
+# and admits at most `1/fraction` calls on one GPU; this only stops a tiny fraction from
+# spawning processes without bound. Past it, a call queues behind the least busy worker.
+_MAX_SUBPROCESS_WORKERS = 32
+
+
+class _Worker:
+ """One subprocess, as a single-worker executor, and the calls currently on it."""
+
+ __slots__ = ("executor", "calls")
-def _restart_pool(old_pool: ProcessPoolExecutor | None = None) -> None:
- """Restart the subprocess pool if it died."""
- global _pool
- with _pool_lock:
- if old_pool is not None and _pool is not old_pool:
- return # Another thread already restarted
- prev_pool = _pool
- _pool = ProcessPoolExecutor(
+ def __init__(self) -> None:
+ self.executor = ProcessPoolExecutor(
max_workers=1,
initializer=_subprocess_init,
initargs=(os.getpid(),),
mp_context=mp.get_context("spawn"),
)
- if prev_pool is not None:
- prev_pool.shutdown(cancel_futures=True)
+ self.calls = 0
+
+
+_workers_lock = threading.Lock()
+# Workers per GPU id. A worker only ever serves the GPU its calls were given, so it
+# holds a CUDA context (and any model it caches) on that device only. Each worker is
+# its own executor, and a call goes to an idle one when there is one: a GPU gets a new
+# worker only when every worker it has is busy, and a worker that dies fails only the
+# calls on it.
+_workers: dict[int, list[_Worker]] = {}
+
+
+def _take_worker(gpu_id: int) -> _Worker:
+ """Assign the next call on `gpu_id` to an idle worker, else a new one, else (at the
+ cap) the least busy one."""
+ with _workers_lock:
+ workers = _workers.setdefault(gpu_id, [])
+ worker = min(workers, key=lambda w: w.calls, default=None)
+ if worker is None or (
+ worker.calls > 0 and len(workers) < _MAX_SUBPROCESS_WORKERS
+ ):
+ worker = _Worker()
+ workers.append(worker)
+ worker.calls += 1
+ return worker
+
+
+def _finish_call(gpu_id: int, worker: _Worker) -> None:
+ """Take a finished call off `worker`, and drop the worker if its process died.
+
+ Runs on the worker's own management thread when a call completes. A dead worker's
+ executor has already terminated its process and failed the calls on it, so all
+ that is left is to drop it. Shutting it down here would wait on this very thread:
+ 3.14 holds the executor's shutdown lock while it fails the calls.
+ """
+ with _workers_lock:
+ worker.calls -= 1
+ workers = _workers.get(gpu_id, [])
+ # Whether the process died, not whether the call raised `BrokenProcessPool`,
+ # which a user function may do itself. The executor sets this before it fails
+ # the calls.
+ if worker.executor._broken and worker in workers:
+ workers.remove(worker)
+
+
+def _discard_worker(gpu_id: int, worker: _Worker) -> None:
+ """Take a worker that failed to accept a call out of service."""
+ with _workers_lock:
+ workers = _workers.get(gpu_id, [])
+ if worker in workers:
+ workers.remove(worker)
+ # `wait=False`: do not block the event loop; calls already on it still finish.
+ worker.executor.shutdown(wait=False)
def _subprocess_init(parent_pid: int) -> None:
@@ -173,7 +211,11 @@ def _start_parent_watchdog(parent_pid: int) -> None:
def _execute_in_subprocess(payload_bytes: bytes) -> bytes:
"""Run in subprocess: unpack, execute, return pickled result."""
- fn, args, kwargs = pickle.loads(payload_bytes)
+ fn, args, kwargs, gpu_ids, fraction = pickle.loads(payload_bytes)
+ # ContextVars do not cross a process boundary, so the parent's assignment
+ # travels in the payload and is re-established here.
+ _current_gpus.set(gpu_ids)
+ _current_gpu_fraction.set(fraction)
result = fn(*args, **kwargs)
# Handle async callables (functions or callable objects with async __call__)
if asyncio.iscoroutine(result):
@@ -181,24 +223,81 @@ def _execute_in_subprocess(payload_bytes: bytes) -> bytes:
return pickle.dumps(result, protocol=pickle.HIGHEST_PROTOCOL)
-async def _submit_to_pool_async(fn: Callable[..., Any], *args: Any) -> Any:
- """Submit work to pool and wait asynchronously."""
- loop = asyncio.get_running_loop()
+class _Submission(NamedTuple):
+ worker: _Worker
+ future: Future[bytes]
+
+
+def _submit(gpu_id: int, payload: bytes) -> _Submission:
+ """Queue `payload` on a worker for `gpu_id`."""
while True:
- pool = _get_pool()
+ worker = _take_worker(gpu_id)
try:
- return await loop.run_in_executor(pool, fn, *args)
+ return _Submission(
+ worker, worker.executor.submit(_execute_in_subprocess, payload)
+ )
except BrokenProcessPool:
- _restart_pool(old_pool=pool)
-
-
-async def execute_in_subprocess(fn: Callable[..., R], *args: Any, **kwargs: Any) -> R:
+ # The worker died while idle and its executor has noticed, so the call never
+ # reached it: drop the worker and give the call to another.
+ _finish_call(gpu_id, worker)
+ except BaseException:
+ _finish_call(gpu_id, worker)
+ _discard_worker(gpu_id, worker)
+ raise
+
+
+async def execute_in_subprocess(
+ gpu_ids: list[int],
+ fraction: float,
+ release: Callable[[], None],
+ fn: Callable[..., R],
+ /,
+ *args: Any,
+ **kwargs: Any,
+) -> R:
"""Execute a function in a subprocess and return the result.
- The function and all arguments must be picklable.
+ The function and all arguments must be picklable. ``gpu_ids`` and ``fraction``
+ are the caller's GPU assignment; the call runs on a worker of its first GPU. The
+ parameters before ``*args`` are positional-only, so the submitted function's
+ keyword arguments cannot collide with them.
+
+ ``release`` hands the assignment back to the GPU pool, and is called exactly
+ once. Once the call is queued, that happens when its future completes, not when
+ this coroutine returns. A started worker cannot be interrupted, so a cancelled
+ call that a worker has started keeps its GPU until the work is off the device,
+ and the next call is not admitted onto a card that is still busy.
+
+ A call whose worker dies fails with ``BrokenProcessPool`` and is not retried, so
+ a function that reliably crashes fails once instead of respawning forever. The
+ engine handles that like any failed component: nothing is written or memoized
+ for it, and the next update retries it. Only a call that never reached its
+ worker, because the worker had already died while idle, is given to another.
"""
- payload = pickle.dumps((fn, args, kwargs), protocol=pickle.HIGHEST_PROTOCOL)
- result_bytes = await _submit_to_pool_async(_execute_in_subprocess, payload)
+ gpu_id = gpu_ids[0]
+ try:
+ payload = pickle.dumps(
+ (fn, args, kwargs, gpu_ids, fraction), protocol=pickle.HIGHEST_PROTOCOL
+ )
+ worker, future = _submit(gpu_id, payload)
+ except BaseException:
+ release()
+ raise
+
+ def _on_done(_: Future[bytes]) -> None:
+ try:
+ # The worker is marked idle before the GPU goes back, so the call that the
+ # release admits finds it idle instead of starting another worker.
+ _finish_call(gpu_id, worker)
+ finally:
+ release()
+
+ # On the `concurrent.futures.Future`, not the asyncio wrapper: the wrapper is
+ # cancelled as soon as the caller is, which would release the GPU while the
+ # worker is still on it. Added before `wrap_future` adds its own callback, so
+ # the GPU is back in the pool by the time the caller sees the result.
+ future.add_done_callback(_on_done)
+ result_bytes = await asyncio.wrap_future(future)
return pickle.loads(result_bytes) # type: ignore[no-any-return]
@@ -239,7 +338,12 @@ def current_gpu_fraction() -> float | None:
def _run_with_gpu_context(
- gpu_ids: list[int], fraction: float, fn: Callable[..., R], *args: Any, **kwargs: Any
+ gpu_ids: list[int],
+ fraction: float,
+ fn: Callable[..., R],
+ /,
+ *args: Any,
+ **kwargs: Any,
) -> R:
tok_gpus = _current_gpus.set(gpu_ids)
tok_frac = _current_gpu_fraction.set(fraction)
@@ -292,6 +396,12 @@ class EmptyContextThreadPoolExecutor(ThreadPoolExecutor):
return Context().run(super().submit, fn, *args, **kwargs)
+class _GPUAssignment(NamedTuple):
+ gpu_id: int
+ # Gives the GPU back to the pool it was acquired from.
+ release: Callable[[], None]
+
+
class GPURunner(Runner):
"""Runner for GPU workloads with fractional allocation support.
@@ -301,9 +411,11 @@ class GPURunner(Runner):
The assigned GPU id(s) are available inside the function via
``coco.current_gpu()`` (first id) and ``coco.current_gpus()`` (full list).
The allocated fraction is available via ``coco.current_gpu_fraction()``.
- For multi-GPU subprocess mode (where ``CUDA_VISIBLE_DEVICES`` must be set
- per-process), use in-process mode (the default) until per-GPU subprocess
- pools are implemented.
+ Subprocess mode reports the same assignment as in-process mode: the id is
+ carried in the payload and re-established in the child. Each GPU has its own
+ workers, so a worker only serves the GPU its calls were given.
+ ``CUDA_VISIBLE_DEVICES`` is left unset, so ``cuda:{coco.current_gpu()}`` names
+ the same device in both modes.
"""
_fraction: float
@@ -337,11 +449,17 @@ class GPURunner(Runner):
)
return self._gpu_executor
- async def _acquire_gpu(self) -> int:
- return await _get_default_gpu_pool().acquire(self._fraction)
+ async def _acquire_gpu(self) -> _GPUAssignment:
+ """Acquire a GPU.
- def _release_gpu(self, gpu_id: int) -> None:
- _get_default_gpu_pool().release(gpu_id, self._fraction)
+ The release is bound to the pool the GPU came from, so it returns the capacity
+ there even if `configure_gpu_pool` has replaced the default pool since.
+ """
+ gpu_pool = _get_default_gpu_pool()
+ gpu_id = await gpu_pool.acquire(self._fraction)
+ return _GPUAssignment(
+ gpu_id, functools.partial(gpu_pool.release, gpu_id, self._fraction)
+ )
async def run(
self, fn: Callable[P, Coroutine[Any, Any, R]], *args: P.args, **kwargs: P.kwargs
@@ -352,20 +470,26 @@ class GPURunner(Runner):
- In-process (default): runs directly on the event loop.
- Subprocess mode: via execute_in_subprocess (asyncio.run() in subprocess).
"""
- gpu_id = await self._acquire_gpu()
- gpu_ids = [gpu_id]
+ assignment = await self._acquire_gpu()
+ gpu_ids = [assignment.gpu_id]
+ if self._should_use_subprocess():
+ return await execute_in_subprocess(
+ gpu_ids,
+ self._fraction,
+ assignment.release,
+ # The subprocess runs a coroutine function through `asyncio.run()`.
+ fn, # type: ignore[arg-type]
+ *args,
+ **kwargs,
+ )
tok_gpus = _current_gpus.set(gpu_ids)
tok_frac = _current_gpu_fraction.set(self._fraction)
try:
- if self._should_use_subprocess():
- _warn_subprocess_multi_gpu()
- # Type ignore: execute_in_subprocess handles async fns via asyncio.run() internally
- return await execute_in_subprocess(fn, *args, **kwargs) # type: ignore[arg-type]
return await fn(*args, **kwargs)
finally:
_current_gpus.reset(tok_gpus)
_current_gpu_fraction.reset(tok_frac)
- self._release_gpu(gpu_id)
+ assignment.release()
async def run_sync_fn(
self, fn: Callable[P, R], *args: P.args, **kwargs: P.kwargs
@@ -376,40 +500,28 @@ class GPURunner(Runner):
- In-process (default): offloads to the dedicated GPU thread pool.
- Subprocess mode: via execute_in_subprocess.
"""
- gpu_id = await self._acquire_gpu()
- gpu_ids = [gpu_id]
+ assignment = await self._acquire_gpu()
+ gpu_ids = [assignment.gpu_id]
+ if self._should_use_subprocess():
+ return await execute_in_subprocess(
+ gpu_ids,
+ self._fraction,
+ assignment.release,
+ fn,
+ *args,
+ **kwargs,
+ )
try:
- if self._should_use_subprocess():
- _warn_subprocess_multi_gpu()
- return await execute_in_subprocess(fn, *args, **kwargs)
- loop = asyncio.get_running_loop()
- return await loop.run_in_executor(
- self._get_gpu_executor(),
- functools.partial(
- _run_with_gpu_context, gpu_ids, self._fraction, fn, *args, **kwargs
- ),
+ future = self._get_gpu_executor().submit(
+ _run_with_gpu_context, gpu_ids, self._fraction, fn, *args, **kwargs
)
- finally:
- self._release_gpu(gpu_id)
+ except BaseException:
+ assignment.release()
+ raise
+ # As in subprocess mode: a started thread cannot be interrupted, so the GPU goes
+ # back when the thread finishes, not when this call returns or is cancelled.
+ future.add_done_callback(lambda _: assignment.release())
+ return await asyncio.wrap_future(future)
GPU = GPURunner(fraction=1.0)
-
-_subprocess_multi_gpu_warned = False
-
-
-def _warn_subprocess_multi_gpu() -> None:
- global _subprocess_multi_gpu_warned
- if _subprocess_multi_gpu_warned:
- return
- _subprocess_multi_gpu_warned = True
- pool = _get_default_gpu_pool()
- if pool.num_gpus > 1:
- warnings.warn(
- f"COCOINDEX_RUN_GPU_IN_SUBPROCESS=1 with num_gpus={pool.num_gpus}: "
- "subprocess mode does not yet support per-GPU CUDA_VISIBLE_DEVICES. "
- "All subprocess calls run on the same GPU regardless of pool "
- "assignment. Use in-process mode for multi-GPU support.",
- UserWarning,
- stacklevel=4,
- )
diff --git a/python/tests/core/test_gpu_subprocess.py b/python/tests/core/test_gpu_subprocess.py
new file mode 100644
index 00000000..1ad85ffe
--- /dev/null
+++ b/python/tests/core/test_gpu_subprocess.py
@@ -0,0 +1,603 @@
+"""Tests for the GPU runner's subprocess mode.
+
+Covers the GPU assignment reaching the subprocess, calls running in parallel, one
+GPU per worker, crashes and dead workers, and when a cancelled call gives its GPU
+back. The last of these also holds in-process, so it is tested in both modes.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import signal
+import threading
+import time
+import uuid
+from collections.abc import Callable, Iterator
+from concurrent.futures import ProcessPoolExecutor
+from concurrent.futures.process import BrokenProcessPool
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+from cocoindex._internal import runner as _runner_mod
+from cocoindex._internal.runner import (
+ GPURunner,
+ _get_default_gpu_pool,
+ configure_gpu_pool,
+)
+
+# Seconds a call in a worker waits for the test, or for its peers, before giving up.
+# Kept under the module timeout so a stuck call fails its own test with a message.
+_CHILD_WAIT_TIMEOUT = 75.0
+
+# Seconds the test itself waits for a condition or a call.
+_WAIT_TIMEOUT = 60.0
+
+# Each test starts `spawn` interpreters that import the Rust extension, which the
+# project-wide 30s budget does not cover on a cold runner.
+pytestmark = pytest.mark.timeout(90)
+
+
[email protected](autouse=True)
+def _subprocess_mode(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ """Run GPU work in subprocesses, from fresh pools, and clean up after."""
+ monkeypatch.setenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS", "1")
+ monkeypatch.setattr(_runner_mod, "_default_gpu_pool", None)
+ monkeypatch.setattr(_runner_mod, "_workers", {})
+ try:
+ yield
+ finally:
+ for workers in _runner_mod._workers.values():
+ for worker in workers:
+ # `wait=False`: joining a worker has no timeout, and a wedged one
+ # would hang teardown until pytest-timeout kills the process.
+ worker.executor.shutdown(wait=False, cancel_futures=True)
+
+
+def _wait_for_file(path: str) -> None:
+ """In a worker: block until `path` exists."""
+ deadline = time.monotonic() + _CHILD_WAIT_TIMEOUT
+ while not os.path.exists(path):
+ if time.monotonic() > deadline:
+ raise TimeoutError(f"{path} never appeared")
+ time.sleep(0.01)
+
+
+def _probe() -> tuple[int | None, float | None, int]:
+ """Report the GPU context and pid visible inside the subprocess."""
+ return coco.current_gpu(), coco.current_gpu_fraction(), os.getpid()
+
+
+async def _aprobe() -> tuple[int | None, float | None, int]:
+ """Async probe: goes through `GPURunner.run` and the child's `asyncio.run`."""
+ return coco.current_gpu(), coco.current_gpu_fraction(), os.getpid()
+
+
+def _probe_together(rendezvous: str, expected: int) -> tuple[int | None, int]:
+ """Report the assignment, but only once every peer has also started.
+
+ Each call announces itself in `rendezvous` and waits for the others, so it
+ cannot return unless all `expected` calls are resident at the same time. Were
+ they to run one after another this raises, rather than merely running slowly.
+ """
+ gpu = coco.current_gpu()
+ open(os.path.join(rendezvous, uuid.uuid4().hex), "w").close()
+ deadline = time.monotonic() + _CHILD_WAIT_TIMEOUT
+ while len(os.listdir(rendezvous)) < expected:
+ if time.monotonic() > deadline:
+ raise TimeoutError(
+ f"only {len(os.listdir(rendezvous))} of {expected} calls "
+ "were running at once"
+ )
+ time.sleep(0.01)
+ return gpu, os.getpid()
+
+
+def _hold_until(started: str, release: str) -> str:
+ """Mark that the call started, then stay on the worker until `release` exists."""
+ open(started, "w").close()
+ _wait_for_file(release)
+ return "held"
+
+
+def _log_span(log: str, tag: str, release: str | None = None) -> str:
+ """Log when the call starts and ends; in between, wait for `release` if given."""
+ with open(log, "a") as handle:
+ print(f"{tag}:start", time.monotonic(), file=handle)
+ if release is not None:
+ _wait_for_file(release)
+ with open(log, "a") as handle:
+ print(f"{tag}:end", time.monotonic(), file=handle)
+ return tag
+
+
+async def _await_condition(
+ condition: Callable[[], object], what: str, task: asyncio.Task[Any] | None = None
+) -> None:
+ """Block until `condition()` holds.
+
+ If `task` finishes first, its exception is raised here rather than the test
+ waiting out its timeout and reporting only `what`.
+ """
+ deadline = time.monotonic() + _WAIT_TIMEOUT
+ while not condition():
+ if task is not None and task.done():
+ task.result()
+ raise AssertionError(f"{what}: the call returned early")
+ assert time.monotonic() < deadline, what
+ await asyncio.sleep(0.05)
+
+
+def _kill_worker() -> None:
+ """Take the worker process down, the way a native crash would."""
+ os._exit(7)
+
+
+def _raise_broken_process_pool() -> None:
+ """A user function that raises `BrokenProcessPool` itself, from a healthy worker."""
+ raise BrokenProcessPool("raised by the function, not by a dying worker")
+
+
+def _identity(value: object) -> object:
+ return value
+
+
+def _echo_kwargs(**kwargs: object) -> dict[str, object]:
+ return kwargs
+
+
+async def _aecho_kwargs(**kwargs: object) -> dict[str, object]:
+ return kwargs
+
+
+def _cuda_probe() -> tuple[int | None, int | None, int]:
+ """Run a real CUDA kernel on the assigned device; report where it landed."""
+ import torch
+
+ assigned = coco.current_gpu()
+ if assigned is None:
+ return None, None, os.getpid()
+ x = torch.randn(256, 256, device=f"cuda:{assigned}")
+ (x @ x.T).sum().item() # force a kernel launch
+ return assigned, x.device.index, os.getpid()
+
+
+def _cuda_device_count() -> int:
+ try:
+ import torch
+ except ImportError:
+ return 0
+ return torch.cuda.device_count() if torch.cuda.is_available() else 0
+
+
+async def _assert_gpu_held_until(release: Path) -> None:
+ """Check the one GPU stays fully taken until `release` is created, then frees up.
+
+ A full-GPU acquire is the direct test: it can only succeed once the cancelled
+ call's capacity is back in the pool.
+ """
+ gpu_pool = _get_default_gpu_pool()
+ with pytest.raises(TimeoutError):
+ await asyncio.wait_for(gpu_pool.acquire(1.0), 1.0)
+ release.touch()
+ gpu = await asyncio.wait_for(gpu_pool.acquire(1.0), _WAIT_TIMEOUT)
+ gpu_pool.release(gpu, 1.0)
+
+
+# A runner of its own: functions cache their batch queue, and the queue holds a
+# reference to the event loop it was first used on.
+_FN_RUNNER = GPURunner(fraction=1.0)
+
+
[email protected]_async(runner=_FN_RUNNER)
+def _held_via_fn(log: str, release: str) -> str:
+ return _log_span(log, "held", release)
+
+
[email protected]_async(runner=_FN_RUNNER)
+def _probe_via_fn(log: str) -> tuple[int | None, int]:
+ return coco.current_gpu(), os.getpid()
+
+
+async def test_subprocess_receives_gpu_assignment() -> None:
+ """current_gpu() in the subprocess is the id the GPU pool handed out."""
+ configure_gpu_pool(1)
+ gpu, fraction, pid = await GPURunner(fraction=1.0).run_sync_fn(_probe)
+ assert gpu == 0
+ assert fraction == 1.0
+ assert pid != os.getpid() # it really did run in a subprocess
+
+
+async def test_async_fn_receives_gpu_assignment() -> None:
+ """`run()` propagates the assignment too, not just `run_sync_fn()`."""
+ configure_gpu_pool(2)
+ gpu, fraction, pid = await GPURunner(fraction=1.0).run(_aprobe)
+ assert gpu in (0, 1)
+ assert fraction == 1.0
+ assert pid != os.getpid()
+
+
+async def test_worker_reports_each_calls_own_assignment() -> None:
+ """A reused worker must not report the previous call's context."""
+ configure_gpu_pool(1)
+ half = GPURunner(fraction=0.5)
+ full = GPURunner(fraction=1.0)
+
+ seen = [
+ (await runner.run_sync_fn(_probe))[1] for runner in (half, full, half, full)
+ ]
+ assert seen == [0.5, 1.0, 0.5, 1.0]
+
+
[email protected]("in_subprocess", [True, False])
[email protected]("method", ["run_sync_fn", "run"])
+async def test_kwargs_named_like_runner_parameters_reach_the_function(
+ monkeypatch: pytest.MonkeyPatch, in_subprocess: bool, method: str
+) -> None:
+ """A function may take keyword arguments named like the runner's own parameters.
+
+ They must reach the function, and must not fail the call after the GPU was
+ acquired, which would leak it and hang every later call.
+ """
+ if not in_subprocess:
+ monkeypatch.delenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS")
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=1.0)
+ call = (
+ runner.run_sync_fn(_echo_kwargs, gpu_ids=1, fraction=2, release=3)
+ if method == "run_sync_fn"
+ else runner.run(_aecho_kwargs, gpu_ids=1, fraction=2, release=3)
+ )
+ assert await call == {"gpu_ids": 1, "fraction": 2, "release": 3}
+ # The GPU came back, so a second full-GPU call is admitted.
+ assert await asyncio.wait_for(runner.run_sync_fn(_echo_kwargs), _WAIT_TIMEOUT) == {}
+
+
+async def test_an_unpicklable_argument_fails_without_leaking_the_gpu() -> None:
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=1.0)
+ with pytest.raises(TypeError):
+ await runner.run_sync_fn(_identity, threading.Lock())
+ assert await asyncio.wait_for(runner.run_sync_fn(_identity, 1), _WAIT_TIMEOUT) == 1
+
+
+async def test_crashing_call_surfaces_instead_of_respawning_forever() -> None:
+ """A call that kills its worker every time must fail, not retry endlessly."""
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=1.0)
+ with pytest.raises(BrokenProcessPool):
+ await runner.run_sync_fn(_kill_worker)
+ # A new worker takes the next call.
+ gpu, _, _ = await runner.run_sync_fn(_probe)
+ assert gpu == 0
+
+
+async def test_real_cuda_work_lands_on_the_assigned_device() -> None:
+ """End to end on real hardware: the tensor lands on the assigned GPU."""
+ # Checked here rather than in `skipif`: every worker imports this module to
+ # unpickle the helpers, and a module-level check would import torch in each.
+ n = _cuda_device_count()
+ if n == 0:
+ pytest.skip("needs a CUDA device")
+ configure_gpu_pool(n)
+ runner = GPURunner(fraction=1.0)
+ assigned, ran_on, pid = await runner.run_sync_fn(_cuda_probe)
+ assert assigned is not None
+ assert ran_on == assigned
+ assert pid != os.getpid()
+
+
+async def test_calls_on_different_gpus_run_at_the_same_time(tmp_path: Path) -> None:
+ configure_gpu_pool(4)
+ runner = GPURunner(fraction=1.0)
+ results = await asyncio.gather(
+ *(runner.run_sync_fn(_probe_together, str(tmp_path), 4) for _ in range(4))
+ )
+ assert sorted(gpu for gpu, _ in results if gpu is not None) == [0, 1, 2, 3]
+ assert len({pid for _, pid in results}) == 4
+
+
+async def test_fractional_calls_share_a_gpu_concurrently(tmp_path: Path) -> None:
+ """Calls sharing one GPU by fraction must also run at the same time."""
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=0.25)
+ results = await asyncio.gather(
+ *(runner.run_sync_fn(_probe_together, str(tmp_path), 4) for _ in range(4))
+ )
+ assert all(gpu == 0 for gpu, _ in results)
+ assert len({pid for _, pid in results}) == 4
+
+
[email protected]("fraction, max_workers", [(1.0, 1), (0.5, 2)])
+async def test_a_gpu_starts_a_worker_only_when_its_workers_are_busy(
+ fraction: float, max_workers: int
+) -> None:
+ """A GPU must not run more workers than it ever has calls at once.
+
+ Every worker holds a CUDA context and its own copy of any model the function
+ caches. Many callers queue here, so each finished call is followed at once by
+ the call its release admits; that call must find the idle worker rather than
+ start another. A `ProcessPoolExecutor` shared by the GPU's calls does start
+ another: it marks a worker idle only after the finished call's callbacks have
+ released the GPU.
+ """
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=fraction)
+ pids: set[int] = set()
+
+ async def caller() -> None:
+ for _ in range(25):
+ pids.add((await runner.run_sync_fn(_probe))[2])
+
+ await asyncio.gather(*(caller() for _ in range(16)))
+ assert len(pids) <= max_workers
+ assert len(_runner_mod._workers[0]) <= max_workers
+
+
+async def test_pool_stays_wide_after_a_crash(tmp_path: Path) -> None:
+ """After a crash, calls sharing the GPU must still run at the same time."""
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=0.5)
+ with pytest.raises(BrokenProcessPool):
+ await runner.run_sync_fn(_kill_worker)
+
+ results = await asyncio.gather(
+ *(runner.run_sync_fn(_probe_together, str(tmp_path), 2) for _ in range(2))
+ )
+ assert len({pid for _, pid in results}) == 2
+
+
+async def test_a_crash_fails_only_the_call_on_that_worker(tmp_path: Path) -> None:
+ """A dying worker must not take down a call running beside it on the same GPU."""
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=0.5)
+ started, release = tmp_path / "started", tmp_path / "release"
+
+ survivor = asyncio.create_task(
+ runner.run_sync_fn(_hold_until, str(started), str(release))
+ )
+ try:
+ await _await_condition(
+ started.exists, "the surviving call never started", survivor
+ )
+ # The survivor's worker is busy, so this call gets a worker of its own.
+ with pytest.raises(BrokenProcessPool):
+ await runner.run_sync_fn(_kill_worker)
+ finally:
+ release.touch()
+ assert await survivor == "held"
+
+
+async def test_a_function_raising_broken_process_pool_keeps_its_worker() -> None:
+ """Only a worker whose process died is dropped, not one whose call raised."""
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=1.0)
+ _, _, pid = await runner.run_sync_fn(_probe)
+ with pytest.raises(BrokenProcessPool, match="raised by the function"):
+ await runner.run_sync_fn(_raise_broken_process_pool)
+ assert (await runner.run_sync_fn(_probe))[2] == pid
+ assert len(_runner_mod._workers[0]) == 1
+
+
+async def test_a_worker_that_fails_to_take_a_call_is_taken_out_of_service(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A submit that fails must not leave a phantom call on the worker.
+
+ Its worker would never look idle again, so the GPU would start a second worker
+ for calls that never overlap.
+ """
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=1.0)
+ await runner.run_sync_fn(_probe)
+
+ submit = ProcessPoolExecutor.submit
+ failures = iter([OSError("could not start the worker")])
+
+ def flaky_submit(self: ProcessPoolExecutor, *args: Any, **kwargs: Any) -> Any:
+ for error in failures:
+ raise error
+ return submit(self, *args, **kwargs)
+
+ monkeypatch.setattr(ProcessPoolExecutor, "submit", flaky_submit)
+ with pytest.raises(OSError, match="could not start the worker"):
+ await runner.run_sync_fn(_probe)
+ assert _runner_mod._workers[0] == []
+
+ for _ in range(3):
+ await runner.run_sync_fn(_probe)
+ assert [worker.calls for worker in _runner_mod._workers[0]] == [0]
+
+
+async def test_each_worker_serves_only_one_gpu() -> None:
+ """A worker must not move between GPUs.
+
+ A process that has run work on a GPU keeps a CUDA context there, plus its
+ allocator's cache and any model it caches per device, until it exits. A worker
+ serving every GPU would hold one of each on every card. Holding one GPU from the
+ parent steers each call onto the other, so the calls alternate between them.
+ """
+ configure_gpu_pool(2)
+ gpu_pool = _get_default_gpu_pool()
+ runner = GPURunner(fraction=1.0)
+ served: dict[int, set[int | None]] = {}
+ held = await gpu_pool.acquire(1.0)
+ for _ in range(4):
+ gpu, _, pid = await runner.run_sync_fn(_probe)
+ assert gpu is not None and gpu != held
+ served.setdefault(pid, set()).add(gpu)
+ # The call's GPU is free again: hold it, so the next call gets the other one.
+ other = await gpu_pool.acquire(1.0)
+ gpu_pool.release(held, 1.0)
+ held = other
+ gpu_pool.release(held, 1.0)
+
+ assert set().union(*served.values()) == {0, 1}
+ assert all(len(gpus) == 1 for gpus in served.values()), (
+ f"a worker served more than one GPU: {served}"
+ )
+
+
+async def test_a_call_after_an_idle_worker_died_still_runs() -> None:
+ """A call must not fail on a worker that died while idle, since it never ran.
+
+ This covers a death the worker's executor has already noticed. A call that
+ reaches the worker in the moment before that still fails, which is why the
+ test waits for the executor first.
+ """
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=1.0)
+ _, _, pid = await runner.run_sync_fn(_probe)
+
+ # Kill the idle worker the way the OOM killer would.
+ os.kill(pid, getattr(signal, "SIGKILL", signal.SIGTERM))
+ executor = _runner_mod._workers[0][0].executor
+ await _await_condition(
+ lambda: executor._broken, "the executor never noticed its worker died"
+ )
+
+ gpu, _, new_pid = await runner.run_sync_fn(_probe)
+ assert gpu == 0
+ assert new_pid != pid
+
+
+async def test_cancelled_call_keeps_the_gpu_until_its_worker_stops(
+ tmp_path: Path,
+) -> None:
+ """A cancelled call must not hand its GPU back while the worker is still on it.
+
+ The child cannot be interrupted once it has started. Releasing the capacity at
+ cancellation time therefore admits the next call onto a card that is still busy,
+ which is how two full-GPU jobs end up on one device. The caller itself does not
+ wait for the worker: the GPU is held, not the caller.
+ """
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=1.0)
+ log, release = tmp_path / "timeline.txt", tmp_path / "release"
+
+ first = asyncio.create_task(
+ runner.run_sync_fn(_log_span, str(log), "cancelled", str(release))
+ )
+ try:
+ await _await_condition(
+ lambda: log.exists() and "cancelled:start" in log.read_text(),
+ "the call never started",
+ first,
+ )
+ first.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first # returns while the worker is still held on `release`
+ assert "cancelled:end" not in log.read_text()
+ await _assert_gpu_held_until(release)
+ finally:
+ release.touch()
+
+
+async def test_cancelled_call_through_coco_fn_keeps_the_gpu(tmp_path: Path) -> None:
+ """The same, through `@coco.fn`, whose batcher cancels the call without awaiting it."""
+ configure_gpu_pool(1)
+ log, release = tmp_path / "timeline.txt", tmp_path / "release"
+
+ first = asyncio.create_task(_held_via_fn(str(log), str(release)))
+ try:
+ await _await_condition(
+ lambda: log.exists() and "held:start" in log.read_text(),
+ "the call never started",
+ first,
+ )
+ first.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first
+ await _assert_gpu_held_until(release)
+ finally:
+ release.touch()
+ # The runner still works afterwards.
+ gpu, pid = await _probe_via_fn(str(log))
+ assert gpu == 0
+ assert pid != os.getpid()
+
+
+async def test_in_process_cancelled_call_keeps_the_gpu_until_its_thread_stops(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """In-process, a started thread cannot be interrupted either."""
+ monkeypatch.delenv("COCOINDEX_RUN_GPU_IN_SUBPROCESS")
+ configure_gpu_pool(1)
+ runner = GPURunner(fraction=1.0)
+ log, release = tmp_path / "timeline.txt", tmp_path / "release"
+
+ first = asyncio.create_task(
+ runner.run_sync_fn(_log_span, str(log), "cancelled", str(release))
+ )
+ try:
+ await _await_condition(
+ lambda: log.exists() and "cancelled:start" in log.read_text(),
+ "the call never started",
+ first,
+ )
+ first.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first
+ await _assert_gpu_held_until(release)
+ finally:
+ release.touch()
+
+
+async def test_a_late_release_goes_back_to_the_pool_it_came_from(
+ tmp_path: Path,
+) -> None:
+ """A cancelled call's GPU must return to the pool it was taken from.
+
+ The GPU is released when the worker finishes, which can be after the caller was
+ cancelled and `configure_gpu_pool` swapped in a new pool. Releasing into the new
+ pool would hand out capacity it never gave, double-booking its GPU.
+ """
+ configure_gpu_pool(1)
+ old_pool = _get_default_gpu_pool()
+ runner = GPURunner(fraction=1.0)
+ started, release = tmp_path / "started", tmp_path / "release"
+
+ call = asyncio.create_task(
+ runner.run_sync_fn(_hold_until, str(started), str(release))
+ )
+ try:
+ await _await_condition(started.exists, "the call never started", call)
+ call.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await call
+
+ configure_gpu_pool(1)
+ new_pool = _get_default_gpu_pool()
+ held = await new_pool.acquire(1.0)
+ finally:
+ release.touch()
+
+ # The worker finishing hands the GPU back to the old pool...
+ assert await asyncio.wait_for(old_pool.acquire(1.0), _WAIT_TIMEOUT) == 0
+ # ...and not to the new one, whose only GPU is still held.
+ with pytest.raises(TimeoutError):
+ await asyncio.wait_for(new_pool.acquire(1.0), 0.5)
+ new_pool.release(held, 1.0)