Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): keep loaded models serving while another model loads or is evicted (#398)
Krisztian Gajdar88ee59aac100
diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.pyindex f9c8c9bdf..253250973 100644--- a/packages/sie_server/src/sie_server/core/model_loader.py+++ b/packages/sie_server/src/sie_server/core/model_loader.py@@ -524,9 +524,9 @@ class ModelLoader:run; it cannot be interrupted from outside.2. The wedged executor is ``shutdown(wait=False)``'d and replacedwith a fresh single-worker pool so subsequent loads do not- queue behind the leaked thread (the registry holds- ``_load_lock`` while awaiting us, so this happens with the- registry quiesced).+ queue behind the leaked thread (the registry holds its load+ admission lock while awaiting us, so no other load is using+ the executor).3. A structured error is logged.4. :class:`ModelLoadTimeoutError` is raised; the registry's``_record_load_failure`` classifies it as ``TIMEOUT``, recordsdiff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex 3d35fab79..6eacd1bca 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -287,10 +287,19 @@ class ModelRegistry:cache_config.local_cache,)- # Concurrency-safe loading+ # Lock order, outermost first: per-model load lock, config update lock,+ # load admission lock, load lock. The load lock guards registry state+ # transitions, eviction decisions and adapter teardown, and is never+ # held across a worker drain, adapter instantiation or adapter load.+ # The admission lock serializes the memory-changing part of every load+ # with other loads and with config mutations. Waiting for an in-flight+ # unload is allowed under any lock except the load lock, because the+ # unload's teardown takes the load lock.self._load_lock: asyncio.Lock | None = None # Created lazily on first useself._model_load_locks: dict[str, asyncio.Lock] = {}+ self._load_admission_lock: asyncio.Lock | None = Noneself._config_update_lock: asyncio.Lock | None = None+ self._unload_done: dict[str, asyncio.Event] = {}# Async lifecycle state is owned by one long-lived server event loop.# Legacy synchronous callers are serialized independently until that# loop is known; after binding they submit work back to the owner loop.@@ -852,27 +861,29 @@ class ModelRegistry:Raises:DevicePlacementError: When no block of that width can be freed."""- candidates = self._group_candidates(width, requested_device)- cheapest: tuple[tuple[int, float], str, list[str], set[str]] | None = None- for anchor, members in candidates:- blockers = self._group_blockers(members, for_model=name)- if blockers is None:- continue- if not blockers:- return anchor, members- if any(self._is_pinned(blocker) for blocker in blockers):- continue- cost = (len(blockers), max(self._last_used_at(blocker) for blocker in blockers))- if cheapest is None or cost < cheapest[0]:- cheapest = (cost, anchor, members, blockers)-- if cheapest is None:- msg = (- f"Model '{name}' declares tensor_parallel_size={width} but no block of {width} "- f"device(s) on this worker can be freed for it (devices={self._devices}, "- f"claims={sorted(self._device_claims)}, pinned={sorted(self._pinned_models)})"- )- raise DevicePlacementError(msg)+ lock = self._get_load_lock()+ async with lock:+ candidates = self._group_candidates(width, requested_device)+ cheapest: tuple[tuple[int, float], str, list[str], set[str]] | None = None+ for anchor, members in candidates:+ blockers = self._group_blockers(members, for_model=name)+ if blockers is None:+ continue+ if not blockers:+ return anchor, members+ if any(self._is_pinned(blocker) for blocker in blockers):+ continue+ cost = (len(blockers), max(self._last_used_at(blocker) for blocker in blockers))+ if cheapest is None or cost < cheapest[0]:+ cheapest = (cost, anchor, members, blockers)++ if cheapest is None:+ msg = (+ f"Model '{name}' declares tensor_parallel_size={width} but no block of {width} "+ f"device(s) on this worker can be freed for it (devices={self._devices}, "+ f"claims={sorted(self._device_claims)}, pinned={sorted(self._pinned_models)})"+ )+ raise DevicePlacementError(msg)_, anchor, members, blockers = cheapestfor blocker in sorted(blockers):@@ -887,12 +898,13 @@ class ModelRegistry:)await self._do_unload(blocker, reason="group_placement")- if not self._is_group_free(members, for_model=name):- msg = (- f"Model '{name}' declares tensor_parallel_size={width} but {members} did not come "- f"free after evicting {sorted(blockers)}"- )- raise DevicePlacementError(msg)+ async with lock:+ if not self._is_group_free(members, for_model=name):+ msg = (+ f"Model '{name}' declares tensor_parallel_size={width} but {members} did not come "+ f"free after evicting {sorted(blockers)}"+ )+ raise DevicePlacementError(msg)return anchor, membersdef _group_holder_to_evict(self, requested_device: str) -> str | None:@@ -932,18 +944,20 @@ class ModelRegistry:Raises:DevicePlacementError: When no device is free and no group can be displaced."""+ lock = self._get_load_lock()for _ in range(len(self._devices) + 1):- try:- load_device = self._resolve_load_device(requested_device)- self._reject_claimed_device(name, load_device)- except DevicePlacementError:- holder = self._group_holder_to_evict(requested_device)- if holder is None:- raise- logger.info("Placement: evicting multi-device model '%s' to place '%s'", holder, name)- await self._do_unload(holder, reason="group_placement")- continue- return load_device+ async with lock:+ try:+ load_device = self._resolve_load_device(requested_device)+ self._reject_claimed_device(name, load_device)+ except DevicePlacementError:+ holder = self._group_holder_to_evict(requested_device)+ if holder is None:+ raise+ logger.info("Placement: evicting multi-device model '%s' to place '%s'", holder, name)+ else:+ return load_device+ await self._do_unload(holder, reason="group_placement")msg = f"Model '{name}' found no device after displacing every eligible multi-device model"raise DevicePlacementError(msg)@@ -1162,6 +1176,13 @@ class ModelRegistry:lock = self._model_load_locks[name] = asyncio.Lock()return lock+ def _get_load_admission_lock(self) -> asyncio.Lock:+ """Serialize placement, eviction, load and registration across models."""+ self._bind_lifecycle_loop()+ if self._load_admission_lock is None:+ self._load_admission_lock = asyncio.Lock()+ return self._load_admission_lock+def _get_config_update_lock(self) -> asyncio.Lock:"""Serialize async config mutations across IPC/hot-reload entrypoints."""self._bind_lifecycle_loop()@@ -1405,7 +1426,11 @@ class ModelRegistry:"""Load a model onto a device (async, concurrency-safe).This method:- - Serializes all load/unload operations via an async lock+ - Serializes loads of one model with a per-model lock, and the placement,+ eviction, load and registration of every model with the admission lock;+ the registry load lock is held only for state transitions and eviction+ decisions, so batched traffic for loaded models keeps flowing+ - Waits for an in-flight unload of the same model instead of failing- Proactively evicts LRU models if memory pressure or load headroom requires it- Runs the blocking load in a thread pool to avoid blocking the event loop- Falls back to OOM-triggered eviction if load still fails (fragmentation)@@ -1429,21 +1454,28 @@ class ModelRegistry:lock = self._get_load_lock()async with self._get_model_load_lock(name):- async with lock:- # Double-check after acquiring lock (another request may have loaded it)- if name in self._loaded:- self._memory_manager_for_model(name).touch(name)- return self._loaded[name].adapter-- # Check if model is being unloaded - caller should retry- if name in self._unloading:- msg = f"Model '{name}' is currently being unloaded"- raise RuntimeError(msg)-- config = self._configs[name]-- # Mark as loading before starting (visible to WebSocket status)- self._loading.add(name)+ while True:+ # A config mutation unloads and swaps as one step; reading the+ # config in between would load from the one being replaced.+ async with self._get_config_update_lock(), lock:+ pending_unload = self._unload_done.get(name)+ if pending_unload is None:+ # Double-check after acquiring lock (another request may have loaded it)+ if name in self._loaded:+ self._memory_manager_for_model(name).touch(name)+ return self._loaded[name].adapter++ # Check if model is being unloaded - caller should retry+ if name in self._unloading:+ msg = f"Model '{name}' is currently being unloaded"+ raise RuntimeError(msg)++ config = self._configs[name]++ # Mark as loading before starting (visible to WebSocket status)+ self._loading.add(name)+ break+ await pending_unload.wait()load_start = time.monotonic()load_outcome = "error"@@ -1461,27 +1493,31 @@ class ModelRegistry:self._reject_unservable_width(name, width)await self._loader.ensure_weights_cached_async(name, config)- async with lock:- if name in self._loaded:- self._memory_manager_for_model(name).touch(name)- load_outcome = "success"- return self._loaded[name].adapter- if name in self._unloading:- msg = f"Model '{name}' is currently being unloaded"- raise RuntimeError(msg)- # Config mutation only takes the registry lock, so the- # config this load started from may have been removed or- # replaced while the weights were fetched. Never register- # an adapter built from a config the registry no longer- # serves; a changed one is retried by the caller.- current_config = self._configs.get(name)- if current_config is None:- msg = f"Model '{name}' config was removed while its weights were being fetched"- raise RuntimeError(msg)- if current_config != config:- msg = f"Model '{name}' config changed while its weights were being fetched; retry"- raise RuntimeError(msg)- model_dir = self._model_dirs.get(name, Path())+ async with self._get_load_admission_lock():+ # Memory decisions below must see what in-flight unloads+ # release, or this load would evict another model instead.+ await self._wait_for_unloads()+ async with lock:+ if name in self._loaded:+ self._memory_manager_for_model(name).touch(name)+ load_outcome = "success"+ return self._loaded[name].adapter+ if name in self._unloading:+ msg = f"Model '{name}' is currently being unloaded"+ raise RuntimeError(msg)+ # Config mutation does not wait for the download, so the+ # config this load started from may have been removed or+ # replaced while the weights were fetched. Never register+ # an adapter built from a config the registry no longer+ # serves; a changed one is retried by the caller.+ current_config = self._configs.get(name)+ if current_config is None:+ msg = f"Model '{name}' config was removed while its weights were being fetched"+ raise RuntimeError(msg)+ if not _model_configs_semantically_equal(current_config, config):+ msg = f"Model '{name}' config changed while its weights were being fetched; retry"+ raise RuntimeError(msg)+ model_dir = self._model_dirs.get(name, Path())if width > 1:# Refuse a profile the adapter would reject before evicting@@ -1500,36 +1536,40 @@ class ModelRegistry:# Pre-load eviction: evict LRU non-pinned models until current pressure# and any adapter-provided load headroom requirement are satisfied.- while memory_manager.should_evict_for_load(required_load_bytes):- lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)- if lru_model is None:- break # No non-pinned models to evict, proceed with load attempt-- if lru_model not in self._loaded:- # Belt-and-braces: a MemoryManager entry with no matching- # ``_loaded`` model is a ghost (see #1600). ``_do_unload``- # would no-op on it, so drop the stale accounting entry and- # re-evaluate rather than spin. The ``_do_unload`` finally- # normally prevents ghosts; this guards any other source.- logger.warning(- "Evictor found ghost '%s' (in memory manager, not loaded); dropping stale entry",+ while True:+ await self._wait_for_unloads()+ async with lock:+ if not memory_manager.should_evict_for_load(required_load_bytes):+ break+ lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)+ if lru_model is None:+ break # No non-pinned models to evict, proceed with load attempt++ if lru_model not in self._loaded:+ # Belt-and-braces: a MemoryManager entry with no matching+ # ``_loaded`` model is a ghost (see #1600). ``_do_unload``+ # would no-op on it, so drop the stale accounting entry and+ # re-evaluate rather than spin. The ``_do_unload`` finally+ # normally prevents ghosts; this guards any other source.+ logger.warning(+ "Evictor found ghost '%s' (in memory manager, not loaded); dropping stale entry",+ lru_model,+ )+ memory_manager.unregister_model(lru_model)+ continue++ stats = memory_manager.get_stats()+ logger.info(+ "Pre-load eviction: %s %.2f GB free, %.2f GB required, %.1f%% used "+ "(threshold %.1f%%); evicting '%s' before loading '%s'",+ load_device,+ stats.available_gb,+ (required_load_bytes or 0) / (1024**3),+ stats.usage_ratio * 100,+ memory_manager.pressure_threshold_pct,lru_model,+ name,)- memory_manager.unregister_model(lru_model)- continue-- stats = memory_manager.get_stats()- logger.info(- "Pre-load eviction: %s %.2f GB free, %.2f GB required, %.1f%% used "- "(threshold %.1f%%); evicting '%s' before loading '%s'",- load_device,- stats.available_gb,- (required_load_bytes or 0) / (1024**3),- stats.usage_ratio * 100,- memory_manager.pressure_threshold_pct,- lru_model,- name,- )await self._do_unload(lru_model, reason="preload_pressure")try:@@ -1540,7 +1580,9 @@ class ModelRegistry:raise# OOM despite pre-load eviction: evict LRU non-pinned model and retry once- lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)+ await self._wait_for_unloads()+ async with lock:+ lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)if lru_model is None:logger.error("OOM loading '%s' but no non-pinned models to evict", name)raise@@ -1557,11 +1599,12 @@ class ModelRegistry:adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, load_device)loaded = await self._loader.load_and_register_async(name, load_device, adapter, config)- # Track loaded state- self._loaded[name] = loaded+ async with lock:+ # Track loaded state+ self._loaded[name] = loaded- # Register with memory manager for LRU tracking- self._register_across_group(name, loaded)+ # Register with memory manager for LRU tracking+ self._register_across_group(name, loaded)load_duration = time.monotonic() - load_startif load_duration > 300:@@ -1812,7 +1855,7 @@ class ModelRegistry:"""Run the blocking ``adapter.unload()`` on a worker thread.Shielded, and awaited again if we are cancelled. Once teardown has- begun it must be allowed to finish: ``_do_unload``'s ``finally``+ begun it must be allowed to finish: ``_finish_unload``'s ``finally``drops the model's MemoryManager entry and the load lock is releasedas the exception unwinds, so returning early would expose a windowin which a concurrent load sizes itself against VRAM this adapter@@ -1864,21 +1907,47 @@ class ModelRegistry:raise TimeoutErrorawait asyncio.wait_for(task, timeout=remaining)+ def _begin_unload(self, name: str) -> LoadedModel | None:+ """Claim a loaded model for unload; None if it is not loaded or already unloading.++ Synchronous on purpose: a caller that decides on ``name`` and claims it+ without an ``await`` in between cannot be overtaken by a request that+ would refresh or restart the model, or by another evictor.+ """+ loaded = self._loaded.get(name)+ if loaded is None or name in self._unloading:+ return None+ self._unloading.add(name)+ self._unload_done[name] = asyncio.Event()+ return loaded++ async def _wait_for_unloads(self) -> None:+ """Wait for the unloads in flight now; unloads that begin later are not awaited."""+ for done in list(self._unload_done.values()):+ await done.wait()+async def _do_unload(self, name: str, *, reason: str = "other") -> None:- """Unload a model safely (drains worker first).+ """Unload a model safely (drains worker first), or wait for its unload in flight.- Must be called while holding _load_lock.+ Must be called WITHOUT holding ``_load_lock``: the drain runs unlocked+ and the teardown takes the lock itself. The model is claimed before the+ first suspension point, so a caller that chose ``name`` under the lock+ and awaits this right after releasing it cannot be overtaken.Args:name: Model name."""- loaded = self._loaded.get(name)+ loaded = self._begin_unload(name)if loaded is None:+ pending_unload = self._unload_done.get(name)+ if pending_unload is not None:+ await pending_unload.wait()return+ await self._finish_unload(name, loaded, reason=reason)- # Mark as unloading so new requests get 503- self._unloading.add(name)-+ async def _finish_unload(self, name: str, loaded: LoadedModel, *, reason: str) -> None:+ """Drain and tear down a model claimed by :meth:`_begin_unload`."""+ done = self._unload_done[name]try:logger.info("Unloading model '%s' (draining worker first)", name)@@ -1920,88 +1989,92 @@ class ModelRegistry:except Exception: # noqa: BLE001 - teardown continues after best-effort drainlogger.warning("Generation adapter drain failed during unload of '%s'", name, exc_info=True)- # Remove from loaded dict before unloading adapter- del self._loaded[name]- device = loaded.device- worker_telemetry().model_evicted(model=name, reason=reason)-- # Once removed from ``_loaded`` above, the model is committed-gone- # from the registry's view, so its MemoryManager entry MUST be- # dropped even if adapter teardown below raises. Otherwise the- # model becomes a "ghost" — absent from ``_loaded`` but still- # counted in ``_models`` — that ``get_lru_model`` keeps- # re-selecting while ``_do_unload`` no-ops on it: a no-yield spin- # under ``_load_lock`` that starves the whole event loop. See #1600.- try:- # Some adapters (e.g. the SGLang generation adapter) hold an- # async HTTP client to a subprocess. ``unload()`` is sync and- # can only fire-and-forget the client close, which races the- # subprocess termination on the next line — the close could be- # cut off before its connections drain, leaking fds / wedging- # on a half-open socket. When the adapter exposes an awaitable- # ``aclose_client``, drive it to completion HERE (we're on the- # event loop) so the client is fully closed against the still-- # live subprocess before ``unload()`` terminates it.- aclose_client = getattr(loaded.adapter, "aclose_client", None)- if aclose_client is not None:- try:- await aclose_client()- except Exception: # noqa: BLE001 - close is best-effort- logger.warning("aclose_client() failed during unload of '%s'", name, exc_info=True)-- # Adapter.unload() handles gc.collect + empty_cache, and for- # subprocess-backed adapters a SIGTERM/SIGKILL wait of up to- # 15s. All of it is blocking, and running it inline froze the- # event loop for the duration: every other coroutine —- # health probes, in-flight responses on models that are not- # being evicted, the metrics endpoint — stopped, not merely- # the load path the lock already serialises (design proposal- # ``settlement-and-queue-scalability.md``, B6 part one; same- # class as the #1600 scar above).- #- # The load lock stays held across this on purpose. The- # ``finally`` below drops this model's MemoryManager entry,- # and until ``unload()`` returns the VRAM is not actually- # free, so a load admitted against the freed accounting- # would size itself against memory the dying adapter still- # holds. A slow unload beats an OOM.- await self._run_adapter_unload(loaded.adapter, name)- finally:- # Always run, even if adapter teardown above raised, so a- # failed unload can never leave a ghost behind (#1600).+ async with self._get_load_lock():+ # Remove from loaded dict before unloading adapter+ del self._loaded[name]+ device = loaded.device+ worker_telemetry().model_evicted(model=name, reason=reason)++ # Once removed from ``_loaded`` above, the model is committed-gone+ # from the registry's view, so its MemoryManager entry MUST be+ # dropped even if adapter teardown below raises. Otherwise the+ # model becomes a "ghost" — absent from ``_loaded`` but still+ # counted in ``_models`` — that ``get_lru_model`` keeps+ # re-selecting while ``_do_unload`` no-ops on it: a no-yield spin+ # under ``_load_lock`` that starves the whole event loop. See #1600.try:- # Unregister tokenizer, preprocessor, and clear metrics- self._loader.unregister(name, device)- except Exception: # noqa: BLE001 - best-effort; must not skip below- logger.warning("loader.unregister failed during unload of '%s'", name, exc_info=True)- # Unregister from every manager that accounted for it (plain- # dict-pops; never raise). Ordered before the claim release,- # because the claim is what names the group's members.- self._unregister_across_group(name, device)- # Hand back any exclusively held devices. A no-op for the- # single-device models that are every profile today.- self._release_device_claims(name)+ # Some adapters (e.g. the SGLang generation adapter) hold an+ # async HTTP client to a subprocess. ``unload()`` is sync and+ # can only fire-and-forget the client close, which races the+ # subprocess termination on the next line — the close could be+ # cut off before its connections drain, leaking fds / wedging+ # on a half-open socket. When the adapter exposes an awaitable+ # ``aclose_client``, drive it to completion HERE (we're on the+ # event loop) so the client is fully closed against the still-+ # live subprocess before ``unload()`` terminates it.+ aclose_client = getattr(loaded.adapter, "aclose_client", None)+ if aclose_client is not None:+ try:+ await aclose_client()+ except Exception: # noqa: BLE001 - close is best-effort+ logger.warning("aclose_client() failed during unload of '%s'", name, exc_info=True)++ # Adapter.unload() handles gc.collect + empty_cache, and for+ # subprocess-backed adapters a SIGTERM/SIGKILL wait of up to+ # 15s. All of it is blocking, and running it inline froze the+ # event loop for the duration: every other coroutine —+ # health probes, in-flight responses on models that are not+ # being evicted, the metrics endpoint — stopped, not merely+ # the load path the lock already serialises (design proposal+ # ``settlement-and-queue-scalability.md``, B6 part one; same+ # class as the #1600 scar above).+ #+ # The load lock stays held across this on purpose. The+ # ``finally`` below drops this model's MemoryManager entry,+ # and until ``unload()`` returns the VRAM is not actually+ # free, so a load admitted against the freed accounting+ # would size itself against memory the dying adapter still+ # holds. A slow unload beats an OOM.+ await self._run_adapter_unload(loaded.adapter, name)+ finally:+ # Always run, even if adapter teardown above raised, so a+ # failed unload can never leave a ghost behind (#1600).+ try:+ # Unregister tokenizer, preprocessor, and clear metrics+ self._loader.unregister(name, device)+ except Exception: # noqa: BLE001 - best-effort; must not skip below+ logger.warning("loader.unregister failed during unload of '%s'", name, exc_info=True)+ # Unregister from every manager that accounted for it (plain+ # dict-pops; never raise). Ordered before the claim release,+ # because the claim is what names the group's members.+ self._unregister_across_group(name, device)+ # Hand back any exclusively held devices. A no-op for the+ # single-device models that are every profile today.+ self._release_device_claims(name)- # Freeing memory makes any prior OOM-class load failure on a- # *sibling* model retryable; clear those records so the next- # request can re-attempt without waiting out the cooldown.- cleared = self._clear_transient_failures((LoadErrorClass.OOM, LoadErrorClass.PLACEMENT))- if cleared:- logger.debug(- "Cleared %d transient failure record(s) after unloading '%s'",- cleared,- name,- )+ # Freeing memory makes any prior OOM-class load failure on a+ # *sibling* model retryable; clear those records so the next+ # request can re-attempt without waiting out the cooldown.+ cleared = self._clear_transient_failures((LoadErrorClass.OOM, LoadErrorClass.PLACEMENT))+ if cleared:+ logger.debug(+ "Cleared %d transient failure record(s) after unloading '%s'",+ cleared,+ name,+ )logger.info("Model '%s' unloaded", name)finally:self._unloading.discard(name)+ if self._unload_done.get(name) is done:+ del self._unload_done[name]+ done.set()async def unload_async(self, name: str, *, reason: str = "manual") -> None:"""Unload a model and free resources (async, concurrency-safe).- This method acquires the load lock and safely drains the worker- before unloading the model.+ This method waits for an in-flight load or unload of the same model,+ then drains the worker before unloading the model.Args:name: Model name.@@ -2018,8 +2091,10 @@ class ModelRegistry:msg = _ERR_MODEL_NOT_FOUND.format(name=name)raise KeyError(msg)- lock = self._get_load_lock()- async with lock:+ async with self._get_model_load_lock(name):+ pending_unload = self._unload_done.get(name)+ if pending_unload is not None:+ await pending_unload.wait()if name not in self._loaded:msg = _ERR_MODEL_NOT_LOADED.format(name=name)raise KeyError(msg)@@ -2049,8 +2124,7 @@ class ModelRegistry:async def unload_all_async(self) -> None:"""Unload all loaded models (async, concurrency-safe)."""- lock = self._get_load_lock()- async with lock:+ async with self._get_load_admission_lock():for name in list(self._loaded.keys()):await self._do_unload(name, reason="shutdown")@@ -2141,7 +2215,7 @@ class ModelRegistry:return updated_ids | removed_idsasync def add_config_async(self, config: ModelConfig, model_dir: Path | None = None) -> set[str]:- """Add a model config, draining removed loaded variants under the load lock."""+ """Add a model config, draining removed loaded variants while no load is admitted."""update_lock = self._get_config_update_lock()async with update_lock:expanded, updated_ids, removed_ids = self._prepare_config_update(config)@@ -2154,8 +2228,7 @@ class ModelRegistry:}invalidated_ids = removed_ids | changed_idsif invalidated_ids:- lock = self._get_load_lock()- async with lock:+ async with self._get_load_admission_lock():for model_id in sorted(invalidated_ids):if model_id in self._loaded:await self._do_unload(model_id, reason="config_change")@@ -2179,8 +2252,7 @@ class ModelRegistry:if not removed_ids:return set()- lock = self._get_load_lock()- async with lock:+ async with self._get_load_admission_lock():for removed_id in sorted(removed_ids):if removed_id in self._loaded:await self._do_unload(removed_id, reason="config_change")@@ -2303,7 +2375,7 @@ class ModelRegistry:"""Replace the registry config set from an authoritative snapshot.Used by worker-sidecar export reconciliation. Removed or changed- loaded models are unloaded under the registry load lock before the+ loaded models are unloaded while no load is admitted, before theconfig map is swapped, so a worker cannot keep serving a model thatdisappeared from the authoritative bundle export."""@@ -2331,8 +2403,7 @@ class ModelRegistry:update_lock = self._get_config_update_lock()async with update_lock:- lock = self._get_load_lock()- async with lock:+ async with self._get_load_admission_lock():removed = set(self._configs) - set(new_configs)changed = {name@@ -2431,9 +2502,13 @@ class ModelRegistry:async def start_worker(self, name: str) -> ModelWorker:"""Start the worker for a loaded model.- If already running, this is a no-op. Uses the load/unload lock so- request-driven idle touches cannot race an idle-eviction unload- decision.+ A running worker is returned without taking the load lock, so a+ request is never queued behind another model's load or eviction.+ Starting a stopped worker takes the lock. Either way the LRU touch+ and the ``_unloading`` check happen without a suspension point, and+ every eviction claims its model in the same step as its decision, so+ a request either refreshes the model before an idle re-check or sees+ it unloading; it can never revive or use a model mid-unload.Args:name: Model name.@@ -2447,6 +2522,12 @@ class ModelRegistry:if name not in self._configs:msg = _ERR_MODEL_NOT_FOUND.format(name=name)raise KeyError(msg)+ loaded = self._loaded.get(name)+ if loaded is not None and name not in self._unloading:+ running = loaded.worker+ if running is not None and running.is_running:+ self._memory_manager_for_model(name).touch(name)+ return runninglock = self._get_load_lock()async with lock:if name not in self._loaded:@@ -2517,17 +2598,11 @@ class ModelRegistry:load-lock is acquired with a soft timeout so a deadlocked / busyregistry doesn't stall the worker indefinitely.- **Concurrency caveat — drain-under-lock:** this method holds the- registry's load-lock for the duration of ``_do_unload``, which- includes ``worker.stop()`` waiting up to ``_DRAIN_TIMEOUT_S`` (30 s)- for in-flight requests to complete. During a memory-pressure- incident multiple workers may invoke ``evict_lru_excluding``- concurrently; the soft ``timeout_s`` here prevents permanent- deadlock, but a single eviction can still block other registry- operations (additional loads / unloads) for up to the drain- timeout. Operators should expect a transient stall window during- large multi-worker OOM episodes and not interpret it as a hang.- Splitting the drain off the lock is tracked as a follow-up.+ The load-lock is held only to choose and claim the sibling. Its+ worker drain, which waits up to the registry drain timeout (30 s by+ default) for in-flight requests, runs without the lock, and only the+ adapter teardown takes it again, so an eviction does not stall other+ models' requests or registry operations for the drain.Args:exclude_name: The calling worker's own model. Never evicted, even@@ -2574,14 +2649,14 @@ class ModelRegistry:manager.device,exclude_name,)- try:- await self._do_unload(candidate, reason="oom_recovery")- except Exception:- logger.exception("OOM recovery: failed to evict '%s'", candidate)- return EvictionResult.UNLOAD_FAILED- return EvictionResult.EVICTEDfinally:lock.release()+ try:+ await self._do_unload(candidate, reason="oom_recovery")+ except Exception:+ logger.exception("OOM recovery: failed to evict '%s'", candidate)+ return EvictionResult.UNLOAD_FAILED+ return EvictionResult.EVICTEDasync def start_memory_monitor(self) -> None:"""Start the background memory monitor task.@@ -2656,16 +2731,18 @@ class ModelRegistry:Runs at the same cadence as the pressure monitor. On each tick:1. Snapshot stale models (no lock — read-only over the LRU dict).- 2. Take the load lock once, walk the snapshot, evict the first- still-stale model, then release. Subsequent stale models wait- for the next tick. This caps lock contention against in-flight- ``load_async`` callers and matches the "one eviction per tick"- cadence of the existing pressure monitor.+ 2. Take the load lock once, walk the snapshot and pick the first+ still-stale model, then release the lock and unload it; the+ drain runs without the lock. Subsequent stale models wait for the+ next tick, matching the "one eviction per tick" cadence of the+ existing pressure monitor.The recheck inside the lock guards against the snapshot/unload race:a request that arrived after the snapshot may have bumped``last_used_at``, in which case we skip and look at the next- candidate.+ candidate. The unload claims the model before the next suspension+ point, so ``start_worker``'s unlocked path either touched it before+ the recheck or observes it unloading.Idle eviction *can* unload the only loaded model. The pressuremonitor explicitly skips that case (because the eviction would@@ -2695,12 +2772,13 @@ class ModelRegistry:continuelock = self._get_load_lock()+ victim: str | None = Noneasync with lock:for name in stale:# Re-check under the lock: model may have been- # unloaded already, or bumped by a request that- # arrived after the snapshot.- if name not in self._loaded:+ # unloaded already, be unloading, or have been+ # bumped by a request that arrived after the snapshot.+ if name not in self._loaded or name in self._unloading:continueinfo = self._memory_manager_for_model(name).get_model_info(name)if info is None:@@ -2714,14 +2792,15 @@ class ModelRegistry:age,threshold,)- try:- await self._do_unload(name, reason="idle")- except Exception:- logger.exception("Idle eviction failed for '%s'", name)- # One eviction per tick: yield the lock so other- # registry operations can make progress. The next- # tick handles any remaining stale models.+ # One eviction per tick. The next tick handles any+ # remaining stale models.+ victim = namebreak+ if victim is not None:+ try:+ await self._do_unload(victim, reason="idle")+ except Exception:+ logger.exception("Idle eviction failed for '%s'", victim)except asyncio.CancelledError:break@@ -2780,12 +2859,17 @@ class ModelRegistry:if not pressured_managers:continue- # Pressure detected - acquire lock and evict+ # Pressure detected - decide under the lock, evict outside itlock = self._get_load_lock()- async with lock:- for manager in pressured_managers:- # Re-check under lock (may have resolved)- while manager.check_pressure():+ for manager in pressured_managers:+ while True:+ # Memory an in-flight unload is about to free may+ # already resolve the pressure.+ await self._wait_for_unloads()+ async with lock:+ # Re-check under lock (may have resolved)+ if not manager.check_pressure():+ break# Don't evict if only 1 model loaded - would cause immediate reloadif manager.loaded_model_count <= 1:logger.debug(@@ -2818,7 +2902,7 @@ class ModelRegistry:manager.pressure_threshold_pct,lru_model,)- await self._do_unload(lru_model, reason="memory_pressure")+ await self._do_unload(lru_model, reason="memory_pressure")except asyncio.CancelledError:breakdiff --git a/packages/sie_server/tests/core/test_registry_async.py b/packages/sie_server/tests/core/test_registry_async.pyindex 997c6b439..e3e7e6163 100644--- a/packages/sie_server/tests/core/test_registry_async.py+++ b/packages/sie_server/tests/core/test_registry_async.py@@ -1050,6 +1050,21 @@ async def test_config_replaced_during_download_is_not_registered(assert not registry.is_loading("slow")+async def test_identical_config_reapplied_during_download_still_loads(patch_ensure_model_cached: MagicMock) -> None:+ """Re-applying an unchanged config replaces the object but must not fail the load."""+ download = _BlockingDownload("org/slow")+ patch_ensure_model_cached.side_effect = download+ registry = _two_model_registry()+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_adapter_factory()):+ slow = asyncio.create_task(registry.load_async("slow", "cpu"))+ await asyncio.to_thread(download.entered.wait, 5)++ await registry.add_config_async(_make_config(name="slow", hf_id="org/slow"))+ download.release.set()+ await asyncio.wait_for(slow, timeout=5)+ assert registry.is_loaded("slow")++def test_loader_shutdown_closes_the_download_executor() -> None:from sie_server.core.model_loader import ModelLoaderdiff --git a/packages/sie_server/tests/fake_stack/test_registry_races.py b/packages/sie_server/tests/fake_stack/test_registry_races.pyindex 5e2dcec7c..30be9e480 100644--- a/packages/sie_server/tests/fake_stack/test_registry_races.py+++ b/packages/sie_server/tests/fake_stack/test_registry_races.py@@ -46,11 +46,15 @@ async def _wait_until(predicate, timeout_s: float = 10.0) -> None:# -- Scenario: evict during load (latch-sequenced) --------------------------------async def test_evict_during_load_returns_lock_timeout(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:- """Characterizes the drain/load-under-lock stall (registry.py:1668-1678):- while a load holds the global load-lock, a concurrent eviction attempt- reports LOCK_TIMEOUT rather than deadlocking, and completes once the- load finishes.+async def test_evict_during_load_does_not_wait_for_the_load(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """An eviction requested while another model's load is pinned mid-flight+ completes at once.++ **A conscious flip.** This test used to characterize the opposite: the+ load held the registry load lock across the adapter load, so the same+ eviction reported LOCK_TIMEOUT until the load finished. The load now+ holds only the admission lock there, and the load lock guards short+ decisions, so an OOM-recovery eviction no longer waits out a cold load."""monkeypatch.setenv(SIE_FAKE_MEMORY_BUDGET_ENV, "1GiB")latch = tmp_path / "release-load"@@ -62,23 +66,20 @@ async def test_evict_during_load_returns_lock_timeout(monkeypatch: pytest.Monkeyawait registry.load_async("sie-fake:small-a", device="cpu")load_task = asyncio.create_task(registry.load_async("sie-fake:small-b", device="cpu"))- # Deterministic sequencing: wait until the in-flight load holds the lock.+ # Deterministic sequencing: wait until the in-flight load is admitted.# Private-state reach is deliberate — the registry exposes no public# "load in flight" observation seam, and polling the lock is the only# race-free way to sequence this characterization.- await _wait_until(lambda: registry._get_load_lock().locked())+ await _wait_until(lambda: registry._get_load_admission_lock().locked())# The race: eviction requested while the load is pinned mid-flight.- result = await registry.evict_lru_excluding("sie-fake:small-b", timeout_s=0.2)- assert result is EvictionResult.LOCK_TIMEOUT+ result = await registry.evict_lru_excluding("sie-fake:small-b", timeout_s=5.0)+ assert result is EvictionResult.EVICTED+ assert not load_task.done()+ assert registry.memory_manager.loaded_models == []latch.touch()await load_task- assert set(registry.memory_manager.loaded_models) == {"sie-fake:small-a", "sie-fake:small-b"}-- # After the load releases the lock the same eviction succeeds.- result = await registry.evict_lru_excluding("sie-fake:small-b", timeout_s=5.0)- assert result is EvictionResult.EVICTEDassert registry.memory_manager.loaded_models == ["sie-fake:small-b"]@@ -87,7 +88,7 @@ async def test_evict_during_load_returns_lock_timeout(monkeypatch: pytest.Monkeyasync def test_concurrent_cross_model_load_under_pressure(monkeypatch: pytest.MonkeyPatch) -> None:"""Three models race to load into a 150 MiB budget (64+64+128 MiB- declared). The global load-lock serializes them FIFO, and the pre-load+ declared). The load admission lock serializes them FIFO, and the pre-loadeviction loop must keep the declared usage within budget at every step —the last loader evicts both predecessors. Only same-model dedupe hadcoverage before (test_registry_async.py:126); this is the cross-modeldiff --git a/packages/sie_server/tests/fake_stack/test_registry_serving_isolation.py b/packages/sie_server/tests/fake_stack/test_registry_serving_isolation.pynew file mode 100644index 000000000..411bb446e--- /dev/null+++ b/packages/sie_server/tests/fake_stack/test_registry_serving_isolation.py@@ -0,0 +1,225 @@+"""A loaded model keeps serving while another model loads or is evicted.++Driven by sie-fake models through the real registry and the real encode+pipeline (``EncodePipeline.run_encode`` -> ``ModelRegistry.start_worker`` ->+``ModelWorker``). Slow loads and slow drains are held open with the fake's+load and dispatch latches, so every assertion is sequenced by state rather+than by timing: under a registry that serializes request admission behind+loads or drains, the encodes below cannot complete until the latch is+released, and ``asyncio.wait_for`` fails the test instead.+"""++from __future__ import annotations++import asyncio+import threading+import time+from pathlib import Path+from typing import Any+from unittest.mock import patch++import pytest+from sie_server.config.engine import EngineConfig+from sie_server.core.encode_pipeline import EncodePipeline+from sie_server.core.loader import load_model_configs+from sie_server.core.memory import SIE_FAKE_MEMORY_BUDGET_ENV, MemoryConfig+from sie_server.core.registry import ModelRegistry+from sie_server.core.residency import EvictionResult+from sie_server.core.worker.types import WorkerDrainedError+from sie_server.types.inputs import Item++pytestmark = pytest.mark.fake_stack++MODELS_DIR = Path(__file__).resolve().parents[2] / "models"+SERVING = "sie-fake:small-a"+OTHER = "sie-fake:small-b"+REQUEST_TIMEOUT_S = 5.0+REQUESTS = 10+++def _fake_registry(**kwargs: Any) -> ModelRegistry:+ registry = ModelRegistry(**kwargs)+ registry.add_config(load_model_configs(MODELS_DIR)["sie-fake"])+ return registry+++async def _wait_until(predicate, timeout_s: float = 10.0) -> None:+ deadline = time.monotonic() + timeout_s+ while not predicate():+ if time.monotonic() >= deadline:+ msg = "condition not reached within timeout"+ raise TimeoutError(msg)+ await asyncio.sleep(0.01)+++async def _encode(registry: ModelRegistry, model: str, text: str) -> list[dict[str, Any]]:+ results, _timing = await EncodePipeline.run_encode(+ registry=registry,+ model=model,+ items=[Item(text=text)],+ output_types=["dense"],+ instruction=None,+ config=registry.get_config(model),+ is_query=False,+ options={},+ )+ return results+++async def _serve(registry: ModelRegistry, model: str) -> None:+ for index in range(REQUESTS):+ results = await asyncio.wait_for(_encode(registry, model, f"request {index}"), REQUEST_TIMEOUT_S)+ assert len(results) == 1+++def _signal_dispatch(monkeypatch: pytest.MonkeyPatch, registry: ModelRegistry, model: str) -> threading.Event:+ """Set an event when the model's adapter starts an inference call."""+ adapter = registry.get(model)+ dispatched = threading.Event()+ real_encode = adapter.encode++ def encode_and_signal(*args: Any, **kwargs: Any) -> Any:+ dispatched.set()+ return real_encode(*args, **kwargs)++ monkeypatch.setattr(adapter, "encode", encode_and_signal)+ return dispatched+++async def test_loaded_model_serves_while_another_model_loads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setenv(SIE_FAKE_MEMORY_BUDGET_ENV, "1GiB")+ latch = tmp_path / "release-load"+ monkeypatch.setenv(+ "SIE_FAKE_FAULTS",+ f'{{"{OTHER}": {{"load_latch_file": "{latch}", "latch_timeout_s": 30}}}}',+ )+ registry = _fake_registry()+ await registry.load_async(SERVING, device="cpu")++ load_task = asyncio.create_task(registry.load_async(OTHER, device="cpu"))+ await _wait_until(lambda: registry._get_load_admission_lock().locked())++ # The first request also starts the serving model's worker.+ await _serve(registry, SERVING)+ assert not load_task.done()+ assert registry.is_loading(OTHER)++ latch.touch()+ await asyncio.wait_for(load_task, REQUEST_TIMEOUT_S)+ assert registry.is_loaded(OTHER)+++async def test_loaded_model_serves_while_another_model_drains(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setenv(SIE_FAKE_MEMORY_BUDGET_ENV, "1GiB")+ latch = tmp_path / "release-dispatch"+ monkeypatch.setenv(+ "SIE_FAKE_FAULTS",+ f'{{"{OTHER}": {{"dispatch_latch_file": "{latch}", "latch_timeout_s": 30}}}}',+ )+ registry = _fake_registry()+ await registry.load_async(SERVING, device="cpu")+ await registry.load_async(OTHER, device="cpu")++ # An inference call on OTHER is in flight and held, so its drain waits.+ dispatched = _signal_dispatch(monkeypatch, registry, OTHER)+ in_flight = asyncio.create_task(_encode(registry, OTHER, "held"))+ assert await asyncio.to_thread(dispatched.wait, REQUEST_TIMEOUT_S)+ # Touching SERVING afterwards leaves OTHER as the eviction candidate.+ await _serve(registry, SERVING)++ eviction = asyncio.create_task(registry.evict_lru_excluding(SERVING))+ await _wait_until(lambda: registry.is_unloading(OTHER))++ await _serve(registry, SERVING)+ assert not eviction.done()+ assert registry.is_unloading(OTHER)+ with pytest.raises(RuntimeError, match="currently being unloaded"):+ await registry.start_worker(OTHER)++ latch.touch()+ assert await asyncio.wait_for(eviction, REQUEST_TIMEOUT_S) is EvictionResult.EVICTED+ with pytest.raises(WorkerDrainedError):+ await asyncio.wait_for(in_flight, REQUEST_TIMEOUT_S)+ assert not registry.is_loaded(OTHER)+ assert registry.is_loaded(SERVING)+ with pytest.raises(KeyError, match="not loaded"):+ await registry.start_worker(OTHER)+++async def test_load_of_a_draining_model_waits_and_reloads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setenv(SIE_FAKE_MEMORY_BUDGET_ENV, "1GiB")+ latch = tmp_path / "release-dispatch"+ monkeypatch.setenv(+ "SIE_FAKE_FAULTS",+ f'{{"{OTHER}": {{"dispatch_latch_file": "{latch}", "latch_timeout_s": 30}}}}',+ )+ registry = _fake_registry()+ await registry.load_async(SERVING, device="cpu")+ await registry.load_async(OTHER, device="cpu")+ evicted_adapter = registry.get(OTHER)+ dispatched = _signal_dispatch(monkeypatch, registry, OTHER)+ in_flight = asyncio.create_task(_encode(registry, OTHER, "held"))+ assert await asyncio.to_thread(dispatched.wait, REQUEST_TIMEOUT_S)++ eviction = asyncio.create_task(registry.evict_lru_excluding(SERVING))+ await _wait_until(lambda: registry.is_unloading(OTHER))+ reload = asyncio.create_task(registry.load_async(OTHER, device="cpu"))+ for _ in range(5):+ await asyncio.sleep(0)+ # Neither served from the draining adapter nor failed as "being unloaded".+ assert not reload.done()++ latch.touch()+ assert await asyncio.wait_for(eviction, REQUEST_TIMEOUT_S) is EvictionResult.EVICTED+ reloaded_adapter = await asyncio.wait_for(reload, REQUEST_TIMEOUT_S)+ with pytest.raises(WorkerDrainedError):+ await asyncio.wait_for(in_flight, REQUEST_TIMEOUT_S)+ assert reloaded_adapter is not evicted_adapter+ assert registry.get(OTHER) is reloaded_adapter+++async def test_request_between_idle_snapshot_and_recheck_keeps_the_model() -> None:+ """The unlocked ``start_worker`` path cannot lose a request to idle eviction.++ The idle evictor snapshots a stale model and then waits for the load lock,+ which the test holds. A request for the model completes while the lock is+ held, and the evictor's re-check under the lock then keeps the model.+ """+ registry = _fake_registry(+ memory_config=MemoryConfig(memory_check_interval_s=0.01),+ engine_config=EngineConfig.model_construct(idle_evict_s=1),+ )+ await registry.load_async(SERVING, device="cpu")+ worker = await registry.start_worker(SERVING)+ manager = registry.memory_manager+ info = manager.get_model_info(SERVING)+ assert info is not None+ info.last_used_at = time.monotonic() - 100.0++ snapshots = 0+ first_snapshot = asyncio.Event()+ second_snapshot = asyncio.Event()+ real_get_idle_models = manager.get_idle_models++ def recording_get_idle_models(**kwargs: Any) -> list[str]:+ nonlocal snapshots+ snapshots += 1+ (first_snapshot if snapshots == 1 else second_snapshot).set()+ return real_get_idle_models(**kwargs)++ lock = registry._get_load_lock()+ with patch.object(manager, "get_idle_models", side_effect=recording_get_idle_models):+ await lock.acquire()+ try:+ await registry.start_idle_evictor()+ await asyncio.wait_for(first_snapshot.wait(), REQUEST_TIMEOUT_S)+ assert await asyncio.wait_for(registry.start_worker(SERVING), REQUEST_TIMEOUT_S) is worker+ finally:+ lock.release()+ await asyncio.wait_for(second_snapshot.wait(), REQUEST_TIMEOUT_S)+ await registry.stop_idle_evictor()++ assert registry.is_loaded(SERVING)+ assert not registry.is_unloading(SERVING)+ assert worker.is_running+ await registry.unload_all_async()diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex 1747fb9a4..f0e2f26c8 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -1049,8 +1049,8 @@ profiles:)assert registry.has_model(variant_id)- load_lock = registry._get_load_lock()- await load_lock.acquire()+ admission_lock = registry._get_load_admission_lock()+ await admission_lock.acquire()remove_task = asyncio.create_task(executor.apply_model_config(ApplyModelConfigRequest(@@ -1081,11 +1081,11 @@ profiles:try:await asyncio.sleep(0)- load_lock.release()+ admission_lock.release()await asyncio.gather(remove_task, readd_task)finally:- if load_lock.locked():- load_lock.release()+ if admission_lock.locked():+ admission_lock.release()for task in (remove_task, readd_task):if not task.done():task.cancel()diff --git a/packages/sie_server_sidecar/src/delivery.rs b/packages/sie_server_sidecar/src/delivery.rsindex 4d0cc7123..9334cee9a 100644--- a/packages/sie_server_sidecar/src/delivery.rs+++ b/packages/sie_server_sidecar/src/delivery.rs@@ -129,6 +129,19 @@ impl Delivery {}}+ /// True when this delivery holds a pull-loop admission permit.+ pub(crate) fn holds_admission_permit(&self) -> bool {+ matches!(self, Self::Nats(_, Some(_)))+ }++ /// Give the pull-loop admission permit back and hold `permit` until+ /// settlement instead. A no-op when no admission permit is held.+ pub(crate) fn exchange_admission_permit(&mut self, permit: OwnedSemaphorePermit) {+ if let Self::Nats(_, held @ Some(_)) = self {+ *held = Some(permit);+ }+ }+/// ACK — "settled, never redeliver". Local deliveries settle via/// their terminal [`LocalDeliveryEvent::Result`], so this is a no-op.pub async fn ack(&self) -> Result<(), String> {@@ -265,6 +278,56 @@ mod tests {}}+ async fn offline_message() -> Message {+ let client = async_nats::ConnectOptions::new()+ .retry_on_initial_connect()+ .connect("nats://127.0.0.1:1")+ .await+ .expect("an offline client needs no server");+ Message {+ message: async_nats::Message {+ subject: "sie.work.test".into(),+ reply: None,+ payload: Default::default(),+ headers: None,+ status: None,+ description: None,+ length: 0,+ },+ context: async_nats::jetstream::new(client),+ }+ }++ #[tokio::test]+ async fn exchanging_the_admission_permit_returns_it_to_the_pull_loop() {+ let admission = std::sync::Arc::new(tokio::sync::Semaphore::new(1));+ let parked = std::sync::Arc::new(tokio::sync::Semaphore::new(1));+ let admitted = std::sync::Arc::clone(&admission)+ .try_acquire_owned()+ .unwrap();+ let mut delivery = Delivery::Nats(offline_message().await, Some(admitted));+ assert!(delivery.holds_admission_permit());++ delivery+ .exchange_admission_permit(std::sync::Arc::clone(&parked).try_acquire_owned().unwrap());+ assert_eq!(admission.available_permits(), 1);+ assert_eq!(parked.available_permits(), 0);++ drop(delivery);+ assert_eq!(parked.available_permits(), 1);+ }++ #[tokio::test]+ async fn a_delivery_without_an_admission_permit_takes_no_parked_permit() {+ let parked = std::sync::Arc::new(tokio::sync::Semaphore::new(1));+ let mut delivery = Delivery::Nats(offline_message().await, None);+ assert!(!delivery.holds_admission_permit());++ delivery+ .exchange_admission_permit(std::sync::Arc::clone(&parked).try_acquire_owned().unwrap());+ assert_eq!(parked.available_permits(), 1);+ }+#[test]fn log_ref_identifies_local_slot() {let (tx, _rx) = mpsc::unbounded_channel();diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 0ecf20dc2..354d7af72 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -4,8 +4,9 @@//!//! fetch -> decode + validate (subject, reply_subject, model_id)//! -> group by model_id-//! -> per model (concurrent, capped by batch_semaphore):-//! EnsureModelReady+//! -> per model (concurrent):+//! EnsureModelReady (still loading -> park the group in its own task)+//! then, capped by batch_semaphore://! apply per-model batch_budget (overflow -> NAK fast)//! fan out encode/score/extract concurrently://! resolve payload -> IPC ProcessXxxBatch -> publish + ACK@@ -578,9 +579,17 @@ pub struct Dispatcher {/// `SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS=1`. See/// `crate::pull_quantum_includes_queue_ms` for the rationale.pub latency_tracker: Arc<Mutex<LatencyTracker>>,- /// Caps concurrent model-group processing. Acquired once per group,- /// held for the lifetime of the encode/score/extract fan-out.+ /// Caps concurrent model-group processing. Acquired once per group+ /// after its model is ready, held for the lifetime of the+ /// encode/score/extract fan-out.pub batch_semaphore: Arc<Semaphore>,+ /// Caps queue items parked while their model loads, at one fetch+ /// (`SIE_NATS_FETCH_BUDGET`). A parked item gives its pull-loop admission+ /// permit back and holds one of these instead, so a cold model cannot+ /// stop the pull loop admitting work for models that are already loaded.+ parked_item_permits: Arc<Semaphore>,+ /// Groups parked while their model loads, joined at shutdown.+ parked_group_handles: Arc<std::sync::Mutex<Vec<JoinHandle<()>>>>,/// Bounds the largest CPU allocation path independently of batch fan-out./// One 12-minute 48 kHz decode can transiently hold about 230 MiB.audio_prep_semaphore: Arc<Semaphore>,@@ -670,6 +679,8 @@ impl Dispatcher {runtime_state,latency_tracker,batch_semaphore: Arc::new(Semaphore::new(default_max_concurrent_batches())),+ parked_item_permits: Arc::new(Semaphore::new(default_batch_budget().max(1) as usize)),+ parked_group_handles: Arc::new(std::sync::Mutex::new(Vec::new())),audio_prep_semaphore: Arc::new(Semaphore::new(default_audio_prep_permits())),tokenizer_registry,scheduler_registry,@@ -1016,8 +1027,10 @@ impl Dispatcher {////// Concurrency:/// * group by `model_id` only.- /// * model groups run concurrently, capped by `batch_semaphore` to- /// avoid ACK-timeout storms.+ /// * model groups run concurrently; once a group's model is ready its+ /// dispatch is capped by `batch_semaphore` to avoid ACK-timeout storms,+ /// and a group whose model is still loading is parked in its own task+ /// so this call does not wait for the load./// * within a model, encode/score/extract run concurrently via/// `tokio::join!` so slow payload fetches don't block other ops.pub(crate) async fn handle_batch(self: &Arc<Self>, messages: Vec<QueuedMessage>) {@@ -1203,22 +1216,7 @@ impl Dispatcher {for (model_id, items) in model_groups {let this = Arc::clone(self);futs.push(async move {- let permit = match this.batch_semaphore.clone().acquire_owned().await {- Ok(p) => p,- Err(_) => {- warn!(model = %model_id, "batch semaphore closed — dropping group");- return;- }- };- let count_model_group_inflight = this.scheduler_registry.is_none();- if count_model_group_inflight {- this.runtime_state.inflight_batches.inc();- }- let result = this.handle_model_group(&model_id, items).await;- if count_model_group_inflight {- this.runtime_state.inflight_batches.dec();- }- drop(permit);+ let result = this.handle_model_group(&model_id, items, None).await;if let Err(e) = result {warn!(model = %model_id, error = %ErrChain(&e), "model group handling failed");}@@ -1822,10 +1820,115 @@ impl Dispatcher {}}+ /// Move a group whose model is still loading into its own task, so the+ /// wait holds no batch permit, keeps no pull-loop dispatch task alive,+ /// and gives back each item's pull-loop admission permit. Items trade+ /// that permit for a parked-item permit; items beyond the parked-item+ /// capacity are NAKed for redelivery rather than held.+ fn park_model_group(self: &Arc<Self>, model_id: &str, items: Vec<(WorkItem, Delivery)>) {+ let mut parked = Vec::with_capacity(items.len());+ let mut overflow = Vec::new();+ for (wi, mut delivery) in items {+ if delivery.holds_admission_permit() {+ match Arc::clone(&self.parked_item_permits).try_acquire_owned() {+ Ok(permit) => delivery.exchange_admission_permit(permit),+ Err(_) => {+ overflow.push((wi, delivery));+ continue;+ }+ }+ }+ parked.push((wi, delivery));+ }+ // Parked items are progress-ACKed, so JetStream never redelivers+ // them on its own; bound the wait by the envelope it would give an+ // unacknowledged message instead.+ let ready_deadline =+ tokio::time::Instant::now() + crate::nats_consumer::redelivery_envelope();+ let this = Arc::clone(self);+ let model = model_id.to_string();+ let handle = tokio::spawn(async move {+ if !overflow.is_empty() {+ info!(+ model = %model,+ overflow = overflow.len(),+ "parked-item capacity exhausted while the model loads — NAKing overflow"+ );+ nak_all(+ &overflow,+ base_nak_delay_ms(),+ &this.runtime_state.telemetry,+ )+ .await;+ }+ if parked.is_empty() {+ return;+ }+ if let Err(e) = this+ .handle_model_group(&model, parked, Some(ready_deadline))+ .await+ {+ warn!(model = %model, error = %ErrChain(&e), "parked model group handling failed");+ }+ });+ let mut handles = self+ .parked_group_handles+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ handles.retain(|h| !h.is_finished());+ handles.push(handle);+ }++ /// `EnsureModelReady` for `items`. A parked group's call is bounded by its+ /// readiness deadline and progress-ACKs the group while it is pending, so+ /// a slow call neither outlives the deadline nor lets JetStream redeliver+ /// the group. `None` when the group was NAKed instead: the deadline passed+ /// first, or a progress ACK failed.+ async fn ensure_model_ready_by(+ &self,+ model_id: &str,+ items: &[(WorkItem, Delivery)],+ ready_deadline: Option<tokio::time::Instant>,+ ) -> Option<Result<crate::ipc_types::EnsureModelReadyResponse, BackendError>> {+ let readiness = self.backend.ensure_model_ready(model_id);+ let Some(deadline) = ready_deadline else {+ return Some(readiness.await);+ };+ tokio::pin!(readiness);+ let progress_every = Duration::from_secs(crate::nats_consumer::ACK_WAIT_SECS)+ / READINESS_PROGRESS_ACK_WAIT_FRACTION as u32;+ loop {+ let next_progress = (tokio::time::Instant::now() + progress_every).min(deadline);+ tokio::select! {+ result = &mut readiness => return Some(result),+ () = tokio::time::sleep_until(next_progress) => {+ if next_progress >= deadline {+ self.nak_group_past_ready_deadline(model_id, items).await;+ return None;+ }+ if !progress_all(items, &self.runtime_state.telemetry).await {+ nak_all(items, base_nak_delay_ms(), &self.runtime_state.telemetry).await;+ return None;+ }+ }+ }+ }+ }++ async fn nak_group_past_ready_deadline(&self, model_id: &str, items: &[(WorkItem, Delivery)]) {+ info!(+ model = %model_id,+ group_size = items.len(),+ "model not ready within the parked readiness wait — NAKing group"+ );+ nak_all(items, base_nak_delay_ms(), &self.runtime_state.telemetry).await;+ }+async fn handle_model_group(self: &Arc<Self>,model_id: &str,items: Vec<(WorkItem, Delivery)>,+ ready_deadline: Option<tokio::time::Instant>,) -> Result<(), DispatchError> {let mut items = self.retain_uncancelled(items, "before_model_readiness")@@ -1857,7 +1960,13 @@ impl Dispatcher {if items.is_empty() {return Ok(());}- let readiness_resp = match self.backend.ensure_model_ready(model_id).await {+ let Some(readiness) = self+ .ensure_model_ready_by(model_id, &items, ready_deadline)+ .await+ else {+ return Ok(());+ };+ let readiness_resp = match readiness {Ok(r) => r,Err(e) => {warn!(@@ -1892,6 +2001,14 @@ impl Dispatcher {if let Some(delay_ms) =readiness_progress_delay_ms(&readiness_resp.state, base_delay_ms){+ let Some(ready_deadline) = ready_deadline else {+ self.park_model_group(model_id, items);+ return Ok(());+ };+ if tokio::time::Instant::now() >= ready_deadline {+ self.nak_group_past_ready_deadline(model_id, &items).await;+ return Ok(());+ }info!(model = %model_id,group_size,@@ -1919,6 +2036,21 @@ impl Dispatcher {return Ok(());};+ // A parked group's last progress ACK may be a full readiness delay+ // old; refresh it so the batch-permit wait starts from a full ACK wait.+ if ready_deadline.is_some() && !progress_all(&items, &self.runtime_state.telemetry).await {+ nak_all(&items, base_delay_ms, &self.runtime_state.telemetry).await;+ return Ok(());+ }+ let Ok(_batch_permit) = self.batch_semaphore.acquire().await else {+ warn!(model = %model_id, "batch semaphore closed — dropping group");+ return Ok(());+ };+ let _inflight_batch = self+ .scheduler_registry+ .is_none()+ .then(|| InflightBatchGuard::enter(Arc::clone(&self.runtime_state)));+items = self.retain_uncancelled(items, "after_model_readiness").await;@@ -3121,6 +3253,45 @@ impl Dispatcher {guard.drain(..).collect()}+ /// Wait, up to `deadline`, for groups parked while their model loads.+ /// Called at shutdown after the pull loops stop and before the scheduler+ /// drain: a parked group sees the shutdown signal, NAKs its items and+ /// exits, or enqueues them if its model became ready first.+ pub async fn join_parked_groups(&self, deadline: Duration) {+ let handles: Vec<JoinHandle<()>> = self+ .parked_group_handles+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .drain(..)+ .collect();+ if handles.is_empty() {+ return;+ }+ let mut pending = handles;+ let joined = tokio::time::timeout(deadline, async {+ while let Some(handle) = pending.last_mut() {+ let _ = handle.await;+ pending.pop();+ }+ })+ .await;+ if joined.is_err() {+ // An aborted group drops its deliveries unsettled, so JetStream+ // redelivers them after the ACK wait.+ warn!(+ parked_groups = pending.len(),+ deadline_ms = deadline.as_millis() as u64,+ "parked model groups did not settle before the shutdown deadline — aborting them"+ );+ for handle in &pending {+ handle.abort();+ }+ for handle in pending {+ let _ = handle.await;+ }+ }+ }+/// Resolve every encode item's payload then submit it into the/// model scheduler under its `options["lora"]` key. Items whose/// payload resolution fails follow the same publish_error + ACK@@ -5578,6 +5749,361 @@ mod tests {})}+ /// Reports `LoadingInProgress` for one model until `loaded` is set and+ /// `Ready` for every other model; records which models were encoded.+ /// When `later_probe_delay` is set, every readiness call for the loading+ /// model after the first takes that long.+ struct LoadingModelBackend {+ loading_model: &'static str,+ loaded: AtomicBool,+ later_probe_delay: Option<Duration>,+ probes: std::sync::atomic::AtomicUsize,+ encoded_models: std::sync::Mutex<Vec<String>>,+ }++ impl LoadingModelBackend {+ fn new(loading_model: &'static str) -> Arc<Self> {+ Self::with_later_probe_delay(loading_model, None)+ }++ fn with_later_probe_delay(+ loading_model: &'static str,+ later_probe_delay: Option<Duration>,+ ) -> Arc<Self> {+ Arc::new(Self {+ loading_model,+ loaded: AtomicBool::new(false),+ later_probe_delay,+ probes: std::sync::atomic::AtomicUsize::new(0),+ encoded_models: std::sync::Mutex::new(Vec::new()),+ })+ }++ fn encoded_models(&self) -> Vec<String> {+ self.encoded_models.lock().unwrap().clone()+ }+ }++ #[async_trait::async_trait]+ impl crate::backend::InferenceBackend for LoadingModelBackend {+ fn name(&self) -> &'static str {+ "loading-model"+ }++ fn supports(&self, _model_id: &str) -> bool {+ true+ }++ async fn ensure_model_ready(+ &self,+ model_id: &str,+ ) -> Result<crate::ipc_types::EnsureModelReadyResponse, BackendError> {+ if model_id == self.loading_model && self.probes.fetch_add(1, Ordering::SeqCst) > 0 {+ if let Some(delay) = self.later_probe_delay {+ tokio::time::sleep(delay).await;+ }+ }+ let state = if model_id == self.loading_model && !self.loaded.load(Ordering::SeqCst) {+ ReadinessState::LoadingInProgress+ } else {+ ReadinessState::Ready+ };+ Ok(crate::ipc_types::EnsureModelReadyResponse {+ state,+ batch_budget: None,+ descriptor: None,+ })+ }++ async fn process_encode_batch(+ &self,+ req: ProcessEncodeBatchRequest,+ ) -> Result<BatchOutcome, BackendError> {+ self.encoded_models+ .lock()+ .unwrap()+ .push(req.model_id.clone());+ let outcomes = req+ .items+ .iter()+ .map(|item| {+ outcome(+ &item.request_id,+ item.item_index,+ Disposition::NakRetry,+ None,+ None,+ )+ })+ .collect();+ Ok(BatchOutcome {+ outcomes,+ batched_f16_multivectors: Vec::new(),+ })+ }++ async fn process_score_batch(+ &self,+ _req: ProcessScoreBatchRequest,+ ) -> Result<BatchOutcome, BackendError> {+ Err(BackendError::UnsupportedModel("score".into()))+ }++ async fn process_extract_batch(+ &self,+ _req: ProcessExtractBatchRequest,+ ) -> Result<BatchOutcome, BackendError> {+ Err(BackendError::UnsupportedModel("extract".into()))+ }+ }++ fn dispatcher_with_backend(backend: SharedBackend) -> Arc<Dispatcher> {+ let runtime_state = Arc::new(RuntimeState::new());+ Arc::new(Dispatcher::new(+ backend,+ adapter_pool_with_runtime_state(Arc::clone(&runtime_state)),+ Arc::new(crate::payload_store::LocalPayloadStore::new(+ None::<PathBuf>,+ )),+ None,+ "worker-test".into(),+ runtime_state,+ Arc::new(Mutex::new(LatencyTracker::new(200, 10))),+ TokenizerRegistry::empty(),+ None,+ None,+ None,+ None,+ BatchCancelState::default(),+ RequestCancelState::new(Duration::from_secs(60)),+ ))+ }++ fn local_group(+ request: &str,+ model: &str,+ slots: std::ops::Range<u32>,+ tx: &tokio::sync::mpsc::UnboundedSender<crate::delivery::LocalDeliveryEvent>,+ ) -> Vec<(WorkItem, Delivery)> {+ slots+ .map(|slot| {+ (+ wi(request, slot, model, "encode"),+ Delivery::Local(LocalDelivery::new(slot as usize, 0, tx.clone())),+ )+ })+ .collect()+ }++ #[tokio::test(start_paused = true)]+ async fn loading_model_group_is_parked_while_other_models_dispatch() {+ let backend = LoadingModelBackend::new("cold");+ let dispatcher = dispatcher_with_backend(backend.clone());+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();++ // Under the paused clock any wait for the load would run the+ // timeout out; parking returns without waiting.+ tokio::time::timeout(+ Duration::from_secs(1),+ dispatcher.dispatch_decoded(+ local_group("cold-req", "cold", 0..3, &tx),+ 3,+ Instant::now(),+ ),+ )+ .await+ .expect("a loading model must not hold the dispatch call");+ assert_eq!(+ dispatcher.batch_semaphore.available_permits(),+ default_max_concurrent_batches(),+ "a parked group must not hold a batch permit"+ );++ tokio::time::timeout(+ Duration::from_secs(1),+ dispatcher.dispatch_decoded(+ local_group("warm-req", "warm", 3..4, &tx),+ 1,+ Instant::now(),+ ),+ )+ .await+ .expect("a loaded model must dispatch while another model loads");+ assert_eq!(backend.encoded_models(), vec!["warm".to_string()]);++ backend.loaded.store(true, Ordering::SeqCst);+ dispatcher.join_parked_groups(Duration::from_secs(60)).await;+ assert_eq!(+ backend.encoded_models(),+ vec!["warm".to_string(), "cold".to_string()],+ "the parked group dispatches once its model is ready"+ );+ }++ #[tokio::test(start_paused = true)]+ async fn parked_group_is_naked_when_its_model_never_becomes_ready() {+ let backend = LoadingModelBackend::new("cold");+ let dispatcher = dispatcher_with_backend(backend.clone());+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();++ dispatcher+ .dispatch_decoded(+ local_group("cold-req", "cold", 0..2, &tx),+ 2,+ Instant::now(),+ )+ .await;+ dispatcher+ .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)+ .await;++ let mut retried = Vec::new();+ while let Ok(event) = rx.try_recv() {+ match event {+ crate::delivery::LocalDeliveryEvent::Retry { slot, delay_ms, .. } => {+ retried.push((slot, delay_ms));+ }+ crate::delivery::LocalDeliveryEvent::Result { slot, .. } => {+ panic!("slot {slot} settled with a result instead of a retry")+ }+ }+ }+ retried.sort_unstable();+ assert_eq!(+ retried,+ vec![(0, base_nak_delay_ms()), (1, base_nak_delay_ms())]+ );+ assert!(backend.encoded_models().is_empty());+ }++ fn retried_slots(+ rx: &mut tokio::sync::mpsc::UnboundedReceiver<crate::delivery::LocalDeliveryEvent>,+ ) -> Vec<usize> {+ let mut slots = Vec::new();+ while let Ok(event) = rx.try_recv() {+ if let crate::delivery::LocalDeliveryEvent::Retry { slot, .. } = event {+ slots.push(slot);+ }+ }+ slots.sort_unstable();+ slots+ }++ /// Far longer than any readiness deadline the tests use.+ const STALLED_PROBE: Duration = Duration::from_secs(1_000_000);++ /// A NATS delivery whose ACK, NAK and progress calls fail: it has no+ /// reply subject and its client never reaches a server.+ async fn unacknowledgeable_nats_delivery() -> Delivery {+ let client = async_nats::ConnectOptions::new()+ .retry_on_initial_connect()+ .connect("nats://127.0.0.1:1")+ .await+ .expect("an offline client needs no server");+ let message = Message {+ message: async_nats::Message {+ subject: "sie.work.test".into(),+ reply: None,+ payload: Default::default(),+ headers: None,+ status: None,+ description: None,+ length: 0,+ },+ context: async_nats::jetstream::new(client),+ };+ Delivery::Nats(message, None)+ }++ #[tokio::test(start_paused = true)]+ async fn a_failed_progress_ack_ends_the_parked_wait() {+ let slow_probe = Duration::from_secs(crate::nats_consumer::ACK_WAIT_SECS * 3);+ let backend = LoadingModelBackend::with_later_probe_delay("cold", Some(slow_probe));+ let dispatcher = dispatcher_with_backend(backend.clone());+ let group = vec![(+ wi("cold-req", 0, "cold", "encode"),+ unacknowledgeable_nats_delivery().await,+ )];++ dispatcher.dispatch_decoded(group, 1, Instant::now()).await;+ backend.loaded.store(true, Ordering::SeqCst);+ let started = tokio::time::Instant::now();+ dispatcher+ .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)+ .await;++ assert!(+ started.elapsed() < slow_probe,+ "the wait must end at the first failed progress ACK, not when readiness returns"+ );+ assert!(backend.encoded_models().is_empty());+ }++ #[tokio::test(start_paused = true)]+ async fn a_parked_readiness_call_slower_than_the_ack_wait_still_dispatches() {+ let slow_probe = Duration::from_secs(crate::nats_consumer::ACK_WAIT_SECS * 3);+ let backend = LoadingModelBackend::with_later_probe_delay("cold", Some(slow_probe));+ let dispatcher = dispatcher_with_backend(backend.clone());+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();++ dispatcher+ .dispatch_decoded(+ local_group("cold-req", "cold", 0..2, &tx),+ 2,+ Instant::now(),+ )+ .await;+ backend.loaded.store(true, Ordering::SeqCst);+ dispatcher+ .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)+ .await;++ assert_eq!(backend.encoded_models(), vec!["cold".to_string()]);+ }++ #[tokio::test(start_paused = true)]+ async fn a_stalled_readiness_call_does_not_outlive_the_parked_wait() {+ let backend = LoadingModelBackend::with_later_probe_delay("cold", Some(STALLED_PROBE));+ let dispatcher = dispatcher_with_backend(backend.clone());+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();++ dispatcher+ .dispatch_decoded(+ local_group("cold-req", "cold", 0..2, &tx),+ 2,+ Instant::now(),+ )+ .await;+ dispatcher+ .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)+ .await;++ assert_eq!(retried_slots(&mut rx), vec![0, 1]);+ }++ #[tokio::test(start_paused = true)]+ async fn shutdown_aborts_a_parked_group_that_does_not_settle_in_time() {+ let backend = LoadingModelBackend::with_later_probe_delay("cold", Some(STALLED_PROBE));+ let dispatcher = dispatcher_with_backend(backend.clone());+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();++ dispatcher+ .dispatch_decoded(+ local_group("cold-req", "cold", 0..2, &tx),+ 2,+ Instant::now(),+ )+ .await;+ dispatcher.join_parked_groups(Duration::from_secs(1)).await;++ assert_eq!(+ Arc::strong_count(&dispatcher),+ 1,+ "the aborted parked task must have released the dispatcher"+ );+ assert!(retried_slots(&mut rx).is_empty());+ }+#[test]fn releasing_cancelled_scheduled_item_clears_global_and_child_pressure() {let runtime_state = Arc::new(RuntimeState::new());diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex ea5e44f13..2e7e302d4 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -642,6 +642,10 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {let _ = h.await;}+ dispatcher+ .join_parked_groups(Duration::from_millis(DRAIN_DEADLINE_MS))+ .await;+// Wait for scheduler drain loops to finish their own final drain// window (bounded by SIE_SCHEDULER_DRAIN_DEADLINE_MS inside each// loop; default 10 s). They exit on `shutdown.wait()` which has already fired@@ -894,6 +898,10 @@ pub async fn run_local(config: WorkerConfig) -> anyhow::Result<()> {let _ = h.await;}+ dispatcher+ .join_parked_groups(Duration::from_millis(DRAIN_DEADLINE_MS))+ .await;+// Same scheduler final-drain contract as `run()` — residual items// surface to the ingest callers as shutdown "cancelled" errors instead// of JetStream redelivery.diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rsindex 8f3f77db0..b054c7abd 100644--- a/packages/sie_server_sidecar/src/nats_consumer.rs+++ b/packages/sie_server_sidecar/src/nats_consumer.rs@@ -43,6 +43,12 @@ fn max_deliver() -> i64 {.unwrap_or(DEFAULT_MAX_DELIVER)}+/// How long JetStream keeps redelivering an unacknowledged work message+/// before it dead-letters it: `max_deliver` rounds of the ACK wait.+pub(crate) fn redelivery_envelope() -> Duration {+ Duration::from_secs(ACK_WAIT_SECS.saturating_mul(max_deliver() as u64))+}+/// The larger of the durable work lifetime and configured retry envelope is the/// active-worker expiry horizon; the bounded state may evict the oldest entry/// sooner. Core NATS cancellation remains best-effort: a worker that starts or