Repository navigation
Add WorkerPool.dispatch for explicit single-dispatch to a given pool — Closes #196 - #453
Merged
conradbzura merged 7 commits intoNov 12, 2026
Merged
Conversation
The pool created its proxy at context entry and dropped the reference, keeping only the context manager. Nothing could route a call through a pool named by its receiver without a handle on the proxy serving it. Bind the proxy the factory yields to the pool for the lifetime of the context, and clear it in a finally so a failed exit leaves no handle behind. Behavior is unchanged; the ambient dispatch path still resolves its proxy from the caller's context.
A routine call dispatches through whichever pool is ambient in the caller's context. Naming a pool instead required either entering it or accepting the keyword collision that kept executor out of wool.to_thread: a pool keyword would silently shadow any routine parameter of the same name. Express the choice through the receiver. WorkerPool.dispatch takes the routine positionally and reserves no keyword, so every keyword reaches the routine. One routine goes to one worker, selected by the pool's load balancer, and the task carries that pool's proxy, so the nested calls the routine makes route through it as well. The routine layer gains the seam this needs. Each decorated wrapper carries a dispatch entrypoint matching its call shape, and dispatch_through routes one call through a proxy its caller names rather than the ambient one. The attribute's absence is what rejects an undecorated callable, which is a rejection the explicit path needs because it is handed a callable rather than invoking one: an undecorated coroutine function is callable and awaitable, so it would run in the caller's own process while the call reported a dispatch. A bound method or classmethod carries its receiver out of band, where an ambient call carries it in the argument list. Unbinding on the way through restores the ambient shape, so obj.method takes the same arguments dispatched as it does called.
Add the explicit-dispatch section to the package README, and correct the worker README's note on concurrent pool entry, which described every dispatch path as binding a context variable. WorkerPool.dispatch binds nothing, threading the retained proxy to the routine layer explicitly, so it never raises ChainContention.
The docstring had three structural defects alongside its prose ones. Its summary line was nominal rather than imperative; the bulk of its prose sat after the field list, where the documented section order puts only examples and the implementation rubric; and it still carried the legacy role markup that new prose is not to introduce. Reorder to summary, prose, field list, examples, rubric. Replace the two interleaved note directives and the six-item best-practices list with named subsections that separate what the process boundary guarantees from what it constrains, collapsing the three items that were advice or restated parity into the claims carrying them. Convert the role markup to the single-backtick convention. No contract claim is dropped.
Drive the dispatch cases through the proxy boundary and assert on the public task fields, so the suite exercises the real dispatch entrypoint rather than a patched stand-in, and the bound-callable contract becomes observable at this level. The stream relay was the gap worth closing. A dispatched async generator relays its result stream without calling asend until the consumer sends a value, and nothing reached that guard through the pool: replacing it with an unconditional asend passed the entire suite. A stream implementing no asend now fails that mutation.
Exercise the override against live workers: a call routed to the receiver while another pool is ambient, the ambient pool restored afterwards and after a stream is abandoned mid-iteration, concurrent dispatches isolated under gather, nested calls following the task's proxy, the generator protocol forwarded end to end, an exception propagated from the routine, and the routine running under the caller's chain.
The explicit path routes through WorkerProxy.dispatch, so every composition axis the matrix varies is live for it, and none was covering it: transport credentials, discovery, pool mode, channel limits, backpressure and the context-var patterns. Add explicit coroutine and async generator shapes to the routine dimension, following the convention the nested shapes already set of naming a dispatch path rather than a callable shape. Extract the generator step driver so the ambient and explicit arms share it instead of duplicating the per-yield assertions. The pairwise filter and the Hypothesis strategy already admit every binding for a shape that pins none, so the two stay in agreement untouched.
conradbzura
force-pushed
the
196-pool-dispatch-method
branch
from
November 5, 2026 20:07
d9ec474 to
0485eda
Compare
conradbzura
marked this pull request as ready for review
November 6, 2026 16:16
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Add
WorkerPool.dispatch, a first-class way to say "dispatch this call through that pool" rather than through whichever pool happens to be ambient in the caller's context.Express the override through the receiver instead of a
pool=keyword. A keyword would silently shadow a routine parameter of the same name — the collision that keptexecutor=out ofwool.to_threadin #314 — so the pool that serves a call is named by the object the call is made on, and no argument name is reserved. This is single-dispatch: one routine to one worker, chosen by the pool's load balancer, and the counterpart to the still-unimplementedpool.broadcastin #195.Reach the dispatch path through the seam the routine layer already had rather than adding one beside it.
wrapper._dispatchhas always taken its proxy as an argument; the wrappers are what readwool.__proxy__to supply it. What was missing was a way for a caller holding only a routine wrapper to reach that seam, since the dispatch tag's components live in the decorator's closure. Expose it asdispatch_through, and the explicit path binds no context variable at all — the proxy is threaded down as an argument, so concurrent explicit and ambient dispatches cannot collide by construction, and the worker layer learns nothing about routines.The trade-off worth naming is a third async-generator relay in
wrapper.py. Python has no asynchronousyield from, so an async generator cannot delegate its protocol without repeating the loop, and the decorator's wrapper has to remain a genuine async-generator function because the worker picks between streaming and unary dispatch by askinginspect.isasyncgenfunctionaboutTask.callable. The relay next to_stream's looks like a duplicate and is not:_streamscopes every step indo_dispatch(True), which is load-bearing and cannot be hoisted around the loop, because an async generator has no context of its own and awithspanning theyieldwould leak the flag to the consumer.Closes #196
Proposed changes
Add
WorkerPool.dispatchDispatch a routine through the pool it is called on.
routineis positional-only, so every keyword reaches the routine, including one namedpoolorroutine. The return value has the routine's own shape — a coroutine to await, an async generator to iterate with the fullasend/athrow/acloseprotocol — and is as lazy as calling the routine: nothing dispatches until the result is consumed.The override reaches the routine's nested calls too, because the task carries this pool's proxy, so a routine the worker calls in turn routes through this pool rather than the caller's.
Worker selection, the quorum gate, lazy startup and every failure mode remain
WorkerProxy.dispatch's. The method adds one of its own: dispatching outside the pool's context raisesRuntimeError, since a pool prepares its proxy at entry and releases it at exit.Retain the dispatch proxy on the pool
Bind the proxy the pool enters to
self._proxysodispatchhas something to route through, and release it in afinallyat context exit so a failed teardown still leaves the pool refusing to dispatch rather than routing through a torn-down proxy. The fourcreate_proxyclosures now yield the proxy they enter instead of discarding it.Expose the routine layer's dispatch seam
Add
dispatch_through(proxy, routine, /, *args, **kwargs), which routes one call through a named proxy by handing it to the same dispatch path the routine would have taken. Both parameters are positional-only for the same reason the public method's are.Two module-level entrypoints back it, one per routine shape, with signatures matching
_dispatch's._dispatch_coroutinetakes a dispatch's single result frame and is verbatim what the coroutine wrapper already did, so that branch collapses to one call and the extraction is net negative there._dispatch_streamrelays the result stream and, being an async-generator function, dispatches nothing until first iteration — matching a routine call's documented laziness.Carry the dispatch spec on the decorated wrapper
@wool.routineattaches__wool_dispatch__, holding(entrypoint, lineno): the dispatch function matching the routine's call shape, and the source line_dispatchfolds into the task tag. Nothing in the ambient path consults it; a routine call still routes on thedo_dispatchflag. Its absence is also what marks a callable as undispatchable, which an explicit dispatch needs because it is handed a callable rather than invoking one: an undecorated coroutine function is callable and awaitable, so without the marker it would run in the caller's own process while the call reported a dispatch.The spec is a tuple in the wrapper's
__dict__rather than a closure over the wrapper, because cloudpickle ships that__dict__for every shape that serializes by value, and a closure over the wrapper would carry its own code object into each such dispatch. Both members cost almost nothing to pickle: the entrypoint is importable andlinenois anint. The shapes that serialize by reference carry no__dict__at all and pay nothing either way.Unbind a bound callable before dispatching
A bound method carries its receiver out of band, where an ambient call carries it in the argument list:
obj.method(a, b)invokes the wrapper aswrapper(obj, a, b). Restore that shape before dispatching, because_dispatchdrops a leading argument for anything carrying__self__— a branch the ambient path keeps dead by only ever handing it the plain wrapper. Passing a bound callable straight through would both trip that branch and ship the receiver twice.The resulting task is the shape the ambient path builds, so nothing downstream distinguishes the two, and the dispatch tag is unaffected because a bound callable and its underlying function report the same qualified name.
Add the
Rtype variableAdd
Rtowool.runtime.typing, bound to a coroutine or an async generator, naming what calling a routine returns sodispatch's signature can promise the routine's own shape back.Rewrite the
routinedocstringBring
@wool.routine's docstring to the documentation guide. Its summary was nominal rather than imperative, most of its prose sat after the field list where the guide places only examples and the implementation rubric, and it carried the legacy role markup new prose does not introduce. Reorder it, replace the two interleavednotedirectives and the six-item best-practices list with named subsections separating what the process boundary guarantees from what it constrains, and convert the markup to the single-backtick convention. No contract claim is dropped, and the implementation rubric defines the dispatch spec on first use.Document explicit dispatch
Add an
Explicit dispatchsubsection to the worker-pool documentation, and qualify the routine-transparency claim with a link, since dispatching through a named pool is the one case where the receiver matters. Note in the worker package's concurrent-entry guard thatdispatchbinds nothing and so never raiseswool.ChainContention.Test cases
TestWorkerPoolTestWorkerPoolpoolandroutineTestWorkerPoolTestWorkerPoolTestWorkerPoolTestWorkerPoolasend__anext__TestWorkerPoolTestWorkerPoolTestWorkerPoolTypeErrorTestWorkerPoolRuntimeErrorTestWorkerPoolRuntimeErrorTestWorkerPoolRuntimeErrorTestWorkerPoolDispatchTestWorkerPoolDispatchTestWorkerPoolDispatchTestWorkerPoolDispatchasyncio.gatherTestWorkerPoolDispatchTestWorkerPoolDispatchpoolandroutineTestWorkerPoolDispatchTestWorkerPoolDispatchTestWorkerPoolDispatchTestWorkerPoolDispatchasendacross the wireTestWorkerPoolDispatchValueErrorValueErroris thrown into the returned generatorathrowacross the wireTestWorkerPoolDispatchTestWorkerPoolDispatchTestWorkerPoolDispatchwool.ContextVar, and an entered pooltest_dispatch_pairwiseEXPLICIT_COROUTINEandEXPLICIT_ASYNC_GENacross every composition axis