Skip to content

Release v0.12.0#289

Open
wool-labs[bot] wants to merge 21 commits into
masterfrom
release
Open

Release v0.12.0#289
wool-labs[bot] wants to merge 21 commits into
masterfrom
release

Conversation

@wool-labs

@wool-labs wool-labs Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Auto-generated by the cut release workflow.

conradbzura and others added 21 commits July 7, 2026 20:53
Split the LoadBalancerLike protocol into two: the new
DelegatingLoadBalancerLike, which only selects worker candidates, and
the deprecated DispatchingLoadBalancerLike, which retains the old
responsibility of owning task dispatch. LoadBalancerLike becomes a
transitional union alias that narrows to the delegating protocol in
the next major release.

A delegating load balancer implements delegate(*, context), an async
generator that yields (WorkerMetadata, WorkerConnection) candidates
and receives dispatch outcomes from the proxy:

  - anext() requests the next candidate
  - athrow(exc) reports a failure; the proxy evicts the worker from
    the context before throwing non-transient errors so the balancer
    observes the capacity change
  - asend(metadata) reports a success; the generator MUST terminate
    after this signal — yielding another candidate is a protocol
    violation and surfaces as a RuntimeError from WorkerProxy

The context passed to delegate is typed as the new read-only
LoadBalancerContextView protocol, enforcing at the type level that
load balancers cannot mutate pool membership. Eviction lives in the
proxy exclusively.

WorkerProxy.dispatch now branches on the balancer's protocol and, for
delegating balancers, owns the full dispatch-retry-evict loop via
_delegate_dispatch. The loop catches Exception (not BaseException)
for non-transient errors so CancelledError, KeyboardInterrupt, and
SystemExit propagate without eviction or retry — cancellation is
caller intent, not a worker health signal. A stream-ownership
handoff via a sentinel variable ensures the gRPC call is released if
the proxy unwinds between connection.dispatch returning and the
stream being handed back to the caller. A DeprecationWarning is
emitted once at start() when a DispatchingLoadBalancerLike is passed.

RoundRobinLoadBalancer reduces to a pure cycling generator: no
dispatch, no error classification, no eviction. The checkpoint-by-UID
termination logic and pickle-safe __reduce__ are preserved.

The load balancer README is rewritten around the delegate protocol,
documents the asend-is-terminal contract, and calls out the
deprecation.
Protocol conformance tests in test_base.py now cover all three
protocols — LoadBalancerContextView, DispatchingLoadBalancerLike,
DelegatingLoadBalancerLike — plus the LoadBalancerLike union alias,
including an edge-case test for classes that implement both
protocols during migration.

test_roundrobin.py is rewritten around the delegate API. The 12
tests cover empty context exhaustion, first-yield behavior, index
advancement on asend and athrow, full-cycle exhaustion via
checkpoint, context mutation reactivity (proxy-driven eviction
between yields), asend as terminal signal, concurrent delegate
drivers for fairness, Hypothesis-driven round-robin sequence
verification, and non-transient error handling. The obsolete
dispatch_side_effect_factory fixture is removed from
loadbalancer/conftest.py.

test_proxy.py adds TestWorkerProxyDelegateDispatch to cover the
proxy-owned retry-evict loop. Tests exercise transient errors
(skip without eviction), non-transient errors (evict before
notifying the balancer), candidate exhaustion in both the initial
anext and the non-transient athrow paths, empty delegate behavior,
success notification via asend, the asend-is-terminal contract
(verified via a malformed balancer that raises RuntimeError and
closes the orphaned stream), cancellation during connection.dispatch
(no eviction, no retry, CancelledError propagates) and cancellation
during asend (orphaned stream is aclosed before CancelledError
propagates). Two tests cover the legacy path: the deprecation
warning is emitted at start(), and dispatch through a legacy
DispatchingLoadBalancerLike still works.

Existing dispatch tests in test_proxy.py (spy_loadbalancer_with_workers,
FailingLoadBalancer, WaitingLoadBalancer, StubLoadBalancer) are
updated from the legacy dispatch method to the delegate async
generator. Dead worker_*_callback helpers on the spy balancer —
which the production proxy never called — are removed. The
mock_worker_connection fixture's dispatch stub now accepts the
timeout keyword argument the proxy passes.

test_public.py is updated to expect the three new public exports:
DelegatingLoadBalancerLike, DispatchingLoadBalancerLike,
LoadBalancerContextView.
The test guide requires tests to exercise only public APIs. Three
violations introduced in the prior commit are corrected:

The pickle roundtrip test for RoundRobinLoadBalancer was probing
_index and _lock directly. It now drives delegate() via the public
API before and after pickle, asserting that the restored instance
starts cycling from position zero on the same context.

TestWorkerProxyDelegateDispatch._start_proxy_with_workers was seeding
workers via proxy._loadbalancer_context.add_worker, bypassing the
public discovery flow. Replaced with _make_proxy_with_workers, which
constructs the proxy with a ReducibleAsyncIterator discovery stream,
patches WorkerConnection so the sentinel creates the intended mock
connections, and waits via the public proxy.workers property.

The legacy dispatch test was similarly using _loadbalancer_context
directly; it now uses the same helper. The orphaned empty
loadbalancer conftest.py is deleted.
The loadbalancer README example used except BaseException around the
delegate yield, which would swallow GeneratorExit from aclose() and
CancelledError from task cancellation. Corrected to except Exception
to match the RoundRobinLoadBalancer implementation.

The worker README error classification table header said "Load
balancer behavior" but post-refactor this is the proxy's
responsibility. Updated to "Dispatch behavior" with clearer action
descriptions (skip vs evict).

The discovery README referenced the deprecated size parameter in its
description of pool modes. Updated to spawn.
Under sustained saturating fan-out, the per-channel client semaphore
releases a permit on stack-unwind before the HTTP/2 stream finishes
closing at the transport, so concurrent streams transiently overshoot
the gate. Because the server advertised MAX_CONCURRENT_STREAMS equal to
that gate, the overshoot pushed past the ceiling and grpc-aio faulted
the connection with INTERNAL / ExecuteBatchError, draining the pool.

Size the server ceiling to twice the advertised gate so the overshoot,
bounded above by ~2x the gate, never reaches it. The advertised gate and
the client semaphore stay unchanged, so client fan-out is not
serialized. Health-aware handling of a fault that does slip through is
tracked separately.
Drive repeated bursts of concurrent dispatches far exceeding a small
worker gate against a one-worker pool, asserting every burst completes
and the healthy worker is retained. The guard fails if the stream
ceiling is recoupled to the gate and the starvation fault fires.
Record that the client sizes its dispatch gate from the advertised
max_concurrent_streams while the worker sets its transport ceiling to
twice that value, so the setting is no longer applied symmetrically on
both ends.
Pushing a guarded context manager onto an ExitStack or AsyncExitStack
raised TypeError, the error the decorator emits for bare functions.
contextlib looks special methods up on the type and calls them unbound,
so type(cm).__enter__(cm) reaches the descriptor itself rather than a
bound wrapper, and __call__ rejected it. WorkerPool was affected: a pool
could not be composed onto a stack alongside other resources.

Record the owning class via __set_name__ and treat an owned descriptor
invoked with an instance of its owner as the bound call it actually is,
delegating through __get__ so the guard, the coroutine-ness, and the
wrapper cache all still apply. Class-level access keeps returning the
descriptor, so introspection is unchanged, and a bare function still has
no owner and is still rejected. Teardown works the same way: contextlib
registers exit as a method of the type, so a guarded __exit__ receives
its exception triple through the same path.
Pin the reported failure at both the utility and the WorkerPool level:
a guarded manager enters through ExitStack and AsyncExitStack, and the
guard still rejects a second entry there.

Guard the argument-forwarding half of the contract, which nothing
exercised. contextlib registers teardown as a method of the type, so a
guarded exit is routed through the descriptor with its exception triple
as trailing arguments; every prior test entered with no arguments at
all, so an implementation that dropped them silently passed. Cover the
exception details reaching a guarded exit through both stacks, and
argument forwarding on a direct unbound call.

Pin the guard as shared across the bound and unbound call forms, by
example and by a property over arbitrary interleavings of the two, so
the widened dispatch cannot become a way around single-use semantics.
Cover a subclass entering through a stack, since dispatch admits any
instance of the owning class rather than only exact instances, and the
plain statement form, which had no coverage of its own.

Rename the bare-function test to say what it asserts: it calls an owned
descriptor with no instance, which is a distinct rejection branch from a
genuinely unowned function. Drop the unbound-access test, whose only
assertion could not fail.
Unlinking a shared-memory segment that another process had already
removed raised FileNotFoundError out of the owner's context exit,
aborting pool teardown, and the raise skipped the atexit unregister so
the fallback fired a second FileNotFoundError at interpreter shutdown.
The failure is reliable under rapid same-namespace pool teardown and
respawn, where a dying process's multiprocessing resource tracker
unlinks the deterministically named segment out from under the owner.

Owner exit now disarms the atexit fallback before unlinking and treats
a missing segment as a no-op, the fallback closure suppresses the same
error at shutdown, and the publisher block finalizer applies the same
disarm-before-unlink ordering so a failed unlink can never leave a
fallback armed.
Add regression tests for the double-unlink crash and the atexit
fallback double-fire, then pin the surrounding teardown contracts:
owner exit unlinks the segment, exceptional exit still tears down,
non-owners neither arm fallbacks nor unlink, namespaces stay reusable
across rapid enter/exit cycles, and overlapping same-namespace
generations unwind cleanly. Recording atexit wrappers pin the
disarm-before-unlink ordering for both the owner exit and the
publisher block finalizer, where an unsuppressed unlink error is the
only observable seam. Hypothesis properties generalize the regression
cases across arbitrary lifecycle interleavings, vanishing-segment
masks, and publisher add/drop sequences. Reword two overclaiming test
docstrings to match what their bodies assert.
Exercise the reported reproduction shapes end to end with real worker
pools: rapid same-namespace teardown and respawn, LIFO overlap, and
owner-first exit with a post-overlap respawn. A cross-process test
proves the genuine failure mechanism by letting an independent
interpreter's resource tracker unlink the shared segment and asserting
the owner still exits cleanly through real interpreter shutdown. A
strict xfail pins the known surviving-pool worker leak so the suite
flags its fix loudly when it lands.
A leaked-context owner interpreter shuts down with the atexit fallback
still armed after an independent attacher's resource tracker unlinked
the segment. The pre-fix bare lambda leaves an atexit traceback on
stderr at shutdown; the suppressing closure shuts down silently. This
is the first behavioral pin for the fallback's own suppression, which
coverage cannot see because it runs in an unmeasured interpreter.
WorkerMetadata hashes by uid alone while the generated dataclass
equality compares every field, so a pool keyed by the metadata record
could not address a worker whose record had changed. Every membership
test failed for exactly the events that mattered: the discovery
sentinel dropped worker-updated events carrying changed metadata, a
worker-dropped event whose record differed from the cached one missed
its entry, and a re-announcement inserted a duplicate that consumed a
second lease slot.

Key the pool by the worker's uid, which is what actually identifies a
worker: LoadBalancerContext maps uid to the worker's current record
and connection. Membership, lookup, and eviction all follow from the
key, so the mutators become single dict operations and a duplicate
entry is no longer possible to express. The lease cap counts distinct
uids, so a worker re-announcing itself refreshes its entry rather than
being turned away at capacity.

The upsert flag goes with the old key. Keying by uid gives add_worker
and update_worker distinct contracts — add admits or replaces, update
refreshes what is already admitted — so the boolean that told them
apart has nothing left to select.

Connections displaced by a refresh are deliberately left unclosed. A
connection is a lazy handle and the channel it names is owned by the
pooling layer, which reaps it by refcount and TTL; closing one here
would evict a channel the replacement may still share.

BREAKING CHANGE: LoadBalancerContextView.workers is now keyed by
uuid.UUID rather than WorkerMetadata, mapping each uid to a
(metadata, connection) pair. A custom balancer that iterates
context.workers.items() must iterate values() instead, and one that
tests membership with a metadata record must test with record.uid.
LoadBalancerContextLike.update_worker no longer accepts the upsert
keyword; call add_worker to admit a worker that may not be pooled yet.
A balancer yielded the (metadata, connection) pair it had read from
the pool, and the proxy dispatched through whatever pair it was handed.
But a balancer selects from a view it may have read before a discovery
refresh replaced a worker's entry: round-robin re-snapshots once per
wrap, and a custom balancer may snapshot once per call. The connection
it yielded could therefore name the worker's superseded address, which
left every balancer that does not check for it dispatching to a dead
endpoint — including the three this package documents as examples.

Yield the worker's uid instead. A selection names a worker; the proxy
resolves that name against the live pool at the moment it dispatches,
so a balancer cannot route a task to a superseded address however
stale the view it chose from. The staleness stops being something
balancer authors must defend against and becomes something they cannot
express.

The connection half of the yield was a round trip in any case: the
balancer took a connection out of the pool and handed it back to the
proxy, which owns the pool. It was also the half that went stale.
Balancers that need a record or a connection to decide — to match
tags, pin a version, weigh a connection — still read them from the
context; they simply no longer carry what they read back across the
boundary. The success echo narrows with the yield: asend now sends
back the uid.

Selecting a worker that has left the pool is no longer an error the
balancer must avoid. The proxy finds no entry, asks for the next
candidate, and reports nothing back, since a worker that has departed
has not failed a dispatch.

BREAKING CHANGE: LoadBalancerLike.delegate now yields uuid.UUID rather
than a (WorkerMetadata, WorkerConnection) pair, and receives a
uuid.UUID from asend. A custom balancer yields the uid it selected:
"yield metadata, connection" becomes "yield uid". Records and
connections remain available through context.workers, which maps each
uid to its current (metadata, connection) pair.
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.

1 participant