Skip to content

Bound the thread join in idle worker-loop retirement so a blocked worker thread cannot stall dispatch — Closes #426, #447 - #442

Merged
conradbzura merged 4 commits into
wool-labs:mainfrom
mikemikimike:codex/issue-426-bounded-idle-worker-retirement
Nov 3, 2026
Merged

conradbzura merged 4 commits into
wool-labs:mainfrom
mikemikimike:codex/issue-426-bounded-idle-worker-retirement

Conversation

@mikemikimike

@mikemikimike mikemikimike commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Idle worker-loop retirement joined the retired thread without a bound. A task a routine leaves behind can block that thread indefinitely, and the join runs under the loop-pool lock, so one wedged thread stalled the next dispatch and the stop RPC with it. Bound the join by the teardown's own worst case — the shared drain budget plus one per-clear floor for each pool clear the teardown runs, 6.5 s at the defaults — and abandon a thread still running at the bound to the process-exit daemon reap, reported at warning level for idle retirement and at debug under a stop request, whose caller chose the bound it outlived.

Two design decisions carry the correctness argument. First, the join budget's provenance rides a ContextVar set only around a stop's own pool clear: a TTL-driven retirement snapshots the context captured when its expiry timer was armed, so an overlapping stop cannot divert the retirement onto the stop's budget by construction, and the finalizer execution-context contract this relies on is now documented on ResourcePool and pinned by tests. Second, the teardown budgets become constructor configuration on WorkerService, so the tests that exercise these bounds configure them through the API instead of patching private module constants.

LocalWorker sizes its stop-RPC deadline against this contract: twice a finite grace — StopRequest.timeout bounds the in-flight drain and the thread join in sequence — plus a public STOP_RPC_MARGIN covering the retirement worst case and one second of transport.

Closes #426
Closes #447

Proposed changes

Bound the idle-retirement join

Join the retired worker thread with a timeout of drain_timeout + len(clears) × min_clear_timeout instead of waiting indefinitely. The derivation follows the teardown's two clocks: the drain deadline starts on the worker loop while the join starts on the service loop, so the worst case is the drain budget, one floor for each clear a spent budget can starve, and the floor the first, never-starved clear does not spend — the handoff slack between the clocks and the loop's final stop and close callbacks. A thread still running at the bound is left to the daemon reap and the overrun is logged with its elapsed bound.

Carry the stop budget on a ContextVar

Map StopRequest.timeout once in _stop — negative to an unbounded join, zero to no synchronous join, positive to that many seconds — and set it on _stop_budget only around the stop's own _loop_pool.clear(). The teardown's snapshot keys both the join bound and the report level on the variable's presence: set means a caller chose the bound (debug), unset means idle retirement computed it (warning). Provenance is therefore a property of the finalizer's execution context, not of service-wide state a concurrent stop could latch.

Expose the teardown budgets as constructor configuration

Add drain_timeout, min_clear_timeout, and worker_loop_ttl keyword parameters to WorkerService. The TTL resolves at construction, where the loop pool consumes it; the teardown budgets resolve per teardown, so an unset parameter follows the module default as it stands when a teardown runs. Rename _CLEAR_FLOOR to _MIN_CLEAR_TIMEOUT to match the parameter it defaults.

Size the LocalWorker stop deadline and document the public contract

Set the stop RPC's deadline to 2 × grace + STOP_RPC_MARGIN, publicizing the margin: the retirement worst case plus one second of transport and response overhead, so a stop that lands during an idle retirement — which waits out that retirement's bound regardless of its own timeout — still returns before the deadline forces SIGTERM on a healthy worker. State the contract where callers read it: the tri-state field comment on wire.proto's StopRequest.timeout, the quantified default worst case in WorkerConnection.stop, and the retirement override in both READMEs.

Promise the pool's finalizer execution context

Document on ResourcePool that clear runs finalizers on the calling task and that TTL cleanup runs in the context captured when the timer was armed. The provenance split above rides on this behavior, so it is stated as a contract and pinned by tests rather than left as an implementation accident.

Test cases

The bounds and report levels are mutation-verified: the unbounded-join, budget-latch, unconditional-report, grace-doubling, and margin-term mutants each fail at least one test below.

# Test Suite Given When Then Coverage Target
1 TestWorkerService A worker loop with a blocked daemon thread and an expired idle TTL Another dispatch arrives Runs on a new worker thread within the retirement bound Dispatch availability under a wedged retirement
2 TestWorkerService A worker loop with a blocked daemon thread The TTL retirement's join outlives the retirement bound Warns and leaves the thread alive as a daemon for the process-exit reap Overrun report with idle provenance
3 TestWorkerService An idle retirement in flight over a blocked thread The stop RPC is invoked with a negative timeout Returns within the retirement bound with the service stopped Stop return under a concurrent retirement
4 TestWorkerService A TTL that fires while a stop with a positive grace is still draining in-flight work The retirement's teardown joins the blocked thread Joins on the idle bound and warns despite the concurrent stop Join-budget provenance under stop/TTL overlap
5 TestWorkerService A warm worker loop with a blocked daemon thread The stop RPC is invoked with a positive timeout Returns within twice the timeout and reports the join overrun at debug Two-wait budget with stop provenance
6 TestWorkerService A warm worker loop with a blocked daemon thread The stop RPC is invoked with a zero timeout Returns within transport slack without joining the thread Zero-timeout fast path
7 TestWorkerService A warm worker loop with a blocked daemon thread The stop RPC is invoked with a negative timeout Does not return until the thread is released Unbounded join on request
8 TestResourcePool A cached entry and a finalizer that reads a context variable The variable is set around a call to clear The finalizer observes the caller's value Finalizer context contract for clear
9 TestResourcePool An entry released while a context variable is set, arming the expiry timer The TTL elapses after the variable is reset The finalizer observes the arm-time value Finalizer context contract for TTL cleanup
10 TestLocalWorker Any finite positive grace period stop() is called Bounds the RPC by twice the grace plus a margin that itself exceeds the worst-case retirement Stop-deadline sizing with a draw-independent margin pin

@conradbzura conradbzura changed the title Bound idle worker-loop retirement Bound the thread join in idle worker-loop retirement so a blocked worker thread cannot stall dispatch — Closes #426 Oct 23, 2026
@conradbzura
conradbzura changed the base branch from main to master October 23, 2026 14:42
@conradbzura
conradbzura self-requested a review October 23, 2026 14:43
@conradbzura conradbzura added this to the v0.15 milestone Oct 23, 2026
@conradbzura
conradbzura force-pushed the codex/issue-426-bounded-idle-worker-retirement branch 2 times, most recently from 29dd29f to 7f7e062 Compare October 23, 2026 15:02
@conradbzura
conradbzura changed the base branch from master to main October 23, 2026 15:02
@conradbzura

conradbzura commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Hey @mikemikimike, thanks for the contribution! I re-targeted your branch against master since it's a bugfix that could have been released as a patch to v0.15, but I thought better of it after seeing that it depends on a few unreleased changes on main. It'll go up with v0.16. I'm reviewing it now.

Comment thread wool/src/wool/runtime/worker/service.py Resolved
Comment thread wool/src/wool/runtime/worker/service.py Resolved
Comment thread wool/src/wool/runtime/worker/service.py Resolved
Comment thread wool/src/wool/runtime/worker/service.py Resolved
Comment thread wool/src/wool/runtime/worker/service.py Resolved
Comment thread wool/src/wool/runtime/worker/service.py Resolved
@conradbzura conradbzura removed this from the v0.15 milestone Oct 26, 2026
@mikemikimike

Copy link
Copy Markdown
Contributor Author

Validation update for head 4f99b3a:

  • The three focused worker-loop regression tests covering the review feedback pass.
  • The broader validation limitations are reproducible on base 77a88e4 and are not introduced by this PR. Installing wool[dev] on Windows stops because uvloop 0.23.0 does not support Windows. The non-integration suite reaches tests/cicd/test_bump_version.py, whose .sh helper Windows cannot launch (WinError 193).
  • The full worker test module stalls at the same synchronous-dispatch test on both base and PR; that test passes when run alone on both. The PR integration run stalled at a channel-pool test, which passes individually on both base and PR; the base integration run also stalled later at a separate test. The full integration result remains inconclusive.
  • Ruff check and format pass on the changed Python files, and git diff --check passes. Project-wide Ruff findings (two lint and two formatting findings) and three Pyright errors are in unchanged files and reproduce on base.
  • GitHub currently reports no checks for this head.

Comment thread wool/src/wool/runtime/worker/service.py Resolved
Comment thread wool/src/wool/runtime/worker/service.py Resolved
Comment thread wool/src/wool/runtime/worker/service.py Resolved
@conradbzura

Copy link
Copy Markdown
Member

@mikemikimike I had a little bit more feedback. It's looking good.

Comment thread wool/src/wool/runtime/worker/service.py Resolved
Comment thread wool/src/wool/runtime/worker/service.py Resolved
@conradbzura

Copy link
Copy Markdown
Member

@mikemikimike A few more test-related items and I think we're good to merge. I'll make a documentation pass once the remaining feedback is addressed.

@conradbzura conradbzura changed the title Bound the thread join in idle worker-loop retirement so a blocked worker thread cannot stall dispatch — Closes #426 Bound the thread join in idle worker-loop retirement so a blocked worker thread cannot stall dispatch — Closes #426, #447 Oct 30, 2026
@conradbzura conradbzura self-assigned this Oct 30, 2026
@conradbzura
conradbzura force-pushed the codex/issue-426-bounded-idle-worker-retirement branch from 9943136 to b8e8775 Compare November 3, 2026 14:44
A finalizer's contextvars context was whatever the triggering operation
happened to carry, undocumented either way. A caller that wants to
scope per-teardown state — a context variable set around a clear, read
by the finalizer that clear runs — had no guarantee to rely on, and the
three paths that reach a finalizer differ: a clear, expire or expire_all
runs it inline on the calling task; dropping the last reference on a
zero-TTL pool or a doomed entry runs it in the releasing task's context;
and a cleanup the TTL spawned runs it in the context captured when the
expiry timer was armed.

The docstring now states all three, and never a later caller's. The
tests pin each one.
The three numbers that shape a worker-loop teardown — the drain budget,
the per-clear floor and the pooled loop's idle TTL — were module
constants, so a test that needed a short one patched the module and a
caller that needed a different one could not have it. They are now
constructor parameters on WorkerService: drain_timeout,
min_clear_timeout and worker_loop_ttl, each defaulting to None and
falling back to the module constant that still records its sizing
rationale.

The drain budget and the floor resolve per teardown rather than at
construction, so a module default rebound after the service exists is
still honoured. The TTL resolves at construction because the loop pool
consumes it there.

_CLEAR_FLOOR is renamed _MIN_CLEAR_TIMEOUT to match the parameter that
now overrides it.
The loop-teardown finalizer joined the worker thread for
self._stop_timeout seconds, which only a stop ever set and which
defaulted to None — an unbounded join. A teardown the idle TTL drove
therefore waited forever on a worker thread that would not exit, and
because the dispatch that needs a fresh loop waits for the retirement
it arrives into, one blocked thread stalled every later dispatch
indefinitely.

The join bound now follows the teardown's provenance rather than
whether a stop was requested. A stop publishes its mapped timeout in a
context variable set around its own pool clear, so exactly the
finalizers that clear runs inherit it — which rests on the finalizer
context ResourcePool now promises. A teardown that finds no budget is
one the TTL drove, including one firing while a stop drains in-flight
work, and bounds its join by the retirement's own worst case: the drain
budget plus one per-clear floor for every clear it runs. A thread still
running at a positive bound is left to the daemon reap at process exit,
reported at warning level for a TTL-driven teardown and at debug for a
stop-driven one, whose caller chose the bound it outlived.

This makes the stop RPC's timeout mapping worth stating, since it now
governs two sequential waits: 0 cancels in-flight work and performs no
join, a positive value bounds each wait in turn, and a negative value
waits indefinitely for both. A stop landing while an idle retirement is
underway waits out that retirement's bound instead, whatever the request
timeout, and can return with the retiring thread still running. The
wire comment, both READMEs, the connection's grace parameter and
dispatch's own docstring now say so where a caller will look.
The graceful stop call's deadline was grace plus a flat five seconds,
sized when the stop timeout bounded one wait. It bounds two — the
in-flight drain and the worker-thread join — so a worker that used its
full grace for the drain had its join cut short by a deadline that
expired during it, and stop() reported a transport failure for a
shutdown that was proceeding correctly.

The deadline is now twice the grace plus a margin sized from the
teardown budgets it has to cover: the drain budget, one per-clear floor
for each of the worker's three pools, and a second of transport and
response overhead. It is computed from the module defaults as they
stand at import, which is what the spawned worker process runs with —
so WorkerProcess forwards none of them, and a comment there says why.

The constant loses its underscore. A margin derived from another
module's defaults has to be referable from that module's side, and
LocalWorker is no longer the only place its sizing matters. It is
package-internal, not part of wool's supported public API.
@conradbzura
conradbzura force-pushed the codex/issue-426-bounded-idle-worker-retirement branch from b8e8775 to 46d3d9f Compare November 3, 2026 18:37
@conradbzura
conradbzura merged commit 7b89c8e into wool-labs:main Nov 3, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants