Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
release: v0.6.3
github-actions[bot]b204605055fb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 819757bd2..0566667d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,30 @@# Changelog+## v0.6.3++- chore(main): release 0.6.3+- test: stabilize SDK timeout retry assertion+- fix: fall back to relay on S3/GCS server-side copy failure+- feat: add server-side copy fast path for cloud weight sync+- fix: address final cloud storage review issues+- fix: harden cloud cache sync paths+- fix: address azure cache review feedback+- feat: support azure blob cluster cache+- feat: add azure blob payload store support+- fix(generate): reject both-present image-bearing content layouts+- fix(generate): image-free content_parts field must not shadow layout+- feat(generate): preserve text/image content-part ordering+- fix(nemo_colembed): trim left-padding rows from v1 conformant doc embeddings (#1163)+- perf(nemo_colembed): engage conformant image preprocessing for v1 (#1163)+- fix: evict stale gateway workers on shutdown+- fix(generate): address huronat review on vision input (F2-F8)+- fix(generate): address CodeRabbit review on vision input+- feat(generate): add vision (image) input to generate()+- fix(deps): clear HIGH Dependabot alerts (docling, rustls-webpki)+- fix(bench): address CodeRabbit — accurate classification comment + quote-agnostic test+- fix: align extraction quality evals with source baselines+- feat: add m4 extraction model configs+## v0.6.2- chore(main): release 0.6.2diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex a73e0ef36..1cd2fe62f 100644--- a/deploy/helm/sie-cluster/Chart.yaml+++ b/deploy/helm/sie-cluster/Chart.yaml@@ -4,8 +4,8 @@ description: >-SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,and observabilitytype: application-version: 0.6.2 # x-release-please-version-appVersion: v0.6.2 # x-release-please-version+version: 0.6.3 # x-release-please-version+appVersion: v0.6.3 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 82a46fb98..c0f2c403d 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -42,7 +42,7 @@ When scaling from zero, expect the following latencies:### Reducing Cold Start Time-1. **Use cluster cache**: Pre-populate S3/GCS with model weights (`--cluster-cache`)+1. **Use cluster cache**: Pre-populate object storage with model weights (`--cluster-cache`)2. **Set minReplicas=1**: Keep one warm replica per critical GPU type3. **Use reserved capacity**: Avoid spot for latency-sensitive workloads4. **Pre-warm models**: Call `/v1/encode/{model}` on startup to load weights@@ -55,9 +55,9 @@ When a pool is scaling from zero, the gateway returns:The SDK handles this automatically with configurable retries.-## Cluster model cache (S3/GCS)+## Cluster model cache-Pre-populate a shared bucket with model weights so worker pods don't re-download from HuggingFace on every cold start. The Python SDK pulls from the bucket first and falls back to HF on miss.+Pre-populate shared object storage with model weights so worker pods don't re-download from HuggingFace on every cold start. The Python SDK pulls from the cache first and falls back to HF on miss.**AWS (Terraform-managed bucket):**@@ -78,7 +78,7 @@ helm upgrade --install sie-cluster . \The Terraform output already includes the `/models` prefix, so the same URL is used for both `sie-admin --target` and `clusterCache.url`.-**Other clouds / BYO bucket:** point `workers.common.clusterCache.url` at any `s3://...` or `gs://...` URL the workload Service Account can read; populate it with the same `sie-admin cache weights sync --dest ...` command.+**Other clouds / BYO bucket:** point `workers.common.clusterCache.url` at any `s3://...`, `gs://...`, `abfs://...`, or `abfss://...` URL the workload identity can read; populate it with the same `sie-admin cache weights sync --dest ...` command.## Autoscalingdiff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex 37988ab7a..2a4cb9931 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -423,14 +423,14 @@ Resolve the effective payload-store URL.Resolution order:1. .Values.payloadStore.url set explicitly -> use it verbatim.2. .Values.workers.common.clusterCache.enabled and .url set -> derive a- sibling /payloads path at the same bucket root. Terraform exposes the- cache URL as "<scheme>://<bucket>/models" by convention, so the- auto-derivation strips a trailing "/models" segment before appending- "/payloads". The resulting layout is:- <bucket>/models/... weights (managed by sie-admin cache)- <bucket>/payloads/... large work-item refs (managed by gateway)- These siblings live at the bucket root, which is what the workload- IAM grants are scoped to in both the AWS and GCP terraform modules.+ sibling /payloads path at the same bucket/container root. Terraform+ exposes the cache URL as "<scheme>://<bucket-or-container>/models" by+ convention, so the auto-derivation strips a trailing "/models" segment+ before appending "/payloads". The resulting layout is:+ <bucket-or-container>/models/... weights (managed by sie-admin cache)+ <bucket-or-container>/payloads/... large work-item refs (managed by gateway)+ These siblings live at the bucket/container root, which is what supported+ cloud workload IAM grants are scoped to.3. Otherwise -> empty string (payload store is off, no env vars rendered).Templates that consume this should treat a non-empty result as "payloaddiff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex 07188ec4c..e181df75e 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -39,8 +39,8 @@and rejects local paths so misconfigured queue clusters fail fast. */}}{{- $payloadStoreUrl := include "sie-cluster.payloadStoreUrl" . }}{{- if $payloadStoreUrl }}- {{- if not (or (hasPrefix "s3://" $payloadStoreUrl) (hasPrefix "gs://" $payloadStoreUrl)) }}- {{- fail (printf "payloadStore.url must be an object-store URL (s3://bucket/prefix or gs://bucket/prefix), not a local path; got %q" $payloadStoreUrl) }}+ {{- if not (or (hasPrefix "s3://" $payloadStoreUrl) (hasPrefix "gs://" $payloadStoreUrl) (hasPrefix "abfs://" $payloadStoreUrl) (hasPrefix "abfss://" $payloadStoreUrl)) }}+ {{- fail (printf "payloadStore.url must be an object-store URL (s3://bucket/prefix, gs://bucket/prefix, or abfs(s)://[email protected]/prefix), not a local path; got %q" $payloadStoreUrl) }}{{- end }}{{- end }}apiVersion: apps/v1diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex d0ac42b19..0c58b3bee 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -143,7 +143,7 @@ spec:name: {{ $root.Values.workers.common.hfCache.tokenSecret }}key: {{ $root.Values.workers.common.hfCache.tokenSecretKey }}{{- end }}- # Cluster cache (S3/GCS)+ # Cluster cache (object storage){{- if $root.Values.workers.common.clusterCache.enabled }}- name: SIE_CLUSTER_CACHEvalue: {{ $root.Values.workers.common.clusterCache.url | quote }}diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 5d614d7c0..023faa9ff 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -357,10 +357,12 @@ workers:# -- Model cache size limit (emptyDir - ephemeral, no zone-lock issues)cacheStorageSize: 300Gi- # -- Cluster cache (S3/GCS) configuration+ # -- Cluster cache (object storage) configurationclusterCache:enabled: false- # -- S3/GCS bucket URL with the /models prefix (e.g., s3://my-bucket/models or gs://my-bucket/models).+ # -- Object-store URL with the /models prefix (for example,+ # s3://my-bucket/models, gs://my-bucket/models, or+ # abfs(s)://[email protected]/models).# AWS users: get this from `terraform output -raw model_cache_bucket_url`.# Pre-populate the bucket once with `sie-admin cache weights sync --bundle default --dest <url>/`.url: ""@@ -1099,32 +1101,35 @@ queueRouting:# -- Payload store for large work item payloads (images, long documents).# When a work item exceeds 1MB, the payload is offloaded to this store.# IMPORTANT: payloadStore.url must point to shared storage accessible by both-# gateway and worker pods. Use s3://bucket/prefix or gs://bucket/prefix.+# gateway and worker pods. Use s3://bucket/prefix, gs://bucket/prefix, or+# abfs(s)://[email protected]/prefix.# Local filesystem paths (e.g., /tmp/payloads) will NOT work in queue mode# because gateway and worker pods have different filesystems.## Auto-derivation: when workers.common.clusterCache.enabled=true and# workers.common.clusterCache.url is set, the chart enables the payload store# automatically and points it at the sibling /payloads prefix of the same-# bucket. By convention the terraform modules expose the cache URL as-# "<scheme>://<bucket>/models", and the chart strips a trailing "/models"-# segment before appending "/payloads" so the two features live at top-level-# sibling prefixes:+# bucket/container. By convention the terraform modules expose the cache URL as+# "<scheme>://<bucket-or-container>/models", and the chart strips a trailing+# "/models" segment before appending "/payloads" so the two features live at+# top-level sibling prefixes:# <bucket>/models/... model weights (managed by sie-admin)# <bucket>/payloads/... large work-item refs (managed by gateway)-# The AWS and GCP terraform modules scope their workload IAM grants to these-# top-level prefixes, so the auto-derived URL aligns with the permissions+# The supported cloud modules scope their workload IAM grants to+# these top-level prefixes, so the auto-derived URL aligns with the permissions# out of the box. Set payloadStore.url explicitly only to override the# default (e.g., a separate bucket); leaving it empty is the right call# for most clusters.payloadStore:- # -- Payload store URL. Must be an S3 or GCS URL (s3://bucket/prefix or gs://bucket/prefix).+ # -- Payload store URL. Must be an S3, GCS, or Azure Blob URL+ # (s3://bucket/prefix, gs://bucket/prefix, or abfs(s)://[email protected]/prefix).# Local paths are rejected when clusterRouting=queue (see gateway-deployment.yaml validation).# Leave empty to auto-derive from workers.common.clusterCache.url (recommended).url: ""# -- TTL for stored payloads in seconds.# For S3: configure via S3 lifecycle rules on the bucket.# For GCS: configure via GCS lifecycle rules on the bucket.+ # For Azure Blob: configure via lifecycle management rules on the storage account.# This value is passed as SIE_PAYLOAD_STORE_TTL env var to the gateway.ttlSeconds: 300diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex a515e94c5..a8702e3dd 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.2"+version = "0.6.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.tomlindex 37ff26a88..b08539ed6 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.2"+version = "0.6.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.tomlindex 35a3ee59b..b32574eaa 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.2"+version = "0.6.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.tomlindex beee4525b..64708b1de 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.2"+version = "0.6.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.tomlindex a1bce1f0c..dee32c3f3 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.2"+version = "0.6.3"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex fe5316fc8..3f805da84 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.2"+version = "0.6.3"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex 7422c2286..f877999d7 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.2"+version = "0.6.3"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 7f5c1f557..37d94ee54 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.2"+version = "0.6.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.jsonindex ee2bf6572..e18571768 100644--- a/integrations/sie_ts_chroma/package.json+++ b/integrations/sie_ts_chroma/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-chroma",- "version": "0.6.2",+ "version": "0.6.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.jsonindex a2f906547..3e7480fc5 100644--- a/integrations/sie_ts_lancedb/package.json+++ b/integrations/sie_ts_lancedb/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-lancedb",- "version": "0.6.2",+ "version": "0.6.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.jsonindex 58188926c..be44f7433 100644--- a/integrations/sie_ts_langchain/package.json+++ b/integrations/sie_ts_langchain/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-langchain",- "version": "0.6.2",+ "version": "0.6.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.jsonindex bef3dcf44..c4fede69e 100644--- a/integrations/sie_ts_llamaindex/package.json+++ b/integrations/sie_ts_llamaindex/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-llamaindex",- "version": "0.6.2",+ "version": "0.6.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.tomlindex ef60fb953..41a89e67f 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.2"+version = "0.6.3"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/package.json b/package.jsonindex 66fdee903..58cfc2a0d 100644--- a/package.json+++ b/package.json@@ -26,7 +26,6 @@"protobufjs": ">=7.5.8","qs": ">=6.15.2","tar": ">=7.5.11",- "thrift": ">=0.23.0","uuid": ">=11.1.1","vite": "^6.4.2","vitest": "^4.1.0",diff --git a/packages/sie_config/pyproject.toml b/packages/sie_config/pyproject.tomlindex 0293d7e80..b9a5add15 100644--- a/packages/sie_config/pyproject.toml+++ b/packages/sie_config/pyproject.toml@@ -12,7 +12,7 @@ dependencies = ["orjson>=3.10,<4","prometheus-client>=0.20,<1","pyyaml>=6,<7",- "sie-sdk>=0.1",+ "sie-sdk[storage]>=0.1","typer>=0.14,<1","rich>=13,<14",]diff --git a/packages/sie_config/src/sie_config/config_store.py b/packages/sie_config/src/sie_config/config_store.pyindex 7e2305b40..6442558f7 100644--- a/packages/sie_config/src/sie_config/config_store.py+++ b/packages/sie_config/src/sie_config/config_store.py@@ -11,19 +11,20 @@ logger = logging.getLogger(__name__)class ConfigStore:- """Config store backed by local filesystem, S3, or GCS.+ """Config store backed by local filesystem, S3, GCS, or Azure Blob.The backend is auto-detected from the base_dir URL scheme:- Local path (e.g., /tmp/config-store) -> LocalBackend- s3://bucket/prefix -> S3Backend- gs://bucket/prefix -> GCSBackend+ - abfs(s)://[email protected]/prefix -> AzureBlobBackendLayout (same for all backends):{base_dir}/models/{model_id}.yaml # Per-model config files{base_dir}/epoch # Monotonic counter (plain text integer)Args:- base_dir: Root path for config storage. Accepts local path, s3://, or gs://.+ base_dir: Root path for config storage. Accepts local path, s3://, gs://, abfs://, or abfss://."""def __init__(self, base_dir: str) -> None:diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lockindex 2b903e930..37717a435 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -1887,6 +1887,7 @@ dependencies = ["bytes","chrono","futures",+ "httparse","humantime","hyper","itertools 0.13.0",@@ -2959,7 +2960,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-gateway"-version = "0.6.2"+version = "0.6.3"dependencies = ["arc-swap","async-nats",diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex bad623261..0a3b22a9b 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.2"+version = "0.6.3"edition = "2021"publish = false@@ -68,8 +68,8 @@ fs2 = "0.4"serde_bytes = "0.11"percent-encoding = "2"-# Cloud config store backends (opt-in)-object_store = { version = "0.11", optional = true, features = ["aws", "gcp"] }+# Cloud payload store backends (opt-in)+object_store = { version = "0.11", optional = true, features = ["aws", "gcp", "azure"] }url = { version = "2", optional = true }utoipa = "5.4.0"diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.mdindex df0db4a50..4d0cff023 100644--- a/packages/sie_gateway/README.md+++ b/packages/sie_gateway/README.md@@ -20,7 +20,7 @@ See [`docs/architecture-guide.md`](docs/architecture-guide.md) for the authorita- **Auth** — static-token auth via `SIE_AUTH_TOKEN[S]`; config write idempotency belongs to `sie-config`- **Demand tracking and readiness** — provisioning responses, pending-demand metrics, and worker ack checks after config changes- **Observability** — Prometheus metrics, structured logging, audit middleware, and HTML/WebSocket status surfaces-- **Optional cloud storage** — `cloud-storage` feature enables S3/GCS payload backends; the Docker build enables it+- **Optional cloud storage** — `cloud-storage` feature enables S3/GCS/Azure Blob payload backends; the Docker build enables it## Quick Start@@ -111,7 +111,7 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio| `SIE_GATEWAY_GPU_ALIASES` | | JSON map of request aliases to canonical machine profiles || `SIE_BUNDLES_DIR` | `bundles` | Optional bundle filesystem seed. Unset in default Helm deploys: the gateway pulls bundles from `sie-config` via `GET /v1/configs/bundles{,/{id}}` at startup and the registry's filesystem reload is a no-op. Only set by the `gateway.embeddedConfigs` / `gateway.configMap` overlays which mount a ConfigMap at `/configs/bundles`. || `SIE_MODELS_DIR` | `models` | Optional model filesystem seed. Same semantics as `SIE_BUNDLES_DIR`: unset in default deploys, runtime model writes always go to `sie-config` and the gateway replays them via `GET /v1/configs/export`. |-| `SIE_PAYLOAD_STORE_URL` | unset | Shared payload offload store path. When unset, large-payload offload is disabled. Queue deployments should use `s3://` or `gs://`; local filesystem paths only work when gateway and workers share the same path |+| `SIE_PAYLOAD_STORE_URL` | unset | Shared payload offload store path. When unset, large-payload offload is disabled. Queue deployments should use `s3://`, `gs://`, `abfs://`, or `abfss://`; local filesystem paths only work when gateway and workers share the same path |## API Endpointsdiff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 53ee78d8c..7d394c388 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -361,8 +361,9 @@ Backend selection is URL-driven (`sie_sdk.storage.get_storage_backend`):- Local filesystem (default).- `s3://bucket/prefix` — S3.- `gs://bucket/prefix` — GCS.+- `abfs(s)://[email protected]/prefix` — Azure Blob / ADLS Gen2.-The **local** backend's `write_text` is atomic: it writes via `tempfile.mkstemp` in the same directory as the destination, `fsync`s, then `Path.replace`s. A mid-write crash cannot leave the destination truncated or empty. The cloud backends (`S3Backend`, `GCSBackend`) implement `write_text` as a single `put_object` / `upload_from_string`; object-store PUTs are last-writer-wins and observably atomic at the object level, but they do not use the tempfile + replace pattern. The atomicity property matters most for the `epoch` file: `ConfigStore.read_epoch` silently maps a malformed or empty integer to `0`, so a zero-byte epoch file would collapse the drift-detection mechanism (`remote == local == 0` would read as "in sync forever").+The **local** backend's `write_text` is atomic: it writes via `tempfile.mkstemp` in the same directory as the destination, `fsync`s, then `Path.replace`s. A mid-write crash cannot leave the destination truncated or empty. The cloud backends (`S3Backend`, `GCSBackend`, `AzureBlobBackend`) implement `write_text` as a single-object write; object-store writes are last-writer-wins and observably atomic at the object level, but they do not use the tempfile + replace pattern. The atomicity property matters most for the `epoch` file: `ConfigStore.read_epoch` silently maps a malformed or empty integer to `0`, so a zero-byte epoch file would collapse the drift-detection mechanism (`remote == local == 0` would read as "in sync forever").`ConfigStore.increment_epoch` is a naive read-modify-write. Its single-writer assumption is enforced at the FastAPI layer by the per-app write lock (§3).diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 61813b9b1..8665a2d11 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -186,10 +186,10 @@"type": "object"},"ChatCompletionMessage": {- "description": "One chat message in an OpenAI chat-completions request.\n\nPer the strict allow-list parser, ``content`` is either a\nplain string OR a list of text-only content parts (``{type:\"text\"|\"input_text\",\ntext:\"...\"}``); ``image_url`` and ``input_image`` parts reject with 400\n``unsupported_field`` until a vision-capable model ships. Assistant\nmessages that carry ``tool_calls`` may set ``content: null``.\n\n``tool_calls`` is accepted only on ``role:\"assistant\"`` messages; each\nentry has the validated shape ``{id, type:\"function\", function:{name, arguments}}``\nwhere ``arguments`` is a JSON-encoded string (OpenAI convention).\n``tool_call_id`` is required on ``role:\"tool\"`` messages and rejected\non every other role.",+ "description": "One chat message in an OpenAI chat-completions request.\n\nPer the strict allow-list parser, ``content`` is either a\nplain string OR a list of content parts (``{type:\"text\"|\"input_text\",\ntext:\"...\"}``). ``image_url`` / ``input_image`` parts carrying a base64\n``data:`` URI are accepted for generation models declaring ``inputs.image`` (non-vision\nmodels reject 400 ``unsupported_field``; remote URLs reject 400\n``invalid_request``). Assistant messages that carry ``tool_calls`` may set\n``content: null``.\n\n``tool_calls`` is accepted only on ``role:\"assistant\"`` messages; each\nentry has the validated shape ``{id, type:\"function\", function:{name, arguments}}``\nwhere ``arguments`` is a JSON-encoded string (OpenAI convention).\n``tool_call_id`` is required on ``role:\"tool\"`` messages and rejected\non every other role.","properties": {"content": {- "description": "Either a string or an array of text-only content parts (`{type:\"text\"|\"input_text\", text:\"...\"}`). Image content parts (`image_url` / `input_image`) reject with 400 unsupported_field until a vision-capable model ships. May be `null` on a `role:\"assistant\"` message that carries `tool_calls`.",+ "description": "Either a string or an array of content parts (`{type:\"text\"|\"input_text\", text:\"...\"}`). Image parts (`image_url` / `input_image`) carrying a base64 `data:` URI are accepted for generation models that declare `inputs.image`; non-vision models reject with 400 unsupported_field and remote (non-`data:`) URLs reject with 400 invalid_request. May be `null` on a `role:\"assistant\"` message that carries `tool_calls`.","oneOf": [{"type": "string"@@ -197,13 +197,31 @@{"items": {"properties": {+ "image_url": {+ "description": "Image payload for `image_url` / `input_image` parts: a base64 `data:` URI, either as a bare string or as `{ \"url\": \"data:...\" }`. Remote (non-`data:`) URLs reject with 400 invalid_request.",+ "oneOf": [+ {+ "type": "string"+ },+ {+ "properties": {+ "url": {+ "type": "string"+ }+ },+ "type": "object"+ }+ ]+ },"text": {"type": "string"},"type": {"enum": ["text",- "input_text"+ "input_text",+ "image_url",+ "input_image"],"type": "string"}@@ -2550,7 +2568,7 @@"type": "object"},"ResponsesRequest": {- "description": "OpenAI-compatible ``POST /v1/responses`` request (Responses MVP).\n\n**Strict allow-list**: unknown fields reject with 400\n``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.\n\n**Known-rejected fields**:\n- ``tools`` / ``tool_choice`` — rejected with 400 ``unsupported_field``.\n- ``previous_response_id`` — rejected with 400 ``unsupported_field``\n (Responses MVP is stateless single-turn).\n- ``reasoning`` — rejected with 400 ``unsupported_field``.\n- ``background`` — rejected with 400 ``unsupported_field``.\n- ``metadata`` — rejected with 400 ``unsupported_field``.\n- ``instructions`` — rejected with 400 ``unsupported_field``.\n- ``stream: true`` — rejected with 400 ``unsupported_field`` (SSE on\n Responses is deferred; use ``stream: false`` or omit).\n- Multimodal ``image_url`` / ``input_image`` content parts on the array\n form — rejected with 400 ``unsupported_field`` until a VL profile ships.",+ "description": "OpenAI-compatible ``POST /v1/responses`` request (Responses MVP).\n\n**Strict allow-list**: unknown fields reject with 400\n``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.\n\n**Known-rejected fields**:\n- ``tools`` / ``tool_choice`` — rejected with 400 ``unsupported_field``.\n- ``previous_response_id`` — rejected with 400 ``unsupported_field``\n (Responses MVP is stateless single-turn).\n- ``reasoning`` — rejected with 400 ``unsupported_field``.\n- ``background`` — rejected with 400 ``unsupported_field``.\n- ``metadata`` — rejected with 400 ``unsupported_field``.\n- ``instructions`` — rejected with 400 ``unsupported_field``.\n- ``stream: true`` — rejected with 400 ``unsupported_field`` (SSE on\n Responses is deferred; use ``stream: false`` or omit).\n- Multimodal ``image_url`` / ``input_image`` content parts on the array\n form — rejected with 400 ``unsupported_field``: the Responses surface is\n text-only. (Vision input is supported on ``/v1/chat/completions``.)","properties": {"input": {"description": "Either a string prompt OR an array of `{role, content}` messages (array-input support). Array form: `role` is one of `\"system\" | \"user\" | \"assistant\" | \"developer\"` (\"developer\" normalizes to \"system\"). `content` is a string or an array of text-only content parts; image parts (`image_url` / `input_image`) reject with 400 unsupported_field. The array must not be empty.",@@ -2890,7 +2908,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.2"+ "version": "0.6.3"},"openapi": "3.1.0","paths": {@@ -3096,7 +3114,7 @@},"/v1/chat/completions": {"post": {- "description": "OpenAI-compatible chat completions. Strict allow-list parser: unknown top-level fields reject with 400 `unsupported_field`. Streaming (`stream: true`) is supported and emits SSE `chat.completion.chunk` events; `n > 1` streaming fans candidates out as per-`choice_index` delta chunks with per-choice closure chunks (each carrying `finish_reason`) before the single global `[DONE]`. Content is either a string or an array of text-only content parts; image content parts (`image_url` / `input_image`) reject with 400 `unsupported_field`. `lora_adapter` is forwarded to the worker as a top-level `lora_path` generation kwarg.",+ "description": "OpenAI-compatible chat completions. Strict allow-list parser: unknown top-level fields reject with 400 `unsupported_field`. Streaming (`stream: true`) is supported and emits SSE `chat.completion.chunk` events; `n > 1` streaming fans candidates out as per-`choice_index` delta chunks with per-choice closure chunks (each carrying `finish_reason`) before the single global `[DONE]`. Content is either a string or an array of content parts; image parts (`image_url` / `input_image`) with a base64 `data:` URI are accepted for generation models declaring `inputs.image` (non-vision/encode-only models reject 400 `unsupported_field`; remote URLs reject 400 `invalid_request`). `lora_adapter` is forwarded to the worker as a top-level `lora_path` generation kwarg.","operationId": "proxy_chat","parameters": [{diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex 5be02a54a..23054f455 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -93,7 +93,8 @@ pub struct Config {// share one admin secret in-cluster.pub config_service_token: Option<String>,- // Payload store (local path, s3://bucket/prefix, or gs://bucket/prefix)+ // Payload store (local path, s3://bucket/prefix, gs://bucket/prefix, or+ // abfs(s)://[email protected]/prefix)pub payload_store_url: String,}diff --git a/packages/sie_gateway/src/discovery/nats_health.rs b/packages/sie_gateway/src/discovery/nats_health.rsindex 3b239f2ab..179221dd6 100644--- a/packages/sie_gateway/src/discovery/nats_health.rs+++ b/packages/sie_gateway/src/discovery/nats_health.rs@@ -50,10 +50,13 @@ impl NatsHealthManager {loop {tokio::select! {_ = interval.tick() => {- let unhealthy = registry.check_heartbeats().await;- for url in &unhealthy {+ let sweep = registry.check_heartbeats().await;+ for url in &sweep.unhealthy {warn!(url = %url, "worker missed heartbeat (NATS)");}+ for url in &sweep.evicted {+ info!(url = %url, "evicted stale worker after missed heartbeats (NATS)");+ }}_ = cancel_rx.changed() => {return;@@ -113,6 +116,14 @@ async fn handle_nats_message(registry: &WorkerRegistry, msg: async_nats::Messagereturn;};+ handle_status_message(registry, subject, status).await;+}++async fn handle_status_message(+ registry: &WorkerRegistry,+ subject: &str,+ status: WorkerStatusMessage,+) {// Extract worker URL from the message or subject// The subject format is sie.health.<worker_identifier>// The worker URL should be in the message payload or derivable from the worker name@@ -126,6 +137,15 @@ async fn handle_nats_message(registry: &WorkerRegistry, msg: async_nats::Messagereturn;};+ if status.terminated {+ if registry.remove_worker(&worker_url).await {+ info!(url = %worker_url, subject = %subject, "worker removed via NATS tombstone");+ } else {+ info!(url = %worker_url, subject = %subject, "NATS tombstone for unknown worker ignored");+ }+ return;+ }+let became_healthy = registry.update_worker(&worker_url, status).await;if became_healthy {info!(url = %worker_url, subject = %subject, "worker became healthy via NATS");@@ -156,3 +176,44 @@ fn extract_worker_url_from_status(status: &WorkerStatusMessage, subject: &str) -None}++#[cfg(test)]+mod tests {+ use std::time::Duration;++ use super::*;++ fn status(ready: bool) -> WorkerStatusMessage {+ WorkerStatusMessage {+ name: "worker-1".into(),+ ready,+ gpu_count: 1,+ machine_profile: "rtx6000".into(),+ pool_name: "default".into(),+ bundle: "sglang".into(),+ bundle_config_hash: "hash".into(),+ loaded_models: vec![],+ models: vec![],+ gpus: vec![],+ queue_depth: None,+ memory_used_bytes: None,+ memory_total_bytes: None,+ saturated: false,+ terminated: false,+ }+ }++ #[tokio::test]+ async fn tombstone_removes_registered_worker() {+ let registry = WorkerRegistry::new(Duration::from_secs(15), None);+ handle_status_message(®istry, "sie.health.worker-1", status(true)).await;+ assert_eq!(registry.workers().await.len(), 1);++ let mut tombstone = status(false);+ tombstone.terminated = true;+ handle_status_message(®istry, "sie.health.worker-1", tombstone).await;++ assert!(registry.workers().await.is_empty());+ assert!(registry.healthy_workers().await.is_empty());+ }+}diff --git a/packages/sie_gateway/src/discovery/ws_health.rs b/packages/sie_gateway/src/discovery/ws_health.rsindex 8890444a6..b2e5e5522 100644--- a/packages/sie_gateway/src/discovery/ws_health.rs+++ b/packages/sie_gateway/src/discovery/ws_health.rs@@ -36,10 +36,13 @@ impl WsHealthManager {let mut interval = tokio::time::interval(Duration::from_secs(5));loop {interval.tick().await;- let unhealthy = registry.check_heartbeats().await;- for url in &unhealthy {+ let sweep = registry.check_heartbeats().await;+ for url in &sweep.unhealthy {warn!(url = %url, "worker missed heartbeat");}+ for url in &sweep.evicted {+ info!(url = %url, "evicted stale worker after missed heartbeats");+ }}});}diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex e3c1c60c8..d403259c4 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -801,6 +801,7 @@ mod tests {gpus: Vec::new(),pool_name: String::new(),saturated: false,+ terminated: false,}}diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 1ac8e5e11..38756b984 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -554,6 +554,7 @@ mod route_tests {gpus: Vec::new(),pool_name: String::new(),saturated: false,+ terminated: false,}}diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 6a963c242..6aeceb93c 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -2585,6 +2585,64 @@ enum ChatParamsResult {Err(Response),}+/// Extract an inline OpenAI ``image_url`` value into ``(base64, format)``.+///+/// Only base64 ``data:`` URIs are accepted — the gateway never fetches+/// remote ``http(s)`` URLs (SSRF surface + a blocking network call on the+/// request path; clients inline images as data URIs, which the SDK does).+/// The ``url`` may be a bare string or the ``{"url": "data:..."}`` object+/// shape.+///+/// Returns the **base64 payload string** (validated to decode and be+/// non-empty) plus the format hint parsed from the MIME subtype. We keep+/// the base64 *string* rather than raw bytes because the work item travels+/// through the sidecar's ``serde_json::Value``, which can't carry a msgpack+/// ``bin`` — see :struct:`ChatImage`. The worker base64-decodes it.+fn decode_image_data_uri(value: &serde_json::Value) -> Result<(String, Option<String>), String> {+ use base64::Engine as _;++ let url = match value {+ serde_json::Value::String(s) => s.as_str(),+ serde_json::Value::Object(o) => o+ .get("url")+ .and_then(|v| v.as_str())+ .ok_or_else(|| "image_url.url must be a non-empty string".to_string())?,+ _ => return Err("image_url must be a string or an object with a 'url'".to_string()),+ };+ if url.is_empty() {+ return Err("image_url.url must be a non-empty string".to_string());+ }+ let rest = url+ .strip_prefix("data:")+ .ok_or_else(|| "image content must be an inline base64 'data:' URI; remote URL fetching is not supported".to_string())?;+ let (header, payload) = rest+ .split_once(',')+ .ok_or_else(|| "malformed image data URI (missing ',')".to_string())?;+ let mut params = header.split(';');+ let mime = params.next().unwrap_or("");+ if !mime.starts_with("image/") {+ // Reject ``data:text/...`` and ``data:;base64,...`` — only image media types.+ return Err("image data URI must have an image/* media type".to_string());+ }+ if !params.any(|p| p == "base64") {+ return Err("image data URI must be base64-encoded".to_string());+ }+ let format = mime+ .split_once('/')+ .map(|(_, sub)| sub.trim().to_ascii_lowercase())+ .filter(|s| !s.is_empty());+ let payload = payload.trim();+ // Validate at the edge (reject malformed base64 / empty image) so the+ // client gets a clean 400, but transport the base64 string itself.+ let decoded = base64::engine::general_purpose::STANDARD+ .decode(payload)+ .map_err(|e| format!("invalid base64 image data: {e}"))?;+ if decoded.is_empty() {+ return Err("image data URI decoded to empty bytes".to_string());+ }+ Ok((payload.to_string(), format))+}+/// Validate an OpenAI ``/v1/chat/completions`` request body against/// the chat-completions supported subset.///@@ -2688,6 +2746,11 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {}};let mut messages: Vec<publisher::ChatMessage> = Vec::with_capacity(messages_arr.len());+ // Cap total images per request so an oversized vision request fails here —+ // before decoding every part and publishing the work — rather than at the+ // worker. Mirrors the worker's ``_MAX_IMAGES_PER_REQUEST``.+ const MAX_IMAGES_PER_REQUEST: usize = 16;+ let mut total_images: usize = 0;// ``tool`` is allowed so the multi-turn tool-use loop works: the// caller replays the assistant's tool_call request and the tool// result back into ``messages`` for the model's final answer.@@ -2876,11 +2939,23 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {// ``content`` is required EXCEPT on an assistant message that// carries tool_calls (OpenAI sends content:null there). Tool and// normal messages still require a string content.+ // Images decoded from this message's ``image_url`` content parts.+ // Whether the model may actually accept them is gated after model+ // resolution (mirrors the grammar/tools capability gates) — parsing+ // here is capability-agnostic because the model isn't resolved yet.+ let mut message_images: Vec<publisher::ChatImage> = Vec::new();+ // Ordered text↔image layout, preserving the parts' original order so+ // the worker can interleave placeholders (vs. images-first). Only the+ // placeholder positions depend on this; bytes still ride+ // ``message_images`` in order. Populated only for the Array branch and+ // only forwarded when the message has ≥1 image (#1294).+ let mut content_parts: Vec<publisher::ContentPart> = Vec::new();let content = match item_obj.get("content") {Some(serde_json::Value::String(c)) => c.clone(),- // OpenAI multimodal content-parts. Concatenate ``text`` parts;- // ``image_url`` is rejected because no vision-capable generation- // model is configured (the contract is ready for when one lands).+ // OpenAI multimodal content-parts. Concatenate ``text`` parts and+ // decode ``image_url`` parts into ``message_images`` (the vision+ // capability gate runs after model resolution); record the ordered+ // layout in ``content_parts`` so interleaving survives to the worker.//// M13: parts with missing/non-string ``text`` (or no ``type``)// previously slipped through via ``filter_map`` — they now@@ -2909,7 +2984,11 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {};match ptype {"text" | "input_text" => match part_obj.get("text") {- Some(serde_json::Value::String(t)) => text.push_str(t),+ Some(serde_json::Value::String(t)) => {+ text.push_str(t);+ content_parts+ .push(publisher::ContentPart::Text { text: t.clone() });+ }Some(_) => {return bad(&format!("messages[{idx}].content[{pi}].text must be a string"),@@ -2928,13 +3007,41 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {}},"image_url" | "input_image" => {- return bad(- &format!(- "messages[{idx}].content[{pi}]: image content is not supported (no vision-capable model is configured)"- ),- Some(&format!("messages[{idx}].content[{pi}].type")),- oai_code::UNSUPPORTED_FIELD,- );+ let Some(image_url) = part_obj.get("image_url") else {+ return bad(+ &format!(+ "messages[{idx}].content[{pi}].image_url is required for image content parts"+ ),+ Some(&format!("messages[{idx}].content[{pi}].image_url")),+ oai_code::INVALID_REQUEST,+ );+ };+ total_images += 1;+ if total_images > MAX_IMAGES_PER_REQUEST {+ return bad(+ &format!(+ "too many images ({total_images}); maximum is {MAX_IMAGES_PER_REQUEST} per request"+ ),+ Some(&format!("messages[{idx}].content[{pi}].image_url")),+ oai_code::INVALID_REQUEST,+ );+ }+ match decode_image_data_uri(image_url) {+ Ok((data, format)) => {+ // Large work items (multi-MB images) are offloaded to+ // the object store by ``publish_generate`` and bounded+ // by the request body cap, so no inline-size gate here.+ message_images.push(publisher::ChatImage { data, format });+ content_parts.push(publisher::ContentPart::Image);+ }+ Err(reason) => {+ return bad(+ &format!("messages[{idx}].content[{pi}]: {reason}"),+ Some(&format!("messages[{idx}].content[{pi}].image_url")),+ oai_code::INVALID_REQUEST,+ );+ }+ }}other => {return bad(@@ -2962,11 +3069,25 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {);}};+ let has_images = !message_images.is_empty();messages.push(publisher::ChatMessage {role,content,tool_calls,tool_call_id,+ images: if has_images {+ Some(message_images)+ } else {+ None+ },+ // Forward the ordered layout only for multimodal messages — a+ // text-only message keeps ``content_parts: None`` and renders from+ // ``content`` as before (no wire bloat, no behavior change).+ content_parts: if has_images {+ Some(content_parts)+ } else {+ None+ },});}@@ -4669,6 +4790,38 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res.into_response();}}+ // Vision capability gate. ``image_url`` content parts were decoded+ // into ``ChatMessage.images`` capability-agnostically (the model+ // wasn't resolved yet); reject here unless the model YAML declares+ // ``inputs.image: true``. Mirrors the tools/grammar gates.+ let has_images = params+ .messages+ .iter()+ .any(|m| m.images.as_ref().is_some_and(|imgs| !imgs.is_empty()));+ if has_images {+ // Vision *generation* requires both image input AND a generation+ // task — ``inputs.image`` alone is also set by encode-only image+ // models (CLIP/SigLIP), which must not accept a chat image request.+ let image_supported = info.info_extras.supports_vision_generation();+ if !image_supported {+ metrics::record_rejected_request_for_pool(+ "unknown",+ "",+ &bundle,+ "vision_capability",+ );+ return (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ format!("Model '{model_name}' does not support image input"),+ oai_type::INVALID_REQUEST,+ Some("messages"),+ oai_code::UNSUPPORTED_FIELD,+ )),+ )+ .into_response();+ }+ }} else if params.grammar.is_some() {// No model info means we cannot determine grammar capabilities;// safer to reject than to publish work the model cannot honour.@@ -4698,6 +4851,24 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res)),).into_response();+ } else if params+ .messages+ .iter()+ .any(|m| m.images.as_ref().is_some_and(|imgs| !imgs.is_empty()))+ {+ // Same defensive rejection for image input when the model is+ // unknown — safer than publishing vision work the model can't honour.+ metrics::record_rejected_request_for_pool("unknown", "", &bundle, "vision_capability");+ return (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ format!("Model '{model_name}' does not support image input (no model info)"),+ oai_type::INVALID_REQUEST,+ Some("messages"),+ oai_code::UNSUPPORTED_FIELD,+ )),+ )+ .into_response();}// -- headers → GPU/pool routing, effective-pool selection, publisher bind.@@ -5639,6 +5810,10 @@ fn responses_params_from_json(body: &serde_json::Value) -> ResponsesParamsResultcontent,tool_calls: None,tool_call_id: None,+ // Responses-API path is text-only for now; vision arrives+ // via /v1/chat/completions (the cut-your-bill skill surface).+ images: None,+ content_parts: None,});}publisher::GenerateInput::Messages { messages }@@ -11678,6 +11853,7 @@ mod tests {memory_used_bytes: None,memory_total_bytes: None,saturated: false,+ terminated: false,}}@@ -12797,7 +12973,9 @@ mod tests {}#[tokio::test]- async fn test_chat_params_rejects_image_content_part() {+ async fn test_chat_params_rejects_remote_image_url() {+ // Remote (http/https) image URLs are not fetched at the gateway —+ // clients must inline images as base64 data URIs.let mut body = _chat_body_min("m");body["messages"] = serde_json::json!([{"role": "user", "content": [@@ -12806,10 +12984,125 @@ mod tests {]}]);let v = _expect_chat_err(body).await;- assert_eq!(v["error"]["code"], "unsupported_field");- // M13: the rejection point is now precise — the offending part's- // ``.type`` rather than the whole content array.- assert_eq!(v["error"]["param"], "messages[0].content[1].type");+ assert_eq!(v["error"]["code"], "invalid_request");+ assert_eq!(v["error"]["param"], "messages[0].content[1].image_url");+ }++ #[test]+ fn test_chat_params_accepts_image_data_uri() {+ // A base64 ``data:`` URI is decoded into ``ChatMessage.images``; the+ // text part lands in ``content``. (Capability gating happens later in+ // ``proxy_chat`` after model resolution, not here.)+ let mut body = _chat_body_min("m");+ body["messages"] = serde_json::json!([+ {"role": "user", "content": [+ {"type": "text", "text": "what is this?"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,aGVsbG8="}},+ ]}+ ]);+ let p = _expect_chat_ok(body);+ assert_eq!(p.messages[0].content, "what is this?");+ let images = p.messages[0].images.as_ref().expect("images populated");+ assert_eq!(images.len(), 1);+ // ``data`` is the base64 payload string (decodes to b"hello"); kept as+ // a string so it survives the sidecar's serde_json::Value.+ assert_eq!(images[0].data, "aGVsbG8=");+ assert_eq!(images[0].format.as_deref(), Some("png"));+ }++ #[test]+ fn test_chat_params_preserves_interleaved_content_parts() {+ // #1294: text↔image interleaving must survive into ``content_parts`` in+ // the original order, while ``images`` stays a flat in-order list and+ // ``content`` stays the concatenated text (back-compat).+ let mut body = _chat_body_min("m");+ body["messages"] = serde_json::json!([+ {"role": "user", "content": [+ {"type": "text", "text": "Page 1:"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,aW1nQQ=="}},+ {"type": "text", "text": "Page 2:"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,aW1nQg=="}},+ {"type": "text", "text": "which has a cat?"},+ ]}+ ]);+ let p = _expect_chat_ok(body);+ // Flat fields unchanged: concatenated text + in-order image bytes.+ assert_eq!(p.messages[0].content, "Page 1:Page 2:which has a cat?");+ let images = p.messages[0].images.as_ref().expect("images populated");+ assert_eq!(images.len(), 2);+ assert_eq!(images[0].data, "aW1nQQ==");+ assert_eq!(images[1].data, "aW1nQg==");+ // Ordered layout records the interleaving the worker renders in place.+ let parts = p.messages[0]+ .content_parts+ .as_ref()+ .expect("content_parts populated for vision msg");+ assert_eq!(parts.len(), 5);+ assert!(matches!(&parts[0], publisher::ContentPart::Text { text } if text == "Page 1:"));+ assert!(matches!(parts[1], publisher::ContentPart::Image));+ assert!(matches!(&parts[2], publisher::ContentPart::Text { text } if text == "Page 2:"));+ assert!(matches!(parts[3], publisher::ContentPart::Image));+ assert!(+ matches!(&parts[4], publisher::ContentPart::Text { text } if text == "which has a cat?")+ );+ }++ #[test]+ fn test_chat_params_text_only_has_no_content_parts() {+ // Text-only messages must NOT carry content_parts (no wire bloat, no+ // behavior change) — the images-first/legacy render path stays in use.+ let mut body = _chat_body_min("m");+ body["messages"] = serde_json::json!([{"role": "user", "content": "hello"}]);+ let p = _expect_chat_ok(body);+ assert!(p.messages[0].content_parts.is_none());+ // A multipart array with NO image also stays content_parts-free.+ let mut body2 = _chat_body_min("m");+ body2["messages"] = serde_json::json!([+ {"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}]}+ ]);+ let p2 = _expect_chat_ok(body2);+ assert_eq!(p2.messages[0].content, "ab");+ assert!(p2.messages[0].content_parts.is_none());+ }++ #[tokio::test]+ async fn test_chat_params_rejects_too_many_images() {+ let mut body = _chat_body_min("m");+ let mut parts = vec![serde_json::json!({"type": "text", "text": "describe"})];+ for _ in 0..17 {+ parts.push(serde_json::json!({+ "type": "image_url",+ "image_url": {"url": "data:image/png;base64,aGk="}+ }));+ }+ body["messages"] = serde_json::json!([{"role": "user", "content": parts}]);+ let v = _expect_chat_err(body).await;+ assert_eq!(v["error"]["code"], "invalid_request");+ assert!(v["error"]["message"]+ .as_str()+ .unwrap()+ .contains("too many images"));+ }++ #[test]+ fn test_decode_image_data_uri_variants() {+ // Returns the base64 payload string + format. Bare-string url form ++ // object form both work.+ let (data, fmt) =+ decode_image_data_uri(&serde_json::json!("data:image/jpeg;base64,aGk=")).unwrap();+ assert_eq!(data, "aGk="); // decodes to b"hi"+ assert_eq!(fmt.as_deref(), Some("jpeg"));+ let (data2, _) =+ decode_image_data_uri(&serde_json::json!({"url": "data:image/png;base64,aGVsbG8="}))+ .unwrap();+ assert_eq!(data2, "aGVsbG8="); // decodes to b"hello"+ // Remote URL, missing base64 marker, and bad base64 all reject.+ assert!(decode_image_data_uri(&serde_json::json!("https://x/y.png")).is_err());+ assert!(decode_image_data_uri(&serde_json::json!("data:image/png,aGk=")).is_err());+ assert!(decode_image_data_uri(&serde_json::json!("data:image/png;base64,!!!")).is_err());+ // Non-image media types reject (must be image/*).+ assert!(decode_image_data_uri(&serde_json::json!("data:text/plain;base64,aGk=")).is_err());+ assert!(decode_image_data_uri(&serde_json::json!("data:;base64,aGk=")).is_err());}#[test]diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rsindex b83503721..dd19c469d 100644--- a/packages/sie_gateway/src/main.rs+++ b/packages/sie_gateway/src/main.rs@@ -512,7 +512,7 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {match nats_manager.get_client().await {Some(client) => {let jetstream = async_nats::jetstream::new(client.clone());- let payload_store = create_payload_store(&config.payload_store_url).await;+ let payload_store = create_payload_store(&config.payload_store_url).await?;let publisher = Arc::new(queue::publisher::WorkPublisher::new(jetstream,nats_manager.router_id().to_string(),diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex acf571a71..40b423663 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -617,10 +617,12 @@ fn patch_chat_message_schema(value: &mut Value) {properties.insert("content".to_string(),json!({- "description": "Either a string or an array of text-only content parts \- (`{type:\"text\"|\"input_text\", text:\"...\"}`). Image content \- parts (`image_url` / `input_image`) reject with 400 \- unsupported_field until a vision-capable model ships. May be \+ "description": "Either a string or an array of content parts \+ (`{type:\"text\"|\"input_text\", text:\"...\"}`). Image parts \+ (`image_url` / `input_image`) carrying a base64 `data:` URI are \+ accepted for generation models that declare `inputs.image`; non-vision models \+ reject with 400 unsupported_field and remote (non-`data:`) URLs \+ reject with 400 invalid_request. May be \`null` on a `role:\"assistant\"` message that carries `tool_calls`.","oneOf": [{"type": "string"},@@ -630,8 +632,15 @@ fn patch_chat_message_schema(value: &mut Value) {"type": "object","required": ["type"],"properties": {- "type": {"type": "string", "enum": ["text", "input_text"]},+ "type": {"type": "string", "enum": ["text", "input_text", "image_url", "input_image"]},"text": {"type": "string"},+ "image_url": {+ "description": "Image payload for `image_url` / `input_image` parts: a base64 `data:` URI, either as a bare string or as `{ \"url\": \"data:...\" }`. Remote (non-`data:`) URLs reject with 400 invalid_request.",+ "oneOf": [+ {"type": "string"},+ {"type": "object", "properties": {"url": {"type": "string"}}},+ ],+ },},},},@@ -842,9 +851,11 @@ fn patch_chat_completion_paths(value: &mut Value) {SSE `chat.completion.chunk` events; `n > 1` streaming fans candidates \out as per-`choice_index` delta chunks with per-choice closure chunks \(each carrying `finish_reason`) before the single global `[DONE]`. \- Content is either a string or an array of text-only content parts; image \- content parts (`image_url` / `input_image`) reject with 400 \- `unsupported_field`. `lora_adapter` is forwarded to the worker as a \+ Content is either a string or an array of content parts; image parts \+ (`image_url` / `input_image`) with a base64 `data:` URI are accepted for \+ generation models declaring `inputs.image` (non-vision/encode-only models reject 400 \+ `unsupported_field`; remote URLs reject 400 `invalid_request`). \+ `lora_adapter` is forwarded to the worker as a \top-level `lora_path` generation kwarg."),);@@ -1441,10 +1452,12 @@ pub struct GenerateResponse {/// One chat message in an OpenAI chat-completions request.////// Per the strict allow-list parser, ``content`` is either a-/// plain string OR a list of text-only content parts (``{type:"text"|"input_text",-/// text:"..."}``); ``image_url`` and ``input_image`` parts reject with 400-/// ``unsupported_field`` until a vision-capable model ships. Assistant-/// messages that carry ``tool_calls`` may set ``content: null``.+/// plain string OR a list of content parts (``{type:"text"|"input_text",+/// text:"..."}``). ``image_url`` / ``input_image`` parts carrying a base64+/// ``data:`` URI are accepted for generation models declaring ``inputs.image`` (non-vision+/// models reject 400 ``unsupported_field``; remote URLs reject 400+/// ``invalid_request``). Assistant messages that carry ``tool_calls`` may set+/// ``content: null``.////// ``tool_calls`` is accepted only on ``role:"assistant"`` messages; each/// entry has the validated shape ``{id, type:"function", function:{name, arguments}}``@@ -1458,8 +1471,10 @@ pub struct ChatCompletionMessage {/// newer alias for ``system`` and is normalized to ``system``. Any other/// role rejects with 400 ``invalid_request``.pub role: String,- /// Either a string or an array of text-only content parts. Image content- /// parts (``image_url`` / ``input_image``) reject with 400 ``unsupported_field``.+ /// Either a string or an array of content parts. ``image_url`` /+ /// ``input_image`` parts with a base64 ``data:`` URI are accepted for+ /// vision-capable generation models (``inputs.image`` + a generate task); non-vision/encode-only models reject 400+ /// ``unsupported_field`` and remote URLs reject 400 ``invalid_request``./// May be ``null`` on an assistant message that carries ``tool_calls``.pub content: Value,/// OpenAI tool-call replay on ``role:"assistant"`` messages.@@ -1759,7 +1774,8 @@ pub struct CompletionsRequest {/// - ``stream: true`` — rejected with 400 ``unsupported_field`` (SSE on/// Responses is deferred; use ``stream: false`` or omit)./// - Multimodal ``image_url`` / ``input_image`` content parts on the array-/// form — rejected with 400 ``unsupported_field`` until a VL profile ships.+/// form — rejected with 400 ``unsupported_field``: the Responses surface is+/// text-only. (Vision input is supported on ``/v1/chat/completions``.)#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct ResponsesRequest {pub model: String,diff --git a/packages/sie_gateway/src/queue/payload_store.rs b/packages/sie_gateway/src/queue/payload_store.rsindex c1793de59..b80414291 100644--- a/packages/sie_gateway/src/queue/payload_store.rs+++ b/packages/sie_gateway/src/queue/payload_store.rs@@ -1,8 +1,18 @@+use std::io;use std::path::{Path, PathBuf};use std::sync::Arc;use async_trait::async_trait;-use tracing::{debug, warn};+use tracing::debug;++const OBJECT_STORE_SCHEMES: &[&str] = &["s3://", "gs://", "abfs://", "abfss://"];++fn object_store_scheme(url: &str) -> Option<&'static str> {+ OBJECT_STORE_SCHEMES+ .iter()+ .copied()+ .find(|scheme| url.starts_with(scheme))+}/// Validate that a key is a plain filename (no path separators or traversal).fn validate_key(key: &str) -> Result<(), String> {@@ -45,14 +55,32 @@ pub struct LocalPayloadStore {}impl LocalPayloadStore {- pub async fn new(base_dir: impl AsRef<Path>) -> Self {+ pub async fn new(base_dir: impl AsRef<Path>) -> io::Result<Self> {let dir = base_dir.as_ref().to_path_buf();- if !dir.exists() {- if let Err(e) = tokio::fs::create_dir_all(&dir).await {- warn!(dir = %dir.display(), error = %e, "failed to create payload store directory");+ match tokio::fs::metadata(&dir).await {+ Ok(metadata) if metadata.is_dir() => {}+ Ok(_) => {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("payload store path {} is not a directory", dir.display()),+ ));+ }+ Err(e) if e.kind() == io::ErrorKind::NotFound => {+ tokio::fs::create_dir_all(&dir).await.map_err(|e| {+ io::Error::new(+ e.kind(),+ format!("create payload store directory {}: {e}", dir.display()),+ )+ })?;+ }+ Err(e) => {+ return Err(io::Error::new(+ e.kind(),+ format!("stat payload store directory {}: {e}", dir.display()),+ ));}}- Self { base_dir: dir }+ Ok(Self { base_dir: dir })}}@@ -94,45 +122,121 @@ pub struct ObjectStorePayloadStore {#[cfg(feature = "cloud-storage")]impl ObjectStorePayloadStore {- pub fn new_s3(path: &str) -> Self {+ pub fn new_s3(path: &str) -> io::Result<Self> {use object_store::aws::AmazonS3Builder;- let (bucket, prefix) = Self::parse_bucket_prefix(path);+ let (bucket, prefix) = Self::parse_bucket_prefix(path, "S3")?;let store = AmazonS3Builder::from_env().with_bucket_name(&bucket).build()- .expect("failed to build S3 payload store");-- let url_prefix = format!("s3://{}", path);- Self {+ .map_err(|e| {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("failed to build S3 payload store: {e}"),+ )+ })?;++ let url_prefix = format!("s3://{}", path.trim_end_matches('/'));+ Ok(Self {store: Box::new(store),prefix: object_store::path::Path::from(prefix),url_prefix,- }+ })}- pub fn new_gcs(path: &str) -> Self {+ pub fn new_gcs(path: &str) -> io::Result<Self> {use object_store::gcp::GoogleCloudStorageBuilder;- let (bucket, prefix) = Self::parse_bucket_prefix(path);+ let (bucket, prefix) = Self::parse_bucket_prefix(path, "GCS")?;let store = GoogleCloudStorageBuilder::from_env().with_bucket_name(&bucket).build()- .expect("failed to build GCS payload store");+ .map_err(|e| {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("failed to build GCS payload store: {e}"),+ )+ })?;++ let url_prefix = format!("gs://{}", path.trim_end_matches('/'));+ Ok(Self {+ store: Box::new(store),+ prefix: object_store::path::Path::from(prefix),+ url_prefix,+ })+ }++ pub fn new_azure(path: &str) -> io::Result<Self> {+ Self::new_azure_with_scheme(path, "abfs://")+ }++ fn new_azure_with_scheme(path: &str, scheme: &'static str) -> io::Result<Self> {+ use object_store::azure::MicrosoftAzureBuilder;- let url_prefix = format!("gs://{}", path);- Self {+ let (container, account, prefix) = Self::parse_azure_path(path)?;+ let store = MicrosoftAzureBuilder::from_env()+ .with_account(&account)+ .with_container_name(&container)+ .build()+ .map_err(|e| {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("failed to build Azure payload store: {e}"),+ )+ })?;++ let url_prefix = format!("{}{}", scheme, path.trim_end_matches('/'));+ Ok(Self {store: Box::new(store),prefix: object_store::path::Path::from(prefix),url_prefix,- }+ })}- fn parse_bucket_prefix(path: &str) -> (String, String) {- match path.split_once('/') {- Some((bucket, prefix)) => (bucket.to_string(), prefix.to_string()),+ fn parse_bucket_prefix(path: &str, provider: &str) -> io::Result<(String, String)> {+ let path = path.trim_matches('/');+ let (bucket, prefix) = match path.split_once('/') {+ Some((bucket, prefix)) => (bucket.to_string(), prefix.trim_matches('/').to_string()),None => (path.to_string(), String::new()),+ };+ if bucket.is_empty() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("{provider} payload store bucket must be non-empty"),+ ));+ }+ Ok((bucket, prefix))+ }++ fn parse_azure_path(path: &str) -> io::Result<(String, String, String)> {+ let path = path.trim_matches('/');+ let (authority, prefix) = match path.split_once('/') {+ Some((authority, prefix)) => (authority, prefix.trim_matches('/').to_string()),+ None => (path, String::new()),+ };+ let Some((container, host)) = authority.split_once('@') else {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "Azure payload store URL must use <container>@<account>.dfs.core.windows.net",+ ));+ };+ if container.is_empty() || host.is_empty() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "Azure payload store container and account must be non-empty",+ ));+ }+ let account = host+ .strip_suffix(".dfs.core.windows.net")+ .or_else(|| host.strip_suffix(".blob.core.windows.net"))+ .unwrap_or(host);+ if account.is_empty() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "Azure payload store account must be non-empty",+ ));}+ Ok((container.to_string(), account.to_string(), prefix))}fn object_key(&self, key: &str) -> object_store::path::Path {@@ -173,42 +277,115 @@ impl PayloadStore for ObjectStorePayloadStore {}/// Factory function to create the appropriate payload store based on URL prefix.-pub async fn create_payload_store(url: &str) -> Arc<dyn PayloadStore> {+pub async fn create_payload_store(url: &str) -> io::Result<Arc<dyn PayloadStore>> {if url.trim().is_empty() {- return Arc::new(DisabledPayloadStore);+ return Ok(Arc::new(DisabledPayloadStore));}#[cfg(feature = "cloud-storage")]{- if let Some(rest) = url.strip_prefix("s3://") {- return Arc::new(ObjectStorePayloadStore::new_s3(rest));- }- if let Some(rest) = url.strip_prefix("gs://") {- return Arc::new(ObjectStorePayloadStore::new_gcs(rest));+ if let Some(scheme) = object_store_scheme(url) {+ if let Some(rest) = url.strip_prefix("s3://") {+ return Ok(Arc::new(ObjectStorePayloadStore::new_s3(rest)?));+ }+ if let Some(rest) = url.strip_prefix("gs://") {+ return Ok(Arc::new(ObjectStorePayloadStore::new_gcs(rest)?));+ }+ if let Some(rest) = url.strip_prefix("abfs://") {+ return Ok(Arc::new(ObjectStorePayloadStore::new_azure(rest)?));+ }+ if let Some(rest) = url.strip_prefix(scheme) {+ return Ok(Arc::new(ObjectStorePayloadStore::new_azure_with_scheme(+ rest, scheme,+ )?));+ }}}#[cfg(not(feature = "cloud-storage"))]{- if url.starts_with("s3://") || url.starts_with("gs://") {- warn!(- url = %url,- "cloud storage payload store requested but 'cloud-storage' feature not enabled — falling back to local"- );+ if let Some(scheme) = object_store_scheme(url) {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!(+ "payload store URL {url} with scheme {scheme} requires the 'cloud-storage' feature; \+ rebuild the gateway with --features cloud-storage or point SIE_PAYLOAD_STORE_URL at a local path"+ ),+ ));}}- Arc::new(LocalPayloadStore::new(url).await)+ Ok(Arc::new(LocalPayloadStore::new(url).await?))}#[cfg(test)]mod tests {use super::*;+ #[cfg(feature = "cloud-storage")]+ use std::sync::{Mutex, OnceLock};++ #[cfg(feature = "cloud-storage")]+ const AZURE_ENV_KEYS: &[&str] = &[+ "AZURE_STORAGE_ACCOUNT_NAME",+ "AZURE_STORAGE_ACCOUNT_KEY",+ "AZURE_STORAGE_ACCESS_KEY",+ "AZURE_STORAGE_CLIENT_ID",+ "AZURE_CLIENT_ID",+ "AZURE_STORAGE_CLIENT_SECRET",+ "AZURE_CLIENT_SECRET",+ "AZURE_STORAGE_TENANT_ID",+ "AZURE_TENANT_ID",+ "AZURE_FEDERATED_TOKEN_FILE",+ "AZURE_STORAGE_AUTHORITY_HOST",+ "AZURE_AUTHORITY_HOST",+ "AZURE_STORAGE_TOKEN",+ "AZURE_USE_AZURE_CLI",+ ];++ #[cfg(feature = "cloud-storage")]+ fn azure_env_lock() -> &'static Mutex<()> {+ static LOCK: OnceLock<Mutex<()>> = OnceLock::new();+ LOCK.get_or_init(|| Mutex::new(()))+ }++ #[cfg(feature = "cloud-storage")]+ struct EnvGuard {+ saved: Vec<(&'static str, Option<String>)>,+ }++ #[cfg(feature = "cloud-storage")]+ impl EnvGuard {+ fn set(vars: &[(&'static str, String)]) -> Self {+ let saved = AZURE_ENV_KEYS+ .iter()+ .map(|key| (*key, std::env::var(key).ok()))+ .collect();+ for key in AZURE_ENV_KEYS {+ std::env::remove_var(key);+ }+ for (key, value) in vars {+ std::env::set_var(key, value);+ }+ Self { saved }+ }+ }++ #[cfg(feature = "cloud-storage")]+ impl Drop for EnvGuard {+ fn drop(&mut self) {+ for (key, value) in &self.saved {+ match value {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ }+ }#[tokio::test]async fn test_local_payload_store_put_delete() {let dir = tempfile::TempDir::new().unwrap();- let store = LocalPayloadStore::new(dir.path()).await;+ let store = LocalPayloadStore::new(dir.path()).await.unwrap();let key = "test_req_0.bin";let data = b"hello world";@@ -227,7 +404,7 @@ mod tests {#[tokio::test]async fn test_local_payload_store_delete_nonexistent() {let dir = tempfile::TempDir::new().unwrap();- let store = LocalPayloadStore::new(dir.path()).await;+ let store = LocalPayloadStore::new(dir.path()).await.unwrap();store.delete("nonexistent.bin").await.unwrap();}@@ -235,7 +412,7 @@ mod tests {async fn test_local_payload_store_creates_dir() {let dir = tempfile::TempDir::new().unwrap();let sub = dir.path().join("sub").join("dir");- let store = LocalPayloadStore::new(&sub).await;+ let store = LocalPayloadStore::new(&sub).await.unwrap();let payload_ref = store.put("test.bin", b"data").await.unwrap();assert!(payload_ref.contains("test.bin"));@@ -245,7 +422,7 @@ mod tests {#[tokio::test]async fn test_validate_key_rejects_path_traversal() {let dir = tempfile::TempDir::new().unwrap();- let store = LocalPayloadStore::new(dir.path()).await;+ let store = LocalPayloadStore::new(dir.path()).await.unwrap();assert!(store.put("../escape.bin", b"data").await.is_err());assert!(store.put("sub/dir.bin", b"data").await.is_err());@@ -257,43 +434,188 @@ mod tests {#[tokio::test]async fn test_create_payload_store_local() {let dir = tempfile::TempDir::new().unwrap();- let _store = create_payload_store(dir.path().to_str().unwrap()).await;+ let _store = create_payload_store(dir.path().to_str().unwrap())+ .await+ .unwrap();}#[tokio::test]async fn test_create_payload_store_empty_disables_offload() {- let store = create_payload_store("").await;+ let store = create_payload_store("").await.unwrap();assert!(store.put("test.bin", b"data").await.is_err());assert!(store.delete("test.bin").await.is_ok());}+ #[tokio::test]+ async fn test_create_payload_store_rejects_file_path() {+ let dir = tempfile::TempDir::new().unwrap();+ let file = dir.path().join("payloads");+ tokio::fs::write(&file, b"not a dir").await.unwrap();++ let err = match create_payload_store(file.to_str().unwrap()).await {+ Ok(_) => panic!("expected file path to be rejected"),+ Err(err) => err,+ };+ assert_eq!(err.kind(), io::ErrorKind::InvalidInput);+ assert!(err.to_string().contains("not a directory"));+ }++ #[cfg(not(feature = "cloud-storage"))]#[tokio::test]async fn test_create_payload_store_s3_without_feature() {- let _store = create_payload_store("s3://my-bucket/prefix").await;+ let err = match create_payload_store("s3://my-bucket/prefix").await {+ Ok(_) => panic!("expected s3:// to require cloud-storage"),+ Err(err) => err,+ };+ assert_eq!(err.kind(), io::ErrorKind::InvalidInput);+ assert!(err.to_string().contains("cloud-storage"));}+ #[cfg(not(feature = "cloud-storage"))]#[tokio::test]async fn test_create_payload_store_gs_without_feature() {- let _store = create_payload_store("gs://my-bucket/prefix").await;+ let err = match create_payload_store("gs://my-bucket/prefix").await {+ Ok(_) => panic!("expected gs:// to require cloud-storage"),+ Err(err) => err,+ };+ assert_eq!(err.kind(), io::ErrorKind::InvalidInput);+ assert!(err.to_string().contains("cloud-storage"));+ }++ #[cfg(not(feature = "cloud-storage"))]+ #[tokio::test]+ async fn test_create_payload_store_abfs_without_feature() {+ let err = match create_payload_store("abfs://[email protected]/prefix")+ .await+ {+ Ok(_) => panic!("expected abfs:// to require cloud-storage"),+ Err(err) => err,+ };+ assert_eq!(err.kind(), io::ErrorKind::InvalidInput);+ assert!(err.to_string().contains("cloud-storage"));}#[cfg(feature = "cloud-storage")]mod cloud_tests {use super::super::*;+ use super::{azure_env_lock, EnvGuard};#[test]fn test_parse_bucket_prefix() {let (bucket, prefix) =- ObjectStorePayloadStore::parse_bucket_prefix("my-bucket/path/to/payloads");+ ObjectStorePayloadStore::parse_bucket_prefix("my-bucket/path/to/payloads", "S3")+ .unwrap();assert_eq!(bucket, "my-bucket");assert_eq!(prefix, "path/to/payloads");}#[test]fn test_parse_bucket_only() {- let (bucket, prefix) = ObjectStorePayloadStore::parse_bucket_prefix("my-bucket");+ let (bucket, prefix) =+ ObjectStorePayloadStore::parse_bucket_prefix("my-bucket", "S3").unwrap();assert_eq!(bucket, "my-bucket");assert_eq!(prefix, "");}++ #[test]+ fn test_parse_bucket_prefix_rejects_empty_bucket() {+ let err = ObjectStorePayloadStore::parse_bucket_prefix("", "S3").unwrap_err();+ assert_eq!(err.kind(), io::ErrorKind::InvalidInput);+ }++ #[test]+ fn test_parse_bucket_prefix_trims_slashes() {+ // Parity with the sidecar's parse_bucket_prefix.+ let (bucket, prefix) =+ ObjectStorePayloadStore::parse_bucket_prefix("/my-bucket/path/to/payloads/", "S3")+ .unwrap();+ assert_eq!(bucket, "my-bucket");+ assert_eq!(prefix, "path/to/payloads");+ }++ #[test]+ fn test_parse_azure_path() {+ let (container, account, prefix) = ObjectStorePayloadStore::parse_azure_path(+ "[email protected]/path/to/payloads",+ )+ .unwrap();+ assert_eq!(container, "payloads");+ assert_eq!(account, "sieacct");+ assert_eq!(prefix, "path/to/payloads");+ }++ #[test]+ fn test_parse_azure_blob_endpoint_path() {+ let (container, account, prefix) = ObjectStorePayloadStore::parse_azure_path(+ "[email protected]/path/to/payloads",+ )+ .unwrap();+ assert_eq!(container, "payloads");+ assert_eq!(account, "sieacct");+ assert_eq!(prefix, "path/to/payloads");+ }++ #[test]+ fn test_parse_azure_path_rejects_missing_account_separator() {+ let err = ObjectStorePayloadStore::parse_azure_path("payloads/path").unwrap_err();+ assert_eq!(err.kind(), io::ErrorKind::InvalidInput);+ }++ #[test]+ fn test_new_azure_builds_from_workload_identity_env() {+ let _lock = azure_env_lock().lock().unwrap();+ let dir = tempfile::TempDir::new().unwrap();+ let token_file = dir.path().join("token");+ std::fs::write(&token_file, "token").unwrap();+ let _env = EnvGuard::set(&[+ ("AZURE_STORAGE_ACCOUNT_NAME", "env-account".to_string()),+ ("AZURE_CLIENT_ID", "client-id".to_string()),+ ("AZURE_TENANT_ID", "tenant-id".to_string()),+ (+ "AZURE_FEDERATED_TOKEN_FILE",+ token_file.to_string_lossy().to_string(),+ ),+ (+ "AZURE_AUTHORITY_HOST",+ "https://login.microsoftonline.com/".to_string(),+ ),+ ]);++ let store = ObjectStorePayloadStore::new_azure(+ "[email protected]/path/to/payloads",+ )+ .unwrap();++ assert_eq!(+ store.url_prefix,+ "abfs://[email protected]/path/to/payloads"+ );+ assert_eq!(store.prefix.as_ref(), "path/to/payloads");+ }++ #[test]+ fn test_create_payload_store_abfss_with_cloud_feature() {+ let _lock = azure_env_lock().lock().unwrap();+ let dir = tempfile::TempDir::new().unwrap();+ let token_file = dir.path().join("token");+ std::fs::write(&token_file, "token").unwrap();+ let _env = EnvGuard::set(&[+ ("AZURE_CLIENT_ID", "client-id".to_string()),+ ("AZURE_TENANT_ID", "tenant-id".to_string()),+ (+ "AZURE_FEDERATED_TOKEN_FILE",+ token_file.to_string_lossy().to_string(),+ ),+ ]);++ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();+ let _store = runtime.block_on(create_payload_store(+ "abfss://[email protected]/path/to/payloads",+ ));+ assert!(_store.is_ok());+ }}}diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex ad5a240c0..339d4810d 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -2,7 +2,7 @@ use std::sync::Arc;use std::time::{Duration, Instant};use async_nats::jetstream;-use dashmap::DashMap;+use dashmap::{DashMap, DashSet};use futures_util::future::try_join_all;use futures_util::StreamExt;use serde::{Deserialize, Serialize};@@ -154,10 +154,43 @@ impl Default for GenerateInput {}}+/// One image attached to a chat message, extracted from an OpenAI+/// ``image_url`` data URI at the gateway.+///+/// ``data`` is the **base64 payload string**, NOT raw bytes. This is+/// deliberate: the generate work item travels through the sidecar's+/// ``WorkItem.generate: serde_json::Value``, and ``serde_json::Value``+/// cannot hold a msgpack ``bin`` (rmp_serde rejects it with "invalid type:+/// byte array"). A base64 string round-trips cleanly through+/// ``serde_json::Value`` with no sidecar changes. The worker base64-decodes+/// it back to bytes (see ``_parse_message_images_field``).+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ChatImage {+ /// Base64-encoded image bytes (standard alphabet, no ``data:`` prefix).+ pub data: String,+ /// Format hint parsed from the data-URI MIME subtype (e.g. ``"png"``).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub format: Option<String>,+}++/// One ordered content part of a multimodal chat message — either a text+/// fragment or an image placeholder (the bytes ride the message's flat+/// ``images`` list, consumed in order as ``Image`` parts are encountered).+/// Serializes internally-tagged so the worker reads ``{"type":"text",…}`` /+/// ``{"type":"image"}`` and round-trips through ``serde_json::Value`` on the+/// sidecar (no msgpack ``bin`` — same constraint as :struct:`ChatImage`).+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum ContentPart {+ Text { text: String },+ Image,+}+/// One chat message in the OpenAI request shape. Role is validated-/// against the allowed set at the gateway; ``content`` is currently a-/// plain string (vision / multi-part content is out of scope on this-/// surface).+/// against the allowed set at the gateway; ``content`` carries the text+/// (multi-part text parts are concatenated). Any ``image_url`` parts are+/// decoded into ``images`` and gated on the model's vision capability+/// after model resolution.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct ChatMessage {pub role: String,@@ -171,6 +204,22 @@ pub struct ChatMessage {/// tool-call it answers. Required by OpenAI on tool messages.#[serde(default, skip_serializing_if = "Option::is_none")]pub tool_call_id: Option<String>,+ /// Vision input: images decoded from the message's ``image_url`` /+ /// ``input_image`` content parts. ``None`` on text-only messages. The+ /// worker renders one placeholder per image, in order, and forwards the+ /// bytes to the engine.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub images: Option<Vec<ChatImage>>,+ /// Ordered content layout for multimodal messages: the original+ /// text↔image interleaving from the OpenAI ``content`` parts array.+ /// ``None`` on text-only / non-interleaved-legacy messages — the worker+ /// then falls back to the images-first ``content`` + ``images`` render.+ /// When present, the worker emits one image placeholder per ``Image`` part+ /// *in place*, pulling bytes from ``images`` in order; only placeholder+ /// positions change (the flat ``images`` list / ``image_data`` to the+ /// engine is unchanged).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub content_parts: Option<Vec<ContentPart>>,}/// Structured-output grammar.@@ -503,6 +552,13 @@ pub struct WorkPublisher {/// generation request. Populated by ``publish_generate_streaming``/// and drained by ``handle_inbox`` when chunk envelopes arrive.pending_streams: DashMap<String, StreamCollector>,+ /// Request ids whose generate work item was offloaded to the object+ /// store (``payload_ref`` set, ``generate`` blanked). The blob lives at+ /// ``{request_id}_0.bin`` and must be deleted once the stream finishes —+ /// promptly at the terminal funnel (``handle_chunk``) and, as a backstop+ /// for failure/timeout terminations, reconciled against ``pending_streams``+ /// by the periodic ``cleanup_expired`` sweep.+ offloaded_streams: DashSet<String>,/// Core NATS client (cancel publishes use core NATS, not/// JetStream). Populated lazily by/// :meth:`start_inbox_subscription`; reads on the cancel path@@ -1048,6 +1104,7 @@ impl WorkPublisher {stream_info_cache: DashMap::new(),pending_results: DashMap::new(),pending_streams: DashMap::new(),+ offloaded_streams: DashSet::new(),nats_client: tokio::sync::RwLock::new(None),inbox_handle: tokio::sync::Mutex::new(None),fallback_buckets: DashMap::new(),@@ -1827,7 +1884,7 @@ impl WorkPublisher {}let work_item_id = format!("{}.0", shared.request_id);- let ref_item = WorkItemRef {+ let mut ref_item = WorkItemRef {work_item_id: &work_item_id,request_id: shared.request_id,item_index: 0,@@ -1860,9 +1917,37 @@ impl WorkPublisher {tracestate: shared.tracestate,};- let encoded =+ let mut encoded =rmp_serde::to_vec_named(&ref_item).map_err(|e| format!("msgpack encode: {}", e))?;+ // Offload large generate work items (e.g. multi-MB document images) to+ // the object store so they don't exceed NATS's max payload — mirrors+ // the encode/score paths. The blob is the ``generate`` params alone+ // (base64-string image data, so it stays serde_json::Value-decodable on+ // the sidecar). ``payload_ref`` lives at ``{request_id}_0.bin``; the+ // sidecar fetches + inlines it before handing the work item to Python.+ let offload_key;+ if encoded.len() > PAYLOAD_OFFLOAD_THRESHOLD {+ let generate = shared+ .params+ .generate+ .as_ref()+ .ok_or_else(|| "generate request missing params for offload".to_string())?;+ let gen_blob = rmp_serde::to_vec_named(generate)+ .map_err(|e| format!("msgpack encode offloaded generate: {}", e))?;+ offload_key = format!("{}_0.bin", shared.request_id);+ if let Err(e) = self.payload_store.put(&offload_key, &gen_blob).await {+ warn!(error = %e, "failed to offload generate payload, sending inline");+ } else {+ ref_item.generate = None;+ ref_item.payload_ref = Some(&offload_key);+ encoded = rmp_serde::to_vec_named(&ref_item)+ .map_err(|e| format!("msgpack encode offloaded generate item: {}", e))?;+ self.offloaded_streams.insert(shared.request_id.to_string());+ metrics::QUEUE_PAYLOAD_OFFLOADS.inc();+ }+ }+// Defense-in-depth dedup: stamp `Nats-Msg-Id` = request_id so a// gateway-side retry (or a duplicate publish racing on the same// request) collapses to a single message inside the stream's@@ -2435,6 +2520,9 @@ impl WorkPublisher {metrics::QUEUE_RESULT_WAIT.with_label_values(&["generate"]).observe(wait_secs);+ // Stream finished — drop any offloaded generate blob now+ // (the periodic reconcile is only the failure-path backstop).+ self.cleanup_offloaded_generate(&request_id).await;}}ChunkApplied::SeqGap => {@@ -2515,6 +2603,57 @@ impl WorkPublisher {}self.cleanup_offloaded_payloads(key, *total).await;}++ // Reconcile offloaded generate blobs: any tracked request whose stream+ // is no longer pending has terminated (success cleans up at the+ // terminal funnel; this is the backstop for failure/timeout paths,+ // including the sync ``fail_pending_stream`` which can't await).+ //+ // Check BOTH in-flight maps: ``publish_generate`` is shared with the+ // batch generate arm (``publish_work``), which tracks requests in+ // ``pending_results`` rather than ``pending_streams``. Excluding only+ // ``pending_streams`` would let this sweep delete a batch request's+ // offloaded blob mid-flight and break redelivery. (That arm is dead+ // today — all generate goes through the streaming path — but this keeps+ // the reconcile correct if it's ever wired up.)+ let orphaned: Vec<String> = self+ .offloaded_streams+ .iter()+ .filter(|id| {+ !self.pending_streams.contains_key(id.key())+ && !self.pending_results.contains_key(id.key())+ })+ .map(|id| id.key().clone())+ .collect();+ for request_id in orphaned {+ self.cleanup_offloaded_generate(&request_id).await;+ }+ }++ /// Delete an offloaded generate blob (``{request_id}_0.bin``) and drop its+ /// tracking entry. Best-effort + idempotent: a no-op when the request had+ /// no offload, so it is safe to call on every stream termination.+ async fn cleanup_offloaded_generate(&self, request_id: &str) {+ // No-op for non-offloaded requests.+ if !self.offloaded_streams.contains(request_id) {+ return;+ }+ let key = format!("{request_id}_0.bin");+ // Delete the blob FIRST and only drop the tracker on success, so a+ // transient delete failure leaves the entry for the next periodic+ // reconcile to retry instead of leaking the blob.+ match self.payload_store.delete(&key).await {+ Ok(()) => {+ self.offloaded_streams.remove(request_id);+ }+ Err(e) => {+ warn!(+ key = %key,+ error = %e,+ "failed to delete offloaded generate payload; will retry on next reconcile"+ );+ }+ }}async fn cleanup_pending_streams(&self) {@@ -2554,6 +2693,10 @@ impl WorkPublisher {metrics::QUEUE_RESULT_WAIT.with_label_values(&["generate"]).observe(wait_secs);+ // Drop any offloaded blob for this shutdown-dropped stream. The+ // periodic reconcile filters against ``pending_streams``, so an+ // entry removed here would otherwise be missed at shutdown.+ self.cleanup_offloaded_generate(&key).await;}}}@@ -3301,6 +3444,102 @@ mod tests {assert_eq!(decoded.max_new_tokens, 8);}+ /// CRITICAL transport invariant: a generate work item carrying images+ /// must decode as ``serde_json::Value`` — that's the type the sidecar's+ /// ``WorkItem.generate`` uses, and ``serde_json::Value`` CANNOT hold a+ /// msgpack ``bin`` (rmp_serde errors "invalid type: byte array"). Image+ /// bytes therefore travel as a base64 *string* in ``ChatImage.data``.+ /// This test pins that contract: had ``ChatImage.data`` been+ /// ``#[serde(with = "serde_bytes")]`` (bin), the serde_json decode below+ /// would fail and the feature would break through the real+ /// NATS→sidecar→worker path.+ #[test]+ fn test_chat_message_images_survive_sidecar_serde_json_value() {+ let msg = ChatMessage {+ role: "user".to_string(),+ content: "what is this?".to_string(),+ tool_calls: None,+ tool_call_id: None,+ images: Some(vec![ChatImage {+ data: "aGVsbG8=".to_string(), // base64 of b"hello"+ format: Some("png".to_string()),+ }]),+ content_parts: None,+ };+ let mp = rmp_serde::to_vec_named(&msg).unwrap();+ // (1) sidecar step: decode as serde_json::Value — MUST succeed.+ let as_value: serde_json::Value = rmp_serde::from_slice(&mp)+ .expect("ChatMessage with images must decode as serde_json::Value (no msgpack bin)");+ assert_eq!(as_value["images"][0]["data"], "aGVsbG8=");+ // (2) sidecar re-encode → worker typed decode: base64 survives.+ let mp2 = rmp_serde::to_vec_named(&as_value).unwrap();+ let back: ChatMessage = rmp_serde::from_slice(&mp2).unwrap();+ let imgs = back.images.expect("images survive round-trip");+ assert_eq!(imgs[0].data, "aGVsbG8=");+ assert_eq!(imgs[0].format.as_deref(), Some("png"));+ }++ /// ``content_parts`` (the #1294 interleaving layout) must survive the same+ /// NATS→sidecar(``serde_json::Value``)→worker round-trip, preserving the+ /// text↔image ORDER and the internally-tagged shape the worker parses+ /// (``{"type":"text","text":…}`` / ``{"type":"image"}``).+ #[test]+ fn test_content_parts_ordering_survives_sidecar_round_trip() {+ let msg = ChatMessage {+ role: "user".to_string(),+ content: "Page 1:Page 2:which has a cat?".to_string(),+ tool_calls: None,+ tool_call_id: None,+ images: Some(vec![+ ChatImage {+ data: "aW1nQQ==".to_string(),+ format: Some("png".to_string()),+ },+ ChatImage {+ data: "aW1nQg==".to_string(),+ format: Some("png".to_string()),+ },+ ]),+ content_parts: Some(vec![+ ContentPart::Text {+ text: "Page 1:".to_string(),+ },+ ContentPart::Image,+ ContentPart::Text {+ text: "Page 2:".to_string(),+ },+ ContentPart::Image,+ ContentPart::Text {+ text: "which has a cat?".to_string(),+ },+ ]),+ };+ let mp = rmp_serde::to_vec_named(&msg).unwrap();+ // (1) sidecar step: decode as serde_json::Value — MUST succeed.+ let as_value: serde_json::Value = rmp_serde::from_slice(&mp).expect(+ "ChatMessage with content_parts must decode as serde_json::Value (no msgpack bin)",+ );+ let parts = as_value["content_parts"]+ .as_array()+ .expect("content_parts is an array");+ assert_eq!(parts.len(), 5);+ assert_eq!(parts[0]["type"], "text");+ assert_eq!(parts[0]["text"], "Page 1:");+ assert_eq!(parts[1]["type"], "image");+ assert_eq!(parts[3]["type"], "image");+ assert_eq!(parts[4]["text"], "which has a cat?");+ // (2) sidecar re-encode → worker typed decode: order survives.+ let mp2 = rmp_serde::to_vec_named(&as_value).unwrap();+ let back: ChatMessage = rmp_serde::from_slice(&mp2).unwrap();+ let back_parts = back+ .content_parts+ .expect("content_parts survive round-trip");+ assert!(matches!(&back_parts[0], ContentPart::Text { text } if text == "Page 1:"));+ assert!(matches!(back_parts[1], ContentPart::Image));+ assert!(matches!(back_parts[3], ContentPart::Image));+ assert!(matches!(&back_parts[4], ContentPart::Text { text } if text == "which has a cat?"));+ }+/// A round-trip through msgpack must preserve the shape — verifies/// that the ``flatten`` / ``untagged`` combination encodes the input/// arm back into the flat wire shape rather than nesting it underdiff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rsindex 6b1c0833c..5f5b1fcbf 100644--- a/packages/sie_gateway/src/state/worker_registry.rs+++ b/packages/sie_gateway/src/state/worker_registry.rs@@ -69,6 +69,12 @@ pub type OnWorkerHealthy = Arc<dyn Fn(&WorkerState) + Send + Sync>;/// ring snapshots and (optionally) to log a structured trace.pub type OnWorkerDegraded = Arc<dyn Fn(&WorkerState) + Send + Sync>;+#[derive(Debug, Default, PartialEq, Eq)]+pub struct HeartbeatSweep {+ pub unhealthy: Vec<String>,+ pub evicted: Vec<String>,+}+/// Concrete queue lane resolved from the worker registry.////// `pool_name` is the logical tenant/capacity pool. `machine_profile`@@ -117,6 +123,7 @@ impl RegistrySnapshot {pub struct WorkerRegistry {workers: RwLock<HashMap<String, WorkerState>>,heartbeat_timeout: Duration,+ stale_evict_after: Duration,on_worker_healthy: Option<OnWorkerHealthy>,on_worker_degraded: Option<OnWorkerDegraded>,/// Pre-computed snapshot for lock-free select_worker lookups.@@ -155,9 +162,11 @@ impl WorkerRegistry {on_worker_healthy: Option<OnWorkerHealthy>,on_worker_degraded: Option<OnWorkerDegraded>,) -> Self {+ let stale_evict_after = heartbeat_timeout.checked_mul(20).unwrap_or(Duration::MAX);Self {workers: RwLock::new(HashMap::new()),heartbeat_timeout,+ stale_evict_after,on_worker_healthy,on_worker_degraded,snapshot: ArcSwap::from_pointee(RegistrySnapshot::default()),@@ -300,10 +309,11 @@ impl WorkerRegistry {became_healthy}- pub async fn remove_worker(&self, url: &str) {+ pub async fn remove_worker(&self, url: &str) -> bool {let mut workers = self.workers.write().await;- workers.remove(url);+ let removed = workers.remove(url).is_some();self.rebuild_snapshot(&workers);+ removed}pub async fn mark_unhealthy(&self, url: &str) {@@ -509,20 +519,29 @@ impl WorkerRegistry {RingSnapshot::new(workers.into_iter().map(|w| w.name))}- pub async fn check_heartbeats(&self) -> Vec<String> {+ pub async fn check_heartbeats(&self) -> HeartbeatSweep {let mut workers = self.workers.write().await;let now = Instant::now();- let mut unhealthy = Vec::new();+ let mut sweep = HeartbeatSweep::default();+ let mut evict = Vec::new();for (url, w) in workers.iter_mut() {- if w.healthy() && now.duration_since(w.last_heartbeat) > self.heartbeat_timeout {+ let age = now.duration_since(w.last_heartbeat);+ if age > self.stale_evict_after {+ evict.push(url.clone());+ } else if w.healthy() && age > self.heartbeat_timeout {w.health = WorkerHealth::Unhealthy;- unhealthy.push(url.clone());+ sweep.unhealthy.push(url.clone());+ }+ }+ for url in evict {+ if workers.remove(&url).is_some() {+ sweep.evicted.push(url);}}- if !unhealthy.is_empty() {+ if !sweep.unhealthy.is_empty() || !sweep.evicted.is_empty() {self.rebuild_snapshot(&workers);}- unhealthy+ sweep}/// Resolve the NATS pool name for queue mode routing.@@ -777,6 +796,7 @@ mod tests {memory_used_bytes: None,memory_total_bytes: None,saturated: false,+ terminated: false,}}@@ -1005,6 +1025,7 @@ mod tests {memory_used_bytes: Some(2000),memory_total_bytes: Some(8000),saturated: false,+ terminated: false,};reg.update_worker("http://w1:8080", msg).await;@@ -1032,6 +1053,7 @@ mod tests {memory_used_bytes: None,memory_total_bytes: None,saturated: false,+ terminated: false,};reg.update_worker("http://w1:8080", msg).await;@@ -1106,19 +1128,56 @@ mod tests {let reg = registry();reg.update_worker("http://w1:8080", make_msg(true)).await;- let unhealthy = reg.check_heartbeats().await;- assert!(unhealthy.is_empty());+ let sweep = reg.check_heartbeats().await;+ assert!(sweep.unhealthy.is_empty());+ assert!(sweep.evicted.is_empty());}#[tokio::test]async fn test_check_heartbeats_expired() {let reg = WorkerRegistry::new(Duration::from_millis(1), None);reg.update_worker("http://w1:8080", make_msg(true)).await;+ {+ let mut workers = reg.workers.write().await;+ workers.get_mut("http://w1:8080").unwrap().last_heartbeat =+ Instant::now() - Duration::from_millis(10);+ }++ let sweep = reg.check_heartbeats().await;+ assert_eq!(sweep.unhealthy, vec!["http://w1:8080"]);+ assert!(sweep.evicted.is_empty());+ assert_eq!(+ reg.workers().await["http://w1:8080"].health,+ WorkerHealth::Unhealthy+ );+ }- tokio::time::sleep(Duration::from_millis(10)).await;+ #[tokio::test]+ async fn test_check_heartbeats_evicts_stale_worker() {+ let reg = WorkerRegistry::new(Duration::from_millis(1), None);+ reg.update_worker("http://w1:8080", make_msg(true)).await;+ {+ let mut workers = reg.workers.write().await;+ workers.get_mut("http://w1:8080").unwrap().last_heartbeat =+ Instant::now() - Duration::from_millis(25);+ }++ let sweep = reg.check_heartbeats().await;+ assert!(sweep.unhealthy.is_empty());+ assert_eq!(sweep.evicted, vec!["http://w1:8080"]);+ assert!(reg.workers().await.is_empty());+ assert!(reg.healthy_workers().await.is_empty());+ }++ #[tokio::test]+ async fn test_check_heartbeats_keeps_not_ready_worker_with_fresh_heartbeat() {+ let reg = WorkerRegistry::new(Duration::from_millis(1), None);+ reg.update_worker("http://w1:8080", make_msg(true)).await;+ reg.update_worker("http://w1:8080", make_msg(false)).await;- let unhealthy = reg.check_heartbeats().await;- assert_eq!(unhealthy, vec!["http://w1:8080"]);+ let sweep = reg.check_heartbeats().await;+ assert!(sweep.unhealthy.is_empty());+ assert!(sweep.evicted.is_empty());assert_eq!(reg.workers().await["http://w1:8080"].health,WorkerHealth::Unhealthy@@ -1499,6 +1558,7 @@ mod tests {memory_used_bytes: None,memory_total_bytes: None,saturated,+ terminated: false,}}diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex 5ed23b2c6..4377b5ab0 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -273,6 +273,16 @@ impl ModelInfoExtras {},}}++ /// Whether the model can serve vision *generation* on+ /// ``/v1/chat/completions``: it must accept image input AND declare a+ /// generation task. ``inputs.image`` alone is also set by encode-only+ /// image models (CLIP/SigLIP), which must not accept a chat image+ /// request; ``outputs`` carries ``"tokens"`` only when a ``generate``+ /// task is present (see ``from_yaml_raw``).+ pub fn supports_vision_generation(&self) -> bool {+ self.inputs.iter().any(|s| s == "image") && self.outputs.iter().any(|s| s == "tokens")+ }}#[derive(Debug, Clone, Deserialize, Serialize)]@@ -961,6 +971,35 @@ tasks:assert_eq!(extras.outputs, vec!["tokens"]);}+ #[test]+ fn test_supports_vision_generation_requires_image_and_generate() {+ // Vision-capable generation model (image input + generate task).+ let vlm = ModelInfoExtras::from_yaml_raw(+ &serde_yaml::from_str(+ "name: m\ninputs:\n text: true\n image: true\ntasks:\n generate: {}\n",+ )+ .unwrap(),+ );+ assert!(vlm.supports_vision_generation());++ // Encode-only image model (CLIP/SigLIP-style: image input, no generate+ // task) must NOT pass the vision-generation gate.+ let encode_only = ModelInfoExtras::from_yaml_raw(+ &serde_yaml::from_str(+ "name: m\ninputs:\n text: true\n image: true\ntasks:\n encode: {}\n",+ )+ .unwrap(),+ );+ assert!(!encode_only.supports_vision_generation());++ // Text-only generation model: generates but no image input.+ let text_gen = ModelInfoExtras::from_yaml_raw(+ &serde_yaml::from_str("name: m\ninputs:\n text: true\ntasks:\n generate: {}\n")+ .unwrap(),+ );+ assert!(!text_gen.supports_vision_generation());+ }+#[test]fn test_lora_adapters_for_profile_returns_scoped_list() {// ``ModelEntry::lora_adapters_for_profile`` is the validationdiff --git a/packages/sie_gateway/src/types/worker.rs b/packages/sie_gateway/src/types/worker.rsindex 6c38fb919..395cfccfc 100644--- a/packages/sie_gateway/src/types/worker.rs+++ b/packages/sie_gateway/src/types/worker.rs@@ -190,6 +190,11 @@ pub struct WorkerStatusMessage {/// running pre-routing builds.#[serde(default)]pub saturated: bool,+ /// Graceful worker shutdown tombstone. When true, the gateway should+ /// remove this worker from the live registry instead of marking it+ /// unhealthy. Defaults to false for older workers.+ #[serde(default)]+ pub terminated: bool,}#[derive(Debug, Clone, Deserialize)]@@ -245,6 +250,7 @@ mod tests {let json = r#"{"ready": true}"#;let msg: WorkerStatusMessage = serde_json::from_str(json).unwrap();assert!(!msg.saturated);+ assert!(!msg.terminated);}#[test]@@ -254,6 +260,14 @@ mod tests {assert!(msg.saturated);}+ #[test]+ fn test_worker_status_message_deserialize_terminated_true() {+ let json = r#"{"ready": false, "terminated": true}"#;+ let msg: WorkerStatusMessage = serde_json::from_str(json).unwrap();+ assert!(!msg.ready);+ assert!(msg.terminated);+ }+#[test]fn test_worker_healthy() {assert!(make_worker(WorkerHealth::Healthy, 0, 0).healthy());@@ -296,6 +310,7 @@ mod tests {assert!(msg.loaded_models.is_empty());assert!(msg.models.is_empty());assert!(msg.gpus.is_empty());+ assert!(!msg.terminated);}#[test]diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex eb81c9752..2b1084cd5 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.2"+version = "0.6.3"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }@@ -27,6 +27,8 @@ dependencies = [[project.optional-dependencies]storage = [+ "azure-identity>=1.17,<2",+ "azure-storage-blob>=12.20,<13","boto3>=1.35,<2","google-cloud-storage>=2.18,<3","huggingface_hub[hf_transfer]>=0.26",diff --git a/packages/sie_sdk/src/sie_sdk/cache.py b/packages/sie_sdk/src/sie_sdk/cache.pyindex b56286de4..5dfb69d28 100644--- a/packages/sie_sdk/src/sie_sdk/cache.py+++ b/packages/sie_sdk/src/sie_sdk/cache.py@@ -2,7 +2,7 @@Implements the caching hierarchy for model weights:1. Local cache (HF_HOME/hub by default)-2. Cluster cache (S3/GCS bucket)+2. Cluster cache (S3/GCS/Azure object storage)3. HuggingFace Hub fallback (if enabled)The caching is transparent to adapters - they always see files in local cache.@@ -51,7 +51,7 @@ class CacheConfig:"""Local cache directory (usually HF_HOME/hub)."""cluster_cache: str | None = None- """Cluster cache URL (s3:// or gs://), or None if not configured."""+ """Cluster cache URL (s3://, gs://, abfs://, or abfss://), or None if not configured."""hf_fallback: bool = True"""Whether to fallback to HuggingFace Hub for downloads."""@@ -62,7 +62,7 @@ def get_cache_config() -> CacheConfig:Reads:SIE_LOCAL_CACHE: Local cache directory (default: HF_HOME/hub)- SIE_CLUSTER_CACHE: Cluster cache URL (s3:// or gs://)+ SIE_CLUSTER_CACHE: Cluster cache URL (s3://, gs://, abfs://, or abfss://)SIE_HF_FALLBACK: Whether to enable HF Hub fallback (default: true)Returns:@@ -79,7 +79,7 @@ def get_cache_config() -> CacheConfig:else:local_cache = Path.home() / ".cache" / "huggingface" / "hub"- # Cluster cache: S3/GCS URL+ # Cluster cache: S3/GCS/Azure object-store URLcluster_cache = os.environ.get("SIE_CLUSTER_CACHE")# HF fallback: default truediff --git a/packages/sie_sdk/src/sie_sdk/storage.py b/packages/sie_sdk/src/sie_sdk/storage.pyindex 98f653d82..b4d448285 100644--- a/packages/sie_sdk/src/sie_sdk/storage.py+++ b/packages/sie_sdk/src/sie_sdk/storage.py@@ -1,7 +1,7 @@-"""Cloud storage abstraction for S3/GCS/local paths.+"""Cloud storage abstraction for S3/GCS/Azure/local paths.Provides a unified interface for:-- Detecting storage type from URL (s3://, gs://, local path)+- Detecting storage type from URL (s3://, gs://, abfs://, abfss://, local path)- Listing objects/files in a location- Downloading files to local cache- Checking if a path exists@@ -13,19 +13,25 @@ Used by:from __future__ import annotations+import contextlibimport fnmatchimport loggingimport osimport shutilimport tempfile+import timefrom abc import ABC, abstractmethodfrom collections.abc import Iterator+from concurrent.futures import ThreadPoolExecutor, as_completedfrom pathlib import Pathfrom typing import Anyfrom urllib.parse import urlparselogger = logging.getLogger(__name__)+CLOUD_SCHEMES = ("s3://", "gs://", "abfs://", "abfss://")+AZURE_SCHEMES = ("abfs", "abfss")+class StorageBackend(ABC):"""Abstract base class for storage backends."""@@ -136,6 +142,25 @@ class StorageBackend(ABC):f"{type(self).__name__} must override write_text_if_match with an atomic implementation")+ def try_server_side_copy(self, src: str, dst: str) -> bool:+ """Attempt a provider-native server-side copy between two URLs.++ Backends that support it (same-provider src/dst, compatible+ accounts/credentials) copy the object inside the provider without+ relaying bytes through this host. The base implementation reports+ "not supported" so callers fall back to download + upload.++ Args:+ src: Source URL.+ dst: Destination URL.++ Returns:+ True if the object was copied server-side. False when no+ native copy applies to this src/dst pair; the caller must+ fall back to a download + upload relay.+ """+ return False+@abstractmethoddef upload_file(self, src: Path, dst: str) -> None:"""Upload a local file to the storage backend.@@ -535,6 +560,39 @@ class S3Backend(StorageBackend):return Falseraise+ def try_server_side_copy(self, src: str, dst: str) -> bool:+ """Server-side S3 copy via boto3 managed copy.++ ``client.copy`` issues CopyObject (or UploadPartCopy for objects+ above the multipart threshold), so bytes never leave AWS. Requires+ the same s3:GetObject / s3:PutObject permissions as the relay path.+ """+ if not (src.startswith("s3://") and dst.startswith("s3://")):+ return False+ # If boto3/botocore is missing the relay path cannot work either,+ # so let the ImportError propagate rather than masking it.+ from botocore.exceptions import BotoCoreError, ClientError++ client = self._get_client()+ src_bucket, src_key = self._parse_s3_url(src)+ dst_bucket, dst_key = self._parse_s3_url(dst)+ logger.debug("Server-side copy s3://%s/%s to s3://%s/%s", src_bucket, src_key, dst_bucket, dst_key)+ config = self._get_transfer_config()+ copy_source = {"Bucket": src_bucket, "Key": src_key}+ try:+ if config:+ client.copy(copy_source, dst_bucket, dst_key, Config=config)+ else:+ client.copy(copy_source, dst_bucket, dst_key)+ except (BotoCoreError, ClientError) as e:+ logger.warning(+ "S3 server-side copy of %s failed (%s); falling back to download+upload",+ src,+ e,+ )+ return False+ return True+def upload_file(self, src: Path, dst: str) -> None:"""Upload file to S3 with multipart for large files."""client = self._get_client()@@ -548,8 +606,6 @@ class S3Backend(StorageBackend):def upload_directory(self, src: Path, dst: str) -> int:"""Upload directory recursively to S3 with parallel file uploads."""- from concurrent.futures import ThreadPoolExecutor, as_completed-client = self._get_client()bucket, base_key = self._parse_s3_url(dst)config = self._get_transfer_config()@@ -765,6 +821,43 @@ class GCSBackend(StorageBackend):except PreconditionFailed:return False+ def try_server_side_copy(self, src: str, dst: str) -> bool:+ """Server-side GCS copy via the rewrite API.++ ``Blob.rewrite`` copies inside GCS (cross-bucket included) and+ chunks arbitrarily large objects through rewrite tokens, so bytes+ never transit this host.+ """+ if not (src.startswith("gs://") and dst.startswith("gs://")):+ return False+ from google.api_core.exceptions import GoogleAPICallError++ client = self._get_client()+ src_bucket_name, src_path = self._parse_gcs_url(src)+ dst_bucket_name, dst_path = self._parse_gcs_url(dst)+ logger.debug(+ "Server-side copy gs://%s/%s to gs://%s/%s",+ src_bucket_name,+ src_path,+ dst_bucket_name,+ dst_path,+ )+ src_blob = client.bucket(src_bucket_name).blob(src_path)+ dst_blob = client.bucket(dst_bucket_name).blob(dst_path)+ token = None+ try:+ while True:+ token, _bytes_rewritten, _total_bytes = dst_blob.rewrite(src_blob, token=token)+ if token is None:+ return True+ except GoogleAPICallError as e:+ logger.warning(+ "GCS server-side copy of %s failed (%s); falling back to download+upload",+ src,+ e,+ )+ return False+def upload_file(self, src: Path, dst: str) -> None:"""Upload file to GCS."""client = self._get_client()@@ -776,8 +869,6 @@ class GCSBackend(StorageBackend):def upload_directory(self, src: Path, dst: str) -> int:"""Upload directory recursively to GCS with parallel file uploads."""- from concurrent.futures import ThreadPoolExecutor, as_completed-client = self._get_client()bucket_name, base_path = self._parse_gcs_url(dst)bucket = client.bucket(bucket_name)@@ -815,11 +906,376 @@ class GCSBackend(StorageBackend):return count+class AzureBlobBackend(StorageBackend):+ """Azure Blob / ADLS Gen2 backend with parallel uploads."""++ MAX_CONCURRENCY = 16++ # Same-account server-side copies are usually instantaneous, but the+ # Copy Blob operation is asynchronous by contract: poll, then abort and+ # fall back to the download + upload relay if it never settles.+ SERVER_COPY_POLL_INTERVAL_S = 2.0+ SERVER_COPY_TIMEOUT_S = 900.0++ def __init__(self) -> None:+ self._container_clients: dict[tuple[str, str], Any] = {}+ # account -> ("key" | "sas" | "token", credential) describing how the+ # account was authorized; consulted to authorize the *source* blob of+ # a server-side copy (the destination credential never carries over).+ self._account_auth: dict[str, tuple[str, Any]] = {}++ def _parse_azure_url(self, url: str) -> tuple[str, str, str, str]:+ """Parse abfs(s)://[email protected]/path.++ Returns:+ Tuple of (container, account, blob_path, account_url).+ """+ parsed = urlparse(url)+ if parsed.scheme not in AZURE_SCHEMES:+ msg = f"Not an Azure Blob URL: {url}"+ raise ValueError(msg)++ authority = parsed.netloc+ if "@" not in authority:+ msg = "Azure Blob URL must use <container>@<account>.dfs.core.windows.net"+ raise ValueError(msg)++ container, host = authority.split("@", 1)+ if not container or not host:+ msg = "Azure Blob URL container and account must be non-empty"+ raise ValueError(msg)++ account = host+ if account.endswith(".dfs.core.windows.net"):+ account = account[: -len(".dfs.core.windows.net")]+ elif account.endswith(".blob.core.windows.net"):+ account = account[: -len(".blob.core.windows.net")]++ if not account:+ msg = "Azure Blob URL account must be non-empty"+ raise ValueError(msg)++ account_url = f"https://{account}.blob.core.windows.net"+ blob_path = parsed.path.lstrip("/")+ return container, account, blob_path, account_url++ @staticmethod+ def _connection_string_account_name(connection_string: str) -> str | None:+ """Extract the storage account name from an Azure connection string."""+ parts = dict(part.split("=", 1) for part in connection_string.split(";") if "=" in part)+ account = parts.get("AccountName")+ if account:+ return account++ blob_endpoint = parts.get("BlobEndpoint")+ if not blob_endpoint:+ return None++ host = urlparse(blob_endpoint).netloc+ if host.endswith(".blob.core.windows.net"):+ return host[: -len(".blob.core.windows.net")]+ return host.split(".", 1)[0] if host else None++ def _build_container_client(self, container: str, account: str, account_url: str) -> Any:+ """Build an Azure container client from standard environment credentials."""+ try:+ from azure.storage.blob import BlobServiceClient+ except ImportError as e:+ msg = (+ "azure-storage-blob is required for Azure Blob storage. "+ "Install with: pip install azure-storage-blob azure-identity"+ )+ raise ImportError(msg) from e++ connection_string = os.environ.get("AZURE_STORAGE_CONNECTION_STRING")+ if connection_string:+ conn_account = self._connection_string_account_name(connection_string)+ if conn_account and conn_account.lower() != account.lower():+ msg = (+ "AZURE_STORAGE_CONNECTION_STRING AccountName "+ f"({conn_account}) does not match URL account ({account})"+ )+ raise ValueError(msg)+ service_client = BlobServiceClient.from_connection_string(connection_string)+ self._account_auth[account] = ("key", None)+ return service_client.get_container_client(container)++ credential: Any+ account_key = (+ os.environ.get("AZURE_STORAGE_ACCOUNT_KEY")+ or os.environ.get("AZURE_STORAGE_ACCESS_KEY")+ or os.environ.get("AZURE_STORAGE_KEY")+ )+ sas_token = os.environ.get("AZURE_STORAGE_SAS_TOKEN")+ if account_key:+ credential = account_key+ self._account_auth[account] = ("key", None)+ elif sas_token:+ credential = sas_token.lstrip("?")+ self._account_auth[account] = ("sas", credential)+ else:+ try:+ from azure.identity import DefaultAzureCredential+ except ImportError as e:+ msg = (+ "azure-identity is required for Azure Blob storage without "+ "AZURE_STORAGE_CONNECTION_STRING, AZURE_STORAGE_ACCOUNT_KEY, "+ "or AZURE_STORAGE_SAS_TOKEN"+ )+ raise ImportError(msg) from e+ credential = DefaultAzureCredential()+ self._account_auth[account] = ("token", credential)++ service_client = BlobServiceClient(account_url=account_url, credential=credential)+ return service_client.get_container_client(container)++ def _get_container_client(self, url: str) -> tuple[Any, str, str, str]:+ """Return (container client, container, account, blob path) for an abfs(s) URL."""+ container, account, blob_path, account_url = self._parse_azure_url(url)+ key = (account, container)+ if key not in self._container_clients:+ self._container_clients[key] = self._build_container_client(container, account, account_url)+ return self._container_clients[key], container, account, blob_path++ @staticmethod+ def _ensure_prefix(path: str) -> str:+ if path and not path.endswith("/"):+ return f"{path}/"+ return path++ def list_dirs(self, path: str) -> Iterator[str]:+ """List immediate virtual directories in an Azure container."""+ container_client, _, _, prefix = self._get_container_client(path)+ prefix = self._ensure_prefix(prefix)++ for item in container_client.walk_blobs(name_starts_with=prefix, delimiter="/"):+ name = getattr(item, "name", "")+ if not name.endswith("/"):+ continue+ relative = name[len(prefix) :].strip("/")+ if relative and "/" not in relative:+ yield relative++ def list_files(self, path: str, pattern: str = "*") -> Iterator[str]:+ """List files in an Azure container matching pattern."""+ container_client, _, _, prefix = self._get_container_client(path)+ prefix = self._ensure_prefix(prefix)++ for blob in container_client.list_blobs(name_starts_with=prefix):+ name = blob.name+ relative = name[len(prefix) :]+ if "/" not in relative and relative and fnmatch.fnmatch(relative, pattern):+ yield relative++ def download_file(self, src: str, dst: Path) -> None:+ """Download a file from Azure Blob storage."""+ container_client, container, account, blob_path = self._get_container_client(src)+ dst.parent.mkdir(parents=True, exist_ok=True)+ logger.debug("Downloading abfs://%s@%s/%s to %s", container, account, blob_path, dst)+ blob_client = container_client.get_blob_client(blob_path)+ with dst.open("wb") as file:+ blob_client.download_blob().readinto(file)++ def exists(self, path: str) -> bool:+ """Check if an Azure blob exists."""+ container_client, _, _, blob_path = self._get_container_client(path)+ return container_client.get_blob_client(blob_path).exists()++ def has_children(self, path: str) -> bool:+ """Check if an Azure virtual directory has at least one blob beneath it."""+ container_client, _, _, prefix = self._get_container_client(path)+ prefix = self._ensure_prefix(prefix)++ for seen, blob in enumerate(container_client.list_blobs(name_starts_with=prefix, results_per_page=2), start=1):+ if blob.name != prefix:+ return True+ if seen >= 2:+ break+ return False++ def read_text(self, path: str) -> str:+ """Read text content from Azure Blob storage."""+ container_client, _, _, blob_path = self._get_container_client(path)+ return container_client.get_blob_client(blob_path).download_blob().readall().decode("utf-8")++ def write_text(self, path: str, content: str) -> None:+ """Write text content to Azure Blob storage."""+ container_client, _, _, blob_path = self._get_container_client(path)+ container_client.get_blob_client(blob_path).upload_blob(content.encode("utf-8"), overwrite=True)++ def write_text_if_match(self, path: str, content: str, expected_content: str) -> bool:+ """Conditional write to Azure Blob storage using ETags for compare-and-swap."""+ try:+ from azure.core import MatchConditions+ from azure.core.exceptions import ResourceExistsError, ResourceModifiedError, ResourceNotFoundError+ except ImportError as e:+ msg = "azure-core is required for Azure Blob conditional writes"+ raise ImportError(msg) from e++ container_client, _, _, blob_path = self._get_container_client(path)+ blob_client = container_client.get_blob_client(blob_path)++ if not expected_content.strip():+ try:+ blob_client.upload_blob(content.encode("utf-8"), overwrite=False)+ return True+ except ResourceExistsError:+ return False++ try:+ properties = blob_client.get_blob_properties()+ current = blob_client.download_blob().readall().decode("utf-8")+ except ResourceNotFoundError:+ return False++ if current.strip() != expected_content.strip():+ return False++ try:+ blob_client.upload_blob(+ content.encode("utf-8"),+ overwrite=True,+ etag=properties.etag,+ match_condition=MatchConditions.IfNotModified,+ )+ return True+ except ResourceModifiedError:+ return False++ def try_server_side_copy(self, src: str, dst: str) -> bool:+ """Server-side Azure copy within a single storage account.++ Uses the asynchronous Copy Blob From URL operation and polls until+ it settles. Cross-account copies need source SAS provisioning, so+ they report unsupported and take the download + upload relay. Any+ copy-specific failure (e.g. CannotVerifyCopySource) also falls back+ rather than failing the sync.+ """+ azure_url_schemes = ("abfs://", "abfss://")+ if not (src.startswith(azure_url_schemes) and dst.startswith(azure_url_schemes)):+ return False+ _, src_account, _, _ = self._parse_azure_url(src)+ _, dst_account, _, _ = self._parse_azure_url(dst)+ if src_account.lower() != dst_account.lower():+ return False++ from azure.core.exceptions import HttpResponseError++ src_container_client, src_container, _, src_path = self._get_container_client(src)+ dst_container_client, dst_container, _, dst_path = self._get_container_client(dst)+ src_blob = src_container_client.get_blob_client(src_path)+ dst_blob = dst_container_client.get_blob_client(dst_path)++ # Authorize the service-side read of the source. Shared-key /+ # connection-string auth covers same-account sources implicitly;+ # SAS must ride on the source URL; OAuth needs an explicit bearer+ # via x-ms-copy-source-authorization.+ source_url = src_blob.url+ copy_kwargs: dict[str, Any] = {}+ kind, credential = self._account_auth.get(src_account, ("key", None))+ if kind == "sas":+ # BlobClient.url already carries the SAS when the client was+ # built from a SAS credential; only append when it does not.+ if "?" not in source_url:+ source_url = f"{source_url}?{credential}"+ elif kind == "token":+ token = credential.get_token("https://storage.azure.com/.default")+ copy_kwargs["source_authorization"] = f"Bearer {token.token}"++ logger.debug(+ "Server-side copy abfs://%s@%s/%s to abfs://%s@%s/%s",+ src_container,+ src_account,+ src_path,+ dst_container,+ dst_account,+ dst_path,+ )+ copy_started: Any = None+ try:+ copy_started = dst_blob.start_copy_from_url(source_url, **copy_kwargs)+ deadline = time.monotonic() + self.SERVER_COPY_TIMEOUT_S+ while True:+ copy_props = dst_blob.get_blob_properties().copy+ if copy_props.status == "success":+ return True+ if copy_props.status != "pending":+ logger.warning(+ "Azure server-side copy of %s ended with status %r; falling back to download+upload",+ src,+ copy_props.status,+ )+ return False+ if time.monotonic() >= deadline:+ dst_blob.abort_copy(copy_props.id)+ logger.warning(+ "Azure server-side copy of %s timed out after %.0fs; falling back to download+upload",+ src,+ self.SERVER_COPY_TIMEOUT_S,+ )+ return False+ time.sleep(self.SERVER_COPY_POLL_INTERVAL_S)+ except HttpResponseError as e:+ # A copy that is still pending blocks the relay's overwrite, so+ # abort it best-effort before falling back.+ copy_id = copy_started.get("copy_id") if copy_started else None+ if copy_id:+ with contextlib.suppress(HttpResponseError):+ dst_blob.abort_copy(copy_id)+ logger.warning(+ "Azure server-side copy of %s failed (%s); falling back to download+upload",+ src,+ e,+ )+ return False++ def upload_file(self, src: Path, dst: str) -> None:+ """Upload file to Azure Blob storage."""+ container_client, container, account, blob_path = self._get_container_client(dst)+ logger.debug("Uploading %s to abfs://%s@%s/%s", src, container, account, blob_path)+ with src.open("rb") as file:+ container_client.get_blob_client(blob_path).upload_blob(file, overwrite=True)++ def upload_directory(self, src: Path, dst: str) -> int:+ """Upload directory recursively to Azure Blob storage with parallel file uploads."""+ container_client, container, account, base_path = self._get_container_client(dst)++ files_to_upload = []+ for file in src.rglob("*"):+ if file.is_file():+ rel_path = file.relative_to(src)+ blob_path = f"{base_path}/{rel_path}" if base_path else str(rel_path)+ files_to_upload.append((file, blob_path))++ if not files_to_upload:+ return 0++ def upload_one(item: tuple[Path, str]) -> bool:+ file_path, blob_path = item+ logger.debug("Uploading %s to abfs://%s@%s/%s", file_path, container, account, blob_path)+ try:+ with file_path.open("rb") as file:+ container_client.get_blob_client(blob_path).upload_blob(file, overwrite=True)+ return True+ except OSError as e:+ logger.error("Failed to upload %s: %s", file_path, e)+ return False++ count = 0+ with ThreadPoolExecutor(max_workers=self.MAX_CONCURRENCY) as executor:+ futures = {executor.submit(upload_one, f): f for f in files_to_upload}+ for future in as_completed(futures):+ if future.result():+ count += 1++ return count++def get_storage_backend(path: str) -> StorageBackend:"""Get the appropriate storage backend for a path.Args:- path: A local path, S3 URL (s3://...), or GCS URL (gs://...).+ path: A local path, S3 URL (s3://...), GCS URL (gs://...), or Azure URL (abfs(s)://...).Returns:The appropriate StorageBackend instance.@@ -828,26 +1284,28 @@ def get_storage_backend(path: str) -> StorageBackend:return S3Backend()if path.startswith("gs://"):return GCSBackend()+ if path.startswith(("abfs://", "abfss://")):+ return AzureBlobBackend()return LocalBackend()def is_cloud_path(path: str) -> bool:- """Check if a path is a cloud URL (S3 or GCS).+ """Check if a path is a cloud URL (S3, GCS, or Azure Blob).Args:path: Path to check.Returns:- True if path is an S3 or GCS URL.+ True if path is an S3, GCS, or Azure Blob URL."""- return path.startswith(("s3://", "gs://"))+ return path.startswith(CLOUD_SCHEMES)def join_path(base: str, *parts: str) -> str:"""Join path components, handling both local and cloud paths.Args:- base: Base path (local, S3, or GCS).+ base: Base path (local, S3, GCS, or Azure Blob).*parts: Path components to join.Returns:diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex 4a0aeb686..378ba6c2b 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -397,17 +397,40 @@ ChatRole = Literal["system", "user", "assistant", "tool", "developer"]ChatFinishReason = Literal["stop", "length", "tool_calls", "content_filter"] | None+class ChatImageURL(TypedDict, total=False):+ """``image_url`` payload of an image content part — a base64 ``data:`` URI.++ May also be supplied as a bare string (the URI) on ``input_image`` parts.+ """++ url: str+++class ChatContentPart(TypedDict, total=False):+ """One part of a multimodal ``messages[*].content`` array.++ Text parts (``text`` / ``input_text``) carry ``text``; image parts+ (``image_url`` / ``input_image``) carry ``image_url`` as a base64 ``data:``+ URI and are accepted for vision-capable generation models.+ """++ type: Literal["text", "input_text", "image_url", "input_image"]+ text: str+ image_url: str | ChatImageURL++class ChatMessage(TypedDict, total=False):"""A single chat message.- The gateway accepts ``system | user | assistant | tool`` with string- ``content``; ``tool_calls`` / ``tool_call_id`` are honoured on the- multi-turn tool-replay path. See the gateway schema for the canonical- accepted subset.+ The gateway accepts ``system | user | assistant | tool`` roles.+ ``content`` is a string OR an array of :class:`ChatContentPart` (text and,+ for vision-capable generation models, base64 ``data:`` image parts);+ ``tool_calls`` / ``tool_call_id`` are honoured on the multi-turn tool-replay+ path. See the gateway schema for the canonical accepted subset."""role: ChatRole- content: str | None+ content: str | list[ChatContentPart] | Nonename: strtool_call_id: strtool_calls: list[dict[str, Any]]diff --git a/packages/sie_sdk/tests/client/test_timeout.py b/packages/sie_sdk/tests/client/test_timeout.pyindex 91e805390..9f27fcc45 100644--- a/packages/sie_sdk/tests/client/test_timeout.py+++ b/packages/sie_sdk/tests/client/test_timeout.py@@ -1,10 +1,12 @@+import timefrom unittest.mock import MagicMock, patchimport httpximport msgpackimport numpy as npimport pytest-from sie_sdk import SIEClient+from sie_sdk import ModelLoadingError, ProvisioningError, SIEClient, SIEConnectionError+from sie_sdk.client._shared import MODEL_LOADING_ERROR_CODEclass TestTimeoutEnforcement:@@ -21,8 +23,6 @@ class TestTimeoutEnforcement:provision_timeout_s. The safeguard was added to prevent scenarios wherehttpx timeout > provision_timeout, causing requests to block indefinitely."""- from sie_sdk.client._shared import MODEL_LOADING_ERROR_CODE-mock_response_503 = MagicMock()mock_response_503.status_code = 503mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}@@ -61,11 +61,6 @@ class TestTimeoutEnforcement:the cumulative wall-clock time is tracked and the operation times outafter provision_timeout_s."""- import time-- from sie_sdk import ModelLoadingError, ProvisioningError- from sie_sdk.client._shared import MODEL_LOADING_ERROR_CODE-mock_response_503 = MagicMock()mock_response_503.status_code = 503mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}@@ -100,10 +95,6 @@ class TestTimeoutEnforcement:When httpx times out (e.g., server hanging), the SDK retries but stillenforces the overall provision_timeout_s."""- import time-- from sie_sdk import SIEConnectionError-with patch("sie_sdk.client.sync.httpx.Client") as mock_client:# Always raise httpx.TimeoutExceptionmock_client.return_value.post = MagicMock(side_effect=httpx.TimeoutException("Request timed out"))@@ -130,10 +121,6 @@ class TestTimeoutEnforcement:The SDK retries on httpx timeout but enforces provision_timeout_s."""- import time-- from sie_sdk import ProvisioningError-with patch("sie_sdk.client.sync.httpx.Client") as mock_client:# Always raise httpx.TimeoutExceptionmock_client.return_value.post = MagicMock(side_effect=httpx.TimeoutException("Request timed out"))@@ -142,14 +129,19 @@ class TestTimeoutEnforcement:start_time = time.monotonic()provision_timeout = 0.05- # With wait_for_capacity, timeout is retried until provision_timeout- with pytest.raises(ProvisioningError, match="exceeded"):+ # With wait_for_capacity, timeout is retried until provision_timeout.+ # Depending on whether the budget is exhausted before the next+ # request or immediately after the final transport timeout, either+ # terminal error is valid.+ with pytest.raises((ProvisioningError, SIEConnectionError)) as exc_info:client.encode("bge-m3",{"text": "hello"},wait_for_capacity=True,provision_timeout_s=provision_timeout,)+ message = str(exc_info.value).lower()+ assert "timeout" in message or "timed out" in messageelapsed = time.monotonic() - start_timediff --git a/packages/sie_sdk/tests/test_cache.py b/packages/sie_sdk/tests/test_cache.pyindex 05af139ad..40b280a28 100644--- a/packages/sie_sdk/tests/test_cache.py+++ b/packages/sie_sdk/tests/test_cache.py@@ -68,6 +68,14 @@ class TestGetCacheConfig:assert config.cluster_cache == "gs://my-bucket/models"+ def test_cluster_cache_azure(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Azure cluster cache URL parsed correctly."""+ monkeypatch.setenv("SIE_CLUSTER_CACHE", "abfs://[email protected]/models")++ config = get_cache_config()++ assert config.cluster_cache == "abfs://[email protected]/models"+def test_hf_fallback_disabled(self, monkeypatch: pytest.MonkeyPatch) -> None:"""SIE_HF_FALLBACK=false disables HF fallback."""monkeypatch.setenv("SIE_HF_FALLBACK", "false")diff --git a/packages/sie_sdk/tests/test_storage.py b/packages/sie_sdk/tests/test_storage.pyindex ac13c7101..7d53cc29b 100644--- a/packages/sie_sdk/tests/test_storage.py+++ b/packages/sie_sdk/tests/test_storage.py@@ -1,9 +1,13 @@"""Tests for storage backend functionality."""+import sys+import typesfrom pathlib import Pathfrom unittest.mock import MagicMock+import pytestfrom sie_sdk.storage import (+ AzureBlobBackend,GCSBackend,LocalBackend,S3Backend,@@ -366,6 +370,162 @@ class TestGCSBackendHasChildren:assert backend.has_children("gs://sie-cache/seeded/snapshots") is True+class TestAzureBlobBackend:+ """Tests for ``AzureBlobBackend`` URL parsing and prefix semantics."""++ def _install_fake_blob_module(+ self,+ monkeypatch: pytest.MonkeyPatch,+ blob_service_client: type[object],+ ) -> None:+ azure_module = types.ModuleType("azure")+ storage_module = types.ModuleType("azure.storage")+ blob_module = types.ModuleType("azure.storage.blob")+ blob_module.BlobServiceClient = blob_service_client+ monkeypatch.setitem(sys.modules, "azure", azure_module)+ monkeypatch.setitem(sys.modules, "azure.storage", storage_module)+ monkeypatch.setitem(sys.modules, "azure.storage.blob", blob_module)++ def _backend_with_mock_container(self, container_client: MagicMock) -> AzureBlobBackend:+ backend = AzureBlobBackend()+ backend._container_clients[("sieacct", "sie-cache")] = container_client+ return backend++ def test_parse_abfs_url(self) -> None:+ backend = AzureBlobBackend()++ container, account, path, account_url = backend._parse_azure_url(+ "abfs://[email protected]/models/org/model"+ )++ assert container == "sie-cache"+ assert account == "sieacct"+ assert path == "models/org/model"+ assert account_url == "https://sieacct.blob.core.windows.net"++ def test_parse_abfss_blob_endpoint_url(self) -> None:+ backend = AzureBlobBackend()++ container, account, path, account_url = backend._parse_azure_url(+ "abfss://[email protected]/models"+ )++ assert container == "sie-cache"+ assert account == "sieacct"+ assert path == "models"+ assert account_url == "https://sieacct.blob.core.windows.net"++ def test_parse_requires_container_account_separator(self) -> None:+ backend = AzureBlobBackend()++ with pytest.raises(ValueError, match="must use <container>@<account>"):+ backend._parse_azure_url("abfs://sie-cache/models")++ def test_has_children_returns_true_when_prefix_has_children(self) -> None:+ container_client = MagicMock()+ child = MagicMock()+ child.name = "models/models--BAAI--bge-m3/snapshots/abc/config.json"+ container_client.list_blobs.return_value = iter([child])+ backend = self._backend_with_mock_container(container_client)++ assert (+ backend.has_children("abfs://[email protected]/models/models--BAAI--bge-m3/snapshots")+ is True+ )++ container_client.list_blobs.assert_called_once_with(+ name_starts_with="models/models--BAAI--bge-m3/snapshots/",+ results_per_page=2,+ )++ def test_has_children_returns_false_when_only_folder_marker_exists(self) -> None:+ container_client = MagicMock()+ marker = MagicMock()+ marker.name = "models/seeded/snapshots/"+ container_client.list_blobs.return_value = iter([marker])+ backend = self._backend_with_mock_container(container_client)++ assert backend.has_children("abfs://[email protected]/models/seeded/snapshots") is False++ def test_list_dirs_uses_hierarchical_prefixes(self) -> None:+ container_client = MagicMock()+ directory = MagicMock()+ directory.name = "models/models--BAAI--bge-m3/"+ file_blob = MagicMock()+ file_blob.name = "models/config.json"+ container_client.walk_blobs.return_value = iter([directory, file_blob])+ backend = self._backend_with_mock_container(container_client)++ assert list(backend.list_dirs("abfs://[email protected]/models")) == [+ "models--BAAI--bge-m3"+ ]+ container_client.walk_blobs.assert_called_once_with(name_starts_with="models/", delimiter="/")++ def test_list_files_filters_to_immediate_files(self) -> None:+ container_client = MagicMock()+ direct = MagicMock()+ direct.name = "models/config.yaml"+ nested = MagicMock()+ nested.name = "models/subdir/config.yaml"+ other = MagicMock()+ other.name = "models/readme.md"+ container_client.list_blobs.return_value = iter([direct, nested, other])+ backend = self._backend_with_mock_container(container_client)++ assert list(backend.list_files("abfss://[email protected]/models", "*.yaml")) == [+ "config.yaml"+ ]++ def test_connection_string_account_mismatch_raises(self, monkeypatch: pytest.MonkeyPatch) -> None:+ class FakeBlobServiceClient:+ @classmethod+ def from_connection_string(cls, connection_string: str) -> "FakeBlobServiceClient":+ raise AssertionError("mismatched connection string should be rejected before client construction")++ backend = AzureBlobBackend()+ self._install_fake_blob_module(monkeypatch, FakeBlobServiceClient)+ monkeypatch.setenv(+ "AZURE_STORAGE_CONNECTION_STRING",+ "DefaultEndpointsProtocol=https;AccountName=otheracct;AccountKey=fake;EndpointSuffix=core.windows.net",+ )++ with pytest.raises(ValueError, match="does not match URL account"):+ backend._build_container_client(+ "sie-cache",+ "sieacct",+ "https://sieacct.blob.core.windows.net",+ )++ def test_connection_string_matching_account_returns_container(self, monkeypatch: pytest.MonkeyPatch) -> None:+ container_client = MagicMock()++ class FakeBlobServiceClient:+ @classmethod+ def from_connection_string(cls, connection_string: str) -> "FakeBlobServiceClient":+ assert "AccountName=sieacct" in connection_string+ return cls()++ def get_container_client(self, container: str) -> MagicMock:+ assert container == "sie-cache"+ return container_client++ backend = AzureBlobBackend()+ self._install_fake_blob_module(monkeypatch, FakeBlobServiceClient)+ monkeypatch.setenv(+ "AZURE_STORAGE_CONNECTION_STRING",+ "DefaultEndpointsProtocol=https;AccountName=sieacct;AccountKey=fake;EndpointSuffix=core.windows.net",+ )++ assert (+ backend._build_container_client(+ "sie-cache",+ "sieacct",+ "https://sieacct.blob.core.windows.net",+ )+ is container_client+ )++class TestHelperFunctions:"""Tests for module-level helper functions."""@@ -373,6 +533,8 @@ class TestHelperFunctions:"""Cloud path detection works correctly."""assert is_cloud_path("s3://bucket/key")assert is_cloud_path("gs://bucket/key")+ assert is_cloud_path("abfs://[email protected]/key")+ assert is_cloud_path("abfss://[email protected]/key")assert not is_cloud_path("/local/path")assert not is_cloud_path("./relative/path")@@ -391,12 +553,19 @@ class TestHelperFunctions:result = join_path("gs://bucket/prefix/", "dir", "file.txt")assert result == "gs://bucket/prefix/dir/file.txt"+ def test_join_path_azure(self) -> None:+ """Path joining works for Azure Blob paths."""+ result = join_path("abfs://[email protected]/models/", "dir", "file.txt")+ assert result == "abfs://[email protected]/models/dir/file.txt"+def test_get_storage_backend(self) -> None:"""Backend selection works correctly."""assert isinstance(get_storage_backend("/local/path"), LocalBackend)- # S3 and GCS backends are lazily initialized,+ # Cloud backends are lazily initialized,# so we just check we get the right type- from sie_sdk.storage import GCSBackend, S3Backend-assert isinstance(get_storage_backend("s3://bucket"), S3Backend)assert isinstance(get_storage_backend("gs://bucket"), GCSBackend)+ assert isinstance(get_storage_backend("abfs://[email protected]/models"), AzureBlobBackend)+ assert isinstance(+ get_storage_backend("abfss://[email protected]/models"), AzureBlobBackend+ )diff --git a/packages/sie_sdk/tests/test_storage_copy.py b/packages/sie_sdk/tests/test_storage_copy.pynew file mode 100644index 000000000..c0f8978b5--- /dev/null+++ b/packages/sie_sdk/tests/test_storage_copy.py@@ -0,0 +1,260 @@+"""Tests for StorageBackend.try_server_side_copy implementations."""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++from azure.core.exceptions import HttpResponseError+from botocore.exceptions import ClientError+from google.api_core.exceptions import Forbidden+from sie_sdk.storage import AzureBlobBackend, GCSBackend, LocalBackend, S3Backend+++class FakeS3Client:+ def __init__(self) -> None:+ self.copies: list[tuple[dict[str, str], str, str]] = []++ def copy(self, copy_source: dict[str, str], bucket: str, key: str, Config: Any = None) -> None: # noqa: N803+ self.copies.append((copy_source, bucket, key))+++class TestS3ServerSideCopy:+ def test_cross_provider_is_unsupported(self) -> None:+ backend = S3Backend()+ assert backend.try_server_side_copy("s3://bucket/a.bin", "gs://bucket/a.bin") is False+ assert backend.try_server_side_copy("gs://bucket/a.bin", "s3://bucket/a.bin") is False+ # Unsupported pairs must not touch (or lazily build) the client.+ assert backend._client is None++ def test_same_provider_issues_copy_object(self) -> None:+ backend = S3Backend()+ client = FakeS3Client()+ backend._client = client++ result = backend.try_server_side_copy("s3://src-bucket/path/a.bin", "s3://dst-bucket/other/a.bin")++ assert result is True+ assert client.copies == [({"Bucket": "src-bucket", "Key": "path/a.bin"}, "dst-bucket", "other/a.bin")]++ def test_client_error_falls_back(self) -> None:+ backend = S3Backend()++ class FailingS3Client:+ def copy(self, copy_source: dict[str, str], bucket: str, key: str, Config: Any = None) -> None: # noqa: N803+ raise ClientError({"Error": {"Code": "AccessDenied", "Message": "denied"}}, "CopyObject")++ backend._client = FailingS3Client()++ assert backend.try_server_side_copy("s3://src-bucket/a.bin", "s3://dst-bucket/a.bin") is False+++class FakeGcsBlob:+ def __init__(self, name: str) -> None:+ self.name = name+ self.rewrite_calls: list[tuple[str, str | None]] = []++ def rewrite(self, source: FakeGcsBlob, token: str | None = None) -> tuple[str | None, int, int]:+ self.rewrite_calls.append((source.name, token))+ # First call returns a continuation token, second completes — covers+ # the multi-step rewrite loop for large objects.+ next_token = "tok-1" if token is None else None+ return (next_token, 100, 200)+++class FakeGcsBucket:+ def __init__(self, name: str) -> None:+ self.name = name+ self.blobs: dict[str, FakeGcsBlob] = {}++ def blob(self, path: str) -> FakeGcsBlob:+ return self.blobs.setdefault(path, FakeGcsBlob(path))+++class FakeGcsClient:+ def __init__(self) -> None:+ self.buckets: dict[str, FakeGcsBucket] = {}++ def bucket(self, name: str) -> FakeGcsBucket:+ return self.buckets.setdefault(name, FakeGcsBucket(name))+++class TestGcsServerSideCopy:+ def test_cross_provider_is_unsupported(self) -> None:+ backend = GCSBackend()+ assert backend.try_server_side_copy("gs://bucket/a.bin", "s3://bucket/a.bin") is False+ assert backend._client is None++ def test_same_provider_loops_rewrite_until_done(self) -> None:+ backend = GCSBackend()+ client = FakeGcsClient()+ backend._client = client++ result = backend.try_server_side_copy("gs://src-bucket/path/a.bin", "gs://dst-bucket/other/a.bin")++ assert result is True+ dst_blob = client.buckets["dst-bucket"].blobs["other/a.bin"]+ assert dst_blob.rewrite_calls == [("path/a.bin", None), ("path/a.bin", "tok-1")]++ def test_api_error_falls_back(self) -> None:+ backend = GCSBackend()+ client = FakeGcsClient()+ backend._client = client++ def raise_forbidden(source: FakeGcsBlob, token: str | None = None) -> tuple[str | None, int, int]:+ raise Forbidden("denied")++ client.bucket("dst-bucket").blob("other/a.bin").rewrite = raise_forbidden # type: ignore[method-assign]++ assert backend.try_server_side_copy("gs://src-bucket/path/a.bin", "gs://dst-bucket/other/a.bin") is False+++class FakeAzureBlobClient:+ def __init__(self, url: str, statuses: list[str]) -> None:+ self.url = url+ self._statuses = statuses+ self.copy_calls: list[tuple[str, dict[str, Any]]] = []+ self.aborted: list[str] = []+ self.properties_error: Exception | None = None++ def start_copy_from_url(self, source_url: str, **kwargs: Any) -> dict[str, Any]:+ self.copy_calls.append((source_url, kwargs))+ return {"copy_id": "copy-1", "copy_status": "pending"}++ def get_blob_properties(self) -> Any:+ if self.properties_error is not None:+ raise self.properties_error+ status = self._statuses.pop(0) if len(self._statuses) > 1 else self._statuses[0]+ return SimpleNamespace(copy=SimpleNamespace(status=status, id="copy-1"))++ def abort_copy(self, copy_id: str) -> None:+ self.aborted.append(copy_id)+++class FakeAzureContainerClient:+ def __init__(self, account: str, container: str, statuses: list[str] | None = None) -> None:+ self.account = account+ self.container = container+ self.statuses = statuses if statuses is not None else ["success"]+ self.blob_clients: dict[str, FakeAzureBlobClient] = {}++ def get_blob_client(self, path: str) -> FakeAzureBlobClient:+ url = f"https://{self.account}.blob.core.windows.net/{self.container}/{path}"+ return self.blob_clients.setdefault(path, FakeAzureBlobClient(url, self.statuses))+++class FakeTokenCredential:+ def get_token(self, scope: str) -> Any:+ return SimpleNamespace(token="tok-123") # noqa: S106 - test fixture, not a secret+++def _azure_backend_with_fakes(+ statuses: list[str] | None = None,+) -> tuple[AzureBlobBackend, FakeAzureContainerClient, FakeAzureContainerClient]:+ backend = AzureBlobBackend()+ backend.SERVER_COPY_POLL_INTERVAL_S = 0.0 # type: ignore[misc]+ src_container = FakeAzureContainerClient("sieacct", "source")+ dst_container = FakeAzureContainerClient("sieacct", "dest", statuses=statuses)+ backend._container_clients[("sieacct", "source")] = src_container+ backend._container_clients[("sieacct", "dest")] = dst_container+ return backend, src_container, dst_container+++class TestAzureServerSideCopy:+ SRC = "abfs://[email protected]/models/a.bin"+ DST = "abfss://[email protected]/models/a.bin"++ def test_cross_provider_is_unsupported(self) -> None:+ backend = AzureBlobBackend()+ assert backend.try_server_side_copy("abfs://[email protected]/x", "s3://bucket/x") is False+ assert backend._container_clients == {}++ def test_cross_account_is_unsupported(self) -> None:+ backend = AzureBlobBackend()+ result = backend.try_server_side_copy(+ "abfs://[email protected]/x",+ "abfs://[email protected]/x",+ )+ assert result is False+ # Decided from URL parsing alone — no clients built.+ assert backend._container_clients == {}++ def test_same_account_copy_succeeds(self) -> None:+ backend, src_container, dst_container = _azure_backend_with_fakes()++ result = backend.try_server_side_copy(self.SRC, self.DST)++ assert result is True+ dst_blob = dst_container.blob_clients["models/a.bin"]+ ((source_url, kwargs),) = dst_blob.copy_calls+ assert source_url == src_container.blob_clients["models/a.bin"].url+ assert kwargs == {}++ def test_pending_copy_polls_until_success(self) -> None:+ backend, _, _ = _azure_backend_with_fakes(statuses=["pending", "success"])++ assert backend.try_server_side_copy(self.SRC, self.DST) is True++ def test_failed_copy_falls_back(self) -> None:+ backend, _, _ = _azure_backend_with_fakes(statuses=["failed"])++ assert backend.try_server_side_copy(self.SRC, self.DST) is False++ def test_http_error_falls_back(self) -> None:+ backend, _, dst_container = _azure_backend_with_fakes()++ def raise_http_error(source_url: str, **kwargs: Any) -> None:+ raise HttpResponseError(message="CannotVerifyCopySource")++ dst_blob = dst_container.get_blob_client("models/a.bin")+ dst_blob.start_copy_from_url = raise_http_error # type: ignore[method-assign]++ assert backend.try_server_side_copy(self.SRC, self.DST) is False+ # No copy ever started — nothing to abort.+ assert dst_blob.aborted == []++ def test_http_error_after_copy_started_aborts_pending_copy(self) -> None:+ backend, _, dst_container = _azure_backend_with_fakes()+ dst_blob = dst_container.get_blob_client("models/a.bin")+ dst_blob.properties_error = HttpResponseError(message="transient poll failure")++ assert backend.try_server_side_copy(self.SRC, self.DST) is False+ # The in-flight copy must be aborted so the relay's overwrite+ # is not rejected with a pending-copy conflict.+ assert dst_blob.aborted == ["copy-1"]++ def test_token_credential_sets_source_authorization(self) -> None:+ backend, _, dst_container = _azure_backend_with_fakes()+ backend._account_auth["sieacct"] = ("token", FakeTokenCredential())++ assert backend.try_server_side_copy(self.SRC, self.DST) is True+ ((_, kwargs),) = dst_container.blob_clients["models/a.bin"].copy_calls+ assert kwargs == {"source_authorization": "Bearer tok-123"}++ def test_sas_credential_rides_on_source_url(self) -> None:+ backend, src_container, dst_container = _azure_backend_with_fakes()+ backend._account_auth["sieacct"] = ("sas", "sig=abc")++ assert backend.try_server_side_copy(self.SRC, self.DST) is True+ ((source_url, kwargs),) = dst_container.blob_clients["models/a.bin"].copy_calls+ assert source_url == f"{src_container.blob_clients['models/a.bin'].url}?sig=abc"+ assert kwargs == {}++ def test_sas_already_on_source_url_is_not_double_appended(self) -> None:+ backend, src_container, dst_container = _azure_backend_with_fakes()+ backend._account_auth["sieacct"] = ("sas", "sig=abc")+ # BlobClient.url carries the SAS when the client was built from a+ # SAS credential — the copy must not append it a second time.+ src_blob = src_container.get_blob_client("models/a.bin")+ src_blob.url += "?sig=abc"++ assert backend.try_server_side_copy(self.SRC, self.DST) is True+ ((source_url, _),) = dst_container.blob_clients["models/a.bin"].copy_calls+ assert source_url == src_blob.url+ assert source_url.count("?") == 1+++class TestBaseBackendDefault:+ def test_local_backend_reports_unsupported(self, tmp_path: Any) -> None:+ backend = LocalBackend()+ assert backend.try_server_side_copy(str(tmp_path / "a"), str(tmp_path / "b")) is Falsediff --git a/packages/sie_server/models/MoritzLaurer__ModernBERT-base-zeroshot-v2.0.yaml b/packages/sie_server/models/MoritzLaurer__ModernBERT-base-zeroshot-v2.0.yamlnew file mode 100644index 000000000..c1c41cf35--- /dev/null+++ b/packages/sie_server/models/MoritzLaurer__ModernBERT-base-zeroshot-v2.0.yaml@@ -0,0 +1,22 @@+sie_id: MoritzLaurer/ModernBERT-base-zeroshot-v2.0+hf_id: MoritzLaurer/ModernBERT-base-zeroshot-v2.0+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode: null+ score: null+ extract: {}+max_sequence_length: 512+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server.adapters.nli_classification_flash:NLIClassificationFlashAdapter+ adapter_options:+ loadtime: {}+ runtime:+ hypothesis_template: This text is about {}.+ multi_label: falsediff --git a/packages/sie_server/models/facebook__bart-large-mnli.yaml b/packages/sie_server/models/facebook__bart-large-mnli.yamlnew file mode 100644index 000000000..577779294--- /dev/null+++ b/packages/sie_server/models/facebook__bart-large-mnli.yaml@@ -0,0 +1,22 @@+sie_id: facebook/bart-large-mnli+hf_id: facebook/bart-large-mnli+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode: null+ score: null+ extract: {}+max_sequence_length: 512+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server.adapters.nli_classification_flash:NLIClassificationFlashAdapter+ adapter_options:+ loadtime: {}+ runtime:+ hypothesis_template: This text is about {}.+ multi_label: falsediff --git a/packages/sie_server/models/fastino__gliner2-large-v1.yaml b/packages/sie_server/models/fastino__gliner2-large-v1.yamlnew file mode 100644index 000000000..7803dd125--- /dev/null+++ b/packages/sie_server/models/fastino__gliner2-large-v1.yaml@@ -0,0 +1,20 @@+sie_id: fastino/gliner2-large-v1+hf_id: fastino/gliner2-large-v1+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode: null+ score: null+ extract: {}+max_sequence_length: 512+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: float16+ adapter_path: sie_server.adapters.gliner2:GLiNER2Adapter+ adapter_options:+ loadtime: {}+ runtime: {}diff --git a/packages/sie_server/models/google__owlv2-large-patch14-ensemble.yaml b/packages/sie_server/models/google__owlv2-large-patch14-ensemble.yamlnew file mode 100644index 000000000..49f4c27d2--- /dev/null+++ b/packages/sie_server/models/google__owlv2-large-patch14-ensemble.yaml@@ -0,0 +1,21 @@+sie_id: google/owlv2-large-patch14-ensemble+hf_id: google/owlv2-large-patch14-ensemble+inputs:+ text: false+ image: true+ audio: false+ video: false+tasks:+ encode: null+ score: null+ extract: {}+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: float16+ adapter_path: sie_server.adapters.owlv2:Owlv2Adapter+ adapter_options:+ loadtime:+ score_threshold: 0.1+ runtime:+ score_threshold: 0.1diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 275a475d0..a26b423e1 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -3,7 +3,7 @@"info": {"title": "SIE Server","description": "Search Inference Engine - GPU inference server for search workloads",- "version": "0.6.2"+ "version": "0.6.3"},"paths": {"/": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex 942cd6ec7..8971876ca 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.2"+version = "0.6.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/_generation_base.py b/packages/sie_server/src/sie_server/adapters/_generation_base.pyindex 640388118..532752e95 100644--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py@@ -23,6 +23,7 @@ from typing import Any, ClassVar, Literal, castfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDims+from sie_server.types.inputs import ImageInputlogger = logging.getLogger(__name__)@@ -247,6 +248,7 @@ class GenerationAdapter(ModelAdapter):logit_bias: dict[str, float] | None = None,logprobs: bool = False,top_logprobs: int | None = None,+ images: list[ImageInput] | None = None,) -> AsyncIterator[GenerationChunk]:"""Stream generation chunks from a prompt.@@ -279,6 +281,13 @@ class GenerationAdapter(ModelAdapter):with per-token log-probabilities.top_logprobs: How many alternates per position; onlyconsulted when ``logprobs`` is True.+ images: Optional list of wire-format :class:`ImageInput`+ entries for vision-language models. The ``prompt`` is+ expected to already carry the model's image placeholder+ tokens (rendered by the chat template upstream); the+ adapter forwards the image bytes to the engine. ``None``+ or empty for text-only generation. Text-only adapters may+ ignore this argument.Yields::class:`GenerationChunk` instances. At least one terminaldiff --git a/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py b/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.pyindex 8879d459d..157379a5a 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@@ -346,6 +346,31 @@ class NemoColEmbedAdapter(BaseAdapter):num_image_token,)+ def get_preprocessor(self) -> Any:+ """Register BOTH a text and an image preprocessor for v1 (#1163).++ v1 documents must take the conformant ``_encode_images_preprocessed`` path,+ which requires an *image* preprocessor to be registered so the encode pipeline+ produces a ``NemoColEmbedPayload`` (with ``pixel_values``) instead of a+ passthrough ``ImagePayload``. Without it every doc batch falls back to the+ model's ``forward_passages`` — which re-tiles each page inline on one thread,+ ~3x slower than running the tiling upstream in the preprocessing thread pool.++ But v1 *queries* (text) still go through ``model.forward_queries`` and rely on+ the batched worker path; registering only the image preprocessor de-registers+ the text one and routes queries to the unbatched direct-call path, which has+ surfaced ``forward_queries`` failures. So we register both: the base+ ``CharCountPreprocessor`` (text → worker-batched queries) and the+ ``NemoColEmbedPreprocessor`` (image → conformant docs). ``model_loader``+ registers each entry of the returned list by its ``modality``.++ v2 (Qwen3-VL backbone) builds no ``_processor`` (``None``); it keeps just the+ base text preprocessor and its native ``forward_images`` path (with #1055 fix).+ """+ if self._processor is None:+ return super().get_preprocessor()+ return [super().get_preprocessor(), self._processor]+def encode(self,items: list[Item],@@ -606,14 +631,25 @@ class NemoColEmbedAdapter(BaseAdapter):if self._normalize:embeddings = functional.normalize(embeddings, p=2, dim=-1)- # Store results for this sub-batch (move to CPU immediately to free GPU memory)+ # Store results for this sub-batch (move to CPU immediately to free GPU+ # memory). Trim each item's left-padding rows before returning: the batch is+ # left-padded, so padded positions are zeroed by the attention_mask above —+ # but emitting them as zero vectors leaks 0-similarity rows into the late-+ # interaction MaxSim (a 0-floor on every query token's max). Because the+ # batcher pads inconsistently across docs, identical docs then score+ # differently by batch and ranking is corrupted on variable-tile batches+ # (#1163: Vidore3 Hr 0.6532 -> 0.5713). Keep only real tokens, matching the+ # native forward_passages path (_unpack_embeddings drops zero rows likewise).for i in range(len(sub_batch_items)):- emb = embeddings[i].float().cpu().numpy()+ keep = batch["attention_mask"][i].bool()+ emb = embeddings[i][keep].float().cpu().numpy()all_embeddings.append(emb)- # Clear GPU memory between sub-batches- del outputs, embeddings, batch- torch.cuda.empty_cache()+ # Free this sub-batch's GPU tensors. NOTE: no per-sub-batch+ # torch.cuda.empty_cache() — repeatedly releasing the allocator's cache and+ # re-acquiring ~GB blocks fragments the pool and OOMs at scale on big GPUs+ # (#1163). The sub-batch loop + immediate CPU offload already bound peak VRAM.+ del outputs, embeddings, attention_mask, batchreturn EncodeOutput(multivector=all_embeddings,diff --git a/packages/sie_server/src/sie_server/adapters/owlv2/__init__.py b/packages/sie_server/src/sie_server/adapters/owlv2/__init__.pyindex 74d86bba4..927527169 100644--- a/packages/sie_server/src/sie_server/adapters/owlv2/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/owlv2/__init__.py@@ -189,7 +189,7 @@ class Owlv2Adapter(BaseAdapter):# Extract options onceopts = options or {}- score_threshold = opts.get("score_threshold", self._score_threshold)+ score_threshold = opts.get("score_threshold", opts.get("threshold", self._score_threshold))# Build text queries once (shared across batch)# OWL-v2 format: list of prompts per imagediff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 4a4711aa9..5fe3221e3 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -19,6 +19,7 @@ HTTP connection, which SGLang treats as a cancel signal. A best-effortfrom __future__ import annotationsimport asyncio+import base64import contextlibimport dataclassesimport json@@ -47,6 +48,7 @@ from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.adapters.sglang import _serverfrom sie_server.observability.metrics import GenerationStreamTimerfrom sie_server.types.grammar import GrammarSpec+from sie_server.types.inputs import ImageInput, media_byteslogger = logging.getLogger(__name__)@@ -91,6 +93,47 @@ def _resolve_read_timeout() -> float | None:_GENERATE_READ_TIMEOUT_S: float | None = _resolve_read_timeout()+# Format hints we re-embed into the SGLang ``image_data`` MIME type. Anything+# else falls back to ``jpeg`` (the engine sniffs the real format from bytes).+_ALLOWED_IMAGE_FORMATS = frozenset({"png", "jpeg", "jpg", "webp", "gif"})+++def _encode_image_data(images: list[ImageInput] | None) -> list[str] | None:+ """Translate wire ``ImageInput`` entries into SGLang ``image_data`` URIs.++ SGLang's ``/generate`` accepts a top-level ``image_data`` field — a list of+ images, each as a base64 string, an ``http(s)`` URL, or a local file path.+ We emit ``data:image/<fmt>;base64,<...>`` data URIs so the format hint+ travels with the bytes and SGLang's image loader can decode without+ sniffing. Bytes are validated through :func:`media_bytes`, the single+ enforcement point for the wire contract (raises :class:`InvalidMediaError`+ on a non-bytes ``data``, e.g. an un-decoded base64 JSON string).++ Returns ``None`` when there are no images so the request body stays+ byte-identical to the text-only path — vision plumbing is inert for the+ text-only models that share this adapter.+ """+ if not images:+ return None+ encoded: list[str] = []+ for image in images:+ raw = media_bytes(image, kind="image")+ fmt = (image.get("format") or "jpeg").strip().lower() or "jpeg"+ # Clamp the client-controlled format hint to a known set before+ # re-embedding it in the data-URI MIME type — an arbitrary subtype+ # would produce a malformed URI for SGLang's loader. The engine+ # sniffs the real format from the bytes regardless, so an unknown+ # hint safely falls back to jpeg.+ if fmt not in _ALLOWED_IMAGE_FORMATS:+ fmt = "jpeg"+ elif fmt == "jpg":+ # ``image/jpg`` is not a registered MIME type; normalise to jpeg.+ fmt = "jpeg"+ b64 = base64.b64encode(raw).decode("ascii")+ encoded.append(f"data:image/{fmt};base64,{b64}")+ return encoded++def _tail_file(path: str, *, max_lines: int = 200) -> str:"""Return the final lines from a startup log for diagnostics."""try:@@ -764,9 +807,17 @@ class SGLangGenerationAdapter(GenerationAdapter):best_of: int | None = None,stream: bool = False,lora_path: str | None = None,+ images: list[ImageInput] | None = None,) -> AsyncIterator[GenerationChunk]:self._check_loaded()+ # Vision input: encode any images into SGLang's top-level ``image_data``+ # field once, then attach to whichever request body we build below. The+ # ``prompt`` is expected to already carry the model's image placeholder+ # tokens (the chat template renders them worker-side). ``None`` when+ # there are no images, keeping the text-only request body unchanged.+ image_data = _encode_image_data(images)+# Guard verdict thresholding only runs on the single-candidate (n=1)# path, so reject multi-candidate sampling up front — otherwise a guard# request with n>1 / best_of>1 would silently return an UN-thresholded@@ -892,6 +943,8 @@ class SGLangGenerationAdapter(GenerationAdapter):}if lora_path:sbody["lora_path"] = lora_path+ if image_data:+ sbody["image_data"] = image_dataif logprobs:sbody["return_logprob"] = True# Without this SGLang omits the decoded token TEXT from@@ -1023,6 +1076,8 @@ class SGLangGenerationAdapter(GenerationAdapter):nbody: dict[str, Any] = {"text": prompt, "sampling_params": sp, "stream": False}if lora_path:nbody["lora_path"] = lora_path+ if image_data:+ nbody["image_data"] = image_dataif logprobs or rank:nbody["return_logprob"] = True# Surface decoded token text (see streaming body below) so the@@ -1125,6 +1180,8 @@ class SGLangGenerationAdapter(GenerationAdapter):# verified on L4). Empirically applies the adapter in-batch per request.if lora_path:body["lora_path"] = lora_path+ if image_data:+ body["image_data"] = image_data# OpenAI ``logprobs`` → SGLang ``return_logprob`` (top-level body# flag, not under sampling_params). ``top_logprobs`` →# ``top_logprobs_num``. SGLang surfaces them underdiff --git a/packages/sie_server/src/sie_server/app/app_state_config.py b/packages/sie_server/src/sie_server/app/app_state_config.pyindex c8ce7ccd9..782f82638 100644--- a/packages/sie_server/src/sie_server/app/app_state_config.py+++ b/packages/sie_server/src/sie_server/app/app_state_config.py@@ -20,7 +20,7 @@ class AppStateConfig:"""models_dir: Path | str | None = None- """Path to models directory (local path, s3://, or gs://). If None, registry starts empty."""+ """Path to models directory (local path, s3://, gs://, abfs://, or abfss://). If None, registry starts empty."""device: str = "cpu""""Device to load models on (e.g., "cuda:0", "cpu", "mps")."""diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.pyindex 0e72af5cb..4b8f8db50 100644--- a/packages/sie_server/src/sie_server/cli.py+++ b/packages/sie_server/src/sie_server/cli.py@@ -220,12 +220,18 @@ def serve(host: str = typer.Option("0.0.0.0", "--host", help="Host to bind to"), # noqa: S104 — intentional bind to all interfaces for serverdevice: str = typer.Option("auto", "--device", "-d", help="Device to use (auto, cuda, mps, cpu)"),models_dir: str = typer.Option(- DEFAULT_MODELS_DIR, "--models-dir", help="Models directory (local path, s3://, or gs://)"+ DEFAULT_MODELS_DIR,+ "--models-dir",+ help="Models directory (local path, s3://, gs://, abfs://, or abfss://)",),bundle: str | None = typer.Option(None, "--bundle", "-b", help="Bundle name to load (from bundles/ dir)"),models: str | None = typer.Option(None, "--models", "-m", help="Comma-separated model names to load"),local_cache: str | None = typer.Option(None, "--local-cache", help="Local cache directory (default: HF_HOME)"),- cluster_cache: str | None = typer.Option(None, "--cluster-cache", help="Cluster cache URL (s3:// or gs://)"),+ cluster_cache: str | None = typer.Option(+ None,+ "--cluster-cache",+ help="Cluster cache URL (s3://, gs://, abfs://, or abfss://)",+ ),hf_fallback: bool = typer.Option(True, "--hf-fallback/--no-hf-fallback", help="Enable HuggingFace Hub fallback"),reload: bool = typer.Option(default=False, help="Enable auto-reload for development"),tracing: bool = typer.Option(default=False, help="Enable OpenTelemetry tracing (exports to localhost:4317)"),diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.pyindex 0337f9a99..90f2275ba 100644--- a/packages/sie_server/src/sie_server/core/loader.py+++ b/packages/sie_server/src/sie_server/core/loader.py@@ -48,7 +48,7 @@ def load_model_configs(models_dir: Path | str) -> dict[str, ModelConfig]:"""Load all model configs from a directory (local or cloud).Args:- models_dir: Path to the models directory (local path, s3://, or gs://).+ models_dir: Path to the models directory (local path, s3://, gs://, abfs://, or abfss://).Returns:Dictionary mapping model names to their ModelConfig objects.@@ -141,7 +141,7 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:def _load_configs_from_cloud(models_dir: str) -> dict[str, ModelConfig]:- """Load model configs from S3/GCS.+ """Load model configs from cloud object storage.Discovers YAML files via LIST operation, downloads them to local cache, and parses them.Model configs are flat YAML files (e.g., gs://bucket/models/BAAI__bge-m3.yaml).diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.pyindex 063d2f391..11ceb69f3 100644--- a/packages/sie_server/src/sie_server/core/model_loader.py+++ b/packages/sie_server/src/sie_server/core/model_loader.py@@ -561,11 +561,16 @@ class ModelLoader:Returns:LoadedModel containing the loaded state."""- # Get preprocessor from adapter - all adapters implement get_preprocessor()- preprocessor = adapter.get_preprocessor()-- # Register the preprocessor based on its modality- if preprocessor is not None:+ # Get preprocessor(s) from adapter - all adapters implement get_preprocessor().+ # Most return a single preprocessor; multi-modal adapters (e.g. NemoColEmbed v1,+ # which needs a text preprocessor for queries AND an image preprocessor for+ # documents) may return a list. Register each by its modality.+ preprocessors = adapter.get_preprocessor()+ if not isinstance(preprocessors, list):+ preprocessors = [preprocessors]+ for preprocessor in preprocessors:+ if preprocessor is None:+ continuemodality = getattr(preprocessor, "modality", None)if modality == "text":self._preprocessor_registry._register(name, preprocessor)diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex 7af06fa9d..8fda0348f 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -82,7 +82,7 @@ class ModelRegistry:"""Initialize the registry.Args:- models_dir: Path to models directory (local path, s3://, or gs://).+ models_dir: Path to models directory (local path, s3://, gs://, abfs://, or abfss://).If None, registry starts empty and configs must be added manually.memory_config: Configuration for memory management. If None, uses defaults.drain_timeout_s: Timeout in seconds to wait for worker drain before unload.@@ -1396,7 +1396,7 @@ class ModelRegistry:logger.debug("No models_dir, skipping hot reload")return- # Don't watch cloud URLs (s3://, gs://)+ # Don't watch cloud URLs (s3://, gs://, abfs(s)://)if is_cloud_path(self._models_dir):logger.debug("Cloud models_dir, skipping hot reload (not supported)")returndiff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 40ff0a4a8..07af78501 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -29,6 +29,8 @@ The chunk envelope uses a discriminated streaming wire shape:from __future__ import annotationsimport asyncio+import base64+import binasciiimport collectionsimport jsonimport logging@@ -65,6 +67,7 @@ from sie_server.processors.tool_call_grammar import ()from sie_server.processors.tool_call_parser import ToolCallFormat, parse_tool_call_streamfrom sie_server.types.grammar import GrammarSpec, GrammarValidationError, hash_grammar+from sie_server.types.inputs import ImageInput# Module-level shim around :func:`asyncio.wait_for`. Tests monkey-patch# this attribute (not the global ``asyncio.wait_for``) so the override@@ -232,6 +235,271 @@ _MAX_PROMPT_CHARS = 4_000_000# the offending ``messages[i].role`` path in ``param``._ALLOWED_CHAT_ROLES: frozenset[str] = frozenset({"system", "user", "assistant", "tool", "developer"})+# Hard cap on images per generate request. Bounds the worker-side decode ++# the engine's vision-encoder cost so one request can't pin a GPU. Vision+# requests over this are rejected with ``invalid_request`` rather than+# silently truncated. Mirrored at the gateway so oversized requests fail+# before decode/publish.+_MAX_IMAGES_PER_REQUEST = 16++# Coarse per-image token estimate for the context-length guard and the+# admission reservation. The chat template renders each image as a short+# placeholder, but the vision encoder expands it into many tokens (Qwen-VL:+# up to ~1280 at max_pixels). Exact counts need the image dimensions + the+# model's vision tokenizer, which we don't have at this layer — so we use a+# conservative constant. Over-reserving is safe; under-counting risks a+# context-window overflow (opaque SGLang error) and admission over-admit.+_VISION_TOKENS_PER_IMAGE_ESTIMATE = 1024++# Hard ceiling on a single decoded image's bytes. Bounds worker memory on the+# decode path even for the direct-queue caller that bypasses the gateway's+# request-body cap. Checked from the base64 length BEFORE decoding (so a huge+# payload never allocates) and again on the decoded bytes (padding/edge cases).+_MAX_DECODE_IMAGE_BYTES = 16 * 1024 * 1024++# OpenAI content-part ``type`` values that carry an image. ``image_url`` is the+# chat-completions shape; ``input_image`` is the Responses-API alias some+# clients send. Both are decoded from an inline ``data:`` URI.+_IMAGE_CONTENT_PART_TYPES: frozenset[str] = frozenset({"image_url", "input_image"})+++def _decode_data_uri_image(url: str) -> tuple[bytes, str | None]:+ """Decode an inline ``data:`` image URI into ``(bytes, format)``.++ Only base64-encoded ``data:`` URIs are supported — the worker never+ fetches remote ``http(s)`` URLs (that would be an SSRF surface and a+ blocking network call on the hot path; clients inline images as data+ URIs, which the SDK/gateway already do). Returns the raw bytes plus the+ format hint parsed from the MIME subtype (e.g. ``"png"``), or ``None``+ when the MIME type is absent/uninformative.++ Raises:+ ValueError: on a non-``data:`` URI, a malformed URI, a non-base64+ payload, or undecodable base64.+ """+ if not url.startswith("data:"):+ raise ValueError("image content must be an inline base64 'data:' URI; remote URL fetching is not supported")+ header, sep, payload = url[len("data:") :].partition(",")+ if not sep:+ raise ValueError("malformed image data URI (missing ',')")+ params = header.split(";")+ if "base64" not in params[1:]:+ raise ValueError("image data URI must be base64-encoded")+ mime = params[0]+ # Mirror the gateway: only image media types (rejects data:text/... and+ # data:;base64,... for direct queue callers too).+ if not mime.startswith("image/"):+ raise ValueError("image data URI must have an image/* media type")+ fmt: str | None = None+ if "/" in mime:+ subtype = mime.split("/", 1)[1].strip().lower()+ fmt = subtype or None+ stripped = payload.strip()+ # Reject oversized images from the base64 length before allocating.+ if (len(stripped) * 3) // 4 > _MAX_DECODE_IMAGE_BYTES:+ raise ValueError(+ f"image too large: exceeds the {_MAX_DECODE_IMAGE_BYTES // (1024 * 1024)} MiB limit "+ "(_decode_data_uri_image)"+ )+ try:+ # ``.strip()`` mirrors the gateway's ``payload.trim()`` so both ends+ # accept the same data URIs (some clients pad base64 with whitespace).+ data = base64.b64decode(stripped, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise ValueError(f"invalid base64 image data: {exc}") from exc+ if not data:+ raise ValueError("image data URI decoded to empty bytes")+ if len(data) > _MAX_DECODE_IMAGE_BYTES:+ raise ValueError(+ f"image too large: {len(data)} bytes exceeds the "+ f"{_MAX_DECODE_IMAGE_BYTES // (1024 * 1024)} MiB limit (_decode_data_uri_image)"+ )+ return data, fmt+++def _parse_message_images_field(raw: object, idx: int) -> tuple[ImageInput, ...] | _ValidationError:+ """Parse a message-level ``images`` field of gateway-forwarded images.++ The gateway extracts OpenAI ``image_url`` data URIs and forwards them as+ ``messages[i].images = [{"data": <base64-str>, "format": <str?>}, ...]``.+ ``data`` is the **base64 payload string**, not raw bytes — that's what+ survives the sidecar's ``WorkItem.generate: serde_json::Value`` (msgpack+ ``bin`` does not; see the gateway ``ChatImage`` doc). We base64-decode here+ into the ``bytes`` the adapter expects. Missing/``None`` → no images.+ """+ if raw is None:+ return ()+ if not isinstance(raw, list):+ return _ValidationError(code="invalid_request", message=f"messages[{idx}].images must be an array")+ out: list[ImageInput] = []+ for i, entry in enumerate(raw):+ if not isinstance(entry, dict):+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].images[{i}] must be an object",+ )+ entry_dict = cast("dict[str, Any]", entry)+ b64 = entry_dict.get("data")+ if not isinstance(b64, str) or not b64:+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].images[{i}].data must be a non-empty base64 string",+ )+ stripped = b64.strip()+ if (len(stripped) * 3) // 4 > _MAX_DECODE_IMAGE_BYTES:+ return _ValidationError(+ code="invalid_request",+ message=(+ f"messages[{idx}].images[{i}]: image too large; exceeds the "+ f"{_MAX_DECODE_IMAGE_BYTES // (1024 * 1024)} MiB limit"+ ),+ )+ try:+ data = base64.b64decode(stripped, validate=True)+ except (binascii.Error, ValueError) as exc:+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].images[{i}]: invalid base64 image data: {exc}",+ )+ if not data:+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].images[{i}]: image data is empty",+ )+ if len(data) > _MAX_DECODE_IMAGE_BYTES:+ return _ValidationError(+ code="invalid_request",+ message=(+ f"messages[{idx}].images[{i}]: image too large ({len(data)} bytes); exceeds the "+ f"{_MAX_DECODE_IMAGE_BYTES // (1024 * 1024)} MiB limit"+ ),+ )+ fmt = entry_dict.get("format")+ out.append({"data": data, "format": fmt if isinstance(fmt, str) else None})+ return tuple(out)+++def _parse_content_parts_field(raw: object, idx: int) -> tuple[dict[str, Any], ...] | None | _ValidationError:+ """Parse a message-level ``content_parts`` field of gateway-forwarded layout.++ The gateway records the original text↔image ordering (#1294) as+ ``messages[i].content_parts = [{"type":"text","text":…} | {"type":"image"}, …]``+ so the worker can place image placeholders in position. Returned in+ chat-template shape (ready for ``apply_chat_template``). ``None`` when the+ field is absent — the message then renders images-first from ``content`` ++ ``images``. The image-marker count is reconciled against the flat ``images``+ list by the caller.+ """+ if raw is None:+ return None+ if not isinstance(raw, list):+ return _ValidationError(code="invalid_request", message=f"messages[{idx}].content_parts must be an array")+ out: list[dict[str, Any]] = []+ for i, entry in enumerate(raw):+ if not isinstance(entry, dict):+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].content_parts[{i}] must be an object",+ )+ entry_dict = cast("dict[str, Any]", entry)+ ptype = entry_dict.get("type")+ if ptype == "text":+ text = entry_dict.get("text")+ if not isinstance(text, str):+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].content_parts[{i}].text must be a string",+ )+ out.append({"type": "text", "text": text})+ elif ptype == "image":+ out.append({"type": "image"})+ else:+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].content_parts[{i}].type must be 'text' or 'image', got {ptype!r}",+ )+ return tuple(out)+++def _parse_chat_content(+ content: object, idx: int+) -> tuple[str, tuple[ImageInput, ...], tuple[dict[str, Any], ...] | None] | _ValidationError:+ """Parse an OpenAI message ``content`` into ``(text, images, content_parts)``.++ Accepts either the legacy string shape (returned verbatim with no+ images) or the multimodal list-of-parts shape, where each part is+ ``{"type": "text", "text": ...}`` or an image part+ (``{"type": "image_url", "image_url": {"url": "data:..."}}`` — the+ ``url`` may also be a bare string, and ``input_image`` is accepted as an+ alias). Text parts are concatenated in order; image parts are decoded to+ :class:`ImageInput` entries in order so they line up with the+ placeholders the chat template will render.++ ``content_parts`` is the ordered text↔image layout in chat-template shape+ (``{"type": "text", "text": …}`` / ``{"type": "image"}``), so+ :meth:`_render_chat_template` can interleave placeholders in place instead+ of emitting all images first (#1294). It is ``None`` for string content and+ for image-free part arrays — those keep the concatenated-``content`` render.++ Returns a :class:`_ValidationError` (not raised) on any malformed part,+ matching the surrounding validator's error-return contract.+ """+ if isinstance(content, str):+ return content, (), None+ if not isinstance(content, list):+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].content must be a string or an array of content parts",+ )+ text_parts: list[str] = []+ images: list[ImageInput] = []+ layout: list[dict[str, Any]] = []+ for part_idx, part in enumerate(content):+ if not isinstance(part, dict):+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].content[{part_idx}] must be an object",+ )+ part_dict = cast("dict[str, Any]", part)+ part_type = part_dict.get("type")+ if part_type in ("text", "input_text"):+ text = part_dict.get("text")+ if not isinstance(text, str):+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].content[{part_idx}].text must be a string",+ )+ text_parts.append(text)+ layout.append({"type": "text", "text": text})+ elif part_type in _IMAGE_CONTENT_PART_TYPES:+ url_field = part_dict.get("image_url")+ url = url_field.get("url") if isinstance(url_field, dict) else url_field+ if not isinstance(url, str) or not url:+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].content[{part_idx}].image_url.url must be a non-empty string",+ )+ try:+ data, fmt = _decode_data_uri_image(url)+ except ValueError as exc:+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].content[{part_idx}]: {exc}",+ )+ images.append({"data": data, "format": fmt})+ layout.append({"type": "image"})+ else:+ return _ValidationError(+ code="invalid_request",+ message=(+ f"messages[{idx}].content[{part_idx}].type must be 'text'/'input_text' or an image part "+ f"({sorted(_IMAGE_CONTENT_PART_TYPES)!r}), got {part_type!r}"+ ),+ )+ # Only carry the ordered layout when there's an image to place — text-only+ # arrays render fine from the concatenated ``content`` (no wire/format bloat).+ return "".join(text_parts), tuple(images), (tuple(layout) if images else None)+# Input-token estimate for the admission controller. Delegates# to :func:`sie_server.core.text_tokens.estimate_tokens_from_chars` so the@@ -252,6 +520,18 @@ class _ChatMessage:# final answer after a tool returns.tool_calls: tuple[dict[str, Any], ...] | None = Nonetool_call_id: str | None = None+ # Vision input: images attached to this message (decoded from OpenAI+ # ``image_url`` content parts). ``None`` for text-only messages. The+ # chat template renders one image placeholder per entry, in order, and+ # the bytes are forwarded to the engine as ``image_data``.+ images: tuple[ImageInput, ...] | None = None+ # Ordered text↔image layout in chat-template shape+ # (``{"type":"text","text":…}`` / ``{"type":"image"}``) preserving the+ # original content-part order so :meth:`_render_chat_template` interleaves+ # placeholders in place (#1294). ``None`` → fall back to images-first+ # rendering from ``content`` + ``images``. Image markers here line up 1:1+ # with ``images`` (same order); only placeholder POSITIONS differ.+ content_parts: tuple[dict[str, Any], ...] | None = None@dataclass(frozen=True)@@ -1214,7 +1494,35 @@ class StreamingProcessor:# tokenize-via-template before handing the rendered string to# the underlying adapter. ``Prompt`` shape goes straight through.prompt_str: str+ # Flat, in-order image list for vision requests — lines up with the+ # placeholders the chat template renders. ``None`` for the prompt+ # shape and for text-only message lists.+ request_images: list[ImageInput] | None = Noneif isinstance(params.input, _MessagesInput):+ collected = [img for m in params.input.messages for img in (m.images or ())]+ request_images = collected or None+ # Worker-side vision capability gate (defense-in-depth for the+ # queue-bypass path). Run it BEFORE chat-template rendering so a+ # text-only model handed images fails fast with a clear error+ # rather than doing — or erroring inside — the CPU-bound render.+ # Skip only when the config is unavailable (mirrors the+ # context-length check's defensive skip).+ if request_images:+ try:+ vision_config = self._registry.get_config(model_id)+ except KeyError:+ vision_config = None+ if vision_config is not None and not vision_config.inputs.image:+ await self._terminal_error_then_settle(+ reply_subject,+ request_id=request_id,+ attempt_id=attempt_id,+ seq=0,+ code="invalid_request",+ message=f"model '{model_id}' does not support image input",+ msg=msg,+ )+ returnrendered = await self._render_chat_template(model_id,params.input.messages,@@ -1247,8 +1555,15 @@ class StreamingProcessor:# §4.3: worker-side context-length validation. Applies# to both Prompt and Messages paths. The rendered string is# already in memory; tokenizing is fast on a cached fast- # tokenizer (<1ms for typical prompts).- ctx_error = await self._check_context_length(model_id, prompt_str, params.max_new_tokens)+ # tokenizer (<1ms for typical prompts). Vision requests add a coarse+ # per-image token estimate so placeholder expansion doesn't overflow+ # the context window unaccounted.+ ctx_error = await self._check_context_length(+ model_id,+ prompt_str,+ params.max_new_tokens,+ num_images=len(request_images) if request_images else 0,+ )if ctx_error is not None:await self._terminal_error_then_settle(reply_subject,@@ -1355,7 +1670,11 @@ class StreamingProcessor:# rescan_configs discovery) still drive the gate. Falls back to# the worker's boot-time default when the lookup fails.budget_override, admission_enabled_override = self._resolve_admission_for_model(model_id)- reserve_tokens = estimate_tokens_from_chars(prompt_str) + params.max_new_tokens+ # Include the coarse per-image token estimate so vision requests+ # reserve KV budget proportional to their real (placeholder-expanded)+ # footprint instead of just the short placeholder text.+ image_reserve = (len(request_images) if request_images else 0) * _VISION_TOKENS_PER_IMAGE_ESTIMATE+ reserve_tokens = estimate_tokens_from_chars(prompt_str) + params.max_new_tokens + image_reserveadmitted = await self._try_reserve(model_id,reserve_tokens,@@ -1422,6 +1741,7 @@ class StreamingProcessor:best_of=params.best_of,stream=params.stream,lora_adapter=params.lora_adapter,+ images=request_images,cancel_event=cancel_event,)finally:@@ -1473,6 +1793,7 @@ class StreamingProcessor:best_of: int | None = None,stream: bool = False,lora_adapter: str | None = None,+ images: list[ImageInput] | None = None,cancel_event: asyncio.Event,) -> None:# ``adapter.generate`` is typed as returning ``AsyncIterator`` on@@ -1538,6 +1859,10 @@ class StreamingProcessor:# SGLang selects the adapter by its registered served-name via# sampling_params.lora_path; no path resolution needed here.gen_kwargs["lora_path"] = lora_adapter+ # Vision: forward decoded images only when present so text-only+ # requests (and adapters that don't accept the kwarg) are unaffected.+ if images:+ gen_kwargs["images"] = imageschunks_iter = cast("AsyncGenerator[GenerationChunk, None]",adapter.generate(**gen_kwargs),@@ -2175,6 +2500,7 @@ class StreamingProcessor:message="'messages' must be a non-empty array",)decoded: list[_ChatMessage] = []+ total_images = 0for idx, item in enumerate(messages_raw):if not isinstance(item, dict):return _ValidationError(@@ -2198,17 +2524,79 @@ class StreamingProcessor:# only carries tool_calls (OpenAI sends content:null there).if content is None and role == "assistant" and tool_calls is not None:content = ""- if not isinstance(content, str):+ # Parse the string-or-parts content. Returns concatenated text+ # plus any inline-decoded images (empty for the common string+ # shape and for the gateway path, which sends text here and the+ # images in the message-level ``images`` field below).+ parsed = _parse_chat_content(content, idx)+ if isinstance(parsed, _ValidationError):+ return parsed+ content_str, content_images, content_layout = parsed+ # Gateway-decoded images ride a message-level ``images`` field+ # (bytes already extracted from the data URI at the edge). Merge+ # with any inline content-part images; in practice exactly one+ # source is populated (gateway path vs direct OpenAI caller).+ field_images = _parse_message_images_field(item_dict.get("images"), idx)+ if isinstance(field_images, _ValidationError):+ return field_images+ message_images = (*content_images, *field_images)+ total_images += len(message_images)+ if total_images > _MAX_IMAGES_PER_REQUEST:return _ValidationError(code="invalid_request",- message=f"messages[{idx}].content must be a string",+ message=(f"too many images ({total_images}); maximum is {_MAX_IMAGES_PER_REQUEST} per request"),)+ # Ordered layout (#1294): gateway forwards it as a message-level+ # ``content_parts`` field; the direct OpenAI caller's layout comes+ # back from ``_parse_chat_content``. Exactly one is populated.+ field_parts = _parse_content_parts_field(item_dict.get("content_parts"), idx)+ if isinstance(field_parts, _ValidationError):+ return field_parts+ # Prefer the gateway-forwarded layout only when it actually+ # carries an image marker — an empty or image-free ``content_parts``+ # field must not shadow a direct-path ``content_layout``. Falling+ # back to ``content_layout`` (which is None unless it has images)+ # also keeps an empty tuple off the interleaved render path, so the+ # render guard (``if m.content_parts``) and the reconcile guard+ # below agree.+ field_has_image = field_parts is not None and any(p.get("type") == "image" for p in field_parts)+ normalized_field_parts = field_parts if field_has_image else None+ # Exactly one image-bearing layout source is allowed. An image-bearing+ # ``content_parts`` field alongside an image-bearing ``content`` array+ # (``content_layout``) would let the field's layout override the layout+ # that ``content`` — and thus the validated ``content_str`` — was parsed+ # from, so the checked text and the rendered layout could diverge. Reject+ # rather than silently honoring one over the other.+ if normalized_field_parts is not None and content_layout is not None:+ return _ValidationError(+ code="invalid_request",+ message=(+ f"messages[{idx}] has both an image-bearing 'content' array and an "+ "image-bearing 'content_parts' field; exactly one layout source is allowed"+ ),+ )+ message_content_parts = normalized_field_parts or content_layout+ # Reconcile placeholder count with the flat image list — a+ # mismatch would desync placeholders from ``image_data`` at the+ # engine, so reject it here rather than mis-render downstream.+ if message_content_parts is not None:+ image_markers = sum(1 for p in message_content_parts if p.get("type") == "image")+ if image_markers != len(message_images):+ return _ValidationError(+ code="invalid_request",+ message=(+ f"messages[{idx}].content_parts has {image_markers} image placeholder(s) "+ f"but {len(message_images)} image(s) were provided"+ ),+ )decoded.append(_ChatMessage(role=role,- content=content,+ content=content_str,tool_calls=tool_calls,tool_call_id=tool_call_id if isinstance(tool_call_id, str) else None,+ images=message_images or None,+ content_parts=message_content_parts,))input_value = _MessagesInput(messages=tuple(decoded))@@ -2663,7 +3051,26 @@ class StreamingProcessor:# defensive for direct worker callers). Qwen's template has no# ``developer`` slot.role = "system" if m.role == "developer" else m.role- d: dict[str, Any] = {"role": role, "content": m.content}+ d: dict[str, Any]+ if m.content_parts:+ # #1294: render text↔image parts in their ORIGINAL order so each+ # placeholder sits where the client placed it. Already in+ # chat-template shape; copy each part so ``apply_chat_template``+ # can't mutate the stored tuple. The bytes ride ``image_data`` in+ # the same order as the ``"image"`` markers here.+ d = {"role": role, "content": [dict(p) for p in m.content_parts]}+ elif m.images:+ # Legacy / no-layout path: hand the template a content-parts list+ # so it inserts one image placeholder per image (Qwen-VL templates+ # key off the ``"image"`` part type; the bytes travel separately+ # as ``image_data``). Images lead, then the text — the flat image+ # order the adapter receives.+ content_parts: list[dict[str, Any]] = [{"type": "image"} for _ in m.images]+ if m.content:+ content_parts.append({"type": "text", "text": m.content})+ d = {"role": role, "content": content_parts}+ else:+ d = {"role": role, "content": m.content}if m.tool_calls:d["tool_calls"] = [self._normalise_tool_call(tc) for tc in m.tool_calls]if m.tool_call_id is not None:@@ -2715,6 +3122,7 @@ class StreamingProcessor:model_id: str,prompt: str,max_new_tokens: int,+ num_images: int = 0,) -> _ValidationError | None:"""Worker-side ``prompt_tokens + max_new_tokens > context_length``guard. Emits a terminal ``code: "context_exceeded"`` chunk when@@ -2782,12 +3190,18 @@ class StreamingProcessor:exc_info=True,)return None- total = prompt_tokens + max_new_tokens+ # Account for vision-encoder token expansion: each image placeholder+ # in ``prompt`` tokenizes to a handful of text tokens but expands to+ # many tokens at inference. Add a coarse per-image estimate so the+ # guard fires before SGLang overflows its context window.+ image_tokens = num_images * _VISION_TOKENS_PER_IMAGE_ESTIMATE+ total = prompt_tokens + image_tokens + max_new_tokensif total > context_length:+ image_note = f" + ~image_tokens ({image_tokens})" if image_tokens else ""return _ValidationError(code="context_exceeded",message=(- f"prompt_tokens ({prompt_tokens}) + max_new_tokens "+ f"prompt_tokens ({prompt_tokens}){image_note} + max_new_tokens "f"({max_new_tokens}) = {total} exceeds context_length "f"({context_length}) for model '{model_id}'"),diff --git a/packages/sie_server/tests/adapters/test_runtime_options.py b/packages/sie_server/tests/adapters/test_runtime_options.pyindex 001c7c6a3..93b08597f 100644--- a/packages/sie_server/tests/adapters/test_runtime_options.py+++ b/packages/sie_server/tests/adapters/test_runtime_options.py@@ -1118,7 +1118,7 @@ class TestExtractRuntimeOptions:)def test_owlv2_reads_score_threshold_from_options(self) -> None:- """OWLv2 adapter reads score_threshold from options."""+ """OWLv2 adapter reads score_threshold and threshold from options."""import inspectfrom sie_server.adapters.owlv2 import Owlv2Adapter@@ -1127,6 +1127,9 @@ class TestExtractRuntimeOptions:assert 'opts.get("score_threshold"' in source, ("Owlv2Adapter.extract() does not read score_threshold from options.")+ assert 'opts.get("threshold"' in source or "opts.get('threshold'" in source, (+ "Owlv2Adapter.extract() does not read threshold alias from options."+ )def test_florence2_reads_task_from_options(self) -> None:"""Florence2 adapter reads task, max_new_tokens, num_beams from options."""diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex 4e09a8dfd..8c360ed57 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -12,6 +12,7 @@ Mocks the subprocess + httpx layer to exercise:from __future__ import annotationsimport asyncio+import base64from typing import Any, Selffrom unittest.mock import AsyncMock, MagicMock, patch@@ -20,10 +21,13 @@ from sie_server.adapters._generation_base import GenerationChunk, collect_generafrom sie_server.adapters.sglang.generation import (SGLangGenerationAdapter,_chunk_from_sglang_event,+ _encode_image_data,_p_unsafe_from_verdict_logprobs,_parse_sglang_generate_response,_thresholded_verdict,)+from sie_server.types.grammar import GrammarSpec+from sie_server.types.inputs import InvalidMediaError@pytest.fixture@@ -331,6 +335,110 @@ def client_instance_stream_body(mock_async_client: MagicMock) -> dict:return mock_async_client.return_value.stream.call_args.kwargs["json"]+def test_encode_image_data_builds_data_uris() -> None:+ # Bytes → base64 data URI carrying the format hint; order preserved.+ out = _encode_image_data(+ [+ {"data": b"\xff\xd8\xff\xe0jpegbytes", "format": "jpeg"},+ {"data": b"\x89PNGpngbytes", "format": "PNG"},+ ]+ )+ assert out is not None+ assert len(out) == 2+ assert out[0].startswith("data:image/jpeg;base64,")+ # Format hint is lower-cased.+ assert out[1].startswith("data:image/png;base64,")+ # Round-trips back to the original bytes.+ payload = out[0].split(",", 1)[1]+ assert base64.b64decode(payload) == b"\xff\xd8\xff\xe0jpegbytes"+++def test_encode_image_data_defaults_format_and_handles_empty() -> None:+ # Missing/blank format defaults to jpeg.+ out = _encode_image_data([{"data": b"raw"}])+ assert out is not None+ assert out[0].startswith("data:image/jpeg;base64,")+ # No images → None so the request body is byte-identical to text-only.+ assert _encode_image_data(None) is None+ assert _encode_image_data([]) is None+++def test_encode_image_data_rejects_non_bytes() -> None:+ # The wire contract: ``data`` must be bytes (un-decoded base64 strings raise).+ with pytest.raises(InvalidMediaError):+ _encode_image_data([{"data": "not-bytes", "format": "jpeg"}])+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_forwards_image_data(mock_async_client: MagicMock, adapter) -> None:+ """Images are forwarded as SGLang's top-level ``image_data`` field+ (list of data URIs), leaving ``sampling_params`` untouched.+ """+ sse_lines = [+ 'data: {"text": "a cat", "meta_info": {"prompt_tokens": 5, "completion_tokens": 2, "finish_reason": {"type": "stop"}}}',+ ]+ stream = _FakeStreamingResponse(sse_lines)+ mock_async_client.return_value = _make_client_with_stream(stream)+ adapter._server_url = "http://localhost:30005"++ images = [{"data": b"\xff\xd8\xff\xe0fakejpeg", "format": "jpeg"}]+ asyncio.run(collect_generation(adapter.generate(prompt="<image>describe this", max_new_tokens=8, images=images)))++ body = client_instance_stream_body(mock_async_client)+ assert isinstance(body["image_data"], list)+ assert body["image_data"][0].startswith("data:image/jpeg;base64,")+ # image_data is a TOP-LEVEL /generate field, not a sampling param.+ assert "image_data" not in body["sampling_params"]+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_omits_image_data_without_images(mock_async_client: MagicMock, adapter) -> None:+ """Text-only generation never sets ``image_data`` — the body stays+ byte-identical for the models that share this adapter without vision.+ """+ sse_lines = [+ 'data: {"text": "hi", "meta_info": {"prompt_tokens": 1, "completion_tokens": 1, "finish_reason": {"type": "stop"}}}',+ ]+ stream = _FakeStreamingResponse(sse_lines)+ mock_async_client.return_value = _make_client_with_stream(stream)+ adapter._server_url = "http://localhost:30005"++ asyncio.run(collect_generation(adapter.generate(prompt="Hi", max_new_tokens=8)))+ body = client_instance_stream_body(mock_async_client)+ assert "image_data" not in body+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_grammar_and_images_coexist(mock_async_client: MagicMock, adapter) -> None:+ """Structured output (Outlines) still applies on a vision request: a+ request carrying BOTH images and a json_schema grammar forwards+ ``image_data`` (top-level) AND ``json_schema`` (sampling_params). The two+ are orthogonal on the ``/generate`` body, so grammar-constrained decoding+ is unaffected by the presence of an image.+ """+ sse_lines = [+ 'data: {"text": "{\\"color\\":\\"red\\"}", "meta_info": {"prompt_tokens": 5, "completion_tokens": 4, "finish_reason": {"type": "stop"}}}',+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ adapter._server_url = "http://localhost:30005"++ images = [{"data": b"\xff\xd8\xff\xe0fakejpeg", "format": "jpeg"}]+ grammar = GrammarSpec(+ kind="json_schema",+ value={"type": "object", "properties": {"color": {"type": "string"}}, "required": ["color"]},+ )+ asyncio.run(+ collect_generation(+ adapter.generate(prompt="<image>what colour?", max_new_tokens=16, images=images, grammar=grammar)+ )+ )++ body = client_instance_stream_body(mock_async_client)+ # Vision payload (top-level) AND grammar constraint (sampling_params) both present.+ assert body["image_data"][0].startswith("data:image/jpeg;base64,")+ assert "json_schema" in body["sampling_params"]++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")def test_generate_best_of_ranks_by_logprob_and_trims(mock_async_client: MagicMock, adapter) -> None:"""`best_of=3, n=1`: generate 3 candidates, return the single highest bydiff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.pyindex 469007a6f..eea305214 100644--- a/packages/sie_server/tests/processors/test_streaming.py+++ b/packages/sie_server/tests/processors/test_streaming.py@@ -14,6 +14,7 @@ Exercises the chunk-publishing path with a fake :class:`GenerationAdapter`:from __future__ import annotationsimport asyncio+import base64import threadingimport timefrom collections.abc import AsyncIterator@@ -2188,3 +2189,482 @@ async def test_tombstone_lazy_cleanup_evicts_when_over_cap(assert "req-live-0" not in proc._cancel_tombstonesassert "req-live-1" not in proc._cancel_tombstonesassert len(proc._cancel_tombstones) <= 4+++# -----------------------------------------------------------------------------+# Vision input (#1233): image content parsing + plumbing to the adapter+# -----------------------------------------------------------------------------+++def _png_data_uri(payload: bytes = b"PNGDATA") -> str:+ return "data:image/png;base64," + base64.b64encode(payload).decode("ascii")+++def test_decode_data_uri_image_parses_bytes_and_format() -> None:+ from sie_server.processors.streaming import _decode_data_uri_image++ data, fmt = _decode_data_uri_image(_png_data_uri(b"hello-png"))+ assert data == b"hello-png"+ assert fmt == "png"+++def test_decode_data_uri_image_rejects_remote_and_malformed() -> None:+ from sie_server.processors.streaming import _decode_data_uri_image++ with pytest.raises(ValueError, match="inline base64 'data:' URI"):+ _decode_data_uri_image("https://example.com/cat.png")+ with pytest.raises(ValueError, match="base64-encoded"):+ # data URI without ;base64+ _decode_data_uri_image("data:image/png,rawbytes")+ with pytest.raises(ValueError, match="invalid base64"):+ _decode_data_uri_image("data:image/png;base64,!!!notbase64!!!")+ with pytest.raises(ValueError, match="empty bytes"):+ _decode_data_uri_image("data:image/png;base64,")+ # Non-image media types reject (mirrors the gateway's image/* check).+ with pytest.raises(ValueError, match="media type"):+ _decode_data_uri_image("data:text/plain;base64," + base64.b64encode(b"hi").decode())+ with pytest.raises(ValueError, match="media type"):+ _decode_data_uri_image("data:;base64," + base64.b64encode(b"hi").decode())+++def test_parse_chat_content_accepts_input_text() -> None:+ # ``input_text`` is accepted alongside ``text`` (gateway/OpenAPI accept both).+ from sie_server.processors.streaming import _parse_chat_content++ text, images, parts = _parse_chat_content([{"type": "input_text", "text": "hi"}], 0)+ assert text == "hi"+ assert images == ()+ assert parts is None # no image → no ordered layout (renders from ``content``)+++def test_parse_chat_content_string_passthrough() -> None:+ from sie_server.processors.streaming import _parse_chat_content++ text, images, parts = _parse_chat_content("plain text", 0)+ assert text == "plain text"+ assert images == ()+ assert parts is None+++def test_parse_chat_content_extracts_text_and_images_in_order() -> None:+ from sie_server.processors.streaming import _parse_chat_content++ content = [+ {"type": "text", "text": "describe "},+ {"type": "image_url", "image_url": {"url": _png_data_uri(b"img1")}},+ {"type": "text", "text": "and this"},+ # ``input_image`` alias + bare-string url form.+ {"type": "input_image", "image_url": _png_data_uri(b"img2")},+ ]+ text, images, parts = _parse_chat_content(content, 0)+ assert text == "describe and this"+ assert [img["data"] for img in images] == [b"img1", b"img2"]+ # #1294: the ordered layout preserves the text↔image interleaving.+ assert parts is not None+ assert [p["type"] for p in parts] == ["text", "image", "text", "image"]+ assert parts[0] == {"type": "text", "text": "describe "}+ assert parts[2] == {"type": "text", "text": "and this"}+++def test_parse_chat_content_rejects_unknown_part_and_bad_text() -> None:+ from sie_server.processors.streaming import _parse_chat_content, _ValidationError++ bad_type = _parse_chat_content([{"type": "audio_url", "audio_url": {"url": "x"}}], 2)+ assert isinstance(bad_type, _ValidationError)+ assert bad_type.code == "invalid_request"+ assert "messages[2].content[0].type" in bad_type.message++ bad_text = _parse_chat_content([{"type": "text", "text": 123}], 0)+ assert isinstance(bad_text, _ValidationError)+ assert "must be a string" in bad_text.message++ bad_url = _parse_chat_content([{"type": "image_url", "image_url": {"url": ""}}], 0)+ assert isinstance(bad_url, _ValidationError)+ assert "image_url.url" in bad_url.message+++def test_render_chat_template_builds_image_placeholders(monkeypatch: pytest.MonkeyPatch) -> None:+ from sie_server.processors.streaming import _ChatMessage++ captured: dict[str, Any] = {}++ class _FakeTok:+ def apply_chat_template(self, message_dicts: Any, **_kw: Any) -> str:+ captured["dicts"] = message_dicts+ return "RENDERED"++ async def _fake_get_tokenizer(self: Any, model_id: str) -> Any:+ return _FakeTok()++ monkeypatch.setattr(StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)+ proc = StreamingProcessor(nc=AsyncMock(), registry=_make_registry(_FakeGenAdapter([])), worker_id="w1")++ messages = (+ _ChatMessage(role="system", content="be helpful"),+ _ChatMessage(+ role="user",+ content="what is this?",+ images=({"data": b"img1", "format": "png"}, {"data": b"img2", "format": "png"}),+ ),+ )++ async def _run() -> Any:+ return await proc._render_chat_template("test/model", messages)++ rendered = asyncio.run(_run())+ assert rendered == "RENDERED"+ dicts = captured["dicts"]+ # Text-only system message stays a plain string.+ assert dicts[0]["content"] == "be helpful"+ # Vision user message becomes a parts list: 2 image placeholders + text.+ user_content = dicts[1]["content"]+ assert [p["type"] for p in user_content] == ["image", "image", "text"]+ assert user_content[2] == {"type": "text", "text": "what is this?"}+++def test_render_chat_template_interleaves_content_parts(monkeypatch: pytest.MonkeyPatch) -> None:+ # #1294: with an ordered layout, placeholders render in their original+ # positions (text↔image interleaved), NOT all-images-first.+ from sie_server.processors.streaming import _ChatMessage++ captured: dict[str, Any] = {}++ class _FakeTok:+ def apply_chat_template(self, message_dicts: Any, **_kw: Any) -> str:+ captured["dicts"] = message_dicts+ return "RENDERED"++ async def _fake_get_tokenizer(self: Any, model_id: str) -> Any:+ return _FakeTok()++ monkeypatch.setattr(StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)+ proc = StreamingProcessor(nc=AsyncMock(), registry=_make_registry(_FakeGenAdapter([])), worker_id="w1")++ messages = (+ _ChatMessage(+ role="user",+ content="Page 1:Page 2:which has a cat?",+ images=({"data": b"imgA", "format": "png"}, {"data": b"imgB", "format": "png"}),+ content_parts=(+ {"type": "text", "text": "Page 1:"},+ {"type": "image"},+ {"type": "text", "text": "Page 2:"},+ {"type": "image"},+ {"type": "text", "text": "which has a cat?"},+ ),+ ),+ )++ async def _run() -> Any:+ return await proc._render_chat_template("test/model", messages)++ rendered = asyncio.run(_run())+ assert rendered == "RENDERED"+ user_content = captured["dicts"][0]["content"]+ assert [p["type"] for p in user_content] == ["text", "image", "text", "image", "text"]+ assert user_content[0] == {"type": "text", "text": "Page 1:"}+ assert user_content[2] == {"type": "text", "text": "Page 2:"}+ assert user_content[4] == {"type": "text", "text": "which has a cat?"}+++def test_parse_content_parts_field() -> None:+ from sie_server.processors.streaming import _parse_content_parts_field, _ValidationError++ assert _parse_content_parts_field(None, 0) is None+ ok = _parse_content_parts_field([{"type": "text", "text": "a"}, {"type": "image"}], 0)+ assert ok == ({"type": "text", "text": "a"}, {"type": "image"})+ bad_type = _parse_content_parts_field([{"type": "audio"}], 1)+ assert isinstance(bad_type, _ValidationError)+ assert "content_parts[0].type" in bad_type.message+ bad_text = _parse_content_parts_field([{"type": "text", "text": 5}], 0)+ assert isinstance(bad_text, _ValidationError)+ assert "content_parts[0].text" in bad_text.message+++def test_validate_rejects_content_parts_image_count_mismatch() -> None:+ # Gateway path: 2 image placeholders but only 1 image byte would desync+ # placeholders from ``image_data`` at the engine — the validator rejects it.+ from sie_server.processors.streaming import _ValidationError++ wi = _make_work_item(+ generate={+ "messages": [+ {+ "role": "user",+ "content": "a b",+ "images": [{"data": base64.b64encode(b"img").decode(), "format": "png"}],+ "content_parts": [+ {"type": "text", "text": "a"},+ {"type": "image"},+ {"type": "image"},+ {"type": "text", "text": "b"},+ ],+ }+ ],+ "max_new_tokens": 8,+ }+ )+ result = StreamingProcessor._validate_generate_params(wi)+ assert isinstance(result, _ValidationError)+ assert "image placeholder" in result.message+++def test_validate_threads_matching_gateway_content_parts() -> None:+ # Gateway path with consistent counts: the ordered layout reaches the+ # decoded message in order so the worker can interleave placeholders.+ from sie_server.processors.streaming import _MessagesInput, _ValidationError++ wi = _make_work_item(+ generate={+ "messages": [+ {+ "role": "user",+ "content": "Page 1:Page 2:",+ "images": [+ {"data": base64.b64encode(b"A").decode(), "format": "png"},+ {"data": base64.b64encode(b"B").decode(), "format": "png"},+ ],+ "content_parts": [+ {"type": "text", "text": "Page 1:"},+ {"type": "image"},+ {"type": "text", "text": "Page 2:"},+ {"type": "image"},+ ],+ }+ ],+ "max_new_tokens": 8,+ }+ )+ result = StreamingProcessor._validate_generate_params(wi)+ assert not isinstance(result, _ValidationError)+ assert isinstance(result.input, _MessagesInput)+ parts = result.input.messages[0].content_parts+ assert parts is not None+ assert [p["type"] for p in parts] == ["text", "image", "text", "image"]+++def test_validate_rejects_both_image_bearing_layout_sources() -> None:+ # A malformed/internal producer can send an image-bearing ``content`` array+ # (the real parsed layout) AND an image-bearing ``content_parts`` field whose+ # layout differs. The field would override the layout ``content`` was parsed+ # from, so the validated text ("REAL") and the rendered layout ("FAKE") would+ # diverge. Exactly one image-bearing layout source is allowed — reject it.+ from sie_server.processors.streaming import _ValidationError++ wi = _make_work_item(+ generate={+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "REAL"},+ {"type": "image_url", "image_url": {"url": _png_data_uri(b"x")}},+ ],+ "content_parts": [+ {"type": "text", "text": "FAKE"},+ {"type": "image"},+ ],+ }+ ],+ "max_new_tokens": 8,+ }+ )+ result = StreamingProcessor._validate_generate_params(wi)+ assert isinstance(result, _ValidationError)+ assert "exactly one layout source" in result.message+++def test_validate_image_free_content_parts_field_does_not_shadow_layout() -> None:+ # Defensive: a request carrying BOTH an array content (direct-path layout+ # with an image) AND an image-free content_parts field must keep the real+ # layout — the image-free field must not shadow it.+ from sie_server.processors.streaming import _ValidationError++ wi = _make_work_item(+ generate={+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "a"},+ {"type": "image_url", "image_url": {"url": _png_data_uri(b"x")}},+ ],+ "content_parts": [{"type": "text", "text": "ignore me"}], # image-free+ }+ ],+ "max_new_tokens": 8,+ }+ )+ result = StreamingProcessor._validate_generate_params(wi)+ assert not isinstance(result, _ValidationError)+ parts = result.input.messages[0].content_parts+ assert parts is not None+ assert [p["type"] for p in parts] == ["text", "image"]+++def test_parse_message_images_field() -> None:+ from sie_server.processors.streaming import _parse_message_images_field, _ValidationError++ # Missing field → no images.+ assert _parse_message_images_field(None, 0) == ()+ # Valid gateway base64 string → decoded to bytes.+ out = _parse_message_images_field([{"data": base64.b64encode(b"catbytes").decode(), "format": "png"}], 0)+ assert not isinstance(out, _ValidationError)+ assert out[0]["data"] == b"catbytes"+ assert out[0]["format"] == "png"+ # Non-list rejects.+ assert isinstance(_parse_message_images_field({"data": "x"}, 1), _ValidationError)+ # Non-string data rejects (gateway sends a base64 string).+ bad = _parse_message_images_field([{"data": 123}], 2)+ assert isinstance(bad, _ValidationError)+ assert "messages[2].images[0]" in bad.message+ # Invalid base64 rejects.+ bad_b64 = _parse_message_images_field([{"data": "!!!notbase64!!!"}], 0)+ assert isinstance(bad_b64, _ValidationError)+ assert "invalid base64" in bad_b64.message+ # Empty data rejects.+ empty = _parse_message_images_field([{"data": ""}], 0)+ assert isinstance(empty, _ValidationError)+ assert "non-empty base64" in empty.message+++async def test_images_rejected_on_text_only_model(monkeypatch: pytest.MonkeyPatch) -> None:+ """Worker-side defense-in-depth gate: a model whose config says+ ``inputs.image`` is False rejects an image request (queue-path bypass of+ the gateway gate) with a clean ``invalid_request`` instead of a broken+ prompt / opaque SGLang error.+ """++ async def _fake_get_tokenizer(self: Any, model_id: str) -> Any:+ class _Tok:+ def apply_chat_template(self, message_dicts: Any, **_kw: Any) -> str:+ return "rendered"++ return _Tok()++ monkeypatch.setattr(StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)+ nc = AsyncMock()+ adapter = _FakeGenAdapter([GenerationChunk(text_delta="", done=True, finish_reason="stop")])+ registry = _make_registry(adapter)+ # Model config declares text-only input.+ registry.get_config.return_value.inputs.image = False+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ wi = _make_work_item(+ generate={+ "messages": [+ {+ "role": "user",+ "content": "what is this?",+ "images": [{"data": base64.b64encode(b"img").decode(), "format": "png"}],+ }+ ],+ "max_new_tokens": 8,+ }+ )+ await proc.process(_make_msg(wi), "test/model")+ terminal = _decode_chunks(nc)[-1]+ assert terminal["done"] is True+ assert terminal["error"]["code"] == "invalid_request"+ assert "does not support image input" in terminal["error"]["message"]+++async def test_messages_images_field_reaches_adapter(monkeypatch: pytest.MonkeyPatch) -> None:+ """The gateway path: a message-level ``images`` field of decoded bytes is+ threaded to ``adapter.generate(images=...)``. ``content`` is plain text.+ """++ class _RecordingAdapter(_FakeGenAdapter):+ def __init__(self, script: list[GenerationChunk]) -> None:+ super().__init__(script)+ self.received_images: Any = "UNSET"++ async def generate(self, prompt: str, *, max_new_tokens: int, **kwargs: Any) -> AsyncIterator[GenerationChunk]:+ self.received_images = kwargs.get("images")+ for chunk in self._script:+ yield chunk++ async def _fake_get_tokenizer(self: Any, model_id: str) -> Any:+ class _Tok:+ def apply_chat_template(self, message_dicts: Any, **_kw: Any) -> str:+ return "rendered prompt"++ return _Tok()++ monkeypatch.setattr(StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)+ script = [+ GenerationChunk(text_delta="a cat", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=5, completion_tokens=2),+ ]+ adapter = _RecordingAdapter(script)+ nc = AsyncMock()+ proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter), worker_id="w1")+ wi = _make_work_item(+ generate={+ "messages": [+ {+ "role": "user",+ "content": "what is this?",+ "images": [{"data": base64.b64encode(b"catbytes").decode(), "format": "png"}],+ }+ ],+ "max_new_tokens": 8,+ }+ )+ await proc.process(_make_msg(wi), "test/model")+ assert isinstance(adapter.received_images, list)+ assert len(adapter.received_images) == 1+ assert adapter.received_images[0]["data"] == b"catbytes"+++async def test_messages_image_reaches_adapter(monkeypatch: pytest.MonkeyPatch) -> None:+ """End-to-end: a generate work item carrying an OpenAI image part is+ decoded and forwarded to ``adapter.generate(images=...)`` as bytes.+ """++ class _RecordingAdapter(_FakeGenAdapter):+ def __init__(self, script: list[GenerationChunk]) -> None:+ super().__init__(script)+ self.received_images: Any = "UNSET"++ async def generate(self, prompt: str, *, max_new_tokens: int, **kwargs: Any) -> AsyncIterator[GenerationChunk]:+ self.received_images = kwargs.get("images")+ for chunk in self._script:+ yield chunk++ async def _fake_get_tokenizer(self: Any, model_id: str) -> Any:+ class _Tok:+ def apply_chat_template(self, message_dicts: Any, **_kw: Any) -> str:+ return "rendered prompt"++ return _Tok()++ monkeypatch.setattr(StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)++ script = [+ GenerationChunk(text_delta="a cat", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=5, completion_tokens=2),+ ]+ adapter = _RecordingAdapter(script)+ nc = AsyncMock()+ proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter), worker_id="w1")++ wi = _make_work_item(+ messages=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "what is this?"},+ {"type": "image_url", "image_url": {"url": _png_data_uri(b"catbytes")}},+ ],+ }+ ]+ )+ await proc.process(_make_msg(wi), "test/model")++ assert isinstance(adapter.received_images, list)+ assert len(adapter.received_images) == 1+ assert adapter.received_images[0]["data"] == b"catbytes"+ assert adapter.received_images[0]["format"] == "png"diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lockindex 0a415a2bb..71bc3f68b 100644--- a/packages/sie_server_sidecar/Cargo.lock+++ b/packages/sie_server_sidecar/Cargo.lock@@ -104,33 +104,33 @@ checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"[[package]]name = "async-nats"-version = "0.38.0"+version = "0.49.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "76433c4de73442daedb3a59e991d94e85c14ebfc33db53dfcd347a21cd6ef4f8"+checksum = "fad3cd6df81292728e2a8cb1f1dcb4d7e7a1ab59b80c14fbbcba2baf9d5cf86a"dependencies = ["base64 0.22.1","bytes",- "futures",+ "futures-util","memchr","nkeys","nuid",- "once_cell","pin-project","portable-atomic",- "rand 0.8.6",+ "rand 0.10.1","regex","ring",- "rustls-native-certs 0.7.3",- "rustls-pemfile",- "rustls-webpki 0.102.8",+ "rustls-native-certs",+ "rustls-pki-types",+ "rustls-webpki","serde","serde_json","serde_nanos","serde_repr",- "thiserror 1.0.69",+ "thiserror 2.0.18","time","tokio","tokio-rustls",+ "tokio-stream","tokio-util","tokio-websockets","tracing",@@ -254,6 +254,17 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"+[[package]]+name = "chacha20"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "rand_core 0.10.1",+]+[[package]]name = "chrono"version = "0.4.44"@@ -339,16 +350,6 @@ version = "0.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"-[[package]]-name = "core-foundation"-version = "0.9.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"-dependencies = [- "core-foundation-sys",- "libc",-]-[[package]]name = "core-foundation"version = "0.10.1"@@ -790,6 +791,7 @@ dependencies = ["cfg-if","libc","r-efi 6.0.0",+ "rand_core 0.10.1","wasip2","wasip3",]@@ -923,11 +925,11 @@ dependencies = ["hyper","hyper-util","rustls",- "rustls-native-certs 0.8.4",+ "rustls-native-certs","tokio","tokio-rustls","tower-service",- "webpki-roots",+ "webpki-roots 1.0.7",][[package]]@@ -1358,6 +1360,7 @@ dependencies = ["bytes","chrono","futures",+ "httparse","humantime","hyper","itertools 0.13.0",@@ -1412,12 +1415,6 @@ dependencies = ["pkg-config",]-[[package]]-name = "openssl-probe"-version = "0.1.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"-[[package]]name = "openssl-probe"version = "0.2.1"@@ -1712,6 +1709,17 @@ dependencies = ["rand_core 0.9.5",]+[[package]]+name = "rand"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"+dependencies = [+ "chacha20",+ "getrandom 0.4.2",+ "rand_core 0.10.1",+]+[[package]]name = "rand_chacha"version = "0.3.1"@@ -1750,6 +1758,12 @@ dependencies = ["getrandom 0.3.4",]+[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"+[[package]]name = "rayon"version = "1.12.0"@@ -1842,7 +1856,7 @@ dependencies = ["pin-project-lite","quinn","rustls",- "rustls-native-certs 0.8.4",+ "rustls-native-certs","rustls-pki-types","serde","serde_json",@@ -1859,7 +1873,7 @@ dependencies = ["wasm-bindgen-futures","wasm-streams","web-sys",- "webpki-roots",+ "webpki-roots 1.0.7",][[package]]@@ -1954,34 +1968,21 @@ dependencies = ["once_cell","ring","rustls-pki-types",- "rustls-webpki 0.103.13",+ "rustls-webpki","subtle","zeroize",]-[[package]]-name = "rustls-native-certs"-version = "0.7.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5"-dependencies = [- "openssl-probe 0.1.6",- "rustls-pemfile",- "rustls-pki-types",- "schannel",- "security-framework 2.11.1",-]-[[package]]name = "rustls-native-certs"version = "0.8.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"dependencies = [- "openssl-probe 0.2.1",+ "openssl-probe","rustls-pki-types","schannel",- "security-framework 3.7.0",+ "security-framework",][[package]]@@ -2003,17 +2004,6 @@ dependencies = ["zeroize",]-[[package]]-name = "rustls-webpki"-version = "0.102.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9"-dependencies = [- "ring",- "rustls-pki-types",- "untrusted",-]-[[package]]name = "rustls-webpki"version = "0.103.13"@@ -2061,19 +2051,6 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"-[[package]]-name = "security-framework"-version = "2.11.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"-dependencies = [- "bitflags",- "core-foundation 0.9.4",- "core-foundation-sys",- "libc",- "security-framework-sys",-]-[[package]]name = "security-framework"version = "3.7.0"@@ -2081,7 +2058,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"dependencies = ["bitflags",- "core-foundation 0.10.1",+ "core-foundation","core-foundation-sys","libc","security-framework-sys",@@ -2216,7 +2193,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-server-sidecar"-version = "0.6.2"+version = "0.6.3"dependencies = ["anyhow","async-nats",@@ -2588,6 +2565,17 @@ dependencies = ["tokio",]+[[package]]+name = "tokio-stream"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+]+[[package]]name = "tokio-util"version = "0.7.18"@@ -2615,11 +2603,11 @@ dependencies = ["httparse","rand 0.8.6","ring",- "rustls-native-certs 0.8.4","rustls-pki-types","tokio","tokio-rustls","tokio-util",+ "webpki-roots 0.26.11",][[package]]@@ -3014,6 +3002,15 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "webpki-roots"+version = "0.26.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"+dependencies = [+ "webpki-roots 1.0.7",+]+[[package]]name = "webpki-roots"version = "1.0.7"diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex 032ec17f8..9739e30e9 100644--- a/packages/sie_server_sidecar/Cargo.toml+++ b/packages/sie_server_sidecar/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-server-sidecar"-version = "0.6.2"+version = "0.6.3"edition = "2021"description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."@@ -14,7 +14,7 @@ path = "src/main.rs"[dependencies]tokio = { version = "1", features = ["full"] }-async-nats = "0.38"+async-nats = "0.49"futures-util = "0.3"serde = { version = "1", features = ["derive"] }@@ -51,7 +51,7 @@ hyper-util = { version = "0.1", features = ["tokio"] }http-body-util = "0.1"# Cloud payload store backends (opt-in, same shape as gateway)-object_store = { version = "0.11", optional = true, features = ["aws", "gcp"] }+object_store = { version = "0.11", optional = true, features = ["aws", "gcp", "azure"] }url = { version = "2", optional = true }# HF fast-tokenizers. Used by `src/tokenize/` to verify thediff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex f28a6418e..03e5c55d9 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -252,7 +252,7 @@ sidecar container itself.| `SIE_NATS_CONSUMER_RECONCILE_INTERVAL_MS` | slow stream/durable reconcile interval, default 30000; non-zero values below 10000 are clamped; `0` disables || `SIE_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS` | generation direct-dispatch activation check interval after startup reports no generation models, default 30000; non-zero values below 5000 are clamped; `0` disables || `SIE_STREAM_MAX_AGE_S` | worker stream max age if worker creates the stream first |-| `SIE_PAYLOAD_STORE_URL` | optional shared payload-store backend (`s3://`, `gs://`, or a local path shared with the gateway) |+| `SIE_PAYLOAD_STORE_URL` | optional shared payload-store backend (`s3://`, `gs://`, `abfs://`, `abfss://`, or a local path shared with the gateway) || `SIE_GATEWAY_URL` | optional gateway base URL used by the pool admission gate || `SIE_GATEWAY_API_KEY` | optional bearer token for gateway pool-status reads || `SIE_POOL_ADMISSION_ENABLED` | pool admission gate toggle, default true when `SIE_GATEWAY_URL` is set |@@ -343,8 +343,8 @@ What is covered:- Rust unit tests for scheduler, adaptive controller, IPC framing/retry,payload confinement, metrics, output framing, tokenizer registry, publisher,shutdown, and NATS helpers. `mise run server-sidecar-test` runs the crate once with- default features and once with `cloud-storage` so S3/GCS payload-store code is- compiled and tested in the normal worker path.+ default features and once with `cloud-storage` so S3/GCS/Azure payload-store+ code is compiled and tested in the normal worker path.- Rust integration smoke tests with real `nats-server`, real `sie-server-sidecar`, anda Python IPC harness.- Python parity tests for `RunBatch` fixtures under `tests/parity/`.diff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rsindex 7c30c726f..15e2f2ed8 100644--- a/packages/sie_server_sidecar/src/config.rs+++ b/packages/sie_server_sidecar/src/config.rs@@ -31,8 +31,8 @@ pub struct WorkerConfig {/// Optional payload store URL — if unset, workers expect items inline/// (large items will be rejected by the gateway's offload). Local paths- /// point at a shared directory; `s3://…` / `gs://…` use cloud stores- /// when built with `--features cloud-storage`.+ /// point at a shared directory; `s3://…` / `gs://…` / `abfs://…` /+ /// `abfss://…` use cloud stores when built with `--features cloud-storage`.pub payload_store_url: Option<String>,/// Optional gateway URL used by the worker-side pool admission gate.diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex e19ac2e06..5080bc7b2 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -485,7 +485,7 @@ impl Dispatcher {}}- async fn handle_generate_item(self: Arc<Self>, wi: WorkItem, msg: Message) {+ async fn handle_generate_item(self: Arc<Self>, mut wi: WorkItem, msg: Message) {let model_id = wi.model_id.clone();let model_lbl = self.metrics.model_label(&model_id).into_owned();let _timer = self@@ -519,6 +519,57 @@ impl Dispatcher {}}+ // Resolve an offloaded generate payload. The gateway offloads large+ // vision work items to the object store (``payload_ref`` set,+ // ``generate`` blanked); fetch + inline so the Python worker — which+ // has no object-store access — receives a self-contained WorkItem. The+ // blob is base64-string image data, so it decodes cleanly as+ // ``serde_json::Value`` (msgpack ``bin`` would not).+ if let Some(payload_ref) = wi.payload_ref.clone() {+ match self.payload_store.get(&payload_ref).await {+ Ok(bytes) => match decode_offloaded_generate(&bytes) {+ Ok(generate) => {+ wi.generate = Some(generate);+ wi.payload_ref = None;+ }+ Err(e) => {+ warn!(+ work_item_id = %wi.work_item_id,+ error = %e,+ "failed to decode offloaded generate payload — publishing error + ACK"+ );+ match self+ .publish_error(+ &wi,+ "internal_error",+ "failed to decode offloaded generate payload",+ )+ .await+ {+ Ok(_) => match ack(&msg).await {+ Ok(()) => self.metrics.messages_acked_total.inc(),+ Err(e) => {+ warn!(error = %e, "ack after offload-decode error failed");+ self.metrics.jetstream_ack_failures_total.inc();+ }+ },+ Err(_) => nak_one(&msg, base_delay_ms, &self.metrics).await,+ }+ return;+ }+ },+ Err(e) => {+ warn!(+ work_item_id = %wi.work_item_id,+ error = %e,+ "failed to resolve offloaded generate payload — NAKing"+ );+ nak_one(&msg, base_delay_ms, &self.metrics).await;+ return;+ }+ }+ }+let work_item_msgpack = match rmp_serde::to_vec_named(&wi) {Ok(bytes) => bytes,Err(e) => {@@ -2659,6 +2710,15 @@ pub(crate) async fn scheduler_drain_loop();}+/// Decode an offloaded generate payload blob (msgpack) into the inline+/// `generate` value. Extracted so the transport contract is directly+/// testable: the gateway offloads `generate` carrying **base64-string** image+/// data, which round-trips through `serde_json::Value`; the original, buggy+/// msgpack-`bin` (`serde_bytes`) shape does NOT decode here.+fn decode_offloaded_generate(bytes: &[u8]) -> Result<Json, rmp_serde::decode::Error> {+ rmp_serde::from_slice(bytes)+}+#[cfg(test)]mod tests {use super::*;@@ -2698,6 +2758,73 @@ mod tests {}}+ #[tokio::test]+ async fn offloaded_generate_blob_with_base64_images_resolves_via_object_store() {+ use crate::payload_store::LocalPayloadStore;++ // Gateway offload shape: `generate` params with base64-STRING image data.+ let generate = serde_json::json!({+ "messages": [{+ "role": "user",+ "content": "what is this?",+ "images": [{"data": "aGVsbG8=", "format": "png"}], // base64 of b"hello"+ }],+ "max_new_tokens": 8,+ });+ let blob = rmp_serde::to_vec_named(&generate).unwrap();++ // Real object store (filesystem), the gateway's `{request_id}_0.bin` key.+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(dir.path().join("req-1_0.bin"), &blob).unwrap();+ let store = LocalPayloadStore::new(Some(dir.path()));++ // The exact sidecar resolution ops: fetch from the object store + decode.+ let bytes = store+ .get("req-1_0.bin")+ .await+ .expect("blob fetched from object store");+ let decoded = decode_offloaded_generate(&bytes)+ .expect("base64-image generate blob must decode as serde_json::Value");+ assert_eq!(decoded["messages"][0]["images"][0]["data"], "aGVsbG8=");++ // Inline into a WorkItem and re-encode → decode (the sidecar → Python+ // worker hop): the base64 image survives the full round trip.+ let mut work = wi("req-1", 0, "Qwen/Qwen3.5-4B", "generate");+ work.item = None;+ work.generate = Some(decoded);+ let reencoded = rmp_serde::to_vec_named(&work).unwrap();+ let back: WorkItem = rmp_serde::from_slice(&reencoded).unwrap();+ let g = back.generate.expect("generate inlined onto the work item");+ assert_eq!(g["messages"][0]["images"][0]["data"], "aGVsbG8=");+ }++ #[test]+ fn bin_generate_blob_fails_to_decode_proving_base64_is_required() {+ // The original (buggy) shape: image bytes as a msgpack `bin` via+ // serde_bytes. `serde_json::Value` cannot hold `bin`, so the sidecar+ // decode fails — this is exactly the transport bug the base64-string+ // representation fixes.+ #[derive(serde::Serialize)]+ struct BinImage {+ #[serde(with = "serde_bytes")]+ data: Vec<u8>,+ }+ #[derive(serde::Serialize)]+ struct BinGenerate {+ images: Vec<BinImage>,+ }+ let blob = rmp_serde::to_vec_named(&BinGenerate {+ images: vec![BinImage {+ data: vec![0xFF, 0xD8, 0xFF, 0xE0],+ }],+ })+ .unwrap();+ assert!(+ decode_offloaded_generate(&blob).is_err(),+ "msgpack bin must NOT decode as serde_json::Value — the exact bug base64 transport fixes"+ );+ }+#[test]fn groups_by_model_and_operation() {let items = vec![diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rsindex e9815ca84..55cf6e33f 100644--- a/packages/sie_server_sidecar/src/health_publisher.rs+++ b/packages/sie_server_sidecar/src/health_publisher.rs@@ -126,6 +126,7 @@ impl HealthPublisherConfig {struct WorkerStatusPayload<'a> {name: &'a str,ready: bool,+ terminated: bool,gpu_count: i32,machine_profile: &'a str,pool_name: &'a str,@@ -138,6 +139,41 @@ struct WorkerStatusPayload<'a> {loaded_models: &'a [&'a str],}+fn encode_payload(+ config: &HealthPublisherConfig,+ ready: bool,+ terminated: bool,+) -> Result<Vec<u8>, serde_json::Error> {+ let hash = config+ .bundle_config_hash+ .read()+ .expect("bundle config hash lock poisoned");+ let payload = WorkerStatusPayload {+ name: &config.worker_id,+ ready,+ terminated,+ gpu_count: config.gpu_count,+ machine_profile: &config.machine_profile,+ pool_name: &config.pool_name,+ bundle: &config.bundle,+ bundle_config_hash: hash.as_str(),+ loaded_models: &[],+ };+ serde_json::to_vec(&payload)+}++pub async fn publish_tombstone(+ nats: &Client,+ config: &HealthPublisherConfig,+) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ let subject = config.subject();+ let bytes = encode_payload(config, false, true)?;+ nats.publish(subject.clone(), bytes.into()).await?;+ nats.flush().await?;+ info!(subject = %subject, "nats-health: shutdown tombstone published");+ Ok(())+}+/// Spawn the heartbeat-publisher loop. The returned [`JoinHandle`]/// is owned by `run()` so shutdown can `.abort()` it after the/// pull loop exits — same lifecycle as `crate::spawn_heartbeat`.@@ -176,36 +212,27 @@ pub fn spawn(tokio::select! {biased;_ = wait => {- debug!(subject = %subject, "nats-health: shutdown observed; stopping publisher");+ debug!(subject = %subject, "nats-health: shutdown observed; publishing tombstone");+ if let Err(e) = publish_tombstone(&nats, &config).await {+ warn!(+ subject = %subject,+ error = %e,+ "nats-health: shutdown tombstone publish failed"+ );+ }return;}_ = tick.tick() => {let snap = readiness.snapshot();let ready = snap.is_ready();- let bytes = {- let hash = config- .bundle_config_hash- .read()- .expect("bundle config hash lock poisoned");- let payload = WorkerStatusPayload {- name: &config.worker_id,- ready,- gpu_count: config.gpu_count,- machine_profile: &config.machine_profile,- pool_name: &config.pool_name,- bundle: &config.bundle,- bundle_config_hash: hash.as_str(),- loaded_models: &[],- };- match serde_json::to_vec(&payload) {- Ok(b) => b,- Err(e) => {- warn!(- error = %e,- "nats-health: serde_json encode failed (unexpected for static shape)"- );- continue;- }+ let bytes = match encode_payload(&config, ready, false) {+ Ok(b) => b,+ Err(e) => {+ warn!(+ error = %e,+ "nats-health: serde_json encode failed (unexpected for static shape)"+ );+ continue;}};match nats.publish(subject.clone(), bytes.into()).await {@@ -289,6 +316,7 @@ mod tests {let payload = WorkerStatusPayload {name: &c.worker_id,ready: true,+ terminated: false,gpu_count: c.gpu_count,machine_profile: &c.machine_profile,pool_name: &c.pool_name,@@ -300,6 +328,7 @@ mod tests {};assert_eq!(json["name"], "worker-l4-0");assert_eq!(json["ready"], true);+ assert_eq!(json["terminated"], false);assert_eq!(json["gpu_count"], 1);assert_eq!(json["machine_profile"], "l4");assert_eq!(json["pool_name"], "l4");@@ -320,6 +349,7 @@ mod tests {let payload = WorkerStatusPayload {name: &c.worker_id,ready: true,+ terminated: false,gpu_count: c.gpu_count,machine_profile: &c.machine_profile,pool_name: &c.pool_name,@@ -332,6 +362,23 @@ mod tests {assert_eq!(json["bundle_config_hash"], "hash-next");}+ #[test]+ fn tombstone_payload_marks_not_ready_and_terminated() {+ let c = cfg();+ let json: serde_json::Value =+ serde_json::from_slice(&encode_payload(&c, false, true).unwrap()).unwrap();++ assert_eq!(json["name"], "worker-l4-0");+ assert_eq!(json["ready"], false);+ assert_eq!(json["terminated"], true);+ assert_eq!(json["gpu_count"], 1);+ assert_eq!(json["machine_profile"], "l4");+ assert_eq!(json["pool_name"], "l4");+ assert_eq!(json["bundle"], "default");+ assert_eq!(json["bundle_config_hash"], "hash-abc");+ assert_eq!(json["loaded_models"], serde_json::json!([]));+ }+#[test]fn payload_uses_local_readiness_for_ready_flag() {// Heartbeat must reflect /readyz state — once drainingdiff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex 3d48448f0..5d539e115 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -521,8 +521,8 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {// ignore. Default is enabled because the sidecar pod has no// `/ws/status` endpoint (that endpoint lives on the Python// container) and therefore forces the gateway into `health_mode=nats`.- let health_publisher_handle = if health_publish_enabled() {- let pub_cfg = crate::health_publisher::HealthPublisherConfig {+ let health_publisher_config = if health_publish_enabled() {+ Some(crate::health_publisher::HealthPublisherConfig {worker_id: config.worker_id.clone(),bundle: config.bundle.clone(),pool_name: config.pool.clone(),@@ -530,17 +530,19 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {gpu_count: config.gpu_count,bundle_config_hash: config_apply_state.bundle_config_hash(),interval: Duration::from_millis(config.health_publish_interval_ms),- };- Some(crate::health_publisher::spawn(- nats_client.clone(),- pub_cfg,- Arc::clone(&readiness),- shutdown.clone(),- ))+ })} else {info!("nats-health: SIE_HEALTH_PUBLISH_ENABLED=false; skipping heartbeat publisher");None};+ let health_publisher_handle = health_publisher_config.as_ref().map(|pub_cfg| {+ crate::health_publisher::spawn(+ nats_client.clone(),+ pub_cfg.clone(),+ Arc::clone(&readiness),+ shutdown.clone(),+ )+ });// --- Main pull looprun_pull_loop(@@ -569,16 +571,32 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {heartbeat_handle.abort();let _ = heartbeat_handle.await; // best-effort join- // Stop the NATS health publisher AFTER `mark_draining`. The- // publisher reads `Readiness::snapshot().is_ready()` on every- // tick, so the now-draining flag means whatever heartbeat it- // sends from here onwards already announces `ready=false`. We- // still abort it explicitly because shutdown raced past the- // tick interval; without the abort it'd run for one more cycle- // before observing the shutdown signal.+ // Let the periodic NATS health publisher observe shutdown and emit+ // its tombstone before we move on. Aborting it immediately here can+ // cut off that publish during Kubernetes termination, leaving the+ // gateway with a stale unhealthy registry row until the fallback TTL.if let Some(h) = health_publisher_handle {- h.abort();- let _ = h.await;+ let mut h = h;+ tokio::select! {+ res = &mut h => {+ if let Err(e) = res {+ warn!(error = %e, "nats-health: heartbeat publisher task failed during shutdown");+ }+ }+ _ = sleep(Duration::from_secs(2)) => {+ warn!("nats-health: heartbeat publisher did not stop before tombstone deadline");+ h.abort();+ let _ = h.await;+ }+ }+ }+ // Idempotent fallback: the publisher emits the first tombstone as+ // soon as shutdown fires; this second publish covers the case where+ // that task had already exited or hit a transient publish error.+ if let Some(pub_cfg) = &health_publisher_config {+ if let Err(e) = crate::health_publisher::publish_tombstone(&nats_client, pub_cfg).await {+ warn!(error = %e, "nats-health: shutdown tombstone publish failed");+ }}if let Some(h) = nats_consumer_reconciler_handle {h.abort();diff --git a/packages/sie_server_sidecar/src/payload_store.rs b/packages/sie_server_sidecar/src/payload_store.rsindex d1f8a958d..db07a8884 100644--- a/packages/sie_server_sidecar/src/payload_store.rs+++ b/packages/sie_server_sidecar/src/payload_store.rs@@ -9,8 +9,8 @@//! (absolute paths are only accepted when they canonicalize inside//! `base_dir`; relative paths are resolved against it). When no//! `base_dir` is configured the reader is disabled for safety.-//! - cloud: `s3://…` / `gs://…` URL (handled when the `cloud-storage`-//! feature is enabled)+//! - cloud: `s3://…` / `gs://…` / `abfs://…` / `abfss://…` URL+//! (handled when the `cloud-storage` feature is enabled)//!//! Security: we canonicalize the resolved path and reject anything that//! escapes `base_dir`. Without this, a compromised gateway could send a@@ -23,6 +23,15 @@ use async_trait::async_trait;use thiserror::Error;use tracing::debug;+const OBJECT_STORE_SCHEMES: &[&str] = &["s3://", "gs://", "abfs://", "abfss://"];++fn object_store_scheme(url: &str) -> Option<&'static str> {+ OBJECT_STORE_SCHEMES+ .iter()+ .copied()+ .find(|scheme| url.starts_with(scheme))+}+#[derive(Debug, Error)]pub enum PayloadError {#[error("io: {0}")]@@ -169,6 +178,29 @@ impl ObjectPayloadStore {})}+ pub fn new_azure(path: &str) -> Result<Self, PayloadError> {+ Self::new_azure_with_scheme(path, "abfs://")+ }++ fn new_azure_with_scheme(path: &str, scheme: &'static str) -> Result<Self, PayloadError> {+ use object_store::azure::MicrosoftAzureBuilder;++ let (container, account, prefix) = Self::parse_azure_path(path)?;+ let store = MicrosoftAzureBuilder::from_env()+ .with_account(&account)+ .with_container_name(&container)+ .build()+ .map_err(|e| {+ PayloadError::Unsupported(format!("failed to build Azure payload store: {e}"))+ })?;+ Ok(Self {+ store: Box::new(store),+ prefix: object_store::path::Path::from(prefix),+ url_prefix: format!("{}{}", scheme, path.trim_end_matches('/')),+ scheme,+ })+ }+fn parse_bucket_prefix(path: &str) -> Result<(String, String), PayloadError> {let path = path.trim_matches('/');let Some((bucket, prefix)) = path.split_once('/') else {@@ -187,6 +219,40 @@ impl ObjectPayloadStore {Ok((bucket.to_string(), prefix.trim_matches('/').to_string()))}+ fn parse_azure_path(path: &str) -> Result<(String, String, String), PayloadError> {+ let path = path.trim_matches('/');+ let Some((authority, prefix)) = path.split_once('/') else {+ return Self::parse_azure_authority(path)+ .map(|(container, account)| (container, account, String::new()));+ };+ let (container, account) = Self::parse_azure_authority(authority)?;+ Ok((container, account, prefix.trim_matches('/').to_string()))+ }++ fn parse_azure_authority(authority: &str) -> Result<(String, String), PayloadError> {+ let Some((container, host)) = authority.split_once('@') else {+ return Err(PayloadError::InvalidRef(+ "Azure payload store URL must use <container>@<account>.dfs.core.windows.net"+ .into(),+ ));+ };+ if container.is_empty() || host.is_empty() {+ return Err(PayloadError::InvalidRef(+ "Azure payload store container and account must be non-empty".into(),+ ));+ }+ let account = host+ .strip_suffix(".dfs.core.windows.net")+ .or_else(|| host.strip_suffix(".blob.core.windows.net"))+ .unwrap_or(host);+ if account.is_empty() {+ return Err(PayloadError::InvalidRef(+ "Azure payload store account must be non-empty".into(),+ ));+ }+ Ok((container.to_string(), account.to_string()))+ }+fn relative_key<'a>(&self, payload_ref: &'a str) -> Result<&'a str, PayloadError> {if payload_ref.is_empty() {return Err(PayloadError::InvalidRef(payload_ref.to_string()));@@ -205,7 +271,7 @@ impl ObjectPayloadStore {)));};rest- } else if payload_ref.starts_with("s3://") || payload_ref.starts_with("gs://") {+ } else if object_store_scheme(payload_ref).is_some() {return Err(PayloadError::InvalidRef(format!("payload ref {payload_ref} uses a different object-store scheme")));@@ -327,14 +393,14 @@ impl PayloadStore for MeteredPayloadStore {/// URL handling:/// * `None` or an empty string → local store with no base_dir (disabled,/// rejects all reads). Pods without offload configured stay safe.-/// * `s3://…` / `gs://…` with the `cloud-storage` feature → object-/// storage reader.-/// * `s3://…` / `gs://…` without the feature → we can't read from+/// * `s3://…` / `gs://…` / `abfs://…` / `abfss://…` with the+/// `cloud-storage` feature → object storage reader.+/// * Those object-store URLs without the feature → we can't read from/// object storage, and we MUST NOT silently treat the URL string as a/// filesystem path (`LocalPayloadStore::new(Some("s3://…"))` canonicalizes/// to a broken, confusing error on every request). Return an explicit-/// `Unsupported` so the worker fails fast at startup instead of-/// NAKing every item at runtime.+/// `Unsupported` so the worker fails fast at startup instead of NAKing+/// every item at runtime./// * `file://path` → strip scheme, treat as local filesystem./// * Anything else → treated as a local filesystem path.pub async fn create_payload_store(@@ -344,7 +410,7 @@ pub async fn create_payload_store(return Ok(std::sync::Arc::new(LocalPayloadStore::new(None::<PathBuf>)));};- if url.starts_with("s3://") || url.starts_with("gs://") {+ if let Some(scheme) = object_store_scheme(url) {#[cfg(feature = "cloud-storage")]{if let Some(rest) = url.strip_prefix("s3://") {@@ -353,11 +419,16 @@ pub async fn create_payload_store(if let Some(rest) = url.strip_prefix("gs://") {return Ok(std::sync::Arc::new(ObjectPayloadStore::new_gcs(rest)?));}+ if let Some(rest) = url.strip_prefix(scheme) {+ return Ok(std::sync::Arc::new(+ ObjectPayloadStore::new_azure_with_scheme(rest, scheme)?,+ ));+ }}#[cfg(not(feature = "cloud-storage"))]{return Err(PayloadError::Unsupported(format!(- "payload store URL {url} requires the 'cloud-storage' feature; \+ "payload store URL {url} with scheme {scheme} requires the 'cloud-storage' feature; \rebuild the worker with --features cloud-storage or point \SIE_PAYLOAD_STORE_URL at a local path")));@@ -371,8 +442,68 @@ pub async fn create_payload_store(#[cfg(test)]mod tests {use super::*;+ #[cfg(feature = "cloud-storage")]+ use std::sync::{Mutex, OnceLock};use tempfile::TempDir;+ #[cfg(feature = "cloud-storage")]+ const AZURE_ENV_KEYS: &[&str] = &[+ "AZURE_STORAGE_ACCOUNT_NAME",+ "AZURE_STORAGE_ACCOUNT_KEY",+ "AZURE_STORAGE_ACCESS_KEY",+ "AZURE_STORAGE_CLIENT_ID",+ "AZURE_CLIENT_ID",+ "AZURE_STORAGE_CLIENT_SECRET",+ "AZURE_CLIENT_SECRET",+ "AZURE_STORAGE_TENANT_ID",+ "AZURE_TENANT_ID",+ "AZURE_FEDERATED_TOKEN_FILE",+ "AZURE_STORAGE_AUTHORITY_HOST",+ "AZURE_AUTHORITY_HOST",+ "AZURE_STORAGE_TOKEN",+ "AZURE_USE_AZURE_CLI",+ ];++ #[cfg(feature = "cloud-storage")]+ fn azure_env_lock() -> &'static Mutex<()> {+ static LOCK: OnceLock<Mutex<()>> = OnceLock::new();+ LOCK.get_or_init(|| Mutex::new(()))+ }++ #[cfg(feature = "cloud-storage")]+ struct EnvGuard {+ saved: Vec<(&'static str, Option<String>)>,+ }++ #[cfg(feature = "cloud-storage")]+ impl EnvGuard {+ fn set(vars: &[(&'static str, String)]) -> Self {+ let saved = AZURE_ENV_KEYS+ .iter()+ .map(|key| (*key, std::env::var(key).ok()))+ .collect();+ for key in AZURE_ENV_KEYS {+ std::env::remove_var(key);+ }+ for (key, value) in vars {+ std::env::set_var(key, value);+ }+ Self { saved }+ }+ }++ #[cfg(feature = "cloud-storage")]+ impl Drop for EnvGuard {+ fn drop(&mut self) {+ for (key, value) in &self.saved {+ match value {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ }+ }+#[tokio::test]async fn local_get_absolute_path_inside_base_dir() {// Gateway writes absolute paths (e.g. /var/cache/sie/uuid.bin);@@ -542,6 +673,144 @@ mod tests {assert!(matches!(err, PayloadError::InvalidRef(_)));}+ #[cfg(feature = "cloud-storage")]+ #[tokio::test]+ async fn object_store_get_accepts_azure_full_ref_inside_prefix() {+ use object_store::path::Path;+ use object_store::{ObjectStore, PutPayload};++ let memory = object_store::memory::InMemory::new();+ memory+ .put(+ &Path::from("payloads/pay.bin"),+ PutPayload::from(b"cloud".to_vec()),+ )+ .await+ .unwrap();++ let store = ObjectPayloadStore {+ store: Box::new(memory),+ prefix: Path::from("payloads"),+ url_prefix: "abfss://[email protected]/payloads".into(),+ scheme: "abfss://",+ };+ let got = store+ .get("abfss://[email protected]/payloads/pay.bin")+ .await+ .unwrap();+ assert_eq!(got, b"cloud");+ }++ #[cfg(feature = "cloud-storage")]+ #[tokio::test]+ async fn object_store_get_rejects_different_azure_scheme() {+ use object_store::path::Path;++ let store = ObjectPayloadStore {+ store: Box::new(object_store::memory::InMemory::new()),+ prefix: Path::from("payloads"),+ url_prefix: "s3://bucket/payloads".into(),+ scheme: "s3://",+ };+ let err = store+ .get("abfs://[email protected]/payloads/pay.bin")+ .await+ .unwrap_err();+ assert!(matches!(err, PayloadError::InvalidRef(_)));+ }++ #[cfg(feature = "cloud-storage")]+ #[test]+ fn new_azure_parses_container_account_and_prefix() {+ let (container, account, prefix) =+ ObjectPayloadStore::parse_azure_path("[email protected]/prefix")+ .unwrap();+ assert_eq!(container, "payloads");+ assert_eq!(account, "sieacct");+ assert_eq!(prefix, "prefix");+ }++ #[cfg(feature = "cloud-storage")]+ #[test]+ fn new_azure_accepts_blob_endpoint_suffix() {+ let (container, account, prefix) =+ ObjectPayloadStore::parse_azure_path("[email protected]/prefix")+ .unwrap();+ assert_eq!(container, "payloads");+ assert_eq!(account, "sieacct");+ assert_eq!(prefix, "prefix");+ }++ #[cfg(feature = "cloud-storage")]+ #[test]+ fn new_azure_rejects_missing_container_account_separator() {+ let err = ObjectPayloadStore::parse_azure_path("payloads/prefix").unwrap_err();+ assert!(matches!(err, PayloadError::InvalidRef(_)));+ }++ #[cfg(feature = "cloud-storage")]+ #[test]+ fn new_azure_builds_from_workload_identity_env() {+ let _lock = azure_env_lock().lock().unwrap();+ let dir = TempDir::new().unwrap();+ let token_file = dir.path().join("token");+ std::fs::write(&token_file, "token").unwrap();+ let _env = EnvGuard::set(&[+ ("AZURE_STORAGE_ACCOUNT_NAME", "env-account".to_string()),+ ("AZURE_CLIENT_ID", "client-id".to_string()),+ ("AZURE_TENANT_ID", "tenant-id".to_string()),+ (+ "AZURE_FEDERATED_TOKEN_FILE",+ token_file.to_string_lossy().to_string(),+ ),+ (+ "AZURE_AUTHORITY_HOST",+ "https://login.microsoftonline.com/".to_string(),+ ),+ ]);++ let store =+ ObjectPayloadStore::new_azure("[email protected]/path/to/payloads")+ .unwrap();++ assert_eq!(store.scheme, "abfs://");+ assert_eq!(+ store.url_prefix,+ "abfs://[email protected]/path/to/payloads"+ );+ assert_eq!(store.prefix.as_ref(), "path/to/payloads");+ }++ #[cfg(feature = "cloud-storage")]+ #[test]+ fn new_azure_with_abfss_preserves_scheme() {+ let _lock = azure_env_lock().lock().unwrap();+ let dir = TempDir::new().unwrap();+ let token_file = dir.path().join("token");+ std::fs::write(&token_file, "token").unwrap();+ let _env = EnvGuard::set(&[+ ("AZURE_CLIENT_ID", "client-id".to_string()),+ ("AZURE_TENANT_ID", "tenant-id".to_string()),+ (+ "AZURE_FEDERATED_TOKEN_FILE",+ token_file.to_string_lossy().to_string(),+ ),+ ]);++ let store = ObjectPayloadStore::new_azure_with_scheme(+ "[email protected]/path/to/payloads",+ "abfss://",+ )+ .unwrap();++ assert_eq!(store.scheme, "abfss://");+ assert_eq!(+ store.url_prefix,+ "abfss://[email protected]/path/to/payloads"+ );+ assert_eq!(store.prefix.as_ref(), "path/to/payloads");+ }+#[cfg(feature = "cloud-storage")]#[tokio::test]async fn object_store_get_accepts_plain_key_under_configured_prefix() {@@ -582,4 +851,18 @@ mod tests {),}}++ #[cfg(not(feature = "cloud-storage"))]+ #[tokio::test]+ async fn factory_abfs_without_feature_errors_loudly() {+ match create_payload_store(Some("abfs://[email protected]/prefix"))+ .await+ {+ Ok(_) => panic!("expected Unsupported for abfs:// without cloud-storage feature"),+ Err(e) => assert!(+ matches!(e, PayloadError::Unsupported(_)),+ "expected Unsupported for abfs://, got {e:?}"+ ),+ }+ }}diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex a11af0cfc..2b24f5c62 100644--- a/packages/sie_ts_sdk/package.json+++ b/packages/sie_ts_sdk/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-sdk",- "version": "0.6.2",+ "version": "0.6.3","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex a5e6883e0..41114913d 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -540,8 +540,9 @@ export interface GenerateResult {** `content` may be a string OR an array of typed content parts. The gateway* concatenates `text` / `input_text` parts; `image_url` / `input_image` parts- * are rejected with `400 unsupported_field` because no vision-capable- * generation model is configured today (the contract is forward-ready). See+ * carrying a base64 `data:` URI are accepted for vision-capable generation+ * models (non-vision/encode-only models reject with `400 unsupported_field`;+ * remote (non-`data:`) URLs reject with `400 invalid_request`). See* `packages/sie_gateway/src/openapi.rs` and `proxy.rs::chat_params_from_json`* for the canonical accepted subset.*/@@ -556,11 +557,16 @@ export interface ChatMessage {}/**- * One content part inside a multimodal `messages[*].content` array. Only the- * text variants are accepted today; image parts are declared so callers can- * see the rejection at the type layer instead of at runtime.+ * One content part inside a multimodal `messages[*].content` array. Text parts+ * (`text` / `input_text`) are concatenated; image parts (`image_url` /+ * `input_image`) carry a base64 `data:` URI and are accepted for vision-capable+ * generation models.*/-export type ChatContentPart = { type: "text"; text: string } | { type: "input_text"; text: string };+export type ChatContentPart =+ | { type: "text"; text: string }+ | { type: "input_text"; text: string }+ | { type: "image_url"; image_url: { url: string } }+ | { type: "input_image"; image_url: string | { url: string } };/** A tool call emitted by the model. */export interface ToolCall {diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 302d1a963..d25623a30 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.6.2"; // x-release-please-version+export const SDK_VERSION = "0.6.3"; // x-release-please-versiondiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ce1f64d88..96aafd6da 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -11,7 +11,6 @@ overrides:protobufjs: '>=7.5.8'qs: '>=6.15.2'tar: '>=7.5.11'- thrift: '>=0.23.0'uuid: '>=11.1.1'vite: ^6.4.2vitest: ^4.1.0@@ -3169,8 +3168,8 @@ packages:resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==}- resolution: {integrity: sha512-j7F1ls8JogClU88Ta/pwD/OzYuiFeD6Z5GoWw7ip+jcDhcNYFKgfXYEsyLXYpiNfJO94fbLnITGxyfZ19YzA6Q==}+ resolution: {integrity: sha512-AW8rwHYjeqXisS8B1iwko2gkNMFwSRJ+bO/W0xTGqRspTD3lGHwZx438+pHdOJ3GwpRAnK7TKbjqPOrHAa7ZwQ==}engines: {node: '>= 10.18.0'}@@ -4134,7 +4133,7 @@ snapshots:long: 5.3.2node-int64: 0.4.0snappyjs: 0.7.0- thrift: 0.23.0+ thrift: 0.21.0varint: 6.0.0xxhash-wasm: 1.1.0transitivePeerDependencies:@@ -7237,13 +7236,12 @@ snapshots:dependencies:any-promise: 1.3.0dependencies:browser-or-node: 1.3.0isomorphic-ws: 4.0.1([email protected])node-int64: 0.4.0q: 1.5.1- uuid: 14.0.0ws: 8.21.0transitivePeerDependencies:- bufferutildiff --git a/uv.lock b/uv.lockindex 7a68e8461..c2ee4862b 100644--- a/uv.lock+++ b/uv.lock@@ -4,7 +4,8 @@ resolution-markers = ["platform_machine != 'aarch64' and sys_platform == 'linux'","platform_machine == 'aarch64' and platform_python_implementation != 'CPython' and sys_platform == 'linux'","platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'",- "sys_platform != 'linux'",+ "sys_platform == 'darwin'",+ "sys_platform != 'darwin' and sys_platform != 'linux'",][manifest]@@ -271,6 +272,50 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/fb/95/adcb68e20c34162e9135f370d6e31737719c2b6f94bc953fe7ed1f10fe21/authlib-1.7.2-py2.py3-none-any.whl", hash = "sha256:3e1faedc9d87e7d56a164eca3ccb6ace0d61b94abe83e92242f8dc8bba9b4a9f", size = 259548 },]+[[package]]+name = "azure-core"+version = "1.41.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "requests" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/a6/f3/b416179e408990df5db0d516283022dde0f5d0111d98c1a848e41853e81c/azure_core-1.41.0.tar.gz", hash = "sha256:f46ff5dfcd230f25cf1c19e8a34b8dc08a337b2503e268bb600a16c00db8ad5a", size = 381042 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/5b/db/325c6d7312d2200251c52323878281045aaffcb5586612296484e4280eaa/azure_core-1.41.0-py3-none-any.whl", hash = "sha256:522b4011e8180b1a3dcd2024396a4e7fe9ac37fb8597db47163d230b5efe892d", size = 220920 },+]++[[package]]+name = "azure-identity"+version = "1.25.3"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "azure-core" },+ { name = "cryptography" },+ { name = "msal" },+ { name = "msal-extensions" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/c5/0e/3a63efb48aa4a5ae2cfca61ee152fbcb668092134d3eb8bfda472dd5c617/azure_identity-1.25.3.tar.gz", hash = "sha256:ab23c0d63015f50b630ef6c6cf395e7262f439ce06e5d07a64e874c724f8d9e6", size = 286304 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/49/9a/417b3a533e01953a7c618884df2cb05a71e7b68bdbce4fbdb62349d2a2e8/azure_identity-1.25.3-py3-none-any.whl", hash = "sha256:f4d0b956a8146f30333e071374171f3cfa7bdb8073adb8c3814b65567aa7447c", size = 192138 },+]++[[package]]+name = "azure-storage-blob"+version = "12.30.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "azure-core" },+ { name = "cryptography" },+ { name = "isodate" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/3b/48/84a820d898267f662b5c06f7cd76fdb8a9e272b44aa9376cef3ec0f6a294/azure_storage_blob-12.30.0.tar.gz", hash = "sha256:2cd74d4d5731e5eb6b8d5c5056ee115a5e88f8fdf22517b739836fda685018be", size = 618229 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/5e/0b/e106f0fd7fa785867d9ffcc47dc9e6237c0e58f51058473b777487a98edc/azure_storage_blob-12.30.0-py3-none-any.whl", hash = "sha256:d415ac50b67a8da6b3ae7e9f1014b1b55cd7aafa0b8d4ca9b380568dc7360423", size = 435610 },+]+[[package]]name = "backoff"version = "2.2.1"@@ -427,7 +472,7 @@ name = "build"version = "1.4.4"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "colorama", marker = "os_name == 'nt' and sys_platform != 'linux'" },+ { name = "colorama", marker = "os_name == 'nt' and sys_platform != 'darwin' and sys_platform != 'linux'" },{ name = "packaging" },{ name = "pyproject-hooks" },]@@ -987,54 +1032,19 @@ wheels = [[[package]]name = "docling"-version = "2.91.0"+version = "2.99.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "accelerate" },- { name = "beautifulsoup4" },- { name = "certifi" },- { name = "defusedxml" },- { name = "docling-core", extra = ["chunking"] },- { name = "docling-ibm-models" },- { name = "docling-parse" },- { name = "filetype" },- { name = "httpx" },- { name = "huggingface-hub" },- { name = "lxml" },- { name = "marko" },- { name = "ocrmac", marker = "sys_platform == 'darwin'" },- { name = "openpyxl" },- { name = "pandas" },- { name = "pillow" },- { name = "pluggy" },- { name = "polyfactory" },- { name = "pydantic" },- { name = "pydantic-settings" },- { name = "pylatexenc" },- { name = "pypdfium2" },- { name = "python-docx" },- { name = "python-pptx" },- { name = "rapidocr" },- { name = "requests" },- { name = "rtree" },- { name = "scipy" },- { name = "torch", version = "2.9.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },- { name = "torch", version = "2.9.1+cu129", source = { registry = "https://download.pytorch.org/whl/cu129" }, marker = "sys_platform == 'linux'" },- { name = "torchvision", version = "0.24.1", source = { registry = "https://download.pytorch.org/whl/cu129" }, marker = "platform_machine == 'aarch64' and sys_platform == 'linux'" },- { name = "torchvision", version = "0.24.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },- { name = "torchvision", version = "0.24.1+cu129", source = { registry = "https://download.pytorch.org/whl/cu129" }, marker = "platform_machine != 'aarch64' and sys_platform == 'linux'" },- { name = "tqdm" },- { name = "typer" },- { name = "websockets" },+ { name = "docling-slim", extra = ["standard"] },]-sdist = { url = "https://files.pythonhosted.org/packages/67/5e/e18d8a351b2b80e77392e48851d0c17ab0e18ccffce5e7fecefce0738fe9/docling-2.91.0.tar.gz", hash = "sha256:c37fa0957e63a784753a4d43fc1271caa869d883a8354d556ee6d52a3046929e", size = 475494 }+sdist = { url = "https://files.pythonhosted.org/packages/61/73/f6a0d6ada626281c1914dfb2de30c6e0067b1f8e3993e77eabb05fb08bf6/docling-2.99.0.tar.gz", hash = "sha256:306ea071d935f3852f75c873fe1b8663da580d2c359b8de162da52a6151c4c91", size = 8755 }wheels = [- { url = "https://files.pythonhosted.org/packages/af/c7/9d46072bd33edb1a4c9e6f233e0a7bf58658718da7ace86ca1144dfd7a31/docling-2.91.0-py3-none-any.whl", hash = "sha256:db413c21b2fe5bec78c32b475346ef770ab40368a331150570371c3281c951a2", size = 498712 },+ { url = "https://files.pythonhosted.org/packages/05/cc/cd8bea43057e64ec7755a18e009270500263f513e058649b909e83e2c0a7/docling-2.99.0-py3-none-any.whl", hash = "sha256:a78d4fd34e4ca495cd50003288b4de4a9b040dbff59f8ca5624aa8fa37d43728", size = 4798 },][[package]]name = "docling-core"-version = "2.74.1"+version = "2.79.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "defusedxml" },@@ -1050,9 +1060,9 @@ dependencies = [{ name = "typer" },{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/e8/94/4856d01de4afd565d0ea12198f157f634cf65dc373a4ee97cb0d789f8554/docling_core-2.74.1.tar.gz", hash = "sha256:46bf298686f2c51ddd69b6935a27dff1cc80838f2f5f1a8823492d99cf1a357b", size = 319269 }+sdist = { url = "https://files.pythonhosted.org/packages/4d/b3/9196498f28c5a872b76b356df3ccefc20f2978eea12b8459a3398d036a2e/docling_core-2.79.0.tar.gz", hash = "sha256:3a5c6f757a95b93a1bb4c2c46efbe580f35a390f762a4b4105d97b7fca7cdfeb", size = 334965 }wheels = [- { url = "https://files.pythonhosted.org/packages/d7/c3/5f8c9a9b0cad437cb7e6ffcd48ccc309b2290cea6aac067569bf61b84743/docling_core-2.74.1-py3-none-any.whl", hash = "sha256:e6464078012b3d45f4e0accd101fcb277063903f355eabbb9aee8de00527a789", size = 276973 },+ { url = "https://files.pythonhosted.org/packages/d0/f2/2cbf2b8ba8f2ebdefa5ebed29cf1d2eb4306a57ebf6c8b98703b7d4e2054/docling_core-2.79.0-py3-none-any.whl", hash = "sha256:42540cbd7ff8bca264e8e8fda9a66ad4446613f520bee8e130588193bc3e0212", size = 286672 },][package.optional-dependencies]@@ -1095,7 +1105,7 @@ wheels = [[[package]]name = "docling-parse"-version = "5.10.1"+version = "6.2.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "docling-core" },@@ -1104,12 +1114,65 @@ dependencies = [{ name = "pywin32", marker = "sys_platform == 'win32'" },{ name = "tabulate" },]-sdist = { url = "https://files.pythonhosted.org/packages/a7/b8/e68f8ec44692d2f913210dd46cb3e7e6e1959053bb05d5c94c5331010f3c/docling_parse-5.10.1.tar.gz", hash = "sha256:10a3d2ba211134f6d1fa9b6be8ef690eb0b1a03b043473a3ef8408ad7b4a857a", size = 6651696 }+sdist = { url = "https://files.pythonhosted.org/packages/64/46/2c9c0738452368ad63018f380f4ad6fad8c69b64f04222aa012190bc8a4f/docling_parse-6.2.0.tar.gz", hash = "sha256:f13d6c49e3b5f9caaf0d626e0dcc7948c5b4700d0eae0559ec353ed07c4f2f50", size = 6670444 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/6b/1b/507361edae548952993d75160884ce7895a93e92cc66b4e30b2cc3616091/docling_parse-6.2.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:6085c2d4611c16fb9b6b96472e4d3ecea4ca701d9b8be58776b4d2572cd98cdc", size = 9141212 },+ { url = "https://files.pythonhosted.org/packages/d0/e0/3ed96ada48b96670a0817bd3fc11f7e6808aaf7d491354dd3b3deddb0725/docling_parse-6.2.0-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:33093dfb3c8105feb618887a127b19327e09fae7bf374eecbf5d10663d474a1e", size = 9808832 },+ { url = "https://files.pythonhosted.org/packages/3c/dd/572cde51f4c192a2752680e76fcb030cb997f656b4eea3b196fe8b7b7b2b/docling_parse-6.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:05f6b1e15408741953ee4beb61442168c3267489634ce16ebd8e9214deec621e", size = 10191025 },+ { url = "https://files.pythonhosted.org/packages/03/29/c46b57a3cce07a14810f539a4402d7d347ddc2b2c63501c344c0541a8697/docling_parse-6.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:6f2be525e2b117afe84033375354c1cee4f77a4598807ca75d5873fd507a52e1", size = 10956918 },+]++[[package]]+name = "docling-slim"+version = "2.99.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "certifi" },+ { name = "docling-core" },+ { name = "filetype" },+ { name = "pluggy" },+ { name = "pydantic" },+ { name = "pydantic-settings" },+ { name = "requests" },+ { name = "tqdm" },+]+sdist = { url = "https://files.pythonhosted.org/packages/a3/10/42e81debe1b7db6ae6dbbcd41f90f2aaa59501a1089fe9f304821783c409/docling_slim-2.99.0.tar.gz", hash = "sha256:b05150cda69e4c24c85aa32d2e329f21188dd4304547928eab32d8bb8b645bba", size = 410480 }wheels = [- { url = "https://files.pythonhosted.org/packages/3e/4a/27e213493bac0877a030f030d44152ba9ef676aebc5890f4dd3e8037592e/docling_parse-5.10.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:8f58e1bf1c6cdf1bfe0594f0903b4b9c33dfc3c2dbba61681f8533158ed640a6", size = 9112936 },- { url = "https://files.pythonhosted.org/packages/ee/b3/85737cecca0e5ed9dc13370e78862054075f64eb988024069296898ec741/docling_parse-5.10.1-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:59880a29231083c17a73533e09abc0610f10a99343762d795de4ceac5b15dfbf", size = 9780913 },- { url = "https://files.pythonhosted.org/packages/17/fa/11dd3328ab708143a291ae53d388a5170095a90b8dc8428e5274e2c09194/docling_parse-5.10.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:478ada90c52b704a04a3c8b4171e3385bb8b5b2f02b9d57c7a5bb06d9cac34fa", size = 10159004 },- { url = "https://files.pythonhosted.org/packages/e7/73/20384b93e220bbeee09b0bc3978907afda1a13599d7a9990614ad1c682ed/docling_parse-5.10.1-cp312-cp312-win_amd64.whl", hash = "sha256:e8e4ae0929b55301c59252453ce87406c003229adac16258c4b6eb31a76d5cb5", size = 10912188 },+ { url = "https://files.pythonhosted.org/packages/1c/d8/caa986a093c89238cc4019e10885677ffe4ee7aeb46a807626ac18654dfb/docling_slim-2.99.0-py3-none-any.whl", hash = "sha256:f67e31ca3cc39c5b19df3cfcb8fbe7bcc5ef29ffff320bbafca56e3b9ce40f24", size = 530895 },+]++[package.optional-dependencies]+standard = [+ { name = "accelerate" },+ { name = "beautifulsoup4" },+ { name = "defusedxml" },+ { name = "docling-core", extra = ["chunking"] },+ { name = "docling-ibm-models" },+ { name = "docling-parse" },+ { name = "httpx" },+ { name = "huggingface-hub" },+ { name = "lxml" },+ { name = "mail-parser" },+ { name = "marko" },+ { name = "numpy" },+ { name = "openpyxl" },+ { name = "pillow" },+ { name = "polyfactory" },+ { name = "pylatexenc" },+ { name = "pypdfium2" },+ { name = "python-docx" },+ { name = "python-pptx" },+ { name = "rapidocr" },+ { name = "rich" },+ { name = "rtree" },+ { name = "scipy" },+ { name = "torch", version = "2.9.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },+ { name = "torch", version = "2.9.1+cu129", source = { registry = "https://download.pytorch.org/whl/cu129" }, marker = "sys_platform == 'linux'" },+ { name = "torchvision", version = "0.24.1", source = { registry = "https://download.pytorch.org/whl/cu129" }, marker = "platform_machine == 'aarch64' and sys_platform == 'linux'" },+ { name = "torchvision", version = "0.24.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },+ { name = "torchvision", version = "0.24.1+cu129", source = { registry = "https://download.pytorch.org/whl/cu129" }, marker = "platform_machine != 'aarch64' and sys_platform == 'linux'" },+ { name = "typer" },+ { name = "websockets" },][[package]]@@ -2193,6 +2256,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/81/38/73fa582d6997362d9b4901b2a8ba1177b2d2896aa59ab8d069a3884e2e0d/ir_datasets-0.5.11-py3-none-any.whl", hash = "sha256:ae78549e5a7fa45e50462b7acb9f0765fc344fec6054108bf3dd063050555206", size = 866095 },]+[[package]]+name = "isodate"+version = "0.7.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/54/4d/e940025e2ce31a8ce1202635910747e5a87cc3a6a6bb2d00973375014749/isodate-0.7.2.tar.gz", hash = "sha256:4cd1aa0f43ca76f4a6c6c0292a85f40b35ec2e43e315b59f06e6d32171a953e6", size = 29705 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/15/aa/0aca39a37d3c7eb941ba736ede56d689e7be91cab5d9ca846bde3999eba6/isodate-0.7.2-py3-none-any.whl", hash = "sha256:28009937d8031054830160fce6d409ed342816b543597cece116d966c6d99e15", size = 22320 },+]+[[package]]name = "itsdangerous"version = "2.2.0"@@ -2824,6 +2896,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/2a/7e/76b7e0c391bee7e9273725c29c8fe41c4df62a215ce58aa8e3518baee0bb/magicattr-0.1.6-py2.py3-none-any.whl", hash = "sha256:d96b18ee45b5ee83b09c17e15d3459a64de62d538808c2f71182777dd9dbbbdf", size = 4664 },]+[[package]]+name = "mail-parser"+version = "4.3.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/01/6b/55b188888abccfc1dba0617a6d99da1c39dc355822900ae9d5bccf8756b2/mail_parser-4.3.0.tar.gz", hash = "sha256:fb4c64ec0a74ed095b3bad274ab08f6fca024ad5fbf72ff9ccc501ba654ba3b2", size = 2792149 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/8d/4f/38717202a3be94a37c262907adca700498fbb435a8356cfaed38387469c8/mail_parser-4.3.0-py3-none-any.whl", hash = "sha256:e4092a15023b7075f4666f5040e2fca71fa35a7020753b7e90359c357ed3a099", size = 33895 },+]+[[package]]name = "mako"version = "1.3.12"@@ -3211,6 +3292,32 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198 },]+[[package]]+name = "msal"+version = "1.37.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "cryptography" },+ { name = "pyjwt", extra = ["crypto"] },+ { name = "requests" },+]+sdist = { url = "https://files.pythonhosted.org/packages/9a/99/d840198ecf6e8057bbc937f129ae940404485d736cda73253bbff9537f01/msal-1.37.0.tar.gz", hash = "sha256:1b1672a33ee467c1d70b341bb16cafd51bb3c817147a95b93263794b03971bec", size = 182444 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/94/b0/d807279f4b55d16d1f120d5ac4344c6e39b56732e2a224d40bded7fd67ad/msal-1.37.0-py3-none-any.whl", hash = "sha256:dd17e95a7c71bce75e8108113438ba7c4a086b3bcad4f57a8c09b7af3d753c2d", size = 123725 },+]++[[package]]+name = "msal-extensions"+version = "1.3.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "msal" },+]+sdist = { url = "https://files.pythonhosted.org/packages/01/99/5d239b6156eddf761a636bded1118414d161bd6b7b37a9335549ed159396/msal_extensions-1.3.1.tar.gz", hash = "sha256:c5b0fd10f65ef62b5f1d62f4251d51cbcaf003fcedae8c91b040a488614be1a4", size = 23315 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/5e/75/bd9b7bb966668920f06b200e84454c8f3566b102183bc55c5473d96cb2b9/msal_extensions-1.3.1-py3-none-any.whl", hash = "sha256:96d3de4d034504e969ac5e85bae8106c8373b5c6568e4c8fa7af2eca9dbe6bca", size = 20583 },+]+[[package]]name = "msgpack"version = "1.1.2"@@ -3655,20 +3762,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/be/9c/92789c596b8df838baa98fa71844d84283302f7604ed565dafe5a6b5041a/oauthlib-3.3.1-py3-none-any.whl", hash = "sha256:88119c938d2b8fb88561af5f6ee0eec8cc8d552b7bb1f712743136eb7523b7a1", size = 160065 },]-[[package]]-name = "ocrmac"-version = "1.0.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "click", marker = "sys_platform != 'linux'" },- { name = "pillow", marker = "sys_platform != 'linux'" },- { name = "pyobjc-framework-vision", marker = "sys_platform != 'linux'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/5e/07/3e15ab404f75875c5e48c47163300eb90b7409044d8711fc3aaf52503f2e/ocrmac-1.0.1.tar.gz", hash = "sha256:507fe5e4cbd67b2d03f6729a52bbc11f9d0b58241134eb958a5daafd4b9d93d9", size = 1454317 }-wheels = [- { url = "https://files.pythonhosted.org/packages/37/15/7cc16507a2aca927abe395f1c545f17ae76b1f8ed44f43ebe4e8670ee203/ocrmac-1.0.1-py3-none-any.whl", hash = "sha256:1cef25426f7ae6bbd57fe3dc5553b25461ae8ad0d2b428a9bbadbf5907349024", size = 9955 },-]-[[package]]name = "olmocr"version = "0.4.27"@@ -3790,7 +3883,7 @@ name = "opencv-python"version = "4.13.0.92"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "numpy", marker = "sys_platform != 'linux'" },+ { name = "numpy", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },][[package]]@@ -4650,6 +4743,11 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/e5/7a/8dd906bd22e79e47397a61742927f6747fe93242ef86645ee9092e610244/pyjwt-2.12.1-py3-none-any.whl", hash = "sha256:28ca37c070cad8ba8cd9790cd940535d40274d22f80ab87f3ac6a713e6e8454c", size = 29726 },]+[package.optional-dependencies]+crypto = [+ { name = "cryptography" },+]+[[package]]name = "pylance"version = "4.0.1"@@ -4717,68 +4815,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/b2/e6/94145d714402fd5ade00b5661f2d0ab981219e07f7db9bfa16786cdb9c04/pynndescent-0.6.0-py3-none-any.whl", hash = "sha256:dc8c74844e4c7f5cbd1e0cd6909da86fdc789e6ff4997336e344779c3d5538ef", size = 73511 },]-[[package]]-name = "pyobjc-core"-version = "12.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/b8/b6/d5612eb40be4fd5ef88c259339e6313f46ba67577a95d86c3470b951fce0/pyobjc_core-12.1.tar.gz", hash = "sha256:2bb3903f5387f72422145e1466b3ac3f7f0ef2e9960afa9bcd8961c5cbf8bd21", size = 1000532 }-wheels = [- { url = "https://files.pythonhosted.org/packages/64/5a/6b15e499de73050f4a2c88fff664ae154307d25dc04da8fb38998a428358/pyobjc_core-12.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:818bcc6723561f207e5b5453efe9703f34bc8781d11ce9b8be286bb415eb4962", size = 678335 },-]--[[package]]-name = "pyobjc-framework-cocoa"-version = "12.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pyobjc-core", marker = "sys_platform != 'linux'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/02/a3/16ca9a15e77c061a9250afbae2eae26f2e1579eb8ca9462ae2d2c71e1169/pyobjc_framework_cocoa-12.1.tar.gz", hash = "sha256:5556c87db95711b985d5efdaaf01c917ddd41d148b1e52a0c66b1a2e2c5c1640", size = 2772191 }-wheels = [- { url = "https://files.pythonhosted.org/packages/95/bf/ee4f27ec3920d5c6fc63c63e797c5b2cc4e20fe439217085d01ea5b63856/pyobjc_framework_cocoa-12.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:547c182837214b7ec4796dac5aee3aa25abc665757b75d7f44f83c994bcb0858", size = 384590 },-]--[[package]]-name = "pyobjc-framework-coreml"-version = "12.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pyobjc-core", marker = "sys_platform != 'linux'" },- { name = "pyobjc-framework-cocoa", marker = "sys_platform != 'linux'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/30/2d/baa9ea02cbb1c200683cb7273b69b4bee5070e86f2060b77e6a27c2a9d7e/pyobjc_framework_coreml-12.1.tar.gz", hash = "sha256:0d1a4216891a18775c9e0170d908714c18e4f53f9dc79fb0f5263b2aa81609ba", size = 40465 }-wheels = [- { url = "https://files.pythonhosted.org/packages/bb/39/4defef0deb25c5d7e3b7826d301e71ac5b54ef901b7dac4db1adc00f172d/pyobjc_framework_coreml-12.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:10dc8e8db53d7631ebc712cad146e3a9a9a443f4e1a037e844149a24c3c42669", size = 11356 },-]--[[package]]-name = "pyobjc-framework-quartz"-version = "12.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pyobjc-core", marker = "sys_platform != 'linux'" },- { name = "pyobjc-framework-cocoa", marker = "sys_platform != 'linux'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/94/18/cc59f3d4355c9456fc945eae7fe8797003c4da99212dd531ad1b0de8a0c6/pyobjc_framework_quartz-12.1.tar.gz", hash = "sha256:27f782f3513ac88ec9b6c82d9767eef95a5cf4175ce88a1e5a65875fee799608", size = 3159099 }-wheels = [- { url = "https://files.pythonhosted.org/packages/e9/9b/780f057e5962f690f23fdff1083a4cfda5a96d5b4d3bb49505cac4f624f2/pyobjc_framework_quartz-12.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:7730cdce46c7e985535b5a42c31381af4aa6556e5642dc55b5e6597595e57a16", size = 218798 },-]--[[package]]-name = "pyobjc-framework-vision"-version = "12.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pyobjc-core", marker = "sys_platform != 'linux'" },- { name = "pyobjc-framework-cocoa", marker = "sys_platform != 'linux'" },- { name = "pyobjc-framework-coreml", marker = "sys_platform != 'linux'" },- { name = "pyobjc-framework-quartz", marker = "sys_platform != 'linux'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/c2/5a/08bb3e278f870443d226c141af14205ff41c0274da1e053b72b11dfc9fb2/pyobjc_framework_vision-12.1.tar.gz", hash = "sha256:a30959100e85dcede3a786c544e621ad6eb65ff6abf85721f805822b8c5fe9b0", size = 59538 }-wheels = [- { url = "https://files.pythonhosted.org/packages/3a/5a/23502935b3fc877d7573e743fc3e6c28748f33a45c43851d503bde52cde7/pyobjc_framework_vision-12.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:6b3211d84f3a12aad0cde752cfd43a80d0218960ac9e6b46b141c730e7d655bd", size = 16625 },-]-[[package]]name = "pyparsing"version = "3.3.2"@@ -5635,7 +5671,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.6.2"+version = "0.6.3"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5668,7 +5704,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.6.2"+version = "0.6.3"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5753,7 +5789,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.6.2"+version = "0.6.3"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5785,7 +5821,7 @@ dependencies = [{ name = "prometheus-client" },{ name = "pyyaml" },{ name = "rich" },- { name = "sie-sdk" },+ { name = "sie-sdk", extra = ["storage"] },{ name = "typer" },{ name = "uvicorn", extra = ["standard"] },{ name = "uvloop" },@@ -5811,7 +5847,7 @@ requires-dist = [{ name = "prometheus-client", specifier = ">=0.20,<1" },{ name = "pyyaml", specifier = ">=6,<7" },{ name = "rich", specifier = ">=13,<14" },- { name = "sie-sdk", editable = "packages/sie_sdk" },+ { name = "sie-sdk", extras = ["storage"], editable = "packages/sie_sdk" },{ name = "typer", specifier = ">=0.14,<1" },{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32,<1" },{ name = "uvloop", specifier = ">=0.22" },@@ -5825,7 +5861,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.2"+version = "0.6.3"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5850,7 +5886,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.2"+version = "0.6.3"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5875,7 +5911,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.2"+version = "0.6.3"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5902,7 +5938,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.2"+version = "0.6.3"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -5929,7 +5965,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.2"+version = "0.6.3"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -5956,7 +5992,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.2"+version = "0.6.3"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -5983,7 +6019,7 @@ requires-dist = [[[package]]name = "sie-qdrant"-version = "0.6.2"+version = "0.6.3"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -6006,7 +6042,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.2"+version = "0.6.3"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -6030,6 +6066,8 @@ llamaindex = [{ name = "llama-index-core" },]storage = [+ { name = "azure-identity" },+ { name = "azure-storage-blob" },{ name = "boto3" },{ name = "google-cloud-storage" },{ name = "huggingface-hub", extra = ["hf-transfer"] },@@ -6038,6 +6076,8 @@ storage = [[package.metadata]requires-dist = [{ name = "aiohttp", specifier = ">=3.9,<4" },+ { name = "azure-identity", marker = "extra == 'storage'", specifier = ">=1.17,<2" },+ { name = "azure-storage-blob", marker = "extra == 'storage'", specifier = ">=12.20,<13" },{ name = "boto3", marker = "extra == 'storage'", specifier = ">=1.35,<2" },{ name = "google-cloud-storage", marker = "extra == 'storage'", specifier = ">=2.18,<3" },{ name = "haystack-ai", marker = "extra == 'haystack'", specifier = ">=2.7,<3" },@@ -6055,7 +6095,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.2"+version = "0.6.3"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -6170,7 +6210,7 @@ dev = [][[package]]name = "sie-weaviate"-version = "0.6.2"+version = "0.6.3"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },@@ -6633,7 +6673,8 @@ name = "torch"version = "2.9.1"source = { registry = "https://pypi.org/simple" }resolution-markers = [- "sys_platform != 'linux'",+ "sys_platform == 'darwin'",+ "sys_platform != 'darwin' and sys_platform != 'linux'",]dependencies = [{ name = "filelock", marker = "sys_platform != 'linux'" },@@ -6710,7 +6751,8 @@ name = "torchvision"version = "0.24.1"source = { registry = "https://pypi.org/simple" }resolution-markers = [- "sys_platform != 'linux'",+ "sys_platform == 'darwin'",+ "sys_platform != 'darwin' and sys_platform != 'linux'",]dependencies = [{ name = "numpy", marker = "sys_platform != 'linux'" },