Skip to content

armgit / sie

Public Imported from GitHub
0

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

release: v0.3.3

github-actions[bot]db3f9007d260
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f81ff2219..f52426299 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,40 @@
# Changelog
+## v0.3.3
+
+- chore(main): release 0.3.3
+- fix(docker): install libspatialindex-c6 in worker images
+- refactor(gliclass): tighten IndexError discriminator with regex
+- fix(gliclass): catch IndexError empty-tensor crash as InputTooLongError
+- test(gliclass): cover _apply_overflow_policy per policy
+- fix(gliclass): raise InputTooLongError from argmax-empty backstop
+- chore(openapi): update openapi spec
+- Fix gateway routing and autoscaling regressions
+- Address Tilt PR review feedback
+- Optimize gateway msgpack success responses
+- Add kind Tilt gateway SDK E2E loop
+- refactor(server): give overflow_policy a typed home
+- test(adaptive-batching): add absolute tolerance to floating-point assertions
+- docs(gliclass): document token accounting in _apply_overflow_policy
+- chore(gliclass): refactoring
+- chore(gliclass): remove redundant docstring _extract_text
+- chore(gliclass): remove redundant "loaded" checks
+- feat(server): enforce overflow_policy in gliclass adapter
+- feat(server): validate overflow_policy in resolve_runtime_options
+- docs(server): surface overflow_policy in extract OpenAPI schema
+- feat(server): route INPUT_TOO_LONG to HTTP 400 in extract API
+- feat(server): add new INPUT_TOO_LONG ErrorCode
+- feat(model-loader): add post-download load timeout with stall-based download bounds
+- fix(ci): peft-adapter base size + ocr force-heavy + drop hf_hub cap
+- fix(bundles): cap huggingface-hub <0.32 in transformers5 bundle
+- fix(ci): drop runner_class from public model YAMLs; route via HF size
+- feat(ci): two GPU lanes (L4 + g7e) with model-driven routing
+- fix(sglang): make startup timeout env-driven; bump default 300 -> 900
+- fix(adapters): preserve encode order/boundaries (colqwen3) + lock v1 to_dict patch (nemo_colembed)
+- fix(nemo_colembed): strip zero-padded rows from v2 batched embeddings
+- fix(nemo_colembed): broaden AutoModel-failure catch for v1 fallback
+- feat(adapters): add ColQwen3 and Nemotron ColEmbed v2 visual document retrieval
+
## v0.3.2
- chore(main): release 0.3.2
diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yaml
index a159400c9..64ae6de29 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 observability
type: application
-version: 0.3.2 # x-release-please-version
-appVersion: v0.3.2 # x-release-please-version
+version: 0.3.3 # x-release-please-version
+appVersion: v0.3.3 # x-release-please-version
keywords:
- inference
- embedding
diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.toml
index ffb59e6be..30114bba1 100644
--- a/integrations/sie_chroma/pyproject.toml
+++ b/integrations/sie_chroma/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-chroma"
-version = "0.3.2"
+version = "0.3.3"
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.toml
index 250fed6e1..2f9e9e12d 100644
--- a/integrations/sie_crewai/pyproject.toml
+++ b/integrations/sie_crewai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-crewai"
-version = "0.3.2"
+version = "0.3.3"
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.toml
index 76d07b7c2..d4e66ad7a 100644
--- a/integrations/sie_dspy/pyproject.toml
+++ b/integrations/sie_dspy/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-dspy"
-version = "0.3.2"
+version = "0.3.3"
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.toml
index b3963d1ab..2302b8fcf 100644
--- a/integrations/sie_haystack/pyproject.toml
+++ b/integrations/sie_haystack/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-haystack"
-version = "0.3.2"
+version = "0.3.3"
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.toml
index 41501851b..cec9522c5 100644
--- a/integrations/sie_lancedb/pyproject.toml
+++ b/integrations/sie_lancedb/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-lancedb"
-version = "0.3.2"
+version = "0.3.3"
description = "SIE integration for LanceDB"
requires-python = ">=3.12"
dependencies = [
diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.toml
index fbcf99d08..16624bed2 100644
--- a/integrations/sie_langchain/pyproject.toml
+++ b/integrations/sie_langchain/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-langchain"
-version = "0.3.2"
+version = "0.3.3"
description = "SIE integration for LangChain"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.toml
index 5c24ae6a3..7bc1fb9e3 100644
--- a/integrations/sie_llamaindex/pyproject.toml
+++ b/integrations/sie_llamaindex/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-llamaindex"
-version = "0.3.2"
+version = "0.3.3"
description = "SIE integration for LlamaIndex"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.toml
index d07d936ca..df3c7f445 100644
--- a/integrations/sie_qdrant/pyproject.toml
+++ b/integrations/sie_qdrant/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-qdrant"
-version = "0.3.2"
+version = "0.3.3"
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.json
index 035a0ae66..bf91fabe4 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.3.2",
+ "version": "0.3.3",
"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.json
index c3cc956f8..4094dc46b 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.3.2",
+ "version": "0.3.3",
"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.json
index 9843f9ec1..53c292fc3 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.3.2",
+ "version": "0.3.3",
"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.json
index 3bab62ab4..b5cf9ea0b 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.3.2",
+ "version": "0.3.3",
"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.toml
index 9868ddd3b..5a25d687f 100644
--- a/integrations/sie_weaviate/pyproject.toml
+++ b/integrations/sie_weaviate/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-weaviate"
-version = "0.3.2"
+version = "0.3.3"
description = "SIE integration for Weaviate"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lock
index 65fa8fdbf..98c8a1b9b 100644
--- a/packages/sie_gateway/Cargo.lock
+++ b/packages/sie_gateway/Cargo.lock
@@ -2774,7 +2774,7 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "sie-gateway"
-version = "0.3.2"
+version = "0.3.3"
dependencies = [
"arc-swap",
"async-nats",
diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.toml
index 173f45881..b98efecc0 100644
--- a/packages/sie_gateway/Cargo.toml
+++ b/packages/sie_gateway/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-gateway"
-version = "0.3.2"
+version = "0.3.3"
edition = "2021"
publish = false
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json
index d8e6fae2c..23f850823 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -1786,7 +1786,7 @@
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
},
"title": "SIE Gateway",
- "version": "0.3.2"
+ "version": "0.3.3"
},
"openapi": "3.1.0",
"paths": {
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index e2f353f68..b58e72d89 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -18,6 +18,7 @@ use crate::queue::publisher;
use crate::server::AppState;
use crate::state::model_registry::ResolveError;
+use crate::state::pool_manager::DEFAULT_POOL_NAME;
use crate::state::worker_registry::WorkerRegistry;
use crate::types::AuditEntry;
@@ -103,11 +104,9 @@ struct PoolLookup {
/// `true` iff a healthy worker with a non-empty pool name existed
/// for the exact `(bundle, gpu)` tuple at lookup time.
///
- /// Always `false` when `gpu.is_empty()` (no exact tuple to match)
- /// or when `pool_name` was caller-pinned (we short-circuit the
- /// registry lookup entirely in that case — callers that care
- /// about demand tracking already know to record it before
- /// trusting the pin).
+ /// Always `false` when `gpu.is_empty()` (no exact tuple to match).
+ /// Caller-pinned pools still probe the registry when a GPU is
+ /// present so demand tracking can avoid spurious scale-up signals.
exact_gpu_match: bool,
}
@@ -121,10 +120,10 @@ struct PoolLookup {
/// there unconditionally. This preserves the "power user" path where
/// the client knows exactly which pool it wants (including cold ones
/// that are expected to scale up on demand).
-/// - Otherwise look up a healthy worker for `(bundle, gpu)`. If GPU was
-/// specified and the exact tuple has no worker, fall back to any worker
-/// on `bundle` (covers single-GPU clusters where the profile-level
-/// distinction is cosmetic).
+/// - Otherwise look up a healthy default-pool worker for `(bundle, gpu)`.
+/// If GPU was specified and the exact tuple has no worker, fall back to
+/// any default-pool worker on `bundle` (covers single-GPU clusters where
+/// the profile-level distinction is cosmetic).
/// - If nothing resolves, return `Provisioning` so the caller can emit
/// `202 + Retry-After` — regardless of whether the caller sent
/// `X-SIE-MACHINE-PROFILE`. Before the fix this branch only fired when
@@ -155,15 +154,22 @@ async fn resolve_effective_pool(
// Primary lookup. Folds the "was the exact tuple routable?"
// question into the same registry load we use to pick a pool.
- let primary = registry.resolve_queue_pool(bundle, gpu).await;
+ let primary = registry
+ .resolve_queue_pool_in_pool(bundle, gpu, DEFAULT_POOL_NAME)
+ .await;
let exact_gpu_match = !gpu.is_empty() && primary.is_some();
// Fallback: caller expressed a GPU preference but nothing matches;
- // try any healthy worker on the bundle. This covers single-GPU
- // clusters where the profile-level distinction is cosmetic.
+ // try any healthy default-pool worker on the bundle. This covers
+ // single-GPU clusters where the profile-level distinction is cosmetic
+ // without leaking traffic into caller-created isolation pools.
let resolved = match primary {
Some(p) => Some(p),
- None if !gpu.is_empty() => registry.resolve_queue_pool(bundle, "").await,
+ None if !gpu.is_empty() => {
+ registry
+ .resolve_queue_pool_in_pool(bundle, "", DEFAULT_POOL_NAME)
+ .await
+ }
None => None,
};
@@ -1183,26 +1189,6 @@ fn result_decode_error_value(r: &publisher::WorkResult, message: String) -> serd
})
}
-fn validated_msgpack_result_blob(r: &publisher::WorkResult) -> Vec<u8> {
- match rmp_serde::from_slice::<rmpv::Value>(&r.result_msgpack) {
- Ok(_) => r.result_msgpack.clone(),
- Err(err) => {
- let placeholder =
- result_decode_error_value(r, format!("failed to decode result_msgpack: {err}"));
- rmp_serde::to_vec(&placeholder).unwrap_or_else(|_| {
- rmp_serde::to_vec(&json!({
- "item_index": r.item_index,
- "error": {
- "code": "RESULT_DECODE_FAILED",
- "message": "failed to encode result decode error",
- },
- }))
- .unwrap_or_default()
- })
- }
- }
-}
-
fn build_queue_success_body(
endpoint: &str,
model: &str,
@@ -1217,26 +1203,29 @@ fn build_queue_success_body(
if use_msgpack {
// Msgpack: build {"model": ..., "items"|"scores": [raw_blobs...]}
- // at byte level. Partial per-item failures are deliberately omitted
- // from 200 bodies to keep parity with the Python server envelope.
- let result_blobs: Vec<Vec<u8>> = successful
+ // at byte level. The worker already produced msgpack bytes, so the
+ // success path trusts and appends them directly instead of decoding and
+ // cloning every blob. JSON responses still decode defensively below.
+ let payload_len = successful
.iter()
- .map(|r| validated_msgpack_result_blob(r))
- .collect();
+ .map(|r| r.result_msgpack.len())
+ .sum::<usize>();
let mut packer = rmp::encode::buffer::ByteBuf::new();
rmp::encode::write_map_len(&mut packer, 2).unwrap();
rmp::encode::write_str(&mut packer, "model").unwrap();
rmp::encode::write_str(&mut packer, model).unwrap();
rmp::encode::write_str(&mut packer, content_key).unwrap();
- if endpoint == "score" && result_blobs.len() == 1 {
+ if endpoint == "score" && successful.len() == 1 {
let mut parts = packer.into_vec();
- parts.extend_from_slice(&result_blobs[0]);
+ parts.reserve(payload_len);
+ parts.extend_from_slice(&successful[0].result_msgpack);
parts
} else {
- rmp::encode::write_array_len(&mut packer, result_blobs.len() as u32).unwrap();
+ rmp::encode::write_array_len(&mut packer, successful.len() as u32).unwrap();
let mut parts = packer.into_vec();
- for blob in &result_blobs {
- parts.extend_from_slice(blob);
+ parts.reserve(payload_len);
+ for result in successful {
+ parts.extend_from_slice(&result.result_msgpack);
}
parts
}
@@ -2662,28 +2651,21 @@ mod tests {
}
#[test]
- fn test_queue_success_body_msgpack_preserves_decode_failure_item() {
+ fn test_queue_success_body_msgpack_trusts_worker_item_bytes() {
let bad = _ok_result(0, vec![0xc1]);
let body = build_queue_success_body("encode", "model-a", &[&bad], true);
- let parsed: serde_json::Value = rmp_serde::from_slice(&body).unwrap();
- assert_eq!(parsed["model"], "model-a");
- let items = parsed["items"].as_array().unwrap();
- assert_eq!(items.len(), 1);
- assert_eq!(items[0]["item_index"], 0);
- assert_eq!(items[0]["work_item_id"], "req.0");
- assert_eq!(items[0]["error"]["code"], "RESULT_DECODE_FAILED");
+ assert!(rmp_serde::from_slice::<serde_json::Value>(&body).is_err());
+ assert_eq!(body.last().copied(), Some(0xc1));
}
#[test]
- fn test_queue_success_body_score_msgpack_replaces_bad_single_payload() {
+ fn test_queue_success_body_score_msgpack_trusts_worker_item_bytes() {
let bad = _ok_result(0, vec![0xc1]);
let body = build_queue_success_body("score", "model-a", &[&bad], true);
- let parsed: serde_json::Value = rmp_serde::from_slice(&body).unwrap();
- assert_eq!(parsed["model"], "model-a");
- assert_eq!(parsed["scores"]["item_index"], 0);
- assert_eq!(parsed["scores"]["error"]["code"], "RESULT_DECODE_FAILED");
+ assert!(rmp_serde::from_slice::<serde_json::Value>(&body).is_err());
+ assert_eq!(body.last().copied(), Some(0xc1));
}
#[test]
@@ -3595,16 +3577,33 @@ mod tests {
assert!(!out.exact_gpu_match);
}
+ #[tokio::test]
+ async fn test_resolve_effective_pool_ignores_isolated_pool_when_unpinned() {
+ // Bare `gpu` traffic belongs to the default pool. A healthy
+ // worker in a caller-created isolation pool must not receive
+ // unpinned traffic just because it matches `(bundle, gpu)`.
+ let reg = pool_registry();
+ reg.update_worker(
+ "http://w1:8080",
+ worker_msg("default", "l4-spot", "eval-l4"),
+ )
+ .await;
+
+ let out = resolve_effective_pool(&reg, "default", "l4-spot", "").await;
+ assert_eq!(out.resolution, PoolResolution::Provisioning);
+ assert!(!out.exact_gpu_match);
+ }
+
#[tokio::test]
async fn test_resolve_effective_pool_bundle_only_fallback_when_gpu_mismatch() {
// Client pinned `l4` but the cluster only has an `a100` worker on
// the same bundle. We still route (the profile distinction is
// cosmetic here) rather than forcing a scale-up.
let reg = pool_registry();
- reg.update_worker("http://w1:8080", worker_msg("default", "a100", "pool-a"))
+ reg.update_worker("http://w1:8080", worker_msg("default", "a100", "default"))
.await;
let out = resolve_effective_pool(&reg, "default", "l4", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("pool-a".to_string()));
+ assert_eq!(out.resolution, PoolResolution::Pool("default".to_string()));
// Exact tuple (default, l4) had no worker — even though we
// still routed via the bundle-only fallback, the caller must
// record demand so KEDA scales up the l4 pool.
@@ -3616,10 +3615,13 @@ mod tests {
// Common default-routing flow: no GPU header, one worker on the
// requested bundle → route to its pool directly (no 202).
let reg = pool_registry();
- reg.update_worker("http://w1:8080", worker_msg("default", "l4-spot", "pool-a"))
- .await;
+ reg.update_worker(
+ "http://w1:8080",
+ worker_msg("default", "l4-spot", "default"),
+ )
+ .await;
let out = resolve_effective_pool(&reg, "default", "", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("pool-a".to_string()));
+ assert_eq!(out.resolution, PoolResolution::Pool("default".to_string()));
// No GPU preference → no demand tracking applicable.
assert!(!out.exact_gpu_match);
}
@@ -3629,10 +3631,13 @@ mod tests {
// Exact (bundle, gpu) worker exists → `exact_gpu_match` is
// `true` and the caller skips the demand-tracking write.
let reg = pool_registry();
- reg.update_worker("http://w1:8080", worker_msg("default", "l4-spot", "pool-a"))
- .await;
+ reg.update_worker(
+ "http://w1:8080",
+ worker_msg("default", "l4-spot", "default"),
+ )
+ .await;
let out = resolve_effective_pool(&reg, "default", "l4-spot", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("pool-a".to_string()));
+ assert_eq!(out.resolution, PoolResolution::Pool("default".to_string()));
assert!(out.exact_gpu_match);
}
diff --git a/packages/sie_gateway/src/metrics.rs b/packages/sie_gateway/src/metrics.rs
index 21f924d8b..7c6e9ccb7 100644
--- a/packages/sie_gateway/src/metrics.rs
+++ b/packages/sie_gateway/src/metrics.rs
@@ -484,11 +484,11 @@ pub fn record_rejected_request(machine_profile: &str, bundle: &str, reason: &str
.inc();
}
-/// Clear PENDING_DEMAND for GPU types that now have healthy workers.
+/// Clear PENDING_DEMAND for WorkerGroups that now have healthy workers.
/// Called when worker metrics are updated to cancel stale demand signals.
/// Uses the DemandTracker to properly cancel expiry timers when clearing.
pub fn clear_fulfilled_demand(
- healthy_gpu_types: &std::collections::HashSet<String>,
+ healthy_worker_groups: &std::collections::HashSet<(String, String)>,
demand_tracker: &crate::state::demand_tracker::DemandTracker,
) {
// Gather current demand label pairs from the metric
@@ -504,8 +504,8 @@ pub fn clear_fulfilled_demand(
.map(|l| (l.get_name(), l.get_value()))
.collect();
if let Some(&gpu) = labels.get("machine_profile") {
- if healthy_gpu_types.contains(&gpu.to_lowercase()) {
- let bundle = labels.get("bundle").copied().unwrap_or("default");
+ let bundle = labels.get("bundle").copied().unwrap_or("default");
+ if healthy_worker_groups.contains(&(gpu.to_lowercase(), bundle.to_lowercase())) {
let current = PENDING_DEMAND.with_label_values(&[gpu, bundle]).get();
if current > 0.0 {
demand_tracker.clear(gpu, bundle);
@@ -849,11 +849,11 @@ mod tests {
.with_label_values(&["l4-spot", "default"])
.set(1.0);
- // Healthy workers include l4-spot
- let mut gpus = std::collections::HashSet::new();
- gpus.insert("l4-spot".to_string());
+ // Healthy workers include l4-spot/default.
+ let mut worker_groups = std::collections::HashSet::new();
+ worker_groups.insert(("l4-spot".to_string(), "default".to_string()));
- clear_fulfilled_demand(&gpus, &tracker);
+ clear_fulfilled_demand(&worker_groups, &tracker);
let val = PENDING_DEMAND
.with_label_values(&["l4-spot", "default"])
@@ -874,17 +874,49 @@ mod tests {
.with_label_values(&["h100", "default"])
.set(1.0);
- // Only l4-spot is healthy
- let mut gpus = std::collections::HashSet::new();
- gpus.insert("l4-spot".to_string());
+ // Only l4-spot/default is healthy.
+ let mut worker_groups = std::collections::HashSet::new();
+ worker_groups.insert(("l4-spot".to_string(), "default".to_string()));
- clear_fulfilled_demand(&gpus, &tracker);
+ clear_fulfilled_demand(&worker_groups, &tracker);
// h100 demand should remain
let val = PENDING_DEMAND.with_label_values(&["h100", "default"]).get();
assert!((val - 1.0).abs() < f64::EPSILON);
}
+ #[test]
+ fn test_clear_fulfilled_demand_preserves_different_bundle() {
+ let _guard = METRICS_TEST_LOCK.lock().unwrap();
+ let _ = &*REGISTRY;
+ reset_test_metrics();
+
+ let tracker = crate::state::demand_tracker::DemandTracker::new();
+
+ // Same machine profile has demand in two bundles.
+ PENDING_DEMAND
+ .with_label_values(&["l4-spot", "default"])
+ .set(1.0);
+ PENDING_DEMAND
+ .with_label_values(&["l4-spot", "sglang"])
+ .set(1.0);
+
+ // A healthy default worker must not clear sglang demand.
+ let mut worker_groups = std::collections::HashSet::new();
+ worker_groups.insert(("l4-spot".to_string(), "default".to_string()));
+
+ clear_fulfilled_demand(&worker_groups, &tracker);
+
+ let default_val = PENDING_DEMAND
+ .with_label_values(&["l4-spot", "default"])
+ .get();
+ let sglang_val = PENDING_DEMAND
+ .with_label_values(&["l4-spot", "sglang"])
+ .get();
+ assert!((default_val - 0.0).abs() < f64::EPSILON);
+ assert!((sglang_val - 1.0).abs() < f64::EPSILON);
+ }
+
// ------------------------------------------------------------------
// Direct emission tests for the 5 metrics added in the audit pass.
//
diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rs
index 514744b55..531845ffc 100644
--- a/packages/sie_gateway/src/queue/publisher.rs
+++ b/packages/sie_gateway/src/queue/publisher.rs
@@ -277,10 +277,12 @@ fn extract_request_id_fast(payload: &[u8]) -> Option<&str> {
let marker = rmp::decode::read_marker(&mut &payload[..]).ok()?;
match marker {
- // Array format: request_id is the first element
- Marker::FixArray(n) if n >= 1 => {
+ // Array format follows WorkResult field order:
+ // work_item_id, request_id, item_index, ...
+ Marker::FixArray(n) if n >= 2 => {
// Marker byte consumed 1 byte
- let (request_id, _) = read_str_from_slice(&payload[1..]).ok()?;
+ let data = skip_msgpack_value(&payload[1..])?;
+ let (request_id, _) = read_str_from_slice(data).ok()?;
Some(request_id)
}
Marker::Array16 => {
@@ -289,10 +291,11 @@ fn extract_request_id_fast(payload: &[u8]) -> Option<&str> {
return None;
}
let len = u16::from_be_bytes([payload[1], payload[2]]);
- if len < 1 {
+ if len < 2 {
return None;
}
- let (request_id, _) = read_str_from_slice(&payload[3..]).ok()?;
+ let data = skip_msgpack_value(&payload[3..])?;
+ let (request_id, _) = read_str_from_slice(data).ok()?;
Some(request_id)
}
Marker::Array32 => {
@@ -301,10 +304,11 @@ fn extract_request_id_fast(payload: &[u8]) -> Option<&str> {
return None;
}
let len = u32::from_be_bytes([payload[1], payload[2], payload[3], payload[4]]);
- if len < 1 {
+ if len < 2 {
return None;
}
- let (request_id, _) = read_str_from_slice(&payload[5..]).ok()?;
+ let data = skip_msgpack_value(&payload[5..])?;
+ let (request_id, _) = read_str_from_slice(data).ok()?;
Some(request_id)
}
@@ -1475,7 +1479,7 @@ mod tests {
};
let encoded = rmp_serde::to_vec(&result).unwrap();
let extracted = extract_request_id_fast(&encoded);
- assert_eq!(extracted, Some("abc-123-def.0"));
+ assert_eq!(extracted, Some("abc-123-def"));
}
#[test]
@@ -1538,8 +1542,7 @@ mod tests {
};
let encoded = rmp_serde::to_vec(&result).unwrap();
let extracted = extract_request_id_fast(&encoded);
- // First field in array format is work_item_id
- assert!(extracted.is_some());
+ assert_eq!(extracted, Some(uuid_str));
}
#[test]
diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rs
index 189ee1e7e..bf0583b3a 100644
--- a/packages/sie_gateway/src/server.rs
+++ b/packages/sie_gateway/src/server.rs
@@ -114,13 +114,20 @@ pub(crate) async fn metrics_handler(
.collect();
metrics::update_worker_metrics(&snapshots);
- // Clear PENDING_DEMAND for GPUs that now have healthy workers
- let healthy_gpus: std::collections::HashSet<String> = snapshots
+ // Clear PENDING_DEMAND only for WorkerGroups that now have healthy workers.
+ let healthy_worker_groups: std::collections::HashSet<(String, String)> = snapshots
.iter()
.filter(|w| w.healthy && !w.machine_profile.is_empty())
- .map(|w| w.machine_profile.to_lowercase())
+ .map(|w| {
+ let bundle = if w.bundle.is_empty() {
+ "default"
+ } else {
+ w.bundle.as_str()
+ };
+ (w.machine_profile.to_lowercase(), bundle.to_lowercase())
+ })
.collect();
- metrics::clear_fulfilled_demand(&healthy_gpus, &state.demand_tracker);
+ metrics::clear_fulfilled_demand(&healthy_worker_groups, &state.demand_tracker);
let model_workers = state.registry.get_models().await;
let model_counts: std::collections::HashMap<String, usize> = model_workers
diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rs
index d87564a0c..acf48f4bc 100644
--- a/packages/sie_gateway/src/state/worker_registry.rs
+++ b/packages/sie_gateway/src/state/worker_registry.rs
@@ -205,6 +205,25 @@ impl WorkerRegistry {
/// Resolve the NATS pool name for queue mode routing.
/// Finds a healthy worker matching the bundle (and optionally GPU) that has a pool_name set.
pub async fn resolve_queue_pool(&self, bundle: &str, gpu: &str) -> Option<String> {
+ self.resolve_queue_pool_matching(bundle, gpu, None)
+ }
+
+ /// Resolve the NATS pool name, constrained to a specific logical pool.
+ pub async fn resolve_queue_pool_in_pool(
+ &self,
+ bundle: &str,
+ gpu: &str,
+ pool_name: &str,
+ ) -> Option<String> {
+ self.resolve_queue_pool_matching(bundle, gpu, Some(pool_name))
+ }
+
+ fn resolve_queue_pool_matching(
+ &self,
+ bundle: &str,
+ gpu: &str,
+ pool_name: Option<&str>,
+ ) -> Option<String> {
let snap = self.snapshot.load();
// `by_bundle` is keyed with `w.bundle.to_lowercase()` in
@@ -225,6 +244,11 @@ impl WorkerRegistry {
if w.pool_name.is_empty() {
continue;
}
+ if let Some(pool_name) = pool_name {
+ if !w.pool_name.eq_ignore_ascii_case(pool_name) {
+ continue;
+ }
+ }
if !gpu.is_empty() && !w.machine_profile.eq_ignore_ascii_case(gpu) {
continue;
}
@@ -770,6 +794,34 @@ mod tests {
assert_eq!(pool, Some("pool-a".to_string()));
}
+ #[tokio::test]
+ async fn test_resolve_queue_pool_in_pool_filters_pool_name() {
+ let reg = registry();
+
+ let mut default_msg = make_msg(true);
+ default_msg.pool_name = "default".into();
+ default_msg.bundle = "default".into();
+ default_msg.machine_profile = "l4-spot".into();
+ reg.update_worker("http://w1:8080", default_msg).await;
+
+ let mut isolated_msg = make_msg(true);
+ isolated_msg.name = "worker-2".into();
+ isolated_msg.pool_name = "eval-l4".into();
+ isolated_msg.bundle = "default".into();
+ isolated_msg.machine_profile = "l4-spot".into();
+ reg.update_worker("http://w2:8080", isolated_msg).await;
+
+ let pool = reg
+ .resolve_queue_pool_in_pool("default", "l4-spot", "eval-l4")
+ .await;
+ assert_eq!(pool, Some("eval-l4".to_string()));
+
+ let missing = reg
+ .resolve_queue_pool_in_pool("default", "l4-spot", "missing")
+ .await;
+ assert!(missing.is_none());
+ }
+
#[tokio::test]
async fn test_resolve_queue_pool_bundle_only() {
let reg = registry();
diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.toml
index 8e3102932..ca474311f 100644
--- a/packages/sie_sdk/pyproject.toml
+++ b/packages/sie_sdk/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-sdk"
-version = "0.3.2"
+version = "0.3.3"
description = "Search Inference Engine - Python SDK"
requires-python = ">=3.12,<3.13"
license = { text = "Apache-2.0" }
diff --git a/packages/sie_server/Dockerfile.cpu b/packages/sie_server/Dockerfile.cpu
index 1533efa97..43297f914 100644
--- a/packages/sie_server/Dockerfile.cpu
+++ b/packages/sie_server/Dockerfile.cpu
@@ -18,14 +18,15 @@ ENV DEBIAN_FRONTEND=noninteractive \
UV_LINK_MODE=copy \
PIP_DISABLE_PIP_VERSION_CHECK=1
-# build-essential + git are builder-only; they do NOT leak into the runtime stage.
+# build-essential + git + zlib1g-dev are builder-only; they do NOT leak into the runtime stage.
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
apt-get update && apt-get install -y --no-install-recommends \
build-essential \
ca-certificates \
curl \
- git
+ git \
+ zlib1g-dev
ARG UV_VERSION=0.9.28
RUN curl -LsSf https://astral.sh/uv/${UV_VERSION}/install.sh | sh \
@@ -154,13 +155,16 @@ ENV DEBIAN_FRONTEND=noninteractive \
OMP_NUM_THREADS=4 \
MKL_NUM_THREADS=4
-# Only the shared libs torch + pillow actually dlopen at runtime.
+# Only the shared libs torch + pillow + rtree actually dlopen at runtime.
+# libspatialindex-c6: rtree (docling dep) dlopens libspatialindex_c.so; the
+# rtree==1.4.1 wheel only bundles the C++ core, not the C wrapper.
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
apt-get update && apt-get install -y --no-install-recommends \
libgomp1 \
libjpeg62-turbo \
- libpng16-16
+ libpng16-16 \
+ libspatialindex-c6
RUN groupadd -g 1000 sie && useradd -u 1000 -g sie -m sie
diff --git a/packages/sie_server/Dockerfile.cuda11 b/packages/sie_server/Dockerfile.cuda11
index 3d4accf74..047860d6c 100644
--- a/packages/sie_server/Dockerfile.cuda11
+++ b/packages/sie_server/Dockerfile.cuda11
@@ -152,6 +152,8 @@ FROM nvidia/cuda:11.8.0-base-ubuntu22.04 AS runtime
ENV DEBIAN_FRONTEND=noninteractive
+# libspatialindex-c6: rtree (docling dep) dlopens libspatialindex_c.so; the
+# rtree==1.4.1 wheel only bundles the C++ core, not the C wrapper.
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
apt-get update && apt-get install -y --no-install-recommends \
@@ -159,7 +161,8 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
gcc \
libc6-dev \
libgomp1 \
- libnuma1
+ libnuma1 \
+ libspatialindex-c6
RUN groupadd -g 1000 sie && useradd -u 1000 -g sie -m sie
diff --git a/packages/sie_server/Dockerfile.cuda12 b/packages/sie_server/Dockerfile.cuda12
index 6ee4e83c5..791d3a94f 100644
--- a/packages/sie_server/Dockerfile.cuda12
+++ b/packages/sie_server/Dockerfile.cuda12
@@ -173,6 +173,8 @@ ENV DEBIAN_FRONTEND=noninteractive
# libnuma1: required by sgl_kernel (SGLang bundle); import fails with a
# misleading SM-arch error without it.
# libgomp1: torch OpenMP runtime.
+# libspatialindex-c6: rtree (docling dep) dlopens libspatialindex_c.so; the
+# rtree==1.4.1 wheel only bundles the C++ core, not the C wrapper.
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
apt-get update && apt-get install -y --no-install-recommends \
@@ -180,7 +182,8 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
gcc \
libc6-dev \
libgomp1 \
- libnuma1
+ libnuma1 \
+ libspatialindex-c6
RUN groupadd -g 1000 sie && useradd -u 1000 -g sie -m sie
diff --git a/packages/sie_server/bundles/default.yaml b/packages/sie_server/bundles/default.yaml
index ff8914973..504178e22 100644
--- a/packages/sie_server/bundles/default.yaml
+++ b/packages/sie_server/bundles/default.yaml
@@ -12,6 +12,7 @@ adapters:
- sie_server.adapters.colbert_rotary_flash
- sie_server.adapters.colpali
- sie_server.adapters.colqwen2
+- sie_server.adapters.colqwen3
- sie_server.adapters.grounding_dino
- sie_server.adapters.gte_sparse_flash
- sie_server.adapters.jina_flash_cross_encoder
@@ -44,7 +45,7 @@ adapters:
- sie_server.adapters.paddleocr_vl
deps:
# Most flash adapters; sentence_transformer needs >=4.57
- transformers: '>=4.57'
+ transformers: '>=4.57,<5'
# Pin torch — flash-attn's unpinned torch dep can pull in 2.10+ which breaks torchvision
torch: '>=2.9,<2.10'
# bge_m3, bge_m3_flash, nemo_colembed, nomic_flash, xlm_roberta_flash
@@ -56,7 +57,7 @@ deps:
# bge_m3_flag
FlagEmbedding: '>=1.3'
# grounding_dino
- pillow: ''
+ pillow: '>=11,<12'
# grounding_dino
requests: ''
# gliner, gliner_bi
diff --git a/packages/sie_server/bundles/transformers5.yaml b/packages/sie_server/bundles/transformers5.yaml
index a5928c926..c1ba180ff 100644
--- a/packages/sie_server/bundles/transformers5.yaml
+++ b/packages/sie_server/bundles/transformers5.yaml
@@ -13,5 +13,8 @@ deps:
transformers: '>=5.0'
# Pin torch — flash-attn's unpinned torch dep can pull in 2.10+ which breaks torchvision
torch: '>=2.9,<2.10'
- huggingface-hub: '>=0.20'
+ # No huggingface-hub override: transformers 5.x's own metadata
+ # pins it to >=1.3,<2.0. An override here was previously
+ # unsatisfiable against that pin and broke `uv run` resolution.
+ # Let transformers drive the version.
pillow: ''
diff --git a/packages/sie_server/models/nvidia__llama-embed-nemotron-8b.yaml b/packages/sie_server/models/nvidia__llama-embed-nemotron-8b.yaml
index f7ab67504..71a0168bf 100644
--- a/packages/sie_server/models/nvidia__llama-embed-nemotron-8b.yaml
+++ b/packages/sie_server/models/nvidia__llama-embed-nemotron-8b.yaml
@@ -18,10 +18,19 @@ profiles:
default:
max_batch_tokens: 8192
compute_precision: bfloat16
- adapter_path: sie_server.adapters.sglang:SGLangEmbeddingAdapter
+ # Was sie_server.adapters.sglang:SGLangEmbeddingAdapter, but
+ # SGLang's generic transformers fallback hits
+ # `assert get_embedding is False` for this Llama-based arch
+ # (no model-specific embedding implementation registered). Route
+ # through PyTorchEmbeddingAdapter like NV-Embed-v2 (also Llama-
+ # based 7B+ embedder); the heavy lane has 96 GiB so non-paged
+ # attention is fine. May be reconciled with a colleague's
+ # in-flight SGLang/arch fix later.
+ adapter_path: sie_server.adapters.pytorch_embedding:PyTorchEmbeddingAdapter
adapter_options:
loadtime:
- mem_fraction_static: 0.85
+ trust_remote_code: true
+ attn_implementation: eager
runtime:
pooling: last_token
normalize: true
diff --git a/packages/sie_server/models/nvidia__nemotron-colembed-vl-4b-v2.yaml b/packages/sie_server/models/nvidia__nemotron-colembed-vl-4b-v2.yaml
new file mode 100644
index 000000000..eb686405a
--- /dev/null
+++ b/packages/sie_server/models/nvidia__nemotron-colembed-vl-4b-v2.yaml
@@ -0,0 +1,43 @@
+sie_id: nvidia/nemotron-colembed-vl-4b-v2
+hf_id: nvidia/nemotron-colembed-vl-4b-v2
+inputs:
+ text: true
+ image: true
+ audio: false
+ video: false
+tasks:
+ encode:
+ dense: null
+ sparse: null
+ multivector:
+ dim: 2560
+ score: null
+ extract: null
+max_sequence_length: 8192
+profiles:
+ default:
+ max_batch_tokens: 4096
+ compute_precision: bfloat16
+ adapter_path: sie_server.adapters.nemo_colembed:NemoColEmbedAdapter
+ adapter_options:
+ loadtime:
+ muvera_config:
+ num_repetitions: 40
+ num_simhash_projections: 6
+ projection_dim: null
+ final_projection_dim: 10240
+ token_dim: 2560
+ runtime:
+ normalize: true
+ batch_size: 4
+ muvera:
+ extends: default
+ adapter_options:
+ runtime:
+ normalize: true
+ batch_size: 4
+ output_types:
+ - dense
+ output_similarity:
+ dense: dot
+ muvera: {}
diff --git a/packages/sie_server/models/tomoroai__tomoro-colqwen3-embed-4b.yaml b/packages/sie_server/models/tomoroai__tomoro-colqwen3-embed-4b.yaml
new file mode 100644
index 000000000..c70287867
--- /dev/null
+++ b/packages/sie_server/models/tomoroai__tomoro-colqwen3-embed-4b.yaml
@@ -0,0 +1,42 @@
+sie_id: TomoroAI/tomoro-colqwen3-embed-4b
+hf_id: TomoroAI/tomoro-colqwen3-embed-4b
+inputs:
+ text: true
+ image: true
+ audio: false
+ video: false
+tasks:
+ encode:
+ dense: null
+ sparse: null
+ multivector:
+ dim: 320
+ score: null
+ extract: null
+max_sequence_length: 8192
+profiles:
+ default:
+ max_batch_tokens: 4096
+ compute_precision: bfloat16
+ adapter_path: sie_server.adapters.colqwen3:ColQwen3Adapter
+ adapter_options:
+ loadtime:
+ muvera_config:
+ num_repetitions: 40
+ num_simhash_projections: 6
+ projection_dim: null
+ final_projection_dim: 10240
+ token_dim: 320
+ trust_remote_code: true
+ runtime:
+ normalize: true
+ muvera:
+ extends: default
+ adapter_options:
+ runtime:
+ normalize: true
+ output_types:
+ - dense
+ output_similarity:
+ dense: dot
+ muvera: {}
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index a59f5b11a..74f39a132 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.3.2"
+ "version": "0.3.3"
},
"paths": {
"/": {
@@ -1740,7 +1740,7 @@
}
],
"default": null,
- "description": "Adapter-specific options",
+ "description": "Adapter-specific options. Recognized sub-keys include 'overflow_policy' (one of 'default', 'truncate_text', 'error'; default 'default') controlling how inputs exceeding the model's max_sequence_length are handled.",
"title": "Options"
}
},
@@ -1763,6 +1763,23 @@
"location"
]
}
+ },
+ {
+ "items": [
+ {
+ "text": "Apple Inc. was founded by Steve Jobs in Cupertino, California."
+ }
+ ],
+ "params": {
+ "labels": [
+ "person",
+ "organization",
+ "location"
+ ],
+ "options": {
+ "overflow_policy": "truncate_text"
+ }
+ }
}
],
"properties": {
diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.toml
index b0a395f3c..5ff0685ea 100644
--- a/packages/sie_server/pyproject.toml
+++ b/packages/sie_server/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-server"
-version = "0.3.2"
+version = "0.3.3"
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/adapters/colqwen3/__init__.py b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py
new file mode 100644
index 000000000..419171f65
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py
@@ -0,0 +1,337 @@
+from __future__ import annotations
+
+import io
+import logging
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+import numpy as np
+import torch
+from torch.nn import functional as F
+
+from sie_server.adapters._base_adapter import BaseAdapter
+from sie_server.adapters._spec import AdapterSpec
+from sie_server.adapters._types import ComputePrecision
+from sie_server.core.inference_output import EncodeOutput
+
+if TYPE_CHECKING:
+ from PIL import Image as PILImage
+
+ from sie_server.types.inputs import Item
+
+logger = logging.getLogger(__name__)
+
+_ERR_NO_INPUT = "ColQwen3Adapter requires either text or images input"
+
+
+class ColQwen3Adapter(BaseAdapter):
+ """Adapter for ColQwen3-style visual document retrieval models.
+
+ ColQwen3 encodes document page images into multi-vector representations
+ (320-dim per token) for late interaction retrieval. Built on Qwen3-VL,
+ with a custom projection layer wrapper that exposes ``out.embeddings``.
+
+ Target model: ``TomoroAI/tomoro-colqwen3-embed-4b`` (4B params).
+
+ Loaded via ``AutoModel`` + ``AutoProcessor`` with ``trust_remote_code``
+ because the model ships its own ``ColQwen3`` / ``ColQwen3Processor``
+ classes (not in native transformers).
+ """
+
+ spec = AdapterSpec(
+ inputs=("text", "image"),
+ outputs=("multivector", "score"),
+ multivector_dim=320,
+ unload_fields=("_model", "_processor"),
+ default_preprocessor="image",
+ )
+
+ def __init__(
+ self,
+ model_name_or_path: str | Path,
+ *,
+ normalize: bool = True,
+ compute_precision: ComputePrecision = "bfloat16",
+ trust_remote_code: bool = True,
+ max_seq_length: int | None = None,
+ muvera_config: dict[str, Any] | None = None,
+ token_dim: int = 320,
+ max_num_visual_tokens: int = 1280,
+ ) -> None:
+ """Initialize the adapter.
+
+ Args:
+ model_name_or_path: HuggingFace model ID or local path.
+ normalize: Whether to L2-normalize embeddings (the model's wrapper
+ already normalizes; kept for interface parity).
+ compute_precision: Compute precision for inference.
+ trust_remote_code: Required for ColQwen3 (custom processor + model classes).
+ max_seq_length: Ignored — ColQwen3 uses dynamic sequence length.
+ muvera_config: Optional MUVERA configuration (passed to postprocessor).
+ token_dim: Per-token embedding dimension (320 for ColQwen3).
+ max_num_visual_tokens: Cap on visual tokens per image (passed to processor).
+ """
+ self._model_name_or_path = str(model_name_or_path)
+ self._normalize = normalize
+ self._compute_precision = compute_precision
+ self._trust_remote_code = trust_remote_code
+ self._max_num_visual_tokens = max_num_visual_tokens
+
+ self._model: Any = None
+ self._processor: Any = None
+ self._device: str | None = None
+ self._multivector_dim: int = token_dim
+
+ def load(self, device: str) -> None:
+ """Load processor + model onto the specified device."""
+ from transformers import AutoModel, AutoProcessor
+
+ self._device = device
+
+ dtype = self._resolve_dtype()
+ attn_impl = self._resolve_attn_implementation(device)
+
+ logger.info(
+ "Loading ColQwen3 model %s on device=%s with dtype=%s, attn=%s",
+ self._model_name_or_path,
+ device,
+ dtype,
+ attn_impl,
+ )
+
+ self._processor = AutoProcessor.from_pretrained(
+ self._model_name_or_path,
+ trust_remote_code=self._trust_remote_code,
+ max_num_visual_tokens=self._max_num_visual_tokens,
+ )
+
+ load_kwargs: dict[str, Any] = {
+ "trust_remote_code": self._trust_remote_code,
+ "device_map": device,
+ "dtype": dtype,
+ }
+ if attn_impl is not None:
+ load_kwargs["attn_implementation"] = attn_impl
+
+ self._model = AutoModel.from_pretrained(
+ self._model_name_or_path,
+ **load_kwargs,
+ ).eval()
+
+ # Discover token dim from the projection layer when present.
+ proj = getattr(self._model, "embedding_proj_layer", None)
+ out_features = getattr(proj, "out_features", None)
+ if isinstance(out_features, int) and out_features > 0:
+ self._multivector_dim = out_features
+
+ def _resolve_dtype(self) -> torch.dtype:
+ if not self._device or not str(self._device).startswith("cuda"):
+ return torch.float32
+ dtype_map = {
+ "float16": torch.float16,
+ "bfloat16": torch.bfloat16,
+ "float32": torch.float32,
+ }
+ return dtype_map.get(self._compute_precision, torch.bfloat16)
+
+ def _resolve_attn_implementation(self, device: str) -> str | None:
+ if not device.startswith("cuda"):
+ return None
+ try:
+ import flash_attn # ty: ignore[unresolved-import]
+
+ return "flash_attention_2"
+ except ImportError:
+ logger.info("flash_attn not available, using sdpa attention")
+ return "sdpa"
+
+ # ------------------------------------------------------------------
+ # Encode
+ # ------------------------------------------------------------------
+
+ def encode(
+ self,
+ items: list[Item],
+ output_types: list[str],
+ *,
+ instruction: str | None = None,
+ is_query: bool = False,
+ prepared_items: Any = None,
+ options: dict[str, Any] | None = None,
+ ) -> EncodeOutput:
+ self._check_loaded()
+ self._validate_output_types(output_types)
+
+ if is_query:
+ multivector_list: list[np.ndarray] = []
+ for item in items:
+ if item.text is None:
+ raise ValueError(_ERR_NO_INPUT)
+ multivector_list.append(self._encode_text(item.text))
+ return EncodeOutput(
+ multivector=multivector_list,
+ batch_size=len(items),
+ is_query=is_query,
+ multivector_token_dim=self._multivector_dim,
+ )
+
+ # Preallocate by index so output order matches input order regardless of
+ # text/image mix, and so multi-image items collapse to one multivector.
+ results: list[np.ndarray | None] = [None] * len(items)
+ all_images: list[PILImage.Image] = []
+ image_slots: list[tuple[int, int]] = [] # (item_idx, image_count)
+ for idx, item in enumerate(items):
+ has_images = item.images is not None and len(item.images) > 0
+ if has_images:
+ images = self._load_images(item)
+ all_images.extend(images)
+ image_slots.append((idx, len(images)))
+ elif item.text is not None:
+ results[idx] = self._encode_text(item.text)
+ else:
+ raise ValueError(_ERR_NO_INPUT)
+
+ if all_images:
+ per_image_mvs = self._encode_images(all_images)
+ cursor = 0
+ for idx, count in image_slots:
+ segment = per_image_mvs[cursor : cursor + count]
+ cursor += count
+ results[idx] = segment[0] if count == 1 else np.concatenate(segment, axis=0)
+
+ multivector_list = [mv for mv in results if mv is not None]
+ assert len(multivector_list) == len(items)
+
+ return EncodeOutput(
+ multivector=multivector_list,
+ batch_size=len(items),
+ is_query=is_query,
+ multivector_token_dim=self._multivector_dim,
+ )
+
+ # ------------------------------------------------------------------
+ # Image encoding
+ # ------------------------------------------------------------------
+
+ def _load_images(self, item: Any) -> list[PILImage.Image]:
+ from PIL import Image
+
+ pil_images: list[PILImage.Image] = []
+ for img_input in item.images or []:
+ pil_img = Image.open(io.BytesIO(img_input["data"]))
+ if pil_img.mode != "RGB":
+ pil_img = pil_img.convert("RGB")
+ pil_images.append(pil_img)
+ return pil_images
+
+ def _encode_images(self, images: list[PILImage.Image]) -> list[np.ndarray]:
+ """Encode a batch of images and return per-image multi-vectors."""
+ assert self._model is not None
+ assert self._processor is not None
+
+ inputs = self._processor(
+ images=images,
+ return_tensors="pt",
+ padding="longest",
+ )
+ inputs = {k: v.to(self._device) for k, v in inputs.items() if hasattr(v, "to")}
+
+ with torch.inference_mode():
+ outputs = self._model(**inputs)
+
+ # ColQwen3 returns a ModelOutput-like object with ``.embeddings``
+ # of shape (batch, seq, token_dim). The wrapper already L2-normalizes
+ # and applies attention-masking; our ``self._normalize`` is a no-op
+ # safety belt for downstream parity.
+ embeddings = outputs.embeddings
+ if self._normalize:
+ embeddings = F.normalize(embeddings, p=2, dim=-1)
+
+ results: list[np.ndarray] = [embeddings[i].float().cpu().numpy() for i in range(embeddings.shape[0])]
+
+ # Free GPU memory between batches to prevent OOM on subsequent calls
+ # (L4 22GB GPUs are tight for VLM models).
+ del outputs, embeddings, inputs
+ if self._device and self._device.startswith("cuda"):
+ torch.cuda.empty_cache()
+
+ return results
+
+ # ------------------------------------------------------------------
+ # Text encoding
+ # ------------------------------------------------------------------
+
+ def _encode_text(self, text: str) -> np.ndarray:
+ """Encode a single text query."""
+ assert self._model is not None
+ assert self._processor is not None
+
+ inputs = self._processor(
+ text=[text],
+ return_tensors="pt",
+ padding="longest",
+ )
+ inputs = {k: v.to(self._device) for k, v in inputs.items() if hasattr(v, "to")}
+
+ with torch.inference_mode():
+ outputs = self._model(**inputs)
+
+ embeddings = outputs.embeddings # (1, seq, token_dim)
+ if self._normalize:
+ embeddings = F.normalize(embeddings, p=2, dim=-1)
+
+ result = embeddings[0].float().cpu().numpy()
+
+ del outputs, embeddings, inputs
+ if self._device and self._device.startswith("cuda"):
+ torch.cuda.empty_cache()
+
+ return result
+
+ # ------------------------------------------------------------------
+ # Scoring
+ # ------------------------------------------------------------------
+
+ def score(
+ self,
+ query: Any,
+ items: list[Any],
+ *,
+ instruction: str | None = None,
+ options: dict[str, Any] | None = None,
+ ) -> list[float]:
+ """Score documents against a text query using MaxSim."""
+ self._check_loaded()
+
+ query_output = self.encode([query], output_types=["multivector"], is_query=True)
+ if query_output.multivector is None:
+ raise RuntimeError("Failed to encode query: no multivector output")
+ query_vecs = query_output.multivector[0]
+
+ doc_output = self.encode(items, output_types=["multivector"], is_query=False)
+ if doc_output.multivector is None:
+ raise RuntimeError("Failed to encode documents: no multivector output")
+
+ scores: list[float] = []
+ query_tensor = torch.from_numpy(query_vecs).to(self._device)
+ for doc_vecs in doc_output.multivector:
+ doc_tensor = torch.from_numpy(doc_vecs).to(self._device)
+ sim = torch.matmul(query_tensor, doc_tensor.T)
+ scores.append(sim.max(dim=-1).values.sum().item())
+ return scores
+
+ # ------------------------------------------------------------------
+ # Helpers
+ # ------------------------------------------------------------------
+
+ def _validate_output_types(self, output_types: list[str]) -> None:
+ unsupported = set(output_types) - {"multivector"}
+ if unsupported:
+ msg = f"Unsupported output types: {unsupported}. ColQwen3Adapter only supports 'multivector'."
+ raise ValueError(msg)
+
+ def get_preprocessor(self) -> Any | None:
+ # ColQwen3 uses a custom processor that handles both text and images
+ # internally via the ColQwen3Processor; the generic ImagePreprocessor
+ # does not match the (text-only / image-only) call pattern.
+ return None
diff --git a/packages/sie_server/src/sie_server/adapters/errors.py b/packages/sie_server/src/sie_server/adapters/errors.py
new file mode 100644
index 000000000..145dc1e00
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/errors.py
@@ -0,0 +1,2 @@
+class InputTooLongError(ValueError):
+ pass
diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
index 2f047a3a5..b2f8fc561 100644
--- a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
@@ -13,6 +13,7 @@ Performance note (Dec 2025):
from __future__ import annotations
+import re
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, Literal
@@ -21,11 +22,14 @@ import torch
from sie_server.adapters._base_adapter import BaseAdapter
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision
+from sie_server.adapters.errors import InputTooLongError
from sie_server.core.inference_output import ExtractOutput
+from sie_server.types.overflow_policy import DEFAULT_OVERFLOW_POLICY, OverflowPolicy
from sie_server.types.responses import Classification
if TYPE_CHECKING:
from gliclass import ZeroShotClassificationPipeline # ty:ignore[unresolved-import]
+ from transformers import PreTrainedTokenizerBase # ty:ignore[unresolved-import]
from sie_server.types.inputs import Item
@@ -35,7 +39,11 @@ _ERR_INPUT_TOO_LONG = (
"this typically indicates the input exceeds the model's max sequence length "
"even after truncation. Reduce input length or split into chunks."
)
-
+# Matches the torch IndexError shape "index N is out of bounds for dimension D
+# with size 0" emitted when gliclass indexes into an empty post-processing
+# tensor on overflowing inputs. ``\b`` anchors the size to a word boundary so a
+# hypothetical "with size 02" cannot falsely match.
+_INDEX_OOB_EMPTY_TENSOR_RE = re.compile(r"out of bounds for dimension \d+ with size 0\b")
ClassificationType = Literal["single-label", "multi-label"]
@@ -52,13 +60,9 @@ class GLiClassAdapter(BaseAdapter):
spec: ClassVar[AdapterSpec] = AdapterSpec(
inputs=("text",),
outputs=("json",),
- unload_fields=("_pipeline",),
+ unload_fields=("_pipeline", "_tokenizer"),
)
- def _check_loaded(self) -> None:
- if self._pipeline is None:
- raise RuntimeError(ERR_NOT_LOADED)
-
def __init__(
self,
model_name_or_path: str | Path,
@@ -91,6 +95,8 @@ class GLiClassAdapter(BaseAdapter):
self._compute_precision = compute_precision
self._pipeline: ZeroShotClassificationPipeline | None = None
+ self._tokenizer: PreTrainedTokenizerBase | None = None
+ self._special_count: int = 0
self._device: str | None = None
def load(self, device: str) -> None:
@@ -117,12 +123,12 @@ class GLiClassAdapter(BaseAdapter):
# Load model and tokenizer
model = GLiClassModel.from_pretrained(self._model_name_or_path)
model = model.to(device, dtype=torch_dtype)
- tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
# Bound the tokenizer's max length so any internal tokenization in the
# gliclass library auto-truncates to the model's actual capacity.
if self._max_seq_length is not None:
- tokenizer.model_max_length = self._max_seq_length
+ self._tokenizer.model_max_length = self._max_seq_length
# Create pipeline. Pass max_length explicitly so the pipeline's
# ``tokenizer(..., truncation=True, max_length=self.max_length)`` calls
@@ -132,32 +138,86 @@ class GLiClassAdapter(BaseAdapter):
# long inputs (see sie-test#88, sie-test#89).
pipeline_kwargs: dict[str, Any] = {
"model": model,
- "tokenizer": tokenizer,
+ "tokenizer": self._tokenizer,
"classification_type": self._classification_type,
"device": device,
}
if self._max_seq_length is not None:
pipeline_kwargs["max_length"] = self._max_seq_length
+ self._special_count = int(self._tokenizer.num_special_tokens_to_add(pair=False))
self._pipeline = ZeroShotClassificationPipeline(**pipeline_kwargs)
def _extract_text(self, item: Item) -> str:
- """Extract text from an item.
-
- Args:
- item: Input item with text field.
-
- Returns:
- Text string.
-
- Raises:
- ValueError: If item has no text.
- """
if not item.text:
msg = "Item must have text for classification"
raise ValueError(msg)
return item.text
+ def _apply_overflow_policy(
+ self,
+ texts: list[str],
+ labels: list[str],
+ policy: OverflowPolicy = DEFAULT_OVERFLOW_POLICY,
+ ) -> list[str]:
+ """Enforce overflow_policy by pre-tokenizing text and label_prompt separately.
+
+ At inference the gliclass pipeline tokenizes the fused string with
+ ``add_special_tokens=True``, so the model sees
+ ``observed = text_tokens + label_prompt_tokens + special_count``, where
+ ``special_count`` is the BERT-style ``[CLS]``/``[SEP]`` wrap (2 for all
+ current gliclass models). We recover the same total without running the
+ model by tokenizing each part with ``add_special_tokens=False``.
+
+ On overflow:
+ - ``default`` returns texts unchanged (upstream as-is — may crash inside
+ the pipeline; the ``c0ce823c`` ``try/except`` in ``extract`` is the
+ defense-in-depth backstop).
+ - ``error`` raises ``InputTooLongError`` (whole batch fails, no partial
+ responses).
+ - ``truncate_text`` slices text to
+ ``budget = max_sequence_length - label_prompt_tokens - special_count``.
+
+ Under ``truncate_text`` and ``error``, ``label_prompt`` alone exceeding
+ the cap always raises.
+ """
+ if policy == "default":
+ return texts
+
+ if self._pipeline is None:
+ raise RuntimeError(ERR_NOT_LOADED)
+ if self._tokenizer is None:
+ raise RuntimeError(ERR_NOT_LOADED)
+ if self._max_seq_length is None:
+ raise RuntimeError(ERR_NOT_LOADED)
+
+ label_prompt = self._pipeline.pipe.prepare_input(text="", labels=labels) # ty:ignore[unresolved-attribute]
+ label_prompt_tokens = len(self._tokenizer(label_prompt, add_special_tokens=False)["input_ids"])
+ overhead = label_prompt_tokens + self._special_count
+ budget = self._max_seq_length - overhead
+
+ if budget <= 0:
+ raise InputTooLongError(
+ f"label_prompt ({label_prompt_tokens} tokens) + special ({self._special_count}) "
+ f"exceeds max_sequence_length ({self._max_seq_length}); reduce the number or length of labels"
+ )
+
+ new_texts: list[str] = []
+ for i, text in enumerate(texts):
+ text_ids = self._tokenizer(text, add_special_tokens=False)["input_ids"]
+ text_tokens = len(text_ids)
+ observed = text_tokens + overhead
+ if observed <= self._max_seq_length:
+ new_texts.append(text)
+ continue
+ if policy == "error":
+ raise InputTooLongError(
+ f"items[{i}] observed_tokens={observed} exceeds max_sequence_length ({self._max_seq_length}) "
+ f"(text={text_tokens}, label_prompt={label_prompt_tokens}, special={self._special_count})"
+ )
+ new_texts.append(self._tokenizer.decode(text_ids[:budget], skip_special_tokens=True))
+ return new_texts
+
def extract(
self,
items: list[Item],
@@ -193,7 +253,6 @@ class GLiClassAdapter(BaseAdapter):
ValueError: If labels not provided or items lack text, or if the
input produced an empty tensor inside the gliclass pipeline.
"""
- self._check_loaded()
if self._pipeline is None:
raise RuntimeError(ERR_NOT_LOADED)
@@ -209,6 +268,9 @@ class GLiClassAdapter(BaseAdapter):
opts = options or {}
effective_threshold = float(opts.get("threshold", self._threshold))
+ overflow_policy = opts.get("overflow_policy", DEFAULT_OVERFLOW_POLICY)
+ texts = self._apply_overflow_policy(texts, labels, overflow_policy)
+
# Run batch classification.
# - threshold=0.0: never let the gliclass library drop labels for us
# (in single-label mode the lib returns only argmax anyway, so we
@@ -223,15 +285,22 @@ class GLiClassAdapter(BaseAdapter):
threshold=0.0,
return_hierarchical=True,
)
- except RuntimeError as exc:
- # The gliclass library calls torch.argmax on potentially-empty
- # tensors when inputs blow past the model's position-embedding
- # capacity. Surface this as a clear validation error rather than a
- # 500 INFERENCE_ERROR. Match on BOTH phrases to avoid catching
- # unrelated runtime errors.
+ except (RuntimeError, IndexError) as exc:
+ # The gliclass library crashes inside the pipeline when inputs exceed
+ # the model's position-embedding capacity, producing empty intermediate
+ # tensors that downstream ops then operate on. Surface the known crash
+ # signatures as InputTooLongError (validation) instead of leaking as
+ # 500 INFERENCE_ERROR. Match must be specific to avoid swallowing
+ # unrelated errors. Catalog of caught signatures:
+ # - RuntimeError "argmax(): ... numel() == 0" (sie-test#89 / #848)
+ # torch.argmax on an empty tensor inside the classification head.
+ # - IndexError "index N is out of bounds for dimension D with size 0" (#860)
+ # indexing an empty tensor in the gliclass post-processing path.
msg = str(exc)
- if "numel() == 0" in msg and "argmax" in msg:
- raise ValueError(_ERR_INPUT_TOO_LONG) from exc
+ if isinstance(exc, RuntimeError) and "numel() == 0" in msg and "argmax" in msg:
+ raise InputTooLongError(_ERR_INPUT_TOO_LONG) from exc
+ if isinstance(exc, IndexError) and _INDEX_OOB_EMPTY_TENSOR_RE.search(msg):
+ raise InputTooLongError(_ERR_INPUT_TOO_LONG) from exc
raise
all_classifications: list[list[Classification]] = []
diff --git a/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py b/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py
index 330a34afb..03470bc10 100644
--- a/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py
@@ -27,6 +27,7 @@ from __future__ import annotations
import io
import logging
+import threading
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -48,6 +49,10 @@ _ERR_REQUIRES_FLASH_ATTN = (
"NemoColEmbedAdapter requires flash_attn. Install with: pip install flash-attn --no-build-isolation"
)
+# Serializes the v1 ``config_class.to_dict`` monkey-patch so concurrent v1
+# loads cannot observe a partially-restored serializer or race on the restore.
+_V1_TO_DICT_PATCH_LOCK = threading.Lock()
+
class NemoColEmbedAdapter(BaseAdapter):
"""Adapter for NVIDIA NeMo ColEmbed visual document retrieval model.
@@ -111,76 +116,139 @@ class NemoColEmbedAdapter(BaseAdapter):
device: Device string (e.g., "cuda:0", "cpu").
Raises:
- ImportError: If flash_attn is not installed.
+ ImportError: If flash_attn is required by the model and not installed.
"""
- # Check flash_attn is available (required by this model)
- try:
- import flash_attn # ty: ignore[unresolved-import]
- except ImportError as e:
- raise ImportError(_ERR_REQUIRES_FLASH_ATTN) from e
-
- from transformers.dynamic_module_utils import get_class_from_dynamic_module
+ from transformers import AutoModel
self._device = device
# Determine dtype
dtype = self._resolve_dtype()
+ attn_impl = self._resolve_attn_implementation(device)
logger.info(
- "Loading NeMo ColEmbed model %s on device=%s with dtype=%s",
+ "Loading NeMo ColEmbed model %s on device=%s with dtype=%s, attn=%s",
self._model_name_or_path,
device,
dtype,
+ attn_impl,
)
- # Load model class directly to bypass AutoModel/AutoConfig introspection.
+ # Try AutoModel first (works for v2: Qwen3-VL backbone, registers cleanly).
+ # Fall back to v1's explicit dynamic-module path with the to_dict monkey-patch
+ # if AutoModel can't resolve the custom architecture. The fallback covers:
+ # - KeyError / ValueError: AutoModel can't find a matching architecture
+ # - ImportError: the dynamic modeling file imports flash_attn at module
+ # top (v1 ships its own modeling file that does this)
+ # - AttributeError: v1's config.to_dict() bug fires inside transformers'
+ # to_diff_dict() comparison when vision_config is absent
+ loaded_via_v1_path = False
+ try:
+ self._model = AutoModel.from_pretrained(
+ self._model_name_or_path,
+ trust_remote_code=True,
+ device_map=device,
+ torch_dtype=dtype,
+ attn_implementation=attn_impl,
+ )
+ except (KeyError, ValueError, ImportError, AttributeError) as automodel_err:
+ logger.info(
+ "AutoModel.from_pretrained failed for %s (%s: %s); falling back to v1 dynamic-module load path",
+ self._model_name_or_path,
+ type(automodel_err).__name__,
+ automodel_err,
+ )
+ self._model = self._load_v1_dynamic(device, dtype)
+ loaded_via_v1_path = True
+
+ self._model.eval()
+
+ # Discover embedding dim with a fallback chain:
+ # 1. config.embedding_dim (v1: 128)
+ # 2. config.hidden_size (v2: 2560)
+ # 3. constructor token_dim (last-resort default)
+ embedding_dim = getattr(self._model.config, "embedding_dim", None)
+ if embedding_dim is None:
+ embedding_dim = getattr(self._model.config, "hidden_size", None)
+ if isinstance(embedding_dim, int) and embedding_dim > 0:
+ self._multivector_dim = embedding_dim
+
+ # Create preprocessor only when the model exposes v1-style attrs (image_size,
+ # num_image_token). v2 (Qwen3-VL) does not, and the SigLIP+Llama-keyed
+ # NemoColEmbedPreprocessor does not apply.
+ if loaded_via_v1_path or (hasattr(self._model, "image_size") and hasattr(self._model, "num_image_token")):
+ self._create_processor()
+ else:
+ logger.info("Skipping NemoColEmbedPreprocessor — model lacks v1 attrs (likely v2 backbone).")
+
+ def _load_v1_dynamic(self, device: str, dtype: torch.dtype) -> Any:
+ """Load v1 (SigLIP+Llama) via the explicit dynamic-module path.
+
+ This path applies a ``to_dict`` monkey-patch to work around a v1
+ config bug that assumes ``vision_config`` always exists. v1 also
+ requires ``flash_attention_2``.
+ """
+ try:
+ import flash_attn # ty: ignore[unresolved-import]
+ except ImportError as e:
+ raise ImportError(_ERR_REQUIRES_FLASH_ATTN) from e
+
+ from transformers.dynamic_module_utils import get_class_from_dynamic_module
+
model_class = get_class_from_dynamic_module(
"modeling_llama_nemoretrievercolembed.llama_NemoRetrieverColEmbed",
self._model_name_or_path,
trust_remote_code=True,
)
- # NVIDIA's config has a bug: to_dict() assumes vision_config exists but it doesn't.
- # The bug is triggered during transformers' to_diff_dict() which creates a new config
- # instance to compare defaults. Monkey-patch the config class to fix it.
+ # v1's config.to_dict() bug: assumes vision_config exists but it doesn't.
+ # Triggered during transformers' to_diff_dict() comparison. Patch around it
+ # only for this v1 fallback path — v2 inherits from Qwen3VLConfig cleanly.
+ # Serialized with _V1_TO_DICT_PATCH_LOCK so concurrent v1 loads can't leak
+ # the patched serializer or race on the restore.
config_class = model_class.config_class # ty:ignore[unresolved-attribute]
- original_to_dict = config_class.to_dict
def patched_to_dict(self: Any) -> dict[str, Any]:
- """Patched to_dict that handles missing vision_config."""
+ """Patched to_dict that handles missing vision_config (v1 only)."""
import copy
output = copy.deepcopy(self.__dict__)
- # Only include vision_config if it exists
if hasattr(self, "vision_config") and self.vision_config is not None:
output["vision_config"] = self.vision_config.to_dict()
- # Only include llm_config if it exists
if hasattr(self, "llm_config") and self.llm_config is not None:
output["llm_config"] = self.llm_config.to_dict()
output["model_type"] = self.__class__.model_type
return output
- config_class.to_dict = patched_to_dict
-
+ with _V1_TO_DICT_PATCH_LOCK:
+ original_to_dict = config_class.to_dict
+ config_class.to_dict = patched_to_dict
+ try:
+ return model_class.from_pretrained( # ty:ignore[unresolved-attribute]
+ self._model_name_or_path,
+ device_map=device,
+ torch_dtype=dtype,
+ attn_implementation="flash_attention_2",
+ )
+ finally:
+ config_class.to_dict = original_to_dict
+
+ def _resolve_attn_implementation(self, device: str) -> str:
+ """Return ``flash_attention_2`` when available on CUDA, else ``sdpa``.
+
+ v2 (Qwen3-VL) tolerates ``sdpa`` cleanly. v1 still requires
+ ``flash_attention_2`` and that requirement is enforced inside
+ ``_load_v1_dynamic`` via an explicit ``import flash_attn`` check.
+ """
+ if not str(device).startswith("cuda"):
+ return "sdpa"
try:
- self._model = model_class.from_pretrained( # ty:ignore[unresolved-attribute]
- self._model_name_or_path,
- device_map=device,
- torch_dtype=dtype,
- attn_implementation="flash_attention_2",
- )
- finally:
- # Restore original to_dict after loading
- config_class.to_dict = original_to_dict
-
- self._model.eval()
-
- # Get embedding dimension from model config if available
- if hasattr(self._model.config, "embedding_dim"):
- self._multivector_dim = self._model.config.embedding_dim
+ import flash_attn # ty: ignore[unresolved-import]
- # Create preprocessor for conformance with SIE infrastructure
- self._create_processor()
+ return "flash_attention_2"
+ except ImportError:
+ logger.info("flash_attn not available, using sdpa attention")
+ return "sdpa"
def _resolve_dtype(self) -> torch.dtype:
"""Resolve dtype based on device and config."""
@@ -307,19 +375,13 @@ class NemoColEmbedAdapter(BaseAdapter):
with torch.inference_mode():
embeddings = self._model.forward_queries(texts, batch_size=self._batch_size)
- # embeddings is a list of tensors [seq_len, dim] for each query
- multivector_list = []
- for emb in embeddings:
- if isinstance(emb, torch.Tensor):
- if self._normalize:
- emb = functional.normalize(emb, p=2, dim=-1)
- emb = emb.float().cpu().numpy()
- else:
- emb = np.array(emb, dtype=np.float32)
- if self._normalize:
- emb = emb / np.linalg.norm(emb, axis=-1, keepdims=True)
+ multivector_list = self._unpack_embeddings(embeddings, expected_count=len(texts))
- multivector_list.append(emb)
+ # Free GPU memory to prevent OOM on subsequent calls
+ del embeddings
+ if self._device and self._device.startswith("cuda"):
+ torch.cuda.empty_cache()
+ _ = functional # silence unused-import in some lint passes
return EncodeOutput(
multivector=multivector_list,
@@ -329,7 +391,7 @@ class NemoColEmbedAdapter(BaseAdapter):
)
def _encode_images(self, items: list[Any], *, is_query: bool) -> EncodeOutput:
- """Encode document images using forward_passages().
+ """Encode document images using forward_images() (v2) or forward_passages() (v1).
Args:
items: List of items with images.
@@ -339,7 +401,6 @@ class NemoColEmbedAdapter(BaseAdapter):
EncodeOutput with multivector embeddings.
"""
from PIL import Image
- from torch.nn import functional
# Item is a TypedDict (dict) - no instance check needed
pil_images = []
@@ -354,23 +415,13 @@ class NemoColEmbedAdapter(BaseAdapter):
pil_img = pil_img.convert("RGB")
pil_images.append(pil_img)
- # Use model's forward_passages method
- with torch.inference_mode():
- embeddings = self._model.forward_passages(pil_images, batch_size=self._batch_size)
+ # v2 exposes ``forward_images`` (Qwen3-VL backbone); v1 exposes ``forward_passages``.
+ forward = getattr(self._model, "forward_images", None) or self._model.forward_passages
- # embeddings is a list of tensors [num_patches, dim] for each image
- multivector_list = []
- for emb in embeddings:
- if isinstance(emb, torch.Tensor):
- if self._normalize:
- emb = functional.normalize(emb, p=2, dim=-1)
- emb = emb.float().cpu().numpy()
- else:
- emb = np.array(emb, dtype=np.float32)
- if self._normalize:
- emb = emb / np.linalg.norm(emb, axis=-1, keepdims=True)
+ with torch.inference_mode():
+ embeddings = forward(pil_images, batch_size=self._batch_size)
- multivector_list.append(emb)
+ multivector_list = self._unpack_embeddings(embeddings, expected_count=len(pil_images))
# Free GPU memory to prevent OOM on subsequent calls
del embeddings
@@ -384,6 +435,58 @@ class NemoColEmbedAdapter(BaseAdapter):
multivector_token_dim=self._multivector_dim,
)
+ def _unpack_embeddings(
+ self,
+ embeddings: Any,
+ *,
+ expected_count: int,
+ ) -> list[np.ndarray]:
+ """Convert v1's list-of-Tensor or v2's padded (B, S, D) tensor to per-item numpy.
+
+ v1 ``forward_queries``/``forward_passages`` return ``list[Tensor]`` where
+ each entry is ``[seq, dim]``. v2 returns a single padded tensor of shape
+ ``[batch, max_seq, dim]``. Normalize per-row when ``self._normalize``.
+ """
+ from torch.nn import functional
+
+ results: list[np.ndarray] = []
+
+ if isinstance(embeddings, torch.Tensor):
+ if embeddings.ndim != 3:
+ msg = (
+ f"NemoColEmbed: unexpected embedding tensor shape {tuple(embeddings.shape)}; "
+ f"expected 3D [batch, seq, dim]"
+ )
+ raise RuntimeError(msg)
+ # v2 right-pads with zero rows so all rows in a batch share a sequence
+ # length. Detect padding before normalization (zero rows become NaN
+ # after L2 normalize) and drop them per-item so downstream MaxSim
+ # doesn't consume padding tokens as content.
+ nonzero_mask = embeddings.abs().sum(dim=-1) > 0
+ tensor = embeddings
+ if self._normalize:
+ tensor = functional.normalize(tensor, p=2, dim=-1)
+ for i in range(tensor.shape[0]):
+ keep = nonzero_mask[i]
+ results.append(tensor[i][keep].float().cpu().numpy())
+ return results
+
+ # Iterable of per-item tensors / arrays (v1 path)
+ for emb in embeddings:
+ if isinstance(emb, torch.Tensor):
+ if self._normalize:
+ emb = functional.normalize(emb, p=2, dim=-1)
+ results.append(emb.float().cpu().numpy())
+ else:
+ arr = np.asarray(emb, dtype=np.float32)
+ if self._normalize:
+ arr = arr / np.linalg.norm(arr, axis=-1, keepdims=True)
+ results.append(arr)
+
+ if len(results) != expected_count:
+ logger.warning("NemoColEmbed: expected %d embeddings, got %d", expected_count, len(results))
+ return results
+
def _encode_images_preprocessed(
self,
items: list[Any],
@@ -411,6 +514,13 @@ class NemoColEmbedAdapter(BaseAdapter):
from sie_server.types.inputs import Item
+ # Belt-and-braces: if no v1 preprocessor (e.g., v2 backbone), defer to the
+ # native forward_images / forward_passages path. The dispatch in ``encode()``
+ # already short-circuits on payload type, so this only triggers when a caller
+ # invokes _encode_images_preprocessed directly.
+ if self._processor is None:
+ return self._encode_images(items, is_query=is_query)
+
# Process in sub-batches to maximize GPU utilization while avoiding OOM
# NemoColEmbed supports batching - model maps tiles to sequences via IMG_CONTEXT token counts
all_embeddings: list[np.ndarray] = []
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/__init__.py b/packages/sie_server/src/sie_server/adapters/sglang/__init__.py
index d933e68c6..d21cb7048 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/__init__.py
@@ -43,8 +43,13 @@ logger = logging.getLogger(__name__)
_ERR_SERVER_STARTUP = "SGLang server failed to start within timeout"
-# Server startup config
-_STARTUP_TIMEOUT_S = 300 # 5 minutes - accounts for HF downloads and model loading
+# Server startup config.
+# 8B+ models can take 5+ min just to download from HF on a fresh cache,
+# plus SGLang itself then loads the model onto the GPU. The default
+# was 300s, which is too tight for nvidia/llama-embed-nemotron-8b
+# and similar. Override via SIE_SGLANG_STARTUP_TIMEOUT_S for hosts
+# with slow network or larger models.
+_STARTUP_TIMEOUT_S = int(os.environ.get("SIE_SGLANG_STARTUP_TIMEOUT_S", "900"))
_HEALTH_CHECK_INTERVAL_S = 2.0
_BASE_PORT = 30000 # Starting port for SGLang servers
diff --git a/packages/sie_server/src/sie_server/api/extract.py b/packages/sie_server/src/sie_server/api/extract.py
index 0a06cfc16..dc409beba 100644
--- a/packages/sie_server/src/sie_server/api/extract.py
+++ b/packages/sie_server/src/sie_server/api/extract.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Annotated, Any, cast
from fastapi import APIRouter, Header, HTTPException, Request, status
from fastapi.responses import JSONResponse
+from sie_server.adapters.errors import InputTooLongError
from sie_server.api.helpers import (
InferenceErrorHandler,
ModelStateChecker,
@@ -367,6 +368,8 @@ async def extract(
timing = worker_result.timing
except QueueFullError as e:
raise error_handler.handle_queue_full(e) from e
+ except InputTooLongError as e:
+ raise error_handler.handle_input_too_long(e) from e
except ValueError as e:
raise error_handler.handle_value_error(e) from e
except Exception as e:
diff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.py
index 9ed3513d2..358e64472 100644
--- a/packages/sie_server/src/sie_server/api/helpers.py
+++ b/packages/sie_server/src/sie_server/api/helpers.py
@@ -9,6 +9,7 @@ import msgspec
from fastapi import HTTPException, Request, status
from fastapi.responses import JSONResponse
+from sie_server.adapters.errors import InputTooLongError
from sie_server.api.serialization import MsgPackResponse, _convert_for_json
from sie_server.core.oom import is_oom_error
from sie_server.core.timing import RequestTiming
@@ -490,6 +491,17 @@ class InferenceErrorHandler:
},
)
+ def handle_input_too_long(self, error: InputTooLongError) -> HTTPException:
+ self.span.set_attribute("error", "input_too_long")
+ record_request(model=self.model, endpoint=self.endpoint, status="error", **self._log_kwargs())
+ return HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={
+ "code": ErrorCode.INPUT_TOO_LONG.value,
+ "message": str(error),
+ },
+ )
+
def handle_inference_error(self, error: Exception, operation: str = "Inference") -> HTTPException:
"""Handle generic inference errors.
diff --git a/packages/sie_server/src/sie_server/api/options.py b/packages/sie_server/src/sie_server/api/options.py
index 206a77321..4a0a0e1b1 100644
--- a/packages/sie_server/src/sie_server/api/options.py
+++ b/packages/sie_server/src/sie_server/api/options.py
@@ -3,6 +3,7 @@ from typing import Any
from fastapi import HTTPException, status
from sie_server.config.model import ModelConfig
+from sie_server.types.overflow_policy import VALID_OVERFLOW_POLICIES
from sie_server.types.responses import ErrorCode
@@ -48,4 +49,18 @@ def resolve_runtime_options(
# Merge request-level overrides (excluding the "profile" key itself)
if request_options:
merged |= {k: v for k, v in request_options.items() if k != "profile"}
+
+ overflow_policy = merged.get("overflow_policy")
+ if overflow_policy is not None and overflow_policy not in VALID_OVERFLOW_POLICIES:
+ span.set_attribute("error", "invalid_overflow_policy")
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={
+ "code": ErrorCode.INVALID_INPUT.value,
+ "message": (
+ f"Invalid overflow_policy: {overflow_policy!r}. Must be one of {sorted(VALID_OVERFLOW_POLICIES)}."
+ ),
+ },
+ )
+
return merged
diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.py
index f9fee3c60..b156f1491 100644
--- a/packages/sie_server/src/sie_server/cli.py
+++ b/packages/sie_server/src/sie_server/cli.py
@@ -1,7 +1,19 @@
from __future__ import annotations
-import logging
+# IMPORTANT: HF timeout defaults must be installed BEFORE ``huggingface_hub``
+# is imported anywhere in the process (the library reads HF_HUB_*_TIMEOUT
+# at module import time). Inlined here — rather than imported from
+# ``sie_server.core.hf_env`` — because importing ``sie_server.core.*``
+# triggers ``core/__init__.py`` which transitively pulls in adapters and
+# could one day import ``huggingface_hub`` itself, latching the stock 10 s
+# defaults before our overrides land. Keep these two ``setdefault`` lines
+# as the very first executable statements after ``__future__``.
import os
+
+os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "60")
+os.environ.setdefault("HF_HUB_ETAG_TIMEOUT", "30")
+
+import logging
from pathlib import Path
import typer
diff --git a/packages/sie_server/src/sie_server/core/hf_env.py b/packages/sie_server/src/sie_server/core/hf_env.py
new file mode 100644
index 000000000..2a8ca8743
--- /dev/null
+++ b/packages/sie_server/src/sie_server/core/hf_env.py
@@ -0,0 +1,37 @@
+from __future__ import annotations
+
+import logging
+import os
+
+logger = logging.getLogger(__name__)
+
+
+# huggingface_hub's stock defaults (10 s for both DOWNLOAD and ETAG) are
+# aggressive enough to spuriously fail on flaky home networks. The values
+# here are tuned for slow-but-real connections: long enough that a 1
+# Mbit/s link with brief stalls still completes a multi-GB download, short
+# enough that a wedged socket fails in under a minute rather than hanging
+# the load executor indefinitely.
+#
+# Operators override by setting the env var explicitly before launching
+# the server — ``os.environ.setdefault`` is intentionally non-clobbering.
+_DEFAULTS: dict[str, str] = {
+ "HF_HUB_DOWNLOAD_TIMEOUT": "60", # per-chunk socket inactivity
+ "HF_HUB_ETAG_TIMEOUT": "30", # metadata HEAD request
+}
+
+
+def set_hf_default_timeouts() -> None:
+ """Set sensible ``huggingface_hub`` timeout defaults if unset.
+
+ Must be called BEFORE ``huggingface_hub`` is imported anywhere in the
+ process — the library reads these env vars at module import time and
+ caches the values. The server entry points (``cli.py``,
+ ``main._create_app_from_env``) call this at the very top, before any
+ transitive import that might pull in ``huggingface_hub``.
+
+ Idempotent: subsequent calls are a no-op once the env vars are set.
+ """
+ for key, value in _DEFAULTS.items():
+ if os.environ.setdefault(key, value) == value:
+ logger.debug("set %s=%s (default; override by exporting before startup)", key, value)
diff --git a/packages/sie_server/src/sie_server/core/load_errors.py b/packages/sie_server/src/sie_server/core/load_errors.py
index c54a56d70..002d42ddc 100644
--- a/packages/sie_server/src/sie_server/core/load_errors.py
+++ b/packages/sie_server/src/sie_server/core/load_errors.py
@@ -28,6 +28,7 @@ class LoadErrorClass(StrEnum):
OOM = "OOM"
NETWORK = "NETWORK"
DEPENDENCY = "DEPENDENCY"
+ TIMEOUT = "TIMEOUT"
UNKNOWN = "UNKNOWN"
@@ -43,9 +44,29 @@ _COOLDOWN_BY_CLASS: dict[LoadErrorClass, float | None] = {
LoadErrorClass.UNKNOWN: _PERMANENT,
LoadErrorClass.OOM: 60.0,
LoadErrorClass.NETWORK: 30.0,
+ LoadErrorClass.TIMEOUT: 30.0,
}
+class ModelLoadTimeoutError(TimeoutError):
+ """Raised when a post-download load stage exceeds ``SIE_MODEL_LOAD_TIMEOUT_S``.
+
+ Subclasses ``TimeoutError`` so callers that only know about the built-in
+ type still match, but the dedicated class lets ``classify_load_error``
+ bucket these into :class:`LoadErrorClass.TIMEOUT` rather than the
+ generic ``NETWORK`` bucket. Carries structured fields for ops triage.
+ """
+
+ def __init__(self, *, model: str, stage: str, elapsed_s: float, timeout_s: float) -> None:
+ self.model = model
+ self.stage = stage
+ self.elapsed_s = elapsed_s
+ self.timeout_s = timeout_s
+ super().__init__(
+ f"Model '{model}' {stage} exceeded timeout: elapsed={elapsed_s:.1f}s, configured={timeout_s:.0f}s"
+ )
+
+
@dataclass(frozen=True)
class LoadFailureClassification:
"""Result of classifying a load-time exception."""
@@ -77,6 +98,17 @@ def classify_load_error(exc: BaseException) -> LoadFailureClassification:
Returns:
Classification with the canonical class and cooldown.
"""
+ # Our own post-download load timeout — must come BEFORE the generic
+ # ``TimeoutError`` → NETWORK branch below, since this subclasses
+ # ``TimeoutError``. Bucketed separately so the metric and the
+ # operator-facing message identify "stuck local load" distinct from
+ # "stuck network".
+ if isinstance(exc, ModelLoadTimeoutError):
+ return LoadFailureClassification(
+ error_class=LoadErrorClass.TIMEOUT,
+ cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.TIMEOUT],
+ )
+
# Gated repo (HF auth) — permanent until operator fixes HF_TOKEN.
if isinstance(exc, GatedModelError):
return LoadFailureClassification(
diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.py
index 301618449..217247768 100644
--- a/packages/sie_server/src/sie_server/core/model_loader.py
+++ b/packages/sie_server/src/sie_server/core/model_loader.py
@@ -2,6 +2,8 @@ from __future__ import annotations
import asyncio
import logging
+import os
+import time
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
@@ -11,11 +13,16 @@ from typing import TYPE_CHECKING, Any
from sie_server.adapters.base import ModelAdapter
from sie_server.config.model import ModelConfig, ProfileAdaptiveBatching
from sie_server.core.inference import AttentionBackend, ComputePrecision
+from sie_server.core.load_errors import ModelLoadTimeoutError
from sie_server.core.loader import load_adapter
from sie_server.core.oom import OomRecoveryConfig
from sie_server.core.worker import ModelWorker, WorkerConfig
from sie_server.core.worker.types import AdaptiveBatchingParams
-from sie_server.observability.metrics import set_model_loaded, set_model_memory
+from sie_server.observability.metrics import (
+ increment_model_load_timeout,
+ set_model_loaded,
+ set_model_memory,
+)
if TYPE_CHECKING:
from sie_server.core.disk_cache import ModelDiskCacheManager
@@ -28,6 +35,42 @@ logger = logging.getLogger(__name__)
# Default maximum LoRAs per model before LRU eviction
DEFAULT_MAX_LORAS = 10
+# Default total-time budget (seconds) for the post-download portion of a
+# model load: adapter instantiation + ``adapter.load(device)`` + warmup.
+# The download phase is intentionally NOT bounded by this budget — it is
+# bounded only by ``HF_HUB_DOWNLOAD_TIMEOUT`` socket-inactivity stalls so
+# users on slow links can still complete legitimate multi-hour downloads.
+#
+# Override via the ``SIE_MODEL_LOAD_TIMEOUT_S`` env var or the
+# ``model_load_timeout_s`` constructor kwarg. ``0`` or a negative value
+# disables the timeout entirely.
+DEFAULT_MODEL_LOAD_TIMEOUT_S = 600.0
+_TIMEOUT_ENV_VAR = "SIE_MODEL_LOAD_TIMEOUT_S"
+
+
+def _resolve_load_timeout(explicit: float | None) -> float:
+ """Resolve effective post-download timeout in seconds.
+
+ Precedence: explicit kwarg > env var > built-in default. Returns ``0.0``
+ when disabled (``0`` or negative); callers treat that as "no
+ ``wait_for`` wrapping".
+ """
+ if explicit is not None:
+ return max(0.0, float(explicit))
+ raw = os.environ.get(_TIMEOUT_ENV_VAR)
+ if raw is None:
+ return DEFAULT_MODEL_LOAD_TIMEOUT_S
+ try:
+ return max(0.0, float(raw))
+ except ValueError:
+ logger.warning(
+ "Invalid %s=%r, falling back to default %ss",
+ _TIMEOUT_ENV_VAR,
+ raw,
+ DEFAULT_MODEL_LOAD_TIMEOUT_S,
+ )
+ return DEFAULT_MODEL_LOAD_TIMEOUT_S
+
@dataclass
class LoadedLora:
@@ -102,6 +145,7 @@ class ModelLoader:
adaptive_batching: AdaptiveBatchingParams | None = None,
oom_recovery: OomRecoveryConfig | None = None,
registry_callbacks: RegistryCallbacks | None = None,
+ model_load_timeout_s: float | None = None,
) -> None:
"""Initialize the model loader.
@@ -128,6 +172,10 @@ class ModelLoader:
self._oom_recovery = oom_recovery or OomRecoveryConfig()
self._registry_callbacks = registry_callbacks
self._load_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="model-load")
+ # Post-download budget (instantiate + adapter.load + warmup). 0.0
+ # disables the outer ``wait_for``. Download is bounded separately
+ # by ``HF_HUB_DOWNLOAD_TIMEOUT``.
+ self._model_load_timeout_s = _resolve_load_timeout(model_load_timeout_s)
def update_configs(self, configs: dict[str, ModelConfig]) -> None:
"""Update the config reference (called after rescan)."""
@@ -145,9 +193,14 @@ class ModelLoader:
This is separated from loading so we can check requires_main_thread
before deciding how to run the load.
- Also ensures model weights are in local cache (from cluster cache if needed).
+ IMPORTANT: As of the post-download-timeout refactor, this method
+ no longer ensures weights are cached — callers must invoke
+ :meth:`ensure_weights_cached` (or :meth:`ensure_weights_cached_async`)
+ first. The split exists so the download phase runs without an
+ outer total-time budget (slow networks are allowed) while the
+ local-only portion runs under ``SIE_MODEL_LOAD_TIMEOUT_S``.
- Note: Dependency checking is done earlier by ModelRegistry._check_model_loadable()
+ Note: Dependency checking is done earlier by ``ModelRegistry._check_model_loadable()``
before this method is called. This ensures errors surface synchronously.
Args:
@@ -158,16 +211,12 @@ class ModelLoader:
Returns:
The unloaded adapter instance (may be fallback adapter for non-CUDA devices).
-
- Raises:
- RuntimeError: If model not cached and HF fallback is disabled.
"""
logger.info("Instantiating adapter for model '%s' (device=%s)", name, device)
- # Ensure model weights are cached (cluster cache -> local cache)
- self._ensure_weights_cached(config)
-
- # Instantiate the adapter (does not load weights yet)
+ # Instantiate the adapter (does not load weights yet). Weight
+ # caching must already have been performed by the caller via
+ # ``ensure_weights_cached`` — see method docstring.
return load_adapter(
config,
model_dir,
@@ -176,7 +225,7 @@ class ModelLoader:
attention_backend=self._attention_backend,
)
- def _ensure_weights_cached(self, config: ModelConfig) -> None:
+ def ensure_weights_cached(self, config: ModelConfig) -> None:
"""Ensure model weights are available in local cache.
Implements the caching hierarchy:
@@ -223,6 +272,22 @@ class ModelLoader:
logger.debug("Model %s available at %s", model_id, cached_path)
+ async def ensure_weights_cached_async(self, name: str, config: ModelConfig) -> None:
+ """Async version of :meth:`ensure_weights_cached`.
+
+ Runs the (potentially long) download on the load executor so it
+ doesn't block the event loop. Intentionally NOT wrapped in
+ ``asyncio.wait_for`` — slow networks are allowed; stalls are
+ detected by ``HF_HUB_DOWNLOAD_TIMEOUT`` inside ``huggingface_hub``.
+
+ Args:
+ name: Model name (for logging context only).
+ config: Model configuration.
+ """
+ logger.debug("Ensuring weights cached for '%s'", name)
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(self._load_executor, self.ensure_weights_cached, config)
+
async def instantiate_adapter_async(
self,
name: str,
@@ -230,25 +295,27 @@ class ModelLoader:
model_dir: Path,
device: str,
) -> ModelAdapter:
- """Instantiate adapter in thread pool (async version).
+ """Instantiate adapter in the load executor with a post-download timeout.
- Args:
- name: Model name.
- config: Model configuration.
- model_dir: Path to model directory.
- device: Device string for device-aware adapter selection.
+ Bounded by ``SIE_MODEL_LOAD_TIMEOUT_S`` (default 600 s). On timeout
+ the underlying thread cannot be killed in Python, so the executor
+ is replaced with a fresh single-worker pool — the wedged thread
+ leaks until process exit but new loads can proceed.
- Returns:
- The unloaded adapter instance (may be fallback adapter for non-CUDA devices).
+ Callers MUST have already invoked :meth:`ensure_weights_cached_async`
+ for this config; this method assumes weights are on local disk.
+
+ Raises:
+ ModelLoadTimeoutError: If instantiation exceeds the configured
+ budget. Classified as ``LoadErrorClass.TIMEOUT`` by the
+ registry's failure recorder, which applies a 30 s cooldown
+ before the next client request can retry.
"""
- loop = asyncio.get_running_loop()
- return await loop.run_in_executor(
- self._load_executor,
- self.instantiate_adapter,
- name,
- config,
- model_dir,
- device,
+ return await self._run_with_timeout(
+ stage="instantiate",
+ name=name,
+ func=self.instantiate_adapter,
+ args=(name, config, model_dir, device),
)
def load_and_register(
@@ -311,25 +378,115 @@ class ModelLoader:
adapter: ModelAdapter,
config: ModelConfig,
) -> LoadedModel:
- """Load adapter in thread pool (for normal adapters).
-
- Args:
- name: Model name.
- device: Device string.
- adapter: The adapter to load.
- config: Model configuration.
-
- Returns:
- LoadedModel containing the loaded state.
+ """Load adapter in thread pool with post-download timeout.
+
+ Bounded by ``SIE_MODEL_LOAD_TIMEOUT_S``. The executor thread runs
+ ONLY ``_run_load_with_markers`` (weight deserialization + warmup);
+ the registry-state side effects (``_finish_load``: pre/postprocessor
+ registration, ``MODEL_LOADED`` gauge, worker creation, LoRA
+ preloading) run on the awaiting coroutine AFTER the future
+ resolves cleanly.
+
+ This split is critical for correctness on timeout: when
+ ``wait_for`` cancels, the orphaned thread keeps running but can
+ only mutate the adapter object itself (which the registry will
+ discard along with the LoadedModel that never gets created). It
+ cannot register stale preprocessors or set ``sie_model_loaded=1``
+ for a model the registry has marked failed.
+
+ ``requires_main_thread`` adapters (e.g. SGLang) are routed through
+ :meth:`_load_main_thread` instead, which intentionally does NOT
+ apply this timeout — those adapters have their own bounded
+ subprocess startup timeout and double-bounding causes spurious
+ mid-startup failures.
"""
- loop = asyncio.get_running_loop()
- def _load_sync() -> LoadedModel:
+ def _deserialize_and_warmup() -> None:
logger.info("Loading model '%s' onto %s", name, device)
_run_load_with_markers(name, device, adapter)
- return self._finish_load(name, device, adapter, config)
- return await loop.run_in_executor(self._load_executor, _load_sync)
+ await self._run_with_timeout(
+ stage="load",
+ name=name,
+ func=_deserialize_and_warmup,
+ args=(),
+ )
+ # Registry-state side effects (preprocessor/postprocessor
+ # registration, metrics, worker creation, LoRA preloading) run
+ # OUTSIDE the executor so an orphan thread from a wait_for
+ # cancellation cannot corrupt registry state. Safe to call from
+ # the awaiting coroutine: only cheap Python work, no I/O.
+ return self._finish_load(name, device, adapter, config)
+
+ async def _run_with_timeout(
+ self,
+ *,
+ stage: str,
+ name: str,
+ func: Any,
+ args: tuple[Any, ...],
+ ) -> Any:
+ """Run ``func(*args)`` in the load executor under the post-download budget.
+
+ Centralises the ``wait_for`` + executor-recreate dance shared by
+ :meth:`instantiate_adapter_async` and :meth:`_load_in_executor`. A
+ timeout of ``0`` (or negative, via env) disables the wrapper and
+ the call runs unbounded — matches the PR convention.
+
+ On timeout:
+ 1. The asyncio task awaiting the executor future is cancelled
+ via ``wait_for``. The underlying Python thread continues to
+ run; it cannot be interrupted from outside.
+ 2. The wedged executor is ``shutdown(wait=False)``'d and replaced
+ with a fresh single-worker pool so subsequent loads do not
+ queue behind the leaked thread (the registry holds
+ ``_load_lock`` while awaiting us, so this happens with the
+ registry quiesced).
+ 3. ``sie_model_load_timeouts_total{model, stage}`` is incremented
+ and a structured error is logged.
+ 4. :class:`ModelLoadTimeoutError` is raised; the registry's
+ ``_record_load_failure`` will classify it as ``TIMEOUT`` and
+ install a 30 s cooldown.
+ """
+ loop = asyncio.get_running_loop()
+ timeout = self._model_load_timeout_s
+ started = time.monotonic()
+ fut = loop.run_in_executor(self._load_executor, func, *args)
+
+ # Disabled: no wait_for wrapper, behave exactly like the pre-PR code.
+ if timeout <= 0:
+ return await fut
+
+ try:
+ return await asyncio.wait_for(fut, timeout=timeout)
+ except TimeoutError as exc:
+ elapsed = time.monotonic() - started
+ logger.error(
+ "Model load timeout: model=%s stage=%s elapsed_s=%.1f timeout_s=%.0f",
+ name,
+ stage,
+ elapsed,
+ timeout,
+ )
+ increment_model_load_timeout(name, stage)
+ # The thread keeps running with a stale adapter/config; we
+ # cannot kill it. Replace the executor so the next load is
+ # not queued behind the leaked worker.
+ self._recreate_executor()
+ raise ModelLoadTimeoutError(model=name, stage=stage, elapsed_s=elapsed, timeout_s=timeout) from exc
+
+ def _recreate_executor(self) -> None:
+ """Discard the current load executor and create a fresh one.
+
+ Called on timeout: the in-flight thread cannot be terminated, so
+ we orphan it (``shutdown(wait=False)`` returns immediately without
+ joining) and bind ``self._load_executor`` to a new single-worker
+ pool. The orphan thread continues to consume RAM/GPU until process
+ exit; ``sie_model_load_timeouts_total`` lets ops observe the rate.
+ """
+ old = self._load_executor
+ self._load_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="model-load")
+ old.shutdown(wait=False)
def _load_main_thread(
self,
@@ -343,6 +500,12 @@ class ModelLoader:
This blocks the event loop but is required for adapters like SGLang
that use Python signal handlers which only work in the main thread.
+ Adapter-internal startup timeouts (e.g. SGLang's subprocess health
+ poll) are rewrapped into :class:`ModelLoadTimeoutError` so the
+ registry's failure classifier buckets them as
+ ``LoadErrorClass.TIMEOUT`` (30 s cooldown) rather than
+ ``UNKNOWN`` (permanent) — consistent with the executor path.
+
Args:
name: Model name.
device: Device string.
@@ -353,7 +516,27 @@ class ModelLoader:
LoadedModel containing the loaded state.
"""
logger.info("Loading model '%s' onto %s (main thread)", name, device)
- _run_load_with_markers(name, device, adapter)
+ started = time.monotonic()
+ try:
+ _run_load_with_markers(name, device, adapter)
+ except RuntimeError as exc:
+ # SGLang raises ``RuntimeError("SGLang server failed to start
+ # within timeout")`` from ``_wait_for_server``. Pattern-match
+ # on the message; narrow enough to not bucket genuine runtime
+ # failures as timeouts. Other adapters that grow their own
+ # startup timeouts should follow the same convention.
+ msg = str(exc).lower()
+ if "failed to start within timeout" in msg or "startup timeout" in msg:
+ elapsed = time.monotonic() - started
+ increment_model_load_timeout(name, "load")
+ logger.error(
+ "Main-thread adapter startup timeout: model=%s elapsed_s=%.1f msg=%s",
+ name,
+ elapsed,
+ exc,
+ )
+ raise ModelLoadTimeoutError(model=name, stage="load", elapsed_s=elapsed, timeout_s=elapsed) from exc
+ raise
return self._finish_load(name, device, adapter, config)
def _finish_load(
diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.py
index f0c0c53d9..7b2734cf7 100644
--- a/packages/sie_server/src/sie_server/core/registry.py
+++ b/packages/sie_server/src/sie_server/core/registry.py
@@ -466,6 +466,13 @@ class ModelRegistry:
msg = _ERR_MODEL_ALREADY_LOADED.format(name=name)
raise ValueError(msg)
+ # Ensure model weights are cached (download from HF / cluster cache
+ # if needed). Kept as a distinct phase from instantiate so the
+ # post-download timeout in ``ModelLoader`` does not cover the
+ # potentially long download — slow networks remain supported via
+ # ``HF_HUB_DOWNLOAD_TIMEOUT`` stall detection only.
+ self._loader.ensure_weights_cached(config)
+
# Instantiate the adapter with device-aware fallback selection
adapter = self._loader.instantiate_adapter(name, config, model_dir, device)
@@ -489,7 +496,8 @@ class ModelRegistry:
)
self.unload(lru_model)
- # Retry once after eviction - need new adapter instance
+ # Retry once after eviction - weights still on disk so we
+ # skip ``ensure_weights_cached`` here.
adapter = self._loader.instantiate_adapter(name, config, model_dir, device)
loaded = self._loader.load_and_register(name, device, adapter, config)
@@ -566,7 +574,14 @@ class ModelRegistry:
config = self._configs[name]
model_dir = self._model_dirs.get(name, Path())
- # Instantiate adapter (in thread pool) with device-aware fallback selection
+ # Ensure weights are cached BEFORE instantiation. This
+ # phase is intentionally unbounded by the post-download
+ # timeout in ``ModelLoader`` — slow user networks are
+ # supported via ``HF_HUB_DOWNLOAD_TIMEOUT`` stall
+ # detection inside ``huggingface_hub`` only.
+ await self._loader.ensure_weights_cached_async(name, config)
+
+ # Instantiate adapter (in thread pool, post-download timeout applies)
adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, device)
try:
@@ -589,7 +604,8 @@ class ModelRegistry:
)
await self._do_unload(lru_model)
- # Retry once after eviction - need new adapter instance
+ # Retry once after eviction. Weights are still cached
+ # on disk so we skip ``ensure_weights_cached_async``.
adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, device)
loaded = await self._loader.load_and_register_async(name, device, adapter, config)
diff --git a/packages/sie_server/src/sie_server/main.py b/packages/sie_server/src/sie_server/main.py
index 328e89206..ade5419f5 100644
--- a/packages/sie_server/src/sie_server/main.py
+++ b/packages/sie_server/src/sie_server/main.py
@@ -1,3 +1,14 @@
+# IMPORTANT: install HF timeout defaults before any transitive import of
+# ``huggingface_hub``. Inlined (not imported from a sie_server submodule)
+# to avoid triggering ``sie_server.core.__init__`` — which pulls in
+# adapters — before the env vars are set. Mirrored from ``cli.py`` to
+# cover uvicorn ``reload=True`` worker re-imports (cli is not re-executed
+# in workers; they invoke this factory directly).
+import os
+
+os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "60")
+os.environ.setdefault("HF_HUB_ETAG_TIMEOUT", "30")
+
import uvicorn
from fastapi import FastAPI
diff --git a/packages/sie_server/src/sie_server/observability/metrics.py b/packages/sie_server/src/sie_server/observability/metrics.py
index 44bc82551..f4d40c27f 100644
--- a/packages/sie_server/src/sie_server/observability/metrics.py
+++ b/packages/sie_server/src/sie_server/observability/metrics.py
@@ -112,6 +112,15 @@ MODEL_MEMORY_BYTES = Gauge(
["model", "device"],
)
+MODEL_LOAD_TIMEOUTS = Counter(
+ "sie_model_load_timeouts_total",
+ "Number of post-download model-load timeouts, broken down by stage. "
+ "Stage is one of: ``instantiate`` (adapter object construction) or "
+ "``load`` (adapter.load + warmup). Download is bounded separately by "
+ "HF_HUB_DOWNLOAD_TIMEOUT and does NOT increment this counter.",
+ ["model", "stage"],
+)
+
# -----------------------------------------------------------------------------
# OOM Recovery Metrics
@@ -294,6 +303,17 @@ def set_model_memory(model: str, device: str, memory_bytes: int) -> None:
MODEL_MEMORY_BYTES.labels(model=model, device=device).set(memory_bytes)
+def increment_model_load_timeout(model: str, stage: str) -> None:
+ """Increment the ``sie_model_load_timeouts_total`` counter.
+
+ Args:
+ model: Model name.
+ stage: One of ``instantiate`` or ``load``. Download stalls are
+ handled by ``huggingface_hub`` and are not counted here.
+ """
+ MODEL_LOAD_TIMEOUTS.labels(model=model, stage=stage).inc()
+
+
def record_oom_recovery_event(
model: str,
*,
diff --git a/packages/sie_server/src/sie_server/types/openapi.py b/packages/sie_server/src/sie_server/types/openapi.py
index 00cd28b11..a265586ca 100644
--- a/packages/sie_server/src/sie_server/types/openapi.py
+++ b/packages/sie_server/src/sie_server/types/openapi.py
@@ -132,7 +132,15 @@ class ExtractParamsModel(BaseModel):
labels: list[str] | None = Field(default=None, description="Entity labels to extract")
output_schema: dict[str, Any] | None = Field(default=None, description="Schema for structured extraction")
instruction: str | None = Field(default=None, description="Task instruction")
- options: dict[str, Any] | None = Field(default=None, description="Adapter-specific options")
+ options: dict[str, Any] | None = Field(
+ default=None,
+ description=(
+ "Adapter-specific options. Recognized sub-keys include "
+ "'overflow_policy' (one of 'default', 'truncate_text', 'error'; "
+ "default 'default') controlling how inputs exceeding the model's "
+ "max_sequence_length are handled."
+ ),
+ )
class ExtractRequestModel(BaseModel):
@@ -147,7 +155,14 @@ class ExtractRequestModel(BaseModel):
{
"items": [{"text": "Apple Inc. was founded by Steve Jobs in Cupertino, California."}],
"params": {"labels": ["person", "organization", "location"]},
- }
+ },
+ {
+ "items": [{"text": "Apple Inc. was founded by Steve Jobs in Cupertino, California."}],
+ "params": {
+ "labels": ["person", "organization", "location"],
+ "options": {"overflow_policy": "truncate_text"},
+ },
+ },
]
}
}
diff --git a/packages/sie_server/src/sie_server/types/overflow_policy.py b/packages/sie_server/src/sie_server/types/overflow_policy.py
new file mode 100644
index 000000000..ac0c62596
--- /dev/null
+++ b/packages/sie_server/src/sie_server/types/overflow_policy.py
@@ -0,0 +1,5 @@
+from typing import Literal
+
+OverflowPolicy = Literal["default", "truncate_text", "error"]
+DEFAULT_OVERFLOW_POLICY: OverflowPolicy = "default"
+VALID_OVERFLOW_POLICIES: frozenset[OverflowPolicy] = frozenset({"default", "truncate_text", "error"})
diff --git a/packages/sie_server/src/sie_server/types/responses.py b/packages/sie_server/src/sie_server/types/responses.py
index b7356385d..4be7335bf 100644
--- a/packages/sie_server/src/sie_server/types/responses.py
+++ b/packages/sie_server/src/sie_server/types/responses.py
@@ -181,6 +181,7 @@ class ErrorCode(StrEnum):
QUEUE_FULL = "QUEUE_FULL"
INTERNAL_ERROR = "INTERNAL_ERROR"
RESOURCE_EXHAUSTED = "RESOURCE_EXHAUSTED" # GPU OOM
+ INPUT_TOO_LONG = "INPUT_TOO_LONG"
class ErrorDetail(TypedDict, total=False):
diff --git a/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py b/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py
new file mode 100644
index 000000000..a8e5e14b9
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py
@@ -0,0 +1,102 @@
+from __future__ import annotations
+
+import pytest
+from sie_server.adapters.errors import InputTooLongError
+from sie_server.adapters.gliclass import GLiClassAdapter
+
+
+class _FakeTokenizer:
+ def __call__(self, text: str, add_special_tokens: bool = False) -> dict[str, list[str]]:
+ return {"input_ids": text.split()}
+
+ def decode(self, ids: list[str], skip_special_tokens: bool = True) -> str:
+ return " ".join(ids)
+
+
+class _FakePipe:
+ def prepare_input(self, text: str, labels: list[str]) -> str:
+ prefix = "<LABEL> " + " <SEP> ".join(labels)
+ return f"{prefix} {text}".strip()
+
+
+class _FakePipeline:
+ pipe = _FakePipe()
+
+
+# With _FakeTokenizer + _FakePipe, N labels produce a 2N-token label_prompt.
+# _LABELS → "<LABEL> x <SEP> y" = 4 tokens; with special_count=2 the overhead
+# is 6, so for max_seq_length=10 the per-text budget is 4 tokens.
+_LABELS = ["x", "y"]
+
+
+def _make_adapter(*, max_seq_length: int = 10, special_count: int = 2) -> GLiClassAdapter:
+ adapter = GLiClassAdapter("test-model")
+ adapter._max_seq_length = max_seq_length
+ adapter._special_count = special_count
+ adapter._tokenizer = _FakeTokenizer() # ty:ignore[invalid-assignment]
+ adapter._pipeline = _FakePipeline() # ty:ignore[invalid-assignment]
+ return adapter
+
+
+class TestApplyOverflowPolicy:
+ def test_default_is_noop_even_when_input_overflows(self) -> None:
+ adapter = _make_adapter()
+ texts = ["a b c d e f g h i j"] # 10 tokens, observed = 16 > 10
+
+ assert adapter._apply_overflow_policy(texts, _LABELS, "default") == texts
+
+ def test_default_is_the_default_arg(self) -> None:
+ adapter = _make_adapter()
+ texts = ["a b c d e f g h i j"]
+
+ assert adapter._apply_overflow_policy(texts, _LABELS) == texts
+
+ def test_truncate_text_passes_fitting_text_through(self) -> None:
+ adapter = _make_adapter()
+ texts = ["a b c d"] # 4 tokens, observed = 10
+
+ assert adapter._apply_overflow_policy(texts, _LABELS, "truncate_text") == ["a b c d"]
+
+ def test_truncate_text_slices_overflowing_text_to_budget(self) -> None:
+ adapter = _make_adapter()
+ texts = ["a b c d e f g"] # 7 tokens, budget = 4
+
+ assert adapter._apply_overflow_policy(texts, _LABELS, "truncate_text") == ["a b c d"]
+
+ def test_truncate_text_mixed_batch(self) -> None:
+ adapter = _make_adapter()
+ texts = ["a b", "a b c d e f g"]
+
+ assert adapter._apply_overflow_policy(texts, _LABELS, "truncate_text") == ["a b", "a b c d"]
+
+ def test_error_raises_on_overflowing_text(self) -> None:
+ adapter = _make_adapter()
+ texts = ["a b c d e"] # 5 tokens, observed = 11 > 10
+
+ with pytest.raises(InputTooLongError, match=r"items\[0\] observed_tokens=11"):
+ adapter._apply_overflow_policy(texts, _LABELS, "error")
+
+ def test_error_reports_first_overflowing_item_index(self) -> None:
+ adapter = _make_adapter()
+ texts = ["a b", "a b c d e f"]
+
+ with pytest.raises(InputTooLongError, match=r"items\[1\]"):
+ adapter._apply_overflow_policy(texts, _LABELS, "error")
+
+ def test_label_prompt_overflow_raises_under_truncate_text(self) -> None:
+ adapter = _make_adapter(max_seq_length=5) # overhead 6 > 5
+
+ with pytest.raises(InputTooLongError, match="label_prompt"):
+ adapter._apply_overflow_policy(["a"], _LABELS, "truncate_text")
+
+ def test_label_prompt_overflow_raises_under_error(self) -> None:
+ adapter = _make_adapter(max_seq_length=5)
+
+ with pytest.raises(InputTooLongError, match="label_prompt"):
+ adapter._apply_overflow_policy(["a"], _LABELS, "error")
+
+ def test_label_prompt_overflow_does_not_raise_under_default(self) -> None:
+ adapter = _make_adapter(max_seq_length=5)
+ texts = ["a b c"]
+
+ assert adapter._apply_overflow_policy(texts, _LABELS, "default") == texts
diff --git a/packages/sie_server/tests/adapters/test_runtime_options.py b/packages/sie_server/tests/adapters/test_runtime_options.py
index f1f0a4e52..238b603ae 100644
--- a/packages/sie_server/tests/adapters/test_runtime_options.py
+++ b/packages/sie_server/tests/adapters/test_runtime_options.py
@@ -933,6 +933,27 @@ class TestExtractRuntimeOptions:
with pytest.raises(ValueError, match="empty tensor"):
adapter.extract([Item(text="x" * 6000)], labels=["Electronics"])
+ def test_gliclass_translates_index_oob_crash_to_validation_error(self) -> None:
+ """The ``IndexError: index ... out of bounds ... size 0`` crash from the
+ gliclass post-processing path on overflowing inputs is surfaced as
+ ValueError (validation), not IndexError (500 INFERENCE_ERROR).
+
+ Regression for #860 — observed on a ~2.5 KB repeated-sentence request to
+ ``knowledgator/gliclass-large-v1.0`` under ``overflow_policy=default``.
+ """
+ from unittest.mock import MagicMock
+
+ from sie_server.adapters.gliclass import GLiClassAdapter
+
+ adapter = GLiClassAdapter("test-model")
+ mock_pipeline = MagicMock()
+ mock_pipeline.side_effect = IndexError("index 0 is out of bounds for dimension 0 with size 0")
+ adapter._pipeline = mock_pipeline
+ adapter._device = "cpu"
+
+ with pytest.raises(ValueError, match="empty tensor"):
+ adapter.extract([Item(text="x" * 6000)], labels=["Electronics"])
+
def test_gliclass_unrelated_runtime_error_propagates(self) -> None:
"""RuntimeErrors that are not the specific empty-tensor argmax crash
must propagate untouched (so genuine bugs surface as 500s instead of
@@ -956,6 +977,19 @@ class TestExtractRuntimeOptions:
with pytest.raises(RuntimeError, match="argmax"):
adapter.extract([Item(text="hello")], labels=["a", "b"])
+ # Also: an IndexError with "out of bounds" but NOT "size 0" must propagate
+ # (e.g. a real out-of-range index against a non-empty tensor).
+ mock_pipeline.side_effect = IndexError("index 5 is out of bounds for dimension 0 with size 3")
+ with pytest.raises(IndexError, match="size 3"):
+ adapter.extract([Item(text="hello")], labels=["a", "b"])
+
+ # Also: an IndexError mentioning "size 0" but NOT "out of bounds for
+ # dimension ... with size 0" must propagate — locks in the full
+ # "out of bounds for dimension D with size 0" discriminator.
+ mock_pipeline.side_effect = IndexError("some unrelated error with size 0 buried in the message")
+ with pytest.raises(IndexError, match="unrelated"):
+ adapter.extract([Item(text="hello")], labels=["a", "b"])
+
def test_gliclass_long_input_does_not_crash(self) -> None:
"""A 6 KB Lorem-ipsum-style input flows through the adapter without crashing
when the pipeline is properly bounded by max_seq_length.
diff --git a/packages/sie_server/tests/adapters/test_visual_document.py b/packages/sie_server/tests/adapters/test_visual_document.py
index 5e645e314..388ff1b67 100644
--- a/packages/sie_server/tests/adapters/test_visual_document.py
+++ b/packages/sie_server/tests/adapters/test_visual_document.py
@@ -4,12 +4,14 @@ These adapters encode document images into multi-vector representations
for late interaction retrieval using MaxSim scoring.
"""
+from typing import Any
from unittest.mock import MagicMock
import numpy as np
import pytest
from sie_server.adapters.colpali import ColPaliAdapter
from sie_server.adapters.colqwen2 import ColQwen2Adapter
+from sie_server.adapters.colqwen3 import ColQwen3Adapter
from sie_server.adapters.nemo_colembed import NemoColEmbedAdapter
from sie_server.types.inputs import Item
@@ -123,6 +125,146 @@ class TestColQwen2Adapter:
adapter.encode(items, output_types=["sparse"])
+class TestColQwen3Adapter:
+ """Tests for ColQwen3Adapter with mocked model."""
+
+ @pytest.fixture
+ def adapter(self) -> ColQwen3Adapter:
+ """Create an adapter instance."""
+ return ColQwen3Adapter(
+ "TomoroAI/tomoro-colqwen3-embed-4b",
+ normalize=True,
+ compute_precision="bfloat16",
+ )
+
+ def test_capabilities(self, adapter: ColQwen3Adapter) -> None:
+ """Adapter reports correct capabilities."""
+ caps = adapter.capabilities
+ assert caps.inputs == ["text", "image"]
+ assert caps.outputs == ["multivector", "score"]
+
+ def test_dims_before_load_has_default(self, adapter: ColQwen3Adapter) -> None:
+ """Dims returns default value before load."""
+ dims = adapter.dims
+ assert dims.multivector == 320 # ColQwen3 default
+
+ def test_encode_before_load_raises(self, adapter: ColQwen3Adapter) -> None:
+ """Encode before load raises error."""
+ items = [Item(text="hello")]
+ with pytest.raises(RuntimeError, match="Model not loaded"):
+ adapter.encode(items, output_types=["multivector"])
+
+ def test_encode_without_input_raises(self, adapter: ColQwen3Adapter) -> None:
+ """Encode raises if item has no text or images."""
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ adapter._device = "cpu"
+
+ items = [Item()] # No text or images
+ with pytest.raises(ValueError, match="requires either text or images"):
+ adapter.encode(items, output_types=["multivector"])
+
+ def test_validate_output_types(self, adapter: ColQwen3Adapter) -> None:
+ """Only multivector output type is supported."""
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ adapter._device = "cpu"
+
+ items = [Item(text="test")]
+ with pytest.raises(ValueError, match="Unsupported output types"):
+ adapter.encode(items, output_types=["dense"])
+
+ with pytest.raises(ValueError, match="Unsupported output types"):
+ adapter.encode(items, output_types=["sparse"])
+
+ def test_encode_mixed_batch_preserves_order(self, adapter: ColQwen3Adapter) -> None:
+ """Mixed text/image items round-trip in input order with one mv per item."""
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ adapter._device = "cpu"
+ adapter._multivector_dim = 4
+
+ # Stamp each output with a unique value so we can assert which item it came from.
+ def fake_load_images(item: Any) -> list[Any]:
+ return [f"img-{item.text}"] * (1 if item.images else 0)
+
+ def fake_encode_images(images: list[Any]) -> list[np.ndarray]:
+ return [np.full((2, 4), float(i + 100), dtype=np.float32) for i, _ in enumerate(images)]
+
+ def fake_encode_text(text: str) -> np.ndarray:
+ return np.full((1, 4), float(hash(text) % 1000), dtype=np.float32)
+
+ adapter._load_images = fake_load_images # type: ignore[method-assign]
+ adapter._encode_images = fake_encode_images # type: ignore[method-assign]
+ adapter._encode_text = fake_encode_text # type: ignore[method-assign]
+
+ items = [
+ Item(text="a", images=[{"data": b"x", "format": "png"}]),
+ Item(text="b"),
+ Item(text="c", images=[{"data": b"y", "format": "png"}]),
+ Item(text="d"),
+ ]
+ out = adapter.encode(items, output_types=["multivector"])
+ assert out.batch_size == len(items)
+ assert out.multivector is not None
+ assert len(out.multivector) == len(items)
+
+ # Image items got the per-image stamp (100, 101) in input order; text items got hash stamps.
+ assert out.multivector[0][0, 0] == 100.0
+ assert out.multivector[1][0, 0] == float(hash("b") % 1000)
+ assert out.multivector[2][0, 0] == 101.0
+ assert out.multivector[3][0, 0] == float(hash("d") % 1000)
+
+ def test_encode_multi_image_item_concatenates_seq_dim(self, adapter: ColQwen3Adapter) -> None:
+ """A single item with N images yields one mv with seq = sum of per-image seqs."""
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ adapter._device = "cpu"
+ adapter._multivector_dim = 4
+
+ adapter._load_images = lambda item: ["img-1", "img-2", "img-3"] # type: ignore[method-assign]
+ per_image = [
+ np.full((3, 4), 1.0, dtype=np.float32),
+ np.full((5, 4), 2.0, dtype=np.float32),
+ np.full((7, 4), 3.0, dtype=np.float32),
+ ]
+ adapter._encode_images = lambda images: per_image # type: ignore[method-assign]
+
+ items = [Item(images=[{"data": b"x", "format": "png"}] * 3)]
+ out = adapter.encode(items, output_types=["multivector"])
+ assert out.multivector is not None
+ assert len(out.multivector) == 1
+ mv = out.multivector[0]
+ assert mv.shape == (3 + 5 + 7, 4)
+ # Concatenation order is per-image order: 3 rows of 1.0, 5 rows of 2.0, 7 rows of 3.0.
+ assert mv[0, 0] == 1.0
+ assert mv[3, 0] == 2.0
+ assert mv[8, 0] == 3.0
+
+
+class TestNemoColEmbedV2Config:
+ """Tests for NemoColEmbedAdapter v2 configuration (Qwen3-VL backbone, token_dim=2560)."""
+
+ def test_v2_token_dim_constructor(self) -> None:
+ """V2 adapter accepts token_dim=2560 and stores it on _multivector_dim."""
+ adapter = NemoColEmbedAdapter(
+ "nvidia/nemotron-colembed-vl-4b-v2",
+ token_dim=2560,
+ normalize=True,
+ )
+ # The class-level spec dim is fixed at 128 (v1) but the per-instance
+ # _multivector_dim must reflect the v2 token_dim.
+ assert adapter._multivector_dim == 2560
+
+ def test_v2_default_compute_precision(self) -> None:
+ """V2 adapter inherits the bf16 default."""
+ adapter = NemoColEmbedAdapter(
+ "nvidia/nemotron-colembed-vl-4b-v2",
+ token_dim=2560,
+ )
+ assert adapter._compute_precision == "bfloat16"
+
+
class TestNemoColEmbedAdapter:
"""Tests for NemoColEmbedAdapter with mocked model."""
@@ -221,6 +363,15 @@ class TestVLMCudaCacheClearing:
"ColQwen2._encode_images must call torch.cuda.empty_cache() to prevent OOM"
)
+ def test_colqwen3_encode_images_has_empty_cache(self) -> None:
+ """ColQwen3 _encode_images source contains empty_cache call."""
+ import inspect
+
+ source = inspect.getsource(ColQwen3Adapter._encode_images)
+ assert "torch.cuda.empty_cache()" in source, (
+ "ColQwen3._encode_images must call torch.cuda.empty_cache() to prevent OOM"
+ )
+
def test_colpali_encode_prepared_batch_has_empty_cache(self) -> None:
"""ColPali _encode_prepared_batch source contains empty_cache call."""
import inspect
diff --git a/packages/sie_server/tests/api/test_extract_integration.py b/packages/sie_server/tests/api/test_extract_integration.py
index 23a4ffe01..97af70df9 100644
--- a/packages/sie_server/tests/api/test_extract_integration.py
+++ b/packages/sie_server/tests/api/test_extract_integration.py
@@ -28,6 +28,7 @@ pytestmark = pytest.mark.skipif(
)
EXTRACT_MODEL = "NeuML/gliner-bert-tiny"
+EXTRACT_FUTURE_TIMEOUT_S = 180
@pytest.mark.integration
@@ -54,7 +55,7 @@ class TestExtractConcurrentBatching:
# Run 2 concurrent extractions
with ThreadPoolExecutor(2) as executor:
futures = [executor.submit(extract_single, text) for text in texts]
- results = [f.result(timeout=60) for f in futures]
+ results = [f.result(timeout=EXTRACT_FUTURE_TIMEOUT_S) for f in futures]
# All requests completed successfully
assert len(results) == 2
@@ -90,7 +91,7 @@ class TestExtractConcurrentBatching:
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=3) as executor:
futures = [executor.submit(extract_single, text) for text in texts]
- concurrent_results = [f.result(timeout=60) for f in futures]
+ concurrent_results = [f.result(timeout=EXTRACT_FUTURE_TIMEOUT_S) for f in futures]
concurrent_time = time.perf_counter() - start
# All results valid
@@ -161,7 +162,7 @@ class TestExtractBackpressure:
# Fire off many concurrent requests
with ThreadPoolExecutor(max_workers=num_requests) as executor:
futures = [executor.submit(extract_single, i) for i in range(num_requests)]
- results = [f.result(timeout=120) for f in as_completed(futures)]
+ results = [f.result(timeout=EXTRACT_FUTURE_TIMEOUT_S) for f in as_completed(futures)]
# Count successes and failures
successes = sum(1 for _, success, _ in results if success)
diff --git a/packages/sie_server/tests/core/test_adaptive_batching.py b/packages/sie_server/tests/core/test_adaptive_batching.py
index 5cb145b15..525bddb8e 100644
--- a/packages/sie_server/tests/core/test_adaptive_batching.py
+++ b/packages/sie_server/tests/core/test_adaptive_batching.py
@@ -396,11 +396,11 @@ class TestAdaptiveBatchController:
_current_wait_ms=10.0,
)
w1, _ = ctrl.step(observed_p50_ms=30.0, fill_ratio=0.5)
- assert w1 == pytest.approx(12.0)
+ assert w1 == pytest.approx(12.0, abs=1e-3)
w2, _ = ctrl.step(observed_p50_ms=40.0, fill_ratio=0.5)
- assert w2 == pytest.approx(13.0)
+ assert w2 == pytest.approx(13.0, abs=1e-3)
w3, _ = ctrl.step(observed_p50_ms=60.0, fill_ratio=0.5)
- assert w3 == pytest.approx(12.0)
+ assert w3 == pytest.approx(12.0, abs=1e-3)
class TestAdaptiveBatchingWorkerIntegration:
diff --git a/packages/sie_server/tests/core/test_model_load_timeout.py b/packages/sie_server/tests/core/test_model_load_timeout.py
new file mode 100644
index 000000000..0641f28d7
--- /dev/null
+++ b/packages/sie_server/tests/core/test_model_load_timeout.py
@@ -0,0 +1,372 @@
+"""Tests for the post-download model-load timeout introduced in sie-internal#846.
+
+Covers:
+- ``_resolve_load_timeout`` precedence (kwarg > env > default).
+- ``ModelLoader._run_with_timeout`` happy path (no wait_for fires).
+- Timeout path: raises ``ModelLoadTimeoutError``, recreates executor,
+ increments the Prometheus counter.
+- ``classify_load_error`` buckets ``ModelLoadTimeoutError`` into
+ ``LoadErrorClass.TIMEOUT`` with a non-permanent cooldown.
+- ``hf_env.set_hf_default_timeouts`` is non-clobbering.
+
+The tests use a stub executor function rather than real model loading;
+they target the timeout machinery itself, not adapter behaviour.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import time
+from concurrent.futures import ThreadPoolExecutor
+from unittest.mock import patch
+
+import pytest
+from sie_server.core.hf_env import set_hf_default_timeouts
+from sie_server.core.load_errors import (
+ LoadErrorClass,
+ ModelLoadTimeoutError,
+ classify_load_error,
+)
+from sie_server.core.model_loader import (
+ DEFAULT_MODEL_LOAD_TIMEOUT_S,
+ ModelLoader,
+ _resolve_load_timeout,
+)
+from sie_server.core.postprocessor_registry import PostprocessorRegistry
+from sie_server.core.preprocessor_registry import PreprocessorRegistry
+
+
+def _make_loader(timeout_s: float | None = None) -> ModelLoader:
+ pre = PreprocessorRegistry()
+ cpu_pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="test-cpu")
+ return ModelLoader(
+ preprocessor_registry=pre,
+ postprocessor_registry=PostprocessorRegistry(cpu_pool),
+ all_configs={},
+ model_load_timeout_s=timeout_s,
+ )
+
+
+class TestResolveLoadTimeout:
+ """``_resolve_load_timeout`` precedence and parsing."""
+
+ def test_explicit_kwarg_wins_over_env(self) -> None:
+ with patch.dict(os.environ, {"SIE_MODEL_LOAD_TIMEOUT_S": "999"}):
+ assert _resolve_load_timeout(42.0) == 42.0
+
+ def test_env_used_when_kwarg_none(self) -> None:
+ with patch.dict(os.environ, {"SIE_MODEL_LOAD_TIMEOUT_S": "123"}):
+ assert _resolve_load_timeout(None) == 123.0
+
+ def test_default_when_unset(self) -> None:
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("SIE_MODEL_LOAD_TIMEOUT_S", None)
+ assert _resolve_load_timeout(None) == DEFAULT_MODEL_LOAD_TIMEOUT_S
+
+ def test_zero_disables(self) -> None:
+ assert _resolve_load_timeout(0) == 0.0
+
+ def test_negative_clamped_to_zero(self) -> None:
+ """Negative values mean "disabled", normalised to 0 for uniform handling."""
+ assert _resolve_load_timeout(-5) == 0.0
+
+ def test_invalid_env_falls_back_to_default(self) -> None:
+ with patch.dict(os.environ, {"SIE_MODEL_LOAD_TIMEOUT_S": "not-a-number"}):
+ assert _resolve_load_timeout(None) == DEFAULT_MODEL_LOAD_TIMEOUT_S
+
+
+class TestRunWithTimeoutHappyPath:
+ """Successful execution returns the value and leaves the executor intact."""
+
+ async def test_returns_func_result(self) -> None:
+ loader = _make_loader(timeout_s=5.0)
+ original_executor = loader._load_executor
+
+ result = await loader._run_with_timeout(
+ stage="instantiate",
+ name="m",
+ func=lambda: "ok",
+ args=(),
+ )
+
+ assert result == "ok"
+ # Executor not swapped on success
+ assert loader._load_executor is original_executor
+
+ async def test_disabled_timeout_runs_unbounded(self) -> None:
+ """A 0/negative budget skips the ``wait_for`` wrapper entirely."""
+ loader = _make_loader(timeout_s=0)
+
+ def _slow() -> str:
+ time.sleep(0.05) # Comfortably exceeds any tight bound
+ return "ok"
+
+ # If wait_for were applied with timeout=0 we'd raise immediately.
+ result = await loader._run_with_timeout(stage="load", name="m", func=_slow, args=())
+ assert result == "ok"
+
+
+class TestRunWithTimeoutFires:
+ """Timeout path: error, metric, executor swap."""
+
+ async def test_raises_model_load_timeout_error(self) -> None:
+ loader = _make_loader(timeout_s=0.05)
+
+ def _hang() -> None:
+ time.sleep(2.0)
+
+ with pytest.raises(ModelLoadTimeoutError) as exc_info:
+ await loader._run_with_timeout(stage="load", name="hang-model", func=_hang, args=())
+
+ err = exc_info.value
+ assert err.model == "hang-model"
+ assert err.stage == "load"
+ assert err.timeout_s == pytest.approx(0.05)
+ assert err.elapsed_s >= 0.05
+
+ async def test_executor_is_recreated(self) -> None:
+ """After a timeout, ``_load_executor`` is a fresh pool so the next
+ load is not queued behind the leaked thread.
+ """
+ loader = _make_loader(timeout_s=0.05)
+ original_executor = loader._load_executor
+
+ def _hang() -> None:
+ time.sleep(2.0)
+
+ with pytest.raises(ModelLoadTimeoutError):
+ await loader._run_with_timeout(stage="load", name="m", func=_hang, args=())
+
+ assert loader._load_executor is not original_executor
+
+ # New executor accepts work
+ result = await loader._run_with_timeout(stage="instantiate", name="m", func=lambda: 42, args=())
+ assert result == 42
+
+ # Leaked thread cleanup: the orphaned executor is shut down so the
+ # interpreter doesn't keep it alive past the test.
+ original_executor.shutdown(wait=True)
+
+ async def test_increments_prometheus_counter(self) -> None:
+ from sie_server.observability.metrics import MODEL_LOAD_TIMEOUTS
+
+ loader = _make_loader(timeout_s=0.05)
+ before = MODEL_LOAD_TIMEOUTS.labels(model="metric-model", stage="load")._value.get()
+
+ def _hang() -> None:
+ time.sleep(2.0)
+
+ with pytest.raises(ModelLoadTimeoutError):
+ await loader._run_with_timeout(stage="load", name="metric-model", func=_hang, args=())
+
+ after = MODEL_LOAD_TIMEOUTS.labels(model="metric-model", stage="load")._value.get()
+ assert after == before + 1
+
+
+class TestClassification:
+ """``ModelLoadTimeoutError`` is bucketed as ``LoadErrorClass.TIMEOUT``."""
+
+ def test_classified_as_timeout(self) -> None:
+ err = ModelLoadTimeoutError(model="m", stage="load", elapsed_s=10.0, timeout_s=5.0)
+ result = classify_load_error(err)
+ assert result.error_class is LoadErrorClass.TIMEOUT
+ # Not permanent — client retry after cooldown is allowed.
+ assert result.cooldown_s == 30.0
+ assert not result.is_permanent
+
+ def test_generic_timeout_error_still_classifies_as_network(self) -> None:
+ """Bare ``TimeoutError`` (not from our wrapper) keeps the existing
+ NETWORK bucket; only our typed subclass routes to TIMEOUT.
+ """
+ result = classify_load_error(TimeoutError("socket read timeout"))
+ assert result.error_class is LoadErrorClass.NETWORK
+
+
+class TestHfEnvDefaults:
+ """``set_hf_default_timeouts`` installs sensible HF socket bounds."""
+
+ def test_sets_defaults_when_unset(self) -> None:
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("HF_HUB_DOWNLOAD_TIMEOUT", None)
+ os.environ.pop("HF_HUB_ETAG_TIMEOUT", None)
+ set_hf_default_timeouts()
+ assert os.environ["HF_HUB_DOWNLOAD_TIMEOUT"] == "60"
+ assert os.environ["HF_HUB_ETAG_TIMEOUT"] == "30"
+
+ def test_does_not_clobber_operator_override(self) -> None:
+ """Operators set tighter or looser values via env; we must not overwrite."""
+ with patch.dict(os.environ, {"HF_HUB_DOWNLOAD_TIMEOUT": "300"}, clear=False):
+ set_hf_default_timeouts()
+ assert os.environ["HF_HUB_DOWNLOAD_TIMEOUT"] == "300"
+
+
+class TestRegistryIntegration:
+ """End-to-end: a load timeout records a TIMEOUT-class failure with cooldown."""
+
+ async def test_registry_records_timeout_failure(self) -> None:
+ """When ``instantiate_adapter_async`` raises ``ModelLoadTimeoutError``,
+ the registry's ``_load_model_background`` records it as a
+ ``LoadErrorClass.TIMEOUT`` failure with the 30 s cooldown.
+ """
+ from pathlib import Path
+
+ from sie_server.config.model import (
+ EmbeddingDim,
+ EncodeTask,
+ ModelConfig,
+ ProfileConfig,
+ Tasks,
+ )
+ from sie_server.core.registry import ModelRegistry
+
+ config = ModelConfig(
+ sie_id="t",
+ hf_id="org/t",
+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=8))),
+ profiles={
+ "default": ProfileConfig(
+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",
+ max_batch_tokens=8,
+ )
+ },
+ )
+ registry = ModelRegistry()
+ registry.add_config(config)
+
+ with (
+ patch("sie_sdk.cache.ensure_model_cached", return_value=Path("/fake")),
+ patch.object(
+ registry._loader,
+ "instantiate_adapter_async",
+ side_effect=ModelLoadTimeoutError(model="t", stage="instantiate", elapsed_s=601.0, timeout_s=600.0),
+ ),
+ ):
+ await registry._load_model_background("t", "cpu")
+
+ assert registry.is_failed("t")
+ failure = registry.get_failure("t")
+ assert failure is not None
+ assert failure.error_class is LoadErrorClass.TIMEOUT
+ assert failure.cooldown_s == 30.0
+
+ async def test_orphan_thread_does_not_corrupt_registry_state(self) -> None:
+ """B1 regression: when ``_load_in_executor`` times out, the
+ orphaned thread must NOT register pre/postprocessors or set
+ ``MODEL_LOADED=1`` on the registry/metrics for a model the
+ registry has marked failed.
+
+ We simulate this by setting a tight timeout and an
+ ``adapter.load`` that blocks past the timeout. ``_run_with_timeout``
+ fires; the orphan keeps running ``adapter.load`` but
+ ``_finish_load`` was lifted out of the executor in the B1 fix —
+ so even if the orphan finishes ``adapter.load`` later, no
+ registry mutation occurs from the leaked thread.
+ """
+ from unittest.mock import MagicMock
+
+ from sie_server.config.model import EmbeddingDim, EncodeTask, ProfileConfig, Tasks
+ from sie_server.observability.metrics import MODEL_LOADED
+
+ loader = _make_loader(timeout_s=0.05)
+
+ adapter = MagicMock()
+ load_finished = False
+
+ def _slow_load(device: str) -> None:
+ nonlocal load_finished
+ time.sleep(0.3) # Comfortably past the 0.05 s budget
+ load_finished = True
+
+ adapter.load.side_effect = _slow_load
+ adapter.warmup.return_value = None
+ adapter.requires_main_thread = False
+
+ config = type(
+ "C",
+ (),
+ {
+ "sie_id": "ghost",
+ "hf_id": "org/ghost",
+ "tasks": Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=8))),
+ "profiles": {
+ "default": ProfileConfig(
+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",
+ max_batch_tokens=8,
+ )
+ },
+ },
+ )()
+
+ before = MODEL_LOADED.labels(model="ghost", device="cpu")._value.get()
+
+ with pytest.raises(ModelLoadTimeoutError):
+ await loader._load_in_executor("ghost", "cpu", adapter, config)
+
+ # Wait for the orphan thread to "complete" so we can assert it
+ # did NOT mutate registry state on its way out.
+ await asyncio.sleep(0.5)
+ assert load_finished, "test bug: orphan didn't reach the post-sleep marker"
+
+ after = MODEL_LOADED.labels(model="ghost", device="cpu")._value.get()
+ assert after == before, (
+ "orphan thread mutated MODEL_LOADED gauge — _finish_load must not run from the executor thread"
+ )
+
+ async def test_sglang_startup_timeout_classifies_as_timeout(self) -> None:
+ """M3 regression: ``_load_main_thread`` rewraps SGLang's
+ ``RuntimeError('SGLang server failed to start within timeout')``
+ into ``ModelLoadTimeoutError`` so the classifier buckets it as
+ ``LoadErrorClass.TIMEOUT`` (30 s cooldown) instead of UNKNOWN
+ (permanent).
+ """
+ from unittest.mock import MagicMock
+
+ loader = _make_loader()
+ adapter = MagicMock()
+ adapter.load.side_effect = RuntimeError("SGLang server failed to start within timeout")
+ adapter.warmup.return_value = None
+
+ with pytest.raises(ModelLoadTimeoutError) as exc_info:
+ loader._load_main_thread("sg", "cuda:0", adapter, config=None) # type: ignore[arg-type]
+
+ assert exc_info.value.stage == "load"
+ # Non-SGLang RuntimeErrors must NOT be rewrapped.
+ adapter2 = MagicMock()
+ adapter2.load.side_effect = RuntimeError("CUDA driver error: misaligned address")
+ with pytest.raises(RuntimeError) as exc_info2:
+ loader._load_main_thread("other", "cuda:0", adapter2, config=None) # type: ignore[arg-type]
+ assert not isinstance(exc_info2.value, ModelLoadTimeoutError)
+
+ async def test_start_load_async_short_circuits_during_cooldown(self) -> None:
+ """While the 30 s cooldown is active, ``start_load_async`` is a no-op."""
+ from sie_server.config.model import (
+ EmbeddingDim,
+ EncodeTask,
+ ModelConfig,
+ ProfileConfig,
+ Tasks,
+ )
+ from sie_server.core.registry import ModelRegistry
+
+ config = ModelConfig(
+ sie_id="t",
+ hf_id="org/t",
+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=8))),
+ profiles={
+ "default": ProfileConfig(
+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",
+ max_batch_tokens=8,
+ )
+ },
+ )
+ registry = ModelRegistry()
+ registry.add_config(config)
+
+ registry._record_load_failure(
+ "t",
+ ModelLoadTimeoutError(model="t", stage="load", elapsed_s=601.0, timeout_s=600.0),
+ )
+
+ started = await registry.start_load_async("t", "cpu")
+ assert started is False
diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.json
index 4bfeafa75..cdb560282 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.3.2",
+ "version": "0.3.3",
"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.ts
index 5ae24e888..b4fdc37f1 100644
--- a/packages/sie_ts_sdk/src/version.ts
+++ b/packages/sie_ts_sdk/src/version.ts
@@ -1 +1 @@
-export const SDK_VERSION = "0.3.2"; // x-release-please-version
+export const SDK_VERSION = "0.3.3"; // x-release-please-version
diff --git a/pyproject.toml b/pyproject.toml
index ca01f033b..23fc48aba 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -108,7 +108,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", "tools/mise_tasks/tests"]
+testpaths = ["packages/sie_server/tests", "packages/sie_sdk/tests", "packages/sie_bench/tests", "packages/sie_admin/tests", "packages/sie_config/tests", "tools/mise_tasks/tests", "tools/quality_eval/tests"]
pythonpath = ["packages/sie_server/src", "packages/sie_sdk/src", "packages/sie_bench/src", "packages/sie_admin/src", "packages/sie_config/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.lock
index 7ed19556a..1318bb2c1 100644
--- a/uv.lock
+++ b/uv.lock
@@ -5219,7 +5219,7 @@ dev = [
[[package]]
name = "sie-admin"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "packages/sie_admin" }
dependencies = [
{ name = "httpx" },
@@ -5252,7 +5252,7 @@ requires-dist = [
[[package]]
name = "sie-bench"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "packages/sie_bench" }
dependencies = [
{ name = "aiohttp" },
@@ -5329,7 +5329,7 @@ requires-dist = [
[[package]]
name = "sie-chroma"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "integrations/sie_chroma" }
dependencies = [
{ name = "chromadb" },
@@ -5401,7 +5401,7 @@ dev = [
[[package]]
name = "sie-crewai"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "integrations/sie_crewai" }
dependencies = [
{ name = "crewai" },
@@ -5426,7 +5426,7 @@ requires-dist = [
[[package]]
name = "sie-dspy"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "integrations/sie_dspy" }
dependencies = [
{ name = "dspy" },
@@ -5451,7 +5451,7 @@ requires-dist = [
[[package]]
name = "sie-haystack"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "integrations/sie_haystack" }
dependencies = [
{ name = "haystack-ai" },
@@ -5478,7 +5478,7 @@ requires-dist = [
[[package]]
name = "sie-lancedb"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "integrations/sie_lancedb" }
dependencies = [
{ name = "lancedb" },
@@ -5505,7 +5505,7 @@ requires-dist = [
[[package]]
name = "sie-langchain"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "integrations/sie_langchain" }
dependencies = [
{ name = "langchain-core" },
@@ -5532,7 +5532,7 @@ requires-dist = [
[[package]]
name = "sie-llamaindex"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "integrations/sie_llamaindex" }
dependencies = [
{ name = "llama-index-core" },
@@ -5559,7 +5559,7 @@ requires-dist = [
[[package]]
name = "sie-qdrant"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "integrations/sie_qdrant" }
dependencies = [
{ name = "qdrant-client" },
@@ -5582,7 +5582,7 @@ requires-dist = [
[[package]]
name = "sie-sdk"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "packages/sie_sdk" }
dependencies = [
{ name = "aiohttp" },
@@ -5631,7 +5631,7 @@ requires-dist = [
[[package]]
name = "sie-server"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "packages/sie_server" }
dependencies = [
{ name = "docling" },
@@ -5744,7 +5744,7 @@ dev = []
[[package]]
name = "sie-weaviate"
-version = "0.3.2"
+version = "0.3.3"
source = { editable = "integrations/sie_weaviate" }
dependencies = [
{ name = "sie-sdk" },