Discovery sentinel drops worker-updated events carrying changed metadata — Closes #292#303
Merged
conradbzura merged 2 commits intoJul 14, 2026
Conversation
b37310f to
809b958
Compare
5603b03 to
83d478a
Compare
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.
83d478a to
1ddd9fd
Compare
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
WorkerMetadatahashes byuidalone 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 droppedworker-updatedevents carrying changed metadata, aworker-droppedevent 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.
LoadBalancerContextmaps uid to the worker's current record and connection, so membership, lookup, and eviction all follow from the key, 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 second commit applies the same move to the balancer protocol, and fixes a defect the first one exposes rather than introduces. 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 refresh replaced a worker's entry, so that pair could name a superseded address.delegatenow yields the worker's uid, and the proxy resolves that name against the live pool at the moment it dispatches. A balancer cannot route a task to a superseded address however stale the view it chose from, because the record it read is not the record dispatched through.Closes #292
Proposed changes
Key the worker pool by uid
LoadBalancerContextstoresdict[uuid.UUID, tuple[WorkerMetadata, WorkerConnection]]. Presence isuid in workers, resolution isworkers[uid], and the three mutators are one dict operation each.add_workeradmits or replaces;update_workerrefreshes what is already admitted;remove_workerevicts. Theupsertflag is gone — the two verbs carry two contracts and no longer need a boolean to tell them apart.LoadBalancerContextViewexposes the uid-keyed mapping and nothing else. Its member set is unchanged, so no existing context implementation breaks itsisinstanceconformance. The mapping's key type does change, which is breaking for a custom balancer that iteratescontext.workers.items().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 on displacement would evict a channel the replacement may still share, since the pool key is
(target, credentials, options)and an update that changes only tags or pid yields the same key. That rationale now lives onWorkerConnection, where channel lifetime is actually owned, and the sites that depend on it point there rather than restating it.Select workers by uid in
LoadBalancerLike.delegateA selection names a worker; the proxy resolves it against the pool at dispatch time and connects through the entry it finds there. 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 — and it was the half that went stale. Balancers that need a record or a connection to decide (match tags, pin a version, weigh a connection) still read them from
context.workers; they simply no longer carry what they read back across the boundary. The success echo narrows with the yield:asendnow sends back the uid.Selecting a worker that has left the pool is no longer an error a balancer must avoid. The proxy finds no entry, requests the next candidate, and reports nothing back — a departed worker has not failed a dispatch.
Round-robin
The rotation snapshots uids once per wrap and indexes them in O(1). Because candidates are uids, a worker refreshed mid-cycle needs no special handling in the balancer at all. The cycle boundary is a uid and survives refreshes; it is reseeded only when that uid leaves the pool, since a departed uid can never recur and would otherwise never close the cycle.
Documentation
The load-balancer README's protocol excerpt declared the superseded
(metadata, connection)signature and is replaced by a pointer toLoadBalancerLike, which owns the contract; the README now states the uid identity model in prose rather than only in its examples. The public docstrings onLoadBalancerLike,LoadBalancerContextView,LoadBalancerContext, andWorkerProxy.workersstate the caller-visible contract and move mechanism intoImplementation notesrubrics, so the guarantees a balancer author must honor are stated once, in the entity that owns them.Breaking changes
This is a pre-1.0 surface, and both changes delete API rather than add it. A custom balancer migrates as follows:
update_workerno longer acceptsupsert; calladd_workerto admit a worker that may not be pooled yet.Test cases
TestLoadBalancerContextworkersTypeErrorTestLoadBalancerContextworkersview captured before any mutationTestLoadBalancerContextadd_workeradmitTestLoadBalancerContextadd_workerreplaceTestLoadBalancerContextTestLoadBalancerContextTestLoadBalancerContextTestLoadBalancerContextTestLoadBalancerContextTestLoadBalancerContextupdate_workerTestLoadBalancerContextTestLoadBalancerContextTestLoadBalancerContextTestLoadBalancerContextTestLoadBalancerContextTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerasendTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerdelegatecallsTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestRoundRobinLoadBalancerTestWorkerProxylease=NoneTestWorkerProxyTestWorkerProxylease=1and a cap-rejected workerTestWorkerProxyworker-updatedarrives with changed metadataTestWorkerProxyTestWorkerProxyTestWorkerProxylease=2at capacityTestWorkerProxyTestWorkerProxyTestWorkerProxyTestWorkerProxyTestWorkerProxyTestWorkerProxyTestWorkerProxyNoWorkersAvailableonce the balancer exhaustsTestWorkerProxydispatch()is calledNoWorkersAvailableand leave the pool emptyTestWorkerProxyquorum=1and an update-only discovery streamstart()is awaitedTimeoutErrorand leave no sentinelTestWorkerUpdatePropagationLocalDiscoveryand a second live workerworker-updatedrepublishes the uid at the new addressTestWorkerUpdatePropagationTestWorkerUpdatePropagationworker-droppedis published for the uidNoWorkersAvailableTestWorkerUpdatePropagationlease=1and a worker discovery registered but the pool never admittedworker-updatedarrives for that workerNoWorkersAvailable— the update neither admits it nor grows the poolupsertpath, end to end