Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(sglang): load declared LoRA adapters on demand

svonava6ae6f6c6c7ac
diff --git a/packages/sie_server/src/sie_server/adapters/_generation_base.py b/packages/sie_server/src/sie_server/adapters/_generation_base.py
index c8401bec0..3feaec396 100644
--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py
+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py
@@ -125,6 +125,15 @@ class GenerationCapacityError(GenerationError):
self.upstream_reason = upstream_reason
+class GenerationLoraLoadingError(GenerationCapacityError):
+ """A selected LoRA is loading or draining for eviction."""
+
+ code = "LORA_LOADING"
+
+ def __init__(self) -> None:
+ super().__init__("The selected LoRA is loading; retry the request", retry_after_s=1)
+
+
class GenerationDrainingError(GenerationCapacityError):
"""The generation backend is draining and cannot accept new work."""
diff --git a/packages/sie_server/src/sie_server/adapters/base.py b/packages/sie_server/src/sie_server/adapters/base.py
index feef90761..b37dff0d9 100644
--- a/packages/sie_server/src/sie_server/adapters/base.py
+++ b/packages/sie_server/src/sie_server/adapters/base.py
@@ -9,7 +9,7 @@ from pydantic import BaseModel, ConfigDict, Field
from sie_server.types.inputs import Item
if TYPE_CHECKING:
- from sie_server.adapters.lora import LoraCapability
+ from sie_server.adapters.lora import LoraCapability, LoraRuntimeConfig
from sie_server.core.inference_output import EncodeOutput, ExtractOutput, ScoreOutput
logger = logging.getLogger(__name__)
@@ -572,30 +572,27 @@ class ModelAdapter(ABC):
LoRA, else ``None``.
One accessor callers use in place of checking :meth:`supports_lora` and
- then calling the individual hooks. PEFT (in-process) is the adapter
- behind this capability; an adapter that cannot load a LoRA at runtime
- returns ``None``.
+ then calling the individual hooks. PEFT and SGLang implement this
+ capability; adapters that cannot load a LoRA at runtime return ``None``.
"""
return self if self.supports_lora() else None
def supports_hot_lora_reload(self) -> bool:
- """Return True if LoRAs can be loaded without blocking inference.
+ """Return True for background fetch and immediate ``LORA_LOADING`` retry.
- - PEFT-based adapters: True (can load in thread pool)
- - SGLang adapters: False (HTTP API blocks during load)
-
- This affects whether the server returns 503 LORA_LOADING during
- loading or blocks all requests until loading completes.
-
- Returns:
- True for non-blocking LoRA loading, False for blocking.
+ Attachment still runs under the adapter's mutation guard and can
+ briefly pause inference. False waits for loading in the caller.
"""
return False
+ def lora_runtime_config(self) -> "LoraRuntimeConfig | None":
+ """Describe engine-owned startup LoRAs, or use the ordinary PEFT preload path."""
+ return None
+
def fetch_lora(self, lora_path: str, revision: str | None = None) -> str:
"""Bring a LoRA adapter's files to one local directory, outside inference.
- Hot-reload adapters (PEFT) download and validate here, so that
+ Runtime LoRA adapters download and validate here, so that
:meth:`load_lora` only attaches from local files.
Args:
@@ -611,6 +608,9 @@ class ModelAdapter(ABC):
msg = f"{self.__class__.__name__} does not support LoRA (supports_lora=False)"
raise NotImplementedError(msg)
+ def discard_lora_source(self, lora_path: str) -> None:
+ """Release an unused temporary source view; ordinary shared caches stay intact."""
+
def load_lora(self, lora_path: str, revision: str | None = None, *, source: str | None = None) -> int:
"""Load a LoRA adapter.
diff --git a/packages/sie_server/src/sie_server/adapters/lora.py b/packages/sie_server/src/sie_server/adapters/lora.py
index cfed2c530..053aa2ba6 100644
--- a/packages/sie_server/src/sie_server/adapters/lora.py
+++ b/packages/sie_server/src/sie_server/adapters/lora.py
@@ -3,16 +3,35 @@
Groups the LoRA lifecycle an adapter exposes when it supports LoRA into one
typed capability, so callers ask ``adapter.lora_capability()`` once and use the
returned handle instead of flag-checking ``supports_lora()`` and then calling
-the individual hooks. The PEFT mixin (in-process, hot-reloadable) implements
-this capability. An adapter whose engine loads its LoRAs at launch, such as the
-SGLang embedding adapter, selects them by served name and returns ``None``.
+the individual hooks. PEFT and SGLang generation/embedding implement this
+capability. SGLang additionally describes engine-owned aliases and pinned
+startup residency; adapters without runtime loading return ``None``.
"""
from __future__ import annotations
+from dataclasses import dataclass
from typing import Protocol
+@dataclass(frozen=True)
+class LoraRuntimeConfig:
+ """Engine-owned aliases and startup residency, keyed by declared source id."""
+
+ aliases: dict[str, str]
+ preloaded: frozenset[str]
+ pinned: frozenset[str]
+ max_loaded: int
+
+
+class LoraStateUncertainError(RuntimeError):
+ """A mutation could not be rolled back; retain its capacity until model reload."""
+
+
+class LoraUnavailableError(ValueError):
+ """The declared adapter is absent or is draining for eviction."""
+
+
class LoraCapability(Protocol):
"""The LoRA lifecycle exposed by a LoRA-capable adapter.
@@ -22,8 +41,11 @@ class LoraCapability(Protocol):
"""
def supports_hot_lora_reload(self) -> bool:
- """True if LoRAs can be loaded without blocking inference (PEFT), False
- if the load blocks all requests (SGLang HTTP).
+ """True when fetch can run in the background before a serialized attach.
+
+ Attach may still briefly pause an engine's scheduler. This flag enables
+ the immediate LORA_LOADING response; it does not promise zero impact
+ on concurrent inference.
"""
def fetch_lora(self, lora_path: str, revision: str | None = None) -> str:
@@ -32,6 +54,9 @@ class LoraCapability(Protocol):
Hot-reload adapters do their network and disk I/O here, outside inference.
"""
+ def discard_lora_source(self, lora_path: str) -> None:
+ """Release temporary fetched files only if no attached adapter can use them."""
+
def load_lora(self, lora_path: str, revision: str | None = None, *, source: str | None = None) -> int:
"""Load a LoRA adapter (optionally at a pinned 40-hex commit SHA), from
``source`` when :meth:`fetch_lora` already brought it local; return its
diff --git a/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py b/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py
index 240816bad..0745286fd 100644
--- a/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py
+++ b/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py
@@ -443,6 +443,9 @@ class PEFTLoRAMixin:
if self._active_lora == lora_name:
self.set_active_lora(None)
+ # PEFT's get_base_model consults active_peft_config, which disappears
+ # when delete_adapter removes the final adapter. Capture it first.
+ base_model = self._peft_model.get_base_model()
# Delete the adapter
self._peft_model.delete_adapter(self._get_peft_adapter_name(lora_name))
self._loaded_loras.discard(lora_name)
@@ -451,8 +454,7 @@ class PEFTLoRAMixin:
# If no LoRAs remain, unwrap the model
if not self._loaded_loras:
logger.debug("No LoRAs remaining, unwrapping PeftModel")
- # Get the base model back
- base_model = self._peft_model.get_base_model()
+ _unwrap_lora_layers(base_model)
self._model = base_model
del self._peft_model
self._peft_model = None
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_lora.py b/packages/sie_server/src/sie_server/adapters/sglang/_lora.py
new file mode 100644
index 000000000..07c76f856
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/sglang/_lora.py
@@ -0,0 +1,430 @@
+"""Declared-source LoRA loading and request leases for an isolated SGLang engine."""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import json
+import os
+import re
+import tempfile
+import threading
+from collections.abc import AsyncGenerator, AsyncIterator, Callable, Iterator
+from pathlib import Path
+from typing import Any, cast
+
+import requests
+from huggingface_hub import snapshot_download
+from safetensors import safe_open
+
+from sie_server.adapters._generation_base import (
+ GenerationChunk,
+ GenerationInvalidRequestError,
+ GenerationLoraLoadingError,
+)
+from sie_server.adapters.lora import LoraRuntimeConfig, LoraStateUncertainError, LoraUnavailableError
+from sie_server.adapters.peft_lora_mixin import is_lora_weight_key
+
+_FILES = ["adapter_config.json", "adapter_model.safetensors"]
+
+
+def leased_generation(
+ method: Callable[..., AsyncIterator[GenerationChunk]],
+) -> Callable[..., AsyncIterator[GenerationChunk]]:
+ """Hold a LoRA lease until completion, cancellation, exception, or iterator close."""
+
+ @functools.wraps(method)
+ async def wrapped(self: Any, *args: Any, **kwargs: Any) -> AsyncIterator[GenerationChunk]:
+ name = kwargs.get("lora_path")
+ with self.lora_request(name, n=kwargs.get("n"), best_of=kwargs.get("best_of")) as engine_name:
+ kwargs["lora_path"] = engine_name
+ iterator = cast("AsyncGenerator[GenerationChunk, None]", method(self, *args, **kwargs))
+ async with contextlib.aclosing(iterator) as chunks:
+ async for chunk in chunks:
+ yield chunk
+
+ return wrapped
+
+
+def leased_encode(method: Callable[..., Any]) -> Callable[..., Any]:
+ """Keep an embedding request's selected adapter resident until its backend call returns."""
+
+ @functools.wraps(method)
+ def wrapped(self: Any, *args: Any, **kwargs: Any) -> Any:
+ with self._lora.lease(self._active_lora):
+ return method(self, *args, **kwargs)
+
+ return wrapped
+
+
+class SGLangLoraMixin:
+ """Expose the shared engine lifecycle through ModelAdapter's capability seam."""
+
+ _lora: SGLangLoraManager
+
+ @contextlib.contextmanager
+ def lora_request(
+ self, name: str | None, *, n: int | None = None, best_of: int | None = None
+ ) -> Iterator[str | None]:
+ """Hold one selection through the entire native or proxied request lifetime."""
+ if name is not None and self._lora.deferred and any((value or 1) > 1 for value in (n, best_of)):
+ raise GenerationInvalidRequestError(
+ "lora_adapter", "Deferred LoRA generation supports only n=1 and best_of=1"
+ )
+ try:
+ with self._lora.lease(name) as engine_name:
+ yield engine_name
+ except LoraUnavailableError as error:
+ raise GenerationLoraLoadingError from error
+
+ def supports_lora(self) -> bool:
+ return bool(self._lora.aliases)
+
+ def supports_hot_lora_reload(self) -> bool:
+ return True
+
+ def lora_runtime_config(self) -> LoraRuntimeConfig:
+ return self._lora.runtime_config()
+
+ def fetch_lora(self, lora_path: str, revision: str | None = None) -> str:
+ return self._lora.fetch(lora_path, revision)
+
+ def discard_lora_source(self, lora_path: str) -> None:
+ self._lora.discard_source(lora_path)
+
+ def load_lora(self, lora_path: str, revision: str | None = None, *, source: str | None = None) -> int:
+ return self._lora.load(lora_path, revision, source=source)
+
+ def unload_lora(self, lora_name: str) -> None:
+ self._lora.unload(lora_name)
+
+
+def validate_preload_loras(paths: Any, preload: Any) -> None:
+ """Validate the optional selector against the resolved profile's source map."""
+ if preload is None:
+ return
+ if not isinstance(paths, dict) or not paths:
+ raise ValueError("preload_loras requires a nonempty lora_paths map")
+ if not isinstance(preload, list) or any(not isinstance(name, str) or not name for name in preload):
+ raise ValueError("preload_loras must be a list of declared served names")
+ if len(preload) != len(set(preload)) or not set(preload).issubset(paths):
+ raise ValueError("preload_loras must contain unique names declared in lora_paths")
+
+
+class SGLangLoraManager:
+ """Keep source authorization, engine names, and residency in one place.
+
+ Downloads happen before the worker's mutation lock. HTTP mutation is
+ synchronous and bounded; SGLang may pause scheduling while attaching.
+ Generation streams acquire per-adapter leases, because they bypass the
+ embedding worker's dispatch lock. An eviction stops new leases before
+ draining old ones, then asks the engine to remove the adapter.
+ """
+
+ def __init__(
+ self,
+ paths: dict[str, str] | None,
+ *,
+ preload: list[str] | None,
+ revisions: dict[str, str | None] | None,
+ max_rank: int | None,
+ target_modules: list[str] | None,
+ max_per_batch: int,
+ server_url: Callable[[], str | None],
+ max_loaded: int | None = None,
+ mutation_timeout_s: float = 60,
+ ) -> None:
+ validate_preload_loras(paths, preload)
+ self.aliases = dict(paths or {})
+ if any(
+ not isinstance(key, str) or not key or not isinstance(value, str) or not value
+ for key, value in self.aliases.items()
+ ):
+ raise ValueError("lora_paths must map nonempty served names to declared source ids")
+ if any(not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", alias) for alias in self.aliases):
+ raise ValueError("LoRA served names may contain only letters, digits, dots, underscores, and hyphens")
+ # Reject ambiguous aliases before source-id requests and served-name
+ # requests can select different adapters.
+ if any(alias in self.aliases.values() and alias != source for alias, source in self.aliases.items()):
+ raise ValueError("A LoRA served name cannot shadow another declared source id")
+ self.revisions = revisions or {}
+ self.preloaded = frozenset(self.aliases[name] for name in (self.aliases if preload is None else preload))
+ self.deferred = set(self.aliases.values()) - self.preloaded
+ self.max_loaded = max_loaded if max_loaded is not None else int(os.environ.get("SIE_MAX_LORAS_PER_MODEL", "10"))
+ if isinstance(self.max_loaded, bool) or not isinstance(self.max_loaded, int) or self.max_loaded < 1:
+ raise ValueError("SIE_MAX_LORAS_PER_MODEL must be positive")
+ if isinstance(max_per_batch, bool) or not isinstance(max_per_batch, int) or max_per_batch < 1:
+ raise ValueError("max_loras_per_batch must be a positive integer")
+ if self.aliases and (max_per_batch > self.max_loaded or len(self.preloaded) > self.max_loaded):
+ raise ValueError("LoRA batch capacity and preload count must not exceed SIE_MAX_LORAS_PER_MODEL")
+ if self.deferred and len(self.preloaded) == self.max_loaded:
+ raise ValueError("Deferred LoRAs require at least one slot not occupied by pinned preloads")
+ if self.deferred and (max_rank is None or not target_modules):
+ raise ValueError("Deferred LoRAs require max_lora_rank and lora_target_modules before engine launch")
+ if max_rank is not None and (isinstance(max_rank, bool) or not isinstance(max_rank, int) or max_rank < 1):
+ raise ValueError("max_lora_rank must be a positive integer")
+ if target_modules is not None and (
+ not isinstance(target_modules, list)
+ or not target_modules
+ or any(not isinstance(name, str) or not name for name in target_modules)
+ or len(set(target_modules)) != len(target_modules)
+ or ("all" in target_modules and target_modules != ["all"])
+ ):
+ raise ValueError("lora_target_modules must contain unique module names, or only 'all'")
+ self.max_rank = max_rank
+ self.target_modules = target_modules
+ self.max_per_batch = max_per_batch
+ self._server_url = server_url
+ self._timeout = mutation_timeout_s
+ self._names = {source: name for name, source in reversed(list(self.aliases.items()))}
+ self._condition = threading.Condition()
+ self._mutation_lock = threading.Lock()
+ self._loaded: set[str] = set()
+ self._draining: set[str] = set()
+ self._uncertain: set[str] = set()
+ self._leases: dict[str, int] = {}
+ self._snapshots: dict[str, tempfile.TemporaryDirectory[str]] = {}
+ self._closed = False
+
+ def runtime_config(self) -> LoraRuntimeConfig:
+ return LoraRuntimeConfig(self.aliases, self.preloaded, self.preloaded, self.max_loaded)
+
+ def source(self, name: str) -> str:
+ source = self.aliases.get(name, name)
+ if source not in self._names:
+ raise ValueError("This LoRA adapter is not declared for the loaded profile")
+ return source
+
+ def engine_name(self, name: str) -> str:
+ return self._names[self.source(name)]
+
+ @property
+ def available(self) -> list[str]:
+ with self._condition:
+ return [
+ name
+ for name, source in self.aliases.items()
+ if source in self._loaded and source not in self._draining and source not in self._uncertain
+ ]
+
+ def fetch(self, name: str, revision: str | None = None) -> str:
+ source = self.source(name)
+ declared_revision = self.revisions.get(source)
+ if declared_revision is not None and revision not in (None, declared_revision):
+ raise ValueError("LoRA revision does not match the declared immutable revision")
+ with self._condition:
+ if self._closed:
+ raise RuntimeError("The LoRA engine was unloaded during fetch")
+ if source in self._snapshots:
+ return self._snapshots[source].name
+ directory = Path(source)
+ if not directory.is_dir():
+ directory = Path(snapshot_download(source, revision=declared_revision or revision, allow_patterns=_FILES))
+ config = json.loads((directory / _FILES[0]).read_text())
+ if not isinstance(config, dict) or config.get("peft_type") != "LORA":
+ raise ValueError("SGLang requires a PEFT LoRA adapter")
+ # Runtime adapters must not replace shared base weights or rely on
+ # training-time transforms that SGLang does not implement.
+ if (
+ any(
+ config.get(key)
+ for key in (
+ "modules_to_save",
+ "layer_replication",
+ "megatron_config",
+ "trainable_token_indices",
+ "use_dora",
+ "rank_pattern",
+ "alpha_pattern",
+ "use_rslora",
+ )
+ )
+ or config.get("bias", "none") != "none"
+ ):
+ raise ValueError("SGLang runtime LoRA requires adapter-only weights without base-model transforms")
+ initializer = config.get("init_lora_weights", True)
+ if not isinstance(initializer, bool) and initializer not in ("gaussian", "eva", "orthogonal"):
+ raise ValueError("LoRA initialization rewrites base weights that SGLang cannot reproduce")
+ rank = config.get("r")
+ if isinstance(rank, bool) or not isinstance(rank, int) or rank < 1 or (self.max_rank and rank > self.max_rank):
+ raise ValueError("LoRA rank exceeds the engine's configured capacity")
+ modules = config.get("target_modules")
+ if not isinstance(modules, list) or not modules or any(not isinstance(module, str) for module in modules):
+ raise ValueError("SGLang LoRA target_modules must be an explicit list")
+ if self.target_modules and self.target_modules != ["all"] and not set(modules).issubset(self.target_modules):
+ raise ValueError("LoRA targets modules outside the engine's configured capacity")
+ with safe_open(str(directory / _FILES[1]), framework="pt") as handle:
+ names = handle.keys()
+ if not names or any(
+ not is_lora_weight_key(name) or not name.endswith(("lora_A.weight", "lora_B.weight")) for name in names
+ ):
+ raise ValueError("LoRA weights contain parameters outside the adapter")
+ # SGLang's generic loader globs the whole directory. A Hub cache or
+ # operator directory can also contain unrelated weights. Expose only
+ # the validated pair, and keep it alive until confirmed engine removal.
+ snapshot = tempfile.TemporaryDirectory(prefix="sie-sglang-lora-")
+ try:
+ for filename in _FILES:
+ (Path(snapshot.name) / filename).symlink_to((directory / filename).resolve())
+ with self._condition:
+ if self._closed:
+ raise RuntimeError("The LoRA engine was unloaded during fetch")
+ existing = self._snapshots.get(source)
+ if existing is None:
+ self._snapshots[source] = snapshot
+ return snapshot.name
+ snapshot.cleanup()
+ return existing.name
+ except BaseException:
+ snapshot.cleanup()
+ raise
+
+ def _release_source(self, source: str) -> None:
+ with self._condition:
+ snapshot = self._snapshots.pop(source, None)
+ if snapshot is not None:
+ snapshot.cleanup()
+
+ def discard_source(self, name: str) -> None:
+ """Drop an unused fetched view after a completed failure or stale load."""
+ source = self.source(name)
+ with self._condition:
+ if source in self._loaded or source in self._uncertain:
+ return
+ snapshot = self._snapshots.pop(source, None)
+ if snapshot is not None:
+ snapshot.cleanup()
+
+ def close(self) -> None:
+ """Release validated source views after the engine process has stopped."""
+ self.stop_mutations()
+ with self._condition:
+ snapshots = list(self._snapshots.values())
+ self._snapshots.clear()
+ self._loaded.clear()
+ for snapshot in snapshots:
+ snapshot.cleanup()
+
+ def stop_mutations(self) -> None:
+ """Join bounded HTTP mutations before the child releases its port.
+
+ Generation has no worker executor to join at model teardown. Closing
+ this gate before stopping the child prevents an old POST from reaching
+ a replacement engine that reuses the port.
+ """
+ with self._condition:
+ self._closed = True
+ self._condition.notify_all()
+ with self._mutation_lock:
+ pass
+
+ def launch_args(self) -> list[str]:
+ with self._condition:
+ self._closed = False
+ if not self.aliases:
+ return []
+ args = [
+ "--enable-lora",
+ "--max-loras-per-batch",
+ str(self.max_per_batch),
+ "--max-loaded-loras",
+ str(self.max_loaded),
+ ]
+ if self.max_rank is not None:
+ args.extend(["--max-lora-rank", str(self.max_rank)])
+ if self.target_modules:
+ args.extend(["--lora-target-modules", *self.target_modules])
+ if self.preloaded:
+ args.append("--lora-paths")
+ args.extend(f"{self._names[source]}={self.fetch(source)}" for source in sorted(self.preloaded))
+ return args
+
+ def started(self) -> None:
+ with self._condition:
+ self._loaded = set(self.preloaded)
+ self._draining.clear()
+ self._uncertain.clear()
+
+ def _mutate(self, endpoint: str, payload: dict[str, Any]) -> None:
+ with self._mutation_lock:
+ with self._condition:
+ if self._closed:
+ raise RuntimeError("The LoRA engine is unloading")
+ url = self._server_url()
+ if url is None:
+ raise RuntimeError("SGLang is not running")
+ response = requests.post(f"{url}/{endpoint}", json=payload, timeout=self._timeout)
+ response.raise_for_status()
+ body = response.json()
+ if not isinstance(body, dict) or body.get("success") is not True:
+ # Backend diagnostics may contain private filesystem or repo paths.
+ raise RuntimeError("SGLang refused the LoRA mutation")
+
+ def load(self, name: str, revision: str | None = None, *, source: str | None = None) -> int:
+ declared = self.source(name)
+ directory = source or self.fetch(declared, revision)
+ with self._condition:
+ if declared in self._uncertain:
+ raise LoraStateUncertainError("LoRA state requires a model reload")
+ if declared in self._loaded:
+ return 0
+ try:
+ self._mutate("load_lora_adapter", {"lora_name": self._names[declared], "lora_path": directory})
+ except Exception:
+ try:
+ self._mutate("unload_lora_adapter", {"lora_name": self._names[declared]})
+ except Exception as rollback_error:
+ with self._condition:
+ self._uncertain.add(declared)
+ raise LoraStateUncertainError(
+ "LoRA attach rollback could not be confirmed; reload the model"
+ ) from rollback_error
+ self._release_source(declared)
+ raise
+ with self._condition:
+ self._loaded.add(declared)
+ # Engine preallocates GPU LoRA buffers at startup; do not double count.
+ return 0
+
+ @contextlib.contextmanager
+ def lease(self, name: str | None) -> Iterator[str | None]:
+ if name is None:
+ yield None
+ return
+ declared = self.source(name)
+ with self._condition:
+ if (
+ self._closed
+ or declared not in self._loaded
+ or declared in self._draining
+ or declared in self._uncertain
+ ):
+ raise LoraUnavailableError("The declared LoRA is loading or draining; retry the request")
+ self._leases[declared] = self._leases.get(declared, 0) + 1
+ try:
+ yield self._names[declared]
+ finally:
+ with self._condition:
+ self._leases[declared] -= 1
+ self._condition.notify_all()
+
+ def unload(self, name: str) -> None:
+ declared = self.source(name)
+ if declared in self.preloaded:
+ raise ValueError("Startup LoRAs are pinned and cannot be evicted")
+ with self._condition:
+ self._draining.add(declared)
+ self._condition.notify_all()
+ if not self._condition.wait_for(lambda: self._leases.get(declared, 0) == 0, timeout=self._timeout):
+ self._draining.discard(declared)
+ raise TimeoutError("Active LoRA requests did not drain before eviction")
+ try:
+ self._mutate("unload_lora_adapter", {"lora_name": self._names[declared]})
+ except Exception as error:
+ with self._condition:
+ self._uncertain.add(declared)
+ raise LoraStateUncertainError("LoRA removal could not be confirmed; reload the model") from error
+ with self._condition:
+ self._loaded.discard(declared)
+ self._draining.discard(declared)
+ self._release_source(declared)
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
index ba5cfd813..e28e21ce8 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
@@ -35,12 +35,12 @@ from sie_server.adapters._base_adapter import BaseAdapter
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecision
from sie_server.adapters.sglang import _server
+from sie_server.adapters.sglang._lora import SGLangLoraManager, SGLangLoraMixin, leased_encode
from sie_server.adapters.sglang._memory import SGLangMemoryBudget
from sie_server.core.inference_output import EncodeOutput
from sie_server.core.tokenizer import load_tokenizer
if TYPE_CHECKING:
- from sie_server.adapters.lora import LoraCapability
from sie_server.types.inputs import Item
logger = logging.getLogger(__name__)
@@ -84,7 +84,7 @@ def _resolve_embed_concurrency(configured: int | None) -> int:
return _DEFAULT_EMBED_CONCURRENCY
-class SGLangEmbeddingAdapter(BaseAdapter):
+class SGLangEmbeddingAdapter(SGLangLoraMixin, BaseAdapter):
"""Adapter for LLM embedding models using SGLang HTTP server backend.
SGLang pre-allocates GPU memory for the KV cache, providing stable memory
@@ -144,6 +144,11 @@ class SGLangEmbeddingAdapter(BaseAdapter):
append_eos: bool = False,
lora_paths: dict[str, str] | None = None,
max_loras_per_batch: int = 8,
+ max_loaded_loras: int | None = None,
+ preload_loras: list[str] | None = None,
+ lora_revisions: dict[str, str | None] | None = None,
+ max_lora_rank: int | None = None,
+ lora_target_modules: list[str] | None = None,
dense_dim: int | None = None,
startup_timeout_s: float | None = None,
embed_concurrency: int | None = None,
@@ -223,6 +228,16 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._append_eos = append_eos
self._eos_token = "" # Resolved from the model tokenizer in load() when append_eos
self._lora_paths = lora_paths or {}
+ self._lora = SGLangLoraManager(
+ lora_paths,
+ preload=preload_loras,
+ revisions=lora_revisions,
+ max_rank=max_lora_rank,
+ target_modules=lora_target_modules,
+ max_per_batch=max_loras_per_batch,
+ max_loaded=max_loaded_loras,
+ server_url=lambda: self._server_url,
+ )
self._max_loras_per_batch = max_loras_per_batch
self._startup_timeout_s = _server.resolve_startup_timeout(startup_timeout_s)
self._embed_concurrency = _resolve_embed_concurrency(embed_concurrency)
@@ -279,7 +294,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
These are the names that can be passed to encode(lora=...).
"""
- return list(self._lora_paths.keys())
+ return self._lora.available
@property
def lora_enabled(self) -> bool:
@@ -363,23 +378,12 @@ class SGLangEmbeddingAdapter(BaseAdapter):
if self._revision is not None:
cmd.extend(["--revision", self._revision])
- # LoRA configuration for the SGLang server.
- if self._lora_paths:
- cmd.append("--enable-lora")
- lora_path_str = ",".join(f"{name}={path}" for name, path in self._lora_paths.items())
- cmd.extend(["--lora-paths", lora_path_str])
- cmd.extend(["--max-loras-per-batch", str(self._max_loras_per_batch)])
- logger.info(
- "LoRA enabled with %d adapters: %s",
- len(self._lora_paths),
- list(self._lora_paths.keys()),
- )
-
# The port (and, once opened, the log fd) belong to this adapter from
# the reservation above onward, so every raise below hands them back
# rather than leaking one slot of the 100-port span per attempt: a full
# /tmp in open_output_log, a failed exec, or a cancelled load included.
try:
+ cmd.extend(self._lora.launch_args())
cmd.extend(self._memory_budget.launch_args(device_indices[0]))
# Only a group rendezvouses, so width one reserves nothing and its
# launch argv is unchanged. Left to the engine it picks a random
@@ -393,8 +397,16 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._nccl_port = self._reserved_nccl_port
cmd.extend(["--nccl-port", str(self._nccl_port)])
self._output_file = _server.open_output_log()
+ extra_env = None
+ if self._lora.deferred:
+ extra_env = {
+ "SIE_SGLANG_LORA_COMPAT": "1",
+ "PYTHONPATH": os.pathsep.join(
+ filter(None, [str(Path(__file__).parent / "_compat"), os.environ.get("PYTHONPATH", "")])
+ ),
+ }
self._process = _server.launch_sglang_server(
- cmd, device_indices=device_indices, output_file=self._output_file
+ cmd, device_indices=device_indices, output_file=self._output_file, extra_env=extra_env
)
if not _server.wait_for_server(
@@ -413,6 +425,8 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._abort_failed_load()
raise
+ self._lora.started()
+
# Concurrent-POST fan-out: a keep-alive session with a connection pool
# sized to the concurrency and a matching thread pool, so a sharded
# ``encode`` keeps ``embed_concurrency`` requests in flight against
@@ -446,6 +460,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
log, and clear _server_url/_device so the adapter does not look "loaded".
Mirrors the generation siblings (SGLang + MLX).
"""
+ self._lora.stop_mutations()
_server.terminate_process(self._process)
self._process = None
_server.release_port(self._port)
@@ -457,11 +472,13 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._nccl_port = None
self._port = None
self._server_url = None
+ self._lora.close()
self._device = None
self._cleanup_output_log()
def unload(self) -> None:
"""Unload the model by stopping SGLang server subprocess."""
+ self._lora.stop_mutations()
if self._post_executor is not None:
self._post_executor.shutdown(wait=False)
self._post_executor = None
@@ -484,6 +501,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._nccl_port = None
self._port = None
self._server_url = None
+ self._lora.close()
self._device = None
self._dense_dim = self._configured_dense_dim
self._cleanup_output_log()
@@ -513,6 +531,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
device_total_bytes=device_total_bytes,
)
+ @leased_encode
def encode(
self,
items: list[Item],
@@ -544,10 +563,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._check_loaded()
# Validate active LoRA if specified
- lora = self._active_lora
- if lora is not None and lora not in self._lora_paths:
- msg = f"LoRA '{lora}' is not loaded"
- raise ValueError(msg)
+ lora = self._lora.engine_name(self._active_lora) if self._active_lora is not None else None
self._validate_output_types(output_types)
@@ -603,7 +619,9 @@ class SGLangEmbeddingAdapter(BaseAdapter):
# ``_embed_texts`` fans the batch out into ``embed_concurrency``
# concurrent POSTs so SGLang's continuous batcher stays fed (the serving
# loop is single-threaded, so a lone blocking POST under-drives it).
- model_name = lora if lora is not None else "default"
+ # Pinned SGLang resolves LoRA only from base:adapter or explicit
+ # lora_path. A bare served alias silently selects the base model.
+ model_name = f"default:{lora}" if lora is not None else "default"
non_empty_embeddings = self._embed_texts(non_empty_texts, model_name)
dense_dim = self._validate_or_set_dense_dim(non_empty_embeddings)
@@ -918,25 +936,6 @@ class SGLangEmbeddingAdapter(BaseAdapter):
"""
return self._max_concurrent_dispatch
- def supports_lora(self) -> bool:
- """Return True if LoRA adapters are configured."""
- return bool(self._lora_paths)
-
- def lora_capability(self) -> LoraCapability | None:
- """Return ``None``: the engine loads its LoRA adapters at launch and cannot load or unload one later.
-
- A LoRA is selected by its served name through :meth:`set_active_lora`.
- """
- return None
-
- def supports_hot_lora_reload(self) -> bool:
- """Return False - SGLang blocks during LoRA loading.
-
- SGLang's /load_lora_adapter endpoint blocks the server until loading
- completes. This is not true hot-reload like PEFT provides.
- """
- return False
-
def set_active_lora(self, lora_name: str | None) -> None:
"""Set the active LoRA for the next encode() call.
@@ -949,7 +948,6 @@ class SGLangEmbeddingAdapter(BaseAdapter):
Raises:
ValueError: ``lora_name`` is not one of the served names the engine launched with.
"""
- if lora_name is not None and lora_name not in self._lora_paths:
- msg = f"LoRA '{lora_name}' is not loaded"
- raise ValueError(msg)
+ with self._lora.lease(lora_name):
+ pass
self._active_lora = lora_name
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
index 22e601ee0..92b09deed 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -57,6 +57,7 @@ from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision
from sie_server.adapters.sglang import _server
from sie_server.adapters.sglang._compat.sie_thinking_budget import PARAM as THINKING_BUDGET_PARAM
from sie_server.adapters.sglang._compat.sie_thinking_budget import PROCESSOR_REFERENCE as THINKING_BUDGET_PROCESSOR
+from sie_server.adapters.sglang._lora import SGLangLoraManager, SGLangLoraMixin, leased_generation
from sie_server.adapters.sglang._memory import SGLangMemoryBudget
from sie_server.observability.generation_diagnostics import GenerationStreamTimer
from sie_server.types.grammar import (
@@ -450,7 +451,7 @@ def _translate_to_mlx_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]:
return {k: v for k, v in kwargs.items() if k in _MLX_PASSTHROUGH_KWARGS}
-class SGLangGenerationAdapter(GenerationAdapter):
+class SGLangGenerationAdapter(SGLangLoraMixin, GenerationAdapter):
"""Streaming SGLang generation adapter.
Lifecycle is identical to :class:`SGLangEmbeddingAdapter`: one subprocess
@@ -526,6 +527,11 @@ class SGLangGenerationAdapter(GenerationAdapter):
# adapters in one batch (SGLang ``--max-loras-per-batch``).
lora_paths: dict[str, str] | None = None,
max_loras_per_batch: int = 4,
+ max_loaded_loras: int | None = None,
+ preload_loras: list[str] | None = None,
+ lora_revisions: dict[str, str | None] | None = None,
+ max_lora_rank: int | None = None,
+ lora_target_modules: list[str] | None = None,
# Tensor-parallel width. One is every existing profile and keeps the
# launch argv byte-identical. Above one, this adapter owns that many
# whole accelerators for the life of the load, which is an exclusive
@@ -660,6 +666,35 @@ class SGLangGenerationAdapter(GenerationAdapter):
tensor_parallel_size=self._tensor_parallel_size,
)
self._lora_paths = dict(lora_paths or {})
+ self._lora = SGLangLoraManager(
+ lora_paths,
+ preload=preload_loras,
+ revisions=lora_revisions,
+ max_rank=max_lora_rank,
+ target_modules=lora_target_modules,
+ max_per_batch=max_loras_per_batch,
+ max_loaded=max_loaded_loras,
+ server_url=lambda: self._server_url,
+ )
+ if self._lora.deferred and any(
+ any(arg.partition("=")[0] == flag for arg in self._extra_launch_args)
+ and _mamba_strategy_value(self._extra_launch_args, flag) != "1"
+ for flag in ("--tokenizer-worker-num", "--dp-size", "--data-parallel-size")
+ ):
+ raise ValueError("Deferred LoRAs require one tokenizer worker and one data-parallel worker")
+ if self._lora.aliases and any(
+ arg.partition("=")[0]
+ in {
+ "--enable-lora",
+ "--lora-paths",
+ "--max-loras-per-batch",
+ "--max-loaded-loras",
+ "--max-lora-rank",
+ "--lora-target-modules",
+ }
+ for arg in self._extra_launch_args
+ ):
+ raise ValueError("Configure LoRA capacity and sources through the profile, not extra_launch_args")
self._max_loras_per_batch = max_loras_per_batch
self._process: subprocess.Popen[bytes] | None = None
@@ -942,11 +977,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
# Multi-LoRA serving: one base, N adapters, per-request selection via
# ``sampling_params["lora_path"]``. Only emitted when the profile
# declared adapters, so non-LoRA deployments are byte-identical.
- if self._lora_paths:
- cmd.append("--enable-lora")
- cmd.extend(["--max-loras-per-batch", str(self._max_loras_per_batch)])
- cmd.append("--lora-paths")
- cmd.extend(f"{served_name}={path}" for served_name, path in self._lora_paths.items())
+ cmd.extend(self._lora.launch_args())
cmd.extend(self._extra_launch_args)
self._output_file = _server.open_output_log()
@@ -959,6 +990,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
# A100-40GB. Set unconditionally when speculative is on — the env var
# is a no-op when sglang doesn't see speculative args.
extra_env: dict[str, str] = dict(self._extra_env)
+ if self._lora.deferred:
+ extra_env["SIE_SGLANG_LORA_COMPAT"] = "1"
if self._speculative and self._speculative.get("enabled"):
extra_env["SGLANG_ENABLE_SPEC_V2"] = "1"
# The pair is required: setting ``SGLANG_ENABLE_SPEC_V2=1``
@@ -1022,6 +1055,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
# Build the error before `load`'s abort deletes the log it reads.
raise _server.startup_failure_error(self._output_file, crash_exit_code=crash_exit_code)
+ self._lora.started()
+
# Best-effort runtime verification that the
# ``--grammar-backend`` flag actually took effect. SGLang's
# exact startup-log token varies across versions; we scan for
@@ -1048,6 +1083,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
log, and clear _server_url/_device so the adapter does not look "loaded"
(_check_loaded() gates only on _server_url). Mirrors the MLX sibling.
"""
+ self._lora.stop_mutations()
_server.terminate_process(self._process)
self._process = None
_server.release_port(self._port)
@@ -1059,6 +1095,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
self._nccl_port = None
self._port = None
self._server_url = None
+ self._lora.close()
self._device = None
self._cleanup_output_log()
@@ -1331,6 +1368,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
logger.warning("aclose_client() failed: %s", exc)
def unload(self) -> None:
+ self._lora.stop_mutations()
if self._http_client is not None:
client = self._http_client
self._http_client = None
@@ -1388,6 +1426,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
self._nccl_port = None
self._port = None
self._server_url = None
+ self._lora.close()
self._device = None
self._cleanup_output_log()
@@ -1497,6 +1536,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
)
return self._http_client
+ @leased_generation
async def generate(
self,
prompt: str,
diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.py
index ee40c6487..0a348d869 100644
--- a/packages/sie_server/src/sie_server/config/model.py
+++ b/packages/sie_server/src/sie_server/config/model.py
@@ -1285,6 +1285,22 @@ class ModelConfig(BaseModel):
parent=self.profiles[profile.extends] if profile.extends is not None else None,
)
+ for name in self.profiles:
+ loadtime = self._resolve_profile_uncached(name).loadtime
+ if "preload_loras" not in loadtime:
+ continue
+ preload = loadtime["preload_loras"]
+ paths = loadtime.get("lora_paths")
+ if (
+ not isinstance(paths, dict)
+ or not paths
+ or not isinstance(preload, list)
+ or any(not isinstance(alias, str) or not alias for alias in preload)
+ or len(preload) != len(set(preload))
+ or not set(preload).issubset(paths)
+ ):
+ raise ValueError(f"Profile '{name}' preload_loras must contain unique declared lora_paths names")
+
return self
@model_validator(mode="after")
diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.py
index c4cb8a26c..c22529655 100644
--- a/packages/sie_server/src/sie_server/core/loader.py
+++ b/packages/sie_server/src/sie_server/core/loader.py
@@ -549,6 +549,7 @@ def load_adapter(
default_compute_precision: ComputePrecision = "float16",
attention_backend: AttentionBackend = "auto",
verified_serving_artifact: VerifiedServingArtifact | None = None,
+ max_loras_per_model: int | None = None,
) -> ModelAdapter:
"""Load and instantiate a model adapter.
@@ -639,6 +640,10 @@ def load_adapter(
budget = config.resolve_profile("default").kv_budget_tokens
if budget is not None:
adapter_kwargs["kv_budget_tokens"] = budget
+ if "lora_revisions" in constructor_parameters:
+ adapter_kwargs["lora_revisions"] = config.lora_revisions()
+ if "max_loaded_loras" in constructor_parameters and max_loras_per_model is not None:
+ adapter_kwargs["max_loaded_loras"] = max_loras_per_model
for keyword, dim in (
("sparse_dim", config.dims.get("sparse")),
("multivector_dim", config.dims.get("multivector")),
@@ -841,9 +846,9 @@ def _build_adapter_kwargs(
# Adapter constructors take ``lora_paths`` as served-name -> bare path/id
# (the sglang ``--lora-paths`` shape). A pinned ``{id, revision}`` value
# (#2113) is a *config* spelling: collapse it to the bare id here so no
- # constructor ever sees the mapping. The revision itself is honored on the
- # hot-reload preload path (``ModelLoader``), which rejects pins on adapters
- # that cannot apply them.
+ # constructor ever sees the mapping. Capable constructors receive the
+ # separate source-to-revision map above; the PEFT preload path receives
+ # each revision directly. ModelLoader rejects adapters unable to honor pins.
lora_paths = kwargs.get("lora_paths")
if isinstance(lora_paths, Mapping):
kwargs["lora_paths"] = {
diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.py
index 3eb5ab796..e2893e12f 100644
--- a/packages/sie_server/src/sie_server/core/model_loader.py
+++ b/packages/sie_server/src/sie_server/core/model_loader.py
@@ -12,6 +12,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any
from sie_server.adapters.base import ModelAdapter
+from sie_server.adapters.lora import LoraRuntimeConfig
from sie_server.config.model import ModelConfig, ProfileAdaptiveBatching, lora_entry_ref
from sie_server.config.serving_artifacts import (
VerifiedServingArtifact,
@@ -81,6 +82,8 @@ class LoadedLora:
memory_bytes: int = 0 # Memory footprint of this LoRA
peft_model: Any | None = None # PeftModel instance (PEFT adapters only)
loading: bool = False # True while async loading is in progress
+ pinned: bool = False # Engine startup adapters are never LRU-evicted
+ unloading: bool = False # Stop new requests before draining existing ones
@dataclass
@@ -105,6 +108,7 @@ class LoadedModel:
loras: OrderedDict[str, LoadedLora] = field(default_factory=OrderedDict)
max_loras: int = DEFAULT_MAX_LORAS
lora_failures: dict[str, LoraLoadFailure] = field(default_factory=dict)
+ lora_runtime: LoraRuntimeConfig | None = None
# Lock for concurrent LoRA loading (created on first use)
_lora_lock: asyncio.Lock | None = field(default=None, init=False, repr=False)
@@ -249,6 +253,7 @@ class ModelLoader:
default_compute_precision=self._default_compute_precision,
attention_backend=self._attention_backend,
verified_serving_artifact=self._verified_serving_artifacts.get(config.sie_id),
+ max_loras_per_model=self._max_loras_per_model,
)
def ensure_weights_cached(self, config: ModelConfig) -> None:
@@ -734,30 +739,32 @@ class ModelLoader:
max_loras=self._max_loras_per_model,
)
- # Preload profile LoRAs if the adapter exposes a LoRA capability.
- # Engine-owned adapters (sglang) expose none: they consume
- # ``loadtime.lora_paths`` themselves at engine launch, so only
- # hot-reload (PEFT) adapters take the loadtime declarations from here.
+ # Engine-owned runtimes report their startup residency. Ordinary
+ # PEFT adapters use the existing preload path below.
lora_cap = adapter.lora_capability()
-
- # A pinned LoRA revision (#2113) is only honored on the hot-reload path
- # (``load_lora(revision=...)``). An engine-owned adapter consumes bare
- # ids at engine launch and a LoRA-less adapter never loads the ref at
- # all — in both cases a declared pin would silently resolve at the
- # Hub's default branch, which is exactly the drift the pin exists to
- # prevent. Fail the load loudly instead.
+ runtime = adapter.lora_runtime_config()
+ if runtime is not None:
+ loaded_model.lora_runtime = runtime
+ loaded_model.max_loras = runtime.max_loaded
+ for source in runtime.preloaded:
+ loaded_model.loras[source] = LoadedLora(adapter_id=source, pinned=source in runtime.pinned)
+
+ # PEFT resolves pins at fetch/load; SGLang receives the source revision
+ # map and materializes pinned startup and deferred sources itself.
+ # Reject adapters without either capability rather than silently
+ # resolving a declared pin at the Hub's default branch.
pinned = {ref: rev for ref, rev in config.lora_revisions().items() if rev is not None}
if pinned and (lora_cap is None or not lora_cap.supports_hot_lora_reload()):
msg = (
f"Model '{name}' pins LoRA revision(s) {pinned!r}, but adapter "
f"{type(adapter).__name__!r} cannot honor a pin: it loads LoRAs at engine "
"launch (or not at all), where only bare ids exist. Remove the pin, or "
- "serve via a hot-reload (PEFT) adapter. In the managed path, staging "
+ "serve via a runtime LoRA adapter. In the managed path, staging "
"resolves pins to local snapshots before the server sees the config."
)
raise ValueError(msg)
- if lora_cap is not None:
+ if lora_cap is not None and runtime is None:
profile_loras = self._collect_profile_loras(
config,
include_loadtime_paths=lora_cap.supports_hot_lora_reload(),
@@ -817,9 +824,8 @@ class ModelLoader:
config: Model configuration.
include_loadtime_paths: Collect the canonical
``loadtime.lora_paths`` declarations. Pass ``False`` for
- engine-owned adapters (sglang) that load those at engine
- launch themselves — preloading them again here would
- double-load.
+ startup-only adapters that load those at engine launch
+ themselves. Runtime metadata bypasses this preload path.
Returns:
Mapping of unique LoRA path/id -> pinned 40-hex revision, or
diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.py
index ce1633fc6..00644660b 100644
--- a/packages/sie_server/src/sie_server/core/registry.py
+++ b/packages/sie_server/src/sie_server/core/registry.py
@@ -29,6 +29,7 @@ from sie_sdk.storage import is_cloud_path
from sie_server.adapters._generation_base import GenerationAdapter
from sie_server.adapters.base import ModelAdapter, released_bytes
+from sie_server.adapters.lora import LoraStateUncertainError
from sie_server.config.device_groups import resolve_device_group, validate_tensor_parallel_size
from sie_server.config.engine import EngineConfig
from sie_server.config.model import ModelConfig
@@ -3358,12 +3359,12 @@ class ModelRegistry:
if loaded is None:
return False
- lora_state = loaded.loras.get(lora)
+ lora_state = loaded.loras.get(self._lora_source(loaded, lora))
if lora_state is None:
return False
# LoRA exists and is not in loading state
- return not lora_state.loading
+ return not lora_state.loading and not lora_state.unloading
def is_lora_loading(self, model: str, lora: str) -> bool:
"""Check if a LoRA adapter is currently being loaded.
@@ -3379,11 +3380,27 @@ class ModelRegistry:
if loaded is None:
return False
- lora_state = loaded.loras.get(lora)
+ lora_state = loaded.loras.get(self._lora_source(loaded, lora))
if lora_state is None:
return False
- return lora_state.loading
+ return lora_state.loading or lora_state.unloading
+
+ def loaded_lora_names(self, model: str) -> list[str]:
+ """Public served names currently ready on this worker; never expose source paths."""
+ loaded = self._loaded.get(model)
+ if loaded is None or loaded.lora_runtime is None or model in self._unloading:
+ return []
+ return [
+ name
+ for name, source in loaded.lora_runtime.aliases.items()
+ if (state := loaded.loras.get(source)) is not None and not state.loading and not state.unloading
+ ]
+
+ @staticmethod
+ def _lora_source(loaded: LoadedModel, name: str) -> str:
+ runtime = loaded.lora_runtime
+ return runtime.aliases.get(name, name) if runtime is not None else name
async def ensure_lora_loaded_async(self, model: str, lora: str) -> tuple[bool, bool]:
"""Ensure a LoRA adapter is loaded, triggering load if needed.
@@ -3418,6 +3435,8 @@ class ModelRegistry:
raise KeyError(msg)
loaded_model = self._loaded[model]
+ if model in self._unloading:
+ return (False, True)
adapter = loaded_model.adapter
# One LoRA capability handle for the whole load path, in place of the
@@ -3427,12 +3446,18 @@ class ModelRegistry:
msg = f"Model '{model}' cannot load a LoRA adapter at runtime"
raise ValueError(msg)
- if lora not in loaded_model.config.lora_revisions():
+ lora = self._lora_source(loaded_model, lora)
+ declared = (
+ set(loaded_model.lora_runtime.aliases.values())
+ if loaded_model.lora_runtime is not None
+ else loaded_model.config.lora_revisions()
+ )
+ if lora not in declared:
msg = f"Model '{model}' does not declare this LoRA adapter"
raise ValueError(msg)
lora_state = loaded_model.loras.get(lora)
- if lora_state is not None and not lora_state.loading:
+ if lora_state is not None and not lora_state.loading and not lora_state.unloading:
loaded_model.loras.move_to_end(lora)
return (True, False)
@@ -3443,7 +3468,7 @@ class ModelRegistry:
# Check if already loaded
lora_state = loaded_model.loras.get(lora)
if lora_state is not None:
- if lora_state.loading:
+ if lora_state.loading or lora_state.unloading:
# Still loading - return loading status
return (False, True)
# Already loaded
@@ -3454,6 +3479,24 @@ class ModelRegistry:
if self._lora_backoff_s(loaded_model, lora) is not None:
return (False, True)
+ # Loading placeholders reserve slots. Never evict one, or drop a
+ # pinned startup adapter. A victim remains tracked until the
+ # engine confirms removal; its replacement owns that one slot.
+ victim: str | None = None
+ occupied = sum(not state.unloading for state in loaded_model.loras.values())
+ if occupied >= loaded_model.max_loras:
+ victim = next(
+ (
+ name
+ for name, state in loaded_model.loras.items()
+ if not state.loading and not state.unloading and not state.pinned
+ ),
+ None,
+ )
+ if victim is None:
+ return (False, True)
+ loaded_model.loras[victim].unloading = True
+
# Not loaded - start loading
logger.info("Starting LoRA load for model '%s': %s", model, lora)
@@ -3463,27 +3506,11 @@ class ModelRegistry:
loading=True,
)
- # LRU eviction if needed (evict oldest LoRA)
- while len(loaded_model.loras) > loaded_model.max_loras:
- oldest_lora = next(iter(loaded_model.loras))
- if oldest_lora == lora:
- # Don't evict the one we're loading
- break
- logger.info(
- "LoRA LRU eviction for model '%s': evicting '%s' (max=%d)",
- model,
- oldest_lora,
- loaded_model.max_loras,
- )
- evicted = loaded_model.loras.pop(oldest_lora)
- if not evicted.loading:
- await self._unload_lora(loaded_model, oldest_lora)
-
# Load outside the lock if adapter supports hot reload
if lora_cap.supports_hot_lora_reload():
# Non-blocking load in background
task = asyncio.create_task(
- self._load_lora(model, lora),
+ self._load_lora(model, lora, loaded_model=loaded_model, victim=victim),
name=f"lora-load-{model}-{lora}",
)
self._background_tasks.add(task)
@@ -3491,10 +3518,12 @@ class ModelRegistry:
return (False, True)
# Blocking load - load synchronously
- await self._load_lora(model, lora)
+ await self._load_lora(model, lora, loaded_model=loaded_model, victim=victim)
return (self.is_lora_loaded(model, lora), self.lora_load_failed(model, lora))
- async def _load_lora(self, model: str, lora: str) -> None:
+ async def _load_lora(
+ self, model: str, lora: str, *, loaded_model: LoadedModel | None = None, victim: str | None = None
+ ) -> None:
"""Load a LoRA adapter and record it, or drop its placeholder and back off when the load fails.
A hot-reload adapter fetches the LoRA's files outside inference and
@@ -3506,8 +3535,8 @@ class ModelRegistry:
model: Model name.
lora: LoRA adapter name/path.
"""
+ loaded_model = loaded_model or self._loaded.get(model)
try:
- loaded_model = self._loaded.get(model)
if loaded_model is None:
logger.warning("Model '%s' unloaded during LoRA load", model)
return
@@ -3528,9 +3557,25 @@ class ModelRegistry:
attach = functools.partial(lora_cap.load_lora, lora, revision=revision, source=source)
else:
attach = functools.partial(lora_cap.load_lora, lora, revision=revision)
- memory_bytes = await self._run_lora_mutation(loaded_model, attach)
+ if self._loaded.get(model) is not loaded_model or model in self._unloading:
+ lora_cap.discard_lora_source(lora)
+ return
+
+ if victim is not None:
+ await self._unload_lora(loaded_model, victim, model=model)
+ async with loaded_model.get_lora_lock():
+ loaded_model.loras.pop(victim, None)
+
+ def attach_current() -> int:
+ if self._loaded.get(model) is not loaded_model or model in self._unloading:
+ raise RuntimeError("Model unloaded before LoRA attach")
+ return attach()
+
+ memory_bytes = await self._run_lora_mutation(loaded_model, attach_current)
async with loaded_model.get_lora_lock():
+ if self._loaded.get(model) is not loaded_model or model in self._unloading:
+ return
loaded_model.lora_failures.pop(lora, None)
lora_state = loaded_model.loras.get(lora)
if lora_state is None:
@@ -3546,12 +3591,20 @@ class ModelRegistry:
memory_bytes / 1024 / 1024,
)
- except Exception:
+ except Exception as error:
logger.exception("Error loading LoRA '%s' for model '%s'", lora, model)
- # Remove failed LoRA from tracking
- loaded_model = self._loaded.get(model)
- if loaded_model:
- loaded_model.loras.pop(lora, None)
+ if loaded_model is not None and (capability := loaded_model.adapter.lora_capability()) is not None:
+ capability.discard_lora_source(lora)
+ # Never mutate a newly loaded incarnation of the same model. An
+ # uncertain backend mutation retains its reservation until reload.
+ if loaded_model is not None and self._loaded.get(model) is loaded_model:
+ uncertain = isinstance(error, LoraStateUncertainError)
+ if not uncertain or victim in loaded_model.loras:
+ loaded_model.loras.pop(lora, None)
+ if victim is not None and victim in loaded_model.loras:
+ victim_state = loaded_model.loras[victim]
+ victim_state.unloading = False
+ victim_state.loading = uncertain
previous = loaded_model.lora_failures.get(lora)
attempts = previous.attempts + 1 if previous is not None else 1
delay_s = min(_LORA_RETRY_BASE_S * 2 ** (attempts - 1), _LORA_RETRY_MAX_S)
@@ -3570,12 +3623,16 @@ class ModelRegistry:
def lora_retry_after_s(self, model: str, lora: str) -> int:
"""Seconds a caller should wait before asking for ``lora`` again: the rest of a failed load's backoff, else 1."""
loaded_model = self._loaded.get(model)
+ if loaded_model is not None:
+ lora = self._lora_source(loaded_model, lora)
backoff = self._lora_backoff_s(loaded_model, lora) if loaded_model is not None else None
return backoff if backoff is not None else 1
def lora_load_failed(self, model: str, lora: str) -> bool:
"""True while ``lora``'s last load failed and the next one waits for the backoff."""
loaded_model = self._loaded.get(model)
+ if loaded_model is not None:
+ lora = self._lora_source(loaded_model, lora)
return loaded_model is not None and self._lora_backoff_s(loaded_model, lora) is not None
def request_lora_load(self, model: str, lora: str) -> int | None:
@@ -3588,14 +3645,21 @@ class ModelRegistry:
``lora`` as a LoRA to load.
"""
loaded_model = self._loaded.get(model)
+ if loaded_model is not None:
+ lora = self._lora_source(loaded_model, lora)
if (
loaded_model is None
or loaded_model.adapter.lora_capability() is None
- or lora not in loaded_model.config.lora_revisions()
+ or lora
+ not in (
+ set(loaded_model.lora_runtime.aliases.values())
+ if loaded_model.lora_runtime is not None
+ else loaded_model.config.lora_revisions()
+ )
):
return None
lora_state = loaded_model.loras.get(lora)
- if lora_state is not None and not lora_state.loading:
+ if lora_state is not None and not lora_state.loading and not lora_state.unloading:
loaded_model.loras.pop(lora)
task = asyncio.create_task(self._ensure_lora_quietly(model, lora), name=f"lora-request-{model}-{lora}")
self._background_tasks.add(task)
@@ -3608,14 +3672,17 @@ class ModelRegistry:
except Exception:
logger.exception("Error starting LoRA load for model '%s': %s", model, lora)
- async def _unload_lora(self, loaded_model: LoadedModel, lora: str) -> None:
+ async def _unload_lora(self, loaded_model: LoadedModel, lora: str, *, model: str | None = None) -> None:
lora_cap = loaded_model.adapter.lora_capability()
if lora_cap is None:
return
- try:
- await self._run_lora_mutation(loaded_model, functools.partial(lora_cap.unload_lora, lora))
- except Exception:
- logger.exception("Error unloading LoRA '%s'", lora)
+
+ def unload_current() -> None:
+ if model is not None and (self._loaded.get(model) is not loaded_model or model in self._unloading):
+ raise RuntimeError("Model unloaded before LoRA eviction")
+ lora_cap.unload_lora(lora)
+
+ await self._run_lora_mutation(loaded_model, unload_current)
@staticmethod
async def _run_lora_mutation[T](loaded_model: LoadedModel, mutation: Callable[[], T]) -> T:
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index 4828b8b7d..b875c22a2 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -1868,6 +1868,36 @@ class StreamingProcessor:
)
return
params = validation
+ if params.lora_adapter is not None and adapter.lora_capability() is not None:
+ try:
+ ready, _ = await self._registry.ensure_lora_loaded_async(model_id, params.lora_adapter)
+ except ValueError:
+ await self._terminal_error_then_settle(
+ reply_subject,
+ request_id=request_id,
+ attempt_id=attempt_id,
+ seq=0,
+ code="invalid_request",
+ message="The selected profile does not support this LoRA adapter",
+ param="lora_adapter",
+ msg=msg,
+ )
+ return
+ except KeyError:
+ ready = False
+ if not ready:
+ await self._terminal_error_then_settle(
+ reply_subject,
+ request_id=request_id,
+ attempt_id=attempt_id,
+ seq=0,
+ code="LORA_LOADING",
+ message="The selected LoRA is loading; retry the request",
+ param="lora_adapter",
+ retry_after_s=self._registry.lora_retry_after_s(model_id, params.lora_adapter),
+ msg=msg,
+ )
+ return
if (
params.stream
and config is not None
@@ -3602,6 +3632,16 @@ class StreamingProcessor:
# Multi-LoRA — served-name of the adapter (gateway-validated shape).
lora_adapter_raw = params.get("lora_adapter")
lora_adapter = lora_adapter_raw if isinstance(lora_adapter_raw, str) and lora_adapter_raw else None
+ if lora_adapter_raw is not None:
+ if lora_adapter is None:
+ return _ValidationError(code="invalid_request", message="'lora_adapter' must be a nonempty string")
+ if config is None:
+ return _ValidationError(code="invalid_request", message="LoRA selection requires a declared profile")
+ profile_name = (options or {}).get("profile") or "default"
+ if lora_adapter not in config.resolve_profile(profile_name).lora_names():
+ return _ValidationError(
+ code="invalid_request", message="The selected profile does not declare this LoRA adapter"
+ )
# OpenAI ``tools`` / ``tool_choice`` / ``parallel_tool_calls``.
# The gateway is the authority for shape validation (JSON-schema
diff --git a/packages/sie_server/tests/adapters/test_lora.py b/packages/sie_server/tests/adapters/test_lora.py
index 3b71554a0..f42459a3a 100644
--- a/packages/sie_server/tests/adapters/test_lora.py
+++ b/packages/sie_server/tests/adapters/test_lora.py
@@ -1071,6 +1071,7 @@ class TestPinnedLoraServing:
adapter.get_preprocessor.return_value = None
adapter.memory_footprint.return_value = 0
adapter.lora_capability.return_value = lora_cap
+ adapter.lora_runtime_config.return_value = None
return adapter
@staticmethod
@@ -1226,7 +1227,22 @@ class _GatedTinyLoRAAdapter(TinyLoRAAdapter):
class TestRegistryLoraLifecycle:
- async def test_a_lora_evicted_while_loading_does_not_stay_resident(self, tmp_path: Path) -> None:
+ def test_final_peft_unload_restores_base_and_allows_reload(self, tmp_path: Path) -> None:
+ lora = _save_plain_lora(tmp_path / "adapter")
+ adapter = TinyLoRAAdapter()
+ adapter.load("cpu")
+ expected = adapter._model(_probe()).detach()
+ for _ in range(2):
+ adapter.load_lora(lora)
+ adapter.set_active_lora(lora)
+ assert not torch.equal(adapter._model(_probe()).detach(), expected)
+ adapter.unload_lora(lora)
+ assert adapter._peft_model is None
+ assert not adapter._loaded_loras
+ assert not any(isinstance(module, BaseTunerLayer) for module in adapter._model.modules())
+ assert torch.equal(adapter._model(_probe()).detach(), expected)
+
+ async def test_loading_lora_reserves_capacity_until_it_can_be_evicted(self, tmp_path: Path) -> None:
first = _save_plain_lora(tmp_path / "first")
second = _save_plain_lora(tmp_path / "second")
gates = {first: threading.Event(), second: threading.Event()}
@@ -1237,10 +1253,11 @@ class TestRegistryLoraLifecycle:
assert await registry.ensure_lora_loaded_async("t/tiny", first) == (False, True)
first_load = next(iter(registry._background_tasks))
assert await registry.ensure_lora_loaded_async("t/tiny", second) == (False, True)
- assert list(loaded.loras) == [second]
+ assert list(loaded.loras) == [first]
gates[first].set()
await first_load
+ assert await registry.ensure_lora_loaded_async("t/tiny", second) == (False, True)
gates[second].set()
await asyncio.gather(*registry._background_tasks)
@@ -1595,11 +1612,18 @@ def _engine_owned_lora_config() -> ModelConfig:
)
+class _StartupOnlyEmbeddingAdapter(SGLangEmbeddingAdapter):
+ """A non-reloadable engine for the generic capability-absence contract."""
+
+ def lora_capability(self):
+ return None
+
+
class TestEngineOwnedLoras:
"""An adapter whose engine loads its LoRAs at launch answers a load request with a terminal error."""
async def test_a_declared_source_is_refused_without_a_load_or_a_backoff(self) -> None:
- adapter = SGLangEmbeddingAdapter("org/engine", lora_paths={"legal": "org/legal-lora"})
+ adapter = _StartupOnlyEmbeddingAdapter("org/engine", lora_paths={"legal": "org/legal-lora"})
registry, loaded = _registry_serving(adapter, _engine_owned_lora_config())
checker = ModelStateChecker(registry, "t/engine", MagicMock())
@@ -1618,7 +1642,7 @@ class TestEngineOwnedLoras:
@pytest.mark.parametrize("preformed", [False, True])
async def test_a_batch_selecting_a_declared_source_fails_with_a_terminal_error(self, preformed: bool) -> None:
- adapter = SGLangEmbeddingAdapter("org/engine", lora_paths={"legal": "org/legal-lora"})
+ adapter = _StartupOnlyEmbeddingAdapter("org/engine", lora_paths={"legal": "org/legal-lora"})
registry, _ = _registry_serving(adapter, _engine_owned_lora_config())
worker = ModelWorker(
adapter, WorkerConfig(max_batch_wait_ms=1), model_name="t/engine", registry_callbacks=registry
diff --git a/packages/sie_server/tests/adapters/test_sglang.py b/packages/sie_server/tests/adapters/test_sglang.py
index d91f2eb3a..2f9082ca3 100644
--- a/packages/sie_server/tests/adapters/test_sglang.py
+++ b/packages/sie_server/tests/adapters/test_sglang.py
@@ -630,6 +630,8 @@ class TestSGLangLoRA:
adapter = SGLangEmbeddingAdapter("test-model", lora_paths=lora_paths)
assert adapter._lora_paths == lora_paths
+ assert adapter.available_loras == []
+ adapter._lora.started()
assert adapter.available_loras == ["legal", "medical"]
assert adapter.lora_enabled is True
@@ -672,7 +674,8 @@ class TestSGLangLoRA:
lora_paths={"legal": "org/legal-lora", "medical": "/path/to/medical"},
max_loras_per_batch=4,
)
- adapter.load("cuda:0")
+ with patch.object(adapter._lora, "fetch", side_effect=lambda source: source):
+ adapter.load("cuda:0")
# Verify command includes LoRA flags
mock_popen.assert_called_once()
@@ -682,9 +685,7 @@ class TestSGLangLoRA:
assert "--lora-paths" in cmd
# Find the lora-paths value
lora_idx = cmd.index("--lora-paths")
- lora_paths_value = cmd[lora_idx + 1]
- assert "legal=" in lora_paths_value
- assert "medical=" in lora_paths_value
+ assert set(cmd[lora_idx + 1 : lora_idx + 3]) == {"legal=org/legal-lora", "medical=/path/to/medical"}
assert "--max-loras-per-batch" in cmd
batch_idx = cmd.index("--max-loras-per-batch")
@@ -731,12 +732,13 @@ class TestSGLangLoRA:
adapter._server_url = "http://localhost:30000"
items = [Item(text="test")]
+ adapter._lora.started()
adapter.set_active_lora("legal")
adapter.encode(items, output_types=["dense"])
# Verify LoRA name is used as model name in request
call_args = mock_post.call_args
- assert call_args[1]["json"]["model"] == "legal"
+ assert call_args[1]["json"]["model"] == "default:legal"
@patch("sie_server.adapters.sglang.embedding.requests.post")
def test_encode_without_lora_uses_default(self, mock_post: MagicMock) -> None:
@@ -767,7 +769,7 @@ class TestSGLangLoRA:
)
adapter._server_url = "http://localhost:30000"
- with pytest.raises(ValueError, match="LoRA 'unknown' is not loaded") as raised:
+ with pytest.raises(ValueError, match="not declared") as raised:
adapter.set_active_lora("unknown")
assert "legal" not in str(raised.value)
@@ -781,7 +783,7 @@ class TestSGLangLoRA:
adapter._server_url = "http://localhost:30000"
adapter._active_lora = "unknown"
- with pytest.raises(ValueError, match="LoRA 'unknown' is not loaded") as raised:
+ with pytest.raises(ValueError, match="not declared") as raised:
adapter.encode([Item(text="test")], output_types=["dense"])
assert "legal" not in str(raised.value)
@@ -790,7 +792,7 @@ class TestSGLangLoRA:
adapter = SGLangEmbeddingAdapter("test-model") # No lora_paths
adapter._server_url = "http://localhost:30000"
- with pytest.raises(ValueError, match="LoRA 'legal' is not loaded"):
+ with pytest.raises(ValueError, match="not declared"):
adapter.set_active_lora("legal")
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index 1511a214e..dcb67759c 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -360,7 +360,8 @@ def test_load_emits_lora_launch_args(
max_loras_per_batch=2,
)
- adapter.load("cuda:0")
+ with patch.object(adapter._lora, "fetch", side_effect=lambda source: source):
+ adapter.load("cuda:0")
cmd = mock_popen.call_args[0][0]
assert "--enable-lora" in cmd
@@ -594,7 +595,7 @@ def test_generate_n_gt_one_fans_out_into_candidates(mock_async_client: MagicMock
@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
-def test_generate_forwards_lora_path(mock_async_client: MagicMock, adapter) -> None:
+def test_generate_forwards_lora_path(mock_async_client: MagicMock) -> None:
"""`lora_path` (the served-name) is forwarded as SGLang
sampling_params.lora_path for per-request adapter selection.
"""
@@ -603,6 +604,8 @@ def test_generate_forwards_lora_path(mock_async_client: MagicMock, adapter) -> N
]
stream = _FakeStreamingResponse(sse_lines)
mock_async_client.return_value = _make_client_with_stream(stream)
+ adapter = SGLangGenerationAdapter("test-model", lora_paths={"acme-support": "acme/support-lora"})
+ adapter._lora.started()
adapter._server_url = "http://localhost:30005"
asyncio.run(collect_generation(adapter.generate(prompt="Hi", max_new_tokens=8, lora_path="acme-support")))
diff --git a/packages/sie_server/tests/adapters/test_sglang_lora.py b/packages/sie_server/tests/adapters/test_sglang_lora.py
new file mode 100644
index 000000000..2c7ed3bc0
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_sglang_lora.py
@@ -0,0 +1,365 @@
+"""Runtime LoRA contracts without importing SGLang or allocating a GPU."""
+
+import asyncio
+import json
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from unittest.mock import Mock
+
+import numpy as np
+import pytest
+from safetensors.numpy import save_file
+from sie_server.adapters._generation_base import GenerationInvalidRequestError, GenerationLoraLoadingError
+from sie_server.adapters.lora import LoraStateUncertainError, LoraUnavailableError
+from sie_server.adapters.sglang._lora import SGLangLoraManager, SGLangLoraMixin, leased_generation
+from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
+
+
+def manager(**kwargs):
+ return SGLangLoraManager(
+ {"a": "org/a", "b": "org/b"},
+ preload=kwargs.pop("preload", []),
+ revisions={"org/a": "a" * 40},
+ max_rank=8,
+ target_modules=["q_proj"],
+ max_per_batch=kwargs.pop("max_per_batch", 2),
+ server_url=lambda: "http://localhost:1234",
+ mutation_timeout_s=0.5,
+ **kwargs,
+ )
+
+
[email protected]("preload", ["a", ["a", "a"], ["unknown"], [1], {}])
+def test_preload_selector_is_strict(preload):
+ with pytest.raises(ValueError, match="preload_loras"):
+ manager(preload=preload)
+
+
+def test_deferred_engine_is_enabled_with_empty_preload():
+ loras = manager()
+ args = loras.launch_args()
+ assert "--enable-lora" in args
+ assert "--lora-paths" not in args
+ assert args[args.index("--max-lora-rank") + 1] == "8"
+ assert loras.runtime_config().preloaded == frozenset()
+
+
+def test_omitted_selector_preloads_and_pins_existing_sources(monkeypatch):
+ loras = manager(preload=None)
+ monkeypatch.setattr(loras, "fetch", lambda source: "/cache/" + source.rsplit("/", 1)[1])
+ args = loras.launch_args()
+ assert args[args.index("--lora-paths") + 1 :] == ["a=/cache/a", "b=/cache/b"]
+ loras.started()
+ assert loras.available == ["a", "b"]
+ with pytest.raises(ValueError, match="pinned"):
+ loras.unload("a")
+
+
+def test_undeclared_source_never_fetches_or_calls_engine(monkeypatch):
+ fetch = Mock()
+ post = Mock()
+ monkeypatch.setattr("sie_server.adapters.sglang._lora.snapshot_download", fetch)
+ monkeypatch.setattr("sie_server.adapters.sglang._lora.requests.post", post)
+ loras = manager()
+ for operation in (loras.fetch, loras.load, loras.unload):
+ with pytest.raises(ValueError, match="not declared"):
+ operation("attacker/arbitrary")
+ fetch.assert_not_called()
+ post.assert_not_called()
+
+
+def test_fetch_uses_immutable_revision_and_only_adapter_files(tmp_path, monkeypatch):
+ (tmp_path / "adapter_config.json").write_text('{"peft_type":"LORA","r":4,"target_modules":["q_proj"]}')
+ save_file(
+ {"base_model.model.q_proj.lora_A.weight": np.ones((4, 2), dtype=np.float32)},
+ str(tmp_path / "adapter_model.safetensors"),
+ )
+ fetch = Mock(return_value=str(tmp_path))
+ monkeypatch.setattr("sie_server.adapters.sglang._lora.snapshot_download", fetch)
+ (tmp_path / "unvalidated.safetensors").write_bytes(b"must not reach the engine")
+ loras = manager()
+ snapshot = Path(loras.fetch("a"))
+ assert snapshot != tmp_path
+ assert sorted(path.name for path in snapshot.iterdir()) == ["adapter_config.json", "adapter_model.safetensors"]
+ assert (snapshot / "adapter_model.safetensors").read_bytes() == (
+ tmp_path / "adapter_model.safetensors"
+ ).read_bytes()
+ fetch.assert_called_once_with(
+ "org/a", revision="a" * 40, allow_patterns=["adapter_config.json", "adapter_model.safetensors"]
+ )
+ with pytest.raises(ValueError, match="revision"):
+ loras.fetch("a", "b" * 40)
+ loras.close()
+ assert not snapshot.exists()
+ assert (tmp_path / "adapter_model.safetensors").exists()
+
+
+ "override",
+ [
+ {"r": 16},
+ {"target_modules": ["v_proj"]},
+ {"rank_pattern": {"q_proj": 2}},
+ {"alpha_pattern": {"q_proj": 2}},
+ {"use_rslora": True},
+ {"init_lora_weights": "pissa"},
+ ],
+)
+def test_fetch_refuses_unsupported_transform_or_engine_capacity(tmp_path, monkeypatch, override):
+ config = {"peft_type": "LORA", "r": 4, "target_modules": ["q_proj"], **override}
+ (tmp_path / "adapter_config.json").write_text(json.dumps(config))
+ monkeypatch.setattr("sie_server.adapters.sglang._lora.snapshot_download", lambda *args, **kwargs: str(tmp_path))
+ with pytest.raises(ValueError, match="LoRA"):
+ manager().fetch("a")
+
+
+def test_fetch_finishing_after_model_close_does_not_retain_source(tmp_path, monkeypatch):
+ (tmp_path / "adapter_config.json").write_text('{"peft_type":"LORA","r":4,"target_modules":["q_proj"]}')
+ save_file(
+ {"base.q_proj.lora_A.weight": np.ones((4, 2), dtype=np.float32)}, str(tmp_path / "adapter_model.safetensors")
+ )
+ entered, release = threading.Event(), threading.Event()
+
+ def download(*args, **kwargs):
+ entered.set()
+ assert release.wait(2)
+ return str(tmp_path)
+
+ monkeypatch.setattr("sie_server.adapters.sglang._lora.snapshot_download", download)
+ loras = manager()
+ with ThreadPoolExecutor() as pool:
+ pending = pool.submit(loras.fetch, "a")
+ assert entered.wait(1)
+ loras.close()
+ release.set()
+ with pytest.raises(RuntimeError, match="unloaded during fetch"):
+ pending.result(timeout=1)
+ assert not loras._snapshots
+
+
+def test_discard_source_keeps_attached_or_uncertain_views_until_model_close(tmp_path, monkeypatch):
+ (tmp_path / "adapter_config.json").write_text('{"peft_type":"LORA","r":4,"target_modules":["q_proj"]}')
+ save_file(
+ {"base.q_proj.lora_A.weight": np.ones((4, 2), dtype=np.float32)}, str(tmp_path / "adapter_model.safetensors")
+ )
+ monkeypatch.setattr("sie_server.adapters.sglang._lora.snapshot_download", lambda *args, **kwargs: str(tmp_path))
+ loras = manager()
+ unused = Path(loras.fetch("a"))
+ loras.discard_source("a")
+ assert not unused.exists()
+ attached = Path(loras.fetch("a"))
+ mutate = Mock()
+ monkeypatch.setattr(loras, "_mutate", mutate)
+ loras.load("a", source=str(attached))
+ loras.discard_source("a")
+ assert attached.exists()
+ mutate.side_effect = TimeoutError()
+ with pytest.raises(LoraStateUncertainError, match="removal"):
+ loras.unload("a")
+ loras.discard_source("a")
+ assert attached.exists()
+ loras.close()
+ assert not attached.exists()
+
+
[email protected]("alias", ["a=b", "a b", "--option", "a\nb"])
+def test_served_name_cannot_be_interpreted_as_cli_syntax(alias):
+ with pytest.raises(ValueError, match="served names"):
+ SGLangLoraManager(
+ {alias: "org/a"},
+ preload=None,
+ revisions=None,
+ max_rank=None,
+ target_modules=None,
+ max_per_batch=1,
+ server_url=lambda: None,
+ )
+
+
+def test_deferred_configuration_requires_an_evictable_slot():
+ with pytest.raises(ValueError, match="at least one slot"):
+ manager(preload=["a"], max_loaded=1, max_per_batch=1)
+
+
[email protected]("flag", ["--tokenizer-worker-num", "--dp-size", "--data-parallel-size"])
[email protected]("joined", [True, False])
+def test_deferred_generation_requires_single_workers_but_allows_explicit_one(flag, joined):
+ config = {
+ "mem_fraction_static": 0.5,
+ "lora_paths": {"a": "org/a"},
+ "preload_loras": [],
+ "max_lora_rank": 8,
+ "lora_target_modules": ["q_proj"],
+ }
+ for count in ("1", "2"):
+ args = [f"{flag}={count}"] if joined else [flag, count]
+ if count == "1":
+ SGLangGenerationAdapter("base", **config, extra_launch_args=args)
+ else:
+ with pytest.raises(ValueError, match="one tokenizer worker"):
+ SGLangGenerationAdapter("base", **config, extra_launch_args=args)
+
+
+def test_fetch_rejects_shared_base_tensor(tmp_path, monkeypatch):
+ (tmp_path / "adapter_config.json").write_text('{"peft_type":"LORA","r":4,"target_modules":["q_proj"]}')
+ save_file(
+ {"base_model.model.q_proj.weight": np.ones((4, 2), dtype=np.float32)},
+ str(tmp_path / "adapter_model.safetensors"),
+ )
+ monkeypatch.setattr("sie_server.adapters.sglang._lora.snapshot_download", lambda *args, **kwargs: str(tmp_path))
+ with pytest.raises(ValueError, match="outside the adapter"):
+ manager().fetch("a")
+
+
+def test_failed_attach_rolls_back_or_keeps_uncertain_reservation(monkeypatch):
+ loras = manager()
+ mutate = Mock(side_effect=[RuntimeError("private source failure"), None])
+ monkeypatch.setattr(loras, "_mutate", mutate)
+ with pytest.raises(RuntimeError, match="private source"):
+ loras.load("a", source="/cache/a")
+ assert mutate.call_args_list[1].args == ("unload_lora_adapter", {"lora_name": "a"})
+ assert loras.available == []
+ mutate.side_effect = [TimeoutError(), TimeoutError()]
+ with pytest.raises(LoraStateUncertainError, match="rollback"):
+ loras.load("a", source="/cache/a")
+ mutate.reset_mock(side_effect=True)
+ with pytest.raises(LoraStateUncertainError, match="reload"):
+ loras.load("a", source="/cache/a")
+ mutate.assert_not_called()
+
+
+def test_eviction_rejects_new_leases_and_drains_before_http(monkeypatch):
+ loras = manager()
+ mutate = Mock()
+ monkeypatch.setattr(loras, "_mutate", mutate)
+ loras.load("a", source="/cache/a")
+ mutate.reset_mock()
+ with ThreadPoolExecutor() as pool:
+ with loras.lease("a"):
+ future = pool.submit(loras.unload, "a")
+ with loras._condition:
+ assert loras._condition.wait_for(lambda: "org/a" in loras._draining, timeout=0.2)
+ with pytest.raises(LoraUnavailableError):
+ with loras.lease("a"):
+ pytest.fail("new lease admitted while evicting")
+ mutate.assert_not_called()
+ future.result(timeout=0.2)
+ mutate.assert_called_once_with("unload_lora_adapter", {"lora_name": "a"})
+ assert loras.available == []
+
+
+def test_failed_unload_keeps_adapter_unavailable(monkeypatch):
+ loras = manager()
+ monkeypatch.setattr(loras, "_mutate", Mock())
+ loras.load("a", source="/cache/a")
+ monkeypatch.setattr(loras, "_mutate", Mock(side_effect=TimeoutError()))
+ with pytest.raises(LoraStateUncertainError, match="removal"):
+ loras.unload("a")
+ assert "org/a" in loras._loaded
+ with pytest.raises(LoraUnavailableError):
+ with loras.lease("a"):
+ pytest.fail("uncertain adapter admitted")
+
+
+def test_teardown_joins_mutation_before_releasing_port_and_rejects_late_posts(monkeypatch):
+ entered, release = threading.Event(), threading.Event()
+ response = Mock()
+ response.json.return_value = {"success": True}
+
+ def post(*args, **kwargs):
+ entered.set()
+ assert release.wait(2)
+ return response
+
+ http = Mock(side_effect=post)
+ monkeypatch.setattr("sie_server.adapters.sglang._lora.requests.post", http)
+ loras = manager()
+ with ThreadPoolExecutor() as pool:
+ mutation = pool.submit(loras._mutate, "unload_lora_adapter", {"lora_name": "a"})
+ assert entered.wait(1)
+ closing = pool.submit(loras.stop_mutations)
+ with loras._condition:
+ assert loras._condition.wait_for(lambda: loras._closed, timeout=1)
+ assert not closing.done()
+ # This models a mutation that passed the registry identity gate but
+ # did not reach the child before unload began.
+ late = pool.submit(loras._mutate, "unload_lora_adapter", {"lora_name": "b"})
+ release.set()
+ mutation.result(timeout=1)
+ closing.result(timeout=1)
+ with pytest.raises(RuntimeError, match="unloading"):
+ late.result(timeout=1)
+ assert http.call_count == 1
+
+
+def test_teardown_refuses_new_leases_while_existing_lease_can_finish():
+ loras = manager(preload=None)
+ loras.started()
+ with loras.lease("a"):
+ loras.stop_mutations()
+ with pytest.raises(LoraUnavailableError):
+ with loras.lease("a"):
+ pytest.fail("adapter admitted during model teardown")
+ assert loras._leases["org/a"] == 1
+ assert loras._leases["org/a"] == 0
+
+
[email protected]("ending", ["close", "cancel", "error", "complete"])
+async def test_generation_lease_released_for_all_iterator_endings(ending, monkeypatch):
+ loras = manager()
+ monkeypatch.setattr(loras, "_mutate", Mock())
+ loras.load("a", source="/cache/a")
+ gate = asyncio.Event()
+ closed = threading.Event()
+
+ class Adapter(SGLangLoraMixin):
+ _lora = loras
+
+ @leased_generation
+ async def generate(self, *, lora_path=None):
+ assert lora_path == "a"
+ try:
+ yield "first"
+ if ending == "error":
+ raise RuntimeError("inference failed")
+ await gate.wait()
+ finally:
+ closed.set()
+
+ stream = Adapter().generate(lora_path="org/a")
+ assert await anext(stream) == "first"
+ assert loras._leases["org/a"] == 1
+ if ending == "close":
+ await stream.aclose()
+ elif ending == "cancel":
+ task = asyncio.create_task(anext(stream))
+ await asyncio.sleep(0)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ elif ending == "error":
+ with pytest.raises(RuntimeError, match="inference failed"):
+ await anext(stream)
+ else:
+ gate.set()
+ with pytest.raises(StopAsyncIteration):
+ await anext(stream)
+ assert loras._leases["org/a"] == 0
+ assert closed.is_set()
+
+
+async def test_generation_missing_lora_and_unsafe_sampling_are_typed():
+ class Adapter(SGLangLoraMixin):
+ _lora = manager()
+
+ @leased_generation
+ async def generate(self, **kwargs):
+ yield kwargs
+
+ with pytest.raises(GenerationLoraLoadingError):
+ await anext(Adapter().generate(lora_path="a"))
+ with pytest.raises(GenerationInvalidRequestError):
+ await anext(Adapter().generate(lora_path="a", n=2))
diff --git a/packages/sie_server/tests/config/test_runtime_lora.py b/packages/sie_server/tests/config/test_runtime_lora.py
new file mode 100644
index 000000000..bce98cf23
--- /dev/null
+++ b/packages/sie_server/tests/config/test_runtime_lora.py
@@ -0,0 +1,76 @@
+"""Declared sources, preload inheritance, and one resolved engine capacity."""
+
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+from sie_server.config.model import ModelConfig
+from sie_server.core.loader import expand_profile_variants, load_adapter
+from sie_server.core.model_loader import ModelLoader
+
+
+def config_values():
+ return {
+ "sie_id": "test/model",
+ "hf_id": "test/model",
+ "inputs": {"text": True},
+ "tasks": {"generate": {"context_length": 1024, "max_output_tokens": 64}},
+ "profiles": {
+ "default": {
+ "adapter_path": "sie_server.adapters.sglang.generation:SGLangGenerationAdapter",
+ "max_batch_tokens": 1024,
+ "kv_budget_tokens": 1024,
+ "adapter_options": {
+ "loadtime": {
+ "lora_paths": {"a": {"id": "org/a", "revision": "a" * 40}, "other-a": "org/a"},
+ "preload_loras": [],
+ "mem_fraction_static": 0.5,
+ "max_lora_rank": 8,
+ "lora_target_modules": ["q_proj"],
+ "max_loras_per_batch": 1,
+ }
+ },
+ }
+ },
+ }
+
+
+def test_loader_preserves_source_revision_and_uses_explicit_capacity(monkeypatch):
+ config = ModelConfig.model_validate(config_values())
+ monkeypatch.setenv("SIE_MAX_LORAS_PER_MODEL", "20")
+ loader = ModelLoader(
+ preprocessor_registry=Mock(), postprocessor_registry=Mock(), all_configs={}, max_loras_per_model=2
+ )
+ adapter = loader.instantiate_adapter("test/model", config, Path(), "cuda:0")
+ assert adapter._lora.revisions == {"org/a": "a" * 40}
+ assert adapter._lora.max_loaded == 2
+ assert adapter._lora.engine_name("a") == adapter._lora.engine_name("other-a")
+ args = adapter._lora.launch_args()
+ assert args[args.index("--max-loaded-loras") + 1] == "2"
+
+
+def test_preload_selector_uses_inherited_source_map():
+ values = config_values()
+ values["profiles"]["default"]["adapter_options"]["loadtime"]["preload_loras"] = ["a"]
+ values["profiles"]["warm"] = {"extends": "default"}
+ config = ModelConfig.model_validate(values)
+ variant = expand_profile_variants([config])["test/model:warm"]
+ adapter = load_adapter(variant, Path(), device="cuda:0")
+ assert adapter._lora.preloaded == frozenset({"org/a"})
+ assert adapter._lora.revisions["org/a"] == "a" * 40
+
+
[email protected]("selector", [None, "a", ["missing"], ["a", "a"], [1], {}])
+def test_invalid_preload_selector_fails_at_config_load(selector):
+ values = config_values()
+ values["profiles"]["default"]["adapter_options"]["loadtime"]["preload_loras"] = selector
+ with pytest.raises(ValueError, match="preload_loras"):
+ ModelConfig.model_validate(values)
+
+
+def test_two_aliases_cannot_pin_one_source_to_different_revisions():
+ values = config_values()
+ paths = values["profiles"]["default"]["adapter_options"]["loadtime"]["lora_paths"]
+ paths["other-a"] = {"id": "org/a", "revision": "b" * 40}
+ with pytest.raises(ValueError, match="two different revisions"):
+ ModelConfig.model_validate(values)
diff --git a/packages/sie_server/tests/core/test_runtime_lora.py b/packages/sie_server/tests/core/test_runtime_lora.py
new file mode 100644
index 000000000..2436bc589
--- /dev/null
+++ b/packages/sie_server/tests/core/test_runtime_lora.py
@@ -0,0 +1,187 @@
+"""Registry residency contracts for engine-owned runtime LoRAs."""
+
+import asyncio
+import threading
+from unittest.mock import Mock
+
+import pytest
+from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
+from sie_server.core.model_loader import LoadedLora, LoadedModel
+from sie_server.core.registry import ModelRegistry
+
+
+def registry_with_loras(monkeypatch, *, capacity=1, preload=None):
+ adapter = SGLangGenerationAdapter(
+ "base",
+ mem_fraction_static=0.5,
+ lora_paths={"a": "org/a", "b": "org/b", "c": "org/c"},
+ preload_loras=preload or [],
+ max_lora_rank=8,
+ lora_target_modules=["q_proj"],
+ max_loras_per_batch=1,
+ max_loaded_loras=capacity,
+ )
+ adapter._lora.started()
+ monkeypatch.setattr(adapter, "fetch_lora", Mock(return_value="/cache/adapter"))
+ monkeypatch.setattr(adapter, "discard_lora_source", Mock(wraps=adapter.discard_lora_source))
+ monkeypatch.setattr(adapter._lora, "_mutate", Mock())
+ config = Mock()
+ config.lora_revisions.return_value = dict.fromkeys(["org/a", "org/b", "org/c"])
+ runtime = adapter.lora_runtime_config()
+ loaded = LoadedModel(config, adapter, "cpu", max_loras=capacity, lora_runtime=runtime)
+ for source in runtime.preloaded:
+ loaded.loras[source] = LoadedLora(source, pinned=True)
+ registry = ModelRegistry()
+ registry._configs["base"] = config
+ registry._loaded["base"] = loaded
+ return registry, loaded, adapter
+
+
+async def finish_loads(registry):
+ await asyncio.wait_for(asyncio.gather(*registry._background_tasks), 2)
+
+
+async def test_first_request_returns_loading_then_alias_and_source_are_ready(monkeypatch):
+ registry, _, adapter = registry_with_loras(monkeypatch)
+ assert await registry.ensure_lora_loaded_async("base", "a") == (False, True)
+ assert await registry.ensure_lora_loaded_async("base", "org/a") == (False, True)
+ await finish_loads(registry)
+ assert await registry.ensure_lora_loaded_async("base", "a") == (True, False)
+ adapter.fetch_lora.assert_called_once_with("org/a", None)
+ assert registry.loaded_lora_names("base") == ["a"]
+
+
+async def test_loading_slot_cannot_be_evicted_or_overcommitted(monkeypatch):
+ registry, loaded, adapter = registry_with_loras(monkeypatch)
+ entered, release = threading.Event(), threading.Event()
+
+ def fetch(*args):
+ entered.set()
+ assert release.wait(2)
+ return "/cache/a"
+
+ monkeypatch.setattr(adapter, "fetch_lora", Mock(side_effect=fetch))
+ assert await registry.ensure_lora_loaded_async("base", "a") == (False, True)
+ await asyncio.to_thread(entered.wait, 1)
+ try:
+ assert await registry.ensure_lora_loaded_async("base", "b") == (False, True)
+ assert list(loaded.loras) == ["org/a"]
+ assert len(registry._background_tasks) == 1
+ finally:
+ release.set()
+ await finish_loads(registry)
+ assert registry.is_lora_loaded("base", "a")
+
+
+async def test_lru_removes_confirmed_victim_before_replacement_and_preserves_pins(monkeypatch):
+ registry, loaded, adapter = registry_with_loras(monkeypatch, capacity=2, preload=["a"])
+ await registry.ensure_lora_loaded_async("base", "b")
+ await finish_loads(registry)
+ adapter._lora._mutate.reset_mock()
+ await registry.ensure_lora_loaded_async("base", "c")
+ assert not registry.is_lora_loaded("base", "b")
+ await finish_loads(registry)
+ assert list(loaded.loras) == ["org/a", "org/c"]
+ assert [call.args[0] for call in adapter._lora._mutate.call_args_list] == [
+ "unload_lora_adapter",
+ "load_lora_adapter",
+ ]
+ assert adapter._lora._mutate.call_args_list[0].args[1] == {"lora_name": "b"}
+
+
+async def test_all_pinned_capacity_returns_retry_without_fetch(monkeypatch):
+ registry, loaded, adapter = registry_with_loras(monkeypatch, capacity=2, preload=["a"])
+ loaded.max_loras = 1 # Defensive runtime state; constructor rejects this declaration.
+ assert await registry.ensure_lora_loaded_async("base", "b") == (False, True)
+ adapter.fetch_lora.assert_not_called()
+ assert list(loaded.loras) == ["org/a"]
+
+
+async def test_failed_unload_retains_capacity_and_does_not_attach_replacement(monkeypatch):
+ registry, loaded, adapter = registry_with_loras(monkeypatch)
+ await registry.ensure_lora_loaded_async("base", "a")
+ await finish_loads(registry)
+ adapter._lora._mutate.reset_mock()
+ adapter._lora._mutate.side_effect = TimeoutError("uncertain removal")
+ await registry.ensure_lora_loaded_async("base", "b")
+ await finish_loads(registry)
+ assert list(loaded.loras) == ["org/a"]
+ assert loaded.loras["org/a"].loading
+ assert await registry.ensure_lora_loaded_async("base", "c") == (False, True)
+ adapter._lora._mutate.assert_called_once_with("unload_lora_adapter", {"lora_name": "a"})
+ adapter.discard_lora_source.assert_called_once_with("org/b")
+ assert registry.loaded_lora_names("base") == []
+
+
+async def test_failed_fetch_restores_unmodified_victim(monkeypatch):
+ registry, loaded, adapter = registry_with_loras(monkeypatch)
+ await registry.ensure_lora_loaded_async("base", "a")
+ await finish_loads(registry)
+ adapter._lora._mutate.reset_mock()
+ adapter.fetch_lora.side_effect = OSError("download failed")
+ await registry.ensure_lora_loaded_async("base", "b")
+ await finish_loads(registry)
+ assert list(loaded.loras) == ["org/a"]
+ assert registry.is_lora_loaded("base", "a")
+ adapter._lora._mutate.assert_not_called()
+
+
[email protected]("fail_fetch", [False, True])
+async def test_delayed_old_fetch_never_attaches_or_changes_replacement_model(monkeypatch, fail_fetch):
+ registry, old, adapter = registry_with_loras(monkeypatch)
+ entered, release = threading.Event(), threading.Event()
+
+ def fetch(*args):
+ entered.set()
+ assert release.wait(2)
+ if fail_fetch:
+ raise OSError("old fetch failed")
+ return "/cache/a"
+
+ monkeypatch.setattr(adapter, "fetch_lora", fetch)
+ await registry.ensure_lora_loaded_async("base", "a")
+ await asyncio.to_thread(entered.wait, 1)
+ replacement = LoadedModel(old.config, adapter, "cpu", lora_runtime=old.lora_runtime)
+ replacement.loras["org/a"] = LoadedLora("org/a")
+ registry._loaded["base"] = replacement
+ release.set()
+ await finish_loads(registry)
+ assert list(replacement.loras) == ["org/a"]
+ assert not replacement.lora_failures
+ adapter._lora._mutate.assert_not_called()
+ adapter.discard_lora_source.assert_called_once_with("org/a")
+
+
+async def test_waiting_victim_unload_rechecks_model_identity_inside_mutation(monkeypatch):
+ registry, old, adapter = registry_with_loras(monkeypatch)
+ await registry.ensure_lora_loaded_async("base", "a")
+ await finish_loads(registry)
+ adapter._lora._mutate.reset_mock()
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def delayed_mutation(mutation):
+ entered.set()
+ await release.wait()
+ return mutation()
+
+ worker = Mock()
+ worker.run_adapter_mutation = delayed_mutation
+ old.worker = worker
+ await registry.ensure_lora_loaded_async("base", "b")
+ await asyncio.wait_for(entered.wait(), 1)
+ replacement = LoadedModel(old.config, adapter, "cpu", lora_runtime=old.lora_runtime)
+ replacement.loras["org/a"] = LoadedLora("org/a")
+ registry._loaded["base"] = replacement
+ release.set()
+ await finish_loads(registry)
+ assert list(replacement.loras) == ["org/a"]
+ assert not replacement.lora_failures
+ adapter._lora._mutate.assert_not_called()
diff --git a/packages/sie_server/tests/processors/test_runtime_lora.py b/packages/sie_server/tests/processors/test_runtime_lora.py
new file mode 100644
index 000000000..f59f3d1ea
--- /dev/null
+++ b/packages/sie_server/tests/processors/test_runtime_lora.py
@@ -0,0 +1,94 @@
+"""Worker authorization and immediate LoRA-loading responses for generation."""
+
+import time
+from unittest.mock import AsyncMock, Mock
+
+import msgpack
+import pytest
+from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
+from sie_server.config.model import ModelConfig
+from sie_server.processors.streaming import StreamingProcessor, _ValidationError
+
+
+def config():
+ return ModelConfig.model_validate(
+ {
+ "sie_id": "test/model",
+ "hf_id": "test/model",
+ "inputs": {"text": True},
+ "tasks": {"generate": {"context_length": 1024, "max_output_tokens": 64}},
+ "profiles": {
+ "default": {
+ "adapter_path": "sie_server.adapters.sglang.generation:SGLangGenerationAdapter",
+ "max_batch_tokens": 1024,
+ "kv_budget_tokens": 1024,
+ "adapter_options": {"loadtime": {"lora_paths": {"allowed": "org/allowed"}}},
+ },
+ "private": {
+ "extends": "default",
+ "adapter_options": {"loadtime": {"lora_paths": {"private": "org/private"}}},
+ },
+ },
+ }
+ )
+
+
+def work_item(lora="allowed", **generate):
+ return {
+ "work_item_id": "req-1.0",
+ "request_id": "req-1",
+ "item_index": 0,
+ "total_items": 1,
+ "operation": "generate",
+ "model_id": "test/model",
+ "profile_id": "default",
+ "pool_name": "default",
+ "machine_profile": "default",
+ "router_id": "router-1",
+ "reply_subject": "_INBOX.router-1.req-1",
+ "timestamp": time.time(),
+ "generate": {"prompt": "Hello", "max_new_tokens": 8, "lora_adapter": lora, **generate},
+ }
+
+
[email protected]("lora", ["private", "org/private", "attacker/arbitrary", "", {}, 3])
+def test_worker_refuses_undeclared_other_profile_or_malformed_lora(lora):
+ result = StreamingProcessor._validate_generate_params(work_item(lora), config())
+ assert isinstance(result, _ValidationError)
+ assert result.code == "invalid_request"
+
+
[email protected]("options", [None, {"profile": None}, {"profile": "default"}])
+def test_declared_selected_profile_alias_is_accepted(options):
+ wi = work_item()
+ wi["options"] = options
+ result = StreamingProcessor._validate_generate_params(wi, config())
+ assert not isinstance(result, _ValidationError)
+ assert result.lora_adapter == "allowed"
+
+
[email protected]("chat", [False, True])
+async def test_cold_generate_and_chat_return_loading_without_inference(chat):
+ adapter = SGLangGenerationAdapter("base", mem_fraction_static=0.5, lora_paths={"allowed": "org/allowed"})
+ registry = Mock()
+ registry.is_loaded.return_value = True
+ registry.get.return_value = adapter
+ registry.get_config.return_value = config()
+ registry.ensure_lora_loaded_async = AsyncMock(return_value=(False, True))
+ registry.lora_retry_after_s.return_value = 3
+ registry.device = "cpu"
+ nc = AsyncMock()
+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="worker-1")
+ wi = work_item()
+ if chat:
+ wi["generate"].pop("prompt")
+ wi["generate"]["messages"] = [{"role": "user", "content": "Hello"}]
+ msg = AsyncMock()
+ msg.data = msgpack.packb(wi, use_bin_type=True)
+ await proc.process(msg, "test/model")
+ registry.ensure_lora_loaded_async.assert_awaited_once_with("test/model", "allowed")
+ chunks = [msgpack.unpackb(call.args[1], raw=False) for call in nc.publish.await_args_list]
+ assert chunks[-1]["error"]["code"] == "LORA_LOADING"
+ assert chunks[-1]["done"]
+ msg.ack.assert_awaited_once()