From 60b1c525228d542c63b90d9a5e7a4128ccba981f Mon Sep 17 00:00:00 2001 From: Greg Aker Date: Fri, 20 Nov 2026 14:42:52 -0600 Subject: [PATCH] Start new tasks as soon as a running task finishes When every slot was busy, the worker slept for minimum_check_interval before it looked for finished tasks. Throughput was therefore capped at concurrency / minimum_check_interval: 4 tasks/s per slot for Worker() (250 ms) and 10 for `docket worker` (100 ms), however fast tasks ran. The worker now waits on its active tasks with FIRST_COMPLETED, using the same interval as a timeout. docket-rs already waits this way with JoinSet::join_next(). test_waiter_woken_before_its_safeguard_exists_cancels_the_safeguard polled for the woken waiter's "queued" state. The worker now claims and finishes the woken task before the poll runs, so the test checks that the state has left "scheduled". Co-Authored-By: Claude Opus 5.5 --- loq.toml | 2 +- python/src/docket/worker.py | 7 +++++-- python/tests/concurrency_limits/test_waiter_safeguard.py | 5 ++++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/loq.toml b/loq.toml index 338fa617..1fa43723 100644 --- a/loq.toml +++ b/loq.toml @@ -12,7 +12,7 @@ max_lines = 750 # Source files that still need exceptions above 750 [[rules]] path = "python/src/docket/worker.py" -max_lines = 1479 +max_lines = 1482 [[rules]] path = "python/src/docket/cli/__init__.py" diff --git a/python/src/docket/worker.py b/python/src/docket/worker.py index 4a90f0a0..f69b0813 100644 --- a/python/src/docket/worker.py +++ b/python/src/docket/worker.py @@ -839,8 +839,11 @@ async def process_completed_tasks() -> None: await process_completed_tasks() available_slots = self.concurrency - len(active_tasks) if available_slots <= 0: - await asyncio.sleep( - self.minimum_check_interval.total_seconds() + # Wake as soon as a task frees a slot. + await asyncio.wait( + active_tasks, + timeout=self.minimum_check_interval.total_seconds(), + return_when=asyncio.FIRST_COMPLETED, ) continue sources = [get_new_deliveries] diff --git a/python/tests/concurrency_limits/test_waiter_safeguard.py b/python/tests/concurrency_limits/test_waiter_safeguard.py index b65ad957..621eba13 100644 --- a/python/tests/concurrency_limits/test_waiter_safeguard.py +++ b/python/tests/concurrency_limits/test_waiter_safeguard.py @@ -37,9 +37,12 @@ async def the_task( finished.append(name) async def is_woken(task_key: str) -> bool: + # A parked waiter's state is "scheduled", and the wake sets "queued". + # The worker can claim and finish the woken task before this probe + # runs, so any state past "scheduled" means the wake happened. async with docket.redis() as redis: state = await redis.hget(docket.runs_key(task_key), "state") - return state == b"queued" + return state is not None and state != b"scheduled" add = docket.add