Skip to content

Back the discovery registry with a file instead of shared memory — Closes #340, #345, #353, #376, #449 - #441

Merged
conradbzura merged 19 commits into
wool-labs:mainfrom
conradbzura:353-mmap-local-discovery
Nov 4, 2026
Merged

conradbzura merged 19 commits into
wool-labs:mainfrom
conradbzura:353-mmap-local-discovery

Conversation

@conradbzura

@conradbzura conradbzura commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

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.SharedMemory enrols every segment with CPython's resource_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 — while pread and pwrite obtain 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 LocalDiscovery context 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 raises DiscoveryNamespaceNotFound at 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 a WorkerPool mints, is never; containment under a single wool/ directory bounds the recovery at rm -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

DiscoveryNamespaceInUse loses its segment field and LocalDiscovery.Publisher loses its block_size parameter, which the owner now stamps. Every discovery exception's field becomes required rather than optional, and DiscoveryNamespaceNotFound renders 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 the args shape cls(*exc.args) reconstructs — the segment removal and the required-field change — and are therefore wire-compatibility breaks; Publisher is not an exception and carries no args, and the message change leaves args at (namespace,) on both sides. WorkerProxy now raises TypeError for an async generator passed as discovery, which it previously accepted: pass the subscriber itself rather than the generator its call returns. LocalDiscovery's block_size floor 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 raise ValueError at construction. Finally, an entry whose namespace directory is replaced faster than it can be claimed raises DiscoveryNamespaceContended, 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_memory and multiprocessing.resource_tracker from local.py, along with _suppressing, _create, _attach, _tracker_lock, _shims, _reinit_tracker_state, the sys.version_info gate and _short_hash. tests/integration/test_local_discovery_tracker.py observed a fault emitted by a process wool does not control, and with the tracker gone it has no subject.

Take every lock through fcntl directly and drop the portalocker dependency. local.py was 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 imports fcntl and os.pread unconditionally, and the package classifies only macOS and Linux.

Narrow DiscoveryNamespaceInUse to 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

<root>/wool/<namespace>/     the claim; outlives any one owner
├── current                  symlink to the live generation
└── <generation>/            one per owner entry
    ├── registry
    ├── registry.tmp         transient, between write and rename
    ├── notify
    └── blocks/<worker-uuid>

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 capacity and block_size into 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 _Binding primitive — 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 fstat rather than by the errno of a failed unlink, and descends only through O_NOFOLLOW, because /dev/shm is mode 1777 and shared by every user on the host. What it cannot remove it reports as a ResourceWarning rather 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 flock on 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_INTERVAL to re-verify that its owner still holds the generation. The wake is a liveness check, not a rescan — two non-blocking locks and a readlink, 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 to pread/pwrite on 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 atexit teardown, 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 covers fork(2) issued from C, which an os.register_at_fork handler 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 ENOLCK on a network filesystem or a KeyboardInterrupt landing 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

Fanout multicasts 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 received StopAsyncIteration from 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 WorkerProxy instances on one namespace share a Fanout, 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 finally and releases its descriptor and watchdog thread; a source with no aclose is 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

WorkerProxy consumes 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 reported asyncio.TimeoutError; a later dispatch reported NoWorkersAvailable. 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

SubscriberMeta registered a construction's factory in a module-global dict that was never pruned. A caller minting a fresh key per lifecycle — as WorkerPool does, one pool-<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 factory parameter on ResourcePool.get was 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

# Test Suite Given When Then Coverage Target
1 TestLocalDiscovery A namespace no owner holds An owner enters it It stages a generation and publishes the pointer to it Claim and stage
2 TestLocalDiscovery A live owner holding a namespace A second owner claims the same namespace It raises DiscoveryNamespaceInUse Single ownership
3 TestLocalDiscovery An owner whose registry is staged A borrower probes during the rename It binds a stamped registry or none Atomic publication
4 TestLocalDiscovery A predecessor killed with its generation intact A fresh owner claims the namespace It sweeps the predecessor and leaves only its own generation Sweep on claim
5 TestLocalDiscovery A rejected claim registered for teardown, and an unrelated directory on the descriptor number it released That rejected instance is exited It leaves the unrelated directory untouched Claim sentinel
6 TestLocalDiscovery A namespace whose generation publication fails partway through An owner enters and exits it It holds no more descriptors than before Staging owns what it opens
7 TestLocalDiscovery An incumbent owner and a filesystem whose lock call fails for a reason other than contention A second owner is entered It raises that error and leaves the incumbent's worker discoverable Claim failure reclaims nothing
8 TestLocalDiscovery An owner and a child forked from it The child runs the inherited teardown and exits It removes nothing and the parent's namespace still binds Fork disown
9 TestLocalDiscovery An owner whose block size exceeds the default A separately constructed publisher publishes oversized metadata It publishes successfully Owner stamps the sizes
10 TestLocalDiscovery An owner with a capacity of one and a worker registered A borrower registers a second worker It raises DiscoveryCapacityExhausted naming the owner's capacity Borrower binds the capacity
11 TestLocalDiscovery An owned namespace whose registry is overwritten unstamped or truncated A publisher binds it It raises DiscoveryNamespaceNotFound Header is validated once, at bind
12 TestLocalDiscovery An owner whose teardown removals fail The owner exits It reports each entry it could not remove as a ResourceWarning Sweep failures are not silent
13 TestLocalDiscoveryPublisher A publisher with a registered worker The worker is dropped It frees the slot and removes the block together Slot and block lifetime
14 TestLocalDiscoveryPublisher A publisher bound while its owner was live The owner exits and a successor claims the namespace It raises DiscoveryNamespaceNotFound and reaches no successor Binding ends with its owner
15 TestLocalDiscoveryPublisher A namespace whose owner was killed outright A publisher binds it It raises DiscoveryNamespaceNotFound Liveness at bind
16 TestLocalDiscoveryPublisher A publisher whose context has been exited It publishes again It raises RuntimeError naming the misuse Lifecycle is explicit
17 TestLocalDiscoverySubscriber A subscription streaming a worker Its owner exits mid-iteration It raises rather than serving the snapshot Loud failure over stale reads
18 TestLocalDiscoverySubscriber A registry slot naming a block that was removed A subscriber scans It skips the slot and still reports the readable worker Carry-forward
19 TestSubscriberLiveness A subscription whose owner is killed with the registry left readable The subscription scans again It raises DiscoveryNamespaceNotFound Liveness lock
20 TestSubscriberLiveness A live owner, one worker, and a drained subscription with no poll interval No publisher writes across several wake boundaries It emits nothing An idle namespace costs nothing
21 TestSubscriberLiveness A subscription whose poll interval far exceeds the liveness interval Its owner is killed It raises on the liveness interval, not the poll one The bound holds for every interval
22 TestSubscriberLiveness A failed subscription with no iteration left open A successor claims the namespace and a fresh subscriber iterates It discovers the successor's worker Recovery after failure
23 TestFanout A fanout over a source with __aiter__ and no aclose Cleanup runs after the iterator is initialised It runs the underlying stream's finally Cleanup closes the iterator
24 TestFanout A fanout whose source raises while closing Cleanup runs It raises that failure and still signals every consumer Close failures reach the pool
25 TestFanoutConsumer Two consumers sharing a source that raises part way through Each pulls again Both raise that failure Failure reaches every consumer
26 TestFanoutConsumer Two consumers sharing a suspended source, one cancelled mid-pull The source yields and the survivor pulls It receives that item and no failure is recorded Cancellation is one consumer's own
27 TestFanoutConsumer Three consumers of one fanout over a source counting its advances All three pull concurrently It advances the source once and hands that item to each Single-flight pull
28 TestWorkerProxy A namespace with no owner and a quorum that can never be met A non-lazy proxy is entered It raises DiscoveryNamespaceNotFound well inside the quorum timeout Quorum wait faults
29 TestWorkerProxy A started proxy whose subscription has since raised A task is dispatched It raises that failure rather than NoWorkersAvailable Dispatch faults
30 TestWorkerProxy A proxy whose subscription failed and whose dispatch reported it The proxy is stopped It returns cleanly Reported once
31 TestWorkerProxy A proxy whose subscription failed with nothing having reported it Its context exits carrying an exception from the body It lets the body's exception reach the caller Teardown displaces nothing
32 TestWorkerProxy A proxy whose subscription failed Many dispatches each report that failure It hands every caller a traceback of the same depth Reports do not accumulate
33 TestSharedSubscription Two iterations of one shared subscription over a suspended source One is cancelled mid-pull and the source yields It delivers the event to the survivor A peer's teardown is not the end
34 TestCrossProcessOwnership An owner in an independent interpreter, killed with SIGKILL A successor claims the namespace It claims, repels a rival, and its exit removes the directory Cross-process reclaim
35 TestCrossProcessOwnership Four interpreters racing one wall-clock deadline All claim the same namespace Exactly one wins Mutual exclusion
36 TestCrossProcessBorrowing A publisher in an independent interpreter whose owner has exited It publishes a worker It reports itself stranded and the successor's registry stays empty No inherited borrowers
37 TestNamespaceResidue A borrowing publisher killed with SIGKILL Its owner exits It reclaims the directory and leaves nothing on disk #345
38 TestNamespaceResidue Three pool lifecycles on default namespaces Each enters, dispatches and exits Each creates one namespace directory and removes it Containment
39 TestPoolNamespaceOwnership A namespace no owner holds A durable pool borrowing it is entered eagerly It raises DiscoveryNamespaceNotFound without waiting out the quorum timeout #376
40 TestDiscoveryFailureIsolation A live two-worker pool whose registry is unlinked externally The pool tears down Both workers are reaped and each announcement failure is logged External removal
41 TestSubscriberMeta A subscriber class constructed but never iterated Every reference is dropped and a collection runs A weak reference to the class clears Factory released with its subscriptions
42 TestSubscriberMeta A key callable omitting a constructor argument, and two constructions differing in it The surviving one is iterated It builds with that construction's argument Build serves the construction it is made for
43 TestSubscriberMeta A key callable returning an unhashable value A subscriber is constructed It raises TypeError at the construction Hashability reported at its source
44 TestSharedSubscription A subscription whose subscriber the pool has retired The same subscription is iterated again It builds a second subscriber and yields from it Rebuild after retirement

@conradbzura conradbzura self-assigned this Sep 18, 2026
@conradbzura conradbzura added this to the v0.16 milestone Sep 18, 2026
@conradbzura
conradbzura force-pushed the 353-mmap-local-discovery branch from 133f60d to 2cabe5a Compare September 20, 2026 00:39
@conradbzura
conradbzura force-pushed the 353-mmap-local-discovery branch from d792b9b to e1417c8 Compare October 6, 2026 18:17
@conradbzura conradbzura changed the title Back the discovery registry with a file instead of multiprocessing.shared_memory — Closes #353 Back the discovery registry with a file instead of shared memory — Closes #353 Oct 22, 2026
@conradbzura
conradbzura force-pushed the 353-mmap-local-discovery branch 2 times, most recently from f339700 to 79444c6 Compare November 3, 2026 13:05
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
conradbzura force-pushed the 353-mmap-local-discovery branch from 22c8196 to fb81bf4 Compare November 3, 2026 18:56
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
conradbzura force-pushed the 353-mmap-local-discovery branch from fb81bf4 to 0d0913d Compare November 3, 2026 19:38
@conradbzura conradbzura removed this from the v0.16 milestone Nov 3, 2026
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
conradbzura marked this pull request as ready for review November 4, 2026 00:22
@conradbzura conradbzura changed the title Back the discovery registry with a file instead of shared memory — Closes #353 Back the discovery registry with a file instead of shared memory — Closes #340, #345, #353, #376 Nov 4, 2026
@conradbzura
conradbzura merged commit b0235e9 into wool-labs:main Nov 4, 2026
11 checks passed
@conradbzura conradbzura changed the title Back the discovery registry with a file instead of shared memory — Closes #340, #345, #353, #376 Back the discovery registry with a file instead of shared memory — Closes #340, #345, #353, #376, #449 Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment