Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(model cache): evict records at shutdown() instead of only releasing shared weights (#9494)
Lincoln Stein62943be71627
diff --git a/invokeai/app/services/model_load/model_load_default.py b/invokeai/app/services/model_load/model_load_default.pyindex 47d385cb56..d5ea060b4e 100644--- a/invokeai/app/services/model_load/model_load_default.py+++ b/invokeai/app/services/model_load/model_load_default.py@@ -111,7 +111,10 @@ class ModelLoadService(ModelLoadServiceBase):ram_cache = self.ram_cachecache_key = str(model_path)try:- return LoadedModelWithoutConfig(cache_record=ram_cache.get(key=cache_key), cache=ram_cache)+ # Retrieve with a first-use claim so the record cannot be evicted between the lookup+ # and the wrapper's first lock (see ModelCache.get_with_first_use_claim).+ cache_record, first_use_claim = ram_cache.get_with_first_use_claim(key=cache_key)+ return LoadedModelWithoutConfig(cache_record=cache_record, cache=ram_cache, first_use_claim=first_use_claim)except IndexError:pass@@ -160,9 +163,17 @@ class ModelLoadService(ModelLoadServiceBase):# a worker sharing this cache built it while we waited.with MODEL_LOAD_LOCK.write_lock():try:- return LoadedModelWithoutConfig(cache_record=ram_cache.get(key=cache_key), cache=ram_cache)+ cache_record, first_use_claim = ram_cache.get_with_first_use_claim(key=cache_key)+ return LoadedModelWithoutConfig(+ cache_record=cache_record, cache=ram_cache, first_use_claim=first_use_claim+ )except IndexError:passraw_model = loader(model_path)- ram_cache.put(key=cache_key, model=raw_model)- return LoadedModelWithoutConfig(cache_record=ram_cache.get(key=cache_key), cache=ram_cache)+ # The admission claim shields the record until this retrieval's own claim takes over+ # (see ModelCache.put), so nothing can evict the model still held in raw_model here.+ admission_claim = ram_cache.put(key=cache_key, model=raw_model, claim_admission=True)+ cache_record, first_use_claim = ram_cache.get_with_first_use_claim(key=cache_key)+ if admission_claim is not None:+ admission_claim.release()+ return LoadedModelWithoutConfig(cache_record=cache_record, cache=ram_cache, first_use_claim=first_use_claim)diff --git a/invokeai/backend/model_manager/load/load_base.py b/invokeai/backend/model_manager/load/load_base.pyindex 9df213f90a..c8bac9b370 100644--- a/invokeai/backend/model_manager/load/load_base.py+++ b/invokeai/backend/model_manager/load/load_base.py@@ -18,7 +18,11 @@ from invokeai.backend.model_manager.load.model_cache.cache_record import CacheRefrom invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_with_partial_load import (CachedModelWithPartialLoad,)-from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK, ModelCache+from invokeai.backend.model_manager.load.model_cache.model_cache import (+ MODEL_LOAD_LOCK,+ FirstUseClaim,+ ModelCache,+)from invokeai.backend.model_manager.taxonomy import AnyModel, SubModelType@@ -53,17 +57,85 @@ class LoadedModelWithoutConfig:do not have a state_dict, in which case this value will be None."""- def __init__(self, cache_record: CacheRecord, cache: ModelCache):+ def __init__(self, cache_record: CacheRecord, cache: ModelCache, first_use_claim: Optional[FirstUseClaim] = None):self._cache_record = cache_recordself._cache = cache- release_first_use_grace = getattr(cache, "release_first_use_grace", None)- self._first_use_finalizer = (- finalize(self, release_first_use_grace, cache_record)- if cache_record.awaiting_first_use and release_first_use_grace is not None+ # The record must stay shielded from the eviction sweeps until this wrapper's first lock:+ # without that, a sweep racing the window — a peer's budget reconcile, another model's+ # make-room, or the cache's shutdown() — evicts the record out from under the wrapper,+ # detaching it from the cache's RAM accounting and (for shared weights) from store+ # ownership while its tensors live on, so a peer's reload of the key mints a duplicate+ # canonical copy the budget counts once.+ #+ # `first_use_claim` is that shield, and callers should always supply one: it was armed by+ # ModelCache.get_with_first_use_claim() under the same lock acquisition as the lookup, so+ # the window is covered from its very first instruction. Adopting it is just holding the+ # reference — its hold is released on the first lock (_end_first_use_window) or, if this+ # wrapper is dropped un-entered, by the claim's own finalizer when it dies with us.+ self._first_use_claim = first_use_claim+ # Fallback for a record obtained through plain get() (or by a caller that could not get a+ # claim): arm the hold here instead. The instructions between that get() returning and+ # this constructor are then unshielded — an eviction landing exactly there is the+ # pre-existing, tolerated issue-7513 detached path, and register_first_use_hold declines+ # to arm on a record that already lost that race. The finalizer below also covers the+ # put()-set admission grace for a record whose hold could not be armed (no deferred worker+ # running). Both release routes quote the epoch the hold was armed under, so a hold the+ # cache's dead-worker recovery already zeroed is never re-released against a successor.+ release_grace = getattr(cache, "release_first_use_grace", None)+ register_hold = getattr(cache, "register_first_use_hold", None)+ self._first_use_hold_epoch: Optional[int] = (+ register_hold(cache_record)+ if first_use_claim is None and register_hold is not None and release_grace is not Noneelse None)+ self._first_use_finalizer = None+ try:+ if (+ first_use_claim is None+ and release_grace is not None+ and (self._first_use_hold_epoch is not None or cache_record.awaiting_first_use)+ ):+ self._first_use_finalizer = finalize(+ self,+ release_grace,+ cache_record,+ self._first_use_hold_epoch is not None,+ self._first_use_hold_epoch if self._first_use_hold_epoch is not None else 0,+ )+ self._first_use_finalizer.atexit = False+ except BaseException:+ # finalize() allocates, and the cache runs at the RAM ceiling by design. A hold armed+ # above with no finalizer to carry its release would shield its record from every+ # eviction path — shutdown()'s sweep included — for the life of the process. Detach+ # first: a failure AFTER the finalizer was registered would otherwise leave it live,+ # and its later release would double-decrement, consuming a hold that by then may+ # belong to a different holder.+ if self._first_use_finalizer is not None:+ self._first_use_finalizer.detach()+ self._first_use_finalizer = None+ if self._first_use_hold_epoch is not None:+ release_hold = getattr(cache, "release_first_use_hold", None)+ if release_hold is not None:+ release_hold(cache_record, self._first_use_hold_epoch)+ self._first_use_hold_epoch = None+ raise++ def _end_first_use_window(self) -> None:+ """This wrapper's first lock ended its get()->lock() window: the record is now pinned by+ its lock count, so drop the abandonment finalizer and release the first-use hold. Runs at+ most once — later re-entries of the context manager find nothing to release."""+ if self._first_use_claim is not None:+ claim, self._first_use_claim = self._first_use_claim, None+ claim.release()if self._first_use_finalizer is not None:- self._first_use_finalizer.atexit = False+ self._first_use_finalizer.detach()+ self._first_use_finalizer = None+ if self._first_use_hold_epoch is not None:+ hold_epoch = self._first_use_hold_epoch+ self._first_use_hold_epoch = None+ release_hold = getattr(self._cache, "release_first_use_hold", None)+ if release_hold is not None:+ release_hold(self._cache_record, hold_epoch)def __enter__(self) -> AnyModel:# Hold the MODEL_LOAD_LOCK read lock across the VRAM load (lock() runs@@ -72,8 +144,7 @@ class LoadedModelWithoutConfig:# Acquired before the cache's own lock to keep a consistent lock order (see MODEL_LOAD_LOCK).with MODEL_LOAD_LOCK.read_lock():self._cache.lock(self._cache_record, None)- if self._first_use_finalizer is not None:- self._first_use_finalizer.detach()+ self._end_first_use_window()try:self.repair_required_tensors_on_device()return self.model@@ -96,8 +167,7 @@ class LoadedModelWithoutConfig:# See __enter__ for why the VRAM load is wrapped in the read lock.with MODEL_LOAD_LOCK.read_lock():self._cache.lock(self._cache_record, working_mem_bytes)- if self._first_use_finalizer is not None:- self._first_use_finalizer.detach()+ self._end_first_use_window()try:self.repair_required_tensors_on_device()yield (self._cache_record.cached_model.get_cpu_state_dict(), self._cache_record.cached_model.model)@@ -113,8 +183,7 @@ class LoadedModelWithoutConfig:def model_in_ram(self) -> Generator[AnyModel, None, None]:"""Pin the model's cache record in RAM without moving the model to its execution device."""self._cache.lock_in_ram(self._cache_record)- if self._first_use_finalizer is not None:- self._first_use_finalizer.detach()+ self._end_first_use_window()try:yield self.modelfinally:@@ -166,8 +235,14 @@ class LoadedModelWithoutConfig:class LoadedModel(LoadedModelWithoutConfig):"""Context manager object that mediates transfer from RAM<->VRAM."""- def __init__(self, config: Optional[AnyModelConfig], cache_record: CacheRecord, cache: ModelCache):- super().__init__(cache_record=cache_record, cache=cache)+ def __init__(+ self,+ config: Optional[AnyModelConfig],+ cache_record: CacheRecord,+ cache: ModelCache,+ first_use_claim: Optional[FirstUseClaim] = None,+ ):+ super().__init__(cache_record=cache_record, cache=cache, first_use_claim=first_use_claim)self.config = configdiff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex e33d870263..9a75588fa6 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -18,6 +18,7 @@ from invokeai.backend.model_manager.load.memory_snapshot import GB, MemorySnapshfrom invokeai.backend.model_manager.load.model_cache.cache_record import CacheRecordfrom invokeai.backend.model_manager.load.model_cache.model_cache import (MODEL_LOAD_LOCK,+ FirstUseClaim,ModelCache,get_model_cache_key,)@@ -249,8 +250,13 @@ class ModelLoader(ModelLoaderBase):if not model_path.exists():raise FileNotFoundError(f"Files for model '{model_config.name}' not found at {model_path}")- cache_record = self._load_and_cache(model_config, submodel_type)- return LoadedModel(config=model_config, cache_record=cache_record, cache=self._ram_cache)+ cache_record, first_use_claim = self._load_and_cache(model_config, submodel_type)+ return LoadedModel(+ config=model_config,+ cache_record=cache_record,+ cache=self._ram_cache,+ first_use_claim=first_use_claim,+ )@propertydef ram_cache(self) -> ModelCache:@@ -285,11 +291,23 @@ class ModelLoader(ModelLoaderBase):return None- def _load_and_cache(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> CacheRecord:+ def _load_and_cache(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None+ ) -> tuple[CacheRecord, Optional[FirstUseClaim]]:+ """Return the model's cache record together with the first-use claim shielding it.++ The claim is armed inside the cache lookup itself (see ModelCache.get_with_first_use_claim)+ and belongs to the LoadedModel this record is about to be wrapped in, which releases it at+ its first lock. It is carried out of here rather than being armed at the wrapper's+ construction so that the record cannot be evicted anywhere along the way — this method's+ two returns, the shell registration below, and load_model()'s own frame. If the load+ raises after the claim is armed, the claim dies with the frame that holds it and releases+ the hold itself.+ """stats_name = ":".join([config.base, config.type, config.name, (submodel_type or "")])cache_key = get_model_cache_key(config.key, submodel_type)try:- return self._ram_cache.get(key=cache_key, stats_name=stats_name)+ return self._ram_cache.get_with_first_use_claim(key=cache_key, stats_name=stats_name)except IndexError:pass@@ -308,7 +326,7 @@ class ModelLoader(ModelLoaderBase):# entry while we waited for the mutex. (Workers on other devices use a different cache,# so they will still miss here and construct their own copy — which is intended.)try:- return self._ram_cache.get(key=cache_key, stats_name=stats_name)+ return self._ram_cache.get_with_first_use_claim(key=cache_key, stats_name=stats_name)except IndexError:pass@@ -354,15 +372,22 @@ class ModelLoader(ModelLoaderBase):# Determine execution device from model config, considering submodel typeexecution_device = self._get_execution_device(config, submodel_type)- self._ram_cache.put(+ admission_claim = self._ram_cache.put(cache_key,model=loaded_model,execution_device=execution_device,+ claim_admission=True,+ )+ # Retrieve immediately, and hold the admission claim across the retrieval: the claim+ # shields the new record until this frame's own claim takes over, so nothing — a peer's+ # reconcile, another model's make-room, the cache's shutdown() — can evict the model+ # this loader is still holding, and a load that dies in between releases the shield by+ # dropping the claim rather than leaving a flag standing that nothing can clear.+ cache_record, first_use_claim = self._ram_cache.get_with_first_use_claim(+ key=cache_key, stats_name=stats_name)- # Retrieve immediately: the new record carries the cache's post-admission grace until- # it is locked, and keeping put() and get() adjacent means no failure in between can- # leave a graced record whose loader never comes back for it.- cache_record = self._ram_cache.get(key=cache_key, stats_name=stats_name)+ if admission_claim is not None:+ admission_claim.release()# Register the shell only after put() has created the shared entry (via the wrapper's# acquire); it is dropped automatically when that entry's last reference is released.@@ -371,7 +396,7 @@ class ModelLoader(ModelLoaderBase):if shared_store is not None:shared_store.set_shell(cache_key, shell_to_register)- return cache_record+ return cache_record, first_use_claimdef get_size_fs(self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = Nonediff --git a/invokeai/backend/model_manager/load/model_cache/cache_record.py b/invokeai/backend/model_manager/load/model_cache/cache_record.pyindex a266cdb79e..14fb4879af 100644--- a/invokeai/backend/model_manager/load/model_cache/cache_record.py+++ b/invokeai/backend/model_manager/load/model_cache/cache_record.py@@ -1,4 +1,6 @@+import weakreffrom dataclasses import dataclass+from typing import Optionalfrom invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_only_full_load import (CachedModelOnlyFullLoad,@@ -22,21 +24,90 @@ class CacheRecord:# change (e.g. fp8_storage toggled during an in-flight generation) takes effect on the# next load instead of silently being ignored.is_stale: bool = False- # Post-admission grace: set by ModelCache.put() (unless the admission is a prefetch of a- # model nothing will come back for) and cleared on the entry's first lock(). A freshly- # admitted model is about to be used — its loader calls get() as soon as put() returns, then- # locks it for inference — so the asynchronous eviction paths (shared-budget reconcile,+ # Post-admission grace: set by ModelCache.put() for unclaimed, non-prefetch admissions and+ # cleared on the entry's first lock(). A freshly admitted model is about to be used - its+ # loader calls get() as soon as put() returns, then+ # locks it for inference - so the asynchronous eviction paths (shared-budget reconcile,# peer-requested eviction) must not treat it as idle: they would evict the record out from# under the in-flight load, breaking the loader's get() or detaching a live model from the# cache's RAM accounting. The grace deliberately survives get(): get() is synchronized, and# its own lock-release hook may run a pending reconcile before the caller can lock the record- # it was just handed. The flag cannot shield a record forever: the cache's local make_room- # path ignores it (cold loads are serialized under MODEL_LOAD_LOCK, so make_room can never- # see another loader's entry inside the put()->lock() window), and the next admission on the- # same cache clears any flag still standing (see the sweep in ModelCache.put()), so a load- # that errors out — or a LoadedModel dropped without ever locking — cannot dodge budget- # reconciles indefinitely.+ # it was just handed. The flag cannot shield a record forever: the synchronous eviction+ # paths (make_room, drop_model) ignore it, and the next admission on the same cache clears+ # any flag still standing (see the sweep in ModelCache.put()), so a load that errors out+ # between put() and the LoadedModel's construction cannot dodge budget reconciles+ # indefinitely. That backstop is why the flag is withheld whenever it could outlive its+ # releasers: an unclaimed admission made with no deferred worker running, and one made after+ # shutdown() - after which no further put() is guaranteed to run the sweep. Claimed admissions+ # use admission_claim_ref below instead, including when no worker can carry a hold. For the same+ # reason shutdown() evicts a record whose only shield is this flag rather than stale-retaining+ # it: a load cancelled before its retrieval leaves no wrapper, so nothing but that sweep could+ # ever have released it. From the retrieval on, the window is+ # tracked by first_use_holds below, whose release is guaranteed by a finalizer rather than by+ # the sweep.awaiting_first_use: bool = False+ # Count of live holders of this record that have retrieved it but not yet locked it. Armed by+ # ModelCache.register_first_use_hold() - from the cache lookup itself+ # (ModelCache.get_with_first_use_claim, so that the window has no unshielded head), or from+ # LoadedModelWithoutConfig.__init__ for a record obtained through plain get() - and released+ # exactly once per holder: on the holder's first lock, or by the weakref finalizer of the+ # FirstUseClaim (or the wrapper) that owns it, if it is dropped without ever locking. Unlike+ # awaiting_first_use, these holds are NOT swept by the next admission: a warm get()'s holder+ # can legitimately sit un-entered across another model's cold load (a node retrieves several+ # models before entering their contexts), and its finalizer guarantees the release the sweep+ # exists to backstop. The only recovery sweep is+ # ModelCache zeroing the counts once the deferred worker - the thread that carries+ # finalizer-initiated releases - is gone (from inside the dying worker itself, and as a+ # backstop at the next worker start and at shutdown), since a release dispatched toward a+ # dead worker may be dropped and would otherwise shield the record forever.+ first_use_holds: int = 0+ # Bumped whenever stranded holds are zeroed (dead-worker recovery). Every hold release+ # carries the epoch it was armed under and is ignored across a bump: without this, a+ # surviving wrapper's late release - or a release enqueued before the old worker died and+ # drained after the restart - would decrement a FRESH hold armed by a different wrapper+ # under the healthy replacement worker, silently unshielding that wrapper's window.+ first_use_holds_epoch: int = 0+ # Weak reference to the FirstUseClaim handed to the loader that admitted this record+ # (ModelCache.put(claim_admission=True)), or None if the admission was not claimed. Resolving+ # it answers, synchronously and with no release path of any kind, the one question the+ # asynchronous eviction sweeps actually need to ask about a just-admitted record: is the load+ # that put it here still running? While it resolves, that loader's own local still holds these+ # tensors, so evicting the record would release shared-store ownership (and debit the budget)+ # for bytes that are still resident - a peer's reload would then mint a duplicate canonical+ # the budget counts once - and would fail the load with an IndexError from a retrieval that+ # can no longer find its own model.+ #+ # This is why the shield the asynchronous sweeps consult is the reference and not the two+ # flags above. awaiting_first_use is unowned: any holder's abandonment+ # (_release_abandoned_holder) and the next admission's sweep clear it on behalf of whoever+ # ran, so one load can strip another's shield. first_use_holds is owned but its release rides+ # on the deferred worker, so dead-worker recovery must zero it - deliberately trading a live+ # holder's shield for the certainty that no record stays shielded forever. A weak reference+ # has neither problem: nothing has to release it, so nothing can release it early or fail to+ # release it at all. That is also why no recovery ever retires it, not even on a shut-down+ # cache with a dead worker: a claim that is still alive means a load that is still between its+ # put() and its retrieval, and evicting its record does not fall back to anything - the+ # retrieval raises. What such a record needs once its claim has died is an eviction trigger,+ # and that is supplied by the claim's finalizer (an abandonment release the queue keeps even+ # with no worker to drain it) and by the sweep every later admission runs when no worker can+ # be started (see ModelCache.put()).+ #+ # Only the asynchronous sweeps consult it, through in_first_use_window below. Synchronous+ # paths ignore this unowned grace, but honor admission_claim_ref because a live claimed load+ # has no other safe fallback after worker recovery.+ admission_claim_ref: Optional["weakref.ref"] = None+ # Set, lock-free, by ModelCache.release_first_use_grace when a hold-less abandonment of this+ # record (a wrapper or claim that never armed a first-use hold) finds it stale and queues the+ # eviction that stale-ness now owes; cleared by the deferred worker the moment it dequeues that+ # item - before the handler runs, so that neither a raise in the handler, nor the worker dying+ # inside it, nor a fork can leave the gate closed with nothing queued behind it. Such+ # abandonments carry nothing to decrement, so one queued+ # item per record is as good as any number, and this flag is what bounds the queue while no+ # worker is draining it: without it every warm get() whose wrapper is dropped un-entered+ # would add an item that nothing removes (JPPhoto review, 2026-09-04). Hold-carrying+ # releases are deliberately not coalesced - each one retires exactly one hold - and are+ # bounded instead by the holds themselves, which are armed only while a worker is alive.+ abandonment_release_pending: bool = Falsedef lock(self) -> None:"""Lock this record."""@@ -51,3 +122,25 @@ class CacheRecord:def is_locked(self) -> bool:"""Return true if record is locked."""return self._locks > 0++ @property+ def admission_in_flight(self) -> bool:+ """True while the load that admitted this record is still between its put() and its+ retrieval - see admission_claim_ref."""+ claim_ref = self.admission_claim_ref+ return claim_ref is not None and claim_ref() is not None++ @property+ def in_first_use_window(self) -> bool:+ """True while a load, a live first-use claim, or a live LoadedModel wrapper is between+ obtaining this record and locking it - including the load that admitted it, for as long as+ it has not come back to retrieve it (admission_in_flight). The asynchronous eviction sweeps+ (budget reconcile and peer-requested eviction) treat such a record like a locked one:+ evicting it would detach a record whose holder is about to lock it, splitting the model from+ the cache's RAM accounting and - for shared weights - releasing store ownership while the+ tensors live on, so a peer's reload would mint a duplicate canonical copy. shutdown() honors+ the owned portions of this window (first_use_holds and admission_in_flight) but deliberately+ does not retain the unowned awaiting_first_use grace. The synchronous paths (make_room,+ drop_model, unlock's stale eviction) honor first_use_holds and admission_claim_ref, but+ ignore the unowned awaiting_first_use grace."""+ return self.awaiting_first_use or self.first_use_holds > 0 or self.admission_in_flightdiff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex 4904ff5d1e..d223a89964 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -8,7 +8,7 @@ from contextlib import contextmanagerfrom dataclasses import dataclassfrom functools import wrapsfrom logging import Logger-from typing import Any, Callable, Dict, Generator, List, Optional, Protocol+from typing import Any, Callable, Dict, Generator, List, NamedTuple, Optional, Protocolimport psutilimport torch@@ -56,6 +56,123 @@ MIN_RAM_CACHE_BYTES = 4 * GB_DEFERRED_RECONCILE = object()_DEFERRED_STOP = object()+_SHUTDOWN_DEFERRED_STOP = object()+++class _AbandonedHolderRelease(NamedTuple):+ """Deferred-work item: a LoadedModel wrapper was dropped without ever locking its record.++ `held_first_use` records whether that wrapper had armed a first-use hold (see+ CacheRecord.first_use_holds), so the release decrements only what its own wrapper armed - a+ grace-only wrapper (one constructed while no worker was running to arm a hold) must not+ consume a hold that belongs to a different, still-live wrapper of the same record.+ `hold_epoch` is the CacheRecord.first_use_holds_epoch the hold was armed under; a release+ from before a dead-worker zeroing sweep must not decrement a hold armed after it.++ The record is referenced WEAKLY. An item can outlive every chance to drain it: the normal+ worker may die after a finalizer dispatches, and a shutdown cache cannot rely on that worker or+ a later admission. A strong reference would pin that record - and through it the model's whole+ CPU state dict - for the life of the process, while the store and the budget both report the+ bytes as released.++ Resolving weakly costs nothing. While the release still has work to do, the record is the live+ occupant of its key in _cached_models, which holds it strongly; and a record already dropped+ from there is one _release_abandoned_holder can do nothing useful for - everything past its+ identity check is gated on live occupancy, and the hold decrement above that check is inert on+ a detached record, since a detached record is never re-attached (put() mints a fresh+ CacheRecord) and every reader of first_use_holds is itself gated on occupancy.+ """++ cache_entry_ref: "weakref.ReferenceType[CacheRecord]"+ held_first_use: bool+ hold_epoch: int+++class FirstUseClaim:+ """Ownership of a first-use hold armed by `ModelCache.get_with_first_use_claim()`.++ The hold is armed under the SAME lock acquisition as the lookup that produced the record,+ which is what makes the shield gapless. Arming it from the LoadedModel constructor instead+ (its original home) leaves the caller's whole get()->construct stretch unshielded, and that+ stretch is not always a few instructions: the configured loader retrieves its record deep+ inside `_load_and_cache` and does the shared-store shell registration and two returns before+ `load_model` wraps it. An eviction landing in that gap - a shutdown sweep, a peer's reconcile+ - detaches the record its holder is about to lock, releasing shared-store ownership while the+ tensors live on, so a peer's reload of the key mints a duplicate canonical copy that the+ budget counts once (JPPhoto review, 2026-08-30).++ The claim releases its hold exactly once, whichever comes first:++ - `release()`, called by the LoadedModel wrapper that adopted the claim when it reaches its+ first lock (see `LoadedModelWithoutConfig._end_first_use_window`);+ - its weakref finalizer, when the claim is dropped without that ever happening - with the+ wrapper that adopted it (dropped un-entered), or with the frame that requested it, if the+ load raised before any wrapper could be built. The finalizer route goes through+ `ModelCache.release_first_use_grace`, so it never takes a lock on the collecting thread+ (see that method), and it quotes the epoch the hold was armed under, so a hold that+ dead-worker recovery already zeroed is never re-released against a successor hold.++ An unadopted claim is therefore not a leak: dropping it is a complete release. That is what+ lets the record be shielded from the moment it is looked up, before any wrapper exists to own+ the shield. After shutdown, its release goes through the dedicated cleanup queue.++ A claim can also be armed with NO hold (`hold_epoch=None`): that is what a lookup hands out+ while no deferred worker is running to carry a hold's finalizer release (a worker that could+ not be started under thread exhaustion). Such a claim has nothing to decrement, but it is+ still the owner of its window in the two ways that matter without a worker. Published on the+ record by a claimed put() (see CacheRecord.admission_claim_ref), it keeps the admission's+ eviction sweeps honest about whether the admitting load is still running - a fact that needs+ no releaser to stay true. And its finalizer still travels the abandonment route, which on a+ stale record queues the eviction that stale-ness owes; after shutdown, the dedicated cleanup+ worker drains that queue independently of the normal worker (see _dispatch_deferred and+ _release_abandoned_holder).++ A put() into a shut-down cache with no worker is the one place this is NOT enough - no worker+ is guaranteed to ever run to drain that kept item, and no later cache operation is guaranteed+ either - so put() refuses that admission outright rather than minting a claim for it (see+ ModelCache.put()). A hold-less claim therefore only ever shields a live cache's admission, or+ a lookup (get_with_first_use_claim) of a record that is already resident - including one the+ shutdown sweep retained, whose eventual eviction the kept queue item does drive.+ """++ def __init__(self, cache: "ModelCache", cache_entry: CacheRecord, hold_epoch: Optional[int]) -> None:+ self._cache = cache+ self._cache_entry = cache_entry+ self._hold_epoch = hold_epoch+ # Seeded first so release() is well defined on a claim whose construction failed partway.+ # It cannot make the construction atomic - weakref.finalize registers itself before it+ # returns, so an async exception landing between that call and the store below leaves a+ # live finalizer for a claim _claim_first_use is about to hand the hold back for, and that+ # finalizer's later release is one this class cannot intercept. A one-bytecode window,+ # unreachable without an asynchronous exception, and it costs at worst one holder's shield+ # rather than a permanently shielded record.+ self._finalizer: Optional[weakref.finalize] = None+ # The finalizer's arguments keep the cache and the record alive for as long as the claim+ # itself is - exactly the lifetime over which the release still has work to do.+ self._finalizer = weakref.finalize(+ self,+ cache.release_first_use_grace,+ cache_entry,+ hold_epoch is not None,+ hold_epoch if hold_epoch is not None else 0,+ )+ self._finalizer.atexit = False++ def release(self) -> None:+ """Release the hold now, synchronously. Idempotent.++ Called from the adopting wrapper's first lock, which runs in an ordinary thread context+ (never a finalizer), so the direct - locking - release is safe here.+ """+ finalizer, self._finalizer = self._finalizer, None+ if finalizer is None:+ return+ if finalizer.detach() is None:+ # Already dead or detached: a racing release() on this same claim has the hold.+ # Releasing it again would decrement a hold armed by a different holder and unshield+ # their window.+ return+ self._cache.release_first_use_hold(self._cache_entry, self._hold_epoch, admission_claim=self)def _run_deferred_work(cache_ref: "weakref.ReferenceType[ModelCache]", work_queue: "queue.SimpleQueue[object]") -> None:@@ -63,41 +180,122 @@ def _run_deferred_work(cache_ref: "weakref.ReferenceType[ModelCache]", work_queuDeliberately a module-level function taking a *weak* reference rather than a bound method: arunning thread is reachable from `threading._active` and keeps its target alive, so a bound- method would make every ModelCache that has ever admitted a model immortal — pinning all of its+ method would make every ModelCache that has ever admitted a model immortal - pinning all of itscached models in RAM for the life of the process unless shutdown() happened to be called. The`weakref.finalize` registered alongside this thread (see ModelCache._ensure_deferred_worker)pushes _DEFERRED_STOP when the cache is collected, so a parked worker wakes and exits ratherthan leaking a thread per abandoned cache.++ The worker outlives shutdown() on purpose for work already in its queue. New abandonment+ releases for shutdown-retained records use a separate cleanup worker, so they remain reclaimable+ even if this worker dies.++ An exit that is NOT one of those two orderly endings runs ModelCache._recover_from_dead_worker+ before the thread unwinds. Every shield this queue exists to release is granted only while a+ worker is alive, so a worker that stops without a successor leaves those shields with nothing+ to lift them; recovering from inside the dying thread makes that recovery independent of a+ later admission, which after shutdown() may never come.+ """+ stopped_on_purpose = False+ try:+ while True:+ work = work_queue.get()+ cache = None+ cache_entry = None+ try:+ if work is _DEFERRED_STOP:+ stopped_on_purpose = True+ return+ cache = cache_ref()+ if cache is None:+ # The cache was collected; nothing can ever need doing again.+ stopped_on_purpose = True+ return+ if work is _DEFERRED_RECONCILE:+ cache._reconcile_budget_if_pending()+ else:+ assert isinstance(work, _AbandonedHolderRelease)+ cache_entry = work.cache_entry_ref()+ if cache_entry is not None:+ # Dequeued means gone: whatever happens to this item from here on - the+ # handler raising, this thread dying inside it, a fork snapshotting it+ # mid-drain - it will never be queued again, so the coalescing gate it+ # closed (CacheRecord.abandonment_release_pending) must open now, not in+ # the handler and not in a recovery that a raise or a fork can skip. A+ # finalizer landing between here and the handler queues at most one+ # duplicate, which drains as a no-op.+ cache_entry.abandonment_release_pending = False+ cache._release_abandoned_holder(cache_entry, work.held_first_use, work.hold_epoch)+ except Exception:+ if cache is not None:+ cache._logger.exception("Error processing deferred model-cache work")+ finally:+ # Drop both references before blocking on the next get(): locals stay bound for as+ # long as this frame lives. `work` may carry a CacheRecord, which transitively holds+ # its model's CPU weights - and _release_abandoned_holder can evict that very+ # record, removing it from the cache AND subtracting its bytes from the RamBudget,+ # so holding it would leave the budget under-reporting a model that is still+ # resident. `cache` must go for the same reason this function takes a weakref at+ # all, and `cache_entry` is the strong reference the queue deliberately does not+ # keep - parking on the next get() while still holding it would defeat the point.+ work = None+ cache = None+ cache_entry = None+ finally:+ # Reached only for an abnormal end (a BaseException - including one raised asynchronously+ # into this thread - or a failure of work_queue.get() itself). The two orderly exits above+ # both mean no shield can outlive the worker: _DEFERRED_STOP is pushed by the+ # cache-collection finalizer, and a collected cache has no records left to shield.+ if not stopped_on_purpose:+ cache = cache_ref()+ if cache is not None:+ try:+ cache._recover_from_dead_worker(threading.current_thread())+ except Exception:+ cache._logger.exception("Error recovering from a dead model-cache deferred-work thread")+ cache = None+++def _log_best_effort(logger: Any, method: str, message: str) -> None:+ """Report housekeeping failures without allowing a broken logging handler to stop cleanup."""+ try:+ getattr(logger, method)(message)+ except Exception:+ pass+++def _run_shutdown_deferred_work(+ cache_ref: "weakref.ReferenceType[ModelCache]", work_queue: "queue.SimpleQueue[object]"+) -> None:+ """Drain abandonment releases after shutdown without depending on the normal worker.++ Shutdown can retain a record for a live first-use claim, then the normal deferred worker can+ die before that claim is dropped. This worker is started by shutdown in an ordinary thread+ context and handles only post-shutdown abandonment releases. It catches BaseException per item:+ cleanup must survive the same failure modes that can kill the normal worker."""while True:work = work_queue.get()cache = None+ cache_entry = Nonetry:- if work is _DEFERRED_STOP:+ if work is _SHUTDOWN_DEFERRED_STOP:returncache = cache_ref()if cache is None:- # The cache was collected; nothing can ever need doing again.return- if cache._shutdown_event.is_set():- continue- if work is _DEFERRED_RECONCILE:- cache._reconcile_budget_if_pending()- else:- assert isinstance(work, CacheRecord)- cache._release_first_use_grace(work)- except Exception:+ assert isinstance(work, _AbandonedHolderRelease)+ cache_entry = work.cache_entry_ref()+ if cache_entry is not None:+ cache_entry.abandonment_release_pending = False+ cache._release_abandoned_holder(cache_entry, work.held_first_use, work.hold_epoch)+ except BaseException:if cache is not None:- cache._logger.exception("Error processing deferred model-cache work")+ _log_best_effort(cache._logger, "exception", "Error processing shutdown model-cache work")finally:- # Drop both references before blocking on the next get(): locals stay bound for as long- # as this frame lives. `work` may be a CacheRecord, which transitively holds its model's- # CPU weights — and _release_first_use_grace's release hook can evict that very record,- # removing it from the cache AND subtracting its bytes from the RamBudget, so holding it- # would leave the budget under-reporting a model that is still resident. `cache` must go- # for the same reason this function takes a weakref at all.work = Nonecache = None+ cache_entry = Noneclass _ModelLoadReadWriteLock:@@ -108,11 +306,11 @@ class _ModelLoadReadWriteLock:replaces `torch.nn.Module.register_parameter` so that every newly-registered parameter is routedto the `meta` device. While that patch is installed, ANY `register_parameter` call in ANY threadis hijacked onto `meta`. VRAM load/unload uses `nn.Module.load_state_dict(assign=True)`, which- assigns `Parameter`s via `__setattr__` -> `register_parameter` — so if it runs concurrently with+ assigns `Parameter`s via `__setattr__` -> `register_parameter` - so if it runs concurrently witha construction on another worker thread, its real weights get stranded on `meta`. That surfaceslater as "Cannot copy out of meta tensor; no data!" or "unrecognized device meta".- - Construction takes the WRITE lock (exclusive — no reader and no other writer may run).+ - Construction takes the WRITE lock (exclusive - no reader and no other writer may run).- VRAM load/unload takes the READ lock (shared, so concurrent moves on different GPUs stilloverlap each other; they only block while a construction holds the write lock).@@ -122,8 +320,8 @@ class _ModelLoadReadWriteLock:Lock-ordering contract: callers MUST acquire this lock *before* any `ModelCache._lock`, neverafter. Readers do so by taking the read lock around the outer `ModelCache.lock()` call (see`LoadedModelWithoutConfig`), and writers around the whole construction (see- `ModelLoader._load_and_cache`). Acquiring it in the other order — cache lock first, then this- lock — would risk an AB-BA deadlock with a writer that takes a cache lock during `put()`.+ `ModelLoader._load_and_cache`). Acquiring it in the other order - cache lock first, then this+ lock - would risk an AB-BA deadlock with a writer that takes a cache lock during `put()`."""def __init__(self) -> None:@@ -181,7 +379,7 @@ def synchronized(method: Callable[..., Any]) -> Callable[..., Any]:After the lock is released, any pending peer-eviction request is honored (seeModelCache.request_budget_reconcile): a peer whose eviction request found this cache's- lock contended relies on this hook — without it, nothing re-checks the shared RAM+ lock contended relies on this hook - without it, nothing re-checks the shared RAMbudget when the lock frees, and the budget could stay exceeded indefinitely."""@@ -200,7 +398,7 @@ def synchronized(method: Callable[..., Any]) -> Callable[..., Any]:except Exception:# The reconcile is deferrable housekeeping and must not fail the operation# that triggered it. It can raise from a sick CUDA context (empty_cache after- # an eviction) — and this hook runs inside the caller's frame AFTER the+ # an eviction) - and this hook runs inside the caller's frame AFTER the# method body, so a raise out of lock_in_ram()/lock() here would propagate# before LoadedModel's unlock-pairing try block is entered, leaking a# permanently locked record (the same shape as a keep-alive Timer.start()@@ -404,6 +602,9 @@ class ModelCache:self._deferred_work_queue: queue.SimpleQueue[object] = queue.SimpleQueue()self._deferred_work_thread: Optional[threading.Thread] = Noneself._deferred_work_finalizer: Optional[weakref.finalize] = None+ self._shutdown_deferred_work_queue: queue.SimpleQueue[object] = queue.SimpleQueue()+ self._shutdown_deferred_work_thread: Optional[threading.Thread] = None+ self._shutdown_deferred_work_finalizer: Optional[weakref.finalize] = Noneif ram_budget is not None:ram_budget.register_cache(self)@@ -508,8 +709,8 @@ class ModelCache:except RuntimeError:# Thread/pid exhaustion (RLIMIT_NPROC, a container's pids.max). The keep-alive timer is# an optimization; it must not fail the cache operation that triggered it. Every- # @record_activity method runs this AFTER its real work — e.g. lock_in_ram() has already- # incremented the record's lock count — so an exception here would propagate to callers+ # @record_activity method runs this AFTER its real work - e.g. lock_in_ram() has already+ # incremented the record's lock count - so an exception here would propagate to callers# like LoadedModelWithoutConfig.model_in_ram() before their unlock-pairing try block is# entered, leaking a permanent pin. Swallow it: the next activity re-arms the timer.self._timeout_timer = None@@ -562,27 +763,123 @@ class ModelCache:@synchronizeddef shutdown(self) -> None:- """Shutdown the model cache, cancelling any pending timers."""+ """Shutdown the model cache: cancel any pending timers and evict the resident records."""if self._shutdown_event.is_set():returnself._shutdown_event.set()- self._deferred_work_queue.put(_DEFERRED_STOP)+ # The deferred worker is deliberately NOT stopped here. The sweep below retains records+ # still owned by a live LoadedModel wrapper or claimed admission; a wrapper that has not+ # yet locked its record may simply be dropped instead of used, so its finalizer-initiated+ # release, carried by the worker, is then the only event left that can evict the record.+ # Stopping the worker at shutdown would strand such records (and their shared-store+ # references and budget bytes) for the life of the process. The worker parks on its queue+ # and is stopped by the cache-collection finalizer+ # registered in _ensure_deferred_worker when the ModelCache itself is finally dropped.if self._timeout_timer is not None:self._timeout_timer.cancel()self._timeout_timer = None- # Release the resident records' shared-weights references now, synchronously. A shut-down- # cache serves no more loads, and waiting for collection would leave the store's refcounts- # (and canonical tensors) to the wrappers' finalizers — which only ENQUEUE, and at teardown- # there may be no later store operation to drain the queue. shutdown() runs in a normal- # thread context, so the direct (locking) release is safe here.- for cache_entry in self._cached_models.values():- cache_entry.cached_model.release_shared_weights()+ # If no live worker remains, the shields it was carrying releases for have nothing left to+ # lift them and would make the sweep below stale-retain their records forever: the+ # wrappers' finalizer releases were (or will be) dropped by the dispatch check, and no+ # unlock() is coming for a never-locked holder. Lift them now so the sweep can evict those+ # records (see _recover_stranded_shields for the trade this takes).+ #+ # The condition is "no live worker", not "a dead thread still in the slot": a worker that+ # ran its own dying recovery retires the slot, and an empty slot means just as surely that+ # nothing is left to carry a release. Keying on the dead thread would skip this lift in+ # exactly the case the dying recovery deliberately leaves for it - a grace it declined to+ # touch because the cache was still live at the time.+ if self._deferred_work_thread is None or not self._deferred_work_thread.is_alive():+ try:+ self._recover_stranded_shields()+ except Exception:+ _log_best_effort(self._logger, "exception", "Error recovering model-cache shields during shutdown")+ # Evict the resident records now rather than merely releasing their shared-store+ # references. Releasing while retaining the records would make the accounting lie two+ # ways: the store stops counting bytes whose tensors the retained wrappers still hold (so+ # a post-shutdown load of the same key on a peer cache registers a duplicate canonical+ # alongside the still-resident released copy), and a later eviction of such a record -+ # put() after shutdown() is reachable, see the note in put() - reads uses_shared_weights+ # as already-False and debits the non-shared budget for bytes that were admitted as+ # shared. Routing through _delete_cache_entry() keeps store ownership until the record+ # itself goes away, so the accounting stays truthful at every point. The release must be+ # synchronous regardless: waiting for collection would leave the refcounts to the+ # wrappers' finalizers - which only ENQUEUE, and at teardown there may be no later store+ # operation to drain the queue. shutdown() runs in a normal thread context, so the direct+ # (locking) release inside _delete_cache_entry() is safe here.+ #+ # Records still in use keep their references: entries locked by an in-flight generation,+ # entries with a first-use wrapper hold, and entries with a claimed admission are marked+ # stale instead. Their eventual release evicts them through this same path: unlock() once+ # the generation lets go, or the appropriate claim/finalizer release if it is abandoned.+ # Without this protection, shutdown() racing the gap between retrieval and __enter__()+ # would evict the record its holder is about to lock, releasing shared-store ownership+ # while the tensors remain live and allowing a peer to mint a duplicate canonical copy.++ # An admission whose load never came back for it is NOT retained here, and needs no+ # special case to avoid it: the loaders claim their admissions (put(claim_admission=True)),+ # so a load cancelled or errored between its put() and its retrieval drops that claim by+ # dying, and the claim's release - the same abandonment path a dropped LoadedModel takes -+ # evicts the record with its shared-store reference and its budget bytes. Without it, the+ # put()-set grace on such a record had no releaser left after shutdown (its other two are+ # the loader's own get() -> lock() and the sweep at the top of the NEXT put(), which is no+ # longer guaranteed to run), and the sweep below stale-RETAINED the record for the life of+ # the cache object (JPPhoto review, 2026-08-30).+ #+ # `awaiting_first_use` is deliberately excluded from the shutdown shield. It is an+ # unowned grace period set by an unclaimed put(), with no wrapper or finalizer able to+ # release it when the load is cancelled before get(). Production loaders use+ # claim_admission=True for this gap; an unclaimed admission must not pin model state after+ # shutdown has removed its next-put sweep backstop.+ #+ # Marked stale BEFORE the shield is consulted, not after. A hold-less abandonment+ # (release_first_use_grace) decides lock-free whether it owes the queue an eviction: it+ # clears its grace, then reads is_stale, and queues nothing for a record that is not+ # stale - the record is ordinarily evictable, so nothing is owed. Consulting the shield+ # first and marking afterwards opens a two-step window that such a finalizer can land+ # in: the shield is read as standing, the finalizer clears it and reads not-stale, and+ # the mark then retains a record with no lock, no shield, no queued item and nothing+ # left to evict it. Marking first closes it in both orders: a finalizer that reads the+ # mark queues the eviction; one that read before it was written has already cleared its+ # shield (the clear precedes the read), so the check below finds the record unshielded+ # and evicts it here. The same holds for a claim dying concurrently - its weak reference+ # is dead before its finalizer runs. A record evicted below carries a stale mark nobody+ # will read; every later reader of a detached record is gated on identity first.+ models_cleared = 0+ bytes_freed = 0+ for cache_entry in list(self._cached_models.values()):+ cache_entry.is_stale = True+ if not (cache_entry.is_locked or cache_entry.first_use_holds > 0 or cache_entry.admission_in_flight):+ bytes_freed += cache_entry.cached_model.total_bytes()+ self._delete_cache_entry(cache_entry)+ models_cleared += 1++ # A claimed admission or first-use wrapper can still be released after the normal worker+ # dies. Give those finalizers a shutdown-specific queue and worker that does not share the+ # normal worker's failure state.+ if any(+ entry.first_use_holds > 0 or entry.admission_in_flight or entry.abandonment_release_pending+ for entry in self._cached_models.values()+ ):+ self._ensure_shutdown_deferred_worker()++ if models_cleared:+ self._notify_models_cleared(+ models_cleared=models_cleared,+ bytes_requested=0,+ bytes_freed=bytes_freed,+ )@synchronized@record_activitydef put(- self, key: str, model: AnyModel, execution_device: Optional[torch.device] = None, prefetch: bool = False- ) -> None:+ self,+ key: str,+ model: AnyModel,+ execution_device: Optional[torch.device] = None,+ prefetch: bool = False,+ claim_admission: bool = False,+ ) -> Optional[FirstUseClaim]:"""Add a model to the cache.Args:@@ -593,13 +890,23 @@ class ModelCache:prefetch: The model is being cached opportunistically (e.g. the unused submodels of asingle-file pipeline load) and no loader will retrieve it after this call. It isadmitted without the post-admission grace, so budget reconciles may evict it- immediately.+ immediately -- and it is refused outright once the cache has shut down, where+ nothing is guaranteed to evict it either.+ claim_admission: Shield the new record with an owned admission claim and return the+ claim that owns it (None only if this call was a no-op because the key was already+ resident; a claim armed while no worker could be started carries no hold, but still+ owns the window - see FirstUseClaim).+ Every loader that is going to retrieve the record it just admitted should ask for+ one and hold it until its retrieval has armed a claim of its own: an owned shield+ cannot outlive its load, so a load that is cancelled or errors before its+ retrieval releases the admission by dying, instead of leaving a grace standing+ that nothing can clear (see shutdown())."""if key in self._cached_models:self._logger.debug(f"Attempted to add model {key} ({model.__class__.__name__}), but it already exists in the cache. No action necessary.")- return+ return None# Start (or revive) the worker before mutating cache state. Every deferred task concerns an# admitted record, so this makes later dispatch queue-only while avoiding a thread for an@@ -608,15 +915,91 @@ class ModelCache:# Any entry still carrying the post-admission grace belongs to an earlier load: cold loads# are serialized under MODEL_LOAD_LOCK's write lock and each load's only graced put() is- # its final one, so a flag that survives to the next admission is stale — its loader+ # its final one, so a flag that survives to the next admission is stale - its loader# either errored out before retrieving the model or dropped the LoadedModel without ever# locking it. Clear such flags so an orphaned record cannot dodge budget reconciles- # indefinitely. (An entry retrieved but not yet locked loses its shield here; if a- # reconcile then evicts it, lock() falls back to the tolerated issue-7513 path and+ # indefinitely. Only the put()-set grace is swept: an entry whose LoadedModel wrapper is+ # already constructed is tracked by first_use_holds instead, which a concurrent cold load+ # must NOT clear - a node may retrieve several models before entering any of their+ # contexts - and whose release is guaranteed by the wrapper's finalizer rather than by+ # this sweep. (An entry retrieved but with no wrapper hold yet loses its shield here; if+ # a reconcile then evicts it, lock() falls back to the tolerated issue-7513 path and# proceeds on the detached record.)for stale_entry in self._cached_models.values():stale_entry.awaiting_first_use = False+ # A shut-down cache that could not start a worker just now has no releaser to offer any+ # new admission and no guarantee of a future cache operation to stand in for one: no+ # worker to drain an abandonment release, and no later put() to run make_room or the+ # sweep below. A record admitted here whose loader then dies before retrieving it - a+ # claimed admission's claim dropped, a wrapper dropped un-entered - would be stale,+ # unshielded and pinned, with its shared-store reference and budget bytes, for the life+ # of the cache object; the queued abandonment release its finalizer leaves cannot help,+ # because nothing will drain it (JPPhoto review, 2026-09-04). So every admission is+ # refused in this state, the same standard the post-shutdown prefetch is already refused+ # under below, and for the same reason. A load racing shutdown into a thread-exhausted+ # process is failing regardless (its retrieval raises IndexError, exactly as a refused+ # prefetch's would); refusing here trades that already-doomed load for the certainty that+ # nothing is left pinned.+ #+ # First, though, reclaim any record ALREADY stranded this way - one admitted while a+ # worker was alive, retained by the shutdown sweep for a live holder, then orphaned when+ # that worker died with the holder's abandonment release undrained. This is the same+ # terminal sweep the dying worker runs (_recover_from_dead_worker), making the same+ # trade: a live un-entered wrapper whose hold the recovery above just zeroed loses its+ # record here and falls back to the tolerated issue-7513 detached path, while a record+ # whose admitting load is still running is owned by the loader's claim+ # (CacheRecord.admission_claim_ref) and is left alone. It is run here, not in+ # _ensure_deferred_worker's failure branch, because that branch also runs under+ # register_first_use_hold in the same lock frame as a lookup, where the record just+ # handed to the retriever is exactly what the sweep would evict; in put() the only record+ # in anyone's hands is the one this call has not inserted yet (cold loads are serialized+ # under MODEL_LOAD_LOCK's write lock, so no other load is between its own put() and its+ # retrieval while this one runs).+ if self._shutdown_event.is_set() and (+ self._deferred_work_thread is None or not self._deferred_work_thread.is_alive()+ ):+ self._evict_stale_unshielded_entries()+ self._logger.debug(+ f"Refusing admission of {key} into a shut-down cache with no deferred worker: "+ "nothing would be guaranteed to release it."+ )+ return None++ # A prefetch admission into a cache that has already shut down has no *guaranteed*+ # releaser -- the same standard the post-admission grace is withheld under, below.+ # Prefetch is the promise that no loader will come back for this record, so there is no+ # get() -> lock() -> unlock() to run the stale eviction below, no wrapper whose finalizer+ # could carry an abandonment release, and no claim whose expiry could stand in for+ # either. What is left are the paths that may or may not run -- another admission's+ # make_room, a budget reconcile, a peer's eviction request, the eviction sweep of a worker+ # death -- and after shutdown not one of them is guaranteed to come. The record is+ # therefore reclaimable only by luck, and otherwise holds its model, its shared-store+ # reference and its budget charge until the cache object is collected.+ #+ # Refusing costs only a reload. The sole caller (the single-file pipeline's submodel+ # prefetch) takes the submodel it was actually asked for from the pipeline object, not+ # from the cache, and discards the rest with the pipeline; a later load reads them from+ # disk again.+ #+ # Placement, each bound of which is load-bearing:+ # - after _ensure_deferred_worker() above, because a post-shutdown prefetch must still+ # revive the worker that carries the shutdown-retained records' abandonment releases;+ # - after the stale-grace sweep above, because on a shut-down cache with a LIVE worker+ # that sweep is the only backstop a stale grace has left (shutdown() runs the recovery+ # only when no worker is alive), so returning above it would strand the very kind of+ # record this method is careful never to strand. (The worker-less shut-down case has+ # already returned above - every admission is refused there, prefetch included - so+ # this refusal only ever fires with a LIVE worker present.);+ # - before _make_room_internal below, so nothing resident is evicted to house a model this+ # call is about to refuse.+ if prefetch and self._shutdown_event.is_set():+ self._logger.debug(+ f"Refusing prefetch admission of {key} into a cache that has been shut down: "+ "nothing will retrieve it, and nothing is guaranteed to release it."+ )+ return None+size = calc_model_size_by_data(self._logger, model)self._make_room_internal(size)@@ -678,23 +1061,56 @@ class ModelCache:cache_key=key,)- # awaiting_first_use protects the new entry from the asynchronous eviction paths (budget- # reconcile, peer-requested eviction) until the loader locks it — see CacheRecord. A- # prefetch admission gets no grace: nothing will come back for it, so it must stay- # ordinarily evictable.+ # awaiting_first_use protects an unclaimed new entry from the asynchronous eviction paths+ # (budget reconcile, peer-requested eviction) until the loader locks it - see CacheRecord.+ # A claimed admission uses its owned claim as the authoritative shield instead: unlike this+ # unowned grace, that claim remains observable after worker recovery and can be honored by+ # synchronous eviction paths too. A prefetch admission gets no grace: nothing will come+ # back for it, so it must stay ordinarily evictable.#- # Neither does an admission made while no deferred worker is running to release the grace- # if the loader abandons the model. Both states are reachable — put() after shutdown()- # (Invoker.stop() stops model_manager before session_processor, so an in-flight generation- # can land here), and a worker that could not be started under thread exhaustion — and in- # both the flag would never be cleared, leaving the record permanently invisible to every- # asynchronous eviction path while its bytes stay charged to the shared budget. Without the- # grace the record is merely ordinarily evictable; lock() still clears the flag on the- # normal path, so nothing changes when the worker is healthy.+ # Neither does an unclaimed admission made while no deferred worker is running to release+ # the grace if the loader abandons the model (a worker that could not be started under thread+ # exhaustion, or one lost to an unexpected error before this put()'s restart attempt+ # could succeed): the flag would never be cleared, leaving the record permanently+ # invisible to every asynchronous eviction path while its bytes stay charged to the+ # shared budget. Without the grace the record is merely ordinarily evictable; lock()+ # still clears the flag on the normal path, so nothing changes when the worker is+ # healthy.+ #+ # Nor does an unclaimed admission after shutdown() (Invoker.stop() stops model_manager before+ # session_processor, so an in-flight generation can land here). The grace has exactly two+ # releasers: the loader's own forward progress (get() -> lock(), or the wrapper's+ # abandonment finalizer once one exists), and the sweep at the top of the NEXT put(). A+ # load cancelled between this put() and the LoadedModel's construction - no wrapper, so no+ # finalizer - depends entirely on that sweep, and after shutdown no further put() is+ # guaranteed to come: the flag would stand for the life of the process, hiding the record+ # from every asynchronous eviction path while its bytes stay charged to the shared budget.+ # Withholding it costs only the shield: the record is ordinarily evictable, is_stale below+ # makes its eventual release evict it, and a loader that does come back gets the same+ # first_use_holds shield as any other wrapper. A loader that claimed its admission is+ # covered between put() and get() regardless, by the claim it holds (see the arming at+ # the end of this method) - a shield that needs no worker and no grace. An unclaimed+ # admission is not: if an eviction wins the race to it while its loader is still between+ # put() and get(), that get() raises rather than falling back - the same trade the+ # synchronous paths (make_room, drop_model) have always made against this flag, taken+ # here only for admissions into an already-shut-down cache.+ #+ # A claimed admission does not get the unowned grace: the record's weak reference to the+ # claim (see the arming at the end of this method, and CacheRecord.admission_claim_ref) is+ # the authoritative shield. It survives worker recovery and is honored by every eviction+ # path, while the claim's finalizer makes the record ordinary again when the load dies.worker_running = self._deferred_work_thread is not None and self._deferred_work_thread.is_alive()+ shutting_down = self._shutdown_event.is_set()cache_record = CacheRecord(- key=key, cached_model=wrapped_model, awaiting_first_use=not prefetch and worker_running+ key=key,+ cached_model=wrapped_model,+ awaiting_first_use=not prefetch and not claim_admission and worker_running and not shutting_down,)+ # An admission after shutdown() (reachable, see above) missed the shutdown sweep, so+ # nothing would ever evict it: mark it stale at birth so its final release - unlock(), or+ # the abandonment path - evicts it instead of leaving it resident until process exit.+ if shutting_down:+ cache_record.is_stale = Trueself._cached_models[key] = cache_recordself._cache_stack.append(key)# Account this model's RAM in the global budget. Shared weights are tracked once by the@@ -710,7 +1126,7 @@ class ModelCache:# Admission left the shared budget exceeded: make-room above exhausted this cache's# own evictable entries, and best-effort peer eviction fell short (a peer's lock was# contended, or the remaining RAM is held by locked in-use entries). Record a- # reconcile request on every peer so each sheds unlocked entries as soon as it can —+ # reconcile request on every peer so each sheds unlocked entries as soon as it can -# the cap must not stay exceeded merely because a peer was busy at the moment we# asked. This runs after the new model is counted so the peers' budget checks see# the true (exceeded) state.@@ -722,7 +1138,40 @@ class ModelCache:# that eventually becomes evictable triggers the reconcile itself. (A request on# self here would be worse than useless: _make_room_internal already evicted# everything unlocked, so the only entry a self-reconcile could ever claim is the- # model just admitted — evicting it out from under its own loader.)+ # model just admitted - evicting it out from under its own loader.)++ # Shield the put() -> retrieval window with an owned claim when the caller asked for one.+ # The claim lives in the loader's frame, so a load cancelled or+ # errored before its retrieval releases it by dying - which is what lets shutdown() retain+ # a claimed admission for a load that is really still in flight (whose local still holds+ # these very tensors) while retiring the unowned graces that nothing can release. The+ # loader hands the shield over to its retrieval's own claim and drops this one.+ #+ # Armed last, once the admission is fully committed. _claim_first_use can raise+ # (weakref.finalize allocates, and this cache runs at the RAM ceiling by design), and a+ # raise between the record's insertion above and the budget accounting would leave a+ # resident, store-owning record that the budget never counted - whose eventual eviction+ # then debits bytes it never added, permanently stealing another record's charge (the+ # debit is clamped to what this cache has tracked). Everything above this point is+ # committed, so the worst a failure here costs is the claim: the record is an ordinary+ # admission, exactly as if the caller had not asked to claim it.+ if not claim_admission or prefetch:+ return None+ admission_claim = self._claim_first_use(cache_record)+ if admission_claim is not None:+ # The record's weak reference to the claim - not the hold, and not the grace - is what+ # actually shields this window (see CacheRecord.admission_claim_ref): it expires with+ # the loader's frame, so no event has to release it, and neither a worker death+ # (which zeroes holds) nor another holder's abandonment (which clears the grace) can+ # strip it while the load is still running. On a LIVE cache the claim is minted even+ # when no worker is running to carry a hold (a hold-less claim, hold_epoch=None): the+ # record is not stale there, so it just becomes ordinary cache content once the load+ # is done, and the ownership still keeps a concurrent worker-less admission's sweep+ # from mistaking a running load for an abandoned one. On a shut-down worker-less+ # cache the admission never reaches this point - it was refused above - so no+ # unreleasable claimed record is ever created.+ cache_record.admission_claim_ref = weakref.ref(admission_claim)+ return admission_claimdef _warn_once(self, topic: str, device: torch.device, message: str) -> None:"""Log `message` the first time `topic` arises for `device`.@@ -744,11 +1193,11 @@ class ModelCache:- Entries keyed by `get_model_cache_key` (model key plus optional ``:submodel`` suffix)are reported with the suffix stripped so they match plain model keys. Entries keyed by- filesystem path (`load_model_from_path`) are excluded: a path — or the bare Windows- drive letter that splitting ``C:\\...`` on ``:`` would leave — is not a model key, and+ filesystem path (`load_model_from_path`) are excluded: a path - or the bare Windows+ drive letter that splitting ``C:\\...`` on ``:`` would leave - is not a model key, andsuch short strings would corrupt substring-based affinity scoring.- Non-blocking: the cache lock is held across long operations (VRAM transfers, cache- clears), and this feeds an opportunistic scheduling heuristic — returning an empty set+ clears), and this feeds an opportunistic scheduling heuristic - returning an empty setwhen the lock is contended is better than stalling a worker's dequeue. For the samereason, a pending budget reconcile observed at release time is handed to a backgroundthread rather than performed inline.@@ -764,19 +1213,21 @@ class ModelCache:# synchronized-decorator hook: a peer whose request found the lock held by this# method relies on the release to process the flag (see request_budget_reconcile).# But reconciliation evicts models and runs gc.collect(), which can pause for- # seconds — running it inline would break this method's no-stall contract. Hand the+ # seconds - running it inline would break this method's no-stall contract. Hand the# work to the cache's background worker instead: it may wait on the cache lock and do# the slow work; this caller returns immediately.if self._ram_budget is not None and self._budget_reconcile_pending.is_set() and not self._lock._is_owned():self._dispatch_deferred(_DEFERRED_RECONCILE)- def release_first_use_grace(self, cache_entry: CacheRecord) -> None:- """Make an abandoned, never-locked record available for budget eviction.+ def release_first_use_grace(+ self, cache_entry: CacheRecord, held_first_use: bool = False, hold_epoch: int = 0+ ) -> None:+ """Make an abandoned, never-locked record available for eviction again.Called from a `weakref.finalize` callback (see LoadedModelWithoutConfig), which runs at anarbitrary decref/garbage-collection point in an arbitrary thread. That thread may already- hold the SharedCpuWeightsStore or RamBudget lock — `SharedCpuWeightsStore.acquire()` sums- tensor sizes inside its critical section, so a generational collection can fire there — and+ hold the SharedCpuWeightsStore or RamBudget lock - `SharedCpuWeightsStore.acquire()` sums+ tensor sizes inside its critical section, so a generational collection can fire there - andboth of those are plain, non-reentrant locks.So this method must do NO locking work itself. Taking the cache lock here would run the@@ -790,13 +1241,57 @@ class ModelCache:The work is therefore handed to the cache's background worker, exactly ascached_model_keys() does with its own reconcile. SimpleQueue.put() is reentrant and neverwaits on the cache, store or budget locks, so it is safe from a finalizer.++ `held_first_use` says whether the dropped wrapper had armed a first-use hold (see+ register_first_use_hold); the deferred release decrements only what that wrapper armed,+ and only while `hold_epoch` still matches the record's - a hold zeroed by dead-worker+ recovery must not be re-released against a successor hold.++ A hold-less abandonment (a wrapper or claim built while no worker was running to arm a+ hold) has nothing to decrement, and its two effects are handled differently:++ - The grace is cleared HERE, lock-free. That is safe for the same reason the read below+ is: the flag is monotonic (put() sets it on a brand-new record and nothing sets it+ again), so a clear from any thread at any point is one the record's other releasers+ would have made anyway, only later. Clearing it through the worker instead is what let+ the queue grow without bound: while no worker could be started, every warm get() whose+ wrapper was dropped un-entered enqueued one more item, and nothing short of a lock() or+ another admission ever cleared the flag that kept them coming (JPPhoto review,+ 2026-09-04).+ - The eviction a stale record owes still needs the cache lock, so it is queued - but at+ most once per record (CacheRecord.abandonment_release_pending, re-opened by the worker+ the moment it dequeues the item), since one queued eviction is as good as any number. A record that is not stale owes nothing: with the+ grace cleared it is ordinarily evictable again. What may still be owed is a budget+ reconcile that was waiting on exactly this record becoming evictable (a peer over the+ shared cap asked this cache to shed, and the graced record was all it had): the drained+ item used to run that reconcile from the worker's release hook, so the worker is still+ woken for it - with a reconcile item, which _dispatch_deferred drops while no worker+ runs, and which the next cache operation's release hook makes redundant anyway.++ Hold-carrying releases are never coalesced. Each one retires exactly one hold, and their+ count is bounded by the holds themselves, which are armed only while a worker is alive."""- # Unsynchronized read: the flag is monotonic (put() is the only writer that sets it, and- # only on a brand-new record), so a False reading is always final and there is nothing to- # release. Losing a race here at worst queues work that no-ops under the lock.- if not cache_entry.awaiting_first_use:- return- self._dispatch_deferred(cache_entry)+ # Unsynchronized reads: awaiting_first_use and is_stale are both monotonic (put() is the+ # only writer that sets the grace, and only on a brand-new record; is_stale is only ever+ # set), and a caller passing held_first_use owns the hold it is releasing, so a+ # nothing-to-release reading is final. Losing a race here at worst queues work that+ # no-ops under the lock. The one ordering that matters is against the stale-marking+ # sweep in shutdown(): the grace is cleared BEFORE is_stale is read, and shutdown()+ # writes the mark BEFORE it consults the shield, so a not-stale reading here means the+ # clear already preceded shutdown()'s look and the sweep itself evicts the record.+ if not held_first_use:+ cache_entry.awaiting_first_use = False+ if not cache_entry.is_stale:+ if self._ram_budget is not None and self._budget_reconcile_pending.is_set():+ self._dispatch_deferred(_DEFERRED_RECONCILE)+ return+ # Two finalizers racing this unsynchronized check can both pass it and queue two+ # items; the second drains as a no-op. What matters is that a third cannot follow+ # while one is still queued.+ if cache_entry.abandonment_release_pending:+ return+ cache_entry.abandonment_release_pending = True+ self._dispatch_deferred(_AbandonedHolderRelease(weakref.ref(cache_entry), held_first_use, hold_epoch))def _ensure_deferred_worker(self) -> None:"""Start the background worker if it is not currently running. Caller must hold the lock.@@ -804,18 +1299,31 @@ class ModelCache:A `threading.Thread` cannot be restarted, so a fresh one is created whenever the previousworker has exited. Without that, a worker lost to an unexpected error (e.g. a logginghandler that raises, or `os.fork()`, neither of which clears `Thread.ident`) would silently- disable every later grace release and budget reconcile for the life of the process — the+ disable every later grace release and budget reconcile for the life of the process - therecord would keep shielding an idle cache from eviction, which is exactly the failure thismechanism exists to prevent.- Never revives the worker after shutdown(): that call's `_DEFERRED_STOP` is still queued, so- a new thread would consume it and exit immediately, and a shut-down cache has no deferred- work worth doing.+ Revival applies after shutdown() too: the worker is what carries abandonment releases for+ the records the shutdown sweep retained, so a post-shutdown admission must restore it the+ same as any other."""- if self._shutdown_event.is_set():- returnif self._deferred_work_thread is not None and self._deferred_work_thread.is_alive():return+ # No worker is running. Recover unconditionally rather than only when a dead thread is+ # still in the slot: the previous worker may have died without running its own recovery (a+ # fork, or a death this call raced), or its recovery may have failed partway through and+ # retired the slot on the way out. The sweep is idempotent and costs nothing on a cache+ # that has no shields standing, so re-running it at every worker start is what makes a+ # failed recovery retryable.+ try:+ self._recover_stranded_shields()+ except Exception:+ # Recovery is best-effort housekeeping. Leave the slot empty so a later admission can+ # retry it; failing the admission would make a transient logger or cleanup failure+ # surface as a model-load failure, while starting a worker with shields still stranded+ # would make the worker-less state impossible to recover.+ _log_best_effort(self._logger, "exception", "Error recovering shields before starting a model-cache worker")+ returnthread = threading.Thread(target=_run_deferred_work,args=(weakref.ref(self), self._deferred_work_queue),@@ -827,9 +1335,17 @@ class ModelCache:except RuntimeError:# Thread/pid exhaustion (RLIMIT_NPROC, a container's pids.max). Deferred work is an# optimization, so it must not take the model load that this put() is completing down- # with it. _dispatch_deferred drops work while no worker is running, and the next put()- # both retries the start and clears stale grace flags itself, so no record can stay+ # with it. _dispatch_deferred drops reconciles while no worker is running (it keeps+ # abandonment releases, whose holders are already gone), and the next put() both+ # retries the start and clears stale grace flags itself, so no record can stay# shielded from eviction indefinitely.+ #+ # Not evicted here, deliberately, even on a shut-down cache where a failed start means+ # nothing is coming: this method also runs from register_first_use_hold, in the same+ # lock frame as the lookup that just handed a record to its retriever, and that record+ # - stale at birth after shutdown, with no hold this call could arm - is exactly what+ # a sweep here would evict, out from under the caller. put() runs that sweep instead,+ # where the only record in anyone's hands is the one it has not inserted yet.self._logger.warning("Could not start the model-cache deferred-work thread; deferred cache work is disabled until the ""next model admission."@@ -837,44 +1353,351 @@ class ModelCache:returnif self._deferred_work_finalizer is None:# Wake the parked worker when this cache is collected so it exits instead of leaking.- # This binds the queue and the sentinel only — never `self`, which would reintroduce the+ # This binds the queue and the sentinel only - never `self`, which would reintroduce the# strong reference that passing a weakref to the thread exists to avoid.self._deferred_work_finalizer = weakref.finalize(self, self._deferred_work_queue.put, _DEFERRED_STOP)self._deferred_work_finalizer.atexit = Falseself._deferred_work_thread = thread+ def _ensure_shutdown_deferred_worker(self) -> None:+ """Start the finalizer-only worker needed by records retained across shutdown.++ Caller must hold the cache lock. This worker is intentionally separate from the normal+ worker: shutdown-retained claims must still be reclaimable if the normal worker dies, and+ restarting the normal worker would unnecessarily revive budget-reconcile machinery.+ """+ if self._shutdown_deferred_work_thread is not None and self._shutdown_deferred_work_thread.is_alive():+ return+ thread = threading.Thread(+ target=_run_shutdown_deferred_work,+ args=(weakref.ref(self), self._shutdown_deferred_work_queue),+ name="model-cache-shutdown-deferred-work",+ daemon=True,+ )+ try:+ thread.start()+ except RuntimeError:+ _log_best_effort(+ self._logger,+ "warning",+ "Could not start the model-cache shutdown cleanup thread; abandoned records may remain resident.",+ )+ return+ if self._shutdown_deferred_work_finalizer is None:+ self._shutdown_deferred_work_finalizer = weakref.finalize(+ self, self._shutdown_deferred_work_queue.put, _SHUTDOWN_DEFERRED_STOP+ )+ self._shutdown_deferred_work_finalizer.atexit = False+ self._shutdown_deferred_work_thread = thread+def _dispatch_deferred(self, work: object) -> None:"""Hand work to the background worker, without blocking and without a lock.Neither caller may block: release_first_use_grace() runs inside a weakref finalizer (see itsdocstring) and cached_model_keys() has a no-stall contract. `SimpleQueue.put()` satisfies- both, but only the worker ever drains the queue, so enqueueing while no worker is running- would grow it without bound — and, for a CacheRecord, pin that model's CPU weights for the- life of the process. Drop the item instead.-- Dropping loses nothing real, because put() only grants the first-use grace when a worker is- running to release it (see put()). So a dropped CacheRecord is one that was never shielded- from eviction in the first place, and a dropped reconcile is re-run by the synchronized- release hook of the next cache operation — put() additionally clears any stale grace flags- itself. What must never happen is a record that is shielded with nothing left to unshield- it; that is what the pairing of these two rules prevents.-- A shutdown() landing between the check and the put() can still strand a single item in the- queue. The cache is being torn down at that point and the cost is bounded by one record, so- that race is tolerated rather than paid for with a lock this method cannot take.+ both. Before shutdown, the normal worker drains this queue; after shutdown, abandonment+ releases are handed to the dedicated cleanup queue when available, with a live normal worker+ as the fallback if its thread could not be started.++ A reconcile is dropped: cached_model_keys() can request one on every call, so keeping them+ would grow the queue without bound, and the synchronized release hook of the next cache+ operation re-runs it anyway.++ An abandonment release is KEPT. Its holder is already gone - finalizers fire once - so no+ lock, no unlock and no second finalizer is ever coming for that record; this item is the+ only thing left that can retire it. Before shutdown it stays in this queue for a replacement+ normal worker. After shutdown it goes to the dedicated cleanup queue, whose worker is+ independent of this one. Dropping it is what leaves a record resident, stale and charged+ for the life of the process.++ The backlog this can build is bounded, in two parts. A hold-carrying item is one per hold+ abandoned while no worker runs, and a hold is only ever armed while a worker is alive, so+ those are capped by the holders that existed at the last worker's death. A hold-less item+ is at most one per record between drains: release_first_use_grace clears the grace itself+ and queues only the eviction a stale record owes, coalesced through+ CacheRecord.abandonment_release_pending - so a warm get() whose wrapper is dropped+ un-entered, repeated indefinitely under thread exhaustion, contributes one item, not one+ per repetition. An item whose record has since gone drains as a no-op.++ The shields themselves are still lifted by the dead-worker recovery rather than by this+ queue - put()'s grace and register_first_use_hold's holds are both granted only while a+ worker is running, and put() sweeps stale grace flags itself. What must never happen is a+ record that is shielded with nothing left to unshield it; that is what the pairing of these+ rules prevents.++ The liveness gate is deliberately unsynchronized (a finalizer must not take the cache lock),+ so it is only advisory before shutdown. After shutdown, dispatch does not consult the normal+ worker's liveness: it queues to the dedicated cleanup worker, which is started before+ shutdown returns whenever a retained record needs a finalizer release. The record remains+ weakly referenced so queued work never pins detached model state."""- if self._shutdown_event.is_set():- return+ if self._shutdown_event.is_set() and isinstance(work, _AbandonedHolderRelease):+ # Finalizers after shutdown should not depend on the normal worker. The dedicated queue+ # is drained by a worker whose lifetime is independent of that worker.+ if self._shutdown_deferred_work_thread is not None:+ self._shutdown_deferred_work_queue.put(work)+ return+ # If the dedicated thread could not be started, a still-live normal worker is a safe+ # fallback. Keep the old liveness gate below for the worker-less case.+thread = self._deferred_work_threadif thread is None or not thread.is_alive():- return+ if not isinstance(work, _AbandonedHolderRelease):+ returnself._deferred_work_queue.put(work)@synchronized- def _release_first_use_grace(self, cache_entry: CacheRecord) -> None:- """Clear an abandoned record's grace, then let the release hook reconcile the budget."""- if self._cached_models.get(cache_entry.key) is cache_entry and not cache_entry.is_locked:+ def register_first_use_hold(self, cache_entry: CacheRecord) -> Optional[int]:+ """Shield a record while a holder is between retrieving it and its first lock. Returns the+ hold's epoch when armed, None when it could not be.++ Normally reached through get_with_first_use_claim(), which arms the hold in the same lock+ acquisition as the lookup; called directly only by a LoadedModel wrapper built from a+ record that was retrieved with plain get().++ The eviction sweeps treat a held record like a locked one (see+ CacheRecord.in_first_use_window) - in particular, shutdown() retains it with its+ shared-store ownership and budget accounting intact instead of evicting it out from under+ the holder. The caller (LoadedModelWithoutConfig) releases the hold exactly once: via+ release_first_use_hold() on its first lock, or via its weakref finalizer if it is dropped+ without ever locking - both quoting the returned epoch, so a hold that dead-worker+ recovery already zeroed is never re-released against a successor (see+ CacheRecord.first_use_holds_epoch). Because the finalizer route travels through the+ deferred worker, the hold is only granted while a worker is running to carry it - the+ same liveness gate as put()'s admission grace - after first attempting to revive a dead+ worker, which also clears any holds stranded by the death (see _ensure_deferred_worker).++ Not armed for a record that is no longer the occupant under its key: an eviction already+ won the race against this wrapper's construction, the tolerated issue-7513 detached path+ is already in effect, and a hold on a detached record shields nothing.+ """+ self._ensure_deferred_worker()+ if self._deferred_work_thread is None or not self._deferred_work_thread.is_alive():+ return None+ if self._cached_models.get(cache_entry.key) is not cache_entry:+ return None+ cache_entry.first_use_holds += 1+ if self._shutdown_event.is_set():+ self._ensure_shutdown_deferred_worker()+ return cache_entry.first_use_holds_epoch++ @synchronized+ def release_first_use_hold(+ self,+ cache_entry: CacheRecord,+ hold_epoch: Optional[int],+ admission_claim: Optional["FirstUseClaim"] = None,+ ) -> None:+ """Release a register_first_use_hold() hold whose holder reached its first lock.++ `hold_epoch` is None for a claim that was armed with no hold (see FirstUseClaim); there+ is then nothing to decrement, and only the admission shield below is retired.++ `admission_claim`, when given, is the claim doing the releasing: if the record still+ points at it as its admission shield (CacheRecord.admission_claim_ref), that shield is+ retired here too. The shield is object liveness, not claim validity, so without this a+ spent claim would go on shielding the record for as long as the loader's frame - or the+ traceback that captured it - kept the object alive, well past the retrieval it was meant+ to cover.+ """+ if (+ hold_epoch is not None+ and cache_entry.first_use_holds > 0+ and cache_entry.first_use_holds_epoch == hold_epoch+ ):+ cache_entry.first_use_holds -= 1+ if admission_claim is not None:+ claim_ref = cache_entry.admission_claim_ref+ if claim_ref is not None and claim_ref() is admission_claim:+ cache_entry.admission_claim_ref = None++ def _clear_stranded_first_use_holds(self) -> None:+ """Zero every record's holds after the deferred worker is found dead. Caller must hold+ the cache lock.++ A hold's finalizer-initiated release may have been dispatched toward the dead thread and+ dropped - finalizers fire once, so a dropped release is never retried - and such a hold+ would shield its record from every eviction path forever. Bumping the epoch makes the+ surviving wrappers' own releases (and any release still sitting in the queue from before+ the death) no-ops, so they cannot consume holds armed afresh under a later worker. A+ still-live wrapper unshielded here merely falls back to the tolerated issue-7513 detached+ path if an eviction actually races its lock, which is recoverable; a permanently shielded+ record is not.+ """+ dropped: list[tuple[str, int]] = []+ for entry in self._cached_models.values():+ if entry.first_use_holds > 0:+ dropped.append((entry.key, entry.first_use_holds))+ entry.first_use_holds = 0+ entry.first_use_holds_epoch += 1+ # Report only once every record is actually unshielded. A logging handler that raises is+ # one of the ways the worker dies in the first place (see _ensure_deferred_worker), and+ # logging inside the loop would let that same handler abort this sweep partway through,+ # leaving the records it had not reached shielded with nothing left to unshield them.+ for key, count in dropped:+ self._logger.warning(+ f"Dropping {count} first-use hold(s) on cache entry {key}: the deferred-work thread died, "+ "so their releases may have been lost."+ )++ def _recover_stranded_shields(self) -> None:+ """Lift the first-use shields whose release depended on a deferred worker that is gone.+ Caller must hold the cache lock. Does not evict - see _evict_stale_unshielded_entries.++ Holds are always lifted: a hold's only releases are its wrapper's first lock and, if that+ never comes, the finalizer-initiated release this worker carried. With the worker gone the+ latter is dropped by _dispatch_deferred before shutdown, and finalizers never fire twice,+ so a hold left standing shields its record from every eviction path for the life of the+ process. A wrapper unshielded here merely falls back to the tolerated issue-7513 detached+ path if an eviction really does race its lock, which is recoverable; a permanently shielded+ record is not. After shutdown, the dedicated cleanup queue carries later releases.++ The put()-set admission grace is lifted only once the cache is shut down, because only+ then has it actually lost a releaser. On a live cache the grace's backstop is the sweep at+ the top of the next put() - not the worker - and that sweep still runs; clearing it here+ would instead unshield a load that is only midway between its put() and its get(), whose+ record a reconcile could then evict out from under it, turning a worker death into a+ failed load. After shutdown that backstop is gone (no further put() is guaranteed) and+ put() no longer arms the grace at all.++ The admission shield a claimed put() published (CacheRecord.admission_claim_ref) is never+ touched here, shut down or not. Nothing has to release it, so a worker death cannot strand+ it: it expires by itself when the loader's frame does. And unlike a hold, it cannot be+ traded away for certainty - a claim that is still alive means a load that is still+ between its put() and its retrieval, and evicting that record does not fall back to the+ tolerated issue-7513 detached path; the retrieval raises and the load fails (JPPhoto+ review, 2026-09-04). What a shut-down cache with a dead worker actually needs for such a+ record is an eviction once the claim has died, and that no longer depends on this+ worker: the claim's finalizer queues an abandonment release for the dedicated shutdown+ worker, and every later admission that cannot start a worker sweeps unowned stale records+ itself (see put()).+ """+ try:+ self._clear_stranded_first_use_holds()+ finally:+ # The hold sweep reports after mutating every hold, but a logging handler can still+ # raise before control reaches this method's old post-sweep cleanup. Shutdown has no+ # later put() to clear this grace, so make that part unconditional once the cache is+ # shut down; _recover_from_dead_worker will then still run the stale eviction sweep.+ if self._shutdown_event.is_set():+ for entry in self._cached_models.values():+ entry.awaiting_first_use = False++ def _evict_stale_unshielded_entries(self) -> None:+ """Evict records left stale with no lock and no first-use shield. Caller holds the lock.++ Only for a shut-down cache with no normal deferred worker - one that died, or one that could not+ be started by the admission running this (see put()). A record the shutdown sweep marked+ stale and retained *because* of a shield now has nothing left to evict it: the shield is+ lifted, no unlock() is coming for a holder that never locked, no abandonment release can+ be carried, and no further admission is guaranteed to run make_room. Before+ shutdown this is deliberately not done - the ordinary eviction paths are all still+ running, and evicting here would release a record's shared-store ownership while live+ wrappers still hold its tensors, which is the accounting lie shutdown() itself refuses to+ make (a peer's reload would mint a duplicate canonical while the budget counted one).+ """+ evicted = 0+ bytes_freed = 0+ for entry in list(self._cached_models.values()):+ if entry.is_stale and not entry.is_locked and not entry.in_first_use_window:+ key = entry.key+ bytes_freed += entry.cached_model.total_bytes()+ self._delete_cache_entry(entry)+ evicted += 1+ _log_best_effort(+ self._logger,+ "debug",+ f"Evicting stale cache entry {key}: nothing is left to release it (no deferred worker).",+ )+ if evicted:+ self._notify_models_cleared(+ models_cleared=evicted,+ bytes_requested=0,+ bytes_freed=bytes_freed,+ )+ try:+ gc.collect()+ TorchDevice.empty_cache()+ except Exception:+ # Deferrable housekeeping: empty_cache() can raise from a sick CUDA context after+ # an eviction, and this runs in a dying worker's last frame. The eviction itself+ # is already done and must not be undone by a failure to hand memory back.+ _log_best_effort(+ self._logger,+ "exception",+ "Error releasing device memory after a stranded-record eviction",+ )++ @synchronized+ def _recover_from_dead_worker(self, worker: threading.Thread) -> None:+ """Run stranded-shield recovery from inside the deferred worker as it dies abnormally.++ The other two recovery sites both depend on something else happening first: the next+ admission (_ensure_deferred_worker) or shutdown(). Neither is guaranteed - a cache that is+ already shut down takes no more admissions, and shutdown()'s own liveness check passes if+ the worker is still running at that moment and dies a moment later. That leaves the+ records the shutdown sweep retained for a live holder shielded by holds nothing can+ release. Recovering here makes the recovery a property of the death itself.+ """+ if self._deferred_work_thread is not worker:+ # A replacement worker has already taken this slot, so the shields standing now were+ # granted under it and are its to release. _ensure_deferred_worker cleared whatever+ # this thread stranded when it started that replacement.+ return+ # Retire the slot first. This thread is still `is_alive()` while it unwinds its own frame,+ # so a concurrent admission would otherwise read the worker as healthy and arm a shield+ # that this recovery is about to zero. With the slot empty, put() withholds the grace and+ # register_first_use_hold starts a replacement worker instead. (An unsynchronized+ # _dispatch_deferred that read the slot just before this can still enqueue against the+ # dying thread; that item is simply never drained, and _AbandonedHolderRelease holds its+ # record weakly so it pins nothing.)+ self._deferred_work_thread = None+ try:+ self._recover_stranded_shields()+ except Exception:+ # Recovery must not prevent the shutdown sweep. In particular, a logging handler can+ # be the reason this worker died and can raise again while _clear_stranded... reports.+ _log_best_effort(self._logger, "exception", "Error recovering shields from a dead model-cache worker")+ finally:+ if self._shutdown_event.is_set():+ try:+ self._evict_stale_unshielded_entries()+ except Exception:+ _log_best_effort(self._logger, "exception", "Error evicting stale model-cache entries")+ finally:+ if any(+ entry.first_use_holds > 0 or entry.admission_in_flight or entry.abandonment_release_pending+ for entry in self._cached_models.values()+ ):+ self._ensure_shutdown_deferred_worker()++ @synchronized+ def _release_abandoned_holder(self, cache_entry: CacheRecord, held_first_use: bool, hold_epoch: int) -> None:+ """Deferred-worker handler for a LoadedModel wrapper dropped without ever locking.++ Releases whatever shield the wrapper held, then - if the abandoned record is stale+ (shutdown() or drop_model() marked it while the wrapper kept it retained) and nothing else+ holds it - evicts it here, because no unlock() is ever coming to run the usual+ stale-eviction path. The synchronized release hook then reconciles the budget as usual.+ """+ if held_first_use and cache_entry.first_use_holds > 0 and cache_entry.first_use_holds_epoch == hold_epoch:+ cache_entry.first_use_holds -= 1+ if self._cached_models.get(cache_entry.key) is not cache_entry:+ return+ if not cache_entry.is_locked:cache_entry.awaiting_first_use = False+ if cache_entry.is_stale and not cache_entry.is_locked and not cache_entry.in_first_use_window:+ key = cache_entry.key+ bytes_freed = cache_entry.cached_model.total_bytes()+ self._delete_cache_entry(cache_entry)+ self._notify_models_cleared(+ models_cleared=1,+ bytes_requested=0,+ bytes_freed=bytes_freed,+ )+ gc.collect()+ TorchDevice.empty_cache()+ _log_best_effort(self._logger, "debug", f"Evicted stale cache entry {key} after its holder was abandoned.")@synchronizeddef _get_cache_snapshot(self) -> dict[str, CacheEntrySnapshot]:@@ -900,7 +1723,21 @@ class ModelCache:Raises IndexError if the model is not in the cache."""- if key in self._cached_models:+ cache_entry = self._cached_models.get(key)+ if (+ cache_entry is not None+ and cache_entry.is_stale+ and not self._shutdown_event.is_set()+ and not cache_entry.is_locked+ and not cache_entry.in_first_use_window+ ):+ # A dead-worker recovery can leave a stale, previously held record with no release+ # worker. Do not return it as a cache hit: drop it before the miss path so the loader+ # can construct a replacement instead of silently reusing invalidated weights.+ self._delete_cache_entry(cache_entry)+ cache_entry = None++ if cache_entry is not None:if self.stats:self.stats.hits += 1else:@@ -913,7 +1750,7 @@ class ModelCache:cache_entry = self._cached_models[key]# Deliberately NOT clearing awaiting_first_use here: this method is synchronized, so its- # own lock-release hook may run a pending budget reconcile before returning — ending the+ # own lock-release hook may run a pending budget reconcile before returning - ending the# grace now would let that hook evict the very record this call just selected, detaching# a live model from the cache (and from the RAM accounting) before the caller can lock# it. The grace ends at lock(), when the entry becomes pinned anyway.@@ -937,6 +1774,57 @@ class ModelCache:return cache_entry+ @synchronized+ def get_with_first_use_claim(+ self, key: str, stats_name: Optional[str] = None+ ) -> tuple[CacheRecord, Optional[FirstUseClaim]]:+ """get(), with the retrieved record's first-use hold armed atomically with the lookup.++ Every caller that is going to wrap the record in a LoadedModel should retrieve it through+ this method rather than get(): the returned claim shields the record from the asynchronous+ eviction sweeps for the whole stretch between the lookup and the wrapper's first lock,+ with no unshielded gap at the front of it (see FirstUseClaim). Both calls below run under+ this frame's lock acquisition, and the synchronized decorator's reconcile hook fires only+ on the outermost frame, so no eviction can run between the lookup and the arming.++ The claim must be handed to the wrapper+ (`LoadedModelWithoutConfig(..., first_use_claim=claim)`) or simply dropped; either way its+ hold is released exactly once and the caller has nothing to clean up.++ While no deferred worker is running to carry a hold's finalizer release (one could not be+ started under thread exhaustion), the claim is armed with no hold: it shields nothing+ from the sweeps, so the caller is exactly where it was before this method existed - the+ record may be evicted under it, and lock() falls back to the tolerated issue-7513+ detached path - but it still owns the window in the sense that matters without a worker+ (see FirstUseClaim). Returns `(record, None)` only when an eviction already detached the+ record, which is the one case there is nothing left to own.++ Raises IndexError if the model is not in the cache, exactly as get() does.+ """+ cache_entry = self.get(key, stats_name)+ return cache_entry, self._claim_first_use(cache_entry)++ def _claim_first_use(self, cache_entry: CacheRecord) -> Optional[FirstUseClaim]:+ """Arm a first-use hold, if a worker is running to carry its release, and wrap it in the+ claim that owns the window. Caller holds the lock. Returns None only for a record that is+ no longer the occupant under its key."""+ hold_epoch = self.register_first_use_hold(cache_entry)+ if hold_epoch is None and self._cached_models.get(cache_entry.key) is not cache_entry:+ return None+ try:+ claim = FirstUseClaim(self, cache_entry, hold_epoch)+ if self._shutdown_event.is_set():+ self._ensure_shutdown_deferred_worker()+ return claim+ except BaseException:+ # The hold is armed, but the object that was to carry its release does not exist -+ # weakref.finalize() allocates, and this cache runs at the RAM ceiling by design. An+ # orphaned hold is the one failure this whole mechanism must not produce: it shields+ # its record from every eviction path, shutdown()'s sweep included, for the life of+ # the process. Hand the hold back before letting the failure out.+ self.release_first_use_hold(cache_entry, hold_epoch)+ raise+@synchronized@record_activitydef lock_in_ram(self, cache_entry: CacheRecord) -> None:@@ -978,7 +1866,7 @@ class ModelCache:# A CPU compute_device means there's no VRAM load to do. This happens in two distinct situations:# 1. The model is explicitly configured cpu_only, but the cache's default execution device is a GPU.# 2. The whole install is CPU-only (no GPU), so every model's compute_device is CPU by default.- # Only case 1 is noteworthy — surface it at INFO with the "(cpu_only)" cause so it mirrors the+ # Only case 1 is noteworthy - surface it at INFO with the "(cpu_only)" cause so it mirrors the# "Loaded model ... onto <device> device" line emitted for GPU loads below. Case 2 would fire for every# lock of every model and says nothing about a per-model choice, so keep it at DEBUG and drop the wording.model_compute_device = cache_entry.cached_model.compute_device@@ -1030,19 +1918,31 @@ class ModelCache:# If `drop_model()` marked this entry stale (e.g. settings changed while a generation# was using it), evict now so the next load rebuilds with the new settings rather than# silently reusing the pre-change cached module.- if cache_entry.is_stale and not cache_entry.is_locked and cache_entry.key in self._cached_models:+ # Identity check, not key membership: if this record was already detached (error-path+ # delete) and the key re-admitted, the occupant is a different, non-stale record that must+ # not be evicted - and no cleared-callback should fire for a no-op.+ # A first-use hold defers the eviction the same way a lock does: another wrapper may+ # already hold this record for its own upcoming lock, and evicting here would detach it+ # mid-window. Whatever releases the hold - that holder's own unlock() after use, or the+ # abandonment path (_release_abandoned_holder) - performs the stale eviction instead.+ # (Only the hold half of the first-use window can be live here: awaiting_first_use is+ # cleared by every lock entry point, and a brand-new record has no lockers before that,+ # so no unlock() can observe it set.)+ if (+ cache_entry.is_stale+ and not cache_entry.is_locked+ and cache_entry.first_use_holds == 0+ and not cache_entry.admission_in_flight+ and self._cached_models.get(cache_entry.key) is cache_entry+ ):bytes_freed = cache_entry.cached_model.total_bytes()self._delete_cache_entry(cache_entry)- if self.stats:- self.stats.cleared = (self.stats.cleared or 0) + 1- snapshot = self._get_cache_snapshot()- for cb in self._on_cache_models_cleared_callbacks:- cb(- models_cleared=1,- bytes_requested=0,- bytes_freed=bytes_freed,- cache_snapshot=snapshot,- )+ self._notify_models_cleared(+ models_cleared=1,+ bytes_requested=0,+ bytes_freed=bytes_freed,+ cumulative_stats=True,+ )gc.collect()TorchDevice.empty_cache()self._logger.debug(f"Evicted stale cache entry {cache_entry.key} after unlock.")@@ -1260,7 +2160,7 @@ class ModelCache:# device flips between workers; querying without the device argument can read a different# (e.g. idle) GPU's allocation. That breaks the cancellation in _get_vram_available# (which adds vram_allocated(execution_device)), inflating "available" toward total VRAM- # so the cache never offloads — causing VRAM OOMs that ignore device_working_mem_gb.+ # so the cache never offloads - causing VRAM OOMs that ignore device_working_mem_gb.return torch.cuda.memory_allocated(self._execution_device)elif self._execution_device.type == "xpu":# Same per-device requirement as CUDA above.@@ -1360,7 +2260,7 @@ class ModelCache:(a fraction of system RAM, less InvokeAI's baseline) with the same minimum floor.In multi-GPU mode there is one cache per device, and each device's heuristic independently- allows up to this fraction of system RAM; summed across N devices that would claim ~N× as+ allows up to this fraction of system RAM; summed across N devices that would claim ~Nx asmuch RAM and cause the system to swap. The model manager uses this value to cap that sum so asafe amount of RAM is always left for the OS and other processes."""@@ -1546,7 +2446,14 @@ class ModelCache:model_key = self._cache_stack[pos]cache_entry = self._cached_models[model_key]- if not cache_entry.is_locked:+ # A first-use hold or live admission claim shields here: a wrapper obtained warm can+ # sit un-entered, or a loader can be between put() and get(), while another model's+ # cold load makes room. Evicting either record would detach it from the holder about+ # to lock it (see CacheRecord.first_use_holds and admission_in_flight). The put()-set+ # grace deliberately does NOT shield from this path (matching its long-standing+ # semantics): its releaser is the loader's own forward progress, not a finalizer, so+ # an orphaned grace must stay reachable by the synchronous eviction paths.+ if not cache_entry.is_locked and cache_entry.first_use_holds == 0 and not cache_entry.admission_in_flight:ram_bytes_freed += cache_entry.cached_model.total_bytes()self._logger.debug(f"Dropping {model_key} from RAM cache to free {(cache_entry.cached_model.total_bytes() / MB):.2f}MB."@@ -1559,11 +2466,11 @@ class ModelCache:if self._ram_budget is not None and bytes_needed > self._get_ram_available():# This cache's own evictable entries are exhausted, but the global budget is still- # short: the remaining usage is held by other device caches — e.g. a shared model whose+ # short: the remaining usage is held by other device caches - e.g. a shared model whose# weights stay live because another (possibly idle) cache retains them. Without# cross-cache eviction the cap would be exceeded for as long as that cache stays idle,# so ask each peer to drop its unlocked entries. Whatever still can't be freed is held- # by locked (in-use) entries, which release soon — the same transient overshoot the+ # by locked (in-use) entries, which release soon - the same transient overshoot the# single-cache path has always allowed.for peer in self._ram_budget.peer_caches(exclude=self):if bytes_needed <= self._get_ram_available():@@ -1576,7 +2483,7 @@ class ModelCache:# That is handled AFTER admission: put() re-checks the budget once the new model is# actually counted and records a reconcile request on every peer (see# request_budget_reconcile). Requesting here, pre-admission, would race the peers'- # reconcile checks against a budget that does not yet include the incoming model —+ # reconcile checks against a budget that does not yet include the incoming model -# a peer could see the budget as satisfied, clear the request, and leave the cap# exceeded once the model lands.@@ -1592,15 +2499,11 @@ class ModelCache:## Keep in mind that gc is only responsible for handling reference cycles. Most objects should be cleaned up# immediately when their reference count hits 0.- if self.stats:- self.stats.cleared = models_cleared- for cb in self._on_cache_models_cleared_callbacks:- cb(- models_cleared=models_cleared,- bytes_requested=bytes_needed,- bytes_freed=ram_bytes_freed,- cache_snapshot=self._get_cache_snapshot(),- )+ self._notify_models_cleared(+ models_cleared=models_cleared,+ bytes_requested=bytes_needed,+ bytes_freed=ram_bytes_freed,+ )gc.collect()TorchDevice.empty_cache()@@ -1611,41 +2514,48 @@ class ModelCache:"""Evict this cache's unlocked entries on behalf of another device's cache (best effort).Called by a peer whose own eviction stack is exhausted while the shared RamBudget is still- over-committed — typically because this cache holds the last reference to shared weights the+ over-committed - typically because this cache holds the last reference to shared weights thepeer already dropped. `is_satisfied` is re-checked after every eviction so no more entriesare dropped than the peer actually needs.The peer calls this while holding its own cache lock, so this cache's lock is takenNON-blocking: if it is contended, this device is actively working and the peer simply skips- it — blocking here could deadlock two caches making room for each other simultaneously.+ it - blocking here could deadlock two caches making room for each other simultaneously.Returns the number of entries evicted, or None if the lock was contended and nothing couldbe attempted. Either way, if the shared budget is still exceeded once the caller admits itsmodel, the caller records a deferred reconcile request on every peer (see- request_budget_reconcile) — and every unlock that leaves the budget exceeded records one on- its own cache — so a skip never leaves the budget exceeded indefinitely.+ request_budget_reconcile) - and every unlock that leaves the budget exceeded records one on+ its own cache - so a skip never leaves the budget exceeded indefinitely."""if not self._lock.acquire(blocking=False):return Nonetry:models_cleared = 0+ bytes_freed = 0pos = 0while pos < len(self._cache_stack) and not is_satisfied():cache_entry = self._cached_models[self._cache_stack[pos]]- if cache_entry.is_locked or cache_entry.awaiting_first_use:+ if cache_entry.is_locked or cache_entry.in_first_use_window:pos += 1continueself._logger.debug(f"Dropping {cache_entry.key} from RAM cache on behalf of a peer device cache "f"({(cache_entry.cached_model.total_bytes() / MB):.2f}MB).")+ bytes_freed += cache_entry.cached_model.total_bytes()self._delete_cache_entry(cache_entry)models_cleared += 1+ self._notify_models_cleared(+ models_cleared=models_cleared,+ bytes_requested=0,+ bytes_freed=bytes_freed,+ )return models_clearedfinally:self._lock.release()# This manual release must honor a pending budget reconcile just like the- # synchronized-decorator hook — a requester whose inline attempt found the lock+ # synchronized-decorator hook - a requester whose inline attempt found the lock# held by this method depends on it (see request_budget_reconcile). Non-blocking:# the peer calling this method holds its own cache lock, and blocking on this# cache's lock while holding another cache's lock is the one shape that could@@ -1659,12 +2569,12 @@ class ModelCache:Called by a peer that admitted a model while the global RamBudget was exceeded and couldnot free enough by evicting from this cache directly (evict_unlocked_for_peer found thelock contended, or everything evictable was already gone). Setting the pending flag alone- is not enough: this cache's busy operation may have released its lock — running its- reconcile hook while the flag was still unset — just before the flag was set here, and if+ is not enough: this cache's busy operation may have released its lock - running its+ reconcile hook while the flag was still unset - just before the flag was set here, and ifthe cache then stays idle no future lock release would ever honor the request (lostwakeup). The inline attempt below closes that window: either the lock is free now and the- reconcile runs immediately, or it is still held and the eventual release hook — which runs- strictly after the flag set below — performs it.+ reconcile runs immediately, or it is still held and the eventual release hook - which runs+ strictly after the flag set below - performs it."""self._budget_reconcile_pending.set()# Non-blocking: the caller holds its own cache lock, and blocking here could deadlock two@@ -1687,7 +2597,7 @@ class ModelCache:returnwhile True:if self._ram_budget.available() >= 0:- # Budget satisfied: retire the request. Clearing races a concurrent admission —+ # Budget satisfied: retire the request. Clearing races a concurrent admission -# a peer counts its new model (driving the budget negative) BEFORE setting the# flag, so if the budget is negative again after the clear, the clear may have# wiped a request whose own inline attempt already saw the flag unset and@@ -1696,62 +2606,107 @@ class ModelCache:if self._ram_budget.available() >= 0:returnself._budget_reconcile_pending.set()+ models_cleared = 0+ bytes_freed = 0+ # Acquire immediately before the try: a BaseException delivered between the two leaks+ # the RLock, and a cache lock owned by a thread that is unwinding blocks every other+ # thread for the life of the process. This narrows that window to the interpreter's+ # own check between acquire() returning and SETUP_FINALLY rather than closing it -+ # inherent to acquiring a lock without `with`, which the blocking flag rules out here.if not self._lock.acquire(blocking=blocking):# Contended (non-blocking caller only): the holder releases through a reconcile# hook, which re-runs this reconcile with the flag still set.return- models_cleared = 0try:pos = 0while pos < len(self._cache_stack) and self._ram_budget.available() < 0:cache_entry = self._cached_models[self._cache_stack[pos]]- if cache_entry.is_locked or cache_entry.awaiting_first_use:+ if cache_entry.is_locked or cache_entry.in_first_use_window:pos += 1continueself._logger.debug(f"Dropping {cache_entry.key} from RAM cache to reconcile the shared RAM budget "f"({(cache_entry.cached_model.total_bytes() / MB):.2f}MB).")+ bytes_freed += cache_entry.cached_model.total_bytes()self._delete_cache_entry(cache_entry)models_cleared += 1finally:self._lock.release()if models_cleared > 0:+ self._notify_models_cleared(+ models_cleared=models_cleared,+ bytes_requested=0,+ bytes_freed=bytes_freed,+ )gc.collect()TorchDevice.empty_cache()if self._ram_budget.available() < 0:# Everything evictable here is gone; the remainder is held by locked (in-use)- # or just-admitted entries. Leave the flag set — the eventual unlock()'s hook+ # or just-admitted entries. Leave the flag set - the eventual unlock()'s hook# (or the loader's next cache operation) retries.return# Satisfied: loop back to retire the flag via the guarded clear above.def _delete_cache_entry(self, cache_entry: CacheRecord) -> None:- """Delete cache_entry from the cache if it exists. No exception is thrown if it doesn't exist."""- was_present = cache_entry.key in self._cached_models+ """Delete cache_entry from the cache if it is the record currently held under its key.+ No exception is thrown if it is absent (or the key is now held by a different record)."""+ # Identity, not key membership: a record can be deleted while still locked (the VRAM-move+ # error paths) and the key re-admitted before the record's last unlock() runs the+ # stale-eviction path. A key-only check would pop the NEW record from the cache - detaching+ # it from all accounting - and, the old record's shared release having already happened,+ # read uses_shared_weights as False and debit the non-shared budget for bytes that were+ # admitted as shared. The identity guard makes a delete of a detached record a full no-op,+ # which also keeps the release exactly-once for double-deletes (release_shared_weights is+ # itself idempotent, but the budget debit is not).+ if self._cached_models.get(cache_entry.key) is not cache_entry:+ returnself._cache_stack = [key for key in self._cache_stack if key != cache_entry.key]- self._cached_models.pop(cache_entry.key, None)+ del self._cached_models[cache_entry.key]# Drop this device's reference to the shared canonical CPU weights so they can be freed once- # the last device releases them. Guard on was_present so a double-delete doesn't- # double-release (release_shared_weights is itself idempotent, but a re-added entry under the- # same key must not be released by a stale delete).- if was_present:- uses_shared = cache_entry.cached_model.uses_shared_weights- total_bytes = cache_entry.cached_model.total_bytes()- cache_entry.cached_model.release_shared_weights()- # Drop the matching non-shared contribution from the global budget (shared weights are- # released via the store above). Captured before release_shared_weights() flips the flag.- if self._ram_budget is not None and not uses_shared:- self._ram_budget.remove_non_shared(total_bytes, cache=self)+ # the last device releases them.+ uses_shared = cache_entry.cached_model.uses_shared_weights+ total_bytes = cache_entry.cached_model.total_bytes()+ cache_entry.cached_model.release_shared_weights()+ # Drop the matching non-shared contribution from the global budget (shared weights are+ # released via the store above). Captured before release_shared_weights() flips the flag.+ if self._ram_budget is not None and not uses_shared:+ self._ram_budget.remove_non_shared(total_bytes, cache=self)++ def _notify_models_cleared(+ self,+ models_cleared: int,+ bytes_requested: int,+ bytes_freed: int,+ *,+ cumulative_stats: bool = False,+ ) -> None:+ """Update clear statistics and notify observers after one or more records were evicted."""+ if models_cleared <= 0:+ return+ if self.stats:+ if cumulative_stats:+ self.stats.cleared = (self.stats.cleared or 0) + models_cleared+ else:+ self.stats.cleared = models_cleared+ snapshot = self._get_cache_snapshot()+ for cb in self._on_cache_models_cleared_callbacks:+ cb(+ models_cleared=models_cleared,+ bytes_requested=bytes_requested,+ bytes_freed=bytes_freed,+ cache_snapshot=snapshot,+ )@synchronizeddef drop_model(self, model_key: str) -> int:"""Drop all cache entries belonging to a model so the next load rebuilds them.Cache keys are `<model_key>` or `<model_key>:<submodel>` (see `get_model_cache_key`),- so a single model may have multiple entries. Locked entries are marked `is_stale` and- evicted by `unlock()` as soon as the last lock releases — without that, a setting- toggled during an in-flight generation would survive on the locked entry and quietly+ so a single model may have multiple entries. Locked entries - and entries inside a+ first-use window (a LoadedModel wrapper obtained but not yet locked) - are marked+ `is_stale` and evicted as soon as the last lock (or the window) releases - without that,+ a setting toggled during an in-flight generation would survive on the locked entry and quietlyget reused by the next generation.Returns the number of entries immediately dropped (locked entries that are only marked@@ -1765,7 +2720,13 @@ class ModelCache:dropped: list[CacheRecord] = []bytes_freed = 0for entry in matching:- if entry.is_locked:+ # A record with a first-use hold or live admission claim is deferred exactly like a+ # locked one: a live wrapper is about to lock it, or its loader is about to retrieve+ # it, and evicting now would detach the record mid-window. The stale mark makes the+ # hold/claim release - unlock() after use, or the abandonment path - perform the+ # eviction. (An orphaned put()-grace, by contrast, stays evictable here, as it always+ # has been on the synchronous paths.)+ if entry.is_locked or entry.first_use_holds > 0 or entry.admission_in_flight:entry.is_stale = Truecontinuebytes_freed += entry.cached_model.total_bytes()@@ -1779,16 +2740,11 @@ class ModelCache:self._shared_cpu_weights.invalidate(model_key)if dropped:- if self.stats:- self.stats.cleared = len(dropped)- snapshot = self._get_cache_snapshot()- for cb in self._on_cache_models_cleared_callbacks:- cb(- models_cleared=len(dropped),- bytes_requested=0,- bytes_freed=bytes_freed,- cache_snapshot=snapshot,- )+ self._notify_models_cleared(+ models_cleared=len(dropped),+ bytes_requested=0,+ bytes_freed=bytes_freed,+ )gc.collect()TorchDevice.empty_cache()return len(dropped)diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py b/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.pyindex c734e96def..f9bf93dd73 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py@@ -1,7 +1,7 @@"""End-to-end tests of the global RamBudget driving eviction across per-device caches.Validates that the budget counts a shared model once (not once-per-GPU), counts non-deduplicated-models per-instance, and that eviction is made against the global deduplicated total — including the+models per-instance, and that eviction is made against the global deduplicated total - including thecase where a cache cannot free RAM because another device still holds the model. Runs on CPU."""@@ -65,7 +65,7 @@ def _use_and_release(cache: ModelCache, key: str):def _wait_until(predicate, timeout: float = 10.0) -> bool:- """Poll until predicate() is true — budget reconciles may run on a background thread."""+ """Poll until predicate() is true - budget reconciles may run on a background thread."""deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:if predicate():@@ -93,7 +93,7 @@ def test_shared_model_counts_once_in_global_budget(mock_logger):def _collect_until(predicate, attempts: int = 5) -> bool:- """gc.collect() until predicate() holds — finalizer chains can need more than one pass."""+ """gc.collect() until predicate() holds - finalizer chains can need more than one pass."""for _ in range(attempts):gc.collect()if predicate():@@ -104,7 +104,7 @@ def _collect_until(predicate, attempts: int = 5) -> bool:def test_shutdown_releases_shared_weights_synchronously(mock_logger):"""shutdown() must release its resident records' shared references itself: the finalizerfallback only enqueues, and at teardown there may be no later store operation to drain the- queue — so relying on collection would leave the canonical tensors pinned indefinitely."""+ queue - so relying on collection would leave the canonical tensors pinned indefinitely."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=10**12, shared_store=store)cache = _make_cache(store, budget, mock_logger)@@ -118,9 +118,1983 @@ def test_shutdown_releases_shared_weights_synchronously(mock_logger):assert store._deferred_releases.qsize() == 0+def test_shutdown_evicts_unlocked_records(mock_logger):+ """shutdown() must route resident records through eviction, not merely release their+ shared-store references: a released-but-retained record keeps its tensors alive while the+ store (and budget) report zero - accounting that no longer describes reality."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ record = _use_and_release(cache, "m")+ wrapper_ref = weakref.ref(record.cached_model)+ del record++ cache.shutdown()+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+ # The record is gone, so the tensors really are released: the zero accounting is true.+ assert _collect_until(lambda: wrapper_ref() is None)+++def test_shutdown_eviction_notifies_observers_and_updates_stats(mock_logger):+ """shutdown() is an eviction path, so its cleared event must match other evictions."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ cache.stats = CacheStats()+ callback = MagicMock()+ cache.on_cache_models_cleared(callback)++ cache.shutdown()++ assert cache.stats.cleared == 1+ callback.assert_called_once()+ kwargs = callback.call_args.kwargs+ assert kwargs["models_cleared"] == 1+ assert kwargs["bytes_requested"] == 0+ assert kwargs["bytes_freed"] > 0+++def test_abandoned_shutdown_record_eviction_notifies_observers_and_updates_stats(mock_logger):+ """Deferred stale eviction must expose the same clear event as synchronous eviction."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ cache.stats = CacheStats()+ callback = MagicMock()+ cache.on_cache_models_cleared(callback)++ cache.shutdown()+ del loaded_model++ assert _wait_until(lambda: "m" not in cache._cached_models)+ assert cache.stats.cleared == 1+ callback.assert_called_once()+ kwargs = callback.call_args.kwargs+ assert kwargs["models_cleared"] == 1+ assert kwargs["bytes_requested"] == 0+ assert kwargs["bytes_freed"] > 0+++def test_budget_reconcile_eviction_notifies_observers_and_updates_stats(mock_logger):+ """Background budget eviction must expose the same clear event as direct eviction."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=int(S * 1.4), shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ cache.stats = CacheStats()+ callback = MagicMock()+ cache.on_cache_models_cleared(callback)++ budget.add_non_shared(S, cache=cache)+ cache.request_budget_reconcile()++ assert _wait_until(lambda: "m" not in cache._cached_models)+ assert cache.stats.cleared == 1+ callback.assert_called_once()+ kwargs = callback.call_args.kwargs+ assert kwargs["models_cleared"] == 1+ assert kwargs["bytes_requested"] == 0+ assert kwargs["bytes_freed"] > 0+++def test_shutdown_retains_locked_records_with_their_accounting(mock_logger):+ """A record locked by an in-flight generation at shutdown() keeps its shared-store reference:+ its tensors really are resident, so the store and budget must keep saying so. unlock() then+ evicts it through the ordinary stale path, releasing exactly once."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ record = cache.get("m")+ cache.lock(record, None)++ cache.shutdown()+ # Still locked: ownership and accounting are retained.+ assert "m" in cache._cached_models+ assert store.refcount("m") == 1+ assert budget.total_in_use() == S++ cache.unlock(record)+ # The last unlock evicts the stale-marked record and returns the accounting to zero.+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_shutdown_evicts_unclaimed_admission_with_live_worker(mock_logger):+ """An unclaimed put() has no owner that can release its admission after shutdown()."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()+ assert cache._cached_models["m"].awaiting_first_use++ cache.shutdown()+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_stale_eviction_ignores_a_readmitted_record_under_the_same_key(mock_logger):+ """A stale-marked record can be detached while still locked (the VRAM-move error paths call+ _delete_cache_entry on a locked record) and the key re-admitted before its last unlock().+ The stale eviction must match the record by IDENTITY: a key-only match would pop the new+ record - detaching it from all accounting - and debit the budget for the old record's bytes."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ record_1 = cache.get("m")+ cache.lock(record_1, None)++ cache.shutdown() # marks the locked record stale+ # Simulate the error-path delete of the locked record (see _move_model_to_vram/_ram), then a+ # post-shutdown re-admission of the same key (reachable: see the put()-after-shutdown() note).+ cache._delete_cache_entry(record_1)+ cache.put("m", DummyModule())+ record_2 = cache._cached_models["m"]+ assert record_2 is not record_1+ in_use_after_readmission = budget.total_in_use()+ assert in_use_after_readmission == S++ # The detached record's last unlock must not evict the re-admitted record or touch the budget.+ cache.unlock(record_1)+ assert cache._cached_models.get("m") is record_2+ assert store.refcount("m") == 1+ assert budget.total_in_use() == in_use_after_readmission+++def test_no_duplicate_canonical_when_peer_reloads_after_shutdown(mock_logger):+ """The canonical entry must survive while a locked holder retains it, so a peer cache+ reloading the key after this cache's shutdown() adopts the SAME canonical tensors instead of+ registering a second copy alongside the still-resident one."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache_a = _make_cache(store, budget, mock_logger)+ cache_b = _make_cache(store, budget, mock_logger)+ try:+ cache_a.put("m", DummyModule())+ record_a = cache_a.get("m")+ cache_a.lock(record_a, None)+ canonical_before = store.peek("m")++ cache_a.shutdown()+ cache_b.put("m", DummyModule())+ _use_and_release(cache_b, "m")+ # cache_b adopted the existing canonical: one copy in RAM, referenced by both holders.+ assert store.peek("m") is canonical_before+ assert store.refcount("m") == 2+ assert budget.total_in_use() == S++ cache_a.unlock(record_a)+ assert store.refcount("m") == 1+ assert budget.total_in_use() == S+ finally:+ cache_b.shutdown()+++def test_shutdown_retains_record_inside_get_to_lock_window(mock_logger):+ """shutdown() racing the gap between get() and the LoadedModel's first lock must retain the+ record (JPPhoto review, 2026-08-13): a warm record is past its admission grace, so without+ the wrapper's first-use hold the sweep would evict it, releasing shared-store ownership while+ the holder proceeds to lock the detached record - and a peer's reload of the same key would+ then mint a duplicate canonical copy that the budget counts only once."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache_a = _make_cache(store, budget, mock_logger)+ cache_b = _make_cache(store, budget, mock_logger)+ try:+ cache_a.put("m", DummyModule())+ _use_and_release(cache_a, "m") # warm: past the admission grace, unlocked++ # A generation retrieves the model; shutdown() lands before it enters the context.+ loaded_model = LoadedModelWithoutConfig(cache_record=cache_a.get("m"), cache=cache_a)+ canonical_before = store.peek("m")+ cache_a.shutdown()++ record = cache_a._cached_models.get("m")+ assert record is loaded_model._cache_record, "shutdown() evicted the record mid-window"+ assert record.is_stale+ assert store.refcount("m") == 1+ assert budget.total_in_use() == S++ # A peer reloading the key while the holder is still using it adopts the SAME canonical.+ with loaded_model as _model:+ assert cache_a._cached_models.get("m") is loaded_model._cache_record, "locked a detached record"+ cache_b.put("m", DummyModule())+ _use_and_release(cache_b, "m")+ assert store.peek("m") is canonical_before, "peer reload minted a duplicate canonical"+ assert store.refcount("m") == 2+ assert budget.total_in_use() == S++ # Exiting the context is the record's last release: the stale mark set at shutdown()+ # evicts it with its accounting.+ assert "m" not in cache_a._cached_models+ assert store.refcount("m") == 1+ assert budget.total_in_use() == S+ finally:+ cache_b.shutdown()+++def test_shutdown_retains_a_claimed_admission_for_its_in_flight_load(mock_logger):+ """A loader between its put() and its retrieval still holds the canonical tensors it just+ admitted, so shutdown() must retain that record. Evicting it would release shared-store+ ownership (and debit the budget) for bytes that are still resident - a peer's reload would+ then mint a duplicate canonical the budget counts once - and would fail the in-flight load+ with an IndexError from a retrieval that no longer finds its own model. Invoker.stop() stops+ the model manager BEFORE the session processor, whose workers are cancelled but not joined,+ so that load is genuinely still running."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache_a = _make_cache(store, budget, mock_logger)+ cache_b = _make_cache(store, budget, mock_logger)+ try:+ # The loader admits its model and still holds it; shutdown() lands before the retrieval.+ admission_claim = cache_a.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None, "the admission was not claimable"+ record = cache_a._cached_models["m"]+ canonical_before = store.peek("m")+ cache_a.shutdown()++ assert cache_a._cached_models.get("m") is record, "shutdown() evicted a record mid-admission"+ assert record.is_stale+ assert store.refcount("m") == 1+ assert budget.total_in_use() == S++ # A peer loading the key now adopts the same canonical rather than duplicating it.+ cache_b.put("m", DummyModule())+ _use_and_release(cache_b, "m")+ assert store.peek("m") is canonical_before, "peer reload minted a duplicate canonical"+ assert store.refcount("m") == 2++ # The loader's retrieval still finds its model, and hands the shield to its own claim.+ retrieved, first_use_claim = cache_a.get_with_first_use_claim("m")+ assert retrieved is record+ admission_claim.release()++ loaded_model = LoadedModelWithoutConfig(cache_record=record, cache=cache_a, first_use_claim=first_use_claim)+ with loaded_model as _model:+ assert cache_a._cached_models.get("m") is record, "locked a detached record"+ assert "m" not in cache_a._cached_models+ assert store.refcount("m") == 1+ assert budget.total_in_use() == S+ finally:+ cache_b.shutdown()+++def test_a_cancelled_claimed_admission_is_evicted_at_shutdown(mock_logger):+ """JPPhoto's report in its own order (2026-08-30): a load that admits a model and is then+ cancelled before its retrieval leaves no wrapper, so no finalizer and no unlock() is ever+ coming, and after shutdown no further put() is guaranteed to run the sweep that was the+ put()-set grace's last backstop - the record, its shared-store reference and its budget charge+ used to stand until the cache object was collected. The admission claim is what ends it:+ dropping it releases the admission, so the shutdown sweep finds an ordinary idle record."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]++ del admission_claim # the load is cancelled between its put() and its retrieval+ gc.collect()+ assert _wait_until(lambda: not record.in_first_use_window), "the cancelled admission stayed shielded"++ cache.shutdown()+ assert "m" not in cache._cached_models, "shutdown() retained an admission nothing can release"+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_a_dropped_admission_claim_lets_shutdown_evict_its_record(mock_logger):+ """The other half of the claimed admission: a load cancelled before its retrieval drops the+ claim, and that release is what evicts the record the shutdown sweep retained for it - with+ its shared-store reference and its budget bytes."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]+ assert record.first_use_holds == 1+ assert not record.awaiting_first_use, "a claimed admission must use its claim instead of grace"++ cache.shutdown()+ assert cache._cached_models.get("m") is record++ del admission_claim # the load was cancelled before it could retrieve the model+ gc.collect()+ assert _wait_until(lambda: "m" not in cache._cached_models), "a cancelled admission stayed resident"+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_a_dead_worker_falls_back_to_the_admission_claim(mock_logger):+ """A claimed admission remains protected by its claim after dead-worker recovery zeroes the+ worker-carried hold."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]+ assert record.first_use_holds == 1 and not record.awaiting_first_use++ _kill_worker_abnormally(cache, record)+ assert record.first_use_holds == 0, "premise broken: the recovery did not zero the hold"+ assert not record.awaiting_first_use, "the claim must not depend on the admission grace"++ # An asynchronous eviction sweep must still skip the record, and the loader's retrieval+ # must still find the model it admitted.+ cache.evict_unlocked_for_peer(lambda: False)+ assert "m" in cache._cached_models, "the admission was evicted out from under its loader"+ assert store.refcount("m") == 1+ retrieved, _claim = cache.get_with_first_use_claim("m")+ assert retrieved is record+ finally:+ cache.shutdown()+++def test_a_failed_admission_claim_leaves_the_admission_fully_accounted(mock_logger, monkeypatch):+ """The claim is armed only once put() has committed. A raise while arming must not leave a+ resident, store-owning record that the budget never counted: the record's eventual eviction+ would then debit bytes that were never added, and the debit is clamped to what this cache has+ tracked - so it lands on a different, still-resident model's charge, permanently."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ # keep_ram_copy=False -> not deduplicated, so each model is charged to the non-shared total.+ cache = _make_cache(store, budget, mock_logger, keep_ram_copy=False)++ def boom(*args, **kwargs):+ raise MemoryError("no room for the claim")++ try:+ cache.put("resident", DummyModule())+ one_model = budget.total_in_use()+ assert one_model > 0++ monkeypatch.setattr(model_cache_module, "FirstUseClaim", boom)+ with pytest.raises(MemoryError):+ cache.put("claimed", DummyModule(), claim_admission=True)+ monkeypatch.undo()++ assert "claimed" in cache._cached_models, "premise: the admission itself completed"+ assert budget.total_in_use() == 2 * one_model, "a resident admission went uncounted"++ # Evicting it debits only its own bytes; the other model's charge survives.+ cache._delete_cache_entry(cache._cached_models["claimed"])+ assert budget.total_in_use() == one_model+ finally:+ monkeypatch.undo()+ cache.shutdown()+++def test_shutdown_retains_a_mid_admission_record_after_a_worker_death_and_restart(mock_logger):+ """A worker death zeroes the admission's hold, and a replacement worker (started by any later+ retrieval or admission) must not affect the live admission claim that still owns the record."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]+ assert record.first_use_holds == 1 and not record.awaiting_first_use++ _kill_worker_abnormally(cache, record)+ assert record.first_use_holds == 0, "premise broken: the recovery did not zero the hold"++ # An unrelated admission restarts the worker - so shutdown() takes its live-worker path,+ # skipping the dead-worker recovery. The live claim remains the admission shield.+ cache.put("other", DummyModule())+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()+ assert not record.awaiting_first_use, "a claimed admission must not use the grace"++ cache.shutdown()+ assert cache._cached_models.get("m") is record, "shutdown() evicted a record mid-admission"+ assert record.is_stale+ assert store.refcount("m") == 1++ # The loader comes back and finds its own model, as it would have before any of this.+ retrieved, _claim = cache.get_with_first_use_claim("m")+ assert retrieved is record+ finally:+ cache.shutdown()+++def test_a_live_admission_survives_worker_hold_being_stripped(mock_logger):+ """With the worker-carried hold absent, the record is still shielded while its admission claim+ lives, and evicting it is only correct once that claim is gone."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]++ record.first_use_holds = 0 # as dead-worker recovery would leave it+ assert not record.awaiting_first_use, "claimed admissions must not carry unowned grace"+ assert record.in_first_use_window, "the live admission claim stopped shielding its record"++ cache.evict_unlocked_for_peer(lambda: False)+ assert "m" in cache._cached_models, "a peer eviction took the record out from under its loader"+ cache.shutdown()+ assert cache._cached_models.get("m") is record, "shutdown() evicted a record mid-admission"++ del admission_claim # the load ends; only now is the record nobody's+ gc.collect()+ assert _wait_until(lambda: "m" not in cache._cached_models), "the finished admission stayed resident"+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0++[email protected]("death_before_shutdown", [True, False], ids=["death-then-shutdown", "shutdown-then-death"])+def test_a_live_admission_claim_survives_a_worker_death_and_shutdown(mock_logger, death_before_shutdown):+ """A claim that is still alive means a load that is still between its put() and its+ retrieval, and the dead-worker recovery must leave it alone even on a shut-down cache.++ Unlike a hold, this shield cannot be traded for certainty: evicting the record does not fall+ back to the tolerated detached path, it fails the load with an IndexError from a retrieval+ that no longer finds its own model (JPPhoto review, 2026-09-04). Both orderings of the two+ recoveries are covered - shutdown() running the recovery because the worker is already dead,+ and the dying worker running it after shutdown() saw it alive."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]++ if death_before_shutdown:+ _kill_worker_abnormally(cache, record)+ cache.shutdown()+ else:+ cache.shutdown()+ _kill_worker_abnormally(cache, record)++ assert record.first_use_holds == 0, "premise broken: the recovery did not zero the hold"+ assert cache._cached_models.get("m") is record, "the admission was evicted out from under its running load"+ assert record.is_stale and record.admission_in_flight+ assert store.refcount("m") == 1+ assert budget.total_in_use() == S++ # The load carries on exactly as it would have: retrieves its record, hands the admission+ # claim over, wraps, uses, and the stale record is evicted by its own unlock().+ retrieved, first_use_claim = cache.get_with_first_use_claim("m")+ assert retrieved is record+ admission_claim.release()+ assert not record.admission_in_flight+ with LoadedModelWithoutConfig(cache_record=retrieved, cache=cache, first_use_claim=first_use_claim) as _model:+ pass+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0++[email protected]("replacement_starts", [False, True], ids=["no-worker", "replacement-worker"])+def test_a_claim_abandoned_after_shutdown_and_a_worker_death_is_reclaimed(mock_logger, monkeypatch, replacement_starts):+ """A shutdown cleanup worker reclaims a claim even when the normal worker died."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]+ _kill_worker_abnormally(cache, record)+ cache.shutdown()+ assert cache._cached_models.get("m") is record, "premise: retained for its live claim"++ # The load dies between its put() and its retrieval.+ del admission_claim+ assert _wait_until(lambda: "m" not in cache._cached_models)+ assert not record.admission_in_flight++ if not replacement_starts:+ _fail_deferred_worker_starts(monkeypatch)+ # The normal worker is independent of shutdown cleanup. A successful claimed admission+ # returns a claim; a refusal returns None.+ result = cache.put("next", DummyModule(), claim_admission=True)+ if replacement_starts:+ assert result is not None+ result.release()+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()+ else:+ assert result is None, "a worker-less post-shutdown admission was not refused"+ assert cache._deferred_work_thread is None+ assert _wait_until(lambda: "m" not in cache._cached_models), "an unowned stale record was never reclaimed"+ assert _wait_until(lambda: store.refcount("m") == 0)+ expected = S if replacement_starts else 0 # "next" is admitted only when a worker started+ assert _wait_until(lambda: budget.total_in_use() == expected)+ assert ("next" in cache._cached_models) is replacement_starts+ finally:+ monkeypatch.undo()+ cache.shutdown()+++def test_releasing_an_admission_claim_retires_its_shield(mock_logger):+ """The shield is the claim's liveness, so a spent claim must retire it explicitly: the loader+ releases at its retrieval, but the object itself lives on to the end of its frame - or for as+ long as a traceback holds that frame - and until then the record would stay invisible to every+ asynchronous eviction path."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]+ assert record.admission_in_flight++ # The loader retrieves, uses and releases the model; the claim object is still alive here.+ _use_and_release(cache, "m")+ admission_claim.release()+ assert not record.admission_in_flight, "a spent claim went on shielding its record"+ assert record.in_first_use_window is False++ cache.evict_unlocked_for_peer(lambda: False)+ assert "m" not in cache._cached_models, "a finished load's record stayed unreclaimable"+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+ finally:+ cache.shutdown()+++def test_a_failed_claim_construction_does_not_strand_its_hold(mock_logger, monkeypatch):+ """The hold is armed before the claim that owns its release exists. If constructing the claim+ raises - it allocates a weakref.finalize, and this cache runs at the RAM ceiling by design -+ the hold must be handed back: an orphaned hold shields its record from every eviction path,+ make_room, drop_model and shutdown's sweep included, for the life of the process."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ record = cache._cached_models["m"]++ def boom(*args, **kwargs):+ raise MemoryError("no room for the claim")++ monkeypatch.setattr(model_cache_module, "FirstUseClaim", boom)+ with pytest.raises(MemoryError):+ cache.get_with_first_use_claim("m")+ monkeypatch.undo()++ assert record.first_use_holds == 0, "a failed claim left its hold armed with no owner"+ cache.shutdown()+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_claim_shields_the_record_from_the_lookup_onward(mock_logger):+ """The first-use hold must be armed by the lookup itself, not by the wrapper's constructor+ (JPPhoto review, 2026-08-30). The stretch in between is not a few instructions - the+ configured loader retrieves its record inside _load_and_cache and then does the shared-store+ shell registration and two returns - and a shutdown landing there would evict the record its+ holder is about to lock, releasing shared-store ownership while the tensors live on, so a+ peer's reload of the key would mint a duplicate canonical copy the budget counts once."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache_a = _make_cache(store, budget, mock_logger)+ cache_b = _make_cache(store, budget, mock_logger)+ try:+ cache_a.put("m", DummyModule())+ _use_and_release(cache_a, "m") # warm: past the admission grace, unlocked++ # The retrieval a load is about to wrap; shutdown() lands before the wrapper exists.+ record, claim = cache_a.get_with_first_use_claim("m")+ assert claim is not None+ assert record.first_use_holds == 1, "the lookup did not arm the shield"+ canonical_before = store.peek("m")+ cache_a.shutdown()++ assert cache_a._cached_models.get("m") is record, "shutdown() evicted the record before its wrapper existed"+ assert record.is_stale+ assert store.refcount("m") == 1+ assert budget.total_in_use() == S++ # The wrapper is built late, adopts the claim, and locks a still-attached record.+ loaded_model = LoadedModelWithoutConfig(cache_record=record, cache=cache_a, first_use_claim=claim)+ with loaded_model as _model:+ assert cache_a._cached_models.get("m") is record, "locked a detached record"+ cache_b.put("m", DummyModule())+ _use_and_release(cache_b, "m")+ assert store.peek("m") is canonical_before, "peer reload minted a duplicate canonical"+ assert store.refcount("m") == 2+ assert budget.total_in_use() == S++ # Exiting the context is the record's last release: the shutdown's stale mark evicts it.+ assert "m" not in cache_a._cached_models+ assert store.refcount("m") == 1+ assert budget.total_in_use() == S+ finally:+ cache_b.shutdown()+++def test_an_unadopted_claim_releases_its_hold_when_dropped(mock_logger):+ """A claim is armed before any wrapper exists, so a load that raises in between must not leave+ the hold standing: dropping the claim is itself a complete release, and on a shut-down cache+ it evicts the record the sweep retained for it, with its accounting."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")++ record, claim = cache.get_with_first_use_claim("m")+ assert claim is not None and record.first_use_holds == 1++ cache.shutdown()+ assert cache._cached_models.get("m") is record, "shutdown() evicted the record out from under its claim"++ del claim # the load raised before it could build a wrapper+ gc.collect()+ assert _wait_until(lambda: "m" not in cache._cached_models), "a dropped claim stranded its record"+ assert record.first_use_holds == 0+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_a_spent_claim_cannot_consume_a_later_holders_hold(mock_logger):+ """A claim releases exactly once. Once its wrapper has locked, the claim is spent, so its+ later collection must not decrement a hold a different, still-live holder armed in the+ meantime - that would unshield the second holder's window and let shutdown() evict the record+ out from under it."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")++ record, claim_a = cache.get_with_first_use_claim("m")+ wrapper_a = LoadedModelWithoutConfig(cache_record=record, cache=cache, first_use_claim=claim_a)+ with wrapper_a as _model:+ pass+ assert record.first_use_holds == 0, "the first lock did not release the adopted claim"++ # Holder B arms a fresh hold on the same record.+ record_b, claim_b = cache.get_with_first_use_claim("m")+ assert record_b is record and record.first_use_holds == 1++ del wrapper_a, claim_a+ gc.collect()+ assert not _wait_until(lambda: record.first_use_holds == 0, timeout=0.5), "a spent claim consumed a later hold"++ cache.shutdown()+ assert cache._cached_models.get("m") is record, "shutdown() evicted the record out from under holder B"++ del claim_b+ gc.collect()+ assert _wait_until(lambda: "m" not in cache._cached_models), "holder B's claim did not release"+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_abandoned_holder_reaches_zero_after_shutdown(mock_logger):+ """A record retained by the shutdown sweep for a wrapper that is then dropped un-entered must+ still reach zero (JPPhoto review, 2026-08-13): no unlock() is ever coming, so the wrapper's+ abandonment finalizer - carried by the deferred worker, which therefore must outlive+ shutdown() - is the only event left that can evict the record and release its shared-store+ reference and budget bytes."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)++ cache.shutdown()+ assert "m" in cache._cached_models, "shutdown() evicted the record out from under its holder"++ del loaded_model+ gc.collect()+ assert _wait_until(lambda: "m" not in cache._cached_models), "the abandoned record was never evicted"+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_cold_admission_sweep_does_not_clear_wrapper_holds(mock_logger):+ """put()'s stale-grace sweep must not unshield a live wrapper: a node may retrieve several+ models and only then enter their contexts, so another model's cold admission (and its+ make-room) can land inside a warm wrapper's get()->lock() window. The hold - unlike the+ put()-set grace - survives the sweep, so a shutdown() after that admission still retains the+ record for its holder."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("first", DummyModule())+ _use_and_release(cache, "first")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("first"), cache=cache)+ record = loaded_model._cache_record+ assert record.first_use_holds == 1++ cache.put("second", DummyModule()) # sweeps stale grace flags; must leave holds alone+ assert record.first_use_holds == 1, "the cold admission cleared a live wrapper's hold"++ cache.shutdown()+ assert cache._cached_models.get("first") is record, "shutdown() evicted the held record"++ with loaded_model as _model:+ assert cache._cached_models.get("first") is record, "locked a detached record"+ assert "first" not in cache._cached_models+ assert store.refcount("first") == 0+++def test_post_shutdown_admission_is_evicted_after_its_use(mock_logger):+ """put() after shutdown() (reachable: Invoker.stop() stops model_manager before+ session_processor) missed the shutdown sweep, so the record is marked stale at admission -+ its final release evicts it instead of leaving it resident until process exit."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("early", DummyModule())+ _use_and_release(cache, "early")+ cache.shutdown()++ cache.put("late", DummyModule())+ assert cache._cached_models["late"].is_stale, "a post-shutdown admission must be stale at birth"+ _use_and_release(cache, "late")+ assert "late" not in cache._cached_models+ assert store.refcount("late") == 0+ assert budget.total_in_use() == 0+++def test_make_room_skips_held_records(mock_logger):+ """make_room (another model's cold load, or the keep-alive timeout's clear) must treat a+ record with a live first-use hold like a locked one: its wrapper is about to lock it, and+ evicting it would detach the record mid-window. Once the hold is consumed by the first lock,+ the record is ordinary evictable content again."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("held", DummyModule())+ _use_and_release(cache, "held")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("held"), cache=cache)++ cache.make_room(10**12)+ assert "held" in cache._cached_models, "make_room evicted a held record mid-window"++ with loaded_model as _model:+ pass+ cache.make_room(10**12)+ assert "held" not in cache._cached_models+ finally:+ cache.shutdown()+++def test_drop_model_defers_eviction_for_held_record(mock_logger):+ """drop_model() must defer a held record exactly as it defers a locked one: mark it stale and+ let the hold's release perform the eviction, instead of detaching the record from the holder+ about to lock it."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = loaded_model._cache_record++ dropped = cache.drop_model("m")+ assert dropped == 0, "drop_model evicted a held record instead of deferring"+ assert cache._cached_models.get("m") is record+ assert record.is_stale++ with loaded_model as _model:+ assert cache._cached_models.get("m") is record, "locked a detached record"+ assert "m" not in cache._cached_models+ assert budget.total_in_use() == 0+ finally:+ cache.shutdown()+++def test_unlock_stale_eviction_defers_to_live_holder(mock_logger):+ """The last unlock() of a stale record must not evict it while another wrapper still holds it+ for its own upcoming lock - that wrapper's own release performs the eviction instead."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ record = cache.get("m")+ cache.lock(record, None) # generation A is using the model+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache) # holder B++ cache.shutdown() # marks the locked record stale+ cache.unlock(record) # A finishes; B's hold defers the stale eviction+ assert cache._cached_models.get("m") is record, "unlock evicted a record another wrapper holds"++ with loaded_model as _model:+ assert cache._cached_models.get("m") is record, "locked a detached record"+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_worker_death_zeroes_stranded_first_use_holds(mock_logger):+ """A hold whose abandonment release was dispatched into a dead worker is dropped for good -+ finalizers fire once - so the next worker start must zero the surviving holds: the+ alternative is a record shielded from every eviction path for the life of the process."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = loaded_model._cache_record+ assert record.first_use_holds == 1++ # The worker dies (the way a raising log handler would kill it) ...+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ # ... and the wrapper's abandonment release is dispatched into the void.+ del loaded_model+ gc.collect()+ assert record.first_use_holds == 1, "the release was not dropped - dead-worker premise broken"++ # The next admission starts a replacement worker, which clears the stranded hold.+ cache.put("next", DummyModule())+ assert record.first_use_holds == 0, "a stranded hold survived the worker restart"+ finally:+ cache.shutdown()+++def test_stale_hold_release_cannot_steal_a_fresh_hold(mock_logger):+ """A release from before a dead-worker zeroing sweep must not decrement a hold armed after+ it: the zeroing bumps the record's hold epoch, and releases quote the epoch they were armed+ under. Without that, a surviving wrapper's late first-lock release would silently consume a+ different wrapper's fresh shield, and a shutdown() in that wrapper's window would evict the+ record out from under it - the exact defect the holds exist to prevent."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ wrapper_a = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = wrapper_a._cache_record+ assert record.first_use_holds == 1++ # The worker dies; the next admission zeroes the stranded hold and bumps the epoch.+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ cache.put("x", DummyModule())+ assert record.first_use_holds == 0++ # A fresh wrapper arms a new-epoch hold under the healthy replacement worker.+ wrapper_b = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ assert record.first_use_holds == 1++ # Wrapper A's late first-lock release quotes the old epoch: it must be a no-op.+ with wrapper_a as _model:+ pass+ assert record.first_use_holds == 1, "a stale release consumed the fresh wrapper's hold"++ # And shutdown() in wrapper B's window therefore still retains the record for it.+ cache.shutdown()+ assert cache._cached_models.get("m") is record, "shutdown() evicted the record out from under its holder"+ with wrapper_b as _model:+ assert cache._cached_models.get("m") is record, "locked a detached record"+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ finally:+ cache.shutdown()+++def test_stale_release_drained_after_worker_restart_is_rejected_by_epoch(mock_logger):+ """A release enqueued while the old worker was alive survives its death in the SimpleQueue+ (the queue is never cleared on restart) and is drained by the replacement worker AFTER+ dead-worker recovery zeroed the holds and bumped the epoch. The abandonment handler must+ reject it: the hold it quotes was already accounted for by the zeroing, so honoring it would+ consume a FRESH hold armed by a different wrapper under the healthy worker."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ record = cache.get("m")+ epoch_before = cache.register_first_use_hold(record) # wrapper A's hold+ assert epoch_before is not None and record.first_use_holds == 1++ # The worker dies; A's abandonment release is already sitting in the queue, undrained.+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)++ # The next admission runs recovery (zero + epoch bump) and starts the replacement worker.+ cache.put("x", DummyModule())+ assert record.first_use_holds == 0+ assert record.first_use_holds_epoch == epoch_before + 1++ # Wrapper B arms a fresh hold under the healthy worker.+ epoch_after = cache.register_first_use_hold(record)+ assert epoch_after == epoch_before + 1 and record.first_use_holds == 1++ # The replacement worker drains A's stale release (invoked directly here - it is exactly+ # what _run_deferred_work does with the surviving queue item): it must be a no-op.+ cache._release_abandoned_holder(record, True, epoch_before)+ assert record.first_use_holds == 1, "a stale queued release consumed the fresh wrapper's hold"++ # B's own release, quoting the current epoch, works normally.+ cache.release_first_use_hold(record, epoch_after)+ assert record.first_use_holds == 0+ finally:+ cache.shutdown()+++def test_shutdown_clears_holds_stranded_by_a_dead_worker(mock_logger):+ """shutdown() must run the dead-worker hold recovery itself: a hold whose abandonment+ release was dropped by the dead-thread dispatch check has no other releaser - no unlock() is+ coming for a never-locked holder, and after shutdown no put() is guaranteed to run the usual+ next-start recovery - so without this the sweep would stale-retain the record, its+ shared-store refcount and its budget bytes for the life of the process."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = loaded_model._cache_record+ assert record.first_use_holds == 1++ # The worker dies; the wrapper is dropped and its release is dispatched into the void.+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ del loaded_model+ gc.collect()+ assert record.first_use_holds == 1, "the release was not dropped - dead-worker premise broken"++ cache.shutdown()+ assert "m" not in cache._cached_models, "shutdown() stale-retained a record nothing can ever release"+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++class _WorkerKill(BaseException):+ """Deliberately not an ``Exception``: the deferred worker catches those per work item, so this+ escapes its loop the way an asynchronously raised BaseException - or a failure of the queue's+ own get() - would, i.e. the abnormal death the recovery path exists for."""+++def _kill_worker_abnormally(cache: ModelCache, record) -> threading.Thread:+ """Kill the deferred worker without the orderly _DEFERRED_STOP, and wait for it to unwind."""+ worker = cache._deferred_work_thread+ assert worker is not None and worker.is_alive()+ with patch.object(cache, "_release_abandoned_holder", side_effect=_WorkerKill):+ cache._deferred_work_queue.put(model_cache_module._AbandonedHolderRelease(weakref.ref(record), False, 0))+ worker.join(timeout=10)+ assert not worker.is_alive(), "the worker did not die"+ return worker++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_abandoned_claim_after_worker_death_leaves_admission_evictable(mock_logger):+ """A claimed admission that is abandoned after its deferred worker dies must leave an+ otherwise idle record evictable."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]++ _kill_worker_abnormally(cache, record)+ del admission_claim+ gc.collect()++ assert not record.awaiting_first_use+ cache.evict_unlocked_for_peer(lambda: False)+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+ finally:+ cache.shutdown()++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_abandoned_claim_after_shutdown_and_worker_death_is_reclaimed_without_later_operation(mock_logger):+ """A shutdown-retained admission claim must not depend on a later cache operation to evict it."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]++ # The replacement/recovery path must keep working after the original worker dies.+ _kill_worker_abnormally(cache, record)+ cache.shutdown()+ assert cache._cached_models.get("m") is record++ del admission_claim+ gc.collect()++ assert _wait_until(lambda: "m" not in cache._cached_models), (+ "a shutdown-retained abandoned claim leaked without a later cache operation"+ )+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+ finally:+ cache.shutdown()+++def test_shutdown_cleanup_start_failure_falls_back_to_a_live_normal_worker(mock_logger, monkeypatch):+ """A terminal-thread start failure must still use the live normal worker."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]+ real_thread_start = threading.Thread.start++ def fail_shutdown_worker_start(thread: threading.Thread) -> None:+ if thread.name == "model-cache-shutdown-deferred-work":+ raise RuntimeError("forced shutdown cleanup start failure")+ real_thread_start(thread)++ monkeypatch.setattr(threading.Thread, "start", fail_shutdown_worker_start)+ cache.shutdown()+ assert cache._shutdown_deferred_work_thread is None+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()++ del admission_claim+ assert _wait_until(lambda: "m" not in cache._cached_models)+ assert record.first_use_holds == 0+ assert store.refcount("m") == 0++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_make_room_keeps_live_claimed_admission_after_worker_death(mock_logger):+ """A live claimed admission remains protected from synchronous eviction after dead-worker+ recovery has removed the worker-carried hold."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ admission_claim = cache.put("m", DummyModule(), claim_admission=True)+ assert admission_claim is not None+ record = cache._cached_models["m"]++ _kill_worker_abnormally(cache, record)+ assert record.first_use_holds == 0+ assert record.admission_in_flight++ cache.make_room(10**12)+ assert cache._cached_models.get("m") is record++ admission_claim.release()+ finally:+ cache.shutdown()++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_stale_record_is_not_returned_after_dead_worker_recovery(mock_logger):+ """A stale record whose first-use wrapper was abandoned after worker death must not be+ returned by the next load after the worker is revived."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ record, first_use_claim = cache.get_with_first_use_claim("m")+ loaded_model = LoadedModelWithoutConfig(cache_record=record, cache=cache, first_use_claim=first_use_claim)+ cache.drop_model("m")++ _kill_worker_abnormally(cache, record)+ del loaded_model, first_use_claim+ gc.collect()++ with pytest.raises(IndexError):+ cache.get_with_first_use_claim("m")+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+ finally:+ cache.shutdown()+++def test_post_shutdown_admission_gets_no_first_use_grace(mock_logger):+ """put() after shutdown() must not arm the post-admission grace.++ The grace's backstop releaser is the sweep at the top of the NEXT put(), and after shutdown no+ further put() is guaranteed. A load cancelled between put() and the LoadedModel's construction+ leaves no wrapper, hence no finalizer either - so an armed flag would stand for the life of the+ process, hiding the record from every asynchronous eviction path while its bytes stay charged+ to the shared budget."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("early", DummyModule())+ _use_and_release(cache, "early")+ cache.shutdown()+ # The worker deliberately outlives shutdown(), so worker liveness is not what withholds the+ # grace here.+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()++ cache.put("late", DummyModule()) # ... and this load is cancelled before it ever calls get()+ record = cache._cached_models["late"]+ assert not record.awaiting_first_use, "a post-shutdown admission armed a grace nothing can release"+ assert not record.in_first_use_window++ # Unshielded, so the asynchronous paths can take the abandoned record back.+ assert cache.evict_unlocked_for_peer(lambda: False) == 1+ assert "late" not in cache._cached_models+ assert store.refcount("late") == 0+ assert budget.total_in_use() == 0++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_worker_death_after_shutdown_recovers_its_stranded_holds(mock_logger):+ """A worker that dies *after* shutdown()'s liveness check must run the recovery itself.++ shutdown() retains a record whose wrapper is still inside its get()->lock() window, counting on+ the worker to carry the wrapper's abandonment release. If the worker then dies, that release is+ dropped by the dead-thread dispatch check, no unlock() is coming for a never-locked holder, and+ a shut-down cache takes no further admission to run the next-start recovery - so the record,+ its shared-store reference and its budget bytes would be stranded for the life of the+ process."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = loaded_model._cache_record+ assert record.first_use_holds == 1++ # shutdown() sees a live worker, so it retains the held record for its holder.+ cache.shutdown()+ assert cache._cached_models.get("m") is record+ assert store.refcount("m") == 1++ _kill_worker_abnormally(cache, record)++ assert record.first_use_holds == 0, "the dying worker left its stranded hold standing"+ assert "m" not in cache._cached_models, "a record nothing can ever release stayed resident"+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+ assert cache._deferred_work_thread is None, "the dead worker was left in the slot as if healthy"++ # The surviving wrapper is still live; dropping it must not disturb the settled accounting.+ del loaded_model+ gc.collect()+ assert budget.total_in_use() == 0+++def test_dying_worker_recovery_leaves_a_replacement_workers_shields_alone(mock_logger):+ """The dying worker's recovery is scoped by identity: once a replacement has taken the slot,+ the shields standing are the replacement's, and _ensure_deferred_worker already cleared+ whatever the dead thread stranded. A late unwind must not zero them."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = loaded_model._cache_record+ assert record.first_use_holds == 1++ # A thread that is not the current worker reports its death.+ cache._recover_from_dead_worker(threading.current_thread())+ assert record.first_use_holds == 1, "an impostor's recovery zeroed the live worker's holds"+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()++ # And the hold still works: shutdown() retains the record for its holder.+ cache.shutdown()+ assert cache._cached_models.get("m") is record+ with loaded_model as _model:+ pass+ assert "m" not in cache._cached_models+ assert budget.total_in_use() == 0+ finally:+ cache.shutdown()++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_dying_worker_does_not_unshield_a_live_caches_fresh_admission(mock_logger):+ """A worker death must not turn into a failed load on a cache that is still running.++ The dying worker is `is_alive()` for as long as it unwinds, so a cold load landing in that+ window starts no replacement worker and is admitted with the ordinary post-admission grace.+ That grace's backstop is the sweep at the top of the NEXT put(), not the worker, and the+ loader has not even called get() yet - clearing it from the dying frame would leave the record+ exposed to a reconcile and the loader's get() raising IndexError."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("resident", DummyModule())+ record = _use_and_release(cache, "resident")+ worker = cache._deferred_work_thread+ assert worker is not None++ # Hold the worker inside its dying recovery so the admission below lands mid-unwind.+ entered = threading.Event()+ released = threading.Event()+ real_recover = cache._recover_from_dead_worker++ def gated(dying_worker):+ entered.set()+ assert released.wait(timeout=10)+ real_recover(dying_worker)++ with (+ patch.object(cache, "_release_abandoned_holder", side_effect=_WorkerKill),+ patch.object(cache, "_recover_from_dead_worker", side_effect=gated),+ ):+ cache._deferred_work_queue.put(model_cache_module._AbandonedHolderRelease(weakref.ref(record), False, 0))+ assert entered.wait(timeout=10), "the worker never reached its recovery"++ # A cold load lands while the worker is still alive-but-unwinding.+ assert worker.is_alive()+ cache.put("loading", DummyModule())+ admitted = cache._cached_models["loading"]+ assert admitted.awaiting_first_use, "premise broken: the admission was not graced"++ released.set()+ worker.join(timeout=10)++ assert admitted.awaiting_first_use, "the dying worker unshielded a load still between put() and get()"+ # The loader's get() therefore still finds its model.+ assert cache.get("loading") is admitted+ finally:+ cache.shutdown()+++def test_a_post_shutdown_admission_that_revives_the_worker_does_not_sweep_live_holders(mock_logger):+ """put()'s unowned-stale sweep is for the case where nothing is coming. When the admission's+ own worker revival succeeds, something IS coming - the replacement drains the kept+ abandonment releases, which are the only evidence of which holders are actually gone - and+ the holds the revival just zeroed make a live wrapper's record indistinguishable from an+ abandoned one. Sweeping there would release shared-store ownership of tensors a live wrapper+ still holds (the duplicate-canonical accounting lie), so the sweep must key on the worker+ being absent AFTER the revival attempt, not on shutdown alone."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ wrapper = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = wrapper._cache_record+ assert record.first_use_holds == 1++ cache.shutdown()+ assert cache._cached_models.get("m") is record and record.is_stale++ # The worker is lost without running its own recovery; the next admission finds it dead,+ # zeroes the hold, and starts a replacement.+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ cache.put("next", DummyModule())+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()+ assert record.first_use_holds == 0, "premise: the revival zeroed the live wrapper's hold"++ assert cache._cached_models.get("m") is record, "the sweep evicted a record a live wrapper still holds"+ assert store.refcount("m") == 1, "shared-store ownership was released while the tensors live on"++ # The wrapper's own use still settles the record.+ with wrapper as _model:+ pass+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+++def test_dead_worker_recovery_at_admission_keeps_a_retained_records_accounting(mock_logger):+ """The recovery run when an admission finds the worker dead must not evict a record whose+ tensors live wrappers still hold.++ Releasing store ownership while the weights live on is the accounting lie shutdown() itself+ refuses to make: the store stops counting bytes that are still resident, so a peer's reload of+ the key mints a duplicate canonical while the budget counts one. Lifting the stranded shield+ is enough - a replacement worker is started two lines later, and the ordinary eviction paths+ are all still reachable."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ wrapper_a = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = wrapper_a._cache_record++ # shutdown() retains the record for its holder ...+ cache.shutdown()+ assert cache._cached_models.get("m") is record++ # ... and the worker is then lost without running its own recovery (a fork, or a death this+ # admission races).+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)++ # A second wrapper's construction runs the dead-worker recovery from _ensure_deferred_worker.+ wrapper_b = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ assert cache._cached_models.get("m") is record, "the recovery detached a record wrappers still hold"+ assert store.refcount("m") == 1, "shared-store ownership was released while the tensors live on"+ assert budget.total_in_use() == S+ assert record.first_use_holds == 1, "the replacement worker's hold was not armed for wrapper B"++ # And the record still settles to zero once that holder is done with it.+ with wrapper_b as _model:+ pass+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+ del wrapper_a+++def test_shutdown_evicts_unclaimed_grace_after_live_recovery(mock_logger):+ """A live cache keeps unclaimed grace for its next put(); shutdown evicts it immediately."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ record = cache._cached_models["m"]+ assert record.awaiting_first_use++ cache._recover_stranded_shields()+ assert record.awaiting_first_use, "a live cache's grace was lifted before it lost its backstop"++ # shutdown() evicts the unclaimed record instead of stale-retaining its grace.+ cache.shutdown()+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ assert budget.total_in_use() == 0+++def test_queued_abandonment_release_does_not_pin_its_record(mock_logger):+ """A release sitting in the deferred queue must pin nothing.++ Such an item can outlive every chance to drain it: _dispatch_deferred's liveness gate is+ unsynchronized, so a finalizer that read the worker slot just before it was retired still+ enqueues against a thread that is alive only because it is unwinding, and on a shut-down cache+ nothing drains the queue again. A strong reference to the CacheRecord would hold that model's+ whole CPU state dict for the life of the process while the store and the budget both reported+ the bytes released."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("parked", DummyModule())+ parked = _use_and_release(cache, "parked")+ cache.put("m", DummyModule())+ record = _use_and_release(cache, "m")+ record_ref = weakref.ref(record)+ module_ref = weakref.ref(record.cached_model.model)++ # Park the worker on an earlier item so the release below stays queued behind it.+ entered = threading.Event()+ unblock = threading.Event()++ def park(*_args):+ entered.set()+ assert unblock.wait(timeout=10)++ with patch.object(cache, "_release_abandoned_holder", side_effect=park):+ cache._deferred_work_queue.put(model_cache_module._AbandonedHolderRelease(weakref.ref(parked), False, 0))+ assert entered.wait(timeout=10), "the worker never picked up the parking item"++ # The real dispatch path, with a worker that is alive but will never get to this item.+ cache.release_first_use_grace(record, held_first_use=True, hold_epoch=record.first_use_holds_epoch)+ assert cache._deferred_work_queue.qsize() == 1, "premise broken: the release was not queued"++ cache.shutdown()+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0++ # The accounting says those bytes are gone, so they must really be gone.+ del record+ assert _collect_until(lambda: record_ref() is None), "the queued release pinned the CacheRecord"+ assert module_ref() is None, "the evicted model is still resident in RAM"+ assert cache._deferred_work_queue.qsize() == 1, "premise broken: the item was drained after all"++ unblock.set()+++def test_post_shutdown_prefetch_admission_is_refused(mock_logger):+ """A prefetch admission into a shut-down cache must not be admitted at all.++ Prefetch means nothing will ever retrieve this record, so it has no releaser: no get() ->+ lock() -> unlock() to run the stale eviction, no wrapper whose finalizer could carry an+ abandonment release, and no claim to expire. Unlike an ordinary post-shutdown admission -- kept+ because its loader really is still coming for it -- there is nobody to keep it for, so+ admitting it would pin the model, its shared-store reference and its budget bytes until the+ process exits."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("early", DummyModule())+ _use_and_release(cache, "early")+ cache.shutdown()+ # The worker deliberately outlives shutdown(), so worker liveness is not what refuses this.+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()++ cache.put("late", DummyModule(), prefetch=True)+ assert "late" not in cache._cached_models, "a prefetch nothing can ever release was admitted"+ assert store.refcount("late") == 0+ assert budget.total_in_use() == 0++ # The refusal is scoped to prefetch: an ordinary admission is still kept for the loader that+ # is going to come back for it.+ cache.put("in_flight", DummyModule())+ assert "in_flight" in cache._cached_models++ # And the refusal comes *after* the worker revival, not instead of it: a post-shutdown+ # prefetch is still one of the events that restores the worker the shutdown-retained records+ # depend on for their abandonment releases.+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ cache._deferred_work_thread.join(timeout=10)+ assert not cache._deferred_work_thread.is_alive()+ cache.put("later", DummyModule(), prefetch=True)+ assert "later" not in cache._cached_models+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive(), (+ "a post-shutdown prefetch was refused before it could revive the worker"+ )++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_shutdown_lifts_a_grace_the_dying_worker_left_standing(mock_logger):+ """The dying worker deliberately leaves a live cache's admission grace alone - the sweep at the+ top of the next put() is still its backstop. shutdown() is where that backstop runs out, and it+ must lift the grace even though the dying worker retired the worker slot on its way out. Keying+ that lift on a dead thread still sitting in the slot would skip exactly the case the dying+ recovery handed to it, stranding the record, its shared-store reference and its budget bytes+ for the life of the process."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("resident", DummyModule())+ resident = _use_and_release(cache, "resident")++ # A load admitted and then cancelled before get(): no wrapper is ever built, so no finalizer+ # will ever exist to release this grace.+ cache.put("orphan", DummyModule())+ orphan = cache._cached_models["orphan"]+ assert orphan.awaiting_first_use++ _kill_worker_abnormally(cache, resident)+ assert cache._deferred_work_thread is None, "premise broken: the dying worker kept the slot"+ assert orphan.awaiting_first_use, "the grace was lifted while the next put() was still its backstop"++ cache.shutdown()+ assert "orphan" not in cache._cached_models, "shutdown() stale-retained a grace nothing can release"+ assert store.refcount("orphan") == 0+ assert budget.total_in_use() == 0++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_worker_start_retries_a_recovery_that_failed_partway(mock_logger):+ """A dying worker's recovery can itself fail - a logging handler that raises is one of the ways+ the worker dies in the first place - and it has already retired the worker slot by then. The+ next worker start must re-run the recovery rather than key on a dead thread still sitting in+ the slot, or the hold it never reached stays shielded for good."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = loaded_model._cache_record+ assert record.first_use_holds == 1++ with patch.object(cache, "_clear_stranded_first_use_holds", side_effect=RuntimeError("logging handler blew up")):+ _kill_worker_abnormally(cache, record)+ assert record.first_use_holds == 1, "premise broken: the recovery did not fail"+ assert cache._deferred_work_thread is None++ # The next worker start re-runs the recovery.+ cache.put("next", DummyModule())+ assert record.first_use_holds == 0, "a recovery that failed partway was never retried"++ # And with the hold gone, the record settles instead of being shielded for good.+ del loaded_model+ cache.shutdown()+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+++def test_failed_worker_recovery_does_not_fail_the_next_admission(mock_logger):+ """A transient recovery failure must leave the cache operation usable and retryable."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = loaded_model._cache_record+ assert record.first_use_holds == 1++ with patch.object(cache, "_clear_stranded_first_use_holds", side_effect=RuntimeError("transient failure")):+ _kill_worker_abnormally(cache, record)+ assert record.first_use_holds == 1++ # Deferred cleanup is best effort: a failed recovery must not fail an unrelated load.+ cache.put("next", DummyModule())++ assert cache._deferred_work_thread is None+ # A later admission retries recovery and starts the worker once the failure is gone.+ cache.put("after-retry", DummyModule())+ assert record.first_use_holds == 0+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()+ del loaded_model+ finally:+ cache.shutdown()++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_abandonment_release_survives_the_worker_that_should_have_carried_it(mock_logger):+ """A shutdown cleanup worker must reclaim a holder after the normal worker is gone."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = loaded_model._cache_record+ assert record.first_use_holds == 1++ # shutdown() retains the held record rather than evicting it out from under the live wrapper.+ cache.shutdown()+ assert cache._cached_models.get("m") is record and record.is_stale++ # The normal worker then dies without running its own recovery. The shutdown-specific worker+ # remains available for the wrapper's finalizer.+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ del loaded_model+ assert _wait_until(lambda: "m" not in cache._cached_models), (+ "the shutdown cleanup worker did not retire the abandoned record"+ )+ assert _wait_until(lambda: store.refcount("m") == 0)++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_a_kept_release_respects_a_hold_armed_under_the_replacement_worker(mock_logger):+ """The other half of the same rule: keeping the release must not become a licence to evict.++ A kept item is drained by a worker that started long after it was enqueued, so it must act on+ the record's evidence at drain time rather than on the state its holder left behind. Here a+ second wrapper arms a fresh hold in the very `register_first_use_hold` frame that starts the+ replacement worker -- so the drain cannot land between the recovery's zeroing and the new hold+ -- and the drained release must leave that record alone. Retiring it would release+ shared-store ownership while the tensors live on, which is the accounting lie that lets a+ peer's reload mint a duplicate canonical the budget counts once.++ What this does NOT claim is that a kept release protects every live holder. Once dead-worker+ recovery has zeroed the holds and no wrapper has re-armed one, a record whose holder is gone+ is indistinguishable from one a live wrapper is still holding, and the release evicts it --+ the same trade _evict_stale_unshielded_entries already makes on the abnormal-death path, and+ for the same reason: a permanently shielded record is worse than an unshielded one."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ _use_and_release(cache, "m")+ wrapper_a = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ record = wrapper_a._cache_record+ assert record.first_use_holds == 1++ cache.shutdown()+ assert cache._cached_models.get("m") is record and record.is_stale++ released = threading.Event()+ entered = threading.Event()+ unblock = threading.Event()+ real_release = cache._release_abandoned_holder++ def _park(cache_entry, held_first_use, hold_epoch):+ entered.set()+ assert unblock.wait(timeout=10)+ try:+ real_release(cache_entry, held_first_use, hold_epoch)+ finally:+ released.set()++ # The normal worker dies without recovery, but the shutdown worker receives A's finalizer. Park+ # it while a new wrapper arms a fresh hold; A's old epoch must not consume B's hold.+ with patch.object(cache, "_release_abandoned_holder", side_effect=_park):+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ del wrapper_a+ assert entered.wait(timeout=10), "the shutdown worker did not receive the abandonment"++ # register_first_use_hold is synchronized and starts the replacement normal worker itself,+ # so its recovery zeroes the old epoch before B's fresh hold is armed.+ wrapper_b = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ assert record.first_use_holds == 1, "premise broken: wrapper B never armed a hold"+ unblock.set()+ assert released.wait(timeout=10), "the shutdown worker never finished the old release"++ assert cache._cached_models.get("m") is record, "a record a live wrapper still holds was retired"+ assert store.refcount("m") == 1, "shared-store ownership was released while the tensors live on"++ # And it still settles once that holder is done with it.+ with wrapper_b as _model:+ pass+ assert _wait_until(lambda: "m" not in cache._cached_models)+ assert _wait_until(lambda: store.refcount("m") == 0)+++def test_a_refused_prefetch_does_not_retain_an_orphaned_grace(mock_logger):+ """Post-shutdown prefetch refusal leaves no earlier unclaimed admission resident."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=int(S * 1.4), shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ # A load cancelled between put() and get(): the grace stands with no wrapper to release it.+ cache.put("orphaned", DummyModule())+ assert cache._cached_models["orphaned"].awaiting_first_use++ cache.shutdown()+ # The worker is alive across shutdown(), but unclaimed grace is not a shutdown shield.+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()+ assert "orphaned" not in cache._cached_models+ assert store.refcount("orphaned") == 0++ cache.put("late", DummyModule(), prefetch=True)+ assert "late" not in cache._cached_models, "a prefetch nothing can ever release was admitted"+ assert budget.total_in_use() == 0+++def _fail_deferred_worker_starts(monkeypatch) -> None:+ """Make every attempt to start the model-cache deferred worker raise, the way thread/pid+ exhaustion (RLIMIT_NPROC, a container's pids.max) does."""+ real_thread_start = threading.Thread.start++ def fail_worker_start(thread: threading.Thread) -> None:+ if thread.name in {"model-cache-deferred-work", "model-cache-shutdown-deferred-work"}:+ raise RuntimeError("forced thread start failure")+ real_thread_start(thread)++ monkeypatch.setattr(threading.Thread, "start", fail_worker_start)+++def test_a_worker_less_post_shutdown_admission_is_refused(mock_logger, monkeypatch):+ """JPPhoto round-7 blocker: a claimed admission into a shut-down cache with no startable+ worker has no releaser - no worker to drain the eviction its finalizer queues, and no+ guaranteed future cache operation to stand in for one - so a load that dies before+ retrieving it pins the record, its store reference and its budget bytes for the life of the+ cache object. Every admission is now refused in that state (claimed, plain, and prefetch),+ so nothing that could be stranded is ever admitted. A load racing shutdown into a+ thread-exhausted process is failing regardless: its retrieval raises IndexError, exactly as+ a refused prefetch's would."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ _fail_deferred_worker_starts(monkeypatch)+ cache.shutdown()+ assert cache._deferred_work_thread is None++ assert cache.put("claimed", DummyModule(), claim_admission=True) is None+ assert cache.put("plain", DummyModule()) is None+ assert cache.put("prefetch", DummyModule(), prefetch=True) is None+ assert cache._cached_models == {}, "an admission was accepted that nothing could release"+ assert budget.total_in_use() == 0++ # The loader-style flow fails cleanly rather than corrupting state: put() returns None,+ # and the retrieval that follows raises IndexError as it would for any missing key.+ assert cache.put("m", DummyModule(), claim_admission=True) is None+ with pytest.raises(IndexError):+ cache.get_with_first_use_claim("m")+ assert "m" not in cache._cached_models+ assert budget.total_in_use() == 0++ # The refusal is scoped to a DEAD worker: while the worker shutdown() kept is alive, the+ # graceful path still admits and later cleans up (test_shutdown_retains_*), so this only+ # ever fires under thread exhaustion.+ finally:+ monkeypatch.undo()+ cache.shutdown()+++def test_shutdown_cleanup_survives_an_orderly_normal_worker_stop(mock_logger, monkeypatch):+ """Shutdown cleanup must reclaim a wrapper after the normal worker is stopped."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ record = _use_and_release(cache, "m")+ wrapper = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ assert record.first_use_holds == 1+ cache.shutdown() # worker alive -> m retained for its live wrapper+ assert cache._cached_models.get("m") is record and record.is_stale++ # Worker exits WITHOUT running its own recovery (an orderly stop models a fork / raced+ # death: the slot still holds the now-dead thread, and the holds are NOT zeroed).+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ del wrapper+ assert _wait_until(lambda: "m" not in cache._cached_models)+ assert record.first_use_holds == 0, "the terminal worker did not release the abandoned hold"++ # A later admission still refuses cleanly when the normal worker cannot be restarted.+ _fail_deferred_worker_starts(monkeypatch)+ assert cache.put("next", DummyModule(), claim_admission=True) is None+ assert "next" not in cache._cached_models+ assert budget.total_in_use() == 0+ finally:+ monkeypatch.undo()+ cache.shutdown()+++def test_grace_only_abandonments_do_not_grow_the_queue_while_no_worker_runs(mock_logger, monkeypatch):+ """JPPhoto's round-6 blocker: a record whose put()-set grace still stands, retrieved warm+ and dropped un-entered over and over while no worker can be started, enqueued one kept item+ per drop - the grace was only ever cleared by the worker, so nothing stopped them coming.+ The grace is now cleared by the abandonment itself, lock-free, and a non-stale record then+ owes the queue nothing."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ record = cache._cached_models["m"]+ assert record.awaiting_first_use+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ _fail_deferred_worker_starts(monkeypatch)++ for _ in range(20):+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)+ del loaded_model+ gc.collect()+ assert cache._deferred_work_queue.qsize() == 0, "grace-only abandonments accumulated in the queue"+ assert not record.awaiting_first_use, "the grace outlived the wrapper that was dropped under it"+ assert "m" in cache._cached_models+ finally:+ monkeypatch.undo()+ cache.shutdown()+++def test_stale_record_abandonments_are_coalesced_to_one_queued_item(mock_logger, monkeypatch):+ """The stale half of the same bound: a stale record's abandonment does owe the queue an+ eviction (it needs the lock), but one queued eviction is as good as any number. Repeated+ hold-less drops while no worker runs must leave a single item, and a restarted cleanup worker+ that drains it must re-arm the gate so a later abandonment can queue again."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("m", DummyModule())+ record = _use_and_release(cache, "m")+ cache.lock(record, None) # in use across shutdown, so it is stale-retained+ cache.shutdown()+ assert record.is_stale+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ cache._ensure_shutdown_deferred_worker()+ cache._shutdown_deferred_work_queue.put(model_cache_module._SHUTDOWN_DEFERRED_STOP)+ assert cache._shutdown_deferred_work_thread is not None+ cache._shutdown_deferred_work_thread.join(timeout=10)+ _fail_deferred_worker_starts(monkeypatch)++ for _ in range(20):+ _record, claim = cache.get_with_first_use_claim("m")+ del claim+ gc.collect()+ assert cache._shutdown_deferred_work_queue.qsize() == 1, "stale-record abandonments were not coalesced"+ assert record.abandonment_release_pending++ # Drained by a replacement worker: the record is still locked, so it survives, and the+ # gate is re-armed so the next abandonment reaches the handler again.+ monkeypatch.undo()+ with patch.object(cache, "_release_abandoned_holder", wraps=cache._release_abandoned_holder) as handler:+ cache.put("next", DummyModule())+ cache._ensure_shutdown_deferred_worker()+ assert _wait_until(lambda: handler.call_count == 1)+ assert _wait_until(lambda: not record.abandonment_release_pending), "the drain left the gate closed"+ assert cache._cached_models.get("m") is record+ _record, claim = cache.get_with_first_use_claim("m")+ del claim+ gc.collect()+ assert _wait_until(lambda: handler.call_count == 2), "the gate stayed closed after the drain"+ assert _wait_until(lambda: not record.abandonment_release_pending)++ cache.unlock(record)+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+ finally:+ monkeypatch.undo()+ cache.shutdown()+++def test_shutdown_marks_stale_before_a_racing_hold_less_abandonment_decides(mock_logger, monkeypatch):+ """Adversarial finding on the lock-free grace release: shutdown() used to read a record's+ shield and mark it stale in two steps. A hold-less holder dropped between them clears the+ grace lock-free, reads the record as not stale, and queues nothing; the mark then retains a+ record with no lock, no shield, no queued item and a live worker that will never be asked+ to evict it. shutdown() now marks first, so the finalizer either sees the mark and queues+ the eviction, or has already cleared its shield by the time shutdown() looks.++ The interleaving is forced by dropping the holder from inside the shield read shutdown()+ performs - a finalizer can fire on any thread at any decref, and running it on the shutdown+ thread between its read and its write is the same ordering."""+ from invokeai.backend.model_manager.load.model_cache.cache_record import CacheRecord++ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ # An unrelated warm record, so a later warm get can revive the worker WITHOUT put()'s+ # grace sweep.+ cache.put("other", DummyModule())+ _use_and_release(cache, "other")+ cache.put("m", DummyModule())+ record = cache._cached_models["m"]+ assert record.awaiting_first_use++ # Worker lost, restarts failing: a holder retrieves the graced record hold-less.+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)+ assert cache._deferred_work_thread is not None+ cache._deferred_work_thread.join(timeout=10)+ _fail_deferred_worker_starts(monkeypatch)+ holder = [LoadedModelWithoutConfig(cache_record=cache.get("m"), cache=cache)]+ assert holder[0]._first_use_hold_epoch is None and holder[0]._first_use_finalizer is not None++ # Threads start again; a warm get elsewhere revives the worker, leaving m's grace standing.+ monkeypatch.undo()+ _record, other_claim = cache.get_with_first_use_claim("other")+ other_claim.release()+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()+ assert record.awaiting_first_use, "premise: no put() ran, so the grace still stands"++ real_window = CacheRecord.in_first_use_window++ def window_then_drop_holder(self):+ value = real_window.fget(self)+ if self is record and holder:+ holder.clear()+ gc.collect()+ return value++ with patch.object(CacheRecord, "in_first_use_window", property(window_then_drop_holder)):+ cache.shutdown()++ assert _wait_until(lambda: "m" not in cache._cached_models), (+ "a record left stale, unshielded and unqueued by a racing abandonment was never evicted"+ )+ assert _wait_until(lambda: store.refcount("m") == 0)+ assert _wait_until(lambda: budget.total_in_use() == 0)+ finally:+ monkeypatch.undo()+ cache.shutdown()++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")[email protected]("handler_failure", [_WorkerKill, RuntimeError], ids=["worker-dies", "worker-survives"])+def test_a_lost_in_flight_item_reopens_the_coalescing_gate(mock_logger, handler_failure):+ """The coalescing gate is closed by the abandonment that queues the item and must be opened+ the moment the cleanup worker dequeues it - not by the handler, which a raise skips. Otherwise+ every later hold-less abandonment of the record is swallowed and the record can never be+ reclaimed through the queue again. Both handler failure classes are covered, and the cleanup+ worker must survive them."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ cache.put("m", DummyModule())+ record = _use_and_release(cache, "m")+ cache.lock(record, None) # in use across shutdown, so it is stale-retained+ cache.shutdown()+ assert record.is_stale++ # A hold-less abandonment (the retrieval claim of a warm get) closes the gate and queues the+ # item; the shutdown worker fails while draining it. It must survive even a BaseException from+ # the handler because no later cache operation is guaranteed.+ handled = threading.Event()++ def failing_handler(*args, **kwargs):+ handled.set()+ raise handler_failure()++ with patch.object(cache, "_release_abandoned_holder", side_effect=failing_handler):+ with patch.object(cache, "register_first_use_hold", return_value=None):+ _record, claim = cache.get_with_first_use_claim("m")+ worker = cache._shutdown_deferred_work_thread+ assert worker is not None and worker.is_alive()+ assert claim is not None and claim._hold_epoch is None+ del claim+ gc.collect()+ assert handled.wait(timeout=10), "premise: the item never reached the handler"+ assert _wait_until(lambda: cache._shutdown_deferred_work_queue.qsize() == 0)+ assert worker.is_alive(), "shutdown cleanup must survive handler failures"+ assert cache._shutdown_deferred_work_queue.qsize() == 0, "premise: the item was dequeued, i.e. lost"+ assert _wait_until(lambda: not record.abandonment_release_pending), "a lost item left the gate closed"++ # The normal worker and the shutdown worker remain independent; a later hold-less abandonment+ # still reaches the shutdown worker.+ cache.put("next", DummyModule())+ assert cache._deferred_work_thread is not None and cache._deferred_work_thread.is_alive()+ with patch.object(cache, "_release_abandoned_holder", wraps=cache._release_abandoned_holder) as handler:+ with patch.object(cache, "register_first_use_hold", return_value=None):+ _record, claim = cache.get_with_first_use_claim("m")+ del claim+ gc.collect()+ assert _wait_until(lambda: handler.call_count == 1), "the abandonment was swallowed by a closed gate"+ cache.unlock(record)+ assert "m" not in cache._cached_models+ assert store.refcount("m") == 0+++def test_hold_recovery_unshields_every_record_before_reporting_any(mock_logger):+ """A logging handler that raises is one of the ways the deferred worker dies in the first+ place, so the recovery must unshield every record before it reports any of them. Logging inside+ the loop would let that same handler abort the sweep partway, leaving the records it never+ reached shielded with nothing left to unshield them."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ wrappers = []+ for key in ("a", "b"):+ cache.put(key, DummyModule())+ _use_and_release(cache, key)+ wrappers.append(LoadedModelWithoutConfig(cache_record=cache.get(key), cache=cache))+ assert all(w._cache_record.first_use_holds == 1 for w in wrappers)++ raising_logger = MagicMock()+ raising_logger.getEffectiveLevel.return_value = logging.INFO+ raising_logger.warning.side_effect = RuntimeError("logging handler blew up")+ with patch.object(cache, "_logger", raising_logger):+ with pytest.raises(RuntimeError):+ cache._clear_stranded_first_use_holds()++ assert [w._cache_record.first_use_holds for w in wrappers] == [0, 0], (+ "a raising log handler aborted the sweep partway, leaving a record shielded for good"+ )+ finally:+ cache.shutdown()++def test_dropped_cache_releases_shared_weights_on_collection(mock_logger):"""A cache dropped without shutdown() must not strand its shared-weights references:- the store's refcount and bytes — and therefore the budget total — must return to zero once the+ the store's refcount and bytes - and therefore the budget total - must return to zero once thecache is collected."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=10**12, shared_store=store)@@ -138,6 +2112,34 @@ def test_dropped_cache_releases_shared_weights_on_collection(mock_logger):assert budget.total_in_use() == 0[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_dead_worker_still_evicts_after_recovery_failure(mock_logger):+ """A failed shield recovery must not skip the shutdown stale-record sweep."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**12, shared_store=store)+ cache = _make_cache(store, budget, mock_logger)+ try:+ cache.put("orphan", DummyModule())+ _use_and_release(cache, "orphan")+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("orphan"), cache=cache)+ record = loaded_model._cache_record+ assert record.first_use_holds == 1++ # shutdown() retains the record because its admission grace is still active. The worker+ # then dies, and the recovery warning is made to fail after the slot is retired.+ cache.shutdown()+ mock_logger.log.side_effect = RuntimeError("logging handler blew up")+ with patch.object(cache, "_clear_stranded_first_use_holds", wraps=cache._clear_stranded_first_use_holds):+ _kill_worker_abnormally(cache, record)++ assert "orphan" not in cache._cached_models, "recovery failure skipped stale eviction"+ assert store.refcount("orphan") == 0+ assert budget.total_in_use() == 0+ del loaded_model+ finally:+ cache.shutdown()++def test_collection_release_is_deferred_not_taken_under_the_store_lock(mock_logger):"""The collection-time release must only ENQUEUE: it runs in GC context, where taking thestore's non-reentrant lock (e.g. while another frame on the same thread is inside acquire())@@ -162,7 +2164,7 @@ def test_collection_release_is_deferred_not_taken_under_the_store_lock(mock_loggdef test_normal_eviction_and_collection_release_exactly_once(mock_logger):"""An entry evicted through _delete_cache_entry (which calls release_shared_weights) must not- be released AGAIN when its wrapper is later collected — the second device's reference would be+ be released AGAIN when its wrapper is later collected - the second device's reference would befreed out from under it."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=10**12, shared_store=store)@@ -279,7 +2281,7 @@ def test_model_in_ram_pins_warm_non_shared_model_against_peer_eviction(mock_loggdef test_model_in_ram_on_a_cold_record_ends_the_grace_and_detaches_the_finalizer(mock_logger):"""A pin on a never-locked record must clear awaiting_first_use and detach the first-use- finalizer — otherwise the warm-path-only coverage leaves both lines of lock_in_ram dead code."""+ finalizer - otherwise the warm-path-only coverage leaves both lines of lock_in_ram dead code."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=10**12, shared_store=store)cache = _make_cache(store, budget, mock_logger, keep_ram_copy=False)@@ -294,9 +2296,11 @@ def test_model_in_ram_on_a_cold_record_ends_the_grace_and_detaches_the_finalizerwith loaded_model.model_in_ram():assert record.is_lockedassert not record.awaiting_first_use- # The grace has been consumed by the pin; the finalizer must be detached so a later GC- # of the handle does not queue a redundant grace release.- assert not loaded_model._first_use_finalizer.alive+ # The grace has been consumed by the pin; the finalizer must be dropped (and the+ # wrapper's first-use hold released) so a later GC of the handle does not queue a+ # redundant release.+ assert loaded_model._first_use_finalizer is None+ assert record.first_use_holds == 0assert not record.is_locked# Post-pin, the record is ordinary evictable cache content.@@ -308,7 +2312,7 @@ def test_model_in_ram_on_a_cold_record_ends_the_grace_and_detaches_the_finalizerdef test_keep_alive_timer_start_failure_does_not_leak_a_pin(mock_logger, monkeypatch):"""Timer.start() raising (thread/pid exhaustion) inside @record_activity must not propagate:lock_in_ram has already incremented the lock count, and the caller's unlock-pairing try block- in model_in_ram() has not been entered yet — an exception here would pin the record forever."""+ in model_in_ram() has not been entered yet - an exception here would pin the record forever."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=10**12, shared_store=store)cache = _make_cache(store, budget, mock_logger, keep_ram_copy=False)@@ -339,7 +2343,7 @@ def test_keep_alive_timer_start_failure_does_not_leak_a_pin(mock_logger, monkeypdef test_reconcile_hook_failure_does_not_leak_a_pin(mock_logger, monkeypatch):"""The synchronized-decorator's post-release reconcile runs inside the caller's frame after the- method body — a raise there (e.g. TorchDevice.empty_cache on a sick CUDA context) escapes+ method body - a raise there (e.g. TorchDevice.empty_cache on a sick CUDA context) escapeslock_in_ram() after the lock count was incremented, before model_in_ram()'s unlock-pairing tryblock. It must be swallowed and logged; the pending flag persists so the next release retries."""store = SharedCpuWeightsStore()@@ -520,7 +2524,7 @@ def test_headroom_clamps_summed_multi_gpu_budget():def test_cache_stats_reflect_shared_global_budget(mock_logger):"""Two distinct caches attached to the same RamBudget report system-wide stats: each cache'scache_size is the SAME single global limit, and each high_watermark observes the SAME global- usage. An aggregator must therefore take the max of these fields — summing them would report+ usage. An aggregator must therefore take the max of these fields - summing them would reportan N-GPU system's capacity and high-water usage N times too large."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=int(S * 10), shared_store=store)@@ -538,7 +2542,7 @@ def test_cache_stats_reflect_shared_global_budget(mock_logger):cache_a.get("m")cache_b.get("m")# Both watermarks sample the same deduplicated global usage (S, counted once), so the true- # system high watermark is their max — not their sum.+ # system high watermark is their max - not their sum.assert cache_a.stats.high_watermark == Sassert cache_b.stats.high_watermark == Sfinally:@@ -558,7 +2562,7 @@ def test_eviction_coordinates_across_device_caches(mock_logger):try:cache_a.put("shared", DummyModule())cache_b.put("shared", DummyModule()) # both devices hold "shared" (refcount 2, counted once)- # Mirror production: each model is retrieved and locked for use, then released — the+ # Mirror production: each model is retrieved and locked for use, then released - the# lock() clears the post-admission grace, leaving the entries as evictable idle residents._use_and_release(cache_a, "shared")_use_and_release(cache_b, "shared")@@ -566,7 +2570,7 @@ def test_eviction_coordinates_across_device_caches(mock_logger):cache_a.put("new", DummyModule()) # triggers make_room; "shared" is a's only droppable entry# a dropped its ref to "shared"; that alone frees nothing (b still held it), so make_room- # asks b — idle, entry unlocked — to drop its reference too, releasing the shared weights.+ # asks b - idle, entry unlocked - to drop its reference too, releasing the shared weights.assert "shared" not in cache_a._cached_modelsassert "shared" not in cache_b._cached_modelsassert store.refcount("shared") == 0@@ -581,7 +2585,7 @@ def test_eviction_coordinates_across_device_caches(mock_logger):def test_contended_peer_reconciles_budget_after_its_operation_completes(mock_logger):"""A peer whose cache lock is held at the moment of a cross-cache eviction request must notleave the budget exceeded indefinitely: the request is recorded on the busy peer, and the- peer sheds its unlocked entries as soon as its current (lock-holding) operation completes —+ peer sheds its unlocked entries as soon as its current (lock-holding) operation completes -in production every operation releases the lock through the synchronized-decorator reconcilehook, which the holder thread emulates here. No other cache access may be needed to triggerthe reconcile (JPPhoto merge blocker, 2026-07-22)."""@@ -594,7 +2598,7 @@ def test_contended_peer_reconciles_budget_after_its_operation_completes(mock_logtry:cache_a.put("shared", DummyModule())cache_b.put("shared", DummyModule())- # Mirror production: each model is used and released — the lock() clears the+ # Mirror production: each model is used and released - the lock() clears the# post-admission grace, leaving b's entry an evictable idle resident._use_and_release(cache_a, "shared")_use_and_release(cache_b, "shared")@@ -619,7 +2623,7 @@ def test_contended_peer_reconciles_budget_after_its_operation_completes(mock_logcache_a.put("new", DummyModule())# b was busy: its unlocked "shared" entry could not be dropped, so the budget is- # transiently exceeded — but the reconcile request has been recorded on b.+ # transiently exceeded - but the reconcile request has been recorded on b.assert "shared" in cache_b._cached_modelsassert budget.total_in_use() == 2 * S@@ -639,7 +2643,7 @@ def test_contended_peer_reconciles_budget_after_its_operation_completes(mock_logdef test_reconcile_request_after_peer_finished_operation_is_not_lost(mock_logger):"""Lost-wakeup regression: the peer's busy operation can release its lock and run its- (no-op — flag not yet set) reconcile hook BEFORE the requester records the reconcile+ (no-op - flag not yet set) reconcile hook BEFORE the requester records the reconcilerequest. If the peer then stays idle, no future lock release exists to honor the request,so request_budget_reconcile must attempt the reconcile inline. The interleaving is forcedby delaying the request until the peer's operation has fully finished, and the budget must@@ -654,7 +2658,7 @@ def test_reconcile_request_after_peer_finished_operation_is_not_lost(mock_loggertry:cache_a.put("shared", DummyModule())cache_b.put("shared", DummyModule())- # Mirror production: each model is used and released — the lock() clears the+ # Mirror production: each model is used and released - the lock() clears the# post-admission grace, leaving b's entry an evictable idle resident._use_and_release(cache_a, "shared")_use_and_release(cache_b, "shared")@@ -665,7 +2669,7 @@ def test_reconcile_request_after_peer_finished_operation_is_not_lost(mock_loggerdef hold_lock() -> None:# b's "busy operation": holds the lock (so evict_unlocked_for_peer fails), then- # releases and runs the synchronized-decorator hook — with the request flag still+ # releases and runs the synchronized-decorator hook - with the request flag still# unset, a no-op. After this thread finishes, b is idle forever.with cache_b._lock:holding.set()@@ -677,7 +2681,7 @@ def test_reconcile_request_after_peer_finished_operation_is_not_lost(mock_loggerassert holding.wait(timeout=10)# Delay the reconcile request until b's operation has completely finished (lock- # released, hook run, thread dead) — the exact window in which a flag-only request+ # released, hook run, thread dead) - the exact window in which a flag-only request# would be lost.original_request = cache_b.request_budget_reconcile@@ -732,7 +2736,7 @@ def test_manual_release_in_cached_model_keys_honors_pending_reconcile(mock_loggearriving while it holds the lock is stranded: the requester's inline attempt fails on thecontended lock, the manual release runs no hook, and an idle cache leaves the budget exceededindefinitely (JPPhoto review, 2026-07-27). The release hands the work to a background- reconcile thread (it must not stall this method — see+ reconcile thread (it must not stall this method - seetest_cached_model_keys_returns_without_waiting_for_reconcile_work), so the outcome isawaited with a deadline."""store = SharedCpuWeightsStore()@@ -778,7 +2782,7 @@ def test_manual_release_in_cached_model_keys_honors_pending_reconcile(mock_loggeassert not holder.is_alive()# cached_model_keys' release handed the pending request to a background reconcile- # thread — no other cache access needed, only time.+ # thread - no other cache access needed, only time.assert _wait_until(lambda: "shared" not in cache_b._cached_models)assert store.refcount("shared") == 0assert budget.total_in_use() == S@@ -840,7 +2844,7 @@ def test_reconcile_clear_does_not_wipe_concurrent_request(mock_logger):"""The satisfied-path clear() in _reconcile_budget_if_pending races a concurrent requester:a peer counts its admission (driving the budget negative) and sets the flag just before theclear lands, then its own inline attempt observes the just-wiped flag and returns. The- reconciler must detect the wiped request — the budget is negative again after its clear —+ reconciler must detect the wiped request - the budget is negative again after its clear -restore the flag, and keep reconciling (JPPhoto review, 2026-07-27)."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=int(S * 1.4), shared_store=store)@@ -853,7 +2857,7 @@ def test_reconcile_clear_does_not_wipe_concurrent_request(mock_logger):fired = [False]class RacingEvent(threading.Event):- """On the first clear(): a peer admission lands and sets the flag — which this+ """On the first clear(): a peer admission lands and sets the flag - which thisclear then wipes. That is exactly the interleaving under test."""def clear(self) -> None:@@ -867,7 +2871,7 @@ def test_reconcile_clear_does_not_wipe_concurrent_request(mock_logger):cache_b._budget_reconcile_pending.set() # a previously recorded, now-satisfied request# A lock release runs the reconcile hook: it sees the budget satisfied and clears the- # flag — colliding with the racing request. (The requester's inline attempt is emulated+ # flag - colliding with the racing request. (The requester's inline attempt is emulated# by the no-op it becomes once it observes the wiped flag.)cache_b._reconcile_budget_if_pending()@@ -937,7 +2941,7 @@ def test_admitting_cache_reconciles_its_own_overshoot_after_unlock(mock_logger):assert budget.total_in_use() == 2 * Scache_a.unlock(record)- # unlock()'s release hook processes this cache's own pending request — no peer action,+ # unlock()'s release hook processes this cache's own pending request - no peer action,# no further model load.assert "locked_model" not in cache_a._cached_modelsassert "new" in cache_a._cached_models@@ -950,7 +2954,7 @@ def test_admitting_cache_reconciles_its_own_overshoot_after_unlock(mock_logger):def test_pending_reconcile_cannot_evict_just_admitted_model_before_first_use(mock_logger):"""A reconcile request pending while put() runs (a peer's request that found this cache- busy) is processed by put()'s own release hook — before the loader can call get(). The hook+ busy) is processed by put()'s own release hook - before the loader can call get(). The hookmust never evict the model that was just admitted: the loader retrieves it via get()immediately after put() returns (load_default.py), and evicting it first would break thein-flight load with an IndexError. The post-admission grace (CacheRecord.awaiting_first_use)@@ -968,7 +2972,7 @@ def test_pending_reconcile_cannot_evict_just_admitted_model_before_first_use(moccache_a._budget_reconcile_pending.set()# Overshoots the budget with "new" as the only unlocked entry. put()'s release hook- # processes the pending request before put() returns — it must skip the just-admitted+ # processes the pending request before put() returns - it must skip the just-admitted# model.cache_a.put("new", DummyModule())assert "new" in cache_a._cached_models@@ -982,7 +2986,7 @@ def test_pending_reconcile_cannot_evict_just_admitted_model_before_first_use(mocdef test_pending_reconcile_cannot_evict_model_between_get_and_lock(mock_logger):"""The admission grace must survive get(): get() is synchronized, so its own lock-release- hook can run a pending reconcile before returning to the caller — if the grace ended inside+ hook can run a pending reconcile before returning to the caller - if the grace ended insideget(), the hook would evict the very record the call just selected, detaching a live modelfrom the cache and its RAM accounting and forcing a reload on the next request. The recordmust stay cached from put() through get() and the subsequent lock() (JPPhoto review,@@ -1001,7 +3005,7 @@ def test_pending_reconcile_cannot_evict_model_between_get_and_lock(mock_logger):cache_a.put("new", DummyModule()) # budget exceeded; "new" is the only unlocked entrynew_record = cache_a.get("new")- # get()'s own release hook ran the pending reconcile — it must not have evicted the+ # get()'s own release hook ran the pending reconcile - it must not have evicted the# record it just returned.assert "new" in cache_a._cached_modelscache_a.lock(new_record, None)@@ -1080,7 +3084,7 @@ def test_abandoned_loaded_model_releases_first_use_grace(mock_logger):# Dropping the never-locked wrapper is the only subsequent cache-A lifecycle event. The# release is handed to a background thread (the finalizer must not do locking work on the- # collecting thread — see ModelCache.release_first_use_grace), so poll for the outcome.+ # collecting thread - see ModelCache.release_first_use_grace), so poll for the outcome.del loaded_modelgc.collect()@@ -1139,16 +3143,36 @@ def test_deferred_worker_start_failure_does_not_fail_the_admission(mock_logger,cache.shutdown()-def test_shutdown_stops_deferred_worker(mock_logger):+def test_deferred_worker_survives_shutdown_and_exits_on_collection(mock_logger):+ """shutdown() must NOT stop the deferred worker: a record the shutdown sweep retained because+ a live LoadedModel wrapper had not locked it yet has no future unlock() if that wrapper is+ simply dropped - the wrapper's abandonment release is carried by the shutdown cleanup worker.+ Both workers exit when the cache itself is collected (via their finalizers), not before."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=int(S * 1.4), shared_store=store)cache = _make_cache(store, budget, mock_logger)cache.put("model", DummyModule())+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("model"), cache=cache)cache.shutdown()- cache._deferred_work_thread.join(timeout=10)+ worker = cache._deferred_work_thread+ shutdown_worker = cache._shutdown_deferred_work_thread+ assert worker is not None+ # join() with a timeout rather than a bare is_alive() check: a worker that shutdown() told to+ # stop may not have consumed the sentinel yet, and a racy alive-reading would pass anyway.+ worker.join(timeout=2)+ assert worker.is_alive(), "shutdown() stopped the deferred worker"+ assert shutdown_worker is not None and shutdown_worker.is_alive()- assert not cache._deferred_work_thread.is_alive()+ del loaded_model++ cache_ref = weakref.ref(cache)+ del cache+ assert _wait_until(lambda: (gc.collect(), cache_ref() is None)[1]), "the cache was not collected"+ worker.join(timeout=10)+ assert not worker.is_alive(), "the worker outlived its collected cache"+ shutdown_worker.join(timeout=10)+ assert not shutdown_worker.is_alive(), "the shutdown worker outlived its collected cache"@pytest.mark.parametrize("finalizer_order", ["before_cache_release", "after_cache_release"])@@ -1252,7 +3276,7 @@ class _ReentryReportingLock:def test_grace_release_does_not_take_cache_lock_on_the_collecting_thread(mock_logger):"""The grace release runs from a weakref.finalize callback, i.e. at an arbitrary- garbage-collection point in an arbitrary thread — including one that already holds the+ garbage-collection point in an arbitrary thread - including one that already holds theSharedCpuWeightsStore lock (`acquire()` sums tensor sizes inside its critical section, so agenerational collection can fire there, and `put()` reaches it via the cached-model wrapper).@@ -1270,7 +3294,7 @@ def test_grace_release_does_not_take_cache_lock_on_the_collecting_thread(mock_lo# The whole point of this test is WHERE the collection happens, so automatic collection must# not pre-empt it: the setup below allocates freely (DummyModule alone is ~70 tracked objects),# and a gen-0 pass landing before the collector thread starts would reclaim the cycle on the- # main thread with no store lock held, making the test pass vacuously — or trip the setup+ # main thread with no store lock held, making the test pass vacuously - or trip the setup# assertions, depending on the ambient allocation count. Disable automatic gc for the setup and# let only the explicit collect below reclaim the cycle.gc.disable()@@ -1279,7 +3303,7 @@ def test_grace_release_does_not_take_cache_lock_on_the_collecting_thread(mock_loloaded_model = LoadedModelWithoutConfig(cache_record=cache_a.get("abandoned"), cache=cache_a)# Trap the wrapper in a reference cycle so only the cyclic collector can reclaim it, which- # is what an exception traceback does to an errored loader's local — precisely the+ # is what an exception traceback does to an errored loader's local - precisely the# abandoned case the grace release exists for. This forces the callback to run inside# gc.collect() rather than at a refcount-zero decref.cycle: dict[str, object] = {"wrapper": loaded_model}@@ -1468,7 +3492,7 @@ def test_deferred_worker_does_not_pin_the_record_it_just_released(mock_logger):assert _wait_until(lambda: budget.total_in_use() == S)# The budget now says those bytes are gone; they must really be gone. No further queue- # traffic is generated here — that is the point.+ # traffic is generated here - that is the point.assert _wait_until(lambda: (gc.collect(), record_ref() is None)[1]), "worker pinned the CacheRecord"assert module_ref() is None, "evicted model is still resident in RAM"finally:@@ -1479,8 +3503,8 @@ def test_deferred_worker_does_not_pin_the_record_it_just_released(mock_logger):def test_deferred_worker_is_revived_after_an_unexpected_death(mock_logger):"""A worker lost to an unexpected error must not silently disable deferred work forever.- Thread objects cannot be restarted and Thread.ident is never cleared, so a liveness check —- not a "was it ever started" check — is what keeps a later put() able to recover.+ Thread objects cannot be restarted and Thread.ident is never cleared, so a liveness check -+ not a "was it ever started" check - is what keeps a later put() able to recover."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=int(S * 1.4), shared_store=store)@@ -1540,8 +3564,9 @@ def test_deferred_dispatch_is_dropped_when_no_worker_is_running(mock_logger):assert idle_cache.cached_model_keys() == set()assert idle_cache._deferred_work_queue.qsize() == 0- # After shutdown the same must hold for a cache that *does* have a (now stopped) worker.- busy_cache.shutdown()+ # The same must hold for a cache whose worker has died (shutdown() no longer stops the+ # worker, so simulate a death the way a raising log handler would cause one).+ busy_cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)assert busy_cache._deferred_work_thread is not Nonebusy_cache._deferred_work_thread.join(timeout=10)assert not busy_cache._deferred_work_thread.is_alive()@@ -1590,7 +3615,7 @@ def test_dropped_cache_is_collectable_and_its_worker_exits(mock_logger):"""A ModelCache released without shutdown() must not be kept alive by its own worker thread.A running thread is reachable from threading._active and keeps its target alive, so a worker- holding a bound method would pin the cache — and every model in it — in RAM for the life of the+ holding a bound method would pin the cache - and every model in it - in RAM for the life of theprocess. The worker takes a weakref and a finalizer wakes it when the cache goes away."""store = SharedCpuWeightsStore()@@ -1641,33 +3666,57 @@ def test_dropped_non_shared_cache_releases_only_its_budget_charge(mock_logger):assert budget.total_in_use() == S-def test_admission_without_a_worker_gets_no_first_use_grace(mock_logger):+def test_admission_without_a_worker_gets_no_first_use_grace_or_holds(mock_logger, monkeypatch):"""A record must never be shielded from eviction with nothing left able to unshield it.- put() after shutdown() is reachable in production — Invoker.stop() stops model_manager before- session_processor, so an in-flight generation can admit a model after every cache has been shut- down — and _ensure_deferred_worker deliberately does not revive the worker there. Granting the- grace anyway would leave the record permanently invisible to both asynchronous eviction paths- while its bytes stayed charged to the shared budget.+ put() (and register_first_use_hold) first try to revive a dead worker, so the no-worker state+ only persists when the thread cannot be started at all (RLIMIT_NPROC, a container's pids.max).+ Granting the grace - or arming a wrapper hold - there would leave the record permanently+ invisible to the asynchronous eviction paths while its bytes stayed charged to the shared+ budget, because the releases both travel through the worker."""store = SharedCpuWeightsStore()budget = RamBudget(max_bytes=int(S * 8), shared_store=store)cache = _make_cache(store, budget, mock_logger)+ real_thread_start = threading.Thread.start++ def fail_worker_start(thread: threading.Thread) -> None:+ if thread.name == "model-cache-deferred-work":+ raise RuntimeError("forced thread start failure")+ real_thread_start(thread)+try:cache.put("normal", DummyModule())assert cache._cached_models["normal"].awaiting_first_use, "a healthy admission keeps its grace"+ _use_and_release(cache, "normal")- cache.shutdown()+ # Kill the worker, then fail every restart so the cache truly has none.+ cache._deferred_work_queue.put(model_cache_module._DEFERRED_STOP)assert cache._deferred_work_thread is not Nonecache._deferred_work_thread.join(timeout=10)+ monkeypatch.setattr(threading.Thread, "start", fail_worker_start)cache.put("late", DummyModule())record = cache._cached_models["late"]- assert cache._deferred_work_thread is not None and not cache._deferred_work_thread.is_alive()assert not record.awaiting_first_use, "admitted with a grace no worker can ever release"- # Being unshielded, it is reachable by the synchronous eviction path.+ # A wrapper constructed now must not arm a hold (its finalizer's release would be+ # dropped), and must therefore not register the finalizer either.+ loaded_model = LoadedModelWithoutConfig(cache_record=cache.get("late"), cache=cache)+ assert record.first_use_holds == 0, "armed a hold no worker can ever release"+ assert loaded_model._first_use_finalizer is None++ # A retrieval that asks for a claim gets one that owns the window but carries no hold:+ # there is nothing to carry a hold's release, and a hold-less claim shields nothing.+ record_again, claim = cache.get_with_first_use_claim("late")+ assert record_again is record+ assert claim is not None and claim._hold_epoch is None+ assert record.first_use_holds == 0+ assert not record.in_first_use_window++ # Being unshielded, the record is reachable by the synchronous eviction path.cache._delete_cache_entry(record)assert "late" not in cache._cached_modelsfinally:+ monkeypatch.undo()cache.shutdown()diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_timeout.py b/tests/backend/model_manager/load/model_cache/test_model_cache_timeout.pyindex 5b27b3d8ef..74a1337dcf 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_timeout.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_timeout.py@@ -109,18 +109,26 @@ def test_no_timeout_keeps_models(model_cache_no_timeout):def test_shutdown_cancels_timer(model_cache_with_timeout):- """Test that shutdown properly cancels the timeout timer."""+ """Test that shutdown properly cancels the timeout timer and evicts resident records."""cache = model_cache_with_timeout- # Add a model to start the timer+ # Add a model to start the timer, and complete its load-use cycle so the record is an+ # ordinary idle resident (a record still inside the put()->lock() admission window is+ # deliberately retained by shutdown()).test_tensor = torch.randn(10, 10)cache.put("test_model", test_tensor)+ record = cache.get("test_model")+ cache.lock(record, None)+ cache.unlock(record)+ assert cache._timeout_timer is not None# Shutdown the cachecache.shutdown()- # Wait for what would be the timeout- time.sleep(1.0)+ # The timer is cancelled and the idle record is evicted with its accounting.+ assert cache._timeout_timer is None+ assert "test_model" not in cache._cached_models- # The model should still be in the cache since shutdown was called- assert "test_model" in cache._cached_models+ # Wait for what would be the timeout; the cancelled timer must not fire or arm a new one.+ time.sleep(1.0)+ assert cache._timeout_timer is None