concurrency
concurrency
¶
Live-resizable concurrency limiter for the conductor (#231).
ConcurrencyGate is a counting gate with a mutable limit. It exists
because the conductor must adjust max_concurrent_jobs on a SIGHUP config
reload without orphaning in-flight job acquisitions.
The previous approach replaced the asyncio.Semaphore object on reload. That
is a broken accounting model: in-flight jobs hold the old object and release
into it, while the new object starts with all permits free and no knowledge of
the running jobs — so lowering the limit immediately over-admits, and the error
compounds across reloads. ("Single-threaded asyncio" prevents data races on the
attribute, not this semantic orphaning.)
This gate tracks _limit and _acquired explicitly and resizes in place
via :meth:set_limit. In-flight holders are never affected — the limit tightens
as they drain (a lower never kills running work; it only blocks new admissions
until _acquired falls below the new limit).
Wakeup model: an :class:asyncio.Event re-check loop. A woken waiter re-checks
_acquired < _limit and increments the counter itself, synchronously, with
no await between the check and the increment. Two consequences:
- Cancellation-safe by construction. A waiter cancelled at
await wait()never incremented_acquired(the increment lives in the branch that returns), so there is no reserved permit to reclaim — no cleanup logic to get wrong, and no granted-then-cancelled deadlock hole. - Not strictly FIFO (eventual admission). On each release/resize all waiters
wake and re-check; whichever the loop schedules first wins. Job admission does
not require FIFO (
asyncio.Semaphoreitself is not FIFO), and the herd is bounded bymax_concurrent_jobs, so the re-check cost is negligible.
.. warning::
Relies on single-threaded asyncio: the no-await-between-check-and-clear
invariant is what prevents lost wakeups. Do not call from threads or
executors.
Classes¶
ConcurrencyGate
¶
An async concurrency limiter whose limit can be changed at runtime.
Source code in src/marianne/daemon/concurrency.py
Attributes¶
Methods:¶
acquire
async
¶
Acquire a slot, blocking until acquired < limit.
Source code in src/marianne/daemon/concurrency.py
release
¶
Release a held slot and wake any waiters.
set_limit
¶
Change the limit in place. Raises wake waiters; lowers tighten as running work drains. Never affects in-flight holders.