Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): roll back a failed LoRA attach and keep adapter sources out of errors (#758)
Krisztian Gajdar6d4371ccff76
diff --git a/packages/sie_server/src/sie_server/adapters/base.py b/packages/sie_server/src/sie_server/adapters/base.pyindex 48e2daaca..feef90761 100644--- a/packages/sie_server/src/sie_server/adapters/base.py+++ b/packages/sie_server/src/sie_server/adapters/base.py@@ -572,8 +572,9 @@ 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) and SGLang (HTTP)- are the two adapters behind this capability.+ 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``."""return self if self.supports_lora() else Nonediff --git a/packages/sie_server/src/sie_server/adapters/lora.py b/packages/sie_server/src/sie_server/adapters/lora.pyindex 74eaf68aa..cfed2c530 100644--- a/packages/sie_server/src/sie_server/adapters/lora.py+++ b/packages/sie_server/src/sie_server/adapters/lora.py@@ -3,8 +3,9 @@Groups the LoRA lifecycle an adapter exposes when it supports LoRA into onetyped capability, so callers ask ``adapter.lora_capability()`` once and use thereturned handle instead of flag-checking ``supports_lora()`` and then calling-the individual hooks. The two implementations behind this capability are the-PEFT mixin (in-process, hot-reloadable) and the SGLang adapter (HTTP, blocking).+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``."""from __future__ import annotationsdiff --git a/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py b/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.pyindex ec4400a51..240816bad 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@@ -54,6 +54,21 @@ def is_lora_weight_key(key: str) -> bool:return tuple(parts[-2:]) in _ADAPTER_WEIGHT_SUFFIXES or parts[-1] in _ADAPTER_WEIGHT_PARAMETERS+def _unwrap_lora_layers(model: Any) -> None:+ """Put back each base module that a PEFT tuner layer wraps inside ``model``, and drop PEFT's config on it."""+ from peft.tuners.tuners_utils import BaseTunerLayer++ for name, module in list(model.named_modules()):+ if not isinstance(module, BaseTunerLayer):+ continue+ parent_name, _, child_name = name.rpartition(".")+ parent = model.get_submodule(parent_name)+ if getattr(parent, child_name, None) is module:+ setattr(parent, child_name, module.get_base_layer())+ if hasattr(model, "peft_config"):+ del model.peft_config++def validate_lora_target_modules(lora_path: str,target_modules: Any,@@ -303,21 +318,25 @@ class PEFTLoRAMixin:peft_adapter_name = self._peft_adapter_name(lora_path)- if self._peft_model is None:- # First LoRA - wrap the base model- logger.debug("Creating PeftModel from base model")- self._peft_model = PeftModel.from_pretrained(- base_model,- source,- adapter_name=peft_adapter_name,- )- # Update self._model to point to the PEFT-wrapped model- # This ensures encode() uses the LoRA-enhanced model- self._model = self._peft_model- else:- # Additional LoRA - add to existing PeftModel- logger.debug("Adding adapter to existing PeftModel")- self._peft_model.load_adapter(source, adapter_name=peft_adapter_name)+ try:+ if self._peft_model is None:+ # First LoRA - wrap the base model+ logger.debug("Creating PeftModel from base model")+ self._peft_model = PeftModel.from_pretrained(+ base_model,+ source,+ adapter_name=peft_adapter_name,+ )+ # Update self._model to point to the PEFT-wrapped model+ # This ensures encode() uses the LoRA-enhanced model+ self._model = self._peft_model+ else:+ # Additional LoRA - add to existing PeftModel+ logger.debug("Adding adapter to existing PeftModel")+ self._peft_model.load_adapter(source, adapter_name=peft_adapter_name)+ except Exception:+ self._detach_failed_lora(base_model, peft_adapter_name)+ raiseself._loaded_loras.add(lora_path)self._lora_adapter_names[lora_path] = peft_adapter_name@@ -335,6 +354,22 @@ class PEFTLoRAMixin:return memory_bytes+ def _detach_failed_lora(self, base_model: Any, peft_adapter_name: str) -> None:+ """Remove what PEFT attached for a LoRA whose load raised, so no request runs through it.++ PEFT injects a LoRA's layers into the model before it loads the+ adapter's weights, so a load that fails on the weights leaves them in+ place. A first LoRA's layers wrap the shared base model's own modules,+ which are restored here; a later LoRA's adapter is deleted from the+ existing PeftModel.+ """+ if self._peft_model is None:+ _unwrap_lora_layers(base_model)+ self._model = base_model+ return+ if peft_adapter_name in self._peft_model.peft_config:+ self._peft_model.delete_adapter(peft_adapter_name)+def _check_lora_config(self, lora_path: str, peft_config: PeftConfig) -> None:"""Refuse a LoRA from its ``adapter_config.json`` before any weights load.@@ -342,7 +377,8 @@ class PEFTLoRAMixin:model, which every request shares, as it was. PEFT rewrites the baseweights while it loads a LoRA whose ``init_lora_weights`` is not one of:data:`_BASE_PRESERVING_INITIALIZERS` or a boolean, restructures the- base model for ``layer_replication``, and imports the module named by+ base model for ``layer_replication``, replaces whole base modules for+ ``modules_to_save`` and ``trainable_token_indices``, and imports the module named by``megatron_core`` for ``megatron_config``. A LoRA whose ``bias`` is not``"none"`` trains biases that live in the base model's own layers; PEFTcannot turn them off with the adapter. A LoRA whose ``target_modules``@@ -362,7 +398,7 @@ class PEFTLoRAMixin:)raise ValueError(msg)- for field in ("layer_replication", "megatron_config"):+ for field in ("layer_replication", "megatron_config", "modules_to_save", "trainable_token_indices"):if getattr(peft_config, field, None):msg = f"LoRA '{lora_path}' sets {field}, which changes the base model every request shares."raise ValueError(msg)diff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.pyindex e939cd903..4c9fff4d6 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py@@ -39,6 +39,7 @@ from sie_server.core.inference_output import EncodeOutputfrom sie_server.core.tokenizer import load_tokenizerif TYPE_CHECKING:+ from sie_server.adapters.lora import LoraCapabilityfrom sie_server.types.inputs import Itemlogger = logging.getLogger(__name__)@@ -914,6 +915,13 @@ class SGLangEmbeddingAdapter(BaseAdapter):"""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.diff --git a/packages/sie_server/src/sie_server/api/encode.py b/packages/sie_server/src/sie_server/api/encode.pyindex 5005175b9..6180622cd 100644--- a/packages/sie_server/src/sie_server/api/encode.py+++ b/packages/sie_server/src/sie_server/api/encode.py@@ -333,7 +333,7 @@ async def encode(# Check if LoRA is specified and ensure it's loadedlora = options.get("lora_id")if lora is not None:- await ModelStateChecker(registry, route.key, span).ensure_lora_loaded(lora)+ await ModelStateChecker(registry, route.key, span).ensure_lora_loaded(lora, request_options)# Worker batcher routes on options["lora"]; profile uses "lora_id".options["lora"] = loradiff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.pyindex a2b2cb1d9..b64548b30 100644--- a/packages/sie_server/src/sie_server/api/helpers.py+++ b/packages/sie_server/src/sie_server/api/helpers.py@@ -487,18 +487,28 @@ class ModelStateChecker:headers={"Retry-After": "5"},)- async def ensure_lora_loaded(self, lora: str) -> None:+ async def ensure_lora_loaded(self, lora: str, request_options: dict[str, Any] | None) -> None:"""Start loading a LoRA adapter if needed, raise 503 to retry.+ The error text names ``lora`` only when the caller's own options carry+ that value. Otherwise ``lora`` is the selected profile's declared+ source, and the text names the profile instead.+Args:lora: LoRA id selected by the resolved profile or request options.+ request_options: The caller's own request options, before the profile's are merged in.Raises:HTTPException: 503 ``LORA_LOADING`` with ``Retry-After`` while theadapter loads or while a failed load waits for its backoff,- 500 if it failed to load, 400 if the model does not support- LoRA or does not declare ``lora``.+ 500 if it failed to load, 400 if the model cannot load a LoRA+ at runtime or does not declare ``lora``."""+ options = request_options or {}+ if lora in (options.get("lora_id"), options.get("lora")):+ subject = f"LoRA '{lora}'"+ else:+ subject = f"The LoRA adapter of profile '{options.get('profile') or 'default'}'"try:is_ready, is_loading = await self.registry.ensure_lora_loaded_async(self.model, lora)if is_loading:@@ -509,7 +519,7 @@ class ModelStateChecker:status_code=status.HTTP_503_SERVICE_UNAVAILABLE,detail={"code": ErrorCode.LORA_LOADING.value,- "message": f"LoRA '{lora}' {state} for model '{self.model}', please retry",+ "message": f"{subject} {state} for model '{self.model}', please retry",},headers={"Retry-After": str(self.registry.lora_retry_after_s(self.model, lora))},)@@ -519,7 +529,7 @@ class ModelStateChecker:status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail={"code": ErrorCode.INFERENCE_ERROR.value,- "message": f"Failed to load LoRA '{lora}' for model '{self.model}'",+ "message": f"{subject} failed to load for model '{self.model}'",},)except ValueError as e:diff --git a/packages/sie_server/src/sie_server/api/openai_compat.py b/packages/sie_server/src/sie_server/api/openai_compat.pyindex 033b0b02a..99f6bfdb3 100644--- a/packages/sie_server/src/sie_server/api/openai_compat.py+++ b/packages/sie_server/src/sie_server/api/openai_compat.py@@ -499,7 +499,7 @@ async def _create_embeddings(lora = options.get("lora_id")if lora is not None:- await ModelStateChecker(registry, route.key, span).ensure_lora_loaded(lora)+ await ModelStateChecker(registry, route.key, span).ensure_lora_loaded(lora, None)options["lora"] = lora# Run encodingdiff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.pyindex 0aeb1b8cb..3eb5ab796 100644--- a/packages/sie_server/src/sie_server/core/model_loader.py+++ b/packages/sie_server/src/sie_server/core/model_loader.py@@ -735,8 +735,8 @@ class ModelLoader:)# Preload profile LoRAs if the adapter exposes a LoRA capability.- # Engine-owned adapters (sglang: ``supports_hot_lora_reload() == False``)- # consume ``loadtime.lora_paths`` themselves at engine launch, so only+ # 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.lora_cap = adapter.lora_capability()diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex f97623aea..3c5ee2b39 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -3427,11 +3427,11 @@ class ModelRegistry:# scattered supports_lora() / supports_hot_lora_reload() flag-checks.lora_cap = adapter.lora_capability()if lora_cap is None:- msg = f"Model '{model}' does not support LoRA"+ msg = f"Model '{model}' cannot load a LoRA adapter at runtime"raise ValueError(msg)if lora not in loaded_model.config.lora_revisions():- msg = f"Model '{model}' does not declare LoRA '{lora}'"+ msg = f"Model '{model}' does not declare this LoRA adapter"raise ValueError(msg)lora_state = loaded_model.loras.get(lora)@@ -3493,7 +3493,7 @@ class ModelRegistry:task.add_done_callback(self._background_tasks.discard)return (False, True)- # Blocking load (SGLang) - load synchronously+ # Blocking load - load synchronouslyawait self._load_lora(model, lora)return (self.is_lora_loaded(model, lora), self.lora_load_failed(model, lora))diff --git a/packages/sie_server/src/sie_server/core/worker/model_worker.py b/packages/sie_server/src/sie_server/core/worker/model_worker.pyindex f5d5a85b3..fe9cfd642 100644--- a/packages/sie_server/src/sie_server/core/worker/model_worker.py+++ b/packages/sie_server/src/sie_server/core/worker/model_worker.py@@ -706,8 +706,9 @@ class ModelWorker:When the registry can load that LoRA, it starts the load and therequests fail with the retryable :class:`LoraNotReadyError`; otherwise- they fail with :class:`InvalidInputError`. Neither message names any- other adapter.+ they fail with :class:`InvalidInputError`. Neither message names an+ adapter: a batch's LoRA can be a profile's declared source that its+ callers never sent."""model = self._model_name or "unknown"logger.warning("LoRA '%s' cannot be made active on model '%s': %s", lora, model, error)@@ -722,10 +723,13 @@ class ModelWorker:failure: Exceptionif retry_after_s is not None:failure = LoraNotReadyError(- f"LoRA '{lora}' is loading on model '{model}', please retry", retry_after_s=retry_after_s+ f"The LoRA adapter this request selects is loading on model '{model}', please retry",+ retry_after_s=retry_after_s,)else:- failure = InvalidInputError(f"LoRA '{lora}' is not available on model '{model}'")+ failure = InvalidInputError(+ f"The LoRA adapter this request selects is not available on model '{model}'"+ )failure.__cause__ = errormetadata.future.set_exception(failure)diff --git a/packages/sie_server/tests/adapters/test_lora.py b/packages/sie_server/tests/adapters/test_lora.pyindex ae00cd954..3b71554a0 100644--- a/packages/sie_server/tests/adapters/test_lora.py+++ b/packages/sie_server/tests/adapters/test_lora.py@@ -27,19 +27,24 @@ from unittest.mock import MagicMock, patchimport pytestimport torch+from fastapi import HTTPExceptionfrom peft import LoraConfig, PeftModel, get_peft_model+from peft.tuners.tuners_utils import BaseTunerLayer+from safetensors.torch import load_file, save_filefrom sie_server.adapters import peft_lora_mixinfrom sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDimsfrom sie_server.adapters.bert_flash import BertFlashAdapterfrom sie_server.adapters.nomic_flash import NomicFlashAdapterfrom sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin, validate_lora_target_modules+from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter+from sie_server.api.helpers import ModelStateCheckerfrom sie_server.config.model import AdapterOptions, EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasksfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.model_loader import DEFAULT_MAX_LORAS, LoadedLora, LoadedModel, ModelLoaderfrom sie_server.core.prepared import make_text_itemfrom sie_server.core.registry import ModelRegistryfrom sie_server.core.worker import ModelWorker, WorkerConfig-from sie_server.types.inputs import Item+from sie_server.types.inputs import InvalidInputError, Itemfrom sie_server.types.responses import ErrorCodefrom torch import nn@@ -688,7 +693,7 @@ class TestLoraRejectionOnNonSupportingAdapters:registry._configs["stub-model"] = MagicMock()registry._loaded["stub-model"] = loaded- with pytest.raises(ValueError, match="does not support LoRA"):+ with pytest.raises(ValueError, match="cannot load a LoRA adapter at runtime"):await registry.ensure_lora_loaded_async("stub-model", "org/customer-lora")@@ -1374,6 +1379,7 @@ class TestLoraFetchOutsideInference:assert result.output.dense is not Noneassert adapter._loaded_loras == {lora}+ assert adapter.fetches == [lora]async def test_a_failing_lora_is_not_fetched_again_inside_its_backoff(self, tmp_path: Path) -> None:lora = _save_plain_lora(tmp_path / "failing")@@ -1467,3 +1473,165 @@ class TestLoraWeightKeys:)def test_any_other_tensor_is_refused(self, key: str) -> None:assert not peft_lora_mixin.is_lora_weight_key(key)+++def _save_rank_mismatched_lora(path: Path) -> str:+ """A LoRA on ``query`` and ``out`` whose ``out.lora_A`` has rank 3 where its config says 2.++ Every tensor name is a LoRA parameter, so the adapter passes the fetch+ checks; PEFT injects its layers and copies the ``query`` tensors before the+ ``out`` shape mismatch fails the load.+ """+ trained = get_peft_model(+ _tiny_encoder(), LoraConfig(r=2, target_modules=["query", "out"], bias="none", init_lora_weights=False)+ )+ trained.save_pretrained(str(path))+ weights = path / "adapter_model.safetensors"+ tensors = load_file(str(weights))+ tensors["base_model.model.out.lora_A.weight"] = torch.ones(3, 4)+ save_file(tensors, str(weights))+ return str(path)+++async def _load_in_background(registry: ModelRegistry, lora: str) -> None:+ assert await registry.ensure_lora_loaded_async("t/tiny", lora) == (False, True)+ await asyncio.gather(*registry._background_tasks)+++async def _encode_one(worker: ModelWorker, lora: str | None) -> torch.Tensor:+ future = await worker.submit(+ [make_text_item([1], 0)], [Item(text="x")], ["dense"], options={"lora": lora} if lora else None+ )+ result = await asyncio.wait_for(future, 5)+ return torch.as_tensor(result.output.dense[0])+++class TestFailedLoraAttach:+ """A LoRA whose attach fails after PEFT injected its layers leaves the shared model as it was."""++ @pytest.mark.parametrize("after_a_loaded_lora", [False, True])+ async def test_base_batches_are_unchanged_after_a_failed_attach_and_its_retry(+ self, tmp_path: Path, after_a_loaded_lora: bool+ ) -> None:+ loaded_lora = _save_plain_lora(tmp_path / "loaded")+ broken = _save_rank_mismatched_lora(tmp_path / "broken")+ adapter = _GatedFetchAdapter({})+ adapter.load("cpu")+ base = adapter._model(_probe()[:1]).detach()[0]+ worker = ModelWorker(adapter, WorkerConfig(max_batch_wait_ms=1))+ registry, loaded = _registry_serving(adapter, _tiny_config([loaded_lora, broken]), worker=worker)+ await worker.start()+ try:+ if after_a_loaded_lora:+ await _load_in_background(registry, loaded_lora)+ with_lora = await _encode_one(worker, loaded_lora)+ base_after: list[torch.Tensor] = []+ for attempt in (1, 2):+ await _load_in_background(registry, broken)+ assert loaded.lora_failures[broken].attempts == attempt+ loaded.lora_failures[broken].retry_at = time.monotonic() - 1+ base_after.append(await _encode_one(worker, None))+ if after_a_loaded_lora:+ with_lora_after = await _encode_one(worker, loaded_lora)+ finally:+ await worker.stop()++ assert all(torch.equal(output, base) for output in base_after)+ assert broken not in adapter._loaded_loras+ if after_a_loaded_lora:+ assert not torch.equal(with_lora, base)+ assert torch.equal(with_lora_after, with_lora)+ assert adapter._peft_adapter_name(broken) not in adapter._peft_model.peft_config+ else:+ assert adapter._peft_model is None+ assert not any(isinstance(module, BaseTunerLayer) for module in adapter._model.modules())+ assert not hasattr(adapter._model, "peft_config")++ @pytest.mark.parametrize("after_a_loaded_lora", [False, True])+ def test_a_declared_lora_whose_preload_fails_leaves_the_base_model_unchanged(+ self, tmp_path: Path, after_a_loaded_lora: bool+ ) -> None:+ broken = _save_rank_mismatched_lora(tmp_path / "broken")+ declared = [_save_plain_lora(tmp_path / "loaded"), broken] if after_a_loaded_lora else [broken]+ adapter = TinyLoRAAdapter()+ adapter.load("cpu")+ expected = adapter._model(_probe()).detach()+ loader = ModelLoader(+ preprocessor_registry=MagicMock(),+ postprocessor_registry=MagicMock(),+ all_configs={},+ )++ loaded = loader._finish_load("t/tiny", "cpu", adapter, _tiny_config(declared))++ assert list(loaded.loras) == declared[:-1]+ adapter.set_active_lora(None)+ assert torch.equal(adapter._model(_probe()), expected)+ if after_a_loaded_lora:+ assert adapter._peft_adapter_name(broken) not in adapter._peft_model.peft_config+ else:+ assert adapter._peft_model is None+ assert not any(isinstance(module, BaseTunerLayer) for module in adapter._model.modules())++ @pytest.mark.parametrize("field", ["modules_to_save", "trainable_token_indices"])+ def test_a_lora_that_replaces_whole_base_modules_is_refused(self, field: str) -> None:+ config = SimpleNamespace(peft_type="LORA", bias="none", init_lora_weights=True, **{field: ["out"]})+ with pytest.raises(ValueError, match=field):+ TinyLoRAAdapter()._check_lora_config("org/lora", config)+++def _engine_owned_lora_config() -> ModelConfig:+ return ModelConfig(+ sie_id="t/engine",+ hf_id="org/engine",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=2))),+ profiles={+ "default": ProfileConfig(+ adapter_path="mod:Cls",+ max_batch_tokens=8,+ adapter_options=AdapterOptions(loadtime={"lora_paths": {"legal": "org/legal-lora"}}),+ )+ },+ )+++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"})+ registry, loaded = _registry_serving(adapter, _engine_owned_lora_config())+ checker = ModelStateChecker(registry, "t/engine", MagicMock())++ for _ in range(3):+ with pytest.raises(ValueError, match="cannot load a LoRA adapter at runtime"):+ await registry.ensure_lora_loaded_async("t/engine", "org/legal-lora")+ with pytest.raises(HTTPException) as raised:+ await checker.ensure_lora_loaded("org/legal-lora", {"lora_id": "org/legal-lora"})+ assert raised.value.status_code == 400+ assert raised.value.headers is None+ assert registry.request_lora_load("t/engine", "org/legal-lora") is None++ assert not registry._background_tasks+ assert not loaded.loras+ assert not loaded.lora_failures++ @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"})+ registry, _ = _registry_serving(adapter, _engine_owned_lora_config())+ worker = ModelWorker(+ adapter, WorkerConfig(max_batch_wait_ms=1), model_name="t/engine", registry_callbacks=registry+ )+ submit = worker.submit_preformed if preformed else worker.submit+ await worker.start()+ try:+ future = await submit(+ [make_text_item([1], 0)], [Item(text="x")], ["dense"], options={"lora": "org/legal-lora"}+ )+ with pytest.raises(InvalidInputError):+ await asyncio.wait_for(future, 5)+ finally:+ await worker.stop()++ assert not registry._background_tasksdiff --git a/packages/sie_server/tests/adapters/test_lora_declared_only.py b/packages/sie_server/tests/adapters/test_lora_declared_only.pyindex 9e7870538..0a1a3cec7 100644--- a/packages/sie_server/tests/adapters/test_lora_declared_only.py+++ b/packages/sie_server/tests/adapters/test_lora_declared_only.py@@ -37,8 +37,10 @@ from sie_server.ipc_types import (ExtractBatchItem,ProcessEncodeBatchRequest,ProcessExtractBatchRequest,+ ProcessScoreBatchRequest,RunBatchItem,RunBatchRequest,+ ScoreBatchItem,)from sie_server.queue_executor import QueueExecutor@@ -101,7 +103,7 @@ def _model_yaml(profiles: dict[str, dict[str, Any]]) -> str:"sie_id": MODEL,"package_backed": True,"inputs": {"text": True},- "tasks": {"encode": {"dense": {"dim": 4}}, "extract": {}},+ "tasks": {"encode": {"dense": {"dim": 4}}, "extract": {}, "score": {}},"profiles": {"default": {"adapter_path": "tiny_lora_adapter.py:TinyLoraAdapter",@@ -112,8 +114,9 @@ def _model_yaml(profiles: dict[str, dict[str, Any]]) -> str:}for name, spec in profiles.items():adapter_options: dict[str, Any] = {}- if "lora_id" in spec:- adapter_options["runtime"] = {"lora_id": spec["lora_id"]}+ runtime = {key: spec[key] for key in ("lora_id", "lora") if key in spec}+ if runtime:+ adapter_options["runtime"] = runtimeif "lora_paths" in spec:adapter_options["loadtime"] = {"dense_dim": 4, "lora_paths": spec["lora_paths"]}config["profiles"][name] = {"extends": "default", "adapter_options": adapter_options}@@ -134,6 +137,20 @@ def _save_lora(helpers: ModuleType, path: Path, **config_overrides: Any) -> str:return str(path)+def _save_rank_mismatched_lora(helpers: ModuleType, path: Path) -> str:+ torch.manual_seed(1)+ trained = get_peft_model(+ helpers.tiny_encoder(),+ LoraConfig(r=2, target_modules=["query", "out"], bias="none", init_lora_weights=False),+ )+ trained.save_pretrained(str(path))+ weights = path / "adapter_model.safetensors"+ tensors = load_file(str(weights))+ tensors["base_model.model.out.lora_A.weight"] = torch.ones(3, 4)+ save_file(tensors, str(weights))+ return str(path)++def _base_vector(helpers: ModuleType, text: str) -> np.ndarray:with torch.no_grad():return helpers.tiny_encoder()(helpers.features(text).unsqueeze(0))[0].numpy()@@ -146,6 +163,21 @@ def _encode(url: str, text: str, options: dict[str, Any] | None = None) -> httpxreturn httpx.post(f"{url}/v1/encode/{MODEL}", json=body, headers={"Accept": "application/json"}, timeout=10)+def _extract(url: str, options: dict[str, Any] | None = None) -> httpx.Response:+ params: dict[str, Any] = {"labels": ["thing"]}+ if options is not None:+ params["options"] = options+ body = {"items": [{"text": "hello"}], "params": params}+ return httpx.post(f"{url}/v1/extract/{MODEL}", json=body, headers={"Accept": "application/json"}, timeout=10)+++def _score(url: str, options: dict[str, Any] | None = None) -> httpx.Response:+ body: dict[str, Any] = {"query": {"text": "hello"}, "items": [{"text": "world"}]}+ if options is not None:+ body["options"] = options+ return httpx.post(f"{url}/v1/score/{MODEL}", json=body, headers={"Accept": "application/json"}, timeout=10)++def _encode_when_ready(url: str, text: str, options: dict[str, Any] | None = None) -> httpx.Response:deadline = time.monotonic() + 30while True:@@ -355,6 +387,8 @@ class TestDirectEncodeRoute:first = _encode(server.url, "hello", {"profile": "missing"})assert first.status_code == 503, first.textassert _error_code(first) == "LORA_LOADING"+ assert "profile 'missing'" in first.text+ assert missing not in first.textdeadline = time.monotonic() + 10while not server.app.state.registry.lora_load_failed(MODEL, missing):assert time.monotonic() < deadline, "the failing load was not recorded"@@ -365,7 +399,66 @@ class TestDirectEncodeRoute:assert response.status_code == 503, response.textassert _error_code(response) == "LORA_LOADING"assert int(response.headers["Retry-After"]) > 1+ assert missing not in response.textassert server.fetches().count(missing) == fetches+ own = _encode(server.url, "hello", {"profile": "missing", "lora_id": missing})+ assert own.status_code == 503, own.text+ assert missing in own.text++ def test_a_caller_who_names_only_the_profile_is_not_told_its_adapter_source(+ self, tmp_path: Path, helpers: ModuleType, serve: Any+ ) -> None:+ selected = str(tmp_path / "selected-lora")+ loaded = str(tmp_path / "loaded-lora")++ with serve({"selects": {"lora_paths": [selected], "lora": selected}, "loads": {"lora_id": loaded}}) as server:+ _encode_when_ready(server.url, "warm")+ for profile in ("selects", "loads"):+ for _ in range(3):+ response = _encode(server.url, "hello", {"profile": profile})+ assert response.status_code == 503, response.text+ assert _error_code(response) == "LORA_LOADING"+ assert str(tmp_path) not in response.text+ deadline = time.monotonic() + 30+ while True:+ response = httpx.post(+ f"{server.url}/v1/embeddings", json={"model": f"{MODEL}:loads", "input": "hello"}, timeout=10+ )+ assert response.status_code == 503, response.text+ assert str(tmp_path) not in response.text+ if "LORA_LOADING" in response.text:+ break+ assert time.monotonic() < deadline, response.text+ time.sleep(0.05)++ @pytest.mark.parametrize("after_a_loaded_lora", [False, True])+ def test_a_declared_lora_whose_attach_fails_leaves_the_base_model_unchanged(+ self, tmp_path: Path, helpers: ModuleType, serve: Any, after_a_loaded_lora: bool+ ) -> None:+ broken = _save_rank_mismatched_lora(helpers, tmp_path / "broken-lora")+ profiles: dict[str, dict[str, Any]] = {"broken": {"lora_id": broken}}+ if after_a_loaded_lora:+ profiles = {"declared": {"lora_id": _save_lora(helpers, tmp_path / "declared-lora")}, **profiles}+ base = _base_vector(helpers, "hello")++ with serve(profiles) as server:+ assert np.allclose(_dense(_encode_when_ready(server.url, "hello")), base, atol=1e-5)+ failures = server.app.state.registry._loaded[MODEL].lora_failures+ for attempt in (1, 2):+ response = _encode(server.url, "hello", {"profile": "broken"})+ assert response.status_code == 503, response.text+ deadline = time.monotonic() + 10+ while broken not in failures or failures[broken].attempts < attempt:+ assert time.monotonic() < deadline, "the failing load was not recorded"+ time.sleep(0.05)+ failures[broken].retry_at = time.monotonic() - 1+ assert np.allclose(_dense(_encode(server.url, "hello")), base, atol=1e-5)+ assert broken not in server.loaded_ids()+ adapter = server.app.state.registry.get(MODEL)+ if after_a_loaded_lora:+ assert adapter._peft_adapter_name(broken) not in adapter._peft_model.peft_config+ else:+ assert adapter._peft_model is Nonedef test_selecting_a_declared_lora_that_is_not_loaded_is_retryable_instead_of_hanging(self, tmp_path: Path, helpers: ModuleType, serve: Any@@ -394,6 +487,31 @@ class TestDirectEncodeRoute:assert _error_code(response) == "LORA_LOADING"+class TestDirectExtractAndScoreRoutes:+ def test_an_undeclared_or_cross_profile_lora_is_refused_without_a_fetch(+ self, tmp_path: Path, helpers: ModuleType, serve: Any, hub_offline: None+ ) -> None:+ banking = _save_lora(helpers, tmp_path / "banking-lora")+ legal = _save_lora(helpers, tmp_path / "legal-lora")++ with serve({"banking": {"lora_id": banking}, "legal": {"lora_id": legal}}) as server:+ _encode_when_ready(server.url, "warm")+ assert _extract(server.url).status_code == 200+ assert _score(server.url).status_code == 200+ for options in (+ {"lora_id": "attacker-org/some-lora"},+ {"lora": "attacker-org/some-lora"},+ {"lora_id": banking},+ {"profile": "legal", "lora_id": banking},+ {"profile": "legal", "lora": banking},+ ):+ for response in (_extract(server.url, options), _score(server.url, options)):+ assert response.status_code == 400, (options, response.text)+ assert _error_code(response) == "INVALID_INPUT"+ assert server.loaded_ids() == {banking, legal}+ assert sorted(server.fetches()) == sorted([banking, legal])++class TestQueuedAndSidecarPaths:"""The worker's pre-formed batch path, reached through the queue executor and the sidecar's RunBatch."""@@ -433,6 +551,74 @@ class TestQueuedAndSidecarPaths:options=options,)+ @staticmethod+ def _score_item(options: dict[str, Any]) -> ScoreBatchItem:+ return ScoreBatchItem(+ work_item_id="req-3.0",+ request_id="req-3",+ item_index=0,+ total_items=1,+ timestamp=time.time(),+ query_item={"text": "hello"},+ score_items=[{"text": "world"}],+ options=options,+ )++ async def test_a_queued_score_refuses_an_undeclared_or_cross_profile_lora(+ self, tmp_path: Path, helpers: ModuleType, models_dir: Callable[[dict[str, dict[str, Any]]], Path]+ ) -> None:+ banking = _save_lora(helpers, tmp_path / "banking-lora")+ legal = _save_lora(helpers, tmp_path / "legal-lora")+ executor = await self._executor(models_dir({"banking": {"lora_id": banking}, "legal": {"lora_id": legal}}))++ (served,) = (+ await executor.process_score_batch(ProcessScoreBatchRequest(model_id=MODEL, items=[self._score_item({})]))+ ).outcomes+ assert served.error is None, served.error+ for options in (+ {"lora_id": "attacker-org/some-lora"},+ {"lora": "attacker-org/some-lora"},+ {"profile": "legal", "lora_id": banking},+ {"profile": "legal", "lora": banking},+ ):+ outcome = await executor.process_score_batch(+ ProcessScoreBatchRequest(model_id=MODEL, items=[self._score_item(options)])+ )+ (item,) = outcome.outcomes+ assert item.disposition == "publish_error_and_ack", options+ assert item.error_code == "INVALID_INPUT", (options, item.error)+ assert set(executor._registry._loaded[MODEL].loras) == {banking, legal}++ async def test_a_caller_who_names_only_the_profile_is_not_told_its_adapter_source(+ self, tmp_path: Path, helpers: ModuleType, models_dir: Callable[[dict[str, dict[str, Any]]], Path]+ ) -> None:+ selected = str(tmp_path / "selected-lora")+ executor = await self._executor(models_dir({"tenant": {"lora_paths": [selected], "lora": selected}}))+ options = {"profile": "tenant"}++ queued = await executor.process_encode_batch(+ ProcessEncodeBatchRequest(model_id=MODEL, items=[self._encode_item(options)])+ )+ extracted = await executor.process_extract_batch(+ ProcessExtractBatchRequest(model_id=MODEL, items=[self._extract_item(options)])+ )+ sidecar = await handle_run_batch(+ executor,+ RunBatchRequest(+ model_id=MODEL,+ batch_id=1,+ lora_key="",+ total_cost=1,+ items=[RunBatchItem(op="encode", encode=self._encode_item(options))],+ ),+ )++ for outcome in (*queued.outcomes, *extracted.outcomes, *sidecar.outcomes):+ assert outcome.disposition == "publish_error_and_ack"+ assert outcome.error_code == "LORA_LOADING", outcome.error+ assert outcome.error is not None+ assert str(tmp_path) not in outcome.error+async def test_a_served_name_the_adapter_cannot_select_fails_without_naming_loaded_adapters(self, tmp_path: Path, helpers: ModuleType, models_dir: Callable[[dict[str, dict[str, Any]]], Path]) -> None:diff --git a/packages/sie_server/tests/core/test_worker_lora.py b/packages/sie_server/tests/core/test_worker_lora.pyindex 94fd830bf..18ab0868a 100644--- a/packages/sie_server/tests/core/test_worker_lora.py+++ b/packages/sie_server/tests/core/test_worker_lora.py@@ -86,7 +86,7 @@ class TestModelWorkerLoRABatching:finally:await worker.stop()- assert "gone" in str(raised.value)+ assert "gone" not in str(raised.value)assert "org/private-lora" not in str(raised.value)assert result.output.dense is not None