Skip to content

Add WorkerPool.dispatch for explicit single-dispatch to a given pool — Closes #196 - #453

Merged
conradbzura merged 7 commits into
wool-labs:mainfrom
conradbzura:196-pool-dispatch-method
Nov 12, 2026
Merged

conradbzura merged 7 commits into
wool-labs:mainfrom
conradbzura:196-pool-dispatch-method

Conversation

@conradbzura

@conradbzura conradbzura commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

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 kept executor= out of wool.to_thread in #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-unimplemented pool.broadcast in #195.

Reach the dispatch path through the seam the routine layer already had rather than adding one beside it. wrapper._dispatch has always taken its proxy as an argument; the wrappers are what read wool.__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 as dispatch_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 asynchronous yield 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 asking inspect.isasyncgenfunction about Task.callable. The relay next to _stream's looks like a duplicate and is not: _stream scopes every step in do_dispatch(True), which is load-bearing and cannot be hoisted around the loop, because an async generator has no context of its own and a with spanning the yield would leak the flag to the consumer.

Closes #196

Proposed changes

Add WorkerPool.dispatch

Dispatch a routine through the pool it is called on. routine is positional-only, so every keyword reaches the routine, including one named pool or routine. The return value has the routine's own shape — a coroutine to await, an async generator to iterate with the full asend/athrow/aclose protocol — 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 raises RuntimeError, since a pool prepares its proxy at entry and releases it at exit.

async with wool.WorkerPool(spawn=4) as gpu:
    async with wool.WorkerPool(spawn=16):
        # Routes through `gpu`, whatever pool is ambient.
        result = await gpu.dispatch(train, dataset)

        # A plain call still routes through the inner pool.
        summary = await summarize(result)

        # Async generator routines stream, with the full protocol intact.
        async for batch in gpu.dispatch(stream_batches, dataset, size=64):
            ...

        # A bound method carries its receiver; no argument is dropped.
        await gpu.dispatch(model.fit, dataset)

Retain the dispatch proxy on the pool

Bind the proxy the pool enters to self._proxy so dispatch has something to route through, and release it in a finally at context exit so a failed teardown still leaves the pool refusing to dispatch rather than routing through a torn-down proxy. The four create_proxy closures 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_coroutine takes 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_stream relays 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.routine attaches __wool_dispatch__, holding (entrypoint, lineno): the dispatch function matching the routine's call shape, and the source line _dispatch folds into the task tag. Nothing in the ambient path consults it; a routine call still routes on the do_dispatch flag. 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 and lineno is an int. 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 as wrapper(obj, a, b). Restore that shape before dispatching, because _dispatch drops 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 R type variable

Add R to wool.runtime.typing, bound to a coroutine or an async generator, naming what calling a routine returns so dispatch's signature can promise the routine's own shape back.

Rewrite the routine docstring

Bring @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 interleaved note directives 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 dispatch subsection 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 that dispatch binds nothing and so never raises wool.ChainContention.

Test cases

# Test Suite Given When Then Coverage Target
1 TestWorkerPool An entered pool whose proxy records its dispatches A routine is dispatched with positional arguments It should build a task carrying the pool's own proxy, the routine and every argument Routing through the retained proxy
2 TestWorkerPool An entered pool and a routine with parameters named pool and routine Both are passed as keywords It should carry both to the task rather than consume either Keyword non-reservation
3 TestWorkerPool An entered pool and a coroutine routine The routine is dispatched It should return a coroutine resolving to the routine's result Shape parity for coroutines
4 TestWorkerPool An entered pool and an async generator routine The routine is dispatched It should return an async generator yielding the routine's frames Shape parity and entrypoint selection
5 TestWorkerPool An entered pool, a coroutine routine and an async generator routine Both are dispatched but neither result is consumed It should not have reached the proxy yet Dispatch laziness
6 TestWorkerPool An entered pool whose proxy streams results without implementing asend A dispatched generator is consumed without sending It should relay every frame and close the stream The relay takes unsent frames with __anext__
7 TestWorkerPool An entered pool and a routine bound to an instance The bound method is dispatched with its full argument list It should carry the receiver ahead of every argument Unbinding an instance method
8 TestWorkerPool An entered pool and a routine bound to a class The classmethod is dispatched with its full argument list It should carry the class ahead of every argument Unbinding a classmethod
9 TestWorkerPool An entered pool and a plain coroutine function The undecorated function is dispatched It should raise TypeError The marker's absence refuses a non-routine
10 TestWorkerPool A pool that has not been entered A routine is dispatched It should raise RuntimeError No proxy outside the pool's context
11 TestWorkerPool A pool whose context has been entered and exited A routine is dispatched afterwards It should raise RuntimeError Proxy release at context exit
12 TestWorkerPool A pool whose context exit itself raised A routine is dispatched afterwards It should raise RuntimeError Proxy release on a failed exit
13 TestWorkerPoolDispatch An entered pool that is also the ambient one A routine is called ambiently and dispatched explicitly It should return the same result both ways Parity with an ambient call
14 TestWorkerPoolDispatch Two entered pools, the inner of which is ambient A routine is dispatched through the outer pool It should run on the outer pool's worker The receiver overrides the ambient pool
15 TestWorkerPoolDispatch Two entered pools, the inner of which is ambient A routine is dispatched explicitly and then called plainly The plain call should land on the ambient pool Ambient routing survives an override
16 TestWorkerPoolDispatch Two entered pools, the inner of which is ambient Explicit and plain calls run concurrently under asyncio.gather Every explicit call should land on the outer pool and every plain call on the ambient one Concurrent dispatches do not collide
17 TestWorkerPoolDispatch Two entered pools, the inner of which is ambient A routine that dispatches nested calls is dispatched explicitly Both the routine and its nested calls should run on the outer pool's worker The override reaches nested dispatches
18 TestWorkerPoolDispatch An entered pool and a routine with parameters named pool and routine Both are supplied as keywords It should deliver both to the routine unshadowed Keyword non-reservation over the wire
19 TestWorkerPoolDispatch An entered pool and a routine bound to an instance The bound method is dispatched with its full argument list It should return what an ambient call returns Unbinding across the process boundary
20 TestWorkerPoolDispatch An entered pool and a routine bound to a class The classmethod is dispatched with its full argument list It should return what an ambient call returns Unbinding a classmethod across the boundary
21 TestWorkerPoolDispatch An entered pool An async generator routine is dispatched and iterated It should yield the same values an ambient call yields Streaming parity
22 TestWorkerPoolDispatch An entered pool and a dispatched generator that echoes what is sent A value is sent to the returned generator It should carry the value to the worker and return the response asend across the wire
23 TestWorkerPoolDispatch An entered pool and a dispatched generator that resets on ValueError A ValueError is thrown into the returned generator It should deliver the exception to the worker and return the response athrow across the wire
24 TestWorkerPoolDispatch Two entered pools, the inner ambient, and a routine that raises The routine is dispatched through the outer pool It should surface the routine's own exception and leave the ambient pool serving Failure propagation
25 TestWorkerPoolDispatch Two entered pools, the inner of which is ambient A dispatched generator is abandoned part-way through its frames The plain calls that follow should land on the ambient pool Ambient routing survives abandonment
26 TestWorkerPoolDispatch A caller that set a wool.ContextVar, and an entered pool A routine reading the variable is dispatched explicitly The worker should observe the caller's value The routine runs under the caller's chain
27 test_dispatch_pairwise Any valid scenario drawn from the covering array A routine is dispatched through the pool the builder yielded It should return the same result the ambient shapes return EXPLICIT_COROUTINE and EXPLICIT_ASYNC_GEN across every composition axis

@conradbzura conradbzura self-assigned this Nov 4, 2026
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
conradbzura force-pushed the 196-pool-dispatch-method branch from d9ec474 to 0485eda Compare November 5, 2026 20:07
@conradbzura
conradbzura marked this pull request as ready for review November 6, 2026 16:16
@conradbzura
conradbzura merged commit 67a8c99 into wool-labs:main Nov 12, 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

Development

Successfully merging this pull request may close these issues.

Add WorkerPool.dispatch for explicit single-dispatch to a given pool

1 participant