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
release: v0.6.19
github-actions[bot]3bf4ea37dbab
diff --git a/.gitignore b/.gitignoreindex 9c9115ac4..0e48927bb 100644--- a/.gitignore+++ b/.gitignore@@ -272,4 +272,5 @@ tmp/.local/.requirements-modal.txt+b6_results.jsonpackages/sie_cloud/deploy/manifests/archive/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 81865d9f8..4153397f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,20 @@# Changelog+## v0.6.19++- chore(main): release 0.6.19+- fix(gateway): bump yanked spin 0.10.0 to 0.10.1 in Cargo.lock+- fix(server): return 404 instead of 500 for unknown models on inference endpoints+- fix(server): guard cross_encoder predict tokenization against the concurrent-metering race (class-fix for #1800)+- fix(server): colbert-small multivector encode returns one vector-set per input, worker-item order (#1800)+- fix(server): load tokenizer by pinned revision so offline chat-template rendering doesn't need refs/main (#1801)+- fix(server): terminal Failed readiness state so the sidecar dead-letters permanently-failed model loads+- chore(models): pin hf_revision for 12 unpinned launch-set models (§6.6)+- fix(server): Florence-2 processor compat with transformers 4.57+- docs(mcp): portable uv commands + context-management framing in README+- fix(cloud): address CodeRabbit review findings on #1782+- feat(cloud): idempotent catalog-sync converges the config catalog to in-repo model YAMLs (#1771)+## v0.6.18- chore(main): release 0.6.18diff --git a/README.md b/README.mdindex a4077d14b..df27ecc8d 100644--- a/README.md+++ b/README.md@@ -32,7 +32,7 @@ SIE is an open-source inference engine that runs the models behind every agent t- 85+ pre-configured models, hot-swappable, all quality-verified against MTEB in CI- Serves multiple models simultaneously with on-demand loading and LRU eviction-- Ships the full production stack: load-balancing gateway, KEDA autoscaling, Grafana dashboards, Terraform for GKE/EKS+- Ships the full production stack: load-balancing gateway, KEDA autoscaling, Grafana dashboards, Terraform for GKE/EKS/AKS- Integrates with LangChain, LlamaIndex, Haystack, DSPy, CrewAI, Chroma, Qdrant, and Weaviate- OpenAI-compatible `/v1/embeddings` endpoint for drop-in migration@@ -144,14 +144,14 @@ For the equivalent TypeScript example, see the [TypeScript SDK docs](https://sup### Production-The same code works against a production cluster. SIE ships a load-balancing gateway, KEDA autoscaling (scale to zero), Grafana dashboards, and Terraform modules for GKE and EKS. Not just the server, the whole stack. All Apache 2.0.+The same code works against a production cluster. SIE ships a load-balancing gateway, KEDA autoscaling (scale to zero), Grafana dashboards, and Terraform modules for GKE, EKS, and AKS. Not just the server, the whole stack. All Apache 2.0.```bashhelm upgrade --install sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \--namespace sie --create-namespace \--set hfToken.create=true \--set hfToken.value=YOUR_HF_TOKEN \- -f deploy/helm/sie-cluster/values-{gke|aws}.yaml+ -f deploy/helm/sie-cluster/values-{gke|aws|aks}.yaml```See the [deployment guide](https://superlinked.com/docs/deployment/).diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex d364dec33..4f4f7448b 100644--- a/deploy/helm/sie-cluster/Chart.yaml+++ b/deploy/helm/sie-cluster/Chart.yaml@@ -4,8 +4,8 @@ description: >-SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,and observabilitytype: application-version: 0.6.18 # x-release-please-version-appVersion: v0.6.18 # x-release-please-version+version: 0.6.19 # x-release-please-version+appVersion: v0.6.19 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex fa0ceb64a..09415ac6e 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.18"+version = "0.6.19"description = "SIE integration for ChromaDB"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.tomlindex 8f824d53c..2fadd3a76 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.18"+version = "0.6.19"description = "SIE integration for CrewAI"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.tomlindex afd71b1c4..f7054ef4e 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.18"+version = "0.6.19"description = "SIE integration for DSPy"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.tomlindex 05c17fe03..5e21ba3aa 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.18"+version = "0.6.19"description = "SIE integration for Haystack"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.tomlindex ad10dc89f..ceaf73696 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.18"+version = "0.6.19"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 84f572364..68cebebbe 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.18"+version = "0.6.19"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex 0ab82ff65..5751b47c5 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.18"+version = "0.6.19"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 7d71f722d..a239696c2 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.18"+version = "0.6.19"description = "SIE integration for Qdrant"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.jsonindex 1a90fb90e..923fa7c9b 100644--- a/integrations/sie_ts_chroma/package.json+++ b/integrations/sie_ts_chroma/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-chroma",- "version": "0.6.18",+ "version": "0.6.19","description": "SIE embedding function for ChromaDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.jsonindex 2c59f0edc..f7d0c2036 100644--- a/integrations/sie_ts_lancedb/package.json+++ b/integrations/sie_ts_lancedb/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-lancedb",- "version": "0.6.18",+ "version": "0.6.19","description": "SIE embedding function and reranker for LanceDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.jsonindex 6a1f53063..ae0703ef1 100644--- a/integrations/sie_ts_langchain/package.json+++ b/integrations/sie_ts_langchain/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-langchain",- "version": "0.6.18",+ "version": "0.6.19","description": "SIE embeddings integration for LangChain.js","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.jsonindex e31c85168..06c5f90d6 100644--- a/integrations/sie_ts_llamaindex/package.json+++ b/integrations/sie_ts_llamaindex/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-llamaindex",- "version": "0.6.18",+ "version": "0.6.19","description": "SIE embeddings integration for LlamaIndex.TS","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.tomlindex 15fe26ef3..ec95f8a7b 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.18"+version = "0.6.19"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_config/src/sie_config/config_api.py b/packages/sie_config/src/sie_config/config_api.pyindex a3ff4b62a..c9cdd454d 100644--- a/packages/sie_config/src/sie_config/config_api.py+++ b/packages/sie_config/src/sie_config/config_api.py@@ -190,6 +190,102 @@ def _get_idempotency_state(app_state: Any) -> _IdempotencyState:return existing+async def _idempotency_claim(+ idem: _IdempotencyState,+ idempotency_key: str,+ body_hash: str,+) -> tuple[Response | None, _IdempotencyInFlight | None]:+ """Wait-or-claim an idempotent write, mirroring ``add_model`` exactly.++ Returns ``(response, owner)``: exactly one is non-``None``. A non-``None``+ ``response`` is a cached/synthetic replay the caller must return verbatim;+ a non-``None`` ``owner`` is the in-flight marker this caller now owns and+ must later resolve via :func:`_idempotency_finalize` / :func:`_idempotency_fail`.+ Factored out of ``add_model`` so ``PUT`` shares byte-identical semantics+ (mismatch=422, cancelled/aborted owner=503, evicted-replay=200).+ """+ waited_in_flight: _IdempotencyInFlight | None = None+ while True:+ if waited_in_flight is not None:+ if waited_in_flight.exception is not None:+ if isinstance(waited_in_flight.exception, asyncio.CancelledError):+ raise HTTPException(+ status_code=503,+ detail={+ "error": "idempotent_inflight_cancelled",+ "idempotency_key": idempotency_key,+ "message": (+ "The prior in-flight request with this Idempotency-Key was cancelled "+ "before it completed. Retry the request to execute it."+ ),+ },+ ) from waited_in_flight.exception+ raise waited_in_flight.exception+ if not waited_in_flight.succeeded:+ raise HTTPException(+ status_code=503,+ detail={+ "error": "idempotent_inflight_aborted",+ "idempotency_key": idempotency_key,+ "message": (+ "The prior in-flight request with this Idempotency-Key ended without "+ "a completed response. Retry the request to execute it."+ ),+ },+ )++ async with idem.lock:+ cached = idem.cache.get(idempotency_key)+ if cached is not None:+ cached_status, cached_body, cached_payload_hash = cached+ if body_hash != cached_payload_hash:+ raise HTTPException(+ status_code=422,+ detail={+ "error": "idempotency_mismatch",+ "message": "Idempotency-Key reused with different payload.",+ },+ )+ return (+ Response(content=cached_body, status_code=cached_status, media_type="application/json"),+ None,+ )+ if waited_in_flight is not None:+ return (+ Response(+ content=orjson.dumps(+ {+ "error": "idempotent_replay_evicted",+ "idempotency_key": idempotency_key,+ "message": (+ "A prior request with this Idempotency-Key completed successfully, "+ "but its cached response was evicted. The write was applied exactly once; "+ "query GET /v1/configs/models/{id} to see the current state."+ ),+ }+ ).decode(),+ status_code=200,+ media_type="application/json",+ ),+ None,+ )+ in_flight = idem.in_flight.get(idempotency_key)+ if in_flight is None:+ owner = _IdempotencyInFlight(body_hash)+ idem.in_flight[idempotency_key] = owner+ return (None, owner)+ if body_hash != in_flight.payload_hash:+ raise HTTPException(+ status_code=422,+ detail={+ "error": "idempotency_mismatch",+ "message": "Idempotency-Key reused with different payload.",+ },+ )+ waited_in_flight = in_flight+ await in_flight.event.wait()++def _emit_audit_log(request: Request,*,@@ -434,99 +530,19 @@ async def add_model(request: Request) -> Response:},)- # Idempotency-Key support (checked after body read for payload hash)+ # Idempotency-Key support (checked after body read for payload hash).+ # The wait/replay/claim dance is shared with PUT via _idempotency_claim:+ # a non-None replay is returned verbatim; otherwise this request owns the+ # in-flight marker and must resolve it below (success caches + wakes, any+ # error records the exception + wakes so waiters aren't stuck forever).idempotency_key = request.headers.get("Idempotency-Key")body_hash = hashlib.sha256(body).hexdigest()idem = _get_idempotency_state(request.app.state) if idempotency_key else None+ owner_in_flight: _IdempotencyInFlight | None = Noneif idempotency_key and idem is not None:- # Track the in-flight record we waited on. A cache miss after- # waiting can mean either "successful response was evicted" or- # "the owner failed/cancelled before caching"; only the former- # may synthesize success.- waited_in_flight: _IdempotencyInFlight | None = None- owner_in_flight: _IdempotencyInFlight | None = None- while True:- if waited_in_flight is not None:- if waited_in_flight.exception is not None:- if isinstance(waited_in_flight.exception, asyncio.CancelledError):- raise HTTPException(- status_code=503,- detail={- "error": "idempotent_inflight_cancelled",- "idempotency_key": idempotency_key,- "message": (- "The prior in-flight request with this Idempotency-Key was cancelled "- "before it completed. Retry the request to execute it."- ),- },- ) from waited_in_flight.exception- raise waited_in_flight.exception- if not waited_in_flight.succeeded:- raise HTTPException(- status_code=503,- detail={- "error": "idempotent_inflight_aborted",- "idempotency_key": idempotency_key,- "message": (- "The prior in-flight request with this Idempotency-Key ended without "- "a completed response. Retry the request to execute it."- ),- },- )-- async with idem.lock:- cached = idem.cache.get(idempotency_key)- if cached is not None:- cached_status, cached_body, cached_payload_hash = cached- if body_hash != cached_payload_hash:- raise HTTPException(- status_code=422,- detail={- "error": "idempotency_mismatch",- "message": "Idempotency-Key reused with different payload.",- },- )- return Response(- content=cached_body,- status_code=cached_status,- media_type="application/json",- )- if waited_in_flight is not None:- # Woken by a completer but the response was evicted- # before we grabbed the lock. This waiter belongs to- # that completed owner, not to any later same-key- # retry that may have started after eviction.- return Response(- content=orjson.dumps(- {- "error": "idempotent_replay_evicted",- "idempotency_key": idempotency_key,- "message": (- "A prior request with this Idempotency-Key completed successfully, "- "but its cached response was evicted. The write was applied exactly once; "- "query GET /v1/configs/models/{id} to see the current state."- ),- }- ).decode(),- status_code=200,- media_type="application/json",- )- in_flight = idem.in_flight.get(idempotency_key)- if in_flight is None:- # Genuinely first request for this key.- owner_in_flight = _IdempotencyInFlight(body_hash)- idem.in_flight[idempotency_key] = owner_in_flight- break- if body_hash != in_flight.payload_hash:- raise HTTPException(- status_code=422,- detail={- "error": "idempotency_mismatch",- "message": "Idempotency-Key reused with different payload.",- },- )- waited_in_flight = in_flight- await in_flight.event.wait()+ replay, owner_in_flight = await _idempotency_claim(idem, idempotency_key, body_hash)+ if replay is not None:+ return replaycancellation_deferred = False@@ -898,6 +914,273 @@ async def add_model(request: Request) -> Response:)+def _canonical_config_for_compare(config: dict[str, Any]) -> Any:+ """A stable JSON-comparable form of a model config for unchanged detection.++ Sorts keys at every level so two YAML documents that differ only in key+ order / whitespace compare equal — the PUT no-op gate must not churn the+ epoch just because the serializer reordered a mapping.+ """+ return orjson.dumps(config, option=orjson.OPT_SORT_KEYS)++[email protected]("/models/{model_id:path}")+async def replace_model(request: Request, model_id: str) -> Response:+ """Replace a model's full config — the catalog-convergence write (#1771).++ ``POST /v1/configs/models`` is append-only: a profile that already exists+ with different content is a 409, so it cannot heal a catalog entry whose+ stored YAML has drifted from the current in-repo source (the stale bge-m3+ class that NAKs staging traffic on a ``bundle_config_hash`` mismatch). This+ endpoint REPLACES the stored config wholesale so the catalog converges to+ the source YAML regardless of prior content.++ Same admin write-auth, same ``Idempotency-Key`` semantics, and the same+ persist -> mutate-registry -> increment-epoch -> publish ordering (under the+ per-app write lock) as ``add_model``. Unchanged content is a genuine no-op:+ it neither bumps the epoch nor publishes, so a re-sync of an already-current+ catalog produces no churn.+ """+ _check_write_auth(request)+ start_time = time.monotonic()++ model_registry = _require_model_registry(request)+ nats_publisher: NatsPublisher | None = getattr(request.app.state, "nats_publisher", None)+ config_store: ConfigStore | None = getattr(request.app.state, "config_store", None)++ _validate_model_id(model_id)++ if nats_publisher and not nats_publisher.connected:+ raise HTTPException(+ status_code=503,+ detail={"error": "nats_unavailable", "message": "NATS not connected -- cannot distribute config changes."},+ )++ body = await request.body()+ if len(body) > _MAX_CONFIG_BODY_BYTES:+ raise HTTPException(+ status_code=413,+ detail={+ "error": "payload_too_large",+ "message": f"Config body exceeds {_MAX_CONFIG_BODY_BYTES} bytes limit.",+ },+ )++ idempotency_key = request.headers.get("Idempotency-Key")+ # Fold the request TARGET (method + model path) into the fingerprint: the+ # idempotency cache is application-wide, so two PUTs to different model paths+ # that share a key and an identical body (e.g. a body omitting sie_id) would+ # otherwise replay the first response and never write the second model.+ body_hash = hashlib.sha256(b"PUT\0" + model_id.encode("utf-8") + b"\0" + body).hexdigest()+ idem = _get_idempotency_state(request.app.state) if idempotency_key else None+ owner_in_flight: _IdempotencyInFlight | None = None+ if idempotency_key and idem is not None:+ replay, owner_in_flight = await _idempotency_claim(idem, idempotency_key, body_hash)+ if replay is not None:+ return replay++ cancellation_deferred = False++ async def _await_committed(awaitable: Any) -> Any:+ nonlocal cancellation_deferred+ task = asyncio.ensure_future(awaitable)+ while True:+ try:+ return await asyncio.shield(task)+ except asyncio.CancelledError:+ current_task = asyncio.current_task()+ if current_task is None or not current_task.cancelling():+ raise+ cancellation_deferred = True+ while current_task.cancelling():+ current_task.uncancel()+ if task.done():+ return task.result()++ try:+ try:+ config = yaml.safe_load(body.decode())+ except yaml.YAMLError as e:+ raise HTTPException(+ status_code=400,+ detail={"error": "parse_error", "message": f"Invalid YAML: {e}"},+ ) from e++ if not isinstance(config, dict):+ raise HTTPException(+ status_code=400,+ detail={"error": "parse_error", "message": "Expected YAML mapping at top level"},+ )++ body_sie_id = config.get("sie_id")+ if body_sie_id and body_sie_id != model_id:+ raise HTTPException(+ status_code=400,+ detail={+ "error": "model_id_mismatch",+ "message": f"Body sie_id {body_sie_id!r} does not match path model id {model_id!r}.",+ },+ )+ config.setdefault("sie_id", model_id)+ _validate_model_id(config["sie_id"])++ write_lock = _get_write_lock(request.app.state)+ async with write_lock:+ # Validate WITHOUT the append-only conflict gate — replace is+ # deliberate — so a malformed/unroutable body is still rejected.+ try:+ model_registry._validate_structure_locked(config)+ except ValueError as e:+ raise HTTPException(+ status_code=422,+ detail={"error": "validation_error", "details": [{"message": str(e)}]},+ ) from e++ # Unchanged-content no-op: compare the incoming config against the+ # registry's current merged config. Equal => no epoch bump, no+ # publish (a re-sync of an already-current catalog stays quiet).+ existing_full = model_registry.get_full_config(model_id)+ changed = existing_full is None or _canonical_config_for_compare(+ existing_full+ ) != _canonical_config_for_compare(config)++ affected_bundles: list[str] = []+ epoch = 0+ config_yaml = ""+ if changed:+ config_yaml = yaml.dump(config, default_flow_style=False, sort_keys=False)+ # Persist FIRST (disk is source of truth on restart), then mutate.+ if config_store:+ await _await_committed(asyncio.to_thread(config_store.write_model, model_id, config_yaml))+ try:+ affected_bundles = model_registry.replace_model_config(config)+ except ValueError as e: # pragma: no cover -- validated above+ raise HTTPException(+ status_code=422,+ detail={"error": "validation_error", "details": [{"message": str(e)}]},+ ) from e+ # Serialize the registry's authoritative merged form for the NATS+ # delta (matches add_model's no-store behaviour).+ merged = model_registry.get_full_config(model_id)+ if merged is not None:+ config_yaml = yaml.dump(merged, default_flow_style=False, sort_keys=False)+ if config_store:+ epoch = await _await_committed(asyncio.to_thread(config_store.increment_epoch))++ total = len(model_registry.list_models())+ api_count = 0+ if config_store:+ api_count = len(await _await_committed(asyncio.to_thread(config_store.list_models)))+ sie_metrics.update_models_gauge(+ api_count=api_count,+ filesystem_count=max(total - api_count, 0),+ )++ bundle_config_hashes = {}+ for bundle_id in affected_bundles:+ bundle_config_hashes[bundle_id] = model_registry.compute_bundle_config_hash(bundle_id)+ all_bundle_pool_config_hashes = model_registry.compute_bundle_pool_config_hashes()+ bundle_pool_config_hashes = {+ bundle_id: all_bundle_pool_config_hashes.get(bundle_id, {}) for bundle_id in affected_bundles+ }+ model_pool = model_registry.get_model_pool_name(model_id)++ nats_publish_failed = False+ partial_publish_failed_bundles: list[str] = []+ if changed and nats_publisher and nats_publisher.connected and affected_bundles:+ try:+ await _await_committed(+ nats_publisher.publish_config_notification(+ model_id=model_id,+ profiles_added=sorted(model_registry.get_model_profile_names(model_id)),+ affected_bundles=affected_bundles,+ bundle_config_hashes=bundle_config_hashes,+ epoch=epoch,+ model_config_yaml=config_yaml,+ model_pool=model_pool,+ bundle_pool_config_hashes=bundle_pool_config_hashes,+ )+ )+ except PartialPublishError as e:+ logger.exception(+ "Partial NATS publish for replaced model %s: %s/%s bundles failed: %s",+ model_id,+ len(e.failed_bundles),+ e.total,+ e.failed_bundles,+ )+ nats_publish_failed = True+ partial_publish_failed_bundles = e.failed_bundles+ except Exception:+ logger.exception("Failed to publish NATS notification for replaced model %s", model_id)+ nats_publish_failed = True++ router_id = nats_publisher.router_id if nats_publisher else "standalone"+ warnings: list[str] = []+ if partial_publish_failed_bundles:+ warnings.append(+ "nats_publish_partial: Config persisted but NATS notification failed for bundle(s) "+ f"{partial_publish_failed_bundles}. Workers on those bundles will stay on the previous "+ "epoch until the gateway's periodic epoch poll triggers a re-export."+ )+ elif nats_publish_failed:+ warnings.append(+ "nats_publish_failed: Config persisted but NATS notification failed. Workers may not be updated."+ )++ response_body: dict[str, Any] = {+ "model_id": model_id,+ "replaced": changed,+ "unchanged": not changed,+ "affected_bundles": affected_bundles,+ "warnings": warnings,+ "router_id": router_id,+ }+ response_json = orjson.dumps(response_body).decode()+ status_code = 200++ if idempotency_key and idem is not None and owner_in_flight is not None:+ await _await_committed(idem.lock.acquire())+ try:+ idem.cache[idempotency_key] = (status_code, response_json, body_hash)+ idem.cache.move_to_end(idempotency_key)+ while len(idem.cache) > _MAX_IDEMPOTENCY_CACHE_SIZE:+ idem.cache.popitem(last=False)+ owner_in_flight.succeeded = True+ if idem.in_flight.get(idempotency_key) is owner_in_flight:+ idem.in_flight.pop(idempotency_key, None)+ owner_in_flight.event.set()+ finally:+ idem.lock.release()++ except (Exception, asyncio.CancelledError) as e:+ if idempotency_key and idem is not None and owner_in_flight is not None:+ await _await_committed(idem.lock.acquire())+ try:+ owner_in_flight.exception = e+ if idem.in_flight.get(idempotency_key) is owner_in_flight:+ idem.in_flight.pop(idempotency_key, None)+ owner_in_flight.event.set()+ finally:+ idem.lock.release()+ raise++ elapsed_ms = (time.monotonic() - start_time) * 1000+ _emit_audit_log(+ request,+ event="config.replace_model",+ status=status_code,+ model=model_id,+ latency_ms=round(elapsed_ms, 2),+ body_bytes=len(body),+ )++ if cancellation_deferred:+ raise asyncio.CancelledError++ return Response(content=response_json, status_code=status_code, media_type="application/json")++@router.post("/resolve")async def resolve_config(request: Request) -> Response:"""Resolve a model spec to its bundle and routing info.diff --git a/packages/sie_config/src/sie_config/model_registry.py b/packages/sie_config/src/sie_config/model_registry.pyindex 0cf89f821..a8715a6c2 100644--- a/packages/sie_config/src/sie_config/model_registry.py+++ b/packages/sie_config/src/sie_config/model_registry.py@@ -1230,6 +1230,183 @@ class ModelRegistry:return created_profiles, skipped_profiles, affected_bundles+ def _validate_structure_locked(self, config: dict) -> None:+ """Structural + routability checks WITHOUT the append-only conflict gate.++ Must be called with ``self._lock`` held. This is the subset of+ ``_validate_config_locked`` that does not consult the model's prior+ profiles: required ``sie_id``/``profiles``, per-profile shape ++ ``adapter_path`` resolution, and the "every adapter module lands in+ some bundle" routability check. ``replace_model_config`` uses it+ because a REPLACE deliberately overwrites existing profiles (the+ append-only conflict check would reject exactly the stale-entry heal+ it exists to perform), yet must still refuse an unroutable or+ malformed body.+ """+ sie_id = config.get("sie_id")+ if not sie_id:+ msg = "Missing required field: sie_id"+ raise ValueError(msg)++ _normalize_pool_name(config)++ profiles = config.get("profiles", {})+ if not profiles:+ msg = "Missing required field: profiles"+ raise ValueError(msg)+ if not isinstance(profiles, dict):+ msg = "Field 'profiles' must be a mapping of profile_name -> profile_config"+ raise ValueError(msg)++ for profile_name, profile in profiles.items():+ _validate_profile_name(str(profile_name))+ if not isinstance(profile, dict):+ msg = f"Profile '{profile_name}' must be a mapping"+ raise ValueError(msg)+ # A REPLACE discards prior profiles, so _effective_adapter_path+ # resolves ``extends`` against ONLY the incoming set (no merge with+ # existing state, unlike the append-only path). An unresolved value —+ # including a dangling ``extends`` whose parent is absent from this+ # body — must be rejected here: there is no prior state to rescue it,+ # so exempting a profile merely because it declares ``extends`` would+ # persist an unrouteable variant.+ adapter_path = _effective_adapter_path(profiles, str(profile_name))+ if not adapter_path:+ msg = f"Profile '{profile_name}' missing adapter_path"+ raise ValueError(msg)++ # A REPLACE resolves routability against ONLY the incoming profiles+ # (it discards the prior ones), so unlike the append-only path there+ # is no merge with existing profiles here.+ new_adapter_modules = _adapter_modules_for_profiles(profiles)+ all_bundle_adapters: set[str] = set()+ for bundle in self._bundles.values():+ all_bundle_adapters.update(bundle.adapters)+ unroutable = new_adapter_modules - all_bundle_adapters+ if unroutable:+ msg = f"Adapter(s) not in any known bundle: {', '.join(sorted(unroutable))}"+ raise ValueError(msg)++ def replace_model_config(self, config: dict) -> list[str]:+ """Replace a model's config wholesale (the catalog-convergence path).++ Unlike :meth:`add_model_config` (append-only: existing profiles are+ immutable), this REPLACES the model's stored profiles + top-level+ metadata with ``config`` exactly. It exists to heal a catalog entry+ whose stored content has drifted from the current source YAML — the+ append-only POST path 409s on a changed profile, so a differing entry+ can only converge through a deliberate replace.++ Rebuilds the model's registry state (profiles, adapter modules, route+ + profile-variant maps, unrouteable snapshot) from the incoming+ config alone. Structural + routability validation still applies (a+ malformed or unroutable body is rejected). Returns the sorted list of+ bundles the replaced model now affects.++ Raises:+ ValueError: If validation fails (missing fields, unroutable adapter).+ """+ with self._lock:+ self._validate_structure_locked(config)++ sie_id = config["sie_id"]+ profiles = config["profiles"]+ existing = self._models.get(sie_id)++ # Build the post-replace state in fresh containers; only the+ # top-level pointer swaps are visible to lock-free readers, so they+ # observe the pre- or post-state, never a half-rebuilt entry (same+ # atomic-pointer-store discipline as add_model_config).+ new_profile_names = {str(pname) for pname in profiles}+ new_profile_configs = {str(pname): _canonical_profile_dict(pdata) for pname, pdata in profiles.items()}++ new_full_config: dict = dict(config)+ new_full_config["profiles"] = {str(pname): dict(pdata) for pname, pdata in profiles.items()}+ new_full_config["sie_id"] = sie_id++ # Bundles the model belonged to BEFORE this replace (captured before+ # the _model_adapter_modules swap below). A replace that moves or+ # drops a profile changes which bundles route to the model, so its OLD+ # bundles must also be notified — otherwise they keep a stale+ # bundle_config_hash (still counting the now-departed model) until a+ # later full refresh, and workers on them NAK on the mismatch (#1771).+ old_affected_bundles = _matching_bundle_names(+ self._model_adapter_modules.get(sie_id, set()),+ self._bundles,+ )+ new_adapter_modules_set = _adapter_modules_for_profiles(new_full_config["profiles"])+ route_adapter_modules = _base_route_adapter_modules(new_full_config["profiles"])+ affected_bundles = old_affected_bundles + _matching_bundle_names(new_adapter_modules_set, self._bundles)+ new_model_info = ModelInfo(+ name=sie_id,+ bundles=_matching_bundle_names(route_adapter_modules, self._bundles),+ )++ # Rebuild this model's profile-variant entries from scratch: drop+ # every variant that belonged to sie_id (stale profiles must not+ # survive a replace) and re-derive from the incoming profiles.+ new_profile_variant_models = {+ name: info+ for name, info in self._profile_variant_models.items()+ if self._profile_variant_base_models.get(name) != sie_id+ }+ new_profile_variant_names_lower = {+ lower: name+ for lower, name in self._profile_variant_names_lower.items()+ if self._profile_variant_base_models.get(name) != sie_id+ }+ new_profile_variant_base_models = {+ name: base for name, base in self._profile_variant_base_models.items() if base != sie_id+ }+ for profile_name in sorted(new_profile_names):+ if profile_name == "default":+ continue+ adapter_path = _effective_adapter_path(new_full_config["profiles"], profile_name)+ module_path = _adapter_module_from_path(adapter_path)+ variant_modules = {module_path} if module_path else set()+ variant_name = f"{sie_id}:{profile_name}"+ new_profile_variant_models[variant_name] = ModelInfo(+ name=variant_name,+ bundles=_matching_bundle_names(variant_modules, self._bundles),+ )+ new_profile_variant_names_lower[variant_name.lower()] = variant_name+ new_profile_variant_base_models[variant_name] = sie_id+ affected_bundles.extend(new_profile_variant_models[variant_name].bundles)+ affected_bundles.sort()+ affected_bundles = list(dict.fromkeys(affected_bundles))++ self._models = {**self._models, sie_id: new_model_info}+ if not existing:+ self._model_names_lower = {**self._model_names_lower, sie_id.lower(): sie_id}+ self._profile_variant_models = new_profile_variant_models+ self._profile_variant_names_lower = new_profile_variant_names_lower+ self._profile_variant_base_models = new_profile_variant_base_models+ self._model_adapter_modules = {**self._model_adapter_modules, sie_id: new_adapter_modules_set}+ self._model_profiles = {**self._model_profiles, sie_id: new_profile_names}+ self._model_profile_configs = {**self._model_profile_configs, sie_id: new_profile_configs}+ self._model_full_configs = {**self._model_full_configs, sie_id: new_full_config}++ all_bundle_adapters: set[str] = set()+ for bundle in self._bundles.values():+ all_bundle_adapters.update(bundle.adapters)+ missing_for_sie_id = new_adapter_modules_set - all_bundle_adapters+ new_unrouteable = {m: set(mods) for m, mods in self._unrouteable_models.items()}+ if missing_for_sie_id:+ new_unrouteable[sie_id] = missing_for_sie_id+ else:+ new_unrouteable.pop(sie_id, None)+ self._unrouteable_models = new_unrouteable++ self._bundle_hash_cache = {}++ logger.info(+ "Replaced model config: %s (profiles=%s, bundles=%s)",+ sie_id,+ sorted(new_profile_names),+ affected_bundles,+ )+ return affected_bundles+def get_model_profile_names(self, model_name: str) -> set[str]:"""Get known profile names for a model."""with self._lock:diff --git a/packages/sie_config/tests/test_config_api.py b/packages/sie_config/tests/test_config_api.pyindex b97b8e8b3..4f78c2682 100644--- a/packages/sie_config/tests/test_config_api.py+++ b/packages/sie_config/tests/test_config_api.py@@ -1983,3 +1983,173 @@ class TestMissingRegistryReturns503:resp = client.get("/v1/configs/export")assert resp.status_code == 503assert resp.json()["detail"]["error"] == "registry_unavailable"+++class TestConfigAPIReplace:+ """PUT /v1/configs/models/{id}: the catalog-convergence write (#1771).++ Unlike append-only POST, PUT replaces a model's stored config wholesale so+ a catalog entry whose content has drifted from the source YAML converges+ (the stale-bge-m3 heal). Unchanged content is a genuine no-op (no epoch+ churn). Same admin write-auth + Idempotency-Key semantics as POST.+ """++ def setup_method(self) -> None:+ self._tmpdir = tempfile.TemporaryDirectory()+ self._root = Path(self._tmpdir.name)+ self._bundles = self._root / "bundles"+ self._models = self._root / "models"+ self._store = self._root / "store"+ self._bundles.mkdir()+ self._models.mkdir()+ _write_bundle(self._bundles, "default", ["sie_server.adapters.bert_flash"])+ self.app = _create_test_app(self._bundles, self._models, str(self._store))+ self.client = TestClient(self.app)++ def teardown_method(self) -> None:+ self._tmpdir.cleanup()++ @staticmethod+ def _yaml(sie_id: str, *, tokens: int = 8192, profiles: str = "default") -> str:+ blocks = "".join(+ f" {p}:\n adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n max_batch_tokens: {tokens}\n"+ for p in profiles.split(",")+ )+ return f"sie_id: {sie_id}\nprofiles:\n{blocks}"++ def test_put_creates_new_model(self) -> None:+ resp = self.client.put("/v1/configs/models/new/model", content=self._yaml("new/model"))+ assert resp.status_code == 200, resp.text+ data = resp.json()+ assert data["model_id"] == "new/model"+ assert data["replaced"] is True+ assert data["unchanged"] is False+ assert self.app.state.config_store.read_model("new/model") is not None+ assert self.app.state.config_store.read_epoch() == 1++ def test_put_heals_a_differing_entry(self) -> None:+ # Seed a "stale" entry (append-only POST would 409 on a changed+ # profile) then converge it with a full replace.+ assert self.client.post("/v1/configs/models", content=self._yaml("stale/model", tokens=1024)).status_code == 201+ resp = self.client.put("/v1/configs/models/stale/model", content=self._yaml("stale/model", tokens=4096))+ assert resp.status_code == 200, resp.text+ assert resp.json()["replaced"] is True++ export = self.client.get("/v1/configs/export")+ entry = {m["model_id"]: m for m in export.json()["models"]}["stale/model"]+ assert entry["model_config"]["profiles"]["default"]["max_batch_tokens"] == 4096++ def test_put_unchanged_content_is_a_noop_no_epoch_bump(self) -> None:+ body = self._yaml("noop/model")+ assert self.client.put("/v1/configs/models/noop/model", content=body).status_code == 200+ epoch_after_first = self.app.state.config_store.read_epoch()+ assert epoch_after_first == 1++ resp = self.client.put("/v1/configs/models/noop/model", content=body)+ assert resp.status_code == 200, resp.text+ assert resp.json()["unchanged"] is True+ assert resp.json()["replaced"] is False+ # No churn: the epoch must not advance on an unchanged re-sync.+ assert self.app.state.config_store.read_epoch() == epoch_after_first++ def test_put_drops_stale_profiles(self) -> None:+ # Seed two profiles, then replace with only one — the dropped profile+ # must not survive (replace is not a merge).+ assert (+ self.client.put(+ "/v1/configs/models/multi/model", content=self._yaml("multi/model", profiles="default,fast")+ ).status_code+ == 200+ )+ resp = self.client.put("/v1/configs/models/multi/model", content=self._yaml("multi/model", profiles="default"))+ assert resp.status_code == 200, resp.text++ export = self.client.get("/v1/configs/export")+ entry = {m["model_id"]: m for m in export.json()["models"]}["multi/model"]+ assert set(entry["model_config"]["profiles"]) == {"default"}++ def test_put_body_sie_id_mismatch_is_400(self) -> None:+ resp = self.client.put("/v1/configs/models/path/id", content=self._yaml("other/id"))+ assert resp.status_code == 400+ assert resp.json()["detail"]["error"] == "model_id_mismatch"++ def test_put_defaults_sie_id_from_path(self) -> None:+ body = (+ "profiles:\n default:\n adapter_path: sie_server.adapters.bert_flash:Bert\n max_batch_tokens: 8192\n"+ )+ resp = self.client.put("/v1/configs/models/derived/id", content=body)+ assert resp.status_code == 200, resp.text+ assert resp.json()["model_id"] == "derived/id"++ def test_put_unroutable_adapter_is_422(self) -> None:+ body = "profiles:\n default:\n adapter_path: sie_server.adapters.unknown:X\n max_batch_tokens: 8192\n"+ resp = self.client.put("/v1/configs/models/bad/model", content=body)+ assert resp.status_code == 422+ assert resp.json()["detail"]["error"] == "validation_error"++ def test_put_invalid_yaml_is_400(self) -> None:+ resp = self.client.put("/v1/configs/models/x/y", content="{{bad")+ assert resp.status_code == 400++ def test_put_requires_admin_token(self, monkeypatch) -> None:+ monkeypatch.setenv("SIE_ADMIN_TOKEN", "admin-secret")+ resp = self.client.put("/v1/configs/models/auth/model", content=self._yaml("auth/model"))+ assert resp.status_code == 401 # missing Authorization header+ resp = self.client.put(+ "/v1/configs/models/auth/model",+ content=self._yaml("auth/model"),+ headers={"Authorization": "Bearer wrong"},+ )+ assert resp.status_code == 403+ resp = self.client.put(+ "/v1/configs/models/auth/model",+ content=self._yaml("auth/model"),+ headers={"Authorization": "Bearer admin-secret"},+ )+ assert resp.status_code == 200, resp.text++ def test_put_idempotency_key_replay(self) -> None:+ body = self._yaml("idem/model")+ headers = {"Idempotency-Key": "put-k1"}+ r1 = self.client.put("/v1/configs/models/idem/model", content=body, headers=headers)+ assert r1.status_code == 200, r1.text+ r2 = self.client.put("/v1/configs/models/idem/model", content=body, headers=headers)+ assert r2.status_code == 200+ assert r2.json() == r1.json()+ # Exactly one write applied.+ assert self.app.state.config_store.read_epoch() == 1++ def test_put_idempotency_key_reuse_different_body_is_422(self) -> None:+ headers = {"Idempotency-Key": "put-k2"}+ assert (+ self.client.put(+ "/v1/configs/models/idem2/model", content=self._yaml("idem2/model", tokens=1024), headers=headers+ ).status_code+ == 200+ )+ resp = self.client.put(+ "/v1/configs/models/idem2/model", content=self._yaml("idem2/model", tokens=2048), headers=headers+ )+ assert resp.status_code == 422+ assert resp.json()["detail"]["error"] == "idempotency_mismatch"++ def test_put_idempotency_same_key_body_different_path_does_not_false_replay(self) -> None:+ # The idempotency cache is application-wide, so the fingerprint folds in+ # the request target (model path). A body that omits sie_id (filled from+ # the path) is byte-identical across two paths; WITHOUT the target in the+ # fingerprint the second PUT would replay the first (returning 200 with+ # model_id="idemx/first") and never write idemx/second. WITH it the second+ # request has a distinct fingerprint, so it is caught as a key reused with a+ # different payload (422) rather than silently mis-written as the first.+ body = "profiles:\n default:\n adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n"+ headers = {"Idempotency-Key": "put-shared"}+ r1 = self.client.put("/v1/configs/models/idemx/first", content=body, headers=headers)+ assert r1.status_code == 200, r1.text+ assert r1.json()["model_id"] == "idemx/first"+ r2 = self.client.put("/v1/configs/models/idemx/second", content=body, headers=headers)+ # NOT a false 200 replay writing the wrong model — the target is in the hash.+ assert r2.status_code == 422+ assert r2.json()["detail"]["error"] == "idempotency_mismatch"+ # The first model still exists; the second was never (mis)written under the key.+ assert self.client.get("/v1/configs/models/idemx/first").status_code == 200+ assert self.client.get("/v1/configs/models/idemx/second").status_code == 404diff --git a/packages/sie_config/tests/test_model_registry_mutation.py b/packages/sie_config/tests/test_model_registry_mutation.pyindex bca6f76d9..e3d70f8dc 100644--- a/packages/sie_config/tests/test_model_registry_mutation.py+++ b/packages/sie_config/tests/test_model_registry_mutation.py@@ -621,3 +621,110 @@ class TestConcurrentAddModelConfig:for f in reader_futs:f.result()assert inconsistencies == [], f"Reader observed torn state: {inconsistencies[:5]}"+++class TestReplaceModelConfig:+ """replace_model_config: the wholesale (non-append) convergence path (#1771)."""++ @pytest.fixture(autouse=True)+ def _setup(self, tmp_path: Path) -> None:+ self._root = tmp_path++ def _cfg(self, sie_id: str, tokens: int = 8192, profiles: tuple[str, ...] = ("default",)) -> dict:+ return {+ "sie_id": sie_id,+ "profiles": {+ p: {"adapter_path": "sie_server.adapters.bert_flash:BertAdapter", "max_batch_tokens": tokens}+ for p in profiles+ },+ }++ def test_replace_creates_new_model(self) -> None:+ registry, _ = _setup_registry(self._root / "r_new")+ bundles = registry.replace_model_config(self._cfg("new/model"))+ assert "default" in bundles+ assert registry.model_exists("new/model")++ def test_replace_converges_changed_profile(self) -> None:+ registry, _ = _setup_registry(self._root / "r_change")+ registry.add_model_config(self._cfg("m/model", tokens=1024))+ assert registry.get_full_config("m/model")["profiles"]["default"]["max_batch_tokens"] == 1024+ registry.replace_model_config(self._cfg("m/model", tokens=4096))+ assert registry.get_full_config("m/model")["profiles"]["default"]["max_batch_tokens"] == 4096++ def test_replace_drops_stale_profiles(self) -> None:+ registry, _ = _setup_registry(self._root / "r_drop")+ registry.replace_model_config(self._cfg("m/model", profiles=("default", "fast")))+ assert registry.get_model_profile_names("m/model") == {"default", "fast"}+ registry.replace_model_config(self._cfg("m/model", profiles=("default",)))+ # The dropped profile must not survive a replace (unlike append-only add).+ assert registry.get_model_profile_names("m/model") == {"default"}+ # And its profile-variant route identity must be gone too.+ assert not registry.model_exists("m/model:fast")++ def test_replace_rejects_unroutable(self) -> None:+ registry, _ = _setup_registry(self._root / "r_bad")+ cfg = {+ "sie_id": "bad/model",+ "profiles": {"default": {"adapter_path": "sie_server.adapters.nope:X", "max_batch_tokens": 8192}},+ }+ with pytest.raises(ValueError, match="not in any known bundle"):+ registry.replace_model_config(cfg)++ def test_replace_rejects_missing_profiles(self) -> None:+ registry, _ = _setup_registry(self._root / "r_empty")+ with pytest.raises(ValueError, match="profiles"):+ registry.replace_model_config({"sie_id": "x/y"})++ def test_replace_updates_bundle_config_hash(self) -> None:+ registry, _ = _setup_registry(self._root / "r_hash")+ registry.add_model_config(self._cfg("m/model", tokens=1024))+ before = registry.compute_bundle_config_hash("default")+ registry.replace_model_config(self._cfg("m/model", tokens=4096))+ after = registry.compute_bundle_config_hash("default")+ # A content change must move the worker-parity hash (the drift the sync heals).+ assert before != after++ def test_replace_rejects_dangling_extends(self) -> None:+ # A replace discards prior profiles, so `extends` resolves against ONLY+ # the incoming set: a profile that extends a parent absent from this body+ # cannot resolve an adapter_path and must be rejected (an `extends` value+ # alone no longer exempts it — that would persist an unrouteable variant).+ registry, _ = _setup_registry(self._root / "r_dangling")+ cfg = {+ "sie_id": "d/model",+ "profiles": {+ "default": {"adapter_path": "sie_server.adapters.bert_flash:BertAdapter", "max_batch_tokens": 8192},+ # extends a parent that is NOT in this body -> unresolvable.+ "orphan": {"extends": "not-in-this-body"},+ },+ }+ with pytest.raises(ValueError, match="missing adapter_path"):+ registry.replace_model_config(cfg)++ def test_replace_notifies_the_bundle_that_loses_the_model(self) -> None:+ # A replace that MOVES a model from bundle A to bundle B must notify BOTH:+ # B (the new home) AND A (which loses the model), or A keeps a stale+ # bundle_config_hash that still counts the departed model until a later+ # full refresh (#1771 lane↔catalog hash-parity).+ registry, _ = _setup_registry(+ self._root / "r_move",+ bundles={+ "a": ["sie_server.adapters.bert_flash"],+ "b": ["sie_server.adapters.sentence_transformer"],+ },+ )+ registry.replace_model_config(+ {+ "sie_id": "mv/model",+ "profiles": {"default": {"adapter_path": "sie_server.adapters.bert_flash:BertAdapter"}},+ }+ )+ moved = registry.replace_model_config(+ {+ "sie_id": "mv/model",+ "profiles": {"default": {"adapter_path": "sie_server.adapters.sentence_transformer:STAdapter"}},+ }+ )+ # Both the old bundle (a) and the new bundle (b) are notified.+ assert set(moved) >= {"a", "b"}diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lockindex 4cb86e87c..7cfaf9207 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -3159,7 +3159,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-gateway"-version = "0.6.18"+version = "0.6.19"dependencies = ["arc-swap","async-nats",@@ -3286,9 +3286,9 @@ dependencies = [[[package]]name = "spin"-version = "0.10.0"+version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d5fe4ccb98d9c292d56fec89a5e07da7fc4cf0dc11e156b41793132775d3e591"+checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3"[[package]]name = "spki"diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 214d34c3c..815139e7f 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.18"+version = "0.6.19"edition = "2021"publish = falsediff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex d50887213..c77721930 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -3020,7 +3020,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.18"+ "version": "0.6.19"},"openapi": "3.1.0","paths": {diff --git a/packages/sie_mcp/README.md b/packages/sie_mcp/README.mdindex d41b5a742..90b22efbb 100644--- a/packages/sie_mcp/README.md+++ b/packages/sie_mcp/README.md@@ -9,6 +9,16 @@ gets back. The raw bytes and any PII reach your edge, never the model API.cluster credential, exposes the document tools below over streamable-HTTP MCP, andauthenticates clients with a connector secret.+The offload is context management as much as it is privacy and cost. A parsed artifact+is roughly 85% fewer tokens than native document ingestion (the text plus a rendered+image per page), which does three things at once: it cuts the token bill, it keeps raw+bytes and PII on the cluster, and it keeps the agent's context window small. The last+one matters because models measurably degrade as context fills (context rot, the+lost-in-the-middle effect), so an agent that works from artifacts instead of raw+documents stays accurate deeper into a session and hits context compaction later. The+effect is strongest for `docs_to_markdown` (near-lossless density win); the summarize+and extract tools trade some information for even smaller context.+> Editable source: [`docs/architecture.excalidraw`](docs/architecture.excalidraw), open at [excalidraw.com](https://excalidraw.com) or the VS Code / Obsidian Excalidraw plugin.@@ -78,8 +88,8 @@ From the repo root:export SIE_MCP_URL="https://<mcp-host>/mcp"export SIE_MCP_CONNECTOR_SECRET="<connector-secret>"-mise run mcp-plugin-pack -- \- --cluster-label sie-test \+uv run --package sie-mcp sie-mcp plugin-pack \+ --cluster-label sie \--mcp-url "$SIE_MCP_URL"```@@ -112,7 +122,7 @@ Use the full plugin pack for normal installs. If you only need the uploadableclaude.ai skill ZIP:```bash-mise exec -- uv run --package sie-mcp python -m sie_mcp.cli skill-zip+uv run --package sie-mcp sie-mcp skill-zip```By default this writes@@ -129,7 +139,7 @@ export SIE_BASE_URL="https://<cluster-gateway>"export SIE_API_KEY="<cluster-api-key>" # omit if the gateway has no authexport SIE_MCP_CONNECTOR_SECRETS="local-dev-secret:local-dev"-mise run mcp-serve -- --host 127.0.0.1 --port 8088+uv run --package sie-mcp sie-mcp serve --host 127.0.0.1 --port 8088```In another shell, verify the server:@@ -189,7 +199,7 @@ connector client: remote streamable HTTP plus an Authorization bearer secret.List the tools:```bash-mise exec -- uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \+uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \--url http://127.0.0.1:8088/mcp \--secret local-dev-secret \--list@@ -198,7 +208,7 @@ mise exec -- uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_Convert a sample HTML document to markdown:```bash-mise exec -- uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \+uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \--url http://127.0.0.1:8088/mcp \--secret local-dev-secret \--file packages/sie_mcp/docs/examples/sample.html \@@ -211,7 +221,7 @@ For a quick custom document:```bashprintf '<h1>Hello</h1><p>local smoke test</p>' > /tmp/sie-mcp-smoke.html-mise exec -- uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \+uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \--url http://127.0.0.1:8088/mcp \--secret local-dev-secret \--file /tmp/sie-mcp-smoke.html \@@ -226,13 +236,13 @@ The first model-backed request can be slow while the cluster loads models.Run the package tests from the repo root:```bash-mise exec -- uv run --package sie-mcp python -m pytest packages/sie_mcp/tests+uv run --package sie-mcp python -m pytest packages/sie_mcp/tests```For a focused check of this plugin-pack and PR #1336 integration path:```bash-mise exec -- uv run --package sie-mcp python -m pytest \+uv run --package sie-mcp python -m pytest \packages/sie_mcp/tests/test_offload.py \packages/sie_mcp/tests/test_plugin_pack.py \packages/sie_mcp/tests/test_skill_zip.py@@ -241,7 +251,6 @@ mise exec -- uv run --package sie-mcp python -m pytest \Useful lightweight checks:```bash-bash -n tools/mise_tasks/mcp-plugin-pack.bashgit diff --check```@@ -250,7 +259,7 @@ git diff --checkOnce the local edge is running, generate an install pack that points at it:```bash-SIE_MCP_CONNECTOR_SECRET=local-dev-secret mise run mcp-plugin-pack -- \+SIE_MCP_CONNECTOR_SECRET=local-dev-secret uv run --package sie-mcp sie-mcp plugin-pack \--cluster-label local-dev \--mcp-url http://127.0.0.1:8088/mcp \--out-dir /tmp/sie-mcp-plugin-pack@@ -260,13 +269,7 @@ Then follow `/tmp/sie-mcp-plugin-pack/INSTALL.md`.## Build And Run The Docker Server-Build with the repo's Docker task:--```bash-mise run docker -- --mcp --docker-platform linux/amd64 --bake-tag local-```--Or build directly:+Build from the repo root:```bashdocker build -t sie-mcp:local -f packages/sie_mcp/Dockerfile .@@ -335,7 +338,7 @@ curl -s https://<mcp-host>/healthzThen generate a user install pack:```bash-SIE_MCP_CONNECTOR_SECRET=tester-secret mise run mcp-plugin-pack -- \+SIE_MCP_CONNECTOR_SECRET=tester-secret uv run --package sie-mcp sie-mcp plugin-pack \--cluster-label <cluster-name> \--mcp-url https://<mcp-host>/mcp```diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex 50747a2c2..4158ac791 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.18"+version = "0.6.19"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml b/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yamlindex b938dd42e..8b4651c39 100644--- a/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml+++ b/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml@@ -1,5 +1,6 @@sie_id: Alibaba-NLP/gte-modernbert-basehf_id: Alibaba-NLP/gte-modernbert-base+hf_revision: e7f32e3c00f91d699e8c43b53106206bcc72bb22inputs:text: trueimage: falsediff --git a/packages/sie_server/models/Qwen__Qwen3-Reranker-0.6B.yaml b/packages/sie_server/models/Qwen__Qwen3-Reranker-0.6B.yamlindex d538cdf01..6233632d4 100644--- a/packages/sie_server/models/Qwen__Qwen3-Reranker-0.6B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3-Reranker-0.6B.yaml@@ -1,5 +1,6 @@sie_id: Qwen/Qwen3-Reranker-0.6Bhf_id: Qwen/Qwen3-Reranker-0.6B+hf_revision: e61197ed45024b0ed8a2d74b80b4d909f1255473inputs:text: trueimage: falsediff --git a/packages/sie_server/models/Snowflake__snowflake-arctic-embed-m-v2.0.yaml b/packages/sie_server/models/Snowflake__snowflake-arctic-embed-m-v2.0.yamlindex 6befc4a82..a2ae6bb46 100644--- a/packages/sie_server/models/Snowflake__snowflake-arctic-embed-m-v2.0.yaml+++ b/packages/sie_server/models/Snowflake__snowflake-arctic-embed-m-v2.0.yaml@@ -1,5 +1,6 @@sie_id: Snowflake/snowflake-arctic-embed-m-v2.0hf_id: Snowflake/snowflake-arctic-embed-m-v2.0+hf_revision: 95c2741480856aa9666782eb4afe11959938017finputs:text: trueimage: falsediff --git a/packages/sie_server/models/colbert-ir__colbertv2.0.yaml b/packages/sie_server/models/colbert-ir__colbertv2.0.yamlindex d660a936c..31e2126f2 100644--- a/packages/sie_server/models/colbert-ir__colbertv2.0.yaml+++ b/packages/sie_server/models/colbert-ir__colbertv2.0.yaml@@ -1,5 +1,6 @@sie_id: colbert-ir/colbertv2.0hf_id: colbert-ir/colbertv2.0+hf_revision: c1e84128e85ef755c096a95bdb06b47793b13acfinputs:text: trueimage: falsediff --git a/packages/sie_server/models/gliner-community__gliner_small-v2.5.yaml b/packages/sie_server/models/gliner-community__gliner_small-v2.5.yamlindex 14818ae05..bbd8f5277 100644--- a/packages/sie_server/models/gliner-community__gliner_small-v2.5.yaml+++ b/packages/sie_server/models/gliner-community__gliner_small-v2.5.yaml@@ -1,5 +1,6 @@sie_id: gliner-community/gliner_small-v2.5hf_id: gliner-community/gliner_small-v2.5+hf_revision: f227d3cd637bd4e6757ae143935316d062393341inputs:text: trueimage: falsediff --git a/packages/sie_server/models/google__siglip2-base-patch16-224.yaml b/packages/sie_server/models/google__siglip2-base-patch16-224.yamlindex 5b37f94fc..e95a0ff59 100644--- a/packages/sie_server/models/google__siglip2-base-patch16-224.yaml+++ b/packages/sie_server/models/google__siglip2-base-patch16-224.yaml@@ -1,5 +1,6 @@sie_id: google/siglip2-base-patch16-224hf_id: google/siglip2-base-patch16-224+hf_revision: 75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2inputs:text: trueimage: truediff --git a/packages/sie_server/models/intfloat__e5-small-v2.yaml b/packages/sie_server/models/intfloat__e5-small-v2.yamlindex 52e64f3c9..03ac64971 100644--- a/packages/sie_server/models/intfloat__e5-small-v2.yaml+++ b/packages/sie_server/models/intfloat__e5-small-v2.yaml@@ -1,5 +1,6 @@sie_id: intfloat/e5-small-v2hf_id: intfloat/e5-small-v2+hf_revision: ffb93f3bd4047442299a41ebb6fa998a38507c52inputs:text: trueimage: falsediff --git a/packages/sie_server/models/knowledgator__gliclass-large-v1.0.yaml b/packages/sie_server/models/knowledgator__gliclass-large-v1.0.yamlindex 7b9abed6f..bf4a13f99 100644--- a/packages/sie_server/models/knowledgator__gliclass-large-v1.0.yaml+++ b/packages/sie_server/models/knowledgator__gliclass-large-v1.0.yaml@@ -1,5 +1,6 @@sie_id: knowledgator/gliclass-large-v1.0hf_id: knowledgator/gliclass-large-v1.0+hf_revision: ae8a18644e84cfda53325bd91c7941f2f6fd0ccbinputs:text: trueimage: falsediff --git a/packages/sie_server/models/mixedbread-ai__mxbai-embed-large-v1.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-embed-large-v1.yamlindex 0dd6b844f..2595de777 100644--- a/packages/sie_server/models/mixedbread-ai__mxbai-embed-large-v1.yaml+++ b/packages/sie_server/models/mixedbread-ai__mxbai-embed-large-v1.yaml@@ -1,5 +1,6 @@sie_id: mixedbread-ai/mxbai-embed-large-v1hf_id: mixedbread-ai/mxbai-embed-large-v1+hf_revision: b33106f585b9ce46904ad7443a3b52b7a63e231cinputs:text: trueimage: falsediff --git a/packages/sie_server/models/mixedbread-ai__mxbai-rerank-base-v2.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-rerank-base-v2.yamlindex 980c13758..41a90cf9e 100644--- a/packages/sie_server/models/mixedbread-ai__mxbai-rerank-base-v2.yaml+++ b/packages/sie_server/models/mixedbread-ai__mxbai-rerank-base-v2.yaml@@ -1,5 +1,6 @@sie_id: mixedbread-ai/mxbai-rerank-base-v2hf_id: mixedbread-ai/mxbai-rerank-base-v2+hf_revision: 3ea9d4dffa7d12a4f366be8e275c349de9fc9865inputs:text: trueimage: falsediff --git a/packages/sie_server/models/nomic-ai__nomic-embed-text-v2-moe.yaml b/packages/sie_server/models/nomic-ai__nomic-embed-text-v2-moe.yamlindex 7c22c457f..4888a9e2b 100644--- a/packages/sie_server/models/nomic-ai__nomic-embed-text-v2-moe.yaml+++ b/packages/sie_server/models/nomic-ai__nomic-embed-text-v2-moe.yaml@@ -1,5 +1,6 @@sie_id: nomic-ai/nomic-embed-text-v2-moehf_id: nomic-ai/nomic-embed-text-v2-moe+hf_revision: 1066b6599d099fbb93dfcb64f9c37a7c9e503e85inputs:text: trueimage: falsediff --git a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-distill.yaml b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-distill.yamlindex 5327f8997..76d22a568 100644--- a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-distill.yaml+++ b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-distill.yaml@@ -1,5 +1,6 @@sie_id: opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distillhf_id: opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distill+hf_revision: babf71f3c48695e2e53a978208e8aba48335e3c0inputs:text: trueimage: falsediff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex d1cded708..3fafe54a6 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -3,7 +3,7 @@"info": {"title": "SIE Server","description": "Search Inference Engine - GPU inference server for search workloads",- "version": "0.6.18"+ "version": "0.6.19"},"paths": {"/": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex dc08488da..c5e2f3273 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.18"+version = "0.6.19"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/src/sie_server/_ipc_test_harness.py b/packages/sie_server/src/sie_server/_ipc_test_harness.pyindex 822ca6399..72660d52a 100644--- a/packages/sie_server/src/sie_server/_ipc_test_harness.py+++ b/packages/sie_server/src/sie_server/_ipc_test_harness.py@@ -332,7 +332,7 @@ def main() -> None:parser.add_argument("--readiness",default="ready",- choices=["ready", "loading_started", "loading_in_progress", "retry_later"],+ choices=["ready", "loading_started", "loading_in_progress", "retry_later", "failed"],help="Canned readiness state returned for every EnsureModelReady",)parser.add_argument("--log-level", default="INFO")diff --git a/packages/sie_server/src/sie_server/adapters/_base_adapter.py b/packages/sie_server/src/sie_server/adapters/_base_adapter.pyindex d5ed33ff9..195658c6e 100644--- a/packages/sie_server/src/sie_server/adapters/_base_adapter.py+++ b/packages/sie_server/src/sie_server/adapters/_base_adapter.py@@ -2,6 +2,9 @@ from __future__ import annotationsimport gcimport logging+import threading+from collections.abc import Iterator+from contextlib import contextmanagerfrom typing import TYPE_CHECKING, Any, ClassVar, castfrom sie_server.adapters._spec import AdapterSpec@@ -33,6 +36,19 @@ class BaseAdapter(ModelAdapter):spec: ClassVar[AdapterSpec]+ # Guards the lazy creation of each instance's ``_tokenizer_lock`` (below).+ # A HuggingFace *fast* tokenizer wraps a Rust object behind a ``RefCell``:+ # calling it from two threads at once — or mutating shared state like+ # ``pad_token_id`` mid-call — raises ``RuntimeError("Already borrowed")``.+ # On the managed worker path the single-threaded inference executor runs an+ # adapter's ``encode()`` (which tokenizes) while a *different* asyncio+ # thread-pool thread runs the §7.3 metering fallback+ # (``count_input_tokens`` → ``_token_counts_or_none``) for another+ # concurrent request against the *same* tokenizer object. Both sides take+ # ``_tokenizer_guard()`` so tokenizer access is serialised per adapter+ # instance and can never overlap. See issue #1800.+ _tokenizer_lock_init: ClassVar[threading.Lock] = threading.Lock()+def __init_subclass__(cls, **kwargs: Any) -> None:super().__init_subclass__(**kwargs)@@ -165,6 +181,32 @@ class BaseAdapter(ModelAdapter):raise NotImplementedError(msg)return grouped_score_pairs(self.score, queries, docs, instruction=instruction)+ # -- Tokenizer concurrency guard -----------------------------------------++ @contextmanager+ def _tokenizer_guard(self) -> Iterator[None]:+ """Serialise access to ``self._tokenizer`` across threads.++ HuggingFace fast tokenizers are not re-entrant: concurrent calls (or a+ ``pad_token_id`` swap mid-call) raise ``RuntimeError("Already+ borrowed")``. The encode/score paths tokenize on the inference-executor+ thread while the metering fallback tokenizes on an asyncio thread-pool+ thread for a *different* concurrent request; wrapping both in this lock+ prevents the collision. The lock is created lazily (adapters set+ ``self._tokenizer`` in their own ``__init__``/``load`` and don't all+ call ``super().__init__``) under a class-level lock so two threads+ cannot race to build it. See issue #1800.+ """+ lock = getattr(self, "_tokenizer_lock", None)+ if lock is None:+ with BaseAdapter._tokenizer_lock_init:+ lock = getattr(self, "_tokenizer_lock", None)+ if lock is None:+ lock = threading.Lock()+ self._tokenizer_lock = lock+ with lock:+ yield+# -- Unit-meter token counting (§7.3) ------------------------------------def _metering_tokenizer(self) -> Any | None:@@ -236,7 +278,11 @@ class BaseAdapter(ModelAdapter):texts.append(text)if not texts:return []- return self._token_counts_or_none(tokenizer, texts, expected_len=len(items))+ # Serialise against the encode/score tokenization running on the+ # inference-executor thread — a bare fast tokenizer raises ``Already+ # borrowed`` when re-tokenized concurrently (#1800).+ with self._tokenizer_guard():+ return self._token_counts_or_none(tokenizer, texts, expected_len=len(items))def count_pair_input_tokens(self,@@ -269,12 +315,15 @@ class BaseAdapter(ModelAdapter):doc_texts.append(doc_text)if not doc_texts:return []- return self._token_counts_or_none(- tokenizer,- [query_text] * len(doc_texts),- doc_texts,- expected_len=len(docs),- )+ # Serialise against the encode/score tokenization on the inference+ # thread (#1800), same as ``count_input_tokens``.+ with self._tokenizer_guard():+ return self._token_counts_or_none(+ tokenizer,+ [query_text] * len(doc_texts),+ doc_texts,+ expected_len=len(docs),+ )def _token_counts_or_none(self,@@ -288,6 +337,13 @@ class BaseAdapter(ModelAdapter):per-entry ``len(input_ids)``; ``None`` on any quirk so a malformed countis never mis-attributed."""+ # NOTE: callers that already hold ``_tokenizer_guard()`` (e.g. CLIP /+ # SigLIP ``_encode_texts`` serialise the whole tokenize-then-count block+ # under their own ``_tokenizer_lock``) invoke this helper directly, so it+ # must NOT re-acquire the guard — the lock is non-reentrant and would+ # deadlock. Serialisation for the standalone metering path is applied at+ # the ``count_input_tokens`` / ``count_pair_input_tokens`` entry points+ # instead. See issue #1800.max_length = self._metering_max_length()try:if text_pair is not None:diff --git a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert/__init__.pyindex b717cf5af..35d55ce51 100644--- a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colbert/__init__.py@@ -623,28 +623,40 @@ class ColBERTAdapter(BaseAdapter):# Adjust max_length if we need to insert a prefix tokeneffective_max_length = max_length - 1 if prefix_id is not None else max_length- # For query expansion, pad to exact length using MASK tokens- if use_expansion:- # Temporarily swap pad_token_id to mask_token_id for MASK token padding- original_pad_id = self._tokenizer.pad_token_id- self._tokenizer.pad_token_id = self._expansion_token_id- batch = self._tokenizer(- texts,- max_length=effective_max_length,- padding="max_length",- truncation=True,- return_tensors="pt",- )- self._tokenizer.pad_token_id = original_pad_id- else:- # Standard padding for documents- batch = self._tokenizer(- texts,- max_length=effective_max_length,- padding=True,- truncation=True,- return_tensors="pt",- )+ # Serialise all tokenizer access (including the transient+ # ``pad_token_id`` swap) against the §7.3 metering tokenization that+ # runs on a separate thread — a bare fast tokenizer would raise+ # ``Already borrowed`` under concurrency (#1800).+ with self._tokenizer_guard():+ # For query expansion, pad to exact length using MASK tokens+ if use_expansion:+ # Temporarily swap pad_token_id to mask_token_id for MASK token+ # padding. Restore in ``finally`` so a tokenizer failure (bad+ # input / OOM) cannot leave the instance's ``pad_token_id`` stuck+ # at the MASK id — under ``_tokenizer_guard()`` that corruption+ # would leak to every later guarded caller (including metering),+ # silently mis-padding until reload (CodeRabbit #1800).+ original_pad_id = self._tokenizer.pad_token_id+ self._tokenizer.pad_token_id = self._expansion_token_id+ try:+ batch = self._tokenizer(+ texts,+ max_length=effective_max_length,+ padding="max_length",+ truncation=True,+ return_tensors="pt",+ )+ finally:+ self._tokenizer.pad_token_id = original_pad_id+ else:+ # Standard padding for documents+ batch = self._tokenizer(+ texts,+ max_length=effective_max_length,+ padding=True,+ truncation=True,+ return_tensors="pt",+ )# Insert prefix token ID at position 1 (after [CLS])if prefix_id is not None:@@ -740,34 +752,45 @@ class ColBERTAdapter(BaseAdapter):# Adjust max_length if we need to insert a prefix tokeneffective_max_length = max_length - 1 if prefix_id is not None else max_length- # For query expansion, pad to exact max_length using MASK tokens- if use_expansion:- original_pad_id = self._tokenizer.pad_token_id- self._tokenizer.pad_token_id = self._expansion_token_id- encodings = [- self._tokenizer(- text,- max_length=effective_max_length,- padding="max_length",- truncation=True,- return_tensors="pt",- return_attention_mask=True,- )- for text in texts- ]- self._tokenizer.pad_token_id = original_pad_id- else:- # Tokenize each sequence individually (no padding)- encodings = [- self._tokenizer(- text,- max_length=effective_max_length,- truncation=True,- return_tensors="pt",- return_attention_mask=True,- )- for text in texts- ]+ # Serialise all tokenizer access (including the transient+ # ``pad_token_id`` swap) against the §7.3 metering tokenization that+ # runs on a separate thread — a bare fast tokenizer would raise+ # ``Already borrowed`` under concurrency (#1800).+ with self._tokenizer_guard():+ # For query expansion, pad to exact max_length using MASK tokens.+ # Restore ``pad_token_id`` in ``finally`` so a mid-comprehension+ # tokenizer failure cannot leave it stuck at the MASK id and leak the+ # corruption to every later guarded caller under ``_tokenizer_guard()``+ # (CodeRabbit #1800).+ if use_expansion:+ original_pad_id = self._tokenizer.pad_token_id+ self._tokenizer.pad_token_id = self._expansion_token_id+ try:+ encodings = [+ self._tokenizer(+ text,+ max_length=effective_max_length,+ padding="max_length",+ truncation=True,+ return_tensors="pt",+ return_attention_mask=True,+ )+ for text in texts+ ]+ finally:+ self._tokenizer.pad_token_id = original_pad_id+ else:+ # Tokenize each sequence individually (no padding)+ encodings = [+ self._tokenizer(+ text,+ max_length=effective_max_length,+ truncation=True,+ return_tensors="pt",+ return_attention_mask=True,+ )+ for text in texts+ ]# Insert prefix token ID at position 1 (after [CLS]) for each encodingif prefix_id is not None:diff --git a/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.pyindex 07939f831..d8f9e480d 100644--- a/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py@@ -169,8 +169,15 @@ class CrossEncoderAdapter(BaseAdapter):# Build (query, document) pairspairs = [(query_text, self._extract_text(item)) for item in items]- # Score pairs- with torch.inference_mode():+ # Score pairs. ``CrossEncoder.predict`` tokenizes ``self._model.tokenizer``+ # internally (fused with the forward, unlike colbert where the two are+ # separable); the §7.3 metering fallback re-tokenizes that same tokenizer+ # on a separate thread-pool thread, so a bare HF fast tokenizer would race+ # into ``RuntimeError("Already borrowed")``. Serialise with the shared+ # ``_tokenizer_guard()`` (class-fix for #1800). The inference executor is+ # single-threaded, so predicts are already serial — the guard adds no GPU+ # throughput cost, it only holds off the concurrent metering re-tokenize.+ with torch.inference_mode(), self._tokenizer_guard():scores = self._model.predict(pairs)# Convert to Python floats@@ -214,8 +221,15 @@ class CrossEncoderAdapter(BaseAdapter):doc_text = self._extract_text(doc)pairs.append((query_text, doc_text))- # Score pairs- with torch.inference_mode():+ # Score pairs. See ``score()``: ``predict`` tokenizes ``self._model``'s+ # tokenizer internally (fused with the forward), and ``_pair_input_token_counts``+ # below re-tokenizes it for §7.3 metering, while the shared metering+ # fallback re-tokenizes it on another thread — all serialised through+ # ``_tokenizer_guard()`` to avoid the ``Already borrowed`` race (#1800).+ # The guard is released between predict and the metering re-tokenize+ # (separate ``with`` blocks); the lock is non-reentrant, so they must not+ # nest.+ with torch.inference_mode(), self._tokenizer_guard():scores = self._model.predict(pairs)# Convert to float32 numpy array and wrap in ScoreOutput@@ -270,16 +284,31 @@ class CrossEncoderAdapter(BaseAdapter):applies (:meth:`_metering_max_length`). Best-effort: any tokenizer quirkreturns ``None`` so the meter falls back to its reserve estimate ratherthan failing the score or billing an approximation as a count.++ Runs inline on the inference-executor thread inside :meth:`score_pairs`,+ re-tokenizing the very tokenizer ``CrossEncoder.predict`` just used (and+ that the §7.3 metering fallback re-tokenizes on a separate thread-pool+ thread for another concurrent request). A bare HF fast tokenizer wraps a+ Rust ``RefCell`` and raises ``RuntimeError("Already borrowed")`` under+ concurrent use, so this re-tokenize is serialised with+ ``_tokenizer_guard()`` — the encode/score-side sibling of the guard the+ shared ``count_pair_input_tokens`` entry point already holds. The lock is+ held only for the pure tokenization (no GPU forward), matching colbert's+ fix for the same class (#1800). NOTE: reached only via ``score_pairs`` —+ never through ``count_pair_input_tokens`` (which already holds the guard+ and routes to ``_token_counts_or_none`` directly), so no non-reentrant+ deadlock."""tokenizer = self._metering_tokenizer()if tokenizer is None:return None- return self._token_counts_or_none(- tokenizer,- [q for q, _ in pairs],- [d for _, d in pairs],- expected_len=len(pairs),- )+ with self._tokenizer_guard():+ return self._token_counts_or_none(+ tokenizer,+ [q for q, _ in pairs],+ [d for _, d in pairs],+ expected_len=len(pairs),+ )def _extract_text(self, item: Item) -> str:"""Extract text from an item."""diff --git a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py b/packages/sie_server/src/sie_server/adapters/florence2/__init__.pyindex f89746b96..958bdb486 100644--- a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/florence2/__init__.py@@ -126,7 +126,7 @@ class Florence2Adapter(BaseAdapter):Args:device: Device string (e.g., "cuda:0", "cpu")."""- from transformers import AutoModelForCausalLM, AutoProcessor+ from transformers import AutoModelForCausalLMself._device = device@@ -145,11 +145,9 @@ class Florence2Adapter(BaseAdapter):self._attn_implementation,)- # Load processor with trust_remote_code (required for Florence-2 custom processor)- self._processor = AutoProcessor.from_pretrained(- self._model_name_or_path,- **shared_kwargs,- )+ # Load the checkpoint's own (remote) processor. AutoProcessor alone is not+ # safe on transformers >= 4.49 — see _load_processor for the incompatibility.+ self._processor = self._load_processor(shared_kwargs)# Load model with trust_remote_code to use model's custom code# attn_implementation options: "eager", "sdpa", "flash_attention_2"@@ -168,6 +166,90 @@ class Florence2Adapter(BaseAdapter):logger.info("Florence-2 model loaded successfully")+ def _load_processor(self, shared_kwargs: dict[str, Any]) -> Any:+ """Load the Florence-2 processor bound to the checkpoint's own remote code.++ transformers >= 4.49 ships a *native* ``Florence2Processor`` (model type+ ``florence2``). Its ``__init__`` reads ``tokenizer.image_token`` /+ ``tokenizer.image_token_id``, which the published microsoft/Florence-2-*+ checkpoints do not provide — they ship a plain ``BartTokenizerFast`` and a+ remote ``processing_florence2.py``. When ``AutoProcessor`` resolves to the+ native class (e.g. the staged copy's ``auto_map`` did not survive+ re-serialization, or trust-remote-code was not honored) construction fails+ with ``AttributeError: BartTokenizerFast has no attribute image_token``.++ We therefore load the processor class declared in the checkpoint's+ ``auto_map`` directly, so the checkpoint's own (Bart-compatible) remote+ processor is always used regardless of the installed transformers version.+ AutoProcessor is used only as a fallback for checkpoints/local paths that do+ not advertise a remote processor.+ """+ from transformers import AutoProcessor+ from transformers.dynamic_module_utils import get_class_from_dynamic_module++ auto_map_ref = self._resolve_processor_auto_map(shared_kwargs)+ if auto_map_ref is not None:+ # Pass the auto_map ref verbatim: get_class_from_dynamic_module parses a+ # "<upstream_repo>--module.Class" prefix itself and fetches the code from+ # that upstream repo (the Florence-2-FT-DocVQA fork points at+ # microsoft/Florence-2-base-ft). ``revision`` is applied only when the+ # code lives in this checkpoint (same-repo), never to the upstream repo.+ revision = shared_kwargs.get("revision")+ processor_class = get_class_from_dynamic_module(+ auto_map_ref,+ self._model_name_or_path,+ revision=revision,+ )+ logger.info(+ "Loading Florence-2 processor from checkpoint remote code: %s",+ auto_map_ref,+ )+ # processor_class is a ProcessorMixin subclass with .from_pretrained;+ # get_class_from_dynamic_module is only typed as returning ``type``.+ return processor_class.from_pretrained( # ty: ignore[unresolved-attribute]+ self._model_name_or_path, **shared_kwargs+ )++ # No remote processor advertised (e.g. a local export) — fall back to+ # AutoProcessor and let transformers resolve the class.+ logger.info("Florence-2 checkpoint has no remote processor auto_map; using AutoProcessor")+ return AutoProcessor.from_pretrained(self._model_name_or_path, **shared_kwargs)++ def _resolve_processor_auto_map(self, shared_kwargs: dict[str, Any]) -> str | None:+ """Return the ``auto_map['AutoProcessor']`` ref for the checkpoint, if any.++ Mirrors how ``AutoProcessor.from_pretrained`` discovers a remote processor:+ it scans ``processor_config.json``, ``preprocessor_config.json`` and+ ``tokenizer_config.json`` for an ``auto_map['AutoProcessor']`` entry — for+ the microsoft/Florence-2-* checkpoints it lives in+ ``preprocessor_config.json``. We only read the class *name*, never+ instantiating the (possibly native, incompatible) processor.+ """+ import json++ from transformers.utils import cached_file++ revision = shared_kwargs.get("revision")+ for filename in ("processor_config.json", "preprocessor_config.json", "tokenizer_config.json"):+ try:+ resolved = cached_file(+ self._model_name_or_path,+ filename,+ revision=revision,+ _raise_exceptions_for_missing_entries=False,+ )+ except Exception: # noqa: BLE001 — auto_map discovery is best-effort; fall through to next config+ logger.debug("Could not resolve %s for %s", filename, self._model_name_or_path, exc_info=True)+ continue+ if not resolved:+ continue+ with open(resolved, encoding="utf-8") as reader:+ config_dict = json.load(reader)+ ref = (config_dict.get("auto_map") or {}).get("AutoProcessor")+ if isinstance(ref, str):+ return ref+ return None+def _resolve_dtype(self) -> torch.dtype:"""Resolve dtype based on device and config."""if not self._device or not str(self._device).startswith("cuda"):diff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.pyindex 80aaaff3c..e8299242d 100644--- a/packages/sie_server/src/sie_server/api/helpers.py+++ b/packages/sie_server/src/sie_server/api/helpers.py@@ -154,9 +154,14 @@ def extract_request_context(if token:api_key = _mask_api_key(token)- # queue_depth: from worker's pending_count+ # queue_depth: from worker's pending_count. Best-effort: endpoints call this+ # before check_exists(), so an unknown model must fall through to their 404+ # instead of KeyError-500ing here.queue_depth: int | None = None- worker = registry.get_worker(model)+ try:+ worker = registry.get_worker(model)+ except KeyError:+ worker = Noneif worker is not None:queue_depth = worker.pending_countdiff --git a/packages/sie_server/src/sie_server/core/tokenizer.py b/packages/sie_server/src/sie_server/core/tokenizer.pyindex 73fd2adfe..a152da1ca 100644--- a/packages/sie_server/src/sie_server/core/tokenizer.py+++ b/packages/sie_server/src/sie_server/core/tokenizer.py@@ -17,17 +17,30 @@ def load_tokenizer(model_path: str | Path,*,trust_remote_code: bool = False,+ revision: str | None = None,) -> PreTrainedTokenizer | PreTrainedTokenizerFast:- """Load a HuggingFace tokenizer from a local path or model id."""+ """Load a HuggingFace tokenizer from a local path or model id.++ When ``revision`` is a pinned commit SHA it is forwarded to+ ``from_pretrained`` so the load resolves the exact ``snapshots/<sha>``+ directory directly. This mirrors how the weights loader pins the+ revision (``core/loader.py``) and — crucially under ``HF_HUB_OFFLINE=1``+ — avoids depending on the ``refs/main`` alias, which the Volume-backed HF+ cache lacks for repos staged by pinned SHA (a no-revision load would try+ to resolve ``refs/main`` and fail offline). ``None`` keeps the legacy+ no-revision behaviour for local-path / unpinned loads.+ """from transformers import AutoTokenizertokenizer = AutoTokenizer.from_pretrained(str(model_path),trust_remote_code=trust_remote_code,+ revision=revision,)logger.debug(- "Loaded tokenizer from %s (fast=%s)",+ "Loaded tokenizer from %s@%s (fast=%s)",model_path,+ revision or "default",getattr(tokenizer, "is_fast", False),)return tokenizerdiff --git a/packages/sie_server/src/sie_server/ipc_types.py b/packages/sie_server/src/sie_server/ipc_types.pyindex 07cd92f2e..3ab4c1040 100644--- a/packages/sie_server/src/sie_server/ipc_types.py+++ b/packages/sie_server/src/sie_server/ipc_types.py@@ -71,7 +71,12 @@ class PingResponse(msgspec.Struct):# EnsureModelReady# ------------------------------------------------------------------------------ReadinessState = Literal["ready", "loading_started", "loading_in_progress", "retry_later"]+# ``"failed"`` is the terminal, non-retryable state (the registry holds a+# PERMANENT ``LoadFailure``, ``cooldown=permanent``). The sidecar+# dead-letters a group in this state as ``MODEL_LOAD_FAILED`` (gateway ->+# 502) instead of re-driving ``EnsureModelReady`` forever — the fast-path+# twin of the ``run_batch`` / direct-HTTP #1786 typed-502 mapping.+ReadinessState = Literal["ready", "loading_started", "loading_in_progress", "retry_later", "failed"]class EnsureModelReadyRequest(msgspec.Struct):diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 52ea9761c..2df932acf 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -2943,10 +2943,20 @@ class StreamingProcessor:if not isinstance(source, str | Path):msg = f"model '{model_id}' has no hf_id or weights_path; cannot load tokenizer"raise RuntimeError(msg)+ # Pin the tokenizer load to the model's immutable ``hf_revision``+ # when loading from an ``hf_id`` — mirrors how the weights loader+ # pins the revision (``core/loader.py``). Under ``HF_HUB_OFFLINE=1``+ # the offline HF cache resolves the exact ``snapshots/<sha>`` dir+ # directly and never touches the ``refs/main`` alias (absent for+ # repos staged by pinned SHA), which otherwise fails the+ # chat-template render (#1801). A local ``weights_path`` has no HF+ # revision, so it stays unpinned.+ revision = config.hf_revision if config.hf_id else Nonetok = await asyncio.to_thread(load_tokenizer,source,trust_remote_code=True,+ revision=revision,)self._tokenizers[model_id] = tokreturn tokdiff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 049d19835..feafc8d39 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -602,6 +602,23 @@ class QueueExecutor:- ``loading_started``: progress-ACK and recheck (this call triggered a new load)- ``loading_in_progress``: progress-ACK and recheck with a longer delay- ``retry_later``: NAK with base delay (unknown error path)+ - ``failed``: TERMINAL — dead-letter as ``MODEL_LOAD_FAILED`` (do NOT+ recheck). Emitted when the registry holds a PERMANENT+ ``LoadFailure`` (``cooldown=permanent``).++ #1786 fast-path twin: a permanent load failure (e.g. gated repo,+ missing dependency) otherwise collapses into ``loading_in_progress``+ here — ``start_load_async`` returns ``False`` under the+ ``registry.is_failed`` guard, indistinguishable from "still loading".+ The Rust sidecar then re-drives ``EnsureModelReady`` every ~10s+ forever and the client hangs. We consult the registry's failure+ record DIRECTLY and report the terminal ``failed`` state for the+ *permanent* classes only, using the SAME ``get_failure().is_permanent``+ classification as the direct-HTTP ``check_not_failed`` gate and the+ Modal lane's ``worker_runtime._terminal_load_failure``. Transient+ in-cooldown classes (OOM / NETWORK / TIMEOUT) are intentionally NOT+ terminal — they stay ``loading_in_progress`` so the caller retries+ after the short cooldown."""if not self._registry.has_model(model_id):return "retry_later"@@ -609,6 +626,10 @@ class QueueExecutor:if self._registry.is_loaded(model_id):return "ready"+ failure = self._registry.get_failure(model_id)+ if failure is not None and failure.is_permanent:+ return "failed"+if self._registry.is_loading(model_id):return "loading_in_progress"@@ -622,7 +643,17 @@ class QueueExecutor:logger.warning("ensure_model_ready: start_load_async failed for %s", model_id, exc_info=True)return "retry_later"- return "loading_started" if started else "loading_in_progress"+ if started:+ return "loading_started"+ # ``start_load_async`` refused to start a new attempt. Usually a+ # transient failure still in cooldown or a concurrent load already+ # in flight — both retryable. But it could also be a PERMANENT+ # failure recorded in the narrow window since the up-front check, so+ # re-read the record and dead-letter rather than re-drive forever.+ failure = self._registry.get_failure(model_id)+ if failure is not None and failure.is_permanent:+ return "failed"+ return "loading_in_progress"# -- Handshake-driven model descriptor --------------------------------diff --git a/packages/sie_server/tests/adapters/test_colbert.py b/packages/sie_server/tests/adapters/test_colbert.pyindex 8d466a163..b67402b9f 100644--- a/packages/sie_server/tests/adapters/test_colbert.py+++ b/packages/sie_server/tests/adapters/test_colbert.py@@ -1,8 +1,11 @@from __future__ import annotationsimport json+import threading+import timefrom pathlib import Pathfrom types import SimpleNamespace+from typing import Anyfrom unittest.mock import MagicMock, patchimport numpy as np@@ -683,3 +686,265 @@ class TestColBERTScorePairsOptions:assert out.scores.shape == (2,)# Options must NOT be threaded into score().assert "options" not in mock_score.call_args.kwargs+++class _ReentrancyDetectingTokenizer:+ """Emulates a HuggingFace fast tokenizer's non-re-entrancy.++ A real fast tokenizer wraps a Rust object behind a ``RefCell``; a second+ call that begins while a first is still in flight raises+ ``RuntimeError("Already borrowed")`` (issue #1800). This fake reproduces+ that exact failure mode: it raises if two threads are inside a tokenizer+ call at the same time, so a correct serialization guard makes it pass and a+ missing guard makes it fail.+ """++ def __init__(self) -> None:+ self.pad_token_id = 0+ self.mask_token_id = 103+ self._active = 0+ self._active_lock = threading.Lock()++ def _enter(self) -> None:+ with self._active_lock:+ if self._active != 0:+ raise RuntimeError("Already borrowed")+ self._active += 1++ def _exit(self) -> None:+ with self._active_lock:+ self._active -= 1++ def _tokenize_one(self, text: str) -> list[int]:+ # Deterministic per-text length: [CLS] + one id per word + [SEP].+ return [1, *[42 for _ in text.split()], 2]++ def __call__(self, texts: Any, **kwargs: Any) -> Any:+ self._enter()+ try:+ # Simulate real tokenizer latency so overlapping threads collide.+ time.sleep(0.002)+ single = isinstance(texts, str)+ text_list = [texts] if single else list(texts)+ padding = kwargs.get("padding")+ ids = [self._tokenize_one(t) for t in text_list]+ if padding in (True, "max_length"):+ width = kwargs.get("max_length") if padding == "max_length" else max(len(x) for x in ids)+ assert width is not None+ pad_id = self.pad_token_id+ mask = [[1] * len(x) + [0] * (width - len(x)) for x in ids]+ ids = [x + [pad_id] * (width - len(x)) for x in ids]+ else:+ mask = [[1] * len(x) for x in ids]+ if kwargs.get("return_tensors") == "pt":+ return _FakeTensorBatch(+ input_ids=torch.tensor(ids),+ attention_mask=torch.tensor(mask),+ )+ return {"input_ids": ids, "attention_mask": mask}+ finally:+ self._exit()+++class _FakeTensorBatch(dict):+ def to(self, _device: str) -> _FakeTensorBatch:+ return self+++class TestColBERTTokenizerConcurrencyGuard:+ """Regression tests for issue #1800: colbert-small multivector encode+ desync surfaced as ``inference_error: Already borrowed`` under concurrency.++ The encode path tokenizes on the inference-executor thread while the §7.3+ metering fallback (``count_input_tokens``) tokenizes on a separate+ thread-pool thread for another concurrent request against the *same*+ tokenizer. ``_tokenizer_guard()`` must serialise both.+ """++ def _make_adapter(self) -> ColBERTAdapter:+ adapter = ColBERTAdapter("test-model", skip_special_tokens=False, query_expansion=False)+ adapter._device = "cpu"+ adapter._actual_token_dim = 8+ adapter._max_seq_length = 512+ tokenizer = _ReentrancyDetectingTokenizer()+ adapter._tokenizer = tokenizer # ty: ignore[invalid-assignment]++ def _fake_forward(**batch: Any) -> Any:+ input_ids = batch["input_ids"]+ b, seq = input_ids.shape+ hidden = torch.ones(b, seq, 8, dtype=torch.float32)+ return SimpleNamespace(last_hidden_state=hidden)++ adapter._model = MagicMock(side_effect=_fake_forward)+ return adapter++ def test_encode_and_metering_do_not_collide_under_concurrency(self) -> None:+ """Encoding on one thread and metering-tokenizing on another must not+ raise ``Already borrowed`` — the guard serialises tokenizer access.+ """+ adapter = self._make_adapter()+ texts = ["a", "the quick brown fox", "x", "a considerably longer piece of text here"]+ items = [Item(text=t) for t in texts]++ errors: list[BaseException] = []+ stop = threading.Event()++ def encode_loop() -> None:+ try:+ for _ in range(40):+ if stop.is_set():+ return+ out = adapter._encode_native(texts, max_length=64, use_expansion=False, is_query=False)+ assert len(out) == len(texts)+ except BaseException as e: # noqa: BLE001+ errors.append(e)++ def metering_loop() -> None:+ try:+ for _ in range(40):+ if stop.is_set():+ return+ counts = adapter.count_input_tokens(items)+ assert counts is not None+ assert len(counts) == len(items)+ except BaseException as e: # noqa: BLE001+ errors.append(e)++ threads = [threading.Thread(target=encode_loop) for _ in range(2)]+ threads += [threading.Thread(target=metering_loop) for _ in range(2)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=30)+ stop.set()++ assert not errors, f"tokenizer collision under concurrency: {errors!r}"++ def test_reentrancy_detector_fires_without_guard(self) -> None:+ """Sanity check the harness: bare concurrent tokenizer calls (no guard)+ DO raise ``Already borrowed`` — otherwise the guard test is vacuous.+ """+ tokenizer = _ReentrancyDetectingTokenizer()+ errors: list[BaseException] = []++ def call_loop() -> None:+ try:+ for _ in range(40):+ tokenizer(["a", "b c"], return_tensors="pt", padding=True)+ except BaseException as e: # noqa: BLE001+ errors.append(e)++ threads = [threading.Thread(target=call_loop) for _ in range(4)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=30)++ assert any(isinstance(e, RuntimeError) and "Already borrowed" in str(e) for e in errors)+++class TestColBERTRaggedMultivectorBatch:+ """Issue #1800: multivector encode must return exactly one vector-set per+ input, in worker-item order, for any batch/length mix.+ """++ def test_encode_native_ragged_batch_one_set_per_input_in_order(self) -> None:+ # normalize=False so the per-row hidden fill is preserved and we can+ # assert worker-item ordering directly.+ adapter = ColBERTAdapter("test-model", skip_special_tokens=False, query_expansion=False, normalize=False)+ adapter._device = "cpu"+ adapter._actual_token_dim = 8+ adapter._max_seq_length = 512+ tokenizer = _ReentrancyDetectingTokenizer()+ adapter._tokenizer = tokenizer # ty: ignore[invalid-assignment]++ def _fake_forward(**batch: Any) -> Any:+ input_ids = batch["input_ids"]+ b, seq = input_ids.shape+ # Row-distinct hidden states so we can assert per-item ordering.+ base = torch.arange(b, dtype=torch.float32).reshape(b, 1, 1)+ hidden = torch.ones(b, seq, 8, dtype=torch.float32) + base+ return SimpleNamespace(last_hidden_state=hidden)++ adapter._model = MagicMock(side_effect=_fake_forward)++ # Ragged: very short and long inputs mixed.+ texts = ["a", "one two three four five", "x", "a b", "the fox ran quickly over"]+ out = adapter._encode_native(texts, max_length=64, use_expansion=False, is_query=False)++ # Exactly one vector-set per input, in order.+ assert len(out) == len(texts)+ for mv in out:+ assert mv.ndim == 2+ assert mv.shape[1] == 8+ assert mv.shape[0] > 0++ # Per-input token counts follow the (padded then attention-masked)+ # lengths: [CLS] + words + [SEP], with PAD rows dropped by the mask.+ expected_lens = [len(t.split()) + 2 for t in texts]+ assert [mv.shape[0] for mv in out] == expected_lens++ # Order preserved: row i's hidden fill == 1.0 + i (from _fake_forward).+ for i, mv in enumerate(out):+ assert float(mv[0, 0]) == 1.0 + i+++class _RaisingExpansionTokenizer:+ """Fake tokenizer whose call raises, used to prove the query-expansion+ ``pad_token_id`` swap is restored even when tokenization fails.++ Exposes a mutable ``pad_token_id`` (the swap target) so the test can assert+ it is back to the original after the raising call propagates.+ """++ def __init__(self) -> None:+ self.pad_token_id = 7 # sentinel "original" pad id+ self.mask_token_id = 103++ def __call__(self, *_args: Any, **_kwargs: Any) -> Any:+ # Malformed-input / OOM analogue: the tokenizer raises mid-call, after+ # ``pad_token_id`` has already been swapped to the MASK id by the caller.+ raise RuntimeError("tokenizer boom")+++class TestColBERTExpansionPadTokenRestore:+ """CodeRabbit #1800: the query-expansion branches swap ``pad_token_id`` to+ the MASK id before tokenizing and must restore it in ``finally``.++ Because the swap now runs under ``_tokenizer_guard()``, a tokenizer failure+ that skipped the restore would leave the instance's ``pad_token_id`` stuck at+ the MASK id and leak that corruption to every later guarded caller+ (including the §7.3 metering re-tokenize) — silently mis-padding and+ mis-counting until the model is reloaded. The ``finally`` must restore the+ original id even when the tokenizer raises.+ """++ def _adapter(self) -> ColBERTAdapter:+ adapter = ColBERTAdapter("test-model", skip_special_tokens=False, query_expansion=True)+ adapter._device = "cpu"+ adapter._actual_token_dim = 8+ adapter._max_seq_length = 512+ adapter._expansion_token_id = 103 # MASK id swapped in during expansion+ adapter._tokenizer = _RaisingExpansionTokenizer() # ty: ignore[invalid-assignment]+ adapter._model = MagicMock()+ return adapter++ def test_encode_native_restores_pad_token_id_on_tokenizer_error(self) -> None:+ adapter = self._adapter()+ original = adapter._tokenizer.pad_token_id+ assert original == 7+ with pytest.raises(RuntimeError, match="tokenizer boom"):+ adapter._encode_native(["query one two"], max_length=8, use_expansion=True, is_query=True)+ # The finally restored the original id despite the raise (not left at+ # the MASK/expansion id 103).+ assert adapter._tokenizer.pad_token_id == original+ assert adapter._tokenizer.pad_token_id != adapter._expansion_token_id++ def test_encode_manual_flash_restores_pad_token_id_on_tokenizer_error(self) -> None:+ adapter = self._adapter()+ original = adapter._tokenizer.pad_token_id+ assert original == 7+ with pytest.raises(RuntimeError, match="tokenizer boom"):+ adapter._encode_manual_flash(["query one two"], max_length=8, use_expansion=True, is_query=True)+ assert adapter._tokenizer.pad_token_id == original+ assert adapter._tokenizer.pad_token_id != adapter._expansion_token_iddiff --git a/packages/sie_server/tests/adapters/test_florence2.py b/packages/sie_server/tests/adapters/test_florence2.pyindex 091dd52b5..7ee898221 100644--- a/packages/sie_server/tests/adapters/test_florence2.py+++ b/packages/sie_server/tests/adapters/test_florence2.py@@ -1,6 +1,6 @@from __future__ import annotations-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchimport pytestfrom sie_server.types.inputs import Item@@ -192,6 +192,130 @@ class TestFlorence2Adapter:assert out.entities[0][0]["label"] == "answer"+class TestFlorence2ProcessorLoading:+ """Tests for the checkpoint-remote processor loading path.++ transformers >= 4.49 ships a *native* ``Florence2Processor`` whose ``__init__``+ reads ``tokenizer.image_token`` — an attribute the published Florence-2+ checkpoints' ``BartTokenizerFast`` does not have. Loading via a bare+ ``AutoProcessor`` can resolve to that native class and crash with+ ``AttributeError: BartTokenizerFast has no attribute image_token``. The adapter+ therefore loads the class named in the checkpoint's ``auto_map`` directly so the+ checkpoint's own (Bart-compatible) remote processor is always used.+ """++ def _adapter(self, model_id: str = "microsoft/Florence-2-base", revision: str | None = None):+ from sie_server.adapters.florence2 import Florence2Adapter++ return Florence2Adapter(model_id, revision=revision)++ def test_resolve_processor_auto_map_reads_preprocessor_config(self) -> None:+ """The AutoProcessor auto_map is discovered from the checkpoint configs."""+ import json++ adapter = self._adapter(revision="deadbeef")++ def fake_cached_file(model_id: str, filename: str, **kwargs: object) -> str | None:+ # Florence-2 checkpoints carry the auto_map in preprocessor_config.json,+ # not processor_config.json — the resolver must scan past the first miss.+ return f"/fake/{filename}" if filename == "preprocessor_config.json" else None++ payload = {"auto_map": {"AutoProcessor": "processing_florence2.Florence2Processor"}}+ with (+ patch("transformers.utils.cached_file", side_effect=fake_cached_file),+ patch("builtins.open", new_callable=MagicMock),+ patch.object(json, "load", return_value=payload),+ ):+ ref = adapter._resolve_processor_auto_map({"trust_remote_code": True, "revision": "deadbeef"})+ assert ref == "processing_florence2.Florence2Processor"++ def test_load_processor_forces_checkpoint_remote_class(self) -> None:+ """When an auto_map ref exists, the remote class is loaded verbatim.++ Regression: the cross-repo form ``<repo>--module.Class`` must be passed+ through unmodified so transformers fetches the upstream repo's code (the+ Florence-2-FT-DocVQA fork points at microsoft/Florence-2-base-ft).+ """+ adapter = self._adapter("mynkchaudhry/Florence-2-FT-DocVQA", revision="abc123")+ cross_repo_ref = "microsoft/Florence-2-base-ft--processing_florence2.Florence2Processor"++ fake_cls = MagicMock()+ fake_cls.from_pretrained.return_value = MagicMock(name="remote_processor")+ with (+ patch.object(adapter, "_resolve_processor_auto_map", return_value=cross_repo_ref),+ patch(+ "transformers.dynamic_module_utils.get_class_from_dynamic_module",+ return_value=fake_cls,+ ) as get_cls,+ ):+ proc = adapter._load_processor({"trust_remote_code": True, "revision": "abc123"})++ # Full ref passed verbatim (prefix NOT stripped) so cross-repo code resolves.+ get_cls.assert_called_once_with(+ cross_repo_ref,+ "mynkchaudhry/Florence-2-FT-DocVQA",+ revision="abc123",+ )+ fake_cls.from_pretrained.assert_called_once()+ assert proc is fake_cls.from_pretrained.return_value++ def test_load_processor_falls_back_to_autoprocessor_without_auto_map(self) -> None:+ """A local export with no remote auto_map falls back to AutoProcessor."""+ adapter = self._adapter("./some-local-export")+ with (+ patch.object(adapter, "_resolve_processor_auto_map", return_value=None),+ patch("transformers.AutoProcessor.from_pretrained", return_value="auto_proc") as auto_proc,+ ):+ proc = adapter._load_processor({"trust_remote_code": True})+ auto_proc.assert_called_once()+ assert proc == "auto_proc"+++class TestFlorence2CpuInference:+ """Heavy end-to-end test: real weights on CPU (deselected by default).++ Guards the transformers-4.57 native-processor regression at the level that+ actually failed on staging: load the pinned checkpoint via the adapter and run+ a real OCR + OD forward. Run with ``mise run test -- -m model``.+ """++ REVISION = "5ca5edf5bd017b9919c05d08aebef5e4c7ac3bac"++ def test_load_and_forward_cpu(self) -> None:+ import io++ from PIL import Image as PILImage+ from PIL import ImageDraw+ from sie_server.adapters.florence2 import Florence2Adapter+ from sie_server.types.inputs import ImageInput++ adapter = Florence2Adapter(+ "microsoft/Florence-2-base",+ revision=self.REVISION,+ default_task="<OCR>",+ attn_implementation="eager",+ )+ adapter.load("cpu")++ # The bug loaded the native processor from transformers.models.florence2;+ # the fix must load the checkpoint's own remote (transformers_modules) class.+ assert type(adapter._processor).__module__.startswith("transformers_modules")++ img = PILImage.new("RGB", (200, 80), (255, 255, 255))+ ImageDraw.Draw(img).text((10, 30), "HELLO", fill=(0, 0, 0))+ buf = io.BytesIO()+ img.save(buf, format="PNG")+ items = [Item(images=[ImageInput(data=buf.getvalue(), format="png")])]++ ocr = adapter.extract(items, options={"task": "<OCR>", "max_new_tokens": 24})+ assert ocr.entities, "OCR forward returned no entities"+ assert ocr.entities[0], "OCR forward returned an empty entity list"++ od = adapter.extract(items, options={"task": "<OD>", "max_new_tokens": 24})+ assert od.objects is not None, "OD forward returned no objects container"++class TestResolveFlorence2Prompt:"""Tests for the shared Florence-2 prompt/task resolver."""diff --git a/packages/sie_server/tests/api/test_encode_endpoint.py b/packages/sie_server/tests/api/test_encode_endpoint.pyindex 5b57bc88b..77ae640b2 100644--- a/packages/sie_server/tests/api/test_encode_endpoint.py+++ b/packages/sie_server/tests/api/test_encode_endpoint.py@@ -218,6 +218,8 @@ class TestEncodeEndpoint:def test_encode_model_not_found(self, client: TestClient, mock_registry: MagicMock) -> None:"""Returns 404 for unknown model."""mock_registry.has_model.return_value = False+ # Real registry raises for unknown models: guards the KeyError-500 regression.+ mock_registry.get_worker.side_effect = KeyError("Model 'unknown-model' not found in registry")response = client.post("/v1/encode/unknown-model",json={"items": [{"text": "Hello"}]},diff --git a/packages/sie_server/tests/api/test_extract.py b/packages/sie_server/tests/api/test_extract.pyindex ef1dcb2ad..289f11a50 100644--- a/packages/sie_server/tests/api/test_extract.py+++ b/packages/sie_server/tests/api/test_extract.py@@ -270,6 +270,8 @@ class TestExtractEndpoint:def test_extract_model_not_found(self, client: TestClient, mock_registry: MagicMock) -> None:"""Returns 404 for unknown model."""mock_registry.has_model.return_value = False+ # Real registry raises for unknown models: guards the KeyError-500 regression.+ mock_registry.get_worker.side_effect = KeyError("Model 'unknown-model' not found in registry")response = client.post("/v1/extract/unknown-model",json={diff --git a/packages/sie_server/tests/api/test_openai_compat.py b/packages/sie_server/tests/api/test_openai_compat.pyindex 771990012..5e878491c 100644--- a/packages/sie_server/tests/api/test_openai_compat.py+++ b/packages/sie_server/tests/api/test_openai_compat.py@@ -168,6 +168,8 @@ class TestOpenAIEmbeddings:def test_model_not_found(self, client: TestClient, mock_registry: MagicMock) -> None:"""Test 404 when model doesn't exist."""mock_registry.has_model.return_value = False+ # Real registry raises for unknown models: guards the KeyError-500 regression.+ mock_registry.get_worker.side_effect = KeyError("Model 'nonexistent-model' not found in registry")response = client.post("/v1/embeddings",diff --git a/packages/sie_server/tests/api/test_score.py b/packages/sie_server/tests/api/test_score.pyindex f9e116af1..67bb55504 100644--- a/packages/sie_server/tests/api/test_score.py+++ b/packages/sie_server/tests/api/test_score.py@@ -285,6 +285,8 @@ class TestScoreEndpoint:def test_score_model_not_found(self, client: TestClient, mock_registry: MagicMock) -> None:"""Returns 404 for unknown model."""mock_registry.has_model.return_value = False+ # Real registry raises for unknown models: guards the KeyError-500 regression.+ mock_registry.get_worker.side_effect = KeyError("Model 'unknown-model' not found in registry")response = client.post("/v1/score/unknown-model",json={diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.pyindex eea305214..6ff261c09 100644--- a/packages/sie_server/tests/processors/test_streaming.py+++ b/packages/sie_server/tests/processors/test_streaming.py@@ -446,16 +446,19 @@ def _make_registry_with_chat_config(chat_template_kwargs: dict[str, Any] | None = None,context_length: int = 32768,hf_id: str = "test/model",+ hf_revision: str | None = None,) -> MagicMock:"""Variant of :func:`_make_registry` that also fakes ``get_config``.The streaming processor's chat-template path reads``config.tasks.generate.chat_template_kwargs`` and the context-lengthpath reads ``config.tasks.generate.context_length`` and ``config.hf_id``.+ The tokenizer load also reads ``config.hf_revision`` to pin the load."""registry = _make_registry(adapter)config = MagicMock()config.hf_id = hf_id+ config.hf_revision = hf_revisionconfig.weights_path = Noneconfig.tasks.generate.chat_template_kwargs = chat_template_kwargs or {}config.tasks.generate.context_length = context_length@@ -518,6 +521,50 @@ async def test_streaming_processor_renders_chat_template(monkeypatch) -> None:assert decoded[-1]["finish_reason"] == "stop"+async def test_streaming_processor_pins_tokenizer_revision(monkeypatch) -> None:+ """The tokenizer load forwards the model's pinned ``hf_revision``.++ Under ``HF_HUB_OFFLINE=1`` a no-revision load resolves ``refs/main``,+ which is absent for repos staged by pinned SHA — pinning the revision+ resolves the ``snapshots/<sha>`` dir directly (#1801).+ """+ nc = AsyncMock()+ script = [+ GenerationChunk(text_delta="ok", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=1, completion_tokens=1),+ ]+ adapter = _FakeGenAdapter(script)+ sha = "cdbee75f17c01a7cc42f958dc650907174af0554"+ registry = _make_registry_with_chat_config(adapter, hf_id="test/model", hf_revision=sha)++ seen: dict[str, Any] = {}++ class _StubTok:+ def apply_chat_template(self, messages, *, tokenize, add_generation_prompt, **kwargs):+ return "<rendered>" + "".join(m["content"] for m in messages) + "</rendered>"++ def encode(self, text, *, add_special_tokens):+ return [0] * len(text.split())++ def _spy_load(source, *, trust_remote_code=False, revision=None):+ seen["source"] = source+ seen["revision"] = revision+ return _StubTok()++ from sie_server.processors import streaming as streaming_mod++ monkeypatch.setattr(streaming_mod, "load_tokenizer", _spy_load)++ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ wi = _make_work_item(messages=[{"role": "user", "content": "ping"}])+ msg = _make_msg(wi)+ await proc.process(msg, "test/model")++ assert seen["source"] == "test/model"+ assert seen["revision"] == sha++@pytest.mark.asyncioasync def test_streaming_processor_chat_template_render_error_becomes_terminal_chunk(monkeypatch) -> None:"""A tokenizer that raises mid-render → terminal ``invalid_request``."""diff --git a/packages/sie_server/tests/test_metering_units.py b/packages/sie_server/tests/test_metering_units.pyindex a2f843331..7f18ec2cd 100644--- a/packages/sie_server/tests/test_metering_units.py+++ b/packages/sie_server/tests/test_metering_units.py@@ -19,6 +19,7 @@ bge-m3 / GLiNER / cross_encoder keep their exact values).from __future__ import annotationsimport asyncio+import threadingimport timefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patch@@ -30,6 +31,7 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters.bert_flash import BertFlashAdapterfrom sie_server.adapters.clip import CLIPAdapterfrom sie_server.adapters.colbert import ColBERTAdapter+from sie_server.adapters.cross_encoder import CrossEncoderAdapterfrom sie_server.adapters.jina_flash_cross_encoder import JinaFlashCrossEncoderAdapterfrom sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapterfrom sie_server.adapters.siglip import SiglipAdapter@@ -864,3 +866,162 @@ class TestVisionTextTokenStamp:adapter._encode_texts = fake_encode_texts # type: ignore[method-assign]out = adapter.encode([Item(text="a b c")], ["dense"])assert out.extra["input_token_counts"] == [5]+++# ---------------------------------------------------------------------------+# cross_encoder predict/metering concurrency guard (#1800 class-fix, #1782)+# ---------------------------------------------------------------------------+++class _ReentrancyDetectingTokenizer:+ """Emulates a HuggingFace fast tokenizer's non-re-entrancy.++ A real fast tokenizer wraps a Rust object behind a ``RefCell``; a second+ call that begins while a first is still in flight raises+ ``RuntimeError("Already borrowed")`` (#1800). This fake reproduces that+ exact failure mode: it raises if two calls are inside a tokenizer call at+ the same time, so a correct serialization guard makes it pass and a missing+ guard makes it fail. It matches the shape the base metering counter expects+ (list-of-lists ``input_ids``, joint ``(text, text_pair)`` support).+ """++ def __init__(self, model_max_length: int = 512) -> None:+ self.model_max_length = model_max_length+ self._active = 0+ self._active_lock = threading.Lock()++ def _enter(self) -> None:+ with self._active_lock:+ if self._active != 0:+ raise RuntimeError("Already borrowed")+ self._active += 1++ def _exit(self) -> None:+ with self._active_lock:+ self._active -= 1++ def __call__(+ self,+ text: list[str] | str,+ text_pair: list[str] | str | None = None,+ *,+ truncation: bool = False,+ max_length: int | None = None,+ **_: Any,+ ) -> dict[str, list[list[int]]]:+ self._enter()+ try:+ # Simulate real tokenizer latency so overlapping threads collide.+ time.sleep(0.002)+ texts = [text] if isinstance(text, str) else list(text)+ if text_pair is not None:+ pairs = [text_pair] if isinstance(text_pair, str) else list(text_pair)+ lengths = [len(a.split()) + len(b.split()) + 3 for a, b in zip(texts, pairs, strict=True)]+ else:+ lengths = [len(t.split()) + 2 for t in texts]+ if truncation and max_length is not None:+ lengths = [min(n, max_length) for n in lengths]+ return {"input_ids": [[0] * n for n in lengths]}+ finally:+ self._exit()+++class TestCrossEncoderTokenizerConcurrencyGuard:+ """Regression for the #1800 class-fix on the sentence-transformers+ ``CrossEncoderAdapter``.++ ``score_pairs`` runs on the single inference-executor thread and does two+ things against the SAME ``self._model.tokenizer``: ``CrossEncoder.predict``+ tokenizes internally (fused with the GPU forward), then the inline+ ``_pair_input_token_counts`` re-tokenizes the pairs for §7.3 metering. The+ shared ``count_pair_input_tokens`` metering fallback re-tokenizes the very+ same tokenizer on a separate thread-pool thread for another concurrent+ request. A bare HF fast tokenizer raises ``Already borrowed`` when two+ tokenize calls overlap; ``_tokenizer_guard()`` on the encode/score-side+ re-tokenize (the sibling of the guard the metering entry point already+ holds) must serialise them.+ """++ def _make_adapter(self, tokenizer: _ReentrancyDetectingTokenizer) -> CrossEncoderAdapter:+ adapter = CrossEncoderAdapter("stub/reranker")+ adapter._device = "cpu"++ def _fake_predict(pairs: list[tuple[str, str]]) -> np.ndarray:+ # Mirror CrossEncoder.predict: tokenize the batch (fused with the+ # forward) on the same tokenizer the metering path re-tokenizes.+ tokenizer([q for q, _ in pairs], [d for _, d in pairs], truncation=True, max_length=512)+ return np.zeros(len(pairs), dtype=np.float32)++ model = MagicMock()+ model.predict.side_effect = _fake_predict+ model.tokenizer = tokenizer+ model.max_length = 512+ adapter._model = model # ty: ignore[invalid-assignment]+ return adapter++ def test_score_and_metering_do_not_collide_under_concurrency(self) -> None:+ """Batched scoring on one thread and metering-tokenizing on another must+ not raise ``Already borrowed`` — the guard serialises tokenizer access.+ """+ tokenizer = _ReentrancyDetectingTokenizer()+ adapter = self._make_adapter(tokenizer)+ query = Item(text="the query terms")+ docs = [Item(text="doc one"), Item(text="a considerably longer document body")]+ queries = [query] * len(docs)++ errors: list[BaseException] = []+ stop = threading.Event()++ def score_loop() -> None:+ try:+ for _ in range(40):+ if stop.is_set():+ return+ out = adapter.score_pairs(queries, docs)+ assert out.input_token_counts is not None+ assert len(out.input_token_counts) == len(docs)+ except BaseException as e: # noqa: BLE001+ errors.append(e)++ def metering_loop() -> None:+ try:+ for _ in range(40):+ if stop.is_set():+ return+ counts = adapter.count_pair_input_tokens(query, docs)+ assert counts is not None+ assert len(counts) == len(docs)+ except BaseException as e: # noqa: BLE001+ errors.append(e)++ threads = [threading.Thread(target=score_loop) for _ in range(2)]+ threads += [threading.Thread(target=metering_loop) for _ in range(2)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=30)+ stop.set()++ assert not errors, f"tokenizer collision under concurrency: {errors!r}"++ def test_reentrancy_detector_fires_without_guard(self) -> None:+ """Sanity check the harness: bare concurrent tokenizer calls (no guard)+ DO raise ``Already borrowed`` — otherwise the guard test is vacuous.+ """+ tokenizer = _ReentrancyDetectingTokenizer()+ errors: list[BaseException] = []++ def call_loop() -> None:+ try:+ for _ in range(40):+ tokenizer(["a", "b c"], ["x", "y z"], truncation=True, max_length=512)+ except BaseException as e: # noqa: BLE001+ errors.append(e)++ threads = [threading.Thread(target=call_loop) for _ in range(4)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=30)++ assert any(isinstance(e, RuntimeError) and "Already borrowed" in str(e) for e in errors)diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.pyindex f73ea2b0f..ab5087f1d 100644--- a/packages/sie_server/tests/test_queue_executor.py+++ b/packages/sie_server/tests/test_queue_executor.py@@ -32,6 +32,11 @@ def _make_registry(*, loaded: bool = True, loading: bool = False) -> MagicMock:reg.is_loaded.return_value = loadedreg.is_loading.return_value = loadingreg.get_config.return_value = MagicMock()+ # No recorded load failure by default — a bare MagicMock would otherwise+ # return a truthy stub for ``get_failure(...)`` and its ``.is_permanent``,+ # which ``ensure_model_ready`` now reads to gate the terminal ``failed``+ # state (#1786 fast-path). Tests that want the terminal path set this.+ reg.get_failure.return_value = Nonereturn reg@@ -159,6 +164,69 @@ class TestEnsureModelReady:ex = QueueExecutor(reg)assert await ex.ensure_model_ready("test/model") == "retry_later"+ @pytest.mark.asyncio+ async def test_permanent_failure_returns_terminal_failed(self) -> None:+ """#1786 fast-path: a PERMANENT load failure surfaces as the terminal+ ``failed`` state (not ``loading_in_progress``) so the sidecar+ dead-letters instead of re-driving forever.+ """+ from sie_server.core.load_errors import LoadErrorClass, LoadFailure++ reg = _make_registry(loaded=False, loading=False)+ reg.get_failure.return_value = LoadFailure(+ error_class=LoadErrorClass.GATED,+ message="repository is gated",+ attempts=1,+ last_attempt_ts=time.monotonic(),+ cooldown_s=None, # permanent+ )+ ex = QueueExecutor(reg)+ assert await ex.ensure_model_ready("test/model") == "failed"+ # Terminal — must NOT try to (re)start a doomed load.+ reg.start_load_async.assert_not_called()++ @pytest.mark.asyncio+ async def test_transient_failure_is_not_terminal(self) -> None:+ """A TRANSIENT in-cooldown failure (OOM/NETWORK/TIMEOUT) stays+ retryable — it must not be reported as terminal ``failed``.+ """+ from sie_server.core.load_errors import LoadErrorClass, LoadFailure++ reg = _make_registry(loaded=False, loading=False)+ reg.get_failure.return_value = LoadFailure(+ error_class=LoadErrorClass.OOM,+ message="cuda oom",+ attempts=1,+ last_attempt_ts=time.monotonic(),+ cooldown_s=30.0, # transient+ )+ reg.start_load_async = AsyncMock(return_value=False)+ ex = QueueExecutor(reg)+ assert await ex.ensure_model_ready("test/model") == "loading_in_progress"++ @pytest.mark.asyncio+ async def test_permanent_failure_recorded_mid_start_returns_failed(self) -> None:+ """A load that flips to a PERMANENT failure while ``start_load_async``+ runs (so it returns ``False``) is dead-lettered, not re-driven.+ """+ from sie_server.core.load_errors import LoadErrorClass, LoadFailure++ reg = _make_registry(loaded=False, loading=False)+ # Clean at the up-front check, permanent by the time start returns False.+ reg.get_failure.side_effect = [+ None,+ LoadFailure(+ error_class=LoadErrorClass.DEPENDENCY,+ message="missing dep",+ attempts=1,+ last_attempt_ts=time.monotonic(),+ cooldown_s=None,+ ),+ ]+ reg.start_load_async = AsyncMock(return_value=False)+ ex = QueueExecutor(reg)+ assert await ex.ensure_model_ready("test/model") == "failed"+@pytest.mark.asyncio@patch("sie_server.core.model_loader.load_adapter")async def test_concurrent_sidecar_ready_loads_use_distinct_configured_devices(diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lockindex 3b050fd43..cd86a9fd0 100644--- a/packages/sie_server_sidecar/Cargo.lock+++ b/packages/sie_server_sidecar/Cargo.lock@@ -2474,7 +2474,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-server-sidecar"-version = "0.6.18"+version = "0.6.19"dependencies = ["anyhow","async-nats",diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex 2a47857f2..e64311dce 100644--- a/packages/sie_server_sidecar/Cargo.toml+++ b/packages/sie_server_sidecar/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-server-sidecar"-version = "0.6.18"+version = "0.6.19"edition = "2021"description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."diff --git a/packages/sie_server_sidecar/src/backend/router.rs b/packages/sie_server_sidecar/src/backend/router.rsindex b40fa3ea1..4659287c8 100644--- a/packages/sie_server_sidecar/src/backend/router.rs+++ b/packages/sie_server_sidecar/src/backend/router.rs@@ -210,6 +210,7 @@ impl BackendRouter {ReadinessState::LoadingStarted => "loading_started",ReadinessState::LoadingInProgress => "loading_in_progress",ReadinessState::RetryLater => "retry_later",+ ReadinessState::Failed => "failed",},Err(BackendError::UnsupportedModel(_)) => "unsupported",Err(BackendError::Draining) => "draining",diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 0330272da..fc5dca74f 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -52,6 +52,15 @@ use crate::tokenize::TokenizerRegistry;use crate::work_types::WorkItem;const MODEL_LOADING_ERROR_CODE: &str = "MODEL_LOADING";+/// Terminal, non-retryable model-load failure. Emitted on the `WorkResult`+/// (encode/score/extract) or the generation terminal chunk when the Python+/// executor reports [`ReadinessState::Failed`] (registry holds a PERMANENT+/// `LoadFailure`). The gateway maps this code to a typed HTTP 502 via+/// `build_model_load_failed_response` (unary/batch path) — the fast-path twin+/// of the #1786 `run_batch` mapping. Kept byte-identical to the gateway+/// constant `sie_gateway::handlers::proxy::MODEL_LOAD_FAILED_ERROR_CODE` and+/// the Python `ErrorCode.MODEL_LOAD_FAILED`.+const MODEL_LOAD_FAILED_ERROR_CODE: &str = "MODEL_LOAD_FAILED";#[derive(serde::Serialize)]struct GenerateTerminalErrorChunk<'a> {@@ -169,7 +178,9 @@ fn readiness_progress_delay_ms(state: &ReadinessState, base_delay_ms: u64) -> OpReadinessState::LoadingInProgress => {Some(base_delay_ms.saturating_mul(2).min(max_delay_ms))}- ReadinessState::Ready | ReadinessState::RetryLater => None,+ // `Failed` is terminal: no progress delay — the caller dead-letters+ // the group instead of re-driving `EnsureModelReady`.+ ReadinessState::Ready | ReadinessState::RetryLater | ReadinessState::Failed => None,}}@@ -980,6 +991,69 @@ impl Dispatcher {}return;}+ ReadinessState::Failed => {+ // Terminal load failure (permanent cooldown). Re-driving would+ // hang the streaming client forever (#1786 fast-path gap), so+ // publish a terminal MODEL_LOAD_FAILED chunk + ACK — the+ // gateway's streaming collector maps the code to a typed+ // failure exactly like the batch path.+ info!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ readiness = ?readiness_resp.state,+ subject = %delivery.subject,+ stream = %delivery.stream,+ consumer = %delivery.consumer,+ stream_seq = delivery.stream_sequence,+ consumer_seq = delivery.consumer_sequence,+ delivery_count = delivery.delivered,+ pending = delivery.pending,+ "generate model load failed terminally — publishing MODEL_LOAD_FAILED chunk + ACK"+ );+ let message = format!("Model '{model_id}' failed to load permanently.");+ match self+ .publish_generate_terminal_error(&wi, MODEL_LOAD_FAILED_ERROR_CODE, &message)+ .await+ {+ Ok(_) => match ack_msg(&msg).await {+ Ok(()) => {+ self.metrics.messages_acked_total.inc();+ self.metrics+ .generate_model_loading_responses_total+ .with_label_values(&[&model_lbl, "failed", "published_acked"])+ .inc();+ }+ Err(e) => {+ warn!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ stream_seq = delivery.stream_sequence,+ delivery_count = delivery.delivered,+ error = %e,+ "ack after MODEL_LOAD_FAILED chunk publish failed"+ );+ self.metrics.jetstream_ack_failures_total.inc();+ self.metrics+ .generate_model_loading_responses_total+ .with_label_values(&[&model_lbl, "failed", "published_ack_failed"])+ .inc();+ }+ },+ Err(_) => {+ self.metrics+ .generate_model_loading_responses_total+ .with_label_values(&[&model_lbl, "failed", "publish_failed"])+ .inc();+ // Terminal failure but the publish itself failed: NAK+ // so redelivery can retry surfacing the typed error+ // rather than silently dropping the client's request.+ nak_msg(&msg, base_delay_ms, &self.metrics).await;+ }+ }+ return;+ }}// Resolve an offloaded generate payload. The gateway offloads large@@ -1240,6 +1314,22 @@ impl Dispatcher {if readiness_resp.state == ReadinessState::Ready {break readiness_resp;}+ if readiness_resp.state == ReadinessState::Failed {+ // Terminal load failure (permanent cooldown on the Python+ // registry). Re-driving `EnsureModelReady` would loop forever+ // and hang the client (#1786 fast-path gap), so dead-letter+ // the whole group as `MODEL_LOAD_FAILED` — the gateway maps+ // that code to a typed 502, exactly like the batch/`run_batch`+ // path. ACK each item after publishing its error so JetStream+ // stops redelivering the doomed work.+ info!(+ model = %model_id,+ group_size,+ "model load failed terminally — dead-lettering group as MODEL_LOAD_FAILED"+ );+ self.dead_letter_all(&items, model_id).await;+ return Ok(());+ }if let Some(delay_ms) =readiness_progress_delay_ms(&readiness_resp.state, base_delay_ms){@@ -2075,6 +2165,49 @@ impl Dispatcher {}}+ /// Dead-letter a whole (op, model) group on a TERMINAL load failure:+ /// publish a typed `MODEL_LOAD_FAILED` error `WorkResult` for every item+ /// and ACK it. This is the [`ReadinessState::Failed`] fast-path twin of+ /// the batch/`run_batch` `MODEL_LOAD_FAILED` mapping (#1786) — the gateway+ /// turns the code into an HTTP 502 so the client fails fast instead of+ /// blocking while the sidecar re-drives a doomed model forever.+ ///+ /// Per-item settlement mirrors [`Self::apply_outcome`] for a+ /// `PublishErrorAndAck` outcome: ACK once the error is published (or the+ /// item is fire-and-forget); if the NATS publish itself fails, NAK so+ /// JetStream redelivers and another attempt can surface the failure.+ async fn dead_letter_all(&self, items: &[(WorkItem, Delivery)], model_id: &str) {+ let message = format!("Model '{model_id}' failed to load permanently.");+ for (wi, delivery) in items {+ match self+ .publish_error(wi, delivery, MODEL_LOAD_FAILED_ERROR_CODE, &message)+ .await+ {+ Ok(_) => match ack(delivery).await {+ Ok(()) => self.metrics.messages_acked_total.inc(),+ Err(e) => {+ warn!(+ work_item_id = %wi.work_item_id,+ error = %e,+ "ack after MODEL_LOAD_FAILED publish failed"+ );+ self.metrics.jetstream_ack_failures_total.inc();+ }+ },+ Err(_) => {+ // Publish failed — the client never got the typed error,+ // so rely on redelivery rather than ACKing it away.+ nak_one(delivery, base_nak_delay_ms(), &self.metrics).await;+ }+ }+ }+ debug!(+ count = items.len(),+ model = %model_id,+ "dead-lettered group as MODEL_LOAD_FAILED"+ );+ }+/// Generate-path twin of [`Self::publish_error`]. The generate flow is/// NATS-only (local-ingest generate items are rejected before reaching/// it, see [`Self::dispatch_decoded`]) and holds its [`Message`] in an@@ -4311,6 +4444,12 @@ mod tests {readiness_progress_delay_ms(&ReadinessState::RetryLater, 5_000),None);+ // Terminal failure is NOT a loading state — no progress-ACK re-drive;+ // the caller dead-letters instead.+ assert_eq!(+ readiness_progress_delay_ms(&ReadinessState::Failed, 5_000),+ None+ );}#[test]diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex 7977f359d..388d1a56f 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -175,6 +175,19 @@ pub enum ReadinessState {LoadingStarted,LoadingInProgress,RetryLater,+ /// Terminal, non-retryable load failure. The Python executor+ /// reports this when the registry holds a PERMANENT `LoadFailure`+ /// (`cooldown=permanent`: `GATED` / `NOT_FOUND` / `DEPENDENCY` /+ /// `UNKNOWN`) — the same classification the direct-HTTP+ /// `check_not_failed` gate and the Modal lane's+ /// `worker_runtime._terminal_load_failure` use for #1786. It exists+ /// so the sidecar can DISTINGUISH "still loading" (retry) from+ /// "dead on arrival" (dead-letter): on `Failed` the dispatcher stops+ /// re-driving `EnsureModelReady` and publishes a typed+ /// `MODEL_LOAD_FAILED` error `WorkResult` (gateway → 502), matching+ /// the batch/`run_batch` path. Wire format is the plain string+ /// `"failed"` (see Python `ReadinessState` Literal).+ Failed,}/// Model descriptor carried on the `EnsureModelReady` handshake.@@ -959,6 +972,14 @@ mod tests {let s = serde_json::to_string(&ReadinessState::RetryLater).unwrap();assert_eq!(s, "\"retry_later\"");++ // Terminal load-failure variant — the string the Python executor+ // sends so the sidecar can dead-letter instead of re-driving.+ let s = serde_json::to_string(&ReadinessState::Failed).unwrap();+ assert_eq!(s, "\"failed\"");+ let bytes = rmp_serde::to_vec_named(&ReadinessState::Failed).unwrap();+ let back: ReadinessState = rmp_serde::from_slice(&bytes).unwrap();+ assert_eq!(back, ReadinessState::Failed);}#[test]diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex bff29af69..44756979d 100644--- a/packages/sie_ts_sdk/package.json+++ b/packages/sie_ts_sdk/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-sdk",- "version": "0.6.18",+ "version": "0.6.19","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 934b9a371..e1bccc05b 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.6.18"; // x-release-please-version+export const SDK_VERSION = "0.6.19"; // x-release-please-versiondiff --git a/pyproject.toml b/pyproject.tomlindex 1c0f8d76e..38349c014 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -120,7 +120,7 @@ members = [[tool.pytest.ini_options]# Note: integrations are NOT in testpaths because each has its own conftest.py# which causes pytest plugin conflicts. Run with: mise run test integrations/-testpaths = ["packages/sie_server/tests", "packages/sie_sdk/tests", "packages/sie_bench/tests", "packages/sie_admin/tests", "packages/sie_config/tests", "packages/sie_mcp/tests", "packages/sie_tools/tests", "tools/mise_tasks/tests", "tools/quality_eval/tests", "product/research/sie-cost-model/bill-cut-model/tests"]+testpaths = ["packages/sie_server/tests", "packages/sie_sdk/tests", "packages/sie_bench/tests", "packages/sie_admin/tests", "packages/sie_config/tests", "packages/sie_mcp/tests", "packages/sie_tools/tests", "tools/mise_tasks/tests", "tools/quality_eval/tests", "tools/model_ops/tests", "product/research/sie-cost-model/bill-cut-model/tests"]pythonpath = ["packages/sie_server/src", "packages/sie_sdk/src", "packages/sie_bench/src", "packages/sie_admin/src", "packages/sie_config/src", "packages/sie_mcp/src", "packages/sie_tools/src", "tools/mise_tasks"]addopts = "-m 'not integration and not docker and not model' --import-mode=importlib"asyncio_mode = "auto"diff --git a/uv.lock b/uv.lockindex e64dca5cf..a0ea0a10c 100644--- a/uv.lock+++ b/uv.lock@@ -5723,7 +5723,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.6.18"+version = "0.6.19"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5756,7 +5756,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.6.18"+version = "0.6.19"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5841,7 +5841,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.6.18"+version = "0.6.19"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5913,7 +5913,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.18"+version = "0.6.19"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5938,7 +5938,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.18"+version = "0.6.19"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5963,7 +5963,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.18"+version = "0.6.19"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5990,7 +5990,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.18"+version = "0.6.19"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -6017,7 +6017,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.18"+version = "0.6.19"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -6044,7 +6044,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.18"+version = "0.6.19"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -6110,7 +6110,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.6.18"+version = "0.6.19"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -6133,7 +6133,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.18"+version = "0.6.19"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -6186,7 +6186,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.18"+version = "0.6.19"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -6324,7 +6324,7 @@ requires-dist = [[[package]]name = "sie-weaviate"-version = "0.6.18"+version = "0.6.19"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },