Repository navigation
Release v0.16.0 - #452
Merged
Merged
Release v0.16.0#452
Conversation
WorkerProxy.start built an AsyncExitStack purely for rollback and then discarded it with a bare pop_all(), so stop() had to rebuild the same unwind by hand. The teardown order lived in two places, and a failed start exited the load balancer and discovery managers with (None, None, None) while stop forwarded the real exception. start now keeps the popped stack and stop unwinds it with the exception info it was given, so the order is written once and a start that fails part-way hands its exception to every context it had entered. The _enter_context/_exit_context pair becomes one asynccontextmanager, _resolved, that enter_async_context composes directly; the sentinel cancel and the attribute reset are split so the reset runs after every context has exited on both paths. A stop whose teardown raises now leaves the proxy stopped rather than half-started. Two tests pin the forwarding: the body's exception reaching the load balancer's __aexit__ through the proxy's async-with, and a failed start exiting the load balancer with the failure.
A pool that rebound to a new loop logged the entries the old loop left behind at warning level only when one was still referenced; idle ones went to debug, as if the drop were the expiry the TTL would have delivered. It is not: expiry runs the finalizer and a drop abandons the resource, so an idle gRPC channel left this way leaks its socket and threads just as a referenced one does. Both counts are now reported at warning level, so the leak is visible without turning debug logging on.
The pool had a teardown primitive, clear, which force-finalizes regardless of reference count, and a per-key retirement, expire, which drains first. Nothing retired a whole pool safely while its loop kept running: a caller that knew a loop was done with its resources could only clear, and clearing with references outstanding lets a later release land on whatever entry has since been rebuilt under the same key. expire_all is expire applied to every cached key at once: unreferenced entries are finalized now, referenced ones are marked and finalized by the release that drops their last reference, and a re-acquire before that release resurrects the entry. The per-entry step is shared with expire through _retire. Retirement is all-or-nothing in reach, not in outcome. A finalizer that raises Exception is contained per entry as before; any other BaseException, such as the CancelledError a cancelled teardown raises out of the first channel close, is re-raised only once every remaining key has been retired, since abandoning the sweep there would strand every key behind it, i.e., the leak the primitive exists to close.
A pooled gRPC channel was closed by nothing but the pool's 60 s TTL timer. A dispatch's release only arms that timer, and WorkerProxy never closed the connections it opened, so a loop that stopped inside the TTL, such as asyncio.run around a short script or a test, left the socket and the gRPC threads behind it abandoned, and the pool's next rebind dropped the entry without running its finalizer. Channel lifetime belongs to the pooling layer by design: the key is (target, credentials, options, peer), so many handles share one channel and dropping a handle cannot close it. What was missing was a signal that a loop is done. channel_pool_hold supplies it as a reference counted hold on the channel pool, composed from ResourcePool itself: a one-key pool whose entry is the channel pool and whose finalizer is expire_all, at ttl=0 so the last release retires inline. A reference count that finalizes on its last release is exactly what ResourcePool already is, so this avoids a second counter reproducing the same rules. WorkerProxy takes the hold first in start and gives it back last in stop, which makes the last proxy on a loop close that loop's channels and leaves a proxy nested inside another on the same loop unable to close the outer one's.
…udes Tests over expire_all cover the states an entry can be retired in: idle, referenced, resurrected by a re-acquire before its last release, and released late, where the retired object must be the one finalized and never the entry rebuilt under the same key. A property over arbitrary reference counts holds the invariant the primitive exists for, each cached object finalized exactly once with the pool left empty. The error paths have their own tests: a finalizer raising Exception still evicts every entry, one raising CancelledError does not spare the entries behind it, the first failure is the one re-raised, and a retirement racing a fired TTL timer on the pool lock cancels that cleanup and finalizes once. The idle-orphan drop test asserts a warning rather than a debug record. At the connection, nested holds show the channel staying open past the inner release and closing once at the outer, a hold released mid-dispatch shows the dispatch's own reference outliving it, and a channel whose close raises or is cancelled is retired anyway rather than wedging the release. At the proxy, two started proxies show the same nesting through start and stop, a start that raises hands its hold back, a teardown that raises still releases the hold, and a restart takes a hold of its own. Six tests that started a proxy and never stopped it now stop it, since a started proxy holds something the next loop's rebind would report. sample_task, async_stream, mock_grpc_call, and dispatching_stub move to the package conftest where the proxy tests can reach them, joined by pooled_channel, the channel mock six connection tests each built by hand.
Eight integration tests over what the pool holds after a dispatch has already succeeded. The pairwise array cannot carry them: its oracle is that the dispatch returned the expected value, while every claim here is an entry count, a drop warning, or a channel closed on one loop and not another, and the arrangements they need, a lifecycle run to completion on a loop that then stops or a worker whose proxy pool retires mid-test, are not dimensions a row can hold without breaking that oracle. A bare WorkerConnection left open on a loop that stops is the control: it is the one case that must report a stranded channel, and what makes the silence of the proxy-held cases mean something. A proxy over an external worker the pool never stops is the case that fails without the hold, as is a worker's own nested-dispatch channel, which now retires with the proxy the worker cached for it. The rest pin the surrounding guarantees: a pool's exit settles to zero, an inner pool on the same loop leaves the outer pool's channel cached and the outer pool dispatchable, and a cancelled consumer whose teardown release chases the pool's exit settles without corrupting the entry the stop RPC rebuilt and without leaving an unawaited coroutine. poll_until_channel_pool_settles absorbs the beat between an exit returning and its retirement landing, run_on_foreign_loop stops a loop the way a finished program does, and a proxy_pool_ttl builder override lets a test watch a worker's proxy retire, following the backpressure precedent for knobs the spawned workers need.
Resource skipped the pool release when the object it held was falsy, so an entry whose factory returned None, 0, an empty container, or False kept its reference count forever and was never finalized. The release now follows the acquisition rather than the value, which also lets a pool cache None as a deliberate placeholder entry.
…Proxy WorkerProxy resolved a configured load balancer or discovery source through one helper, and WorkerPool resolved its discovery and publisher through a byte-identical pair, so the two drifted on the axis that mattered: the proxy's helper forwarded the live exception to a context manager's exit while the pool's reconstructed it from sys.exc_info. One asynccontextmanager, resolved, now lives beside the Factory alias whose forms it interprets, and both use it. A manager's exit receives the block's exception info and its return value is ignored, so a manager that suppresses cannot swallow the failure of the block that entered it.
Brings the pre-first-step teardown fix from master into main, where the channel-pool retirement work had changed the same test modules. Resolutions: - tests/runtime/worker/test_connection.py: main had moved the dispatch fixtures into the worker conftest; keep that move and carry master's call-recording dispatching_stub into conftest, which the new teardown tests read back. Keep both sides' imports. - tests/integration/routines.py: keep both sides' imports. Reviewed without conflict: connection.py applies master's teardown change beside main's pool changes with the exit stack unchanged, and test_worker_shutdown.py, test_session.py, and helpers.py add master's tests alongside main's.
Brings the peer-tolerant worker-loop drain from master into main, where the channel-pool retirement work had changed the same teardown. Resolutions: - service.py: keep main's clear sequence, which adds the channel pool after the proxy and subscriber pools and runs the drain from a finally so a clear that raises an interrupt cannot skip it; apply master's per-clear retry on a peer cancel to every entry in that sequence, and master's stop timer, private-future drain, and fresh leak count. The teardown docstring takes master's concise form with main's contract points on clear order, the budget, the interrupt path, and the zero-timeout race. - test_service.py: scope the abandoned proxy-pool clear test's clear warnings to the proxy pool, since the peer it plants now also cancels the channel clear that follows. - routines.py: keep both sides' imports.
The reap fixture cancels and awaits every task on a leftover worker loop, and gave up waiting for the loop to stop after five seconds. A stop that returns without joining its thread can leave the service's own drain running when the fixture starts; that drain absorbs the fixture's cancel and, awaited by the fixture, runs to its full budget. The fixture could then return with the loop still running, and the channel-pool teardown that follows raised on the pool still bound to it. Wait past the service's drain budget instead.
A pool served one running loop at a time: it bound to the first loop that touched it, rebound when another loop arrived once the first had stopped, dropping whatever that loop left, and raised when two running loops used it at once. The pooled objects are loop-affine, so a process that drives one pool from several loops, or from a loop that outlives the one that first touched it, had no correct path. Each loop now gets a private partition: its own cache, reference counts, lock, and TTL timers, reached through a weak-key registry guarded by a threading lock so the lookup stays correct without the GIL. Every operation acts on the calling loop's partition alone, and a process-wide clear no longer exists. Liveness is whether the loop is closed, the predicate asyncio's own cross-loop paths use: a loop paused between two runs keeps its partition, while a partition whose loop closed without clearing is discarded by the next mutating operation on any loop, its entries dropped without their finalizers and the drop reported at warning level under the pool's factory name, since a resource stranded that way is a leak whether or not anything still referenced it. The reads discard, register, and log nothing. A reference is taken and dropped only through the Resource that get returns; the pool-level acquire and release pair is removed, so a caller can only return what it was given. The handle releases into the entry it acquired from, matched by identity, so a release whose entry a clear evicted drops nothing, and an exit on another loop is refused but handed to the acquiring loop rather than lost. The reference is dropped before the exit can suspend, and a last release that must finalize runs as a shielded task the partition tracks. clear takes a deadline that bounds each key's finalizer, stops the sweep when it elapses, and limits the wait for in-flight releases. The channel pool's stats and clear are loop-scoped accordingly, the clear drops the loop's holds before its channels under the same deadline, and channel_pool_hold_stats reads the holds pool. Resource and ResourcePool join the public surface. LocalDiscovery's publisher keeps a handle per published block and closes every block it holds before exiting the pool, propagating the first failure.
The discovery subscriber pool was created inside the first dispatch task that needed it and set on that task's context. A ContextVar set there is invisible to the servicer task that later tears the worker loop down, so a pool the teardown could not see was a partition dropped unfinalized when the loop closed. install_subscriber_pool creates and sets the pool in the calling context when it has none, and the worker process calls it during bootstrap, in its own context rather than a dispatch task's, so every task in the process inherits one pool the teardown can reach.
The worker-loop finalizer ran each pool clear under wait_for with whatever remained of the shared drain budget. A clear reached after an earlier one had consumed the budget was handed a zero timeout, and wait_for cancels a coroutine given no time before its first step, so that clear was skipped rather than bounded; the channel clear, always last, was the one most likely to be dropped, leaving the loop's channels for the next loop to report. Cancelling the whole clear was also the wrong bound: a sweep absorbs a delivered cancellation per key and carries on, so an outer cancel cost one finalizer and let the rest run unbounded. Each clear now runs on the teardown task under timeout_at with a deadline off the shared budget but never less than _CLEAR_FLOOR in the future, and is handed that deadline so the pool cancels the finalizer that is overrunning rather than the clear as a whole. The floor bounds the teardown's worst case at the budget plus one floor per starved clear. A clear that exceeds its deadline is logged; a peer's cancellation, or one the clear absorbed and re-raised, is retried while the deadline remains; and the drain runs whatever a clear raised. With each loop clearing its own partition, the zero-timeout path can no longer race a successor loop's first use of the channel pool.
Everything start entered belongs to the loop that entered it. Under the old pool contract a stop from another loop hit the bound-loop error; under partitioning the exit stack unwinds on the wrong loop and keeps going past the first exit that fails, so the innermost context's refusal survives only as a __context__ while the outer ones have already torn foreign state down. WorkerProxy records the loop it started on, and stop and exit on any other loop are refused with RuntimeError before the stack is touched, leaving the proxy started and every resource intact for the owning loop to stop. A pooled proxy whose exit fails during its finalization is logged rather than passed over.
The guide sets both abbreviations in American style, with a comma after the closing period. These are the sites that lacked it.
The pool suite gains shared fixtures for loops on daemon threads and for loops left stopped or closed, and covers the registry under real contention, the discard from every mutating entry point and its absence from the reads, stranded-count reporting over the whole count domain, a paused loop's entries, timers, and in-flight cleanups surviving another loop's use of the pool, the cross-loop release and its hand-back in every ordering of its checks, a release cancelled in the woken-waiter window, clear under a deadline already elapsed, one that elapses mid-sweep, and one that leaves an in-flight release running, and bookkeeping independence under any interleaving of operations on two loops. The TTL schedule and the get contract are properties over their domains. Tests that asserted API shape, duplicated a sibling, or exercised the removed primitives are removed; the rest are named for the public method each body drives and ordered foundational-first. The connection suite exercises stats, clear, and the hold across live loops with a channel built per call, pins both pools' discard records, the holds pool's counters, and the clear's deadline over both pools, and generalizes retirement to any subset of loops. The service suite pins the teardown deadline for every clear and any budget, the floor handed to a starved clear, the bound on a stop whose clear overruns, and a retried clear reaching the clear after it, driving real pools wherever a test asserts that a clear did its work. The proxy suite pins loop-scoped hold release, a whole lifecycle off the main loop, and a cross-loop stop refused yet handing its hold back. The discovery suite pins a subscriber per loop, a loop-scoped clear, the installed pool, and the publisher's exit releasing every block. The reap fixture cancels once and waits rather than gathering, so it cannot recurse into a production drain on the same loop.
An autouse gate fails a test that ends with a channel or a hold still cached on its loop, before clearing, so a stranded entry is attributed to the test that caused it rather than reported against whichever test runs next. The lifecycle module gains two pool lifecycles on two concurrent loops, the discard from a loop that already holds a partition, both pools' records for a proxy stranded with its hold open, a clear and a hold release on a foreign loop leaving this loop's channels alone, one channel per loop to one worker, a stream parked mid-dispatch across another loop's lifecycle, the retired nested pool mode, and the worker loop's own partition. Worker teardown is observed through the spawned worker's stderr, and the tests that need it skip rather than pass vacuously when stderr is not captured: a graceful stop after a nested dispatch reaps without a failed clear or a stranded partition, and a default-grace stop landing on an in-flight nested dispatch returns within its bound. The builder gains a pool mode in which a nested pool has retired before the test body runs, its tests assert the process and channel counts that distinguish each nested mode, the discovery constraints are shared by the pairwise filter and the Hypothesis strategy and checked to agree, and the scenario model gains merge identity, merge idempotence, and its string invariant as properties.
The done-callback on a fired TTL cleanup task only logged failures. A task cancelled by anything but the pool, as a loop-wide drain that cancels every pending task does, left its entry cached with no timer and no live cleanup, so nothing would ever finalize it. A cancellation landing after the task's first step orphaned the entry the same way, since the cleanup absorbs cancellation and ends normally with the entry untouched. The callback now re-arms the entry's TTL when the task settles with the entry still cached, unreferenced, untimed, and still naming that task as its cleanup. The last condition separates an outside cancellation from the pool's own, which unrecords the task before cancelling it. The entry is finalized when the TTL elapses again.
The READMEs name the owner, borrower and orphan roles, show how a durable pool borrows a local namespace, and defer the contract to the LocalDiscovery docstring.
A finalizer's contextvars context was whatever the triggering operation happened to carry, undocumented either way. A caller that wants to scope per-teardown state — a context variable set around a clear, read by the finalizer that clear runs — had no guarantee to rely on, and the three paths that reach a finalizer differ: a clear, expire or expire_all runs it inline on the calling task; dropping the last reference on a zero-TTL pool or a doomed entry runs it in the releasing task's context; and a cleanup the TTL spawned runs it in the context captured when the expiry timer was armed. The docstring now states all three, and never a later caller's. The tests pin each one.
The three numbers that shape a worker-loop teardown — the drain budget, the per-clear floor and the pooled loop's idle TTL — were module constants, so a test that needed a short one patched the module and a caller that needed a different one could not have it. They are now constructor parameters on WorkerService: drain_timeout, min_clear_timeout and worker_loop_ttl, each defaulting to None and falling back to the module constant that still records its sizing rationale. The drain budget and the floor resolve per teardown rather than at construction, so a module default rebound after the service exists is still honoured. The TTL resolves at construction because the loop pool consumes it there. _CLEAR_FLOOR is renamed _MIN_CLEAR_TIMEOUT to match the parameter that now overrides it.
The loop-teardown finalizer joined the worker thread for self._stop_timeout seconds, which only a stop ever set and which defaulted to None — an unbounded join. A teardown the idle TTL drove therefore waited forever on a worker thread that would not exit, and because the dispatch that needs a fresh loop waits for the retirement it arrives into, one blocked thread stalled every later dispatch indefinitely. The join bound now follows the teardown's provenance rather than whether a stop was requested. A stop publishes its mapped timeout in a context variable set around its own pool clear, so exactly the finalizers that clear runs inherit it — which rests on the finalizer context ResourcePool now promises. A teardown that finds no budget is one the TTL drove, including one firing while a stop drains in-flight work, and bounds its join by the retirement's own worst case: the drain budget plus one per-clear floor for every clear it runs. A thread still running at a positive bound is left to the daemon reap at process exit, reported at warning level for a TTL-driven teardown and at debug for a stop-driven one, whose caller chose the bound it outlived. This makes the stop RPC's timeout mapping worth stating, since it now governs two sequential waits: 0 cancels in-flight work and performs no join, a positive value bounds each wait in turn, and a negative value waits indefinitely for both. A stop landing while an idle retirement is underway waits out that retirement's bound instead, whatever the request timeout, and can return with the retiring thread still running. The wire comment, both READMEs, the connection's grace parameter and dispatch's own docstring now say so where a caller will look.
The graceful stop call's deadline was grace plus a flat five seconds, sized when the stop timeout bounded one wait. It bounds two — the in-flight drain and the worker-thread join — so a worker that used its full grace for the drain had its join cut short by a deadline that expired during it, and stop() reported a transport failure for a shutdown that was proceeding correctly. The deadline is now twice the grace plus a margin sized from the teardown budgets it has to cover: the drain budget, one per-clear floor for each of the worker's three pools, and a second of transport and response overhead. It is computed from the module defaults as they stand at import, which is what the spawned worker process runs with — so WorkerProcess forwards none of them, and a comment there says why. The constant loses its underscore. A margin derived from another module's defaults has to be referable from that module's side, and LocalWorker is no longer the only place its sizing matters. It is package-internal, not part of wool's supported public API.
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.
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.
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.
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.
Auto-generated by the cut release workflow.