Repository navigation
Back the discovery registry with a file instead of shared memory — Closes #340, #345, #353, #376, #449 - #441
Merged
conradbzura merged 19 commits intoNov 4, 2026
Conversation
conradbzura
force-pushed
the
353-mmap-local-discovery
branch
from
September 20, 2026 00:39
133f60d to
2cabe5a
Compare
conradbzura
force-pushed
the
353-mmap-local-discovery
branch
from
October 6, 2026 18:17
d792b9b to
e1417c8
Compare
conradbzura
force-pushed
the
353-mmap-local-discovery
branch
2 times, most recently
from
November 3, 2026 13:05
f339700 to
79444c6
Compare
The task lifecycle events section documented TaskEvent, TaskEventType, IterationEvent, their handler protocol and the decorator that registers handlers for them. The package provides none of those names, so the section told readers to import and register against an API that cannot be reached.
A container that fails once owes the same exception to every caller that later asks it for something the failure made impossible: the consumers of a shared subscription, the dispatches of a proxy whose membership feed died. Those callers must each receive an exception they can match on, so the instance itself has to be handed to all of them rather than rebuilt or wrapped. Raising one instance repeatedly costs what the first raise does not. Each propagation prepends a traceback node per frame it unwinds through, and each node pins that frame's locals, so a held failure raised often enough retains a slice of every call that received it. FailureReport captures the failure's traceback, context and context-suppression flag as they stood at the first report and restores them before each raise. The depth a caller receives is then the same at the hundredth report as at the first, and identity and type are untouched. What it bounds is growth, not retention.
A source that failed reached only whichever consumer happened to be pulling; every other consumer ended as though the source had simply run out. The failure is now recorded on the container and re-raised from each consumer in place of StopAsyncIteration, including consumers that join after it happened. The pull also belongs to the container rather than to the consumer that started it. A consumer cancelled while waiting no longer throws into the shared source, and the item that pull was fetching still reaches every queue, which is what makes one consumer's teardown its own business. Cancelling the pull is cleanup's alone. Cleanup now cancels an in-flight pull, closes an iterator that is an async generator or exposes an awaitable aclose, and propagates a close failure to the caller that knows which resource was being retired. Consumers are signalled either way. BREAKING CHANGE: FanoutConsumer.enqueue is removed. Pass the items to Fanout.consumer instead, which primes them before the consumer joins the broadcast set, so no source item and no ending can land ahead of them. Fanout now accepts any AsyncIterable and rejects anything else at the construction that supplied it rather than from a later iteration.
The fanout over a pooled subscriber and the worker map replayed to a late joiner lived in class-level weak dictionaries keyed on the subscriber, and the factory that builds a subscriber lived in a module-level registry keyed on the cache key. Neither was reclaimed on the two paths ResourcePool documents as evicting without running finalizers, and the factory registry outlived every subscription that could have used it. Both now hang off the pool entry. _PooledSubscriber carries the subscriber, its fanout and its replay map; the key carries the factory while comparing and hashing on identity alone. The entry is the only referrer, so whatever drops the entry drops them. That bounds the retention, not the teardown those two paths still skip. The class is now part of the cache identity, applied by the metaclass rather than asked of each key callable: the class is not a constructor argument, so a callable returning every argument satisfied the contract while leaving two conforming classes to share one subscriber. The key's hashability is checked at construction rather than from inside the first iteration. The pool finalizer runs both teardown steps even when the first raises, so a subscriber is never left un-retired because closing its fanout failed, and reports the first failure.
ReducibleAsyncIterator returned itself from __aiter__ over a consumed index, so a second iteration yielded nothing. DiscoverySubscriberLike requires iterations to be independent, and a proxy reset to NEW re-iterates whatever it was given — which answered with no events at all while the quorum wait ran out.
__aiter__ is DiscoverySubscriberLike's only member and an async generator has one, so the generator a subscriber returns satisfied both the structural check and a type checker. It is its own iterator, so nothing can iterate it a second time, and it is unpicklable. The test runs ahead of the protocol check rather than inside it: the structural check admits the very object being rejected, so a test nested under it is unreachable.
A discovery subscription that raised left its failure on the detached sentinel task and nothing ever read it. A proxy with a quorum waited out quorum_timeout for a wake-up nothing could send and then reported that timeout; a proxy without one reported NoWorkersAvailable, naming the consequence of a lost membership feed and leaving its cause to be guessed. The sentinel's failure is now read off the task and raised by the next caller the lost membership actually denies: from the quorum wait in place of its timeout, from a dispatch the balancer declines with no worker left to try, and from teardown when neither ran. A dispatch the workers already reported can still serve is served rather than failed, because discovery is a membership feed and not the data plane. Every report goes through one door, which records that the failure reached a caller. Teardown therefore does not raise it a second time, and never displaces an exception the unwind already carries — that one is logged instead. The sentinel also wakes the quorum wait as it ends, since every other setter of that event is on a path the sentinel itself owns.
Every field was optional, so an exception could render a message that omitted the one fact it exists to carry — a capacity, a payload size, a namespace. A keyword-only field cannot survive the worker serializer's cls(*exc.args) rebuild in either direction: riding args makes the call raise for too many positional arguments, and staying out of args either raises for a missing argument or, where the field has a default, succeeds while silently substituting it. Every field is therefore positional and required. Two meanings narrow with it. DiscoveryNamespaceInUse is raised only while a process holding the namespace's claim lives, and no longer names a shared-memory segment for the caller to remove. DiscoveryNamespaceNotFound becomes per-binding rather than per-namespace: it reports that no live owner serves this binding, which is raised while a successor owns the namespace and is live. DiscoveryNamespaceContended is new, for an entry whose namespace directory is replaced faster than it can take the claim. No process holds the claim in that case, so a retry meets the same contention and the remedy is a root nothing else writes to. BREAKING CHANGE: DiscoveryCapacityExhausted, DiscoveryBlockExhausted, DiscoveryWorkerNotFound, DiscoveryNamespaceInUse and DiscoveryNamespaceNotFound all require their fields. DiscoveryNamespaceInUse no longer accepts segment. Every rendered message changed.
The suite drove standalone interpreters to prove that attaching to a namespace's shared-memory segment emits nothing from multiprocessing's resource tracker, and reached into LocalDiscovery for the _attach helper and the segment-name hash to do it. A file-backed registry has no segment and no resource tracker, so neither the helper nor the behaviour this suite was written about survives the change it precedes.
conradbzura
force-pushed
the
353-mmap-local-discovery
branch
from
November 3, 2026 18:56
22c8196 to
fb81bf4
Compare
LocalDiscovery kept its registry in a shared-memory segment. No process can reclaim a segment after a kill, and a namespace had no way to tell a live owner from the residue of a dead one, so a killed pool's namespace stayed in use until something removed its segment by hand and a borrower could not distinguish an owner that had gone from one that was serving it. The registry, the notification file a subscriber watches and each worker's metadata block are now files under a namespace directory, and ownership is a claim an owner holds on it. Each entry mints a generation directory for that owner's artifacts and publishes it through a current pointer; a borrower resolves that pointer and stays pinned to the generation it bound, so it reaches one owner's artifacts and never drifts onto a successor's. A claim sweeps whatever a killed predecessor left before staging its own. A binding now ends with the owner it was made against. A publisher's next publish and a subscriber's next scan raise rather than writing into a registry nothing reads or serving the snapshot they last saw, and that holds however the owner ended: exiting removes the generation, and an owner killed outright is detected because the lock it held dies with its process. A subscription raises rather than reporting every worker as dropped, because an owner leaving is not a membership change. Entry validates what it is given. The namespace must name a single path component, capacity at least one worker, block_size enough for the length prefix and the smallest metadata any worker serializes to, poll_interval positive where given, and lock_timeout non-negative. The claim retry is bounded because entry spins on the caller's thread, and reports contention rather than spinning on. portalocker is no longer a dependency; the cross-process lock is taken through the standard library. BREAKING CHANGE: a namespace's registry is a directory tree rather than a shared-memory segment, so processes on either side of this change do not see each other. LocalDiscovery is single-use — a second entry raises RuntimeError rather than contending — and a borrower whose owner has gone now raises DiscoveryNamespaceNotFound at its next operation instead of serving its last snapshot.
Covers the layout, the ownership contract and the failure modes the file-backed registry introduces: what a claim sweeps, what a fork inherits, what survives a kill, which operations a borrower loses when its owner goes, and the validation entry applies to its arguments. The layout the assertions name is derived from the module rather than respelled, so a rename cannot leave a test pointing at a path nothing creates — which would hold however much residue the product left behind. The shared-memory mock is gone, along with the suites that asserted against it.
The ownership contract is only observable between processes: a claim held per open file description, an owner killed outright, a borrower that outlives one. These drive real subprocesses against a real registry rather than a mock of one. Namespaces are minted through a fixture that removes their directories afterwards, because a namespace whose owner is killed keeps its directory by contract. The residue assertions stay in the tests that make them, since a fixture asserting them would mask the leaks they pin.
The two discovery overviews and the worker README's trust discussion still described LocalDiscovery as shared-memory IPC, and the discovery README named the owner as the instance that created the registry rather than the one holding its claim. The borrowing paragraph also said a borrower that outlives its owner is orphaned, which is no longer what happens: it fails loudly instead.
The raises list named two discovery errors and described one of them as raised when the namespace's registry already exists. It said nothing about the errors a worker start raises through its gather, so DiscoveryCapacityExhausted and DiscoveryBlockExhausted were reachable only by an ExceptionGroup the docstring did not mention, and DiscoveryNamespaceNotFound and TimeoutError each arrive both wrapped and unwrapped depending on which wait finds them. Also records that a discovery instance passed to the pool is entered for the pool's lifetime, so a single-use backend cannot be reused by a second pool, and that a factory is what makes a pool reconstructible.
A pool that owns its registry stamped the backend's default capacity and then spawned one worker per CPU, so on a host with more CPUs than that default the last workers' registrations were refused for want of a slot. The capacity is now the spawn count.
Each example enters a real pool, and the discovery publishes its workers under a cross-process lock that genuinely serializes them, so an example's wall-clock cost scales with the generated worker count and with whatever else the host is doing. A per-example deadline measures the machine rather than the property.
conradbzura
force-pushed
the
353-mmap-local-discovery
branch
from
November 3, 2026 19:38
fb81bf4 to
0d0913d
Compare
Every detailed claim in this module lived at its implementation site, where it duplicated a docstring that already owned it and would rot on the next edit to the code beside it. Three comment blocks ran four to seven lines apiece, and one restated the three lines directly below it. Move that substance to an Implementation notes rubric on the entity that owns the behavior, leaving a pointer where a reader needs one. Plain comment lines drop from 28 to 10 and no block now exceeds two lines. The surviving comments each carry a constraint with no other home: a parsing quirk that forces an annotation off the as target, two notes on why the metaclass hashes early and closes over the pre-injection init, and the duck-type on the optional shutdown hook that DiscoverySubscriberLike does not declare. Two claims had no home at all and gain one. __reduce__ now documents the two-element reduction that keeps the unpicklable factory off the wire, and _iter documents the RuntimeError it raises without a pool. Drop the enumeration of a LocalDiscovery subscriber's exit stack from _PooledSubscriber in favour of a pointer. That list belongs to the class that owns the stack and would drift the moment it changed. State cardinality outright where the names invert it: a _SharedSubscription exists per construction while the _PooledSubscriber it reaches is the shared object. Settle the module on imperative summaries, which the four that were already imperative establish and which the documentation guide requires. No executable code changes. Every definition body is byte-identical after stripping docstrings, and member order is unchanged.
_pool_finalizer sat last in the module, roughly two hundred lines from its sibling _pool_factory and from the ResourcePool construction that passes both. Move it up beside the factory so the pool's two callbacks and the installer that wires them read as the one concept they are, which the Python style guide sanctions as topic-interleaved layout. Pure relocation. The function's text is unchanged and nothing else in the module moves. The stricter ordering the guide states as its default, with every class ahead of every function, would relocate _SharedSubscription and SubscriberMeta for no gain in legibility and is left alone.
The two names inverted the sharing they described. A _SharedSubscription exists once per construction and is never shared, while the _PooledSubscriber it reaches is the object every consumer of a key has in common. A reader who trusted the names got the cardinality backwards, and the suite constructs two of these over one key precisely because each belongs to one caller. _Subscription drops the false claim and the adjective that competed with _PooledSubscriber. It also matches the vocabulary the docstrings already use, where a subscription outlives the subscriber it built, so the three names now read as what they are: a _Subscription iterates a shared subscriber held in a _PooledSubscriber under a _SubscriberKey. Pure rename, with TestSharedSubscription following to TestSubscription. Every changed line differs only by the identifier, except in the test module's import block, where the new name sorts after _SubscriberKey and swaps two lines with it. Test-local names are left alone. A local called shared, which the suite uses in forty-odd tests, is not making the claim the class name made: the subscriber it reaches really is shared.
conradbzura
marked this pull request as ready for review
November 4, 2026 00:22
conradbzura
added a commit
that referenced
this pull request
Nov 4, 2026
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
Replace the POSIX shared-memory segment backing
LocalDiscovery's registry with an ordinary file, and extend the resulting ownership model to every artifact a namespace holds.The motivating defect is not the segment, but its custodian.
multiprocessing.shared_memory.SharedMemoryenrols every segment with CPython'sresource_tracker, a service wool does not use and, below Python 3.13, cannot decline, so the module carried 271 lines whose sole function was escaping that enrolment. Two of the faults the machinery existed to work around — #336 and #340 — are tracker accounting errors rather than wool errors, and are unreachable once no tracker participates.Address the file at fixed offsets through a held descriptor rather than mapping it. On Apple platforms CPython issues a device-level flush (
F_FULLFSYNC) whenever it maps a file descriptor — a cost of milliseconds per mapping, imposed on the whole host — whilepreadandpwriteobtain the same cross-process visibility through the page cache without it. This departs from the mechanism the issue specifies, and the access pattern is the warrant: the registry is a header and fixed-width slots addressed by offset, never traversed as memory, so the mapping purchased nothing the descriptor does not provide.A file-backed registry makes the ownership model expressible, which is the larger half of the change. Each entry of a
LocalDiscoverycontext mints a generation — a directory holding that owner's registry, notification file and worker blocks — published by renaming a pointer atomically into place. The owner owns every artifact within it and stamps the sizes every borrower binds at; its exit frees all of it. A borrower that outlives its owner raisesDiscoveryNamespaceNotFoundat its next read or write, rather than reaching a successor's registry or serving the snapshot it last read, and that error now reaches the caller rather than settling on a task nobody awaits.Two residuals are accepted rather than solved. An owner killed outright leaves its generation on disk until something re-enters the namespace — which, for the per-lifecycle
pool-<uuid>namespaces aWorkerPoolmints, is never; containment under a singlewool/directory bounds the recovery atrm -rf <root>/wool. A process forked from an entered owner disowns the claim but cannot release it, so the namespace remains in use until that fork exits.Breaking changes
DiscoveryNamespaceInUseloses itssegmentfield andLocalDiscovery.Publisherloses itsblock_sizeparameter, which the owner now stamps. Every discovery exception's field becomes required rather than optional, andDiscoveryNamespaceNotFoundrenders a message that no longer asserts the registry is absent, since it fires while a successor's may be present. Of these four, two alter theargsshapecls(*exc.args)reconstructs — thesegmentremoval and the required-field change — and are therefore wire-compatibility breaks;Publisheris not an exception and carries noargs, and the message change leavesargsat(namespace,)on both sides.WorkerProxynow raisesTypeErrorfor an async generator passed asdiscovery, which it previously accepted: pass the subscriber itself rather than the generator its call returns.LocalDiscovery'sblock_sizefloor rises from 5 to the length prefix plus the smallest serialized worker metadata — 68 under the current schema, and derived from it, so a schema change moves the floor rather than stranding the validator — and constructions between the two floors, which previously succeeded and then failed every publish, now raiseValueErrorat construction. Finally, an entry whose namespace directory is replaced faster than it can be claimed raisesDiscoveryNamespaceContended, a new exported exception, where it previously retried without bound.Closes #340
Closes #345
Closes #353
Closes #376
Closes #449
Proposed changes
Back the registry with a file
Remove
multiprocessing.shared_memoryandmultiprocessing.resource_trackerfromlocal.py, along with_suppressing,_create,_attach,_tracker_lock,_shims,_reinit_tracker_state, thesys.version_infogate and_short_hash.tests/integration/test_local_discovery_tracker.pyobserved a fault emitted by a process wool does not control, and with the tracker gone it has no subject.Take every lock through
fcntldirectly and drop theportalockerdependency.local.pywas the package's only consumer, and routing one of four locks through a wrapper produced two spellings of one syscall, two exception vocabularies and two sets of flag constants. The wrapper's stated justification was a portability the module no longer possesses: it importsfcntlandos.preadunconditionally, and the package classifies only macOS and Linux.Narrow
DiscoveryNamespaceInUseto name the namespace rather than a shared-memory segment, and make every discovery exception's field required. No raise site in the tree produces the unknown case — each supplies a concrete value — so the optionality obliged every handler to narrow a value the library never leaves unset.Scope every artifact to an owner's generation
Generation names are minted per entry and never reused, so a borrower pinned to one generation cannot find a different owner's file at a path it remembers. Blocks sit one level down, so the directory a subscriber watches carries registry traffic alone.
The owner stamps both
capacityandblock_sizeinto the registry header, and a borrower binds at those values rather than supplying its own. Sizing an artifact the owner owns is not a borrower's decision: two publishers with different block sizes would otherwise leave differently-sized blocks in one generation, determined by whichever registered each worker first.A publisher no longer owns the blocks it creates. A drop removes the block and nulls its slot within one critical section under the registry lock, which collapses the four-state slot-block space and eliminates the unsynchronised deletion that allowed one publisher's teardown to unlink a block another was writing. A publisher's exit releases handles and removes nothing, so the leak in #345 has no remaining path: no artifact's reclamation depends on a borrower surviving to perform it.
Both borrower kinds bind through one
_Bindingprimitive — resolve the pointer, read the header, pin a descriptor on the generation, probe the owner — so a publisher and a subscriber cannot disagree about what a missing generation, a replaced directory or a dead owner means, and a descriptor exhaustion cannot present as a vanished namespace.Claiming a namespace sweeps whatever a killed predecessor left before staging. The sweep is sound only because a binding now ends with its owner: holding the claim proves the absence of a live writer. It resolves nothing — it lists and unlinks through descriptors, decides directory-ness by
fstatrather than by the errno of a failed unlink, and descends only throughO_NOFOLLOW, because/dev/shmis mode 1777 and shared by every user on the host. What it cannot remove it reports as aResourceWarningrather than suppressing: a stranded generation is the larger of the two leaks this module can produce.Detect an owner that did not exit
Removing a generation is what makes a stale borrower fail, and it covers an owner that exits and an owner swept by a successor. It does not cover an owner killed outright with nothing replacing it, whose files survive and remain readable.
The owner therefore holds an exclusive
flockon its generation directory for that generation's life, and a borrower tests the lock — shared, non-blocking, through a descriptor pinned at bind — within work it already performs. A lock that cannot be taken proves the owner's process alive; one that can be taken proves the kernel dropped it, which it does however the owner died. This is the oracle LMDB and SQLite employ. Only contention answers "alive": a descriptor this process no longer holds answers "dead" because it proves nothing, and anything the probe cannot answer is raised rather than guessed.Probing the generation rather than the claim ensures a borrower can never cause a rival claimant's lock attempt to fail; taking the probe shared ensures concurrent borrowers do not exclude one another. Pinning the descriptor costs 583 ns against 10.4 µs for reopening per check — roughly 1% of a publish, measured at 55–65 µs, and 0.35% of a scan over eight workers, measured at ~167 µs. The probe adds latency and never contention: while the owner lives, every probe fails immediately without acquiring anything.
A parked subscription wakes on
_LIVENESS_INTERVALto re-verify that its owner still holds the generation. The wake is a liveness check, not a rescan — two non-blocking locks and areadlink, against a rescan's read of every registered worker's block and an event per worker — so a subscription with no poll interval stays silent over an idle namespace for as long as it lives, and one with a long poll interval still detects a lost owner without waiting that interval out.Read a block read-only, through an unbuffered handle. The subscriber opens one block per registered worker per scan and never writes, while
_File's reads and writes go directly topread/pwriteon the descriptor, so the buffered read-write handle paid for a write mode it never used and an 8 KiB buffer nothing touched. Measured on APFS: 18,647 ns to 11,039 ns per block, a 39% reduction.Disown an inherited claim in a fork
A process forked from an entered owner inherits its descriptors and its
atexitteardown, so the fork's ordinary exit reclaimed the live parent's namespace. An owner now records the pid that entered it, and teardown running in a process whose pid no longer matches removes nothing. That check is the entire mechanism, and it is the stronger of the two available: it also coversfork(2)issued from C, which anos.register_at_forkhandler never observes.Claiming is split from staging so that a failure has one meaning at each step. Until the claim's lock is held this process owns nothing, and a failure there closes only what it opened — releasing instead would purge the incumbent's generation, which an
ENOLCKon a network filesystem or aKeyboardInterruptlanding mid-call would otherwise trigger. Staging owns the descriptor it opens and closes it on any failure, so the retry loop leaks nothing.Deliver a failure to every consumer of a shared subscription
Fanoutmulticasts one source to several consumers and delivered an exception only to whichever consumer was pulling. The shared iterator remained bound to the generator its own exception had closed, so the next consumer receivedStopAsyncIterationfrom it — every consumer but one ended as though the source had run out.The pull now belongs to the container rather than to the consumer that starts it. A consumer waits on that task without owning it, so a cancellation reaches only that consumer: the pull runs on, the item still reaches every queue, and the shared generator is never thrown into. This is what renders one consumer's teardown its own business, and the property matters in production: two
WorkerProxyinstances on one namespace share aFanout, so stopping one would otherwise freeze the other's membership feed silently.Cleanup closes the iterator rather than the source, which is what actually runs the subscriber's
finallyand releases its descriptor and watchdog thread; a source with noacloseis no longer mistaken for a teardown failure, and a genuine close failure propagates to the pool, which knows which resource it belongs to.Surface a dead subscription to the caller
WorkerProxyconsumes its subscription in a detached task, so the exception settled on a task nobody awaited until teardown. A pool whose namespace lost its owner waited out its whole quorum timeout and reportedasyncio.TimeoutError; a later dispatch reportedNoWorkersAvailable. The class already documented the intended behaviour; the implementation now provides it.The failure is read from the sentinel task rather than cached, so no window exists in which the task holds the answer and the proxy does not. The sentinel wakes the quorum wait from its own
finally, and the placement is load-bearing: every other setter of that event lies on a path the sentinel owns, so a caller parked in the wait would otherwise wait out the timeout for an event nothing could set.Teardown reports the failure only when nothing else is reporting one. A failure a dispatch already raised is not raised again, and one that would displace an exception already unwinding the caller's block is logged instead — a teardown report is worth less than the failure the caller is already handling. Each report restores the chaining state the failure held when first reported, so a caller's traceback is the origin plus their own call rather than the origin plus every call that preceded it.
A proxy whose subscription failed stays started — it retains the balancer, the channel-pool hold and whatever membership it last held — so every later dispatch the membership cannot serve reports the same failure, and retrying those does not help. Recovery is stopping the proxy and starting another, or leaving and re-entering the pool context. With no quorum configured there is no wait for the cause to arrive in, so a dispatch issued first still reports
NoWorkersAvailable, and the cause reaches the dispatch after it; closing that first-dispatch window requires a readiness seam through the subscription pipeline, whose design #444 carries.Release a pooled subscriber's factory with its subscriptions
SubscriberMetaregistered a construction's factory in a module-global dict that was never pruned. A caller minting a fresh key per lifecycle — asWorkerPooldoes, onepool-<uuid>namespace per instance — left one closure behind for the life of the process, under a key tuple holding the subscriber class with it.The registry was redundant. A shared subscription already carries the construction its factory closes over, so one fact had two homes with different lifetimes: the subscription's copy dies with it, the registry's never did. The factory now travels inside the cache key, a frozen pair whose factory member is excluded from equality and hashing, so sharing is decided by the identity alone, exactly as before, while the closure is reachable only from the subscriptions that could use it.
Registering in the old dict hashed the key there, so a key callable returning an unhashable value failed at the construction that supplied it. Carrying the factory in the key would defer every hash to the pool and report the caller's mistake from inside the first iteration, so the identity is hashed at construction instead.
A per-acquisition
factoryparameter onResourcePool.getwas considered and rejected: the pool already lets the caller choose the key, so the payload belongs in the key rather than beside it, and a parameter silently ignored on a cache hit promises more than it delivers.Test cases
TestLocalDiscoveryTestLocalDiscoveryDiscoveryNamespaceInUseTestLocalDiscoveryTestLocalDiscoveryTestLocalDiscoveryTestLocalDiscoveryTestLocalDiscoveryTestLocalDiscoveryTestLocalDiscoveryTestLocalDiscoveryDiscoveryCapacityExhaustednaming the owner's capacityTestLocalDiscoveryDiscoveryNamespaceNotFoundTestLocalDiscoveryResourceWarningTestLocalDiscoveryPublisherTestLocalDiscoveryPublisherDiscoveryNamespaceNotFoundand reaches no successorTestLocalDiscoveryPublisherDiscoveryNamespaceNotFoundTestLocalDiscoveryPublisherRuntimeErrornaming the misuseTestLocalDiscoverySubscriberTestLocalDiscoverySubscriberTestSubscriberLivenessDiscoveryNamespaceNotFoundTestSubscriberLivenessTestSubscriberLivenessTestSubscriberLivenessTestFanout__aiter__and noaclosefinallyTestFanoutTestFanoutConsumerTestFanoutConsumerTestFanoutConsumerTestWorkerProxyDiscoveryNamespaceNotFoundwell inside the quorum timeoutTestWorkerProxyNoWorkersAvailableTestWorkerProxyTestWorkerProxyTestWorkerProxyTestSharedSubscriptionTestCrossProcessOwnershipSIGKILLTestCrossProcessOwnershipTestCrossProcessBorrowingTestNamespaceResidueSIGKILLTestNamespaceResidueTestPoolNamespaceOwnershipDiscoveryNamespaceNotFoundwithout waiting out the quorum timeoutTestDiscoveryFailureIsolationTestSubscriberMetaTestSubscriberMetaTestSubscriberMetaTypeErrorat the constructionTestSharedSubscription