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
sync source: v0.7.2 sync authority: 493d57564f2b8161b2524f48e4584a23409f0b70
github-actions[bot]9a7e8d3599f7
diff --git a/.gitignore b/.gitignoreindex 6b61fdcd7..d5d72e4f7 100644--- a/.gitignore+++ b/.gitignore@@ -142,10 +142,8 @@ celerybeat.pid# Environments.env-# Managed-service cloud provisioning secrets (cloud-provision / deploy/cloud).-# Vendor credentials live in the env or a gitignored secrets file, never the-# repo (audit §1/§14). Belt-and-braces so a local copy can never be committed.-*.sie-cloud-secrets.env+# Local service credential bundles must never be committed.+*-secrets.env.env.cloud.venvenv/@@ -244,33 +242,6 @@ override.tf.json# tfvars files may contain secrets*.tfvars*.tfvars.json-# Reviewed worker-AMI release contracts contain only immutable public package,-# AMI, and Terraform backend coordinates; the release workflow accepts only-# committed files from this exact internal path.-!deploy/terraform/aws/internal-examples/cloud-benchmark-runner/worker-ami/releases/*.tfvars.json-# Exception: this edge tfvars carries only a Secrets Manager ARN (a resource-# identifier, not a secret) so the staging-us edge apply needs no manual -var.-!deploy/cloud/terraform/aws-edge/staging-us.tfvars-# This dev adoption contract contains only public AWS resource identifiers; it-# is checked in so a reviewed plan cannot silently target a different orphan-# VPC/listener through an operator-local tfvars file.-!deploy/cloud/terraform/dev-controlplane-https-adoption/dev-us.tfvars-!deploy/cloud/terraform/dev-controlplane-https-adoption/.terraform.lock.hcl-# Managed release roots commit their exact provider selections. Release-# preflights and applies use these read-only instead of selecting a newer-# compatible provider during a long-running deployment.-!deploy/cloud/terraform/release-infrastructure/.terraform.lock.hcl-!deploy/cloud/terraform/aws-controlplane/.terraform.lock.hcl-!deploy/cloud/terraform/aws-edge/.terraform.lock.hcl-!deploy/cloud/terraform/s3-state/.terraform.lock.hcl-!deploy/cloud/terraform/vercel/.terraform.lock.hcl-!deploy/cloud/terraform/console-preview/.terraform.lock.hcl-!deploy/cloud/terraform/examples/dev/.terraform.lock.hcl-!deploy/cloud/terraform/examples/dev-eu/.terraform.lock.hcl-!deploy/cloud/terraform/examples/staging/.terraform.lock.hcl-!deploy/cloud/terraform/examples/staging-eu/.terraform.lock.hcl-!deploy/cloud/terraform/examples/prod-us/.terraform.lock.hcl-# Keep .terraform.lock.hcl for reproducibility (provider versions)# Node.jsnode_modules/@@ -294,12 +265,7 @@ tmp/.tmp/.local/-.requirements-modal.txt-.mpa-i6pn-*-requirements-modal.txtb6_results.json-# Raw dev-cloud load-test reports are local artifacts, not source-controlled baselines.-packages/sie_cloud/bench/results/dev-us-*/-# Personal mise overrides (per-developer toolchain tweaks, e.g. rustup# component naming differences across rustup versions).mise.local.tomldiff --git a/COMPATIBILITY.md b/COMPATIBILITY.mdindex 3a01543cc..12eaada3a 100644--- a/COMPATIBILITY.md+++ b/COMPATIBILITY.md@@ -27,7 +27,7 @@ All packages share a **single version number**, managed by [release-please](http| `sie-server`, `sie-gateway` Docker images | ghcr.io | 0.1.6 || `superlinked/sie/google`, `superlinked/sie/aws` Terraform modules | Terraform Registry | 0.1.6 |-`sie-server`, `sie-gateway`, `sie-admin`, and `sie-bench` are internal packages distributed via Docker images or used in development only — they are not published to PyPI.+`sie-server` and `sie-gateway` are distributed as Docker images rather than PyPI packages.**Why mono-version:** Simplifies compatibility reasoning. Users deploy matching versions of SDK, server, gateway, and Helm chart. The version skew detection (see below) depends on this guarantee.@@ -118,11 +118,11 @@ Same criteria as the Python SDK, applied to `SIEClient` and its types in `@super### Environment Variables (not breaking)- Adding a new environment variable with a default that preserves existing behavior-- Test-harness variables (`SIE_FAKE_MEMORY_BUDGET`, `SIE_FAKE_FAULTS` — the Fake Engine, see `docs/fake-models.md`) are development/CI tooling, not part of the compatibility surface; they may change without deprecation+- Test-harness variables (`SIE_FAKE_MEMORY_BUDGET`, `SIE_FAKE_FAULTS`) are development tooling, not part of the compatibility surface; they may change without deprecation### CLI (breaking)-- Removing or renaming a CLI command or flag (e.g., `sie-server serve`, `sie-gateway`, `sie-admin cache`)+- Removing or renaming a CLI command or flag (e.g., `sie-server serve` or the `sie-gateway` binary)### Terraform Modules (breaking)diff --git a/Cargo.lock b/Cargo.lockindex 10ea400d3..f04553777 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -324,7 +324,7 @@ dependencies = ["serde_json","serde_path_to_error","serde_urlencoded",- "sha1",+ "sha1 0.10.7","sync_wrapper","tokio","tokio-tungstenite",@@ -376,6 +376,12 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"+[[package]]name = "base64ct"version = "1.8.3"@@ -552,6 +558,12 @@ dependencies = ["cc",]+[[package]]+name = "cmov"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"+[[package]]name = "colorchoice"version = "1.0.5"@@ -604,6 +616,26 @@ version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"+[[package]]+name = "const-random"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"+dependencies = [+ "const-random-macro",+]++[[package]]+name = "const-random-macro"+version = "0.1.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"+dependencies = [+ "getrandom 0.2.17",+ "once_cell",+ "tiny-keccak",+]+[[package]]name = "constant_time_eq"version = "0.4.2"@@ -704,6 +736,15 @@ dependencies = ["hybrid-array",]+[[package]]+name = "ctutils"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"+dependencies = [+ "cmov",+]+[[package]]name = "curve25519-dalek"version = "4.1.3"@@ -974,6 +1015,7 @@ dependencies = ["block-buffer 0.12.1","const-oid 0.10.2","crypto-common 0.2.2",+ "ctutils",][[package]]@@ -987,6 +1029,15 @@ dependencies = ["syn",]+[[package]]+name = "dlv-list"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"+dependencies = [+ "const-random",+]+[[package]]name = "dunce"version = "1.0.5"@@ -1353,9 +1404,9 @@ dependencies = [[[package]]name = "h2"-version = "0.4.15"+version = "0.4.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155"+checksum = "a9f37a958b41b3b19ee2707c06439c0e9e547e847223eb791ecb0cb821c65e27"dependencies = ["atomic-waker","bytes",@@ -1416,6 +1467,21 @@ version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"+[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "hmac"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"+dependencies = [+ "digest 0.11.3",+]+[[package]]name = "hostname"version = "0.4.2"@@ -1771,10 +1837,12 @@ checksum = "961d16382652bfdd8c6f68b223b26a8c93e0d475c672f414411db31c6c5c900e"dependencies = ["defmt","jiff-static",+ "jiff-tzdb-platform","log","portable-atomic","portable-atomic-util","serde_core",+ "windows-link",][[package]]@@ -1788,6 +1856,21 @@ dependencies = ["syn",]+[[package]]+name = "jiff-tzdb"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e"++[[package]]+name = "jiff-tzdb-platform"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"+dependencies = [+ "jiff-tzdb",+]+[[package]]name = "jni"version = "0.22.4"@@ -2119,6 +2202,16 @@ dependencies = ["digest 0.11.3",]+[[package]]+name = "mea"+version = "0.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c709842c4ce65cb91e2666ad5319dfc1efc3af0d34f02075eddca9000d9f8afb"+dependencies = [+ "hashbrown 0.17.1",+ "slab",+]+[[package]]name = "memchr"version = "2.8.3"@@ -2497,6 +2590,16 @@ dependencies = ["num-traits",]+[[package]]+name = "ordered-multimap"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"+dependencies = [+ "dlv-list",+ "hashbrown 0.14.5",+]+[[package]]name = "parking"version = "2.2.1"@@ -3064,6 +3167,72 @@ version = "0.8.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"+[[package]]+name = "reqsign-aliyun-oss"+version = "3.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10909dbc9fcb78f913014d78a5c9d1d51c477f491b1006fd1baba4fd286181df"+dependencies = [+ "anyhow",+ "form_urlencoded",+ "http",+ "log",+ "percent-encoding",+ "reqsign-core",+ "rust-ini",+ "serde",+ "serde_json",+]++[[package]]+name = "reqsign-core"+version = "3.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff052daffb0599681c50f85c59e7236438976efe991ab864edd9f3b235501a0f"+dependencies = [+ "anyhow",+ "base64 0.23.1",+ "bytes",+ "futures",+ "hex",+ "hmac",+ "http",+ "jiff",+ "log",+ "mea",+ "percent-encoding",+ "sha1 0.11.0",+ "sha2 0.11.0",+ "windows-sys 0.61.2",+]++[[package]]+name = "reqsign-file-read-tokio"+version = "3.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3235df90a6bca681aa47dd86f2393d122a6d77042aa8a7c81e218cd45c5bfc0"+dependencies = [+ "anyhow",+ "reqsign-core",+ "tokio",+]++[[package]]+name = "reqsign-http-send-reqwest"+version = "4.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a2c75a3a87bc894a10ef7e7139e71a330a3f602cfaab38c4578ec9aefc181df"+dependencies = [+ "anyhow",+ "bytes",+ "futures-channel",+ "http",+ "http-body-util",+ "reqsign-core",+ "reqwest",+ "wasm-bindgen-futures",+]+[[package]]name = "reqwest"version = "0.13.4"@@ -3166,6 +3335,16 @@ dependencies = ["windowfunctions",]+[[package]]+name = "rust-ini"+version = "0.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"+dependencies = [+ "cfg-if",+ "ordered-multimap",+]+[[package]]name = "rustc-hash"version = "2.1.3"@@ -3544,6 +3723,17 @@ dependencies = ["digest 0.10.7",]+[[package]]+name = "sha1"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "digest 0.11.3",+]+[[package]]name = "sha2"version = "0.10.9"@@ -3583,7 +3773,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-audio-prep"-version = "0.7.1"+version = "0.7.2"dependencies = ["audioadapter-buffers","opusic-sys",@@ -3597,7 +3787,7 @@ dependencies = [[[package]]name = "sie-gateway"-version = "0.7.1"+version = "0.7.2"dependencies = ["arc-swap","async-nats",@@ -3624,6 +3814,10 @@ dependencies = ["opentelemetry_sdk","percent-encoding","rand 0.10.2",+ "reqsign-aliyun-oss",+ "reqsign-core",+ "reqsign-file-read-tokio",+ "reqsign-http-send-reqwest","reqwest","rmp","rmp-serde",@@ -3655,7 +3849,7 @@ dependencies = [[[package]]name = "sie-server-sidecar"-version = "0.7.1"+version = "0.7.2"dependencies = ["anyhow","async-nats",@@ -3666,6 +3860,7 @@ dependencies = ["clap","futures-util","half",+ "http","http-body-util","hyper","hyper-util",@@ -3673,6 +3868,10 @@ dependencies = ["opentelemetry","opentelemetry-otlp","opentelemetry_sdk",+ "reqsign-aliyun-oss",+ "reqsign-core",+ "reqsign-file-read-tokio",+ "reqsign-http-send-reqwest","reqwest","rmp","rmp-serde",@@ -3694,6 +3893,7 @@ dependencies = ["tracing-subscriber","url","uuid",+ "wiremock",][[package]]@@ -4141,6 +4341,15 @@ dependencies = ["time-core",]+[[package]]+name = "tiny-keccak"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"+dependencies = [+ "crunchy",+]+[[package]]name = "tinystr"version = "0.8.3"@@ -4541,7 +4750,7 @@ dependencies = ["httparse","log","rand 0.9.5",- "sha1",+ "sha1 0.10.7","thiserror",]diff --git a/Cargo.toml b/Cargo.tomlindex f56698508..5be045572 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,18 +1,7 @@-# Virtual workspace over the PUBLIC Rust crates (#2339): one lockfile, one-# `cargo deny` sweep, one dependency-resolution surface for the crates that-# sync to the OSS `sie` repo (INF13 allowlist). The workspace boundary is-# deliberately the public/proprietary boundary, so the root Cargo.toml,-# Cargo.lock, and deny.toml sync verbatim and the public repo is a complete,+# Virtual workspace over the public Rust crates: one lockfile, one `cargo deny`+# sweep, and one dependency-resolution surface. The root Cargo.toml, Cargo.lock,+# and deny.toml are published verbatim so a public checkout is a complete,# buildable workspace.-#-# Deliberately NOT members (each keeps its own Cargo.lock):-# - packages/sie_cloud/gateway — proprietary managed composition crate,-# excluded from the public sync; consumes sie_gateway/sie_audio_prep as-# plain path deps, exactly as before this workspace existed.-# - packages/sie_server_rust — its vendored candle CUDA forks (vendor/*) are-# path deps that cargo would auto-promote to members (exclude does not-# override that for path deps, rust-lang/cargo#6745), and as members they-# would break every `cargo <cmd> --workspace` run on non-CUDA machines.[workspace]resolver = "2"members = [@@ -21,7 +10,3 @@ members = ["packages/sie_server_sidecar","packages/sie_telemetry",]-exclude = [- "packages/sie_cloud/gateway",- "packages/sie_server_rust",-]diff --git a/README.md b/README.mdindex 4ad7ca524..58ec3d2eb 100644--- a/README.md+++ b/README.md@@ -34,24 +34,36 @@ SIE is an open-source inference engine that runs the models behind every agent t- OpenAI-compatible API for drop-in migration: `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`- Pre-configured model catalog: Stella, SPLADE, Qwen3, GLiNER, SigLIP, and more; embedding and retrieval models benchmarked on MTEB- Serves multiple models simultaneously with on-demand loading and LRU eviction-- Ships the full production stack: load-balancing gateway, KEDA autoscaling, Grafana dashboards, Terraform for GKE, EKS, and AKS+- Ships Kubernetes and Helm deployment configs for the load-balancing gateway, KEDA autoscaling, and Grafana dashboards- Integrates with LangChain, LlamaIndex, Haystack, DSPy, CrewAI, Chroma, Qdrant, Weaviate, and LanceDB## Development-The repository root is a virtual Python workspace. From the repository root,-install and verify every workspace member with the committed lock (the-audio-prep member requires its documented native build prerequisites):+Install [mise](https://mise.jdx.dev/getting-started.html), then bootstrap the+versioned Python, Rust, Node.js, and Helm toolchains from the repository root:```bash-uv python install 3.12-uv lock --check-uv sync --frozen --all-packages-uv run --frozen --project . --no-sync pytest -c pyproject.toml+./tools/init.sh```-Package membership is explicit in the root `pyproject.toml`; a package joins-the workspace only in the same change that adds its complete source.+The common development checks and local server are available as mise tasks:++```bash+mise run test+mise run lint+mise run typecheck+mise run serve+mise run rust-check+mise run rust-test+mise run gateway-test+mise run server-sidecar-test+```++The Python workspace uses the committed root lock. Package membership is+explicit in `pyproject.toml`; a package joins the workspace only in the same+change that adds its complete source. Native audio is always an opt-in build:+install cmake, then run+`mise exec -- uv sync --frozen --project . --all-packages --all-extras`.## Tasks@@ -67,8 +79,6 @@ One SIE cluster runs the inference behind a whole agent. Each task is a handful## Quickstart-Prefer a notebook? [`examples/quickstart.ipynb`](examples/quickstart.ipynb) runs this same flow, on your machine or a free Colab GPU.-**1. Start the server**```bash@@ -173,10 +183,10 @@ For generation on Apple Silicon (MLX), the TypeScript walkthrough, and every con### Production-The same code works against a production cluster. SIE ships a load-balancing gateway, KEDA autoscaling (scale to zero), Grafana dashboards, and Terraform modules for [GKE](https://github.com/superlinked/terraform-google-sie), [EKS](https://github.com/superlinked/terraform-aws-sie), and [AKS](https://github.com/superlinked/terraform-azure-sie). Not just the server, the whole stack. All Apache 2.0.+The same code works against a production cluster. SIE ships a load-balancing gateway and Kubernetes deployment surface, including Helm charts, KEDA autoscaling (scale to zero), and Grafana dashboards. Public Terraform modules are maintained separately for [Alibaba Cloud ACK](https://github.com/superlinked/terraform-alicloud-sie), [EKS](https://github.com/superlinked/terraform-aws-sie), [AKS](https://github.com/superlinked/terraform-azure-sie), and [GKE](https://github.com/superlinked/terraform-google-sie). Not just the server, the whole stack. All Apache 2.0.```bash-# pick one values overlay: values-gke.yaml / values-aws.yaml / values-aks.yaml+# pick one values overlay: values-ack.yaml / values-aws.yaml / values-aks.yaml / values-gke.yaml# (pin a chart version for reproducible installs, e.g. --version 0.6.18)helm upgrade --install sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \--namespace sie --create-namespace \@@ -197,7 +207,7 @@ See the [deployment guide](https://superlinked.com/docs/deployment/).[**Integrations**](https://superlinked.com/docs/integrations/): setup guides for all nine framework and vector-store integrations, in Python and TypeScript.-[**Examples**](examples/): A quickstart notebook and an end-to-end project gallery.+[**Examples**](examples/): An end-to-end project gallery.[**MCP edge**](packages/sie_mcp/): offload document work from Claude and other MCP clients to your cluster and save agent tokens.diff --git a/conformance/bundle_config_hash/canonical_profile_falsy_vectors.json b/conformance/bundle_config_hash/canonical_profile_falsy_vectors.jsonindex b975ceaad..feb843d6a 100644--- a/conformance/bundle_config_hash/canonical_profile_falsy_vectors.json+++ b/conformance/bundle_config_hash/canonical_profile_falsy_vectors.json@@ -1,5 +1,5 @@{- "_comment": "Shared conformance vectors for bundle_config_hash adapter_options canonicalization (issue #1542). Loaded by the Rust gateway (`packages/sie_gateway/src/types/model.rs`), the sie_config config service (`_canonical_adapter_options`), and the sie_server worker (`api.ws._compact_adapter_options_for_hash`). A divergence here makes a worker's advertised bundle_config_hash never match the gateway's expected hash, leaving it in pending_workers forever. `strip_to_none` and `keep_unchanged` exercise the GENERIC flat canonicalizers (gateway + config service), which strip an options map to None when every value is falsy (null/false/0/0.0/\"\"/[]/{}) and otherwise drop empty nested maps. `transform` exercises the loadtime/runtime compaction that real profiles use (adapter_options is always shaped {loadtime, runtime}); all three implementations — including the worker, whose canonicalizer is loadtime/runtime-structured rather than flat — must agree on it.",+ "_comment": "Shared conformance vectors for bundle_config_hash adapter_options canonicalization. Loaded by the Rust gateway (`packages/sie_gateway/src/types/model.rs`), the sie_config config service (`_canonical_adapter_options`), and the sie_server worker (`api.ws._compact_adapter_options_for_hash`). A divergence here makes a worker's advertised bundle_config_hash never match the gateway's expected hash, leaving it in pending_workers forever. `strip_to_none` and `keep_unchanged` exercise the GENERIC flat canonicalizers (gateway + config service), which strip an options map to None when every value is falsy (null/false/0/0.0/\"\"/[]/{}) and otherwise drop empty nested maps. `transform` exercises the loadtime/runtime compaction that real profiles use (adapter_options is always shaped {loadtime, runtime}); all three implementations — including the worker, whose canonicalizer is loadtime/runtime-structured rather than flat — must agree on it.","strip_to_none": [{ "name": "null_only", "adapter_options": { "x": null } },{ "name": "false_only", "adapter_options": { "enabled": false } },diff --git a/deny.toml b/deny.tomlindex c03513813..6bbc5a9d3 100644--- a/deny.toml+++ b/deny.toml@@ -1,14 +1,11 @@-# cargo-deny policy for the workspace (sie-gateway, sie-gateway-cloud,-# sie-server-sidecar, sie-audio-prep) — merged from the former per-crate-# packages/sie_gateway/deny.toml + packages/sie_audio_prep/deny.toml (#2339).-# packages/sie_server_rust is not a workspace member (see Cargo.toml) and,-# as before this merge, is not deny-audited.+# cargo-deny policy for the public Rust workspace. Standalone crates excluded+# from the root workspace are outside this single-lock audit.## Run with: `mise run gateway-deny`# Docs: https://embarkstudios.github.io/cargo-deny/[graph]-all-features = true # audit cloud-storage feature deps too+all-features = true # audit optional feature dependencies toono-default-features = false[advisories]@@ -26,8 +23,7 @@ ignore = [# depending on quick-xml >=0.41.{ id = "RUSTSEC-2026-0194", reason = "quick-xml <0.41 quadratic duplicate-attribute parse DoS (upstream #969); transitive via object_store 0.14.0 (pins ^0.40.1); awaiting upstream bump" },{ id = "RUSTSEC-2026-0195", reason = "quick-xml <0.41 namespace-declaration allocation DoS (upstream #970); transitive via object_store 0.14.0 (pins ^0.40.1); awaiting upstream bump" },- # Surfaced when the sidecar joined deny coverage (#2339): `paste` is- # archived-unmaintained (no vulnerability), transitive via+ # `paste` is archived and unmaintained (no vulnerability), transitive via# tokenizers 0.23 -> macro_rules_attribute. Drop when tokenizers ships a# release off macro_rules_attribute/paste.{ id = "RUSTSEC-2024-0436", reason = "paste unmaintained (archived, no vuln); transitive via tokenizers 0.23 macro_rules_attribute; awaiting upstream bump" },diff --git a/deploy/helm/sie-cluster/.helmignore b/deploy/helm/sie-cluster/.helmignorenew file mode 100644index 000000000..ad11ed634--- /dev/null+++ b/deploy/helm/sie-cluster/.helmignore@@ -0,0 +1,4 @@+# Helm dependency builds use tmpcharts-* staging directories. Exclude an+# interrupted build's residue from release records and the Kubernetes Secret+# size budget.+tmpcharts-*diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex 1de881f8b..9b667a58c 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.7.1 # x-release-please-version-appVersion: v0.7.1 # x-release-please-version+version: 0.7.2 # x-release-please-version+appVersion: v0.7.2 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex e6cf84484..90692a8d1 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -46,7 +46,7 @@ canonical physical tuple.## Cold Start Expectations-When scaling from zero, expect the following latencies:+The current GKE/EKS scale-from-zero guidance is:| Step | Duration | Notes ||-------|----------|-------|@@ -55,6 +55,11 @@ When scaling from zero, expect the following latencies:| **Model loading** | 10-120s | Download weights (if not cached), load to GPU || **Total cold start** | 3-7 min | First request to a scaled-to-zero pool |+These figures are not an ACK performance claim; this repository has no ACK+cold-start baseline. The Alibaba Terraform module defaults its shared NAT EIP+to 100 Mbit/s, and observed ACK cold start depends on current GPU inventory and+quota, effective bandwidth, image and model size, and cache state.+### Reducing Cold Start Time1. **Use cluster cache**: Pre-populate object storage with model weights (`--cluster-cache`)@@ -75,26 +80,79 @@ The SDK handles this automatically with configurable retries.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):**+**AWS example:**```bash-# 1. Provision the bucket via the AWS Terraform module (created by default; create_model_cache=true)-cd deploy/terraform/aws/examples/dev-g6-spot-terraform apply--# 2. One-time populate from your laptop-sie-admin cache weights sync --bundle default \- --dest $(terraform output -raw model_cache_bucket_url)/+# 1. Provision object storage and populate its /models prefix with model weights.+MODEL_CACHE_URL="s3://<bucket>/models"-# 3. Wire into Helm+# 2. Wire the readable object-store URL into Helm.helm upgrade --install sie-cluster . \--set workers.common.clusterCache.enabled=true \- --set workers.common.clusterCache.url=$(terraform output -raw model_cache_bucket_url)+ --set workers.common.clusterCache.url="$MODEL_CACHE_URL"+```++The configured URL must include the `/models` prefix and be readable by the worker workload identity. Because `payloadStore.enabled` defaults to `true`, the chart also derives a `/payloads` URL from this cache URL; grant the gateway workload write access and worker workloads read access to that prefix, configure a separate writable `payloadStore.url`, or set `payloadStore.enabled=false`.++**Other clouds / BYO bucket:** point `workers.common.clusterCache.url` at any `s3://...`, `gs://...`, `abfs://...`, `abfss://...`, or `oss://...` URL the worker workload identity can read, and populate the `/models` prefix with your object-storage tooling or existing cache pipeline. With the default payload store enabled, also grant the gateway workload write access and worker workloads read access to the derived `/payloads` prefix, configure a separate writable `payloadStore.url`, or set `payloadStore.enabled=false`.++## SGLang kernel cache++SGLang, FlashInfer, DeepGEMM, Triton, and the CUDA driver can compile kernels+after model weights are available. SIE remains fully cacheless-capable, but a+persistent compiler cache can avoid repeating that work after a container or+worker-pod replacement. It does not remove the first compilation on a genuinely+empty cache, and CUDA graphs are still captured by each live SGLang process.++For a local CUDA container, mount one named volume at the image's default cache+path:++```bash+docker run --gpus all -p 8080:8080 \+ -v sie-hf-cache:/app/.cache/huggingface \+ -v sie-kernel-cache:/app/.cache/sie-kernels \+ ghcr.io/superlinked/sie-server:latest-cuda13-sglang-cu130+```++CUDA images use `/app/.cache/sie-kernels` automatically; the named volume only+upgrades that container-local default to survive container replacement. The+adapter namespaces artifacts by the installed JIT dependency ABI and exact GPU+product name, then sets upstream cache locations only when operators have not+set those variables explicitly. An unwritable or unidentifiable cache falls+back to ordinary compilation.++For Kubernetes, enable retained per-replica claims globally or only for a+specific generation lane:++```yaml+workers:+ common:+ kernelCache:+ enabled: false+ storageSize: 20Gi+ storageClassName: "" # cluster default+ pools:+ h100:+ bundles:+ sglang-cu130:+ kernelCache:+ enabled: true+ preloadModels:+ - Qwen/Qwen3.8-27B-FP8:h100-256k```-The Terraform output already includes the `/models` prefix, so the same URL is used for both `sie-admin --target` and `clusterCache.url`.+Each StatefulSet ordinal receives its own `ReadWriteOnce` PVC, retained across+scale-down and pod replacement by the StatefulSet's default PVC policy. Do not+replace this with one concurrently writable RWX DeepGEMM cache. Ensure the+chosen StorageClass can provision in every zone that may host the GPU pool;+retained claims otherwise constrain later scheduling to their volume topology.+`preloadModels` fills the cache while the worker is still NotReady.-**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.+Adding or removing `volumeClaimTemplates` is an immutable StatefulSet change.+For an existing release, enable or disable this setting during a controlled+recreation of the affected worker StatefulSet; retained cache PVCs are+disposable acceleration state and may be deleted separately when no longer+needed.## Payload store@@ -104,7 +162,7 @@ It is therefore **enabled by default** (`payloadStore.enabled=true`) and is **deURL resolution, in order:-1. `payloadStore.url`, if set: the terraform `payload_store_url` output (the `/payloads` prefix of the shared bucket), or any `s3://` / `gs://` / `abfs(s)://` URL the workload identity can read and write.+1. `payloadStore.url`, if set: the terraform `payload_store_url` output (the `/payloads` prefix of the shared bucket), or any `s3://` / `gs://` / `abfs(s)://` / `oss://` URL the workload identity can read and write.2. otherwise derived from `workers.common.clusterCache.url` by swapping the trailing `/models` prefix for `/payloads` (the same bucket).```bash@@ -122,6 +180,80 @@ helm upgrade --install sie-cluster . --set payloadStore.enabled=false> **Upgrade note:** the payload store is on by default. An existing queue-mode install with *no* payload store and *no* cluster cache will fail on upgrade until it either sets a URL (above) or `payloadStore.enabled=false`. Installs that already set `workers.common.clusterCache.url` keep working; the payload store derives its URL from it.+### Alibaba Cloud ACK OSS and RRSA++`values-ack.yaml` enables the payload store and configures every OSS-consuming+container for `eu-central-1`, the private OSS endpoint, and disabled ECS+metadata credentials. Install with Terraform's native OSS outputs and exact+RRSA role-name annotation:++```bash+helm upgrade --install sie-cluster . -f values-ack.yaml \+ --set workers.common.clusterCache.enabled=true \+ --set workers.common.clusterCache.url="$(terraform output -raw model_cache_bucket_url)" \+ --set payloadStore.url="$(terraform output -raw payload_store_url)" \+ --set-string 'serviceAccount.annotations.pod-identity\.alibabacloud\.com/role-name'="$(terraform output -raw rrsa_workload_role_name)"+```++The shared `sie-server` ServiceAccount and+`pod-identity.alibabacloud.com/injection: "on"` pod label engage ACK RRSA. Do+not render long-lived AccessKeys or `ALIBABA_CLOUD_STS_ENDPOINT`; the Terraform+webhook config leaves STS convenience-env injection off so the runtime keeps+its fixed official endpoint policy. Mutable `sie-config` state remains on its+local/PVC `SIE_CONFIG_STORE_DIR`; `oss://` is intentionally rejected for that+epoch/CAS authority.++ACK may install disk CSI classes without marking one as default. The ACK+overlay therefore binds the config, Prometheus, Grafana, and Loki claims to+`alicloud-disk-topology-alltype`, the topology-aware WFFC class, and raises the+config/Grafana claims to ACK's 20 GiB dynamic-disk minimum. The retained+capacities are 20 GiB config, 20 GiB Grafana, 100 GiB Prometheus, and 50 GiB+Loki. The built-in class does not itself prove encryption. Deployments+requiring encrypted PVCs must provide a governed encrypted WFFC class and+override all four paths together:++```yaml+config:+ configStore:+ storageClassName: your-encrypted-class+kube-prometheus-stack:+ prometheus:+ prometheusSpec:+ storageSpec:+ volumeClaimTemplate:+ spec:+ storageClassName: your-encrypted-class+ grafana:+ persistence:+ storageClassName: your-encrypted-class+loki:+ singleBinary:+ persistence:+ storageClass: your-encrypted-class+```++The overlay also runs `sie-config` as UID/GID 1000 with `fsGroup: 1000` and+`fsGroupChangePolicy: OnRootMismatch`, keeping the CSI volume writable without+granting root execution.++Storage class is not an ordinary values-only in-place migration for a bound+PVC, and a StatefulSet volume-claim template is immutable. For an empty failed+install, uninstall the exact release, independently prove that every retained+old claim is `Pending`, unbound, and has no volume, delete only those exact+empty claims, verify their absence, and then reinstall. StatefulSet and+operator-created claims can survive Helm uninstall. A data-bearing installation+requires a separately planned backup and volume migration; do not apply these+overrides as an in-place Helm-only change.++### Alibaba Cloud ACK ingress++`values-ack.yaml` sets `ingress.enabled=false` because the Alibaba Terraform+module does not install an ingress controller. Install and secure an+ACK-compatible controller such as ingress-nginx first, wait for its controller+and load balancer to be ready, and only then enable this chart's Ingress with a+matching `ingress.className`. Until then, use cluster-private service access or+an explicitly controlled port-forward.+## AutoscalingKEDA-based autoscaling with scale-to-zero support:@@ -200,13 +332,18 @@ the collector, Prometheus, KEDA, image, quota, or permission issue, and rerunthe same forward upgrade. There is no extra migration command, pauseannotation, values overlay, second release, or target-owned migration state.Canonical `0.6.20` can leave one inert hook ConfigMap containing obsolete-manifest text; remove it once after success using the upgrade runbook's exact-post-success check. Fresh installs and later compatible releases use the normal-Helm procedure as well.+manifest text. After the target health hooks succeed, inspect that exact source+object and remove it once; deletion is post-success hygiene, not part of the+cutover:-The complete preflight, external-dependency requirements, over-limit lane-reduction, verification, and one-time inert ConfigMap cleanup are in the-[upgrade runbook](../../upgrade-runbook.md).+```bash+LEGACY_KEDA_CONFIGMAP="<SOURCE_FULLNAME>-keda-scaledobjects"+kubectl get configmap "$LEGACY_KEDA_CONFIGMAP" -n <NAMESPACE> -o yaml+# Delete only after confirming component=keda-apply and the old Helm hook annotations.+kubectl delete configmap "$LEGACY_KEDA_CONFIGMAP" -n <NAMESPACE> --ignore-not-found+```++Fresh installs and later compatible releases use the normal Helm procedure.Disabling autoscaling or uninstalling runs a small hook that deletes onlyScaledObjects carrying this release's managed identity or the exact canonical@@ -333,10 +470,14 @@ See `values.yaml` for all options. Key settings:**Important**: All worker pools are disabled by default. You must explicitly enablethe pools you need in your values override.-The values below are an illustrative shape; concrete per-cluster sizes-live in each cluster's own values file (e.g. the tester cluster's-rtx6000 default bundle scales 3–10 — see-`deploy/terraform/aws/internal-examples/tester-cluster/DEPLOY.md`).+> **Bundle rename:** the CUDA 13 SGLang bundle formerly named `gemma` is now+> `sglang-cu130`, and its image tag is `cuda13-sglang-cu130`. Existing values+> overrides must rename the `workers.common.bundlePlatforms` key, worker bundle+> key, and any explicit image tag together. There is no runtime alias because+> the bundle name is part of worker routing and release-image identity.++The values below are an illustrative shape; concrete per-cluster sizes belong+in each deployment's own values file.```yaml# Worker pool configuration (must explicitly enable pools)@@ -405,7 +546,7 @@ fixed sidecar policy.For local CPU-only dev, `workers.pools.<name>.sidecar.emulatedChildCount` canrender multiple CPU worker children with distinct IPC sockets and no-`nvidia.com/gpu` request. This is intended for Tilt/e2e coverage of child+`nvidia.com/gpu` request. This is intended for local integration coverage of childrouting and metrics only; GPU pools must use `gpu.count` for real capacity.This is the Req6 one-child-at-a-time model placement topology. It distributes@@ -484,6 +625,75 @@ For emergency or legacy static namespaces that are not backed by eithergate. Prefer declaring static pools instead, so capped/dynamic pools keep theirfail-closed isolation behavior.+### Work-queue durability (memory vs file storage)++The work queues ship **memory-backed and single-replica**, which is the only+behavior this chart has ever had. `WORK_POOL_{pool}`, the per-worker+direct-dispatch streams, and `DEAD_LETTERS` live in the NATS broker's RAM. That+is durable against *worker* failure — a pod that dies mid-item leaves the item+unacked and another worker picks it up — but **not** against *broker* failure. A+restart of the NATS pod erases every queued and delivered-but-unacked item along+with the dead-letter records that would have named them, and because the gateway+is queue-only with no direct-HTTP fallback, the restart is a full inference+outage for its duration.++The trigger is specifically a restart of the **NATS** pod: an OOM kill, a NATS+version or config rollout, or a node drain that evicts that pod. Draining a node+that hosts only workers or gateways is harmless here, as is a worker or gateway+rollout. At the default `streamReplicas: 1` any eviction of that single pod+loses the state; with a replicated stream it survives while one peer holding it+stays up, which is what makes rolling NATS maintenance safe.++To opt into file-backed, replicated storage:++```yaml+queueRouting:+ streamStorage: file # default: memory+ streamReplicas: 3 # default: 1+nats:+ config:+ cluster:+ enabled: true # required for streamReplicas > 1+ replicas: 3+ jetstream:+ fileStore:+ enabled: true # required for streamStorage=file+ pvc:+ size: 10Gi+```++`streamStorage` and `streamReplicas` are rendered into `SIE_STREAM_STORAGE` /+`SIE_STREAM_REPLICAS` on **both** the gateway and the worker sidecars. Both+create streams and whoever gets there first wins, so the chart is the single+source of truth for the pair; the template rejects a render where the requested+durability outruns what the broker is configured to provide, and both env names+are reserved, so a `gateway.extraEnv` or+`workers.common.workerSidecar.extraEnv` entry that tried to override one on a+single side fails the render rather than silently splitting the two creators.++That render guard is load-bearing for `streamReplicas`, because **NATS will not+catch the mistake for you**: a single-node server accepts `num_replicas: 3` and+then reports R3, with no peers to replicate to (verified against nats-server+2.12.6). Without the guard, a replicated-looking stream would run+single-copy.++**The trade-off.** File storage puts a disk write in front of every publish+ACK, so it costs publish latency on the inference hot path, and it needs a PVC+per NATS pod sized for peak queue depth (`max_msgs` is 100,000 per pool stream)+plus 24 h of `DEAD_LETTERS` retention. Replication multiplies that cost by the+replica count and adds a quorum round trip. This is why the default is left+memory-backed: whether the latency and disk are worth the durability depends on+the workload, and that is an operator decision, not a chart default.++**Changing it on a live cluster.** JetStream refuses an in-place storage-type+change (err_code 10052), so flipping `streamStorage` does **not** convert+existing streams. The gateway and sidecars log a warning naming the divergence+and leave the streams alone, which is deliberate: converting would mean deleting+and recreating the stream, destroying exactly the queued work that durability is+meant to protect. Drain the pool and delete the streams during a maintenance+window to pick up the new storage. `streamReplicas`, by contrast, **is**+reconciled onto existing streams.+### Upgrading from the legacy single-bundle pool schemaReleases up to and including 0.4.x used a flat schema where each pool@@ -848,13 +1058,10 @@ telemetry:deploymentEnv: staging # production (default) | staging | development | ci```-> **Internal Superlinked clusters:** any cluster owned by Superlinked that is-> not a customer-facing production install MUST set `telemetry.deploymentEnv`-> to one of `staging | development | ci`. The chart default is `production`-> so that customer Helm installs are correctly tagged out of the box; internal-> stacks must opt out explicitly to keep them out of the production telemetry-> dashboards. See `deploy/terraform/{aws,gcp}/internal-examples/` for the-> per-cluster mapping.+> **Non-production deployments:** set `telemetry.deploymentEnv` to one of+> `staging | development | ci`. The chart default is `production`, so every+> non-production values overlay must opt out explicitly to keep its signals out+> of production dashboards.## Observabilitydiff --git a/deploy/helm/sie-cluster/files/.gitignore b/deploy/helm/sie-cluster/files/.gitignoreindex d74d475b3..58f0f3e0e 100644--- a/deploy/helm/sie-cluster/files/.gitignore+++ b/deploy/helm/sie-cluster/files/.gitignore@@ -1,4 +1,4 @@# Auto-generated files for embeddedConfigs-# These are copied from packages/sie_server/ by matrix-eval before helm install+# ``mise run helm`` stages these from packages/sie_server/ before installation.bundles/models/diff --git a/deploy/helm/sie-cluster/files/dashboards/generation.json b/deploy/helm/sie-cluster/files/dashboards/generation.jsonindex 2cf70d1a1..d667ba264 100644--- a/deploy/helm/sie-cluster/files/dashboards/generation.json+++ b/deploy/helm/sie-cluster/files/dashboards/generation.json@@ -986,6 +986,11 @@"legendFormat": "TTFT {{model}} / {{profile}} / {{grammar}}","refId": "A"},+ {+ "expr": "histogram_quantile(0.95, sum by (le, model, profile, grammar) (rate(sie_worker_generation_worker_wait_seconds_bucket{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-worker\"}[$rate_window])))",+ "legendFormat": "worker wait {{model}} / {{profile}} / {{grammar}}",+ "refId": "W"+ },{"expr": "histogram_quantile(0.95, sum by (le, model, profile, grammar) (rate(sie_worker_generation_tpot_seconds_bucket{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-worker\"}[$rate_window])))","legendFormat": "TPOT {{model}} / {{profile}} / {{grammar}}",diff --git a/deploy/helm/sie-cluster/files/dashboards/perf-tuning.json b/deploy/helm/sie-cluster/files/dashboards/perf-tuning.jsonindex b713184a8..093251801 100644--- a/deploy/helm/sie-cluster/files/dashboards/perf-tuning.json+++ b/deploy/helm/sie-cluster/files/dashboards/perf-tuning.json@@ -7,15 +7,7 @@"fiscalYearStartMonth": 0,"graphTooltip": 1,"id": null,- "links": [- {- "title": "Findings doc",- "url": "https://github.com/superlinked/sie-perf-lab/blob/main/docs/l4-cluster-perf-tuning.md",- "type": "link",- "targetBlank": true,- "tags": []- }- ],+ "links": [],"panels": [{"gridPos": { "h": 2, "w": 24, "x": 0, "y": 0 },@@ -363,7 +355,7 @@"type": "text","options": {"mode": "markdown",- "content": "## GPU device counters (DCGM)\nL4 TDP = **72 W**, stock max proc clock = **2040 MHz**. Sustained power ≥ 65 W with proc clock ≤ 1500 MHz is the **power-capped** signature. See sie-perf-lab/docs/l4-cluster-perf-tuning.md §6.\n\n**MFU proxies** (below): `DCGM_FI_PROF_SM_ACTIVE` ≈ fraction of cycles an SM has ≥1 warp assigned (saturation). `DCGM_FI_PROF_PIPE_FP16_ACTIVE` + `PIPE_TENSOR_ACTIVE` = fraction of cycles the FP16/HMMA pipes are computing — our embedding model runs FP16 so `PIPE_FP16_ACTIVE` ≫ `PIPE_TENSOR_ACTIVE` is expected on varlen flash-attn."+ "content": "## GPU device counters (DCGM)\nL4 TDP = **72 W**, stock max proc clock = **2040 MHz**. Sustained power ≥ 65 W with proc clock ≤ 1500 MHz is the **power-capped** signature.\n\n**MFU proxies** (below): `DCGM_FI_PROF_SM_ACTIVE` ≈ fraction of cycles an SM has ≥1 warp assigned (saturation). `DCGM_FI_PROF_PIPE_FP16_ACTIVE` + `PIPE_TENSOR_ACTIVE` = fraction of cycles the FP16/HMMA pipes are computing — our embedding model runs FP16 so `PIPE_FP16_ACTIVE` ≫ `PIPE_TENSOR_ACTIVE` is expected on varlen flash-attn."}},{diff --git a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json b/deploy/helm/sie-cluster/files/dashboards/queue-routing.jsonindex 2ecabdb98..bd33989dd 100644--- a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json+++ b/deploy/helm/sie-cluster/files/dashboards/queue-routing.json@@ -1028,7 +1028,7 @@},"id": 70,"title": "Gateway Config, Queue, and Provisioning Event Rate",- "description": "Bounded gateway config operations, logical queue publishes/result waits, durability events, and provisioning responses.",+ "description": "Bounded gateway config operations, logical queue publishes/result waits, durability events, provisioning responses, and per-lane queue admission decisions. A lane_admission outcome of shed_shadow is the decision the per-lane check would have taken with SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE on; it never changes admission, so it is how the shadow period is read before the flag is flipped.","type": "timeseries","fieldConfig": {"defaults": {@@ -1076,6 +1076,11 @@"expr": "sum by (surface, http_status_code) (rate(sie_gateway_provisioning_responses_total{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"}[$rate_window]))","legendFormat": "provisioning {{surface}} / {{http_status_code}}","refId": "E"+ },+ {+ "expr": "sum by (pool, machine_profile, bundle, outcome) (rate(sie_gateway_queue_lane_admission_decisions_total{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"}[$rate_window]))",+ "legendFormat": "lane admission {{pool}}/{{machine_profile}}/{{bundle}} / {{outcome}}",+ "refId": "F"}]},@@ -1556,6 +1561,178 @@"refId": "A"}]+ },+ {+ "gridPos": {+ "h": 8,+ "w": 12,+ "x": 12,+ "y": 101+ },+ "id": 115,+ "type": "timeseries",+ "title": "Work item age at execution",+ "description": "Age of a work item at the instant the worker commits to executing it, measured from the gateway publish timestamp on its envelope, per operation. This is the TRANSPORT queue age and is not the same thing as the worker-local scheduler wait next to it: it spans broker enqueue, redelivery, pull, payload fetch, and scheduling. Recorded at every execution-commit point including generation, so no operation is missing; items that never execute (cancelled, payload-fetch failures, NAK-for-redelivery) are deliberately not counted. Read the 120s line against the client-facing request ceiling - work above it started after its caller could still have been waiting, which is work the cluster ran for nobody. The p50/p95 split says whether that is a tail or the steady state.",+ "fieldConfig": {+ "defaults": {+ "unit": "s",+ "min": 0+ }+ },+ "options": {+ "legend": {+ "calcs": [+ "mean",+ "max"+ ],+ "displayMode": "table",+ "placement": "bottom",+ "showLegend": true+ },+ "tooltip": {+ "mode": "multi",+ "sort": "desc"+ }+ },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "expr": "histogram_quantile(0.50, sum by (le, operation) (rate(sie_worker_work_item_age_seconds_bucket{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-worker-sidecar\"}[$rate_window])))",+ "legendFormat": "p50 {{operation}}",+ "refId": "A"+ },+ {+ "expr": "histogram_quantile(0.95, sum by (le, operation) (rate(sie_worker_work_item_age_seconds_bucket{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-worker-sidecar\"}[$rate_window])))",+ "legendFormat": "p95 {{operation}}",+ "refId": "B"+ }+ ]+ },+ {+ "gridPos": {+ "h": 8,+ "w": 12,+ "x": 0,+ "y": 109+ },+ "id": 116,+ "type": "timeseries",+ "title": "Key snapshot poll outcomes",+ "description": "Effectiveness of the managed gateway's conditional key-snapshot poll. `not_modified` is the 304 fast path, where the control plane computed no body at all. `installed` is a 200 that advanced this replica's held version. `discarded` is the one to watch: a 200 whose body did NOT advance the version, so it was computed, serialised, transferred, parsed, and thrown away. A high discarded rate means the fast path is missing because something in the estate keeps bumping the global version inside the poll window. Managed-topology only; a self-hosted cluster does not poll a control plane and reports no series here.",+ "fieldConfig": {+ "defaults": {+ "unit": "reqps",+ "min": 0+ }+ },+ "options": {+ "legend": {+ "calcs": [+ "mean",+ "lastNotNull"+ ],+ "displayMode": "table",+ "placement": "bottom",+ "showLegend": true+ },+ "tooltip": {+ "mode": "multi",+ "sort": "desc"+ }+ },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "expr": "sum by (outcome) (rate(sie_gateway_key_snapshot_polls_total{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"}[$rate_window]))",+ "legendFormat": "{{outcome}}/sec",+ "refId": "A"+ }+ ]+ },+ {+ "gridPos": {+ "h": 8,+ "w": 12,+ "x": 12,+ "y": 109+ },+ "id": 117,+ "type": "timeseries",+ "title": "Settlement confirm on the buffered response path",+ "description": "What a buffered managed response waits on before it is returned to the customer. The duration is the control-plane settlement confirmation only; compare it against sie_gateway_request_duration_seconds on the same producer to get the confirm's share of end-to-end buffered latency. The `skipped` outcome is a request that took no reservation and issued no control-plane call, so it is counted but contributes no duration. This panel mixes two units deliberately - the p95 series are seconds and the outcome series are events per second, as the legend labels say - so the axis unit is neutral rather than mislabelling the rates as durations. Managed-topology only.",+ "fieldConfig": {+ "defaults": {+ "unit": "short",+ "min": 0+ }+ },+ "options": {+ "legend": {+ "calcs": [+ "mean",+ "max"+ ],+ "displayMode": "table",+ "placement": "bottom",+ "showLegend": true+ },+ "tooltip": {+ "mode": "multi",+ "sort": "desc"+ }+ },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(sie_gateway_settlement_confirm_duration_seconds_bucket{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"}[$rate_window])))",+ "legendFormat": "p95 confirm s {{outcome}}",+ "refId": "A"+ },+ {+ "expr": "sum by (outcome) (rate(sie_gateway_settlement_confirms_total{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"}[$rate_window]))",+ "legendFormat": "{{outcome}}/sec",+ "refId": "B"+ }+ ]+ },+ {+ "description": "Pressure on the gateway's keyed worker pools, by pool and event. The two pools have deliberately opposite policies, so the two rates mean different things and carry different expectations.\n\n`inbox/saturated`: a shard queue filled and the decode task blocked rather than dropping. Dropping a result or a stream chunk is a correctness fault, so blocking is the intended behaviour. Expected to sit at zero; a sustained non-zero rate means results are arriving faster than that shard drains, which is worth correlating with decode latency and downstream handler time before concluding where the bottleneck is.\n\n`payload_cleanup/shed`: an offloaded-payload delete was dropped because its pool was full. This is by design and is recovered by the expiry reconcile, so a non-zero rate is not an error; it costs bounded blob residency until the next reconcile. Watch it for a sustained climb rather than for any activity at all.",+ "fieldConfig": {+ "defaults": {+ "unit": "short"+ }+ },+ "gridPos": {+ "h": 8,+ "w": 24,+ "x": 0,+ "y": 117+ },+ "id": 118,+ "options": {+ "legend": {+ "calcs": [+ "mean",+ "max"+ ],+ "displayMode": "table",+ "placement": "bottom",+ "showLegend": true+ },+ "tooltip": {+ "mode": "multi",+ "sort": "desc"+ }+ },+ "targets": [+ {+ "expr": "sum by (pool, event) (rate(sie_gateway_queue_worker_pool_events_total{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"}[$__rate_interval]))",+ "legendFormat": "{{pool}} {{event}}/sec",+ "refId": "A"+ }+ ],+ "title": "Gateway Queue Worker-Pool Backpressure and Shed",+ "type": "timeseries"}],"refresh": "10s",diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex 9ece2ad26..350977cda 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -322,6 +322,55 @@ Gateway service name (used for worker discovery){{- printf "%s-gateway" $fullname }}{{- end }}+{{/*+Gateway preStop sleep (seconds), read once so the Deployment's lifecycle hook+and the derived grace period below can never disagree.+Consume with: include "sie-cluster.gateway.preStopSleepSeconds" .+*/}}+{{- define "sie-cluster.gateway.preStopSleepSeconds" -}}+{{- $drain := default (dict) (default (dict) .Values.gateway).drain -}}+{{- $preStopS := int (dig "preStopSleepSeconds" 10 $drain) -}}+{{- if lt $preStopS 0 -}}+{{- fail (printf "gateway.drain.preStopSleepSeconds must be >= 0, got %d: a negative sleep renders an invalid preStop hook and shortens the derived terminationGracePeriodSeconds" $preStopS) -}}+{{- end -}}+{{- $preStopS -}}+{{- end -}}++{{/*+Gateway terminationGracePeriodSeconds, DERIVED from the gateway drain budget so+the two numbers cannot drift apart.++Shutting a gateway pod down is three serial phases, and the grace period is the+single clock covering all of them (kubelet starts it when the pod goes+Terminating, i.e. before preStop runs):++ 1. gateway.drain.preStopSleepSeconds — preStop sleep. The pod is already out+ of the EndpointSlice, but kube-proxy/ingress dataplane updates are+ eventually consistent, so it keeps serving newly-arriving requests. No+ SIGTERM is delivered during this window.+ 2. gateway.drain.inFlightSeconds — axum graceful shutdown after SIGTERM. It is+ unbounded in the binary (packages/sie_gateway/src/main.rs), so this value+ is the real bound: the longest response the gateway may still be carrying,+ including SSE generation streams and queued-result waits.+ 3. QUEUE_DRAIN_S — the fixed post-serve `drain_pending(5s)` in the same file,+ which lets already-published work items land their NATS `_INBOX` replies+ instead of dying with the subscription.++Whatever is still running when the grace period expires is SIGKILLed, which is+exactly the mid-response connection cut this budget exists to prevent.+Consume with: include "sie-cluster.gateway.terminationGracePeriodSeconds" .+*/}}+{{- define "sie-cluster.gateway.terminationGracePeriodSeconds" -}}+{{- $drain := default (dict) (default (dict) .Values.gateway).drain -}}+{{- $preStopS := int (include "sie-cluster.gateway.preStopSleepSeconds" .) -}}+{{- $inFlightS := int (dig "inFlightSeconds" 120 $drain) -}}+{{- if lt $inFlightS 0 -}}+{{- fail (printf "gateway.drain.inFlightSeconds must be >= 0, got %d: a negative budget shortens the grace period below the gateway's own fixed queue drain, so in-flight work is SIGKILLed" $inFlightS) -}}+{{- end -}}+{{- $queueDrainS := 5 -}}+{{- add $preStopS $inFlightS $queueDrainS -}}+{{- end -}}+{{/*In-cluster URL used by workers to ask the gateway whether they are admittedto pull from their configured queue pool.@@ -412,6 +461,30 @@ Consume with: include "sie-cluster.ingress.hosts" . | fromJsonArray{{- $hosts | toJson -}}{{- end -}}+{{/*+nginx proxy read/send timeout (seconds) for every SIE ingress, derived from+`workers.common.modelReadyTimeoutSec` so the edge budget cannot drift below the+cold-load budget it fronts.++The first request against an unloaded model produces no response bytes until+the worker finishes loading it (up to modelReadyTimeoutSec), and nginx's+proxy-read-timeout applies to exactly that no-first-byte window. An edge+timeout below the load budget turns a healthy cold start into a 504 plus a+client retry that can re-enter the same wait. Already-streaming responses are+unaffected — the read timeout resets on each chunk.+++60s covers serving the request itself once the model is ready; the 600s floor+preserves the chart's historical minimum when modelReadyTimeoutSec is lowered+(note that `ingress.annotations` cannot lower it either — sprig `merge` keeps+the destination's value, so the chart's nginx defaults win over user keys).+Consume with: include "sie-cluster.ingress.proxyTimeoutSeconds" .+*/}}+{{- define "sie-cluster.ingress.proxyTimeoutSeconds" -}}+{{- $workersCommon := default (dict) (default (dict) .Values.workers).common -}}+{{- $modelReadyTimeoutS := int (dig "modelReadyTimeoutSec" 900 $workersCommon) -}}+{{- max (add $modelReadyTimeoutS 60) 600 -}}+{{- end -}}+{{/*Validation: TLS / cert-manager / trust-manager configuration consistency.Runs from NOTES.txt so every install/upgrade is checked, regardless of which (or no) Issuer template renders.@@ -642,20 +715,24 @@ Resolution order:exposes the cache URL as "<scheme>://<bucket-or-container>/models" byconvention, so the auto-derivation strips a trailing "/models" segmentbefore appending "/payloads". The resulting layout is:- <bucket-or-container>/models/... weights (managed by sie-admin cache)+ <bucket-or-container>/models/... weights (populated separately)<bucket-or-container>/payloads/... large work-item refs (managed by gateway)- These siblings live at the bucket/container root, which is what the- workload IAM grants are scoped to in all three (AWS, GCP, Azure)- terraform modules.+ Managed-storage payload object access is scoped to payloads/: AWS grants+ object actions on payloads/* and conditions bucket-level ListBucket on+ that prefix; GCP conditions payload get/create/delete on payloads/ but+ grants storage.objects.list separately bucket-wide; and Azure conditions+ blob data actions on payloads/ while exempting Blob.List from the path+ condition; and Alibaba grants payload object actions on payloads/* while+ conditioning bucket-level ListObjects on models/* and payloads/*. The+ legacy GCP BYO-bucket path grants objectViewer bucket-wide; operators own+ IAM scoping for other explicitly configured BYO storage.3. Otherwise -> empty string (payload store is off, no env vars rendered).Supported URL schemes: s3:// (AWS), gs:// (GCP), abfs:// + abfss:// (Azure-Data Lake Storage Gen2 / Blob with hierarchical namespace enabled). The-Azure scheme variant is treated identically to the AWS/GCP variants for-the derivation step — the trailing "/models" → "/payloads" swap works-the same way because Azure URLs follow the same-"<scheme>://<container>@<account>.dfs.core.windows.net/<prefix>"-convention exposed by the deploy/terraform/azure module.+Data Lake Storage Gen2 / Blob with hierarchical namespace enabled), and+oss:// (Alibaba Cloud). The trailing "/models" -> "/payloads" derivation+works for every supported URL shape, including the ADLS Gen2+"<scheme>://<container>@<account>.dfs.core.windows.net/<prefix>" form.Templates that consume this should treat a non-empty result as "payloadstore enabled" and an empty result as "off".diff --git a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl b/deploy/helm/sie-cluster/templates/_otel-collector-config.tplindex df1f573f6..364f0b5aa 100644--- a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl+++ b/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl@@ -89,18 +89,18 @@ processors:error_mode: propagatemetrics:metric:- - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pool[.]pinned_model[.]loaded|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]capacity[.]snapshot[.]timestamp)$")'+ - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]queue[.]worker_pool[.]events|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pool[.]pinned_model[.]loaded|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]capacity[.]snapshot[.]timestamp|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'- 'resource.attributes["service.name"] != "sie-gateway"'filter/prometheus_application_contract:error_mode: propagatemetrics:metric:- - 'not IsMatch(name, "^(sie[.]dispatcher[.]invocations|sie[.]dispatcher[.]invocation[.]duration|sie[.]dispatcher[.]inflight|sie[.]dispatcher[.]sealed[.]stage|sie[.]dispatcher[.]sealed[.]stage[.]duration|sie[.]dispatcher[.]sealed[.]resident|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds|sie[.]dispatcher[.]sealed[.]cold_start[.]seconds|sie[.]config[.]requests|sie[.]config[.]request[.]duration|sie[.]config[.]epoch|sie[.]config[.]models|sie[.]config[.]publish|sie[.]config[.]store[.]writes|sie[.]config[.]messaging[.]ready|sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]ipc[.]requests|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]ipc[.]response[.]chunks|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]count|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]config[.]applies|sie[.]worker[.]config[.]epoch|sie[.]worker[.]config[.]degraded|sie[.]worker[.]nats[.]operations|sie[.]worker[.]nats[.]delivery[.]attempts|sie[.]worker[.]result[.]transport[.]attempts|sie[.]worker[.]result[.]chunks[.]published|sie[.]worker[.]result[.]chunk[.]size|sie[.]worker[.]payload[.]fetches|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]payload[.]size|sie[.]worker[.]gpu[.]slots|sie[.]worker[.]pending[.]items|sie[.]worker[.]pending[.]cost|sie[.]worker[.]inflight[.]batches|sie[.]worker[.]saturated|sie[.]worker[.]ipc[.]capacity|sie[.]worker[.]ipc[.]inflight|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]generation[.]model_loading[.]responses|sie[.]worker[.]shutdown[.]drain[.]duration|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]batch[.]subgroups|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]units|sie[.]worker[.]model[.]loaded|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]model[.]memory|sie[.]worker[.]oom[.]recoveries|sie[.]worker[.]model[.]evictions|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]inflight|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget|sie[.]worker[.]generation[.]admission[.]decisions|sie[.]worker[.]generation[.]duplicate_prevented|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]generation[.]grammar[.]cache[.]lookups|sie[.]worker[.]generation[.]grammar[.]requests|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]worker[.]runtime[.]forward[.]concurrent|sie[.]worker[.]runtime[.]forward[.]limit)$")'+ - 'not IsMatch(name, "^(sie[.]dispatcher[.]invocations|sie[.]dispatcher[.]invocation[.]duration|sie[.]dispatcher[.]inflight|sie[.]dispatcher[.]sealed[.]stage|sie[.]dispatcher[.]sealed[.]stage[.]duration|sie[.]dispatcher[.]sealed[.]resident|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds|sie[.]dispatcher[.]sealed[.]cold_start[.]seconds|sie[.]config[.]requests|sie[.]config[.]request[.]duration|sie[.]config[.]epoch|sie[.]config[.]models|sie[.]config[.]publish|sie[.]config[.]store[.]writes|sie[.]config[.]messaging[.]ready|sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]ipc[.]requests|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]ipc[.]response[.]chunks|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]count|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]config[.]applies|sie[.]worker[.]config[.]epoch|sie[.]worker[.]config[.]degraded|sie[.]worker[.]nats[.]operations|sie[.]worker[.]nats[.]delivery[.]attempts|sie[.]worker[.]result[.]transport[.]attempts|sie[.]worker[.]result[.]chunks[.]published|sie[.]worker[.]result[.]chunk[.]size|sie[.]worker[.]payload[.]fetches|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]payload[.]size|sie[.]worker[.]gpu[.]slots|sie[.]worker[.]pending[.]items|sie[.]worker[.]pending[.]cost|sie[.]worker[.]inflight[.]batches|sie[.]worker[.]saturated|sie[.]worker[.]ipc[.]capacity|sie[.]worker[.]ipc[.]inflight|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]generation[.]model_loading[.]responses|sie[.]worker[.]shutdown[.]drain[.]duration|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]batch[.]subgroups|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]units|sie[.]worker[.]model[.]loaded|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]model[.]memory|sie[.]worker[.]oom[.]recoveries|sie[.]worker[.]model[.]evictions|sie[.]worker[.]generation[.]worker_wait|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]inflight|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget|sie[.]worker[.]generation[.]admission[.]decisions|sie[.]worker[.]generation[.]duplicate_prevented|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]generation[.]grammar[.]cache[.]lookups|sie[.]worker[.]generation[.]grammar[.]requests|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]worker[.]runtime[.]forward[.]concurrent|sie[.]worker[.]runtime[.]forward[.]limit|sie[.]worker[.]work_item[.]age)$")'- 'resource.attributes["service.name"] != "sie-config" and resource.attributes["service.name"] != "sie-dispatcher" and resource.attributes["service.name"] != "sie-worker" and resource.attributes["service.name"] != "sie-worker-sidecar"'- 'resource.attributes["service.name"] == "sie-dispatcher" and not IsMatch(name, "^(sie[.]dispatcher[.]invocations|sie[.]dispatcher[.]invocation[.]duration|sie[.]dispatcher[.]inflight|sie[.]dispatcher[.]sealed[.]stage|sie[.]dispatcher[.]sealed[.]stage[.]duration|sie[.]dispatcher[.]sealed[.]resident|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds|sie[.]dispatcher[.]sealed[.]cold_start[.]seconds)$")'- 'resource.attributes["service.name"] == "sie-config" and not IsMatch(name, "^(sie[.]config[.]requests|sie[.]config[.]request[.]duration|sie[.]config[.]epoch|sie[.]config[.]models|sie[.]config[.]publish|sie[.]config[.]store[.]writes|sie[.]config[.]messaging[.]ready)$")'- - 'resource.attributes["service.name"] == "sie-worker-sidecar" and not IsMatch(name, "^(sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]ipc[.]requests|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]ipc[.]response[.]chunks|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]count|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]config[.]applies|sie[.]worker[.]config[.]epoch|sie[.]worker[.]config[.]degraded|sie[.]worker[.]nats[.]operations|sie[.]worker[.]nats[.]delivery[.]attempts|sie[.]worker[.]result[.]transport[.]attempts|sie[.]worker[.]result[.]chunks[.]published|sie[.]worker[.]result[.]chunk[.]size|sie[.]worker[.]payload[.]fetches|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]payload[.]size|sie[.]worker[.]gpu[.]slots|sie[.]worker[.]pending[.]items|sie[.]worker[.]pending[.]cost|sie[.]worker[.]inflight[.]batches|sie[.]worker[.]saturated|sie[.]worker[.]ipc[.]capacity|sie[.]worker[.]ipc[.]inflight|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]generation[.]model_loading[.]responses|sie[.]worker[.]shutdown[.]drain[.]duration)$")'- - 'resource.attributes["service.name"] == "sie-worker" and not IsMatch(name, "^(sie[.]worker[.]queue[.]duration|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]batch[.]subgroups|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]units|sie[.]worker[.]model[.]loaded|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]model[.]memory|sie[.]worker[.]oom[.]recoveries|sie[.]worker[.]model[.]evictions|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]inflight|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget|sie[.]worker[.]generation[.]admission[.]decisions|sie[.]worker[.]generation[.]duplicate_prevented|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]generation[.]grammar[.]cache[.]lookups|sie[.]worker[.]generation[.]grammar[.]requests|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]worker[.]runtime[.]forward[.]concurrent|sie[.]worker[.]runtime[.]forward[.]limit)$")'+ - 'resource.attributes["service.name"] == "sie-worker-sidecar" and not IsMatch(name, "^(sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]ipc[.]requests|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]ipc[.]response[.]chunks|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]count|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]config[.]applies|sie[.]worker[.]config[.]epoch|sie[.]worker[.]config[.]degraded|sie[.]worker[.]nats[.]operations|sie[.]worker[.]nats[.]delivery[.]attempts|sie[.]worker[.]result[.]transport[.]attempts|sie[.]worker[.]result[.]chunks[.]published|sie[.]worker[.]result[.]chunk[.]size|sie[.]worker[.]payload[.]fetches|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]payload[.]size|sie[.]worker[.]gpu[.]slots|sie[.]worker[.]pending[.]items|sie[.]worker[.]pending[.]cost|sie[.]worker[.]inflight[.]batches|sie[.]worker[.]saturated|sie[.]worker[.]ipc[.]capacity|sie[.]worker[.]ipc[.]inflight|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]generation[.]model_loading[.]responses|sie[.]worker[.]shutdown[.]drain[.]duration|sie[.]worker[.]work_item[.]age)$")'+ - 'resource.attributes["service.name"] == "sie-worker" and not IsMatch(name, "^(sie[.]worker[.]queue[.]duration|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]batch[.]subgroups|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]units|sie[.]worker[.]model[.]loaded|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]model[.]memory|sie[.]worker[.]oom[.]recoveries|sie[.]worker[.]model[.]evictions|sie[.]worker[.]generation[.]worker_wait|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]inflight|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget|sie[.]worker[.]generation[.]admission[.]decisions|sie[.]worker[.]generation[.]duplicate_prevented|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]generation[.]grammar[.]cache[.]lookups|sie[.]worker[.]generation[.]grammar[.]requests|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]worker[.]runtime[.]forward[.]concurrent|sie[.]worker[.]runtime[.]forward[.]limit)$")'# This is the metric field firewall shared by Prometheus and OTLP# destinations. Every descriptor and point is reduced to the checked-in# contract; resource and instrumentation-scope extensions are discarded.@@ -121,19 +121,21 @@ processors:statements:- set(description, "")- 'set(unit, "{request}") where IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]config[.]requests|sie[.]worker[.]ipc[.]requests|sie[.]worker[.]ipc[.]capacity|sie[.]worker[.]ipc[.]inflight|sie[.]worker[.]generation[.]inflight|sie[.]worker[.]generation[.]duplicate_prevented|sie[.]worker[.]generation[.]grammar[.]requests|sie[.]gateway[.]pending_demand|sie[.]gateway[.]rejected[.]requests)$")'- - 'set(unit, "s") where IsMatch(name, "^(sie[.]gateway[.]request[.]duration|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]dispatcher[.]invocation[.]duration|sie[.]dispatcher[.]sealed[.]stage[.]duration|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds|sie[.]dispatcher[.]sealed[.]cold_start[.]seconds|sie[.]config[.]request[.]duration|sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]shutdown[.]drain[.]duration|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]capacity[.]snapshot[.]timestamp)$")'+ - 'set(unit, "s") where IsMatch(name, "^(sie[.]gateway[.]request[.]duration|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]dispatcher[.]invocation[.]duration|sie[.]dispatcher[.]sealed[.]stage[.]duration|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds|sie[.]dispatcher[.]sealed[.]cold_start[.]seconds|sie[.]config[.]request[.]duration|sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]shutdown[.]drain[.]duration|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]generation[.]worker_wait|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]capacity[.]snapshot[.]timestamp|sie[.]gateway[.]settlement[.]confirm[.]duration|sie[.]worker[.]work_item[.]age)$")'- 'set(unit, "{epoch}") where IsMatch(name, "^(sie[.]gateway[.]config[.]applied_epoch|sie[.]config[.]epoch|sie[.]worker[.]config[.]epoch)$")'- 'set(unit, "{operation}") where IsMatch(name, "^(sie[.]gateway[.]config[.]operations|sie[.]config[.]publish|sie[.]config[.]store[.]writes|sie[.]worker[.]nats[.]operations)$")'- 'set(unit, "1") where IsMatch(name, "^(sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]config[.]messaging[.]ready|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]config[.]degraded|sie[.]worker[.]saturated|sie[.]gateway[.]pool[.]pinned_model[.]loaded)$")'- 'set(unit, "{publish}") where name == "sie.gateway.queue.publishes"'- 'set(unit, "{item}") where IsMatch(name, "^(sie[.]gateway[.]queue[.]publish[.]items|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]pending[.]items|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]gateway[.]lane[.]queue[.]depth)$")'- 'set(unit, "{wait}") where name == "sie.gateway.queue.result_waits"'+ - 'set(unit, "{poll}") where name == "sie.gateway.key_snapshot.polls"'+ - 'set(unit, "{confirm}") where name == "sie.gateway.settlement.confirms"'- 'set(unit, "{chunk}") where IsMatch(name, "^(sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]worker[.]ipc[.]response[.]chunk[.]count|sie[.]worker[.]result[.]chunks[.]published)$")'- 'set(unit, "{transfer}") where IsMatch(name, "^(sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]worker[.]ipc[.]response[.]chunks)$")'- 'set(unit, "{rejection}") where name == "sie.gateway.queue.result_chunk.rejections"'- 'set(unit, "{attempt}") where name == "sie.worker.result.transport.attempts"'- 'set(unit, "By") where IsMatch(name, "^(sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]result[.]chunk[.]size)$")'- - 'set(unit, "{event}") where IsMatch(name, "^(sie[.]gateway[.]queue[.]events|sie[.]gateway[.]generation[.]events)$")'+ - 'set(unit, "{event}") where IsMatch(name, "^(sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]worker_pool[.]events|sie[.]gateway[.]generation[.]events)$")'- 'set(unit, "{response}") where IsMatch(name, "^(sie[.]gateway[.]provisioning[.]responses|sie[.]worker[.]generation[.]model_loading[.]responses)$")'- 'set(unit, "{token}") where IsMatch(name, "^(sie[.]gateway[.]generation[.]tokens|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget)$")'- 'set(unit, "{invocation}") where IsMatch(name, "^(sie[.]dispatcher[.]invocations|sie[.]dispatcher[.]inflight)$")'@@ -152,6 +154,7 @@ processors:- 'set(unit, "{unit}") where name == "sie.worker.units"'- 'set(unit, "{recovery}") where name == "sie.worker.oom.recoveries"'- 'set(unit, "{decision}") where name == "sie.worker.generation.admission.decisions"'+ - 'set(unit, "{decision}") where name == "sie.gateway.queue.lane_admission.decisions"'- 'set(unit, "{lookup}") where name == "sie.worker.generation.grammar.cache.lookups"'- 'set(unit, "{forward}") where IsMatch(name, "^(sie[.]worker[.]runtime[.]forward[.]concurrent|sie[.]worker[.]runtime[.]forward[.]limit)$")'- 'set(unit, "{gpu}") where name == "sie.gateway.active_lease.gpus"'@@ -166,10 +169,13 @@ processors:- 'keep_keys(attributes, []) where IsMatch(metric.name, "^(sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]config[.]epoch|sie[.]gateway[.]capacity[.]snapshot[.]timestamp)$")'- 'keep_keys(attributes, ["transport"]) where IsMatch(metric.name, "^(sie[.]gateway[.]messaging[.]client[.]ready|sie[.]config[.]messaging[.]ready)$")'- 'keep_keys(attributes, ["event", "outcome"]) where metric.name == "sie.gateway.queue.events"'+ - 'keep_keys(attributes, ["pool", "event"]) where metric.name == "sie.gateway.queue.worker_pool.events"'- 'keep_keys(attributes, ["surface", "http.status_code"]) where metric.name == "sie.gateway.provisioning.responses"'- 'keep_keys(attributes, ["event", "reason", "outcome"]) where metric.name == "sie.gateway.generation.events"'- 'keep_keys(attributes, ["operation"]) where IsMatch(metric.name, "^(sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot)$")'- 'keep_keys(attributes, ["operation", "token.kind"]) where metric.name == "sie.gateway.generation.tokens"'+ - 'keep_keys(attributes, ["outcome"]) where IsMatch(metric.name, "^(sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'+ - 'keep_keys(attributes, ["operation", "lane"]) where metric.name == "sie.worker.work_item.age"'- 'keep_keys(attributes, ["operation", "dispatch.path", "outcome", "lane"]) where IsMatch(metric.name, "^(sie[.]dispatcher[.]invocations|sie[.]dispatcher[.]invocation[.]duration)$")'- 'keep_keys(attributes, ["operation", "dispatch.path", "lane"]) where metric.name == "sie.dispatcher.inflight"'- 'keep_keys(attributes, ["outcome"]) where IsMatch(metric.name, "^(sie[.]dispatcher[.]sealed[.]stage|sie[.]dispatcher[.]sealed[.]stage[.]duration)$")'@@ -205,7 +211,7 @@ processors:- 'keep_keys(attributes, ["outcome", "stage", "backend", "lane", "model", "profile"]) where metric.name == "sie.worker.model.load.duration"'- 'keep_keys(attributes, ["strategy", "outcome", "backend", "lane", "model", "profile"]) where metric.name == "sie.worker.oom.recoveries"'- 'keep_keys(attributes, ["reason", "backend", "lane", "model", "profile"]) where metric.name == "sie.worker.model.evictions"'- - 'keep_keys(attributes, ["grammar", "backend", "lane", "model", "profile"]) where IsMatch(metric.name, "^(sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot)$")'+ - 'keep_keys(attributes, ["grammar", "backend", "lane", "model", "profile"]) where IsMatch(metric.name, "^(sie[.]worker[.]generation[.]worker_wait|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot)$")'- 'keep_keys(attributes, ["token.type", "grammar", "backend", "lane", "model", "profile"]) where metric.name == "sie.worker.generation.tokens"'- 'keep_keys(attributes, ["outcome", "reason", "backend", "lane", "model", "profile"]) where metric.name == "sie.worker.generation.admission.decisions"'- 'keep_keys(attributes, ["dispatch.path", "backend", "lane", "model", "profile"]) where metric.name == "sie.worker.generation.duplicate_prevented"'@@ -218,6 +224,7 @@ processors:- 'keep_keys(attributes, ["pool", "model"]) where metric.name == "sie.gateway.pool.pinned_model.loaded"'- 'keep_keys(attributes, ["pool", "machine_profile", "bundle"]) where IsMatch(metric.name, "^(sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor)$")'- 'keep_keys(attributes, ["pool", "machine_profile", "bundle", "reason", "scaling_action"]) where metric.name == "sie.gateway.rejected.requests"'+ - 'keep_keys(attributes, ["pool", "machine_profile", "bundle", "outcome"]) where metric.name == "sie.gateway.queue.lane_admission.decisions"'# Prometheus producer labels are explicit collector output, not copied# from exported_job/exported_instance after scrape-label conflict handling.transform/prometheus_gateway_identity:@@ -274,18 +281,18 @@ processors:error_mode: propagatemetrics:metric:- - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests)$")'+ - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'- 'resource.attributes["service.name"] != "sie-gateway"'filter/remote_application_contract:error_mode: propagatemetrics:metric:- - 'not IsMatch(name, "^(sie[.]dispatcher[.]invocations|sie[.]dispatcher[.]invocation[.]duration|sie[.]dispatcher[.]inflight|sie[.]dispatcher[.]sealed[.]stage|sie[.]dispatcher[.]sealed[.]stage[.]duration|sie[.]dispatcher[.]sealed[.]resident|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds|sie[.]dispatcher[.]sealed[.]cold_start[.]seconds|sie[.]config[.]requests|sie[.]config[.]request[.]duration|sie[.]config[.]epoch|sie[.]config[.]models|sie[.]config[.]publish|sie[.]config[.]store[.]writes|sie[.]config[.]messaging[.]ready|sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]ipc[.]requests|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]ipc[.]response[.]chunks|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]count|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]config[.]applies|sie[.]worker[.]config[.]epoch|sie[.]worker[.]config[.]degraded|sie[.]worker[.]nats[.]operations|sie[.]worker[.]nats[.]delivery[.]attempts|sie[.]worker[.]result[.]transport[.]attempts|sie[.]worker[.]result[.]chunks[.]published|sie[.]worker[.]result[.]chunk[.]size|sie[.]worker[.]payload[.]fetches|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]payload[.]size|sie[.]worker[.]gpu[.]slots|sie[.]worker[.]pending[.]items|sie[.]worker[.]pending[.]cost|sie[.]worker[.]inflight[.]batches|sie[.]worker[.]saturated|sie[.]worker[.]ipc[.]capacity|sie[.]worker[.]ipc[.]inflight|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]generation[.]model_loading[.]responses|sie[.]worker[.]shutdown[.]drain[.]duration|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]batch[.]subgroups|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]units|sie[.]worker[.]model[.]loaded|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]model[.]memory|sie[.]worker[.]oom[.]recoveries|sie[.]worker[.]model[.]evictions|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]inflight|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget|sie[.]worker[.]generation[.]admission[.]decisions|sie[.]worker[.]generation[.]duplicate_prevented|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]generation[.]grammar[.]cache[.]lookups|sie[.]worker[.]generation[.]grammar[.]requests|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]worker[.]runtime[.]forward[.]concurrent|sie[.]worker[.]runtime[.]forward[.]limit)$")'+ - 'not IsMatch(name, "^(sie[.]dispatcher[.]invocations|sie[.]dispatcher[.]invocation[.]duration|sie[.]dispatcher[.]inflight|sie[.]dispatcher[.]sealed[.]stage|sie[.]dispatcher[.]sealed[.]stage[.]duration|sie[.]dispatcher[.]sealed[.]resident|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds|sie[.]dispatcher[.]sealed[.]cold_start[.]seconds|sie[.]config[.]requests|sie[.]config[.]request[.]duration|sie[.]config[.]epoch|sie[.]config[.]models|sie[.]config[.]publish|sie[.]config[.]store[.]writes|sie[.]config[.]messaging[.]ready|sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]ipc[.]requests|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]ipc[.]response[.]chunks|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]count|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]config[.]applies|sie[.]worker[.]config[.]epoch|sie[.]worker[.]config[.]degraded|sie[.]worker[.]nats[.]operations|sie[.]worker[.]nats[.]delivery[.]attempts|sie[.]worker[.]result[.]transport[.]attempts|sie[.]worker[.]result[.]chunks[.]published|sie[.]worker[.]result[.]chunk[.]size|sie[.]worker[.]payload[.]fetches|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]payload[.]size|sie[.]worker[.]gpu[.]slots|sie[.]worker[.]pending[.]items|sie[.]worker[.]pending[.]cost|sie[.]worker[.]inflight[.]batches|sie[.]worker[.]saturated|sie[.]worker[.]ipc[.]capacity|sie[.]worker[.]ipc[.]inflight|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]generation[.]model_loading[.]responses|sie[.]worker[.]shutdown[.]drain[.]duration|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]batch[.]subgroups|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]units|sie[.]worker[.]model[.]loaded|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]model[.]memory|sie[.]worker[.]oom[.]recoveries|sie[.]worker[.]model[.]evictions|sie[.]worker[.]generation[.]worker_wait|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]inflight|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget|sie[.]worker[.]generation[.]admission[.]decisions|sie[.]worker[.]generation[.]duplicate_prevented|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]generation[.]grammar[.]cache[.]lookups|sie[.]worker[.]generation[.]grammar[.]requests|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]worker[.]runtime[.]forward[.]concurrent|sie[.]worker[.]runtime[.]forward[.]limit|sie[.]worker[.]work_item[.]age)$")'- 'resource.attributes["service.name"] != "sie-config" and resource.attributes["service.name"] != "sie-dispatcher" and resource.attributes["service.name"] != "sie-worker" and resource.attributes["service.name"] != "sie-worker-sidecar"'- 'resource.attributes["service.name"] == "sie-dispatcher" and not IsMatch(name, "^(sie[.]dispatcher[.]invocations|sie[.]dispatcher[.]invocation[.]duration|sie[.]dispatcher[.]inflight|sie[.]dispatcher[.]sealed[.]stage|sie[.]dispatcher[.]sealed[.]stage[.]duration|sie[.]dispatcher[.]sealed[.]resident|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds|sie[.]dispatcher[.]sealed[.]cold_start[.]seconds)$")'- 'resource.attributes["service.name"] == "sie-config" and not IsMatch(name, "^(sie[.]config[.]requests|sie[.]config[.]request[.]duration|sie[.]config[.]epoch|sie[.]config[.]models|sie[.]config[.]publish|sie[.]config[.]store[.]writes|sie[.]config[.]messaging[.]ready)$")'- - 'resource.attributes["service.name"] == "sie-worker-sidecar" and not IsMatch(name, "^(sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]ipc[.]requests|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]ipc[.]response[.]chunks|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]count|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]config[.]applies|sie[.]worker[.]config[.]epoch|sie[.]worker[.]config[.]degraded|sie[.]worker[.]nats[.]operations|sie[.]worker[.]nats[.]delivery[.]attempts|sie[.]worker[.]result[.]transport[.]attempts|sie[.]worker[.]result[.]chunks[.]published|sie[.]worker[.]result[.]chunk[.]size|sie[.]worker[.]payload[.]fetches|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]payload[.]size|sie[.]worker[.]gpu[.]slots|sie[.]worker[.]pending[.]items|sie[.]worker[.]pending[.]cost|sie[.]worker[.]inflight[.]batches|sie[.]worker[.]saturated|sie[.]worker[.]ipc[.]capacity|sie[.]worker[.]ipc[.]inflight|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]generation[.]model_loading[.]responses|sie[.]worker[.]shutdown[.]drain[.]duration)$")'- - 'resource.attributes["service.name"] == "sie-worker" and not IsMatch(name, "^(sie[.]worker[.]queue[.]duration|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]batch[.]subgroups|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]units|sie[.]worker[.]model[.]loaded|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]model[.]memory|sie[.]worker[.]oom[.]recoveries|sie[.]worker[.]model[.]evictions|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]inflight|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget|sie[.]worker[.]generation[.]admission[.]decisions|sie[.]worker[.]generation[.]duplicate_prevented|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]generation[.]grammar[.]cache[.]lookups|sie[.]worker[.]generation[.]grammar[.]requests|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]worker[.]runtime[.]forward[.]concurrent|sie[.]worker[.]runtime[.]forward[.]limit)$")'+ - 'resource.attributes["service.name"] == "sie-worker-sidecar" and not IsMatch(name, "^(sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]ipc[.]requests|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]ipc[.]response[.]chunks|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]count|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]config[.]applies|sie[.]worker[.]config[.]epoch|sie[.]worker[.]config[.]degraded|sie[.]worker[.]nats[.]operations|sie[.]worker[.]nats[.]delivery[.]attempts|sie[.]worker[.]result[.]transport[.]attempts|sie[.]worker[.]result[.]chunks[.]published|sie[.]worker[.]result[.]chunk[.]size|sie[.]worker[.]payload[.]fetches|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]payload[.]size|sie[.]worker[.]gpu[.]slots|sie[.]worker[.]pending[.]items|sie[.]worker[.]pending[.]cost|sie[.]worker[.]inflight[.]batches|sie[.]worker[.]saturated|sie[.]worker[.]ipc[.]capacity|sie[.]worker[.]ipc[.]inflight|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]generation[.]model_loading[.]responses|sie[.]worker[.]shutdown[.]drain[.]duration|sie[.]worker[.]work_item[.]age)$")'+ - 'resource.attributes["service.name"] == "sie-worker" and not IsMatch(name, "^(sie[.]worker[.]queue[.]duration|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]batch[.]cost|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]cost|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]scheduler[.]starvation[.]resets|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]batch[.]subgroups|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]units|sie[.]worker[.]model[.]loaded|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]model[.]memory|sie[.]worker[.]oom[.]recoveries|sie[.]worker[.]model[.]evictions|sie[.]worker[.]generation[.]worker_wait|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]inflight|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget|sie[.]worker[.]generation[.]admission[.]decisions|sie[.]worker[.]generation[.]duplicate_prevented|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]generation[.]grammar[.]cache[.]lookups|sie[.]worker[.]generation[.]grammar[.]requests|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]worker[.]runtime[.]forward[.]concurrent|sie[.]worker[.]runtime[.]forward[.]limit)$")'{{- end }}{{- if $betterStack.enabled }}# Collector implementation health is isolated from the applicationdiff --git a/deploy/helm/sie-cluster/templates/config-deployment.yaml b/deploy/helm/sie-cluster/templates/config-deployment.yamlindex e2ac4f7ac..01d1ba527 100644--- a/deploy/helm/sie-cluster/templates/config-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/config-deployment.yaml@@ -58,6 +58,10 @@ spec:checksum/otel-resource: {{ include "sie-cluster.otel.resourceChecksum" . | quote }}spec:{{- include "sie-cluster.imagePullSecrets" . | nindent 6 }}+ {{- with .Values.config.podSecurityContext }}+ securityContext:+ {{- toYaml . | nindent 8 }}+ {{- end }}serviceAccountName: {{ include "sie-cluster.serviceAccountName" . }}containers:- name: configdiff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex 0d1e45b81..b883c1509 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -10,7 +10,14 @@{{- end }}{{- /* Telemetry identity and routing are control-plane-owned. Becausegateway.extraEnv is rendered after the canonical block, reject duplicate- names instead of relying on Kubernetes's last-entry-wins behavior. */}}+ names instead of relying on Kubernetes's last-entry-wins behavior.++ The SIE_STREAM_* trio is reserved for a second reason beyond+ chart-ownership: the gateway and the worker sidecars both create the+ work streams and whoever gets there first wins, so the chart renders one+ value onto both. An extraEnv override would move only the gateway and+ silently reintroduce exactly the divergence the render guards below+ exist to prevent. Fail the render instead. */}}{{- $reservedGatewayEnv := concat(include "sie-cluster.otel.reservedEnvNames" . | fromJsonArray)(list@@ -19,7 +26,10 @@"SIE_GATEWAY_GPU_ALIASES""SIE_GATEWAY_HEALTH_MODE""SIE_GATEWAY_MACHINE_PROFILES"- "SIE_GATEWAY_STATIC_QUEUE_POOLS") -}}+ "SIE_GATEWAY_STATIC_QUEUE_POOLS"+ "SIE_STREAM_MAX_AGE_S"+ "SIE_STREAM_REPLICAS"+ "SIE_STREAM_STORAGE") -}}{{- include "sie-cluster.env.assertNoReserved" (dict "path" "gateway.extraEnv" "entries" .Values.gateway.extraEnv "reserved" $reservedGatewayEnv) -}}{{- range $annotation := list "checksum/gpu-config" "checksum/otel-resource" -}}{{- if hasKey $.Values.gateway.podAnnotations $annotation -}}@@ -52,6 +62,33 @@{{- if not .Values.nats.config.jetstream.enabled }}{{- fail "clusterRouting=queue requires nats.config.jetstream.enabled=true" }}{{- end }}+{{- /* Validate: work-queue durability. `queueRouting.streamStorage` is+ rendered into SIE_STREAM_STORAGE on both the gateway and the worker+ sidecars, so the two stream creators always agree — but the broker has+ to be able to honor it. File-backed streams need the NATS sub-chart's+ JetStream fileStore (a PVC per pod), and replicated streams need a NATS+ cluster with at least that many members. Catching the mismatch here beats+ discovering it as a stream-create failure that manifests as a 503 on the+ inference path. See the chart README's "Work-queue durability" section. */}}+{{- $streamStorage := lower (default "memory" .Values.queueRouting.streamStorage) }}+{{- if not (has $streamStorage (list "memory" "file")) }}+ {{- fail (printf "queueRouting.streamStorage=%q is not supported; use \"memory\" (default) or \"file\"." $streamStorage) }}+{{- end }}+{{- if and (eq $streamStorage "file") (not .Values.nats.config.jetstream.fileStore.enabled) }}+ {{- fail "queueRouting.streamStorage=file requires nats.config.jetstream.fileStore.enabled=true (the broker needs a JetStream file store to persist the streams)" }}+{{- end }}+{{- $streamReplicas := int (default 1 .Values.queueRouting.streamReplicas) }}+{{- if lt $streamReplicas 1 }}+ {{- fail (printf "queueRouting.streamReplicas=%d is invalid; JetStream requires at least 1." $streamReplicas) }}+{{- end }}+{{- if gt $streamReplicas 1 }}+ {{- if not .Values.nats.config.cluster.enabled }}+ {{- fail (printf "queueRouting.streamReplicas=%d requires nats.config.cluster.enabled=true (a single NATS server has no peers to replicate to, and will NOT reject the request — it reports the replica count it was asked for, so this must be caught here)" $streamReplicas) }}+ {{- end }}+ {{- if gt $streamReplicas (int .Values.nats.config.cluster.replicas) }}+ {{- fail (printf "queueRouting.streamReplicas=%d exceeds nats.config.cluster.replicas=%d" $streamReplicas (int .Values.nats.config.cluster.replicas)) }}+ {{- end }}+{{- end }}{{- /* Resolve the effective payload-store URL once (helper applies theauto-derivation: explicit url > clusterCache.url + /payloads > empty).The chart treats a non-empty resolved URL as "payload store enabled"@@ -66,8 +103,8 @@{{- fail "payloadStore.enabled=true but no payload-store URL resolved. Work items >1MB will fail without it. Set payloadStore.url to the terraform `payload_store_url` output (or workers.common.clusterCache.url for the shared bucket), or set payloadStore.enabled=false to disable. See deploy/helm/sie-cluster/README.md" }}{{- end }}{{- if $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) }}+ {{- if not (or (hasPrefix "s3://" $payloadStoreUrl) (hasPrefix "gs://" $payloadStoreUrl) (hasPrefix "abfs://" $payloadStoreUrl) (hasPrefix "abfss://" $payloadStoreUrl) (hasPrefix "oss://" $payloadStoreUrl)) }}+ {{- fail (printf "payloadStore.url must be an object-store URL (s3://bucket/prefix, gs://bucket/prefix, abfs(s)://[email protected]/prefix, or oss://bucket/prefix), not a local path; got %q" $payloadStoreUrl) }}{{- end }}{{- end }}apiVersion: apps/v1@@ -108,6 +145,9 @@ spec:spec:{{- include "sie-cluster.imagePullSecrets" . | nindent 6 }}serviceAccountName: {{ include "sie-cluster.serviceAccountName" . }}+ # Derived from gateway.drain (preStop sleep + in-flight budget + the+ # gateway's own 5s queue drain); see the helper for the arithmetic.+ terminationGracePeriodSeconds: {{ include "sie-cluster.gateway.terminationGracePeriodSeconds" . }}{{- if and .Values.config.enabled .Values.gateway.waitForConfig.enabled }}# Gate the gateway on sie-config readiness before its cold-start# bootstrap fires. Without this, during a rolling chart upgrade the@@ -246,6 +286,14 @@ spec:{{- with .Values.queueRouting }}- name: SIE_STREAM_MAX_AGE_Svalue: {{ .streamMaxAgeSec | default 1800 | quote }}+ # Work-queue durability. Rendered identically onto the worker+ # sidecars: whoever creates the stream first wins, so gateway and+ # workers must agree. Defaults are memory-backed / single-replica,+ # i.e. unchanged from before these knobs existed.+ - name: SIE_STREAM_STORAGE+ value: {{ $streamStorage | quote }}+ - name: SIE_STREAM_REPLICAS+ value: {{ $streamReplicas | quote }}{{- with .staticQueuePools }}- name: SIE_GATEWAY_STATIC_QUEUE_POOLSvalue: {{ toJson . | quote }}@@ -301,6 +349,25 @@ spec:# Operator-supplied env passthrough (parity with workers.common.extraEnv).{{- toYaml . | nindent 12 }}{{- end }}+ {{- $preStopSleepS := int (include "sie-cluster.gateway.preStopSleepSeconds" .) }}+ {{- if gt $preStopSleepS 0 }}+ lifecycle:+ preStop:+ # Hold the pod open after it leaves the EndpointSlice so+ # kube-proxy/ingress stop sending it new requests BEFORE the+ # process is signalled. Without it every rolling deploy, node+ # drain and KEDA scale-in cuts live connections (SSE generation+ # streams, queued-result waits) at SIGTERM.+ #+ # The native sleep action is used because the gateway image is+ # distroless (packages/sie_gateway/Dockerfile) and has no shell+ # or `sleep` binary for an exec hook like the worker's. Needs+ # Kubernetes >= 1.30 (PodLifecycleSleepAction, beta and on by+ # default there, GA in 1.33); an older API server drops the+ # field, which loses the delay but breaks nothing.+ sleep:+ seconds: {{ $preStopSleepS }}+ {{- end }}startupProbe:httpGet:path: /healthz@@ -380,6 +447,20 @@ spec:{{- with .Values.gateway.affinity }}affinity:{{- toYaml . | nindent 8 }}+ {{- else }}+ affinity:+ # Prefer spreading gateway replicas across nodes, mirroring the worker+ # StatefulSet. Without it two replicas can co-schedule and a single+ # node drain takes the whole edge out at once. Preferred (not+ # required) so single-node dev clusters still schedule every replica.+ podAntiAffinity:+ preferredDuringSchedulingIgnoredDuringExecution:+ - weight: 100+ podAffinityTerm:+ labelSelector:+ matchLabels:+ {{- include "sie-cluster.gateway.selectorLabels" . | nindent 20 }}+ topologyKey: kubernetes.io/hostname{{- end }}{{- with .Values.gateway.tolerations }}tolerations:diff --git a/deploy/helm/sie-cluster/templates/gateway-pdb.yaml b/deploy/helm/sie-cluster/templates/gateway-pdb.yamlnew file mode 100644index 000000000..74b96d66b--- /dev/null+++ b/deploy/helm/sie-cluster/templates/gateway-pdb.yaml@@ -0,0 +1,29 @@+{{- /* Voluntary disruptions (node drain, cluster upgrade, descheduler) have+ nothing stopping them from evicting every gateway pod at once, which+ takes the whole inference gateway down together with the in-flight NATS+ `_INBOX` result subscriptions those pods own.++ Rendered only when the tier is guaranteed to have a spare pod. At+ gateway.replicas=1 a maxUnavailable=1 PDB is worse than no PDB: as soon+ as the single pod is unhealthy `disruptionsAllowed` drops to 0 and the+ budget blocks the very drain that would reschedule it. Operators can+ force the decision either way with gateway.podDisruptionBudget.enabled. */ -}}+{{- $pdb := default (dict) .Values.gateway.podDisruptionBudget -}}+{{- $enabled := gt (int .Values.gateway.replicas) 1 -}}+{{- if and (hasKey $pdb "enabled") (kindIs "bool" $pdb.enabled) -}}+{{- $enabled = $pdb.enabled -}}+{{- end -}}+{{- if $enabled }}+apiVersion: policy/v1+kind: PodDisruptionBudget+metadata:+ name: {{ include "sie-cluster.gateway.serviceName" . }}+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.gateway.labels" . | nindent 4 }}+spec:+ maxUnavailable: {{ dig "maxUnavailable" 1 $pdb }}+ selector:+ matchLabels:+ {{- include "sie-cluster.gateway.selectorLabels" . | nindent 6 }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/hooks/keda-ready-test.yaml b/deploy/helm/sie-cluster/templates/hooks/keda-ready-test.yamlindex 511f33afa..ed49b106d 100644--- a/deploy/helm/sie-cluster/templates/hooks/keda-ready-test.yaml+++ b/deploy/helm/sie-cluster/templates/hooks/keda-ready-test.yaml@@ -1,10 +1,12 @@{{- if .Values.autoscaling.enabled }}{{- $expectedScaledObjects := 1 -}}+{{- $expectedExternalMetrics := 1 -}}{{- range $pool := .Values.workers.pools -}}{{- if $pool.enabled -}}{{- range $bundleCfg := $pool.bundles -}}{{- if dig "enabled" true $bundleCfg -}}{{- $expectedScaledObjects = add1 $expectedScaledObjects -}}+{{- $expectedExternalMetrics = add $expectedExternalMetrics 5 -}}{{- end -}}{{- end -}}{{- end -}}@@ -13,8 +15,12 @@{{- $maxPollingInterval := max 30 $workerPollingInterval -}}{{- $failureThreshold := 3 -}}{{- $validationWindow := mul $maxPollingInterval $failureThreshold -}}-{{- $checkInterval := min 30 (max 5 $workerPollingInterval) -}}-{{- $timeout := add $validationWindow 180 -}}+{{- $probeConcurrency := 16 -}}+{{- $probeRequestTimeout := 5 -}}+{{- $probeBatches := div (add $expectedScaledObjects (sub $probeConcurrency 1)) $probeConcurrency -}}+{{- $probeRoundBudget := mul $probeBatches (mul 5 $probeRequestTimeout) -}}+{{- $probeBudget := mul $probeRoundBudget $failureThreshold -}}+{{- $timeout := add (add $validationWindow $probeBudget) 180 -}}{{- $activeDeadline := add $timeout 60 -}}# RBAC must be at a lower weight than the Job so it is fully propagated before the pod starts.apiVersion: v1@@ -49,6 +55,14 @@ rules:- apiGroups: ["autoscaling"]resources: ["horizontalpodautoscalers"]verbs: ["get", "list"]+ # Query each exact KEDA-generated external metric so scale-to-zero targets+ # populate trigger health even while the HPA is disabled at zero. The+ # aggregated API authorizes an exact-metric response as a namespaced list on+ # its wildcard resource; strict path/catalog validation below narrows use to+ # the five chart-owned metric names.+ - apiGroups: ["external.metrics.k8s.io"]+ resources: ["*"]+ verbs: ["list"]---apiVersion: rbac.authorization.k8s.io/v1kind: RoleBinding@@ -104,18 +118,24 @@ spec:command: ["/bin/sh", "-c"]args:- |- set -e+ set -euNAMESPACE="{{ include "sie-cluster.namespace" . }}"{{- include "sie-cluster.kubernetes.inClusterKubeconfig" . | nindent 14 }}EXPECTED_COUNT={{ $expectedScaledObjects }}+ EXPECTED_METRIC_COUNT={{ $expectedExternalMetrics }}SCALEDOBJECT_SELECTOR='app.kubernetes.io/instance={{ .Release.Name }},app.kubernetes.io/part-of=sie,app.kubernetes.io/managed-by=Helm,sie.superlinked.com/scaler-managed=true,sie.superlinked.com/scaler-revision={{ .Release.Revision }},sie.superlinked.com/helm-namespace={{ .Release.Namespace }}'HPA_SELECTOR='app.kubernetes.io/instance={{ .Release.Name }},app.kubernetes.io/part-of=sie,app.kubernetes.io/managed-by=Helm,sie.superlinked.com/scaler-managed=true,sie.superlinked.com/helm-namespace={{ .Release.Namespace }}'FAILURE_THRESHOLD={{ $failureThreshold }}VALIDATION_WINDOW={{ $validationWindow }}TIMEOUT={{ $timeout }}- INTERVAL={{ $checkInterval }}+ INTERVAL={{ $maxPollingInterval }}+ PROBE_CONCURRENCY={{ $probeConcurrency }}+ PROBE_REQUEST_TIMEOUT={{ $probeRequestTimeout }}+ EXTERNAL_METRIC_MAX_BYTES=65536SCALEDOBJECTS_FILE=/tmp/keda-scaledobjects.jsonHPAS_FILE=/tmp/keda-hpas.json+ EXTERNAL_METRICS_FILE=/tmp/keda-external-metrics.tsv+ EXTERNAL_METRIC_DIR=/tmp/keda-external-metric-responsesecho "=== ScaledObject Health Test ==="# Ordinary kubectl resource reads use the projected in-cluster@@ -196,50 +216,169 @@ spec:'}- elapsed=0- echo "Waiting ${VALIDATION_WINDOW}s (failureThreshold=${FAILURE_THRESHOLD}, max polling interval={{ $maxPollingInterval }}s) before accepting KEDA status"- while [ "$elapsed" -lt "$VALIDATION_WINDOW" ]; do- remaining=$((VALIDATION_WINDOW - elapsed))- delay=$INTERVAL- if [ "$delay" -gt "$remaining" ]; then- delay=$remaining+ # Kubernetes HPA deliberately stops requesting external metrics+ # while a scale target is at zero. Query every exact KEDA metric+ # through the aggregated API so the adapter evaluates each+ # trigger and KEDA can publish the otherwise-empty health map.+ prime_external_metrics() {+ if ! jq -e --arg namespace "$NAMESPACE" \+ --argjson expected_count "$EXPECTED_COUNT" \+ --argjson expected_metrics "$EXPECTED_METRIC_COUNT" '+ def dns_label:+ type == "string" and length >= 1 and length <= 63 and+ test("^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$");+ ($namespace | dns_label) and+ (.items | type == "array" and length == $expected_count) and+ ([.items[].spec.triggers[]] | length == $expected_metrics) and+ all(.items[];+ (.metadata.name | dns_label) and+ (.spec.triggers | type == "array" and length >= 1 and length <= 5) and+ all(.spec.triggers | to_entries[];+ .key >= 0 and .key <= 4 and .value.type == "prometheus"+ )+ )+ ' "$SCALEDOBJECTS_FILE" >/dev/null; then+ echo "KEDA external metric catalog failed validation" >&2+ return 1+ fi+ if ! jq -r '+ .items | to_entries[] |+ .key as $object_index |+ .value.metadata.name as $scaledobject |+ .value.spec.triggers | to_entries[] |+ [$object_index, $scaledobject, "s\(.key)-\(.value.type)"] | @tsv+ ' "$SCALEDOBJECTS_FILE" > "$EXTERNAL_METRICS_FILE"; then+ echo "KEDA external metric catalog could not be generated" >&2+ return 1+ fi+ if ! metric_count=$(wc -l < "$EXTERNAL_METRICS_FILE" | tr -d ' '); then+ echo "KEDA external metric catalog could not be counted" >&2+ return 1+ fi+ if [ "$metric_count" -ne "$EXPECTED_METRIC_COUNT" ]; then+ echo "KEDA external metric catalog count mismatch" >&2+ return 1+ fi+ if ! mkdir -p "$EXTERNAL_METRIC_DIR"; then+ echo "KEDA external metric response directory could not be created" >&2+ return 1fi- sleep "$delay"- elapsed=$((elapsed + delay))- done+ probe_batch=0+ probe_pids=""+ probe_failed=0+ probe_object_index=0+ while [ "$probe_object_index" -lt "$EXPECTED_COUNT" ]; do+ current_object_index=$probe_object_index+ (+ object_metric_index=0+ while IFS="$(printf '\t')" read -r catalog_object_index scaledobject metric; do+ if [ "$catalog_object_index" -ne "$current_object_index" ]; then+ continue+ fi+ object_metric_index=$((object_metric_index + 1))+ response_file="${EXTERNAL_METRIC_DIR}/${current_object_index}-${object_metric_index}.json"+ if ! encoded_namespace=$(jq -rn --arg value "$NAMESPACE" '$value | @uri'); then+ exit 1+ fi+ if ! encoded_metric=$(jq -rn --arg value "$metric" '$value | @uri'); then+ exit 1+ fi+ if ! encoded_selector=$(jq -rn --arg value "scaledobject.keda.sh/name=$scaledobject" '$value | @uri'); then+ exit 1+ fi+ metric_path="/apis/external.metrics.k8s.io/v1beta1/namespaces/${encoded_namespace}/${encoded_metric}?labelSelector=${encoded_selector}"+ if ! kubectl get --request-timeout="${PROBE_REQUEST_TIMEOUT}s" --raw "$metric_path" 2>/dev/null \+ | head -c $((EXTERNAL_METRIC_MAX_BYTES + 1)) > "$response_file"; then+ exit 1+ fi+ if ! response_bytes=$(wc -c < "$response_file" | tr -d ' '); then+ exit 1+ fi+ if [ "$response_bytes" -gt "$EXTERNAL_METRIC_MAX_BYTES" ]; then+ exit 1+ fi+ if ! jq -e --arg metric "$metric" '+ type == "object" and+ .apiVersion == "external.metrics.k8s.io/v1beta1" and+ .kind == "ExternalMetricValueList" and+ (.items | type == "array" and length == 1) and+ (.items[0] | type == "object") and+ .items[0].metricName == $metric and+ ((.items[0].metricLabels == null) or (.items[0].metricLabels | type == "object")) and+ (.items[0].timestamp | type == "string" and length >= 1 and length <= 64) and+ (.items[0].value | type == "string" and length >= 1 and length <= 64)+ ' "$response_file" >/dev/null; then+ exit 1+ fi+ done < "$EXTERNAL_METRICS_FILE"+ if [ "$object_metric_index" -lt 1 ] || [ "$object_metric_index" -gt 5 ]; then+ exit 1+ fi+ ) &+ probe_pids="$probe_pids $!"+ probe_batch=$((probe_batch + 1))+ probe_object_index=$((probe_object_index + 1))+ if [ "$probe_batch" -ge "$PROBE_CONCURRENCY" ]; then+ for probe_pid in $probe_pids; do+ if ! wait "$probe_pid"; then+ probe_failed=1+ fi+ done+ if [ "$probe_failed" -ne 0 ]; then+ echo "KEDA external metric query batch failed" >&2+ return 1+ fi+ probe_batch=0+ probe_pids=""+ fi+ done+ for probe_pid in $probe_pids; do+ if ! wait "$probe_pid"; then+ probe_failed=1+ fi+ done+ if [ "$probe_failed" -ne 0 ] || [ "$probe_object_index" -ne "$EXPECTED_COUNT" ]; then+ echo "KEDA external metric query round failed" >&2+ return 1+ fi+ }++ elapsed=0+ consecutive_successes=0+ echo "Requiring ${FAILURE_THRESHOLD} complete healthy rounds across ${VALIDATION_WINDOW}s"while [ $elapsed -lt $TIMEOUT ]; do- if ! summary=$(k8s_summary); then- echo "Waiting for the release ScaledObject API... (${elapsed}s/${TIMEOUT}s)"- sleep $INTERVAL- elapsed=$((elapsed + INTERVAL))- continue+ sleep "$INTERVAL"+ elapsed=$((elapsed + INTERVAL))+ round_healthy=false+ if summary=$(k8s_summary) \+ && printf '%s' "$summary" | jq -e --argjson expected "$EXPECTED_COUNT" '+ .count == $expected and .hpa_count == $expected+ ' >/dev/null \+ && prime_external_metrics \+ && summary=$(k8s_summary) \+ && printf '%s' "$summary" | jq -e --argjson expected "$EXPECTED_COUNT" '+ .count == $expected and+ .hpa_count == $expected and+ .ready == $expected and+ .status_reconciled == $expected and+ .healthy == $expected and+ .fallback == 0 and+ .hpa_set_reconciled == true+ ' >/dev/null; then+ round_healthy=truefi- count=$(printf '%s' "$summary" | jq -r '.count')- hpa_count=$(printf '%s' "$summary" | jq -r '.hpa_count')- ready_count=$(printf '%s' "$summary" | jq -r '.ready')- fallback_count=$(printf '%s' "$summary" | jq -r '.fallback')- status_reconciled_count=$(printf '%s' "$summary" | jq -r '.status_reconciled')- healthy_count=$(printf '%s' "$summary" | jq -r '.healthy')- hpa_set_reconciled=$(printf '%s' "$summary" | jq -r '.hpa_set_reconciled')- if [ "$count" -ne "$EXPECTED_COUNT" ] || [ "$hpa_count" -ne "$EXPECTED_COUNT" ]; then- echo "Waiting for release autoscalers: ScaledObjects=$count HPAs=$hpa_count expected=$EXPECTED_COUNT (${elapsed}s/${TIMEOUT}s)"- sleep $INTERVAL- elapsed=$((elapsed + INTERVAL))- continue+ if [ "$round_healthy" = "true" ]; then+ consecutive_successes=$((consecutive_successes + 1))+ else+ consecutive_successes=0fi- if [ "$ready_count" -eq "$EXPECTED_COUNT" ] \- && [ "$status_reconciled_count" -eq "$EXPECTED_COUNT" ] \- && [ "$healthy_count" -eq "$EXPECTED_COUNT" ] \- && [ "$fallback_count" -eq "0" ] \- && [ "$hpa_set_reconciled" = "true" ]; then- echo "SUCCESS: All $EXPECTED_COUNT release ScaledObjects and controller-reconciled HPAs are current with trigger health Happy"+ if [ "$consecutive_successes" -ge "$FAILURE_THRESHOLD" ] \+ && [ "$elapsed" -ge "$VALIDATION_WINDOW" ]; then+ echo "SUCCESS: All $EXPECTED_COUNT release ScaledObjects passed $consecutive_successes complete external-metric health rounds"exit 0fi- echo "Waiting for KEDA reconciliation: ready=$ready_count/$EXPECTED_COUNT status=$status_reconciled_count/$EXPECTED_COUNT healthy=$healthy_count/$EXPECTED_COUNT fallback=$fallback_count HPA-set-current=$hpa_set_reconciled (${elapsed}s/${TIMEOUT}s)"- echo "Status sample: $summary"- sleep $INTERVAL- elapsed=$((elapsed + INTERVAL))+ echo "Waiting for consecutive KEDA health: rounds=$consecutive_successes/$FAILURE_THRESHOLD elapsed=${elapsed}s/${TIMEOUT}s"doneecho "FAILED: ScaledObjects and controller-reconciled HPAs did not become current, Ready, and trigger-healthy after a complete KEDA failure window"exit 1diff --git a/deploy/helm/sie-cluster/templates/ingress.yaml b/deploy/helm/sie-cluster/templates/ingress.yamlindex d767b12b0..4063f8a95 100644--- a/deploy/helm/sie-cluster/templates/ingress.yaml+++ b/deploy/helm/sie-cluster/templates/ingress.yaml@@ -11,11 +11,15 @@ metadata:{{- $annotations := dict }}{{- /* nginx default annotations */ -}}{{- /* - proxy-body-size: images can be large (base64 encoded) */ -}}- {{- /* - proxy-read/send-timeout: model loading can take 5+ minutes for large models */ -}}+ {{- /* - proxy-read/send-timeout: a cold model load emits no bytes for minutes, and+ the read timeout governs that no-first-byte window. Derived from+ workers.common.modelReadyTimeoutSec so the edge cannot 504 a request that is+ still inside the cluster's own load budget. */ -}}+ {{- $proxyTimeoutS := include "sie-cluster.ingress.proxyTimeoutSeconds" . }}{{- $nginxDefaults := dict"nginx.ingress.kubernetes.io/proxy-body-size" "100m"- "nginx.ingress.kubernetes.io/proxy-read-timeout" "600"- "nginx.ingress.kubernetes.io/proxy-send-timeout" "600"+ "nginx.ingress.kubernetes.io/proxy-read-timeout" $proxyTimeoutS+ "nginx.ingress.kubernetes.io/proxy-send-timeout" $proxyTimeoutS}}{{- $annotations = merge $annotations $nginxDefaults }}{{- if .Values.ingress.annotations }}diff --git a/deploy/helm/sie-cluster/templates/keda-lifecycle.yaml b/deploy/helm/sie-cluster/templates/keda-lifecycle.yamlindex c8864008a..0aee8087e 100644--- a/deploy/helm/sie-cluster/templates/keda-lifecycle.yaml+++ b/deploy/helm/sie-cluster/templates/keda-lifecycle.yaml@@ -99,18 +99,19 @@ spec:# exact selector solely so a direct disable upgrade does not# leave the old HPA control path active.LEGACY_SELECTOR='app.kubernetes.io/name={{ include "sie-cluster.name" . }},app.kubernetes.io/instance={{ .Release.Name }},app.kubernetes.io/part-of=sie,app.kubernetes.io/managed-by=Helm,app.kubernetes.io/component in (worker,gateway),helm.sh/chart=sie-cluster-0.6.20,app.kubernetes.io/version=v0.6.20,!sie.superlinked.com/scaler-managed'- if ! resources="$(kubectl api-resources --api-group=keda.sh 2>/dev/null)"; then- echo "FAILED: Kubernetes API discovery failed before KEDA cleanup" >&2- exit 1- fi- if ! printf '%s\n' "$resources" | grep -q '^scaledobjects'; then+ api_error=""+ if ! api_error="$(kubectl get --raw /apis/keda.sh/v1alpha1 2>&1 >/dev/null)"; then+ if ! printf '%s\n' "$api_error" | grep -Eq 'Error from server \(NotFound\):|the server could not find the requested resource'; then+ echo "FAILED: Kubernetes API discovery failed before KEDA cleanup" >&2+ exit 1+ fiecho "KEDA API is absent; nothing to clean"exit 0fifor selector in "$MANAGED_SELECTOR" "$LEGACY_SELECTOR"; do- kubectl delete scaledobjects -n "$NAMESPACE" -l "$selector" \+ kubectl delete scaledobjects.keda.sh -n "$NAMESPACE" -l "$selector" \--ignore-not-found --wait=true- if [ -n "$(kubectl get scaledobjects -n "$NAMESPACE" -l "$selector" -o name)" ]; then+ if [ -n "$(kubectl get scaledobjects.keda.sh -n "$NAMESPACE" -l "$selector" -o name)" ]; thenecho "FAILED: release-owned ScaledObjects remain after cleanup" >&2exit 1fidiff --git a/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yaml b/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yamlindex b900893b1..4b7ec9954 100644--- a/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yaml+++ b/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yaml@@ -23,11 +23,14 @@ metadata:{{- include "sie-cluster.mcpEdge.labels" . | nindent 4 }}{{- $annotations := dict }}{{- /* base64 documents can be large; MCP streamable-HTTP needs unbuffered,- long-lived responses. */ -}}+ long-lived responses. The edge fans out to the same workers, so its+ read/send timeout is derived from workers.common.modelReadyTimeoutSec+ too — see "sie-cluster.ingress.proxyTimeoutSeconds". */ -}}+ {{- $proxyTimeoutS := include "sie-cluster.ingress.proxyTimeoutSeconds" . }}{{- $nginxDefaults := dict"nginx.ingress.kubernetes.io/proxy-body-size" "100m"- "nginx.ingress.kubernetes.io/proxy-read-timeout" "600"- "nginx.ingress.kubernetes.io/proxy-send-timeout" "600"+ "nginx.ingress.kubernetes.io/proxy-read-timeout" $proxyTimeoutS+ "nginx.ingress.kubernetes.io/proxy-send-timeout" $proxyTimeoutS"nginx.ingress.kubernetes.io/proxy-buffering" "off"}}{{- $annotations = merge $annotations $nginxDefaults }}diff --git a/deploy/helm/sie-cluster/templates/serviceaccount.yaml b/deploy/helm/sie-cluster/templates/serviceaccount.yamlindex 72480ad30..ebf223ccf 100644--- a/deploy/helm/sie-cluster/templates/serviceaccount.yaml+++ b/deploy/helm/sie-cluster/templates/serviceaccount.yaml@@ -8,6 +8,8 @@in values-aws.yaml or via --set serviceAccount.annotations."eks\.amazonaws\.com/role-arn"=<ARN>.AKS: azure.workload.identity/client-id annotation is injected via serviceAccount.annotationsand azure.workload.identity/use label via serviceAccount.labels / podLabels.+ ACK: pod-identity.alibabacloud.com/role-name is injected via+ serviceAccount.annotations and RRSA admission is enabled via podLabels.If overriding serviceAccount.name, update the matching TF variable sie_service_account_name.*/ -}}apiVersion: v1diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex 2411bab28..14720d032 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -32,8 +32,13 @@ fast at render time.{{- fail (printf "workers.common.modelReadyTimeoutSec=%d must be lower than the adapter worker liveness budget (%d * %d = %ds); increase workers.common.probes.liveness.failureThreshold/periodSeconds or lower modelReadyTimeoutSec" $modelReadyTimeoutS $workerLivenessFailures $workerLivenessPeriodS $workerLivenessBudgetS) }}{{- end }}{{- $reservedOtelEnv := include "sie-cluster.otel.reservedEnvNames" $root | fromJsonArray -}}-{{- $reservedWorkerEnv := concat $reservedOtelEnv (list "SIE_BUNDLE" "SIE_GPU_TYPE" "SIE_MACHINE_PROFILE" "SIE_POOL" "SIE_WORKER_ID") -}}-{{- $reservedSidecarEnv := concat $reservedOtelEnv (list "SIE_BUNDLE" "SIE_GPU_COUNT" "SIE_HEALTH_PUBLISH_ENABLED" "SIE_HEALTH_PUBLISH_INTERVAL_MS" "SIE_MACHINE_PROFILE" "SIE_OTEL_LANE" "SIE_POOL" "SIE_WORKER_ID") -}}+{{- $reservedWorkerEnv := concat $reservedOtelEnv (list "SIE_BUNDLE" "SIE_GPU_TYPE" "SIE_MACHINE_PROFILE" "SIE_POOL" "SIE_SGLANG_KERNEL_CACHE_ROOT" "SIE_WORKER_ID") -}}+{{- /* The SIE_STREAM_* trio is chart-owned on the sidecar for the same+ reason as on the gateway: both create the work streams, first creator+ wins, so the chart renders one value onto both. An extraEnv override+ here would move only the workers and silently reintroduce the divergence+ the gateway-deployment render guards exist to prevent. */}}+{{- $reservedSidecarEnv := concat $reservedOtelEnv (list "SIE_BUNDLE" "SIE_GPU_COUNT" "SIE_HEALTH_PUBLISH_ENABLED" "SIE_HEALTH_PUBLISH_INTERVAL_MS" "SIE_MACHINE_PROFILE" "SIE_OTEL_LANE" "SIE_POOL" "SIE_STREAM_MAX_AGE_S" "SIE_STREAM_REPLICAS" "SIE_STREAM_STORAGE" "SIE_WORKER_ID") -}}{{- include "sie-cluster.env.assertNoReserved" (dict "path" "workers.common.extraEnv" "entries" $root.Values.workers.common.extraEnv "reserved" $reservedWorkerEnv) -}}{{- include "sie-cluster.env.assertNoReserved" (dict "path" "workers.common.workerSidecar.extraEnv" "entries" $root.Values.workers.common.workerSidecar.extraEnv "reserved" $reservedSidecarEnv) -}}{{- range $poolName, $pool := .Values.workers.pools }}@@ -79,9 +84,9 @@ fast at render time.and image with `sglang`) set this to the bundle whose image they reuse. Labels, envvars, --bundle flag, and metrics still use $bundle. */ -}}{{- $imageBundle := default $bundle $bundleCfg.imageBundle }}-{{- /* Fail fast when a bundle is placed on a platform whose image the release- pipeline does not build — mirrors docker_task.platform_supports_bundle and- .github/release-matrix.json. Inert for bundles absent from bundlePlatforms. */ -}}+{{- /* Fail fast when a bundle is placed on a platform without a matching+ published image. This mirrors bundlePlatforms and is inert for bundles+ absent from that map. */ -}}{{- $bundlePlatforms := $root.Values.workers.common.bundlePlatforms | default dict }}{{- $requiredPlatform := index $bundlePlatforms $imageBundle | default "" }}{{- if and $requiredPlatform (ne $requiredPlatform $platform) }}@@ -94,6 +99,35 @@ fast at render time.{{- if and (eq $engine "candle") (ne $bundle "candle") }}{{- fail (printf "workers.pools.%s.bundles.%s.engine=candle requires bundle=candle so gateway routing and worker heartbeats agree" $poolName $bundleName) }}{{- end }}+{{- $kernelCacheCommon := default dict $root.Values.workers.common.kernelCache }}+{{- if not (kindIs "map" $kernelCacheCommon) }}+{{- fail "workers.common.kernelCache must be a map with an enabled boolean" }}+{{- end }}+{{- $kernelCacheEnabled := false }}+{{- if hasKey $kernelCacheCommon "enabled" }}+{{- if not (kindIs "bool" (index $kernelCacheCommon "enabled")) }}+{{- fail "workers.common.kernelCache.enabled must be a boolean" }}+{{- end }}+{{- $kernelCacheEnabled = index $kernelCacheCommon "enabled" }}+{{- end }}+{{- if hasKey $bundleCfg "kernelCache" }}+{{- if not (kindIs "map" $bundleCfg.kernelCache) }}+{{- fail (printf "workers.pools.%s.bundles.%s.kernelCache must be a map with an enabled boolean" $poolName $bundleName) }}+{{- end }}+{{- if hasKey $bundleCfg.kernelCache "enabled" }}+{{- if not (kindIs "bool" (index $bundleCfg.kernelCache "enabled")) }}+{{- fail (printf "workers.pools.%s.bundles.%s.kernelCache.enabled must be a boolean" $poolName $bundleName) }}+{{- end }}+{{- $kernelCacheEnabled = index $bundleCfg.kernelCache "enabled" }}+{{- end }}+{{- end }}+{{- if and $kernelCacheEnabled (ne $engine "pytorch") }}+{{- fail (printf "workers.pools.%s.bundles.%s.kernelCache is supported only for pytorch/SGLang workers" $poolName $bundleName) }}+{{- end }}+{{- $kernelCacheStorageSize := dig "storageSize" "" $kernelCacheCommon | toString | trim }}+{{- if and $kernelCacheEnabled (eq $kernelCacheStorageSize "") }}+{{- fail "workers.common.kernelCache.storageSize must be non-empty when the kernel cache is enabled" }}+{{- end }}{{- $gpuCount := int $pool.gpu.count }}{{- $poolSidecar := default dict $pool.sidecar }}{{- $emulatedChildCount := int (dig "emulatedChildCount" 0 $poolSidecar) }}@@ -154,6 +188,22 @@ spec:{{- include "sie-cluster.worker.selectorLabels" $root | nindent 6 }}sie.superlinked.com/pool: {{ $poolName | quote }}sie.superlinked.com/bundle: {{ $bundle | quote }}+ {{- if $kernelCacheEnabled }}+ # One retained claim per StatefulSet ordinal. Never point multiple workers at+ # one writable DeepGEMM cache: upstream compilation is not cross-process safe.+ volumeClaimTemplates:+ - metadata:+ name: kernel-cache+ spec:+ accessModes: ["ReadWriteOnce"]+ {{- $kernelCacheStorageClass := dig "storageClassName" "" $kernelCacheCommon | toString | trim }}+ {{- if $kernelCacheStorageClass }}+ storageClassName: {{ $kernelCacheStorageClass | quote }}+ {{- end }}+ resources:+ requests:+ storage: {{ $kernelCacheStorageSize | quote }}+ {{- end }}template:metadata:labels:@@ -306,6 +356,12 @@ spec:- name: SIE_CLUSTER_CACHEvalue: {{ $root.Values.workers.common.clusterCache.url | quote }}{{- end }}+ {{- if $kernelCacheEnabled }}+ # The adapter adds an installed-ABI + exact-GPU namespace below+ # this per-child root before setting upstream compiler cache vars.+ - name: SIE_SGLANG_KERNEL_CACHE_ROOT+ value: {{ printf "/var/cache/sie-kernels/%s" $workerContainerName | quote }}+ {{- end }}- name: SIE_POOLvalue: {{ $queuePool | quote }}{{- with $root.Values.queueRouting }}@@ -395,6 +451,10 @@ spec:volumeMounts:- name: model-cachemountPath: /models+ {{- if $kernelCacheEnabled }}+ - name: kernel-cache+ mountPath: /var/cache/sie-kernels+ {{- end }}- name: shmmountPath: /dev/shm{{- if $root.Values.workers.common.workerSidecar.enabled }}@@ -504,6 +564,13 @@ spec:# consumers must agree on max_age or retries race against purge.- name: SIE_STREAM_MAX_AGE_Svalue: {{ .streamMaxAgeSec | default 1800 | quote }}+ # Work-queue durability, in lockstep with the gateway for the same+ # first-creator-wins reason. Validated once in+ # templates/gateway-deployment.yaml.+ - name: SIE_STREAM_STORAGE+ value: {{ lower (default "memory" .streamStorage) | quote }}+ - name: SIE_STREAM_REPLICAS+ value: {{ int (default 1 .streamReplicas) | quote }}{{- if .maxAckPending }}- name: SIE_MAX_ACK_PENDINGvalue: {{ .maxAckPending | quote }}diff --git a/deploy/helm/sie-cluster/values-ack.yaml b/deploy/helm/sie-cluster/values-ack.yamlnew file mode 100644index 000000000..1d1e4a016--- /dev/null+++ b/deploy/helm/sie-cluster/values-ack.yaml@@ -0,0 +1,198 @@+# Alibaba Cloud ACK specific values+fullnameOverride: sie++# ACK RRSA admission injects short-lived OIDC credentials into every SIE pod+# template that uses the shared sie-server ServiceAccount.+podLabels:+ pod-identity.alibabacloud.com/injection: "on"++# Sub-charts required for queue-depth autoscaling and observability.+keda:+ install: true++kube-prometheus-stack:+ install: true+ # ACK manages its own control plane.+ kubeApiServer:+ enabled: false+ kubeControllerManager:+ enabled: false+ kubeScheduler:+ enabled: false+ kubeProxy:+ enabled: false+ kubeEtcd:+ enabled: false+ prometheus:+ prometheusSpec:+ storageSpec:+ volumeClaimTemplate:+ spec:+ storageClassName: alicloud-disk-topology-alltype+ grafana:+ persistence:+ storageClassName: alicloud-disk-topology-alltype+ # ACK disk CSI rejects smaller dynamically provisioned disks.+ size: 20Gi++observability:+ logs:+ install: true++loki:+ singleBinary:+ persistence:+ storageClass: alicloud-disk-topology-alltype++# ACK may mark none of its built-in disk CSI classes as default. The selected+# topology-aware class delays allocation until scheduling and falls back from+# ESSD to SSD/ultra in the chosen zone. It does not itself prove encryption;+# use a governed encrypted WFFC class and override all four ACK storage paths+# together when encrypted PVCs are required.++kubernetes-event-exporter:+ install: false++# Autoscaling via KEDA (queries Prometheus for scaling decisions).+# prometheusAddress is auto-derived when kube-prometheus-stack.install=true.+autoscaling:+ enabled: true+ cooldownPeriod: 600+ scaleDownStabilization: 300++serviceMonitor:+ enabled: true+ labels:+ app.kubernetes.io/part-of: sie++machineProfiles:+ # Alibaba Cloud ecs.gn7i-c8g1.2xlarge (NVIDIA A10, 24 GiB).+ a10:+ gpuType: nvidia-a10+ machineType: ecs.gn7i-c8g1.2xlarge+ spot: false++ingress:+ # Install and wait for an ACK-compatible ingress controller before enabling.+ enabled: false+ className: nginx++gateway:+ replicas: 2+ image:+ pullPolicy: IfNotPresent+ resources:+ requests:+ cpu: "500m"+ memory: "512Mi"+ limits:+ cpu: "2"+ memory: "2Gi"+ extraEnv:+ - name: SIE_OSS_REGION+ value: "eu-central-1"+ - name: SIE_OSS_USE_INTERNAL_ENDPOINT+ value: "true"+ - name: ALIBABA_CLOUD_ECS_METADATA_DISABLED+ value: "true"++config:+ enabled: true+ podSecurityContext:+ fsGroup: 1000+ fsGroupChangePolicy: OnRootMismatch+ runAsGroup: 1000+ runAsNonRoot: true+ runAsUser: 1000+ # Mutable epoch state remains on an ACK disk. OSS cannot provide the+ # compare-and-swap contract required by sie-config.+ configStore:+ enabled: true+ storageClassName: alicloud-disk-topology-alltype+ # ACK disk CSI rejects smaller dynamically provisioned disks.+ size: 20Gi+ image:+ pullPolicy: IfNotPresent+ resources:+ requests:+ cpu: "100m"+ memory: "256Mi"+ limits:+ cpu: "1"+ memory: "1Gi"++workers:+ common:+ # Node-backed emptyDir cache. The Terraform GPU disk default is 500 GiB,+ # leaving nominal headroom for images, logs, OS, and kubelet thresholds.+ cacheStorageSize: 300Gi+ extraEnv:+ - name: SIE_OSS_REGION+ value: "eu-central-1"+ - name: SIE_OSS_USE_INTERNAL_ENDPOINT+ value: "true"+ - name: ALIBABA_CLOUD_ECS_METADATA_DISABLED+ value: "true"+ workerSidecar:+ extraEnv:+ - name: SIE_OSS_REGION+ value: "eu-central-1"+ - name: SIE_OSS_USE_INTERNAL_ENDPOINT+ value: "true"+ - name: ALIBABA_CLOUD_ECS_METADATA_DISABLED+ value: "true"+ pools:+ a10:+ enabled: true+ machineProfile: a10+ gpuType: a10+ # Match the generic GPU labels and the Terraform pool's exact GPU type.+ nodeSelector:+ ack.node.gpu.schedule: default+ sie.superlinked.com/gpu-type: a10+ sie.superlinked.com/node-type: gpu+ gpu:+ count: 1+ product: NVIDIA-A10+ resources:+ requests:+ cpu: "4"+ memory: "16Gi"+ limits:+ cpu: "8"+ memory: "24Gi"+ # Matches the taint applied by the Alibaba Terraform module.+ tolerations:+ - key: nvidia.com/gpu+ operator: Equal+ value: present+ effect: NoSchedule+ bundles:+ default:+ minReplicas: 0+ maxReplicas: 10++# Pass Terraform's `payload_store_url` output at install time. Native OSS V4+# uses RRSA and is required for queue work items larger than 1 MiB.+payloadStore:+ enabled: true++# Pass Terraform's `rrsa_workload_role_name` output through the exact+# `pod-identity.alibabacloud.com/role-name` annotation at install time. The+# chart never renders an AccessKey or projected token value.+serviceAccount:+ create: true+ name: "sie-server"+ annotations: {}++dcgm-exporter:+ # If enabled, keep the exporter on the same ACK GPU pools as workers.+ nodeSelector:+ ack.node.gpu.schedule: default+ sie.superlinked.com/gpu-type: a10+ sie.superlinked.com/node-type: gpu+ tolerations:+ - key: nvidia.com/gpu+ operator: Equal+ value: present+ effect: NoSchedulediff --git a/deploy/helm/sie-cluster/values-aws.yaml b/deploy/helm/sie-cluster/values-aws.yamlindex 787fb5f65..1d62da447 100644--- a/deploy/helm/sie-cluster/values-aws.yaml+++ b/deploy/helm/sie-cluster/values-aws.yaml@@ -30,7 +30,7 @@ kubernetes-event-exporter:# prometheusAddress is auto-derived when kube-prometheus-stack.install=trueautoscaling:enabled: true- # Match GCP (600s/300s) - must survive gaps between matrix eval task transitions+ # Match GCP (600s/300s) - must survive gaps between long evaluation/workload transitionscooldownPeriod: 600scaleDownStabilization: 300@@ -158,8 +158,8 @@ workers:maxReplicas: 4# ServiceAccount — Helm manages creation; IRSA annotation must be injected at deploy time.-# NAMING CONTRACT: name must match module.sie_irsa_role namespace_service_accounts-# in deploy/terraform/aws/irsa.tf (currently "sie:sie-server").+# NAMING CONTRACT: name must match the namespace/service-account binding in+# your workload-identity configuration (the default is "sie:sie-server").# To inject the IRSA role ARN at deploy time:# --set serviceAccount.annotations."eks\.amazonaws\.com/role-arn"=<ARN># Note: The hf-token secret is NOT created by the Helm chart. It must be createddiff --git a/deploy/helm/sie-cluster/values-gke.yaml b/deploy/helm/sie-cluster/values-gke.yamlindex ced220100..a0cd68e64 100644--- a/deploy/helm/sie-cluster/values-gke.yaml+++ b/deploy/helm/sie-cluster/values-gke.yaml@@ -149,12 +149,11 @@ workers:maxReplicas: 10# ServiceAccount — Helm manages creation; Workload Identity annotation injected at deploy time.-# NAMING CONTRACT: name must match Terraform's Workload Identity binding-# in deploy/terraform/gcp/infra/iam.tf (currently "sie:sie-server").+# NAMING CONTRACT: name must match the namespace/service-account binding in+# your Workload Identity configuration (the default is "sie:sie-server").# To inject the GCP SA at deploy time:# --set serviceAccount.annotations."iam\.gke\.io/gcp-service-account"=<EMAIL>-# Or use terraform output:-# --set serviceAccount.annotations."iam\.gke\.io/gcp-service-account"="$(terraform -chdir=deploy/terraform/gcp/infra output -raw sie_workload_service_account)"+# Or pass the corresponding output from your infrastructure configuration.serviceAccount:create: truename: "sie-server"diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex acf463ab0..38d5d5686 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -86,6 +86,10 @@ config:# -- Pod annotationspodAnnotations: {}+ # -- Optional pod-level security context. Set fsGroup when a CSI-backed+ # configStore volume needs to be writable by the non-root sie-config user.+ podSecurityContext: {}+# -- Node selectornodeSelector: {}@@ -158,6 +162,52 @@ gateway:# restart is an unacceptable blip on inference traffic.replicas: 1+ # -- Graceful-shutdown budget for a terminating gateway pod. The chart+ # DERIVES `terminationGracePeriodSeconds` from these two knobs (helper+ # `sie-cluster.gateway.terminationGracePeriodSeconds`) instead of carrying a+ # second magic number that can drift:+ #+ # terminationGracePeriodSeconds+ # = preStopSleepSeconds + inFlightSeconds + 5s queue drain+ # = 10 + 120 + 5 = 135s with the defaults below+ #+ # The trailing 5s is the gateway's own post-serve `drain_pending(5s)`+ # (packages/sie_gateway/src/main.rs) and is not chart-configurable.+ drain:+ # -- Seconds the pod stays up, still serving, after it goes Terminating+ # and before its container is signalled. Endpoint removal is eventually+ # consistent, so without this delay kube-proxy and the ingress can still+ # be routing new requests to a pod that has already begun shutting down —+ # on every rolling deploy, node drain and KEDA scale-in. Set 0 to drop the+ # hook. Rendered as the native `lifecycle.preStop.sleep` action (the+ # gateway image is distroless, so there is no shell for an exec hook),+ # which needs Kubernetes >= 1.30; older API servers drop the field and the+ # pod simply loses the delay.+ preStopSleepSeconds: 10+ # -- Seconds the gateway may spend finishing in-flight work after SIGTERM.+ # axum's graceful shutdown is unbounded in the binary, so this is the real+ # bound: anything still running when the derived grace period expires is+ # SIGKILLed mid-response (a cut SSE generation stream or queued-result+ # wait). The default matches the gateway's own SIE_GATEWAY_REQUEST_TIMEOUT+ # default of 120s, which caps every queued-result wait; raise it for+ # deployments serving longer streams.+ inFlightSeconds: 120++ # -- PodDisruptionBudget for the gateway tier. Without one, a node drain or+ # cluster upgrade may evict every gateway pod simultaneously and take the+ # whole inference gateway down at once.+ podDisruptionBudget:+ # -- Empty (default) lets the chart decide: a PDB is created only when+ # `gateway.replicas` is above 1, i.e. when the tier is guaranteed to have a+ # spare pod. At a single replica a maxUnavailable=1 budget is worse than+ # none — once that pod is unhealthy `disruptionsAllowed` drops to 0 and the+ # PDB blocks the drain that would have rescheduled it. Set true/false to+ # force the decision (for example true on an autoscaled cluster that keeps+ # `gateway.replicas: 1` as the KEDA floor but normally runs several pods).+ enabled: ""+ # -- Voluntary disruptions tolerated at once.+ maxUnavailable: 1+# -- Worker-health discovery mode. Empty lets the chart choose the# routing-safe default: "nats" when NATS and the worker-sidecar are# enabled, otherwise the gateway binary default.@@ -205,7 +255,17 @@ gateway:# -- Tolerationstolerations: []- # -- Affinity rules+ # -- Affinity rules. Empty keeps the chart default: a PREFERRED pod+ # anti-affinity on `kubernetes.io/hostname` that spreads gateway replicas+ # across nodes, mirroring the worker StatefulSet. Preferred rather than+ # required so a single-node dev cluster still schedules every replica.+ # Setting this replaces the default outright (no merge).+ #+ # `topologySpreadConstraints` are deliberately not rendered: nothing in this+ # chart declares a zone topology (no zone nodeSelectors, no zone-aware+ # storage), the worker tier already establishes host-level anti-affinity as+ # the chart's spreading idiom, and a DoNotSchedule constraint would leave+ # replicas Pending on the single- and two-node clusters the chart supports.affinity: {}# -- Gateway auth (static token)@@ -380,14 +440,14 @@ workers:# -- Map of imageBundle -> required platform. Mirrors each bundle's# -- `platform:` field in packages/sie_server/bundles/*.yaml and the- # -- `.github/release-matrix.json` `include` pairs (KEEP IN SYNC). The chart+ # -- published image variants (KEEP IN SYNC). The chart# -- fails fast if a pool places a listed bundle on a different platform:# -- the release pipeline only builds the matching `<platform>-<bundle>`# -- image, so a mismatch would otherwise ImagePullBackOff at runtime.# -- Bundles not listed here default to the common `platform` above.bundlePlatforms:- # gemma 4 (sglang 0.5.13 / torch 2.11 cu130) ships only as a CUDA 13 image.- gemma: cuda13+ # SGLang cu130 (Gemma 4 plus newer Qwen profiles) ships only as a CUDA 13 image.+ sglang-cu130: cuda13# -- Image pre-pull DaemonSet (caches worker image on GPU nodes before worker pods schedule)imagePrepull:@@ -432,9 +492,34 @@ workers:# -- Runtime class for workers (e.g., "nvidia" to enable GPU runtime)runtimeClassName: ""- # -- Model cache size limit (emptyDir - ephemeral, no zone-lock issues)+ # -- Model cache size limit (emptyDir - ephemeral, no zone-lock issues).+ # This is a sizeLimit on an emptyDir, which lives on the NODE's root+ # volume: it caps the cache, it does not reserve the space. Keep the GPU+ # node disk comfortably above this value (Terraform+ # `gpu_disk_size_gb` / `gpu_node_groups[*].disk_size_gb` on AWS,+ # `gpu_node_pools[*].disk_size_gb` on GCP, `os_disk_size_gb` on Azure --+ # defaults leave ~100GiB of headroom over this 300Gi). If the disk is+ # smaller, a worker lazily loading several large models fills the root+ # volume first and kubelet evicts it (and its co-located pods) on disk+ # pressure mid-inference, long before this sizeLimit ever engages.cacheStorageSize: 300Gi+ # -- Optional persistent cache for SGLang/FlashInfer/DeepGEMM/Triton+ # compiled kernels. Disabled by default: workers remain cacheless-capable+ # and no PVC is required for a normal install. When enabled, every worker+ # StatefulSet replica gets its own ReadWriteOnce claim; claims are never+ # shared across replicas because upstream JIT writers are not safe under+ # concurrent cross-process mutation. A bundle-level+ # `kernelCache.enabled` overrides this common default.+ kernelCache:+ enabled: false+ # -- Requested storage for each retained per-replica compiler cache.+ storageSize: 20Gi+ # -- StorageClass for compiler-cache claims. Empty uses the cluster+ # default. Prefer a class available in every zone that can host the+ # corresponding GPU pool.+ storageClassName: ""+# -- Cluster cache (object storage) for model WEIGHTS only. Optional# perf/offline feature (a cache miss falls back to HuggingFace), default# off. Decoupled from the payload store (top-level `payloadStore`), which@@ -447,7 +532,7 @@ workers:# - s3://<bucket>/models (AWS — terraform output -raw model_cache_bucket_url)# - gs://<bucket>/models (GCP — same output name)# - abfs(s)://<container>@<account>.dfs.core.windows.net/models (Azure ADLS Gen2 — same output name)- # Pre-populate the bucket once with `sie-admin cache weights sync --bundle default --dest <url>/`.+ # Pre-populate the /models prefix with your object-storage tooling or cache pipeline.url: ""# -- HuggingFace cache configuration@@ -499,6 +584,13 @@ workers:# SIE_WORKER_LIVENESS_BUDGET_S as periodSeconds * failureThreshold and both# Python and sidecar reject larger cold-start timeouts so kubelet does not# kill the pod before the cleanup-safe startup timeout can finish.+ # The nginx ingress proxy-read/send-timeout annotations are DERIVED from+ # this value (max(this + 60, 600) seconds, see+ # `sie-cluster.ingress.proxyTimeoutSeconds`) so the edge never 504s a first+ # request that is still legitimately waiting on a cold model load. This is+ # the only knob for that edge budget: raising this raises the edge timeout+ # with it, and the chart's nginx annotation defaults take precedence over+ # `ingress.annotations`.modelReadyTimeoutSec: 900# -- Liveness/readiness/startup probe timing for worker pods. The httpGet@@ -750,6 +842,8 @@ workers:# `sglang-vision-extract` -> `sglang`).# preloadModels: Optional list of models to preload for this specific# worker lane. Overrides pool/common preloadModels.+ # kernelCache: Optional `{enabled: bool}` override for the common+ # per-replica SGLang compiler-cache policy.# extraEnv: list. Extra env vars on the ``worker`` container.# Rendered after workers.common.extraEnv so a# bundle-level entry wins on duplicate names.@@ -858,16 +952,17 @@ workers:minReplicas: 0maxReplicas: 3- # Gemma 4 (CUDA 13 / cu130). NOTE the `platform: cuda13` — the gemma image- # is built/tagged cuda13-gemma; omitting this (defaulting to cuda12) makes+ # SGLang cu130 generation (Gemma 4 plus newer Qwen profiles). NOTE the+ # `platform: cuda13` — the image is built/tagged cuda13-sglang-cu130;+ # omitting this (defaulting to cuda12) makes# the chart fail fast (see workers.common.bundlePlatforms). The 26B-A4B model# needs a 96 GB+ card (H200 / RTX PRO 6000); E2B/E4B fit smaller GPUs.# When productionizing, also add a matching entry under the top-level# `machineProfiles:` map so it surfaces in the machine-profiles ConfigMap,# and set `gpu.product` to your node's actual GPU label.- gemma:+ sglang-cu130:enabled: false- machineProfile: gemma+ machineProfile: sglang-cu130gpuType: h200platform: cuda13nodeSelector: {}@@ -886,7 +981,7 @@ workers:operator: Existseffect: NoSchedulebundles:- gemma:+ sglang-cu130:minReplicas: 0maxReplicas: 2@@ -1099,11 +1194,15 @@ auth:# and pod annotation iam.gke.io/gcp-service-account# EKS: module.sie_irsa_role namespace_service_accounts = ["sie:sie-server"]# and pod annotation eks.amazonaws.com/role-arn+# ACK: RRSA role trust subject "system:serviceaccount:sie:sie-server"+# and pod annotation pod-identity.alibabacloud.com/role-name# If you override serviceAccount.name, update the matching TF variable sie_service_account_name.# If you override the Kubernetes namespace (or deploy the SA in a different namespace),# also update the corresponding Workload Identity / IRSA bindings and Terraform variables-# (e.g. sie_service_account_name) and pod annotations (iam.gke.io/gcp-service-account or-# eks.amazonaws.com/role-arn) so they reference the same namespace and KSA name "sie-server".+# (e.g. sie_service_account_name) and pod annotations+# (iam.gke.io/gcp-service-account, eks.amazonaws.com/role-arn, or+# pod-identity.alibabacloud.com/role-name) so they reference the same namespace+# and KSA name "sie-server".serviceAccount:# -- Create service accountcreate: true@@ -1214,6 +1313,13 @@ nats:# NOTE: These keys are passed to the NATS sub-chart (nats/nats) which expects# config.jetstream.memoryStore.maxSize (not memStorage/size).config:+ # -- NATS server clustering. Off by default: a single NATS pod is the+ # shipped topology. A replicated work queue+ # (queueRouting.streamReplicas > 1) needs this enabled with+ # replicas >= streamReplicas, otherwise stream creation fails.+ cluster:+ enabled: false+ replicas: 3jetstream:# -- Enable JetStream for the NATS work queue.# Required when clusterRouting=queue (the default).@@ -1223,10 +1329,22 @@ nats:memoryStore:enabled: truemaxSize: 512MB- # -- File storage (disabled for memory-only work queues).- # Enable with a PVC if you need persistent DLQ or large stream retention.+ # -- File storage. Off by default, matching the memory-backed default+ # of queueRouting.streamStorage.+ # NOTE: enabling this alone changes NOTHING about the work queue or the+ # DLQ — the gateway and sidecars create their streams with whatever+ # queueRouting.streamStorage says, and server-side fileStore only backs+ # streams explicitly created with File storage. Set+ # queueRouting.streamStorage=file to actually persist them; the chart+ # then requires this to be enabled (see the gateway-deployment guard).fileStore:enabled: false+ # Sub-chart PVC template for the JetStream store, mounted on each NATS+ # pod. Size must comfortably exceed peak queue depth (max_msgs is+ # 100_000 per pool stream) plus the 24 h DEAD_LETTERS retention.+ pvc:+ enabled: true+ size: 10Gi# -- Prometheus NATS exporter sidecar.# Exposes NATS server internals (connections, JetStream streams/consumers) to Prometheus.promExporter:@@ -1271,6 +1389,40 @@ queueRouting:# Keep above maxDeliver * 30s so failed work remains fetchable# after the retry/DLQ envelope for operator inspection.streamMaxAgeSec: 1800+ # -- JetStream storage backing for the work-queue streams+ # (`WORK_POOL_{pool}`, the per-worker direct-dispatch streams, and+ # `DEAD_LETTERS`). One of "memory" (default) or "file". Rendered into+ # SIE_STREAM_STORAGE on BOTH the gateway and the worker sidecars so the two+ # stream creators cannot disagree — whoever creates a stream first wins.+ #+ # "memory" (the shipped default, and the only behaviour that existed before+ # this knob) keeps queued and delivered-but-unacked work only in the+ # broker's RAM. A restart of the NATS pod — an OOM kill, a NATS rollout, or+ # a node drain that evicts THAT pod — erases every queued item AND the+ # DEAD_LETTERS record that would have named them. (Draining a node hosting+ # only workers or gateways is harmless here; at streamReplicas=1 any+ # eviction of the single NATS pod loses the state, while a replicated stream+ # survives as long as a peer holding it stays up.) The gateway is queue-only+ # with no direct fallback, so a broker restart is a full inference outage for+ # its duration, and in-flight work does not come back.+ #+ # "file" persists work across a broker restart. It is NOT a free upgrade:+ # it requires nats.config.jetstream.fileStore.enabled=true (a PVC per NATS+ # pod), adds a disk write to every publish, and raises publish latency on+ # the inference hot path. Sizing the PVC is on the operator.+ #+ # Flipping this on an existing cluster does NOT convert live streams:+ # JetStream refuses an in-place storage-type change, so the gateway and+ # sidecars log a loud warning and leave existing streams alone. The new+ # setting takes effect only for streams created afterwards — drain the pool+ # and delete the streams during a maintenance window to convert.+ streamStorage: memory+ # -- JetStream replica count for those same streams (SIE_STREAM_REPLICAS).+ # 1 (default) means a single copy: losing the broker holding it loses the+ # work even with file storage. Values above 1 require a clustered NATS+ # (nats.config.cluster.enabled=true with at least this many replicas).+ # Unlike streamStorage, this IS reconciled on existing streams.+ streamReplicas: 1# -- Non-expiring pool objects synthesized by the gateway for Helm-declared# physical queue namespaces. Keys are queue pool names; names are normalized to# lowercase before gateway storage/routing. Use this when@@ -1324,12 +1476,17 @@ queueRouting:# filesystems) and are rejected.# 2. else derived from workers.common.clusterCache.url by swapping a trailing# "/models" prefix for "/payloads" (shared bucket, sibling prefixes:-# <bucket>/models/... model weights (managed by sie-admin)+# <bucket>/models/... model weights (populated separately)# <bucket>/payloads/... large work-item refs (managed by gateway)).# Supported schemes: s3:// (AWS), gs:// (GCP), abfs:// + abfss:// (Azure ADLS-# Gen2). All three terraform modules expose `payload_store_url` (the /payloads-# URL) and scope the workload IAM grant to that prefix, so the wiring aligns-# out of the box.+# Gen2), and oss:// (Alibaba Cloud). All four terraform modules expose+# `payload_store_url` (the /payloads URL). For managed storage, payload object+# actions are prefix-scoped. AWS also+# conditions bucket-level ListBucket on payloads/; GCP grants object listing+# separately bucket-wide; and Azure exempts Blob.List from its payloads/ ABAC+# condition; Alibaba conditions bucket-level ListObjects on models/* and+# payloads/*. The legacy GCP BYO path grants objectViewer bucket-wide;+# operators own IAM scoping for other explicitly configured BYO storage.## If enabled and clusterRouting=queue but no URL resolves, the chart FAILS the# install with guidance (see deploy/helm/sie-cluster/README.md). Set@@ -1337,7 +1494,7 @@ queueRouting:payloadStore:# -- Enable the payload store. Default true: required for >1MB work items.enabled: true- # -- Payload store URL (object storage: s3://, gs://, abfs://, abfss://).+ # -- Payload store URL (object storage: s3://, gs://, abfs://, abfss://, oss://).# Empty derives from workers.common.clusterCache.url (the shared bucket's# /payloads sibling). Set explicitly to the terraform `payload_store_url`# output (or a separate bucket). Local paths are rejected in queue mode.@@ -1900,6 +2057,8 @@ mcpEdge:# Connector secrets (the per-user auth shim). Comma-separated `secret[:user_id]`.# Rendered into a chart-managed Secret when set; or point existingSecretName at# a Secret you manage (key: connector-secrets). NEVER commit a real secret here.+ # Local-only demo example: `local-dev-secret:local-dev`. Replace it before any+ # shared or production deployment.connectorSecrets: ""existingSecretName: ""# SIE_MCP_PUBLIC_URL — the externally reachable https origin (e.g.diff --git a/integrations/README.md b/integrations/README.mdindex 9a7a08c5b..6b9ad71a2 100644--- a/integrations/README.md+++ b/integrations/README.md@@ -82,20 +82,20 @@ We use a layered testing approach:mise run test# Run tests for a specific integration-mise run test integrations/sie_langchain/tests/+mise run test -- integrations/sie_langchain/tests/```**Integration tests** (require running server):```bash# Start SIE server-mise run serve -d cpu -p 8080+mise run serve -- -d cpu -p 8080# Run all integration tests-mise run test -i+mise run test -- -i# Run integration tests for specific package-mise run test -i integrations/sie_langchain/+mise run test -- -i integrations/sie_langchain/```### Creating a New Integration@@ -297,7 +297,7 @@ image_emb = client.encode("openai/clip-vit-large-patch14", Item(image=image))# Visual document retrieval with ColPalipage_image = Image.open("document_page.png")-page_emb = client.encode("vidore/colpali-v1.2", Item(image=page_image), output_types=["multivector"])+page_emb = client.encode("vidore/colpali-v1.3-hf", Item(image=page_image), output_types=["multivector"])```**Supported vector databases for multi-vector:**@@ -317,8 +317,6 @@ Each integration is versioned and released independently:## Contributing-See the main repository's CONTRIBUTING.md for general guidelines.-For integration-specific contributions:1. Follow the framework's conventions and best practicesdiff --git a/integrations/conftest.py b/integrations/conftest.pyindex 5be352daa..3c659aaca 100644--- a/integrations/conftest.py+++ b/integrations/conftest.py@@ -180,14 +180,21 @@ def mock_sie_client() -> MagicMock:for item in items]- def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> list[dict]:- """Mock score that returns relevance scores."""+ def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> dict[str, Any]:+ """Mock score that returns a ScoreResult envelope.++ Mirrors the real SDK ``SIEClient.score()`` shape: a ``{model, scores,+ ...}`` envelope with ranked entries under ``scores`` (not a bare list).+ """query_text = _get_text(query)item_dicts = [{"id": i.get("id", str(idx)) if isinstance(i, dict) else str(idx), "text": _get_text(i)}for idx, i in enumerate(items)]- return _create_mock_score_result(query_text, item_dicts, kwargs.get("top_k"))+ return {+ "model": _model,+ "scores": _create_mock_score_result(query_text, item_dicts, kwargs.get("top_k")),+ }def mock_extract(_model: str, items: Any, labels: list[str], **_kwargs: Any) -> list[dict] | dict:"""Mock extract that returns NER entities."""@@ -237,13 +244,16 @@ def mock_sie_async_client() -> MagicMock:for item in items]- async def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> list[dict]:+ async def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> dict[str, Any]:query_text = _get_text(query)item_dicts = [{"id": i.get("id", str(idx)) if isinstance(i, dict) else str(idx), "text": _get_text(i)}for idx, i in enumerate(items)]- return _create_mock_score_result(query_text, item_dicts, kwargs.get("top_k"))+ return {+ "model": _model,+ "scores": _create_mock_score_result(query_text, item_dicts, kwargs.get("top_k")),+ }async def mock_extract(_model: str, items: Any, labels: list[str], **_kwargs: Any) -> list[dict] | dict:if _is_single_item(items):diff --git a/integrations/sie_chroma/README.md b/integrations/sie_chroma/README.mdindex 023c93a32..a47f09a87 100644--- a/integrations/sie_chroma/README.md+++ b/integrations/sie_chroma/README.md@@ -112,7 +112,7 @@ from llama_index.vector_stores.chroma import ChromaVectorStoreStart the SIE server before using this integration:```bash-mise run serve -d cpu -p 8080+mise run serve -- -d cpu -p 8080```## Testingdiff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex 582abfeb6..a27d56425 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.7.1"+version = "0.7.2"description = "SIE integration for ChromaDB"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_chroma/tests/test_integration.py b/integrations/sie_chroma/tests/test_integration.pyindex 30911788b..d16aa8ff6 100644--- a/integrations/sie_chroma/tests/test_integration.py+++ b/integrations/sie_chroma/tests/test_integration.py@@ -6,7 +6,7 @@ of ChromaDB workflows using SIE embeddings.Run with: pytest -m integration integrations/sie_chroma/tests/Prerequisites:- mise run serve -d cpu -p 8080+ mise run serve -- -d cpu -p 8080ChromaDB Use Cases Demonstrated:- Semantic search over document collectionsdiff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.tomlindex eed5a94b3..02e0035ac 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.7.1"+version = "0.7.2"description = "SIE integration for CrewAI"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_crewai/src/sie_crewai/tools.py b/integrations/sie_crewai/src/sie_crewai/tools.pyindex 24ba60ac9..5b2f86b12 100644--- a/integrations/sie_crewai/src/sie_crewai/tools.py+++ b/integrations/sie_crewai/src/sie_crewai/tools.py@@ -5,12 +5,50 @@ Provides tools for reranking and entity extraction using SIE.from __future__ import annotations+from collections.abc import Mappingfrom typing import Anyfrom crewai.tools import BaseToolfrom pydantic import BaseModel, Field+def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:+ """Map ScoreResult entries back to input positions by item_id.++ Parses each entry's ``item_id`` defensively: a missing, non-integer,+ negative, or out-of-range id is skipped (that document keeps its 0.0+ default) so a malformed entry can neither crash the rerank nor mis-assign a+ score to the wrong document.++ Args:+ results: ScoreResult envelope from ``SIEClient.score()``.+ count: Number of input documents.++ Returns:+ Scores indexed by input position (0.0 for any unscored/invalid item).+ """+ scores = [0.0] * count+ for entry in results.get("scores", []):+ item_id = entry.get("item_id", entry.get("index"))+ # Accept only a genuine integer or an integer string. Reject bool (an int+ # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer+ # strings, so a malformed id cannot silently overwrite the wrong position.+ if isinstance(item_id, bool):+ continue+ if isinstance(item_id, int):+ idx = item_id+ elif isinstance(item_id, str):+ try:+ idx = int(item_id)+ except ValueError:+ continue+ else:+ continue+ if 0 <= idx < count:+ scores[idx] = float(entry.get("score", 0.0))+ return scores++class RerankerInput(BaseModel):"""Input schema for SIERerankerTool."""@@ -97,11 +135,17 @@ class SIERerankerTool(BaseTool):results = self.client.score(self.model, query_item, doc_items)+ # ``results`` is a ScoreResult envelope; ranked entries are under+ # ``results["scores"]`` (each a ScoreEntry keyed by ``item_id`` = input+ # position, plus ``score``). Map scores back to input order by item_id+ # rather than zipping positionally — the entries are sorted by relevance,+ # not by input order. ``results["request"]`` (request id) and+ # ``results["usage"]`` (token usage) are also available but intentionally+ # not surfaced here.+ score_by_index = _scores_by_index(results, len(documents))+# Build scored documents- scored = []- for doc, result in zip(documents, results, strict=True):- score = result.get("score", 0.0) if isinstance(result, dict) else getattr(result, "score", 0.0)- scored.append((float(score), doc))+ scored = [(score_by_index[idx], doc) for idx, doc in enumerate(documents)]# Sort by score descendingscored.sort(key=lambda x: x[0], reverse=True)diff --git a/integrations/sie_crewai/tests/conftest.py b/integrations/sie_crewai/tests/conftest.pyindex 2797df54d..0e542f14d 100644--- a/integrations/sie_crewai/tests/conftest.py+++ b/integrations/sie_crewai/tests/conftest.py@@ -51,20 +51,24 @@ def _create_mock_encode_result(def _create_mock_score_result(query: str, items: list[dict]) -> list[dict[str, Any]]:- """Create mock score results."""+ """Create mock score results matching the ranked-envelope contract.++ The SDK's ScoreResult is sorted by descending score, so sort here too and+ assign ``rank`` from the sorted position (``item_id`` stays the original+ input index).+ """rng = np.random.default_rng(hash(query) % (2**32))scores = rng.uniform(0, 1, len(items))- results = []- for idx, score in enumerate(scores):- results.append(- {- "item_id": str(idx),- "score": float(score),- "rank": idx,- }- )- return results+ sorted_indices = np.argsort(scores)[::-1]+ return [+ {+ "item_id": str(idx),+ "score": float(scores[idx]),+ "rank": rank,+ }+ for rank, idx in enumerate(sorted_indices)+ ]def _create_mock_extract_result(text: str, labels: list[str]) -> list[dict[str, Any]]:@@ -120,10 +124,15 @@ def mock_sie_client() -> MagicMock:item_dicts = [{"text": _get_text(i)} for i in items]return _create_mock_encode_result(item_dicts, is_query=is_query, output_types=output_types)- def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> list[dict]:+ def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> dict[str, Any]:+ # Mirror the real SDK: a ScoreResult envelope with ranked entries under+ # "scores", not a bare list.query_text = _get_text(query)item_dicts = [{"id": str(idx), "text": _get_text(i)} for idx, i in enumerate(items)]- return _create_mock_score_result(query_text, item_dicts)+ return {+ "model": _model,+ "scores": _create_mock_score_result(query_text, item_dicts),+ }def mock_extract(_model: str, item: Any, labels: list[str], **_kwargs: Any) -> list[dict]:return _create_mock_extract_result(_get_text(item), labels)diff --git a/integrations/sie_crewai/tests/test_integration.py b/integrations/sie_crewai/tests/test_integration.pyindex c134545e2..c3f4dfff6 100644--- a/integrations/sie_crewai/tests/test_integration.py+++ b/integrations/sie_crewai/tests/test_integration.py@@ -6,7 +6,7 @@ of CrewAI workflows using SIE tools.Run with: pytest -m integration integrations/sie_crewai/tests/Prerequisites:- mise run serve -d cpu -p 8080+ mise run serve -- -d cpu -p 8080"""from __future__ import annotationsdiff --git a/integrations/sie_crewai/tests/test_tools.py b/integrations/sie_crewai/tests/test_tools.pyindex 4a4f38234..065c7bacb 100644--- a/integrations/sie_crewai/tests/test_tools.py+++ b/integrations/sie_crewai/tests/test_tools.py@@ -2,6 +2,8 @@from __future__ import annotations+from unittest.mock import MagicMock+from sie_crewai import SIEExtractorTool, SIERerankerTool, SIESparseEmbedder@@ -50,6 +52,72 @@ class TestSIERerankerTool:# Should return all documentsassert result.count("[Score:") == len(research_documents)+ def test_rerank_maps_scores_by_item_id(self, mock_sie_client: object) -> None:+ """Top-ranked document is the relevant one, scores mapped by item_id."""+ documents = ["alpha", "bravo", "charlie", "delta", "echo"]+ # Ranked entries reference input positions via item_id (delta = index 3+ # is most relevant), out of input order.+ mock_sie_client.score = MagicMock(+ return_value={+ "model": "test-reranker",+ "scores": [+ {"item_id": "3", "score": 0.9, "rank": 0},+ {"item_id": "1", "score": 0.7, "rank": 1},+ {"item_id": "4", "score": 0.5, "rank": 2},+ {"item_id": "0", "score": 0.3, "rank": 3},+ {"item_id": "2", "score": 0.1, "rank": 4},+ ],+ }+ )+ reranker = SIERerankerTool(model="test-reranker")+ reranker._client = mock_sie_client++ result = reranker._run(query="query", documents=documents)++ # Ranked most-relevant first: delta, bravo, echo, alpha, charlie.+ assert (+ result.index("delta")+ < result.index("bravo")+ < result.index("echo")+ < result.index("alpha")+ < result.index("charlie")+ )+ assert "[Score: 0.9000] delta" in result+ # All five documents are represented (no duplication or loss).+ assert all(doc in result for doc in documents)++ def test_rerank_skips_malformed_item_id(self, mock_sie_client: object) -> None:+ """Malformed item_ids are skipped (no crash, no misassignment)."""+ documents = ["alpha", "bravo", "charlie"]+ # Only item_id "1" (bravo) is usable; the rest are malformed. The float+ # 1.5 and bool True come after the valid "1": if int() accepted them+ # (int(1.5) == 1, int(True) == 1) they would overwrite bravo's score.+ mock_sie_client.score = MagicMock(+ return_value={+ "model": "test-reranker",+ "scores": [+ {"item_id": "1", "score": 0.8, "rank": 0},+ {"item_id": "not-an-int", "score": 0.95, "rank": 1},+ {"item_id": "-1", "score": 0.9, "rank": 2},+ {"item_id": "99", "score": 0.7, "rank": 3},+ {"score": 0.5, "rank": 4},+ {"item_id": 1.5, "score": 0.99, "rank": 5},+ {"item_id": True, "score": 0.98, "rank": 6},+ ],+ }+ )+ reranker = SIERerankerTool(model="test-reranker")+ reranker._client = mock_sie_client++ result = reranker._run(query="query", documents=documents)++ # All three documents represented, none dropped or duplicated.+ assert result.count("[Score:") == 3+ assert "[Score: 0.8000] bravo" in result+ # bravo (the only scored doc) ranks first.+ assert result.index("bravo") < result.index("alpha")+ assert result.index("bravo") < result.index("charlie")+def test_custom_model(self, mock_sie_client: object, research_documents: list[str]) -> None:"""Test using a custom reranker model."""reranker = SIERerankerTool(model="custom/reranker-model")diff --git a/integrations/sie_dspy/README.md b/integrations/sie_dspy/README.mdindex 34d5e6c14..a845aec28 100644--- a/integrations/sie_dspy/README.md+++ b/integrations/sie_dspy/README.md@@ -137,7 +137,7 @@ result = rag("What is machine learning?")Start the SIE server before using this integration:```bash-mise run serve -d cpu -p 8080+mise run serve -- -d cpu -p 8080```## Testingdiff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.tomlindex 690bf17ac..347bfc27d 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.7.1"+version = "0.7.2"description = "SIE integration for DSPy"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_dspy/src/sie_dspy/modules.py b/integrations/sie_dspy/src/sie_dspy/modules.pyindex 9a46dc56f..bf6a1d9c2 100644--- a/integrations/sie_dspy/src/sie_dspy/modules.py+++ b/integrations/sie_dspy/src/sie_dspy/modules.py@@ -5,12 +5,50 @@ Provides reranking and extraction modules compatible with DSPy pipelines.from __future__ import annotations+from collections.abc import Mappingfrom dataclasses import dataclassfrom typing import Anyimport dspy+def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:+ """Map ScoreResult entries back to input positions by item_id.++ Parses each entry's ``item_id`` defensively: a missing, non-integer,+ negative, or out-of-range id is skipped (that passage keeps its 0.0+ default) so a malformed entry can neither crash the rerank nor mis-assign a+ score to the wrong passage.++ Args:+ results: ScoreResult envelope from ``SIEClient.score()``.+ count: Number of input passages.++ Returns:+ Scores indexed by input position (0.0 for any unscored/invalid item).+ """+ scores = [0.0] * count+ for entry in results.get("scores", []):+ item_id = entry.get("item_id", entry.get("index"))+ # Accept only a genuine integer or an integer string. Reject bool (an int+ # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer+ # strings, so a malformed id cannot silently overwrite the wrong position.+ if isinstance(item_id, bool):+ continue+ if isinstance(item_id, int):+ idx = item_id+ elif isinstance(item_id, str):+ try:+ idx = int(item_id)+ except ValueError:+ continue+ else:+ continue+ if 0 <= idx < count:+ scores[idx] = float(entry.get("score", 0.0))+ return scores++@dataclassclass Entity:"""Extracted entity with metadata."""@@ -134,11 +172,17 @@ class SIEReranker(dspy.Module):results = self.client.score(self._model, query_item, passage_items)+ # ``results`` is a ScoreResult envelope; ranked entries are under+ # ``results["scores"]`` (each a ScoreEntry keyed by ``item_id`` = input+ # position, plus ``score``). Map scores back to input order by item_id+ # rather than zipping positionally — the entries are sorted by relevance,+ # not by input order. ``results["request"]`` (request id) and+ # ``results["usage"]`` (token usage) are also available but intentionally+ # not surfaced here.+ score_by_index = _scores_by_index(results, len(passages))+# Build scored passages- scored = []- for passage, result in zip(passages, results, strict=True):- score = result.get("score", 0.0) if isinstance(result, dict) else getattr(result, "score", 0.0)- scored.append((float(score), passage))+ scored = [(score_by_index[idx], passage) for idx, passage in enumerate(passages)]# Sort by score descendingscored.sort(key=lambda x: x[0], reverse=True)diff --git a/integrations/sie_dspy/tests/conftest.py b/integrations/sie_dspy/tests/conftest.pyindex 2df020c55..886224078 100644--- a/integrations/sie_dspy/tests/conftest.py+++ b/integrations/sie_dspy/tests/conftest.py@@ -57,20 +57,24 @@ def _create_mock_encode_result(def _create_mock_score_result(query: str, items: list[dict]) -> list[dict[str, Any]]:- """Create mock score results."""+ """Create mock score results matching the ranked-envelope contract.++ The SDK's ScoreResult is sorted by descending score, so sort here too and+ assign ``rank`` from the sorted position (``item_id`` stays the original+ input index).+ """rng = np.random.default_rng(hash(query) % (2**32))scores = rng.uniform(0, 1, len(items))- results = []- for idx, score in enumerate(scores):- results.append(- {- "item_id": str(idx),- "score": float(score),- "rank": idx,- }- )- return results+ sorted_indices = np.argsort(scores)[::-1]+ return [+ {+ "item_id": str(idx),+ "score": float(scores[idx]),+ "rank": rank,+ }+ for rank, idx in enumerate(sorted_indices)+ ]def _create_mock_extract_result(text: str, labels: list[str]) -> list[dict[str, Any]]:@@ -130,10 +134,15 @@ def mock_sie_client() -> MagicMock:item_dicts = [{"text": _get_text(i)} for i in items]return _create_mock_encode_result(item_dicts, is_query=is_query, output_types=output_types)- def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> list[dict]:+ def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> dict[str, Any]:+ # Mirror the real SDK: a ScoreResult envelope with ranked entries under+ # "scores", not a bare list.query_text = _get_text(query)item_dicts = [{"id": str(idx), "text": _get_text(i)} for idx, i in enumerate(items)]- return _create_mock_score_result(query_text, item_dicts)+ return {+ "model": _model,+ "scores": _create_mock_score_result(query_text, item_dicts),+ }def mock_extract(_model: str, item: Any, labels: list[str], **_kwargs: Any) -> list[dict]:return _create_mock_extract_result(_get_text(item), labels)diff --git a/integrations/sie_dspy/tests/test_integration.py b/integrations/sie_dspy/tests/test_integration.pyindex 2142764f4..dd0a22ae4 100644--- a/integrations/sie_dspy/tests/test_integration.py+++ b/integrations/sie_dspy/tests/test_integration.py@@ -6,7 +6,7 @@ of DSPy workflows using SIE components.Run with: pytest -m integration integrations/sie_dspy/tests/Prerequisites:- mise run serve -d cpu -p 8080+ mise run serve -- -d cpu -p 8080DSPy Use Cases Demonstrated:- RAG pipelines with optimizable componentsdiff --git a/integrations/sie_dspy/tests/test_modules.py b/integrations/sie_dspy/tests/test_modules.pyindex f0f5f0bd9..c9ab673cf 100644--- a/integrations/sie_dspy/tests/test_modules.py+++ b/integrations/sie_dspy/tests/test_modules.py@@ -2,6 +2,9 @@from __future__ import annotations+from collections import Counter+from unittest.mock import MagicMock+import dspyfrom sie_dspy import SIEExtractor, SIERerankerfrom sie_dspy.modules import Entity@@ -55,6 +58,69 @@ class TestSIEReranker:assert len(result.passages) == len(ml_corpus)assert len(result.scores) == len(ml_corpus)+ # Every passage comes back exactly as many times as it went in (Counter+ # checks multiplicity, not just membership). The envelope bug tried to+ # zip passages against the ScoreResult dict's keys.+ assert Counter(result.passages) == Counter(ml_corpus)+ # Distinct and descending.+ assert result.scores == sorted(result.scores, reverse=True)+ assert len(set(result.scores)) == len(result.scores)++ def test_rerank_maps_scores_by_item_id(self, mock_sie_client: object) -> None:+ """Top-ranked passage is the relevant one, scores mapped by item_id."""+ passages = [f"doc-{i}" for i in range(5)]+ # Ranked entries reference input positions via item_id (doc-3 = index 3+ # is most relevant), out of input order.+ mock_sie_client.score = MagicMock(+ return_value={+ "model": "test-reranker",+ "scores": [+ {"item_id": "3", "score": 0.9, "rank": 0},+ {"item_id": "1", "score": 0.7, "rank": 1},+ {"item_id": "4", "score": 0.5, "rank": 2},+ {"item_id": "0", "score": 0.3, "rank": 3},+ {"item_id": "2", "score": 0.1, "rank": 4},+ ],+ }+ )+ reranker = SIEReranker(model="test-reranker")+ reranker._client = mock_sie_client++ result = reranker(query="query", passages=passages)++ assert result.passages == ["doc-3", "doc-1", "doc-4", "doc-0", "doc-2"]+ assert result.scores == [0.9, 0.7, 0.5, 0.3, 0.1]++ def test_rerank_skips_malformed_item_id(self, mock_sie_client: object) -> None:+ """Malformed item_ids are skipped (no crash, no misassignment)."""+ passages = [f"doc-{i}" for i in range(3)]+ # Only item_id "1" is usable; the rest are malformed. The float 1.5 and+ # bool True come after the valid "1": if int() accepted them+ # (int(1.5) == 1, int(True) == 1) they would overwrite doc-1's score.+ mock_sie_client.score = MagicMock(+ return_value={+ "model": "test-reranker",+ "scores": [+ {"item_id": "1", "score": 0.8, "rank": 0},+ {"item_id": "not-an-int", "score": 0.95, "rank": 1},+ {"item_id": "-1", "score": 0.9, "rank": 2},+ {"item_id": "99", "score": 0.7, "rank": 3},+ {"score": 0.5, "rank": 4},+ {"item_id": 1.5, "score": 0.99, "rank": 5},+ {"item_id": True, "score": 0.98, "rank": 6},+ ],+ }+ )+ reranker = SIEReranker(model="test-reranker")+ reranker._client = mock_sie_client++ result = reranker(query="query", passages=passages)++ assert len(result.passages) == 3+ assert Counter(result.passages) == Counter(["doc-0", "doc-1", "doc-2"])+ by_passage = dict(zip(result.passages, result.scores, strict=True))+ assert by_passage == {"doc-1": 0.8, "doc-0": 0.0, "doc-2": 0.0}+ assert result.passages[0] == "doc-1"def test_rerank_k_larger_than_passages(self, mock_sie_client: object) -> None:"""Test reranking when k is larger than passage count."""diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.tomlindex c3283de37..325c81d54 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.7.1"+version = "0.7.2"description = "SIE integration for Haystack"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_haystack/src/sie_haystack/rankers.py b/integrations/sie_haystack/src/sie_haystack/rankers.pyindex cbe42beb9..f37970236 100644--- a/integrations/sie_haystack/src/sie_haystack/rankers.py+++ b/integrations/sie_haystack/src/sie_haystack/rankers.py@@ -5,11 +5,49 @@ Provides SIERanker for reranking documents by relevance to a query.from __future__ import annotations+from collections.abc import Mappingfrom typing import Anyfrom haystack import Document, component+def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:+ """Map ScoreResult entries back to input positions by item_id.++ Parses each entry's ``item_id`` defensively: a missing, non-integer,+ negative, or out-of-range id is skipped (that document keeps its 0.0+ default) so a malformed entry can neither crash the rerank nor mis-assign a+ score to the wrong document.++ Args:+ results: ScoreResult envelope from ``SIEClient.score()``.+ count: Number of input documents.++ Returns:+ Scores indexed by input position (0.0 for any unscored/invalid item).+ """+ scores = [0.0] * count+ for entry in results.get("scores", []):+ item_id = entry.get("item_id", entry.get("index"))+ # Accept only a genuine integer or an integer string. Reject bool (an int+ # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer+ # strings, so a malformed id cannot silently overwrite the wrong position.+ if isinstance(item_id, bool):+ continue+ if isinstance(item_id, int):+ idx = item_id+ elif isinstance(item_id, str):+ try:+ idx = int(item_id)+ except ValueError:+ continue+ else:+ continue+ if 0 <= idx < count:+ scores[idx] = float(entry.get("score", 0.0))+ return scores++@componentclass SIERanker:"""Reranks documents by relevance to a query using SIE.@@ -108,10 +146,19 @@ class SIERanker:# Score documentsresults = self.client.score(self._model, query_item, doc_items)+ # ``results`` is a ScoreResult envelope; ranked entries are under+ # ``results["scores"]`` (each a ScoreEntry keyed by ``item_id`` = input+ # position, plus ``score``). Map scores back to input order by item_id+ # rather than zipping positionally — the entries are sorted by relevance,+ # not by input order. The envelope also carries ``results["request"]``+ # (request id) and ``results["usage"]`` (token usage); those are+ # available but intentionally not surfaced through the Haystack contract.+ score_by_index = _scores_by_index(results, len(documents))+# Build scored documentsscored_docs = []- for doc, result in zip(documents, results, strict=True):- score = self._extract_score(result)+ for idx, doc in enumerate(documents):+ score = score_by_index[idx]# Store score in document metadatadoc_with_score = Document(id=doc.id,@@ -131,9 +178,3 @@ class SIERanker:ranked_docs = ranked_docs[:effective_top_k]return {"documents": ranked_docs}-- def _extract_score(self, result: Any) -> float:- """Extract score from SDK result."""- if isinstance(result, dict):- return float(result.get("score", 0.0))- return float(getattr(result, "score", 0.0))diff --git a/integrations/sie_haystack/tests/conftest.py b/integrations/sie_haystack/tests/conftest.pyindex f2a4934d0..ba2ece611 100644--- a/integrations/sie_haystack/tests/conftest.py+++ b/integrations/sie_haystack/tests/conftest.py@@ -155,13 +155,18 @@ def mock_sie_client() -> MagicMock:for item in items]- def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> list[dict]:+ def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> dict[str, Any]:+ # Mirror the real SDK: a ScoreResult envelope with ranked entries under+ # "scores", not a bare list.query_text = _get_text(query)item_dicts = [{"id": i.get("id", str(idx)) if isinstance(i, dict) else str(idx), "text": _get_text(i)}for idx, i in enumerate(items)]- return _create_mock_score_result(query_text, item_dicts, kwargs.get("top_k"))+ return {+ "model": _model,+ "scores": _create_mock_score_result(query_text, item_dicts, kwargs.get("top_k")),+ }def mock_extract(_model: str, items: Any, labels: list[str], **_kwargs: Any) -> list[dict]:# Extract always returns a list of entities for Haystackdiff --git a/integrations/sie_haystack/tests/test_integration.py b/integrations/sie_haystack/tests/test_integration.pyindex da124acd2..26c2fa525 100644--- a/integrations/sie_haystack/tests/test_integration.py+++ b/integrations/sie_haystack/tests/test_integration.py@@ -4,7 +4,7 @@ These tests require a running SIE server and serve as runnable examples.Run with: pytest -m integration integrations/sie_haystack/tests/Prerequisites:- mise run serve -d cpu -p 8080+ mise run serve -- -d cpu -p 8080"""from __future__ import annotationsdiff --git a/integrations/sie_haystack/tests/test_rankers.py b/integrations/sie_haystack/tests/test_rankers.pyindex c7b2deae4..a876d73ca 100644--- a/integrations/sie_haystack/tests/test_rankers.py+++ b/integrations/sie_haystack/tests/test_rankers.py@@ -2,9 +2,42 @@from __future__ import annotations+from collections import Counter+from unittest.mock import MagicMock+from haystack import Documentfrom sie_haystack import SIERanker+# Ranked entries reference input positions via item_id, out of input order and+# sorted by relevance (doc-3 most relevant).+_RANKED_ENVELOPE = {+ "model": "test-reranker",+ "scores": [+ {"item_id": "3", "score": 0.9, "rank": 0},+ {"item_id": "1", "score": 0.7, "rank": 1},+ {"item_id": "4", "score": 0.5, "rank": 2},+ {"item_id": "0", "score": 0.3, "rank": 3},+ {"item_id": "2", "score": 0.1, "rank": 4},+ ],+}++# Envelope for three inputs where only item_id "1" is usable; the rest are+# malformed and must be skipped without crashing so their inputs keep the 0.0+# default. The float 1.5 and bool True come AFTER the valid "1": if int()+# accepted them (int(1.5) == 1, int(True) == 1) they would overwrite position 1.+_MALFORMED_ENVELOPE = {+ "model": "test-reranker",+ "scores": [+ {"item_id": "1", "score": 0.8, "rank": 0},+ {"item_id": "not-an-int", "score": 0.95, "rank": 1},+ {"item_id": "-1", "score": 0.9, "rank": 2},+ {"item_id": "99", "score": 0.7, "rank": 3},+ {"score": 0.5, "rank": 4},+ {"item_id": 1.5, "score": 0.99, "rank": 5},+ {"item_id": True, "score": 0.98, "rank": 6},+ ],+}+class TestSIERanker:"""Tests for SIERanker component."""@@ -22,11 +55,44 @@ class TestSIERanker:result = ranker.run(query=test_query, documents=haystack_documents)assert "documents" in result- assert len(result["documents"]) == len(haystack_documents)- # All results should have scores in metadata- for doc in result["documents"]:- assert "score" in doc.meta- assert isinstance(doc.meta["score"], float)+ docs = result["documents"]+ # Every input document comes back exactly as many times as it went in+ # (Counter checks multiplicity, not just membership). The envelope bug+ # tried to zip documents against the ScoreResult dict's keys.+ assert len(docs) == len(haystack_documents)+ assert Counter(d.content for d in docs) == Counter(d.content for d in haystack_documents)+ scores = [d.meta["score"] for d in docs]+ assert all(isinstance(s, float) for s in scores)+ # Distinct and descending.+ assert scores == sorted(scores, reverse=True)+ assert len(set(scores)) == len(scores)++ def test_run_maps_scores_by_item_id(self, mock_sie_client: object) -> None:+ """Top-ranked document is the relevant one, scores mapped by item_id."""+ documents = [Document(content=f"doc-{i}") for i in range(5)]+ mock_sie_client.score = MagicMock(return_value=_RANKED_ENVELOPE)+ ranker = SIERanker(model="test-reranker")+ ranker._client = mock_sie_client++ ranked = ranker.run(query="query", documents=documents)["documents"]++ assert [d.content for d in ranked] == ["doc-3", "doc-1", "doc-4", "doc-0", "doc-2"]+ assert ranked[0].meta["score"] == 0.9+ assert [d.meta["score"] for d in ranked] == [0.9, 0.7, 0.5, 0.3, 0.1]++ def test_run_skips_malformed_item_id(self, mock_sie_client: object) -> None:+ """Malformed item_ids are skipped (no crash, no misassignment)."""+ documents = [Document(content=f"doc-{i}") for i in range(3)]+ mock_sie_client.score = MagicMock(return_value=_MALFORMED_ENVELOPE)+ ranker = SIERanker(model="test-reranker")+ ranker._client = mock_sie_client++ ranked = ranker.run(query="query", documents=documents)["documents"]++ assert len(ranked) == 3+ by_content = {d.content: d.meta["score"] for d in ranked}+ assert by_content == {"doc-1": 0.8, "doc-0": 0.0, "doc-2": 0.0}+ assert ranked[0].content == "doc-1"def test_run_empty_list(self, mock_sie_client: object) -> None:"""Test that run handles empty document list."""diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.tomlindex 6b4e1d7ed..6447f7601 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.7.1"+version = "0.7.2"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_lancedb/tests/test_integration.py b/integrations/sie_lancedb/tests/test_integration.pyindex 16c7e54a8..131028bd1 100644--- a/integrations/sie_lancedb/tests/test_integration.py+++ b/integrations/sie_lancedb/tests/test_integration.py@@ -6,7 +6,7 @@ of LanceDB workflows using SIE embeddings, reranking, and extraction.Run with: pytest -m integration integrations/sie_lancedb/tests/Prerequisites:- mise run serve -d cpu -p 8080+ mise run serve -- -d cpu -p 8080"""from __future__ import annotationsdiff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 34a74fdaf..0dce46fd9 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.7.1"+version = "0.7.2"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_langchain/src/sie_langchain/rerankers.py b/integrations/sie_langchain/src/sie_langchain/rerankers.pyindex 539c15c20..5cbdb9f0e 100644--- a/integrations/sie_langchain/src/sie_langchain/rerankers.py+++ b/integrations/sie_langchain/src/sie_langchain/rerankers.py@@ -13,11 +13,48 @@ from langchain_core.documents.compressor import BaseDocumentCompressorfrom pydantic import ConfigDictif TYPE_CHECKING:- from collections.abc import Sequence+ from collections.abc import Mapping, Sequencefrom sie_sdk import SIEAsyncClient, SIEClient+def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:+ """Map ScoreResult entries back to input positions by item_id.++ Parses each entry's ``item_id`` defensively: a missing, non-integer,+ negative, or out-of-range id is skipped (that input keeps its 0.0 default)+ so a malformed entry can neither crash the rerank nor mis-assign a score to+ the wrong input.++ Args:+ results: ScoreResult envelope from ``SIEClient.score()``.+ count: Number of input items.++ Returns:+ Scores indexed by input position (0.0 for any unscored/invalid item).+ """+ scores = [0.0] * count+ for entry in results.get("scores", []):+ item_id = entry.get("item_id", entry.get("index"))+ # Accept only a genuine integer or an integer string. Reject bool (an int+ # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer+ # strings, so a malformed id cannot silently overwrite the wrong position.+ if isinstance(item_id, bool):+ continue+ if isinstance(item_id, int):+ idx = item_id+ elif isinstance(item_id, str):+ try:+ idx = int(item_id)+ except ValueError:+ continue+ else:+ continue+ if 0 <= idx < count:+ scores[idx] = float(entry.get("score", 0.0))+ return scores++class SIEReranker(BaseDocumentCompressor):"""LangChain document compressor using SIE's reranking.@@ -174,39 +211,32 @@ class SIEReranker(BaseDocumentCompressor):return reranked[: self.top_k]return reranked- def _build_reranked_documents(self, documents: Sequence[Document], results: list[Any]) -> list[Document]:+ def _build_reranked_documents(self, documents: Sequence[Document], results: Mapping[str, Any]) -> list[Document]:"""Build reranked documents from score results.Args:documents: Original documents.- results: Score results from SIE.+ results: ScoreResult envelope from ``SIEClient.score()``. Ranked+ entries live under ``results["scores"]`` (each a ScoreEntry with+ ``item_id`` = input position and ``score``), already sorted by+ relevance descending. The envelope also carries+ ``results["request"]`` (request id) and ``results["usage"]``+ (token usage); those are available but intentionally not plumbed+ through the LangChain contract.Returns:- Reranked documents with scores.+ Reranked documents (relevance descending) with scores in metadata."""- reranked = []-- for result in results:- # Handle dict or object result- if isinstance(result, dict):- idx = result.get("item_id", result.get("index", 0))- score = result.get("score", 0.0)- else:- idx = getattr(result, "item_id", getattr(result, "index", 0))- score = getattr(result, "score", 0.0)-- # Parse index if it's a string- if isinstance(idx, str):- idx = int(idx)-- if idx < len(documents):- doc = documents[idx]- # Create new document with score in metadata- reranked.append(- Document(- page_content=doc.page_content,- metadata={**doc.metadata, "relevance_score": float(score)},- )- )-- return reranked+ # Map each ScoreEntry back to its input position by item_id. Parse+ # defensively: a missing, non-integer, negative, or out-of-range id is+ # skipped (its document keeps the 0.0 default) rather than crashing the+ # whole rerank or mis-assigning a score to the wrong document.+ scores = _scores_by_index(results, len(documents))+ order = sorted(range(len(documents)), key=lambda i: scores[i], reverse=True)+ return [+ Document(+ page_content=documents[i].page_content,+ metadata={**documents[i].metadata, "relevance_score": scores[i]},+ )+ for i in order+ ]diff --git a/integrations/sie_langchain/tests/test_integration.py b/integrations/sie_langchain/tests/test_integration.pyindex e0ee44896..3f7e71f9f 100644--- a/integrations/sie_langchain/tests/test_integration.py+++ b/integrations/sie_langchain/tests/test_integration.py@@ -4,7 +4,7 @@ These tests require a running SIE server and serve as runnable examples.Run with: pytest -m integration integrations/sie_langchain/tests/Prerequisites:- mise run serve -d cpu -p 8080+ mise run serve -- -d cpu -p 8080"""from __future__ import annotations@@ -192,6 +192,12 @@ class TestRerankerIntegration:# Scores should be in descending orderscores = [d.metadata["relevance_score"] for d in reranked]assert scores == sorted(scores, reverse=True)+ # Scores must be distinct, not all 0.0. The envelope-read bug returned the+ # same document duplicated at 0.0, which still satisfied len==3 and the+ # sorted() check above — so assert real, distinct relevance here.+ assert len(set(scores)) == len(scores)+ # The semantically most relevant document ranks first for this query.+ assert reranked[0].page_content == "Semantic search understands meaning."class TestRAGPipelineIntegration:diff --git a/integrations/sie_langchain/tests/test_rerankers.py b/integrations/sie_langchain/tests/test_rerankers.pyindex a6a1d5ba5..64f127fd7 100644--- a/integrations/sie_langchain/tests/test_rerankers.py+++ b/integrations/sie_langchain/tests/test_rerankers.py@@ -2,10 +2,43 @@from __future__ import annotations+from collections import Counter+from unittest.mock import MagicMock+import pytestfrom langchain_core.documents import Documentfrom sie_langchain import SIEReranker+# Ranked entries reference input positions via item_id, out of input order and+# sorted by relevance (doc-3 most relevant). Shared across the mapping tests.+_RANKED_ENVELOPE = {+ "model": "test-reranker",+ "scores": [+ {"item_id": "3", "score": 0.9, "rank": 0},+ {"item_id": "1", "score": 0.7, "rank": 1},+ {"item_id": "4", "score": 0.5, "rank": 2},+ {"item_id": "0", "score": 0.3, "rank": 3},+ {"item_id": "2", "score": 0.1, "rank": 4},+ ],+}++# Envelope for three inputs where only item_id "1" is usable; the rest are+# malformed and must be skipped without crashing so their inputs keep the 0.0+# default. The float 1.5 and bool True come AFTER the valid "1": if int()+# accepted them (int(1.5) == 1, int(True) == 1) they would overwrite position 1.+_MALFORMED_ENVELOPE = {+ "model": "test-reranker",+ "scores": [+ {"item_id": "1", "score": 0.8, "rank": 0},+ {"item_id": "not-an-int", "score": 0.95, "rank": 1},+ {"item_id": "-1", "score": 0.9, "rank": 2},+ {"item_id": "99", "score": 0.7, "rank": 3},+ {"score": 0.5, "rank": 4},+ {"item_id": 1.5, "score": 0.99, "rank": 5},+ {"item_id": True, "score": 0.98, "rank": 6},+ ],+}+class TestSIEReranker:"""Tests for SIEReranker class."""@@ -17,11 +50,42 @@ class TestSIEReranker:result = reranker.compress_documents(documents, "test query")- assert len(result) > 0- # All results should have relevance_score in metadata- for doc in result:- assert "relevance_score" in doc.metadata- assert isinstance(doc.metadata["relevance_score"], float)+ # Every input document comes back exactly as many times as it went in+ # (Counter checks multiplicity, not just membership). The envelope bug+ # iterated the ScoreResult dict's keys, returning documents[0] duplicated.+ assert len(result) == len(documents)+ assert Counter(d.page_content for d in result) == Counter(d.page_content for d in documents)+ scores = [doc.metadata["relevance_score"] for doc in result]+ assert all(isinstance(s, float) for s in scores)+ # Distinct and descending — the bug produced identical 0.0 scores.+ assert scores == sorted(scores, reverse=True)+ assert len(set(scores)) == len(scores)++ def test_compress_documents_maps_scores_by_item_id(self, mock_sie_client: object) -> None:+ """Top-ranked document is the relevant one, scores mapped by item_id."""+ documents = [Document(page_content=f"doc-{i}") for i in range(5)]+ mock_sie_client.score = MagicMock(return_value=_RANKED_ENVELOPE)+ reranker = SIEReranker(client=mock_sie_client, model="test-reranker")++ result = reranker.compress_documents(documents, "query")++ assert [d.page_content for d in result] == ["doc-3", "doc-1", "doc-4", "doc-0", "doc-2"]+ assert result[0].metadata["relevance_score"] == 0.9+ assert [d.metadata["relevance_score"] for d in result] == [0.9, 0.7, 0.5, 0.3, 0.1]++ def test_compress_documents_skips_malformed_item_id(self, mock_sie_client: object) -> None:+ """Malformed item_ids are skipped (no crash, no misassignment)."""+ documents = [Document(page_content=f"doc-{i}") for i in range(3)]+ mock_sie_client.score = MagicMock(return_value=_MALFORMED_ENVELOPE)+ reranker = SIEReranker(client=mock_sie_client, model="test-reranker")++ result = reranker.compress_documents(documents, "query")++ assert len(result) == 3+ assert Counter(d.page_content for d in result) == Counter(["doc-0", "doc-1", "doc-2"])+ by_content = {d.page_content: d.metadata["relevance_score"] for d in result}+ assert by_content == {"doc-1": 0.8, "doc-0": 0.0, "doc-2": 0.0}+ assert result[0].page_content == "doc-1"def test_compress_documents_empty(self, mock_sie_client: object) -> None:"""Test reranking empty list returns empty."""diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex 8e8ca7e6c..c907abca1 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.7.1"+version = "0.7.2"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/src/sie_llamaindex/rerankers.py b/integrations/sie_llamaindex/src/sie_llamaindex/rerankers.pyindex 7bca0ff26..94d1b15ba 100644--- a/integrations/sie_llamaindex/src/sie_llamaindex/rerankers.py+++ b/integrations/sie_llamaindex/src/sie_llamaindex/rerankers.py@@ -12,9 +12,48 @@ from llama_index.core.postprocessor.types import BaseNodePostprocessorfrom llama_index.core.schema import NodeWithScore, QueryBundleif TYPE_CHECKING:+ from collections.abc import Mapping+from sie_sdk import SIEAsyncClient, SIEClient+def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:+ """Map ScoreResult entries back to input positions by item_id.++ Parses each entry's ``item_id`` defensively: a missing, non-integer,+ negative, or out-of-range id is skipped (that input keeps its 0.0 default)+ so a malformed entry can neither crash the rerank nor mis-assign a score to+ the wrong input.++ Args:+ results: ScoreResult envelope from ``SIEClient.score()``.+ count: Number of input items.++ Returns:+ Scores indexed by input position (0.0 for any unscored/invalid item).+ """+ scores = [0.0] * count+ for entry in results.get("scores", []):+ item_id = entry.get("item_id", entry.get("index"))+ # Accept only a genuine integer or an integer string. Reject bool (an int+ # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer+ # strings, so a malformed id cannot silently overwrite the wrong position.+ if isinstance(item_id, bool):+ continue+ if isinstance(item_id, int):+ idx = item_id+ elif isinstance(item_id, str):+ try:+ idx = int(item_id)+ except ValueError:+ continue+ else:+ continue+ if 0 <= idx < count:+ scores[idx] = float(entry.get("score", 0.0))+ return scores++class SIENodePostprocessor(BaseNodePostprocessor):"""LlamaIndex node postprocessor using SIE's reranking.@@ -154,40 +193,27 @@ class SIENodePostprocessor(BaseNodePostprocessor):def _build_reranked_nodes(self,nodes: list[NodeWithScore],- results: list[Any],+ results: Mapping[str, Any],) -> list[NodeWithScore]:"""Build reranked nodes from score results.Args:nodes: Original nodes.- results: Score results from SIE.+ results: ScoreResult envelope from ``SIEClient.score()``. Ranked+ entries live under ``results["scores"]`` (each a ScoreEntry with+ ``item_id`` = input position and ``score``), already sorted by+ relevance descending. The envelope also exposes+ ``results["request"]`` (request id) and ``results["usage"]``+ (token usage); those are available but intentionally not plumbed+ through the LlamaIndex contract.Returns:- Reranked nodes with new scores.+ Reranked nodes (relevance descending) with new scores."""- reranked = []-- for result in results:- # Handle dict or object result- if isinstance(result, dict):- idx = result.get("item_id", result.get("index", 0))- score = result.get("score", 0.0)- else:- idx = getattr(result, "item_id", getattr(result, "index", 0))- score = getattr(result, "score", 0.0)-- # Parse index if it's a string- if isinstance(idx, str):- idx = int(idx)-- if idx < len(nodes):- original_node = nodes[idx]- # Create new NodeWithScore with updated score- reranked.append(- NodeWithScore(- node=original_node.node,- score=float(score),- )- )-- return reranked+ # Map each ScoreEntry back to its input position by item_id. Parse+ # defensively: a missing, non-integer, negative, or out-of-range id is+ # skipped (its node keeps the 0.0 default) rather than crashing the whole+ # rerank or mis-assigning a score to the wrong node.+ scores = _scores_by_index(results, len(nodes))+ order = sorted(range(len(nodes)), key=lambda i: scores[i], reverse=True)+ return [NodeWithScore(node=nodes[i].node, score=scores[i]) for i in order]diff --git a/integrations/sie_llamaindex/tests/test_integration.py b/integrations/sie_llamaindex/tests/test_integration.pyindex f37674333..eee965c69 100644--- a/integrations/sie_llamaindex/tests/test_integration.py+++ b/integrations/sie_llamaindex/tests/test_integration.py@@ -4,7 +4,7 @@ These tests require a running SIE server and serve as runnable examples.Run with: pytest -m integration integrations/sie_llamaindex/tests/Prerequisites:- mise run serve -d cpu -p 8080+ mise run serve -- -d cpu -p 8080"""from __future__ import annotationsdiff --git a/integrations/sie_llamaindex/tests/test_rerankers.py b/integrations/sie_llamaindex/tests/test_rerankers.pyindex 8018cc18e..d02a2bae0 100644--- a/integrations/sie_llamaindex/tests/test_rerankers.py+++ b/integrations/sie_llamaindex/tests/test_rerankers.py@@ -2,9 +2,42 @@from __future__ import annotations+from collections import Counter+from unittest.mock import MagicMock+from llama_index.core.schema import NodeWithScore, QueryBundle, TextNodefrom sie_llamaindex import SIENodePostprocessor+# Ranked entries reference input positions via item_id, out of input order and+# sorted by relevance (doc-3 most relevant).+_RANKED_ENVELOPE = {+ "model": "test-reranker",+ "scores": [+ {"item_id": "3", "score": 0.9, "rank": 0},+ {"item_id": "1", "score": 0.7, "rank": 1},+ {"item_id": "4", "score": 0.5, "rank": 2},+ {"item_id": "0", "score": 0.3, "rank": 3},+ {"item_id": "2", "score": 0.1, "rank": 4},+ ],+}++# Envelope for three inputs where only item_id "1" is usable; the rest are+# malformed and must be skipped without crashing so their inputs keep the 0.0+# default. The float 1.5 and bool True come AFTER the valid "1": if int()+# accepted them (int(1.5) == 1, int(True) == 1) they would overwrite position 1.+_MALFORMED_ENVELOPE = {+ "model": "test-reranker",+ "scores": [+ {"item_id": "1", "score": 0.8, "rank": 0},+ {"item_id": "not-an-int", "score": 0.95, "rank": 1},+ {"item_id": "-1", "score": 0.9, "rank": 2},+ {"item_id": "99", "score": 0.7, "rank": 3},+ {"score": 0.5, "rank": 4},+ {"item_id": 1.5, "score": 0.99, "rank": 5},+ {"item_id": True, "score": 0.98, "rank": 6},+ ],+}+class TestSIENodePostprocessor:"""Tests for SIENodePostprocessor class."""@@ -19,11 +52,43 @@ class TestSIENodePostprocessor:result = postprocessor._postprocess_nodes(nodes, query_bundle)- assert len(result) > 0- # All results should have scores- for node in result:- assert node.score is not None- assert isinstance(node.score, float)+ # Every input node comes back exactly as many times as it went in+ # (Counter checks multiplicity, not just membership). The envelope bug+ # iterated the ScoreResult dict's keys, returning nodes[0] duplicated.+ assert len(result) == len(nodes)+ assert Counter(n.node.get_content() for n in result) == Counter(n.node.get_content() for n in nodes)+ scores = [n.score for n in result]+ assert all(isinstance(s, float) for s in scores)+ # Distinct and descending — the bug produced identical 0.0 scores.+ assert scores == sorted(scores, reverse=True)+ assert len(set(scores)) == len(scores)++ def test_postprocess_nodes_maps_scores_by_item_id(self, mock_sie_client: object) -> None:+ """Top-ranked node is the relevant one, scores mapped by item_id."""+ nodes = [NodeWithScore(node=TextNode(text=f"doc-{i}"), score=0.5) for i in range(5)]+ mock_sie_client.score = MagicMock(return_value=_RANKED_ENVELOPE)+ postprocessor = SIENodePostprocessor(model="test-reranker")+ postprocessor._client = mock_sie_client++ result = postprocessor._postprocess_nodes(nodes, QueryBundle(query_str="query"))++ assert [n.node.get_content() for n in result] == ["doc-3", "doc-1", "doc-4", "doc-0", "doc-2"]+ assert result[0].score == 0.9+ assert [n.score for n in result] == [0.9, 0.7, 0.5, 0.3, 0.1]++ def test_postprocess_nodes_skips_malformed_item_id(self, mock_sie_client: object) -> None:+ """Malformed item_ids are skipped (no crash, no misassignment)."""+ nodes = [NodeWithScore(node=TextNode(text=f"doc-{i}"), score=0.5) for i in range(3)]+ mock_sie_client.score = MagicMock(return_value=_MALFORMED_ENVELOPE)+ postprocessor = SIENodePostprocessor(model="test-reranker")+ postprocessor._client = mock_sie_client++ result = postprocessor._postprocess_nodes(nodes, QueryBundle(query_str="query"))++ assert len(result) == 3+ by_content = {n.node.get_content(): n.score for n in result}+ assert by_content == {"doc-1": 0.8, "doc-0": 0.0, "doc-2": 0.0}+ assert result[0].node.get_content() == "doc-1"def test_postprocess_nodes_empty(self, mock_sie_client: object) -> None:"""Test reranking empty list returns empty."""diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 703d46d51..3c90b9f91 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.7.1"+version = "0.7.2"description = "SIE integration for Qdrant"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_qdrant/tests/test_integration.py b/integrations/sie_qdrant/tests/test_integration.pyindex a55ddd518..05ed40ee7 100644--- a/integrations/sie_qdrant/tests/test_integration.py+++ b/integrations/sie_qdrant/tests/test_integration.py@@ -6,7 +6,7 @@ Run with: pytest -m integration integrations/sie_qdrant/tests/Prerequisites:# SIE server- mise run serve -d cpu -p 8080+ mise run serve -- -d cpu -p 8080# Qdrant (Docker)docker run -d -p 6333:6333 -p 6334:6334 qdrant/qdrant:v1.13.2diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.jsonindex ffb1d4eb3..e97dbcb60 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.7.1",+ "version": "0.7.2","description": "SIE embedding function for ChromaDB","type": "module","main": "./dist/index.cjs",@@ -54,7 +54,7 @@"license": "MIT","repository": {"type": "git",- "url": "https://github.com/superlinked/sie-internal.git",+ "url": "https://github.com/superlinked/sie.git","directory": "integrations/sie_ts_chroma"},"publishConfig": {diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.jsonindex f75ab02bc..a640f9271 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.7.1",+ "version": "0.7.2","description": "SIE embedding function and reranker for LanceDB","type": "module","main": "./dist/index.cjs",@@ -56,7 +56,7 @@"license": "MIT","repository": {"type": "git",- "url": "https://github.com/superlinked/sie-internal.git",+ "url": "https://github.com/superlinked/sie.git","directory": "integrations/sie_ts_lancedb"},"publishConfig": {diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.jsonindex 617f0921d..a57360e61 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.7.1",+ "version": "0.7.2","description": "SIE embeddings integration for LangChain.js","type": "module","main": "./dist/index.cjs",@@ -53,7 +53,7 @@"license": "MIT","repository": {"type": "git",- "url": "https://github.com/superlinked/sie-internal.git",+ "url": "https://github.com/superlinked/sie.git","directory": "integrations/sie_ts_langchain"},"publishConfig": {diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.jsonindex 4a421bfe0..a0f05489d 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.7.1",+ "version": "0.7.2","description": "SIE embeddings integration for LlamaIndex.TS","type": "module","main": "./dist/index.cjs",@@ -54,7 +54,7 @@"license": "MIT","repository": {"type": "git",- "url": "https://github.com/superlinked/sie-internal.git",+ "url": "https://github.com/superlinked/sie.git","directory": "integrations/sie_ts_llamaindex"},"publishConfig": {diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.tomlindex f9e03b4f9..dfc6b1163 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.7.1"+version = "0.7.2"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_weaviate/tests/test_integration.py b/integrations/sie_weaviate/tests/test_integration.pyindex 83b57b3ce..d3e65942a 100644--- a/integrations/sie_weaviate/tests/test_integration.py+++ b/integrations/sie_weaviate/tests/test_integration.py@@ -6,7 +6,7 @@ Run with: pytest -m integration integrations/sie_weaviate/tests/Prerequisites:# SIE server- mise run serve -d cpu -p 8080+ mise run serve -- -d cpu -p 8080# Weaviate (Docker)docker run -d -p 8090:8080 -p 50051:50051 \diff --git a/mise.toml b/mise.tomlnew file mode 100644index 000000000..0a5f6dd74--- /dev/null+++ b/mise.toml@@ -0,0 +1,31 @@+[settings]+experimental = true++[tools]+python = "3.12.12"+uv = "0.5.31"+rust = { version = "1.97.0", profile = "default", components = ["rustfmt", "clippy", "llvm-tools-preview"] }+"cargo:cargo-deny" = "0.20.2"+"cargo:cargo-llvm-cov" = "0.8.7"+node = ["24.12.0", "22.23.2"]+pnpm = "9.15.9"+helm = "3.16.4"++[env]+MISE_CACHE_DIR = "{{config_root}}/.cache/mise"+MISE_CONFIG_DIR = "{{config_root}}/.cache/mise-config"+MISE_DATA_DIR = "{{config_root}}/.cache/mise-data"+MISE_GLOBAL_CONFIG_FILE = "{{config_root}}/.cache/mise-config/config.toml"+MISE_GLOBAL_CONFIG_ROOT = "{{config_root}}"+MISE_PROJECT_ROOT = "{{config_root}}"+MISE_TRUSTED_CONFIG_PATHS = "{{config_root}}:{{env.HOME}}/.config/mise"+MISE_IGNORED_CONFIG_PATHS = "{{env.HOME}}/.config/mise"+MISE_STATE_DIR = "{{config_root}}/.cache/mise-state"+MISE_SYSTEM_CONFIG_FILE = "{{config_root}}/.cache/mise-config/system.toml"+UV_CACHE_DIR = "{{env.HOME}}/.cache/sie/uv"+XDG_CACHE_HOME = "{{env.HOME}}/.cache/sie/xdg-cache"+XDG_CONFIG_HOME = "{{config_root}}/.cache/xdg-config"+XDG_STATE_HOME = "{{config_root}}/.cache/xdg-state"++[task_config]+includes = ["tools/mise_tasks"]diff --git a/packages/sie_audio_prep/Cargo.toml b/packages/sie_audio_prep/Cargo.tomlindex c5eece835..11d5dfde2 100644--- a/packages/sie_audio_prep/Cargo.toml+++ b/packages/sie_audio_prep/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-audio-prep"-version = "0.7.1"+version = "0.7.2"edition = "2021"license = "Apache-2.0"description = "Bounded, shared audio decoding and resampling for SIE workers."diff --git a/packages/sie_audio_prep/build_wheel.py b/packages/sie_audio_prep/build_wheel.pyindex b196d47cc..4c61c2f0b 100644--- a/packages/sie_audio_prep/build_wheel.py+++ b/packages/sie_audio_prep/build_wheel.py@@ -16,7 +16,7 @@ import zipfilefrom pathlib import PathMATURIN_VERSION = "1.13.3"-AUDIO_PREP_VERSION = "0.7.1" # x-release-please-version+AUDIO_PREP_VERSION = "0.7.2" # x-release-please-versionAUDIO_WHEEL_COMPATIBILITY = "manylinux_2_28"AUDIO_WHEEL_FILENAME = f"sie_audio_prep-{AUDIO_PREP_VERSION}-cp312-abi3-{AUDIO_WHEEL_COMPATIBILITY}_x86_64.whl"AUDIO_WHEEL_REMOTE = f"/opt/sie/wheels/{AUDIO_WHEEL_FILENAME}"diff --git a/packages/sie_audio_prep/pyproject.toml b/packages/sie_audio_prep/pyproject.tomlindex 2929995f0..cdcec896b 100644--- a/packages/sie_audio_prep/pyproject.toml+++ b/packages/sie_audio_prep/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "maturin"[project]name = "sie-audio-prep"-version = "0.7.1"+version = "0.7.2"description = "Bounded, shared audio decoding and resampling for SIE workers."requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_config/Dockerfile b/packages/sie_config/Dockerfileindex 67c335d38..335ee81dd 100644--- a/packages/sie_config/Dockerfile+++ b/packages/sie_config/Dockerfile@@ -42,7 +42,8 @@ RUN find .venv -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || trueFROM python:3.12-slim AS runtime# Create non-root user-RUN useradd --create-home --shell /bin/bash sie+RUN groupadd --gid 1000 sie \+ && useradd --uid 1000 --gid 1000 --create-home --shell /bin/bash sieWORKDIR /appdiff --git a/packages/sie_config/src/sie_config/config_store.py b/packages/sie_config/src/sie_config/config_store.pyindex 650b91fc4..90e825dc5 100644--- a/packages/sie_config/src/sie_config/config_store.py+++ b/packages/sie_config/src/sie_config/config_store.py@@ -11,7 +11,7 @@ logger = logging.getLogger(__name__)class ConfigStore:- """Config store backed by local filesystem, S3, GCS, or Azure Blob.+ """Mutable 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@@ -25,10 +25,21 @@ class ConfigStore:Args:base_dir: Root path for config storage. Accepts local path, s3://, gs://, abfs://, or abfss://.++ Note:+ Alibaba OSS is supported for model/cache objects, but not here: OSS+ PutObject cannot satisfy the non-empty ETag compare-and-swap contract+ required by mutable config epochs."""def __init__(self, base_dir: str) -> None:self._base_dir = base_dir.rstrip("/")+ if self._base_dir.startswith("oss://"):+ raise ValueError(+ "Alibaba OSS cannot be used as a mutable ConfigStore because OSS PutObject "+ "cannot satisfy the required epoch compare-and-swap contract; use local/PVC, s3://, gs://, "+ "or abfs(s):// storage"+ )self._backend: StorageBackend = get_storage_backend(self._base_dir)self._models_path = join_path(self._base_dir, "models")self._epoch_path = join_path(self._base_dir, "epoch")diff --git a/packages/sie_config/tests/test_config_store.py b/packages/sie_config/tests/test_config_store.pyindex ecf821973..11f1963d5 100644--- a/packages/sie_config/tests/test_config_store.py+++ b/packages/sie_config/tests/test_config_store.py@@ -1,6 +1,8 @@import tempfilefrom pathlib import Path+from unittest.mock import patch+import pytestfrom sie_config.config_store import ConfigStore@@ -112,3 +114,23 @@ class TestConfigStore:self.store.write_model("org/model", "sie_id: org/model\n")store2 = ConfigStore(self.store.base_dir)assert store2.read_model("org/model") == "sie_id: org/model\n"++ def test_oss_is_rejected_for_mutable_epoch_storage(self) -> None:+ with pytest.raises(ValueError, match="cannot satisfy the required epoch compare-and-swap contract"):+ ConfigStore("oss://config-bucket/sie-config")++ @pytest.mark.parametrize(+ "url",+ [+ "s3://config-bucket/sie-config",+ "gs://config-bucket/sie-config",+ "abfs://[email protected]/sie-config",+ "abfss://[email protected]/sie-config",+ ],+ )+ def test_existing_mutable_cloud_backends_still_construct(self, url: str) -> None:+ with patch("sie_config.config_store.get_storage_backend") as get_backend:+ store = ConfigStore(url)++ assert store.base_dir == url+ get_backend.assert_called_once_with(url)diff --git a/packages/sie_config/tests/test_dockerfile_contract.py b/packages/sie_config/tests/test_dockerfile_contract.pynew file mode 100644index 000000000..9f13de2d2--- /dev/null+++ b/packages/sie_config/tests/test_dockerfile_contract.py@@ -0,0 +1,11 @@+from pathlib import Path+++def test_runtime_identity_is_pinned_to_chart_security_context() -> None:+ dockerfile = (Path(__file__).parents[1] / "Dockerfile").read_text(encoding="utf-8")+ normalized = " ".join(dockerfile.split())++ assert "groupadd --gid 1000 sie" in normalized+ assert "useradd --uid 1000 --gid 1000 --create-home --shell /bin/bash sie" in normalized+ user_instructions = [line.strip() for line in dockerfile.splitlines() if line.lstrip().startswith("USER ")]+ assert user_instructions == ["USER sie"]diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 2f8431267..2bcc03bbe 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.7.1"+version = "0.7.2"edition = "2021"publish = false@@ -35,6 +35,7 @@ dashmap = "6"tower = "0.5"tower-http = { version = "0.7", features = ["cors"] }bytes = "1"+http = "1"# Phase 4: Model registry + hot reloadarc-swap = "1"@@ -73,6 +74,10 @@ percent-encoding = "2"# Cloud payload store backends (opt-in)object_store = { version = "0.14", optional = true, features = ["aws", "gcp", "azure"] }url = { version = "2", optional = true }+reqsign-aliyun-oss = { version = "=3.1.5", optional = true }+reqsign-core = { version = "=3.3.1", optional = true }+reqsign-file-read-tokio = { version = "=3.0.6", optional = true }+reqsign-http-send-reqwest = { version = "=4.0.6", optional = true }utoipa = "5.4.0"# W3C Trace Context propagation. The gateway extracts the@@ -116,7 +121,14 @@ tracing-opentelemetry = "0.33"[features]default = []-cloud-storage = ["dep:object_store", "dep:url"]+cloud-storage = [+ "dep:object_store",+ "dep:reqsign-aliyun-oss",+ "dep:reqsign-core",+ "dep:reqsign-file-read-tokio",+ "dep:reqsign-http-send-reqwest",+ "dep:url",+]# Test-target-only seam used by the managed composition's release telemetry# benchmark. It installs a synchronous in-memory reader, so the timed path# exercises the real facade without exporter network or background work.@@ -130,7 +142,6 @@ raw-routing-logs = [][dev-dependencies]tempfile = "3"-http = "1"tower = { version = "0.5", features = ["util"] }wiremock = "0.6"# `testing` unlocks the in-memory metric exporter used to assert the gateway'sdiff --git a/packages/sie_gateway/Dockerfile b/packages/sie_gateway/Dockerfileindex 6023d929b..2c1d2cd58 100644--- a/packages/sie_gateway/Dockerfile+++ b/packages/sie_gateway/Dockerfile@@ -1,8 +1,8 @@-FROM rust:1.97.0-slim-bookworm AS chef+FROM rust:1.97.0-slim-bookworm@sha256:6d220bf85c74e842a79da63997af8d2e74455c0b8847d8bb3a5888572334991d AS chefRUN cargo install cargo-chef --lockedWORKDIR /app-# The build runs at the workspace root (#2339): the root Cargo.toml/Cargo.lock+# The build runs at the workspace root: the root Cargo.toml/Cargo.lock# plus every member's manifest+sources must be present for cargo to load the# workspace, and the binary is selected with `-p sie-gateway`.FROM chef AS plannerdiff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.mdindex 51866ed5c..e30d5d759 100644--- a/packages/sie_gateway/README.md+++ b/packages/sie_gateway/README.md@@ -1,6 +1,6 @@# SIE Gateway (Rust)-Runtime gateway for elastic GPU inference deployments. It routes the four SIE primitives: `encode`, `score`, and `extract` over NATS JetStream (queue transport, at-least-once delivery), plus OpenAI-compatible and SIE-native **generation** endpoints (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/generate/{model}`) over direct-dispatch per-worker streams with cache-aware prefix routing. The gateway also owns pool coordination and worker health. Config writes live in `sie-config`; the gateway is a pure consumer of config state, bootstrapping from `GET /v1/configs/export` and subscribing to NATS deltas.+Runtime gateway for elastic GPU inference deployments. It routes the four SIE primitives over NATS JetStream: ordinary `encode`, `score`, and `extract` requests use pool queues (at-least-once delivery), while capped logical batch pools may target an assigned worker directly. OpenAI-compatible and SIE-native **generation** endpoints (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/generate/{model}`) use per-worker direct-dispatch subjects with cache-aware prefix routing. The gateway also owns pool coordination and worker health. Config writes live in `sie-config`; the gateway is a pure consumer of config state, bootstrapping from `GET /v1/configs/export` and subscribing to NATS deltas.Generation is treated as a supported fourth primitive.@@ -8,7 +8,7 @@ See [`docs/architecture-guide.md`](docs/architecture-guide.md) for the authorita## Features-- **Two transports** — NATS JetStream for `encode`/`score`/`extract`; direct-dispatch streaming `/generate` connections for the four generation endpoints (cache-aware prefix routing, pool fallback, first-chunk timeout fallback)+- **Two dispatch modes** — pool-subject JetStream for ordinary `encode`/`score`/`extract`; per-worker JetStream direct-dispatch for capped logical batch pools and the four generation endpoints (cache-aware prefix routing, pool fallback, first-chunk timeout fallback)- **Worker discovery** — static URLs or Kubernetes service endpoints- **Health monitoring** — WebSocket streaming or NATS heartbeats- **Queue transport** — JetStream work publish, reply inbox collection, backpressure handling, and DLQ republish@@ -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** — canonical OpenTelemetry metrics, privacy-safe logs, distributed tracing, audit middleware, and HTML/WebSocket status surfaces-- **Optional cloud storage** — `cloud-storage` feature enables S3/GCS/Azure Blob payload backends; the Docker build enables it+- **Optional cloud storage** — `cloud-storage` enables S3/GCS/Azure Blob and native Alibaba OSS V4 payload backends; the Docker build enables it## Quick Start@@ -49,8 +49,8 @@ SIE_NATS_URL=nats://localhost:4222 \Notes:-- `encode` / `score` / `extract` are queue-only: if no usable NATS client is available, these requests return `503`.-- Generation endpoints use direct-dispatch and do not depend on JetStream for their hot path (NATS Core is still used for worker health and config distribution). There is no direct worker HTTP fallback mode and no `SIE_CLUSTER_ROUTING` toggle.+- `encode` / `score` / `extract` are JetStream-only: ordinary requests use pool queues, while capped logical batch pools may use worker-direct subjects. If no usable NATS client is available, these requests return `503`.+- Generation endpoints require per-worker JetStream direct-dispatch. NATS Core remains responsible for worker health, config distribution, and result delivery. There is no direct worker HTTP fallback mode and no `SIE_CLUSTER_ROUTING` toggle.## CLI@@ -100,7 +100,9 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio| `SIE_LOG_LEVEL` | `info` | Log level (`debug`, `info`, `warn`, `error`) || `SIE_LOG_JSON` | `false` | Structured JSON logging (for Loki) || `SIE_GATEWAY_REQUEST_TIMEOUT` | `120.0` | Non-generation queue result wait timeout in seconds |-| `SIE_GATEWAY_MAX_STREAM_PENDING` | `50000` | Max pending stream items per JetStream work stream |+| `SIE_GATEWAY_MAX_STREAM_PENDING` | `50000` | Max pending stream items per JetStream work stream. Pool-wide: a stream is per pool, so this number cannot tell a hot model's backlog from a cold one's |+| `SIE_GATEWAY_MAX_LANE_IN_FLIGHT_ITEMS` | `10000` | Per-lane (`pool`/`machine_profile`/`bundle`) in-flight work-item ceiling. Always evaluated and recorded on `sie.gateway.queue.lane_admission.decisions`; only sheds when `SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE` is on |+| `SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE` | `false` | Act on the per-lane decision. Off = shadow mode: the decision is computed and recorded, and admission is governed by `SIE_GATEWAY_MAX_STREAM_PENDING` alone. On = a saturated lane gets a targeted 503 while other lanes on the same pool keep admitting || `SIE_GATEWAY_DEFAULT_MAX_TOKENS` | `1024` | Output-token cap applied to `/v1/chat/completions` requests that omit both `max_completion_tokens` and `max_tokens`. OpenAI treats the field as optional, so the gateway defaults rather than rejecting — generic clients (Open WebUI) rely on this || `SIE_GATEWAY_ENABLE_POOLS` | `false` | Enable pool management || `SIE_GATEWAY_HOT_RELOAD` | `false` | Enable filesystem watcher for bundle/model directories |@@ -112,7 +114,9 @@ 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://`, `gs://`, `abfs://`, or `abfss://`; 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://`, `abfss://`, or `oss://`; local filesystem paths only work when gateway and workers share the same path |+| `SIE_OSS_REGION` | unset | Required explicit Alibaba region for `oss://`; OSS V4 is region-scoped |+| `SIE_OSS_USE_INTERNAL_ENDPOINT` | `false` | Derive the Alibaba VPC-internal HTTPS endpoint for `oss://`; arbitrary endpoint overrides are not accepted |## API Endpoints@@ -194,7 +198,12 @@ Not registered on the gateway:## Docker-The gateway image is built via the monorepo Docker tooling; see `tools/mise_tasks/docker.bash` and `deploy/` for chart/values.+Build the gateway image from the repository root; the Helm chart and values are+under `deploy/helm/sie-cluster`.++```bash+docker build -f packages/sie_gateway/Dockerfile -t sie-gateway .+```## Testing@@ -224,7 +233,7 @@ src/health.rs Health and status endpointsmodels.rs GET /v1/models helperspools.rs Pool CRUD- proxy.rs Two transports: encode/score/extract queue routing + generation direct-dispatch (chat/completions/responses/generate)+ proxy.rs Two dispatch modes: ordinary encode/score/extract pool queues + capped-pool/generation worker-directconfig_api.rs Read-only config API (GET /v1/configs/*, including /status dispatch); POST /v1/configs/models is NOT registered (gateway returns 405)middleware/auth.rs Token authenticationdiff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex bb2b7cace..9c1f1df97 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -1,10 +1,10 @@# SIE Architecture-This document describes the current deployed architecture of the SIE control plane and inference edge. It is verified against the `sie-internal` monorepo (`packages/sie_gateway`, `packages/sie_config`, `packages/sie_sdk`). Every behavior described here is what the code does on this branch.+This document describes the current deployed architecture of the SIE control plane and inference gateway. It is verified against the public `packages/sie_gateway`, `packages/sie_config`, and `packages/sie_sdk` implementations. Every behavior described here is what the code does on this branch.Top-level summary:-- `sie-gateway` (Rust) is the inference edge. It is queue-only for inference and serves read-side configuration.+- `sie-gateway` (Rust) is the inference gateway. It routes ordinary encode, score, and extract requests through pool queues, capped logical batch pools and generation through worker direct-dispatch, all over JetStream, and serves read-side configuration.- `sie-config` (Python) is the configuration control plane. It owns writes, persistence, and delta publication.- Workers execute inference.- NATS carries runtime messaging. JetStream carries inference work and the DLQ. Core pub/sub carries config deltas, worker health, and inference results.@@ -24,7 +24,7 @@ The gateway's contract with admin tooling for post-write readiness is `GET /v1/c|---|---|---|---|| Client SDK | Submits inference requests | HTTP inference requests | HTTP inference responses || Admin / deploy tooling | Mutates config, reads control-plane state | HTTP config requests | HTTP config responses |-| `sie-gateway` (Rust) | Queue-only inference edge; read-side config; pool management; health and metrics | Queue work items, inference results acks, read-side config responses, pool state changes, DLQ republishes, metrics | Client inference requests, worker results, worker health, config deltas, K8s pool state |+| `sie-gateway` (Rust) | JetStream-dispatched inference gateway: ordinary encode/score/extract are pool-queued, while capped logical batch pools and generation are worker-direct; read-side config; pool management; health and metrics | Queue work items, read-side config responses, pool state changes, DLQ republishes, metrics | Client inference requests, worker results, worker health, config deltas, K8s pool state || `sie-config` (Python) | Config control plane; single writer | Config write responses, read responses, snapshot/export responses, config deltas (NATS) | Admin/config-management requests || Workers | Execute inference | Result messages, health signals | Queue work items || NATS / JetStream | Message bus | — | — |@@ -46,7 +46,7 @@ Key terms used throughout this document:- `POST /v1/extract/{*model}`- `POST /v1/embeddings` — OpenAI-compatible JSON surface; the gateway accepts **string** or **list of strings** for `input`, supports `encoding_format=float` (default) or `base64`, translates to an internal **`POST /v1/encode/{model}`** with `items[].text` and `params.output_types=["dense"]`, then maps encode `items[].dense` vectors into OpenAI `data[].embedding` plus a rough `usage` estimate. Token-id / nested-array inputs are rejected with **`400`**. The wrapper must buffer the whole encode reply before reshaping it, and that reply is an *amplification* of the request (N short texts in, N × `dim` floats out), so the buffer is bounded by its own **response**-specific cap, `MAX_COMPAT_RESPONSE_BODY` (16 MiB) — deliberately a separate constant from the request cap it used to be derived from, since the two quantities are unrelated and a change to ingress must not silently move this bound. The value holds today's effective bound rather than raising it: at the queue's item ceiling a float reply reaches ~90 MB at 1024 dims and ~224 MB at 2560 dims (`Qwen/Qwen3-Embedding-4B`, served here), the handler holds ~4 copies at once, and the deployed gateway is a 1 GiB container running 4 requests concurrently — so no bound both admits the largest real reply and fits. **Consequence, stated plainly: a batch above roughly 760 inputs at 1024 dims cannot be served on this surface.** The cure is an ingress item cap (terminal `400` before any GPU work), streaming assembly, or a larger container — each its own change. Over the cap the surface answers a **terminal `413`** naming the one remedy that works (fewer inputs — `encoding_format=base64` is inert here, because the field is never forwarded to `/v1/encode` and base64 is applied afterwards to the outer response), never a retryable `503`. Both that `413` and the unreadable-body `500` carry `GatewayOwnedFault`: the worker has already run and reported its units, so a metered composition must release the hold rather than bill for a response carrying zero embeddings.2. Gateway resolves the request to a model, a bundle, a machine profile, a logical API pool, and the backing queue pool using its in-memory registry.-3. Gateway publishes work to JetStream on the backing queue subject `sie.work.{pool}.{machine_profile}.{bundle}.{model}` and carries the logical pool as `admission_pool` in the work item.+3. Gateway ordinarily publishes work to JetStream on the backing queue subject `sie.work.{pool}.{machine_profile}.{bundle}.{model}` and carries the logical pool as `admission_pool` in the work item. A capped logical batch pool instead targets one assigned worker on `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`.4. A matching worker consumes the work item, verifies its logical pool assignment when `admission_pool` differs from its physical queue pool, and executes inference.5. Worker publishes the result on `_INBOX.{router_id}.{request_id}` (NATS Core).6. Gateway collects the result and returns the HTTP response.@@ -54,12 +54,12 @@ Key terms used throughout this document:Rules enforced on the inference path:- The inference hot path does not call `sie-config`.-- The inference hot path is queue-only. There is no direct-HTTP fallback. `src/handlers/proxy.rs` is the queue-submission handler despite its name.+- Ordinary encode, score, and extract use pool-queue dispatch; capped logical batch pools and generation use worker direct-dispatch. Both paths use JetStream, with no direct-HTTP fallback. `src/handlers/proxy.rs` is the JetStream submission handler despite its name.- If the queue transport is unavailable (no usable NATS client at init), the gateway returns `503`. It does not fall back to direct mode.- Unknown model ids fast-fail with `404` whenever the in-memory `ModelRegistry` has been populated (either by the filesystem seed or by a successful bootstrap / delta from `sie-config`). In the pre-bootstrap edge case where the registry is still empty — no seed, no export applied yet — the proxy falls back to the caller-supplied bundle (or `"default"`) so an unseeded gateway can still publish work to a cold pool that a caller pinned via `X-SIE-Pool`. Once any model is registered, this fallback is disabled and the 404 contract applies.- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. Explicit `X-SIE-Pool` selects a logical pool; the gateway publishes to that pool's backing queue pool (`PoolSpec.queue_pool`, default `default`) and stamps the logical pool into the work item as `admission_pool`. Deliveries whose hash is not the worker-sidecar's current hash, or logical pools that do not assign that worker, are NAKed before backend IPC. Successful non-streaming results echo the execution hash; the gateway emits `X-SIE-Model-Revision` only when every successful result matches the hash and immutable revision captured atomically at routing time. Streaming responses omit this post-execution attestation because headers precede the terminal result.- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.-- On no-consumer conditions for the JetStream publish, the gateway treats the miss as the same pre-execution provisioning state and returns the same retryable `503 PROVISIONING` contract (`Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and surface-specific error envelope). On backpressure conditions the gateway returns `503` with `Retry-After: 5`.+- On no-consumer conditions for the JetStream publish, the gateway treats the miss as the same pre-execution provisioning state and returns the same retryable `503 PROVISIONING` contract (`Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and surface-specific error envelope). On backpressure conditions the gateway returns `503` with `Retry-After: 5`. Backpressure is evaluated twice: pool-wide against the `WORK_POOL_{pool}` stream's pending count (`SIE_GATEWAY_MAX_STREAM_PENDING`), and per lane (`pool`/`machine_profile`/`bundle`) against a gateway-local in-flight work-item count (`SIE_GATEWAY_MAX_LANE_IN_FLIGHT_ITEMS`). The per-lane decision is always computed and recorded on `sie.gateway.queue.lane_admission.decisions`, but it only sheds when `SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE` is set; with the flag off (the default) the pool-wide check is the sole gate. Both sheds produce the same `503` contract and both record pending demand for the exact physical lane so KEDA scales it.- On queue result timeouts the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5`. This means the gateway accepted and published the work item, but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`; it must not be collapsed into worker-emitted `MODEL_LOADING`, which remains a separate retryable `503 MODEL_LOADING` signal.- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED` (worker-side OOM recovery exhausted — `Retry-After: 5`), `MODEL_LOADING`, and `LORA_LOADING`. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.- When **every** failed item carries **`MODEL_LOAD_FAILED`**, the gateway returns **`502 Bad Gateway`** with the SDK-style **`error`** object (`code`, `message`, `error_class`, `attempts`, `permanent`) — matching the terminal model-load contract consumed by SDK retry logic (no `Retry-After`; the SDK must not burn the `MODEL_LOADING` retry budget). The gateway synthesises conservative `attempts` / `permanent` fields on this queue path when the worker payload does not carry registry-shaped failure metadata.@@ -295,7 +295,7 @@ Per-subject transport:| Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (section 4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through backend IPC. || Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`) and supervises the subscriber task: reconnects normally resume in `async-nats`, but a terminated subscription stream is recreated with bounded backoff because there is no full-state health poller. Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply. Helm sidecar deployments set `health_mode=nats`; the gateway binary default remains `ws` so standalone/test deployments can use the Python WebSocket path. || DLQ advisories | `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` | NATS Core (advisory) | JetStream emits these; gateway replicas subscribe in `queue/dlq.rs` and publish to `DEAD_LETTERS` with a deterministic `Nats-Msg-Id`, so JetStream dedupes replica fan-out. |-| DLQ storage | `sie.dlq.{model_token}` | JetStream | Single stream `DEAD_LETTERS` (Limits retention, memory storage, 24 h `max_age`) captures `sie.dlq.>`. `model_token` is derived from the advisory's original work subject by taking the model segment and replacing `/` with `_`. |+| DLQ storage | `sie.dlq.{model_token}` | JetStream | Single stream `DEAD_LETTERS` (Limits retention, 24 h `max_age`) captures `sie.dlq.>`. Storage and replicas track the work-queue setting (`SIE_STREAM_STORAGE` / `SIE_STREAM_REPLICAS`, memory/1 by default), so a memory-backed DLQ is erased by the same broker restart that erases the work it recorded. `model_token` is derived from the advisory's original work subject by taking the model segment and replacing `/` with `_`. |### 8.2 Work-stream configuration and the model-ID constraint@@ -305,12 +305,16 @@ The gateway's `ensure_stream` (per pool, called lazily on first publish) createsname: WORK_POOL_{pool}subjects: ["sie.work.{pool}.*.*.*"]retention: WorkQueue-storage: Memory+storage: Memory by default (`SIE_STREAM_STORAGE`: memory | file)+replicas: 1 by default (`SIE_STREAM_REPLICAS`)max_age: 1800s (shared gateway/worker default)max_msgs: 100_000+discard: New (reject publishes at the max_msgs cap)```-max_age defaults to 1800 s on both the gateway (`SIE_STREAM_MAX_AGE_S`) and worker sidecar. The default intentionally stays above `max_deliver * 30s` for the pool consumer so the original work payload remains fetchable after the retry/DLQ envelope trips. `get_or_create_stream` / `add_stream` does not update an existing stream's config, so both gateway and sidecar reconcile existing stream `max_age` during stream ensure; keep the Helm value wired to both gateway and workers so they repair to the same target.+Storage defaults to `Memory`, which means queued and delivered-but-unacked work lives only in the broker's RAM: a NATS restart erases it along with the `DEAD_LETTERS` record that would have named it, and since the gateway is queue-only that restart is also a full inference outage. `SIE_STREAM_STORAGE=file` (plus a JetStream file store on the broker) persists the streams at the cost of disk and publish latency; `SIE_STREAM_REPLICAS` raises the replica count on a clustered NATS. Helm renders both onto the gateway and the worker sidecars from `queueRouting.streamStorage` / `queueRouting.streamReplicas` so the two stream creators cannot disagree.++max_age defaults to 1800 s on both the gateway (`SIE_STREAM_MAX_AGE_S`) and worker sidecar. The default intentionally stays above `max_deliver * 30s` for the pool consumer so the original work payload remains fetchable after the retry/DLQ envelope trips. The `New` discard policy makes the broker reject a publish once the stream sits at `max_msgs`, so the failed ACK surfaces on the existing 503 queue-unavailable path; the async-nats default (`Old`) would instead silently discard the oldest queued work, whose clients then ride to a 504. `get_or_create_stream` / `add_stream` does not update an existing stream's config, so both gateway and sidecar reconcile existing stream `max_age`, `discard`, and `num_replicas` during stream ensure; keep the Helm value wired to both gateway and workers so they repair to the same target. `storage` is deliberately NOT reconciled: JetStream refuses an in-place storage-type change (err_code 10052, "stream configuration update can not change storage type" — the message store is already materialized), and repairing it would mean deleting and recreating the stream, destroying the very work durability is meant to protect. A mismatch is logged as a warning and the stream is left alone until an operator drains the pool and recreates it. The same policy covers `DEAD_LETTERS` (`queue/dlq.rs`), which shares the reconcile helpers in `queue/stream_durability.rs` — destroying the forensic record to change its storage type would be the failure the knob exists to prevent. Note NATS does not validate `num_replicas` against the real topology (a single-node server accepts and reports R3), so the Helm chart, not the broker, is what guards a replica count against the deployed NATS cluster size.When a gateway or sidecar observes an existing `WORK_POOL_{pool}` stream, itreconciles the stream subjects to exactly `sie.work.{pool}.*.*.*`. Legacy@@ -405,8 +409,10 @@ Backend selection is URL-driven (`sie_sdk.storage.get_storage_backend`):- `s3://bucket/prefix` — S3.- `gs://bucket/prefix` — GCS.- `abfs(s)://[email protected]/prefix` — Azure Blob / ADLS Gen2.+- `oss://bucket/prefix` — Alibaba OSS for discovery/cache copies only; mutable+ `ConfigStore` construction rejects it because OSS cannot satisfy epoch CAS.-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").+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 S3/GCS/Azure config backends 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. OSS is available to cache/discovery code but is rejected as a mutable config base. 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).@@ -414,7 +420,7 @@ The gateway has no persistent config store. `SIE_CONFIG_STORE_DIR` and `SIE_CONF## 10. Deployment Topology-- `sie-gateway` and `sie-config` are separate Kubernetes Deployments with separate images, built via `tools/mise_tasks/docker_task.py` (invoked as `mise run docker --{gateway,config,bake}`). On a `v*` git tag, `.github/workflows/release-docker.yml` publishes `ghcr.io/superlinked/sie-{config,gateway}:<tag>` and the per-platform/bundle `sie-server:<tag>-<platform>-<bundle>` matrix (plus floating `:latest` variants) to GHCR, which the Helm chart consumes by default. The `aws_docker`/`aws_deploy` tasks handle manual pushes to ECR/AR for cluster-local iteration.+- `sie-gateway` and `sie-config` are separate Kubernetes Deployments with separate images. Their public build definitions live in `packages/sie_gateway/Dockerfile` and `packages/sie_config/Dockerfile`; the Helm chart consumes tagged `ghcr.io/superlinked/sie-{config,gateway}:<tag>` images by default, and consumes the per-platform/bundle `sie-server:<tag>-<platform>-<bundle>` matrix when a worker pool is enabled.- `sie-config` runs as **a single replica**. Multi-replica is blocked by the in-memory idempotency cache (see §11 "Known operational caveats"). Config persistence is opt-in: when `config.configStore.enabled: true` in the Helm values, a PVC is mounted at `/var/lib/sie-config` (default mount path) and `SIE_CONFIG_STORE_DIR` / `SIE_CONFIG_RESTORE` are set so the store survives pod restarts; with the default `enabled: false`, the store is ephemeral (backed by the pod filesystem) and a pod restart resets the epoch to 0 and drops every API-added model — `sie-config` does not subscribe to NATS (it is the sole publisher) so there is no replay path, and the registry rebuilds from the image-baked `/app/bundles` + `/app/models` baseline only. Every gateway replica's `state::config_poller` then detects `remote_epoch < local_epoch` and force-resets to match the restarted `sie-config`, picking up whatever baseline it now advertises. Operators who need API-added models to survive `sie-config` restarts must set `config.configStore.enabled: true`. The Helm chart (`deploy/helm/sie-cluster/values.yaml`) documents the SPOF posture.- `sie-gateway` scales horizontally. Each replica maintains its own in-memory `ModelRegistry` and its own `ConfigEpoch`. They all converge on the same state via a combination of bootstrap, deltas, and the poller; they do not coordinate with each other.- Bundles live on `sie-config`'s filesystem at `SIE_BUNDLES_DIR` (default `/app/bundles`, set via `sharedPaths.bundlesDir`) and are baked into its image. `sie-config` reads them at startup, validates writes against them, and re-serves them over HTTP at `GET /v1/configs/bundles{,/{id}}`. The gateway fetches that surface during `state::config_bootstrap::bootstrap` and installs it via `ModelRegistry::install_bundles` — there is no second copy. The `gateway.embeddedConfigs` / `gateway.configMap` overlays still exist for the rare case of running the gateway without `sie-config` (e.g., self-contained smoke tests); they mount a ConfigMap at `/configs/bundles` which the registry's filesystem reload picks up before the (no-op) bootstrap runs. In all cases, updating bundles is a `sie-config` redeploy and the gateway picks up the change on its next bootstrap or poller-driven reconcile, not via a runtime API call.@@ -800,6 +806,8 @@ Workers are multi-model: one `default` worker can serve BGE-M3, a cross-encoder,On each inbox message, the gateway first runs `extract_request_id_fast` — a bounded scan of the raw msgpack bytes that locates the `request_id` (or, for array-shape `WorkResult` payloads, the first string field, which the current codec places at the `request_id` / `work_item_id` position) without a full deserialization. If the extracted ID is not present in the `pending_results` `DashMap`, the message is dropped immediately (already completed, duplicate redelivery, or stale). Only when it is live does the handler decode the payload. An exact `kind: result_chunk_v1` discriminator enters the v1 decoder and malformed exact-v1 envelopes fail closed; ordinary or future `WorkResult` maps remain compatible even if they add fields such as `total_bytes`. V1 accepts out-of-order and byte-identical duplicate chunks, and rejects identity/metadata conflicts, bad length/digest, more than 64 chunks, or more than 16 MiB per item. Chunk zero with a new digest replaces stale retry state. Chunk zero may also safely restart the same digest with a new canonical chunk count; bounded digest/layout tombstones stop delayed fragments from an abandoned attempt from mixing with or flipping the replacement. Unknown non-zero retry fragments are ignored.+Decoding and handling are separate stages. The subscription feeds one decode task, which does the fast-path skip and the single msgpack decode (`inbox_work_for_payload`) and then hands the typed envelope to a bounded worker pool keyed by request id (`queue/keyed_worker_pool.rs`). A request id always maps to the same shard and a shard drains its channel in order, awaiting each handler, so a request's messages are handled in arrival order — which streaming depends on, since a reordered `seq` is dropped as a duplicate or fails the stream as a `transport_failure` gap. Different requests take different shards and proceed concurrently. When a shard is saturated the decode task waits for a slot rather than dropping a result or a chunk; that degrades to the pre-pool behaviour of handling everything inline and is counted as `sie_gateway_queue_worker_pool_events_total{pool="inbox",event="saturated"}`. Completion-time object-store deletes do not run on either stage: `handle_result` and the streaming terminal funnel queue them onto a second pool (`pool="payload_cleanup"`), which sheds at its bound because the periodic `cleanup_expired` reconcile already retries orphaned keys.+Memory is admission-controlled before a transfer allocates its chunk vector. Each item conservatively reserves three times its encoded length (partial fragments, contiguous reassembly/decode copy, and the decoded result retained until all request items complete) plus 4 KiB of bookkeeping headroom. Reservations for accepted completed chunked items are held until request completion; completed results rejected by first-result or stale direct-fallback semantics release their reservation immediately. Reservations are capped at 64 MiB per request and 256 MiB gateway-wide. The process-wide ceiling is one eighth of the gateway's 2 GiB container limit, leaving 1.75 GiB for normal response buffers, JSON expansion, NATS, allocator overhead, and the rest of the process. Request-collector RAII releases reservations on success, validation failure, timeout, and publish failure. The current reservation is exposed as `sie_gateway_queue_result_chunk_reserved_bytes`; global exhaustion increments `sie_gateway_queue_result_chunk_rejections_total{reason="global_budget"}`. Invalid transfers terminate the pending request with a static, non-retry-hinted `503 transport_failure` instead of waiting for timeout.The inbox remains a trusted in-cluster worker boundary, as it already was for one-shot `WorkResult`: a publisher that can write to another gateway's private inbox can name a live request. Chunk validation fails such a request closed, but never reflects the supplied ids, payload, or validation detail to the caller; the public message is the static transport error above.@@ -869,4 +877,4 @@ A pool spec may also carry `pinned_models` (a per-pool set of always-loaded modeCreating a usable custom pool has two supported shapes. For a dynamic logical pool over base capacity, call `POST /v1/pools` with the logical name and GPU requirements and omit `queue_pool`; it defaults to `default`, so no additional Helm worker group is required. Pool `name` is user/dynamic. Non-default `queue_pool` is infra/admin: it must name a Helm-rendered `queuePool`/`SIE_POOL` backing lane declared under `queueRouting.staticQueuePools`. For a dedicated physical queue, first add that worker group to Helm values and declare the same name under `queueRouting.staticQueuePools`, then create logical pools with `queue_pool` set to that queue. Lease-owned dynamic pools expire after their TTL unless renewed with `POST /v1/pools/{name}/renew`. Clients target either shape with an explicit `X-SIE-POOL` header, for example `X-SIE-POOL: customer-acme`, or SDK `gpu="customer-acme/l4"`. The `default` pool is protected and cannot be deleted. Missing named pools intentionally fail closed so capped/dynamic pool isolation is not weakened by a silent fallback.-Model configs registered via the control plane (`sie-config`) may carry a top-level `pool` field. That field is model routing/config assignment: omitted or empty means `default`, and a request that omits `X-SIE-POOL` defaults to the model's assigned pool. It does not create workers, KEDA ScaledObjects, or runtime pool leases. Worker counts, machine profiles, bundles, and autoscaling lanes are still Helm-driven physical capacity; `/v1/pools` and `queueRouting.staticQueuePools` only create or renew runtime admission/capacity state, optionally backed by existing `default` capacity through `PoolSpec.queue_pool`. Because workers filter materialized model configs by their physical `SIE_POOL`, a model config for a dedicated queue should use the physical queue pool name; gateway requests may still target a logical pool whose `queue_pool` resolves to that physical name. A default-backed logical pool should not use a non-default model-config `pool` unless a matching dedicated worker queue exists.+Model configs registered via the control plane (`sie-config`) may carry a top-level `pool` field. That field is model routing/config assignment: omitted or empty means `default`, and a request that omits `X-SIE-POOL` defaults to the model's assigned pool. It does not create workers, KEDA ScaledObjects, or runtime pool leases. Worker counts, machine profiles, bundles, and autoscaling lanes are still Helm-driven physical capacity; `/v1/pools` and `queueRouting.staticQueuePools` only create or renew runtime admission/capacity state, optionally backed by existing `default` capacity through `PoolSpec.queue_pool`. In the Kubernetes/Helm composition, workers filter materialized model configs by their physical `SIE_POOL`, so a model config for a dedicated queue normally uses the physical queue-pool name; gateway requests may still target a logical pool whose `queue_pool` resolves to that physical name. A default-backed logical pool should not use a non-default model-config `pool` unless a matching dedicated worker queue exists. The managed Modal composition has one governed exception: a deployment-owned diagnostic admission queue may reuse the complete `default` catalog in a separate worker app. Dispatch stays on that physical queue, but bundle-hash and immutable-revision evidence are atomically scoped to the requested model's declared catalog pool. A known catalog model with a missing scoped hash fails closed rather than enabling the empty-hash wildcard; unknown sealed compatibility remains separately bounded.diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 71f715438..8b3978058 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -41,6 +41,35 @@],"type": "object"},+ "AudioInput": {+ "properties": {+ "data": {+ "contentEncoding": "base64",+ "description": "Media bytes. Base64-encoded on the JSON path; native binary on the msgpack path.",+ "type": "string"+ },+ "format": {+ "type": [+ "string",+ "null"+ ]+ },+ "sample_rate": {+ "description": "Sample rate in Hz. Must be positive.",+ "exclusiveMinimum": 0,+ "format": "int32",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },"BundleConfigDocument": {"properties": {"adapters": {@@ -1050,12 +1079,9 @@"DocumentInput": {"properties": {"data": {- "items": {- "format": "int32",- "minimum": 0,- "type": "integer"- },- "type": "array"+ "contentEncoding": "base64",+ "description": "Media bytes. Base64-encoded on the JSON path; native binary on the msgpack path.",+ "type": "string"},"format": {"type": [@@ -1146,6 +1172,16 @@"$ref": "#/components/schemas/TimingInfo"}]+ },+ "usage": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/Usage"+ }+ ]}},"required": [@@ -1327,6 +1363,16 @@},"model": {"type": "string"+ },+ "usage": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/Usage"+ }+ ]}},"required": [@@ -1869,12 +1915,9 @@"ImageInput": {"properties": {"data": {- "items": {- "format": "int32",- "minimum": 0,- "type": "integer"- },- "type": "array"+ "contentEncoding": "base64",+ "description": "Media bytes. Base64-encoded on the JSON path; native binary on the msgpack path.",+ "type": "string"},"format": {"type": [@@ -1938,6 +1981,16 @@},"ItemInput": {"properties": {+ "audio": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AudioInput"+ }+ ]+ },"document": {"oneOf": [{@@ -1969,6 +2022,16 @@"string","null"]+ },+ "video": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/VideoInput"+ }+ ]}},"type": "object"@@ -2162,6 +2225,13 @@"ModelInfoWire": {"description": "Wire shape aligned with ``sie_server`` ``ModelInfo`` for ``GET /v1/models``.","properties": {+ "aliases": {+ "description": "Short task-tier names that resolve to this model, for example\n``[\"rerank-fast\"]``. Send one anywhere a model id is accepted and it\nresolves to this entry, billed at this model's rate.\n\nAlways present, and empty when the model has none. Only names declared\nby the released catalog or by operator configuration appear here.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },"capabilities": {"oneOf": [{@@ -2240,7 +2310,8 @@"dims","loaded","state",- "profiles"+ "profiles",+ "aliases"],"type": "object"},@@ -2439,14 +2510,27 @@],"type": "object"},+ "OpenAIEmbeddingTokenSource": {+ "enum": [+ "worker",+ "character_estimate"+ ],+ "type": "string"+ },"OpenAIEmbeddingUsage": {"properties": {"prompt_tokens": {+ "description": "Exact post-tokenization input tokens when `sie_token_source` is\n`worker`; a character-based approximation when it is\n`character_estimate`.","format": "int64","minimum": 0,"type": "integer"},+ "sie_token_source": {+ "$ref": "#/components/schemas/OpenAIEmbeddingTokenSource",+ "description": "SIE extension. `worker` when the counts above are the model's own\npost-tokenization measurement, `character_estimate` when the serving\npath reported no counts and the numbers are approximate."+ },"total_tokens": {+ "description": "Equal to `prompt_tokens`; embeddings produce no output tokens.","format": "int64","minimum": 0,"type": "integer"@@ -2454,7 +2538,8 @@},"required": ["prompt_tokens",- "total_tokens"+ "total_tokens",+ "sie_token_source"],"type": "object"},@@ -3655,6 +3740,47 @@],"type": "object"},+ "Usage": {+ "description": "Authoritative worker-emitted usage. Post-tokenization counts, never a\ncharacter estimate. A reported `0` is a measurement (a request that read no\ntext); an absent block means the serving path could not count. Structurally\nidentical to `ScoreUsage`, which shipped this shape first.",+ "properties": {+ "images": {+ "format": "int64",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "input_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "input_tokens"+ ],+ "type": "object"+ },+ "VideoInput": {+ "properties": {+ "data": {+ "contentEncoding": "base64",+ "description": "Media bytes. Base64-encoded on the JSON path; native binary on the msgpack path.",+ "type": "string"+ },+ "format": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },"WorkerInfo": {"properties": {"bundle": {@@ -3745,7 +3871,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.7.1"+ "version": "0.7.2"},"openapi": "3.1.0","paths": {diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex 8be5cb40e..afe7b2196 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::env;use serde::Deserialize;@@ -6,7 +6,7 @@ use serde::Deserialize;use crate::state::demand_tracker::PhysicalLaneCatalog;use crate::types::pool::PoolSpec;-/// Modal platform proxy-auth credential (superlinked/sie-internal #1740).+/// Modal platform proxy-auth credential.////// When a managed ingress endpoint (config service, generation-lane `/gen`/// WebSocket, OTLP collector) is deployed with `requires_proxy_auth=True`,@@ -38,6 +38,54 @@ impl std::fmt::Debug for ModalProxyToken {}}+/// JetStream storage backing for the work-queue and DLQ streams.+///+/// `Memory` (the default, and the only behaviour that existed before this+/// knob) keeps queued and delivered-but-unacknowledged work **only in the+/// broker's RAM**: a restart of the NATS pod — an OOM kill, a NATS rollout,+/// or a node drain that evicts *that* pod — erases every queued item and the+/// `DEAD_LETTERS` record that would have named them. Draining a node hosting+/// only workers or gateways costs nothing here. At the default single replica+/// any eviction of the one NATS pod loses the state; a replicated stream+/// survives while a peer holding it stays up.+/// `File` persists them to the broker's JetStream store so they survive a+/// broker restart, at the cost of disk (a PVC on the NATS pods) and extra+/// publish latency.+///+/// The default is deliberately unchanged: flipping a live cluster to `File`+/// is an operator decision (disk sizing, PVCs, latency budget), not a code+/// default. Set `SIE_STREAM_STORAGE=file` on BOTH the gateway and the worker+/// sidecars, and enable the NATS sub-chart's `fileStore`, to opt in.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum StreamStorage {+ #[default]+ Memory,+ File,+}++impl StreamStorage {+ /// Parse the `SIE_STREAM_STORAGE` spelling. Unrecognized values fall back+ /// to the default rather than panicking — a typo must not take the queue+ /// edge down, and the effective value is logged at startup via `Config`'s+ /// `Debug`.+ pub fn parse(raw: &str) -> Option<Self> {+ match raw.trim().to_ascii_lowercase().as_str() {+ "memory" | "mem" => Some(Self::Memory),+ "file" | "disk" => Some(Self::File),+ _ => None,+ }+ }+}++impl From<StreamStorage> for async_nats::jetstream::stream::StorageType {+ fn from(value: StreamStorage) -> Self {+ match value {+ StreamStorage::Memory => Self::Memory,+ StreamStorage::File => Self::File,+ }+ }+}+// `Debug` is hand-written (below) rather than derived: several fields hold// secret material (`auth_tokens`, `admin_token`, `config_service_token`, and// `config_modal_proxy_token`) and `Config` is `{:?}`-formatted at startup, so a@@ -95,7 +143,27 @@ pub struct Config {// Tuningpub request_timeout: f64,pub max_stream_pending: u64,+ /// Per-lane in-flight work-item ceiling+ /// (`SIE_GATEWAY_MAX_LANE_IN_FLIGHT_ITEMS`). The per-lane decision is+ /// always computed against this; whether it sheds is+ /// `lane_backpressure_enforce`.+ pub max_lane_in_flight_items: u64,+ /// Act on the per-lane backpressure decision+ /// (`SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE`, default `false`).+ ///+ /// The flag gates enforcement, not computation: with it off the gateway+ /// still evaluates and records each lane's decision, and admission is+ /// governed by the pool-wide `max_stream_pending` check exactly as before.+ pub lane_backpressure_enforce: bool,pub stream_max_age_s: u64,+ /// Storage backing for `WORK_POOL_{pool}` and `DEAD_LETTERS`+ /// (`SIE_STREAM_STORAGE`, default `memory`). Must match the worker+ /// sidecars: whoever creates the stream first wins, and JetStream does+ /// NOT allow changing an existing stream's storage type in place.+ pub stream_storage: StreamStorage,+ /// JetStream replica count for those streams (`SIE_STREAM_REPLICAS`,+ /// default 1). Values above 1 require a clustered NATS deployment.+ pub stream_num_replicas: usize,// Configured GPUs (survives scale-to-zero)pub configured_gpus: Vec<String>,@@ -116,6 +184,18 @@ pub struct Config {// (JSON map). Mirrors the `SIE_GATEWAY_GPU_ALIASES` mechanism.pub model_aliases: HashMap<String, String>,+ // The subset of `model_aliases` that `/v1/models` may advertise (#2843).+ //+ // The three compiled-in built-ins are deliberately NOT in here. They are+ // internal routing defaults, not product names: `code`/`sql` point at+ // Qwen3-4B-Instruct-2507, which is absent from the managed launch catalog,+ // so publishing them would both name a model a managed customer cannot+ // otherwise see AND turn an implementation detail into a documented+ // contract that could not be repointed later without a breaking change.+ // Aliases an operator or a released catalog declared on purpose ARE+ // publishable — those are the names the epic exists to make discoverable.+ pub published_model_aliases: HashSet<String>,+// Model registry paths (filesystem seed; same volume mounted into sie-config// for consistency, but the gateway never writes to them).pub bundles_dir: String,@@ -134,14 +214,15 @@ pub struct Config {pub config_service_token: Option<String>,// Optional Modal platform proxy-auth token the gateway's config client- // presents ALONGSIDE `config_service_token` on `GET /v1/configs/*` calls- // (superlinked/sie-internal #1740). `Some` only when both+ // presents ALONGSIDE `config_service_token` on `GET /v1/configs/*` calls.+ // `Some` only when both// `SIE_MODAL_PROXY_TOKEN_ID` and `SIE_MODAL_PROXY_TOKEN_SECRET` are set;// absent on self-host / dev (no Modal edge), so no proxy headers are sent.pub config_modal_proxy_token: Option<ModalProxyToken>,- // Payload store (local path, s3://bucket/prefix, gs://bucket/prefix, or- // abfs(s)://[email protected]/prefix)+ // Payload store (local path, s3://bucket/prefix, gs://bucket/prefix,+ // abfs(s)://[email protected]/prefix, or+ // oss://bucket/prefix)pub payload_store_url: String,// The gateway's own EXTERNAL https origin (`SIE_GATEWAY_PUBLIC_URL`,@@ -203,7 +284,11 @@ impl std::fmt::Debug for Config {.field("multi_router", &self.multi_router).field("request_timeout", &self.request_timeout).field("max_stream_pending", &self.max_stream_pending)+ .field("max_lane_in_flight_items", &self.max_lane_in_flight_items)+ .field("lane_backpressure_enforce", &self.lane_backpressure_enforce).field("stream_max_age_s", &self.stream_max_age_s)+ .field("stream_storage", &self.stream_storage)+ .field("stream_num_replicas", &self.stream_num_replicas).field("configured_gpus", &self.configured_gpus).field("gpu_profile_map", &self.gpu_profile_map).field("configured_physical_lanes", &self.configured_physical_lanes)@@ -359,6 +444,17 @@ fn env_finite_float(key: &str, fallback: f64) -> f64 {value}+/// Read `SIE_STREAM_STORAGE`. An unset, empty, or unrecognized value keeps+/// the historical `Memory` behaviour so a typo can never silently change the+/// durability posture of a running cluster in the *other* direction either.+fn env_stream_storage(key: &str) -> StreamStorage {+ env::var(key)+ .ok()+ .as_deref()+ .and_then(StreamStorage::parse)+ .unwrap_or_default()+}+fn env_u64(key: &str, fallback: u64) -> u64 {env::var(key).ok()@@ -486,7 +582,12 @@ fn env_static_queue_pools(key: &str) -> Vec<PoolSpec> {/// — e.g. map `sql` to a BF16 bundle that avoids the FP8 SQL-accuracy/// regression (ADR 0001). `resolve_model_spec_with_aliases` (proxy.rs) applies/// the bundle and preserves concrete profile variants.-fn build_model_aliases(overrides: HashMap<String, String>) -> HashMap<String, String> {+/// Returns the resolution map plus the subset that may be advertised on+/// `/v1/models`. Only explicitly-declared aliases are publishable; see+/// [`Config::published_model_aliases`].+fn build_model_aliases(+ overrides: HashMap<String, String>,+) -> (HashMap<String, String>, HashSet<String>) {let mut map: HashMap<String, String> = HashMap::new();// Built-in: the code-generation job → the model with a MEASURED// HumanEval/MBPP pass@1 baseline that also serves reliably@@ -507,15 +608,19 @@ fn build_model_aliases(overrides: HashMap<String, String>) -> HashMap<String, St"guard".to_string(),"ibm-granite/granite-guardian-3.0-2b".to_string(),);+ let mut published: HashSet<String> = HashSet::new();for (alias, target) in overrides {let alias = alias.trim().to_lowercase();let target = target.trim().to_string();if alias.is_empty() || target.is_empty() {continue;}+ // An override that shadows a built-in name becomes publishable: the+ // operator chose that name, so it is theirs, not an internal default.+ published.insert(alias.clone());map.insert(alias, target);}- map+ (map, published)}fn build_gpu_profile_map(@@ -560,7 +665,8 @@ impl Config {&configured_gpus,env_json_string_map("SIE_GATEWAY_GPU_ALIASES"),);- let model_aliases = build_model_aliases(env_json_string_map("SIE_GATEWAY_MODEL_ALIASES"));+ let (model_aliases, published_model_aliases) =+ build_model_aliases(env_json_string_map("SIE_GATEWAY_MODEL_ALIASES"));Self {host: "0.0.0.0".to_string(),@@ -605,13 +711,23 @@ impl Config {request_timeout: env_finite_float("SIE_GATEWAY_REQUEST_TIMEOUT", 120.0),max_stream_pending: env_u64("SIE_GATEWAY_MAX_STREAM_PENDING", 50_000),+ max_lane_in_flight_items: env_u64(+ "SIE_GATEWAY_MAX_LANE_IN_FLIGHT_ITEMS",+ crate::queue::lane_admission::DEFAULT_MAX_LANE_IN_FLIGHT_ITEMS,+ ),+ lane_backpressure_enforce: env_bool("SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE"),stream_max_age_s: env_u64("SIE_STREAM_MAX_AGE_S", 1_800),+ stream_storage: env_stream_storage("SIE_STREAM_STORAGE"),+ // `env_u64` already falls back on a parse failure; clamp 0 up to 1+ // because JetStream treats 0 replicas as invalid.+ stream_num_replicas: env_u64("SIE_STREAM_REPLICAS", 1).max(1) as usize,configured_gpus,gpu_profile_map,configured_physical_lanes,static_queue_pools: env_static_queue_pools("SIE_GATEWAY_STATIC_QUEUE_POOLS"),model_aliases,+ published_model_aliases,bundles_dir: env_default("SIE_BUNDLES_DIR", "bundles"),models_dir: env_default("SIE_MODELS_DIR", "models"),@@ -1070,7 +1186,7 @@ mod tests {#[test]fn test_build_model_aliases_has_builtin_code_default() {- let result = build_model_aliases(HashMap::new());+ let (result, published) = build_model_aliases(HashMap::new());assert_eq!(result.get("code"),Some(&"Qwen/Qwen3-4B-Instruct-2507".to_string())@@ -1083,6 +1199,11 @@ mod tests {result.get("guard"),Some(&"ibm-granite/granite-guardian-3.0-2b".to_string()));+ // The built-ins resolve but are NOT public API (#2843). `code`/`sql`+ // point at a model absent from the managed launch catalog, so listing+ // them would name something a managed caller cannot otherwise see and+ // freeze an internal default into a contract we could not repoint.+ assert!(published.is_empty());}#[test]@@ -1092,11 +1213,17 @@ mod tests {overrides.insert("SQL".to_string(), "Org/SQLModel".to_string()); // extend + lowercasedoverrides.insert("blank".to_string(), "".to_string()); // skipped (empty target)- let result = build_model_aliases(overrides);+ let (result, published) = build_model_aliases(overrides);assert_eq!(result.get("code"), Some(&"Org/Coder".to_string()));assert_eq!(result.get("sql"), Some(&"Org/SQLModel".to_string()));assert!(!result.contains_key("blank"));+ // An operator who names an alias owns that name, so it is publishable+ // even when it shadows a built-in. A skipped entry never becomes one.+ assert!(published.contains("code"));+ assert!(published.contains("sql"));+ assert!(!published.contains("blank"));+ assert!(!published.contains("guard"));}#[test]@@ -1408,6 +1535,58 @@ mod tests {});}+ /// The shipped default must stay memory-backed / single-replica: this PR+ /// makes durability configurable, it does NOT flip the production+ /// posture. A change here is a deliberate operator-facing decision.+ #[test]+ fn test_stream_storage_defaults_to_memory_single_replica() {+ without_env(&["SIE_STREAM_STORAGE", "SIE_STREAM_REPLICAS"], || {+ let cfg = Config::load();+ assert_eq!(cfg.stream_storage, StreamStorage::Memory);+ assert_eq!(cfg.stream_num_replicas, 1);+ });+ }++ #[test]+ fn test_stream_storage_from_env() {+ with_env(+ &[("SIE_STREAM_STORAGE", "file"), ("SIE_STREAM_REPLICAS", "3")],+ || {+ let cfg = Config::load();+ assert_eq!(cfg.stream_storage, StreamStorage::File);+ assert_eq!(cfg.stream_num_replicas, 3);+ },+ );+ }++ /// A typo must not take the queue edge down, and must not silently move+ /// the cluster off its configured posture either — it falls back to the+ /// shipped default and the effective value is visible in the startup+ /// `Config` dump.+ #[test]+ fn test_stream_storage_rejects_garbage_and_zero_replicas() {+ with_env(+ &[+ ("SIE_STREAM_STORAGE", "durable-please"),+ ("SIE_STREAM_REPLICAS", "0"),+ ],+ || {+ let cfg = Config::load();+ assert_eq!(cfg.stream_storage, StreamStorage::Memory);+ assert_eq!(cfg.stream_num_replicas, 1);+ },+ );+ }++ #[test]+ fn test_stream_storage_parse_spellings() {+ assert_eq!(StreamStorage::parse("Memory"), Some(StreamStorage::Memory));+ assert_eq!(StreamStorage::parse(" FILE "), Some(StreamStorage::File));+ assert_eq!(StreamStorage::parse("disk"), Some(StreamStorage::File));+ assert_eq!(StreamStorage::parse(""), None);+ assert_eq!(StreamStorage::parse("s3"), None);+ }+#[test]fn test_admin_token_populates_config_service_token() {with_env(&[("SIE_ADMIN_TOKEN", "super-secret")], || {@@ -1575,12 +1754,17 @@ mod tests {multi_router: false,request_timeout: 0.0,max_stream_pending: 0,+ max_lane_in_flight_items: 0,+ lane_backpressure_enforce: false,stream_max_age_s: 0,+ stream_storage: StreamStorage::Memory,+ stream_num_replicas: 1,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),configured_physical_lanes: PhysicalLaneCatalog::default(),static_queue_pools: Vec::new(),model_aliases: HashMap::new(),+ published_model_aliases: Default::default(),bundles_dir: String::new(),models_dir: String::new(),config_service_url: None,diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex a97812f0e..675cf9947 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -470,12 +470,18 @@ mod tests {multi_router: false,request_timeout: 30.0,max_stream_pending: 50_000,+ max_lane_in_flight_items:+ crate::queue::lane_admission::DEFAULT_MAX_LANE_IN_FLIGHT_ITEMS,+ lane_backpressure_enforce: false,stream_max_age_s: 1_800,+ stream_storage: crate::config::StreamStorage::Memory,+ stream_num_replicas: 1,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),configured_physical_lanes: Default::default(),static_queue_pools: Vec::new(),model_aliases: HashMap::new(),+ published_model_aliases: Default::default(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),payload_store_url: String::new(),diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 1530457f7..82254eb3d 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -59,6 +59,7 @@ pub async fn get_models(.is_none_or(|p| p.visible(name, ext))}).collect();+ let aliases_by_target = published_aliases_by_target(state.as_ref());let models: Vec<serde_json::Value> = model_names.iter().map(|name| {@@ -70,6 +71,7 @@ pub async fn get_models(};attach_model_revision(&mut body, state.as_ref(), name);attach_pending_generation(&mut body, state.as_ref(), name);+ attach_model_aliases(&mut body, &aliases_by_target, name);body}).collect();@@ -179,10 +181,56 @@ pub async fn get_model(}attach_model_revision(&mut body, state.as_ref(), &canonical_model);attach_pending_generation(&mut body, state.as_ref(), &canonical_model);+ // Reached only after the same #1841 visibility gate the listing applies,+ // so a detail hit on an invisible model 404s before this line.+ attach_model_aliases(+ &mut body,+ &published_aliases_by_target(state.as_ref()),+ &canonical_model,+ );(StatusCode::OK, Json(body)).into_response()}+/// Reverse the alias table once: canonical target -> its published aliases.+///+/// Built per request rather than per model — the map is small and the listing+/// walks hundreds of entries. Only [`Config::published_model_aliases`] members+/// appear, so the compiled-in `code`/`sql`/`guard` routing defaults stay+/// private (#2843); publishing them would name a model absent from the managed+/// catalog and freeze an internal default into public contract.+///+/// Nothing here decides VISIBILITY. The caller attaches aliases only to models+/// that already survived the `#1841` org filter, so an alias pointing at a+/// model this caller cannot see is never emitted — there is no listing in+/// which to emit it. That ordering is the whole guard; keep it.+fn published_aliases_by_target(state: &AppState) -> HashMap<String, Vec<String>> {+ let mut by_target: HashMap<String, Vec<String>> = HashMap::new();+ for (alias, target) in &state.config.model_aliases {+ if !state.config.published_model_aliases.contains(alias) {+ continue;+ }+ by_target+ .entry(target.clone())+ .or_default()+ .push(alias.clone());+ }+ for aliases in by_target.values_mut() {+ aliases.sort();+ }+ by_target+}++fn attach_model_aliases(body: &mut Value, by_target: &HashMap<String, Vec<String>>, model: &str) {+ // Always emit the key, even when empty: a consumer distinguishing "no+ // aliases" from "this gateway predates the field" needs the difference to+ // be in the payload, not in its absence.+ let aliases = by_target.get(model).cloned().unwrap_or_default();+ if let Some(map) = body.as_object_mut() {+ map.insert("aliases".to_string(), json!(aliases));+ }+}+fn attach_model_revision(body: &mut Value, state: &AppState, model: &str) {let Some(revision) = state.model_registry.get_model_revision(model) else {return;@@ -297,12 +345,18 @@ mod route_tests {multi_router: false,request_timeout: 30.0,max_stream_pending: 50_000,+ max_lane_in_flight_items:+ crate::queue::lane_admission::DEFAULT_MAX_LANE_IN_FLIGHT_ITEMS,+ lane_backpressure_enforce: false,stream_max_age_s: 1_800,+ stream_storage: crate::config::StreamStorage::Memory,+ stream_num_replicas: 1,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),configured_physical_lanes: Default::default(),static_queue_pools: Vec::new(),model_aliases: HashMap::new(),+ published_model_aliases: Default::default(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),payload_store_url: String::new(),@@ -315,6 +369,17 @@ mod route_tests {// Returned tempdirs must outlive the router so they drop after the test.async fn build_router_with_state(+ ) -> (Router, Arc<AppState>, tempfile::TempDir, tempfile::TempDir) {+ build_router_with_aliases(HashMap::new(), Vec::new()).await+ }++ /// `build_router_with_state` with an alias table. `published` names the+ /// subset `/v1/models` may advertise; anything in `aliases` but not in+ /// `published` still RESOLVES and stays unlisted, which is exactly how the+ /// compiled-in `code`/`sql`/`guard` built-ins behave (#2843).+ async fn build_router_with_aliases(+ aliases: HashMap<String, String>,+ published: Vec<&str>,) -> (Router, Arc<AppState>, tempfile::TempDir, tempfile::TempDir) {let bundles_dir = tempfile::TempDir::new().unwrap();let models_dir = tempfile::TempDir::new().unwrap();@@ -329,10 +394,13 @@ mod route_tests {).unwrap();- let config = Arc::new(test_config(+ let mut base = test_config(bundles_dir.path().to_str().unwrap(),models_dir.path().to_str().unwrap(),- ));+ );+ base.model_aliases = aliases;+ base.published_model_aliases = published.into_iter().map(|name| name.to_string()).collect();+ let config = Arc::new(base);let model_registry = Arc::new(ModelRegistry::new(bundles_dir.path(),models_dir.path(),@@ -656,6 +724,140 @@ mod route_tests {assert_eq!(models[0]["pending_generation"]["total"], 0);}+ #[tokio::test]+ async fn test_list_models_advertises_published_aliases_only() {+ // The discoverability half of #2839: an alias you can send is useless+ // if nothing tells you it exists. `rerank-fast` is catalog-declared and+ // listed; `code` resolves identically but is an internal routing+ // default, so it must not appear.+ let mut aliases = HashMap::new();+ aliases.insert("rerank-fast".to_string(), "BAAI/bge-m3".to_string());+ aliases.insert("code".to_string(), "BAAI/bge-m3".to_string());+ let (app, state, _bundles_dir, _models_dir) =+ build_router_with_aliases(aliases, vec!["rerank-fast"]).await;+ seed_model(&state, "BAAI/bge-m3");++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ let body = body_json(response).await;+ let models = body["models"].as_array().unwrap();+ assert_eq!(models[0]["aliases"], serde_json::json!(["rerank-fast"]));+ }++ #[tokio::test]+ async fn test_list_models_emits_an_empty_alias_list_not_a_missing_key() {+ // A consumer must be able to tell "this model has no aliases" from+ // "this gateway predates the field". Absence cannot carry that.+ let (app, state, _bundles_dir, _models_dir) = build_router_with_state().await;+ seed_model(&state, "BAAI/bge-m3");++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ let body = body_json(response).await;+ let models = body["models"].as_array().unwrap();+ assert_eq!(models[0]["aliases"], serde_json::json!([]));+ }++ #[tokio::test]+ async fn test_list_models_groups_and_sorts_multiple_aliases_per_model() {+ // One model can carry several names — `fastino/gliner2-large-v1` is+ // both knowledge-graph-best and named-entities-best in the live+ // catalog. Order is sorted so the payload is deterministic.+ let mut aliases = HashMap::new();+ aliases.insert("named-entities-best".to_string(), "BAAI/bge-m3".to_string());+ aliases.insert(+ "knowledge-graph-best".to_string(),+ "BAAI/bge-m3".to_string(),+ );+ let (app, state, _bundles_dir, _models_dir) =+ build_router_with_aliases(aliases, vec!["named-entities-best", "knowledge-graph-best"])+ .await;+ seed_model(&state, "BAAI/bge-m3");++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ let body = body_json(response).await;+ let models = body["models"].as_array().unwrap();+ assert_eq!(+ models[0]["aliases"],+ serde_json::json!(["knowledge-graph-best", "named-entities-best"])+ );+ }++ #[tokio::test]+ async fn test_an_alias_to_an_unlisted_model_is_never_emitted() {+ // The existence-oracle guard. An alias whose target is not in this+ // caller's listing has no entry to attach to, so it cannot leak that+ // the target exists. Structural, not a filter that could be forgotten.+ let mut aliases = HashMap::new();+ aliases.insert("secret-best".to_string(), "org-9/private".to_string());+ let (app, state, _bundles_dir, _models_dir) =+ build_router_with_aliases(aliases, vec!["secret-best"]).await;+ seed_model(&state, "BAAI/bge-m3");++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ let body = serde_json::to_string(&body_json(response).await).unwrap();+ assert!(!body.contains("secret-best"));+ assert!(!body.contains("org-9/private"));+ }++ #[tokio::test]+ async fn test_model_detail_carries_the_same_aliases() {+ let mut aliases = HashMap::new();+ aliases.insert("rerank-fast".to_string(), "BAAI/bge-m3".to_string());+ aliases.insert("code".to_string(), "BAAI/bge-m3".to_string());+ let (app, state, _bundles_dir, _models_dir) =+ build_router_with_aliases(aliases, vec!["rerank-fast"]).await;+ seed_model(&state, "BAAI/bge-m3");++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models/BAAI%2Fbge-m3")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let body = body_json(response).await;+ assert_eq!(body["aliases"], serde_json::json!(["rerank-fast"]));+ }+#[tokio::test]async fn test_list_models_emits_openai_list_shape() {// OpenAI-compat: `/v1/models` must carry the OpenAI list shapediff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 31c6b2da1..37fc43cc1 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -111,7 +111,7 @@ pub fn compat_request_body_limit(_path: &str) -> usize {/// An earlier revision of this constant set 64 MiB and claimed it was "anchored"/// to `queue::publisher::MAX_RESULT_CHUNK_RESERVED_BYTES_PER_REQUEST`. That was/// wrong twice over, and the corrected reasoning is recorded here so it is not-/// re-derived the same way (#2617):+/// re-derived the same way:////// 1. That constant bounds a RESERVATION, not a payload. `result_chunk_reservation_bytes`/// computes `payload × 3 + 4 KiB` and checks the PRODUCT against the 64 MiB@@ -126,18 +126,17 @@ pub fn compat_request_body_limit(_path: &str) -> usize {/// (`MAX_QUEUE_REQUEST_ITEMS` = 4096) a float reply is ~90 MB at 1024 dims and/// ~224 MB at 2560 dims (`Qwen/Qwen3-Embedding-4B`, shipped on this very surface/// in `beta-launch-v1.yaml`). The handler holds roughly four copies at once (the-/// buffer, the parsed tree, the projected `data`, the re-serialised body), and-/// the deployed gateway is a **1 GiB container running 4 requests concurrently**-/// (`sie_cloud/deploy/gateway_app.py`, `GATEWAY_MEMORY_MIB=1024`,-/// `GATEWAY_MAX_INPUTS=4`). Admitting the largest real reply would need several-/// gigabytes. So this is a CHOSEN bound with a stated rationale, not a derived one.+/// buffer, the parsed tree, the projected `data`, and the re-serialised body).+/// Four ~224 MB copies total ~896 MB, or about 1 GB for one request; concurrent+/// requests can therefore drive the process into several gigabytes. So this is+/// a CHOSEN bound with a stated rationale, not a derived one.////// The choice is to hold today's effective bound exactly. 16 MiB is what the/// surface enforces in production right now, so it is provably non-breaking in/// BOTH directions: it refuses nothing that is served today, and it raises-/// per-request heap on that 1 GiB container by nothing. Raising it would trade a-/// clean, diagnosable 413 for an OOM kill that also destroys the three unrelated-/// requests sharing the container — strictly worse than the refusal it removes.+/// per-request heap by nothing. Raising it would trade a clean, diagnosable 413+/// for an OOM kill that can also destroy unrelated concurrent requests —+/// strictly worse than the refusal it removes.////// # What this deliberately does NOT fix///@@ -745,6 +744,10 @@ async fn queue_pool_for_request(manager.queue_pool_for_pool(&normalized).await}+fn catalog_execution_hash_is_ready(bundle_config_hash: &str, uses_catalog_scope: bool) -> bool {+ !uses_catalog_scope || !bundle_config_hash.is_empty()+}+async fn demand_profiles_for_pool(pool_manager: Option<&PoolManager>,pool_name: &str,@@ -810,12 +813,19 @@ fn record_provisioning_response(surface: ProvisioningSurface, status: StatusCode/// Returns the `Retry-After` value the caller should surface (`None` for a/// generic publish failure). The `no consumers` case is handled by the/// caller — it needs a provisioning response / surface-specific retry.-fn record_publish_failure(+///+/// A broker-side rejection at the stream's `max_messages` cap counts as+/// backpressure too. With `DiscardPolicy::New` (see `ensure_stream`) a full+/// work stream refuses the publish with JetStream's "maximum messages+/// exceeded" instead of silently dropping the oldest queued item, and that+/// rejection means the same thing as the gateway-local gate: the lane is+/// saturated and is exactly the one to scale up.+pub(crate) fn record_publish_failure(state: &AppState,physical_lane: &PhysicalLane,err_lower: &str,) -> Option<&'static str> {- if err_lower.contains("backpressure") {+ if err_lower.contains("backpressure") || err_lower.contains("maximum messages exceeded") {telemetry::record_rejected_request(state.demand_tracker.as_ref(),physical_lane,@@ -1343,6 +1353,41 @@ pub async fn proxy_generate(state: State<Arc<AppState>>, req: Request) -> impl I/// every caller a read of the alias table — including targets in another org's/// reserved namespace. It also makes this 404 byte-identical to the #1841/// cross-org one, which is the whole point of answering "not found" there.+/// The one native-surface `MODEL_NOT_FOUND` body.+///+/// Three native call sites answer "this model is not here": the #1841+/// visibility gate, the populated-registry unknown-model arm of+/// [`resolve_bundle_for_request`], and the #3441 pre-governed ordering check in+/// [`resolve_routing`]. They must stay **byte-identical** — the no-oracle+/// property (#2542) is that a hidden model, an absent model, and a model whose+/// governed route was never compiled are one indistinguishable response — so+/// they render through this one function instead of three copies that can drift.+///+/// `requested` is always the CALLER's string, never a resolved/governed id: a+/// resolved id can be an alias target in another org's reserved namespace.+fn unknown_model_response(endpoint: &str, requested: &str) -> Response {+ endpoint_error_response(+ endpoint,+ StatusCode::NOT_FOUND,+ err_code::MODEL_NOT_FOUND,+ oai_type::MODEL_NOT_FOUND,+ oai_code::MODEL_NOT_FOUND,+ Some("model"),+ format!("Model '{}' not found", requested),+ )+}++/// Is this id absent from a registry that has models?+///+/// The exact condition the populated-registry 404 arm below fires on, named so+/// the #3441 ordering check in [`resolve_routing`] can ask the same question+/// ahead of governed lookup without restating it. An EMPTY registry is+/// deliberately not "absent": that is the pre-bootstrap deployment path, which+/// falls back to the caller's bundle override rather than 404ing.+fn absent_from_populated_registry(registry: &ModelRegistry, model_name: &str) -> bool {+ !registry.model_exists(model_name) && registry.has_any_models()+}+fn resolve_bundle_for_request(registry: &ModelRegistry,model_name: &str,@@ -1393,15 +1438,7 @@ fn resolve_bundle_for_request(}}} else if registry.has_any_models() {- return Err(Box::new(endpoint_error_response(- endpoint,- StatusCode::NOT_FOUND,- err_code::MODEL_NOT_FOUND,- oai_type::MODEL_NOT_FOUND,- oai_code::MODEL_NOT_FOUND,- Some("model"),- format!("Model '{}' not found", requested),- )));+ return Err(Box::new(unknown_model_response(endpoint, requested)));} else if bundle_override.is_empty() {"default".to_string()} else {@@ -1809,15 +1846,7 @@ async fn resolve_routing(.as_ref().is_some_and(|p| !p.visible(&model_name, ext)){- return Err(Box::new(endpoint_error_response(- endpoint,- StatusCode::NOT_FOUND,- err_code::MODEL_NOT_FOUND,- oai_type::MODEL_NOT_FOUND,- oai_code::MODEL_NOT_FOUND,- Some("model"),- format!("Model '{}' not found", model),- )));+ return Err(Box::new(unknown_model_response(endpoint, &model)));}// #2542 deployment serving policy on the RESOLVED id: the authoritative// "we do not serve this model here" verdict (the managed service's §6.5@@ -1899,6 +1928,32 @@ async fn resolve_routing(if generation_intent == Some(GenerationRequestIntent::Grammar) {route_grammar_to_profile(&state.model_registry, &mut dispatch_model);}+ // #3441 ordering: a model this data plane does not have is answered by the+ // populated-registry `MODEL_NOT_FOUND` 404 BEFORE the governed lookup runs.+ //+ // Governed lookup is keyed on `(customer_model, intent)`, so an unknown id is+ // simply a policy miss, and a miss fails closed as a 503 — the correct verdict+ // for *deployment drift* (a catalog model whose route was not compiled), but+ // the wrong one for a model that does not resolve here at all. §7.5 of the+ // managed-service design separates the two: unresolvable → terminal 404,+ // routable-but-broken → retryable 503. Without this check a typo'd or retired+ // model id (prod-US, 2026-08-14: `Qwen__Qwen3-4B-Instruct-2507`) told the+ // caller to retry forever against a model that will never exist.+ //+ // Only the native generate path needs it: the OpenAI body-model routes reach+ // `resolve_model_and_bundle`'s identical 404 before `resolve_generation_route`+ // performs the same governed lookup. Scoped to `generation_intent` because+ // governed lookup is the only step that can precede the 404 — for every other+ // native endpoint `resolve_bundle_for_request` below is still the first+ // verdict, and reordering it there would change nothing.+ //+ // Sealed custom models (#1841) already returned above; they are legitimately+ // absent from the catalog registry and must not be caught here.+ if generation_intent.is_some()+ && absent_from_populated_registry(&state.model_registry, &model_name)+ {+ return Err(Box::new(unknown_model_response(endpoint, &model)));+ }let governed_route = if let Some(intent) = generation_intent {match governed_generation_route(state, &model_name, &dispatch_model, intent) {Ok(route) => route,@@ -2241,10 +2296,20 @@ async fn proxy_request_inner(let requested_pool = normalize_pool_name(&pool_name);return build_pool_not_found_response_for_surface(&requested_pool, provisioning_surface);};- let (bundle_config_hash, model_revision) =- state- .model_registry- .bundle_execution_evidence(&bundle, &hash_pool, &dispatch_model);+ let (bundle_config_hash, model_revision, uses_catalog_scope) = state+ .model_registry+ .bundle_execution_evidence(&bundle, &hash_pool, &dispatch_model);+ if !catalog_execution_hash_is_ready(&bundle_config_hash, uses_catalog_scope) {+ return endpoint_error_response(+ endpoint,+ StatusCode::SERVICE_UNAVAILABLE,+ err_code::QUEUE_UNAVAILABLE,+ oai_type::SERVER_ERROR,+ oai_code::TRANSPORT_FAILURE,+ None,+ "Model execution evidence is unavailable while configuration converges",+ );+ }// Resolve the effective pool in one shot. `resolve_effective_pool`// folds the demand-tracking probe ("was there an exact@@ -4119,6 +4184,11 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {"cancelled" => oai_code::CANCELLED,"rate_limit_exceeded" => oai_code::RATE_LIMIT_EXCEEDED,COLD_START_RATE_LIMITED_ERROR_CODE => COLD_START_RATE_LIMITED_ERROR_CODE,+ // Terminal empty-output stamp (#3136): forwarded verbatim so+ // buffered consumers see the same typed code the SSE path+ // already streams. Same 500 / ``server_error`` / no-retry+ // convention as the generic ``inference_error`` fallback.+ oai_code::EMPTY_MODEL_OUTPUT => oai_code::EMPTY_MODEL_OUTPUT,_ => "inference_error",};let mut body = json_openai_error(message.clone(), err_type, None, stable_code);@@ -6558,10 +6628,21 @@ async fn resolve_generation_route(ProvisioningSurface::OpenAiCompat,));};- let (bundle_config_hash, model_revision) =- state- .model_registry- .bundle_execution_evidence(&bundle, &hash_pool, dispatch_model);+ let (bundle_config_hash, model_revision, uses_catalog_scope) = state+ .model_registry+ .bundle_execution_evidence(&bundle, &hash_pool, dispatch_model);+ if !catalog_execution_hash_is_ready(&bundle_config_hash, uses_catalog_scope) {+ return Err((+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json_openai_error(+ "Model execution evidence is unavailable while configuration converges",+ oai_type::SERVER_ERROR,+ None,+ oai_code::TRANSPORT_FAILURE,+ )),+ )+ .into_response());+ }// #1841: pin the sealed engine marker (see the top-of-fn note); a bundle-less// "sealed" bundle has no BundleInfo, so the else-branch would yield DEFAULT_ENGINE.let engine = match &sealed {@@ -6959,7 +7040,7 @@ async fn proxy_chat_inner(// 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.+ // ``inputs.image: true``. Mirrors the grammar validation gates.let has_images = params.messages.iter()@@ -9431,7 +9512,17 @@ fn result_decode_error_value(r: &publisher::WorkResult, message: String) -> serd})}-fn aggregate_score_usage(successful: &[&publisher::WorkResult]) -> Option<Value> {+/// The `usage` block for an items-shaped queue response, summed from the+/// workers' own authoritative [`publisher::UnitCounts`].+///+/// Serves `score` and `encode` alike: the two envelopes report the same shape+/// from the same numbers, so a caller reading `usage` on either endpoint reads+/// the post-tokenization count the worker measured — never a character+/// estimate. `None` when ANY successful result lacks the dimension: a partial+/// sum is not a measurement of the request, and omitting is the only honest+/// rendering of "this path could not count". A unit of `0` is a measurement and+/// is reported as such.+fn aggregate_result_usage(successful: &[&publisher::WorkResult]) -> Option<Value> {if successful.is_empty() {return None;}@@ -9474,8 +9565,12 @@ fn build_queue_success_body("items"};- let usage = if endpoint == "score" {- aggregate_score_usage(successful)+ // `encode` joins `score` here so the queue ingress reports the same+ // authoritative counts the direct ingress puts on `EncodeResponse.usage`,+ // and so the `/v1/embeddings` compatibility layer has a real number to+ // render on both paths instead of a character estimate.+ let usage = if endpoint == "score" || endpoint == "encode" {+ aggregate_result_usage(successful)} else {None};@@ -12094,6 +12189,47 @@ fn estimate_embedding_tokens(texts: &[String]) -> u64 {u64::max(1, (total / 4) as u64)}+/// `usage.sie_token_source` — whether the emitted `/v1/embeddings` token count+/// is the worker's exact post-tokenization number or the request-time+/// character approximation. Reported because the two cannot be told apart from+/// the numbers alone, and only one of them reconciles with a token bill.+const USAGE_SOURCE_WORKER: &str = "worker";+const USAGE_SOURCE_ESTIMATE: &str = "character_estimate";++/// The authoritative token count the inner `/v1/encode` reply reported, if any.+///+/// Both encode ingresses now carry it: the direct one puts the worker's+/// `input_token_counts` on `EncodeResponse.usage`, and the queue one aggregates+/// the same numbers out of the workers' `UnitCounts`+/// ([`aggregate_result_usage`]). `None` means neither could count, never that+/// the count was zero — a measured `0` (a request that read no text) arrives+/// here as `Some(0)` and is reported as `0`.+fn encode_usage_input_tokens(encode_response: &Value) -> Option<u64> {+ encode_response.get("usage")?.get("input_tokens")?.as_u64()+}++/// The `usage` block `/v1/embeddings` reports, from the encode reply the+/// request actually produced.+///+/// The worker's exact count wins. When the encode reply carried none, the+/// request-time character estimate is emitted rather than dropping `usage`+/// altogether — a successful embedding must not turn into an error over a+/// reporting field, and the `openai` client cannot parse a response without+/// `usage` at all — but it is LABELLED `character_estimate`, so a caller+/// reconciling `usage` against a token bill can see which of the two numbers+/// they hold instead of silently trusting `chars / 4`.+fn embeddings_usage(encode_response: &Value, estimated_tokens: u64) -> Value {+ let (prompt_tokens, token_source) = match encode_usage_input_tokens(encode_response) {+ Some(tokens) => (tokens, USAGE_SOURCE_WORKER),+ None => (estimated_tokens, USAGE_SOURCE_ESTIMATE),+ };+ json!({+ "prompt_tokens": prompt_tokens,+ "total_tokens": prompt_tokens,+ "sie_token_source": token_source,+ })+}+/// The native `/v1/encode/{model}` body ONE `/v1/embeddings` request rewrites/// itself into before the in-process re-dispatch.///@@ -12512,12 +12648,12 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Re);}};- let token_est = token_count;+ let usage = embeddings_usage(&enc, token_count);let out = json!({"object": "list","data": data,"model": model_str,- "usage": {"prompt_tokens": token_est, "total_tokens": token_est},+ "usage": usage,});let mut out_resp = (StatusCode::OK, Json(out)).into_response();for (k, v) in enc_headers.iter() {@@ -13039,8 +13175,7 @@ pub async fn proxy_moderations() -> Response {(StatusCode::NOT_IMPLEMENTED,Json(json_openai_error(- "the /v1/moderations endpoint is not implemented; no moderation model is configured. \- See product/research: Tier 0 abuse/content-safety work.",+ "the /v1/moderations endpoint is not implemented; no moderation model is configured.",oai_type::SERVER_ERROR,None,"not_implemented",@@ -13710,6 +13845,13 @@ mod tests {assert!(headers.get("x-sie-model-revision").is_none());}+ #[test]+ fn test_catalog_execution_hash_is_fail_closed_for_every_known_model() {+ assert!(!catalog_execution_hash_is_ready("", true));+ assert!(catalog_execution_hash_is_ready(&"a".repeat(64), true));+ assert!(catalog_execution_hash_is_ready("", false));+ }+#[test]fn test_execution_identity_header_requires_valid_unanimous_worker_proof() {let identity = "c".repeat(64);@@ -13966,12 +14108,18 @@ mod tests {multi_router: false,request_timeout: 30.0,max_stream_pending: 1024,+ max_lane_in_flight_items:+ crate::queue::lane_admission::DEFAULT_MAX_LANE_IN_FLIGHT_ITEMS,+ lane_backpressure_enforce: false,stream_max_age_s: 300,+ stream_storage: crate::config::StreamStorage::Memory,+ stream_num_replicas: 1,configured_gpus: vec!["l4".to_string()],gpu_profile_map,configured_physical_lanes: configured_physical_lanes.clone(),static_queue_pools: Vec::new(),model_aliases: std::collections::HashMap::new(),+ published_model_aliases: Default::default(),bundles_dir: bundles_dir.path().to_string_lossy().to_string(),models_dir: models_dir.path().to_string_lossy().to_string(),config_service_url: None,@@ -14098,14 +14246,31 @@ mod tests {(Arc::new(state), policy)}- struct EmptyGenerationRoutePolicy;+ /// A policy that is installed but compiles no route at all, and records every+ /// id it was asked about. The recording is what makes the #3441 ordering+ /// observable: an unknown model must 404 without the policy ever being+ /// consulted, and "was consulted" is not visible in the status code alone.+ #[derive(Default)]+ struct EmptyGenerationRoutePolicy {+ asked: std::sync::Mutex<Vec<String>>,+ }++ impl EmptyGenerationRoutePolicy {+ fn asked(&self) -> Vec<String> {+ self.asked.lock().expect("asked lock").clone()+ }+ }impl crate::server::GenerationRoutePolicy for EmptyGenerationRoutePolicy {fn resolve(&self,- _customer_model: &str,+ customer_model: &str,_intent: GenerationRequestIntent,) -> Option<GovernedGenerationRoute> {+ self.asked+ .lock()+ .expect("asked lock")+ .push(customer_model.to_string());None}}@@ -14391,7 +14556,7 @@ mod tests {}),);- let (bundle_hash, _) = state+ let (bundle_hash, _, _) = state.model_registry.bundle_execution_evidence("default", "default", "org/g");let mut worker_profiles = profiles;@@ -14684,7 +14849,7 @@ mod tests {pool_manager.create_default_pool().await;let mut state = admission_test_state(pool_manager);state.model_registry = Arc::new(grammar_routed_registry());- install_generation_policy(&mut state, Arc::new(EmptyGenerationRoutePolicy));+ install_generation_policy(&mut state, Arc::new(EmptyGenerationRoutePolicy::default()));let state = Arc::new(state);let native = proxy_request(@@ -14815,6 +14980,210 @@ mod tests {}}+ /// A governed managed deployment whose registry holds exactly one generation+ /// model (`org/g`, with its `:no-spec` grammar variant) and whose installed+ /// policy compiles no route at all — so every governed lookup that runs is a+ /// miss, and a miss is a 503. Also carries an operator alias onto a model the+ /// data plane does not have, so the alias spelling can be exercised too.+ async fn governed_deployment_with_no_compiled_routes(+ ) -> (Arc<AppState>, Arc<EmptyGenerationRoutePolicy>) {+ let pool_manager = Arc::new(PoolManager::new(vec!["l4".to_string()]));+ pool_manager.create_default_pool().await;+ let mut state = admission_test_state(pool_manager);+ state.model_registry = Arc::new(grammar_routed_registry());+ let mut config = (*state.config).clone();+ config+ .model_aliases+ .insert("retired".to_string(), "vendor/missing".to_string());+ state.config = Arc::new(config);+ let policy = Arc::new(EmptyGenerationRoutePolicy::default());+ install_generation_policy(&mut state, policy.clone());+ (Arc::new(state), policy)+ }++ fn openai_error(body: &serde_json::Value, path: &str) -> (String, String, String) {+ let error = &body["error"];+ for field in ["type", "code", "param"] {+ assert!(+ error[field].is_string(),+ "{path}: OpenAI error envelope is missing `{field}`: {body}"+ );+ }+ (+ error["type"].as_str().expect("type").to_string(),+ error["code"].as_str().expect("code").to_string(),+ error["param"].as_str().expect("param").to_string(),+ )+ }++ /// #3441 ordering lock on the NATIVE PUBLIC ROUTE: a model that does not+ /// resolve in this data plane is answered `404 MODEL_NOT_FOUND` before the+ /// governed `(customer_model, intent)` lookup can report its miss as a 503.+ ///+ /// Driven through `proxy_request`, not `governed_generation_route`: the+ /// helper-level test proves a miss fails closed, which is precisely the+ /// verdict that used to leak onto this route, so it cannot observe the+ /// ordering. `policy.asked()` is the ordering evidence — the status code alone+ /// cannot distinguish "404 first" from "asked, missed, then 404 anyway".+ ///+ /// The spellings cover the ways one absent id can reach the route: the SDK+ /// `__` form (the prod-US 2026-08-14 report), percent-encoded and literal+ /// slashes, case folding, a `:profile` suffix, an explicit `bundle:/` pin, and+ /// an operator alias whose target is absent. Each runs with and without a+ /// grammar block, because grammar is the other intent the governed key carries.+ #[tokio::test]+ async fn native_generate_unknown_model_404s_before_the_governed_lookup() {+ let (state, policy) = governed_deployment_with_no_compiled_routes().await;+ let bodies = [+ serde_json::json!({"prompt": "hello", "max_new_tokens": 4}),+ serde_json::json!({+ "prompt": "hello",+ "max_new_tokens": 4,+ "grammar": {"json_schema": {"type": "object"}}+ }),+ ];++ for path in [+ "/v1/generate/Qwen__Qwen3-4B-Instruct-2507",+ "/v1/generate/vendor%2Fmissing",+ "/v1/generate/vendor/missing",+ "/v1/generate/VENDOR__MISSING",+ "/v1/generate/vendor%2Fmissing%3Ano-spec",+ "/v1/generate/default%3A%2Fvendor%2Fmissing",+ "/v1/generate/retired",+ ] {+ for body in &bodies {+ let response = proxy_request(+ State(Arc::clone(&state)),+ json_request(path, body.clone()),+ "generate",+ )+ .await;+ assert_eq!(+ response.status(),+ StatusCode::NOT_FOUND,+ "{path} must be terminally not-found, not a retryable 503"+ );+ let body = to_bytes(response.into_body(), 64 * 1024)+ .await+ .expect("body");+ let body: serde_json::Value = serde_json::from_slice(&body).expect("error JSON");+ assert_eq!(+ openai_error(&body, path),+ (+ "model_not_found".to_string(),+ "model_not_found".to_string(),+ "model".to_string()+ ),+ "{path}"+ );+ }+ }+ assert!(+ policy.asked().is_empty(),+ "governed lookup ran for models this deployment does not have: {:?}",+ policy.asked()+ );++ // The control, and the half of the contract this fix must NOT widen: a+ // model the registry DOES have, whose governed route was never compiled,+ // is deployment drift. It still fails closed as 503 — and the policy is+ // consulted, which is what proves the 404 above is about absence and not+ // about the governed step having been skipped wholesale.+ let known = proxy_request(+ State(Arc::clone(&state)),+ json_request(+ "/v1/generate/org%2Fg",+ serde_json::json!({"prompt": "hello", "max_new_tokens": 4}),+ ),+ "generate",+ )+ .await;+ assert_eq!(known.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(policy.asked(), vec!["org/g".to_string()]);+ }++ /// #2542 no-oracle rendering, carried onto the #3441 path: the governed+ /// deployment's unknown-model 404 must be **byte-identical** to the one the+ /// same registry gives with no policy installed. If the governed surface grew+ /// its own wording, the response would tell a caller whether this deployment+ /// governs generation at all.+ #[tokio::test]+ async fn governed_unknown_model_404_is_byte_identical_to_the_ungoverned_one() {+ let path = "/v1/generate/Qwen__Qwen3-4B-Instruct-2507";+ let body = serde_json::json!({"prompt": "hello", "max_new_tokens": 4});++ let (governed_state, _policy) = governed_deployment_with_no_compiled_routes().await;+ let governed = proxy_request(+ State(governed_state),+ json_request(path, body.clone()),+ "generate",+ )+ .await;+ assert_eq!(governed.status(), StatusCode::NOT_FOUND);++ let (ungoverned_state, _) = governed_deployment_with_no_compiled_routes().await;+ let mut ungoverned_state =+ Arc::try_unwrap(ungoverned_state).unwrap_or_else(|_| panic!("unique test state"));+ ungoverned_state.model_access_policy = None;+ let ungoverned = proxy_request(+ State(Arc::new(ungoverned_state)),+ json_request(path, body),+ "generate",+ )+ .await;+ assert_eq!(ungoverned.status(), StatusCode::NOT_FOUND);++ let governed = to_bytes(governed.into_body(), 64 * 1024)+ .await+ .expect("body");+ let ungoverned = to_bytes(ungoverned.into_body(), 64 * 1024)+ .await+ .expect("body");+ assert_eq!(+ String::from_utf8(governed.to_vec()).expect("utf8"),+ String::from_utf8(ungoverned.to_vec()).expect("utf8"),+ "governed and ungoverned not-found must be one response"+ );+ }++ /// The OpenAI body-model route was already correct (`resolve_model_and_bundle`+ /// runs before `resolve_generation_route`); this pins that the shared+ /// `unknown_model_response` refactor kept it that way, on the same deployment+ /// that exercises the native path above.+ #[tokio::test]+ async fn openai_body_model_keeps_model_not_found_under_a_governed_policy() {+ let (state, policy) = governed_deployment_with_no_compiled_routes().await;+ let chat = proxy_chat(+ State(Arc::clone(&state)),+ json_request(+ "/v1/chat/completions",+ serde_json::json!({+ "model": "Qwen__Qwen3-4B-Instruct-2507",+ "messages": [{"role": "user", "content": "hello"}],+ "max_tokens": 4+ }),+ ),+ )+ .await;+ assert_eq!(chat.status(), StatusCode::NOT_FOUND);+ let body = to_bytes(chat.into_body(), 64 * 1024).await.expect("body");+ let body: serde_json::Value = serde_json::from_slice(&body).expect("error JSON");+ assert_eq!(+ openai_error(&body, "/v1/chat/completions"),+ (+ "model_not_found".to_string(),+ "model_not_found".to_string(),+ "model".to_string()+ )+ );+ assert!(+ policy.asked().is_empty(),+ "governed lookup ran for an unknown OpenAI body model: {:?}",+ policy.asked()+ );+ }+/// A #1841 test policy: reports `visible` per the flag and marks any/// `org-`-prefixed id as sealed. Lets the native resolve path's sealed branch be/// exercised (and its ordering behind the visibility gate be locked) without the@@ -15424,6 +15793,21 @@ mod tests {);state.demand_tracker.clear(&lane);+ // A full work stream rejects the publish at the broker under+ // `DiscardPolicy::New`; that is backpressure by another name, so it+ // must earn the same Retry-After and KEDA demand signal.+ let retry_full = record_publish_failure(+ &state,+ &lane,+ "failed to publish: maximum messages exceeded",+ );+ assert_eq!(retry_full, Some(BACKPRESSURE_RETRY_AFTER));+ assert!(+ state.demand_tracker.active_lanes().contains(&lane),+ "a stream-full rejection must record pending demand for KEDA"+ );+ state.demand_tracker.clear(&lane);+let retry_other = record_publish_failure(&state, &lane, "connection reset by peer");assert_eq!(retry_other, None);assert!(@@ -21009,8 +21393,7 @@ mod tests {/// ``n=1`` (the only currently-implemented value) parses and round-/// trips onto :class:`ChatRequestParams.n`. The wire shape is in- /// place; the chat-handler-side fan-out is the missing piece —- /// see ``product/research/generation-primitive-status.md`` §4.12 (n>1 deferred).+ /// place; gateway-side fan-out for larger values remains deferred.#[test]fn test_chat_params_from_json_n_equals_one_ok() {let mut body = _chat_body_min("m");@@ -22782,6 +23165,39 @@ mod tests {assert_eq!(v["error"]["code"], COLD_START_RATE_LIMITED_ERROR_CODE);}+ /// The worker's typed ``empty_model_output`` terminal (#3136) must reach+ /// buffered consumers verbatim — not flattened to the generic+ /// ``inference_error`` fallback — with the same 500 / ``server_error`` /+ /// no-Retry-After convention buffered inference errors already use+ /// (terminal, not a capacity state).+ #[tokio::test]+ async fn test_streaming_empty_model_output_code_preserved_on_buffered_path() {+ let err = StreamingDriverErr::WorkerError {+ code: oai_code::EMPTY_MODEL_OUTPUT.to_string(),+ message: "model produced no visible output text".to_string(),+ request_id: "req-empty-1".to_string(),+ attempt_id: "att-empty-1".to_string(),+ };+ let resp = build_streaming_error_response(&err);++ assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);+ // Terminal code: never a retry hint.+ assert!(resp.headers().get("retry-after").is_none());+ assert_eq!(+ resp.headers().get("x-sie-request-id").unwrap(),+ "req-empty-1"+ );+ let body = axum::body::to_bytes(resp.into_body(), 16 * 1024)+ .await+ .unwrap();+ let v: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(v["error"]["type"], oai_type::SERVER_ERROR);+ assert_eq!(v["error"]["code"], oai_code::EMPTY_MODEL_OUTPUT);+ assert_eq!(v["error"]["attempt_id"], "att-empty-1");+ // The retry classifier must keep treating it as terminal.+ assert_eq!(worker_error_retry_after(oai_code::EMPTY_MODEL_OUTPUT), None);+ }+async fn assert_streaming_worker_error_is_retryable(code: &'static str,retry_after: &'static str,@@ -22974,8 +23390,8 @@ mod tests {}}- fn successful_score_result(- scores: Value,+ fn successful_item_result(+ payload: Value,units: Option<publisher::UnitCounts>,) -> publisher::WorkResult {publisher::WorkResult {@@ -22983,7 +23399,7 @@ mod tests {request_id: "request".to_string(),item_index: 0,success: true,- result_msgpack: rmp_serde::to_vec_named(&scores).unwrap(),+ result_msgpack: rmp_serde::to_vec_named(&payload).unwrap(),error: None,error_code: None,inference_ms: None,@@ -23002,7 +23418,7 @@ mod tests {#[test]fn test_score_success_body_includes_authoritative_usage_json_and_msgpack() {- let result = successful_score_result(+ let result = successful_item_result(json!([{"item_id": "0", "score": 0.75, "rank": 0}]),Some(publisher::UnitCounts {input_tokens: Some(19),@@ -23027,9 +23443,121 @@ mod tests {}}+ /// The queue ingress reports the worker's own token count on `encode`, so+ /// the two encode ingresses agree and `/v1/embeddings` has an exact number+ /// to render on the managed path too.+ #[test]+ fn test_encode_success_body_includes_authoritative_usage_json_and_msgpack() {+ let result = successful_item_result(+ json!({"id": "0", "dense": {"dims": 2, "dtype": "float32", "values": [0.1, 0.2]}}),+ Some(publisher::UnitCounts {+ input_tokens: Some(19),+ pages: None,+ images: Some(2),+ audio_ms: None,+ pairs: None,+ gpu_second: None,+ output_tokens: None,+ }),+ );+ for use_msgpack in [false, true] {+ let body = build_queue_success_body("encode", "embedder", &[&result], use_msgpack);+ let response: Value = if use_msgpack {+ rmp_serde::from_slice(&body).unwrap()+ } else {+ serde_json::from_slice(&body).unwrap()+ };+ assert_eq!(response["usage"]["input_tokens"], 19);+ assert_eq!(response["usage"]["images"], 2);+ assert_eq!(response["items"][0]["id"], "0");+ }+ }++ /// A worker that authoritatively read no text reports `0`, not a missing+ /// dimension: zero is a measurement, and the caller is entitled to read it.+ #[test]+ fn test_encode_success_body_reports_an_authoritative_zero() {+ let result = successful_item_result(+ json!({"id": "0"}),+ Some(publisher::UnitCounts {+ input_tokens: Some(0),+ pages: None,+ images: Some(3),+ audio_ms: None,+ pairs: None,+ gpu_second: None,+ output_tokens: None,+ }),+ );+ let body = build_queue_success_body("encode", "embedder", &[&result], false);+ let response: Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(response["usage"]["input_tokens"], 0);+ assert_eq!(response["usage"]["images"], 3);+ }++ /// No units, no `usage`. Omission is the only honest rendering of "this+ /// path could not count" — the alternative is an invented number.+ #[test]+ fn test_encode_success_body_omits_usage_without_worker_units() {+ let result = successful_item_result(json!({"id": "0"}), None);+ let body = build_queue_success_body("encode", "embedder", &[&result], false);+ let response: Value = serde_json::from_slice(&body).unwrap();+ assert!(response.get("usage").is_none());+ assert_eq!(response["items"][0]["id"], "0");+ }++ /// `/v1/embeddings` reports the worker's count, NOT `chars / 4`.+ ///+ /// The estimate for this input is 12 (48 characters); the worker measured+ /// 7. The endpoint that carries the most traffic must not be the one whose+ /// `usage` disagrees with the bill.+ #[test]+ fn test_embeddings_usage_prefers_the_worker_count_over_the_estimate() {+ let texts = vec!["x".repeat(48)];+ let estimate = estimate_embedding_tokens(&texts);+ assert_eq!(estimate, 12, "guard: the estimate is chars / 4");++ let usage = embeddings_usage(&json!({"usage": {"input_tokens": 7}}), estimate);+ assert_eq!(usage["prompt_tokens"], 7);+ assert_eq!(usage["total_tokens"], 7);+ assert_eq!(usage["sie_token_source"], "worker");+ }++ /// An authoritative zero survives the compat layer as `0` and stays+ /// labelled exact — it must not fall through to the estimate, which can+ /// never be zero (it floors at 1).+ #[test]+ fn test_embeddings_usage_reports_an_authoritative_zero() {+ let usage = embeddings_usage(&json!({"usage": {"input_tokens": 0}}), 12);+ assert_eq!(usage["prompt_tokens"], 0);+ assert_eq!(usage["total_tokens"], 0);+ assert_eq!(usage["sie_token_source"], "worker");+ }++ /// With no authoritative count the estimate is still emitted — dropping+ /// `usage` would break every OpenAI client on a successful embedding — but+ /// it says so.+ #[test]+ fn test_embeddings_usage_labels_the_character_estimate_fallback() {+ for encode_response in [+ json!({"items": []}),+ json!({"usage": {}}),+ json!({"usage": {"input_tokens": "seven"}}),+ json!({"usage": null}),+ ] {+ let usage = embeddings_usage(&encode_response, 12);+ assert_eq!(usage["prompt_tokens"], 12);+ assert_eq!(usage["total_tokens"], 12);+ assert_eq!(+ usage["sie_token_source"], "character_estimate",+ "an estimate presented as exact is the defect being fixed: {encode_response}",+ );+ }+ }+#[test]fn test_score_success_body_omits_unavailable_usage_fields() {- let result = successful_score_result(+ let result = successful_item_result(json!([{"item_id": "0", "score": 0.75, "rank": 0}]),Some(publisher::UnitCounts {input_tokens: Some(19),@@ -23049,7 +23577,7 @@ mod tests {#[test]fn test_score_usage_aggregation_rejects_partial_worker_counts() {- let complete = successful_score_result(+ let complete = successful_item_result(json!([]),Some(publisher::UnitCounts {input_tokens: Some(19),@@ -23061,7 +23589,7 @@ mod tests {output_tokens: None,}),);- let missing_tokens = successful_score_result(+ let missing_tokens = successful_item_result(json!([]),Some(publisher::UnitCounts {input_tokens: None,@@ -23073,12 +23601,12 @@ mod tests {output_tokens: None,}),);- assert!(aggregate_score_usage(&[&complete, &missing_tokens]).is_none());+ assert!(aggregate_result_usage(&[&complete, &missing_tokens]).is_none());}#[test]fn test_score_usage_aggregation_rejects_overflow() {- let maximum = successful_score_result(+ let maximum = successful_item_result(json!([]),Some(publisher::UnitCounts {input_tokens: Some(u64::MAX),@@ -23090,7 +23618,7 @@ mod tests {output_tokens: None,}),);- let one = successful_score_result(+ let one = successful_item_result(json!([]),Some(publisher::UnitCounts {input_tokens: Some(1),@@ -23102,7 +23630,7 @@ mod tests {output_tokens: None,}),);- assert!(aggregate_score_usage(&[&maximum, &one]).is_none());+ assert!(aggregate_result_usage(&[&maximum, &one]).is_none());}#[test]@@ -23643,7 +24171,7 @@ mod tests {for (marker, end, marked_constructor) in [("// From here the worker has already run and reported its units, so EVERY",- "let token_est = token_count;",+ "let usage = embeddings_usage(&enc, token_count);","return compat_translation_fault(",),(diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex 77227f7c8..1d7adc9fe 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -230,16 +230,12 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {"no_consumers",);Some(crate::handlers::proxy::PROVISIONING_RETRY_AFTER)- } else if lower.contains("backpressure") {- telemetry::record_rejected_request(- state.demand_tracker.as_ref(),- &physical_lane,- "backpressure",- );- state.demand_tracker.record(&physical_lane);- Some("5")} else {- None+ // Shared with the buffered and streaming paths rather than+ // re-derived here: this arm used to match only "backpressure"+ // and so missed the broker's own stream-full rejection, which+ // means the same thing.+ crate::handlers::proxy::record_publish_failure(state, &physical_lane, &lower)};return crate::handlers::proxy::build_streaming_publish_failed_for_sse(&e, retry_after);}@@ -1272,6 +1268,12 @@ fn build_chat_chunk_event("code": err.code,}),);+ // Gateway request id, in-band on the ERROR chunk only (#3136):+ // a streamed response has no terminal headers, and the+ // ``chatcmpl-*`` id is not the correlation key server logs use.+ // Additive top-level member — named to match the SIE-native+ // generate error chunk — that OpenAI clients ignore.+ obj.insert("request_id".to_string(), json!(chunk.request_id));}}body@@ -1470,7 +1472,11 @@ async fn send_error_chunk("type": "server_error","param": Value::Null,"code": code,- }+ },+ // Gateway request id, in-band on the ERROR chunk only (#3136) —+ // additive, mirrors the generate-shape member below so SDK+ // consumers can correlate stream failures with gateway logs.+ "request_id": request_id,}),SseEndpoint::Generate => json!({"request_id": request_id,@@ -2101,6 +2107,21 @@ mod tests {assert_eq!(v["error"]["type"], "context_length_exceeded");assert!(v["error"]["param"].is_null());assert_eq!(v["error"]["message"], "prompt too long");+ // #3136: the ERROR chunk carries the gateway request id in-band+ // (additive member; OpenAI clients ignore it) so SDK consumers can+ // correlate stream failures with gateway logs.+ assert_eq!(v["request_id"], "req-test");+ }++ /// #3136 scope guard: ``request_id`` rides ERROR chunks only — normal+ /// deltas and clean terminals keep the exact pre-existing chat shape.+ #[test]+ fn test_sse_chat_non_error_chunks_omit_request_id() {+ let delta = build_chat_chunk_event("chatcmpl-1", 0, "m", &_delta_chunk(0, "Hi"), true);+ assert!(delta.get("request_id").is_none());+ let terminal =+ build_chat_chunk_event("chatcmpl-1", 0, "m", &_terminal_chunk("stop", None), false);+ assert!(terminal.get("request_id").is_none());}// ── Generate (SIE-native) chunk shape ─────────────────────────@@ -2188,6 +2209,9 @@ mod tests {assert!(v["choices"][0]["finish_reason"].is_null());assert_eq!(v["error"]["code"], "first_chunk_timeout");assert_eq!(v["error"]["type"], "server_error");+ // #3136: gateway-synthesized chat error chunks carry the gateway+ // request id in-band, mirroring the generate shape.+ assert_eq!(v["request_id"], "req-1");}#[tokio::test]diff --git a/packages/sie_gateway/src/http_error.rs b/packages/sie_gateway/src/http_error.rsindex 6db575b31..4b08ad52e 100644--- a/packages/sie_gateway/src/http_error.rs+++ b/packages/sie_gateway/src/http_error.rs@@ -144,6 +144,11 @@ pub mod openai_code {pub const RATE_LIMIT_EXCEEDED: &str = "rate_limit_exceeded";/// OpenAI-compatible scale-from-zero / worker provisioning signal.pub const PROVISIONING: &str = "provisioning";+ /// Worker terminal for a generation that finished nominally but produced+ /// no visible output text or tool calls (e.g. private reasoning consumed+ /// the whole budget, #3104/#3136). Terminal and non-retryable: tokens were+ /// genuinely consumed, so it settles exactly like ``inference_error``.+ pub const EMPTY_MODEL_OUTPUT: &str = "empty_model_output";}/// OpenAI-shaped error body:diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rsindex a3253ed8e..a8461f6e8 100644--- a/packages/sie_gateway/src/main.rs+++ b/packages/sie_gateway/src/main.rs@@ -515,22 +515,40 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {Some(client) => {let jetstream = async_nats::jetstream::new(client.clone());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(),- payload_store,- Duration::from_secs_f64(config.request_timeout),- config.max_stream_pending,- Duration::from_secs(config.stream_max_age_s),- ));+ let publisher = Arc::new(+ queue::publisher::WorkPublisher::new(+ jetstream,+ nats_manager.router_id().to_string(),+ payload_store,+ Duration::from_secs_f64(config.request_timeout),+ config.max_stream_pending,+ queue::publisher::WorkStreamConfig {+ max_age: Duration::from_secs(config.stream_max_age_s),+ storage: config.stream_storage.into(),+ num_replicas: config.stream_num_replicas,+ },+ )+ .with_lane_admission(+ queue::lane_admission::LaneAdmissionControl::new(+ config.max_lane_in_flight_items,+ config.lane_backpressure_enforce,+ config.configured_physical_lanes.clone(),+ ),+ ),+ );if let Err(e) = publisher.start_inbox_subscription(&client).await {tracing::warn!(error = %e, "failed to start inbox subscription");}let dlq_jetstream = async_nats::jetstream::new(client.clone());- if let Err(e) =- queue::dlq::DlqListener::start(dlq_jetstream, client.clone()).await+ if let Err(e) = queue::dlq::DlqListener::start(+ dlq_jetstream,+ client.clone(),+ config.stream_storage.into(),+ config.stream_num_replicas,+ )+ .await{tracing::warn!(error = %e, "failed to start DLQ listener");}diff --git a/packages/sie_gateway/src/middleware/audit.rs b/packages/sie_gateway/src/middleware/audit.rsindex c9b825ce2..443b8db64 100644--- a/packages/sie_gateway/src/middleware/audit.rs+++ b/packages/sie_gateway/src/middleware/audit.rs@@ -1,3 +1,18 @@+//! Content-free per-request audit record (`event="api_request"`).+//!+//! # Placement contract+//!+//! The emitted `status` is presented as the status the customer received, so+//! this layer MUST be installed outside every layer that can replace the+//! response it observes. In the OSS composition nothing rewrites a handler+//! response, so [`crate::server::AuditPlacement::Core`] keeps the layer inside+//! the route stack. The managed composition wraps the same routes in billing+//! admission middleware that replaces an inner dispatch-reservation 503 with+//! the customer-facing 402 (`slab_ledger::reservation_failure_response`), so it+//! selects [`crate::server::AuditPlacement::Composition`] and installs this+//! layer outside those gates instead — otherwise the audit record reports the+//! provisional inner status and disagrees with what the client received.+use axum::body::Body;use axum::http::Request;use axum::response::Response;@@ -9,6 +24,7 @@ use tower::{Layer, Service};use tracing::info;use super::auth::mask_token;+use crate::observability::metrics::AdmissionOutcomeSlot;#[derive(Clone)]pub struct AuditLayer;@@ -98,6 +114,14 @@ where.unwrap_or("").to_string();+ // Bounded admission verdict, installed by the outer request-telemetry+ // layer and set by whichever policy gate rejected the request. Cloned+ // out of the extensions here because `inner.call(req)` consumes the+ // request; the slot itself is an `Arc`, so this reads the same cell the+ // gates write. Absent whenever that layer is not installed (telemetry+ // disabled) or the path is not an inference route.+ let admission_slot = req.extensions().get::<AdmissionOutcomeSlot>().cloned();+let mut inner = self.inner.clone();Box::pin(async move {@@ -105,6 +129,12 @@ wherelet elapsed = start.elapsed();let status = response.status().as_u16();+ // Never a raw reason string: a bounded enum label, or empty when no+ // gate recorded a verdict.+ let admission = admission_slot+ .and_then(|slot| slot.get())+ .map(|outcome| outcome.as_str())+ .unwrap_or("");let worker = response.headers()@@ -120,6 +150,7 @@ wheremethod = %method,endpoint = %path,status = status,+ admission = %admission,token_id = %token_id,model = %model,pool = %pool,@@ -147,6 +178,19 @@ fn is_infrastructure_path(path: &str) -> bool {mod tests {use super::*;+ use std::io::Write;+ use std::sync::{Arc, Mutex};++ use axum::extract::State;+ use axum::http::StatusCode;+ use axum::response::IntoResponse;+ use axum::routing::post;+ use axum::Router;+ use tower::ServiceExt;+ use tracing::instrument::WithSubscriber;++ use crate::observability::metrics::AdmissionOutcome;+#[test]fn test_infrastructure_paths() {assert!(is_infrastructure_path("/health"));@@ -154,4 +198,150 @@ mod tests {assert!(is_infrastructure_path("/readyz"));assert!(!is_infrastructure_path("/v1/encode/model"));}++ /// JSON-line sink for the emitted `tracing` events, so the assertions read+ /// the record an operator actually receives rather than a stand-in.+ #[derive(Clone, Default)]+ struct CapturedEvents(Arc<Mutex<Vec<u8>>>);++ impl CapturedEvents {+ /// The single `event="api_request"` record's fields, or `None` when the+ /// layer emitted nothing.+ fn api_request(&self) -> Option<serde_json::Value> {+ let buffer = self.0.lock().expect("captured events");+ let text = String::from_utf8(buffer.clone()).expect("utf8 log lines");+ let mut records: Vec<serde_json::Value> = text+ .lines()+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())+ .map(|record| record["fields"].clone())+ .filter(|fields| fields["event"] == "api_request")+ .collect();+ assert!(records.len() <= 1, "one audit record per request");+ records.pop()+ }+ }++ impl Write for CapturedEvents {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ self.0+ .lock()+ .expect("captured events")+ .extend_from_slice(buf);+ Ok(buf.len())+ }++ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+ }++ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedEvents {+ type Writer = Self;++ fn make_writer(&'a self) -> Self::Writer {+ self.clone()+ }+ }++ /// Drive one request through `router` with every event captured. The+ /// subscriber is attached to the future (not `with_default`) so events+ /// emitted after an await point are still recorded.+ async fn audit_one_request(+ router: Router,+ slot: Option<AdmissionOutcomeSlot>,+ ) -> (StatusCode, Option<serde_json::Value>) {+ let events = CapturedEvents::default();+ let subscriber = tracing_subscriber::fmt()+ .json()+ .with_writer(events.clone())+ .finish();++ let mut request = Request::builder()+ .method("POST")+ .uri("/v1/embeddings")+ .body(Body::empty())+ .expect("request");+ if let Some(slot) = slot {+ request.extensions_mut().insert(slot);+ }++ let response = router+ .oneshot(request)+ .with_subscriber(subscriber)+ .await+ .expect("response");+ (response.status(), events.api_request())+ }++ /// The placement contract in miniature: an admission layer that replaces+ /// the handler response with the customer-facing one is exactly what the+ /// managed slab wrapper does (#3442).+ async fn rewrite_503_to_402(+ State(slot): State<AdmissionOutcomeSlot>,+ req: Request<Body>,+ next: axum::middleware::Next,+ ) -> Response {+ let inner = next.run(req).await;+ if inner.status() == StatusCode::SERVICE_UNAVAILABLE {+ slot.set(AdmissionOutcome::KeySpendLimitExceeded);+ return StatusCode::PAYMENT_REQUIRED.into_response();+ }+ inner+ }++ fn provisional_503_router() -> Router {+ Router::new().route(+ "/v1/embeddings",+ post(|| async { StatusCode::SERVICE_UNAVAILABLE }),+ )+ }++ #[tokio::test]+ async fn audit_inside_a_rewriting_layer_records_the_provisional_status() {+ let slot = AdmissionOutcomeSlot::default();+ let router = provisional_503_router().layer(AuditLayer::new()).layer(+ axum::middleware::from_fn_with_state(slot.clone(), rewrite_503_to_402),+ );++ let (status, record) = audit_one_request(router, Some(slot)).await;+ let record = record.expect("audit record");++ // Documents the defect this placement causes, so a future move back+ // inside a rewriting layer fails loudly instead of silently lying.+ assert_eq!(status, StatusCode::PAYMENT_REQUIRED);+ assert_eq!(record["status"], 503);+ }++ #[tokio::test]+ async fn audit_outside_a_rewriting_layer_records_the_final_status() {+ let slot = AdmissionOutcomeSlot::default();+ let router = provisional_503_router()+ .layer(axum::middleware::from_fn_with_state(+ slot.clone(),+ rewrite_503_to_402,+ ))+ .layer(AuditLayer::new());++ let (status, record) = audit_one_request(router, Some(slot)).await;+ let record = record.expect("audit record");++ assert_eq!(status, StatusCode::PAYMENT_REQUIRED);+ assert_eq!(record["status"], 402);+ // Bounded label, never a free-form reason string.+ assert_eq!(record["admission"], "key_spend_limit_exceeded");+ }++ #[tokio::test]+ async fn audit_admission_is_empty_without_a_recorded_verdict() {+ let router = Router::new()+ .route("/v1/embeddings", post(|| async { StatusCode::OK }))+ .layer(AuditLayer::new());++ let (status, record) = audit_one_request(router, None).await;+ let record = record.expect("audit record");++ assert_eq!(status, StatusCode::OK);+ assert_eq!(record["status"], 200);+ assert_eq!(record["admission"], "");+ }}diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rsindex 92c74b9ec..977b5ac2e 100644--- a/packages/sie_gateway/src/middleware/auth.rs+++ b/packages/sie_gateway/src/middleware/auth.rs@@ -15,13 +15,13 @@ use crate::config::Config;/// Probe paths shared by every gateway surface (auth exemption here,/// audit classification in `middleware::audit`, OpenAPI security-/// patching in `openapi`, and the managed cloud gateway's key auth /-/// route classifier). Kubernetes liveness/readiness probes carry no+/// patching in `openapi`, and downstream key-auth route classifiers).+/// Kubernetes liveness/readiness probes carry no/// credentials; gating them would take the pod out of rotation during/// an auth misconfiguration. `/health` (rich status JSON with worker/// URLs, bundle assignments, queue depth, GPU inventory) is/// intentionally NOT in this list — see `EXEMPT_OPERATIONAL_PATHS`.-/// `/livez` (#1025) is a server-side probe, not a gateway route, so it+/// `/livez` is a server-side probe, not a gateway route, so it/// is deliberately absent. Consumers with deliberate extras compose/// them explicitly instead of re-declaring this pair.pub const PROBE_PATHS: &[&str] = &["/healthz", "/readyz"];@@ -195,7 +195,7 @@ fn is_admin_endpoint(method: &Method, path: &str) -> bool {/// `Bearer <token>` (case-insensitive prefix) or a raw token value.////// Canonical shared implementation: also consumed by `handlers::proxy`-/// and the managed cloud gateway (`sie_gateway_cloud::key_auth`).+/// and downstream authentication layers.pub fn extract_bearer_token(headers: &axum::http::HeaderMap) -> Option<String> {let header = headers.get("authorization")?@@ -442,12 +442,17 @@ mod tests {multi_router: false,request_timeout: 0.0,max_stream_pending: 0,+ max_lane_in_flight_items: 0,+ lane_backpressure_enforce: false,stream_max_age_s: 0,+ stream_storage: crate::config::StreamStorage::Memory,+ stream_num_replicas: 1,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),configured_physical_lanes: Default::default(),static_queue_pools: Vec::new(),model_aliases: HashMap::new(),+ published_model_aliases: Default::default(),bundles_dir: String::new(),models_dir: String::new(),config_service_url: None,diff --git a/packages/sie_gateway/src/observability/metrics.rs b/packages/sie_gateway/src/observability/metrics.rsindex 545ac48b4..cb7f37dea 100644--- a/packages/sie_gateway/src/observability/metrics.rs+++ b/packages/sie_gateway/src/observability/metrics.rs@@ -14,6 +14,7 @@ use opentelemetry::metrics::{Counter, Gauge, Histogram, ObservableGauge};use opentelemetry::trace::SpanContext;use opentelemetry::{global, Context, KeyValue};+use crate::queue::lane_admission::LaneAdmissionOutcome;use crate::state::demand_tracker::{DemandTracker, PhysicalLane};pub const REQUESTS_METRIC_NAME: &str = "sie.gateway.requests";@@ -55,12 +56,18 @@ pub const QUEUE_RESULT_CHUNK_STALE_RETRIES_METRIC_NAME: &str ="sie.gateway.queue.result_chunk.stale_retries";pub const QUEUE_RESULT_CHUNK_RESERVED_BYTES_METRIC_NAME: &str ="sie.gateway.queue.result_chunk.reserved_bytes";+pub const QUEUE_WORKER_POOL_EVENTS_METRIC_NAME: &str = "sie.gateway.queue.worker_pool.events";pub const QUEUE_EVENTS_METRIC_NAME: &str = "sie.gateway.queue.events";+pub const QUEUE_LANE_ADMISSION_DECISIONS_METRIC_NAME: &str =+ "sie.gateway.queue.lane_admission.decisions";pub const PROVISIONING_RESPONSES_METRIC_NAME: &str = "sie.gateway.provisioning.responses";pub const GENERATION_EVENTS_METRIC_NAME: &str = "sie.gateway.generation.events";pub const GENERATION_TTFT_METRIC_NAME: &str = "sie.gateway.generation.ttft";pub const GENERATION_TPOT_METRIC_NAME: &str = "sie.gateway.generation.tpot";pub const GENERATION_TOKENS_METRIC_NAME: &str = "sie.gateway.generation.tokens";+pub const KEY_SNAPSHOT_POLLS_METRIC_NAME: &str = "sie.gateway.key_snapshot.polls";+pub const SETTLEMENT_CONFIRMS_METRIC_NAME: &str = "sie.gateway.settlement.confirms";+pub const SETTLEMENT_CONFIRM_DURATION_METRIC_NAME: &str = "sie.gateway.settlement.confirm.duration";pub const REQUEST_LATENCY_BUCKETS: [f64; 21] = [0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.025, 0.03, 0.04, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75,@@ -79,6 +86,17 @@ pub const GENERATION_DURATION_BUCKETS: [f64; 15] = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0,];+/// The settlement confirm is one control-plane round trip that may internally+/// retry up to four times under a five-second client timeout each, so the+/// interesting range runs from a sub-millisecond local hop to the ~20s worst+/// case. `REQUEST_LATENCY_BUCKETS` is reused as the denominator series, so the+/// shared boundaries below `1.0` are deliberately identical to it — that is+/// what makes "confirm latency as a fraction of buffered response latency"+/// readable off two histograms without a join.+pub const SETTLEMENT_CONFIRM_DURATION_BUCKETS: [f64; 16] = [+ 0.0005, 0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0,+];+/// Runtime catalog allowlist for the bounded managed `lane` dimension.#[allow(dead_code)] // Managed composition API; the standalone binary duplicates this module tree.const LANE_APP_MAP_ENV: &str = "SIE_LANE_APP_MAP";@@ -412,6 +430,27 @@ impl QueueResultOutcome {}}+/// Bound events on a [`crate::queue::keyed_worker_pool::KeyedWorkerPool`].+///+/// Both are saturation of one shard's bounded channel; they differ only in the+/// caller's policy at the bound. `Saturated` means the caller waited for a+/// slot (nothing lost, the caller stalls); `Shed` means the caller declined to+/// wait and left the work to its own retry path.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum QueueWorkerPoolEvent {+ Saturated,+ Shed,+}++impl QueueWorkerPoolEvent {+ fn as_str(self) -> &'static str {+ match self {+ Self::Saturated => "saturated",+ Self::Shed => "shed",+ }+ }+}+/// Bounded validation failure for one chunked queue-result transfer.////// The gateway's result-chunk decoder is the sole source of these values. A@@ -521,6 +560,75 @@ impl ProvisioningSurface {}}+/// Terminal classification of one key-snapshot poll tick.+///+/// The managed gateway polls the control plane's versioned key snapshot on a+/// fixed interval, offering the version it already holds as `If-None-Match`.+/// This enum separates the three outcomes that a bare success/error split+/// hides:+///+/// - `NotModified` — the control plane answered 304. The snapshot body was+/// neither computed nor transferred.+/// - `Installed` — a 200 whose body strictly advanced the held version. The+/// fetch bought new information.+/// - `Discarded` — a 200 whose body did NOT advance the held version, so the+/// replica serialized, transferred, parsed, and then dropped it. This is the+/// wasted-fetch case, and it is deliberately distinguishable from `Installed`+/// rather than folded into one "200" bucket.+/// - `Error` — the tick failed and the previous snapshot is still being served.+#[allow(dead_code)] // Managed composition API; unused by the standalone gateway binary.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum KeySnapshotPollOutcome {+ NotModified,+ Installed,+ Discarded,+ Error,+}++#[allow(dead_code)]+impl KeySnapshotPollOutcome {+ fn as_str(self) -> &'static str {+ match self {+ Self::NotModified => "not_modified",+ Self::Installed => "installed",+ Self::Discarded => "discarded",+ Self::Error => "error",+ }+ }+}++/// Terminal classification of one managed settlement-confirmation attempt on+/// the buffered response path.+///+/// `Skipped` is the branch that took no reservation and therefore never issued+/// a control-plane call. It is counted but contributes no duration observation,+/// so the duration histogram stays a clean measure of what the response+/// actually waited for.+#[allow(dead_code)] // Managed composition API; unused by the standalone gateway binary.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum SettlementConfirmOutcome {+ Success,+ Error,+ Skipped,+}++#[allow(dead_code)]+impl SettlementConfirmOutcome {+ fn as_str(self) -> &'static str {+ match self {+ Self::Success => "success",+ Self::Error => "error",+ Self::Skipped => "skipped",+ }+ }++ /// Whether this outcome awaited a control-plane round trip and therefore+ /// carries a meaningful duration.+ fn is_timed(self) -> bool {+ !matches!(self, Self::Skipped)+ }+}+/// Generation transport stage represented by the consolidated integrity/// counter. Values are deliberately finite and do not carry request data.#[derive(Clone, Copy, Debug, Eq, PartialEq)]@@ -693,12 +801,20 @@ struct GatewayTelemetry {#[allow(dead_code)] // Retains the observable callback registration.queue_result_chunk_reserved_bytes: ObservableGauge<u64>,queue_result_chunk_reserved_bytes_state: Arc<ResultChunkReservationObservableState>,+ queue_worker_pool_events: Counter<u64>,queue_events: Counter<u64>,+ queue_lane_admission_decisions: Counter<u64>,provisioning_responses: Counter<u64>,generation_events: Counter<u64>,generation_ttft: Histogram<f64>,generation_tpot: Histogram<f64>,generation_tokens: Counter<u64>,+ #[allow(dead_code)] // Managed composition API.+ key_snapshot_polls: Counter<u64>,+ #[allow(dead_code)] // Managed composition API.+ settlement_confirms: Counter<u64>,+ #[allow(dead_code)] // Managed composition API.+ settlement_confirm_duration: Histogram<f64>,capacity_snapshot_lock: Mutex<()>,previous_pending_lanes: Mutex<HashSet<LaneKey>>,previous_lease_lanes: Mutex<HashSet<LaneKey>>,@@ -929,6 +1045,13 @@ impl GatewayTelemetry {}).build(),queue_result_chunk_reserved_bytes_state,+ queue_worker_pool_events: meter+ .u64_counter(QUEUE_WORKER_POOL_EVENTS_METRIC_NAME)+ .with_description(+ "Bound events on the gateway's keyed inbox/cleanup worker pools.",+ )+ .with_unit("{event}")+ .build(),queue_events: meter.u64_counter(QUEUE_EVENTS_METRIC_NAME).with_description(@@ -936,6 +1059,14 @@ impl GatewayTelemetry {).with_unit("{event}").build(),+ queue_lane_admission_decisions: meter+ .u64_counter(QUEUE_LANE_ADMISSION_DECISIONS_METRIC_NAME)+ .with_description(+ "Count of per-lane queue admission decisions, including shadow-mode sheds \+ that were recorded but not enforced.",+ )+ .with_unit("{decision}")+ .build(),provisioning_responses: meter.u64_counter(PROVISIONING_RESPONSES_METRIC_NAME).with_description(@@ -967,6 +1098,28 @@ impl GatewayTelemetry {.with_description("Generation tokens accounted from terminal chunk usage.").with_unit("{token}").build(),+ key_snapshot_polls: meter+ .u64_counter(KEY_SNAPSHOT_POLLS_METRIC_NAME)+ .with_description(+ "Terminal outcomes of the managed key-snapshot conditional poll.",+ )+ .with_unit("{poll}")+ .build(),+ settlement_confirms: meter+ .u64_counter(SETTLEMENT_CONFIRMS_METRIC_NAME)+ .with_description(+ "Terminal outcomes of the settlement confirmation on the buffered response path.",+ )+ .with_unit("{confirm}")+ .build(),+ settlement_confirm_duration: meter+ .f64_histogram(SETTLEMENT_CONFIRM_DURATION_METRIC_NAME)+ .with_description(+ "Time a buffered response waited on its control-plane settlement confirmation.",+ )+ .with_unit("s")+ .with_boundaries(SETTLEMENT_CONFIRM_DURATION_BUCKETS.to_vec())+ .build(),capacity_snapshot_lock: Mutex::new(()),previous_pending_lanes: Mutex::new(HashSet::new()),previous_lease_lanes: Mutex::new(HashSet::new()),@@ -1034,6 +1187,22 @@ impl GatewayTelemetry {);}+ #[allow(dead_code)] // Managed composition API.+ fn record_key_snapshot_poll(&self, outcome: KeySnapshotPollOutcome) {+ self.key_snapshot_polls+ .add(1, &[KeyValue::new("outcome", outcome.as_str())]);+ }++ #[allow(dead_code)] // Managed composition API.+ fn record_settlement_confirm(&self, outcome: SettlementConfirmOutcome, duration: Duration) {+ let attributes = [KeyValue::new("outcome", outcome.as_str())];+ self.settlement_confirms.add(1, &attributes);+ if outcome.is_timed() {+ self.settlement_confirm_duration+ .record(duration.as_secs_f64(), &attributes);+ }+ }+fn record_queue_publish(&self, observation: &QueuePublishObservation<'_>) {let attributes =queue_operation_attributes(observation.operation, observation.outcome.as_str());@@ -1064,6 +1233,16 @@ impl GatewayTelemetry {}}+ fn record_queue_worker_pool_event(&self, pool: &'static str, event: QueueWorkerPoolEvent) {+ self.queue_worker_pool_events.add(+ 1,+ &[+ KeyValue::new("pool", pool),+ KeyValue::new("event", event.as_str()),+ ],+ );+ }+fn record_queue_result_chunk_rejection(&self, reason: QueueResultChunkRejectionReason) {self.queue_result_chunk_rejections.add(1, &[KeyValue::new("reason", reason.as_str())]);@@ -1124,6 +1303,22 @@ impl GatewayTelemetry {);}+ fn record_queue_lane_admission_decision(+ &self,+ lane: &PhysicalLane,+ outcome: LaneAdmissionOutcome,+ ) {+ self.queue_lane_admission_decisions.add(+ 1,+ &[+ KeyValue::new("pool", lane.pool().to_string()),+ KeyValue::new("machine_profile", lane.machine_profile().to_string()),+ KeyValue::new("bundle", lane.bundle().to_string()),+ KeyValue::new("outcome", outcome.as_str()),+ ],+ );+ }+fn record_provisioning_response(&self, surface: ProvisioningSurface, status: u16) {let status = if (100..=599).contains(&status) {status@@ -1618,6 +1813,53 @@ pub fn set_messaging_client_ready(ready: bool) {}}+#[allow(dead_code)] // Managed composition API.+fn record_key_snapshot_poll_to(+ target: Option<&GatewayTelemetry>,+ outcome: KeySnapshotPollOutcome,+) -> bool {+ let Some(target) = target else {+ return false;+ };+ target.record_key_snapshot_poll(outcome);+ true+}++/// Count one terminal key-snapshot poll tick.+///+/// The managed key poller calls this once per tick. The `not_modified` versus+/// `installed`/`discarded` split is the conditional-GET hit rate for this+/// replica; `discarded` additionally isolates full snapshot bodies that were+/// fetched and then dropped because the version had not advanced.+#[allow(dead_code)] // Managed composition API.+pub fn record_key_snapshot_poll(outcome: KeySnapshotPollOutcome) {+ let _ = record_key_snapshot_poll_to(telemetry(), outcome);+}++#[allow(dead_code)] // Managed composition API.+fn record_settlement_confirm_to(+ target: Option<&GatewayTelemetry>,+ outcome: SettlementConfirmOutcome,+ duration: Duration,+) -> bool {+ let Some(target) = target else {+ return false;+ };+ target.record_settlement_confirm(outcome, duration);+ true+}++/// Record one settlement-confirmation event on the buffered response path.+///+/// The duration is the wall-clock time the response was held waiting on the+/// control plane, and is recorded only for the two outcomes that actually+/// awaited it. Divide against `sie.gateway.request.duration` on the same+/// process to read the confirm's share of buffered response latency.+#[allow(dead_code)] // Managed composition API.+pub fn record_settlement_confirm(outcome: SettlementConfirmOutcome, duration: Duration) {+ let _ = record_settlement_confirm_to(telemetry(), outcome, duration);+}+fn record_queue_publish_to(target: Option<&GatewayTelemetry>,observation: &QueuePublishObservation<'_>,@@ -1636,6 +1878,20 @@ pub fn record_queue_publish(observation: QueuePublishObservation<'_>) {let _ = record_queue_publish_to(telemetry(), &observation);}+/// Count one per-lane queue admission decision.+///+/// `lane` must be an exact member of the deployment's physical lane catalog.+/// Callers that cannot resolve one omit the observation rather than inventing+/// a synthetic lane — the contract's `gateway_lane_admission_domain` forbids a+/// fallback series, and the lane-free+/// [`record_queue_publish`] counter still carries the aggregate+/// `backpressure` outcome for an enforced shed.+pub fn record_queue_lane_admission_decision(lane: &PhysicalLane, outcome: LaneAdmissionOutcome) {+ if let Some(telemetry) = telemetry() {+ telemetry.record_queue_lane_admission_decision(lane, outcome);+ }+}+/// Record one terminal result-wait event exactly once.pub fn record_queue_result_wait(operation: &str, outcome: QueueResultOutcome, duration: Duration) {if let Some(telemetry) = telemetry() {@@ -1661,6 +1917,24 @@ pub fn record_queue_result_chunk_received(payload_bytes: Option<usize>) {let _ = record_queue_result_chunk_received_to(telemetry(), payload_bytes);}+fn record_queue_worker_pool_event_to(+ target: Option<&GatewayTelemetry>,+ pool: &'static str,+ event: QueueWorkerPoolEvent,+) -> bool {+ let Some(target) = target else {+ return false;+ };+ target.record_queue_worker_pool_event(pool, event);+ true+}++/// Count one bound event on a keyed worker pool. `pool` is a compile-time+/// constant per pool, so the attribute cardinality stays finite.+pub fn record_queue_worker_pool_event(pool: &'static str, event: QueueWorkerPoolEvent) {+ let _ = record_queue_worker_pool_event_to(telemetry(), pool, event);+}+fn record_queue_result_chunk_rejection_to(target: Option<&GatewayTelemetry>,reason: QueueResultChunkRejectionReason,@@ -2036,6 +2310,234 @@ mod tests {assert_eq!(duration_attributes, dispatch_attributes);}+ /// The worker-pool counter is the two fixed pools crossed with the two+ /// saturation events, so its whole series ceiling is four and cannot grow+ /// with traffic, tenants, or models. Pinning the exported name here as+ /// well as the shape: the collector drops metric names absent from its+ /// contract filter, so a rename that misses `telemetry/contract.yaml`+ /// would emit into a void rather than fail loudly.+ #[test]+ fn queue_worker_pool_counter_is_a_closed_pool_by_event_classification() {+ // Uninitialised telemetry must be a no-op, not a panic: these pools run+ // on the inbox hot path, which is live before the provider is built in+ // some test and early-startup paths.+ assert!(+ !record_queue_worker_pool_event_to(None, "inbox", QueueWorkerPoolEvent::Saturated),+ "a None target must return before instrumenting"+ );++ let (telemetry, exporter, provider) = metric_points();+ for (pool, event) in [+ ("inbox", QueueWorkerPoolEvent::Saturated),+ ("inbox", QueueWorkerPoolEvent::Saturated),+ ("payload_cleanup", QueueWorkerPoolEvent::Shed),+ ] {+ telemetry.record_queue_worker_pool_event(pool, event);+ }++ provider.force_flush().expect("force_flush");+ let resource_metrics = exporter.get_finished_metrics().expect("finished metrics");+ let metrics: Vec<_> = resource_metrics+ .iter()+ .flat_map(|resource| resource.scope_metrics())+ .flat_map(|scope| scope.metrics())+ .collect();+ let events = metrics+ .iter()+ .find(|metric| metric.name() == QUEUE_WORKER_POOL_EVENTS_METRIC_NAME)+ .expect("queue worker pool counter");+ assert_eq!(events.name(), "sie.gateway.queue.worker_pool.events");+ assert_eq!(events.unit(), "{event}");+ let AggregatedMetrics::U64(MetricData::Sum(sum)) = events.data() else {+ panic!("queue worker pool events must export as a u64 sum")+ };+ let mut observed: Vec<(String, String, u64)> = sum+ .data_points()+ .map(|point| {+ let mut keys: Vec<&str> = point.attributes().map(|a| a.key.as_str()).collect();+ keys.sort();+ assert_eq!(+ keys,+ vec!["event", "pool"],+ "pool and event are the only dimensions"+ );+ let attributes: HashMap<_, _> = point+ .attributes()+ .map(|attribute| {+ (+ attribute.key.as_str(),+ attribute.value.as_str().into_owned(),+ )+ })+ .collect();+ (+ attributes["pool"].clone(),+ attributes["event"].clone(),+ point.value(),+ )+ })+ .collect();+ observed.sort();+ assert_eq!(+ observed,+ vec![+ ("inbox".to_string(), "saturated".to_string(), 2),+ ("payload_cleanup".to_string(), "shed".to_string(), 1),+ ]+ );+ }++ /// The key-snapshot poll counter is a pure four-value classification with+ /// no other dimension, so its whole series ceiling is four.+ #[test]+ fn key_snapshot_poll_counter_is_a_closed_four_value_classification() {+ let (telemetry, exporter, provider) = metric_points();+ for outcome in [+ KeySnapshotPollOutcome::NotModified,+ KeySnapshotPollOutcome::NotModified,+ KeySnapshotPollOutcome::Installed,+ KeySnapshotPollOutcome::Discarded,+ KeySnapshotPollOutcome::Error,+ ] {+ telemetry.record_key_snapshot_poll(outcome);+ }++ provider.force_flush().expect("force_flush");+ let resource_metrics = exporter.get_finished_metrics().expect("finished metrics");+ let metrics: Vec<_> = resource_metrics+ .iter()+ .flat_map(|resource| resource.scope_metrics())+ .flat_map(|scope| scope.metrics())+ .collect();+ assert_eq!(metrics.len(), 1, "one event owns exactly one instrument");+ let polls = metrics+ .iter()+ .find(|metric| metric.name() == KEY_SNAPSHOT_POLLS_METRIC_NAME)+ .expect("key snapshot poll counter");+ assert_eq!(polls.unit(), "{poll}");+ let AggregatedMetrics::U64(MetricData::Sum(sum)) = polls.data() else {+ panic!("key snapshot polls must export as a u64 sum")+ };+ let mut observed: Vec<(String, u64)> = sum+ .data_points()+ .map(|point| {+ let attributes: Vec<&str> = point.attributes().map(|a| a.key.as_str()).collect();+ assert_eq!(attributes, vec!["outcome"], "outcome is the only dimension");+ let outcome = point+ .attributes()+ .next()+ .expect("outcome")+ .value+ .as_str()+ .into_owned();+ (outcome, point.value())+ })+ .collect();+ observed.sort();+ assert_eq!(+ observed,+ vec![+ ("discarded".to_string(), 1),+ ("error".to_string(), 1),+ ("installed".to_string(), 1),+ ("not_modified".to_string(), 2),+ ]+ );+ }++ /// The confirm that never happened is counted but not timed: `skipped`+ /// increments the counter and contributes no histogram observation, so the+ /// duration series stays a clean measure of what a response actually waited+ /// for.+ #[test]+ fn settlement_confirm_counts_every_branch_but_times_only_the_awaited_ones() {+ let (telemetry, exporter, provider) = metric_points();+ telemetry.record_settlement_confirm(+ SettlementConfirmOutcome::Success,+ Duration::from_millis(25),+ );+ telemetry+ .record_settlement_confirm(SettlementConfirmOutcome::Error, Duration::from_secs(20));+ telemetry+ .record_settlement_confirm(SettlementConfirmOutcome::Skipped, Duration::from_secs(9));++ provider.force_flush().expect("force_flush");+ let resource_metrics = exporter.get_finished_metrics().expect("finished metrics");+ let metrics: Vec<_> = resource_metrics+ .iter()+ .flat_map(|resource| resource.scope_metrics())+ .flat_map(|scope| scope.metrics())+ .collect();+ assert_eq!(metrics.len(), 2, "one event owns exactly two instruments");++ let confirms = metrics+ .iter()+ .find(|metric| metric.name() == SETTLEMENT_CONFIRMS_METRIC_NAME)+ .expect("settlement confirm counter");+ assert_eq!(confirms.unit(), "{confirm}");+ let AggregatedMetrics::U64(MetricData::Sum(sum)) = confirms.data() else {+ panic!("settlement confirms must export as a u64 sum")+ };+ let mut counted: Vec<String> = sum+ .data_points()+ .map(|point| {+ assert_eq!(point.value(), 1);+ point+ .attributes()+ .next()+ .expect("outcome")+ .value+ .as_str()+ .into_owned()+ })+ .collect();+ counted.sort();+ assert_eq!(+ counted,+ vec![+ "error".to_string(),+ "skipped".to_string(),+ "success".to_string()+ ],+ "every branch is counted, including the one that issued no call"+ );++ let duration = metrics+ .iter()+ .find(|metric| metric.name() == SETTLEMENT_CONFIRM_DURATION_METRIC_NAME)+ .expect("settlement confirm duration");+ assert_eq!(duration.unit(), "s");+ let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = duration.data() else {+ panic!("settlement confirm duration must export as an f64 histogram")+ };+ let mut timed: Vec<(String, u64, f64)> = histogram+ .data_points()+ .map(|point| {+ assert_eq!(+ point.bounds().collect::<Vec<_>>(),+ SETTLEMENT_CONFIRM_DURATION_BUCKETS+ );+ let outcome = point+ .attributes()+ .next()+ .expect("outcome")+ .value+ .as_str()+ .into_owned();+ (outcome, point.count(), point.sum())+ })+ .collect();+ timed.sort_by(|a, b| a.0.cmp(&b.0));+ assert_eq!(+ timed,+ vec![+ ("error".to_string(), 1, 20.0),+ ("success".to_string(), 1, 0.025)+ ],+ "the skipped branch awaited nothing and must not be timed"+ );+ }+#[test]fn operational_contract_exports_grouped_bounded_observations() {let (telemetry, exporter, provider) = metric_points();diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 65f8fe4fc..0465cc81d 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -83,6 +83,8 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {AllItemsFailedResponse,BundleRoutingConflictDetail,BundleConflictResponse,+ AudioInput,+ VideoInput,DocumentInput,DenseVector,EncodeParams,@@ -115,6 +117,7 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {OpenAIEmbeddingEncodingFormat,OpenAIEmbeddingInput,OpenAIEmbeddingRequest,+ OpenAIEmbeddingTokenSource,OpenAIEmbeddingUsage,OpenAIEmbeddingVector,OpenAIEmbeddingsListResponse,@@ -164,6 +167,7 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {ScoreResponse,SparseVector,TimingInfo,+ Usage,crate::types::pool::AssignedWorker,crate::types::worker::WorkerInfo)),@@ -1778,8 +1782,23 @@ pub struct OpenAIEmbeddingDataEntry {#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct OpenAIEmbeddingUsage {+ /// Exact post-tokenization input tokens when `sie_token_source` is+ /// `worker`; a character-based approximation when it is+ /// `character_estimate`.pub prompt_tokens: u64,+ /// Equal to `prompt_tokens`; embeddings produce no output tokens.pub total_tokens: u64,+ /// SIE extension. `worker` when the counts above are the model's own+ /// post-tokenization measurement, `character_estimate` when the serving+ /// path reported no counts and the numbers are approximate.+ pub sie_token_source: OpenAIEmbeddingTokenSource,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum OpenAIEmbeddingTokenSource {+ Worker,+ CharacterEstimate,}#[derive(Debug, Serialize, Deserialize, ToSchema)]@@ -2536,6 +2555,25 @@ pub struct ModelInfoWire {pub capabilities: Option<ModelCapabilitiesWire>,#[serde(default)]pub pending_generation: crate::queue::publisher::PendingGenerationSnapshot,+ /// Short task-tier names that resolve to this model, for example+ /// ``["rerank-fast"]``. Send one anywhere a model id is accepted and it+ /// resolves to this entry, billed at this model's rate.+ ///+ /// Always present, and empty when the model has none. Only names declared+ /// by the released catalog or by operator configuration appear here.+ //+ // Maintainer note, deliberately a non-doc comment: everything above this+ // line is published verbatim as the field's description in the public+ // OpenAPI document, so implementation rationale must not join it.+ //+ // Deliberately NOT `#[serde(default)]`: that would drop the field from the+ // schema's `required` set, and a generated client would then type it+ // optional and force a null check on something the handler always emits.+ // The always-emit guarantee is the whole reason the empty list is sent+ // rather than omitted, so the schema has to carry it. `ModelInfoWire` is a+ // documentation type — nothing deserializes it — so requiring the field+ // cannot break parsing of an older payload.+ pub aliases: Vec<String>,}/// Capability summary surfaced on each entry of ``GET /v1/models``.@@ -2709,8 +2747,50 @@ pub struct ResolveConfigResponse {pub profiles: Vec<String>,}+// Native media bytes (`ImageInput` / `AudioInput` / `VideoInput` /+// `DocumentInput` below) carry ONE spelling per ingress, and the schema has to+// name the JSON one.+//+// A bare `Vec<u8>` renders as an ARRAY OF INTEGERS, which is not an encoding+// this edge accepts: `decode_native_media_object_data` converts a base64+// **string** into msgpack `bin` and leaves every other shape untouched, so an+// array would reach the worker as an array and fail its typed `bytes` decode.+// A client generated from that schema is broken before it sends a byte, which+// defeats the point of publishing a schema at all.+//+// On the msgpack ingress the same field is native `bin` and needs no+// transcoding. `content_encoding` describes the JSON spelling — the only one+// an OpenAPI-generated client can produce.+#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct ImageInput {+ /// Media bytes. Base64-encoded on the JSON path; native binary on the msgpack path.+ #[schema(value_type = String, content_encoding = "base64")]+ pub data: Vec<u8>,+ #[serde(default)]+ pub format: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct AudioInput {+ /// Media bytes. Base64-encoded on the JSON path; native binary on the msgpack path.+ #[schema(value_type = String, content_encoding = "base64")]+ pub data: Vec<u8>,+ #[serde(default)]+ pub format: Option<String>,+ // The audio preprocessor rejects a non-positive rate outright+ // ("audio.sample_rate must be a positive integer or null"), so the bound+ // belongs in the published contract rather than only in the error path.+ /// Sample rate in Hz. Must be positive.+ #[serde(default)]+ #[schema(exclusive_minimum = 0)]+ pub sample_rate: Option<u32>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct VideoInput {+ /// Media bytes. Base64-encoded on the JSON path; native binary on the msgpack path.+ #[schema(value_type = String, content_encoding = "base64")]pub data: Vec<u8>,#[serde(default)]pub format: Option<String>,@@ -2718,6 +2798,8 @@ pub struct ImageInput {#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct DocumentInput {+ /// Media bytes. Base64-encoded on the JSON path; native binary on the msgpack path.+ #[schema(value_type = String, content_encoding = "base64")]pub data: Vec<u8>,#[serde(default)]pub format: Option<String>,@@ -2732,6 +2814,10 @@ pub struct ItemInput {#[serde(default)]pub images: Option<Vec<ImageInput>>,#[serde(default)]+ pub audio: Option<AudioInput>,+ #[serde(default)]+ pub video: Option<VideoInput>,+ #[serde(default)]pub document: Option<DocumentInput>,#[serde(default)]pub metadata: Option<Value>,@@ -2884,6 +2970,17 @@ pub struct ScoreUsage {pub images: Option<u64>,}+/// Authoritative worker-emitted usage. Post-tokenization counts, never a+/// character estimate. A reported `0` is a measurement (a request that read no+/// text); an absent block means the serving path could not count. Structurally+/// identical to `ScoreUsage`, which shipped this shape first.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct Usage {+ pub input_tokens: u64,+ #[serde(default)]+ pub images: Option<u64>,+}+#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct RerankResponse {pub model: String,@@ -2948,6 +3045,8 @@ pub struct EncodeResponse {pub items: Vec<EncodeResult>,#[serde(default)]pub timing: Option<TimingInfo>,+ #[serde(default)]+ pub usage: Option<Usage>,}#[derive(Debug, Serialize, Deserialize, ToSchema)]@@ -2996,6 +3095,8 @@ pub struct ExtractResult {pub struct ExtractResponse {pub model: String,pub items: Vec<ExtractResult>,+ #[serde(default)]+ pub usage: Option<Usage>,}#[derive(Debug, Serialize, Deserialize, ToSchema)]@@ -3033,6 +3134,51 @@ mod tests {assert_eq!(doc.info.title, "SIE Gateway");}+ /// Every native media `data` field must advertise the ONE JSON encoding+ /// the ingress accepts: a base64 string.+ ///+ /// `handlers::proxy::decode_native_media_object_data` transcodes a base64+ /// **string** into msgpack `bin` and passes every other shape through+ /// untouched, so anything else this schema advertised — an array of+ /// integers (the bare `Vec<u8>` rendering), or `format: binary` meaning+ /// raw octets — would generate a client whose requests die at the+ /// worker's typed `bytes` decode. The companion runtime test is+ /// `handlers::proxy::tests::test_parse_queue_request_json_decodes_native_media_data_to_binary`;+ /// this one holds the published contract to the same rule so the two+ /// cannot drift apart.+ #[test]+ fn openapi_documents_media_bytes_as_base64_strings() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ for schema in ["ImageInput", "AudioInput", "VideoInput", "DocumentInput"] {+ let data = &spec["components"]["schemas"][schema]["properties"]["data"];+ assert_eq!(+ data["type"], "string",+ "{schema}.data must be a string, not an array of integers"+ );+ assert_eq!(+ data["contentEncoding"], "base64",+ "{schema}.data must declare base64 content encoding"+ );+ assert!(+ data.get("format").is_none(),+ "{schema}.data must not claim `format` (binary means raw octets): {data}"+ );+ }+ }++ /// The audio preprocessor rejects a non-positive `sample_rate`, so the+ /// schema has to say so rather than leaving a generated client to send a+ /// zero and learn about the rule from a 400.+ #[test]+ fn openapi_documents_positive_audio_sample_rate() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ let sample_rate = &spec["components"]["schemas"]["AudioInput"]["properties"]["sample_rate"];+ assert_eq!(+ sample_rate["exclusiveMinimum"], 0,+ "AudioInput.sample_rate must advertise its positive bound: {sample_rate}"+ );+ }+#[test]fn openapi_documents_rerank_compatibility_contract() {let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();diff --git a/packages/sie_gateway/src/queue/dlq.rs b/packages/sie_gateway/src/queue/dlq.rsindex 71ce8f18e..d3b0ad392 100644--- a/packages/sie_gateway/src/queue/dlq.rs+++ b/packages/sie_gateway/src/queue/dlq.rs@@ -4,6 +4,7 @@ use async_nats::jetstream;use futures_util::StreamExt;use tracing::{debug, error, info, warn};+use super::stream_durability;use crate::observability::metrics::{self as telemetry, QueueEvent, QueueEventOutcome};const DLQ_STREAM_NAME: &str = "DEAD_LETTERS";@@ -14,30 +15,87 @@ const ADVISORY_SUBJECT: &str = "$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>";pub struct DlqListener;impl DlqListener {- /// Start listening for NATS JetStream advisory events and routing- /// max-delivery messages to a dead letter stream.- pub async fn start(- jetstream: jetstream::Context,- client: async_nats::Client,+ /// Create-or-reconcile the dead-letter stream.+ ///+ /// Split out of [`Self::start`] and parameterized by name/subject purely+ /// so the live test can drive this logic against a uniquely-named stream.+ /// `DEAD_LETTERS` is a single fixed-name stream shared by every gateway+ /// replica on a broker, so a test that operated on the real name would be+ /// destructive well beyond its own scope — and deleting it to set up a+ /// test would be precisely the delete-and-recreate this function exists to+ /// avoid. Production always passes [`DLQ_STREAM_NAME`]/[`DLQ_SUBJECT`].+ ///+ /// Storage tracks the work-queue setting (`SIE_STREAM_STORAGE`, default+ /// `Memory`): a memory-backed DLQ is erased by the same broker restart+ /// that erases the work it was recording, which is the worst possible+ /// time to lose the forensic record. Enabling file storage for the work+ /// queue therefore enables it here too, from the same knob.+ async fn ensure_dlq_stream(+ jetstream: &jetstream::Context,+ stream_name: &str,+ subject: &str,+ storage: jetstream::stream::StorageType,+ num_replicas: usize,) -> Result<(), String> {- // Ensure the dead letter stream exists- jetstream+ let num_replicas = num_replicas.max(1);+ let mut stream = jetstream.get_or_create_stream(jetstream::stream::Config {- name: DLQ_STREAM_NAME.to_string(),- subjects: vec![DLQ_SUBJECT.to_string()],+ name: stream_name.to_string(),+ subjects: vec![subject.to_string()],retention: jetstream::stream::RetentionPolicy::Limits,- storage: jetstream::stream::StorageType::Memory,+ storage,+ num_replicas,max_age: Duration::from_secs(DLQ_RETENTION_SECS),..Default::default()}).await.map_err(|e| format!("create DLQ stream: {}", e))?;+ // `get_or_create_stream` silently ignores the requested config when+ // the stream already exists, so a DLQ created by an earlier release+ // (or before the durability knobs existed) would keep its old shape+ // with no signal at all. Reconcile it exactly like the work streams:+ // replicas repaired, storage reported but never repaired.+ //+ // Emphatically NOT delete-and-recreate. The DLQ is the forensic+ // record of work that has already been lost once; destroying it to+ // change its storage type would be the same class of failure this+ // whole knob exists to fix.+ stream_durability::reconcile_num_replicas(+ jetstream,+ &mut stream,+ stream_name,+ num_replicas,+ )+ .await?;+ stream_durability::warn_on_storage_mismatch(&stream, stream_name, storage);+info!(- stream = DLQ_STREAM_NAME,+ stream = stream_name,retention_hours = DLQ_RETENTION_SECS / 3600,+ storage = ?storage,+ num_replicas,"dead letter queue stream ready");+ Ok(())+ }++ /// Start listening for NATS JetStream advisory events and routing+ /// max-delivery messages to a dead letter stream.+ pub async fn start(+ jetstream: jetstream::Context,+ client: async_nats::Client,+ storage: jetstream::stream::StorageType,+ num_replicas: usize,+ ) -> Result<(), String> {+ Self::ensure_dlq_stream(+ &jetstream,+ DLQ_STREAM_NAME,+ DLQ_SUBJECT,+ storage,+ num_replicas,+ )+ .await?;// Subscribe every gateway replica to max-delivery advisories. The// publish into DEAD_LETTERS is stamped with a deterministic message id@@ -231,6 +289,153 @@ mod tests {assert!(ADVISORY_SUBJECT.starts_with("$JS.EVENT.ADVISORY"));}+ /// Live JetStream test for the DLQ's durability reconcile+ /// (CodeRabbit findings on PR #3263).+ ///+ /// `get_or_create_stream` silently ignores the requested config when the+ /// stream already exists, so a dead-letter stream created before these+ /// knobs existed would keep memory storage with no signal. The reconcile+ /// must:+ ///+ /// 1. honour storage on the fresh-create path,+ /// 2. on an existing stream whose storage differs, NOT fail, and above all+ /// NOT delete/recreate — the DLQ is the forensic record of already-lost+ /// work, so destroying it to change its type would be the exact failure+ /// this knob exists to prevent, and+ /// 3. reconcile `num_replicas`, which unlike storage IS changeable.+ ///+ /// Runs against a uniquely-named stream, never the real `DEAD_LETTERS`:+ /// that name is shared by every gateway replica and every concurrent test+ /// on the broker, so operating on it would be destructive far outside this+ /// test's scope — and tearing it down for a fixture would be the very+ /// delete-and-recreate the code under test refuses to do. This is what+ /// `ensure_dlq_stream` is parameterized for; the production name is+ /// covered by `test_dlq_constants`.+ ///+ /// NATS-gated, like the publisher's stream tests.+ #[tokio::test]+ async fn test_dlq_stream_storage_is_honoured_but_never_recreated() {+ let Ok(url) = std::env::var("NATS_URL") else {+ eprintln!("skipping: NATS_URL not set");+ return;+ };+ let client =+ match tokio::time::timeout(Duration::from_secs(2), async_nats::connect(&url)).await {+ Ok(Ok(c)) => c,+ _ => {+ eprintln!("skipping: could not connect to NATS at {url}");+ return;+ }+ };+ let context = async_nats::jetstream::new(client.clone());+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ // Unique name AND unique subject: JetStream rejects two streams whose+ // subjects overlap, so reusing `sie.dlq.>` would collide with a real+ // DEAD_LETTERS on the same broker.+ let stream_name = format!("DEAD_LETTERS_TEST_{nanos}");+ let subject = format!("sie.dlqtest.{nanos}.>");++ // Fresh-create path must honour the requested storage.+ DlqListener::ensure_dlq_stream(+ &context,+ &stream_name,+ &subject,+ jetstream::stream::StorageType::File,+ 1,+ )+ .await+ .expect("ensure_dlq_stream (fresh create)");+ let created = context+ .get_stream(&stream_name)+ .await+ .expect("get DLQ stream")+ .info()+ .await+ .expect("DLQ stream info")+ .config+ .clone();+ assert_eq!(+ created.storage,+ jetstream::stream::StorageType::File,+ "DLQ must be created with the configured storage type"+ );+ assert_eq!(created.num_replicas, 1);++ // Existing stream with diverging storage: must succeed, warn, and+ // leave the stream (and its contents) intact.+ DlqListener::ensure_dlq_stream(+ &context,+ &stream_name,+ &subject,+ jetstream::stream::StorageType::Memory,+ 1,+ )+ .await+ .expect("a DLQ storage mismatch must not fail startup");+ let after = context+ .get_stream(&stream_name)+ .await+ .expect("re-get DLQ stream")+ .info()+ .await+ .expect("DLQ stream info after mismatch")+ .config+ .clone();+ assert_eq!(+ after.storage,+ jetstream::stream::StorageType::File,+ "the DLQ must NOT be deleted/recreated to change its storage type"+ );+ assert_eq!(+ after.max_age,+ Duration::from_secs(DLQ_RETENTION_SECS),+ "DLQ retention must survive the reconcile"+ );++ // Replicas, unlike storage, ARE reconciled onto the existing stream.+ // This phase is what discriminates the fix: the storage assertions+ // above hold under the old `get_or_create_stream`-only code too+ // (leaving the stream alone is what it already did, just silently),+ // whereas a replica change is a real, observable `update_stream`.+ //+ // Note this single-node server happily reports R3 without a cluster+ // to back it — NATS does not reject the request, which is precisely+ // why the chart guards `streamReplicas > 1` against+ // `nats.config.cluster.enabled` rather than leaving it to the broker.+ DlqListener::ensure_dlq_stream(+ &context,+ &stream_name,+ &subject,+ jetstream::stream::StorageType::File,+ 3,+ )+ .await+ .expect("DLQ replica reconcile");+ assert_eq!(+ context+ .get_stream(&stream_name)+ .await+ .expect("re-get DLQ stream")+ .info()+ .await+ .expect("DLQ stream info after replica reconcile")+ .config+ .num_replicas,+ 3,+ "a DLQ replica divergence must be reconciled onto the existing \+ stream, not silently ignored"+ );++ // Only this test's own stream is removed.+ context+ .delete_stream(&stream_name)+ .await+ .expect("delete DLQ test stream");+ }+#[test]fn test_dlq_subject_format() {// DLQ subjects use sie.dlq.{model_normalized}diff --git a/packages/sie_gateway/src/queue/keyed_worker_pool.rs b/packages/sie_gateway/src/queue/keyed_worker_pool.rsnew file mode 100644index 000000000..9bd9c2ca6--- /dev/null+++ b/packages/sie_gateway/src/queue/keyed_worker_pool.rs@@ -0,0 +1,485 @@+//! Bounded worker pool keyed by request id.+//!+//! The gateway inbox is one subscription feeding one tokio task+//! (`publisher::WorkPublisher::handle_inbox`). Before this module that task+//! also *ran* every handler inline, so one slow handler — most sharply an+//! object-store delete on request completion — stalled decode for every other+//! in-flight request in the process. For streamed generation that is every+//! token chunk of every concurrent stream behind one await.+//!+//! This pool splits the *running* from the *decoding*. The decode task stays+//! single (the msgpack decode still happens exactly once, on that task) and+//! hands each decoded item to one of a fixed number of shards. A shard is a+//! tokio task draining a bounded channel strictly in order.+//!+//! # Ordering+//!+//! A key always maps to the same shard ([`shard_index`] is a pure function of+//! the key), and a shard drains its channel in FIFO order and awaits each+//! handler to completion before taking the next item. Therefore **two items+//! with the same key are handled in dispatch order**, which is the order the+//! decode task read them off the subscription. That is the property streaming+//! depends on: `StreamCollector::apply` drops a chunk whose `seq` is not+//! greater than the last applied one and fails the whole stream on a forward+//! gap, so a reordered pair of chunks would truncate or kill a live stream.+//!+//! Items with *different* keys may land on different shards and then run+//! concurrently. Cross-key ordering was never a property of the old inline+//! loop that anything depended on — every request's state is keyed by request+//! id in its own `DashMap` entry.+//!+//! # Bound+//!+//! Each shard's channel has a fixed depth, so a slow handler cannot grow an+//! unbounded queue of decoded payloads. Two policies are offered at the bound+//! and callers pick per workload:+//!+//! * [`KeyedWorkerPool::dispatch`] — **backpressure**. Awaits a free slot.+//! Correct for work that must not be lost: at worst the decode task blocks,+//! which is exactly what it did for *every* message before this change, so+//! saturation degrades to the old behaviour rather than to a new failure+//! mode. Nothing is dropped.+//! * [`KeyedWorkerPool::try_dispatch`] — **shed**. Returns `false` instead of+//! waiting. Correct only for work that has an independent retry path, so+//! that shedding costs latency and not correctness.++use std::future::Future;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;++use tokio::sync::mpsc;+use tracing::{debug, info, warn};++use crate::observability::metrics::{self as telemetry, QueueWorkerPoolEvent};++/// Map a key onto one of `shards` ordering domains.+///+/// FNV-1a, written out rather than taken from `DefaultHasher` so the mapping+/// is deterministic across processes and toolchain versions: tests pick keys+/// that land on distinct shards by calling this directly, and an operator+/// reading a shard label in a log can reproduce the assignment.+pub(crate) fn shard_index(key: &str, shards: usize) -> usize {+ debug_assert!(shards > 0, "shard_index needs at least one shard");+ const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;+ const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;+ let mut hash = FNV_OFFSET_BASIS;+ for byte in key.as_bytes() {+ hash ^= u64::from(*byte);+ hash = hash.wrapping_mul(FNV_PRIME);+ }+ (hash % shards.max(1) as u64) as usize+}++/// Work that carries its own ordering key.+///+/// The key travels with the item so a caller cannot accidentally dispatch an+/// item under the wrong key and silently break its ordering domain.+pub(crate) trait ShardKeyed {+ fn shard_key(&self) -> &str;+}++struct Shard<T> {+ sender: mpsc::Sender<T>,+ /// Edge trigger for the saturation warning. Sustained saturation would+ /// otherwise emit one warning per message; the counter carries the volume.+ saturated: AtomicBool,+}++/// A fixed set of ordered, bounded worker tasks addressed by key.+///+/// See the module docs for the ordering guarantee and the two bound policies.+/// Dropping the pool closes every shard channel, which ends the shard tasks+/// once they finish draining.+pub(crate) struct KeyedWorkerPool<T> {+ /// Bounded-cardinality metric label identifying this pool.+ name: &'static str,+ shards: Vec<Shard<T>>,+}++impl<T: Send + 'static> KeyedWorkerPool<T> {+ /// Spawn `shards` worker tasks, each draining a channel of depth `depth`.+ ///+ /// Shards are ordering domains, not threads: they are ordinary tokio tasks+ /// multiplexed onto the runtime's existing workers, so the count is chosen+ /// for concurrency width and bounded buffering, not for core count.+ pub(crate) fn new<F, Fut>(name: &'static str, shards: usize, depth: usize, handler: F) -> Self+ where+ F: Fn(T) -> Fut + Send + Sync + 'static,+ Fut: Future<Output = ()> + Send + 'static,+ {+ assert!(shards > 0, "keyed worker pool needs at least one shard");+ assert!(depth > 0, "keyed worker pool needs a non-zero queue depth");++ let handler = Arc::new(handler);+ let shards = (0..shards)+ .map(|_| {+ let (sender, mut receiver) = mpsc::channel::<T>(depth);+ let handler = Arc::clone(&handler);+ tokio::spawn(async move {+ // Sequential drain. This `await` is what makes same-shard+ // (and therefore same-key) handling strictly ordered.+ while let Some(item) = receiver.recv().await {+ handler(item).await;+ }+ });+ Shard {+ sender,+ saturated: AtomicBool::new(false),+ }+ })+ .collect::<Vec<_>>();++ info!(+ pool = name,+ shards = shards.len(),+ depth,+ "started keyed worker pool"+ );+ Self { name, shards }+ }++ /// Hand `item` to the shard owning its key, waiting for a free slot.+ ///+ /// Returns `false` only when the pool's worker task is gone, which can+ /// only happen if it panicked — the caller should treat that as fatal for+ /// its own loop rather than spin.+ pub(crate) async fn dispatch(&self, item: T) -> bool+ where+ T: ShardKeyed,+ {+ let index = shard_index(item.shard_key(), self.shards.len());+ let shard = &self.shards[index];+ let item = match shard.sender.try_send(item) {+ Ok(()) => {+ shard.saturated.store(false, Ordering::Relaxed);+ return true;+ }+ Err(mpsc::error::TrySendError::Full(item)) => item,+ Err(mpsc::error::TrySendError::Closed(_)) => {+ warn!(pool = self.name, shard = index, "worker pool shard closed");+ return false;+ }+ };++ telemetry::record_queue_worker_pool_event(self.name, QueueWorkerPoolEvent::Saturated);+ if !shard.saturated.swap(true, Ordering::Relaxed) {+ warn!(+ pool = self.name,+ shard = index,+ depth = shard.sender.max_capacity(),+ "worker pool shard saturated — applying backpressure to the caller"+ );+ }+ if shard.sender.send(item).await.is_err() {+ warn!(pool = self.name, shard = index, "worker pool shard closed");+ return false;+ }+ true+ }++ /// Hand `item` to the shard owning its key without waiting.+ ///+ /// Returns `false` when the shard is saturated (or closed) and the item+ /// was **not** accepted. Only use this where the caller has an independent+ /// path that will redo the work.+ pub(crate) fn try_dispatch(&self, item: T) -> bool+ where+ T: ShardKeyed,+ {+ let index = shard_index(item.shard_key(), self.shards.len());+ let shard = &self.shards[index];+ match shard.sender.try_send(item) {+ Ok(()) => {+ shard.saturated.store(false, Ordering::Relaxed);+ true+ }+ Err(mpsc::error::TrySendError::Full(_)) => {+ telemetry::record_queue_worker_pool_event(self.name, QueueWorkerPoolEvent::Shed);+ if !shard.saturated.swap(true, Ordering::Relaxed) {+ warn!(+ pool = self.name,+ shard = index,+ depth = shard.sender.max_capacity(),+ "worker pool shard saturated — shedding to the caller's retry path"+ );+ }+ false+ }+ Err(mpsc::error::TrySendError::Closed(_)) => {+ debug!(pool = self.name, shard = index, "worker pool shard closed");+ false+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::BTreeMap;+ use std::sync::Mutex;+ use std::time::Duration;++ /// Every bound test uses one key so it addresses exactly one shard.+ const KEY: &str = "k";++ /// A keyed chunk: `key` is the ordering domain, `seq` the position in it.+ #[derive(Debug)]+ struct Keyed {+ key: String,+ seq: u32,+ }++ impl ShardKeyed for Keyed {+ fn shard_key(&self) -> &str {+ &self.key+ }+ }++ impl ShardKeyed for String {+ fn shard_key(&self) -> &str {+ self+ }+ }++ /// Two keys that provably land on different shards, so the concurrency+ /// tests below assert real concurrency instead of hash luck.+ fn keys_on_distinct_shards(shards: usize) -> (String, String) {+ let first = "req-0".to_string();+ let first_shard = shard_index(&first, shards);+ for candidate in 1..1_000 {+ let key = format!("req-{candidate}");+ if shard_index(&key, shards) != first_shard {+ return (first, key);+ }+ }+ panic!("no two keys landed on distinct shards");+ }++ #[test]+ fn shard_index_is_stable_and_in_range() {+ for shards in [1usize, 2, 4, 8, 13] {+ for candidate in 0..256 {+ let key = format!("request-{candidate}");+ let index = shard_index(&key, shards);+ assert!(index < shards, "shard index must be in range");+ assert_eq!(+ index,+ shard_index(&key, shards),+ "shard index must be a pure function of the key"+ );+ }+ }+ }++ /// The load-bearing property: interleave many sequences across several+ /// keys and every key's handler must observe strictly increasing `seq`.+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]+ async fn preserves_per_key_order_under_concurrency() {+ const KEYS: usize = 16;+ const PER_KEY: u32 = 64;++ let seen: Arc<Mutex<BTreeMap<String, Vec<u32>>>> = Arc::new(Mutex::new(BTreeMap::new()));+ let recorder = Arc::clone(&seen);+ let pool = KeyedWorkerPool::new("test-order", 8, 4, move |item: Keyed| {+ let recorder = Arc::clone(&recorder);+ async move {+ // Yield inside the handler so a broken implementation that+ // spawned per item (rather than draining in order) would+ // interleave and be caught.+ tokio::task::yield_now().await;+ recorder+ .lock()+ .expect("recorder")+ .entry(item.key)+ .or_default()+ .push(item.seq);+ }+ });++ // Round-robin across keys so each shard's channel sees an interleaved+ // stream, exactly like the real inbox under concurrent streams.+ for seq in 0..PER_KEY {+ for key_index in 0..KEYS {+ let key = format!("req-{key_index}");+ assert!(pool.dispatch(Keyed { key, seq }).await, "dispatch accepted");+ }+ }+ drop(pool);++ // Drain: wait until every key has all its items.+ let deadline = std::time::Instant::now() + Duration::from_secs(10);+ loop {+ let complete = {+ let guard = seen.lock().expect("recorder");+ guard.len() == KEYS && guard.values().all(|seqs| seqs.len() == PER_KEY as usize)+ };+ if complete {+ break;+ }+ assert!(std::time::Instant::now() < deadline, "pool did not drain");+ tokio::time::sleep(Duration::from_millis(10)).await;+ }++ let guard = seen.lock().expect("recorder");+ for (key, seqs) in guard.iter() {+ assert_eq!(+ *seqs,+ (0..PER_KEY).collect::<Vec<_>>(),+ "key {key} must observe strictly increasing seq in dispatch order"+ );+ }+ }++ /// If the pool ever serialized everything again this deadlocks: the first+ /// key's handler only returns once the second key's handler has run.+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]+ async fn distinct_keys_proceed_concurrently() {+ let (blocking_key, other_key) = keys_on_distinct_shards(8);+ let unblock = Arc::new(tokio::sync::Notify::new());+ let completed = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let handler_unblock = Arc::clone(&unblock);+ let handler_completed = Arc::clone(&completed);+ let blocking = blocking_key.clone();++ let pool = KeyedWorkerPool::new("test-concurrency", 8, 4, move |key: String| {+ let unblock = Arc::clone(&handler_unblock);+ let completed = Arc::clone(&handler_completed);+ let blocking = blocking.clone();+ async move {+ if key == blocking {+ // Held until the *other* key's item has been handled. If+ // the pool serialized every key onto one worker, the+ // other key's item would sit behind this await forever.+ unblock.notified().await;+ } else {+ unblock.notify_one();+ }+ completed.fetch_add(1, Ordering::SeqCst);+ }+ });++ assert!(pool.dispatch(blocking_key.clone()).await);+ assert!(pool.dispatch(other_key.clone()).await);++ tokio::time::timeout(Duration::from_secs(5), async {+ while completed.load(Ordering::SeqCst) < 2 {+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ })+ .await+ .expect("distinct keys must not serialize behind each other");+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn dispatch_applies_backpressure_when_saturated() {+ let release = Arc::new(tokio::sync::Notify::new());+ let handler_release = Arc::clone(&release);+ let pool = KeyedWorkerPool::new("test-backpressure", 1, 1, move |_: Keyed| {+ let release = Arc::clone(&handler_release);+ async move {+ release.notified().await;+ }+ });++ // One item is taken by the worker (which then blocks) and one fills+ // the depth-1 channel. The pool is now saturated.+ assert!(+ pool.dispatch(Keyed {+ key: KEY.into(),+ seq: 0+ })+ .await+ );+ assert!(+ pool.dispatch(Keyed {+ key: KEY.into(),+ seq: 1+ })+ .await+ );+ tokio::time::sleep(Duration::from_millis(50)).await;++ // The third dispatch must wait rather than drop or grow the queue.+ let blocked = tokio::time::timeout(+ Duration::from_millis(200),+ pool.dispatch(Keyed {+ key: KEY.into(),+ seq: 2,+ }),+ )+ .await;+ assert!(+ blocked.is_err(),+ "dispatch must block at the bound instead of over-filling"+ );++ // Releasing the handler lets the queue drain and the dispatch land.+ release.notify_waiters();+ let drained = tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ release.notify_waiters();+ if pool+ .dispatch(Keyed {+ key: KEY.into(),+ seq: 3,+ })+ .await+ {+ return;+ }+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ })+ .await;+ assert!(drained.is_ok(), "dispatch must complete once slots free up");+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn try_dispatch_sheds_when_saturated() {+ let release = Arc::new(tokio::sync::Notify::new());+ let handler_release = Arc::clone(&release);+ let pool = KeyedWorkerPool::new("test-shed", 1, 1, move |_: Keyed| {+ let release = Arc::clone(&handler_release);+ async move {+ release.notified().await;+ }+ });++ assert!(pool.try_dispatch(Keyed {+ key: KEY.into(),+ seq: 0+ }));+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert!(+ pool.try_dispatch(Keyed {+ key: KEY.into(),+ seq: 1+ }),+ "the depth-1 channel accepts one"+ );+ assert!(+ !pool.try_dispatch(Keyed {+ key: KEY.into(),+ seq: 2+ }),+ "a saturated shard must shed rather than block"+ );++ release.notify_waiters();+ let accepted = tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ release.notify_waiters();+ if pool.try_dispatch(Keyed {+ key: KEY.into(),+ seq: 3,+ }) {+ return;+ }+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ })+ .await;+ assert!(accepted.is_ok(), "shedding must be transient, not sticky");+ }+}diff --git a/packages/sie_gateway/src/queue/lane_admission.rs b/packages/sie_gateway/src/queue/lane_admission.rsnew file mode 100644index 000000000..e88534323--- /dev/null+++ b/packages/sie_gateway/src/queue/lane_admission.rs@@ -0,0 +1,453 @@+//! Per-lane admission accounting for queue publishes.+//!+//! Pool-granular backpressure sheds every model sharing a pool as soon as+//! *one* model's backlog crosses the pool threshold, because the number+//! [`crate::queue::publisher::WorkPublisher::check_backpressure`] compares is+//! the whole `WORK_POOL_{pool}` stream's pending count and a stream is per+//! pool, not per lane.+//!+//! The proposal names two realistic implementations. This is the first: a+//! gateway-local in-flight counter per lane. It is approximate — it does not+//! survive a gateway restart and it does not see the other replicas' work —+//! and it is deliberately the reversible one. Per-lane JetStream streams are+//! exact but are a topology migration and a soft one-way door.+//!+//! ## What is counted+//!+//! Work *items*, not requests. The proposal's correction to the review matters+//! here: the worker scheduler is not strictly FIFO within a lane (batchers are+//! per LoRA key with cross-key FCFS on head age, and a batcher cost-sorts its+//! pending queue ascending before every extract), so a cheap request does not+//! queue behind an expensive one on cost. What it queues behind is **depth**:+//! one 4096-item request contributes 4096 cheap items that fill every+//! subsequent batch. Counting items is what makes that visible; counting+//! requests would not.+//!+//! A reservation is taken for every publish that passes the check and is+//! released when the request's result collector is dropped — on success,+//! timeout, publish failure, or the expiry sweep alike, because every one of+//! those paths drops the collector.+//!+//! ## Shadow mode+//!+//! The decision is computed and recorded on every publish. Enforcement is a+//! separate flag. With enforcement off the outcome is+//! [`LaneAdmissionOutcome::ShedShadow`], the caller admits the work anyway,+//! and the only trace is telemetry, so the new decision can be evaluated+//! against production traffic before it sheds anything.++use dashmap::DashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;++use crate::state::demand_tracker::{PhysicalLane, PhysicalLaneCatalog};++/// Per-lane in-flight item ceiling used when the caller does not configure one.+///+/// Deliberately well below the pool-wide `SIE_GATEWAY_MAX_STREAM_PENDING`+/// default of 50000 — a per-lane threshold at or above the pool-wide one could+/// never fire first, which is the entire point. This is a shadow-mode starting+/// value, not a tuned one: read the shed rate per lane off+/// `sie.gateway.queue.lane_admission.decisions` before enabling enforcement.+pub const DEFAULT_MAX_LANE_IN_FLIGHT_ITEMS: u64 = 10_000;++/// The lane a work item is published onto: the `(pool, machine_profile,+/// bundle)` triple that names one physical worker lane.+///+/// This is the same triple the telemetry contract already treats as a bounded+/// catalog (`gateway_lane_admission_domain`, which reuses the KEDA domain's+/// `SIE_GATEWAY_CONFIGURED_PHYSICAL_LANES` source and fail-closed rules without+/// being a KEDA control signal). Model and tenant are deliberately+/// absent: they are unbounded, and the contract forbids them as metric labels.+#[derive(Clone, Debug, Eq, Hash, PartialEq)]+pub struct LaneKey {+ pub pool: String,+ pub machine_profile: String,+ pub bundle: String,+}++impl LaneKey {+ pub fn new(pool: &str, machine_profile: &str, bundle: &str) -> Self {+ Self {+ pool: pool.to_string(),+ machine_profile: machine_profile.to_string(),+ bundle: bundle.to_string(),+ }+ }+}++/// What the per-lane check decided, and whether it was acted on.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum LaneAdmissionOutcome {+ /// The lane was below its ceiling.+ Admitted,+ /// The lane was over its ceiling but enforcement is off, so the work was+ /// admitted anyway. Recorded, never acted on.+ ShedShadow,+ /// The lane was over its ceiling and enforcement is on: the caller must+ /// reject this publish.+ ShedEnforced,+}++impl LaneAdmissionOutcome {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Admitted => "admitted",+ Self::ShedShadow => "shed_shadow",+ Self::ShedEnforced => "shed_enforced",+ }+ }++ /// True when the caller must refuse the publish.+ pub fn rejects(self) -> bool {+ matches!(self, Self::ShedEnforced)+ }+}++/// One lane's reservation, released on drop.+///+/// Held by the request's result collector so that every terminal path —+/// completion, timeout, publish failure, cancellation, the expiry sweep —+/// releases it without needing its own release call. An early return between+/// reservation and collector installation drops the guard and releases too.+#[derive(Debug)]+pub struct LaneReservation {+ counter: Arc<AtomicU64>,+ items: u64,+}++impl Drop for LaneReservation {+ fn drop(&mut self) {+ if self.items == 0 {+ return;+ }+ // Saturating: a double release would otherwise wrap the counter to+ // u64::MAX and shed the lane permanently.+ let _ = self+ .counter+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {+ Some(current.saturating_sub(self.items))+ });+ }+}++/// One evaluated admission: what was decided, and the reservation it took.+#[derive(Debug)]+pub struct LaneAdmission {+ pub outcome: LaneAdmissionOutcome,+ /// In-flight items on this lane *before* this request's reservation.+ pub in_flight: u64,+ pub threshold: u64,+ /// `None` only for [`LaneAdmissionOutcome::ShedEnforced`], where the work+ /// never enters the queue and therefore reserves nothing.+ pub reservation: Option<LaneReservation>,+}++/// Gateway-local per-lane in-flight accounting.+///+/// The counter map is keyed by lane. Its key space is bounded in practice by+/// the deployment's lane catalog; entries are retained rather than reaped+/// because a lane that has served traffic once will serve it again, and the+/// catalog caps the deployment at 1024 lanes.+pub struct LaneAdmissionControl {+ lanes: DashMap<LaneKey, Arc<AtomicU64>>,+ max_in_flight_items: u64,+ enforce: bool,+ /// Deployment-owned lane catalog. Only exact members carry lane labels on+ /// the decision metric; anything else is recorded without a lane rather+ /// than under a synthetic one, matching the contract's+ /// `synthetic_fallback_lane: forbidden`.+ catalog: PhysicalLaneCatalog,+}++impl Default for LaneAdmissionControl {+ /// Shadow mode at the default ceiling: the decision is computed and+ /// recorded, never enforced.+ fn default() -> Self {+ Self::new(+ DEFAULT_MAX_LANE_IN_FLIGHT_ITEMS,+ false,+ PhysicalLaneCatalog::default(),+ )+ }+}++impl LaneAdmissionControl {+ pub fn new(max_in_flight_items: u64, enforce: bool, catalog: PhysicalLaneCatalog) -> Self {+ Self {+ lanes: DashMap::new(),+ max_in_flight_items,+ enforce,+ catalog,+ }+ }++ /// Resolve `lane` against the deployment catalog, for bounded telemetry+ /// labels. `None` means the lane is not a configured physical lane.+ pub fn resolve(&self, lane: &LaneKey) -> Option<PhysicalLane> {+ self.catalog+ .resolve(&lane.pool, &lane.machine_profile, &lane.bundle)+ }++ /// Evaluate one publish against its lane's ceiling and, unless the+ /// decision is an enforced shed, reserve `items` on that lane.+ ///+ /// The comparison is against the depth already outstanding on the lane,+ /// not against depth-plus-this-request. That mirrors the pool-wide check+ /// it complements (`num_pending > threshold`) and, more importantly, means+ /// a single large request is never rejected outright on an idle lane: it+ /// is admitted, and it is the *next* arrival on that same lane that pays,+ /// which is exactly the depth-fairness behaviour B5 asks for.+ ///+ /// The check and the reservation are one atomic operation. A plain load+ /// followed by a separate `fetch_add` would let a concurrent burst on one+ /// lane all observe the same sub-threshold depth and all reserve against+ /// it — and a concurrent burst on one lane is precisely the saturation+ /// case this exists to catch, so the race is not a rare interleaving but+ /// the expected traffic shape. `fetch_update` retries its compare-exchange+ /// until the depth it observed is the depth it reserved against, which+ /// bounds the overshoot to the single request that crosses the ceiling.+ pub fn admit(&self, lane: &LaneKey, items: u64) -> LaneAdmission {+ let counter = self.counter_for(lane);+ // `Err` carries the observed value on abort, `Ok` the pre-update+ // value, so either way this yields the depth the decision was made+ // against. Shadow mode never aborts: the closure only refuses when+ // enforcement is on, so a shadow shed still reserves and the shadow+ // counter tracks real depth rather than a hypothetical one.+ let reserved = counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {+ if current > self.max_in_flight_items && self.enforce {+ None+ } else {+ // Saturating so a pathological counter cannot wrap to zero and+ // silently reopen a lane that is over its ceiling.+ Some(current.saturating_add(items))+ }+ });+ let (in_flight, reservation) = match reserved {+ Ok(previous) => (previous, Some(LaneReservation { counter, items })),+ Err(current) => (current, None),+ };+ let over = in_flight > self.max_in_flight_items;+ let outcome = match (over, self.enforce) {+ (false, _) => LaneAdmissionOutcome::Admitted,+ (true, false) => LaneAdmissionOutcome::ShedShadow,+ (true, true) => LaneAdmissionOutcome::ShedEnforced,+ };+ debug_assert_eq!(+ outcome.rejects(),+ reservation.is_none(),+ "an enforced shed must reserve nothing and every other outcome must reserve"+ );+ LaneAdmission {+ outcome,+ in_flight,+ threshold: self.max_in_flight_items,+ reservation,+ }+ }++ /// In-flight items currently reserved on `lane`.+ #[cfg(test)]+ pub fn in_flight(&self, lane: &LaneKey) -> u64 {+ self.lanes+ .get(lane)+ .map(|counter| counter.load(Ordering::Relaxed))+ .unwrap_or(0)+ }++ fn counter_for(&self, lane: &LaneKey) -> Arc<AtomicU64> {+ if let Some(existing) = self.lanes.get(lane) {+ return Arc::clone(existing.value());+ }+ Arc::clone(+ self.lanes+ .entry(lane.clone())+ .or_insert_with(|| Arc::new(AtomicU64::new(0)))+ .value(),+ )+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn control(enforce: bool) -> LaneAdmissionControl {+ LaneAdmissionControl::new(10, enforce, PhysicalLaneCatalog::default())+ }++ fn lane(pool: &str) -> LaneKey {+ LaneKey::new(pool, "a10g", "default")+ }++ #[test]+ fn admits_while_the_lane_is_under_its_ceiling() {+ let control = control(true);+ let admission = control.admit(&lane("hot"), 4);+ assert_eq!(admission.outcome, LaneAdmissionOutcome::Admitted);+ assert_eq!(admission.in_flight, 0);+ assert_eq!(control.in_flight(&lane("hot")), 4);+ }++ #[test]+ fn a_saturated_lane_sheds_and_a_cold_lane_on_the_same_pool_still_admits() {+ // Two lanes differing only in machine profile: the pool-wide check+ // cannot tell them apart, which is the defect this replaces.+ let control = control(true);+ let hot = LaneKey::new("shared", "h100", "default");+ let cold = LaneKey::new("shared", "a10g", "default");++ let _hot_reservation = control.admit(&hot, 11).reservation;+ assert_eq!(+ control.admit(&hot, 1).outcome,+ LaneAdmissionOutcome::ShedEnforced+ );+ assert_eq!(+ control.admit(&cold, 1).outcome,+ LaneAdmissionOutcome::Admitted+ );+ }++ #[test]+ fn an_enforced_shed_reserves_nothing() {+ let control = control(true);+ let _held = control.admit(&lane("hot"), 11).reservation;+ let shed = control.admit(&lane("hot"), 100);+ assert!(shed.reservation.is_none());+ assert_eq!(control.in_flight(&lane("hot")), 11);+ }++ #[test]+ fn shadow_mode_records_the_shed_without_changing_admission() {+ let control = control(false);+ let _held = control.admit(&lane("hot"), 11).reservation;+ let shadow = control.admit(&lane("hot"), 5);+ assert_eq!(shadow.outcome, LaneAdmissionOutcome::ShedShadow);+ assert!(!shadow.outcome.rejects());+ // The shadow admission still reserves, so the shadow counter tracks+ // real depth rather than a hypothetical one.+ assert!(shadow.reservation.is_some());+ assert_eq!(control.in_flight(&lane("hot")), 16);+ }++ #[test]+ fn dropping_the_reservation_releases_the_lane() {+ let control = control(true);+ {+ let _held = control.admit(&lane("hot"), 11).reservation;+ assert_eq!(+ control.admit(&lane("hot"), 1).outcome,+ LaneAdmissionOutcome::ShedEnforced+ );+ }+ assert_eq!(control.in_flight(&lane("hot")), 0);+ assert_eq!(+ control.admit(&lane("hot"), 1).outcome,+ LaneAdmissionOutcome::Admitted+ );+ }++ #[test]+ fn release_saturates_instead_of_wrapping() {+ let control = control(true);+ let lane = lane("hot");+ let counter = control.counter_for(&lane);+ let reservation = LaneReservation {+ counter: Arc::clone(&counter),+ items: 5,+ };+ drop(reservation);+ assert_eq!(control.in_flight(&lane), 0);+ }++ /// Exactly one request may cross the ceiling, however many arrive at once.+ ///+ /// Each round parks the lane at exactly the threshold and then releases a+ /// thundering herd at that boundary. The predicate is+ /// `depth-before-this-request > threshold`, so the single request that+ /// observes `threshold` is admitted and every request that observes the+ /// resulting `threshold + 1` is shed — one admission per round, no matter+ /// how the threads interleave.+ ///+ /// This is the property atomicity buys, and the boundary is where it is+ /// visible: with a load followed by a separate `fetch_add`, two threads+ /// that both read `threshold` before either adds will both admit, and the+ /// round records more than one. A concurrent burst on a lane sitting at+ /// its ceiling is not an exotic interleaving here — it is the saturation+ /// traffic the whole mechanism exists for, so the race would fire exactly+ /// when it matters most. Repeated because a thread race cannot be made+ /// deterministic; the rounds make an escape overwhelmingly unlikely.+ #[test]+ fn only_one_request_may_cross_the_ceiling_under_concurrency() {+ const THRESHOLD: u64 = 10;+ const THREADS: usize = 16;+ const ROUNDS: usize = 250;++ for round in 0..ROUNDS {+ let control = Arc::new(LaneAdmissionControl::new(+ THRESHOLD,+ true,+ PhysicalLaneCatalog::default(),+ ));+ let lane = lane("hot");++ // Park the lane at exactly the ceiling, held for the whole round.+ let _parked = control.admit(&lane, THRESHOLD).reservation;+ assert_eq!(control.in_flight(&lane), THRESHOLD);++ let barrier = Arc::new(std::sync::Barrier::new(THREADS));+ let admitted = Arc::new(AtomicU64::new(0));+ let workers: Vec<_> = (0..THREADS)+ .map(|_| {+ let control = Arc::clone(&control);+ let barrier = Arc::clone(&barrier);+ let admitted = Arc::clone(&admitted);+ let lane = lane.clone();+ std::thread::spawn(move || {+ barrier.wait();+ let admission = control.admit(&lane, 1);+ if admission.reservation.is_some() {+ admitted.fetch_add(1, Ordering::Relaxed);+ }+ // Hold the reservation until the round is scored.+ admission.reservation+ })+ })+ .collect();++ let held: Vec<_> = workers+ .into_iter()+ .map(|worker| worker.join().expect("worker"))+ .collect();++ assert_eq!(+ admitted.load(Ordering::Relaxed),+ 1,+ "round {round}: exactly one request may cross the ceiling"+ );+ assert_eq!(control.in_flight(&lane), THRESHOLD + 1, "round {round}");+ drop(held);+ }+ }++ #[test]+ fn unresolved_lanes_carry_no_catalog_identity() {+ let control = control(true);+ assert!(control.resolve(&lane("hot")).is_none());+ }++ #[test]+ fn configured_lanes_resolve_for_bounded_labels() {+ let catalog = PhysicalLaneCatalog::try_from_raw([(+ "hot".to_string(),+ "a10g".to_string(),+ "default".to_string(),+ )])+ .expect("catalog");+ let control = LaneAdmissionControl::new(10, true, catalog);+ let resolved = control.resolve(&lane("hot")).expect("resolved lane");+ assert_eq!(resolved.pool(), "hot");+ assert_eq!(resolved.machine_profile(), "a10g");+ assert_eq!(resolved.bundle(), "default");+ }+}diff --git a/packages/sie_gateway/src/queue/mod.rs b/packages/sie_gateway/src/queue/mod.rsindex a7276f992..dd5e1f1fc 100644--- a/packages/sie_gateway/src/queue/mod.rs+++ b/packages/sie_gateway/src/queue/mod.rs@@ -2,6 +2,11 @@ pub mod backlog;pub mod dispatch;pub mod dlq;pub mod identity;+pub mod keyed_worker_pool;+pub mod lane_admission;+#[cfg(feature = "cloud-storage")]+pub mod oss_payload_store;pub mod payload_store;pub mod publisher;+pub mod stream_durability;pub mod streaming;diff --git a/packages/sie_gateway/src/queue/oss_payload_store.rs b/packages/sie_gateway/src/queue/oss_payload_store.rsnew file mode 100644index 000000000..d9a70edf2--- /dev/null+++ b/packages/sie_gateway/src/queue/oss_payload_store.rs@@ -0,0 +1,655 @@+//! Native Alibaba OSS payload writer.+//!+//! OSS is intentionally not routed through `object_store`: its current OSS+//! backend signs with Signature V1. This module always uses region-scoped OSS+//! Signature V4 and a deliberately restricted credential source (either+//! explicit environment credentials or ACK RRSA OIDC, never both). Node metadata, profiles,+//! credential files, URI providers, and generic AssumeRole are omitted.++use std::io;+use std::time::Duration;++use async_trait::async_trait;+use reqsign_aliyun_oss::{+ AssumeRoleWithOidcCredentialProvider, Credential, EnvCredentialProvider, RequestSigner,+ SigningVersion,+};+use reqsign_core::{Context, OsEnv, ProvideCredential, Signer};+use reqsign_file_read_tokio::TokioFileRead;+use reqsign_http_send_reqwest::ReqwestHttpSend;+use reqwest::{Client, Method, StatusCode};+use url::Url;++use super::payload_store::PayloadStore;++const MAX_ATTEMPTS: usize = 3;+const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);++#[derive(Clone, Debug, PartialEq, Eq)]+struct OssLocation {+ bucket: String,+ prefix: String,+}++#[derive(Debug)]+struct OssCredentialProvider {+ source: OssCredentialSource,+}++impl OssCredentialProvider {+ fn new(source: OssCredentialSource) -> Self {+ Self { source }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum OssCredentialSource {+ Environment,+ Oidc,+}++impl ProvideCredential for OssCredentialProvider {+ type Credential = Credential;++ async fn provide_credential(+ &self,+ context: &Context,+ ) -> reqsign_core::Result<Option<Self::Credential>> {+ match self.source {+ OssCredentialSource::Environment => {+ EnvCredentialProvider::new()+ .provide_credential(context)+ .await+ }+ OssCredentialSource::Oidc => {+ AssumeRoleWithOidcCredentialProvider::new()+ .provide_credential(context)+ .await+ }+ }+ }+}++impl OssLocation {+ fn parse(value: &str) -> io::Result<Self> {+ if value.contains('%') {+ return Err(invalid(+ "OSS payload-store URL must not contain percent-encoded components",+ ));+ }+ let rest = value+ .strip_prefix("oss://")+ .ok_or_else(|| invalid("OSS payload-store URL must use oss://"))?;+ let (raw_authority, raw_path) = rest.split_once('/').unwrap_or((rest, ""));+ if !valid_bucket(raw_authority) {+ return Err(invalid("OSS payload-store bucket is invalid or empty"));+ }+ let prefix = validate_raw_prefix(raw_path)?;+ let parsed = Url::parse(value).map_err(|_| invalid("invalid OSS payload-store URL"))?;+ if parsed.scheme() != "oss" {+ return Err(invalid("OSS payload-store URL must use oss://"));+ }+ if !parsed.username().is_empty() || parsed.password().is_some() {+ return Err(invalid(+ "OSS payload-store URL must not contain credentials",+ ));+ }+ if parsed.query().is_some() || parsed.fragment().is_some() || parsed.port().is_some() {+ return Err(invalid(+ "OSS payload-store URL must not contain a port, query, or fragment",+ ));+ }+ let bucket = parsed+ .host_str()+ .filter(|bucket| valid_bucket(bucket))+ .ok_or_else(|| invalid("OSS payload-store bucket is invalid or empty"))?+ .to_owned();+ Ok(Self { bucket, prefix })+ }++ fn object_key(&self, key: &str) -> String {+ if self.prefix.is_empty() {+ key.to_owned()+ } else {+ format!("{}/{key}", self.prefix)+ }+ }++ fn canonical_ref(&self, key: &str) -> String {+ if self.prefix.is_empty() {+ format!("oss://{}/{key}", self.bucket)+ } else {+ format!("oss://{}/{}/{key}", self.bucket, self.prefix)+ }+ }+}++/// Native OSS V4 PUT/DELETE implementation used by the gateway.+pub struct OssPayloadStore {+ client: Client,+ signer: Signer<Credential>,+ location: OssLocation,+ endpoint: Url,+}++impl OssPayloadStore {+ pub fn from_url(value: &str) -> io::Result<Self> {+ let location = OssLocation::parse(value)?;+ let region = required_region()?;+ let credential_source = credential_source_from_environment()?;+ let internal = internal_endpoint_enabled()?;+ let suffix = if internal { "-internal" } else { "" };+ let endpoint = Url::parse(&format!(+ "https://{}.oss-{}{}.aliyuncs.com",+ location.bucket, region, suffix+ ))+ .map_err(|_| invalid("failed to derive OSS endpoint"))?;+ let client = Client::builder()+ .timeout(REQUEST_TIMEOUT)+ .build()+ .map_err(|_| invalid("failed to build OSS HTTP client"))?;+ let provider = OssCredentialProvider::new(credential_source);+ Ok(Self::new_with_provider(+ location, region, endpoint, client, provider,+ ))+ }++ fn new_with_provider(+ location: OssLocation,+ region: String,+ endpoint: Url,+ client: Client,+ provider: impl ProvideCredential<Credential = Credential>,+ ) -> Self {+ let context = Context::new()+ .with_file_read(TokioFileRead)+ .with_http_send(ReqwestHttpSend::new(client.clone()))+ .with_env(OsEnv);+ let request_signer = RequestSigner::new(&location.bucket)+ .with_region(region)+ .with_signing_version(SigningVersion::V4);+ Self {+ client,+ signer: Signer::new(context, provider, request_signer),+ location,+ endpoint,+ }+ }++ fn object_url(&self, key: &str) -> Result<Url, String> {+ let mut url = self.endpoint.clone();+ {+ let mut segments = url+ .path_segments_mut()+ .map_err(|_| "OSS request URL construction failed".to_owned())?;+ segments.clear();+ for segment in self.location.object_key(key).split('/') {+ segments.push(segment);+ }+ }+ Ok(url)+ }++ async fn execute(+ &self,+ operation: &'static str,+ method: Method,+ key: &str,+ data: &[u8],+ ) -> Result<(), String> {+ for attempt in 0..MAX_ATTEMPTS {+ let url = self.object_url(key)?;+ let request = http::Request::builder()+ .method(method.clone())+ .uri(url.as_str())+ .header(http::header::CONTENT_LENGTH, data.len())+ .body(reqwest::Body::from(data.to_vec()))+ .map_err(|_| format!("OSS {operation} request construction failed"))?;+ let (mut parts, body) = request.into_parts();+ self.signer+ .sign(&mut parts, None)+ .await+ .map_err(|_| format!("OSS {operation} credential or signing failed"))?;+ let request = http::Request::from_parts(parts, body)+ .try_into()+ .map_err(|_| format!("OSS {operation} request construction failed"))?;++ match self.client.execute(request).await {+ Ok(response) if response.status().is_success() => return Ok(()),+ Ok(response)+ if method == Method::DELETE && response.status() == StatusCode::NOT_FOUND =>+ {+ return Ok(())+ }+ Ok(response) => {+ let status = response.status();+ if retryable_status(status) && attempt + 1 < MAX_ATTEMPTS {+ retry_delay(attempt).await;+ continue;+ }+ let code = provider_error_code(&response);+ return Err(sanitized_http_error(operation, status, code.as_deref()));+ }+ Err(_) if attempt + 1 < MAX_ATTEMPTS => retry_delay(attempt).await,+ Err(_) => return Err(format!("OSS {operation} transport failed after retry")),+ }+ }+ Err(format!("OSS {operation} failed after retry"))+ }+}++#[async_trait]+impl PayloadStore for OssPayloadStore {+ async fn put(&self, key: &str, data: &[u8]) -> Result<String, String> {+ validate_payload_key(key)?;+ self.execute("PUT", Method::PUT, key, data).await?;+ Ok(self.location.canonical_ref(key))+ }++ async fn delete(&self, key: &str) -> Result<(), String> {+ validate_payload_key(key)?;+ self.execute("DELETE", Method::DELETE, key, &[]).await+ }+}++fn required_region() -> io::Result<String> {+ let region = std::env::var("SIE_OSS_REGION")+ .map_err(|_| invalid("SIE_OSS_REGION is required for oss:// payload storage"))?;+ if !valid_region(®ion) {+ return Err(invalid("SIE_OSS_REGION is invalid"));+ }+ Ok(region)+}++fn internal_endpoint_enabled() -> io::Result<bool> {+ match std::env::var("SIE_OSS_USE_INTERNAL_ENDPOINT") {+ Ok(value) if value.eq_ignore_ascii_case("true") || value == "1" => Ok(true),+ Ok(value) if value.eq_ignore_ascii_case("false") || value == "0" => Ok(false),+ Ok(_) => Err(invalid(+ "SIE_OSS_USE_INTERNAL_ENDPOINT must be true, false, 1, or 0",+ )),+ Err(std::env::VarError::NotPresent) => Ok(false),+ Err(_) => Err(invalid("SIE_OSS_USE_INTERNAL_ENDPOINT is invalid")),+ }+}++fn credential_source_from_environment() -> io::Result<OssCredentialSource> {+ if std::env::var_os("ALIBABA_CLOUD_STS_ENDPOINT").is_some() {+ return Err(invalid("custom Alibaba STS endpoints are not supported"));+ }+ let alibaba_static = validate_pair(+ "ALIBABA_CLOUD_ACCESS_KEY_ID",+ "ALIBABA_CLOUD_ACCESS_KEY_SECRET",+ )?;+ let oss_static = validate_pair("OSS_ACCESS_KEY_ID", "OSS_ACCESS_KEY_SECRET")?;+ if optional_token_is_invalid("ALIBABA_CLOUD_SECURITY_TOKEN", alibaba_static)+ || optional_token_is_invalid("OSS_SESSION_TOKEN", oss_static)+ || (alibaba_static && oss_static)+ {+ return Err(invalid(+ "Alibaba static credential configuration is ambiguous or incomplete",+ ));+ }+ let oidc_names = [+ "ALIBABA_CLOUD_ROLE_ARN",+ "ALIBABA_CLOUD_OIDC_PROVIDER_ARN",+ "ALIBABA_CLOUD_OIDC_TOKEN_FILE",+ ];+ let oidc_present = oidc_names.map(|name| std::env::var_os(name).is_some());+ let oidc = oidc_names.map(environment_value_is_nonempty);+ if oidc_present.iter().any(|set| *set) && !oidc.iter().all(|set| *set) {+ return Err(invalid("Alibaba RRSA configuration is incomplete"));+ }+ select_credential_source(alibaba_static || oss_static, oidc).map_err(invalid)+}++fn optional_token_is_invalid(name: &str, base_credentials_configured: bool) -> bool {+ !optional_token_configuration_is_valid(+ base_credentials_configured,+ std::env::var_os(name).is_some(),+ environment_value_is_nonempty(name),+ )+}++fn optional_token_configuration_is_valid(+ base_configured: bool,+ token_present: bool,+ token_nonempty: bool,+) -> bool {+ !token_present || (base_configured && token_nonempty)+}++fn select_credential_source(+ static_configured: bool,+ oidc: [bool; 3],+) -> Result<OssCredentialSource, &'static str> {+ if oidc.iter().any(|set| *set) && !oidc.iter().all(|set| *set) {+ return Err("Alibaba RRSA configuration is incomplete");+ }+ if oidc.iter().all(|set| *set) {+ if static_configured {+ return Err("Alibaba static credentials and RRSA must not be configured together");+ }+ return Ok(OssCredentialSource::Oidc);+ }+ Ok(OssCredentialSource::Environment)+}++fn validate_pair(first: &str, second: &str) -> io::Result<bool> {+ let first_present = std::env::var_os(first).is_some();+ let second_present = std::env::var_os(second).is_some();+ let first_set = environment_value_is_nonempty(first);+ let second_set = environment_value_is_nonempty(second);+ if first_present != second_present || first_present != first_set || second_present != second_set+ {+ return Err(invalid(+ "Alibaba static credential configuration is incomplete",+ ));+ }+ Ok(first_set)+}++fn environment_value_is_nonempty(name: &str) -> bool {+ std::env::var(name).is_ok_and(|value| !value.trim().is_empty())+}++fn validate_payload_key(key: &str) -> Result<(), String> {+ if key.is_empty()+ || key.contains("..")+ || !key+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))+ {+ return Err("invalid OSS payload key".to_owned());+ }+ Ok(())+}++fn validate_raw_prefix(raw_path: &str) -> io::Result<String> {+ if raw_path.is_empty() {+ return Ok(String::new());+ }+ if raw_path.starts_with('/')+ || raw_path.contains("//")+ || raw_path.contains('\\')+ || raw_path.split('/').any(|segment| {+ segment == "."+ || segment == ".."+ || !segment+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))+ })+ {+ return Err(invalid("OSS payload-store prefix is malformed"));+ }+ Ok(raw_path.strip_suffix('/').unwrap_or(raw_path).to_owned())+}++fn valid_bucket(bucket: &str) -> bool {+ (3..=63).contains(&bucket.len())+ && bucket+ .bytes()+ .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')+ && bucket+ .as_bytes()+ .first()+ .is_some_and(u8::is_ascii_alphanumeric)+ && bucket+ .as_bytes()+ .last()+ .is_some_and(u8::is_ascii_alphanumeric)+}++fn valid_region(region: &str) -> bool {+ !region.is_empty()+ && region+ .bytes()+ .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')+ && region+ .as_bytes()+ .first()+ .is_some_and(u8::is_ascii_alphanumeric)+ && region+ .as_bytes()+ .last()+ .is_some_and(u8::is_ascii_alphanumeric)+}++fn retryable_status(status: StatusCode) -> bool {+ status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error()+}++async fn retry_delay(attempt: usize) {+ tokio::time::sleep(Duration::from_millis(50 * (attempt as u64 + 1))).await;+}++fn provider_error_code(response: &reqwest::Response) -> Option<String> {+ response+ .headers()+ .get("x-oss-error-code")+ .and_then(|value| value.to_str().ok())+ .and_then(clean_error_code)+}++fn clean_error_code(value: &str) -> Option<String> {+ if value.is_empty()+ || value.len() > 64+ || !value+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))+ {+ return None;+ }+ Some(value.to_owned())+}++fn sanitized_http_error(operation: &str, status: StatusCode, code: Option<&str>) -> String {+ match code {+ Some(code) => format!(+ "OSS {operation} failed: status={} code={code}",+ status.as_u16()+ ),+ None => format!("OSS {operation} failed: status={}", status.as_u16()),+ }+}++fn invalid(message: &str) -> io::Error {+ io::Error::new(io::ErrorKind::InvalidInput, message)+}++#[cfg(test)]+mod tests {+ use super::*;+ use reqsign_aliyun_oss::StaticCredentialProvider;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::sync::Arc;+ use wiremock::matchers::{header_regex, method, path, query_param};+ use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};++ fn loopback_store(server: &MockServer) -> OssPayloadStore {+ let client = Client::builder().timeout(REQUEST_TIMEOUT).build().unwrap();+ OssPayloadStore::new_with_provider(+ OssLocation::parse("oss://sie-test-bucket/payloads").unwrap(),+ "eu-central-1".to_owned(),+ Url::parse(&server.uri()).unwrap(),+ client,+ StaticCredentialProvider::new("test-access-key", "test-secret-key"),+ )+ }++ #[derive(Clone)]+ struct RetryThenOk(Arc<AtomicUsize>);++ impl Respond for RetryThenOk {+ fn respond(&self, _request: &Request) -> ResponseTemplate {+ if self.0.fetch_add(1, Ordering::SeqCst) == 0 {+ ResponseTemplate::new(503)+ } else {+ ResponseTemplate::new(200)+ }+ }+ }++ #[test]+ fn strict_location_contract() {+ let location = OssLocation::parse("oss://sie-test-bucket/payloads").unwrap();+ assert_eq!(location.bucket, "sie-test-bucket");+ assert_eq!(location.prefix, "payloads");+ assert_eq!(+ location.canonical_ref("request_0.bin"),+ "oss://sie-test-bucket/payloads/request_0.bin"+ );+ for invalid_value in [+ "oss:///payloads",+ "oss://user@sie-test-bucket/payloads",+ "oss://sie-test-bucket/payloads?x=1",+ "oss://sie-test-bucket/payloads#fragment",+ "oss://sie-test-bucket/a//b",+ "oss://sie-test-bucket/a/%2e%2e/b",+ "oss://sie-test-bucket/a/../b",+ "oss://sie-test-bucket/a/./b",+ "oss://sie-test-bucket//payloads",+ "oss://sie-test-bucket/payloads//",+ "oss://SIE-test-bucket/payloads",+ ] {+ assert!(+ OssLocation::parse(invalid_value).is_err(),+ "{invalid_value}"+ );+ }+ }++ #[test]+ fn rrsa_is_exclusive_and_cannot_be_masked_by_static_credentials() {+ assert_eq!(+ select_credential_source(false, [true, true, true]),+ Ok(OssCredentialSource::Oidc)+ );+ assert!(select_credential_source(true, [true, true, true]).is_err());+ assert!(select_credential_source(false, [true, false, true]).is_err());+ assert_eq!(+ select_credential_source(true, [false, false, false]),+ Ok(OssCredentialSource::Environment)+ );+ assert!(!optional_token_configuration_is_valid(true, true, false));+ assert!(!optional_token_configuration_is_valid(false, true, true));+ assert!(optional_token_configuration_is_valid(true, true, true));+ }++ #[test]+ fn payload_keys_are_plain_and_safe() {+ assert!(validate_payload_key("request_0.bin").is_ok());+ for key in ["", "../x", "a/b", "a\\b", "a?query", "a%2fb"] {+ assert!(validate_payload_key(key).is_err(), "{key}");+ }+ }++ #[test]+ fn errors_expose_only_closed_fields() {+ let error = sanitized_http_error(+ "PUT",+ StatusCode::FORBIDDEN,+ clean_error_code("AccessDenied").as_deref(),+ );+ assert_eq!(error, "OSS PUT failed: status=403 code=AccessDenied");+ for secret in ["Authorization", "SecurityToken", "AccessKey", "RequestId"] {+ assert!(!error.contains(secret));+ }+ }++ #[test]+ fn loads_shared_wire_fixture() {+ let fixture: serde_json::Value = serde_json::from_str(include_str!(+ "../../../wire-fixtures/oss_payload_store.json"+ ))+ .unwrap();+ let configured = format!(+ "oss://{}/{}",+ fixture["bucket"].as_str().unwrap(),+ fixture["prefix"].as_str().unwrap()+ );+ let location = OssLocation::parse(&configured).unwrap();+ let key = fixture["plain_key"].as_str().unwrap();+ assert_eq!(location.object_key(key), fixture["object_key"]);+ assert_eq!(location.canonical_ref(key), fixture["full_reference"]);+ }++ #[tokio::test]+ async fn loopback_put_delete_use_v4_and_retry() {+ let server = MockServer::start().await;+ let attempts = Arc::new(AtomicUsize::new(0));+ Mock::given(method("PUT"))+ .and(path("/payloads/request_0.bin"))+ .and(header_regex("authorization", "^OSS4-HMAC-SHA256 "))+ .respond_with(RetryThenOk(attempts.clone()))+ .expect(2)+ .mount(&server)+ .await;+ Mock::given(method("DELETE"))+ .and(path("/payloads/request_0.bin"))+ .and(header_regex("authorization", "^OSS4-HMAC-SHA256 "))+ .respond_with(ResponseTemplate::new(404))+ .expect(1)+ .mount(&server)+ .await;++ let store = loopback_store(&server);+ assert_eq!(+ store.put("request_0.bin", b"payload").await.unwrap(),+ "oss://sie-test-bucket/payloads/request_0.bin"+ );+ store.delete("request_0.bin").await.unwrap();+ assert_eq!(attempts.load(Ordering::SeqCst), 2);+ }++ #[tokio::test]+ async fn oidc_refresh_rereads_projected_token() {+ let server = MockServer::start().await;+ let directory = tempfile::TempDir::new().unwrap();+ let token_path = directory.path().join("rrsa-token");+ std::fs::write(&token_path, "first-token").unwrap();+ let expiration =+ (reqsign_core::time::Timestamp::now() + Duration::from_secs(60)).format_rfc3339_zulu();+ let response = serde_json::json!({+ "Credentials": {+ "SecurityToken": "temporary-security-token",+ "Expiration": expiration,+ "AccessKeySecret": "temporary-secret",+ "AccessKeyId": "temporary-access-key"+ }+ });+ for token in ["first-token", "second-token"] {+ Mock::given(method("GET"))+ .and(query_param("Action", "AssumeRoleWithOIDC"))+ .and(query_param("OIDCToken", token))+ .respond_with(ResponseTemplate::new(200).set_body_json(&response))+ .expect(1)+ .mount(&server)+ .await;+ }+ Mock::given(method("PUT"))+ .and(path("/payloads/request_0.bin"))+ .and(header_regex("authorization", "^OSS4-HMAC-SHA256 "))+ .respond_with(ResponseTemplate::new(200))+ .expect(2)+ .mount(&server)+ .await;++ let client = Client::builder().timeout(REQUEST_TIMEOUT).build().unwrap();+ let provider = AssumeRoleWithOidcCredentialProvider::new()+ .with_role_arn("acs:ram::000000000000:role/test")+ .with_oidc_provider_arn("acs:ram::000000000000:oidc-provider/test")+ .with_oidc_token_file(token_path.to_string_lossy())+ .with_sts_endpoint(server.uri());+ let store = OssPayloadStore::new_with_provider(+ OssLocation::parse("oss://sie-test-bucket/payloads").unwrap(),+ "eu-central-1".to_owned(),+ Url::parse(&server.uri()).unwrap(),+ client,+ provider,+ );+ store.put("request_0.bin", b"one").await.unwrap();+ std::fs::write(&token_path, "second-token").unwrap();+ store.put("request_0.bin", b"two").await.unwrap();+ }+}diff --git a/packages/sie_gateway/src/queue/payload_store.rs b/packages/sie_gateway/src/queue/payload_store.rsindex 61839a5c6..9b8902c4b 100644--- a/packages/sie_gateway/src/queue/payload_store.rs+++ b/packages/sie_gateway/src/queue/payload_store.rs@@ -8,7 +8,7 @@ use tracing::debug;#[cfg(feature = "cloud-storage")]use object_store::ObjectStoreExt;-const OBJECT_STORE_SCHEMES: &[&str] = &["s3://", "gs://", "abfs://", "abfss://"];+const OBJECT_STORE_SCHEMES: &[&str] = &["s3://", "gs://", "abfs://", "abfss://", "oss://"];fn object_store_scheme(url: &str) -> Option<&'static str> {OBJECT_STORE_SCHEMES@@ -281,13 +281,19 @@ impl PayloadStore for ObjectStorePayloadStore {/// Factory function to create the appropriate payload store based on URL prefix.pub async fn create_payload_store(url: &str) -> io::Result<Arc<dyn PayloadStore>> {- if url.trim().is_empty() {+ let url = url.trim();+ if url.is_empty() {return Ok(Arc::new(DisabledPayloadStore));}#[cfg(feature = "cloud-storage")]{if let Some(scheme) = object_store_scheme(url) {+ if let Some(rest) = url.strip_prefix("oss://") {+ return Ok(Arc::new(+ super::oss_payload_store::OssPayloadStore::from_url(&format!("oss://{rest}"))?,+ ));+ }if let Some(rest) = url.strip_prefix("s3://") {return Ok(Arc::new(ObjectStorePayloadStore::new_s3(rest)?));}@@ -498,6 +504,28 @@ mod tests {assert!(err.to_string().contains("cloud-storage"));}+ #[cfg(not(feature = "cloud-storage"))]+ #[tokio::test]+ async fn test_create_payload_store_oss_without_feature() {+ let err = match create_payload_store("oss://my-bucket/payloads").await {+ Ok(_) => panic!("expected oss:// 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_trims_before_scheme_classification() {+ let err = match create_payload_store(" oss://my-bucket/payloads ").await {+ Ok(_) => panic!("expected trimmed oss:// 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::*;diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex 4206a57fc..4f2f51381 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -18,7 +18,10 @@ use rmp::Marker;use super::dispatch::{DispatchDurability, PendingDispatchKind};use super::identity::canonical_work_item_id;+use super::keyed_worker_pool::{KeyedWorkerPool, ShardKeyed};+use super::lane_admission::{LaneAdmissionControl, LaneAdmissionOutcome, LaneKey, LaneReservation};use super::payload_store::PayloadStore;+use super::stream_durability;use super::streaming::{ChunkApplied, ChunkEnvelope, ChunkError, NakEnvelope, StreamCollector, StreamOutcome,};@@ -36,6 +39,28 @@ pub(crate) const MAX_QUEUE_REQUEST_ITEMS: usize = 4_096;const MAX_CONCURRENT_INITIAL_PUBLISHES: usize = 64;const PUBLISH_ACK_COMPLETION_TIMEOUT: Duration = Duration::from_secs(6);+/// Metric label for the inbox handler pool.+const INBOX_POOL_NAME: &str = "inbox";+/// Ordering domains for inbox work. A shard is a tokio task multiplexed onto+/// the existing runtime workers, not a thread, so this is a concurrency width+/// rather than a core count: wide enough that unrelated requests rarely share+/// a shard, narrow enough to keep worst-case buffered bytes small.+const INBOX_POOL_SHARDS: usize = 8;+/// Queue depth per inbox shard. Deliberately shallow. A queued item is a fully+/// decoded envelope whose size is bounded only by the NATS max payload, so+/// `SHARDS * DEPTH` is what bounds the transient duplicate residency of result+/// bytes ahead of the per-request reservation. With cleanup moved off them,+/// the handlers are DashMap work plus a channel send, so a shallow queue is+/// already enough to decouple decode from a momentarily slow handler.+const INBOX_POOL_DEPTH: usize = 16;+/// Metric label for the object-store cleanup pool.+const CLEANUP_POOL_NAME: &str = "payload_cleanup";+const CLEANUP_POOL_SHARDS: usize = 4;+/// A queued cleanup item is one request id, so this queue can be deep without+/// costing memory. It is still bounded; overflow falls back to the periodic+/// `cleanup_expired` reconcile.+const CLEANUP_POOL_DEPTH: usize = 256;+const RESULT_CHUNK_KIND: &str = "result_chunk_v1";const MAX_RESULT_CHUNK_ITEM_BYTES: usize = 16 * 1_024 * 1_024;const MAX_RESULT_CHUNKS_PER_ITEM: u32 = 64;@@ -799,13 +824,34 @@ fn accumulate_pending_generation_group(group.oldest_request_age_ms = group.oldest_request_age_ms.max(age_ms);}+/// The shape of the `WORK_POOL_{pool}` streams this gateway creates.+///+/// Grouped rather than passed as loose constructor arguments because the+/// three move together: they are the part of the stream config that the+/// worker sidecars must mirror exactly (`SIE_STREAM_MAX_AGE_S`,+/// `SIE_STREAM_STORAGE`, `SIE_STREAM_REPLICAS`, all rendered onto both by+/// Helm), since whoever creates a stream first wins.+#[derive(Debug, Clone, Copy)]+pub struct WorkStreamConfig {+ pub max_age: Duration,+ /// Storage backing. Defaults to `Memory`, which is the only behaviour+ /// that existed before the knob: queued work lives in the broker's RAM+ /// and a NATS restart erases it. See [`crate::config::StreamStorage`]+ /// for the trade-off and [`WorkPublisher::ensure_stream`] for why an+ /// existing stream's storage type is reported rather than reconciled.+ pub storage: jetstream::stream::StorageType,+ /// JetStream replica count (default 1). Unlike `storage`, this IS+ /// reconcilable in place.+ pub num_replicas: usize,+}+pub struct WorkPublisher {jetstream: jetstream::Context,router_id: String,payload_store: Arc<dyn PayloadStore>,result_timeout: Duration,max_stream_pending: u64,- stream_max_age: Duration,+ stream: WorkStreamConfig,/// Pools we've already `get_or_create_stream`'d for, keyed by pool/// name so we skip the admin-API round trip on subsequent/// requests. The value is the pre-computed JetStream stream name@@ -817,6 +863,10 @@ pub struct WorkPublisher {/// primes it synchronously in [`Self::ensure_stream`] so we/// don't fail-open during the initial monitor interval.stream_info_cache: DashMap<String, CachedStreamInfo>,+ /// Per-lane in-flight accounting (B5, first half). Complements+ /// `max_stream_pending`, which is whole-stream and therefore pool-wide.+ /// Its decision is always computed; whether it sheds is its own flag.+ lane_admission: LaneAdmissionControl,pending_results: DashMap<String, ResultCollector>,/// Process-wide result-chunk reservation pool shared by every pending/// request owned by this publisher.@@ -845,6 +895,15 @@ pub struct WorkPublisher {/// tolerate ``None`` (cancellation simply becomes a no-op).nats_client: tokio::sync::RwLock<Option<async_nats::Client>>,inbox_handle: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,+ /// Runs inbox handlers off the single decode task, keyed by request id so+ /// one request's messages stay strictly ordered while different requests+ /// proceed concurrently. Created on the first+ /// [`Self::start_inbox_subscription`] and reused across NATS reconnects,+ /// so a re-subscribe never abandons already-queued work.+ inbox_pool: tokio::sync::OnceCell<KeyedWorkerPool<InboxWork>>,+ /// Runs object-store payload deletes off both the decode task and the+ /// inbox handlers. See [`Self::defer_cleanup`] for the bound policy.+ cleanup_pool: tokio::sync::OnceCell<KeyedWorkerPool<CleanupWork>>,/// H9 — first-chunk-fallback rate-limit buckets, keyed by/// ``"{model}|{pool}"``. Each bucket gates calls into/// [`Self::republish_to_pool`] tagged with the@@ -930,6 +989,10 @@ struct ResultCollector {direct_fallback_republished_indices: BTreeSet<usize>,direct_fallback_payloads: Vec<Option<Vec<u8>>>,direct_fallback_republished: bool,+ /// Per-lane in-flight reservation, released when this collector drops.+ /// Every terminal path (completion, timeout, publish failure, the expiry+ /// sweep) drops the collector, so no path needs its own release call.+ _lane_reservation: Option<LaneReservation>,}#[derive(Debug)]@@ -1882,6 +1945,23 @@ impl PublishTarget {} => machine_profile,}}++ pub fn bundle(&self) -> &str {+ match self {+ PublishTarget::Worker { bundle, .. } | PublishTarget::Pool { bundle, .. } => bundle,+ }+ }++ /// The `(pool, machine_profile, bundle)` lane this target publishes onto.+ ///+ /// Both variants share it: a worker-direct target is one worker inside the+ /// same lane as its pool fallback, so per-lane admission accounting covers+ /// direct dispatch too — the blind spot recorded in+ /// [`WorkPublisher::check_backpressure`]'s doc block, where a saturated+ /// worker inbox reads as a healthy pool stream, does not apply here.+ pub fn lane(&self) -> LaneKey {+ LaneKey::new(self.pool(), self.machine_profile(), self.bundle())+ }}/// Peek the top-level `kind` discriminator on an already-decoded@@ -1907,6 +1987,173 @@ fn envelope_kind(value: &rmpv::Value) -> Option<&str> {None}+/// One decoded inbox message together with the request it belongs to.+///+/// Produced only by [`inbox_work_for_payload`], which owns the single msgpack+/// decode. Handing this — rather than the raw payload — to the worker pool is+/// what keeps the "decode exactly once, on the decode task" property while+/// the handlers run elsewhere.+#[derive(Debug)]+enum InboxWork {+ ResultChunk(Box<ResultChunkV1>),+ /// A `result_chunk_v1` envelope that failed to decode. The request is+ /// known (from the fast-path peek) and must be failed, and that failure+ /// has to be ordered against the request's other inbox work.+ ResultChunkDecodeFailure {+ request_id: String,+ },+ Chunk(Box<ChunkEnvelope>),+ Nak(Box<NakEnvelope>),+ Result(Box<WorkResult>),+}++/// Every variant carries exactly one request id, so all of a request's inbox+/// work lands on one shard and is handled in arrival order.+impl ShardKeyed for InboxWork {+ fn shard_key(&self) -> &str {+ match self {+ Self::ResultChunk(chunk) => &chunk.request_id,+ Self::ResultChunkDecodeFailure { request_id } => request_id,+ Self::Chunk(chunk) => &chunk.request_id,+ Self::Nak(nak) => &nak.request_id,+ Self::Result(result) => &result.request_id,+ }+ }+}++/// Turn one raw inbox payload into the work its handler needs, or `None` when+/// the message is to be dropped.+///+/// This is the entire decode side of the inbox loop, extracted from+/// [`WorkPublisher::handle_inbox`] so it is unit-testable without a broker.+/// In order:+///+/// 1. Fast path — peek `request_id` out of the raw bytes and drop the message+/// outright when this gateway tracks no such request, without decoding it.+/// 2. Decode the msgpack payload **exactly once** into an `rmpv::Value`.+/// 3. Peek the `kind` discriminator on that decoded value and convert the+/// *same* value into the typed envelope via `rmpv::ext::from_value` — never+/// a second decode from the raw slice. Older code re-decoded up to three+/// times per chunk, which is the hot path for streaming generation.+///+/// Only the exact v1 discriminator enters the v1 decoder. That fails malformed+/// exact-v1 envelopes closed while preserving forward compatibility for+/// ordinary/future `WorkResult` fields such as `total_bytes`.+fn inbox_work_for_payload(payload: &[u8], is_tracked: impl Fn(&str) -> bool) -> Option<InboxWork> {+ let request_id_hint = extract_request_id_fast(payload);+ if let Some(request_id) = request_id_hint {+ if !is_tracked(request_id) {+ debug!(+ request_id = %request_id,+ "fast-path skip: result for unknown request"+ );+ return None;+ }+ }++ let value: rmpv::Value = match rmp_serde::from_slice(payload) {+ Ok(value) => value,+ Err(e) => {+ warn!(error = %e, "failed to decode inbox payload");+ return None;+ }+ };++ match envelope_kind(&value) {+ Some(RESULT_CHUNK_KIND) => match rmpv::ext::from_value::<ResultChunkV1>(value) {+ Ok(chunk) => Some(InboxWork::ResultChunk(Box::new(chunk))),+ Err(e) => {+ telemetry::record_queue_result_chunk_received(None);+ telemetry::record_queue_result_chunk_rejection(+ telemetry::QueueResultChunkRejectionReason::Decode,+ );+ warn!(error = %e, "failed to decode result chunk envelope");+ request_id_hint.map(|request_id| InboxWork::ResultChunkDecodeFailure {+ request_id: request_id.to_string(),+ })+ }+ },+ // Chunk envelopes feed the streaming aggregator.+ Some("chunk") => match rmpv::ext::from_value::<ChunkEnvelope>(value) {+ Ok(chunk) => Some(InboxWork::Chunk(Box::new(chunk))),+ Err(e) => {+ warn!(error = %e, "failed to decode chunk envelope");+ None+ }+ },+ // Worker-emitted NAK. The publisher republishes the cached work item+ // to the pool subject; if the republish fails we surface a+ // transport-style terminal outcome to the HTTP handler.+ Some("nak") => match rmpv::ext::from_value::<NakEnvelope>(value) {+ Ok(nak) => Some(InboxWork::Nak(Box::new(nak))),+ Err(e) => {+ warn!(error = %e, "failed to decode nak envelope");+ None+ }+ },+ // Anything else (encode/score/extract WorkResults — an array-shaped+ // payload, or a map with an unknown/absent `kind`) flows to the+ // ResultCollector path.+ _ => match rmpv::ext::from_value::<WorkResult>(value) {+ Ok(result) => Some(InboxWork::Result(Box::new(result))),+ Err(e) => {+ warn!(error = %e, "failed to decode inbox result");+ None+ }+ },+ }+}++/// Deferred object-store cleanup for one finished request.+///+/// Both variants are best-effort deletes with an independent backstop in+/// [`WorkPublisher::cleanup_expired`], which is what makes it safe to shed+/// them at the queue bound.+#[derive(Debug)]+enum CleanupWork {+ /// Non-streaming request payload blobs (`offloaded_payload_keys`).+ Payloads(String),+ /// Offloaded generate blob for a streaming request (`offloaded_streams`).+ Generate(String),+}++impl ShardKeyed for CleanupWork {+ fn shard_key(&self) -> &str {+ match self {+ Self::Payloads(request_id) | Self::Generate(request_id) => request_id,+ }+ }+}++/// Hand one cleanup to the pool, or give it back for the caller to run inline.+///+/// Extracted from [`WorkPublisher::defer_cleanup`] so the hand-off policy is+/// unit-testable without a live JetStream context (matching the treatment of+/// [`cleanup_offloaded_payloads_inner`] for issue #1471).+///+/// * `pool` present and with room — queued, `None`. **The caller does not+/// await the object-store round trip.**+/// * `pool` present and saturated — shed, `None`. Safe because+/// [`WorkPublisher::cleanup_expired`] reconciles orphaned keys every 10s.+/// * `pool` absent (a publisher with no inbox subscription) — `Some(work)`,+/// so cleanup still happens inline rather than being silently skipped.+fn queue_cleanup(+ pool: Option<&KeyedWorkerPool<CleanupWork>>,+ work: CleanupWork,+) -> Option<CleanupWork> {+ let Some(pool) = pool else {+ return Some(work);+ };+ let request_id = work.shard_key().to_string();+ if !pool.try_dispatch(work) {+ debug!(+ request_id = %request_id,+ "cleanup queue saturated — leaving the blob to the periodic reconcile"+ );+ }+ None+}+/// Fast-path extraction of `request_id` from raw msgpack bytes./// Returns None on any parse failure (caller falls back to full deserialization).fn extract_request_id_fast(payload: &[u8]) -> Option<&str> {@@ -2216,6 +2463,92 @@ fn already_republished_nak_decision(AlreadyRepublishedNakDecision::Fail}+/// Pool-wide admission from one cached `WORK_POOL_{pool}` snapshot.+///+/// `num_pending` is a whole-stream count and a stream is per pool, so this+/// number cannot tell a hot model's backlog from a cold model's. That is the+/// defect [`check_lane_backpressure`] addresses; this stays exactly as it was+/// and remains the sole gate whenever per-lane enforcement is off.+///+/// Free function so the composition of the two checks is testable without a+/// live broker.+fn pool_backpressure_error(info: &CachedStreamInfo, max_stream_pending: u64) -> Option<String> {+ if info.num_consumers == 0 {+ return Some("no consumers available for work stream".to_string());+ }+ if info.num_pending > max_stream_pending {+ return Some(format!(+ "backpressure: {} pending messages exceeds threshold {}",+ info.num_pending, max_stream_pending+ ));+ }+ None+}++/// Evaluate one publish against its lane's own in-flight ceiling.+///+/// The decision is computed on every publish regardless of the enforcement+/// flag, and recorded, so it can be evaluated against production traffic+/// before it is acted on. With enforcement off this always returns `Ok`, which+/// leaves [`pool_backpressure_error`] as the only gate — today's behaviour+/// exactly.+///+/// Returns the reservation the caller must keep alive for the lifetime of the+/// request; dropping it releases the lane.+fn check_lane_backpressure(+ lane_admission: &LaneAdmissionControl,+ lane: &LaneKey,+ items: u64,+) -> Result<Option<LaneReservation>, String> {+ let admission = lane_admission.admit(lane, items);+ // Lane labels are bounded by the deployment's physical lane catalog. A+ // lane outside it is logged but not counted rather than counted under a+ // synthetic label — see `gateway_lane_admission_domain` in+ // `telemetry/contract.yaml`.+ if let Some(resolved) = lane_admission.resolve(lane) {+ telemetry::record_queue_lane_admission_decision(&resolved, admission.outcome);+ }+ match admission.outcome {+ LaneAdmissionOutcome::Admitted => Ok(admission.reservation),+ LaneAdmissionOutcome::ShedShadow => {+ debug!(+ pool = %lane.pool,+ machine_profile = %lane.machine_profile,+ bundle = %lane.bundle,+ in_flight = admission.in_flight,+ threshold = admission.threshold,+ "lane backpressure would shed this publish (shadow mode; not enforced)"+ );+ Ok(admission.reservation)+ }+ LaneAdmissionOutcome::ShedEnforced => {+ warn!(+ pool = %lane.pool,+ machine_profile = %lane.machine_profile,+ bundle = %lane.bundle,+ in_flight = admission.in_flight,+ threshold = admission.threshold,+ "lane backpressure shed this publish"+ );+ // The "backpressure:" prefix is load-bearing: it is what+ // `QueuePublishOutcome::from_error` classifies on and what+ // `handlers::proxy::record_publish_failure` matches to return the+ // same 503 + `Retry-After` as a pool-wide shed and to record+ // pending demand so KEDA scales the saturated lane.+ //+ // The lane's identity stays out of the message. This string+ // reaches the client in the `QUEUE_UNAVAILABLE` body, and a pool+ // name is operator-defined and may encode tenant context. The+ // `warn!` above and the decision metric carry the identity. The+ // wording still distinguishes a lane shed from the pool-wide one.+ Err(format!(+ "backpressure: work lane saturated ({} in-flight items exceeds threshold {})",+ admission.in_flight, admission.threshold+ ))+ }+ }+}+impl WorkPublisher {pub fn new(jetstream: jetstream::Context,@@ -2223,7 +2556,7 @@ impl WorkPublisher {payload_store: Arc<dyn PayloadStore>,result_timeout: Duration,max_stream_pending: u64,- stream_max_age: Duration,+ stream: WorkStreamConfig,) -> Self {Self {jetstream,@@ -2231,9 +2564,13 @@ impl WorkPublisher {payload_store,result_timeout,max_stream_pending,- stream_max_age,+ stream: WorkStreamConfig {+ num_replicas: stream.num_replicas.max(1),+ ..stream+ },ensured_streams: DashMap::new(),stream_info_cache: DashMap::new(),+ lane_admission: LaneAdmissionControl::default(),pending_results: DashMap::new(),result_chunk_budget: Arc::clone(&RESULT_CHUNK_BUDGET),pending_streams: DashMap::new(),@@ -2241,12 +2578,24 @@ impl WorkPublisher {offloaded_payload_keys: DashMap::new(),nats_client: tokio::sync::RwLock::new(None),inbox_handle: tokio::sync::Mutex::new(None),+ inbox_pool: tokio::sync::OnceCell::new(),+ cleanup_pool: tokio::sync::OnceCell::new(),fallback_buckets: DashMap::new(),fallback_rate_per_sec: FALLBACK_RATE_PER_SEC_DEFAULT,fallback_burst: FALLBACK_BURST_DEFAULT,}}+ /// Install the deployment's per-lane admission policy.+ ///+ /// Constructed separately from [`Self::new`] because it is a policy, not+ /// part of the queue's wiring: [`Self::new`] installs the shadow-mode+ /// default so a publisher built without one still records the decision.+ pub fn with_lane_admission(mut self, lane_admission: LaneAdmissionControl) -> Self {+ self.lane_admission = lane_admission;+ self+ }+/// Try to consume one first-chunk-fallback token for ``(model, pool)``./// Returns true when a republish is permitted, false when the bucket is/// empty (the caller MUST surface a 504 / refused-republish outcome).@@ -2284,6 +2633,11 @@ impl WorkPublisher {/// Returns the cached JetStream stream name as an `Arc<str>` so/// callers can avoid rebuilding `format!("WORK_POOL_{pool}")` on/// the hot path.+ ///+ /// Reconciliation of an existing stream covers `subjects`, `max_age`,+ /// `discard`, and `num_replicas`. It deliberately does NOT cover+ /// `storage`: JetStream refuses an in-place storage-type change, so a+ /// mismatch is logged as a warning and the stream is left as-is.pub async fn ensure_stream(&self, pool: &str) -> Result<Arc<str>, String> {if let Some(existing) = self.ensured_streams.get(pool) {return Ok(Arc::clone(&existing));@@ -2299,9 +2653,19 @@ impl WorkPublisher {name: name.clone(),subjects,retention: jetstream::stream::RetentionPolicy::WorkQueue,- storage: jetstream::stream::StorageType::Memory,- max_age: self.stream_max_age,+ // Configurable via `SIE_STREAM_STORAGE` / `SIE_STREAM_REPLICAS`;+ // defaults are `Memory` / 1, i.e. unchanged from before the knob+ // existed. Must match the worker sidecars — whoever creates the+ // stream first wins.+ storage: self.stream.storage,+ num_replicas: self.stream.num_replicas,+ max_age: self.stream.max_age,max_messages: 100_000,+ // Must match the sidecar's stream creators: at the+ // `max_messages` cap the broker rejects the new publish+ // (surfacing on the existing 503 queue-unavailable path)+ // instead of silently discarding the oldest queued work.+ discard: jetstream::stream::DiscardPolicy::New,..Default::default()}).await@@ -2329,9 +2693,9 @@ impl WorkPublisher {);}let observed_max_age = stream.cached_info().config.max_age;- if observed_max_age != self.stream_max_age {+ if observed_max_age != self.stream.max_age {let mut updated = stream.cached_info().config.clone();- updated.max_age = self.stream_max_age;+ updated.max_age = self.stream.max_age;self.jetstream.update_stream(updated).await@@ -2344,10 +2708,43 @@ impl WorkPublisher {info!(stream = %name,observed_max_age_s = observed_max_age.as_secs(),- desired_max_age_s = self.stream_max_age.as_secs(),+ desired_max_age_s = self.stream.max_age.as_secs(),"reconciled JetStream stream max_age");}+ // Repair pre-existing streams created with the async-nats default+ // (`Old`), which silently discards the oldest queued work at the+ // `max_messages` cap instead of rejecting the new publish.+ let observed_discard = stream.cached_info().config.discard;+ if observed_discard != jetstream::stream::DiscardPolicy::New {+ let mut updated = stream.cached_info().config.clone();+ updated.discard = jetstream::stream::DiscardPolicy::New;+ self.jetstream+ .update_stream(updated)+ .await+ .map_err(|e| format!("update stream {} discard: {}", name, e))?;+ stream = self+ .jetstream+ .get_stream(name.clone())+ .await+ .map_err(|e| format!("refresh stream {} after discard update: {}", name, e))?;+ info!(+ stream = %name,+ observed_discard = ?observed_discard,+ "reconciled JetStream stream discard policy to New (reject publishes at cap)"+ );+ }+ // Durability reconcile policy (replicas repaired, storage reported+ // but never repaired) is shared with the DLQ stream — see+ // `queue::stream_durability` for why the two fields differ.+ stream_durability::reconcile_num_replicas(+ &self.jetstream,+ &mut stream,+ &name,+ self.stream.num_replicas,+ )+ .await?;+ stream_durability::warn_on_storage_mismatch(&stream, &name, self.stream.storage);// Prime the backpressure cache so the very first request to// this pool sees real consumer/pending numbers instead of@@ -2394,20 +2791,22 @@ impl WorkPublisher {/// pick it up. Tighter per-worker admission is M5+ work (tracked/// alongside the §6 mixed-pool fairness scheduler).fn check_backpressure(&self, pool: &str) -> Result<(), String> {- if let Some(info) = self.stream_info_cache.get(pool) {- if info.num_consumers == 0 {- return Err("no consumers available for work stream".to_string());- }- if info.num_pending > self.max_stream_pending {- return Err(format!(- "backpressure: {} pending messages exceeds threshold {}",- info.num_pending, self.max_stream_pending- ));- }- }// No cached info yet (ensure_stream failed to prime) — allow// through; the monitor task will fill the cache shortly.- Ok(())+ let Some(info) = self.stream_info_cache.get(pool) else {+ return Ok(());+ };+ pool_backpressure_error(&info, self.max_stream_pending).map_or(Ok(()), Err)+ }++ /// Evaluate this publish against its lane's own in-flight ceiling, on top+ /// of the pool-wide [`Self::check_backpressure`].+ fn check_lane_backpressure(+ &self,+ lane: &LaneKey,+ items: u64,+ ) -> Result<Option<LaneReservation>, String> {+ check_lane_backpressure(&self.lane_admission, lane, items)}/// Clear cached stream state on NATS reconnect.@@ -2547,6 +2946,16 @@ impl WorkPublisher {// Check backpressure (lock-free read from background-updated cache)self.check_backpressure(&pool)?;+ let total_items = if endpoint == "score" || endpoint == "generate" {+ 1+ } else {+ items.len() as u32+ };+ // Then the lane this request actually lands on. The reservation lives+ // in the result collector below; if any of the early returns between+ // here and that insert fires, dropping it releases the lane.+ let lane_reservation =+ self.check_lane_backpressure(&target.lane(), u64::from(total_items))?;// UUIDv7 keeps the leading 48 bits as a big-endian Unix// millisecond timestamp, so lexicographic / B-tree-indexed@@ -2555,11 +2964,6 @@ impl WorkPublisher {// extra fields. v4 gave us uniqueness but nothing else.let request_id = uuid::Uuid::now_v7().to_string();let reply_subject = format!("_INBOX.{}.{}", self.router_id, request_id);- let total_items = if endpoint == "score" || endpoint == "generate" {- 1- } else {- items.len() as u32- };let subject = target.subject();let (pool_fallback_subject, direct_fallback_worker_id) = match (&target, endpoint) {@@ -2599,6 +3003,7 @@ impl WorkPublisher {direct_fallback_republished_indices: BTreeSet::new(),direct_fallback_payloads: vec![None; total_items as usize],direct_fallback_republished: false,+ _lane_reservation: lane_reservation,},);let mut publish_guard = PendingPublishGuard::new(Arc::clone(self), request_id.clone());@@ -2972,22 +3377,34 @@ impl WorkPublisher {// mid-`put` may still have landed the blob, so it must stay eligible// for cleanup.record_offloaded_payload_key(&self.offloaded_payload_keys, shared.request_id, &ref_key);- if let Err(e) = self.payload_store.put(&ref_key, &score_payload).await {- telemetry::record_queue_event(QueueEvent::PayloadOffload, QueueEventOutcome::Error);- warn!(error = %e, "failed to offload score payload, sending inline");- } else {- telemetry::record_queue_event(- QueueEvent::PayloadOffload,- QueueEventOutcome::Success,- );- let offloaded = WorkItemRef {- query_item: None,- query_payload_ref: Some(&ref_key),- score_items: None,- ..ref_item- };- encoded = rmp_serde::to_vec_named(&offloaded)- .map_err(|e| format!("msgpack encode offloaded score: {}", e))?;+ match put_payload_for_plain_queue_key(+ self.payload_store.as_ref(),+ &ref_key,+ &score_payload,+ )+ .await+ {+ Err(e) => {+ telemetry::record_queue_event(+ QueueEvent::PayloadOffload,+ QueueEventOutcome::Error,+ );+ warn!(error = %e, "failed to offload score payload, sending inline");+ }+ Ok(queue_key) => {+ telemetry::record_queue_event(+ QueueEvent::PayloadOffload,+ QueueEventOutcome::Success,+ );+ let offloaded = WorkItemRef {+ query_item: None,+ query_payload_ref: Some(&queue_key),+ score_items: None,+ ..ref_item+ };+ encoded = rmp_serde::to_vec_named(&offloaded)+ .map_err(|e| format!("msgpack encode offloaded score: {}", e))?;+ }}}@@ -3080,6 +3497,9 @@ impl WorkPublisher {// the batch path. The stream collector replaces ResultCollector.self.ensure_stream(&pool).await?;self.check_backpressure(&pool)?;+ // One streamed generation is one queued work item, so it reserves one+ // in-flight unit on its lane.+ let lane_reservation = self.check_lane_backpressure(&target.lane(), 1)?;if params.generate.is_none() {return Err("generate request missing 'prompt' / 'max_new_tokens'".to_string());@@ -3102,6 +3522,7 @@ impl WorkPublisher {// ``:no-spec`` dispatch variant (#1324).collector.display_model = display_model.to_string();collector.pool_fallback_subject = Some(pool_fallback_subject.clone());+ collector.lane_reservation = lane_reservation;// Capture the activity handle before the collector moves into// ``pending_streams`` so the caller never has to re-look it up// (eliminates the .expect() race window where an error path@@ -3224,6 +3645,9 @@ impl WorkPublisher {let machine_profile = target.machine_profile().to_string();self.ensure_stream(&pool).await?;self.check_backpressure(&pool)?;+ // One streamed generation is one queued work item, so it reserves one+ // in-flight unit on its lane.+ let lane_reservation = self.check_lane_backpressure(&target.lane(), 1)?;if params.generate.is_none() {return Err("generate request missing 'prompt' / 'max_new_tokens'".to_string());@@ -3247,6 +3671,7 @@ impl WorkPublisher {// ``:no-spec`` dispatch variant (#1324).collector.display_model = display_model.to_string();collector.pool_fallback_subject = Some(pool_fallback_subject.clone());+ collector.lane_reservation = lane_reservation;let chunk_rx = collector.install_chunk_tap();self.pending_streams.insert(request_id.clone(), collector);@@ -3561,19 +3986,31 @@ impl WorkPublisher {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 {- telemetry::record_queue_event(QueueEvent::PayloadOffload, QueueEventOutcome::Error);- warn!(error = %e, "failed to offload generate payload, sending inline");- } else {- telemetry::record_queue_event(- QueueEvent::PayloadOffload,- QueueEventOutcome::Success,- );- 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());+ match put_payload_for_plain_queue_key(+ self.payload_store.as_ref(),+ &offload_key,+ &gen_blob,+ )+ .await+ {+ Err(e) => {+ telemetry::record_queue_event(+ QueueEvent::PayloadOffload,+ QueueEventOutcome::Error,+ );+ warn!(error = %e, "failed to offload generate payload, sending inline");+ }+ Ok(queue_key) => {+ telemetry::record_queue_event(+ QueueEvent::PayloadOffload,+ QueueEventOutcome::Success,+ );+ ref_item.generate = None;+ ref_item.payload_ref = Some(&queue_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());+ }}}@@ -3847,18 +4284,30 @@ impl WorkPublisher {shared.request_id,&offload_key,);- if let Err(e) = self.payload_store.put(&offload_key, &item_msgpack).await {- telemetry::record_queue_event(QueueEvent::PayloadOffload, QueueEventOutcome::Error);- warn!(error = %e, "failed to offload payload, sending inline");- } else {- telemetry::record_queue_event(- QueueEvent::PayloadOffload,- QueueEventOutcome::Success,- );- ref_item.item = None;- ref_item.payload_ref = Some(&offload_key);- encoded = rmp_serde::to_vec_named(&ref_item)- .map_err(|e| format!("msgpack encode offloaded: {}", e))?;+ match put_payload_for_plain_queue_key(+ self.payload_store.as_ref(),+ &offload_key,+ &item_msgpack,+ )+ .await+ {+ Err(e) => {+ telemetry::record_queue_event(+ QueueEvent::PayloadOffload,+ QueueEventOutcome::Error,+ );+ warn!(error = %e, "failed to offload payload, sending inline");+ }+ Ok(queue_key) => {+ telemetry::record_queue_event(+ QueueEvent::PayloadOffload,+ QueueEventOutcome::Success,+ );+ ref_item.item = None;+ ref_item.payload_ref = Some(&queue_key);+ encoded = rmp_serde::to_vec_named(&ref_item)+ .map_err(|e| format!("msgpack encode offloaded: {}", e))?;+ }}}@@ -4039,8 +4488,105 @@ impl WorkPublisher {let _ = sender.send(results);}+ self.defer_cleanup(CleanupWork::Payloads(request_id.clone()))+ .await;+ }+ }+ }++ /// The keyed pool that runs inbox handlers off the decode task.+ ///+ /// The handler holds a `Weak` so the pool tasks never keep the publisher+ /// alive on their own, and a dropped publisher makes them no-ops.+ async fn inbox_pool(self: &Arc<Self>) -> &KeyedWorkerPool<InboxWork> {+ self.inbox_pool+ .get_or_init(|| async {+ let publisher = Arc::downgrade(self);+ KeyedWorkerPool::new(+ INBOX_POOL_NAME,+ INBOX_POOL_SHARDS,+ INBOX_POOL_DEPTH,+ move |work: InboxWork| {+ let publisher = publisher.clone();+ async move {+ let Some(publisher) = publisher.upgrade() else {+ return;+ };+ publisher.apply_inbox_work(work).await;+ }+ },+ )+ })+ .await+ }++ /// The keyed pool that runs object-store cleanup off every hot path.+ async fn cleanup_pool(self: &Arc<Self>) -> &KeyedWorkerPool<CleanupWork> {+ self.cleanup_pool+ .get_or_init(|| async {+ let publisher = Arc::downgrade(self);+ KeyedWorkerPool::new(+ CLEANUP_POOL_NAME,+ CLEANUP_POOL_SHARDS,+ CLEANUP_POOL_DEPTH,+ move |work: CleanupWork| {+ let publisher = publisher.clone();+ async move {+ let Some(publisher) = publisher.upgrade() else {+ return;+ };+ publisher.run_cleanup(work).await;+ }+ },+ )+ })+ .await+ }++ /// Run one decoded inbox message's handler. Called only from an inbox+ /// worker task, never from the decode task.+ async fn apply_inbox_work(&self, work: InboxWork) {+ match work {+ InboxWork::ResultChunk(chunk) => self.handle_result_chunk(*chunk).await,+ InboxWork::ResultChunkDecodeFailure { request_id } => {+ self.fail_result_chunk_request(&request_id).await;+ }+ InboxWork::Chunk(chunk) => self.handle_chunk(*chunk).await,+ InboxWork::Nak(nak) => self.handle_nak(*nak).await,+ InboxWork::Result(result) => self.handle_result(*result).await,+ }+ }++ /// Queue object-store cleanup for a finished request instead of awaiting+ /// it here.+ ///+ /// Cleanup is an object-store round trip. Awaiting it on a hot path — for+ /// the completion funnels below, historically the single inbox decode task+ /// — stalls every other in-flight request in the process, which is the+ /// defect this exists to remove.+ ///+ /// **At the bound this sheds rather than blocks.** Both cleanups are+ /// already best-effort with an independent backstop: `cleanup_expired`+ /// reconciles `offloaded_payload_keys` and `offloaded_streams` against the+ /// in-flight maps every 10s and retries whatever is orphaned. So a shed+ /// enqueue costs at most one reconcile interval of object-store residency+ /// and nothing else, whereas blocking would put the stall back on the+ /// caller. This is the opposite policy from the inbox pool, where nothing+ /// may be dropped.+ async fn defer_cleanup(&self, work: CleanupWork) {+ if let Some(work) = queue_cleanup(self.cleanup_pool.get(), work) {+ self.run_cleanup(work).await;+ }+ }++ async fn run_cleanup(&self, work: CleanupWork) {+ match work {+ CleanupWork::Payloads(request_id) => {self.cleanup_offloaded_payloads(&request_id).await;}+ CleanupWork::Generate(request_id) => {+ self.cleanup_offloaded_generate(&request_id).await;+ }}}@@ -4058,6 +4604,12 @@ impl WorkPublisher {*slot = Some(client.clone());}+ // Bring both worker pools up before the first message can arrive.+ // They are `OnceCell`s, so a reconnect re-subscribe reuses the running+ // pools instead of abandoning whatever they still have queued.+ self.inbox_pool().await;+ self.cleanup_pool().await;+let inbox_subject = format!("_INBOX.{}.>", self.router_id);let subscriber = client@@ -4082,77 +4634,38 @@ impl WorkPublisher {Ok(())}- async fn handle_inbox(&self, mut subscriber: async_nats::Subscriber) {+ /// The single inbox decode task.+ ///+ /// It now only decodes (exactly once per message, in+ /// [`inbox_work_for_payload`]) and hands the typed result to the keyed+ /// worker pool. Handlers no longer run here, so one slow handler cannot+ /// hold up decode for every other in-flight request in the process.+ async fn handle_inbox(self: &Arc<Self>, mut subscriber: async_nats::Subscriber) {+ let pool = self.inbox_pool().await;while let Some(msg) = subscriber.next().await {- // Fast-path: extract request_id without full deserialization.- // DashMap contains_key is lock-free.- let request_id_hint = extract_request_id_fast(&msg.payload);- if let Some(request_id) = request_id_hint {- if !self.pending_results.contains_key(request_id)- && !self.pending_streams.contains_key(request_id)- {- debug!(- request_id = %request_id,- "fast-path skip: result for unknown request"- );- continue;- }- }-- // Decode the msgpack payload exactly once into an- // `rmpv::Value`, peek the `kind` discriminator on the decoded- // value, then convert the *same* value into the typed- // envelope via `rmpv::ext::from_value` — no second decode- // from the raw slice. The previous code re-decoded the- // payload up to three times per chunk (`is_chunk_envelope`- // peek + `is_nak_envelope` peek + the typed `from_slice`),- // which is the hot path for streaming generation.- let value: rmpv::Value = match rmp_serde::from_slice(&msg.payload) {- Ok(v) => v,- Err(e) => {- warn!(error = %e, "failed to decode inbox payload");- continue;- }+ // DashMap contains_key is lock-free; this is the fast-path skip+ // that keeps unknown-request traffic from ever being decoded.+ let Some(work) = inbox_work_for_payload(&msg.payload, |request_id| {+ self.pending_results.contains_key(request_id)+ || self.pending_streams.contains_key(request_id)+ }) else {+ continue;};- // Only the exact v1 discriminator enters the v1 decoder. This- // fails malformed exact-v1 envelopes closed while preserving- // forward compatibility for ordinary/future WorkResult fields- // such as `total_bytes`.- match envelope_kind(&value) {- Some(RESULT_CHUNK_KIND) => match rmpv::ext::from_value::<ResultChunkV1>(value) {- Ok(chunk) => self.handle_result_chunk(chunk).await,- Err(e) => {- telemetry::record_queue_result_chunk_received(None);- telemetry::record_queue_result_chunk_rejection(- telemetry::QueueResultChunkRejectionReason::Decode,- );- warn!(error = %e, "failed to decode result chunk envelope");- if let Some(request_id) = request_id_hint {- self.fail_result_chunk_request(request_id).await;- }- }- },- // Chunk envelopes feed the streaming aggregator.- Some("chunk") => match rmpv::ext::from_value::<ChunkEnvelope>(value) {- Ok(chunk) => self.handle_chunk(chunk).await,- Err(e) => warn!(error = %e, "failed to decode chunk envelope"),- },- // Worker-emitted NAK. The publisher republishes the- // cached work item to the pool subject; if the republish- // fails we surface a transport-style terminal outcome to- // the HTTP handler.- Some("nak") => match rmpv::ext::from_value::<NakEnvelope>(value) {- Ok(nak) => self.handle_nak(nak).await,- Err(e) => warn!(error = %e, "failed to decode nak envelope"),- },- // Anything else (encode/score/extract WorkResults — an- // array-shaped payload, or a map with an unknown/absent- // `kind`) flows to the ResultCollector path.- _ => match rmpv::ext::from_value::<WorkResult>(value) {- Ok(result) => self.handle_result(result).await,- Err(e) => warn!(error = %e, "failed to decode inbox result"),- },+ // Bounded hand-off keyed by request id: all of one request's+ // messages take the same shard and stay in arrival order, while+ // different requests run concurrently.+ //+ // At the bound this blocks rather than sheds. A dropped message+ // here would be a lost result (request times out) or a lost chunk+ // (`StreamCollector::apply` sees a `seq` gap and fails the stream+ // with `transport_failure`) — a throughput fix must not buy+ // itself a new failure mode. Blocking is also never worse than+ // the behaviour this replaces, where *every* message was handled+ // inline on this task.+ if !pool.dispatch(work).await {+ warn!("inbox worker pool unavailable — ending inbox loop");+ break;}}@@ -4414,8 +4927,12 @@ impl WorkPublisher {}}// Stream finished — drop any offloaded generate blob now- // (the periodic reconcile is only the failure-path backstop).- self.cleanup_offloaded_generate(&request_id).await;+ // (the periodic reconcile is only the failure-path+ // backstop). Queued, not awaited: this funnel runs on an+ // inbox worker, and an object-store round trip here would+ // hold up every other request sharing that shard.+ self.defer_cleanup(CleanupWork::Generate(request_id.clone()))+ .await;}}ChunkApplied::SeqGap => {@@ -4640,6 +5157,18 @@ fn record_offloaded_payload_key(.insert(key.to_string());}+/// Persist one payload while preserving the queue's plain-key wire contract.+/// Cloud stores return a canonical full URL for operator visibility, but the+/// publisher must queue the same safe key that cleanup later deletes.+async fn put_payload_for_plain_queue_key(+ payload_store: &dyn PayloadStore,+ key: &str,+ payload: &[u8],+) -> Result<String, String> {+ let _canonical_reference = payload_store.put(key, payload).await?;+ Ok(key.to_owned())+}+/// Delete the object-store blobs an offloaded request wrote or attempted. No-op/// when the request offloaded nothing. Successful deletes are dropped from/// tracking; failed deletes are retained so the periodic reconcile can retry.@@ -4715,45 +5244,221 @@ pub fn encode_response(mod tests {use super::*;- #[test]- fn unit_counts_decodes_legacy_positional_array_without_field_shift() {- let legacy = rmp_serde::to_vec(&(Some(11_u64), Some(2_u64), Some(3_u64), Some(4_000_u64)))- .expect("legacy positional units");- let decoded: UnitCounts = rmp_serde::from_slice(&legacy).expect("additive decode");+ /// Two lanes on one pool, differing only in machine profile. The pool-wide+ /// check cannot tell them apart — the whole point of B5's first half.+ fn hot_lane() -> LaneKey {+ LaneKey::new("shared", "h100", "default")+ }- assert_eq!(decoded.input_tokens, Some(11));- assert_eq!(decoded.pages, Some(2));- assert_eq!(decoded.images, Some(3));- assert_eq!(decoded.audio_ms, Some(4_000));- assert_eq!(decoded.pairs, None);- assert_eq!(decoded.gpu_second, None);- assert_eq!(decoded.output_tokens, None);+ fn cold_lane() -> LaneKey {+ LaneKey::new("shared", "a10g", "default")}- /// `output_tokens` (#2432) is additive: a worker that already stamps- /// `pairs` and `gpu_second` positionally must keep decoding without a- /// field shift, and the new dimension must read as absent — never as a- /// fabricated zero the settle path would bill.+ fn lane_control(enforce: bool) -> LaneAdmissionControl {+ LaneAdmissionControl::new(+ 10,+ enforce,+ crate::state::demand_tracker::PhysicalLaneCatalog::default(),+ )+ }++ /// Fill `lane` past its ceiling and hold the reservations.+ fn saturate(control: &LaneAdmissionControl, lane: &LaneKey) -> Option<LaneReservation> {+ check_lane_backpressure(control, lane, 11).expect("first publish is admitted")+ }++ /// Enforced: the deep lane sheds and a cold lane on the SAME pool still+ /// admits.+ ///+ /// Reverting to pool-granular backpressure makes this fail: a pool-wide+ /// gate reads one `num_pending` for the whole `WORK_POOL_shared` stream,+ /// so it either admits both lanes or sheds both. There is no pool-wide+ /// arrangement of inputs under which one of these two assertions holds+ /// and the other does not.#[test]- fn unit_counts_output_tokens_is_wire_additive() {- let legacy = rmp_serde::to_vec(&(- Some(11_u64),- Some(2_u64),- Some(3_u64),- Some(4_000_u64),- Some(5_u64),- Some(6_u64),- ))- .expect("legacy positional units through gpu_second");- let decoded: UnitCounts = rmp_serde::from_slice(&legacy).expect("additive decode");+ fn a_saturated_lane_sheds_only_that_lane() {+ let control = lane_control(true);+ let _held = saturate(&control, &hot_lane());- assert_eq!(decoded.input_tokens, Some(11));- assert_eq!(decoded.pages, Some(2));- assert_eq!(decoded.images, Some(3));- assert_eq!(decoded.audio_ms, Some(4_000));- assert_eq!(decoded.pairs, Some(5));- assert_eq!(decoded.gpu_second, Some(6));- assert_eq!(decoded.output_tokens, None);+ let hot = check_lane_backpressure(&control, &hot_lane(), 1);+ let cold = check_lane_backpressure(&control, &cold_lane(), 1);++ assert!(hot.is_err(), "the saturated lane must shed");+ assert!(+ cold.is_ok(),+ "a cold lane on the same pool must still admit"+ );+ }++ /// Shadow mode records the decision and changes nothing about admission.+ #[test]+ fn shadow_mode_records_the_decision_without_changing_admission() {+ let shadow = lane_control(false);+ let _held = saturate(&shadow, &hot_lane());++ // Identical lane state to `a_saturated_lane_sheds_only_that_lane`.+ assert!(+ check_lane_backpressure(&shadow, &hot_lane(), 1).is_ok(),+ "shadow mode must not shed"+ );+ // The decision itself is still computed, and it is a shed.+ assert_eq!(+ shadow.admit(&hot_lane(), 1).outcome,+ LaneAdmissionOutcome::ShedShadow+ );+ }++ /// Flag off reproduces today's behaviour exactly: the pool-wide check is+ /// the only gate, and it is byte-for-byte the message it always was.+ #[test]+ fn the_flag_off_leaves_pool_wide_backpressure_as_the_only_gate() {+ let shadow = lane_control(false);+ let _held = saturate(&shadow, &hot_lane());+ assert!(check_lane_backpressure(&shadow, &hot_lane(), 4_096).is_ok());++ let healthy = CachedStreamInfo {+ num_pending: 10,+ num_consumers: 1,+ };+ assert_eq!(pool_backpressure_error(&healthy, 50_000), None);++ let saturated_pool = CachedStreamInfo {+ num_pending: 50_001,+ num_consumers: 1,+ };+ assert_eq!(+ pool_backpressure_error(&saturated_pool, 50_000).as_deref(),+ Some("backpressure: 50001 pending messages exceeds threshold 50000")+ );++ let no_consumers = CachedStreamInfo {+ num_pending: 0,+ num_consumers: 0,+ };+ assert_eq!(+ pool_backpressure_error(&no_consumers, 50_000).as_deref(),+ Some("no consumers available for work stream")+ );+ }++ /// The pool-wide gate is unchanged and still applies with enforcement on:+ /// per-lane admission is added in front of it, not substituted for it.+ #[test]+ fn the_pool_wide_gate_survives_enforcement() {+ let control = lane_control(true);+ assert!(check_lane_backpressure(&control, &cold_lane(), 1).is_ok());++ let saturated_pool = CachedStreamInfo {+ num_pending: 50_001,+ num_consumers: 1,+ };+ assert!(pool_backpressure_error(&saturated_pool, 50_000).is_some());+ }++ /// An enforced lane shed must classify exactly like a pool-wide shed, so+ /// it reaches the client as the same 503 + `Retry-After` and records+ /// pending demand for the saturated lane (`record_publish_failure`).+ #[test]+ fn an_enforced_lane_shed_classifies_as_backpressure() {+ let control = lane_control(true);+ let _held = saturate(&control, &hot_lane());+ let error = check_lane_backpressure(&control, &hot_lane(), 1).expect_err("shed");++ assert_eq!(+ QueuePublishOutcome::from_error(&error),+ QueuePublishOutcome::Backpressure+ );+ assert!(error.to_ascii_lowercase().contains("backpressure"));+ assert!(+ error.contains("work lane saturated"),+ "a lane shed must read differently from a pool-wide shed: {error}"+ );+ // The message reaches the client. Pool names are operator-defined and+ // may encode tenant context, so lane identity stays in the log and the+ // decision metric.+ for token in ["shared", "h100", "default"] {+ assert!(+ !error.contains(token),+ "lane identity must not reach the client body: {error}"+ );+ }+ }++ /// Releasing a request's reservation reopens its lane, and only its lane.+ #[test]+ fn releasing_a_request_reopens_its_own_lane() {+ let control = lane_control(true);+ {+ let _held = saturate(&control, &hot_lane());+ assert!(check_lane_backpressure(&control, &hot_lane(), 1).is_err());+ }+ assert_eq!(control.in_flight(&hot_lane()), 0);+ assert!(check_lane_backpressure(&control, &hot_lane(), 1).is_ok());+ }++ /// A worker-direct target and its pool fallback are the same lane, so+ /// direct dispatch is accounted too — the blind spot `check_backpressure`+ /// documents for the pool-wide count.+ #[test]+ fn worker_direct_and_pool_targets_share_one_lane() {+ let direct = PublishTarget::Worker {+ pool: "shared".to_string(),+ machine_profile: "h100".to_string(),+ bundle: "default".to_string(),+ model: "BAAI/bge-m3".to_string(),+ worker_id: "worker-1".to_string(),+ };+ let fanout = PublishTarget::Pool {+ pool: "shared".to_string(),+ machine_profile: "h100".to_string(),+ bundle: "default".to_string(),+ // A different model on the same lane shares the accounting: the+ // lane is the physical worker set, not the model.+ model: "intfloat/e5-base-v2".to_string(),+ };+ assert_eq!(direct.lane(), fanout.lane());+ assert_eq!(direct.lane(), hot_lane());+ }++ #[test]+ fn unit_counts_decodes_legacy_positional_array_without_field_shift() {+ let legacy = rmp_serde::to_vec(&(Some(11_u64), Some(2_u64), Some(3_u64), Some(4_000_u64)))+ .expect("legacy positional units");+ let decoded: UnitCounts = rmp_serde::from_slice(&legacy).expect("additive decode");++ assert_eq!(decoded.input_tokens, Some(11));+ assert_eq!(decoded.pages, Some(2));+ assert_eq!(decoded.images, Some(3));+ assert_eq!(decoded.audio_ms, Some(4_000));+ assert_eq!(decoded.pairs, None);+ assert_eq!(decoded.gpu_second, None);+ assert_eq!(decoded.output_tokens, None);+ }++ /// `output_tokens` (#2432) is additive: a worker that already stamps+ /// `pairs` and `gpu_second` positionally must keep decoding without a+ /// field shift, and the new dimension must read as absent — never as a+ /// fabricated zero the settle path would bill.+ #[test]+ fn unit_counts_output_tokens_is_wire_additive() {+ let legacy = rmp_serde::to_vec(&(+ Some(11_u64),+ Some(2_u64),+ Some(3_u64),+ Some(4_000_u64),+ Some(5_u64),+ Some(6_u64),+ ))+ .expect("legacy positional units through gpu_second");+ let decoded: UnitCounts = rmp_serde::from_slice(&legacy).expect("additive decode");++ assert_eq!(decoded.input_tokens, Some(11));+ assert_eq!(decoded.pages, Some(2));+ assert_eq!(decoded.images, Some(3));+ assert_eq!(decoded.audio_ms, Some(4_000));+ assert_eq!(decoded.pairs, Some(5));+ assert_eq!(decoded.gpu_second, Some(6));+ assert_eq!(decoded.output_tokens, None);}#[test]@@ -4809,6 +5514,55 @@ mod tests {}}+ struct FullReferencePayloadStore {+ full_reference: String,+ puts: std::sync::Mutex<Vec<(String, usize)>>,+ deleted: std::sync::Mutex<Vec<String>>,+ }++ #[async_trait]+ impl PayloadStore for FullReferencePayloadStore {+ async fn put(&self, key: &str, data: &[u8]) -> Result<String, String> {+ self.puts.lock().unwrap().push((key.to_owned(), data.len()));+ Ok(self.full_reference.clone())+ }++ async fn delete(&self, key: &str) -> Result<(), String> {+ self.deleted.lock().unwrap().push(key.to_owned());+ Ok(())+ }+ }++ #[tokio::test]+ async fn large_oss_payload_queues_plain_key_and_cleans_exact_key() {+ let fixture: serde_json::Value = serde_json::from_str(include_str!(+ "../../../wire-fixtures/oss_payload_store.json"+ ))+ .unwrap();+ let key = fixture["plain_key"].as_str().unwrap();+ let store = FullReferencePayloadStore {+ full_reference: fixture["full_reference"].as_str().unwrap().to_owned(),+ puts: std::sync::Mutex::new(Vec::new()),+ deleted: std::sync::Mutex::new(Vec::new()),+ };+ let payload = vec![0; PAYLOAD_OFFLOAD_THRESHOLD + 1];+ let offloaded: DashMap<String, BTreeSet<String>> = DashMap::new();+ record_offloaded_payload_key(&offloaded, "request_00000000", key);++ let queued_ref = put_payload_for_plain_queue_key(&store, key, &payload)+ .await+ .unwrap();+ assert_eq!(queued_ref, key, "the queue must retain the safe plain key");+ assert_eq!(+ store.puts.lock().unwrap().as_slice(),+ &[(key.to_owned(), PAYLOAD_OFFLOAD_THRESHOLD + 1)]+ );++ cleanup_offloaded_payloads_inner(&store, &offloaded, "request_00000000").await;+ assert_eq!(store.deleted.lock().unwrap().as_slice(), &[key.to_owned()]);+ assert!(!offloaded.contains_key("request_00000000"));+ }+// Common case (issue #1471): a small/inline request that never offloaded a// payload must issue zero object-store DELETEs. The unconditional// per-request DELETE storm is exactly what capped throughput.@@ -5016,6 +5770,278 @@ mod tests {);}+ // --- B4: payload cleanup must not run on the caller's task ---++ /// A payload store whose `delete` never returns, standing in for a slow+ /// object-store round trip.+ struct HangingDeleteStore {+ attempted: Arc<std::sync::Mutex<Vec<String>>>,+ }++ #[async_trait]+ impl PayloadStore for HangingDeleteStore {+ async fn put(&self, _key: &str, _data: &[u8]) -> Result<String, String> {+ Ok(String::new())+ }++ async fn delete(&self, key: &str) -> Result<(), String> {+ self.attempted.lock().unwrap().push(key.to_string());+ std::future::pending::<()>().await;+ Ok(())+ }+ }++ fn hanging_cleanup_pool(+ attempted: Arc<std::sync::Mutex<Vec<String>>>,+ shards: usize,+ depth: usize,+ ) -> KeyedWorkerPool<CleanupWork> {+ let offloaded: Arc<DashMap<String, BTreeSet<String>>> = Arc::new(DashMap::new());+ KeyedWorkerPool::new("test-cleanup", shards, depth, move |work: CleanupWork| {+ let store = HangingDeleteStore {+ attempted: Arc::clone(&attempted),+ };+ let offloaded = Arc::clone(&offloaded);+ async move {+ let CleanupWork::Payloads(request_id) = work else {+ return;+ };+ record_offloaded_payload_key(+ &offloaded,+ &request_id,+ &format!("{request_id}_0.bin"),+ );+ cleanup_offloaded_payloads_inner(&store, &offloaded, &request_id).await;+ }+ })+ }++ /// The second half of B4: completing a request used to await an+ /// object-store delete on the inbox decode task, stalling decode for every+ /// other in-flight request. Handing the cleanup to the pool must return+ /// immediately even while the delete is wedged.+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn queue_cleanup_does_not_await_the_object_store_delete() {+ let attempted = Arc::new(std::sync::Mutex::new(Vec::new()));+ let pool = hanging_cleanup_pool(Arc::clone(&attempted), 1, 4);++ // A hung delete must not be observable by the caller at all: this+ // returns without ever awaiting the store.+ assert!(+ queue_cleanup(Some(&pool), CleanupWork::Payloads("req-hang".to_string())).is_none(),+ "a live cleanup pool takes ownership of the work"+ );++ // The delete really is in flight on the pool, not on this task.+ let deadline = Instant::now() + Duration::from_secs(5);+ while attempted.lock().unwrap().is_empty() {+ assert!(Instant::now() < deadline, "cleanup never reached the store");+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ assert_eq!(+ attempted.lock().unwrap().clone(),+ vec!["req-hang_0.bin".to_string()],+ "the queued cleanup must be the one that ran"+ );+ }++ /// Without a pool (a publisher that never started an inbox subscription)+ /// the work comes back so the caller still runs it inline. Cleanup is+ /// never silently skipped.+ #[tokio::test]+ async fn queue_cleanup_returns_work_when_there_is_no_pool() {+ let work = queue_cleanup(None, CleanupWork::Generate("req-inline".to_string()));+ assert!(+ matches!(work, Some(CleanupWork::Generate(id)) if id == "req-inline"),+ "no pool must hand the work back for inline execution"+ );+ }++ /// At the bound the cleanup pool sheds rather than blocking, because the+ /// periodic `cleanup_expired` reconcile is an independent retry path for+ /// exactly these keys.+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn queue_cleanup_sheds_at_the_bound_and_the_reconcile_still_deletes() {+ let attempted = Arc::new(std::sync::Mutex::new(Vec::new()));+ // One shard, depth one, and every delete hangs: one item is taken by+ // the worker, one fills the queue, everything after that is shed.+ let pool = hanging_cleanup_pool(Arc::clone(&attempted), 1, 1);+ assert!(queue_cleanup(Some(&pool), CleanupWork::Payloads("a".to_string())).is_none());+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert!(queue_cleanup(Some(&pool), CleanupWork::Payloads("b".to_string())).is_none());++ // Shed: taken off the caller's hands, but never enqueued. The caller+ // still does not block.+ let shed_started = Instant::now();+ assert!(queue_cleanup(Some(&pool), CleanupWork::Payloads("c".to_string())).is_none());+ assert!(+ shed_started.elapsed() < Duration::from_millis(500),+ "shedding must not block the caller"+ );+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert_eq!(+ attempted.lock().unwrap().clone(),+ vec!["a_0.bin".to_string()],+ "the shed request must not have reached the store"+ );++ // The backstop: the shed request's keys are still tracked, and the+ // reconcile path deletes them on its next sweep.+ let offloaded: DashMap<String, BTreeSet<String>> = DashMap::new();+ record_offloaded_payload_key(&offloaded, "c", "c_0.bin");+ let orphaned = collect_orphaned_offloaded_payload_requests(&offloaded, |_request_id| false);+ assert_eq!(+ orphaned,+ vec!["c".to_string()],+ "a shed cleanup must still be discoverable by the periodic reconcile"+ );+ let store = CountingPayloadStore::default();+ cleanup_offloaded_payloads_inner(&store, &offloaded, "c").await;+ assert_eq!(+ store.deleted.lock().unwrap().clone(),+ vec!["c_0.bin".to_string()],+ "the reconcile must delete what the bound shed"+ );+ }++ /// Live end-to-end proof of both B4 moves against the real inbox loop.+ ///+ /// One request completes with an object-store delete that never returns.+ /// Before this change that delete was awaited on the single decode task,+ /// so every other in-flight request in the process stopped: the second+ /// request's chunks would never be handled and its outcome would never+ /// arrive. Now the cleanup is queued and decode keeps running, so the+ /// second request completes — with its chunks in order.+ ///+ /// NATS-gated like the other live tests here: a no-op pass when+ /// `NATS_URL` is unset so the hermetic run stays green.+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]+ async fn inbox_decode_survives_a_wedged_cleanup_and_keeps_stream_order() {+ let Ok(url) = std::env::var("NATS_URL") else {+ eprintln!("skipping: NATS_URL not set");+ return;+ };+ let client =+ match tokio::time::timeout(Duration::from_secs(2), async_nats::connect(&url)).await {+ Ok(Ok(c)) => c,+ _ => {+ eprintln!("skipping: could not connect to NATS at {url}");+ return;+ }+ };+ let context = async_nats::jetstream::new(client.clone());+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ let router_id = format!("b4router{nanos}");++ let attempted = Arc::new(std::sync::Mutex::new(Vec::new()));+ let publisher = Arc::new(WorkPublisher::new(+ context,+ router_id.clone(),+ Arc::new(HangingDeleteStore {+ attempted: Arc::clone(&attempted),+ }),+ Duration::from_secs(30),+ 1024,+ WorkStreamConfig {+ max_age: Duration::from_secs(300),+ storage: jetstream::stream::StorageType::Memory,+ num_replicas: 1,+ },+ ));+ publisher+ .start_inbox_subscription(&client)+ .await+ .expect("start inbox subscription");++ // `wedged` completes first and its cleanup delete never returns.+ //+ // Both requests are deliberately placed on the SAME inbox shard, so+ // the live request is strictly serialized behind the wedged request's+ // handler. Sharding alone therefore cannot rescue it: it completes+ // only because that handler declines to await the object-store+ // delete. This is the assertion the cleanup move owns.+ let wedged = format!("wedged-{nanos}");+ let shard = crate::queue::keyed_worker_pool::shard_index(&wedged, INBOX_POOL_SHARDS);+ let live = (0..1_000)+ .map(|n| format!("live-{nanos}-{n}"))+ .find(|id| crate::queue::keyed_worker_pool::shard_index(id, INBOX_POOL_SHARDS) == shard)+ .expect("a live request id sharing the wedged request's shard");+ let (wedged_tx, _wedged_rx) = oneshot::channel();+ publisher.pending_streams.insert(+ wedged.clone(),+ StreamCollector::new(wedged_tx, "m".to_string(), "default".to_string()),+ );+ publisher.offloaded_streams.insert(wedged.clone());++ // `live` must still complete, in order, behind it.+ let (live_tx, live_rx) = oneshot::channel();+ publisher.pending_streams.insert(+ live.clone(),+ StreamCollector::new(live_tx, "m".to_string(), "default".to_string()),+ );++ let subject = format!("_INBOX.{router_id}.reply");+ let terminal = |request_id: &str, seq: u32| {+ rmp_serde::to_vec_named(&WireChunk {+ kind: "chunk",+ request_id,+ seq,+ text_delta: "",+ done: true,+ })+ .expect("encode terminal")+ };++ // Wedge the cleanup path first.+ client+ .publish(subject.clone(), terminal(&wedged, 0).into())+ .await+ .expect("publish wedged terminal");++ // Then a long interleaved stream for the live request.+ const CHUNKS: u32 = 64;+ for seq in 0..CHUNKS {+ client+ .publish(subject.clone(), wire_chunk(&live, seq).into())+ .await+ .expect("publish live chunk");+ }+ client+ .publish(subject.clone(), terminal(&live, CHUNKS).into())+ .await+ .expect("publish live terminal");+ client.flush().await.expect("flush inbox publishes");++ let outcome = tokio::time::timeout(Duration::from_secs(10), live_rx)+ .await+ .expect("a wedged cleanup must not stall decode for other requests")+ .expect("live outcome sender must not be dropped");++ // Ordering: `StreamCollector::apply` drops a chunk whose seq is not+ // greater than the watermark and fails the stream on a forward gap, so+ // any reordering shows up as short/failed text here.+ assert_eq!(+ outcome.text,+ "tok".repeat(CHUNKS as usize),+ "every chunk must be applied exactly once, in seq order"+ );+ assert!(+ outcome.error.is_none(),+ "no seq gap may be observed: {:?}",+ outcome.error+ );++ // And the wedged cleanup really did start — off the decode task.+ assert_eq!(+ attempted.lock().unwrap().clone(),+ vec![format!("{wedged}_0.bin")],+ "the wedged request's delete must be in flight on the cleanup pool"+ );+ }+#[derive(Debug, Clone, Serialize, Deserialize)]struct WorkItem {pub work_item_id: String,@@ -5111,6 +6137,252 @@ mod tests {);}+ /// Live JetStream reconcile test for the work-stream discard policy+ /// (architecture-review finding B3). A stream created by a pre-fix+ /// gateway carries the async-nats default `DiscardPolicy::Old`, which+ /// silently drops the oldest queued work at the `max_messages` cap;+ /// `ensure_stream` must repair it to `New` (and create fresh streams+ /// with `New`) so a full queue rejects the publish onto the loud 503+ /// path instead. NATS-gated like the other live tests here: a no-op+ /// pass when `NATS_URL` is unset so the hermetic run stays green.+ #[tokio::test]+ async fn test_ensure_stream_reconciles_discard_policy_to_new() {+ let Ok(url) = std::env::var("NATS_URL") else {+ eprintln!("skipping: NATS_URL not set");+ return;+ };+ let client =+ match tokio::time::timeout(Duration::from_secs(2), async_nats::connect(&url)).await {+ Ok(Ok(c)) => c,+ _ => {+ eprintln!("skipping: could not connect to NATS at {url}");+ return;+ }+ };+ let context = async_nats::jetstream::new(client);+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ let stream_max_age = Duration::from_secs(300);++ // Pre-create the pool stream exactly as a pre-fix gateway did:+ // no `discard` field, so the async-nats default (`Old`) sticks.+ let legacy_pool = format!("discardold{nanos}");+ let legacy_stream_name = stream_name(&legacy_pool);+ let mut legacy_stream = context+ .get_or_create_stream(jetstream::stream::Config {+ name: legacy_stream_name.clone(),+ subjects: vec![format!("sie.work.{legacy_pool}.*.*.*")],+ retention: jetstream::stream::RetentionPolicy::WorkQueue,+ storage: jetstream::stream::StorageType::Memory,+ max_age: stream_max_age,+ max_messages: 100_000,+ ..Default::default()+ })+ .await+ .expect("create legacy work stream");+ assert_eq!(+ legacy_stream+ .info()+ .await+ .expect("legacy stream info")+ .config+ .discard,+ jetstream::stream::DiscardPolicy::Old,+ "precondition: the legacy creation path must yield the Old default"+ );++ let publisher = Arc::new(WorkPublisher::new(+ context.clone(),+ "it-router".to_string(),+ Arc::new(crate::queue::payload_store::DisabledPayloadStore),+ Duration::from_secs(5),+ 1024,+ WorkStreamConfig {+ max_age: stream_max_age,+ storage: jetstream::stream::StorageType::Memory,+ num_replicas: 1,+ },+ ));+ publisher+ .ensure_stream(&legacy_pool)+ .await+ .expect("ensure_stream over the legacy stream");+ let mut reconciled = context+ .get_stream(&legacy_stream_name)+ .await+ .expect("get reconciled stream");+ assert_eq!(+ reconciled+ .info()+ .await+ .expect("reconciled stream info")+ .config+ .discard,+ jetstream::stream::DiscardPolicy::New,+ "ensure_stream must repair a pre-existing stream's discard policy to New"+ );++ // Fresh-create path: a pool with no pre-existing stream must get+ // `New` at creation time.+ let fresh_pool = format!("discardnew{nanos}");+ publisher+ .ensure_stream(&fresh_pool)+ .await+ .expect("ensure_stream fresh create");+ let mut fresh = context+ .get_stream(stream_name(&fresh_pool))+ .await+ .expect("get fresh stream");+ assert_eq!(+ fresh+ .info()+ .await+ .expect("fresh stream info")+ .config+ .discard,+ jetstream::stream::DiscardPolicy::New,+ "ensure_stream must create fresh streams with discard New"+ );++ context+ .delete_stream(&legacy_stream_name)+ .await+ .expect("delete legacy test stream");+ context+ .delete_stream(stream_name(&fresh_pool))+ .await+ .expect("delete fresh test stream");+ }++ /// Live JetStream contract test for the work-stream durability knobs+ /// (architecture-review finding B1). Pins three things:+ ///+ /// 1. `SIE_STREAM_STORAGE` / `SIE_STREAM_REPLICAS` reach the created+ /// stream, so `file` actually produces a file-backed stream.+ /// 2. NATS REJECTS an in-place storage-type change. This is the reason+ /// `ensure_stream` warns instead of reconciling storage, so the+ /// behaviour is asserted rather than assumed.+ /// 3. `num_replicas` IS reconciled on an existing stream (the one knob+ /// of the two that JetStream will change in place).+ ///+ /// NATS-gated like the other live tests here.+ #[tokio::test]+ async fn test_ensure_stream_storage_is_configurable_but_not_reconcilable() {+ let Ok(url) = std::env::var("NATS_URL") else {+ eprintln!("skipping: NATS_URL not set");+ return;+ };+ let client =+ match tokio::time::timeout(Duration::from_secs(2), async_nats::connect(&url)).await {+ Ok(Ok(c)) => c,+ _ => {+ eprintln!("skipping: could not connect to NATS at {url}");+ return;+ }+ };+ let context = async_nats::jetstream::new(client);+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ let stream_max_age = Duration::from_secs(300);++ // A file-backed publisher must create a file-backed stream.+ let file_pool = format!("storagefile{nanos}");+ let file_publisher = Arc::new(WorkPublisher::new(+ context.clone(),+ "it-router".to_string(),+ Arc::new(crate::queue::payload_store::DisabledPayloadStore),+ Duration::from_secs(5),+ 1024,+ WorkStreamConfig {+ max_age: stream_max_age,+ storage: jetstream::stream::StorageType::File,+ num_replicas: 1,+ },+ ));+ file_publisher+ .ensure_stream(&file_pool)+ .await+ .expect("ensure_stream with File storage");+ let mut file_stream = context+ .get_stream(stream_name(&file_pool))+ .await+ .expect("get file-backed stream");+ let file_config = file_stream+ .info()+ .await+ .expect("file-backed stream info")+ .config+ .clone();+ assert_eq!(+ file_config.storage,+ jetstream::stream::StorageType::File,+ "SIE_STREAM_STORAGE=file must produce a file-backed stream"+ );++ // The core finding: JetStream refuses to change storage in place.+ let mut wants_memory = file_config.clone();+ wants_memory.storage = jetstream::stream::StorageType::Memory;+ let update_err = context.update_stream(wants_memory).await.err();+ // NATS 2.12 answers this with err_code 10052,+ // "stream configuration update can not change storage type".+ assert!(+ update_err.is_some(),+ "JetStream is expected to reject an in-place storage-type change; \+ if this ever starts succeeding, ensure_stream can reconcile storage \+ instead of only warning"+ );+ eprintln!("in-place storage change rejected by NATS: {update_err:?}");++ // So a publisher configured for Memory over that same File stream+ // must NOT fail and must NOT mutate it — it warns and moves on.+ let memory_publisher = Arc::new(WorkPublisher::new(+ context.clone(),+ "it-router".to_string(),+ Arc::new(crate::queue::payload_store::DisabledPayloadStore),+ Duration::from_secs(5),+ 1024,+ WorkStreamConfig {+ max_age: stream_max_age,+ storage: jetstream::stream::StorageType::Memory,+ num_replicas: 1,+ },+ ));+ memory_publisher+ .ensure_stream(&file_pool)+ .await+ .expect("a storage mismatch must not fail ensure_stream");+ assert_eq!(+ context+ .get_stream(stream_name(&file_pool))+ .await+ .expect("re-get stream")+ .info()+ .await+ .expect("stream info after mismatch")+ .config+ .storage,+ jetstream::stream::StorageType::File,+ "ensure_stream must leave a diverging stream's storage untouched"+ );++ // Replicas, unlike storage, ARE reconciled. A single-node NATS caps+ // R at 1, so only assert the no-op direction there; the reconcile+ // path itself is exercised by the R1 -> R1 equality short-circuit.+ assert_eq!(+ file_config.num_replicas, 1,+ "default replica count must stay 1"+ );++ context+ .delete_stream(stream_name(&file_pool))+ .await+ .expect("delete file-backed test stream");+ }+fn result_collector(total_items: usize,) -> (ResultCollector, oneshot::Receiver<Vec<WorkResult>>) {@@ -5146,6 +6418,7 @@ mod tests {direct_fallback_republished_indices: BTreeSet::new(),direct_fallback_payloads: vec![None; total_items],direct_fallback_republished: false,+ _lane_reservation: None,},rx,)@@ -5815,6 +7088,7 @@ mod tests {direct_fallback_republished_indices: BTreeSet::new(),direct_fallback_payloads: vec![Some(vec![0]), Some(vec![1]), Some(vec![2])],direct_fallback_republished: false,+ _lane_reservation: None,};let (subject, worker_id, payloads) =@@ -5847,6 +7121,7 @@ mod tests {direct_fallback_republished_indices: BTreeSet::new(),direct_fallback_payloads: vec![None],direct_fallback_republished: false,+ _lane_reservation: None,};let first = WorkResult {@@ -5909,6 +7184,7 @@ mod tests {direct_fallback_republished_indices: BTreeSet::from([0]),direct_fallback_payloads: vec![Some(vec![0])],direct_fallback_republished: true,+ _lane_reservation: None,};let stale_direct = WorkResult {@@ -6491,6 +7767,182 @@ mod tests {assert_eq!(PAYLOAD_OFFLOAD_THRESHOLD, 1_048_576);}+ // --- B4: decode-side classification (`inbox_work_for_payload`) ---++ /// Minimal streaming chunk on the wire. Every other `ChunkEnvelope` field+ /// carries a serde default, so this is what a worker's smallest legal+ /// chunk decodes from.+ #[derive(Serialize)]+ struct WireChunk<'a> {+ kind: &'a str,+ request_id: &'a str,+ seq: u32,+ text_delta: &'a str,+ done: bool,+ }++ #[derive(Serialize)]+ struct WireNak<'a> {+ kind: &'a str,+ request_id: &'a str,+ reason: &'a str,+ }++ fn wire_chunk(request_id: &str, seq: u32) -> Vec<u8> {+ rmp_serde::to_vec_named(&WireChunk {+ kind: "chunk",+ request_id,+ seq,+ text_delta: "tok",+ done: false,+ })+ .expect("encode chunk")+ }++ fn wire_work_result(request_id: &str) -> Vec<u8> {+ rmp_serde::to_vec(&WorkResult {+ work_item_id: format!("{request_id}.0"),+ request_id: request_id.to_string(),+ item_index: 0,+ success: true,+ result_msgpack: vec![1, 2, 3],+ error: None,+ error_code: None,+ inference_ms: None,+ queue_ms: None,+ processing_ms: None,+ worker_id: None,+ tokenization_ms: None,+ postprocessing_ms: None,+ payload_fetch_ms: None,+ units: None,+ worker_direct: false,+ executed_bundle_config_hash: None,+ execution_identity_sha256: None,+ })+ .expect("encode work result")+ }++ /// The fast path is a mitigation this change must preserve: a result for a+ /// request this gateway no longer tracks is dropped without decoding.+ #[test]+ fn inbox_work_skips_untracked_requests_without_decoding() {+ assert!(+ inbox_work_for_payload(&wire_chunk("req-gone", 7), |_| false).is_none(),+ "an untracked request must be dropped on the fast path"+ );+ // Same payload, now tracked — it decodes.+ assert!(matches!(+ inbox_work_for_payload(&wire_chunk("req-gone", 7), |_| true),+ Some(InboxWork::Chunk(_))+ ));+ }++ #[test]+ fn inbox_work_routes_each_envelope_kind_to_its_handler() {+ let chunk = inbox_work_for_payload(&wire_chunk("req-a", 3), |_| true);+ match chunk {+ Some(InboxWork::Chunk(envelope)) => {+ assert_eq!(envelope.request_id, "req-a");+ assert_eq!(envelope.seq, 3);+ }+ other => panic!("expected a stream chunk, got {other:?}"),+ }++ let nak_payload = rmp_serde::to_vec_named(&WireNak {+ kind: "nak",+ request_id: "req-b",+ reason: "kv_budget",+ })+ .expect("encode nak");+ match inbox_work_for_payload(&nak_payload, |_| true) {+ Some(InboxWork::Nak(nak)) => {+ assert_eq!(nak.request_id, "req-b");+ assert_eq!(nak.reason, "kv_budget");+ }+ other => panic!("expected a nak, got {other:?}"),+ }++ let transfer = ResultChunkV1 {+ kind: RESULT_CHUNK_KIND.to_string(),+ work_item_id: "req-c.0".to_string(),+ request_id: "req-c".to_string(),+ item_index: 0,+ transfer_digest: vec![0u8; 32],+ chunk_index: 0,+ chunk_count: 1,+ total_bytes: 3,+ payload: vec![1, 2, 3],+ };+ let transfer_payload = rmp_serde::to_vec_named(&transfer).expect("encode result chunk");+ match inbox_work_for_payload(&transfer_payload, |_| true) {+ Some(InboxWork::ResultChunk(decoded)) => assert_eq!(*decoded, transfer),+ other => panic!("expected a result chunk transfer, got {other:?}"),+ }++ match inbox_work_for_payload(&wire_work_result("req-d"), |_| true) {+ Some(InboxWork::Result(result)) => assert_eq!(result.request_id, "req-d"),+ other => panic!("expected a WorkResult, got {other:?}"),+ }+ }++ /// A malformed exact-v1 transfer still has to fail its request, and that+ /// failure has to be ordered against the request's other inbox work — so+ /// it becomes a work item under the same key rather than running on the+ /// decode task.+ #[test]+ fn inbox_work_turns_a_malformed_transfer_into_keyed_failure_work() {+ // Right discriminator, wrong shape: `chunk_index` is a string.+ #[derive(Serialize)]+ struct BadTransfer<'a> {+ kind: &'a str,+ request_id: &'a str,+ chunk_index: &'a str,+ }+ let payload = rmp_serde::to_vec_named(&BadTransfer {+ kind: RESULT_CHUNK_KIND,+ request_id: "req-bad",+ chunk_index: "not-a-number",+ })+ .expect("encode malformed transfer");++ match inbox_work_for_payload(&payload, |_| true) {+ Some(work @ InboxWork::ResultChunkDecodeFailure { .. }) => {+ assert_eq!(+ work.shard_key(),+ "req-bad",+ "the failure must be keyed to the failing request"+ );+ }+ other => panic!("expected keyed failure work, got {other:?}"),+ }+ }++ #[test]+ fn inbox_work_drops_undecodable_payloads() {+ assert!(inbox_work_for_payload(&[0xc1], |_| true).is_none());+ }++ /// Every variant keys on its own request id, which is what puts all of one+ /// request's inbox work on a single shard.+ #[test]+ fn inbox_work_keys_on_the_request_id() {+ let cases = [+ wire_chunk("req-key", 0),+ wire_work_result("req-key"),+ rmp_serde::to_vec_named(&WireNak {+ kind: "nak",+ request_id: "req-key",+ reason: "kv_budget",+ })+ .expect("encode nak"),+ ];+ for payload in cases {+ let work = inbox_work_for_payload(&payload, |_| true).expect("decoded work");+ assert_eq!(work.shard_key(), "req-key");+ }+ }+// --- Fast-path request_id extraction tests ---#[test]@@ -7404,7 +8856,11 @@ mod tests {Arc::new(crate::queue::payload_store::DisabledPayloadStore),Duration::from_secs(5),1024,- Duration::from_secs(300),+ WorkStreamConfig {+ max_age: Duration::from_secs(300),+ storage: jetstream::stream::StorageType::Memory,+ num_replicas: 1,+ },));let target = PublishTarget::Pool {@@ -7429,6 +8885,7 @@ mod tests {storage: jetstream::stream::StorageType::Memory,max_age: Duration::from_secs(300),max_messages: 100_000,+ discard: jetstream::stream::DiscardPolicy::New,..Default::default()}).await@@ -7513,6 +8970,133 @@ mod tests {.await;}+ /// Real publisher regression for native OSS-shaped payload stores. This is+ /// NATS-gated like the adjacent publish-span integration test: point+ /// `NATS_URL` at an ephemeral memory-backed JetStream server to exercise+ /// public `publish_work` and its real terminal cleanup path.+ #[tokio::test]+ async fn publisher_large_oss_payload_emits_plain_ref_and_terminal_delete() {+ use futures_util::StreamExt;++ if std::env::var("SIE_RUN_NATS_PUBLISHER_TEST").as_deref() != Ok("1") {+ eprintln!("skipping: SIE_RUN_NATS_PUBLISHER_TEST=1 was not requested");+ return;+ }+ let url =+ std::env::var("NATS_URL").expect("mandatory publisher regression requires NATS_URL");+ let client = tokio::time::timeout(Duration::from_secs(2), async_nats::connect(&url))+ .await+ .expect("timed out connecting mandatory publisher regression to NATS")+ .expect("failed to connect mandatory publisher regression to NATS");+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|duration| duration.as_nanos())+ .unwrap_or(0);+ let pool = format!("osspayload{nanos}");+ let model = "BAAI__bge-m3";+ let store = Arc::new(FullReferencePayloadStore {+ full_reference: "oss://sie-wire-fixture/payloads/provider-returned-full-ref.bin"+ .to_owned(),+ puts: std::sync::Mutex::new(Vec::new()),+ deleted: std::sync::Mutex::new(Vec::new()),+ });+ let publisher = Arc::new(WorkPublisher::new(+ async_nats::jetstream::new(client.clone()),+ "oss-publisher-test".to_owned(),+ store.clone(),+ Duration::from_secs(5),+ 1024,+ WorkStreamConfig {+ max_age: Duration::from_secs(300),+ storage: jetstream::stream::StorageType::Memory,+ num_replicas: 1,+ },+ ));+ let target = PublishTarget::Pool {+ pool: pool.clone(),+ machine_profile: "a10".to_owned(),+ bundle: "default".to_owned(),+ model: model.to_owned(),+ };+ let subject = target.subject();+ let context = async_nats::jetstream::new(client.clone());+ let stream = context+ .get_or_create_stream(jetstream::stream::Config {+ name: stream_name(&pool),+ subjects: vec![format!("sie.work.{pool}.*.*.*")],+ retention: jetstream::stream::RetentionPolicy::WorkQueue,+ storage: jetstream::stream::StorageType::Memory,+ max_age: Duration::from_secs(300),+ max_messages: 100_000,+ discard: jetstream::stream::DiscardPolicy::New,+ ..Default::default()+ })+ .await+ .expect("create OSS publisher test stream");+ stream+ .create_consumer(jetstream::consumer::pull::Config {+ durable_name: Some("oss-payload-worker".to_owned()),+ filter_subject: subject.clone(),+ ..Default::default()+ })+ .await+ .expect("create OSS publisher test consumer");+ let mut subscription = client.subscribe(subject).await.expect("subscribe");+ client.flush().await.expect("flush subscription");++ let params = WorkParams {+ output_types: None,+ instruction: None,+ is_query: false,+ options: None,+ labels: None,+ output_schema: None,+ query_item: None,+ generate: None,+ routing_key: None,+ prompt_cache_key: None,+ };+ let items = vec![rmpv::Value::Map(vec![(+ rmpv::Value::String("image".into()),+ rmpv::Value::Binary(vec![7; PAYLOAD_OFFLOAD_THRESHOLD + 1024]),+ )])];+ let (request_id, _rx, durability) = publisher+ .publish_work(+ target, &pool, "encode", model, "pytorch", "", items, ¶ms,+ )+ .await+ .expect("publish oversized work item");+ durability.wait().await.expect("durable publish ACK");++ let message = tokio::time::timeout(Duration::from_secs(5), subscription.next())+ .await+ .expect("timed out waiting for oversized work item")+ .expect("subscription closed before oversized work item");+ let work: WorkItem = rmp_serde::from_slice(&message.payload).expect("decode work item");+ let expected_key = format!("{request_id}_0.bin");+ assert!(work.item.is_none());+ assert_eq!(work.payload_ref.as_deref(), Some(expected_key.as_str()));+ {+ let puts = store.puts.lock().unwrap();+ assert_eq!(puts.len(), 1);+ assert_eq!(puts[0].0, expected_key);+ assert!(puts[0].1 > PAYLOAD_OFFLOAD_THRESHOLD);+ }++ assert!(publisher.drop_pending_result(&request_id));+ publisher.finish_abandoned_work(&request_id).await;+ assert_eq!(+ store.deleted.lock().unwrap().as_slice(),+ std::slice::from_ref(&expected_key)+ );+ assert!(!publisher.offloaded_payload_keys.contains_key(&request_id));++ context+ .delete_stream(stream_name(&pool))+ .await+ .expect("delete OSS publisher test stream");+ }+// ----- H9 — first-chunk-fallback rate limit ---------------------/// A NAK is dropped as stale only when the collector can identify it as andiff --git a/packages/sie_gateway/src/queue/stream_durability.rs b/packages/sie_gateway/src/queue/stream_durability.rsnew file mode 100644index 000000000..f44d5ffc6--- /dev/null+++ b/packages/sie_gateway/src/queue/stream_durability.rs@@ -0,0 +1,85 @@+//! Shared reconcile policy for the durability knobs on JetStream streams+//! this gateway owns: the `WORK_POOL_{pool}` work queues and `DEAD_LETTERS`.+//!+//! Both are created from `SIE_STREAM_STORAGE` / `SIE_STREAM_REPLICAS`, and+//! both face the same question on an *existing* stream: what happens when the+//! live stream's shape does not match the configured one? The answer differs+//! per field and is easy to get wrong in one place and not the other, so it+//! lives here once:+//!+//! - `num_replicas` IS changeable on a live stream (this is JetStream's+//! supported R1 -> R3 scaling path), so it is reconciled.+//! - `storage` is NOT. NATS rejects the update with err_code 10052,+//! "stream configuration update can not change storage type", because the+//! message store is already materialized in RAM or on disk. The only way to+//! "fix" it is to delete and recreate the stream — which destroys the+//! queued work, or the forensic dead-letter record, that durability exists+//! to protect. So a divergence is reported loudly and the stream is left+//! intact for the operator to convert during a maintenance window.+//!+//! See the chart README's "Work-queue durability" section.++use async_nats::jetstream;+use tracing::{info, warn};++/// Reconcile an existing stream's replica count to `desired_replicas`.+///+/// Refreshes the caller's stream handle when an update is applied, so code+/// that keeps using it observes the new config.+///+/// Note that NATS does not police this against the actual topology: a+/// single-node server accepts `num_replicas: 3` and then reports R3, with no+/// cluster to back it (verified against nats-server 2.12.6). Guarding a+/// replica count against the deployed NATS cluster size is therefore the+/// chart's job, not the broker's — see the `streamReplicas` guards in+/// deploy/helm/sie-cluster/templates/gateway-deployment.yaml.+pub async fn reconcile_num_replicas(+ jetstream: &jetstream::Context,+ stream: &mut jetstream::stream::Stream,+ name: &str,+ desired_replicas: usize,+) -> Result<(), String> {+ let observed_replicas = stream.cached_info().config.num_replicas;+ if observed_replicas == desired_replicas {+ return Ok(());+ }++ let mut updated = stream.cached_info().config.clone();+ updated.num_replicas = desired_replicas;+ jetstream+ .update_stream(updated)+ .await+ .map_err(|e| format!("update stream {} num_replicas: {}", name, e))?;+ *stream = jetstream+ .get_stream(name.to_string())+ .await+ .map_err(|e| format!("refresh stream {} after num_replicas update: {}", name, e))?;+ info!(+ stream = %name,+ observed_replicas,+ desired_replicas,+ "reconciled JetStream stream num_replicas"+ );+ Ok(())+}++/// Report — but never repair — a storage-type divergence on an existing+/// stream. See the module docs for why this is deliberately not reconciled.+pub fn warn_on_storage_mismatch(+ stream: &jetstream::stream::Stream,+ name: &str,+ desired_storage: jetstream::stream::StorageType,+) {+ let observed_storage = stream.cached_info().config.storage;+ if observed_storage == desired_storage {+ return;+ }+ warn!(+ stream = %name,+ observed_storage = ?observed_storage,+ desired_storage = ?desired_storage,+ "JetStream stream storage type differs from SIE_STREAM_STORAGE and CANNOT be changed \+ in place; the stream keeps its existing storage until an operator drains it and \+ recreates it during a maintenance window"+ );+}diff --git a/packages/sie_gateway/src/queue/streaming.rs b/packages/sie_gateway/src/queue/streaming.rsindex 94983721f..ebcd20163 100644--- a/packages/sie_gateway/src/queue/streaming.rs+++ b/packages/sie_gateway/src/queue/streaming.rs@@ -30,6 +30,7 @@ use tokio::sync::{broadcast, oneshot, Notify};use crate::observability::metrics::{self as telemetry, GenerationEvent, GenerationEventOutcome, GenerationEventReason,};+use crate::queue::lane_admission::LaneReservation;/// Broadcast channel capacity for the per-request SSE chunk tap.///@@ -170,7 +171,7 @@ fn default_tool_call_type() -> String {}/// Wire-level allowlist for ``finish_reason`` values produced by the-/// worker. OpenAI canonical values plus the SIE-internal additions for+/// worker. OpenAI canonical values plus the gateway-specific additions for/// gateway-driven cancellation and error surfacing. Keep in lockstep with/// ``GenerationChunk.finish_reason`` in the Python adapter.fn is_known_finish_reason(reason: &str) -> bool {@@ -388,6 +389,11 @@ pub struct StreamCollector {/// than surfacing an empty body. Overwritten on every bump; a/// successful new attempt (no rewind) simply never reads it.snapshot: Option<AttemptSnapshot>,+ /// Per-lane in-flight reservation, released when this collector drops.+ /// Installed by the publish path after the lane admission check; `None`+ /// on a collector built outside it. See+ /// [`crate::queue::lane_admission`].+ pub lane_reservation: Option<LaneReservation>,}/// State saved by ``bump_attempt_generation`` so a failed-publish@@ -446,6 +452,7 @@ impl StreamCollector {abandoned_attempt_id: None,client_disconnected: Arc::new(AtomicBool::new(false)),snapshot: None,+ lane_reservation: None,}}diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex e864ec511..fd0109785 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -417,8 +417,26 @@ fn active_lease_values(})}+/// Where the customer-facing `event="api_request"` audit record is emitted for+/// one composition.+///+/// The record's `status` is read as the status the client received, so the+/// [`AuditLayer`] has to sit outside everything that can replace a response.+/// See the `middleware::audit` module docs for the full contract.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum AuditPlacement {+ /// Emit inside this route stack. Correct wherever nothing outside the core+ /// rewrites a handler response — the OSS composition.+ Core,+ /// Omit the layer here. The caller installs [`AuditLayer`] itself, outside+ /// every response-rewriting layer it adds, so the record carries the final+ /// status when managed billing rewrites an inner 503 to 402.+ #[allow(dead_code)] // Managed composition API; unused by the standalone gateway binary.+ Composition,+}+pub fn create_router(state: Arc<AppState>, config: Arc<Config>) -> Router {- apply_request_telemetry(create_router_core(state, config))+ apply_request_telemetry(create_router_core(state, config, AuditPlacement::Core))}/// Build the reusable gateway route stack without the outer request telemetry@@ -427,10 +445,16 @@ pub fn create_router(state: Arc<AppState>, config: Arc<Config>) -> Router {/// Managed compositions add admission middleware and cloud-owned routes around/// this core, then call [`apply_request_telemetry`] after the final merge so/// early 401/402/403 responses are observed whenever a request signal is live.-/// Standalone callers should use [`create_router`], which preserves the OSS-/// composition and conditionally adds that layer.-pub fn create_router_core(state: Arc<AppState>, config: Arc<Config>) -> Router {- Router::new()+/// They also pass [`AuditPlacement::Composition`] and install the audit layer+/// outside their own response-rewriting gates. Standalone callers should use+/// [`create_router`], which preserves the OSS composition and conditionally+/// adds that layer.+pub fn create_router_core(+ state: Arc<AppState>,+ config: Arc<Config>,+ audit: AuditPlacement,+) -> Router {+ let router = Router::new()// Status page.route("/", get(health::status_page))// Health endpoints@@ -494,10 +518,14 @@ pub fn create_router_core(state: Arc<AppState>, config: Arc<Config>) -> Router {.route("/v1/encode/{*model}", post(proxy::proxy_encode)).route("/v1/score/{*model}", post(proxy::proxy_score)).route("/v1/extract/{*model}", post(proxy::proxy_extract))- .route("/v1/generate/{*model}", post(proxy::proxy_generate))- .layer(AuditLayer::new())- .layer(AuthLayer::new(config))- .with_state(state)+ .route("/v1/generate/{*model}", post(proxy::proxy_generate));++ let router = match audit {+ AuditPlacement::Core => router.layer(AuditLayer::new()),+ AuditPlacement::Composition => router,+ };++ router.layer(AuthLayer::new(config)).with_state(state)}#[cfg(test)]@@ -885,19 +913,19 @@ mod capacity_snapshot_tests {#[cfg(test)]mod flat_404_tests {- //! Flat-404 wire contract for managed-service routes (#1757).+ //! Flat-404 wire contract for unregistered compatibility routes.//!//! The Files, Batches, batch-cancel, and file-upload surfaces//! (`/v1/files*`, `/v1/batches*`, `/v1/batches/{id}/cancel`,- //! `POST /v1/files`) are OpenAI-compatible routes the *managed- //! service* fronts (see `sie_tools`/`sie_sdk` `.files`/`.batches`);- //! the inference-edge gateway does NOT back them. Because they are- //! not registered in [`create_router`] and there is no custom- //! `.fallback()`, axum's default fallback answers them with a- //! **flat 404**: status `404 Not Found` and an **empty body**.+ //! `POST /v1/files`) are OpenAI-compatible routes that compatible+ //! `.files`/`.batches` clients may call. The inference gateway does+ //! not implement them. Because they are not registered in+ //! [`create_router`] and there is no custom `.fallback()`, axum's+ //! default fallback answers them with a **flat 404**: status+ //! `404 Not Found` and an **empty body**.//!- //! That is the contract these tests pin: an unbacked managed-service- //! route returns a clean 404 with no body — never a leaky/verbose+ //! That is the contract these tests pin: an unregistered compatibility+ //! route returns a clean 404 with no body — never a leaky or verbose//! error envelope and never a 500. Contrast `config_api`'s//! `test_post_model_config_returns_405_method_not_allowed`, which//! covers a *registered* path hit with an unbacked method (405); an@@ -947,12 +975,18 @@ mod flat_404_tests {multi_router: false,request_timeout: 30.0,max_stream_pending: 50_000,+ max_lane_in_flight_items:+ crate::queue::lane_admission::DEFAULT_MAX_LANE_IN_FLIGHT_ITEMS,+ lane_backpressure_enforce: false,stream_max_age_s: 1_800,+ stream_storage: crate::config::StreamStorage::Memory,+ stream_num_replicas: 1,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),configured_physical_lanes: Default::default(),static_queue_pools: Vec::new(),model_aliases: HashMap::new(),+ published_model_aliases: Default::default(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),payload_store_url: String::new(),@@ -1010,7 +1044,7 @@ mod flat_404_tests {assert_eq!(status,StatusCode::NOT_FOUND,- "{method} {uri} must return a flat 404 (unbacked managed-service route), got {status}",+ "{method} {uri} must return a flat 404 (unregistered compatibility route), got {status}",);// Explicitly guard against a 5xx masquerading — the route must be// rejected by the fallback, never reach a handler that could 500.diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex ad92a0162..4363ed3fb 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -1572,23 +1572,39 @@ impl ModelRegistry {/// Return the routing hash and immutable model revision from one registry/// snapshot. Keeping these values in one read is required for response/// provenance: a config delta must not pair hash A with revision B.+ ///+ /// The supplied pool is the physical/admission fallback for an unknown+ /// (for example sealed) model. A catalog model always scopes its hash to+ /// the pool declared by that model, independently of the physical queue+ /// selected for dispatch. This keeps dedicated physical lanes from+ /// accidentally turning config-hash enforcement into an empty wildcard.+ /// The scope bit reports whether the hash is governed by a known catalog+ /// model. Proxy paths use it to reject a missing known hash instead of+ /// treating it as the legacy unknown/sealed wildcard.pub fn bundle_execution_evidence(&self,bundle_id: &str,pool_name: &str,model: &str,- ) -> (String, Option<String>) {+ ) -> (String, Option<String>, bool) {let snap = self.snapshot.load();+ let canonical = Self::canonical_model_name(&snap, model);+ let uses_catalog_scope = canonical.is_some();+ let pool_name = canonical+ .as_ref()+ .and_then(|canonical| snap.models.get(canonical))+ .map(Self::entry_pool_name)+ .unwrap_or(pool_name);let pool_name = Self::normalize_pool_name(pool_name);let bundle_config_hash = snap.bundle_pool_config_hashes.get(&(bundle_id.to_string(), pool_name)).cloned().unwrap_or_default();- let revision = Self::canonical_model_name(&snap, model)+ let revision = canonical.and_then(|canonical| snap.models.get(&canonical)).and_then(Self::immutable_model_revision);- (bundle_config_hash, revision)+ (bundle_config_hash, revision, uses_catalog_scope)}/// Resolve one connector encode identity from a single registry snapshot.@@ -4988,7 +5004,7 @@ profiles:).unwrap();let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);- let (first, first_revision) =+ let (first, first_revision, _) =registry.bundle_execution_evidence("default", "default", "org/revisioned");assert_eq!(first_revision.as_deref(),@@ -5020,7 +5036,7 @@ profiles:registry.get_model_revision("org/revisioned").as_deref(),Some("89abcdef0123456789abcdef0123456789abcdef"));- let (second, second_revision) =+ let (second, second_revision, _) =registry.bundle_execution_evidence("default", "default", "org/revisioned");assert_ne!(first, second);assert_eq!(@@ -5112,6 +5128,25 @@ profiles:registry.compute_bundle_config_hash_for_pool("default", "customer-a"),tenant_hash);++ let (tenant_execution_hash, _, uses_catalog_scope) = registry.bundle_execution_evidence(+ "default",+ "dedicated-physical-queue",+ "tenant/model",+ );+ assert_eq!(tenant_execution_hash, tenant_hash);+ assert!(!tenant_execution_hash.is_empty());+ assert!(uses_catalog_scope);++ let (default_execution_hash, _, uses_catalog_scope) =+ registry.bundle_execution_evidence("default", "qwen4b-benchmark", "default/model");+ assert_eq!(default_execution_hash, default_hash);+ assert!(uses_catalog_scope);++ let (unknown_execution_hash, _, uses_catalog_scope) =+ registry.bundle_execution_evidence("default", "qwen4b-benchmark", "org/sealed-unknown");+ assert!(unknown_execution_hash.is_empty());+ assert!(!uses_catalog_scope);}#[test]diff --git a/packages/sie_mcp/Dockerfile b/packages/sie_mcp/Dockerfileindex e4659f6df..cc35cd48f 100644--- a/packages/sie_mcp/Dockerfile+++ b/packages/sie_mcp/Dockerfile@@ -1,5 +1,5 @@# syntax=docker/dockerfile:1.6-# SIE MCP edge — hosted MCP server exposing SIE document jobs (Req 12).+# SIE MCP edge — hosted MCP server exposing SIE document jobs.# Lightweight image: a sie_sdk client, no GPU/model dependencies.## Build (from repo root):diff --git a/packages/sie_mcp/README.md b/packages/sie_mcp/README.mdindex 90b22efbb..8ce99e0a0 100644--- a/packages/sie_mcp/README.md+++ b/packages/sie_mcp/README.md@@ -57,9 +57,8 @@ The generated Claude Code skill pack includes:- `redact-pii`: calls `redact_pii`.The redaction MCP tool intentionally does not return a placeholder-to-original-map. That keeps original PII from being handed back to the calling model. Use the-older local `sie_tools` redaction flow from PR #1336 if a de-redaction map is-required.+map. That keeps original PII from being handed back to the calling model. Do not+use this flow when de-redaction is required.## Credentials Model@@ -67,9 +66,10 @@ There are two different credentials:- Server operator credential: `SIE_API_KEY`, used by the MCP edge to call the SIEcluster gateway. Only the edge process should have this.-- Connector credential: `SIE_MCP_CONNECTOR_SECRETS`, used by users or agent- surfaces to authenticate to `/mcp`. Give users this connector secret, not the- cluster API key.+- Server connector-credential map: `SIE_MCP_CONNECTOR_SECRETS`, read by the MCP+ edge to validate clients. Give users their connector secret, not the cluster+ API key. Client-side shell examples use the singular+ `SIE_MCP_CONNECTOR_SECRET` only to construct an authorization header.The edge also needs `SIE_BASE_URL`, the gateway URL for the SIE cluster. For anin-cluster Helm deployment this can be left unset and the chart points at the@@ -79,22 +79,22 @@ gateway service.Use this when an operator has already given you:-- An MCP URL such as `https://<mcp-host>/mcp`.+- An MCP URL such as `https://mcp.example.com/mcp`.- A connector secret.From the repo root:```bash-export SIE_MCP_URL="https://<mcp-host>/mcp"-export SIE_MCP_CONNECTOR_SECRET="<connector-secret>"+export SIE_MCP_URL="https://mcp.example.com/mcp"uv run --package sie-mcp sie-mcp plugin-pack \- --cluster-label sie \+ --cluster-label my-sie-cluster \--mcp-url "$SIE_MCP_URL"```The generated pack is written to-`packages/sie_mcp/dist/superlinked-docs-plugin/` and contains:+`packages/sie_mcp/dist/superlinked-docs-plugin/` and contains no connector+credential:- `INSTALL.md`: endpoint-specific install commands.- `superlinked-docs-skill.zip`: uploadable claude.ai skill ZIP.@@ -105,6 +105,7 @@ Install it into Claude Code:```bashcd packages/sie_mcp/dist/superlinked-docs-plugin+export SIE_MCP_CONNECTOR_SECRET='replace-with-connector-secret'claude mcp add --scope user --transport http superlinked-docs \"$SIE_MCP_URL" \@@ -112,6 +113,7 @@ claude mcp add --scope user --transport http superlinked-docs \mkdir -p ~/.claude/skillscp -R claude-code/* ~/.claude/skills/+unset SIE_MCP_CONNECTOR_SECRET```Restart Claude Code after adding the MCP server and skills.@@ -135,8 +137,8 @@ This starts only the lightweight MCP edge locally; document processing still runon the configured SIE cluster.```bash-export SIE_BASE_URL="https://<cluster-gateway>"-export SIE_API_KEY="<cluster-api-key>" # omit if the gateway has no auth+export SIE_BASE_URL="https://gateway.example.com"+export SIE_API_KEY='replace-with-cluster-api-key' # omit if the gateway has no authexport SIE_MCP_CONNECTOR_SECRETS="local-dev-secret:local-dev"uv run --package sie-mcp sie-mcp serve --host 127.0.0.1 --port 8088@@ -239,7 +241,7 @@ Run the package tests from the repo root:uv run --package sie-mcp python -m pytest packages/sie_mcp/tests```-For a focused check of this plugin-pack and PR #1336 integration path:+For a focused check of the plugin-pack and document-offload path:```bashuv run --package sie-mcp python -m pytest \@@ -259,13 +261,17 @@ git diff --checkOnce the local edge is running, generate an install pack that points at it:```bash-SIE_MCP_CONNECTOR_SECRET=local-dev-secret uv run --package sie-mcp sie-mcp plugin-pack \+uv run --package sie-mcp sie-mcp plugin-pack \--cluster-label local-dev \--mcp-url http://127.0.0.1:8088/mcp \--out-dir /tmp/sie-mcp-plugin-pack++export SIE_MCP_CONNECTOR_SECRET='local-dev-secret'```Then follow `/tmp/sie-mcp-plugin-pack/INSTALL.md`.+The guide contains a placeholder; retrieve the local-only connector secret from+your environment or local secret store when running its install command.## Build And Run The Docker Server@@ -293,11 +299,14 @@ Then reuse the smoke-test commands above withThe Helm chart has an optional `mcpEdge` section. A typical hosted deployment hasone public HTTPS host for the MCP edge and a connector secret for users.+The commands below use `local-dev-secret` as a local-only demo connector secret.+Replace it before any shared or production deployment.+Create the connector secret:```bashkubectl -n sie create secret generic sie-mcp-connector-secrets \- --from-literal=connector-secrets="tester-secret:tester"+ --from-literal=connector-secrets="local-dev-secret:local-dev"```If the edge calls an external gateway that requires a cluster API key, create a@@ -305,26 +314,29 @@ separate secret for that server-side key:```bashkubectl -n sie create secret generic sie-mcp-cluster-api-key \- --from-literal=api-key="<cluster-api-key>"+ --from-literal=api-key='replace-with-cluster-api-key'```Enable the edge:+Replace the example `v0.7.1` image tag below with the SIE release you want+to deploy.+```bashhelm upgrade sie deploy/helm/sie-cluster -n sie --reuse-values \--set mcpEdge.enabled=true \--set mcpEdge.image.repository=ghcr.io/superlinked/sie-mcp \- --set mcpEdge.image.tag=<tag> \+ --set mcpEdge.image.tag=v0.7.1 \--set mcpEdge.existingSecretName=sie-mcp-connector-secrets \- --set mcpEdge.publicUrl=https://<mcp-host> \+ --set mcpEdge.publicUrl=https://mcp.example.com \--set mcpEdge.ingress.enabled=true \- --set mcpEdge.ingress.host=<mcp-host>+ --set mcpEdge.ingress.host=mcp.example.com```For an external gateway instead of the in-cluster gateway, add:```bash---set mcpEdge.clusterBaseUrl=https://<cluster-gateway> \+--set mcpEdge.clusterBaseUrl=https://gateway.example.com \--set mcpEdge.clusterApiKey.existingSecretName=sie-mcp-cluster-api-key```@@ -332,17 +344,20 @@ Verify:```bashkubectl -n sie rollout status deploy/sie-mcp --timeout=180s-curl -s https://<mcp-host>/healthz+curl -s https://mcp.example.com/healthz```Then generate a user install pack:```bash-SIE_MCP_CONNECTOR_SECRET=tester-secret uv run --package sie-mcp sie-mcp plugin-pack \- --cluster-label <cluster-name> \- --mcp-url https://<mcp-host>/mcp+uv run --package sie-mcp sie-mcp plugin-pack \+ --cluster-label my-sie-cluster \+ --mcp-url https://mcp.example.com/mcp```+Keep the real connector secret in connector configuration or a local secret+store. The generated pack contains only placeholder-based instructions.+## How Users Use It In Claude CodeAfter installing the generated pack, users can ask Claude Code to process files@@ -365,9 +380,9 @@ The skill instructions tell Claude Code to:## Troubleshooting-`401` from `/mcp` means the connector secret is missing or wrong. Re-run the-generated `claude mcp add ... --header "Authorization: Bearer ..."` command from-`INSTALL.md`.+`401` from `/mcp` means the connector secret is missing or wrong. Retrieve the+secret into `SIE_MCP_CONNECTOR_SECRET`, then re-run the placeholder-based+`claude mcp add ...` command from `INSTALL.md`.`/healthz` works but tools fail usually means the edge cannot call the SIEcluster. Check `SIE_BASE_URL`, `SIE_API_KEY`, and cluster worker availability.@@ -376,5 +391,10 @@ The first document request can take longer than later requests because modelworkers may need to start or load weights.claude.ai custom connectors require a public HTTPS MCP URL and the OAuth bridge.-Set `SIE_MCP_PUBLIC_URL=https://<mcp-host>` for hosted deployments so OAuth-metadata contains stable public URLs.+For hosted deployments, export the public origin before starting the MCP edge:++```bash+export SIE_MCP_PUBLIC_URL='https://mcp.example.com'+```++This ensures that OAuth metadata contains stable public URLs.diff --git a/packages/sie_mcp/docs/examples/mcp_smoke.py b/packages/sie_mcp/docs/examples/mcp_smoke.pyindex bc977fb41..fa97bb57d 100644--- a/packages/sie_mcp/docs/examples/mcp_smoke.py+++ b/packages/sie_mcp/docs/examples/mcp_smoke.py@@ -7,10 +7,10 @@ lists tools, and (optionally) calls docs_to_markdown on a local file.Run it in the sie-mcp package env so the `mcp` client is importable:mise exec -- uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \- --url http://localhost:8088/mcp --secret <secret> --list+ --url http://localhost:8088/mcp --secret 'replace-with-connector-secret' --listmise exec -- uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \- --url http://localhost:8088/mcp --secret <secret> \+ --url http://localhost:8088/mcp --secret 'replace-with-connector-secret' \--file packages/sie_mcp/docs/examples/sample.html --filename sample.html --engine docling"""diff --git a/packages/sie_mcp/plugin/SKILL.md b/packages/sie_mcp/plugin/SKILL.mdindex dd7e69366..27af77dcd 100644--- a/packages/sie_mcp/plugin/SKILL.md+++ b/packages/sie_mcp/plugin/SKILL.md@@ -42,9 +42,11 @@ markdown.The tool response also includes a `metadata` object with two distinct figures: a liveper-call `markdown_tokens_estimate` (a rough ~4 chars/token count of *this* response — an-estimate, not a billed figure) and `token_reduction`, the committed #1311 benchmark+estimate, not a billed figure) and `token_reduction`, the reference benchmarkmeasurement of markdown vs direct document ingestion. Surface these if the user asks how-much was saved; the exact percentages and the benchmark path are in the metadata.+much was saved; the exact percentages and measurement run are in the metadata. Its+`source` is a stable, public-safe run label; `issue` is `null` because no public issue+tracks that committed measurement.## summarize document@@ -160,5 +162,5 @@ pixels reach the calling model.`docs_to_markdown`, `summarize_document`, `extract_entities`, `redact_pii`,`describe_image`, `extract_structured`, and `generate_structured` are all served by theSuperlinked MCP connector. Configure the connector with your **connector secret** —-credentials are never pasted into the chat. For this POC the connector secret is provided-by your cluster operator; self-serve issuance arrives with the managed service.+credentials are never pasted into the chat. The connector secret is provided by your+cluster operator.diff --git a/packages/sie_mcp/plugin/claude-code/extract-entities/SKILL.md b/packages/sie_mcp/plugin/claude-code/extract-entities/SKILL.mdindex 0356f67a7..8b5034c96 100644--- a/packages/sie_mcp/plugin/claude-code/extract-entities/SKILL.md+++ b/packages/sie_mcp/plugin/claude-code/extract-entities/SKILL.md@@ -6,8 +6,7 @@ description: Extract people, organizations, dates, amounts, or custom labels fro# Extract Entities with Superlinked MCPUse the connected Superlinked MCP server to run zero-shot entity extraction on-the SIE cluster. This mirrors the `extract-entities` flow from the `sie_tools`-plugin in PR #1336, but uses the MCP `extract_entities` tool.+the SIE cluster through the MCP `extract_entities` tool.## Stepsdiff --git a/packages/sie_mcp/plugin/claude-code/parse-document/SKILL.md b/packages/sie_mcp/plugin/claude-code/parse-document/SKILL.mdindex dffacd644..a47045743 100644--- a/packages/sie_mcp/plugin/claude-code/parse-document/SKILL.md+++ b/packages/sie_mcp/plugin/claude-code/parse-document/SKILL.md@@ -5,10 +5,8 @@ description: Convert a PDF, scan, image of a page, or office file to clean markd# Parse a Document with Superlinked MCP-Use the connected Superlinked MCP server to convert the source file to markdown,-then work from the markdown artifact. This mirrors the `parse-document` flow from-the `sie_tools` plugin in PR #1336, but uses the MCP `docs_to_markdown` tool-instead of the gateway-backed `~/.sie/bin/sie` wrapper.+Use the connected Superlinked MCP server to convert the source file to markdown+through the MCP `docs_to_markdown` tool, then work from the markdown artifact.## Stepsdiff --git a/packages/sie_mcp/plugin/claude-code/redact-pii/SKILL.md b/packages/sie_mcp/plugin/claude-code/redact-pii/SKILL.mdindex 416a81766..7c42b6daa 100644--- a/packages/sie_mcp/plugin/claude-code/redact-pii/SKILL.md+++ b/packages/sie_mcp/plugin/claude-code/redact-pii/SKILL.md@@ -6,8 +6,7 @@ description: Redact personal data from a document through the connected Superlin# Redact PII with Superlinked MCPUse the connected Superlinked MCP server to detect and replace PII on the SIE-cluster. This mirrors the `redact-pii` flow from the `sie_tools` plugin in-PR #1336, but uses the MCP `redact_pii` tool.+cluster through the MCP `redact_pii` tool.## Hard Rulesdiff --git a/packages/sie_mcp/plugin/claude-code/summarize-document/SKILL.md b/packages/sie_mcp/plugin/claude-code/summarize-document/SKILL.mdindex c126b7e7c..efe377e52 100644--- a/packages/sie_mcp/plugin/claude-code/summarize-document/SKILL.md+++ b/packages/sie_mcp/plugin/claude-code/summarize-document/SKILL.md@@ -6,9 +6,7 @@ description: Summarize a long PDF, scan, office file, text file, or markdown fil# Summarize a Document with Superlinked MCPUse the connected Superlinked MCP server to summarize the source on the SIE-cluster. This mirrors the `summarize-document` flow from the `sie_tools` plugin-in PR #1336, but uses the MCP `summarize_document` tool instead of the-gateway-backed `~/.sie/bin/sie` wrapper.+cluster through the MCP `summarize_document` tool.## Stepsdiff --git a/packages/sie_mcp/plugin/superlinked.md b/packages/sie_mcp/plugin/superlinked.mdindex 4ba83bed9..78d1d5a24 100644--- a/packages/sie_mcp/plugin/superlinked.md+++ b/packages/sie_mcp/plugin/superlinked.md@@ -3,30 +3,33 @@`superlinked.md` is a router to each surface's **native** install path. There is nodrop-a-file auto-install — pick your surface below.-## Managed sie-test quick install+## Hosted cluster quick install-If a Superlinked operator gives you a hosted MCP endpoint for `sie-test` plus a connector-secret, you can use the MCP-based document offload flow without deploying a self-hosted AWS-cluster. Build a small install pack from this repo:+If a Superlinked operator gives you a hosted MCP endpoint plus a connector secret, you can+use the MCP-based document offload flow. Replace the example host with the endpoint the+operator provided, then build a small install pack from this repo:```bashmise run mcp-plugin-pack -- \- --cluster-label sie-test \- --mcp-url https://<sie-test-mcp-host>/mcp+ --cluster-label my-sie-cluster \+ --mcp-url https://mcp.example.com/mcp```-Add `SIE_MCP_CONNECTOR_SECRET=<secret>` or `--connector-secret <secret>` if you want the-generated `INSTALL.md` to include the exact connector command. The command writes:+The command writes:- `dist/superlinked-docs-plugin/INSTALL.md` — endpoint-specific install steps for ClaudeCode, claude.ai / desktop, and Cowork.- `dist/superlinked-docs-plugin/superlinked-docs-skill.zip` — the claude.ai skill ZIP.- `dist/superlinked-docs-plugin/claude-code/*/SKILL.md` — Claude Code skills in the- local skill layout, including PR #1336-style `parse-document`, `summarize-document`,+ local skill layout, including `parse-document`, `summarize-document`,`extract-entities`, and `redact-pii` skills backed by MCP tools.-The connector secret is printed only in `INSTALL.md` when you pass it; it is not embedded-in the skill ZIP or skill file.+No connector secret is written to the pack. Retrieve it from connector configuration or a+local secret store only when following the placeholder-based steps in `INSTALL.md`.+For local setup, load it into `SIE_MCP_CONNECTOR_SECRET` (using+`'replace-with-connector-secret'` only as the placeholder) and unset it after installation.+This singular name is a client-side shell variable used to construct the authorization+header; the MCP server instead reads the plural `SIE_MCP_CONNECTOR_SECRETS` runtime map.The MCP redaction flow returns redacted text and counts, but not a localplaceholder-to-original map; do not use it when de-redaction is required.@@ -48,7 +51,7 @@ served at — e.g. the value of `SIE_MCP_HOST` for your cluster):- Auth header: `Authorization: Bearer <connector-secret>`- Health check: `GET https://<host>/healthz`-## claude.ai (#1312)+## claude.aiclaude.ai is a **two-piece** install: a custom **connector** (the remote MCP) plus a**skill ZIP** (the agent skill). Unlike Cowork, claude.ai connectors are OAuth-only — you@@ -91,7 +94,7 @@ as on Cowork).are stable (otherwise they are derived per-request from forwarded host/proto headers).- Run the edge as a **single worker** (the default `mise run mcp-serve`): the OAuthauthorization-code store is in-process, so a code issued on one worker cannot be- redeemed on another. A shared store lands with per-user key issuance in Req 10 (#1313).+ redeemed on another.- The OAuth redirect allowlist defaults to claude.ai's callback; override with`SIE_MCP_OAUTH_REDIRECT_URIS` (comma-separated). Set `SIE_MCP_OAUTH_ENABLED=0` todisable the bridge for Cowork-only deployments.diff --git a/packages/sie_mcp/pyproject.toml b/packages/sie_mcp/pyproject.tomlindex d34e07c8a..c2cebd25f 100644--- a/packages/sie_mcp/pyproject.toml+++ b/packages/sie_mcp/pyproject.toml@@ -1,7 +1,7 @@[project]name = "sie-mcp"version = "0.1.0"-description = "SIE MCP edge - hosted MCP server exposing SIE document jobs (Req 12)"+description = "SIE MCP edge - hosted MCP server exposing SIE document jobs"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }dependencies = [@@ -13,7 +13,7 @@ dependencies = [# Post-validation of cluster output against the requested schema. Already a# transitive dependency via ``mcp``; declared directly since we import it."jsonschema>=4",- # VL-OCR routing (#1307): rasterize scanned/complex PDF pages for the VL-OCR model.+ # VL-OCR routing: rasterize scanned or complex PDF pages for the VL-OCR model."pypdfium2>=5.6.0","pillow>=12.2.0",]diff --git a/packages/sie_mcp/src/sie_mcp/app.py b/packages/sie_mcp/src/sie_mcp/app.pyindex 3f2bc8a0a..f1c1796ab 100644--- a/packages/sie_mcp/src/sie_mcp/app.py+++ b/packages/sie_mcp/src/sie_mcp/app.py@@ -22,7 +22,7 @@ def build_app() -> Starlette:app.router.routes.append(Route("/healthz", _healthz, methods=["GET"]))if config.oauth_enabled:# The OAuth bridge lets claude.ai connectors authenticate via the connector- # secret (#1312); the gate below exempts these bootstrap endpoints.+ # secret; the gate below exempts these bootstrap endpoints.app.router.routes.extend(build_oauth_routes(config))app.add_middleware(ConnectorSecretAuthMiddleware, config=config)return appdiff --git a/packages/sie_mcp/src/sie_mcp/auth.py b/packages/sie_mcp/src/sie_mcp/auth.pyindex d98623f90..9fb90fcd7 100644--- a/packages/sie_mcp/src/sie_mcp/auth.py+++ b/packages/sie_mcp/src/sie_mcp/auth.py@@ -1,7 +1,7 @@-"""Connector-secret auth at the MCP edge (the Req 12 shim).+"""Connector-secret authentication at the MCP edge.A per-user connector secret (Bearer) is validated here and mapped to a stable-user identity, so per-user metering can attach later (Req 10, #1313). The cluster+user identity, so per-user metering can attach later. The clustercredential the service uses downstream is held server-side and never travelsthrough this edge.@@ -18,7 +18,7 @@ from starlette.types import ASGIApp, Receive, Scope, Sendfrom sie_mcp.config import MCPConfig# The OAuth bridge endpoints bootstrap auth for claude.ai connectors, so they sit-# in front of the connector-secret gate (#1312). Metadata + DCR + authorize + token+# in front of the connector-secret gate. Metadata + DCR + authorize + token# must all be reachable unauthenticated._EXEMPT_PATHS = frozenset({diff --git a/packages/sie_mcp/src/sie_mcp/chunking.py b/packages/sie_mcp/src/sie_mcp/chunking.pyindex 5e0e545a7..fd208bccd 100644--- a/packages/sie_mcp/src/sie_mcp/chunking.py+++ b/packages/sie_mcp/src/sie_mcp/chunking.py@@ -1,9 +1,9 @@-"""Transient text chunking for ``answer_questions`` (#1309).+"""Transient text chunking for ``answer_questions``.SIE has no chunking pipeline today, so this is a deliberately small,self-contained primitive: a fixed-size sliding character window with overlap. Itruns entirely in the MCP edge per request — chunks are never persisted and no-index is built (the Req 12 "transient retrieval" boundary).+index is built, preserving a transient retrieval boundary.Character windows (not model-tokenizer windows) keep the job dependency-free andpredictable; sizes are expressed in characters and approximate a token budget atdiff --git a/packages/sie_mcp/src/sie_mcp/cli.py b/packages/sie_mcp/src/sie_mcp/cli.pyindex 0d7d7f1ae..ab046f2b0 100644--- a/packages/sie_mcp/src/sie_mcp/cli.py+++ b/packages/sie_mcp/src/sie_mcp/cli.py@@ -12,7 +12,7 @@ import uvicornfrom sie_mcp.plugin_pack import build_plugin_packfrom sie_mcp.skill_zip import build_skill_zip, skill_name-app = typer.Typer(name="sie-mcp", help="SIE MCP edge service (Req 12).", no_args_is_help=True)+app = typer.Typer(name="sie-mcp", help="SIE MCP edge service.", no_args_is_help=True)_PACKAGE_ROOT = Path(__file__).resolve().parents[2]_DEFAULT_SKILL_MD = _PACKAGE_ROOT / "plugin" / "SKILL.md"@@ -65,7 +65,7 @@ def skill_zip(typer.Option("--out", "-o", help="Output .zip path (default: dist/<name>-skill.zip)."),] = None,) -> None:- """Package the surface-agnostic Superlinked Agent Skill as a claude.ai-uploadable ZIP (#1312)."""+ """Package the surface-agnostic Superlinked Agent Skill as a claude.ai-uploadable ZIP."""if not skill.is_file():raise typer.BadParameter(f"SKILL.md not found at {skill}")text = skill.read_text(encoding="utf-8")@@ -83,7 +83,7 @@ def plugin_pack(typer.Option("--mcp-url",envvar="SIE_MCP_URL",- help="Hosted MCP endpoint to install, e.g. https://mcp.sie-test.example/mcp.",+ help="Hosted or self-hosted MCP endpoint to install, e.g. https://mcp.example.com/mcp.",),],connector_secret: Annotated[@@ -91,13 +91,16 @@ def plugin_pack(typer.Option("--connector-secret",envvar="SIE_MCP_CONNECTOR_SECRET",- help="Optional connector secret to print in INSTALL.md; prefer the env var to avoid shell history.",+ help=(+ "Deprecated compatibility input; ignored and never used, written, or printed. "+ "Provide the secret during connector installation."+ ),),] = None,cluster_label: Annotated[str,typer.Option("--cluster-label", help="Human-readable cluster label for the generated install guide."),- ] = "sie-test",+ ] = "sie-cluster",skill: Annotated[Path,typer.Option("--skill", "-s", help="Path to the surface-agnostic Superlinked SKILL.md to package."),@@ -118,7 +121,7 @@ def plugin_pack(typer.Option("--out-dir", "-o", help="Output directory for the plugin pack."),] = _PACKAGE_ROOT / "dist" / "superlinked-docs-plugin",) -> None:- """Build a quick install pack for a hosted/test-cluster Superlinked MCP edge."""+ """Build a quick install pack for a hosted or self-hosted Superlinked MCP edge."""if not skill.is_file():raise typer.BadParameter(f"SKILL.md not found at {skill}")cowork_text = Nonediff --git a/packages/sie_mcp/src/sie_mcp/config.py b/packages/sie_mcp/src/sie_mcp/config.pyindex 50c3f3365..07a343619 100644--- a/packages/sie_mcp/src/sie_mcp/config.py+++ b/packages/sie_mcp/src/sie_mcp/config.py@@ -1,8 +1,8 @@"""Environment-driven configuration for the SIE MCP edge service.The edge holds one server-side cluster credential (`SIE_API_KEY`) and validates-per-user connector secrets at its own boundary — the Req 12 auth shim. Real-per-user key issuance + metering integrates later via Req 10 (#1313).+per-user connector secrets at its own boundary. Issued per-user keys and metering+can integrate at that boundary later."""import os@@ -10,7 +10,7 @@ from dataclasses import dataclass_DEFAULT_BASE_URL = "http://localhost:8080"_DEFAULT_MODEL = "docling"-# answer_questions (#1309) model ids: dense encoder and cross-encoder reranker.+# answer_questions model ids: dense encoder and cross-encoder reranker.# The grounded-answer generator reuses _DEFAULT_GENERATE_MODEL (defined below)._DEFAULT_ENCODE_MODEL = "BAAI/bge-m3"_DEFAULT_RERANK_MODEL = "BAAI/bge-reranker-v2-m3"@@ -33,7 +33,7 @@ _DEFAULT_QA_MAX_CHUNKS = 2000_DEFAULT_CAPTION_MODEL = "microsoft/Florence-2-base-ft"# CLIP is the zero-shot default: it is contrastively trained for cosine ranking,# so client-side cosine/argmax separates labels cleanly. SigLIP's sigmoid-trained-# embeddings rank poorly under naive cosine (validated live on Modal) — override+# embeddings rank poorly under naive cosine — override# via SIE_MCP_EMBED_MODEL if you supply your own scoring._DEFAULT_EMBED_MODEL = "openai/clip-vit-base-patch32"_DEFAULT_IMAGE_TOP_K = 5@@ -74,9 +74,8 @@ DEFAULT_MAX_DOCUMENT_BYTES = 50 * 1024 * 1024# rendered to images. Override via SIE_MCP_MAX_IMAGE_BYTES.DEFAULT_MAX_IMAGE_BYTES = 20 * 1024 * 1024-# Provisional VL-OCR default for the scanned/complex-page quality upgrade (#1307).-# The committed OCR-engine choice is owned by Req 1's ADR (#955); pin MinerU2.5-Pro-# here as the demo default and re-source from #955 once that decision lands.+# Provisional VL-OCR default for scanned and complex pages. Pin MinerU2.5-Pro+# here as the demo default; deployments can override it through configuration.DEFAULT_VLOCR_MODEL = "opendatalab/MinerU2.5-Pro-2604-1.2B"# GLiNER models for extract_entities / redact_pii. Env-overridable (SIE_MCP_EXTRACT_MODEL@@ -200,7 +199,7 @@ class MCPConfig:qa_max_questions: intqa_max_chunks: int# claude.ai connectors are OAuth-only (no pasteable Bearer); the edge bridges- # the OAuth handshake onto the connector-secret shim (#1312). `public_base_url`+ # the OAuth handshake onto the connector-secret shim. `public_base_url`# pins the externally reachable origin used to build OAuth metadata URLs; when# unset it is derived per-request from forwarded host/proto headers.oauth_enabled: booldiff --git a/packages/sie_mcp/src/sie_mcp/describe.py b/packages/sie_mcp/src/sie_mcp/describe.pyindex df0e86d15..2f65b9af1 100644--- a/packages/sie_mcp/src/sie_mcp/describe.py+++ b/packages/sie_mcp/src/sie_mcp/describe.py@@ -1,4 +1,4 @@-"""``describe_image`` — the Req 12 image-understanding job (#1310).+"""The ``describe_image`` image-understanding job.Stateless orchestration over two existing SIE primitives, run entirelyclient-side in the MCP edge so the gateway and workers stay stateless perdiff --git a/packages/sie_mcp/src/sie_mcp/jobs.py b/packages/sie_mcp/src/sie_mcp/jobs.pyindex 47dbf7e48..8e177d6c1 100644--- a/packages/sie_mcp/src/sie_mcp/jobs.py+++ b/packages/sie_mcp/src/sie_mcp/jobs.py@@ -1,4 +1,4 @@-"""``docs_to_markdown`` — the Req 12 docs→markdown job (#1306, thickened in #1307).+"""The ``docs_to_markdown`` document-conversion job.Stateless orchestration over the SIE ``extract`` primitive: a document's bytes goto the cluster and come back as markdown. Docling is the front door for alldiff --git a/packages/sie_mcp/src/sie_mcp/oauth.py b/packages/sie_mcp/src/sie_mcp/oauth.pyindex 5bd590143..1eebe319e 100644--- a/packages/sie_mcp/src/sie_mcp/oauth.py+++ b/packages/sie_mcp/src/sie_mcp/oauth.py@@ -1,4 +1,4 @@-"""OAuth 2.0 bridge for the claude.ai connector surface (Req 12 #1312).+"""OAuth 2.0 bridge for the claude.ai connector surface.claude.ai custom connectors are OAuth-only — a user cannot paste a Bearer/connectorsecret into the connector UI the way the Cowork plugin bakes one into its header.@@ -8,17 +8,17 @@ page, and a token endpoint) and maps it onto the **existing** connector-secret sthe user types their connector secret on the authorize page, and the token endpointreturns that secret as the access token. claude.ai then sends it as``Authorization: Bearer <secret>`` and ``auth.authenticate`` validates it unchanged.-The MCP tools and the auth shim are untouched; #1313 (Req 10) later swaps the static-secret for real issued keys.+The MCP tools and the auth shim are untouched; the static connector secret can+later be replaced with issued keys.Security notes:- Connector secrets, authorization codes, and access tokens are NEVER logged.- PKCE is required; redirect URIs are validated against a configured allowlist.- Authorization codes are bound to the requesting ``client_id`` (when one ispresented), so a leaked code cannot be redeemed by a different public client.- Audience (``resource``) binding lands with real issued keys in #1313 (Req 10).+ Audience (``resource``) binding belongs with real issued keys.- Authorization codes are single-use and short-lived, held in-process (the edge runs- as a single uvicorn worker for the POC; a shared store is the Req 10 follow-up).+ as a single uvicorn worker; a multi-worker deployment requires a shared store)."""import base64diff --git a/packages/sie_mcp/src/sie_mcp/ocr_routing.py b/packages/sie_mcp/src/sie_mcp/ocr_routing.pyindex 17f104a0b..ca14d011f 100644--- a/packages/sie_mcp/src/sie_mcp/ocr_routing.py+++ b/packages/sie_mcp/src/sie_mcp/ocr_routing.py@@ -1,11 +1,11 @@-"""VL-OCR quality routing for ``docs_to_markdown`` (#1307).+"""VL-OCR quality routing for ``docs_to_markdown``.Born-digital documents convert cleanly through Docling, but scanned / image-onlypages carry no text layer for Docling to read — its built-in OCR is the baselinethis path improves on. We rasterize such pages and route them to a vision-language-OCR model (MinerU2.5-Pro, the provisional default pinned in :mod:`sie_mcp.config`;-the committed engine choice is owned by Req 1's OCR-engine ADR, #955), then stitch-the per-page markdown back together in page order.+OCR model (MinerU2.5-Pro, the provisional default pinned in+:mod:`sie_mcp.config`), then stitch the per-page markdown back together in page+order.Two return shapes have to be reconciled here: Docling fills``ExtractResult["data"]["markdown"]``, whereas MinerU returns generated text indiff --git a/packages/sie_mcp/src/sie_mcp/offload.py b/packages/sie_mcp/src/sie_mcp/offload.pyindex 2ea177822..41566684b 100644--- a/packages/sie_mcp/src/sie_mcp/offload.py+++ b/packages/sie_mcp/src/sie_mcp/offload.py@@ -1,4 +1,4 @@-"""MCP-backed document offload jobs adapted from the PR #1336 sie_tools skills."""+"""MCP-backed document offload jobs."""from __future__ import annotations@@ -110,7 +110,7 @@ async def summarize_document(gpu: str | None = None,max_output_tokens: int = SUMMARY_REDUCE_MAX_TOKENS,) -> dict[str, Any]:- """Summarize content on the SIE cluster using the PR #1336 map-reduce flow."""+ """Summarize content on the SIE cluster using a bounded map-reduce flow."""if not content.strip():raise OffloadError("content contains no text to summarize")diff --git a/packages/sie_mcp/src/sie_mcp/plugin_pack.py b/packages/sie_mcp/src/sie_mcp/plugin_pack.pyindex 897b4ac60..9176141ba 100644--- a/packages/sie_mcp/src/sie_mcp/plugin_pack.py+++ b/packages/sie_mcp/src/sie_mcp/plugin_pack.py@@ -1,4 +1,4 @@-"""Build a ready-to-share plugin install pack for a hosted SIE MCP edge."""+"""Build a ready-to-share plugin install pack for an SIE MCP edge."""from __future__ import annotations@@ -56,11 +56,14 @@ def build_plugin_pack(mcp_url: str,out_dir: Path,connector_secret: str | None = None,- cluster_label: str = "sie-test",+ cluster_label: str = "sie-cluster",claude_code_skill_mds: Iterable[str] = (),cowork_guide_md: str | None = None,) -> PluginPackReport:- """Write a hosted-cluster plugin pack: skill ZIP, Claude Code skill, and install guide."""+ """Write a plugin pack: skill ZIP, Claude Code skill, and install guide."""+ # Keep accepting the former keyword without using or persisting it. Users+ # provide connector credentials only at installation time.+ del connector_secretnormalized_url = normalize_mcp_url(mcp_url)name = skill_name(skill_md)@@ -83,7 +86,6 @@ def build_plugin_pack(render_install_guide(cluster_label=cluster_label,mcp_url=normalized_url,- connector_secret=connector_secret,skill_name_value=name,skill_zip_name=skill_zip.name,claude_code_skill_names=tuple(path.parent.name for path in claude_code_skills),@@ -128,48 +130,69 @@ def render_install_guide(*,cluster_label: str,mcp_url: str,- connector_secret: str | None,skill_name_value: str,skill_zip_name: str,claude_code_skill_names: tuple[str, ...],has_cowork_guide: bool,) -> str:"""Render endpoint-specific install instructions for the generated plugin pack."""- secret = connector_secret or "<connector-secret>"- auth_header = f"Authorization: Bearer {secret}"+ secret_placeholder = "<connector-secret-from-local-secret-store>" # noqa: S105 - non-secret placeholder.+ auth_header = f"Authorization: Bearer {secret_placeholder}"claude_code_add = ("claude mcp add --scope user --transport http "- f"{skill_name_value} {shlex.quote(mcp_url)} --header {shlex.quote(auth_header)}"+ f"{shlex.quote(skill_name_value)} {shlex.quote(mcp_url)} "+ '--header "Authorization: Bearer '+ '${SIE_MCP_CONNECTOR_SECRET:?set it from your local secret store}"'+ )+ claude_code_names = ", ".join(f"`{name}`" for name in claude_code_skill_names)+ claude_code_files = (+ f"- `claude-code/*/SKILL.md` - Claude Code skill files ({claude_code_names}).\n"+ if claude_code_skill_names+ else ""+ )+ claude_code_install = (+ "mkdir -p ~/.claude/skills\ncp -R claude-code/* ~/.claude/skills/\n" if claude_code_skill_names else ""+ )+ claude_code_skills_note = (+ "Restart Claude Code after adding the server and skills. "+ f"The included Claude Code skills ({claude_code_names}) call the MCP tools "+ "exposed by the edge directly. "+ if claude_code_skill_names+ else "Restart Claude Code after adding the server. "+ )+ redaction_note = (+ "The MCP redaction flow returns redacted text and counts, but not a local "+ "placeholder-to-original map; do not use it when de-redaction is required."+ if "redact-pii" in claude_code_skill_names+ else "")cowork_note = "- `cowork/superlinked.md` - Cowork/plugin install notes.\n" if has_cowork_guide else ""return (f"# Superlinked MCP plugin pack for {cluster_label}\n\n""This pack connects an agent surface to an already-running Superlinked MCP edge. "- "Use it for the hosted sie-test flow or any managed test cluster where an operator "- "has given you an MCP URL and connector secret. You do not need to deploy AWS infra.\n\n"+ "Use it for any hosted or self-hosted cluster where an operator has given you "+ "an MCP URL and connector secret.\n\n""## Files\n\n"f"- `{skill_zip_name}` - uploadable skill ZIP for claude.ai.\n"- f"- `claude-code/*/SKILL.md` - Claude Code skill files ({', '.join(claude_code_skill_names)}).\n"+ f"{claude_code_files}"f"{cowork_note}""\n""## Connector\n\n"f"- MCP endpoint: `{mcp_url}`\n"- f"- Connector secret: `{secret}`\n\n"- "The connector secret is used only in connector settings or the Claude Code MCP command. "- "It is not embedded in the skill ZIP or the Claude Code skill file.\n\n"+ "- Connector secret: retrieve it from your connector configuration or local secret store.\n\n"+ "No connector secret is embedded in any file in this pack. Keep it in connector settings "+ "or a local secret store; never paste it into chat.\n\n""## Claude Code\n\n"- "Run these commands from this directory:\n\n"+ "Load the secret into a local environment variable from your secret store, then run "+ "these commands from this directory. Do not save the value in this pack:\n\n""```bash\n"f"{claude_code_add}\n"- "mkdir -p ~/.claude/skills\n"- "cp -R claude-code/* ~/.claude/skills/\n"+ f"{claude_code_install}"+ "unset SIE_MCP_CONNECTOR_SECRET\n""```\n\n"- "Restart Claude Code after adding the server and skills. The Claude Code skills mirror "- "the PR #1336 parse, summarize, entity-extraction, and PII-redaction flows, but call "- "the MCP tools exposed by the Req 12 edge instead of the gateway-backed `sie_tools` CLI. "- "The MCP redaction flow returns redacted text and counts, but not a local "- "placeholder-to-original map; do not use it when de-redaction is required.\n\n"+ f"{claude_code_skills_note}"+ f"{redaction_note}\n\n""## claude.ai / Claude desktop app\n\n""1. Add a custom connector with the MCP endpoint above.\n""2. Click Connect and complete the OAuth sign-in. Enter the connector secret on the "diff --git a/packages/sie_mcp/src/sie_mcp/qa.py b/packages/sie_mcp/src/sie_mcp/qa.pyindex 238fcd0a4..c9d94e604 100644--- a/packages/sie_mcp/src/sie_mcp/qa.py+++ b/packages/sie_mcp/src/sie_mcp/qa.py@@ -1,4 +1,4 @@-"""``answer_questions`` — the Req 12 transient-QA job (#1309).+"""Transient question answering for ``answer_questions``.Grounded question answering over a document set too large to drop whole into asingle context window. Composed from shipped SIE primitives and run client-sidediff --git a/packages/sie_mcp/src/sie_mcp/savings.py b/packages/sie_mcp/src/sie_mcp/savings.pyindex d8b04841d..00bb10520 100644--- a/packages/sie_mcp/src/sie_mcp/savings.py+++ b/packages/sie_mcp/src/sie_mcp/savings.py@@ -4,11 +4,11 @@ Two distinct figures travel in the metadata; do not conflate them:- ``markdown_tokens_estimate`` — a LIVE, per-call estimate of *this* response'smarkdown, via a ~4 chars/token heuristic. Order-of-magnitude only.-- ``token_reduction`` — the COMMITTED #1311 measurement of markdown vs direct- document ingestion, copied verbatim from the benchmark run (AGENTS.md: never- ship perf claims without baseline data). The authoritative method is- ``count_tokens`` on the document block (text + one image per page) vs the SIE- markdown; full detail in ``benchmarks/token_reduction/results/latest.json``.+- ``token_reduction`` — the committed measurement of markdown vs direct+ document ingestion, copied verbatim from the benchmark run. The measurement+ compares+ ``count_tokens`` on the document block (text plus one image per page) with the+ SIE markdown."""import copy@@ -17,17 +17,17 @@ from typing import Any_CHARS_PER_TOKEN = 4 # rough Claude/GPT-family heuristic-# Committed token-reduction measurement — issue #1311, run 20260610T144234Z.-# Source of truth: benchmarks/token_reduction/results/latest.json. Every number-# below is copied verbatim from that committed run; re-run the benchmark to-# change them, never hand-edit (AGENTS.md: no fabricated/rounded perf claims).+# Committed token-reduction measurement from run 20260610T144234Z.+# Every number below is copied verbatim from that committed run; re-run the+# benchmark to change them; never hand-edit or round performance claims.# The dict is read-only; build_metadata deep-copies it so callers can't mutate it.-_BENCHMARK_PATH = "benchmarks/token_reduction/results/latest.json"_OPUS = "claude-opus-4-8"_SONNET = "claude-sonnet-4-6"_TOKEN_REDUCTION: dict[str, Any] = {- "source": _BENCHMARK_PATH,- "issue": 1311,+ "source": "committed benchmark run 20260610T144234Z",+ # The response shape retains this provenance slot, but no public issue+ # tracks the measurement.+ "issue": None,"run": "20260610T144234Z","method": ("count_tokens on the document block (text + one image per page, as "@@ -46,12 +46,12 @@ _blended = _TOKEN_REDUCTION["blended_reduction_pct"]_per_type = _TOKEN_REDUCTION["per_file_type_reduction_pct"]_NOTE = ("markdown_tokens_estimate is a live ~4 chars/token estimate of this response, "- "not a measured count. token_reduction is the committed #1311 measurement of "+ "not a measured count. token_reduction is the committed measurement of ""markdown vs direct document ingestion: blended "f"{_blended[_OPUS]}% (Opus 4.8, the conservative profile) and "f"{_blended[_SONNET]}% (Sonnet 4.6); per-file-type reductions span "f"{_per_type['min']}%-{_per_type['max']}% across both profiles "- f"(floor Opus/HTML, ceiling Sonnet/PPTX). See {_BENCHMARK_PATH}."+ f"(floor Opus/HTML, ceiling Sonnet/PPTX), measured in run {_TOKEN_REDUCTION['run']}.")diff --git a/packages/sie_mcp/src/sie_mcp/server.py b/packages/sie_mcp/src/sie_mcp/server.pyindex e50c6b4c9..b15dda5fc 100644--- a/packages/sie_mcp/src/sie_mcp/server.py+++ b/packages/sie_mcp/src/sie_mcp/server.py@@ -1,7 +1,7 @@-"""FastMCP server exposing the Req 12 document tools.+"""FastMCP server exposing document tools.-Tracer bullet (#1306): a single ``docs_to_markdown`` tool. The cluster client is-created once per process in the lifespan and reused across requests.+The cluster client is created once per process in the lifespan and reused across+requests."""import base64@@ -214,9 +214,7 @@ def build_server(config: MCPConfig) -> FastMCP:Provide exactly one of ``content``, ``content_base64``, or ``document_base64``.For source documents, pass raw file bytes as ``document_base64``; the edge first- converts them through ``docs_to_markdown`` and then summarizes the markdown. This- mirrors the PR #1336 summarize-document skill without routing through the- gateway-backed ``sie_tools`` CLI.+ converts them through ``docs_to_markdown`` and then summarizes the markdown.Args:content: Plain text/markdown content. Prefer ``content_base64`` for large files@@ -265,7 +263,7 @@ def build_server(config: MCPConfig) -> FastMCP:Provide labels such as ``["person", "organization", "date", "amount"]`` andexactly one of ``content``, ``content_base64``, or ``document_base64``. Document- inputs are converted to markdown first, matching the PR #1336 flow.+ inputs are converted to markdown first."""lifespan_ctx = ctx.request_context.lifespan_contextclient = lifespan_ctx["client"]diff --git a/packages/sie_mcp/src/sie_mcp/skill_zip.py b/packages/sie_mcp/src/sie_mcp/skill_zip.pyindex c25f26208..aa5a736d6 100644--- a/packages/sie_mcp/src/sie_mcp/skill_zip.py+++ b/packages/sie_mcp/src/sie_mcp/skill_zip.py@@ -1,4 +1,4 @@-"""Package the claude.ai Agent Skill as an uploadable ZIP (Req 12 #1312).+"""Package the claude.ai Agent Skill as an uploadable ZIP.claude.ai's two-piece install takes the remote MCP connector plus a **skill ZIP**.The platform requires the archive to contain a single top-level folder named afterdiff --git a/packages/sie_mcp/src/sie_mcp/structured.py b/packages/sie_mcp/src/sie_mcp/structured.pyindex f7bb98d8e..da91ed545 100644--- a/packages/sie_mcp/src/sie_mcp/structured.py+++ b/packages/sie_mcp/src/sie_mcp/structured.py@@ -1,4 +1,4 @@-"""``extract_structured`` + ``generate_structured`` — the Req 12 structured jobs (#1308).+"""Structured-output jobs for ``extract_structured`` and ``generate_structured``.Both produce schema/grammar-constrained output off the cluster via theOpenAI-compatible chat-completions surface (``response_format``), *not* the@@ -14,9 +14,8 @@ of a ``grammar_capability`` / ``unsupported_field`` round-trip.It also *post-validates* the cluster's response against the requested schema.Decode-time grammar enforcement is the primary guarantee, but a serving-layer-profile can bypass the grammar FSM (e.g. NEXTN speculative decoding on the-Qwen3.5 default profile — see ``tools/validate_mcp_structured_gpu.py`` and-#1302/#1231); when that happens the output is rejected with a clear error+profile can bypass the grammar FSM (for example, speculative decoding can+produce extra keys or truncated JSON); when that happens the output is rejected with a clear errorrather than returned as if it conformed."""@@ -120,7 +119,31 @@ def _is_outlines_backed(model: str) -> bool:return model in _OUTLINES_BACKED_MODELS-def _walk_schema(node: Any, *, path: str, depth: int, counter: list[int]) -> None:+def _schema_child_context(parent: str, key: str) -> str:+ """Map a parent schema context + child key to the child's context.++ Mirrors ``schema_child_context`` in the gateway+ (``packages/sie_gateway/src/handlers/grammar.rs``) and+ ``_schema_child_context`` in the server (``api/generate.py``). Keywords are+ only meaningful in a ``"schema"`` position; a ``properties`` /+ ``patternProperties`` / ``$defs`` map has *property names* for keys+ (``"schema_map"``), so a property literally named ``if`` / ``then`` / ``$ref``+ is data, not a keyword.+ """+ if parent == "schema":+ if key in {"properties", "patternProperties", "$defs", "definitions", "dependentSchemas"}:+ return "schema_map"+ if key in {"oneOf", "anyOf", "allOf", "prefixItems"}:+ return "schema_array"+ if key in {"items", "additionalProperties", "contains", "propertyNames", "not", "if", "then", "else"}:+ return "schema"+ return "other"+ if parent == "schema_map":+ return "schema"+ return "other"+++def _walk_schema(node: Any, *, path: str, depth: int, counter: list[int], context: str = "schema") -> None:# Mirror the gateway's per-node accounting: every visited value (objects,# array elements, scalars) counts toward ``_MAX_SCHEMA_NODES`` so a wide# schema is bounded even when it stays shallow.@@ -132,22 +155,35 @@ def _walk_schema(node: Any, *, path: str, depth: int, counter: list[int]) -> Nonmsg = f"output_schema nesting depth exceeds limit ({_MAX_SCHEMA_DEPTH}) at {path}"raise StructuredOutputError(msg)if isinstance(node, dict):- # Reject before descending so the message names the shallowest occurrence.- for kw in _UNSUPPORTED_KEYWORDS:- if kw in node:- detail = (- "'$ref' is not supported (the schema subset rejects all $ref, "- "including internal '#/...', so recursion is not expressible)"- if kw == "$ref"- else f"JSON Schema keyword '{kw}' is not supported by the Outlines subset"- )- raise StructuredOutputError(f"{detail} at {path}.{kw}")+ # Keywords are only rejected in an actual schema position. Under a+ # ``properties`` map (``"schema_map"``) the keys are property *names*+ # supplied by the caller, so a property named ``if`` / ``then`` / ``$ref``+ # is data and must not be treated as a keyword, matching the same+ # context-sensitive validation in the gateway and server.+ if context == "schema":+ # Reject before descending so the message names the shallowest occurrence.+ for kw in _UNSUPPORTED_KEYWORDS:+ if kw in node:+ detail = (+ "'$ref' is not supported (the schema subset rejects all $ref, "+ "including internal '#/...', so recursion is not expressible)"+ if kw == "$ref"+ else f"JSON Schema keyword '{kw}' is not supported by the Outlines subset"+ )+ raise StructuredOutputError(f"{detail} at {path}.{kw}")for key, child in node.items():- child_depth = depth + 1 if key in _SCHEMA_NESTING_KEYS else depth- _walk_schema(child, path=f"{path}.{key}", depth=child_depth, counter=counter)+ child_depth = depth + 1 if context == "schema" and key in _SCHEMA_NESTING_KEYS else depth+ _walk_schema(+ child,+ path=f"{path}.{key}",+ depth=child_depth,+ counter=counter,+ context=_schema_child_context(context, key),+ )elif isinstance(node, list):+ child_context = "schema" if context in {"schema", "schema_array"} else "other"for i, child in enumerate(node):- _walk_schema(child, path=f"{path}[{i}]", depth=depth, counter=counter)+ _walk_schema(child, path=f"{path}[{i}]", depth=depth, counter=counter, context=child_context)def validate_output_schema(schema: Any) -> None:@@ -177,17 +213,16 @@ def _validate_against_schema(data: Any, schema: dict[str, Any]) -> None:"""Post-validate cluster output against the requested schema (defense in depth).Decode-time grammar enforcement is the primary guarantee, but a serving- profile can bypass the grammar FSM (NEXTN speculative decoding on the- Qwen3.5 default profile leaks keys / truncates — see- ``tools/validate_mcp_structured_gpu.py`` and #1302/#1231). When the returned+ profile can bypass the grammar FSM (speculative decoding can produce extra+ keys or truncated JSON). When the returnedobject does not conform, raise rather than hand back non-conforming JSON asif it were schema-valid.``jsonschema`` is a guaranteed transitive dependency of the MCP edge- (``mcp`` → ``jsonschema``); it is imported lazily so ``structured.py`` stays- importable standalone by the GPU validation harness (which adds the source- to ``sys.path`` without installing the package). If it is somehow absent the- check is skipped — this layer is additive safety, not the only guard.+ (``mcp`` → ``jsonschema``); it is imported lazily to support lightweight+ standalone validation without installing the package. If it is somehow+ absent the check is skipped — this layer is additive safety, not the only+ guard."""try:import jsonschema # noqa: PLC0415 (lazy: keeps structured.py standalone-importable)diff --git a/packages/sie_mcp/tests/test_jobs.py b/packages/sie_mcp/tests/test_jobs.pyindex 03562b2da..7919fae9e 100644--- a/packages/sie_mcp/tests/test_jobs.py+++ b/packages/sie_mcp/tests/test_jobs.py@@ -45,12 +45,14 @@ async def test_returns_markdown_and_metadata() -> None:assert result["metadata"]["source_pages"] == 1assert result["metadata"]["markdown_tokens_estimated"] is Trueassert result["metadata"]["markdown_chars"] == len("# Title\n\nbody")- # Committed #1311 figures are wired in and trace back to the benchmark run.+ # Committed figures are wired in and trace back to the benchmark run.reduction = result["metadata"]["token_reduction"]+ assert reduction["source"] == "committed benchmark run 20260610T144234Z"+ assert reduction["issue"] is Noneassert reduction["run"] == "20260610T144234Z"assert reduction["blended_reduction_pct"] == {"claude-opus-4-8": 82.9, "claude-sonnet-4-6": 86.5}assert reduction["per_file_type_reduction_pct"] == {"min": 63.3, "max": 94.8}- assert reduction["source"].endswith("latest.json")+ assert "count_tokens" in reduction["method"]async def test_token_reduction_is_isolated_from_committed_figures() -> None:diff --git a/packages/sie_mcp/tests/test_plugin_pack.py b/packages/sie_mcp/tests/test_plugin_pack.pyindex dd8eb8a00..72c9720fd 100644--- a/packages/sie_mcp/tests/test_plugin_pack.py+++ b/packages/sie_mcp/tests/test_plugin_pack.py@@ -1,9 +1,19 @@+import base64import io+import os+import shlex+import subprocessimport zipfile+from dataclasses import asdictfrom pathlib import Path+from urllib.parse import quoteimport pytest-from sie_mcp.plugin_pack import build_plugin_pack, normalize_mcp_url+from click import Group+from sie_mcp.cli import app+from sie_mcp.plugin_pack import build_plugin_pack, normalize_mcp_url, render_install_guide+from typer.main import get_command+from typer.testing import CliRunner_SKILL_MD = """---name: superlinked-docs@@ -47,14 +57,40 @@ description: Redact PII through the Superlinked MCP edge.# Redact"""+_TEST_CONNECTOR_SECRET = "pack-secret/that+must?stay=local" # noqa: S105 - inert test fixture+++def _secret_encodings(secret: str) -> tuple[bytes, ...]:+ raw = secret.encode()+ return (+ raw,+ base64.b64encode(raw),+ base64.urlsafe_b64encode(raw),+ quote(secret, safe="").encode(),+ raw.hex().encode(),+ )+++def _assert_secret_absent(value: bytes | str, secret: str = _TEST_CONNECTOR_SECRET) -> None:+ contents = value.encode() if isinstance(value, str) else value+ for encoded in _secret_encodings(secret):+ assert encoded not in contents+++def _assert_pack_has_no_secret(out_dir: Path, secret: str = _TEST_CONNECTOR_SECRET) -> None:+ generated_files = tuple(path for path in out_dir.rglob("*") if path.is_file())+ assert generated_files+ for path in generated_files:+ _assert_secret_absent(path.read_bytes(), secret)+@pytest.mark.parametrize(("raw", "expected"),[- ("https://mcp.sie-test.example", "https://mcp.sie-test.example/mcp"),- ("https://mcp.sie-test.example/", "https://mcp.sie-test.example/mcp"),- ("https://mcp.sie-test.example/mcp/", "https://mcp.sie-test.example/mcp"),- ("https://mcp.sie-test.example/api/mcp", "https://mcp.sie-test.example/api/mcp"),+ ("https://mcp.example.com", "https://mcp.example.com/mcp"),+ ("https://mcp.example.com/", "https://mcp.example.com/mcp"),+ ("https://mcp.example.com/mcp/", "https://mcp.example.com/mcp"),+ ("https://mcp.example.com/api/mcp", "https://mcp.example.com/api/mcp"),],)def test_normalize_mcp_url(raw: str, expected: str) -> None:@@ -65,11 +101,11 @@ def test_normalize_mcp_url(raw: str, expected: str) -> None:"raw",["",- "mcp.sie-test.example/mcp",- "ftp://mcp.sie-test.example/mcp",- "https://mcp.sie-test.example/not-mcp",- "https://mcp.sie-test.example/mcp?secret=nope",- "https://mcp.sie-test.example/mcp#frag",+ "mcp.example.com/mcp",+ "ftp://mcp.example.com/mcp",+ "https://mcp.example.com/not-mcp",+ "https://mcp.example.com/mcp?secret=nope",+ "https://mcp.example.com/mcp#frag",],)def test_normalize_mcp_url_rejects_bad_values(raw: str) -> None:@@ -78,12 +114,10 @@ def test_normalize_mcp_url_rejects_bad_values(raw: str) -> None:def test_build_plugin_pack_writes_install_artifacts(tmp_path: Path) -> None:- connector_secret = "demo-connector-secret" # noqa: S105 - inert test fixturereport = build_plugin_pack(_SKILL_MD,- mcp_url="https://mcp.sie-test.example",- connector_secret=connector_secret,- cluster_label="sie-test",+ mcp_url="https://mcp.example.com",+ connector_secret=_TEST_CONNECTOR_SECRET,claude_code_skill_mds=[_EXTRACT_ENTITIES_SKILL_MD,_PARSE_DOCUMENT_SKILL_MD,@@ -94,7 +128,7 @@ def test_build_plugin_pack_writes_install_artifacts(tmp_path: Path) -> None:out_dir=tmp_path,)- assert report.mcp_url == "https://mcp.sie-test.example/mcp"+ assert report.mcp_url == "https://mcp.example.com/mcp"assert report.skill_name == "superlinked-docs"assert report.skill_zip == tmp_path / "superlinked-docs-skill.zip"assert report.claude_code_skill == tmp_path / "claude-code" / "superlinked-docs" / "SKILL.md"@@ -115,24 +149,78 @@ def test_build_plugin_pack_writes_install_artifacts(tmp_path: Path) -> None:assert report.cowork_guide.read_text(encoding="utf-8") == "# Cowork install\n"guide = report.install_guide.read_text(encoding="utf-8")- assert "https://mcp.sie-test.example/mcp" in guide- assert "demo-connector-secret" in guide+ assert "# Superlinked MCP plugin pack for sie-cluster" in guide+ assert "https://mcp.example.com/mcp" in guide+ _assert_pack_has_no_secret(tmp_path)+ _assert_secret_absent(repr(report))+ _assert_secret_absent(repr(asdict(report)))+ assert "${SIE_MCP_CONNECTOR_SECRET:?set it from your local secret store}" in guide+ assert "<connector-secret-from-local-secret-store>" in guideassert "claude mcp add --scope user --transport http superlinked-docs" in guideassert "cp -R claude-code/* ~/.claude/skills/" in guideassert "parse-document" in guideassert "summarize-document" in guideassert "extract-entities" in guideassert "redact-pii" in guide- assert "PR #1336" in guide+ assert (+ "The included Claude Code skills (`superlinked-docs`, `extract-entities`, `parse-document`, "+ "`redact-pii`, `summarize-document`)" in guide+ )assert "superlinked-docs-skill.zip" in guide+def test_plugin_router_uses_shell_safe_example_values() -> None:+ router = Path(__file__).parents[1] / "plugin" / "superlinked.md"+ guidance = router.read_text(encoding="utf-8")++ assert "<mcp-host>" not in guidance+ assert "<secret>" not in guidance+ assert "https://mcp.example.com/mcp" in guidance+ assert "'replace-with-connector-secret'" in guidance+ assert "`SIE_MCP_CONNECTOR_SECRET`" in guidance+ assert "client-side shell variable" in guidance+ assert "`SIE_MCP_CONNECTOR_SECRETS` runtime map" in guidance+++def test_public_mcp_command_examples_use_shell_safe_values() -> None:+ package_root = Path(__file__).parents[1]+ readme = (package_root / "README.md").read_text(encoding="utf-8")+ guidance = "\n".join(+ path.read_text(encoding="utf-8")+ for path in (package_root / "README.md", package_root / "docs" / "examples" / "mcp_smoke.py")+ )++ for placeholder in (+ "<cluster-api-key>",+ "<cluster-gateway>",+ "<cluster-name>",+ "<connector-secret>",+ "<mcp-host>",+ "<secret>",+ "<tag>",+ ):+ assert placeholder not in guidance+ assert "https://mcp.example.com/mcp" in guidance+ assert "'replace-with-connector-secret'" in guidance+ assert "export SIE_MCP_PUBLIC_URL='https://mcp.example.com'" in readme+++def test_helm_and_plugin_pack_examples_share_one_local_only_demo_secret() -> None:+ repo_root = Path(__file__).parents[3]+ readme = (Path(__file__).parents[1] / "README.md").read_text(encoding="utf-8")+ helm_values = (repo_root / "deploy/helm/sie-cluster/values.yaml").read_text(encoding="utf-8")++ assert "`local-dev-secret` as a local-only demo connector secret" in readme+ assert '--from-literal=connector-secrets="local-dev-secret:local-dev"' in readme+ assert "SIE_MCP_CONNECTOR_SECRET='local-dev-secret'" in readme+ assert "Local-only demo example: `local-dev-secret:local-dev`" in helm_values++def test_build_plugin_pack_keeps_connector_secret_out_of_skill_zip(tmp_path: Path) -> None:- connector_secret = "secret-that-must-not-enter-the-skill" # noqa: S105 - inert test fixturereport = build_plugin_pack(_SKILL_MD,- mcp_url="https://mcp.sie-test.example/mcp",- connector_secret=connector_secret,+ mcp_url="https://mcp.example.com/mcp",+ connector_secret=_TEST_CONNECTOR_SECRET,out_dir=tmp_path,)@@ -141,14 +229,116 @@ def test_build_plugin_pack_keeps_connector_secret_out_of_skill_zip(tmp_path: Patskill_text = archive.read("superlinked-docs/SKILL.md").decode()assert names == ["superlinked-docs/SKILL.md"]- assert "secret-that-must-not-enter-the-skill" not in skill_text+ _assert_secret_absent(skill_text)+ _assert_pack_has_no_secret(tmp_path)def test_build_plugin_pack_uses_placeholder_when_secret_omitted(tmp_path: Path) -> None:- report = build_plugin_pack(_SKILL_MD, mcp_url="https://mcp.sie-test.example/mcp", out_dir=tmp_path)+ report = build_plugin_pack(_SKILL_MD, mcp_url="https://mcp.example.com/mcp", out_dir=tmp_path)++ guide = report.install_guide.read_text(encoding="utf-8")+ assert "Authorization: Bearer ${SIE_MCP_CONNECTOR_SECRET:?set it from your local secret store}" in guide+ assert "Authorization: Bearer <connector-secret-from-local-secret-store>" in guide+ assert "Claude Code skill files (`superlinked-docs`)" in guide+ assert "The included Claude Code skills (`superlinked-docs`)" in guide+ assert "parse-document" not in guide+ assert "summarize-document" not in guide+ assert "extract-entities" not in guide+ assert "redact-pii" not in guide++def test_generated_claude_command_cannot_run_with_unset_secret(tmp_path: Path) -> None:+ report = build_plugin_pack(_SKILL_MD, mcp_url="https://mcp.example.com/mcp", out_dir=tmp_path / "pack")guide = report.install_guide.read_text(encoding="utf-8")- assert "Authorization: Bearer <connector-secret>" in guide+ command = next(line for line in guide.splitlines() if line.startswith("claude mcp add "))+ invoked = tmp_path / "claude-invoked"+ script = (+ f"claude() {{ printf invoked > {shlex.quote(str(invoked))}; }}\nunset SIE_MCP_CONNECTOR_SECRET\n{command}\n"+ )+ env = os.environ.copy()+ env.pop("SIE_MCP_CONNECTOR_SECRET", None)++ result = subprocess.run( # noqa: S603 - executes the generated command in an isolated shell fixture.+ ["/bin/bash", "-c", script],+ check=False,+ capture_output=True,+ text=True,+ env=env,+ )++ assert result.returncode != 0+ assert not invoked.exists()+ assert "SIE_MCP_CONNECTOR_SECRET" in result.stderr+++def test_render_install_guide_omits_claude_code_skills_when_none_are_included() -> None:+ guide = render_install_guide(+ cluster_label="sie-cluster",+ mcp_url="https://mcp.example.com/mcp",+ skill_name_value="superlinked-docs",+ skill_zip_name="superlinked-docs-skill.zip",+ claude_code_skill_names=(),+ has_cowork_guide=False,+ )++ assert "claude-code/*/SKILL.md" not in guide+ assert "cp -R claude-code/* ~/.claude/skills/" not in guide+ assert "Claude Code skill files" not in guide+ assert "The included Claude Code skills" not in guide+ assert "Restart Claude Code after adding the server." in guide+++def test_plugin_pack_cli_never_emits_or_persists_connector_secret(tmp_path: Path) -> None:+ result = CliRunner(mix_stderr=False).invoke(+ app,+ [+ "plugin-pack",+ "--mcp-url",+ "https://mcp.example.com/mcp",+ "--connector-secret",+ _TEST_CONNECTOR_SECRET,+ "--out-dir",+ str(tmp_path),+ ],+ )++ assert result.exit_code == 0, result.output+ _assert_secret_absent(result.output)+ _assert_secret_absent(result.stdout)+ _assert_secret_absent(result.stderr)+ _assert_secret_absent(repr(result.exception))+ _assert_pack_has_no_secret(tmp_path)+++def test_plugin_pack_cli_exception_never_emits_connector_secret(tmp_path: Path) -> None:+ result = CliRunner(mix_stderr=False).invoke(+ app,+ [+ "plugin-pack",+ "--mcp-url",+ "not-an-http-url",+ "--connector-secret",+ _TEST_CONNECTOR_SECRET,+ "--out-dir",+ str(tmp_path),+ ],+ )++ assert result.exit_code != 0+ _assert_secret_absent(result.output)+ _assert_secret_absent(result.stdout)+ _assert_secret_absent(result.stderr)+ _assert_secret_absent(repr(result.exception))+++def test_plugin_pack_help_describes_both_endpoint_types() -> None:+ root_command = get_command(app)+ assert isinstance(root_command, Group)+ mcp_url_option = next(+ parameter for parameter in root_command.commands["plugin-pack"].params if parameter.name == "mcp_url"+ )++ assert mcp_url_option.help == "Hosted or self-hosted MCP endpoint to install, e.g. https://mcp.example.com/mcp."def test_build_plugin_pack_refreshes_claude_code_skills(tmp_path: Path) -> None:@@ -156,7 +346,7 @@ def test_build_plugin_pack_refreshes_claude_code_skills(tmp_path: Path) -> None:stale.parent.mkdir(parents=True)stale.write_text("old", encoding="utf-8")- build_plugin_pack(_SKILL_MD, mcp_url="https://mcp.sie-test.example/mcp", out_dir=tmp_path)+ build_plugin_pack(_SKILL_MD, mcp_url="https://mcp.example.com/mcp", out_dir=tmp_path)assert not stale.exists()assert (tmp_path / "claude-code" / "superlinked-docs" / "SKILL.md").exists()diff --git a/packages/sie_mcp/tests/test_structured.py b/packages/sie_mcp/tests/test_structured.pyindex edc97245e..ac9feed86 100644--- a/packages/sie_mcp/tests/test_structured.py+++ b/packages/sie_mcp/tests/test_structured.py@@ -80,6 +80,44 @@ def test_accepts_schema_at_depth_limit() -> None:validate_output_schema(leaf) # no raise+def test_accepts_property_names_colliding_with_keywords() -> None:+ # A property *name* that collides with a JSON-Schema keyword is data, not a+ # keyword: under ``properties`` the keys are caller-supplied names. The subset+ # walk must accept them, matching the gateway and server validators.+ schema = {+ "type": "object",+ "properties": {+ "if": {"type": "string"},+ "then": {"type": "string"},+ "else": {"type": "string"},+ "$ref": {"type": "string"},+ "dependentSchemas": {"type": "boolean"},+ "unevaluatedProperties": {"type": "integer"},+ },+ }+ validate_output_schema(schema) # no raise+++def test_accepts_keyword_named_property_nested_in_pattern_properties() -> None:+ # ``patternProperties`` is also a schema-map: its keys are patterns (data),+ # so a keyword-named pattern key must be accepted. Using ``then`` here is+ # deliberate — if ``patternProperties`` were walked as a *schema* context+ # instead of ``schema_map``, this key would be rejected as a keyword.+ schema = {+ "type": "object",+ "patternProperties": {"then": {"type": "object", "properties": {"if": {"type": "string"}}}},+ }+ validate_output_schema(schema) # no raise+++def test_rejects_keyword_in_real_schema_position_under_properties() -> None:+ # The gate must not over-accept: a genuine keyword sitting in a *schema*+ # position (the value of a property is a schema) is still rejected.+ schema = {"type": "object", "properties": {"a": {"type": "object", "if": {"x": True}}}}+ with pytest.raises(StructuredOutputError, match="if"):+ validate_output_schema(schema)++# ── gateway safety caps (mirror handlers/grammar.rs) ─────────────────────diff --git a/packages/sie_sdk/CONTRIBUTING.md b/packages/sie_sdk/CONTRIBUTING.mdindex 2aefc2965..f3dc3c558 100644--- a/packages/sie_sdk/CONTRIBUTING.md+++ b/packages/sie_sdk/CONTRIBUTING.md@@ -14,12 +14,12 @@ mise trust && mise install## Running Tests```bash-mise run test packages/sie_sdk+mise run test -- packages/sie_sdk```## Code Style-- Format with `mise run lint -f`+- Format with `mise run lint -- -f`- Type check with `mise run typecheck`## Pull Requestsdiff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.mdindex 6ed9c2078..7cd1400ad 100644--- a/packages/sie_sdk/README.md+++ b/packages/sie_sdk/README.md@@ -16,16 +16,101 @@ from sie_sdk.types import Itemclient = SIEClient("http://localhost:8080")-# Encode text+# Encode text. Results are TypedDicts — access fields by key.result = client.encode("BAAI/bge-m3", Item(text="Hello world"))-print(result.dense) # [0.1, 0.2, ...]+print(result["dense"].shape) # (1024,)++# Score items against a query with a reranker model.+# Scores come back sorted by relevance (rank 0 = most relevant).+scores = client.score(+ "BAAI/bge-reranker-v2-m3",+ query=Item(text="What is machine learning?"),+ items=[+ Item(id="doc-1", text="Machine learning is a subfield of AI."),+ Item(id="doc-2", text="Python is a programming language."),+ ],+)+for entry in scores["scores"]:+ print(entry["item_id"], entry["score"])+```++## Connecting to a managed SIE platform++The examples above target a local server. For a managed SIE gateway,+pass the gateway URL as `base_url` and your API key (sent as a Bearer+token):++```python+from sie_sdk import SIEClient-# Score pairs-scores = client.score("cross-encoder", [- (Item(text="query"), Item(text="document"))-])+client = SIEClient(+ "https://your-gateway.example.com",+ api_key="YOUR_API_KEY",+)```+## Object storage and model caches++Install the `storage` extra to use `s3://`, `gs://`, `abfs(s)://`, or native+Alibaba `oss://` model/cache paths:++```bash+pip install 'sie-sdk[storage]'+```++Alibaba OSS always uses region-scoped Signature V4. Set `SIE_OSS_REGION` to+the bucket's region (for example, `eu-central-1`). Set+`SIE_OSS_USE_INTERNAL_ENDPOINT=true` only inside the matching Alibaba Cloud+network; the SDK derives the HTTPS endpoint and does not accept endpoint URLs+from storage paths.++On ACK, RRSA supplies `ALIBABA_CLOUD_ROLE_ARN`,+`ALIBABA_CLOUD_OIDC_PROVIDER_ARN`, and `ALIBABA_CLOUD_OIDC_TOKEN_FILE`. The SDK+requires all three together and refreshes short-lived credentials through the+Alibaba Credentials client. Local operators can use that client's standard+credential sources instead. Never place credentials, queries, or fragments in+an `oss://` URL.++`oss://` is supported for model discovery, cache population, and object copies.+It is deliberately not a mutable `sie-config` epoch store because OSS+PutObject cannot provide the required non-empty ETag compare-and-swap contract;+use local/PVC, S3, GCS, or Azure storage for that store.++## Error handling++Server-reported errors are raised as typed exceptions from+`sie_sdk.client.errors`; all inherit from `SIEError`, and errors that+carry a server response expose `.code` and `.status_code`. Invalid+client-side arguments (for example, a bad `base_url_headers` value)+raise ordinary Python exceptions such as `ValueError`.++Several `503` codes are transient and retried automatically (see the+next section for the `RESOURCE_EXHAUSTED` budget):++- `PROVISIONING` — the cluster is scaling capacity from zero. Retry is+ governed by `wait_for_capacity`: retried under `provision_timeout_s`+ when `True` (the default); surfaces immediately as+ `ProvisioningError` when `False`.+- `MODEL_LOADING` — the worker accepted the request and is cold-loading+ the target model. Retried until `provision_timeout_s`; raises+ `ModelLoadingError` if the budget is exhausted.+- `LORA_LOADING` — the requested LoRA adapter is still loading. Retried+ a bounded number of times; raises `LoraLoadingError` when the retry+ budget is exhausted.+- `RESOURCE_EXHAUSTED` — the server ran out of GPU memory and exhausted+ its internal recovery. Retried with bounded backoff; raises+ `ResourceExhaustedError` when retries run out. Pass+ `max_oom_retries=0` to disable these retries and fail fast.++One generation-specific error is terminal and never retried:++- `empty_model_output` — the generation finished nominally but produced+ no visible output text (for example, private reasoning consumed the+ whole token budget). Tokens were genuinely consumed, so the request+ is not re-run. Surfaces as `ServerError` with+ `code == "empty_model_output"`; on streaming calls it is raised+ mid-stream with the gateway request id attached for correlation.+## Handling resource exhaustionThe SDK automatically retries requests that the server signals asdiff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex 3f523aa2f..80db89cc4 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.7.1"+version = "0.7.2"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }@@ -27,11 +27,13 @@ dependencies = [[project.optional-dependencies]storage = [+ "alibabacloud-credentials>=1.0.12,<2","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,<2",+ "oss2>=2.19.1,<3",]langchain = ["langchain-core>=0.3,<1"]llamaindex = ["llama-index-core>=0.12,<1"]diff --git a/packages/sie_sdk/src/sie_sdk/__init__.py b/packages/sie_sdk/src/sie_sdk/__init__.pyindex 35b535e22..a79da5101 100644--- a/packages/sie_sdk/src/sie_sdk/__init__.py+++ b/packages/sie_sdk/src/sie_sdk/__init__.py@@ -3,7 +3,7 @@Example:>>> from sie_sdk import SIEClient>>> client = SIEClient("http://localhost:8080")- >>> result = client.encode("bge-m3", {"text": "Hello world"})+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello world"})>>> result["dense"] # np.ndarray, shape [1024]For ColBERT/late interaction models, use the scoring module:@@ -12,19 +12,27 @@ For ColBERT/late interaction models, use the scoring module:"""from sie_sdk.client import (+ AccountInactiveError,+ AccountStateUnavailableError,EstimateUnroutableError,+ IncompleteBatchError,InputTooLongError,+ InsufficientCreditsError,+ JobFailedError,LoraLoadingError,ModelLoadFailedError,ModelLoadingError,PoolError,ProvisioningError,+ RateLimitError,RequestError,+ ResourceExhaustedError,ServerError,SIEAsyncClient,SIEClient,SIEConnectionError,SIEError,+ SpendLimitError,)from sie_sdk.encoding import (SparseVector,@@ -34,8 +42,9 @@ from sie_sdk.encoding import (sparse_embedding,sparse_embedding_dict,)+from sie_sdk.exceptions import GatedModelErrorfrom sie_sdk.files import resolve_upload-from sie_sdk.jobs import build_job_body, connection_name+from sie_sdk.jobs import MalformedChunkError, build_job_body, connection_namefrom sie_sdk.types import (# Response typesAppliedRate,@@ -93,6 +102,8 @@ from sie_sdk.types import (__version__ = "0.1.0"__all__ = [+ "AccountInactiveError",+ "AccountStateUnavailableError","AppliedRate","AssignedWorkerInfo","Batch",@@ -116,13 +127,17 @@ __all__ = ["File","FileDeleted","FileList",+ "GatedModelError","GenerateChunk","GenerateResult","GenerationUsage","HealthResponse",+ "IncompleteBatchError","InputTooLongError",+ "InsufficientCreditsError","Item","JobChunk",+ "JobFailedError","JobFieldMap","JobList","JobResultItem",@@ -131,6 +146,7 @@ __all__ = ["JobStatus","JobSubmitResult","LoraLoadingError",+ "MalformedChunkError","ModelInfo","ModelLoadFailedError","ModelLoadingError",@@ -144,7 +160,9 @@ __all__ = ["PoolStatusInfo","ProvisioningError","RateIdentity",+ "RateLimitError","RequestError",+ "ResourceExhaustedError","SIEAsyncClient","SIEClient","SIEConnectionError",@@ -153,6 +171,7 @@ __all__ = ["ServerError","SparseResult","SparseVector",+ "SpendLimitError","StatusMessage","TimingInfo","WorkerInfo",diff --git a/packages/sie_sdk/src/sie_sdk/_msgpack.py b/packages/sie_sdk/src/sie_sdk/_msgpack.pynew file mode 100644index 000000000..b14af6100--- /dev/null+++ b/packages/sie_sdk/src/sie_sdk/_msgpack.py@@ -0,0 +1,132 @@+"""Numeric-only MessagePack helpers for SDK request and response bodies."""++from __future__ import annotations++from collections.abc import Mapping+from importlib import import_module+from typing import Any++import numpy as np++try:+ _native_msgpack = import_module("msgpack._cmsgpack")+except ImportError: # pragma: no cover - msgpack wheels use the C extension.+ _native_msgpack = import_module("msgpack.fallback")++_NativePacker = _native_msgpack.Packer+_native_unpackb = _native_msgpack.unpackb+++_NUMERIC_DTYPE_CODES = frozenset(+ {+ "<f2",+ "<f4",+ "<f8",+ "<i2",+ "<i4",+ "<i8",+ "<u2",+ "<u4",+ "<u8",+ ">f2",+ ">f4",+ ">f8",+ ">i2",+ ">i4",+ ">i8",+ ">u2",+ ">u4",+ ">u8",+ "|b1",+ "|i1",+ "|u1",+ }+)+_MAX_NUMPY_DIMENSIONS = 8+++class UnsafeMessagePackError(ValueError):+ """A MessagePack NumPy sentinel is outside the SDK's numeric wire contract."""+++def _numeric_dtype(value: object) -> np.dtype[Any]:+ if not isinstance(value, str) or value not in _NUMERIC_DTYPE_CODES:+ raise UnsafeMessagePackError("MessagePack NumPy dtype is not an allowed numeric dtype")+ dtype = np.dtype(value)+ if dtype.hasobject or dtype.fields is not None or dtype.subdtype is not None:+ raise UnsafeMessagePackError("MessagePack NumPy dtype is not a flat numeric dtype")+ return dtype+++def _numeric_default(value: object) -> Mapping[bytes, object]:+ if isinstance(value, np.ndarray):+ dtype = _numeric_dtype(value.dtype.str)+ contiguous = np.ascontiguousarray(value, dtype=dtype)+ return {+ b"nd": True,+ b"type": dtype.str,+ b"kind": b"",+ b"shape": contiguous.shape,+ b"data": contiguous.tobytes(),+ }+ if isinstance(value, np.generic):+ dtype = _numeric_dtype(value.dtype.str)+ return {+ b"nd": False,+ b"type": dtype.str,+ b"data": value.tobytes(),+ }+ raise TypeError(f"cannot MessagePack-encode {type(value).__name__}")+++def packb(value: object, *, use_bin_type: bool = True) -> bytes:+ """Pack one SDK body without installing process-global NumPy hooks."""+ return _NativePacker(default=_numeric_default, use_bin_type=use_bin_type).pack(value)+++def _numeric_object_hook(value: dict[object, object]) -> object:+ if b"nd" not in value:+ if b"complex" in value:+ raise UnsafeMessagePackError("complex MessagePack NumPy values are not supported")+ return value++ is_array = value.get(b"nd")+ if not isinstance(is_array, bool):+ raise UnsafeMessagePackError("MessagePack NumPy nd marker must be boolean")+ if value.get(b"kind", b"") not in {b"", ""}:+ # In particular, kind=O invokes pickle.loads in msgpack-numpy and+ # kind=V admits attacker-selected structured dtype descriptors.+ raise UnsafeMessagePackError("object and structured MessagePack NumPy values are not supported")++ dtype = _numeric_dtype(value.get(b"type"))+ data = value.get(b"data")+ if not isinstance(data, bytes):+ raise UnsafeMessagePackError("MessagePack NumPy data must be bytes")++ if not is_array:+ if len(data) != dtype.itemsize:+ raise UnsafeMessagePackError("MessagePack NumPy scalar byte length does not match its dtype")+ return np.frombuffer(data, dtype=dtype, count=1)[0]++ raw_shape = value.get(b"shape")+ if not isinstance(raw_shape, list) or len(raw_shape) > _MAX_NUMPY_DIMENSIONS:+ raise UnsafeMessagePackError("MessagePack NumPy array shape is malformed")+ shape: list[int] = []+ elements = 1+ for raw_dimension in raw_shape:+ if not isinstance(raw_dimension, int) or isinstance(raw_dimension, bool) or raw_dimension < 0:+ raise UnsafeMessagePackError("MessagePack NumPy array dimension is malformed")+ dimension = int(raw_dimension)+ elements *= dimension+ shape.append(dimension)+ if elements * dtype.itemsize != len(data):+ raise UnsafeMessagePackError("MessagePack NumPy array byte length does not match its shape")+ return np.frombuffer(data, dtype=dtype).reshape(tuple(shape))+++def unpackb(value: bytes, *, numeric_arrays: bool) -> Any:+ """Unpack one untrusted body with optional numeric-only NumPy decoding."""+ kwargs: dict[str, Any] = {"raw": False}+ if numeric_arrays:+ kwargs["object_hook"] = _numeric_object_hook+ return _native_unpackb(value, **kwargs)diff --git a/packages/sie_sdk/src/sie_sdk/cache.py b/packages/sie_sdk/src/sie_sdk/cache.pyindex 7e9f5525d..ae400d113 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/Azure object storage)+2. Cluster cache (S3/GCS/Azure/Alibaba OSS 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://, gs://, abfs://, or abfss://), or None if not configured."""+ """Cluster cache URL (s3://, gs://, abfs(s)://, or oss://), 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://, gs://, abfs://, or abfss://)+ SIE_CLUSTER_CACHE: Cluster cache URL (s3://, gs://, abfs(s)://, or oss://)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/Azure object-store URL+ # Cluster cache: S3/GCS/Azure/Alibaba OSS object-store URLcluster_cache = os.environ.get("SIE_CLUSTER_CACHE")# HF fallback: default true@@ -377,7 +377,7 @@ def populate_cluster_cache() -> bool:"""Upload model from local cache to cluster cache.- Used by sie-admin to pre-populate cluster cache. Inverse of+ Used by cluster-management clients to pre-populate cluster cache. Inverse of:func:`_download_from_cluster_cache`: the model's HF-style cachedirectory (``models--{org}--{name}``) is mirrored recursively to thesame folder name under ``config.cluster_cache``, so workers hydratingdiff --git a/packages/sie_sdk/src/sie_sdk/client/__init__.py b/packages/sie_sdk/src/sie_sdk/client/__init__.pyindex 92c957f4f..9e12cd1e7 100644--- a/packages/sie_sdk/src/sie_sdk/client/__init__.py+++ b/packages/sie_sdk/src/sie_sdk/client/__init__.py@@ -5,32 +5,48 @@ Re-exports all client classes and errors for backwards compatibility.from sie_sdk.client.async_ import SIEAsyncClientfrom sie_sdk.client.errors import (+ AccountInactiveError,+ AccountStateUnavailableError,EstimateUnroutableError,+ IncompleteBatchError,InputTooLongError,+ InsufficientCreditsError,+ JobFailedError,LoraLoadingError,ModelLoadFailedError,ModelLoadingError,PoolError,ProvisioningError,+ RateLimitError,RequestError,+ ResourceExhaustedError,ServerError,SIEConnectionError,SIEError,+ SpendLimitError,)from sie_sdk.client.sync import SIEClient__all__ = [+ "AccountInactiveError",+ "AccountStateUnavailableError","EstimateUnroutableError",+ "IncompleteBatchError","InputTooLongError",+ "InsufficientCreditsError",+ "JobFailedError","LoraLoadingError","ModelLoadFailedError","ModelLoadingError","PoolError","ProvisioningError",+ "RateLimitError","RequestError",+ "ResourceExhaustedError","SIEAsyncClient","SIEClient","SIEConnectionError","SIEError","ServerError",+ "SpendLimitError",]diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex 66adb6be6..49a94a6d0 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -13,12 +13,13 @@ from datetime import UTC, datetimefrom email.utils import parsedate_to_datetimefrom importlib.metadata import PackageNotFoundErrorfrom importlib.metadata import version as pkg_version-from typing import Any, Protocol, cast-from urllib.parse import urljoin, urlsplit+from typing import Any, NoReturn, Protocol, cast+from urllib.parse import parse_qsl, urljoin, urlsplit-import msgpackimport numpy as np+from msgpack.exceptions import UnpackException+from sie_sdk._msgpack import unpackb as unpack_msgpackfrom sie_sdk.images import convert_item_images_logger = logging.getLogger(__name__)@@ -26,7 +27,9 @@ _logger = logging.getLogger(__name__)_HTTP_HEADER_NAME = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")_HTTP_MEDIA_TYPE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+/[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")-_CONTENT_SAFE_MEDIA_TYPES = frozenset({"application/json", "application/problem+json", "text/html"})+_CONTENT_SAFE_MEDIA_TYPES = frozenset(+ {"application/json", "application/msgpack", "application/problem+json", "text/html"}+)_RESERVED_BASE_URL_HEADERS = frozenset({"accept",@@ -49,6 +52,8 @@ _RESERVED_BASE_URL_HEADERS = frozenset("x-sie-sdk-version",})+MODAL_CONTINUATION_MAX_HOPS = 20+_MODAL_CONTINUATION_QUERY_PARAMETER = "__modal_attempt_token"def copy_base_url_headers(headers: Mapping[str, str] | None) -> dict[str, str]:@@ -112,6 +117,46 @@ def base_url_accepts_origin_credentials(base_url: str) -> bool:return origin is not None and origin[0] == "https"+def validate_base_url(base_url: str) -> None:+ """Reject a malformed ``base_url`` at construction.++ A scheme-less URL such as ``"localhost:8080"`` would otherwise surface+ only at request time as an opaque transport error+ (``httpx.UnsupportedProtocol`` on the sync client), or — worse — be+ silently retried as a "connect" failure for the whole provision budget.+ A hostless URL such as ``"http:///v1"`` parses with a valid scheme but an+ empty host, which cannot be connected to; reject it here too. A textual or+ out-of-range port (``"http://host:notaport"``, ``"http://host:99999"``)+ likewise fails here rather than at request time.+ """+ parts = urlsplit(base_url)+ msg = (+ "base_url must be an absolute http:// or https:// URL with a host "+ f"(e.g. 'http://localhost:8080'), got {base_url!r}"+ )+ if parts.scheme not in {"http", "https"} or not parts.hostname:+ raise ValueError(msg)+ try:+ # ``urlsplit`` validates the port lazily, on access.+ _ = parts.port+ except ValueError as exc:+ raise ValueError(msg) from exc+++def url_origin_for_logging(url: str) -> str:+ """Return only the ``scheme://host[:port]`` origin of ``url``.++ Path, query, fragment, and any ``user:password@`` userinfo are dropped, so+ a ``base_url`` carrying embedded credentials or a token query parameter+ never reaches a log line. The value is+ for logging only — callers still issue requests against the real URL.+ """+ parts = urlsplit(url)+ host = parts.hostname or ""+ netloc = f"{host}:{parts.port}" if parts.port is not None else host+ return f"{parts.scheme}://{netloc}" if parts.scheme else netloc++def request_matches_base_url_origin(base_url: str, request_url: str) -> bool:"""Whether ``request_url`` resolves to the exact HTTP origin of ``base_url``."""base_origin = _http_origin(base_url)@@ -121,6 +166,40 @@ def request_matches_base_url_origin(base_url: str, request_url: str) -> bool:return _http_origin(resolved) == base_origin+def modal_continuation_path(base_url: str, response: _HttpResponse) -> str | None:+ """Return a safe edge-relative Modal result URL for an HTTP 303.++ Modal turns a web request that exceeds 150 seconds into a 303 whose+ ``Location`` identifies the *same in-flight request*. Following that+ result URL with GET consumes the original response; it does not replay the+ non-idempotent POST. Only the documented attempt-token shape on the exact+ configured origin is accepted so SDK credentials can never cross an+ origin boundary.+ """+ if response.status_code != 303:+ return None+ location = _header_value(response.headers, "Location")+ if not isinstance(location, str) or not location or len(location) > 8192:+ return None+ if any(ord(char) < 0x20 or ord(char) == 0x7F for char in location):+ return None++ resolved = urljoin(f"{base_url.rstrip('/')}/", location)+ if not request_matches_base_url_origin(base_url, resolved):+ return None+ try:+ parsed = urlsplit(resolved)+ query = parse_qsl(parsed.query, keep_blank_values=True, max_num_fields=100)+ except ValueError:+ return None+ tokens = [value for key, value in query if key == _MODAL_CONTINUATION_QUERY_PARAMETER]+ if parsed.fragment or len(tokens) != 1 or not tokens[0]:+ return None++ path = parsed.path or "/"+ return f"{path}?{parsed.query}" if parsed.query else path++def websocket_matches_base_url_origin(base_url: str, websocket_url: str) -> bool:"""Whether a ws(s) URL is the WebSocket counterpart of ``base_url``'s origin."""parsed = urlsplit(websocket_url)@@ -160,14 +239,20 @@ from sie_sdk.types import ()from .errors import (+ AccountInactiveError,+ AccountStateUnavailableError,EstimateUnroutableError,+ IncompleteBatchError,InputTooLongError,+ InsufficientCreditsError,ModelLoadFailedError,ModelLoadingError,ProvisioningError,+ RateLimitError,RequestError,ResourceExhaustedError,ServerError,+ SpendLimitError,)# Content types@@ -187,6 +272,12 @@ HTTP_GATEWAY_TIMEOUT = 504JOB_RESULT_NOT_FOUND_ERROR_CODE = "RESULT_NOT_FOUND"JOB_RESULT_REF_MAX_REFRESHES = 3+# jobs.results() decodes chunk refs into per-item results. A non-terminal job+# has no stable result set: its ref list is still growing, so decoding one would+# return a partial subset indistinguishable from a partial-FAILURE subset. The+# SDK refuses with this code rather than return a misleading partial.+JOB_NOT_TERMINAL_ERROR_CODE = "job_not_terminal"+_GENERATE_GRAMMAR_VARIANTS = frozenset({"json_schema", "regex", "ebnf"})_GENERATE_GRAMMAR_FIELDS = _GENERATE_GRAMMAR_VARIANTS | {"label", "strict"}@@ -277,6 +368,7 @@ INPUT_TOO_LONG_ERROR_CODE = "INPUT_TOO_LONG"# ── cost-estimate dry run (POST /v1/estimate, #2435) ──────────────────────ESTIMATE_PATH = "/v1/estimate"+RECOMMEND_PATH = "/v1/recommend"# The gateway answers an unpriced/unroutable identity with the SAME code the# live billing path uses for "this request cannot be priced, so it will not be# run". Both are mapped to ``EstimateUnroutableError``; a slab-capacity 503@@ -348,6 +440,43 @@ RESOURCE_EXHAUSTED_DEFAULT_DELAY_S = 5.0RESOURCE_EXHAUSTED_MAX_DELAY_S = 30.0RESOURCE_EXHAUSTED_ERROR_CODE = "RESOURCE_EXHAUSTED"+# ── Pre-execution admission backpressure / billing signals (pass-2 audit) ──+# All of these are emitted BEFORE any work is published to the queue, so+# retrying them is idempotent even on the non-idempotent generate paths. They+# are honored on the SDK's admission ladder (:func:`admission_retry_delay`),+# bounded by the caller's ``provision_timeout_s`` budget and the server's+# ``Retry-After``. Kept deliberately separate from the 402/403 credit/account+# errors below, which are TERMINAL and must NEVER be retried.+#+# B1 — 429 rate limit (rate_limit.rs): per-key/per-account, default-on. The+# gateway always supplies a ``Retry-After``; the SDK honors it and gives up as+# a typed :class:`RateLimitError` when the budget is spent.+HTTP_TOO_MANY_REQUESTS = 429+RATE_LIMIT_ERROR_CODE = "RATE_LIMIT"+RATE_LIMIT_DEFAULT_DELAY_S = 1.0 # Fallback when the server omits Retry-After++# B2 — 503 BILLING_CAPACITY_UNAVAILABLE (slab_ledger.rs): a gateway-local+# family cap on billing admission, NOT customer credit exhaustion. Server sends+# Retry-After: 1. B7 — 503 QUEUE_FULL (self-hosted server, #3180): transient+# queue backpressure, Retry-After: 1. Both are retryable 503s the pre-existing+# ladder did not match, so they fell through and failed hard.+BILLING_CAPACITY_UNAVAILABLE_ERROR_CODE = "BILLING_CAPACITY_UNAVAILABLE"+QUEUE_FULL_ERROR_CODE = "QUEUE_FULL"+BACKPRESSURE_503_ERROR_CODES = frozenset({BILLING_CAPACITY_UNAVAILABLE_ERROR_CODE, QUEUE_FULL_ERROR_CODE})+BACKPRESSURE_503_DEFAULT_DELAY_S = 1.0 # Fallback when the server omits Retry-After++# ── Terminal credit / account errors (pass-2 audit B3) — NEVER retried ──+# 402/403 credit/account failures are mapped to typed exceptions in+# ``handle_error`` and, having no arm on any retry ladder, surface on the first+# response (single attempt). Retrying a credit/account failure would be wrong.+HTTP_PAYMENT_REQUIRED = 402+HTTP_FORBIDDEN = 403+INSUFFICIENT_CREDITS_ERROR_CODE = "INSUFFICIENT_CREDITS"+KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE = "KEY_SPEND_LIMIT_EXCEEDED"+ACCOUNT_SUSPENDED_ERROR_CODE = "ACCOUNT_SUSPENDED"+ACCOUNT_PENDING_REVIEW_ERROR_CODE = "ACCOUNT_PENDING_REVIEW"+ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE = "ACCOUNT_STATE_UNAVAILABLE"+# Retry jitter. Fixed / pure-exponential backoff makes every client that# lost a worker at the same instant (cluster cold start, rolling restart)# wake up and retry in lockstep — a thundering herd that re-saturates the@@ -520,6 +649,8 @@ def compute_retry_delay(error_label: str,error: BaseException,rng: random.Random | None = None,+ attempt: int | None = None,+ target: str | None = None,) -> float | None:"""Sleep duration for the next transport-error retry, or ``None`` ifthe provision-timeout budget is exhausted (caller must re-raise).@@ -529,15 +660,26 @@ def compute_retry_delay(lockstep. The jittered value never exceeds ``timeout - elapsed``, sothe provision-timeout budget is still respected. ``rng`` is exposedfor deterministic tests.++ When ``attempt`` is 0 the retry is logged at WARNING — matching the+ OOM-retry convention — so a user at the default log level can see+ "the SDK is retrying you" (naming the unreachable ``target`` and the+ total wait budget) instead of silently blocking for the whole+ provision timeout. Subsequent retries stay at INFO to avoid log spam."""elapsed = time.monotonic() - start_timeif elapsed >= timeout:return Noneactual_delay = apply_jitter(min(MODEL_LOADING_DEFAULT_DELAY_S, timeout - elapsed), rng=rng)- _logger.info(- "%s (%s), retrying in %.1fs (elapsed: %.1fs, timeout: %.1fs): %s",+ log_fn = _logger.warning if attempt == 0 else _logger.info+ # Log only the origin: drops path/query/fragment and any embedded+ # credentials before the URL reaches the log.+ safe_target = url_origin_for_logging(target) if target else None+ log_fn(+ "%s (%s)%s, retrying in %.1fs (elapsed: %.1fs, timeout: %.1fs): %s",error_label,type(error).__name__,+ f" contacting {safe_target}" if safe_target else "",actual_delay,elapsed,timeout,@@ -707,6 +849,26 @@ def _settled_charge_from_body(body: Any) -> tuple[int, str] | None:return settled_charge_from_usage(body.get("usage"))+def valid_stream_request_id(value: Any) -> str | None:+ """Return ``value`` when it is a well-formed request id, else ``None``.++ Same rules as ``parse_request_metadata`` (non-empty visible ASCII without+ surrounding whitespace, bounded length). Stream error chunks carry the id+ in-band; a malformed value must be dropped BEFORE it is placed on a+ synthetic HTTP header, where non-ASCII would raise ``UnicodeEncodeError``+ inside HTTPX and bypass the retry path (#3136).+ """+ if (+ isinstance(value, str)+ and 0 < len(value) <= _MAX_REQUEST_ID_LENGTH+ and value == value.strip()+ and value.isascii()+ and value.isprintable()+ ):+ return value+ return None++def parse_request_metadata(headers: Any, body: Any = None) -> RequestMetadata | None:"""Parse optional metadata from one terminal response.@@ -819,6 +981,33 @@ def parse_terminal_json_object(response: _HttpResponse, *, owner: str) -> dict[sreturn data+def parse_terminal_msgpack_object(response: _HttpResponse, *, owner: str) -> dict[str, Any]:+ """Parse one successful terminal MessagePack object with content-safe diagnostics."""+ request = parse_request_metadata(response.headers)+ diagnostic = _terminal_response_diagnostic(response)++ if not 200 <= response.status_code < 300:+ msg = f"Unexpected {owner} HTTP response ({diagnostic})"+ raise RequestError(msg, status_code=response.status_code, request=request)++ malformed = False+ try:+ data = unpack_msgpack(response.content, numeric_arrays=True)+ except (TypeError, ValueError, UnpackException):+ # Raise only after the parser exception context has been cleared.+ # MessagePack exceptions can retain decoded or trailing body content,+ # which must never escape through exception chaining.+ malformed = True+ data = None+ if malformed:+ msg = f"Malformed {owner} MessagePack response ({diagnostic})"+ raise RequestError(msg, status_code=response.status_code, request=request)+ if not isinstance(data, dict):+ msg = f"Unexpected {owner} response shape: {type(data).__name__} ({diagnostic})"+ raise RequestError(msg, status_code=response.status_code, request=request)+ return data++def attach_request_metadata(results: Sequence[Any], headers: Any, body: Any = None) -> None:"""Attach detached request-scoped metadata to one or more results.@@ -874,7 +1063,7 @@ def get_error_detail(response: _HttpResponse) -> dict[str, Any] | None:"""try:if MSGPACK_CONTENT_TYPE in response.headers.get("content-type", ""):- data = msgpack.unpackb(response.content, raw=False)+ data = unpack_msgpack(response.content, numeric_arrays=False)else:data = response.json()@@ -887,7 +1076,7 @@ def get_error_detail(response: _HttpResponse) -> dict[str, Any] | None:detail = data["detail"]if isinstance(detail, dict):return detail- except (ValueError, KeyError, TypeError):+ except (ValueError, KeyError, TypeError, UnpackException):# Malformed error body — caller treats as "no detail" and falls back.passreturn None@@ -971,12 +1160,23 @@ def raise_if_input_too_long(response: _HttpResponse, model: str | None = None) -raise InputTooLongError(message, model=model, request=parse_request_metadata(response.headers))-def handle_error(response: _HttpResponse) -> None:+def handle_error(response: _HttpResponse) -> NoReturn:"""Handle error response from server.+ Always raises — every path terminates in a typed exception. Declared+ ``NoReturn`` so callers (and the type checker) know a call terminates+ control flow, e.g. the admission-ladder give-up paths.+Raises:- RequestError: For 4xx responses.- ServerError: For 5xx responses.+ RateLimitError: For 429 responses (retry budget already spent by the+ caller, or a direct terminal path).+ InsufficientCreditsError / SpendLimitError: For 402 credit/spend+ failures (terminal — never retried).+ AccountInactiveError: For 403 account suspended / pending review+ (terminal — never retried).+ AccountStateUnavailableError: For 503 ACCOUNT_STATE_UNAVAILABLE.+ RequestError: For other 4xx responses.+ ServerError: For other 5xx responses."""code = Nonemessage = f"HTTP {response.status_code}"@@ -984,7 +1184,7 @@ def handle_error(response: _HttpResponse) -> None:try:# Try msgpack firstif MSGPACK_CONTENT_TYPE in response.headers.get("content-type", ""):- data = msgpack.unpackb(response.content, raw=False)+ data = unpack_msgpack(response.content, numeric_arrays=False)else:data = response.json()@@ -1003,7 +1203,7 @@ def handle_error(response: _HttpResponse) -> None:message = detail.get("message", str(detail))else:message = str(detail)- except (ValueError, KeyError, TypeError):+ except (ValueError, KeyError, TypeError, UnpackException):# Fall back to raw textmessage = response.text or message@@ -1021,6 +1221,27 @@ def handle_error(response: _HttpResponse) -> None:raise ProvisioningError(message, retry_after=get_retry_after(response))if response.status_code == HTTP_CLIENT_ERROR and code == INPUT_TOO_LONG_ERROR_CODE:raise InputTooLongError(message, request=request)+ # Rate limit (pass-2 audit B1). Retried on the admission ladder in the+ # buffered loops; a give-up there raises RateLimitError directly. This arm+ # covers the terminal paths (streaming, list_models, estimate, …) so a 429+ # is always a typed RateLimitError rather than a generic RequestError.+ if response.status_code == HTTP_TOO_MANY_REQUESTS:+ raise RateLimitError(message, code=code, retry_after=get_retry_after(response), request=request)+ # Terminal credit / account failures (pass-2 audit B3). 402/403 are NEVER+ # retried — they have no arm on any retry ladder, so they surface here on+ # the first response. Unrecognised 402/403 codes stay generic RequestError.+ if response.status_code == HTTP_PAYMENT_REQUIRED:+ if code == INSUFFICIENT_CREDITS_ERROR_CODE:+ raise InsufficientCreditsError(message, request=request)+ if code == KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE:+ raise SpendLimitError(message, request=request)+ if response.status_code == HTTP_FORBIDDEN and code in (+ ACCOUNT_SUSPENDED_ERROR_CODE,+ ACCOUNT_PENDING_REVIEW_ERROR_CODE,+ ):+ raise AccountInactiveError(message, code=code, request=request)+ if response.status_code == HTTP_SERVICE_UNAVAILABLE and code == ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE:+ raise AccountStateUnavailableError(message, request=request)if response.status_code >= HTTP_SERVER_ERROR:raise ServerError(message, code=code, status_code=response.status_code, request=request)raise RequestError(message, code=code, status_code=response.status_code, request=request)@@ -1049,6 +1270,69 @@ def provisioning_retry_delay(return apply_jitter(min(DEFAULT_RETRY_DELAY_S, remaining))+def admission_retry_delay(+ response: _HttpResponse,+ *,+ start_time: float,+ timeout: float,+) -> float | None:+ """Delay before retrying a pre-execution admission rejection, or ``None``+ when the response is not a retryable admission signal (the caller then+ falls through to its existing terminal handling).++ Handles the pass-2 audit backpressure/billing signals that are safe to+ retry because NO work has been published to the queue yet — they are+ admission decisions the gateway/self-hosted server makes *before*+ dispatch, so retrying is idempotent even on the non-idempotent generate+ paths:++ * ``429 TOO_MANY_REQUESTS`` (code ``RATE_LIMIT``, B1) — per-key/per-account+ rate limiting. On give-up (``provision_timeout_s`` budget spent) raises a+ typed :class:`RateLimitError` carrying the last ``Retry-After``.+ * ``503 BILLING_CAPACITY_UNAVAILABLE`` (B2 — a gateway-local billing-family+ cap, NOT customer credit exhaustion) and ``503 QUEUE_FULL`` (B7 —+ self-hosted queue backpressure, #3180). On give-up raises the server's+ terminal 503 verbatim via :func:`handle_error` (a :class:`ServerError`+ preserving the code).++ Retry timing mirrors :func:`provisioning_retry_delay`: the server-supplied+ ``Retry-After`` is honored verbatim, and only the SDK's own fallback default+ is jittered. Give-up mirrors :func:`_handle_oom_retry`: when the budget is+ spent OR the next wait would consume the rest of it (leaving no room for the+ retried request to run), the typed root cause is surfaced NOW instead of+ sleeping the budget away and letting the outer loop's ``remaining <= 0``+ guard mask it as a ``ProvisioningError``.++ IMPORTANT: 402/403 credit/account failures are deliberately NOT handled+ here. They are terminal and must never be retried; :func:`handle_error`+ maps them to typed exceptions on the first response.+ """+ status = response.status_code+ if status == HTTP_TOO_MANY_REQUESTS:+ retry_after = get_retry_after(response)+ elapsed = time.monotonic() - start_time+ remaining = timeout - elapsed+ delay = retry_after if retry_after is not None else apply_jitter(min(RATE_LIMIT_DEFAULT_DELAY_S, remaining))+ if remaining <= 0 or delay >= remaining:+ msg = f"Rate limited (429); retry budget ({timeout:.1f}s) exhausted after {elapsed:.1f}s"+ raise RateLimitError(msg, retry_after=retry_after, request=parse_request_metadata(response.headers))+ return delay+ if status == HTTP_SERVICE_UNAVAILABLE and get_error_code(response) in BACKPRESSURE_503_ERROR_CODES:+ retry_after = get_retry_after(response)+ elapsed = time.monotonic() - start_time+ remaining = timeout - elapsed+ delay = (+ retry_after if retry_after is not None else apply_jitter(min(BACKPRESSURE_503_DEFAULT_DELAY_S, remaining))+ )+ if remaining <= 0 or delay >= remaining:+ # Budget spent (or the next wait would consume it): surface the+ # server's terminal 503 (ServerError, code preserved) now.+ # ``handle_error`` is NoReturn.+ handle_error(response)+ return delay+ return None++def next_stream_retry_delay(response: _HttpResponse,*,@@ -1352,47 +1636,103 @@ def parse_encode_results(items: list[dict[str, Any]]) -> list[EncodeResult]:return results-def validate_encode_result_count(- results: list[EncodeResult],- expected: int,+def _missing_result_ids(+ results: Sequence[Mapping[str, Any]],+ submitted: Sequence[Any],+) -> list[str] | None:+ """Best-effort ids of submitted items absent from a shortened response.++ Only computed when ids identify every position on both sides: every+ submitted item carries a string ``id`` and every returned item echoes+ one. Otherwise the set difference could mislabel a present-but-unnamed+ item as missing, so the diagnostic degrades to ``None`` (positional+ counts only).++ This runs only while building an exception, so it degrades rather than+ raises: a non-mapping item must not replace the actionable count error+ with an ``AttributeError`` from the diagnostic itself.+ """+ if not all(isinstance(item, Mapping) for item in submitted):+ return None+ submitted_ids = [item.get("id") for item in submitted]+ if not all(isinstance(item_id, str) for item_id in submitted_ids):+ return None+ returned_ids: set[str] = set()+ for result in results:+ result_id = result.get("id")+ if not isinstance(result_id, str):+ return None+ returned_ids.add(result_id)+ missing = [item_id for item_id in submitted_ids if isinstance(item_id, str) and item_id not in returned_ids]+ return missing or None+++def validate_batch_result_count(+ results: Sequence[Mapping[str, Any]],+ # `Sequence[Any]`, not `Sequence[Mapping[...]]`: callers pass the+ # single-or-list item argument, whose `Item | list[Item]` union survives+ # the isinstance ternary, and only `len()` is actually required here. The+ # id diagnostic guards element shape at runtime instead.+ submitted: Sequence[Any],model: str,*,+ operation: str,request: RequestMetadata | None = None,) -> None:- """Guard the encode contract: exactly one result per input item.-- Encode is positional — callers rely on a 1:1 input↔output correspondence:- ``encode()`` returns ``results[0]`` for a single-item request, and batch- callers (e.g. the eval harness ``SIEEncoderWrapper``) reassemble embeddings- by index. The contract can break with an HTTP 200 whose ``items`` list is- *shorter* than the request: the gateway returns mixed-success batches as- ``200`` carrying only the successful items (a per-item server-side failure —- e.g. an input exceeding the model's ``max_sequence_length`` — is dropped from- the body, not surfaced as an error envelope). Without this check, that short- list flows into a positional access and raises a context-free- ``IndexError: list index out of range`` deep in a caller (issue #1526).-- Raising a typed, actionable :class:`ServerError` here keeps the failure- legible — it names the model and the expected vs. returned counts instead of- a bare ``IndexError``. A common trigger is an input that exceeds the model's- ``max_sequence_length``.+ """Guard the positional batch contract: exactly one result per input item.++ Encode and extract are positional — callers rely on a 1:1 input↔output+ correspondence: both return ``results[0]`` for a single-item request, and+ batch callers reassemble results by index. The contract can break with an+ HTTP 200 whose ``items`` list is *shorter* than the request: the gateway+ returns mixed-success+ batches as ``200`` carrying only the successful items (a per-item+ server-side failure — e.g. an input exceeding the model's+ ``max_sequence_length`` — is dropped from the body, not surfaced as an+ error envelope). Without this check, that short list flows into positional+ access: either a context-free ``IndexError`` (issue #1526) or — worse —+ a silently misaligned zip that stores results against the wrong inputs.++ Raising a typed, actionable :class:`IncompleteBatchError` keeps the+ failure legible: it names the model, the expected vs. returned counts,+ the gateway request id, and — when the submitted items carried ids — the+ ids the response dropped.Args:- results: Parsed encode results from the server response.- expected: Number of input items in the request.+ results: Parsed results from the server response.+ submitted: The input items submitted in this HTTP request.model: Model name, for the error message.+ operation: ``"encode"`` or ``"extract"`` — selects the error code+ and wording.+ request: Request metadata parsed from the terminal response headers.Raises:- ServerError: If ``len(results) != expected``.+ IncompleteBatchError: If ``len(results) != len(submitted)``."""- if len(results) != expected:- msg = (- f"Encode response desync for model {model!r}: server returned "- f"{len(results)} embedding(s) for {expected} input item(s); expected "- f"exactly one per input. An input may have failed server-side "- f"(e.g. exceeding the model's max_sequence_length) and been dropped from the batch."- )- raise ServerError(msg, code="ENCODE_RESULT_COUNT_MISMATCH", request=request)+ if len(results) == len(submitted):+ return+ if operation == "encode":+ label, noun, code = "Encode", "embedding(s)", "ENCODE_RESULT_COUNT_MISMATCH"+ else:+ label, noun, code = "Extract", "extraction result(s)", "EXTRACT_RESULT_COUNT_MISMATCH"+ missing_ids = _missing_result_ids(results, submitted)+ msg = (+ f"{label} response desync for model {model!r}: server returned "+ f"{len(results)} {noun} for {len(submitted)} input item(s); expected "+ f"exactly one per input. An input may have failed server-side "+ f"(e.g. exceeding the model's max_sequence_length) and been dropped from the batch."+ )+ if missing_ids is not None:+ msg += f" Missing item id(s): {', '.join(missing_ids)}."+ raise IncompleteBatchError(+ msg,+ code=code,+ expected=len(submitted),+ received=len(results),+ model=model,+ missing_ids=missing_ids,+ request=request,+ )def parse_score_result(data: dict[str, Any]) -> ScoreResult:diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex 9b2d26dd4..75407b8b9 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -6,7 +6,7 @@ Async variants for all client methods.Example:>>> async with SIEAsyncClient("http://localhost:8080") as client:- ... result = await client.encode("bge-m3", {"text": "Hello world"})+ ... result = await client.encode("BAAI/bge-m3", {"text": "Hello world"})... print(result["dense"].shape)(1024,)@@ -16,14 +16,14 @@ Example:... gpu="l4",... options={"normalize": True},... ) as client:- ... result = await client.encode("bge-m3", {"text": "Hello"}) # uses l4+ ... result = await client.encode("BAAI/bge-m3", {"text": "Hello"}) # uses l4>>> # With resource pool for isolated capacity>>> async with SIEAsyncClient(... "http://gateway:8080",... pool={"name": "eval-bench", "gpus": {"l4": 2}},... ) as client:- ... result = await client.encode("bge-m3", {"text": "Hello"}, gpu="eval-bench/l4")+ ... result = await client.encode("BAAI/bge-m3", {"text": "Hello"}, gpu="eval-bench/l4")"""from __future__ import annotations@@ -40,15 +40,15 @@ from typing import IO, Any, Literal, Self, cast, overloadfrom urllib.parse import quote, urlencodeimport aiohttp-import msgpack-import msgpack_numpy as m+from sie_sdk._msgpack import packb as pack_msgpackfrom sie_sdk.audio import convert_item_audiofrom sie_sdk.documents import convert_item_documentfrom sie_sdk.files import resolve_uploadfrom sie_sdk.images import ImageLike, convert_images_for_json, convert_item_imagesfrom sie_sdk.jobs import (TERMINAL_JOB_STATES,+ MalformedChunkError,build_job_body,decode_chunk_bytes,job_chunks,@@ -85,6 +85,7 @@ from sie_sdk.types import (OutputType,PoolInfo,PoolSpec,+ Recommendation,RequestMetadata,ResponseInputMessage,ResponseResult,@@ -100,21 +101,26 @@ from ._shared import (HTTP_CLIENT_ERROR,HTTP_GATEWAY_TIMEOUT,HTTP_SERVICE_UNAVAILABLE,+ JOB_NOT_TERMINAL_ERROR_CODE,JOB_RESULT_NOT_FOUND_ERROR_CODE,JOB_RESULT_REF_MAX_REFRESHES,JSON_CONTENT_TYPE,LORA_LOADING_DEFAULT_DELAY_S,LORA_LOADING_ERROR_CODE,LORA_LOADING_MAX_RETRIES,+ MODAL_CONTINUATION_MAX_HOPS,MODEL_LOADING_DEFAULT_DELAY_S,MODEL_LOADING_ERROR_CODE,MSGPACK_CONTENT_TYPE,PROVISIONING_ERROR_CODE,+ RECOMMEND_PATH,+ REQUEST_ID_HEADER,RESOURCE_EXHAUSTED_ERROR_CODE,RESOURCE_EXHAUSTED_MAX_RETRIES,SDK_VERSION_HEADER,SERVER_VERSION_HEADER,_coerce_token_count,+ admission_retry_delay,attach_request_metadata,base_url_accepts_origin_credentials,build_chat_body,@@ -130,6 +136,7 @@ from ._shared import (get_sdk_version,handle_error,is_transient_connect_error,+ modal_continuation_path,next_stream_retry_delay,parse_encode_results,parse_extract_results,@@ -137,6 +144,7 @@ from ._shared import (parse_request_metadata,parse_score_result,parse_terminal_json_object,+ parse_terminal_msgpack_object,provisioning_retry_delay,raise_if_estimate_unroutable,raise_if_input_too_long,@@ -146,13 +154,16 @@ from ._shared import (settled_charge_from_usage,sse_chunk_error,sse_headers,- validate_encode_result_count,+ valid_stream_request_id,+ validate_base_url,+ validate_batch_result_count,validate_generate_grammar,validate_generate_request_body,websocket_matches_base_url_origin,)from ._sse import aiter_sse_payloadsfrom .errors import (+ JobFailedError,LoraLoadingError,ModelLoadingError,PoolError,@@ -209,10 +220,6 @@ _RETRYABLE_TRANSPORT_ERRORS: tuple[type[BaseException], ...] = (_LEASE_RENEWAL_MAX_RETRIES = 5-# NOTE: msgpack_numpy.patch() is called lazily in SIEAsyncClient.__init__-# (see sync.py for details).-_NUMPY_PATCHED = False-def _parse_generate_result_async(data: dict[str, Any],@@ -395,7 +402,7 @@ class SIEAsyncClient:Example:>>> async with SIEAsyncClient("http://localhost:8080") as client:- ... result = await client.encode("bge-m3", {"text": "Hello world"})+ ... result = await client.encode("BAAI/bge-m3", {"text": "Hello world"})... print(result["dense"].shape)(1024,)@@ -405,14 +412,14 @@ class SIEAsyncClient:... gpu="l4",... options={"normalize": True},... ) as client:- ... result = await client.encode("bge-m3", {"text": "Hello"}) # uses l4+ ... result = await client.encode("BAAI/bge-m3", {"text": "Hello"}) # uses l4>>> # With resource pool for isolated capacity>>> async with SIEAsyncClient(... "http://gateway:8080",... pool={"name": "eval-bench", "gpus": {"l4": 2}},... ) as client:- ... result = await client.encode("bge-m3", {"text": "Hello"}, gpu="eval-bench/l4")+ ... result = await client.encode("BAAI/bge-m3", {"text": "Hello"}, gpu="eval-bench/l4")"""_version_warning_logged = False@@ -432,15 +439,8 @@ class SIEAsyncClient:org: str | None = None,base_url_headers: Mapping[str, str] | None = None,) -> None:- # Ensure msgpack-numpy hooks are installed (once per process).- # Done lazily here instead of at module level to avoid monkey-patching- # msgpack in processes that import sie_sdk but never use the client.- global _NUMPY_PATCHED- if not _NUMPY_PATCHED:- m.patch()- _NUMPY_PATCHED = True-# Normalize base_url (remove trailing slash)+ validate_base_url(base_url)self._base_url = base_url.rstrip("/")self._base_url_headers = copy_base_url_headers(base_url_headers)if self._base_url_headers and not base_url_accepts_origin_credentials(self._base_url):@@ -623,6 +623,42 @@ class SIEAsyncClient:logger.warning(warning)SIEAsyncClient._version_warning_logged = True+ async def _follow_modal_continuations(+ self,+ response: _AioResponse,+ *,+ start_time: float,+ budget_s: float,+ ) -> _AioResponse:+ """Consume bounded same-origin Modal 303 result URLs without replaying POST."""+ for _ in range(MODAL_CONTINUATION_MAX_HOPS):+ path = modal_continuation_path(self._base_url, response)+ if path is None:+ return response+ remaining = budget_s - (time.monotonic() - start_time)+ if remaining <= 0:+ msg = f"Provision timeout ({budget_s:.1f}s) exceeded while awaiting generation result"+ raise ProvisioningError(msg)+ try:+ async with (+ self._throttle(),+ self._ensure_session().get(+ path,+ headers=self._headers_for_request(path, {"Accept": JSON_CONTENT_TYPE}),+ timeout=aiohttp.ClientTimeout(total=min(self._timeout, remaining)),+ allow_redirects=False,+ ) as raw,+ ):+ content = await raw.read()+ response = _AioResponse(raw.status, content, raw.headers)+ except (aiohttp.ClientError, OSError) as exc:+ msg = f"Failed to retrieve the in-flight generation result: {type(exc).__name__}"+ raise SIEConnectionError(msg) from exc+ if modal_continuation_path(self._base_url, response) is not None:+ msg = f"Provisioning result remained in flight after {MODAL_CONTINUATION_MAX_HOPS} continuation hops"+ raise ProvisioningError(msg)+ return response+def _resolve_gpu(self, gpu: str | None) -> str | None:"""Resolve GPU, using default if not specified."""return gpu if gpu is not None else self._default_gpu@@ -1251,7 +1287,7 @@ class SIEAsyncClient:request_body["params"] = params# Serialize with msgpack- body = msgpack.packb(request_body, use_bin_type=True)+ body = pack_msgpack(request_body, use_bin_type=True)# Build headers with optional GPU and pool routingheaders: dict[str, str] = {}@@ -1268,6 +1304,7 @@ class SIEAsyncClient:lora_retries = 0# Retry counter for server-side OOM (RESOURCE_EXHAUSTED).oom_retries = 0+ connect_retries = 0# Retry loop for retryable provisioning/capacity responses.while True:@@ -1313,8 +1350,11 @@ class SIEAsyncClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1await asyncio.sleep(delay_s)continuemsg = f"Failed to connect to {self._base_url}: {e}"@@ -1323,7 +1363,7 @@ class SIEAsyncClient:msg = f"Failed to connect to {self._base_url}: {e}"raise SIEConnectionError(msg) from e- # Short-circuit terminal load failures (sie-test#85).+ # Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)# Handle 503 with LORA_LOADING or MODEL_LOADING - auto-retry@@ -1398,6 +1438,24 @@ class SIEAsyncClient:)continue+ # Retryable pre-execution admission backpressure (pass-2 audit+ # B1/B2/B7): a 429 RATE_LIMIT, or a retryable 503+ # (BILLING_CAPACITY_UNAVAILABLE / QUEUE_FULL) the ladder above did+ # not match. No work was published, so retry within the+ # provision-timeout budget honoring Retry-After; a give-up raises a+ # typed RateLimitError (429) or the server's terminal 503.+ # 402/403 credit/account errors are terminal and NOT handled here.+ admission_delay = admission_retry_delay(response, start_time=start_time, timeout=timeout)+ if admission_delay is not None:+ logger.info(+ "Admission backpressure (HTTP %d), retrying in %.1fs (timeout: %.1fs)",+ response.status_code,+ admission_delay,+ timeout,+ )+ await asyncio.sleep(admission_delay)+ continue+# Handle 504 (gateway timeout): queued work was published, but the# gateway did not receive a worker result before its deadline.# Encode/score/extract are idempotent, so callers that opted into@@ -1428,7 +1486,7 @@ class SIEAsyncClient:self._check_server_version(response)# Deserialize response- response_data = msgpack.unpackb(response.content, raw=False)+ response_data = parse_terminal_msgpack_object(response, owner="encode")# Get timing info if presenttiming = response_data.get("timing")@@ -1436,12 +1494,15 @@ class SIEAsyncClient:# Parse results and inject timing into eachresults = parse_encode_results(response_data["items"])# Guard the 1:1 input↔output contract before any positional access- # (``results[0]`` below, or batch reassembly in callers). A desynced- # count otherwise surfaces as a context-free ``IndexError`` (#1526).- validate_encode_result_count(+ # (``results[0]`` below, or batch reassembly in callers). The gateway's+ # queue path returns mixed-success batches as 200 with only the+ # successful items, so a desynced count otherwise misaligns every+ # zip-inputs-to-outputs consumer (#1526, finding U1).+ validate_batch_result_count(results,- len(items_list),+ items_list, # ty: ignore[invalid-argument-type]model,+ operation="encode",request=parse_request_metadata(response.headers),)if timing:@@ -1473,6 +1534,37 @@ class SIEAsyncClient:data = response.json()return data["models"]+ async def recommend(+ self,+ task: str,+ *,+ # Same rationale as `estimate`: this is the per-call HTTP budget, not a+ # caller-supplied cancellation budget.+ timeout: float | None = None, # noqa: ASYNC109+ ) -> Recommendation:+ """Async version of recommend(). See SIEClient.recommend() for details."""+ try:+ response = await self._post(+ RECOMMEND_PATH,+ json_data={"task": task},+ headers={+ "Accept": JSON_CONTENT_TYPE,+ "Content-Type": JSON_CONTENT_TYPE,+ },+ timeout_s=timeout if timeout is not None else self._timeout,+ )+ except TimeoutError as e:+ msg = f"Request timed out: {e}"+ raise SIEConnectionError(msg) from e+ except (aiohttp.ClientError, OSError) as e:+ msg = f"Failed to connect to {self._base_url}: {e}"+ raise SIEConnectionError(msg) from e++ if response.status_code >= HTTP_CLIENT_ERROR:+ handle_error(response)++ return cast("Recommendation", response.json())+async def estimate(self,endpoint: str,@@ -1754,7 +1846,7 @@ class SIEAsyncClient:request_body["options"] = resolved_options# Serialize with msgpack- body = msgpack.packb(request_body, use_bin_type=True)+ body = pack_msgpack(request_body, use_bin_type=True)# Build headers with optional GPU and pool routingheaders: dict[str, str] = {}@@ -1770,6 +1862,7 @@ class SIEAsyncClient:# Model loading uses time-based timeout only (no retry counter)# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.oom_retries = 0+ connect_retries = 0# Retry loop for retryable provisioning/capacity responses.while True:@@ -1815,8 +1908,11 @@ class SIEAsyncClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1await asyncio.sleep(delay_s)continuemsg = f"Failed to connect to {self._base_url}: {e}"@@ -1825,7 +1921,7 @@ class SIEAsyncClient:msg = f"Failed to connect to {self._base_url}: {e}"raise SIEConnectionError(msg) from e- # Short-circuit terminal load failures (sie-test#85).+ # Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)# Handle 503 with MODEL_LOADING - auto-retry@@ -1877,6 +1973,24 @@ class SIEAsyncClient:)continue+ # Retryable pre-execution admission backpressure (pass-2 audit+ # B1/B2/B7): a 429 RATE_LIMIT, or a retryable 503+ # (BILLING_CAPACITY_UNAVAILABLE / QUEUE_FULL) the ladder above did+ # not match. No work was published, so retry within the+ # provision-timeout budget honoring Retry-After; a give-up raises a+ # typed RateLimitError (429) or the server's terminal 503.+ # 402/403 credit/account errors are terminal and NOT handled here.+ admission_delay = admission_retry_delay(response, start_time=start_time, timeout=timeout)+ if admission_delay is not None:+ logger.info(+ "Admission backpressure (HTTP %d), retrying in %.1fs (timeout: %.1fs)",+ response.status_code,+ admission_delay,+ timeout,+ )+ await asyncio.sleep(admission_delay)+ continue+# Handle 504 (gateway timeout). See encode() above for rationale.if response.status_code == HTTP_GATEWAY_TIMEOUT and wait_for_capacity:elapsed = time.monotonic() - start_time@@ -1901,7 +2015,7 @@ class SIEAsyncClient:self._check_server_version(response)- response_data = msgpack.unpackb(response.content, raw=False)+ response_data = parse_terminal_msgpack_object(response, owner="score")result = parse_score_result(response_data)attach_request_metadata([result], response.headers, response_data)@@ -1979,6 +2093,7 @@ class SIEAsyncClient:timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_Sstart_time = time.monotonic()oom_retries = 0+ connect_retries = 0while True:elapsed = time.monotonic() - start_time@@ -2020,8 +2135,11 @@ class SIEAsyncClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1await asyncio.sleep(delay_s)continuemsg = f"Failed to connect to {self._base_url}: {e}"@@ -2036,6 +2154,7 @@ class SIEAsyncClient:msg = f"Request failed: {e}"raise SIEConnectionError(msg) from e+ response = await self._follow_modal_continuations(response, start_time=start_time, budget_s=timeout)raise_if_model_load_failed(response, model=model)if response.status_code == 503:@@ -2051,14 +2170,28 @@ class SIEAsyncClient:await asyncio.sleep(delay)continue- if error_code == MODEL_LOADING_ERROR_CODE and wait_for_capacity:+ if error_code == MODEL_LOADING_ERROR_CODE:+ # Retried regardless of ``wait_for_capacity``, matching+ # encode/score/extract/chat/responses/streaming: the worker+ # has already accepted the request and is loading the model,+ # so this is a pre-execution signal, not a capacity wait.elapsed = time.monotonic() - start_timeif elapsed >= timeout:msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"raise ModelLoadingError(msg, model=model)retry_after = get_retry_after(response)delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)- await asyncio.sleep(min(delay, timeout - elapsed))+ remaining = timeout - elapsed+ if delay >= remaining:+ # Sleeping through the rest of the budget would make+ # the NEXT loop iteration raise a generic+ # ProvisioningError; surface the typed root cause now.+ msg = (+ f"Model loading retry delay ({delay:.1f}s) would exceed the "+ f"provision timeout ({timeout:.1f}s, {elapsed:.1f}s elapsed) for '{model}'"+ )+ raise ModelLoadingError(msg, model=model)+ await asyncio.sleep(delay)continueif error_code == RESOURCE_EXHAUSTED_ERROR_CODE:oom_retries = await _handle_oom_retry(@@ -2071,6 +2204,24 @@ class SIEAsyncClient:)continue+ # Retryable pre-execution admission backpressure (pass-2 audit+ # B1/B2/B7): a 429 RATE_LIMIT, or a retryable 503+ # (BILLING_CAPACITY_UNAVAILABLE / QUEUE_FULL) the ladder above did+ # not match. No work was published, so retry within the+ # provision-timeout budget honoring Retry-After; a give-up raises a+ # typed RateLimitError (429) or the server's terminal 503.+ # 402/403 credit/account errors are terminal and NOT handled here.+ admission_delay = admission_retry_delay(response, start_time=start_time, timeout=timeout)+ if admission_delay is not None:+ logger.info(+ "Admission backpressure (HTTP %d), retrying in %.1fs (timeout: %.1fs)",+ response.status_code,+ admission_delay,+ timeout,+ )+ await asyncio.sleep(admission_delay)+ continue+# Do NOT retry 504 here. Unlike the idempotent encode/score/extract# paths (which keep the 504 retry block), generation is NOT# idempotent and carries no dedup key. A 504 GATEWAY_TIMEOUT is a@@ -2080,8 +2231,9 @@ class SIEAsyncClient:# surface it as a terminal ServerError instead (same reasoning as# the mid-flight transport-error block above). The pre-execution# 503 MODEL_LOADING / PROVISIONING retries above remain because- # those fire *before* any generation can have started and the- # caller has opted into capacity waiting.+ # those fire *before* any generation can have started+ # (MODEL_LOADING unconditionally; PROVISIONING when the caller+ # has opted into capacity waiting).if response.status_code == HTTP_GATEWAY_TIMEOUT:msg = ("Gateway timed out (504) after the generate request was published to the "@@ -2148,6 +2300,7 @@ class SIEAsyncClient:timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_Sstart_time = time.monotonic()oom_retries = 0+ connect_retries = 0while True:remaining = timeout - (time.monotonic() - start_time)if remaining <= 0:@@ -2173,8 +2326,11 @@ class SIEAsyncClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1await asyncio.sleep(delay_s)continuemsg = f"Failed to connect to {self._base_url}: {e}"@@ -2183,6 +2339,7 @@ class SIEAsyncClient:msg = f"Request failed: {e}"raise SIEConnectionError(msg) from e+ response = await self._follow_modal_continuations(response, start_time=start_time, budget_s=timeout)if response.status_code == 200:breakdelay, oom_retries = next_stream_retry_delay(@@ -2287,6 +2444,7 @@ class SIEAsyncClient:timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_Sstart_time = time.monotonic()oom_retries = 0+ connect_retries = 0while True:remaining = timeout - (time.monotonic() - start_time)if remaining <= 0:@@ -2308,9 +2466,15 @@ class SIEAsyncClient:except aiohttp.ClientConnectorError as e:if wait_for_capacity and is_transient_connect_error(e):delay_s = compute_retry_delay(- start_time=start_time, timeout=timeout, error_label="Connect error", error=e+ start_time=start_time,+ timeout=timeout,+ error_label="Connect error",+ error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1await asyncio.sleep(delay_s)continuemsg = f"Failed to connect to {self._base_url}: {e}"@@ -2321,6 +2485,7 @@ class SIEAsyncClient:msg = f"Request failed: {e}"raise SIEConnectionError(msg) from e+ response = await self._follow_modal_continuations(response, start_time=start_time, budget_s=timeout)if response.status_code == 200:breakdelay, oom_retries = next_stream_retry_delay(@@ -2534,6 +2699,7 @@ class SIEAsyncClient:timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_Sstart_time = time.monotonic()oom_retries = 0+ connect_retries = 0while True:remaining = timeout - (time.monotonic() - start_time)if remaining <= 0:@@ -2547,7 +2713,22 @@ class SIEAsyncClient:url,data=body,headers=self._headers_for_request(url, headers),- timeout=aiohttp.ClientTimeout(total=min(self._timeout, remaining)),+ # No ``total`` timeout: it would cover the entire SSE+ # body and kill any stream running longer than+ # ``timeout_s`` mid-generation (the TS SDK documents+ # the same trap and uses a pre-stream-only timeout).+ # Connection establishment stays bounded by the+ # pre-stream retry budget; reads are bounded+ # *per-read* so a dead connection still fails within+ # ~``timeout_s`` while a healthy long stream — whose+ # chunks keep arriving — survives. Mirrors the sync+ # twin, where the httpx float timeout is per-phase+ # (per socket read), not total.+ timeout=aiohttp.ClientTimeout(+ total=None,+ connect=min(self._timeout, remaining),+ sock_read=self._timeout,+ ),allow_redirects=False,) as raw,):@@ -2577,11 +2758,20 @@ class SIEAsyncClient:err = sse_chunk_error(chunk)if err is not None:code, message = err+ # Terminal error chunks — on both the+ # SIE-native generate shape and the OpenAI+ # chat shape — carry the gateway request+ # id in-band (streamed responses have no+ # terminal headers); forward it so typed+ # errors like ``empty_model_output`` stay+ # correlatable (#3136).+ request_id = valid_stream_request_id(chunk.get("request_id"))+ error_headers = {REQUEST_ID_HEADER: request_id} if request_id else Noneif not yielded_chunk:capacity_response = _AioResponse(HTTP_SERVICE_UNAVAILABLE,json.dumps({"error": {"code": code, "message": message}}).encode(),- {},+ error_headers or {},)retry_delay, oom_retries = next_stream_retry_delay(capacity_response,@@ -2594,7 +2784,11 @@ class SIEAsyncClient:max_oom_retries=max_oom_retries,)break- raise ServerError(message, code=code)+ raise ServerError(+ message,+ code=code,+ request=parse_request_metadata(error_headers or {}),+ )yield chunkyielded_chunk = Trueelse:@@ -2602,9 +2796,15 @@ class SIEAsyncClient:except aiohttp.ClientConnectorError as e:if wait_for_capacity and is_transient_connect_error(e):delay_s = compute_retry_delay(- start_time=start_time, timeout=timeout, error_label="Connect error", error=e+ start_time=start_time,+ timeout=timeout,+ error_label="Connect error",+ error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1await asyncio.sleep(delay_s)continuemsg = f"Failed to connect to {self._base_url}: {e}"@@ -2702,7 +2902,7 @@ class SIEAsyncClient:request_body["params"] = params# Serialize with msgpack- body = msgpack.packb(request_body, use_bin_type=True)+ body = pack_msgpack(request_body, use_bin_type=True)# Build headers with optional GPU and pool routingheaders: dict[str, str] = {}@@ -2718,6 +2918,7 @@ class SIEAsyncClient:# Model loading uses time-based timeout only (no retry counter)# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.oom_retries = 0+ connect_retries = 0# Retry loop for retryable provisioning/capacity responses.while True:@@ -2763,8 +2964,11 @@ class SIEAsyncClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1await asyncio.sleep(delay_s)continuemsg = f"Failed to connect to {self._base_url}: {e}"@@ -2773,7 +2977,7 @@ class SIEAsyncClient:msg = f"Failed to connect to {self._base_url}: {e}"raise SIEConnectionError(msg) from e- # Short-circuit terminal load failures (sie-test#85).+ # Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)# Short-circuit token-budget overruns (#849).@@ -2828,6 +3032,24 @@ class SIEAsyncClient:)continue+ # Retryable pre-execution admission backpressure (pass-2 audit+ # B1/B2/B7): a 429 RATE_LIMIT, or a retryable 503+ # (BILLING_CAPACITY_UNAVAILABLE / QUEUE_FULL) the ladder above did+ # not match. No work was published, so retry within the+ # provision-timeout budget honoring Retry-After; a give-up raises a+ # typed RateLimitError (429) or the server's terminal 503.+ # 402/403 credit/account errors are terminal and NOT handled here.+ admission_delay = admission_retry_delay(response, start_time=start_time, timeout=timeout)+ if admission_delay is not None:+ logger.info(+ "Admission backpressure (HTTP %d), retrying in %.1fs (timeout: %.1fs)",+ response.status_code,+ admission_delay,+ timeout,+ )+ await asyncio.sleep(admission_delay)+ continue+# Handle 504 (gateway timeout). See encode() above for rationale.if response.status_code == HTTP_GATEWAY_TIMEOUT and wait_for_capacity:elapsed = time.monotonic() - start_time@@ -2852,9 +3074,19 @@ class SIEAsyncClient:self._check_server_version(response)- response_data = msgpack.unpackb(response.content, raw=False)+ response_data = parse_terminal_msgpack_object(response, owner="extract")results = parse_extract_results(response_data["items"])+ # Same positional contract as encode: ``results[0]`` below and+ # index-based reassembly in batch callers both assume one result per+ # input, and the queue path drops failed items from a 200 body.+ validate_batch_result_count(+ results,+ items_list, # ty: ignore[invalid-argument-type]+ model,+ operation="extract",+ request=parse_request_metadata(response.headers),+ )attach_request_metadata(results, response.headers, response_data)@@ -3019,18 +3251,44 @@ class _AsyncJobs(_AsyncNamespace):)async def results(self, job_id: str) -> JobResults:- """Async ``jobs.results`` — read + decode the finished job's chunk refs."""+ """Async ``jobs.results`` — read + decode a terminal job's chunk refs.++ Reads every chunk that published a ref (a ``failed`` chunk still carries+ one with its SUCCESSFUL, already-billed siblings plus the per-item+ failures); only chunks with no ref are skipped. Raises ``RequestError``+ with code ``job_not_terminal`` on a non-terminal job, warns neutrally+ when fewer items are retrieved than ``total_items``, and warns distinctly+ when a chunk ref could not be decoded. See the sync+ :meth:`SIEClient.jobs.results` for the full contract.+ """refreshes = 0while True:job = await self.get(job_id)+ state = job.get("state")+ if state not in TERMINAL_JOB_STATES:+ msg = (+ f"job {job_id} is {state!r}, not terminal; results are decodable only after the "+ "job reaches a terminal state (succeeded/failed/suspended/cancelled)"+ )+ raise RequestError(msg, code=JOB_NOT_TERMINAL_ERROR_CODE, status_code=409)chunks = job_chunks(job)items = []try:for chunk in chunks:ref = chunk.get("ref")- if chunk.get("state") != "succeeded" or not ref:+ if not ref:continue- items.extend(decode_chunk_bytes(await self._read_ref(ref)))+ raw = await self._read_ref(ref)+ try:+ items.extend(decode_chunk_bytes(raw))+ except MalformedChunkError:+ # Garbage bytes are a DECODE fault, not proof of failed+ # publication/billing — confine it and flag it distinctly.+ warnings.warn(+ f"job {job_id} chunk (seq={chunk.get('seq')}) ref could not be decoded "+ "(malformed bytes); its items are omitted from the results",+ stacklevel=2,+ )except RequestError as exc:refreshable = exc.status_code == 404 and exc.code == JOB_RESULT_NOT_FOUND_ERROR_CODEif refreshable and refreshes < JOB_RESULT_REF_MAX_REFRESHES:@@ -3038,26 +3296,62 @@ class _AsyncJobs(_AsyncNamespace):continueraisedims = next((it["dims"] for it in items if it.get("dims")), None)+ retrieved = len(items)+ total_items = job.get("total_items")+ if total_items is not None and retrieved < total_items:+ # Neutral: state only what is known; do not assert a cause.+ warnings.warn(+ f"job {job_id} results are incomplete: retrieved {retrieved} of {total_items} items",+ stacklevel=2,+ )return {"job_id": job.get("id", job_id),- "state": job.get("state"),- "total_items": job.get("total_items"),+ "state": state,+ "total_items": total_items,"settled_credits": job.get("settled_credits"),"chunks": chunks,- "retrieved": len(items),+ "retrieved": retrieved,"dims": dims,"items": items,}- async def wait(self, job_id: str, *, timeout_s: float = 600.0, poll_s: float = 2.0) -> JobStatus:- """Poll until terminal, or return a connector plan at its stable planned phase."""+ async def wait(+ self,+ job_id: str,+ *,+ timeout_s: float = 600.0,+ poll_s: float = 2.0,+ raise_on_failure: bool = False,+ ) -> JobStatus:+ """Poll until terminal, or return a connector plan at its stable planned phase.++ With ``raise_on_failure=True`` a non-successful terminal+ (``failed``/``suspended``/``cancelled``) raises :class:`JobFailedError`+ carrying the status doc's ``outcome``/``error_code``. The default is+ unchanged and back-compatible (see the sync :meth:`SIEClient.jobs.wait`).+ """deadline = time.monotonic() + timeout_swhile True:job = await self.get(job_id)- if job.get("state") in TERMINAL_JOB_STATES or job.get("phase") == "planned":+ if job.get("phase") == "planned":+ return job+ state = job.get("state")+ if state in TERMINAL_JOB_STATES:+ if raise_on_failure and state != "succeeded":+ outcome = job.get("outcome")+ error_code = job.get("error_code")+ reason = f" (outcome={outcome!r}, error_code={error_code!r})" if outcome or error_code else ""+ msg = f"job {job_id} terminated {state!r}{reason}"+ raise JobFailedError(+ msg,+ job_id=job.get("id", job_id),+ state=state,+ outcome=outcome,+ error_code=error_code,+ )return jobif time.monotonic() >= deadline:- msg = f"job {job_id} still {job.get('state')!r} after {timeout_s:.0f}s"+ msg = f"job {job_id} still {state!r} after {timeout_s:.0f}s"raise RequestError(msg, code="job_wait_timeout", status_code=504)await asyncio.sleep(poll_s)diff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.pyindex 3cc786fde..401b8dcf6 100644--- a/packages/sie_sdk/src/sie_sdk/client/errors.py+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py@@ -270,6 +270,122 @@ class EstimateUnroutableError(ServerError):super().__init__(message, code=code, status_code=503, request=request)+class RateLimitError(RequestError):+ """Error when the gateway rate-limits the caller and retries are exhausted.++ Raised when the gateway returns HTTP ``429 TOO_MANY_REQUESTS`` (code+ ``RATE_LIMIT``, per-key or per-account, default-on) and the SDK's+ bounded, ``Retry-After``-honoring retry budget (capped by+ ``provision_timeout_s``) is spent. The SDK honors the server's+ ``Retry-After`` on each attempt before giving up.++ Subclass of :class:`RequestError` so existing 4xx handlers keep working;+ new code can catch :class:`RateLimitError` specifically to back off at a+ higher level, shed load, or route elsewhere.++ Attributes:+ retry_after: The last ``Retry-After`` hint the server supplied+ (seconds), if any.+ """++ def __init__(+ self,+ message: str,+ *,+ code: str | None = "RATE_LIMIT",+ retry_after: float | None = None,+ request: RequestMetadata | None = None,+ ) -> None:+ super().__init__(message, code=code, status_code=429, request=request)+ self.retry_after = retry_after+++class InsufficientCreditsError(RequestError):+ """Error when the account has insufficient credits to run the request.++ Raised when the gateway returns HTTP ``402 PAYMENT_REQUIRED`` with code+ ``INSUFFICIENT_CREDITS``. This is a TERMINAL billing failure — the SDK+ never retries it, because retrying a credit failure would be wrong.++ Subclass of :class:`RequestError` so existing 4xx handlers keep working;+ new code can catch :class:`InsufficientCreditsError` specifically to+ surface a top-up prompt or halt a batch.+ """++ def __init__(+ self,+ message: str,+ *,+ request: RequestMetadata | None = None,+ ) -> None:+ super().__init__(message, code="INSUFFICIENT_CREDITS", status_code=402, request=request)+++class SpendLimitError(RequestError):+ """Error when the API key's configured spend limit is exceeded.++ Raised when the gateway returns HTTP ``402 PAYMENT_REQUIRED`` with code+ ``KEY_SPEND_LIMIT_EXCEEDED``. This is a TERMINAL policy failure — the SDK+ never retries it. Distinct from :class:`InsufficientCreditsError`: the+ account may have credits, but this key has hit its own spend cap.++ Subclass of :class:`RequestError` so existing 4xx handlers keep working.+ """++ def __init__(+ self,+ message: str,+ *,+ request: RequestMetadata | None = None,+ ) -> None:+ super().__init__(message, code="KEY_SPEND_LIMIT_EXCEEDED", status_code=402, request=request)+++class AccountInactiveError(RequestError):+ """Error when the account is not permitted to submit work.++ Raised when the gateway returns HTTP ``403 FORBIDDEN`` with code+ ``ACCOUNT_SUSPENDED`` or ``ACCOUNT_PENDING_REVIEW``. This is a TERMINAL+ account-state failure — the SDK never retries it, because the account+ must be activated/reinstated out of band before work is accepted.++ Subclass of :class:`RequestError` so existing 4xx handlers keep working;+ new code can catch :class:`AccountInactiveError` and branch on+ :attr:`code` (``ACCOUNT_SUSPENDED`` vs ``ACCOUNT_PENDING_REVIEW``).+ """++ def __init__(+ self,+ message: str,+ *,+ code: str | None = None,+ request: RequestMetadata | None = None,+ ) -> None:+ super().__init__(message, code=code, status_code=403, request=request)+++class AccountStateUnavailableError(ServerError):+ """Error when the gateway cannot resolve the account's admission state.++ Raised when the gateway returns HTTP ``503`` with code+ ``ACCOUNT_STATE_UNAVAILABLE`` — a fail-closed infrastructure signal (the+ control plane could not resolve account state), distinct from a customer+ suspension. Surfaced as a typed TERMINAL error rather than being retried+ on the SDK's admission ladder: a caller may re-issue the whole request,+ but the SDK does not silently loop on an unresolved account state.++ Subclass of :class:`ServerError` so existing 5xx handlers keep working.+ """++ def __init__(+ self,+ message: str,+ *,+ request: RequestMetadata | None = None,+ ) -> None:+ super().__init__(message, code="ACCOUNT_STATE_UNAVAILABLE", status_code=503, request=request)++class ResourceExhaustedError(ServerError):"""Error when the server has exhausted its OOM-recovery strategies.@@ -298,3 +414,88 @@ class ResourceExhaustedError(ServerError):super().__init__(message, code="RESOURCE_EXHAUSTED", status_code=503, request=request)self.model = modelself.retries = retries+++class IncompleteBatchError(ServerError):+ """A successful (HTTP 200) batch response dropped or added items.++ The gateway's queue path returns mixed-success batches as ``200`` carrying+ only the successful items — a per-item failure is dropped from the body,+ not surfaced as an error envelope. Batch responses are positional (item+ ``id`` is optional), so a shortened body silently shifts every item after+ the dropped one: a zip-inputs-to-outputs consumer would store results+ against the wrong inputs. The SDK guards the 1:1 input↔output contract on+ every batch response and raises this instead of returning a desynced list.++ Subclass of :class:`ServerError` — the server violated the response-shape+ contract even though the HTTP status was 200 — so existing ``ServerError``+ handlers keep working (this refines the untyped guard from #1526).+ ``status_code`` is ``None``: the response was not an HTTP error. Callers+ can catch :class:`IncompleteBatchError` specifically and retry item-wise+ (single-item batches get per-item error visibility) using+ :attr:`missing_ids` when available.++ Attributes:+ expected: Number of items submitted in this HTTP request.+ received: Number of items the response body carried.+ model: The model that was requested.+ missing_ids: Ids of submitted items absent from the response — only+ when ids identify every item on both sides (every submitted item+ carried an ``id`` and every returned item echoed one), ``None``+ otherwise.+ request_id: Gateway request id (``x-sie-request-id``) when the+ response carried one; quote it when reporting the incident.+ """++ def __init__(+ self,+ message: str,+ *,+ code: str | None = None,+ expected: int,+ received: int,+ model: str | None = None,+ missing_ids: list[str] | None = None,+ request: RequestMetadata | None = None,+ ) -> None:+ super().__init__(message, code=code, request=request)+ self.expected = expected+ self.received = received+ self.model = model+ self.missing_ids = missing_ids+ self.request_id: str | None = (request or {}).get("id")+++class JobFailedError(SIEError):+ """A job reached a non-successful terminal state (``failed``/``suspended``/``cancelled``).++ Raised by :meth:`SIEClient.jobs.wait` / :meth:`SIEAsyncClient.jobs.wait`+ only when called with ``raise_on_failure=True``; the default remains+ back-compatible and returns the terminal status doc unchanged. The+ gateway's terminal reason rides ``outcome`` / ``error_code`` on the status+ doc (see :class:`sie_sdk.types.JobStatus`); this surfaces them so a caller+ can branch on the failure without re-reading the doc.++ Attributes:+ job_id: The job that failed.+ state: The terminal state (``failed``, ``suspended``, or ``cancelled``).+ outcome: The gateway's terminal outcome (e.g. ``reexecution_required``),+ or ``None`` when the status doc carried none.+ error_code: The gateway's terminal error code (e.g.+ ``RESULT_HANDLE_EXPIRED``), or ``None`` when absent.+ """++ def __init__(+ self,+ message: str,+ *,+ job_id: str | None = None,+ state: str | None = None,+ outcome: str | None = None,+ error_code: str | None = None,+ ) -> None:+ super().__init__(message)+ self.job_id = job_id+ self.state = state+ self.outcome = outcome+ self.error_code = error_codediff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 73ae3ac1f..f19640dbb 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -10,14 +10,14 @@ Provides a Python client for the Search Inference Engine server.Example:>>> from sie_sdk import SIEClient>>> client = SIEClient("http://localhost:8080")- >>> result = client.encode("bge-m3", {"text": "Hello world"})+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello world"})>>> result["dense"] # np.ndarray, shape [1024]GPU Selection and Auto-Retry:>>> # Request specific GPU, auto-retry while scaling up>>> client = SIEClient("http://gateway:8080")>>> result = client.encode(- ... "bge-m3",+ ... "BAAI/bge-m3",... {"text": "Hello"},... gpu="l4",... wait_for_capacity=True, # Auto-retry explicit capacity 503s and transient transport errors@@ -28,7 +28,7 @@ Resource Pools:>>> # Create pool for isolated capacity>>> client = SIEClient("http://gateway:8080")>>> client.create_pool("eval-bench", {"l4": 2}) # 2 L4 GPUs- >>> result = client.encode("bge-m3", {"text": "Hello"}, gpu="eval-bench/l4")+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello"}, gpu="eval-bench/l4")>>> client.delete_pool("eval-bench") # Cleanup when done"""@@ -40,6 +40,7 @@ import jsonimport loggingimport threadingimport time+import warningsimport weakreffrom collections.abc import Iterator, Mapping, Sequencefrom functools import partial@@ -48,15 +49,15 @@ from typing import IO, Any, Literal, Self, cast, overloadfrom urllib.parse import quote, urlencodeimport httpx-import msgpack-import msgpack_numpy as m+from sie_sdk._msgpack import packb as pack_msgpackfrom sie_sdk.audio import convert_item_audiofrom sie_sdk.documents import convert_item_documentfrom sie_sdk.files import resolve_uploadfrom sie_sdk.images import ImageLike, convert_images_for_json, convert_item_imagesfrom sie_sdk.jobs import (TERMINAL_JOB_STATES,+ MalformedChunkError,build_job_body,decode_chunk_bytes,job_chunks,@@ -93,6 +94,7 @@ from sie_sdk.types import (OutputType,PoolInfo,PoolSpec,+ Recommendation,RequestMetadata,ResponseInputMessage,ResponseResult,@@ -108,22 +110,27 @@ from ._shared import (HTTP_CLIENT_ERROR,HTTP_GATEWAY_TIMEOUT,HTTP_SERVICE_UNAVAILABLE,+ JOB_NOT_TERMINAL_ERROR_CODE,JOB_RESULT_NOT_FOUND_ERROR_CODE,JOB_RESULT_REF_MAX_REFRESHES,JSON_CONTENT_TYPE,LORA_LOADING_DEFAULT_DELAY_S,LORA_LOADING_ERROR_CODE,LORA_LOADING_MAX_RETRIES,+ MODAL_CONTINUATION_MAX_HOPS,MODEL_LOADING_DEFAULT_DELAY_S,MODEL_LOADING_ERROR_CODE,MODEL_REVISION_HEADER,MSGPACK_CONTENT_TYPE,PROVISIONING_ERROR_CODE,+ RECOMMEND_PATH,+ REQUEST_ID_HEADER,RESOURCE_EXHAUSTED_ERROR_CODE,RESOURCE_EXHAUSTED_MAX_RETRIES,SDK_VERSION_HEADER,SERVER_VERSION_HEADER,_coerce_token_count,+ admission_retry_delay,attach_request_metadata,base_url_accepts_origin_credentials,build_chat_body,@@ -139,6 +146,7 @@ from ._shared import (get_sdk_version,handle_error,is_transient_connect_error,+ modal_continuation_path,next_stream_retry_delay,parse_encode_results,parse_extract_results,@@ -146,6 +154,7 @@ from ._shared import (parse_request_metadata,parse_score_result,parse_terminal_json_object,+ parse_terminal_msgpack_object,provisioning_retry_delay,raise_if_estimate_unroutable,raise_if_input_too_long,@@ -155,13 +164,16 @@ from ._shared import (settled_charge_from_usage,sse_chunk_error,sse_headers,- validate_encode_result_count,+ valid_stream_request_id,+ validate_base_url,+ validate_batch_result_count,validate_generate_grammar,validate_generate_request_body,websocket_matches_base_url_origin,)from ._sse import iter_sse_payloadsfrom .errors import (+ JobFailedError,LoraLoadingError,ModelLoadingError,PoolError,@@ -189,12 +201,6 @@ _RETRYABLE_TRANSPORT_ERRORS: tuple[type[Exception], ...] = (_LEASE_RENEWAL_MAX_RETRIES = 5-# NOTE: msgpack_numpy.patch() is called lazily in SIEClient.__init__-# to avoid monkey-patching the global msgpack module at import time.-# This prevents overhead in processes that import sie_sdk but don't use-# the client (e.g., the gateway only needs sie_sdk.types/queue_types).-_NUMPY_PATCHED = False-def _parse_generate_result(data: dict[str, Any],@@ -370,7 +376,7 @@ class SIEClient:Example:>>> client = SIEClient("http://localhost:8080")- >>> result = client.encode("bge-m3", {"text": "Hello world"})+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello world"})>>> print(result["dense"].shape)(1024,)@@ -380,13 +386,13 @@ class SIEClient:... gpu="l4",... options={"normalize": True},... )- >>> result = client.encode("bge-m3", {"text": "Hello"}) # uses l4- >>> result = client.encode("bge-m3", {"text": "Hello"}, gpu="a100") # overrides+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello"}) # uses l4+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello"}, gpu="a100") # overrides>>> # With resource pool for isolated capacity (new API)>>> client = SIEClient("http://gateway:8080")>>> client.create_pool("eval-bench", {"l4": 2})- >>> result = client.encode("bge-m3", {"text": "Hello"}, gpu="eval-bench/l4")+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello"}, gpu="eval-bench/l4")>>> client.delete_pool("eval-bench")"""@@ -406,15 +412,8 @@ class SIEClient:org: str | None = None,base_url_headers: Mapping[str, str] | None = None,) -> None:- # Ensure msgpack-numpy hooks are installed (once per process).- # Done lazily here instead of at module level to avoid monkey-patching- # msgpack in processes that import sie_sdk but never use the client.- global _NUMPY_PATCHED- if not _NUMPY_PATCHED:- m.patch()- _NUMPY_PATCHED = True-# Normalize base_url (remove trailing slash)+ validate_base_url(base_url)self._base_url = base_url.rstrip("/")self._base_url_headers = copy_base_url_headers(base_url_headers)if self._base_url_headers and not base_url_accepts_origin_credentials(self._base_url):@@ -543,6 +542,36 @@ class SIEClient:logger.warning(warning)SIEClient._version_warning_logged = True+ def _follow_modal_continuations(+ self,+ response: httpx.Response,+ *,+ start_time: float,+ budget_s: float,+ ) -> httpx.Response:+ """Consume bounded same-origin Modal 303 result URLs without replaying POST."""+ for _ in range(MODAL_CONTINUATION_MAX_HOPS):+ path = modal_continuation_path(self._base_url, response)+ if path is None:+ return response+ remaining = budget_s - (time.monotonic() - start_time)+ if remaining <= 0:+ msg = f"Provision timeout ({budget_s:.1f}s) exceeded while awaiting generation result"+ raise ProvisioningError(msg)+ try:+ response = self._client.get(+ path,+ headers={"Accept": JSON_CONTENT_TYPE},+ timeout=min(self._timeout, remaining),+ )+ except httpx.HTTPError as exc:+ msg = f"Failed to retrieve the in-flight generation result: {type(exc).__name__}"+ raise SIEConnectionError(msg) from exc+ if modal_continuation_path(self._base_url, response) is not None:+ msg = f"Provisioning result remained in flight after {MODAL_CONTINUATION_MAX_HOPS} continuation hops"+ raise ProvisioningError(msg)+ return response+def _resolve_gpu(self, gpu: str | None) -> str | None:"""Resolve GPU, using default if not specified."""return gpu if gpu is not None else self._default_gpu@@ -776,7 +805,7 @@ class SIEClient:Example:>>> client.create_pool("eval", {"l4": 2}, bundle="default", minimum_worker_count=1)- >>> result = client.encode("bge-m3", {"text": "Hello"}, gpu="eval/l4")+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello"}, gpu="eval/l4")>>> client.delete_pool("eval")"""with self._pools_lock:@@ -1099,7 +1128,7 @@ class SIEClient:"""Encode items into vector representations.Args:- model: Model name to use for encoding (e.g., "bge-m3").+ model: Model name to use for encoding (e.g., "BAAI/bge-m3").items: Single Item or list of Items to encode.output_types: Which outputs to return: ["dense"], ["sparse"], ["dense", "sparse", "multivector"].Default: ["dense"].@@ -1130,6 +1159,12 @@ class SIEClient:under ``ModelLoadingError`` / ``LoraLoadingError`` /``ResourceExhaustedError`` below; the ``RESOURCE_EXHAUSTED``branch can be disabled by passing ``max_oom_retries=0``.+ The pre-dispatch admission signals ``429 RATE_LIMIT``,+ ``503 BILLING_CAPACITY_UNAVAILABLE`` and ``503 QUEUE_FULL``+ are likewise retried regardless of this flag — no work has+ been published yet — honouring ``Retry-After`` and capped by+ ``provision_timeout_s``. On give-up they raise+ ``RateLimitError`` (429) or the server's terminal 503.provision_timeout_s: Maximum time to wait for capacity when wait_for_capacity=True.Default: 900 seconds (15 minutes).max_oom_retries: Public retry knob capping the number of@@ -1169,19 +1204,19 @@ class SIEClient:Example:>>> # Single item- >>> result = client.encode("bge-m3", {"text": "Hello"})+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello"})>>> result["dense"] # np.ndarray>>> # Batch- >>> results = client.encode("bge-m3", [{"text": "Hello"}, {"text": "World"}])+ >>> results = client.encode("BAAI/bge-m3", [{"text": "Hello"}, {"text": "World"}])>>> len(results) # 2>>> # With GPU selection (for gateway)- >>> result = client.encode("bge-m3", {"text": "Hello"}, gpu="l4")+ >>> result = client.encode("BAAI/bge-m3", {"text": "Hello"}, gpu="l4")>>> # Auto-wait for capacity during scale-up>>> result = client.encode(- ... "bge-m3",+ ... "BAAI/bge-m3",... {"text": "Hello"},... gpu="l4",... wait_for_capacity=True,@@ -1190,7 +1225,7 @@ class SIEClient:>>> # Query embedding with instruction (for E5, GTE-Qwen, etc.)>>> result = client.encode(- ... "gte-qwen2-7b",+ ... "Alibaba-NLP/gte-Qwen2-7B-instruct",... {"text": "What is ML?"},... instruction="Retrieve passages that answer the question",... is_query=True,@@ -1242,7 +1277,7 @@ class SIEClient:request_body["params"] = params# Serialize with msgpack- body = msgpack.packb(request_body, use_bin_type=True)+ body = pack_msgpack(request_body, use_bin_type=True)# Build headers with optional GPU and pool routingheaders: dict[str, str] = {}@@ -1262,6 +1297,7 @@ class SIEClient:# cause unbounded blocking; each retry uses bounded exponential# backoff via ``compute_oom_backoff``.oom_retries = 0+ connect_retries = 0# Retry loop for retryable provisioning/capacity responses.while True:@@ -1285,8 +1321,11 @@ class SIEClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1self._record_retry()time.sleep(delay_s)continue@@ -1317,7 +1356,7 @@ class SIEClient:# MODEL_LOADING retry budget. The server emits 502# MODEL_LOAD_FAILED for permanent classes (gated repos,# missing deps) — retrying would waste 5 minutes on a- # known-bad config (sie-test#85).+ # known-bad configuration.raise_if_model_load_failed(response, model=model)# Handle 503 with LORA_LOADING or MODEL_LOADING - auto-retry@@ -1396,6 +1435,25 @@ class SIEClient:self._record_retry()continue+ # Retryable pre-execution admission backpressure (pass-2 audit+ # B1/B2/B7): a 429 RATE_LIMIT, or a retryable 503+ # (BILLING_CAPACITY_UNAVAILABLE / QUEUE_FULL) the ladder above did+ # not match. No work was published, so retry within the+ # provision-timeout budget honoring Retry-After; a give-up raises a+ # typed RateLimitError (429) or the server's terminal 503.+ # 402/403 credit/account errors are terminal and NOT handled here.+ admission_delay = admission_retry_delay(response, start_time=start_time, timeout=timeout)+ if admission_delay is not None:+ logger.info(+ "Admission backpressure (HTTP %d), retrying in %.1fs (timeout: %.1fs)",+ response.status_code,+ admission_delay,+ timeout,+ )+ self._record_retry()+ time.sleep(admission_delay)+ continue+# Handle 504 (gateway timeout): queued work was published, but the# gateway did not receive a worker result before its deadline.# Encode/score/extract are idempotent, so callers that opted into@@ -1427,7 +1485,7 @@ class SIEClient:self._check_server_version(response)# Deserialize response- response_data = msgpack.unpackb(response.content, raw=False)+ response_data = parse_terminal_msgpack_object(response, owner="encode")# Get timing info if presenttiming = response_data.get("timing")@@ -1439,12 +1497,15 @@ class SIEClient:for result in results:result["model"] = response_model# Guard the 1:1 input↔output contract before any positional access- # (``results[0]`` below, or batch reassembly in callers). A desynced- # count otherwise surfaces as a context-free ``IndexError`` (#1526).- validate_encode_result_count(+ # (``results[0]`` below, or batch reassembly in callers). The gateway's+ # queue path returns mixed-success batches as 200 with only the+ # successful items, so a desynced count otherwise misaligns every+ # zip-inputs-to-outputs consumer (#1526, finding U1).+ validate_batch_result_count(results,- len(items_list),+ items_list, # ty: ignore[invalid-argument-type]model,+ operation="encode",request=parse_request_metadata(response.headers),)if timing:@@ -1542,7 +1603,7 @@ class SIEClient:>>> quote["estimated_credits"]1>>> quote["rate_book_version"]- '2026-07-26-production-bootstrap-v2'+ '2026-08-09-production-bootstrap-v3'"""# Every other public method opens with this. Without it `estimate()`# inherits whatever `last_retry_count` / `last_model_revision` the@@ -1574,6 +1635,72 @@ class SIEClient:return cast("CostEstimate", response.json())+ def recommend(self, task: str, *, timeout: float | None = None) -> Recommendation:+ """Ask which model to use for a task family (``POST /v1/recommend``).++ Read-only and non-billable: no dispatch, no reservation, no credits.+ The managed gateway answers from evidence compiled into the release it+ is running, so the recommendation and the ``/v1/catalog`` entry it+ names can never disagree.++ The answer always states its ``basis``. ``ranked`` means two or more of+ the family's choices were measured on the same benchmark, so the+ ordering rests on a comparison somebody ran. ``curated`` means evidence+ exists but no two choices share a benchmark, so the pick is the+ catalog's judgement and is labelled as such rather than dressed up as a+ measurement. ``no_evidence`` means the family cites nothing. Read it+ before trusting a pick — that is what it is for.++ Args:+ task: A catalog task family id, e.g. ``"rerank"``. A 404 names+ every id this release recommends for.+ timeout: Per-call timeout override in seconds.++ Returns:+ :class:`~sie_sdk.types.Recommendation` with ``fast`` and/or+ ``best``, each carrying its alias, evidence refs, and+ ``evidence_guarded``. Both are optional: a pick names only a model+ this release can serve, so a family with nothing serveable answers+ 200 with its evidence and no picks.++ Raises:+ RequestError: 400 for an empty or malformed ``task``; 404 when the+ task family is unknown to this release.+ SIEConnectionError: If unable to connect to the server.+ ServerError: For other 5xx responses.++ Example:+ >>> pick = client.recommend("rerank")+ >>> pick["best"]["alias"]+ 'rerank-best'+ >>> pick["basis"]+ 'ranked'+ """+ # Same reason every other public method opens with this: without it the+ # call inherits the previous call's retry/revision state on this thread.+ self._reset_retry_count()+ try:+ response = self._client.post(+ RECOMMEND_PATH,+ json={"task": task},+ headers={+ "Accept": JSON_CONTENT_TYPE,+ "Content-Type": JSON_CONTENT_TYPE,+ },+ timeout=timeout if timeout is not None else self._timeout,+ )+ except httpx.ConnectError as e:+ msg = f"Failed to connect to {self._base_url}: {e}"+ raise SIEConnectionError(msg) from e+ except httpx.TimeoutException as e:+ msg = f"Request timed out: {e}"+ raise SIEConnectionError(msg) from e++ if response.status_code >= HTTP_CLIENT_ERROR:+ handle_error(response)++ return cast("Recommendation", response.json())+def get_model(self, model: str) -> ModelInfo:"""Get details for a specific model.@@ -1834,7 +1961,7 @@ class SIEClient:>>> print(f"Ready with {capacity['worker_count']} L4 workers")>>> # Wait and pre-load a model- >>> capacity = client.wait_for_capacity("l4", model="bge-m3")+ >>> capacity = client.wait_for_capacity("l4", model="BAAI/bge-m3")"""timeout = timeout_s if timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_Sstart_time = time.monotonic()@@ -1918,7 +2045,13 @@ class SIEClient:Their budgets are documented under ``ModelLoadingError`` /``ResourceExhaustedError`` below; the``RESOURCE_EXHAUSTED`` branch can be disabled by passing- ``max_oom_retries=0``.+ ``max_oom_retries=0``. The pre-dispatch admission signals+ ``429 RATE_LIMIT``, ``503 BILLING_CAPACITY_UNAVAILABLE`` and+ ``503 QUEUE_FULL`` are likewise retried regardless of this+ flag — no work has been published yet — honouring+ ``Retry-After`` and capped by ``provision_timeout_s``. On+ give-up they raise ``RateLimitError`` (429) or the server's+ terminal 503.provision_timeout_s: Maximum time to wait for capacity when wait_for_capacity=True.Default: 900 seconds (15 minutes).max_oom_retries: Public retry knob capping the number of@@ -1954,7 +2087,7 @@ class SIEClient:Example:>>> result = client.score(- ... "bge-reranker-v2",+ ... "BAAI/bge-reranker-v2-m3",... query={"text": "What is machine learning?"},... items=[{"text": "ML is AI..."}, {"text": "Python is..."}],... )@@ -1976,7 +2109,7 @@ class SIEClient:request_body["options"] = resolved_options# Serialize with msgpack- body = msgpack.packb(request_body, use_bin_type=True)+ body = pack_msgpack(request_body, use_bin_type=True)# Build headers with optional GPU and pool routingheaders: dict[str, str] = {}@@ -1992,6 +2125,7 @@ class SIEClient:# Model loading uses time-based timeout only (no retry counter)# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.oom_retries = 0+ connect_retries = 0# Retry loop for retryable provisioning/capacity responses.while True:@@ -2015,8 +2149,11 @@ class SIEClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1self._record_retry()time.sleep(delay_s)continue@@ -2043,7 +2180,7 @@ class SIEClient:)raise SIEConnectionError(msg) from e- # Short-circuit terminal load failures (sie-test#85).+ # Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)# Handle 503 with MODEL_LOADING - auto-retry@@ -2100,6 +2237,25 @@ class SIEClient:self._record_retry()continue+ # Retryable pre-execution admission backpressure (pass-2 audit+ # B1/B2/B7): a 429 RATE_LIMIT, or a retryable 503+ # (BILLING_CAPACITY_UNAVAILABLE / QUEUE_FULL) the ladder above did+ # not match. No work was published, so retry within the+ # provision-timeout budget honoring Retry-After; a give-up raises a+ # typed RateLimitError (429) or the server's terminal 503.+ # 402/403 credit/account errors are terminal and NOT handled here.+ admission_delay = admission_retry_delay(response, start_time=start_time, timeout=timeout)+ if admission_delay is not None:+ logger.info(+ "Admission backpressure (HTTP %d), retrying in %.1fs (timeout: %.1fs)",+ response.status_code,+ admission_delay,+ timeout,+ )+ self._record_retry()+ time.sleep(admission_delay)+ continue+# Handle 504 (gateway timeout): queued work was published, but the# gateway did not receive a worker result before its deadline.# Encode/score/extract are idempotent, so callers that opted into@@ -2131,7 +2287,7 @@ class SIEClient:self._check_server_version(response)# Deserialize response- response_data = msgpack.unpackb(response.content, raw=False)+ response_data = parse_terminal_msgpack_object(response, owner="score")# Build ScoreResultresult = parse_score_result(response_data)@@ -2165,10 +2321,11 @@ class SIEClient:) -> GenerateResult:"""Generate text from a prompt (walking-skeleton SDK surface).- The SDK does not currently expose streaming chunks to the caller;- the worker streams chunks to the gateway, the gateway aggregates,- and the SDK returns the assembled result plus SIE-native timing- metadata (``ttft_ms``, ``tpot_ms``, ``attempt_id``).+ This method returns the aggregated outcome: the worker streams+ chunks to the gateway, the gateway aggregates, and the SDK+ returns the assembled result plus SIE-native timing metadata+ (``ttft_ms``, ``tpot_ms``, ``attempt_id``). To consume chunks as+ they arrive, use :meth:`stream_generate` instead.Args:model: Model name. HF-style IDs such as@@ -2205,15 +2362,24 @@ class SIEClient:sampler arguments win. Select non-default profiles through the``model:profile`` identity rather than ``options.profile``.gpu: Target GPU type / pool spec; see ``encode``.- wait_for_capacity: Auto-retry 503 PROVISIONING / MODEL_LOADING responses+ wait_for_capacity: Auto-retry 503 PROVISIONING responsesunder ``provision_timeout_s``. See ``encode``. Unlike theidempotent encode/score/extract paths, a ``504`` gatewaytimeout is NOT retried here: generation is non-idempotentand a 504 is a post-publish timeout, so retrying coulddouble-bill an inference. A ``504`` is surfaced as aterminal :class:`ServerError`. Pass ``False`` to surface- pre-execution provisioning and model-loading responses without- retrying them.+ pre-execution provisioning responses without retrying them.+ ``503 MODEL_LOADING`` is retried regardless of this flag+ (matching encode/score/extract): the worker has already+ accepted the request and is loading the target model. The+ pre-dispatch admission signals ``429 RATE_LIMIT``,+ ``503 BILLING_CAPACITY_UNAVAILABLE`` and ``503 QUEUE_FULL``+ are also retried regardless of this flag — they reject the+ request before any generation is published, so retrying+ cannot double-bill — honouring ``Retry-After`` and capped by+ ``provision_timeout_s``; on give-up they raise+ ``RateLimitError`` (429) or the server's terminal 503.provision_timeout_s: Maximum time to wait for capacity.Returns:@@ -2266,6 +2432,7 @@ class SIEClient:timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_Sstart_time = time.monotonic()oom_retries = 0+ connect_retries = 0while True:elapsed = time.monotonic() - start_time@@ -2291,8 +2458,11 @@ class SIEClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1self._record_retry()time.sleep(delay_s)continue@@ -2315,6 +2485,7 @@ class SIEClient:)raise SIEConnectionError(msg) from e+ response = self._follow_modal_continuations(response, start_time=start_time, budget_s=timeout)raise_if_model_load_failed(response, model=model)if response.status_code == 503:@@ -2331,16 +2502,29 @@ class SIEClient:time.sleep(actual_delay)continue- if error_code == MODEL_LOADING_ERROR_CODE and wait_for_capacity:+ if error_code == MODEL_LOADING_ERROR_CODE:+ # Retried regardless of ``wait_for_capacity``, matching+ # encode/score/extract/chat/responses/streaming: the worker+ # has already accepted the request and is loading the model,+ # so this is a pre-execution signal, not a capacity wait.elapsed = time.monotonic() - start_timeif elapsed >= timeout:msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"raise ModelLoadingError(msg, model=model)retry_after = get_retry_after(response)delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)- actual_delay = min(delay, timeout - elapsed)+ remaining = timeout - elapsed+ if delay >= remaining:+ # Sleeping through the rest of the budget would make+ # the NEXT loop iteration raise a generic+ # ProvisioningError; surface the typed root cause now.+ msg = (+ f"Model loading retry delay ({delay:.1f}s) would exceed the "+ f"provision timeout ({timeout:.1f}s, {elapsed:.1f}s elapsed) for '{model}'"+ )+ raise ModelLoadingError(msg, model=model)self._record_retry()- time.sleep(actual_delay)+ time.sleep(delay)continueif error_code == RESOURCE_EXHAUSTED_ERROR_CODE:oom_retries = _handle_oom_retry(@@ -2354,6 +2538,26 @@ class SIEClient:self._record_retry()continue+ # Retryable pre-execution admission backpressure (pass-2 audit+ # B1/B2/B7): a 429 RATE_LIMIT, or a retryable 503+ # (BILLING_CAPACITY_UNAVAILABLE / QUEUE_FULL). These are admission+ # rejections BEFORE the generate work is published, so retrying is+ # safe (unlike the post-publish 504 below). Honor Retry-After within+ # the provision-timeout budget; a give-up raises a typed+ # RateLimitError (429) or the server's terminal 503. 402/403+ # credit/account errors are terminal and NOT handled here.+ admission_delay = admission_retry_delay(response, start_time=start_time, timeout=timeout)+ if admission_delay is not None:+ logger.info(+ "Admission backpressure (HTTP %d), retrying in %.1fs (timeout: %.1fs)",+ response.status_code,+ admission_delay,+ timeout,+ )+ self._record_retry()+ time.sleep(admission_delay)+ continue+# Do NOT retry 504 here. Unlike the idempotent encode/score/extract# paths (which keep the 504 retry block), generation is NOT# idempotent and carries no dedup key. A 504 GATEWAY_TIMEOUT is a@@ -2363,8 +2567,9 @@ class SIEClient:# surface it as a terminal ServerError instead (same reasoning as# the mid-flight transport-error block above). The pre-execution# 503 MODEL_LOADING / PROVISIONING retries above remain because- # those fire *before* any generation can have started and the- # caller has opted into capacity waiting.+ # those fire *before* any generation can have started+ # (MODEL_LOADING unconditionally; PROVISIONING when the caller+ # has opted into capacity waiting).if response.status_code == HTTP_GATEWAY_TIMEOUT:msg = ("Gateway timed out (504) after the generate request was published to the "@@ -2466,6 +2671,7 @@ class SIEClient:timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_Sstart_time = time.monotonic()oom_retries = 0+ connect_retries = 0while True:remaining = timeout - (time.monotonic() - start_time)if remaining <= 0:@@ -2485,8 +2691,11 @@ class SIEClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1self._record_retry()time.sleep(delay_s)continue@@ -2496,6 +2705,7 @@ class SIEClient:msg = f"Connection lost mid-request ({type(e).__name__}): {e}"raise SIEConnectionError(msg) from e+ response = self._follow_modal_continuations(response, start_time=start_time, budget_s=timeout)if response.status_code == 200:breakdelay, oom_retries = next_stream_retry_delay(@@ -2603,6 +2813,7 @@ class SIEClient:timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_Sstart_time = time.monotonic()oom_retries = 0+ connect_retries = 0while True:remaining = timeout - (time.monotonic() - start_time)if remaining <= 0:@@ -2618,9 +2829,15 @@ class SIEClient:except httpx.ConnectError as e:if wait_for_capacity and is_transient_connect_error(e):delay_s = compute_retry_delay(- start_time=start_time, timeout=timeout, error_label="Connect error", error=e+ start_time=start_time,+ timeout=timeout,+ error_label="Connect error",+ error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1self._record_retry()time.sleep(delay_s)continue@@ -2632,6 +2849,7 @@ class SIEClient:msg = f"Connection lost mid-request ({type(e).__name__}): {e}"raise SIEConnectionError(msg) from e+ response = self._follow_modal_continuations(response, start_time=start_time, budget_s=timeout)if response.status_code == 200:breakdelay, oom_retries = next_stream_retry_delay(@@ -2850,6 +3068,7 @@ class SIEClient:timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_Sstart_time = time.monotonic()oom_retries = 0+ connect_retries = 0while True:remaining = timeout - (time.monotonic() - start_time)if remaining <= 0:@@ -2888,10 +3107,20 @@ class SIEClient:err = sse_chunk_error(chunk)if err is not None:code, message = err+ # Terminal error chunks — on both the+ # SIE-native generate shape and the OpenAI+ # chat shape — carry the gateway request+ # id in-band (streamed responses have no+ # terminal headers); forward it so typed+ # errors like ``empty_model_output`` stay+ # correlatable (#3136).+ request_id = valid_stream_request_id(chunk.get("request_id"))+ error_headers = {REQUEST_ID_HEADER: request_id} if request_id else Noneif not yielded_chunk:capacity_response = httpx.Response(HTTP_SERVICE_UNAVAILABLE,json={"error": {"code": code, "message": message}},+ headers=error_headers,)retry_delay, oom_retries = next_stream_retry_delay(capacity_response,@@ -2905,7 +3134,11 @@ class SIEClient:)self._record_retry()break- raise ServerError(message, code=code)+ raise ServerError(+ message,+ code=code,+ request=parse_request_metadata(error_headers or {}),+ )yield chunkyielded_chunk = Trueelse:@@ -2913,9 +3146,15 @@ class SIEClient:except httpx.ConnectError as e:if wait_for_capacity and is_transient_connect_error(e):delay_s = compute_retry_delay(- start_time=start_time, timeout=timeout, error_label="Connect error", error=e+ start_time=start_time,+ timeout=timeout,+ error_label="Connect error",+ error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1self._record_retry()time.sleep(delay_s)continue@@ -2979,7 +3218,7 @@ class SIEClient:"""Extract entities or structured data from items.Args:- model: Model name to use for extraction (e.g., "gliner-multi-v2.1").+ model: Model name to use for extraction (e.g., "urchade/gliner_multi-v2.1").items: Single Item or list of Items to extract from.labels: Entity types to extract (e.g., ["person", "organization"]).output_schema: JSON schema for structured extraction output.@@ -3005,7 +3244,13 @@ class SIEClient:Their budgets are documented under ``ModelLoadingError`` /``ResourceExhaustedError`` below; the``RESOURCE_EXHAUSTED`` branch can be disabled by passing- ``max_oom_retries=0``.+ ``max_oom_retries=0``. The pre-dispatch admission signals+ ``429 RATE_LIMIT``, ``503 BILLING_CAPACITY_UNAVAILABLE`` and+ ``503 QUEUE_FULL`` are likewise retried regardless of this+ flag — no work has been published yet — honouring+ ``Retry-After`` and capped by ``provision_timeout_s``. On+ give-up they raise ``RateLimitError`` (429) or the server's+ terminal 503.provision_timeout_s: Maximum time to wait for capacity when wait_for_capacity=True.Default: 900 seconds (15 minutes).max_oom_retries: Public retry knob capping the number of@@ -3042,7 +3287,7 @@ class SIEClient:Example:>>> # Single item>>> result = client.extract(- ... "gliner-multi-v2.1",+ ... "urchade/gliner_multi-v2.1",... {"text": "Apple was founded by Steve Jobs."},... labels=["person", "organization"],... )@@ -3053,7 +3298,7 @@ class SIEClient:>>> # Batch>>> results = client.extract(- ... "gliner-multi-v2.1",+ ... "urchade/gliner_multi-v2.1",... [{"text": "Tesla CEO Elon Musk..."}, {"text": "Google's Sundar Pichai..."}],... labels=["person", "organization"],... )@@ -3096,7 +3341,7 @@ class SIEClient:request_body["params"] = params# Serialize with msgpack- body = msgpack.packb(request_body, use_bin_type=True)+ body = pack_msgpack(request_body, use_bin_type=True)# Build headers with optional GPU and pool routingheaders: dict[str, str] = {}@@ -3112,6 +3357,7 @@ class SIEClient:# Model loading uses time-based timeout only (no retry counter)# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.oom_retries = 0+ connect_retries = 0# Retry loop for retryable provisioning/capacity responses.while True:@@ -3135,8 +3381,11 @@ class SIEClient:timeout=timeout,error_label="Connect error",error=e,+ attempt=connect_retries,+ target=self._base_url,)if delay_s is not None:+ connect_retries += 1self._record_retry()time.sleep(delay_s)continue@@ -3163,7 +3412,7 @@ class SIEClient:)raise SIEConnectionError(msg) from e- # Short-circuit terminal load failures (sie-test#85).+ # Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)# Short-circuit token-budget overruns (#849).@@ -3223,6 +3472,25 @@ class SIEClient:self._record_retry()continue+ # Retryable pre-execution admission backpressure (pass-2 audit+ # B1/B2/B7): a 429 RATE_LIMIT, or a retryable 503+ # (BILLING_CAPACITY_UNAVAILABLE / QUEUE_FULL) the ladder above did+ # not match. No work was published, so retry within the+ # provision-timeout budget honoring Retry-After; a give-up raises a+ # typed RateLimitError (429) or the server's terminal 503.+ # 402/403 credit/account errors are terminal and NOT handled here.+ admission_delay = admission_retry_delay(response, start_time=start_time, timeout=timeout)+ if admission_delay is not None:+ logger.info(+ "Admission backpressure (HTTP %d), retrying in %.1fs (timeout: %.1fs)",+ response.status_code,+ admission_delay,+ timeout,+ )+ self._record_retry()+ time.sleep(admission_delay)+ continue+# Handle 504 (gateway timeout): queued work was published, but the# gateway did not receive a worker result before its deadline.# Encode/score/extract are idempotent, so callers that opted into@@ -3254,7 +3522,7 @@ class SIEClient:self._check_server_version(response)# Deserialize response- response_data = msgpack.unpackb(response.content, raw=False)+ response_data = parse_terminal_msgpack_object(response, owner="extract")# Parse resultsresults = parse_extract_results(response_data["items"])@@ -3262,6 +3530,16 @@ class SIEClient:if isinstance(response_model, str) and response_model:for result in results:result["model"] = response_model+ # Same positional contract as encode: ``results[0]`` below and+ # index-based reassembly in batch callers both assume one result per+ # input, and the queue path drops failed items from a 200 body.+ validate_batch_result_count(+ results,+ items_list, # ty: ignore[invalid-argument-type]+ model,+ operation="extract",+ request=parse_request_metadata(response.headers),+ )attach_request_metadata(results, response.headers, response_data)@@ -3440,23 +3718,58 @@ class _SyncJobs(_SyncNamespace):)def results(self, job_id: str) -> JobResults:- """Retrieve a finished job's chunk refs and decode the per-item results.+ """Retrieve a terminal job's chunk refs and decode the per-item results.++ Reads every chunk that published a TTL'd payload-store ref (local path+ or http(s) URL in the POC) and unpacks the msgpack ``WorkResult`` array;+ dense embeddings decode to numpy arrays (like :meth:`encode`). A+ ``failed`` chunk still carries a ref with its SUCCESSFUL siblings (which+ are billed) plus the per-item failures, so those refs are read too — only+ chunks with no ref at all are skipped. Each item's ``success`` and+ ``error`` distinguish the two.- Reads each succeeded chunk's TTL'd payload-store ref (local path or- http(s) URL in the POC) and unpacks the msgpack ``WorkResult`` array;- dense embeddings decode to numpy arrays (like :meth:`encode`).+ Raises:+ RequestError: With code ``job_not_terminal`` when the job has not+ reached a terminal state — decoding one then would return a+ partial subset indistinguishable from a partial-failure subset.++ Warns:+ UserWarning: Neutrally, when fewer items are retrieved than+ ``total_items`` (the returned set is incomplete) — without+ asserting a cause. Separately, and distinctly, when a chunk ref's+ bytes could not be decoded (a decode fault), so a garbage ref is+ not conflated with a genuinely-unpublished chunk."""refreshes = 0while True:job = self.get(job_id)+ state = job.get("state")+ if state not in TERMINAL_JOB_STATES:+ msg = (+ f"job {job_id} is {state!r}, not terminal; results are decodable only after the "+ "job reaches a terminal state (succeeded/failed/suspended/cancelled)"+ )+ raise RequestError(msg, code=JOB_NOT_TERMINAL_ERROR_CODE, status_code=409)chunks = job_chunks(job)items = []try:for chunk in chunks:ref = chunk.get("ref")- if chunk.get("state") != "succeeded" or not ref:+ if not ref:continue- items.extend(decode_chunk_bytes(self._read_ref(ref)))+ raw = self._read_ref(ref)+ try:+ items.extend(decode_chunk_bytes(raw))+ except MalformedChunkError:+ # Garbage bytes are a DECODE fault, not proof of failed+ # publication/billing — confine it and flag it distinctly+ # rather than folding it into the neutral incompleteness+ # warning below.+ warnings.warn(+ f"job {job_id} chunk (seq={chunk.get('seq')}) ref could not be decoded "+ "(malformed bytes); its items are omitted from the results",+ stacklevel=2,+ )except RequestError as exc:refreshable = exc.status_code == 404 and exc.code == JOB_RESULT_NOT_FOUND_ERROR_CODEif refreshable and refreshes < JOB_RESULT_REF_MAX_REFRESHES:@@ -3464,26 +3777,67 @@ class _SyncJobs(_SyncNamespace):continueraisedims = next((it["dims"] for it in items if it.get("dims")), None)+ retrieved = len(items)+ total_items = job.get("total_items")+ if total_items is not None and retrieved < total_items:+ # Neutral: state only what is known (fewer items decoded than the+ # job's item count). Do NOT assert a cause — the shortfall may be+ # an unpublished chunk OR an undecodable ref, and this call cannot+ # prove billing from the status doc.+ warnings.warn(+ f"job {job_id} results are incomplete: retrieved {retrieved} of {total_items} items",+ stacklevel=2,+ )return {"job_id": job.get("id", job_id),- "state": job.get("state"),- "total_items": job.get("total_items"),+ "state": state,+ "total_items": total_items,"settled_credits": job.get("settled_credits"),"chunks": chunks,- "retrieved": len(items),+ "retrieved": retrieved,"dims": dims,"items": items,}- def wait(self, job_id: str, *, timeout_s: float = 600.0, poll_s: float = 2.0) -> JobStatus:- """Poll until terminal, or return a connector plan at its stable planned phase."""+ def wait(+ self,+ job_id: str,+ *,+ timeout_s: float = 600.0,+ poll_s: float = 2.0,+ raise_on_failure: bool = False,+ ) -> JobStatus:+ """Poll until terminal, or return a connector plan at its stable planned phase.++ With ``raise_on_failure=True`` a non-successful terminal+ (``failed``/``suspended``/``cancelled``) raises :class:`JobFailedError`+ carrying the status doc's ``outcome``/``error_code`` so the failure is+ actionable without re-reading the doc. The default is unchanged and+ back-compatible: every terminal (and the ``planned`` plan phase) is+ returned as-is.+ """deadline = time.monotonic() + timeout_swhile True:job = self.get(job_id)- if job.get("state") in TERMINAL_JOB_STATES or job.get("phase") == "planned":+ if job.get("phase") == "planned":+ return job+ state = job.get("state")+ if state in TERMINAL_JOB_STATES:+ if raise_on_failure and state != "succeeded":+ outcome = job.get("outcome")+ error_code = job.get("error_code")+ reason = f" (outcome={outcome!r}, error_code={error_code!r})" if outcome or error_code else ""+ msg = f"job {job_id} terminated {state!r}{reason}"+ raise JobFailedError(+ msg,+ job_id=job.get("id", job_id),+ state=state,+ outcome=outcome,+ error_code=error_code,+ )return jobif time.monotonic() >= deadline:- msg = f"job {job_id} still {job.get('state')!r} after {timeout_s:.0f}s"+ msg = f"job {job_id} still {state!r} after {timeout_s:.0f}s"raise RequestError(msg, code="job_wait_timeout", status_code=504)time.sleep(poll_s)diff --git a/packages/sie_sdk/src/sie_sdk/jobs.py b/packages/sie_sdk/src/sie_sdk/jobs.pyindex 9f4bdbfa3..bf23a8068 100644--- a/packages/sie_sdk/src/sie_sdk/jobs.py+++ b/packages/sie_sdk/src/sie_sdk/jobs.py@@ -19,11 +19,10 @@ from collections.abc import Mapping, Sequencefrom typing import TYPE_CHECKING, Any, Literalfrom urllib.parse import urlsplit-import msgpack-import msgpack_numpyimport numpy as np-from sie_sdk.types import JobChunk, JobResultItem+from sie_sdk._msgpack import unpackb as unpack_msgpack+from sie_sdk.types import JobChunk, JobItemErrorDetail, JobResultItemif TYPE_CHECKING:from numpy.typing import NDArray@@ -55,9 +54,6 @@ _POSTGRES_SCHEMA_PATTERN = re.compile(r"[A-Za-z_][A-Za-z0-9_$]{0,62}\Z", re.ASCI# mutation._CONNECTOR_IDEMPOTENCY_KEY_MAX_BYTES = 256-# msgpack + the numpy codec are hard deps of the SDK, so always importable here.-_RESULT_OBJECT_HOOK = msgpack_numpy.decode-def _norm_item(item: Any, index: int) -> dict[str, Any]:"""Normalize a job item to the ``/v1/encode`` item contract (``{text}``/``{id,text}``)."""@@ -358,29 +354,66 @@ def _dense_info(dense: Any) -> tuple[int | None, NDArray[Any] | None]:return (int(vector.shape[0]) if vector is not None else None), vector+def _result_item_error(result: Mapping[str, Any]) -> JobItemErrorDetail | None:+ """Extract a per-item failure from a ``WorkResult`` map (``error``/``error_code``).++ The gateway writes every item's ``WorkResult`` into the chunk ref — including+ failures, each carrying its own ``error`` (free text) and ``error_code`` — so+ a caller can see WHY a specific item failed. Returns ``None`` when the item+ reports no failure signal (a success, or a bare-count chunk error with no+ per-item detail).+ """+ code = result.get("error_code")+ message = result.get("error")+ if code is None and message is None:+ return None+ detail: JobItemErrorDetail = {}+ if code is not None:+ detail["code"] = code+ if message is not None:+ detail["message"] = message+ return detail++def decode_result_item(result: Any) -> JobResultItem:"""Decode one WorkResult map (from a chunk ref) into a per-item result.The chunk's ``result_msgpack`` bytes carry the same wire shape the realtimepath returns per item; the dense vector decodes to a numpy array (SDK-native,- like :meth:`SIEClient.encode`).+ like :meth:`SIEClient.encode`). A failed item carries no ``result_msgpack``+ but does carry ``success=False`` plus an ``error``/``error_code`` pair, which+ surfaces as :data:`JobResultItem.error`."""payload = result.get("result_msgpack") if isinstance(result, dict) else Nonedecoded: Any = Noneif isinstance(payload, (bytes, bytearray)):try:- decoded = msgpack.unpackb(payload, raw=False, object_hook=_RESULT_OBJECT_HOOK)+ decoded = unpack_msgpack(bytes(payload), numeric_arrays=True)except Exception: # noqa: BLE001 - a malformed payload should not abort retrievaldecoded = Nonedense = decoded.get("dense") if isinstance(decoded, dict) else Nonedims, vector = _dense_info(dense)+ if isinstance(result, dict):+ # The wire id is ``work_item_id``; older/inline results use ``id``. The+ # bare-count chunk error names no ids, so a per-item id comes only from+ # the item's own WorkResult (never fabricated). Fall back on an explicit+ # ``is None`` check, not ``or``: a falsy-but-valid id (integer ``0`` or an+ # empty string) is a real id and must be preserved, not replaced.+ item_id = result.get("id")+ if item_id is None:+ item_id = result.get("work_item_id")+ else:+ item_id = Noneitem: JobResultItem = {- "id": result.get("id") if isinstance(result, dict) else None,+ "id": item_id,"success": result.get("success") if isinstance(result, dict) else None,"units": result.get("units") if isinstance(result, dict) else None,"dims": dims,"dense": vector,}+ error = _result_item_error(result) if isinstance(result, dict) else None+ if error is not None:+ item["error"] = errorreturn item@@ -402,9 +435,33 @@ def job_chunks(job_doc: Mapping[str, Any]) -> list[JobChunk]:]+class MalformedChunkError(Exception):+ """A chunk ref's bytes could not be decoded as a msgpack ``WorkResult`` array.++ Distinct from a chunk that published no ref at all: the bytes exist but are+ garbage (not msgpack, or not a list). That is a DECODE fault, not evidence of+ failed publication or billing, so the caller flags it separately and never+ conflates it with a genuinely-unpublished, already-billed chunk.+ """++def decode_chunk_bytes(raw: bytes) -> list[JobResultItem]:- """Decode a chunk ref's msgpack ``WorkResult`` array into per-item results."""- results = msgpack.unpackb(raw, raw=False)+ """Decode a chunk ref's msgpack ``WorkResult`` array into per-item results.++ Raises:+ MalformedChunkError: If the ref's bytes are not decodable msgpack or do+ not decode to a list. The caller confines this (one bad chunk cannot+ sink the whole ``jobs.results()`` call) and reports it as a decode+ fault, distinct from an unpublished chunk. Per-item decoding stays+ defensive (see :func:`decode_result_item`).+ """+ try:+ results = unpack_msgpack(raw, numeric_arrays=False)+ except Exception as exc:+ # Normalize any decode failure (FormatError, ExtraData, ...) to one signal.+ msg = "chunk ref bytes are not decodable msgpack"+ raise MalformedChunkError(msg) from excif not isinstance(results, list):- return []+ msg = f"chunk ref decoded to {type(results).__name__}, not a WorkResult list"+ raise MalformedChunkError(msg)return [decode_result_item(r) for r in results]diff --git a/packages/sie_sdk/src/sie_sdk/redaction.py b/packages/sie_sdk/src/sie_sdk/redaction.pyindex e1d353a70..4e5401e90 100644--- a/packages/sie_sdk/src/sie_sdk/redaction.py+++ b/packages/sie_sdk/src/sie_sdk/redaction.py@@ -9,17 +9,68 @@ previously re-implemented per surface:- :func:`endpoint_origin_for_log` — credential- and query-free endpointorigin for diagnostics, consumed by the managed worker runtime and thedispatcher telemetry setup.+- :func:`redact_secrets` — scrubs credential- and PII-shaped substrings out+ of free text (a remote error body, a captured stderr) whose contents the+ caller does not control, before it reaches a terminal or a log.This lives in ``sie_sdk`` (not ``sie_server``) because every Pythonsurface that logs — server, managed worker runtime, dispatcher — has theSDK in its dependency closure, while the dispatcher deliberately does notdepend on ``sie_server``.++The benchmark campaign serializer keeps its own equivalent pattern tuple on+purpose: those patterns feed content-addressed campaign artifact digests, so+re-pointing them at this module would let an unrelated pattern change rewrite+committed artifact hashes."""from __future__ import annotations+import refrom urllib.parse import urlsplit+REDACTED = "[REDACTED]"++# Credential and PII shapes. Over-redaction is the safe failure mode here: the+# consumer is a diagnostic, and a scrubbed word costs less than a leaked token.+_SECRET_PATTERNS: tuple[re.Pattern[str], ...] = (+ re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{8,}"),+ re.compile(r"\bsk-[A-Za-z0-9_-]{16,}"),+ # AKIA is a long-lived access key, ASIA an STS temporary one. Temporary+ # does not mean harmless: an ASIA id still pairs with a live secret and+ # session token for the life of the session.+ re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),+ # A JWT, i.e. base64url header then payload then signature, dot separated.+ re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+"),+ # key=value / "key": "value" for any key that names a credential.+ re.compile(+ r"(?i)\b([\w.-]*(?:api[_-]?key|token|password|passwd|secret|credential)[\w.-]*)\"?\s*[:=]\s*\"?[^\s,;\"}]+"+ ),+ # Email addresses are the PII shape that actually shows up in error bodies.+ re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]*\w\b"),+)+++def _redaction_replacement(match: re.Match[str]) -> str:+ """Keep a matched key name, drop everything else."""+ if match.lastindex:+ return f"{match.group(1)}={REDACTED}"+ return REDACTED+++def redact_secrets(text: str) -> str:+ """Scrub credential- and PII-shaped substrings out of untrusted free text.++ Intended for text the caller did not author — a remote HTTP error body,+ captured subprocess output — that is about to be printed or logged. This+ is a best-effort scrubber, not a certified one: it is a last line of+ defence, never a licence to route secrets through a log in the first+ place.+ """+ for pattern in _SECRET_PATTERNS:+ text = pattern.sub(_redaction_replacement, text)+ return text+def mask_token(token: str) -> str:"""Mask a token for logs: keep the last 4 characters, star the rest."""diff --git a/packages/sie_sdk/src/sie_sdk/scoring.py b/packages/sie_sdk/src/sie_sdk/scoring.pyindex 5007d8303..b069014f2 100644--- a/packages/sie_sdk/src/sie_sdk/scoring.py+++ b/packages/sie_sdk/src/sie_sdk/scoring.py@@ -27,6 +27,16 @@ Example:>>>>>> # Compute MaxSim scores>>> scores = maxsim(query_result["multivector"], doc_vectors)++Naming differs from the TypeScript SDK and the two are not interchangeable:++=========================== =================================================+Python TypeScript+=========================== =================================================+``maxsim(q, docs) -> list`` ``maxsimDocuments(q, docs) -> number[]``+(no equivalent) ``maxsim(q, doc) -> number`` (one document)+``maxsim_batch -> [Q, D]`` ``maxsimBatch -> flat Float32Array`` (length Q*D)+=========================== ================================================="""from __future__ import annotations@@ -40,6 +50,43 @@ if TYPE_CHECKING:FloatMultivector = NDArray[np.float16] | NDArray[np.float32]+_MULTIVECTOR_NDIM = 2+++def _as_multivector(array: object, *, label: str) -> np.ndarray:+ """Coerce one multivector to a 2-D float array, or explain what is wrong.++ Callers of this module hold vectors they fetched back out of a vector+ database, so shape faults are the normal failure — a stored row read back+ flat, a corpus encoded with a different model, an empty result set. NumPy+ reports those in terms of its own gufunc signature+ (``(n?,k),(k,m?)->(n?,m?)``), which says nothing about queries, documents,+ or which side was wrong.+ """+ coerced = np.asarray(array, dtype=np.float32)+ if coerced.ndim != _MULTIVECTOR_NDIM:+ msg = (+ f"{label} must be a 2-D array of shape [num_tokens, dim], got shape {coerced.shape}. "+ "A single token vector needs an outer dimension (use `vector[None, :]`); "+ "a list of documents belongs in the `documents` argument, not here."+ )+ raise ValueError(msg)+ if coerced.shape[0] == 0:+ msg = f"{label} has 0 tokens (shape {coerced.shape}); MaxSim is undefined with no tokens to match."+ raise ValueError(msg)+ return coerced+++def _check_dim(query: np.ndarray, document: np.ndarray, *, index: int) -> None:+ """Reject a query/document embedding-width mismatch by name."""+ if query.shape[1] != document.shape[1]:+ msg = (+ f"dim mismatch: query has dim {query.shape[1]} but documents[{index}] has dim {document.shape[1]}. "+ "Both sides must come from the same model — check that the stored document vectors "+ "were produced by the model now encoding the query."+ )+ raise ValueError(msg)+def maxsim(query: FloatMultivector,@@ -66,6 +113,18 @@ def maxsim(Higher scores indicate greater relevance. Similarities and the finaltoken sum are accumulated in float32 for both float16 and float32 inputs.+ Raises:+ ValueError: If ``query`` or any document is not a 2-D+ ``[num_tokens, dim]`` array, has zero tokens, or has an embedding+ width that differs from the query's.++ Note:+ The TypeScript SDK's ``maxsim`` scores a *single* document and returns+ one number; its ``maxsimDocuments`` is the analogue of this function.+ The two SDKs' ``maxsimBatch``/``maxsim_batch`` also differ in return+ shape (flat array vs 2-D matrix). Do not port a call between them by+ name alone.+Example:>>> query = np.array([[1.0, 0.0], [0.0, 1.0]]) # 2 query tokens>>> doc1 = np.array([[1.0, 0.0], [0.5, 0.5]]) # 2 doc tokens@@ -74,24 +133,27 @@ def maxsim(>>> # scores[0] > scores[1] because doc1 matches both query tokens"""# Handle single document case (2D array = single document)- multivector_ndim = 2doc_list: list[FloatMultivector]- if isinstance(documents, np.ndarray) and documents.ndim == multivector_ndim:+ if isinstance(documents, np.ndarray) and documents.ndim == _MULTIVECTOR_NDIM:doc_list = cast("list[FloatMultivector]", [documents])elif isinstance(documents, np.ndarray):+ # A 3-D stack is a list of multivectors; anything else (notably a 1-D+ # vector passed unwrapped) is caught per-element by _as_multivector.doc_list = list(documents)else:doc_list = documents- query_f32 = np.asarray(query, dtype=np.float32)+ query_f32 = _as_multivector(query, label="query")scores: list[float] = []- for doc in doc_list:- # Compute all pairwise similarities: [num_query_tokens, num_doc_tokens]- # This is just matrix multiplication since vectors are L2-normalized.+ for index, doc in enumerate(doc_list):# Cast f16 transport values before matmul so NumPy does not accumulate# an entire late-interaction score at f16 precision.- doc_f32 = np.asarray(doc, dtype=np.float32)+ doc_f32 = _as_multivector(doc, label=f"documents[{index}]")+ _check_dim(query_f32, doc_f32, index=index)++ # Compute all pairwise similarities: [num_query_tokens, num_doc_tokens]+ # This is just matrix multiplication since vectors are L2-normalized.sim = np.matmul(query_f32, doc_f32.T)# For each query token, find max similarity with any doc token@@ -124,6 +186,15 @@ def maxsim_batch(scores[i, j] is the MaxSim score between query i and document j.Similarities and token sums are accumulated in float32.+ Raises:+ ValueError: If any query or document is not a 2-D+ ``[num_tokens, dim]`` array, has zero tokens, or has an embedding+ width that differs from the queries'.++ Note:+ The TypeScript SDK's ``maxsimBatch`` returns a *flat* array of length+ ``num_queries * num_documents``; this returns a 2-D matrix.+Example:>>> queries = [query1, query2] # 2 queries>>> docs = [doc1, doc2, doc3] # 3 documents@@ -133,14 +204,15 @@ def maxsim_batch(num_queries = len(queries)num_docs = len(documents)scores = np.zeros((num_queries, num_docs), dtype=np.float32)- queries_f32 = [np.asarray(query, dtype=np.float32) for query in queries]+ queries_f32 = [_as_multivector(query, label=f"queries[{i}]") for i, query in enumerate(queries)]# Cast one document at a time so f16-backed corpora are not duplicated in# full at f32 precision. Queries are typically the much smaller side and# stay cached across the document loop.for j, doc in enumerate(documents):- doc_f32 = np.asarray(doc, dtype=np.float32)+ doc_f32 = _as_multivector(doc, label=f"documents[{j}]")for i, query in enumerate(queries_f32):+ _check_dim(query, doc_f32, index=j)# Compute pairwise similaritiessim = np.matmul(query, doc_f32.T)# MaxSim: max over doc tokens, sum over query tokensdiff --git a/packages/sie_sdk/src/sie_sdk/storage.py b/packages/sie_sdk/src/sie_sdk/storage.pyindex 907ff217c..d8ed6b889 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/Azure/local paths.+"""Cloud storage abstraction for S3/GCS/Azure/Alibaba OSS/local paths.Provides a unified interface for:-- Detecting storage type from URL (s3://, gs://, abfs://, abfss://, local path)+- Detecting storage type from URL (s3://, gs://, abfs://, abfss://, oss://, local path)- Listing objects/files in a location- Downloading files to local cache- Checking if a path exists@@ -17,6 +17,7 @@ import contextlibimport fnmatchimport loggingimport os+import reimport shutilimport tempfileimport time@@ -24,13 +25,52 @@ from abc import ABC, abstractmethodfrom collections.abc import Iteratorfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom pathlib import Path-from typing import Any+from typing import Any, Neverfrom urllib.parse import urlparselogger = logging.getLogger(__name__)-CLOUD_SCHEMES = ("s3://", "gs://", "abfs://", "abfss://")+CLOUD_SCHEMES = ("s3://", "gs://", "abfs://", "abfss://", "oss://")AZURE_SCHEMES = ("abfs", "abfss")+OSS_BUCKET_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]{1,61}[a-z0-9]")+OSS_REGION_PATTERN = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)+")+OSS_RRSA_REQUIRED_ENV = (+ "ALIBABA_CLOUD_ROLE_ARN",+ "ALIBABA_CLOUD_OIDC_PROVIDER_ARN",+ "ALIBABA_CLOUD_OIDC_TOKEN_FILE",+)+++class _AlibabaCredentialsProvider:+ """Adapt the Alibaba Credentials client to the oss2 provider contract."""++ def __init__(self, client: Any) -> None:+ self._client = client++ def get_credentials(self) -> Any:+ """Return a freshly resolved credential for every OSS signature.++ The Alibaba Credentials client owns expiry caching and refresh. Its+ OIDC provider rereads the projected token file whenever STS credentials+ are refreshed, which is required for rotating ACK RRSA tokens.+ """+ try:+ credential = self._client.get_credential()+ except Exception: # noqa: BLE001 - sanitize every optional-provider failure at the credential boundary.+ raise RuntimeError("Alibaba Cloud credentials could not be resolved") from None++ access_key_id = getattr(credential, "access_key_id", None)+ access_key_secret = getattr(credential, "access_key_secret", None)+ security_token = getattr(credential, "security_token", None) or ""+ if not access_key_id or not access_key_secret:+ raise RuntimeError("Alibaba Cloud credentials are incomplete")++ try:+ from oss2.credentials import Credentials+ except ImportError as e:+ msg = "oss2 is required for Alibaba OSS storage; install the sie-sdk storage extra"+ raise ImportError(msg) from e+ return Credentials(access_key_id, access_key_secret, security_token)class StorageBackend(ABC):@@ -1319,11 +1359,363 @@ class AzureBlobBackend(StorageBackend):return count+class OSSBackend(StorageBackend):+ """Alibaba Cloud OSS backend using region-scoped Signature V4.++ ``oss://`` URLs intentionally contain only a bucket and object key. The+ region and public/internal endpoint selection are explicit runtime settings+ so an untrusted URL cannot redirect signed requests to another endpoint.+ """++ MAX_CONCURRENCY = 16+ REGION_ENV = "SIE_OSS_REGION"+ INTERNAL_ENDPOINT_ENV = "SIE_OSS_USE_INTERNAL_ENDPOINT"++ def __init__(self) -> None:+ self._credential_client: Any = None+ self._credentials_provider: Any = None+ self._auth: Any = None+ self._buckets: dict[str, Any] = {}+ self._region: str | None = None+ self._endpoint: str | None = None++ @staticmethod+ def _parse_oss_url(url: str) -> tuple[str, str]:+ """Parse a strict ``oss://bucket[/key]`` URL.++ Userinfo, ports, query strings, fragments, escaped separators, and+ path-normalization segments are rejected. This keeps credentials out+ of URLs and ensures every accepted object key has one unambiguous+ representation.+ """+ parsed = urlparse(url)+ if parsed.scheme != "oss":+ raise ValueError("Expected an oss:// URL")+ if parsed.params or parsed.query or parsed.fragment:+ raise ValueError("OSS URLs must not contain parameters, queries, or fragments")+ if parsed.username is not None or parsed.password is not None or "@" in parsed.netloc:+ raise ValueError("OSS URLs must not contain credentials")+ bucket = parsed.netloc+ if not OSS_BUCKET_PATTERN.fullmatch(bucket):+ raise ValueError("OSS URL must contain a valid 3-63 character bucket name")+ if parsed.path and not parsed.path.startswith("/"):+ raise ValueError("OSS object paths must begin after the bucket authority")++ key = parsed.path[1:] if parsed.path else ""+ if not key:+ return bucket, ""+ if len(key.encode("utf-8")) > 1023:+ raise ValueError("OSS object keys must not exceed 1023 UTF-8 bytes")+ if (+ "%" in key+ or "\\" in key+ or any(character.isspace() or ord(character) < 32 or ord(character) == 127 for character in key)+ ):+ raise ValueError("OSS object keys must not contain escapes, backslashes, whitespace, or control characters")++ # A single trailing slash is a valid directory-like prefix. All other+ # empty/dot segments are ambiguous under common path normalization.+ segments = key[:-1].split("/") if key.endswith("/") else key.split("/")+ if not segments or any(segment in {"", ".", ".."} for segment in segments):+ raise ValueError("OSS object keys must not contain empty, dot, or parent segments")+ return bucket, key++ @staticmethod+ def _require_object_key(key: str) -> None:+ if not key or key.endswith("/"):+ raise ValueError("OSS object operations require a non-empty object key")++ @staticmethod+ def _normalized_prefix(key: str) -> str:+ return f"{key}/" if key and not key.endswith("/") else key++ @classmethod+ def _resolve_runtime_endpoint(cls) -> tuple[str, str]:+ region = os.environ.get(cls.REGION_ENV, "").strip()+ if not OSS_REGION_PATTERN.fullmatch(region):+ raise ValueError(f"{cls.REGION_ENV} must be set to a valid Alibaba Cloud region")++ internal_value = os.environ.get(cls.INTERNAL_ENDPOINT_ENV, "false").strip().lower()+ if internal_value in {"true", "1", "yes", "on"}:+ internal = True+ elif internal_value in {"false", "0", "no", "off"}:+ internal = False+ else:+ raise ValueError(f"{cls.INTERNAL_ENDPOINT_ENV} must be a boolean")++ endpoint_kind = "-internal" if internal else ""+ return region, f"https://oss-{region}{endpoint_kind}.aliyuncs.com"++ @staticmethod+ def _build_credential_client() -> Any:+ rrsa_values = {name: os.environ.get(name) for name in OSS_RRSA_REQUIRED_ENV}+ configured = {name for name, value in rrsa_values.items() if value is not None}+ if configured:+ missing = [name for name, value in rrsa_values.items() if not value]+ if missing:+ joined = ", ".join(OSS_RRSA_REQUIRED_ENV)+ raise RuntimeError(f"Alibaba RRSA configuration is incomplete; set {joined} together")++ try:+ from alibabacloud_credentials.client import Client+ from alibabacloud_credentials.models import Config+ except ImportError as e:+ msg = "alibabacloud-credentials is required for Alibaba OSS storage; install the sie-sdk storage extra"+ raise ImportError(msg) from e++ if configured:+ config = Config(+ type="oidc_role_arn",+ # The fail-closed check above proves these values non-empty;+ # ``or ""`` only narrows the third-party model's annotations.+ role_arn=rrsa_values["ALIBABA_CLOUD_ROLE_ARN"] or "",+ oidc_provider_arn=rrsa_values["ALIBABA_CLOUD_OIDC_PROVIDER_ARN"] or "",+ oidc_token_file_path=rrsa_values["ALIBABA_CLOUD_OIDC_TOKEN_FILE"] or "",+ role_session_name=os.environ.get("ALIBABA_CLOUD_ROLE_SESSION_NAME") or "sie-oss",+ )+ return Client(config)+ return Client()++ def _get_bucket(self, bucket_name: str) -> Any:+ bucket = self._buckets.get(bucket_name)+ if bucket is not None:+ return bucket++ try:+ import oss2+ except ImportError as e:+ msg = "oss2 is required for Alibaba OSS storage; install the sie-sdk storage extra"+ raise ImportError(msg) from e++ if self._region is None or self._endpoint is None:+ self._region, self._endpoint = self._resolve_runtime_endpoint()+ if self._credential_client is None:+ self._credential_client = self._build_credential_client()+ if self._credentials_provider is None:+ self._credentials_provider = _AlibabaCredentialsProvider(self._credential_client)+ if self._auth is None:+ # oss2's HTTP and V4 debug traces include Authorization/security+ # token headers and signed canonical requests. Keep every oss2+ # child logger above DEBUG even when SIE itself runs at DEBUG.+ for logger_name in ("oss2", "oss2.auth", "oss2.http", "oss2.api"):+ logging.getLogger(logger_name).setLevel(logging.WARNING)+ logging.getLogger("alibabacloud_credentials").setLevel(logging.WARNING)+ self._auth = oss2.ProviderAuthV4(self._credentials_provider)++ bucket = oss2.Bucket(+ self._auth,+ self._endpoint,+ bucket_name,+ app_name="sie-sdk",+ region=self._region,+ )+ self._buckets[bucket_name] = bucket+ return bucket++ @staticmethod+ def _provider_error_details(error: Exception) -> tuple[int | None, str | None]:+ status = getattr(error, "status", None)+ if not isinstance(status, int):+ status = None+ code = getattr(error, "code", None)+ if not isinstance(code, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", code):+ code = None+ return status, code++ @classmethod+ def _raise_sanitized_error(cls, operation: str, error: Exception) -> Never:+ status, code = cls._provider_error_details(error)+ details = []+ if status is not None:+ details.append(f"status={status}")+ if code:+ details.append(f"code={code}")+ suffix = f" ({', '.join(details)})" if details else ""+ raise RuntimeError(f"Alibaba OSS {operation} failed{suffix}") from None++ @classmethod+ def _call(cls, operation: str, function: Any, *args: Any, **kwargs: Any) -> Any:+ try:+ return function(*args, **kwargs)+ except Exception as error: # noqa: BLE001 - sanitize every provider/network failure before it can escape.+ cls._raise_sanitized_error(operation, error)++ def _iter_list_pages(self, bucket: Any, prefix: str, *, delimiter: str) -> Iterator[Any]:+ continuation_token = ""+ seen_tokens: set[str] = set()+ while True:+ result = self._call(+ "list",+ bucket.list_objects_v2,+ prefix=prefix,+ delimiter=delimiter,+ continuation_token=continuation_token,+ max_keys=1000,+ )+ yield result+ if not getattr(result, "is_truncated", False):+ return+ next_token = getattr(result, "next_continuation_token", "")+ if not isinstance(next_token, str) or not next_token or next_token in seen_tokens:+ raise RuntimeError("Alibaba OSS list failed (invalid pagination state)")+ seen_tokens.add(next_token)+ continuation_token = next_token++ def list_dirs(self, path: str) -> Iterator[str]:+ """List immediate directory-like common prefixes."""+ bucket_name, key = self._parse_oss_url(path)+ prefix = self._normalized_prefix(key)+ bucket = self._get_bucket(bucket_name)+ for page in self._iter_list_pages(bucket, prefix, delimiter="/"):+ for child_prefix in getattr(page, "prefix_list", []):+ relative = child_prefix[len(prefix) :].rstrip("/")+ if relative and "/" not in relative:+ yield relative++ def list_files(self, path: str, pattern: str = "*") -> Iterator[str]:+ """List immediate objects matching ``pattern``."""+ bucket_name, key = self._parse_oss_url(path)+ prefix = self._normalized_prefix(key)+ bucket = self._get_bucket(bucket_name)+ for page in self._iter_list_pages(bucket, prefix, delimiter="/"):+ for obj in getattr(page, "object_list", []):+ object_key = getattr(obj, "key", "")+ if not isinstance(object_key, str) or not object_key.startswith(prefix):+ continue+ relative = object_key[len(prefix) :]+ if relative and "/" not in relative and fnmatch.fnmatch(relative, pattern):+ yield relative++ def download_file(self, src: str, dst: Path) -> None:+ """Download one OSS object to a local path."""+ bucket_name, key = self._parse_oss_url(src)+ self._require_object_key(key)+ dst.parent.mkdir(parents=True, exist_ok=True)+ bucket = self._get_bucket(bucket_name)+ self._call("download", bucket.get_object_to_file, key, str(dst))++ def exists(self, path: str) -> bool:+ """Check whether one exact OSS object exists."""+ bucket_name, key = self._parse_oss_url(path)+ self._require_object_key(key)+ bucket = self._get_bucket(bucket_name)+ try:+ return bool(bucket.object_exists(key))+ except Exception as error: # noqa: BLE001 - sanitize every provider/network failure before it can escape.+ self._raise_sanitized_error("exists", error)++ def has_children(self, path: str) -> bool:+ """Check whether an OSS prefix contains a non-marker child."""+ bucket_name, key = self._parse_oss_url(path)+ prefix = self._normalized_prefix(key)+ bucket = self._get_bucket(bucket_name)+ result = self._call(+ "list",+ bucket.list_objects_v2,+ prefix=prefix,+ delimiter="",+ continuation_token="",+ max_keys=2,+ )+ return any(+ isinstance(object_key := getattr(obj, "key", None), str) and object_key != prefix+ for obj in getattr(result, "object_list", [])+ )++ def read_text(self, path: str) -> str:+ """Read one UTF-8 OSS object."""+ bucket_name, key = self._parse_oss_url(path)+ self._require_object_key(key)+ bucket = self._get_bucket(bucket_name)+ result = self._call("read", bucket.get_object, key)+ try:+ data = self._call("read", result.read)+ finally:+ close = getattr(result, "close", None)+ if close is not None:+ with contextlib.suppress(Exception):+ close()+ try:+ return data.decode("utf-8")+ except (AttributeError, UnicodeDecodeError):+ raise RuntimeError("Alibaba OSS text object is not valid UTF-8") from None++ def write_text(self, path: str, content: str) -> None:+ """Write UTF-8 text to one OSS object."""+ bucket_name, key = self._parse_oss_url(path)+ self._require_object_key(key)+ bucket = self._get_bucket(bucket_name)+ self._call("write", bucket.put_object, key, content.encode("utf-8"))++ def delete_file(self, path: str) -> None:+ """Delete one OSS object; a missing object is already deleted."""+ bucket_name, key = self._parse_oss_url(path)+ self._require_object_key(key)+ bucket = self._get_bucket(bucket_name)+ try:+ bucket.delete_object(key)+ except Exception as error: # noqa: BLE001 - OSS SDK exceptions vary by response code; all are sanitized below.+ status, code = self._provider_error_details(error)+ if status == 404 or code in {"NoSuchKey", "NoSuchObject"}:+ return+ self._raise_sanitized_error("delete", error)++ def try_server_side_copy(self, src: str, dst: str) -> bool:+ """Attempt an OSS-native copy, falling back to the caller's relay."""+ if not (src.startswith("oss://") and dst.startswith("oss://")):+ return False+ src_bucket, src_key = self._parse_oss_url(src)+ dst_bucket, dst_key = self._parse_oss_url(dst)+ self._require_object_key(src_key)+ self._require_object_key(dst_key)+ bucket = self._get_bucket(dst_bucket)+ try:+ bucket.copy_object(src_bucket, src_key, dst_key)+ except Exception as error: # noqa: BLE001 - copy failures deliberately fall back without leaking SDK details.+ status, code = self._provider_error_details(error)+ logger.warning(+ "Alibaba OSS server-side copy failed; falling back to download+upload",+ extra={"provider_status": status, "provider_error_code": code},+ )+ return False+ return True++ def upload_file(self, src: Path, dst: str) -> None:+ """Upload one local file to OSS."""+ bucket_name, key = self._parse_oss_url(dst)+ self._require_object_key(key)+ bucket = self._get_bucket(bucket_name)+ self._call("upload", bucket.put_object_from_file, key, str(src))++ def upload_directory(self, src: Path, dst: str) -> int:+ """Upload a local directory recursively with bounded parallelism."""+ bucket_name, base_key = self._parse_oss_url(dst)+ bucket = self._get_bucket(bucket_name)+ files_to_upload: list[tuple[Path, str]] = []+ for file in src.rglob("*"):+ if file.is_file():+ relative = file.relative_to(src).as_posix()+ key = f"{base_key.rstrip('/')}/{relative}" if base_key else relative+ files_to_upload.append((file, key))+ if not files_to_upload:+ return 0++ def upload_one(item: tuple[Path, str]) -> None:+ file, key = item+ self._call("upload", bucket.put_object_from_file, key, str(file))++ with ThreadPoolExecutor(max_workers=self.MAX_CONCURRENCY) as executor:+ futures = [executor.submit(upload_one, item) for item in files_to_upload]+ for future in as_completed(futures):+ future.result()+ return len(files_to_upload)++def get_storage_backend(path: str) -> StorageBackend:"""Get the appropriate storage backend for a path.Args:- path: A local path, S3 URL (s3://...), GCS URL (gs://...), or Azure URL (abfs(s)://...).+ path: A local path or a supported object-store URL.Returns:The appropriate StorageBackend instance.@@ -1334,17 +1726,19 @@ def get_storage_backend(path: str) -> StorageBackend:return GCSBackend()if path.startswith(("abfs://", "abfss://")):return AzureBlobBackend()+ if path.startswith("oss://"):+ return OSSBackend()return LocalBackend()def is_cloud_path(path: str) -> bool:- """Check if a path is a cloud URL (S3, GCS, or Azure Blob).+ """Check if a path is a supported cloud-object-store URL.Args:path: Path to check.Returns:- True if path is an S3, GCS, or Azure Blob URL.+ True if path is an S3, GCS, Azure Blob, or Alibaba OSS URL."""return path.startswith(CLOUD_SCHEMES)@@ -1353,7 +1747,7 @@ def join_path(base: str, *parts: str) -> str:"""Join path components, handling both local and cloud paths.Args:- base: Base path (local, S3, GCS, or Azure Blob).+ base: Base path (local, S3, GCS, Azure Blob, or Alibaba OSS).*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 c9b0c4b99..c556e4e12 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -35,7 +35,7 @@ OutputType = Literal["dense", "sparse", "multivector"]# Model state (for status messages).# ``failed`` is the terminal branch added for non-retryable load failures-# (gated repos, missing dependencies, etc.). See sie-test#85 for context.+# (gated repos, missing dependencies, etc.).ModelState = Literal["available", "loading", "loaded", "unloading", "failed"]@@ -173,6 +173,34 @@ class RequestUsage(TypedDict, total=False):rate_book_version: str+#: The metered dimensions of :class:`RequestUsage` — the units a consumer+#: prices. Every member is a non-negative integer count.+TERMINAL_UNIT_FIELDS: frozenset[str] = frozenset(+ {"audio_ms", "images", "input_tokens", "output_tokens", "pages", "pairs"}+)++#: The settled-charge annotations of :class:`RequestUsage`. The gateway is+#: their only writer; it adds them to the `usage` block of every settled+#: response it can rewrite. They are NOT metered dimensions and must never be+#: summed as one.+SETTLED_CHARGE_FIELDS: frozenset[str] = frozenset({"credits_charged", "rate_book_version"})++#: Every key the `usage` block is allowed to carry, as a single set.+#:+#: A consumer that meters this block should fail closed on a key OUTSIDE this+#: union — an undeclared key is a renamed or unrecognised meter, and silently+#: dropping one produces confident, wrong billing evidence. It must NOT fail+#: closed on the settled-charge annotations, which are a legitimate producer+#: extension of the same block: doing so nulled every terminal-unit reading on+#: the managed path (issue #3063).+#:+#: The partition is pinned language-neutrally in+#: `packages/wire-fixtures/request_usage.json`, which the gateway asserts+#: against too, so a gateway that starts publishing a third field cannot reach+#: production before this declaration follows it.+DECLARED_USAGE_FIELDS: frozenset[str] = TERMINAL_UNIT_FIELDS | SETTLED_CHARGE_FIELDS++class RequestMetadata(TypedDict, total=False):"""Gateway metadata from the successful terminal response.@@ -259,20 +287,108 @@ class ModelCapabilities(TypedDict, total=False):guard: bool+class ProfileInfo(TypedDict, total=False):+ """One entry of ``ModelInfo.profiles``.++ Mirrors the server's ``sie_server.api.models.ProfileInfo`` and the+ gateway's ``ProfileInfoWire``. ``is_default`` marks the profile served+ when a request names the bare model id rather than ``model@profile``.+ """++ is_default: bool+++class ModelLoadError(TypedDict, total=False):+ """Diagnostic detail for a recorded load failure.++ Present as ``ModelInfo.last_error`` when the registry holds a sticky+ failure for the model (normally alongside ``state == "failed"``);+ ``None`` otherwise. Mirrors the server's+ ``sie_server.api.models.ModelLoadError``.++ ``permanent`` is the field to branch on: ``True`` means the load will+ not auto-retry and an operator must intervene, so a client should+ surface the failure rather than poll.+ """++ code: str # Stable enum value ("GATED", "OOM", ...) for client routing+ message: str+ attempts: int+ permanent: bool+++class PendingGenerationGroup(TypedDict, total=False):+ """Queue-depth breakdown for one (model, pool) pair."""++ model: str+ display_model: str+ pool: str+ count: int+ waiting_first_chunk: int+ active_streams: int+ republished: int+ oldest_request_age_ms: int+++class PendingGeneration(TypedDict, total=False):+ """In-flight generation work the gateway holds for a model.++ Gateway-only: a single ``sie_server`` has no queue and omits the field.+ This is a point-in-time telemetry snapshot, not model metadata — for+ continuous monitoring prefer ``SIEClient.watch()`` over polling+ ``/v1/models``.+ """++ total: int+ groups: list[PendingGenerationGroup]++class ModelInfo(TypedDict, total=False):"""Information about a model returned by list_models().Note: Server returns flat structure with inputs/outputs at top level.++ The declared key set is pinned by ``packages/wire-fixtures/model_info.json``+ and enforced in ``tests/test_wire_contract.py``. The OpenAI-compat keys+ ``id``/``object``/``created``/``owned_by`` that ``GET /v1/models/{model}``+ merges in are deliberately excluded — see that fixture for why."""name: strloaded: bool+ """Backwards-compatible boolean. Prefer ``state`` for the full lifecycle."""++ state: ModelState+ """Lifecycle state, including the terminal ``failed`` branch.++ ``loaded`` cannot distinguish ``available`` from ``loading`` from+ ``failed`` — all three report ``False``.+ """++ last_error: ModelLoadError | None+ """Recorded load failure (when ``state == "failed"``), else ``None``."""+inputs: list[str] # ["text"], ["text", "image"], etc.outputs: list[str] # ["dense"], ["dense", "sparse"], etc.dims: ModelDims- max_sequence_length: int+ max_sequence_length: int | Nonerevision: str | None- capabilities: ModelCapabilities+ profiles: dict[str, ProfileInfo]+ """Servable profiles keyed by name; address one as ``"model@profile"``."""++ capabilities: ModelCapabilities | None+ """``None`` for models that declare no ``generate`` task."""++ pending_generation: PendingGeneration+ """Gateway-only queue snapshot; absent when talking to a single server."""++ aliases: list[str]+ """Short task-tier names resolving to this model, e.g. ``["rerank-fast"]``.++ Send one anywhere a model id is accepted. Always emitted and empty when the+ model has none; the gateway's compiled-in routing defaults are not public+ API and never appear here.+ """class ScoreEntry(TypedDict):@@ -1209,6 +1325,47 @@ class AppliedRate(TypedDict):rate_denominator: int+class RecommendedChoice(TypedDict, total=False):+ """One tier's pick for a task family, with the evidence behind it."""++ intent: str+ model: str+ runtime_id: str+ profile: str+ alias: str | None+ available: bool+ quality_ref: str | None+ performance_ref: str | None+ measurement_status: str | None+ evidence_guarded: bool+ """Whether a committed target floor guards the cited number.++ A cited measurement with no floor is a real number that nothing protects+ from silently regressing. False does not mean unmeasured; it means+ unguarded.+ """+++class Recommendation(TypedDict, total=False):+ """The answer for one task family (``POST /v1/recommend``)."""++ task: str+ label: str+ basis: str+ """``ranked`` | ``curated`` | ``no_evidence``.++ ``ranked`` means two or more choices were measured on the same benchmark.+ ``curated`` means evidence exists but no two choices share one, so the+ order is the catalog's judgement rather than a measurement. ``no_evidence``+ means the family cites no measurements at all. The three are distinct on+ purpose: a recommendation whose basis cannot be checked is worth less than+ no recommendation.+ """+ shared_benchmarks: list[str]+ fast: RecommendedChoice+ best: RecommendedChoice++class CostEstimate(TypedDict):"""A dispatch-free quote from ``POST /v1/estimate``.@@ -1484,14 +1641,36 @@ class JobList(TypedDict, total=False):data: list[JobStatus]+class JobItemErrorDetail(TypedDict, total=False):+ """Stable per-item job failure (mirrors :class:`ExtractItemErrorDetail`).++ Decoded from the failed item's ``WorkResult`` in a chunk ref: ``code`` is+ the worker's ``error_code`` and ``message`` its free-text ``error``. Either+ may be absent, so both keys are optional.+ """++ code: str+ message: str++class JobResultItem(TypedDict, total=False):- """One decoded per-item result retrieved from a finished job's chunk refs."""+ """One decoded per-item result retrieved from a finished job's chunk refs.++ A ``failed`` chunk still writes a result ref carrying every item's+ ``WorkResult`` — successful siblings AND the failures — so ``success``+ distinguishes them and ``error`` carries the failure reason when the item+ did not succeed.+ """- id: str | None+ #: Per-item id echoed from the item's ``WorkResult`` (``id`` or the wire's+ #: ``work_item_id``). Ids may be integers, so ``0`` is a valid id, not absent.+ id: str | int | Nonesuccess: bool | Noneunits: Anydims: int | Nonedense: Any+ #: Per-item failure reason, present only when the item did not succeed.+ error: JobItemErrorDetailclass JobResults(TypedDict, total=False):diff --git a/packages/sie_sdk/tests/client/test_backpressure_billing.py b/packages/sie_sdk/tests/client/test_backpressure_billing.pynew file mode 100644index 000000000..c7a02db8d--- /dev/null+++ b/packages/sie_sdk/tests/client/test_backpressure_billing.py@@ -0,0 +1,359 @@+# Tests for the pass-2 audit backpressure / billing signals the gateway emits+# that the SDK previously discarded:+#+# B1 — 429 RATE_LIMIT -> retried (Retry-After), typed RateLimitError on give-up+# B2 — 503 BILLING_CAPACITY_UNAVAILABLE -> retried (Retry-After), terminal ServerError on give-up+# B7 — 503 QUEUE_FULL -> retried (Retry-After)+# B3 — 402/403 credit & account failures -> TERMINAL, typed, NEVER retried (single attempt)+#+# Mirrors the harness in ``test_oom_retry.py``: stub the underlying transport+# with a canned response sequence, patch the sleep to a no-op, and assert the+# retry count / honored Retry-After / final typed error. ``time.monotonic`` is+# stubbed only where a give-up must be forced within the provision-timeout+# budget.++from __future__ import annotations++import asyncio # noqa: F401 — referenced via the async sleep patch target+import json+import time+from unittest.mock import AsyncMock, MagicMock, patch++import msgpack+import numpy as np+import pytest+from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk.client._shared import handle_error+from sie_sdk.client.async_ import _AioResponse+from sie_sdk.client.errors import (+ AccountInactiveError,+ AccountStateUnavailableError,+ InsufficientCreditsError,+ RateLimitError,+ RequestError,+ ServerError,+ SpendLimitError,+)++# --------------------------------------------------------------------------+# Sync response fixtures+# --------------------------------------------------------------------------+++def _resp_429(retry_after: str = "0.01") -> MagicMock:+ resp = MagicMock()+ resp.status_code = 429+ resp.headers = {+ "Retry-After": retry_after,+ "content-type": "application/json",+ "X-SIE-Error-Code": "RATE_LIMIT",+ }+ resp.json.return_value = {"detail": {"code": "RATE_LIMIT", "message": "rate limited"}}+ return resp+++def _resp_503(code: str, retry_after: str = "0.01") -> MagicMock:+ resp = MagicMock()+ resp.status_code = 503+ resp.headers = {"Retry-After": retry_after, "content-type": "application/json"}+ resp.json.return_value = {"detail": {"code": code, "message": code.lower()}}+ return resp+++def _resp_terminal(status: int, code: str) -> MagicMock:+ resp = MagicMock()+ resp.status_code = status+ resp.headers = {"content-type": "application/json"}+ resp.json.return_value = {"detail": {"code": code, "message": code.lower()}}+ resp.text = json.dumps(resp.json.return_value)+ return resp+++def _resp_200_encode() -> MagicMock:+ resp = MagicMock()+ resp.status_code = 200+ resp.headers = {"content-type": "application/msgpack"}+ resp.content = msgpack.packb(+ {"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]},+ use_bin_type=True,+ )+ return resp+++# ``time.monotonic`` stub: first call (start_time) and the loop-top elapsed+# check stay within budget; the admission-ladder elapsed check jumps past it so+# the give-up branch fires without a second network round-trip.+def _exhausted_ticks(base: float = 1000.0) -> object:+ return iter([base, base, base + 100.0, base + 100.0, base + 100.0, base + 100.0])+++# --------------------------------------------------------------------------+# B1 — 429 rate limit (sync)+# --------------------------------------------------------------------------+++class TestSyncRateLimit:+ def test_retry_then_success_honors_retry_after(self) -> None:+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep") as mock_sleep,+ ):+ mock_client.return_value.post = MagicMock(+ side_effect=[_resp_429("0.02"), _resp_429("0.02"), _resp_200_encode()]+ )+ client = SIEClient("http://localhost:8080")++ result = client.encode("bge-m3", {"text": "hi"})++ assert result["dense"].shape == (4,)+ assert mock_client.return_value.post.call_count == 3+ # Server Retry-After honored verbatim on every retry.+ assert [c.args[0] for c in mock_sleep.call_args_list] == [0.02, 0.02]+ client.close()++ def test_giveup_raises_rate_limit_error(self) -> None:+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep"),+ patch.object(time, "monotonic", side_effect=_exhausted_ticks()),+ ):+ mock_client.return_value.post = MagicMock(side_effect=[_resp_429("30"), _resp_200_encode()])+ client = SIEClient("http://localhost:8080")++ with pytest.raises(RateLimitError) as excinfo:+ client.encode("bge-m3", {"text": "hi"}, provision_timeout_s=10.0)++ assert excinfo.value.status_code == 429+ assert excinfo.value.retry_after == 30.0+ # Budget spent on the first 429 — no second network round-trip.+ assert mock_client.return_value.post.call_count == 1+ client.close()+++# --------------------------------------------------------------------------+# B2 / B7 — retryable 503 backpressure (sync)+# --------------------------------------------------------------------------+++class TestSyncBackpressure503:+ @pytest.mark.parametrize("code", ["BILLING_CAPACITY_UNAVAILABLE", "QUEUE_FULL"])+ def test_retry_then_success(self, code: str) -> None:+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep") as mock_sleep,+ ):+ mock_client.return_value.post = MagicMock(side_effect=[_resp_503(code, "1"), _resp_200_encode()])+ client = SIEClient("http://localhost:8080")++ result = client.encode("bge-m3", {"text": "hi"})++ assert result["dense"].shape == (4,)+ assert mock_client.return_value.post.call_count == 2+ assert mock_sleep.call_args_list[0].args[0] == 1.0 # Retry-After honored+ client.close()++ def test_giveup_raises_server_error_preserving_code(self) -> None:+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep"),+ patch.object(time, "monotonic", side_effect=_exhausted_ticks()),+ ):+ mock_client.return_value.post = MagicMock(+ side_effect=[_resp_503("BILLING_CAPACITY_UNAVAILABLE", "1"), _resp_200_encode()]+ )+ client = SIEClient("http://localhost:8080")++ with pytest.raises(ServerError) as excinfo:+ client.encode("bge-m3", {"text": "hi"}, provision_timeout_s=10.0)++ assert excinfo.value.status_code == 503+ assert excinfo.value.code == "BILLING_CAPACITY_UNAVAILABLE"+ # Terminal 503 must NOT be a RateLimitError.+ assert not isinstance(excinfo.value, RateLimitError)+ assert mock_client.return_value.post.call_count == 1+ client.close()+++# --------------------------------------------------------------------------+# B3 — terminal credit / account failures (sync) — NEVER retried+# --------------------------------------------------------------------------+++class TestSyncTerminalBillingErrors:+ @pytest.mark.parametrize(+ ("status", "code", "exc"),+ [+ (402, "INSUFFICIENT_CREDITS", InsufficientCreditsError),+ (402, "KEY_SPEND_LIMIT_EXCEEDED", SpendLimitError),+ (403, "ACCOUNT_SUSPENDED", AccountInactiveError),+ (403, "ACCOUNT_PENDING_REVIEW", AccountInactiveError),+ (503, "ACCOUNT_STATE_UNAVAILABLE", AccountStateUnavailableError),+ ],+ )+ def test_terminal_typed_and_not_retried(self, status: int, code: str, exc: type[Exception]) -> None:+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep") as mock_sleep,+ ):+ # A 200 is queued AFTER the failure to prove the SDK never reaches it.+ mock_client.return_value.post = MagicMock(side_effect=[_resp_terminal(status, code), _resp_200_encode()])+ client = SIEClient("http://localhost:8080")++ with pytest.raises(exc) as excinfo:+ client.encode("bge-m3", {"text": "hi"})++ assert getattr(excinfo.value, "code", None) == code+ assert getattr(excinfo.value, "status_code", None) == status+ # Single attempt — no retry, no sleep.+ assert mock_client.return_value.post.call_count == 1+ assert mock_sleep.call_count == 0+ client.close()+++# --------------------------------------------------------------------------+# Async response fixtures+# --------------------------------------------------------------------------+++def _aio_429(retry_after: str = "0.01") -> object:+ return _AioResponse(+ 429,+ json.dumps({"detail": {"code": "RATE_LIMIT", "message": "rate limited"}}).encode(),+ {"Retry-After": retry_after, "content-type": "application/json", "X-SIE-Error-Code": "RATE_LIMIT"},+ )+++def _aio_503(code: str, retry_after: str = "0.01") -> object:+ return _AioResponse(+ 503,+ json.dumps({"detail": {"code": code, "message": code.lower()}}).encode(),+ {"Retry-After": retry_after, "content-type": "application/json"},+ )+++def _aio_terminal(status: int, code: str) -> object:+ return _AioResponse(+ status,+ json.dumps({"detail": {"code": code, "message": code.lower()}}).encode(),+ {"content-type": "application/json"},+ )+++def _aio_200_encode() -> object:+ return _AioResponse(+ 200,+ msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True),+ {"content-type": "application/msgpack"},+ )+++# --------------------------------------------------------------------------+# Async client+# --------------------------------------------------------------------------+++class TestAsyncBackpressureBilling:+ @pytest.mark.asyncio+ async def test_rate_limit_retry_then_success(self) -> None:+ with (+ patch("sie_sdk.client.async_.aiohttp.ClientSession"),+ patch("sie_sdk.client.async_.asyncio.sleep") as mock_sleep,+ ):+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(side_effect=[_aio_429("0.02"), _aio_200_encode()])++ result = await client.encode("bge-m3", {"text": "hi"})++ assert result["dense"].shape == (4,)+ assert client._post.await_count == 2+ assert mock_sleep.call_args_list[0].args[0] == 0.02+ await client.close()++ @pytest.mark.asyncio+ async def test_rate_limit_giveup_raises(self) -> None:+ with (+ patch("sie_sdk.client.async_.aiohttp.ClientSession"),+ patch("sie_sdk.client.async_.asyncio.sleep"),+ patch.object(time, "monotonic", side_effect=_exhausted_ticks()),+ ):+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(side_effect=[_aio_429("30"), _aio_200_encode()])++ with pytest.raises(RateLimitError) as excinfo:+ await client.encode("bge-m3", {"text": "hi"}, provision_timeout_s=10.0)++ assert excinfo.value.retry_after == 30.0+ assert client._post.await_count == 1+ await client.close()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("code", ["BILLING_CAPACITY_UNAVAILABLE", "QUEUE_FULL"])+ async def test_backpressure_503_retry_then_success(self, code: str) -> None:+ with (+ patch("sie_sdk.client.async_.aiohttp.ClientSession"),+ patch("sie_sdk.client.async_.asyncio.sleep") as mock_sleep,+ ):+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(side_effect=[_aio_503(code, "1"), _aio_200_encode()])++ result = await client.encode("bge-m3", {"text": "hi"})++ assert result["dense"].shape == (4,)+ assert client._post.await_count == 2+ assert mock_sleep.call_args_list[0].args[0] == 1.0+ await client.close()++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("status", "code", "exc"),+ [+ (402, "INSUFFICIENT_CREDITS", InsufficientCreditsError),+ (402, "KEY_SPEND_LIMIT_EXCEEDED", SpendLimitError),+ (403, "ACCOUNT_SUSPENDED", AccountInactiveError),+ (403, "ACCOUNT_PENDING_REVIEW", AccountInactiveError),+ (503, "ACCOUNT_STATE_UNAVAILABLE", AccountStateUnavailableError),+ ],+ )+ async def test_terminal_typed_and_not_retried(self, status: int, code: str, exc: type[Exception]) -> None:+ with (+ patch("sie_sdk.client.async_.aiohttp.ClientSession"),+ patch("sie_sdk.client.async_.asyncio.sleep") as mock_sleep,+ ):+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(side_effect=[_aio_terminal(status, code), _aio_200_encode()])++ with pytest.raises(exc) as excinfo:+ await client.encode("bge-m3", {"text": "hi"})++ assert getattr(excinfo.value, "code", None) == code+ assert client._post.await_count == 1+ assert mock_sleep.call_count == 0+ await client.close()+++# --------------------------------------------------------------------------+# Direct handle_error mapping (covers terminal / streaming / list paths)+# --------------------------------------------------------------------------+++class TestHandleErrorMapping:+ @pytest.mark.parametrize(+ ("status", "code", "exc"),+ [+ (429, "RATE_LIMIT", RateLimitError),+ (402, "INSUFFICIENT_CREDITS", InsufficientCreditsError),+ (402, "KEY_SPEND_LIMIT_EXCEEDED", SpendLimitError),+ (403, "ACCOUNT_SUSPENDED", AccountInactiveError),+ (403, "ACCOUNT_PENDING_REVIEW", AccountInactiveError),+ (503, "ACCOUNT_STATE_UNAVAILABLE", AccountStateUnavailableError),+ ],+ )+ def test_handle_error_maps_code(self, status: int, code: str, exc: type[Exception]) -> None:+ with pytest.raises(exc):+ handle_error(_resp_terminal(status, code))++ def test_unrecognized_403_stays_generic(self) -> None:+ # A 403 with a NON-account code must not become AccountInactiveError.+ with pytest.raises(RequestError) as excinfo:+ handle_error(_resp_terminal(403, "INVALID_KEY"))+ assert not isinstance(excinfo.value, AccountInactiveError)diff --git a/packages/sie_sdk/tests/client/test_base_url_headers.py b/packages/sie_sdk/tests/client/test_base_url_headers.pyindex db80bf528..967d2ad5d 100644--- a/packages/sie_sdk/tests/client/test_base_url_headers.py+++ b/packages/sie_sdk/tests/client/test_base_url_headers.py@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytestfrom sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk.client._shared import modal_continuation_pathfrom sie_sdk.client.async_ import _AioResponseBASE_URL = "https://gateway.example.test"@@ -158,7 +159,13 @@ def test_async_rejects_edge_header_that_would_override_connector_idempotency() -],)def test_sync_rejects_origin_credentials_without_secure_absolute_origin(base_url: str) -> None:- with patch("sie_sdk.client.sync.httpx.Client"), pytest.raises(ValueError, match="absolute https"):+ # A scheme-less base_url is rejected even earlier by the generic+ # construction-time scheme validation; either ValueError upholds the+ # "no edge headers without a secure absolute origin" property.+ with (+ patch("sie_sdk.client.sync.httpx.Client"),+ pytest.raises(ValueError, match=r"absolute https|http:// or https://"),+ ):SIEClient(base_url, base_url_headers=EDGE_HEADERS)@@ -328,5 +335,47 @@ async def test_async_adversarial_redirect_ref_is_not_followed_or_credentialed()],)def test_async_rejects_origin_credentials_without_secure_absolute_origin(base_url: str) -> None:- with pytest.raises(ValueError, match="absolute https"):+ # A scheme-less base_url is rejected even earlier by the generic+ # construction-time scheme validation; either ValueError upholds the+ # "no edge headers without a secure absolute origin" property.+ with pytest.raises(ValueError, match=r"absolute https|http:// or https://"):SIEAsyncClient(base_url, base_url_headers=EDGE_HEADERS)+++ "location",+ [+ "https://attacker.example/result?__modal_attempt_token=opaque",+ "https://gateway.example.test.attacker.example/result?__modal_attempt_token=opaque",+ "http://gateway.example.test/result?__modal_attempt_token=opaque",+ "https://[email protected]/result?__modal_attempt_token=opaque",+ "/result",+ "/result?__modal_attempt_token=",+ "/result?__modal_attempt_token=one&__modal_attempt_token=two",+ "/result?__modal_attempt_token=opaque#fragment",+ "/result?__modal_attempt_token=opaque\r\nX-Evil:true",+ ],+)+def test_modal_continuation_rejects_adversarial_locations(location: str) -> None:+ response = MagicMock(status_code=303, headers={"Location": location}, content=b"")++ assert modal_continuation_path("https://gateway.example.test", response) is None+++ ("location", "expected"),+ [+ (+ "/v1/generate/m?existing=1&__modal_attempt_token=opaque",+ "/v1/generate/m?existing=1&__modal_attempt_token=opaque",+ ),+ (+ "https://gateway.example.test/v1/generate/m?__modal_attempt_token=opaque",+ "/v1/generate/m?__modal_attempt_token=opaque",+ ),+ ],+)+def test_modal_continuation_accepts_only_exact_origin_attempt_urls(location: str, expected: str) -> None:+ response = MagicMock(status_code=303, headers={"location": location}, content=b"")++ assert modal_continuation_path("https://gateway.example.test", response) == expecteddiff --git a/packages/sie_sdk/tests/client/test_base_url_validation.py b/packages/sie_sdk/tests/client/test_base_url_validation.pynew file mode 100644index 000000000..aa0319251--- /dev/null+++ b/packages/sie_sdk/tests/client/test_base_url_validation.py@@ -0,0 +1,55 @@+"""Construction-time base_url scheme validation (both clients).++A scheme-less base_url ("localhost:8080") previously surfaced only at request+time — as an opaque ``httpx.UnsupportedProtocol`` on the sync client — or was+silently retried as a connect failure for the whole provision budget. Both+clients must reject it eagerly with a pointed ``ValueError``.+"""++from __future__ import annotations++import pytest+from sie_sdk import SIEAsyncClient, SIEClient++_BAD_BASE_URLS = [+ "localhost:8080",+ "example.com",+ "//host:8080",+ "ftp://host:21",+ "unix:///tmp/sie.sock",+ "",+ # Valid scheme but no host — parses, cannot be connected to.+ "http:///v1",+ "https:///v1",+ "http://",+ "http://:8080",+ # Textual / out-of-range port — must fail at construction, not at request time.+ "http://host:notaport",+ "http://host:99999",+]++[email protected]("bad", _BAD_BASE_URLS)+def test_sync_client_rejects_base_url_without_http_scheme(bad: str) -> None:+ with pytest.raises(ValueError, match="http:// or https://"):+ SIEClient(bad)++[email protected]("bad", _BAD_BASE_URLS)+def test_async_client_rejects_base_url_without_http_scheme(bad: str) -> None:+ with pytest.raises(ValueError, match="http:// or https://"):+ SIEAsyncClient(bad)++[email protected]("good", ["http://localhost:8080", "https://gateway.example.com", "HTTP://localhost:8080"])+async def test_clients_accept_http_and_https_base_urls(good: str) -> None:+ client = SIEClient(good)+ client.close()+ async_client = SIEAsyncClient(good)+ try:+ assert async_client is not None+ finally:+ # Close the async client so its aiohttp session/destructor cannot emit+ # a ResourceWarning.+ await async_client.close()diff --git a/packages/sie_sdk/tests/client/test_chat.py b/packages/sie_sdk/tests/client/test_chat.pyindex 4e69965ef..64afc8268 100644--- a/packages/sie_sdk/tests/client/test_chat.py+++ b/packages/sie_sdk/tests/client/test_chat.py@@ -125,6 +125,32 @@ def test_chat_completions_parses_and_sends_json_shape() -> None:client.close()+def test_chat_completions_consumes_modal_continuation_without_reposting() -> None:+ payload = {+ "id": "chatcmpl-1",+ "object": "chat.completion",+ "created": 0,+ "model": "m",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "Hi"}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ }+ redirect = MagicMock(+ status_code=303,+ headers={"Location": "/v1/chat/completions?__modal_attempt_token=opaque"},+ content=b"",+ )+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.post.return_value = redirect+ mc.return_value.get.return_value = _ok_json(payload)+ client = SIEClient("https://gateway.example.test")+ out = client.chat_completions("m", [{"role": "user", "content": "hi"}])+ client.close()++ assert out["choices"][0]["message"]["content"] == "Hi"+ assert mc.return_value.post.call_count == 1+ assert mc.return_value.get.call_args.args[0] == "/v1/chat/completions?__modal_attempt_token=opaque"++def test_stream_chat_completions_yields_chunks_and_sets_stream_flag() -> None:lines = _sse(_chat_chunk("He"), _chat_chunk("llo", finish="stop"))with patch("sie_sdk.client.sync.httpx.Client") as mc:@@ -239,6 +265,121 @@ def test_stream_raises_server_error_on_error_chunk() -> None:with pytest.raises(ServerError) as ei:list(client.stream_generate("m", "hi", max_new_tokens=8))assert ei.value.code == "inference_error"+ assert ei.value.request == {"id": "r"}+ client.close()+++def test_stream_generate_surfaces_empty_model_output_code_and_request_id() -> None:+ """#3136: the typed ``empty_model_output`` terminal (PR #3139) must reach+ the caller as a distinguishable code plus the in-band gateway request id —+ streamed responses carry no terminal headers, so the chunk is the only+ source.+ """+ err = {+ "request_id": "req-empty-1",+ "seq": 0,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ "usage": {"prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12},+ "error": {"code": "empty_model_output", "message": "model produced no visible output text"},+ }+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.stream.return_value = _FakeStream(lines=_sse(err))+ client = SIEClient("http://localhost:8080")+ with pytest.raises(ServerError) as ei:+ list(client.stream_generate("m", "hi", max_new_tokens=8))+ assert ei.value.code == "empty_model_output"+ assert ei.value.request == {"id": "req-empty-1"}+ client.close()+++def test_stream_generate_drops_malformed_request_id() -> None:+ """A non-ASCII / padded in-band id must be dropped before it reaches the+ synthetic HTTP headers — HTTPX raises ``UnicodeEncodeError`` on non-ASCII+ header values, which would bypass the typed-error path entirely (#3136).+ """+ err = {+ "request_id": " r\u00e9q-bad ",+ "seq": 0,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ "error": {"code": "empty_model_output", "message": "model produced no visible output text"},+ }+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.stream.return_value = _FakeStream(lines=_sse(err))+ client = SIEClient("http://localhost:8080")+ with pytest.raises(ServerError) as ei:+ list(client.stream_generate("m", "hi", max_new_tokens=8))+ assert ei.value.code == "empty_model_output"+ assert ei.value.request is None+ client.close()+++def test_stream_generate_error_after_output_retains_request_id() -> None:+ delta = {"request_id": "req-mid-1", "seq": 0, "text_delta": "Hi", "done": False}+ err = {+ "request_id": "req-mid-1",+ "seq": 1,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ "error": {"code": "inference_error", "message": "boom"},+ }+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.stream.return_value = _FakeStream(lines=_sse(delta, err))+ client = SIEClient("http://localhost:8080")+ with pytest.raises(ServerError) as ei:+ list(client.stream_generate("m", "hi", max_new_tokens=8))+ assert ei.value.code == "inference_error"+ assert ei.value.request == {"id": "req-mid-1"}+ client.close()+++def _chat_error_chunk(code: str, message: str, request_id: str) -> dict[str, Any]:+ """Chat-shape stream error chunk as the gateway emits it (#3136): the+ OpenAI envelope plus a top-level ``error`` block and the additive+ ``request_id`` member (the ``chatcmpl-*`` id is not the correlation key+ gateway logs use).+ """+ return {+ "id": "chatcmpl-1",+ "object": "chat.completion.chunk",+ "created": 0,+ "model": "m",+ "system_fingerprint": None,+ "choices": [{"index": 0, "delta": {}, "finish_reason": None, "logprobs": None}],+ "error": {"message": message, "type": "server_error", "param": None, "code": code},+ "request_id": request_id,+ }+++def test_stream_chat_error_chunk_surfaces_request_id() -> None:+ """#3136: a chat-shape stream error before any output must surface the+ in-band gateway request id — streamed responses carry no terminal headers,+ so the chunk is the only source.+ """+ err = _chat_error_chunk("first_chunk_timeout", "Generation aborted: first_chunk timeout", "req-chat-1")+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.stream.return_value = _FakeStream(lines=_sse(err))+ client = SIEClient("http://localhost:8080")+ with pytest.raises(ServerError) as ei:+ list(client.stream_chat_completions("m", [{"role": "user", "content": "hi"}]))+ assert ei.value.code == "first_chunk_timeout"+ assert ei.value.request == {"id": "req-chat-1"}+ client.close()+++def test_stream_chat_error_after_output_retains_request_id() -> None:+ err = _chat_error_chunk("inference_error", "boom", "req-chat-2")+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.stream.return_value = _FakeStream(lines=_sse(_chat_chunk("Hi"), err))+ client = SIEClient("http://localhost:8080")+ with pytest.raises(ServerError) as ei:+ list(client.stream_chat_completions("m", [{"role": "user", "content": "hi"}]))+ assert ei.value.code == "inference_error"+ assert ei.value.request == {"id": "req-chat-2"}client.close()diff --git a/packages/sie_sdk/tests/client/test_chat_async.py b/packages/sie_sdk/tests/client/test_chat_async.pyindex a1bbc0d86..112491593 100644--- a/packages/sie_sdk/tests/client/test_chat_async.py+++ b/packages/sie_sdk/tests/client/test_chat_async.py@@ -122,6 +122,37 @@ async def test_async_chat_completions_parses_and_sends_json() -> None:await client.close()+async def test_async_chat_completions_consumes_modal_continuation_without_reposting() -> None:+ payload = {+ "id": "chatcmpl-1",+ "object": "chat.completion",+ "created": 0,+ "model": "m",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "Hi"}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ }+ client = SIEAsyncClient("https://gateway.example.test")+ session = _patch_session(+ client,+ post_returns=_FakeRaw(+ status=303,+ body={},+ headers={"Location": "/v1/chat/completions?__modal_attempt_token=opaque"},+ ),+ )+ session.get = MagicMock(+ return_value=_FakeRaw(status=200, body=payload, headers={"content-type": "application/json"})+ )++ out = await client.chat_completions("m", [{"role": "user", "content": "hi"}])+ await client.close()++ assert out["choices"][0]["message"]["content"] == "Hi"+ assert session.post.call_count == 1+ assert session.get.call_args.args[0] == "/v1/chat/completions?__modal_attempt_token=opaque"++@pytest.mark.asyncioasync def test_async_stream_chat_yields_chunks() -> None:raw = _FakeRaw(status=200, line_bytes=_sse_bytes(_chat_chunk("He"), _chat_chunk("llo", finish="stop")))@@ -234,6 +265,94 @@ async def test_async_stream_raises_on_error_chunk() -> None:with pytest.raises(ServerError) as ei:_ = [c async for c in client.stream_generate("m", "hi", max_new_tokens=8)]assert ei.value.code == "inference_error"+ assert ei.value.request == {"id": "r"}+ await client.close()+++async def test_async_stream_generate_surfaces_empty_model_output_code_and_request_id() -> None:+ """#3136: async mirror — the typed ``empty_model_output`` terminal must+ surface its code and in-band request id to the caller.+ """+ err = {+ "request_id": "req-empty-1",+ "seq": 0,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ "usage": {"prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12},+ "error": {"code": "empty_model_output", "message": "model produced no visible output text"},+ }+ client = SIEAsyncClient("http://localhost:8080")+ _patch_session(client, post_returns=_FakeRaw(status=200, line_bytes=_sse_bytes(err)))+ with pytest.raises(ServerError) as ei:+ _ = [c async for c in client.stream_generate("m", "hi", max_new_tokens=8)]+ assert ei.value.code == "empty_model_output"+ assert ei.value.request == {"id": "req-empty-1"}+ await client.close()+++async def test_async_stream_generate_error_after_output_retains_request_id() -> None:+ delta = {"request_id": "req-mid-1", "seq": 0, "text_delta": "Hi", "done": False}+ err = {+ "request_id": "req-mid-1",+ "seq": 1,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ "error": {"code": "inference_error", "message": "boom"},+ }+ client = SIEAsyncClient("http://localhost:8080")+ _patch_session(client, post_returns=_FakeRaw(status=200, line_bytes=_sse_bytes(delta, err)))+ with pytest.raises(ServerError) as ei:+ _ = [c async for c in client.stream_generate("m", "hi", max_new_tokens=8)]+ assert ei.value.code == "inference_error"+ assert ei.value.request == {"id": "req-mid-1"}+ await client.close()+++def _chat_error_chunk(code: str, message: str, request_id: str) -> dict[str, Any]:+ """Chat-shape stream error chunk as the gateway emits it (#3136): the+ OpenAI envelope plus a top-level ``error`` block and the additive+ ``request_id`` member.+ """+ return {+ "id": "chatcmpl-1",+ "object": "chat.completion.chunk",+ "created": 0,+ "model": "m",+ "system_fingerprint": None,+ "choices": [{"index": 0, "delta": {}, "finish_reason": None, "logprobs": None}],+ "error": {"message": message, "type": "server_error", "param": None, "code": code},+ "request_id": request_id,+ }+++async def test_async_stream_chat_error_chunk_surfaces_request_id() -> None:+ """#3136: async mirror — a chat-shape stream error must surface the+ in-band gateway request id.+ """+ err = _chat_error_chunk("first_chunk_timeout", "Generation aborted: first_chunk timeout", "req-chat-1")+ client = SIEAsyncClient("http://localhost:8080")+ _patch_session(client, post_returns=_FakeRaw(status=200, line_bytes=_sse_bytes(err)))+ with pytest.raises(ServerError) as ei:+ _ = [c async for c in client.stream_chat_completions("m", [{"role": "user", "content": "hi"}])]+ assert ei.value.code == "first_chunk_timeout"+ assert ei.value.request == {"id": "req-chat-1"}+ await client.close()+++async def test_async_stream_chat_error_after_output_retains_request_id() -> None:+ err = _chat_error_chunk("inference_error", "boom", "req-chat-2")+ client = SIEAsyncClient("http://localhost:8080")+ _patch_session(client, post_returns=_FakeRaw(status=200, line_bytes=_sse_bytes(_chat_chunk("Hi"), err)))+ with pytest.raises(ServerError) as ei:+ _ = [c async for c in client.stream_chat_completions("m", [{"role": "user", "content": "hi"}])]+ assert ei.value.code == "inference_error"+ assert ei.value.request == {"id": "req-chat-2"}await client.close()diff --git a/packages/sie_sdk/tests/client/test_generate.py b/packages/sie_sdk/tests/client/test_generate.pyindex ae8776344..4d27a0878 100644--- a/packages/sie_sdk/tests/client/test_generate.py+++ b/packages/sie_sdk/tests/client/test_generate.py@@ -18,9 +18,9 @@ from unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytestfrom sie_sdk import SIEAsyncClient, SIEClient, SIEConnectionError-from sie_sdk.client._shared import validate_generate_grammar+from sie_sdk.client._shared import MODAL_CONTINUATION_MAX_HOPS, validate_generate_grammarfrom sie_sdk.client.async_ import _AioResponse-from sie_sdk.client.errors import ProvisioningError, RequestError, ServerError+from sie_sdk.client.errors import ModelLoadingError, ProvisioningError, RequestError, ServerErrordef _ok_response(payload: dict, headers: dict[str, str] | None = None) -> MagicMock:@@ -358,7 +358,11 @@ class TestSyncGenerate:assert client.last_retry_count == 0client.close()- def test_generate_wait_for_capacity_false_does_not_retry_model_loading(self) -> None:+ def test_generate_wait_for_capacity_false_still_retries_model_loading(self) -> None:+ # 503 MODEL_LOADING is retried regardless of wait_for_capacity,+ # matching encode/score/extract/chat/responses/streaming: the worker+ # already accepted the request and is loading the target model, so+ # this is a pre-execution signal rather than a capacity wait.with (patch("sie_sdk.client.sync.httpx.Client") as mock_client,patch("sie_sdk.client.sync.time.sleep") as mock_sleep,@@ -368,17 +372,36 @@ class TestSyncGenerate:_ok_response(_ok_envelope()),]client = SIEClient("http://localhost:8080")- with pytest.raises(ServerError, match="loading") as excinfo:- client.generate(- "m",- prompt="hi",- max_new_tokens=8,- wait_for_capacity=False,- provision_timeout_s=10,- )- assert excinfo.value.code == "MODEL_LOADING"+ result = client.generate(+ "m",+ prompt="hi",+ max_new_tokens=8,+ wait_for_capacity=False,+ provision_timeout_s=10,+ )+ assert result["text"] == "ok"+ assert mock_client.return_value.post.call_count == 2+ assert client.last_retry_count == 1+ mock_sleep.assert_called_once()+ client.close()++ def test_generate_model_loading_delay_exhausting_budget_raises_typed_error(self) -> None:+ # When the server's Retry-After delay would consume the remaining+ # provision budget, generate() must raise the typed ModelLoadingError+ # immediately instead of sleeping through the budget and letting the+ # NEXT loop iteration raise a generic ProvisioningError.+ loading = _resp_503_model_loading()+ loading.headers = {**loading.headers, "Retry-After": "60"}+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep") as mock_sleep,+ ):+ mock_client.return_value.post.return_value = loading+ client = SIEClient("http://localhost:8080")+ with pytest.raises(ModelLoadingError, match="provision timeout") as excinfo:+ client.generate("m", prompt="hi", max_new_tokens=8, provision_timeout_s=10)+ assert excinfo.value.model == "m"assert mock_client.return_value.post.call_count == 1- assert client.last_retry_count == 0mock_sleep.assert_not_called()client.close()@@ -453,6 +476,52 @@ class TestSyncGenerate:assert mock_client.call_args.kwargs["follow_redirects"] is Falseredirect.json.assert_not_called()+ def test_generate_consumes_same_origin_modal_continuation_without_reposting(self) -> None:+ redirect = MagicMock(+ status_code=303,+ headers={"Location": "/v1/generate/m?__modal_attempt_token=opaque"},+ content=b"",+ )+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = redirect+ mock_client.return_value.get.return_value = _ok_response(_ok_envelope())+ client = SIEClient("https://gateway.example.test", api_key="secret")+ try:+ result = client.generate("m", prompt="hi", max_new_tokens=4)+ finally:+ client.close()++ assert result["text"] == "ok"+ assert mock_client.return_value.post.call_count == 1+ mock_client.return_value.get.assert_called_once_with(+ "/v1/generate/m?__modal_attempt_token=opaque",+ headers={"Accept": "application/json"},+ timeout=pytest.approx(30),+ )+ assert client.last_retry_count == 0++ def test_generate_fails_typed_when_modal_continuation_hops_are_exhausted(self) -> None:+ redirect = MagicMock(+ status_code=303,+ headers={"Location": "/v1/generate/m?__modal_attempt_token=opaque"},+ content=b"",+ )+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = redirect+ mock_client.return_value.get.return_value = redirect+ client = SIEClient("https://gateway.example.test", api_key="secret", timeout_s=300)+ try:+ with pytest.raises(+ ProvisioningError,+ match=f"remained in flight after {MODAL_CONTINUATION_MAX_HOPS} continuation hops",+ ):+ client.generate("m", prompt="hi", max_new_tokens=4, provision_timeout_s=600)+ finally:+ client.close()++ assert mock_client.return_value.post.call_count == 1+ assert mock_client.return_value.get.call_count == MODAL_CONTINUATION_MAX_HOPS+def test_generate_malformed_json_has_content_safe_diagnostics(self) -> None:response = MagicMock()response.status_code = 200@@ -683,6 +752,58 @@ class TestAsyncGenerate:assert ensure.return_value.post.call_count == 1assert ensure.return_value.post.call_args.kwargs["allow_redirects"] is False+ @pytest.mark.asyncio+ async def test_generate_consumes_same_origin_modal_continuation_without_reposting(self) -> None:+ client = SIEAsyncClient("https://gateway.example.test", api_key="secret")+ client._post = AsyncMock( # type: ignore[method-assign]+ return_value=_aio_raw_resp(+ 303,+ b"",+ {"Location": "/v1/generate/m?__modal_attempt_token=opaque"},+ )+ )+ continuation = AsyncMock(return_value=_aio_resp(200, _ok_envelope()))+ with patch.object(client, "_ensure_session") as ensure:+ ensure.return_value.post = _make_session_post(client._post)+ ensure.return_value.get = _make_session_post(continuation)+ try:+ result = await client.generate("m", prompt="hi", max_new_tokens=4)+ finally:+ await client.close()++ assert result["text"] == "ok"+ assert client._post.call_count == 1+ assert ensure.return_value.post.call_count == 1+ assert continuation.call_count == 1+ get_call = ensure.return_value.get.call_args+ assert get_call.args[0] == "/v1/generate/m?__modal_attempt_token=opaque"+ assert get_call.kwargs["allow_redirects"] is False++ @pytest.mark.asyncio+ async def test_generate_fails_typed_when_modal_continuation_hops_are_exhausted(self) -> None:+ redirect = _aio_raw_resp(+ 303,+ b"",+ {"Location": "/v1/generate/m?__modal_attempt_token=opaque"},+ )+ client = SIEAsyncClient("https://gateway.example.test", api_key="secret", timeout_s=300)+ client._post = AsyncMock(return_value=redirect) # type: ignore[method-assign]+ continuation = AsyncMock(return_value=redirect)+ with patch.object(client, "_ensure_session") as ensure:+ ensure.return_value.post = _make_session_post(client._post)+ ensure.return_value.get = _make_session_post(continuation)+ try:+ with pytest.raises(+ ProvisioningError,+ match=f"remained in flight after {MODAL_CONTINUATION_MAX_HOPS} continuation hops",+ ):+ await client.generate("m", prompt="hi", max_new_tokens=4, provision_timeout_s=600)+ finally:+ await client.close()++ assert client._post.call_count == 1+ assert continuation.call_count == MODAL_CONTINUATION_MAX_HOPS+@pytest.mark.asyncio@pytest.mark.parametrize("body", [{"text": "ok"}, {"model": "m"}])async def test_generate_invalid_object_retains_request_metadata(self, body: dict) -> None:@@ -871,7 +992,11 @@ class TestAsyncGenerate:assert client._post.call_count == 2@pytest.mark.asyncio- async def test_generate_wait_for_capacity_false_does_not_retry_model_loading(self) -> None:+ async def test_generate_wait_for_capacity_false_still_retries_model_loading(self) -> None:+ # 503 MODEL_LOADING is retried regardless of wait_for_capacity,+ # matching encode/score/extract/chat/responses/streaming: the worker+ # already accepted the request and is loading the target model, so+ # this is a pre-execution signal rather than a capacity wait.client = SIEAsyncClient("http://localhost:8080")client._post = AsyncMock( # type: ignore[method-assign]side_effect=[@@ -887,17 +1012,49 @@ class TestAsyncGenerate:ensure.return_value.post = _make_session_post(client._post)with patch("sie_sdk.client.async_.asyncio.sleep", new_callable=AsyncMock) as mock_sleep:try:- with pytest.raises(ServerError, match="loading") as excinfo:- await client.generate(- "m",- prompt="hi",- max_new_tokens=8,- wait_for_capacity=False,- provision_timeout_s=10,- )+ result = await client.generate(+ "m",+ prompt="hi",+ max_new_tokens=8,+ wait_for_capacity=False,+ provision_timeout_s=10,+ )+ finally:+ await client.close()+ assert result["text"] == "ok"+ assert client._post.call_count == 2+ mock_sleep.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_generate_model_loading_delay_exhausting_budget_raises_typed_error(self) -> None:+ # When the server's Retry-After delay would consume the remaining+ # provision budget, generate() must raise the typed ModelLoadingError+ # immediately instead of sleeping through the budget and letting the+ # NEXT loop iteration raise a generic ProvisioningError.+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock( # type: ignore[method-assign]+ side_effect=[+ _aio_resp(+ 503,+ {"error": {"code": "MODEL_LOADING", "message": "loading"}},+ {+ "X-SIE-Error-Code": "MODEL_LOADING",+ "Retry-After": "60",+ "content-type": "application/json",+ },+ ),+ _aio_resp(200, _ok_envelope()),+ ]+ )+ with patch.object(client, "_ensure_session") as ensure:+ ensure.return_value.post = _make_session_post(client._post)+ with patch("sie_sdk.client.async_.asyncio.sleep", new_callable=AsyncMock) as mock_sleep:+ try:+ with pytest.raises(ModelLoadingError, match="provision timeout") as excinfo:+ await client.generate("m", prompt="hi", max_new_tokens=8, provision_timeout_s=10)finally:await client.close()- assert excinfo.value.code == "MODEL_LOADING"+ assert excinfo.value.model == "m"assert client._post.call_count == 1mock_sleep.assert_not_awaited()diff --git a/packages/sie_sdk/tests/client/test_incomplete_batch.py b/packages/sie_sdk/tests/client/test_incomplete_batch.pynew file mode 100644index 000000000..65f887d2d--- /dev/null+++ b/packages/sie_sdk/tests/client/test_incomplete_batch.py@@ -0,0 +1,198 @@+"""Positional batch-contract guard (architecture-review finding U1).++The gateway's queue path answers a mixed-success batch with ``200`` carrying+only the *successful* items, and batch results are positional (item ``id`` is+optional). A shortened body therefore shifts every result after the dropped+item, so a zip-inputs-to-outputs consumer stores results against the wrong+inputs — silently. Both clients guard the 1:1 contract on encode and extract+and raise :class:`IncompleteBatchError` instead of returning a desynced list.++The pre-existing count assertions for encode live in ``test_sync.py`` /+``test_async.py`` (#1526); this module covers the typed error, its+diagnostic attributes, and the extract + async surfaces.+"""++from unittest.mock import AsyncMock, MagicMock, patch++import msgpack+import numpy as np+import pytest+from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk.client.async_ import _AioResponse+from sie_sdk.client.errors import IncompleteBatchError, ServerError+++def _dense(value: float) -> dict[str, object]:+ return {"dims": 4, "dtype": "float32", "values": np.array([value, value, value, value])}+++def _sync_response(payload: dict[str, object], headers: dict[str, str] | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = 200+ response.headers = headers or {}+ response.content = msgpack.packb(payload, use_bin_type=True)+ return response+++def _async_response(payload: dict[str, object], headers: dict[str, str] | None = None) -> _AioResponse:+ return _AioResponse(200, msgpack.packb(payload, use_bin_type=True), headers or {})+++class TestEncodeGuard:+ def test_dropped_item_raises_typed_error_with_counts(self) -> None:+ response = _sync_response(+ {"model": "e5-mistral", "items": [{"dense": _dense(1.0)}]},+ headers={"X-SIE-Request-ID": "req-drop"},+ )++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ with pytest.raises(IncompleteBatchError) as excinfo:+ client.encode("e5-mistral", [{"text": "ok"}, {"text": "over-length"}])++ error = excinfo.value+ assert error.expected == 2+ assert error.received == 1+ assert error.model == "e5-mistral"+ assert error.code == "ENCODE_RESULT_COUNT_MISMATCH"+ assert error.request is not None+ assert error.request["id"] == "req-drop"+ client.close()++ def test_remains_a_server_error_for_existing_handlers(self) -> None:+ """Subclassing keeps pre-#3221-era ``except ServerError`` callers working."""+ response = _sync_response({"model": "e5-mistral", "items": []})++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ with pytest.raises(ServerError):+ client.encode("e5-mistral", {"text": "hello"})+ client.close()++ def test_names_the_dropped_ids_when_items_carry_them(self) -> None:+ response = _sync_response(+ {+ "model": "e5-mistral",+ "items": [{"id": "doc-a", "dense": _dense(1.0)}, {"id": "doc-c", "dense": _dense(3.0)}],+ }+ )++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ with pytest.raises(IncompleteBatchError) as excinfo:+ client.encode(+ "e5-mistral",+ [+ {"id": "doc-a", "text": "a"},+ {"id": "doc-b", "text": "b"},+ {"id": "doc-c", "text": "c"},+ ],+ )++ assert excinfo.value.missing_ids == ["doc-b"]+ assert "doc-b" in str(excinfo.value)+ client.close()++ def test_missing_ids_is_none_when_ids_are_absent(self) -> None:+ """Without ids on both sides the set difference could mislabel a+ present-but-unnamed item, so the diagnostic degrades to counts only.+ """+ response = _sync_response({"model": "e5-mistral", "items": [{"dense": _dense(1.0)}]})++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ with pytest.raises(IncompleteBatchError) as excinfo:+ client.encode("e5-mistral", [{"text": "a"}, {"text": "b"}])++ assert excinfo.value.missing_ids is None+ client.close()++ def test_matched_counts_pass_through(self) -> None:+ response = _sync_response({"model": "e5-mistral", "items": [{"dense": _dense(1.0)}, {"dense": _dense(2.0)}]})++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ results = client.encode("e5-mistral", [{"text": "a"}, {"text": "b"}])++ assert len(results) == 2+ client.close()+++class TestExtractGuard:+ def test_dropped_item_raises_typed_error(self) -> None:+ response = _sync_response(+ {+ "model": "gliner",+ "items": [{"entities": [{"text": "Apple", "label": "org", "score": 0.9, "start": 0, "end": 5}]}],+ }+ )++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ with pytest.raises(IncompleteBatchError) as excinfo:+ client.extract("gliner", [{"text": "Apple info"}, {"text": "Tesla info"}], labels=["org"])++ error = excinfo.value+ assert error.expected == 2+ assert error.received == 1+ assert error.code == "EXTRACT_RESULT_COUNT_MISMATCH"+ assert "extraction result(s)" in str(error)+ client.close()++ def test_matched_counts_pass_through(self) -> None:+ response = _sync_response(+ {+ "model": "gliner",+ "items": [+ {"entities": [{"text": "Apple", "label": "org", "score": 0.9, "start": 0, "end": 5}]},+ {"entities": [{"text": "Tesla", "label": "org", "score": 0.95, "start": 0, "end": 5}]},+ ],+ }+ )++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ results = client.extract("gliner", [{"text": "Apple info"}, {"text": "Tesla info"}], labels=["org"])++ assert len(results) == 2+ client.close()+++class TestAsyncParity:+ @pytest.mark.asyncio+ async def test_encode_dropped_item_raises_typed_error(self) -> None:+ response = _async_response({"model": "e5-mistral", "items": [{"dense": _dense(1.0)}]})++ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(return_value=response) # type: ignore[method-assign]+ with pytest.raises(IncompleteBatchError) as excinfo:+ await client.encode("e5-mistral", [{"text": "a"}, {"text": "b"}])++ assert excinfo.value.expected == 2+ assert excinfo.value.received == 1+ assert excinfo.value.code == "ENCODE_RESULT_COUNT_MISMATCH"+ await client.close()++ @pytest.mark.asyncio+ async def test_extract_dropped_item_raises_typed_error(self) -> None:+ response = _async_response(+ {+ "model": "gliner",+ "items": [{"entities": [{"text": "Apple", "label": "org", "score": 0.9, "start": 0, "end": 5}]}],+ }+ )++ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(return_value=response) # type: ignore[method-assign]+ with pytest.raises(IncompleteBatchError) as excinfo:+ await client.extract("gliner", [{"text": "a"}, {"text": "b"}], labels=["org"])++ assert excinfo.value.code == "EXTRACT_RESULT_COUNT_MISMATCH"+ await client.close()diff --git a/packages/sie_sdk/tests/client/test_jobs.py b/packages/sie_sdk/tests/client/test_jobs.pyindex 52f45ee30..486acbf1a 100644--- a/packages/sie_sdk/tests/client/test_jobs.py+++ b/packages/sie_sdk/tests/client/test_jobs.py@@ -9,6 +9,8 @@ from unittest.mock import AsyncMock, MagicMock, patchimport msgpackimport pytestfrom sie_sdk import RequestError, ServerError, SIEAsyncClient, SIEClient+from sie_sdk.client.errors import JobFailedError+from sie_sdk.jobs import MalformedChunkError, decode_chunk_bytes, decode_result_itemGW = "http://gw.test:8080"KEY = "sk-sie-testkey"@@ -55,6 +57,50 @@ def _result_job(*refs: str) -> dict[str, Any]:}+def _mixed_chunk() -> bytes:+ """One chunk ref carrying a successful item AND a failed sibling (both billed)."""+ return msgpack.packb(+ [+ {+ "success": True,+ "id": "ok-1",+ "units": {"input_tokens": 5},+ "result_msgpack": msgpack.packb({"dense": {"dims": 2, "values": [0.1, 0.2]}}, use_bin_type=True),+ },+ {+ "success": False,+ "id": "bad-1",+ "error": "tokenization failed",+ "error_code": "INFERENCE_ERROR",+ },+ ],+ use_bin_type=True,+ )+++def _partial_failure_job() -> dict[str, Any]:+ """A terminal `failed` job: chunk 0 published a ref (billed siblings); chunk 1 lost its results."""+ return {+ "id": "job-1",+ "state": "failed",+ "total_items": 3,+ "settled_credits": 5,+ "output": {+ "kind": "refs",+ "chunks": [+ {+ "seq": 0,+ "items": 2,+ "state": "failed",+ "ref": "https://gw.test/chunk-0",+ "error": "1 of 2 items failed",+ },+ {"seq": 1, "items": 1, "state": "failed", "ref": None, "error": "result publication failed"},+ ],+ },+ }++def _resp(status: int, body: Any) -> MagicMock:r = MagicMock()r.status_code = status@@ -376,6 +422,172 @@ def test_results_does_not_refresh_unrelated_ref_failures(error: RequestError | Sclient.close()+def test_decode_result_item_populates_error_and_surfaces_work_item_id() -> None:+ ok = decode_result_item(+ {+ "success": True,+ "id": "a",+ "result_msgpack": msgpack.packb({"dense": {"dims": 2, "values": [0.1, 0.2]}}, use_bin_type=True),+ }+ )+ assert ok["success"] is True+ assert "error" not in ok # a success carries no failure detail++ bad = decode_result_item({"success": False, "work_item_id": "b", "error": "boom", "error_code": "INFERENCE_ERROR"})+ assert bad["success"] is False+ assert bad["id"] == "b" # id surfaced from the wire `work_item_id`, never fabricated+ assert bad["error"] == {"code": "INFERENCE_ERROR", "message": "boom"}+++def test_decode_result_item_preserves_falsy_but_valid_id() -> None:+ # Item ids can be integers: id 0 (and empty-string id) are VALID and must not+ # be replaced by work_item_id via a truthiness fallback. Assert the runtime+ # type too — JobResultItem["id"] is typed str | int | None.+ zero = decode_result_item({"success": True, "id": 0, "work_item_id": "wi-9"})+ assert zero["id"] == 0+ assert isinstance(zero["id"], int)+ empty = decode_result_item({"success": True, "id": "", "work_item_id": "wi-9"})+ assert empty["id"] == ""+ assert isinstance(empty["id"], str)+ # The work_item_id fallback only applies when id is genuinely absent (None).+ assert decode_result_item({"success": False, "work_item_id": "wi-9"})["id"] == "wi-9"+++def test_decode_result_item_tolerates_malformed_payloads() -> None:+ # A non-dict element (e.g. a bare int the wire never should send) degrades to+ # a null result rather than raising out of the per-chunk decode loop.+ item = decode_result_item(42)+ assert item["id"] is None+ assert item["success"] is None+ assert "error" not in item+ # A dict whose result_msgpack is garbage bytes still decodes (vector is None).+ garbage_payload = decode_result_item({"success": True, "id": "x", "result_msgpack": b"\xc1\xc1 not msgpack"})+ assert garbage_payload["id"] == "x"+ assert garbage_payload["dense"] is None+++def test_decode_chunk_bytes_signals_malformed_refs_distinctly() -> None:+ # Garbage bytes (not msgpack) → a distinct MalformedChunkError, not a silent+ # empty list, so the caller can tell a decode fault from an unpublished chunk.+ with pytest.raises(MalformedChunkError):+ decode_chunk_bytes(b"\xc1\xc1\xc1 total garbage")+ # Valid msgpack that is not a list of results is also malformed.+ with pytest.raises(MalformedChunkError):+ decode_chunk_bytes(msgpack.packb({"not": "a list"}, use_bin_type=True))+ # A well-formed list still decodes normally.+ good = decode_chunk_bytes(_mixed_chunk())+ assert [it["id"] for it in good] == ["ok-1", "bad-1"]+++def test_results_confines_a_garbage_failed_chunk_ref_without_crashing() -> None:+ job = {+ "id": "job-1",+ "state": "failed",+ "total_items": 3,+ "settled_credits": 5,+ "output": {+ "kind": "refs",+ "chunks": [+ {"seq": 0, "items": 2, "state": "failed", "ref": "https://gw.test/good"},+ {"seq": 1, "items": 1, "state": "succeeded", "ref": "https://gw.test/garbage"},+ ],+ },+ }+ with patch("sie_sdk.client.sync.httpx.Client"):+ client = SIEClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", return_value=job),+ patch.object(client.jobs, "_read_ref", side_effect=[_mixed_chunk(), b"\xc1\xc1 garbage"]),+ pytest.warns(UserWarning, match="results are incomplete") as record,+ ):+ results = client.jobs.results("job-1")++ # The good chunk's 2 items survive; the garbage ref contributes none, and+ # the whole call does not crash on the decode error.+ assert results["retrieved"] == 2+ assert [it["id"] for it in results["items"]] == ["ok-1", "bad-1"]+ messages = [str(w.message) for w in record]+ # The malformed ref is flagged distinctly (a decode fault)...+ assert any("could not be decoded" in m for m in messages)+ # ...and the incompleteness warning stays NEUTRAL — no billing/publication+ # claim, since a succeeded chunk with garbage bytes proves neither.+ assert any("results are incomplete: retrieved 2 of 3" in m for m in messages)+ assert not any("billed" in m or "publishing" in m for m in messages)+ client.close()+++def test_results_surfaces_billed_successful_items_from_a_failed_chunk_and_warns() -> None:+ with patch("sie_sdk.client.sync.httpx.Client"):+ client = SIEClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", return_value=_partial_failure_job()) as get_job,+ patch.object(client.jobs, "_read_ref", return_value=_mixed_chunk()) as read_ref,+ pytest.warns(UserWarning, match="incomplete: retrieved 2 of 3"),+ ):+ results = client.jobs.results("job-1")++ # The `failed` chunk's ref is read (not dropped): its successful, already-billed+ # sibling is surfaced, and the failed sibling carries its per-item error.+ read_ref.assert_called_once_with("https://gw.test/chunk-0")+ assert get_job.call_count == 1+ assert results["retrieved"] == 2+ assert results["state"] == "failed"+ ok, bad = results["items"]+ assert (ok["id"], ok["success"]) == ("ok-1", True)+ assert ok["dense"].shape == (2,)+ assert "error" not in ok+ assert (bad["id"], bad["success"]) == ("bad-1", False)+ assert bad["error"] == {"code": "INFERENCE_ERROR", "message": "tokenization failed"}+ client.close()+++def test_results_on_non_terminal_job_raises_job_not_terminal_without_reading_refs() -> None:+ running = {"id": "job-1", "state": "running", "total_items": 3, "output": {"kind": "refs", "chunks": []}}+ with patch("sie_sdk.client.sync.httpx.Client"):+ client = SIEClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", return_value=running),+ patch.object(client.jobs, "_read_ref") as read_ref,+ pytest.raises(RequestError) as excinfo,+ ):+ client.jobs.results("job-1")++ assert excinfo.value.code == "job_not_terminal"+ assert excinfo.value.status_code == 409+ read_ref.assert_not_called()+ client.close()+++def test_wait_raise_on_failure_raises_job_failed_error_carrying_outcome() -> None:+ failed = {+ "id": "job-1",+ "state": "failed",+ "outcome": "reexecution_required",+ "error_code": "RESULT_HANDLE_EXPIRED",+ }+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.request = MagicMock(return_value=_resp(200, failed))+ client = SIEClient(GW, api_key=KEY)+ with pytest.raises(JobFailedError) as excinfo:+ client.jobs.wait("job-1", poll_s=0, raise_on_failure=True)+ assert excinfo.value.state == "failed"+ assert excinfo.value.outcome == "reexecution_required"+ assert excinfo.value.error_code == "RESULT_HANDLE_EXPIRED"+ assert excinfo.value.job_id == "job-1"+ # Default stays back-compatible: the terminal doc is returned, not raised.+ assert client.jobs.wait("job-1", poll_s=0)["state"] == "failed"+ client.close()+++def test_wait_raise_on_failure_returns_succeeded_terminal_unchanged() -> None:+ ok = {"id": "job-1", "state": "succeeded", "total_items": 2}+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.request = MagicMock(return_value=_resp(200, ok))+ client = SIEClient(GW, api_key=KEY)+ assert client.jobs.wait("job-1", poll_s=0, raise_on_failure=True)["state"] == "succeeded"+ client.close()++# ---------------------------------------------------------------------------# async# ---------------------------------------------------------------------------@@ -606,3 +818,92 @@ async def test_async_results_does_not_refresh_unrelated_ref_failures(error: Requread_ref.assert_awaited_once_with("https://gw.test/ref")assert excinfo.value is errorawait client.close()+++async def test_async_results_surfaces_billed_successful_items_from_a_failed_chunk_and_warns() -> None:+ client = SIEAsyncClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", new=AsyncMock(return_value=_partial_failure_job())),+ patch.object(client.jobs, "_read_ref", new=AsyncMock(return_value=_mixed_chunk())) as read_ref,+ pytest.warns(UserWarning, match="incomplete: retrieved 2 of 3"),+ ):+ results = await client.jobs.results("job-1")++ read_ref.assert_awaited_once_with("https://gw.test/chunk-0")+ assert results["retrieved"] == 2+ ok, bad = results["items"]+ assert (ok["id"], ok["success"]) == ("ok-1", True)+ assert "error" not in ok+ assert (bad["id"], bad["success"]) == ("bad-1", False)+ assert bad["error"] == {"code": "INFERENCE_ERROR", "message": "tokenization failed"}+ await client.close()+++async def test_async_results_on_non_terminal_job_raises_job_not_terminal() -> None:+ running = {"id": "job-1", "state": "running", "total_items": 3, "output": {"kind": "refs", "chunks": []}}+ client = SIEAsyncClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", new=AsyncMock(return_value=running)),+ patch.object(client.jobs, "_read_ref", new=AsyncMock()) as read_ref,+ pytest.raises(RequestError) as excinfo,+ ):+ await client.jobs.results("job-1")++ assert excinfo.value.code == "job_not_terminal"+ assert excinfo.value.status_code == 409+ read_ref.assert_not_awaited()+ await client.close()+++async def test_async_wait_raise_on_failure_raises_job_failed_error_carrying_outcome() -> None:+ failed = {+ "id": "job-1",+ "state": "failed",+ "outcome": "reexecution_required",+ "error_code": "RESULT_HANDLE_EXPIRED",+ }+ client = SIEAsyncClient(GW, api_key=KEY)+ client._get = AsyncMock(return_value=_FakeAio(200, failed))+ with pytest.raises(JobFailedError) as excinfo:+ await client.jobs.wait("job-1", poll_s=0, raise_on_failure=True)+ assert excinfo.value.state == "failed"+ assert excinfo.value.outcome == "reexecution_required"+ assert excinfo.value.error_code == "RESULT_HANDLE_EXPIRED"+ # Default stays back-compatible: the terminal doc is returned, not raised.+ assert (await client.jobs.wait("job-1", poll_s=0))["state"] == "failed"+ await client.close()+++async def test_async_results_confines_a_garbage_failed_chunk_ref_without_crashing() -> None:+ job = {+ "id": "job-1",+ "state": "failed",+ "total_items": 3,+ "settled_credits": 5,+ "output": {+ "kind": "refs",+ "chunks": [+ {"seq": 0, "items": 2, "state": "failed", "ref": "https://gw.test/good"},+ {"seq": 1, "items": 1, "state": "succeeded", "ref": "https://gw.test/garbage"},+ ],+ },+ }+ client = SIEAsyncClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", new=AsyncMock(return_value=job)),+ patch.object(client.jobs, "_read_ref", new=AsyncMock(side_effect=[_mixed_chunk(), b"\xc1\xc1 garbage"])),+ pytest.warns(UserWarning, match="results are incomplete") as record,+ ):+ results = await client.jobs.results("job-1")++ assert results["retrieved"] == 2+ assert [it["id"] for it in results["items"]] == ["ok-1", "bad-1"]+ messages = [str(w.message) for w in record]+ assert any("could not be decoded" in m for m in messages)+ assert any("results are incomplete: retrieved 2 of 3" in m for m in messages)+ assert not any("billed" in m or "publishing" in m for m in messages)+ await client.close()diff --git a/packages/sie_sdk/tests/client/test_malformed_retry_after.py b/packages/sie_sdk/tests/client/test_malformed_retry_after.pyindex 3e3ba3645..1d921e89b 100644--- a/packages/sie_sdk/tests/client/test_malformed_retry_after.py+++ b/packages/sie_sdk/tests/client/test_malformed_retry_after.py@@ -127,7 +127,6 @@ class TestSyncGenerateMalformedRetryAfter:"""def test_perpetual_503_provisioning_nan_does_not_crash_and_is_bounded(self) -> None:- from sie_sdk.client.errors import ProvisioningErrordef _resp_503_provisioning_nan() -> MagicMock:response = MagicMock()@@ -174,12 +173,13 @@ class TestAsyncGenerateMalformedRetryAfter:within a small budget (no busy-loop) and raise the expected loading /provisioning error.- The defining assertion is on the *delay value* every ``asyncio.sleep``- receives: before the fix the malformed header was passed through, so+ Before the fix the malformed header was passed through, so``asyncio.sleep(nan)`` / ``asyncio.sleep(-10)`` returned INSTANTLY and theloop busy-spun (~1000 attempts in 0.3s). After the fix the hint is- discarded and the default delay (capped to remaining budget) is used, so- every sleep is finite, non-negative, and the attempt count stays tiny.+ discarded and the default 5s delay applies; since that exceeds the tiny+ 0.3s budget, ``generate()`` raises the typed ``ModelLoadingError``+ immediately (no sleep, single attempt) instead of sleeping through the+ budget."""@pytest.mark.asyncio@@ -212,14 +212,16 @@ class TestAsyncGenerateMalformedRetryAfter:try:# Tiny budget; if the malformed Retry-After busy-loops, the# call count explodes into the hundreds/thousands.- with pytest.raises((ModelLoadingError, ProvisioningError)):+ with pytest.raises(ModelLoadingError):await client.generate("m", prompt="hi", max_new_tokens=8, provision_timeout_s=0.3)finally:await client.close()- # No busy-loop: every sleep delay is finite and non-negative (the- # malformed -10 / nan hint was discarded), and the attempt count stays- # bounded over the 0.3s budget.- assert slept, "expected at least one retry sleep"+ # No busy-loop: the malformed -10 / nan hint was discarded, so the+ # default 5s delay applies; it exceeds the 0.3s budget, so the SDK+ # raises the typed ModelLoadingError immediately — no sleeps, single+ # attempt. (Before the fix the hint was passed through and asyncio+ # slept instantly, busy-spinning for hundreds of attempts.)+ assert slept == []assert all(math.isfinite(d) and d >= 0 for d in slept)- assert 0 < client._post.call_count < 50+ assert client._post.call_count == 1diff --git a/packages/sie_sdk/tests/client/test_model_load_failed.py b/packages/sie_sdk/tests/client/test_model_load_failed.pyindex ca8d02549..cc7e3c75f 100644--- a/packages/sie_sdk/tests/client/test_model_load_failed.py+++ b/packages/sie_sdk/tests/client/test_model_load_failed.py@@ -1,4 +1,4 @@-"""Tests for the ``ModelLoadFailedError`` short-circuit (sie-test#85).+"""Tests for the ``ModelLoadFailedError`` short-circuit.A 502 ``MODEL_LOAD_FAILED`` response must:- raise :class:`ModelLoadFailedError` immediately on the first responsediff --git a/packages/sie_sdk/tests/client/test_recommend.py b/packages/sie_sdk/tests/client/test_recommend.pynew file mode 100644index 000000000..2aaba066f--- /dev/null+++ b/packages/sie_sdk/tests/client/test_recommend.py@@ -0,0 +1,189 @@+"""Tests for the model recommendation read (``POST /v1/recommend``, #2845).++The SDK's job here is narrow: send the task, return the gateway's answer+unchanged, and map transport failures onto the same typed errors every other+method uses.++"Unchanged" is the load-bearing part. The answer carries ``basis`` and a+per-choice ``evidence_guarded``, and those two fields are the entire reason a+caller can decide whether to trust a pick. An SDK that returned only the model+id — or that quietly dropped a field it did not recognise — would convert a+checkable recommendation into an unfalsifiable one.+"""++from __future__ import annotations++import json+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk.client.async_ import _AioResponse+from sie_sdk.client.errors import RequestError, ServerError++RANKED: dict[str, Any] = {+ "task": "rerank",+ "label": "Rerank",+ "basis": "ranked",+ "shared_benchmarks": ["mteb__AskUbuntuDupQuestions"],+ "fast": {+ "intent": "fast",+ "model": "Qwen/Qwen3-Reranker-0.6B",+ "runtime_id": "Qwen/Qwen3-Reranker-0.6B",+ "profile": "default",+ "alias": "rerank-fast",+ "available": True,+ "quality_ref": "quality-evidence/rerank-fast.json",+ "performance_ref": None,+ "measurement_status": "verified",+ "evidence_guarded": True,+ },+ "best": {+ "intent": "smart",+ "model": "Qwen/Qwen3-Reranker-4B",+ "runtime_id": "Qwen/Qwen3-Reranker-4B",+ "profile": "default",+ "alias": "rerank-best",+ "available": True,+ "quality_ref": "quality-evidence/rerank-best.json",+ "performance_ref": None,+ "measurement_status": "verified",+ "evidence_guarded": False,+ },+}++NO_EVIDENCE: dict[str, Any] = {+ "task": "structured-output",+ "label": "Structured output",+ "basis": "no_evidence",+ "shared_benchmarks": [],+ "fast": {+ "intent": "fast",+ "model": "Qwen/Qwen3.5-4B",+ "runtime_id": "Qwen/Qwen3.5-4B",+ "profile": "default",+ "alias": None,+ "available": True,+ "evidence_guarded": False,+ },+}++UNKNOWN_TASK = {+ "detail": {+ "code": "TASK_NOT_FOUND",+ "message": 'unknown task "embeddings"; this release recommends for: chat, ocr, rerank, search',+ }+}+++def _resp(status: int, body: dict[str, Any]) -> MagicMock:+ resp = MagicMock()+ resp.status_code = status+ resp.headers = {"content-type": "application/json"}+ resp.json.return_value = body+ resp.content = json.dumps(body).encode()+ resp.text = json.dumps(body)+ return resp+++def _aio(status: int, body: dict[str, Any]) -> _AioResponse:+ return _AioResponse(status, json.dumps(body).encode(), {"content-type": "application/json"})+++class TestSyncRecommend:+ def test_posts_the_task_and_returns_the_answer_verbatim(self) -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post = MagicMock(return_value=_resp(200, RANKED))+ client = SIEClient("http://localhost:8080")++ answer = client.recommend("rerank")++ assert answer == RANKED+ url = mock_client.return_value.post.call_args[0]+ kwargs = mock_client.return_value.post.call_args[1]+ assert url[0] == "/v1/recommend"+ assert kwargs["json"] == {"task": "rerank"}+ client.close()++ def test_carries_the_fields_that_make_a_pick_checkable(self) -> None:+ """`basis` and `evidence_guarded` must survive the round trip.++ `rerank-best` here is measured but UNGUARDED — the live `search` and+ `redact-pii` shape. A caller that cannot see that flag cannot tell a+ floored number from an unfloored one.+ """+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post = MagicMock(return_value=_resp(200, RANKED))+ client = SIEClient("http://localhost:8080")++ answer = client.recommend("rerank")++ assert answer["basis"] == "ranked"+ assert answer["shared_benchmarks"] == ["mteb__AskUbuntuDupQuestions"]+ assert answer["best"]["alias"] == "rerank-best"+ assert answer["best"]["evidence_guarded"] is False+ assert answer["fast"]["evidence_guarded"] is True+ client.close()++ def test_a_family_with_no_evidence_says_so_rather_than_omitting_the_basis(self) -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post = MagicMock(return_value=_resp(200, NO_EVIDENCE))+ client = SIEClient("http://localhost:8080")++ answer = client.recommend("structured-output")++ assert answer["basis"] == "no_evidence"+ assert "best" not in answer+ client.close()++ def test_unknown_task_raises_request_error(self) -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post = MagicMock(return_value=_resp(404, UNKNOWN_TASK))+ client = SIEClient("http://localhost:8080")++ with pytest.raises(RequestError):+ client.recommend("embeddings")+ client.close()++ def test_server_error_maps_to_server_error(self) -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post = MagicMock(+ return_value=_resp(503, {"detail": {"code": "UNAVAILABLE", "message": "down"}})+ )+ client = SIEClient("http://localhost:8080")++ with pytest.raises(ServerError):+ client.recommend("rerank")+ client.close()+++class TestAsyncRecommend:+ @pytest.mark.asyncio+ async def test_matches_the_sync_twin(self) -> None:+ """The async client must reach the same route with the same body.++ The two drifting is the failure this pins: `recommend` shipped on the+ sync client first, and an async caller silently lacking it is the kind+ of gap that only shows up in someone else's code.+ """+ with patch("sie_sdk.client.async_.aiohttp.ClientSession"):+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(return_value=_aio(200, RANKED)) # type: ignore[method-assign]++ answer = await client.recommend("rerank")++ assert answer == RANKED+ assert client._post.await_args[0][0] == "/v1/recommend"+ assert client._post.await_args[1]["json_data"] == {"task": "rerank"}+ await client.close()++ @pytest.mark.asyncio+ async def test_unknown_task_raises_request_error(self) -> None:+ with patch("sie_sdk.client.async_.aiohttp.ClientSession"):+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(return_value=_aio(404, UNKNOWN_TASK)) # type: ignore[method-assign]++ with pytest.raises(RequestError):+ await client.recommend("embeddings")+ await client.close()diff --git a/packages/sie_sdk/tests/client/test_responses.py b/packages/sie_sdk/tests/client/test_responses.pyindex cae2c64a4..3ee243677 100644--- a/packages/sie_sdk/tests/client/test_responses.py+++ b/packages/sie_sdk/tests/client/test_responses.py@@ -208,6 +208,25 @@ def test_responses_rejects_redirect_without_retrying() -> None:client.close()+def test_responses_consumes_modal_continuation_without_reposting() -> None:+ redirect = _sync_response(+ 303,+ {},+ headers={"location": "/v1/responses?__modal_attempt_token=opaque"},+ )+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:+ client_cls.return_value.post.return_value = redirect+ client_cls.return_value.get.return_value = _sync_response(200, _payload())+ client = SIEClient("https://gateway.example.test")++ result = client.responses("m", "Hi")++ assert result["status"] == "completed"+ assert client_cls.return_value.post.call_count == 1+ assert client_cls.return_value.get.call_args.args[0] == "/v1/responses?__modal_attempt_token=opaque"+ client.close()++def test_responses_does_not_retry_midflight_transport_failure() -> None:with patch("sie_sdk.client.sync.httpx.Client") as client_cls:client_cls.return_value.post.side_effect = httpx.ReadError("connection reset")@@ -354,3 +373,24 @@ async def test_async_responses_does_not_retry_post_publish_timeout() -> None:"credits_debited": 12,}await client.close()+++async def test_async_responses_consumes_modal_continuation_without_reposting() -> None:+ client = SIEAsyncClient("https://gateway.example.test")+ session = _patch_async_session(+ client,+ post_returns=_AsyncRaw(+ 303,+ {},+ headers={"location": "/v1/responses?__modal_attempt_token=opaque"},+ ),+ )+ session.get = MagicMock(return_value=_AsyncRaw(200, _payload()))++ result = await client.responses("m", "Hi")++ assert result["status"] == "completed"+ assert session.post.call_count == 1+ assert session.get.call_args.args[0] == "/v1/responses?__modal_attempt_token=opaque"+ await client.close()diff --git a/packages/sie_sdk/tests/client/test_stream_timeout.py b/packages/sie_sdk/tests/client/test_stream_timeout.pynew file mode 100644index 000000000..c41eca6b1--- /dev/null+++ b/packages/sie_sdk/tests/client/test_stream_timeout.py@@ -0,0 +1,135 @@+"""Async SSE streaming must not be killed by a *total* timeout.++The async client used ``aiohttp.ClientTimeout(total=...)`` on the streaming+POST, which covers the ENTIRE SSE body: any generation streaming longer than+``timeout_s`` (default 30s) died mid-stream with a non-retryable+``SIEConnectionError`` — after the tokens were billed. The read timeout must+be per-read (``sock_read``), so long generations survive while dead+connections still fail within ~``timeout_s``. The sync twin already has+per-read semantics (httpx float timeout is per-phase / per socket read).+"""++from __future__ import annotations++import asyncio+import json+import time+from typing import Any, Self+from unittest.mock import AsyncMock, MagicMock++import pytest+from aiohttp import web+from sie_sdk import SIEAsyncClient+from sie_sdk.client.errors import SIEConnectionError+++class _FakeRaw:+ """Stand-in for an aiohttp response used as an async context manager."""++ def __init__(self, *, line_bytes: list[bytes]) -> None:+ self.status = 200+ self.headers = {"content-type": "text/event-stream"}+ self._line_bytes = line_bytes+ self.content = self._aiter_bytes()++ async def _aiter_bytes(self):+ for b in self._line_bytes:+ yield b++ async def __aenter__(self) -> Self:+ return self++ async def __aexit__(self, *exc: object) -> bool:+ return False+++def _sse_bytes(*chunks: dict[str, Any]) -> list[bytes]:+ out: list[bytes] = []+ for c in chunks:+ out.append(f"data: {json.dumps(c)}\n".encode())+ out.append(b"\n")+ out.append(b"data: [DONE]\n")+ return out+++async def test_async_stream_timeout_is_per_read_not_total() -> None:+ """Pin the ClientTimeout shape on the streaming POST: no ``total``."""+ client = SIEAsyncClient("http://localhost:8080", timeout_s=30.0)+ session = MagicMock()+ session.post = MagicMock(return_value=_FakeRaw(line_bytes=_sse_bytes({"text": "hi"})))+ session.close = AsyncMock()+ client._session = session++ out = [c async for c in client.stream_generate("m", "hi", max_new_tokens=8)]++ assert [c["text"] for c in out] == ["hi"]+ timeout = session.post.call_args.kwargs["timeout"]+ assert timeout.total is None, "a total timeout would kill any stream longer than timeout_s"+ assert timeout.sock_read == 30.0+ assert timeout.connect is not None+ assert timeout.connect <= 30.0+ await client.close()+++async def _start_sse_server(handler: Any) -> tuple[web.AppRunner, str]:+ app = web.Application()+ app.router.add_post("/v1/generate/m", handler)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ host, port = runner.addresses[0][:2]+ return runner, f"http://{host}:{port}"+++async def test_async_stream_survives_longer_than_timeout_s() -> None:+ """End-to-end: chunks each arrive within ``timeout_s`` but the stream as a+ whole runs longer — it must complete, not die mid-stream.+ """++ async def handler(request: web.Request) -> web.StreamResponse:+ resp = web.StreamResponse(headers={"Content-Type": "text/event-stream"})+ await resp.prepare(request)+ for i in range(4):+ await asyncio.sleep(0.25) # inter-chunk gap < timeout_s+ await resp.write(f'data: {{"text": "t{i}"}}\n\n'.encode())+ await resp.write(b"data: [DONE]\n\n")+ await resp.write_eof()+ return resp++ runner, base_url = await _start_sse_server(handler)+ try:+ client = SIEAsyncClient(base_url, timeout_s=0.5) # < total stream duration (~1s)+ out = [c async for c in client.stream_generate("m", "hi", max_new_tokens=8)]+ assert [c["text"] for c in out] == ["t0", "t1", "t2", "t3"]+ await client.close()+ finally:+ await runner.cleanup()+++async def test_async_stream_dead_connection_fails_within_read_timeout() -> None:+ """A stalled stream (no chunks arriving) must still fail in ~``timeout_s``,+ not hang forever now that there is no total timeout.+ """++ async def handler(request: web.Request) -> web.StreamResponse:+ resp = web.StreamResponse(headers={"Content-Type": "text/event-stream"})+ await resp.prepare(request)+ await resp.write(b'data: {"text": "t0"}\n\n')+ await asyncio.sleep(30) # stall: no further reads possible+ return resp++ runner, base_url = await _start_sse_server(handler)+ try:+ client = SIEAsyncClient(base_url, timeout_s=0.4)+ received: list[Any] = []+ start = time.monotonic()+ with pytest.raises(SIEConnectionError):+ async for c in client.stream_generate("m", "hi", max_new_tokens=8):+ received.append(c)+ elapsed = time.monotonic() - start+ assert [c["text"] for c in received] == ["t0"]+ assert elapsed < 5.0, f"dead stream not detected within read timeout: {elapsed:.1f}s"+ await client.close()+ finally:+ await runner.cleanup()diff --git a/packages/sie_sdk/tests/client/test_terminal_msgpack.py b/packages/sie_sdk/tests/client/test_terminal_msgpack.pynew file mode 100644index 000000000..e74d6d5b8--- /dev/null+++ b/packages/sie_sdk/tests/client/test_terminal_msgpack.py@@ -0,0 +1,175 @@+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from msgpack.exceptions import UnpackException+from sie_sdk import RequestError, ServerError, SIEAsyncClient, SIEClient+from sie_sdk._msgpack import packb as pack_msgpack+from sie_sdk.client._shared import get_error_detail, handle_error, parse_terminal_msgpack_object+from sie_sdk.client.async_ import _AioResponse++_ATTACKER_BODY = b"attacker-private-response-token"+++def _object_array_sentinel() -> dict[bytes, object]:+ return {+ b"nd": True,+ b"type": "|O",+ b"kind": b"O",+ b"shape": [1],+ b"data": b"attacker-controlled-pickle",+ }+++def _assert_content_safe_error(error: RequestError, *, expected: str, status_code: int, request_id: str) -> None:+ message = str(error)+ assert message == expected+ assert _ATTACKER_BODY.decode() not in message+ assert error.__context__ is None+ assert error.status_code == status_code+ assert error.request == {"id": request_id}+++ ("status_code", "expected_prefix"),+ [+ (303, "Unexpected score HTTP response"),+ (200, "Malformed score MessagePack response"),+ ],+)+def test_sync_score_rejects_nonterminal_msgpack_content_safely(status_code: int, expected_prefix: str) -> None:+ request_id = f"req-sync-score-{status_code}"+ response = MagicMock(+ status_code=status_code,+ content=_ATTACKER_BODY,+ headers={"content-type": "application/msgpack", "x-sie-request-id": request_id},+ )++ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:+ client_cls.return_value.post.return_value = response+ client = SIEClient("https://gateway.example.test")+ try:+ with pytest.raises(RequestError) as exc_info:+ client.score("Qwen/Qwen3-Reranker-4B", "query", ["candidate"])+ finally:+ client.close()++ _assert_content_safe_error(+ exc_info.value,+ expected=(+ f"{expected_prefix} "+ f"(status={status_code}, content_type=application/msgpack, body_bytes={len(_ATTACKER_BODY)})"+ ),+ status_code=status_code,+ request_id=request_id,+ )+ assert client_cls.call_args.kwargs["follow_redirects"] is False+ client_cls.return_value.post.assert_called_once()+++ ("status_code", "expected_prefix"),+ [+ (303, "Unexpected score HTTP response"),+ (200, "Malformed score MessagePack response"),+ ],+)+async def test_async_score_rejects_nonterminal_msgpack_content_safely(+ status_code: int,+ expected_prefix: str,+) -> None:+ request_id = f"req-async-score-{status_code}"+ response = _AioResponse(+ status_code,+ _ATTACKER_BODY,+ {"content-type": "application/msgpack", "x-sie-request-id": request_id},+ )+ client = SIEAsyncClient("https://gateway.example.test")+ client._post = AsyncMock(return_value=response) # type: ignore[method-assign]+ try:+ with pytest.raises(RequestError) as exc_info:+ await client.score("Qwen/Qwen3-Reranker-4B", "query", ["candidate"])+ finally:+ await client.close()++ _assert_content_safe_error(+ exc_info.value,+ expected=(+ f"{expected_prefix} "+ f"(status={status_code}, content_type=application/msgpack, body_bytes={len(_ATTACKER_BODY)})"+ ),+ status_code=status_code,+ request_id=request_id,+ )+ client._post.assert_awaited_once() # type: ignore[attr-defined]++[email protected]("status_code", [200, 303])+def test_terminal_msgpack_never_unpickles_object_arrays(status_code: int) -> None:+ response = MagicMock(+ status_code=status_code,+ content=pack_msgpack({"items": [{"dense": {"values": _object_array_sentinel()}}]}),+ headers={"content-type": "application/msgpack", "x-sie-request-id": "req-object-array"},+ )++ with patch("msgpack_numpy.pickle.loads") as pickle_loads:+ with pytest.raises(RequestError) as exc_info:+ parse_terminal_msgpack_object(response, owner="encode")++ pickle_loads.assert_not_called()+ assert exc_info.value.status_code == status_code+ assert exc_info.value.request == {"id": "req-object-array"}+ assert exc_info.value.__context__ is None+ assert b"attacker-controlled-pickle" not in str(exc_info.value).encode()+++def test_msgpack_unpack_exceptions_are_sanitized() -> None:+ terminal_response = MagicMock(+ status_code=200,+ content=b"",+ headers={"content-type": "application/msgpack", "x-sie-request-id": "req-truncated"},+ )+ error_response = MagicMock(+ status_code=500,+ content=b"",+ headers={"content-type": "application/msgpack", "x-sie-request-id": "req-truncated"},+ text="safe fallback",+ )++ with patch(+ "sie_sdk.client._shared.unpack_msgpack",+ side_effect=UnpackException("private parser context"),+ ) as unpack:+ with pytest.raises(RequestError) as terminal_error:+ parse_terminal_msgpack_object(terminal_response, owner="encode")+ assert get_error_detail(error_response) is None+ with pytest.raises(ServerError, match="safe fallback") as server_error:+ handle_error(error_response)++ assert unpack.call_count == 3+ assert terminal_error.value.__context__ is None+ assert "private parser context" not in str(terminal_error.value)+ assert "private parser context" not in str(server_error.value)+++ ("status_code", "error_type"),+ [(400, RequestError), (500, ServerError)],+)+def test_msgpack_error_envelopes_never_unpickle_object_arrays(+ status_code: int,+ error_type: type[RequestError | ServerError],+) -> None:+ response = MagicMock(+ status_code=status_code,+ content=pack_msgpack({"error": _object_array_sentinel()}),+ headers={"content-type": "application/msgpack"},+ )++ with patch("msgpack_numpy.pickle.loads") as pickle_loads:+ detail = get_error_detail(response)+ with pytest.raises(error_type):+ handle_error(response)++ pickle_loads.assert_not_called()+ assert detail == _object_array_sentinel()diff --git a/packages/sie_sdk/tests/client/test_transport_error_retry.py b/packages/sie_sdk/tests/client/test_transport_error_retry.pyindex 973254732..ecb58ee27 100644--- a/packages/sie_sdk/tests/client/test_transport_error_retry.py+++ b/packages/sie_sdk/tests/client/test_transport_error_retry.py@@ -6,6 +6,7 @@from __future__ import annotations+import loggingimport threadingimport timefrom concurrent.futures import ThreadPoolExecutor@@ -16,6 +17,8 @@ import httpximport msgpackimport numpy as npimport pytest+from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk.client._shared import url_origin_for_logging@pytest.fixture(autouse=True)@@ -29,6 +32,17 @@ def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr("sie_sdk.client.async_.asyncio.sleep", _noop_async_sleep)+def _logged_origin(message: str) -> str:+ """Extract the origin the retry WARNING reports.++ The message is ``"... contacting <origin>, retrying in ..."``; returning+ the exact token lets tests assert equality against the expected origin+ instead of a URL substring-membership check (``"<url>" in message``),+ which trips CodeQL's ``py/incomplete-url-substring-sanitization`` rule.+ """+ return message.split(" contacting ", 1)[1].split(",", 1)[0]++def _mock_response_200() -> MagicMock:resp = MagicMock()resp.status_code = 200@@ -567,6 +581,122 @@ class TestSyncTransportErrorRetryScoreExtract:assert mock_client.return_value.post.call_count == 1client.close()+ @pytest.mark.usefixtures("_no_sleep")+ def test_connect_retry_logging_first_warning_then_info(self, caplog: pytest.LogCaptureFixture) -> None:+ """The FIRST connect-retry surfaces at WARNING (naming the target URL+ and the total wait budget) so a user at the default log level can see+ the SDK is retrying instead of silently blocking for up to the whole+ provision budget; subsequent retries stay at INFO (OOM convention).++ Declares ``_no_sleep`` via ``usefixtures`` so the retry sleeps are+ patched explicitly (the fixture is also module-autouse).+ """+ exc = httpx.ConnectError("Connection refused")+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post = MagicMock(side_effect=[exc, exc, _mock_response_200()])+ client = SIEClient("http://localhost:8080")++ with caplog.at_level(logging.INFO, logger="sie_sdk.client._shared"):+ client.encode(+ "bge-m3",+ {"text": "hello"},+ wait_for_capacity=True,+ provision_timeout_s=10.0,+ )++ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]+ assert len(warnings) == 1+ message = warnings[0].getMessage()+ assert _logged_origin(message) == "http://localhost:8080"+ assert "timeout: 10.0s" in message+ infos = [r for r in caplog.records if r.levelno == logging.INFO and "Connect error" in r.getMessage()]+ assert len(infos) == 1+ client.close()++ @pytest.mark.asyncio+ @pytest.mark.usefixtures("_no_sleep")+ async def test_async_connect_retry_logging_first_warning_then_info(self, caplog: pytest.LogCaptureFixture) -> None:+ """Async mirror of the first-connect-retry WARNING convention.++ Declares ``_no_sleep`` via ``usefixtures`` so the retry sleeps are+ patched explicitly (the fixture is also module-autouse).+ """+ exc = TestAsyncTransportErrorRetry._make_connector_error()+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(side_effect=[exc, exc, _async_response_200()]) # type: ignore++ with caplog.at_level(logging.INFO, logger="sie_sdk.client._shared"):+ await client.encode(+ "bge-m3",+ {"text": "hello"},+ wait_for_capacity=True,+ provision_timeout_s=10.0,+ )++ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]+ assert len(warnings) == 1+ message = warnings[0].getMessage()+ assert _logged_origin(message) == "http://localhost:8080"+ assert "timeout: 10.0s" in message+ infos = [r for r in caplog.records if r.levelno == logging.INFO and "Connect error" in r.getMessage()]+ assert len(infos) == 1+ await client.close()++ # A base_url carrying credentials in userinfo AND a token query param —+ # the log must leak neither. Only the scheme://host:port origin is logged.+ _CREDENTIALED_BASE_URL = "https://user:[email protected]:8443/v1?access_token=querysecret"++ @pytest.mark.usefixtures("_no_sleep")+ def test_connect_retry_warning_logs_origin_only(self, caplog: pytest.LogCaptureFixture) -> None:+ """A base_url carrying credentials/tokens must NOT leak them into logs.++ The retry WARNING logs only the+ ``scheme://host:port`` origin — no userinfo, no path, no query.+ """+ # The helper strips userinfo, path, and query — only the origin remains.+ expected_origin = url_origin_for_logging(self._CREDENTIALED_BASE_URL)+ assert expected_origin == "https://gateway.example.test:8443"++ exc = httpx.ConnectError("Connection refused")+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post = MagicMock(side_effect=[exc, _mock_response_200()])+ client = SIEClient(self._CREDENTIALED_BASE_URL)++ with caplog.at_level(logging.INFO, logger="sie_sdk.client._shared"):+ client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=True, provision_timeout_s=10.0)++ blob = "\n".join(r.getMessage() for r in caplog.records)+ assert "s3cr3t-token" not in blob+ assert "querysecret" not in blob+ assert "user:" not in blob+ assert "access_token" not in blob+ warning = next(r.getMessage() for r in caplog.records if r.levelno == logging.WARNING)+ assert _logged_origin(warning) == expected_origin+ client.close()++ @pytest.mark.asyncio+ @pytest.mark.usefixtures("_no_sleep")+ async def test_async_connect_retry_warning_logs_origin_only(self, caplog: pytest.LogCaptureFixture) -> None:+ """Async mirror: embedded credentials and query tokens must not reach the log."""+ expected_origin = url_origin_for_logging(self._CREDENTIALED_BASE_URL)+ assert expected_origin == "https://gateway.example.test:8443"++ exc = TestAsyncTransportErrorRetry._make_connector_error()+ client = SIEAsyncClient(self._CREDENTIALED_BASE_URL)+ client._post = AsyncMock(side_effect=[exc, _async_response_200()]) # type: ignore++ with caplog.at_level(logging.INFO, logger="sie_sdk.client._shared"):+ await client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=True, provision_timeout_s=10.0)++ blob = "\n".join(r.getMessage() for r in caplog.records)+ assert "s3cr3t-token" not in blob+ assert "querysecret" not in blob+ assert "user:" not in blob+ assert "access_token" not in blob+ warning = next(r.getMessage() for r in caplog.records if r.levelno == logging.WARNING)+ assert _logged_origin(warning) == expected_origin+ await client.close()+def test_extract_fails_fast_on_permanent_connect_error(self) -> None:import ssldiff --git a/packages/sie_sdk/tests/test_cache.py b/packages/sie_sdk/tests/test_cache.pyindex 3e2d68564..77d668f22 100644--- a/packages/sie_sdk/tests/test_cache.py+++ b/packages/sie_sdk/tests/test_cache.py@@ -1,6 +1,7 @@"""Tests for model weight caching hierarchy."""from pathlib import Path+from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport pytest@@ -17,6 +18,42 @@ from sie_sdk.cache import (populate_cluster_cache,)from sie_sdk.exceptions import GatedModelError+from sie_sdk.storage import OSSBackend+++class FakeOSSCacheBucket:+ """Small hierarchical OSS fake backed by realistic HF cache objects."""++ def __init__(self, objects: dict[str, bytes]) -> None:+ self.objects = objects++ def list_objects_v2(+ self,+ *,+ prefix: str,+ delimiter: str,+ continuation_token: str,+ max_keys: int,+ ) -> SimpleNamespace:+ assert continuation_token == ""+ matching = [key for key in sorted(self.objects) if key.startswith(prefix)]+ object_keys: list[str] = []+ prefix_keys: set[str] = set()+ for key in matching:+ relative = key[len(prefix) :]+ if delimiter and delimiter in relative:+ prefix_keys.add(f"{prefix}{relative.split(delimiter, maxsplit=1)[0]}{delimiter}")+ else:+ object_keys.append(key)+ return SimpleNamespace(+ object_list=[SimpleNamespace(key=key) for key in object_keys[:max_keys]],+ prefix_list=sorted(prefix_keys)[:max_keys],+ is_truncated=False,+ next_continuation_token="",+ )++ def get_object_to_file(self, key: str, filename: str) -> None:+ Path(filename).write_bytes(self.objects[key])class TestGetCacheConfig:@@ -77,6 +114,13 @@ class TestGetCacheConfig:assert config.cluster_cache == "abfs://[email protected]/models"+ def test_cluster_cache_oss(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_CLUSTER_CACHE", "oss://my-bucket/models")++ config = get_cache_config()++ assert config.cluster_cache == "oss://my-bucket/models"+def test_hf_fallback_disabled(self, monkeypatch: pytest.MonkeyPatch) -> None:"""SIE_HF_FALLBACK=false disables HF fallback."""monkeypatch.setenv("SIE_HF_FALLBACK", "false")@@ -219,6 +263,31 @@ class TestEnsureModelCached:with pytest.raises(RuntimeError, match="not found in local or cluster cache"):ensure_model_cached("BAAI/bge-m3", config)+ def test_realistic_hf_snapshot_tree_downloads_from_oss(self, tmp_path: Path) -> None:+ model_root = "models/models--openai--clip-vit-base-patch32"+ snapshot = "0123456789abcdef"+ objects = {+ f"{model_root}/refs/main": snapshot.encode(),+ f"{model_root}/blobs/config-hash": b"{}",+ f"{model_root}/snapshots/{snapshot}/config.json": b'{"model_type":"clip"}',+ f"{model_root}/snapshots/{snapshot}/model.safetensors": b"weights",+ }+ backend = OSSBackend()+ backend._buckets["model-cache"] = FakeOSSCacheBucket(objects)+ config = CacheConfig(+ local_cache=tmp_path,+ cluster_cache="oss://model-cache/models",+ hf_fallback=False,+ )++ with patch("sie_sdk.cache.get_storage_backend", return_value=backend):+ result = ensure_model_cached("openai/clip-vit-base-patch32", config)++ assert result == tmp_path / "models--openai--clip-vit-base-patch32"+ assert (result / "refs" / "main").read_text() == snapshot+ assert (result / "snapshots" / snapshot / "config.json").read_text() == '{"model_type":"clip"}'+ assert (result / "snapshots" / snapshot / "model.safetensors").read_bytes() == b"weights"+class TestCacheHierarchy:"""Integration tests for the full caching hierarchy."""diff --git a/packages/sie_sdk/tests/test_error_exports.py b/packages/sie_sdk/tests/test_error_exports.pynew file mode 100644index 000000000..c761b80a6--- /dev/null+++ b/packages/sie_sdk/tests/test_error_exports.py@@ -0,0 +1,145 @@+"""Every SDK error a caller can be handed must be importable from ``sie_sdk``.++The SDK's error docstrings tell callers to catch specific classes ("new code+can catch :class:`RateLimitError` specifically to back off at a higher level"),+but a class that is raised on a public code path and absent from the top-level+package is unreachable advice: ``from sie_sdk import RateLimitError`` fails, so+the caller is forced to reach into ``sie_sdk.client.errors`` or to over-catch a+base class. These tests pin the public surface so an error added to+``client/errors.py`` cannot ship without an export again.++The TypeScript SDK already exports its full error set from ``index.ts``; the+cross-SDK parity test below keeps the two surfaces from drifting apart.+"""++from __future__ import annotations++import inspect+import re+from pathlib import Path++import pytest+import sie_sdk+import sie_sdk.client+import sie_sdk.client.errors++# tests/ -> sie_sdk/ -> packages/ ; the TS SDK is a sibling package.+_TS_INDEX = Path(__file__).parents[2] / "sie_ts_sdk" / "src" / "index.ts"++# TS-only classes with no Python counterpart by design:+# SIEStreamError — the TS client's SSE-abort signal; the Python client+# surfaces stream faults as SIEConnectionError.+_TS_ONLY = frozenset({"SIEStreamError"})+++def _public_error_classes(module: object) -> set[str]:+ """Names of public exception classes defined directly in ``module``."""+ return {+ name+ for name, obj in inspect.getmembers(module, inspect.isclass)+ if issubclass(obj, BaseException) and not name.startswith("_") and obj.__module__ == module.__name__+ }+++def test_every_error_class_is_exported_from_the_package_root() -> None:+ """No error defined in ``client/errors.py`` may be missing from ``sie_sdk``."""+ missing = sorted(_public_error_classes(sie_sdk.client.errors) - set(sie_sdk.__all__))+ assert not missing, f"error classes unreachable via `from sie_sdk import ...`: {missing}"+++def test_every_error_class_is_exported_from_the_client_package() -> None:+ """``sie_sdk.client`` documents itself as re-exporting *all* client errors."""+ missing = sorted(_public_error_classes(sie_sdk.client.errors) - set(sie_sdk.client.__all__))+ assert not missing, f"error classes missing from sie_sdk.client.__all__: {missing}"+++# Errors a caller can be handed that are NOT defined in client/errors.py, with+# the module that raises each. They belong in the root package but not in+# `sie_sdk.client`, which re-exports the *client's* errors:+# GatedModelError raised by sie_sdk.cache during a gated weight download+# MalformedChunkError raised by sie_sdk.jobs.decode_chunk_bytes; the client+# catches it internally and warns rather than propagating+_NON_CLIENT_ERRORS = frozenset({"GatedModelError", "MalformedChunkError"})+++ "name",+ [+ "AccountInactiveError",+ "AccountStateUnavailableError",+ "EstimateUnroutableError",+ "GatedModelError",+ "IncompleteBatchError",+ "InputTooLongError",+ "InsufficientCreditsError",+ "JobFailedError",+ "LoraLoadingError",+ "MalformedChunkError",+ "ModelLoadFailedError",+ "ModelLoadingError",+ "PoolError",+ "ProvisioningError",+ "RateLimitError",+ "RequestError",+ "ResourceExhaustedError",+ "SIEConnectionError",+ "SIEError",+ "ServerError",+ "SpendLimitError",+ ],+)+def test_error_is_importable_and_declared(name: str) -> None:+ """Each caller-catchable error resolves as an attribute and is in ``__all__``.++ Checked against both public namespaces, except for the errors that are not+ the client's to export (see ``_NON_CLIENT_ERRORS``) — putting those in+ ``sie_sdk.client`` would advertise them as client errors, which they are+ not.+ """+ assert name in sie_sdk.__all__, f"{name} missing from sie_sdk.__all__"+ obj = getattr(sie_sdk, name)+ assert isinstance(obj, type), f"{name} is not a class"+ assert issubclass(obj, BaseException), f"{name} is not an exception type"++ if name in _NON_CLIENT_ERRORS:+ assert name not in sie_sdk.client.__all__, (+ f"{name} is not defined in client/errors.py; exporting it from sie_sdk.client "+ "would mislabel it as a client error"+ )+ return+ assert name in sie_sdk.client.__all__, f"{name} missing from sie_sdk.client.__all__"+ assert getattr(sie_sdk.client, name) is obj, f"{name} differs between sie_sdk and sie_sdk.client"+++def test_all_entries_resolve() -> None:+ """``__all__`` must not advertise a name the package cannot supply."""+ unresolved = [name for name in sie_sdk.__all__ if not hasattr(sie_sdk, name)]+ assert not unresolved, f"names in __all__ with no attribute: {unresolved}"+++def test_all_is_sorted_and_unique() -> None:+ """Keep ``__all__`` in the sorted, duplicate-free form ruff's RUF022 expects."""+ assert sie_sdk.__all__ == sorted(set(sie_sdk.__all__))+ assert sie_sdk.client.__all__ == sorted(set(sie_sdk.client.__all__))+++def test_non_client_errors_are_still_reachable_from_the_root() -> None:+ """The classes excluded from `sie_sdk.client` must not be unreachable."""+ for name in sorted(_NON_CLIENT_ERRORS):+ assert name in sie_sdk.__all__+ assert issubclass(getattr(sie_sdk, name), BaseException)++[email protected](not _TS_INDEX.is_file(), reason="TypeScript SDK not present in this checkout")+def test_python_exports_every_error_the_typescript_sdk_exports() -> None:+ """Both SDKs must offer the same catchable error vocabulary.++ A caller porting error handling between the two SDKs should not discover+ that a class exists in one and not the other.+ """+ block = re.search(r"export \{([^}]*)\} from \"\./errors\.js\";", _TS_INDEX.read_text())+ assert block is not None, "could not locate the error re-export block in index.ts"+ ts_errors = {name.strip() for name in block.group(1).split(",") if name.strip()}++ missing = sorted(ts_errors - _TS_ONLY - set(sie_sdk.__all__))+ assert not missing, f"exported by the TypeScript SDK but not by sie_sdk: {missing}"diff --git a/packages/sie_sdk/tests/test_msgpack_safety.py b/packages/sie_sdk/tests/test_msgpack_safety.pynew file mode 100644index 000000000..b11550a78--- /dev/null+++ b/packages/sie_sdk/tests/test_msgpack_safety.py@@ -0,0 +1,103 @@+from __future__ import annotations++from unittest.mock import patch++import msgpack+import numpy as np+import pytest+from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk._msgpack import UnsafeMessagePackError, packb, unpackb+from sie_sdk.jobs import decode_chunk_bytes+++def _object_array_sentinel() -> dict[bytes, object]:+ return {+ b"nd": True,+ b"type": "|O",+ b"kind": b"O",+ b"shape": [1],+ b"data": b"attacker-controlled-pickle",+ }+++ "array",+ [+ np.array([1.0, 2.0], dtype=np.float32),+ np.array([1, 2], dtype=np.int32),+ np.array([[1.0, 2.0]], dtype=np.float16),+ np.array([[1.0, 2.0]], dtype=np.float32),+ np.array([1, 2], dtype=np.uint8),+ np.array([1, 2], dtype=np.uint16),+ ],+)+def test_numeric_msgpack_round_trip_preserves_array(array: np.ndarray) -> None:+ decoded = unpackb(packb({"value": array}), numeric_arrays=True)["value"]++ assert isinstance(decoded, np.ndarray)+ assert decoded.dtype == array.dtype+ assert decoded.shape == array.shape+ np.testing.assert_array_equal(decoded, array)+++ "array",+ [+ np.array([object()], dtype=object),+ np.array([(1,)], dtype=[("value", "<i4")]),+ ],+)+def test_numeric_msgpack_encoder_rejects_object_and_structured_arrays(array: np.ndarray) -> None:+ with pytest.raises(UnsafeMessagePackError):+ packb({"value": array})+++ "sentinel",+ [+ _object_array_sentinel(),+ {b"nd": True, b"type": "<i4", b"kind": b"V", b"shape": [1], b"data": b"\0\0\0\0"},+ {b"nd": True, b"type": "<f4", b"shape": [2], b"data": b"\0\0\0\0"},+ {b"nd": True, b"type": "<f4", b"shape": [True], b"data": b"\0\0\0\0"},+ ],+)+def test_numeric_msgpack_decoder_rejects_unsafe_or_malformed_arrays(+ sentinel: dict[bytes, object],+) -> None:+ raw = packb({"value": sentinel})++ with patch("msgpack_numpy.pickle.loads") as pickle_loads:+ with pytest.raises(UnsafeMessagePackError):+ unpackb(raw, numeric_arrays=True)++ pickle_loads.assert_not_called()+++def test_job_chunk_decoders_never_unpickle_outer_or_inner_payloads() -> None:+ inner = packb({"dense": {"dims": 1, "values": _object_array_sentinel()}})+ outer = packb(+ [+ {"id": "inner", "success": True, "result_msgpack": inner},+ _object_array_sentinel(),+ ]+ )++ with patch("msgpack_numpy.pickle.loads") as pickle_loads:+ decoded = decode_chunk_bytes(outer)++ pickle_loads.assert_not_called()+ assert len(decoded) == 2+ assert decoded[0]["id"] == "inner"+ assert decoded[0]["dense"] is None+++async def test_client_construction_does_not_patch_process_global_msgpack() -> None:+ before = (msgpack.Packer, msgpack.Unpacker, msgpack.packb, msgpack.unpackb)++ sync_client = SIEClient("https://gateway.example.test")+ async_client = SIEAsyncClient("https://gateway.example.test")+ sync_client.close()+ await async_client.close()++ assert (msgpack.Packer, msgpack.Unpacker, msgpack.packb, msgpack.unpackb) == beforediff --git a/packages/sie_sdk/tests/test_redaction.py b/packages/sie_sdk/tests/test_redaction.pyindex e19c3e9a9..8f7bce49c 100644--- a/packages/sie_sdk/tests/test_redaction.py+++ b/packages/sie_sdk/tests/test_redaction.py@@ -1,6 +1,7 @@"""Shared redaction helpers (#2339) — canonical behavior both planes rely on."""-from sie_sdk.redaction import endpoint_origin_for_log, mask_token+import pytest+from sie_sdk.redaction import REDACTED, endpoint_origin_for_log, mask_token, redact_secretsdef test_mask_token_long() -> None:@@ -31,3 +32,47 @@ def test_endpoint_origin_redacts_non_http_or_unparseable() -> None:def test_endpoint_origin_brackets_ipv6() -> None:assert endpoint_origin_for_log("http://[::1]:4318/v1/metrics") == "http://[::1]:4318"+++# Fixtures are concatenated at runtime: a secret-shaped literal in a committed+# file trips the repo's gitleaks pre-commit hook even when it is a test double.+_FAKE_BEARER = "abcdefghij" + "klmnop1234"+_FAKE_API_KEY = "sk-" + "sie-0123456789abcdefghij"+_FAKE_AWS_KEY_ID = "AKIA" + "IOSFODNN7EXAMPLE"+# STS temporary credentials use the ASIA prefix; still live for the session.+_FAKE_AWS_STS_KEY_ID = "ASIA" + "IOSFODNN7EXAMPLE"+_FAKE_JWT_SIGNATURE = "dBjftJeZ4CVPmB92" + "K27uhbUJU1p1r_wW1gFWFOEjXk"+_FAKE_JWT = ".".join(["eyJ" + "hbGciOiJIUzI1NiJ9", "eyJ" + "zdWIiOiIxMjM0NTY3ODkwIn0", _FAKE_JWT_SIGNATURE])+++ ("secret", "must_not_survive"),+ [+ (f"Bearer {_FAKE_BEARER}", _FAKE_BEARER),+ (_FAKE_API_KEY, _FAKE_API_KEY),+ (_FAKE_AWS_KEY_ID, _FAKE_AWS_KEY_ID),+ (_FAKE_AWS_STS_KEY_ID, _FAKE_AWS_STS_KEY_ID),+ (_FAKE_JWT, _FAKE_JWT_SIGNATURE),+ ("api_key=hunter2andthensome", "hunter2andthensome"),+ ('refresh_token: "rt-abcdefghijklmnop"', "rt-abcdefghijklmnop"),+ ("client_secret=zzzzzzzzzzzz", "zzzzzzzzzzzz"),+ ("[email protected]", "[email protected]"),+ ],+)+def test_redact_secrets_scrubs_credential_and_pii_shapes(secret: str, must_not_survive: str) -> None:+ scrubbed = redact_secrets(f"upstream said: {secret} -- retry later")+ assert must_not_survive not in scrubbed+ assert REDACTED in scrubbed+ # The surrounding diagnostic survives.+ assert "upstream said" in scrubbed+ assert "retry later" in scrubbed+++def test_redact_secrets_keeps_the_key_name_for_key_value_shapes() -> None:+ assert redact_secrets("api_key=abcdefgh") == f"api_key={REDACTED}"+ assert redact_secrets("access_token: abcdefgh") == f"access_token={REDACTED}"+++def test_redact_secrets_leaves_ordinary_diagnostics_intact() -> None:+ message = "no healthy workers for BAAI/bge-m3 (queue depth 12, gpu l4)"+ assert redact_secrets(message) == messagediff --git a/packages/sie_sdk/tests/test_scoring.py b/packages/sie_sdk/tests/test_scoring.pyindex d54500fcb..23845de38 100644--- a/packages/sie_sdk/tests/test_scoring.py+++ b/packages/sie_sdk/tests/test_scoring.py@@ -1,6 +1,7 @@"""Tests for SDK scoring module (maxsim / maxsim_batch utilities)."""import numpy as np+import pytestfrom sie_sdk.scoring import maxsim, maxsim_batch# Create a random generator for tests@@ -150,3 +151,85 @@ class TestMaxSimBatch:actual = maxsim_batch(queries, docs)np.testing.assert_allclose(actual, expected, rtol=0, atol=0)+++class TestMaxsimInputValidation:+ """Common misuse must name the fault, not leak NumPy's gufunc signature.++ Callers hold vectors they read back out of a vector database, so shape and+ width faults are the expected failure mode. Before this, all three cases+ below surfaced as raw NumPy errors quoting+ ``gufunc signature (n?,k),(k,m?)->(n?,m?)`` — which never mentions query,+ document, or which side was wrong.+ """++ def test_dim_mismatch_names_both_widths(self) -> None:+ query = np.zeros((3, 128), dtype=np.float32)+ doc = np.zeros((4, 64), dtype=np.float32)++ with pytest.raises(ValueError, match=r"dim mismatch: query has dim 128 but documents\[0\] has dim 64"):+ maxsim(query, [doc])++ def test_empty_document_is_rejected_with_its_shape(self) -> None:+ query = np.zeros((3, 128), dtype=np.float32)+ empty = np.zeros((0, 128), dtype=np.float32)++ with pytest.raises(ValueError, match=r"documents\[0\] has 0 tokens"):+ maxsim(query, [empty])++ def test_empty_query_is_rejected(self) -> None:+ with pytest.raises(ValueError, match=r"query has 0 tokens"):+ maxsim(np.zeros((0, 128), dtype=np.float32), [np.zeros((2, 128), dtype=np.float32)])++ def test_single_vector_passed_unwrapped_explains_the_fix(self) -> None:+ """A 1-D array is the classic slip; the message must say how to fix it."""+ query = np.zeros((3, 128), dtype=np.float32)++ with pytest.raises(ValueError, match=r"must be a 2-D array"):+ maxsim(query, np.zeros(128, dtype=np.float32))++ def test_1d_query_is_rejected(self) -> None:+ with pytest.raises(ValueError, match=r"query must be a 2-D array"):+ maxsim(np.zeros(128, dtype=np.float32), [np.zeros((2, 128), dtype=np.float32)])++ def test_the_offending_document_is_identified_by_index(self) -> None:+ query = np.zeros((2, 8), dtype=np.float32)+ docs = [np.zeros((3, 8), dtype=np.float32), np.zeros((3, 4), dtype=np.float32)]++ with pytest.raises(ValueError, match=r"documents\[1\] has dim 4"):+ maxsim(query, docs)++ def test_empty_document_list_still_returns_no_scores(self) -> None:+ """Zero documents is a legitimate empty result, not an error."""+ assert maxsim(np.zeros((2, 8), dtype=np.float32), []) == []++ def test_valid_input_is_unaffected(self) -> None:+ query = np.array([[1.0, 0.0], [0.0, 1.0]], dtype=np.float32)+ doc1 = np.array([[1.0, 0.0], [0.5, 0.5]], dtype=np.float32)+ doc2 = np.array([[0.0, 1.0]], dtype=np.float32)++ scores = maxsim(query, [doc1, doc2])+ assert len(scores) == 2+ assert scores[0] > scores[1]++ def test_batch_dim_mismatch_is_named(self) -> None:+ with pytest.raises(ValueError, match=r"dim mismatch"):+ maxsim_batch(+ [np.zeros((2, 8), dtype=np.float32)],+ [np.zeros((3, 5), dtype=np.float32)],+ )++ def test_batch_empty_document_is_named(self) -> None:+ with pytest.raises(ValueError, match=r"documents\[0\] has 0 tokens"):+ maxsim_batch(+ [np.zeros((2, 8), dtype=np.float32)],+ [np.zeros((0, 8), dtype=np.float32)],+ )++ def test_batch_valid_input_is_unaffected(self) -> None:+ queries = [np.array([[1.0, 0.0]], dtype=np.float32), np.array([[0.0, 1.0]], dtype=np.float32)]+ docs = [np.array([[1.0, 0.0]], dtype=np.float32), np.array([[0.0, 1.0]], dtype=np.float32)]++ scores = maxsim_batch(queries, docs)+ assert scores.shape == (2, 2)+ assert scores[0, 0] > scores[0, 1]diff --git a/packages/sie_sdk/tests/test_storage.py b/packages/sie_sdk/tests/test_storage.pyindex 7d53cc29b..c0c955ce8 100644--- a/packages/sie_sdk/tests/test_storage.py+++ b/packages/sie_sdk/tests/test_storage.py@@ -1,8 +1,11 @@"""Tests for storage backend functionality."""+import json+import loggingimport sysimport typesfrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import MagicMockimport pytest@@ -10,7 +13,9 @@ from sie_sdk.storage import (AzureBlobBackend,GCSBackend,LocalBackend,+ OSSBackend,S3Backend,+ _AlibabaCredentialsProvider,get_storage_backend,is_cloud_path,join_path,@@ -526,6 +531,280 @@ class TestAzureBlobBackend:)+class TestOSSBackend:+ """Alibaba OSS uses strict URLs, V4 signing, and provider credentials."""++ @staticmethod+ def _backend_with_bucket(bucket: MagicMock) -> OSSBackend:+ backend = OSSBackend()+ backend._buckets["sie-cache"] = bucket+ return backend++ @pytest.mark.parametrize(+ "url",+ [+ "oss://",+ "oss://ABCD/models",+ "oss://ab/models",+ "oss://user:password@sie-cache/models",+ "oss://sie-cache/models?token=sensitive",+ "oss://sie-cache/models#fragment",+ "oss://sie-cache//models",+ "oss://sie-cache/models/../payloads",+ "oss://sie-cache/models/%2e%2e/payloads",+ "oss://sie-cache/models\\payloads",+ "oss://sie-cache/models with spaces",+ f"oss://sie-cache/{'a' * 1024}",+ ],+ )+ def test_parse_rejects_ambiguous_or_credential_bearing_urls(self, url: str) -> None:+ with pytest.raises(ValueError, match="OSS"):+ OSSBackend._parse_oss_url(url)++ def test_parse_accepts_bucket_root_and_safe_prefix(self) -> None:+ assert OSSBackend._parse_oss_url("oss://sie-cache") == ("sie-cache", "")+ assert OSSBackend._parse_oss_url("oss://sie-cache/models/snapshots/") == (+ "sie-cache",+ "models/snapshots/",+ )++ def test_shared_payload_wire_fixture_matches_python_path_contract(self) -> None:+ fixture_path = Path(__file__).parents[2] / "wire-fixtures" / "oss_payload_store.json"+ fixture = json.loads(fixture_path.read_text())++ bucket, object_key = OSSBackend._parse_oss_url(fixture["full_reference"])+ assert fixture["version"] == 1+ assert fixture["scheme"] == "oss"+ assert bucket == fixture["bucket"]+ assert object_key == fixture["object_key"]+ assert object_key == f"{fixture['prefix']}/{fixture['plain_key']}"+ assert join_path(f"oss://{bucket}", fixture["prefix"], fixture["plain_key"]) == fixture["full_reference"]++ def test_paginated_listing_filters_markers_and_nested_files(self) -> None:+ bucket = MagicMock()+ page_marker = "page-2"+ bucket.list_objects_v2.side_effect = [+ SimpleNamespace(+ prefix_list=["models/first/"],+ object_list=[],+ is_truncated=True,+ next_continuation_token=page_marker,+ ),+ SimpleNamespace(+ prefix_list=["models/second/"],+ object_list=[],+ is_truncated=False,+ next_continuation_token="",+ ),+ SimpleNamespace(+ prefix_list=[],+ object_list=[+ SimpleNamespace(key="models/"),+ SimpleNamespace(key="models/config.yaml"),+ SimpleNamespace(key="models/readme.md"),+ SimpleNamespace(key="models/nested/ignored.yaml"),+ ],+ is_truncated=False,+ next_continuation_token="",+ ),+ ]+ backend = self._backend_with_bucket(bucket)++ assert list(backend.list_dirs("oss://sie-cache/models")) == ["first", "second"]+ assert list(backend.list_files("oss://sie-cache/models", "*.yaml")) == ["config.yaml"]+ assert bucket.list_objects_v2.call_args_list[0].kwargs["continuation_token"] == ""+ assert bucket.list_objects_v2.call_args_list[1].kwargs["continuation_token"] == page_marker++ def test_has_children_ignores_folder_marker(self) -> None:+ bucket = MagicMock()+ bucket.list_objects_v2.side_effect = [+ SimpleNamespace(object_list=[SimpleNamespace(key="models/snapshots/")]),+ SimpleNamespace(+ object_list=[+ SimpleNamespace(key="models/snapshots/"),+ SimpleNamespace(key="models/snapshots/abc/config.json"),+ ]+ ),+ ]+ backend = self._backend_with_bucket(bucket)++ assert backend.has_children("oss://sie-cache/models/snapshots") is False+ assert backend.has_children("oss://sie-cache/models/snapshots") is True+ assert bucket.list_objects_v2.call_args.kwargs == {+ "prefix": "models/snapshots/",+ "delimiter": "",+ "continuation_token": "",+ "max_keys": 2,+ }++ def test_download_exists_and_read_text_use_exact_key(self, tmp_path: Path) -> None:+ bucket = MagicMock()+ bucket.object_exists.return_value = True+ result = MagicMock()+ result.read.return_value = b"model: clip\n"+ bucket.get_object.return_value = result+ backend = self._backend_with_bucket(bucket)+ destination = tmp_path / "nested" / "config.yaml"++ backend.download_file("oss://sie-cache/models/config.yaml", destination)+ assert backend.exists("oss://sie-cache/models/config.yaml") is True+ assert backend.read_text("oss://sie-cache/models/config.yaml") == "model: clip\n"++ bucket.get_object_to_file.assert_called_once_with("models/config.yaml", str(destination))+ bucket.object_exists.assert_called_once_with("models/config.yaml")+ bucket.get_object.assert_called_once_with("models/config.yaml")+ result.close.assert_called_once_with()++ def test_provider_failure_is_sanitized(self) -> None:+ class SecretError(Exception):+ status = 403+ code = "AccessDenied"++ def __str__(self) -> str:+ return "token=projected-secret request-id=raw-id"++ bucket = MagicMock()+ bucket.get_object.side_effect = SecretError()+ backend = self._backend_with_bucket(bucket)++ with pytest.raises(RuntimeError) as exc_info:+ backend.read_text("oss://sie-cache/models/config.yaml")++ message = str(exc_info.value)+ assert message == "Alibaba OSS read failed (status=403, code=AccessDenied)"+ assert "projected-secret" not in message+ assert "raw-id" not in message++ def test_bucket_construction_uses_v4_and_derived_internal_endpoint(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ calls: dict[str, object] = {}+ oss2_module = types.ModuleType("oss2")++ def provider_auth_v4(provider: object) -> object:+ calls["provider"] = provider+ return "v4-auth"++ def bucket_factory(auth: object, endpoint: str, bucket_name: str, **kwargs: object) -> object:+ calls["bucket"] = (auth, endpoint, bucket_name, kwargs)+ return object()++ oss2_module.ProviderAuthV4 = provider_auth_v4+ oss2_module.Bucket = bucket_factory+ monkeypatch.setitem(sys.modules, "oss2", oss2_module)+ monkeypatch.setenv("SIE_OSS_REGION", "eu-central-1")+ monkeypatch.setenv("SIE_OSS_USE_INTERNAL_ENDPOINT", "true")++ backend = OSSBackend()+ backend._credential_client = MagicMock()+ backend._get_bucket("sie-cache")++ assert calls["bucket"] == (+ "v4-auth",+ "https://oss-eu-central-1-internal.aliyuncs.com",+ "sie-cache",+ {"app_name": "sie-sdk", "region": "eu-central-1"},+ )+ assert calls["provider"] is backend._credentials_provider+ assert not hasattr(oss2_module, "Auth")+ assert logging.getLogger("oss2.http").getEffectiveLevel() >= logging.WARNING++ def test_endpoint_config_rejects_invalid_region_and_boolean(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_OSS_REGION", "https://attacker.invalid")+ with pytest.raises(ValueError, match="SIE_OSS_REGION"):+ OSSBackend._resolve_runtime_endpoint()++ monkeypatch.setenv("SIE_OSS_REGION", "eu-central-1")+ monkeypatch.setenv("SIE_OSS_USE_INTERNAL_ENDPOINT", "sometimes")+ with pytest.raises(ValueError, match="SIE_OSS_USE_INTERNAL_ENDPOINT"):+ OSSBackend._resolve_runtime_endpoint()++ def test_partial_rrsa_configuration_fails_closed(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("ALIBABA_CLOUD_ROLE_ARN", "sensitive-role-value")+ monkeypatch.delenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN", raising=False)+ monkeypatch.delenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE", raising=False)++ with pytest.raises(RuntimeError) as exc_info:+ OSSBackend._build_credential_client()++ message = str(exc_info.value)+ assert "incomplete" in message+ assert "sensitive-role-value" not in message++ def test_complete_rrsa_configuration_selects_explicit_oidc_client(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ package = types.ModuleType("alibabacloud_credentials")+ client_module = types.ModuleType("alibabacloud_credentials.client")+ models_module = types.ModuleType("alibabacloud_credentials.models")++ class FakeConfig:+ def __init__(self, **kwargs: object) -> None:+ self.kwargs = kwargs++ class FakeClient:+ def __init__(self, config: FakeConfig | None = None) -> None:+ self.config = config++ client_module.Client = FakeClient+ models_module.Config = FakeConfig+ monkeypatch.setitem(sys.modules, "alibabacloud_credentials", package)+ monkeypatch.setitem(sys.modules, "alibabacloud_credentials.client", client_module)+ monkeypatch.setitem(sys.modules, "alibabacloud_credentials.models", models_module)+ monkeypatch.setenv("ALIBABA_CLOUD_ROLE_ARN", "acs:ram::example:role/workload")+ monkeypatch.setenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN", "acs:ram::example:oidc-provider/ack")+ monkeypatch.setenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE", "/var/run/secrets/ack/token")+ monkeypatch.setenv("ALIBABA_CLOUD_ROLE_SESSION_NAME", "sie-worker")++ client = OSSBackend._build_credential_client()++ assert client.config is not None+ assert client.config.kwargs == {+ "type": "oidc_role_arn",+ "role_arn": "acs:ram::example:role/workload",+ "oidc_provider_arn": "acs:ram::example:oidc-provider/ack",+ "oidc_token_file_path": "/var/run/secrets/ack/token",+ "role_session_name": "sie-worker",+ }++ def test_credentials_adapter_refreshes_and_sanitizes(self, monkeypatch: pytest.MonkeyPatch) -> None:+ credentials_module = types.ModuleType("oss2.credentials")++ class FakeCredentials:+ def __init__(self, access_key_id: str, access_key_secret: str, security_token: str) -> None:+ self.values = (access_key_id, access_key_secret, security_token)++ credentials_module.Credentials = FakeCredentials+ monkeypatch.setitem(sys.modules, "oss2.credentials", credentials_module)+ client = MagicMock()+ first_values = ("id-1", "secret-1", "token-1")+ second_values = ("id-2", "secret-2", "token-2")+ client.get_credential.side_effect = [+ SimpleNamespace(+ access_key_id=first_values[0],+ access_key_secret=first_values[1],+ security_token=first_values[2],+ ),+ SimpleNamespace(+ access_key_id=second_values[0],+ access_key_secret=second_values[1],+ security_token=second_values[2],+ ),+ ]+ provider = _AlibabaCredentialsProvider(client)++ assert provider.get_credentials().values == first_values+ assert provider.get_credentials().values == second_values+ assert client.get_credential.call_count == 2++ client.get_credential.side_effect = RuntimeError("OIDC token=projected-secret")+ with pytest.raises(RuntimeError, match="could not be resolved") as exc_info:+ provider.get_credentials()+ assert "projected-secret" not in str(exc_info.value)++class TestHelperFunctions:"""Tests for module-level helper functions."""@@ -535,6 +814,7 @@ class TestHelperFunctions:assert is_cloud_path("gs://bucket/key")assert is_cloud_path("abfs://[email protected]/key")assert is_cloud_path("abfss://[email protected]/key")+ assert is_cloud_path("oss://bucket/key")assert not is_cloud_path("/local/path")assert not is_cloud_path("./relative/path")@@ -558,6 +838,10 @@ class TestHelperFunctions:result = join_path("abfs://[email protected]/models/", "dir", "file.txt")assert result == "abfs://[email protected]/models/dir/file.txt"+ def test_join_path_oss(self) -> None:+ result = join_path("oss://bucket/models/", "dir", "file.txt")+ assert result == "oss://bucket/models/dir/file.txt"+def test_get_storage_backend(self) -> None:"""Backend selection works correctly."""assert isinstance(get_storage_backend("/local/path"), LocalBackend)@@ -565,6 +849,7 @@ class TestHelperFunctions:# so we just check we get the right typeassert isinstance(get_storage_backend("s3://bucket"), S3Backend)assert isinstance(get_storage_backend("gs://bucket"), GCSBackend)+ assert isinstance(get_storage_backend("oss://bucket"), OSSBackend)assert isinstance(get_storage_backend("abfs://[email protected]/models"), AzureBlobBackend)assert isinstance(get_storage_backend("abfss://[email protected]/models"), AzureBlobBackenddiff --git a/packages/sie_sdk/tests/test_storage_copy.py b/packages/sie_sdk/tests/test_storage_copy.pyindex c0f8978b5..f49874735 100644--- a/packages/sie_sdk/tests/test_storage_copy.py+++ b/packages/sie_sdk/tests/test_storage_copy.py@@ -8,7 +8,7 @@ from typing import Anyfrom azure.core.exceptions import HttpResponseErrorfrom botocore.exceptions import ClientErrorfrom google.api_core.exceptions import Forbidden-from sie_sdk.storage import AzureBlobBackend, GCSBackend, LocalBackend, S3Backend+from sie_sdk.storage import AzureBlobBackend, GCSBackend, LocalBackend, OSSBackend, S3Backendclass FakeS3Client:@@ -254,6 +254,62 @@ class TestAzureServerSideCopy:assert source_url.count("?") == 1+class TestOSSServerSideCopy:+ def test_cross_provider_is_unsupported(self) -> None:+ backend = OSSBackend()++ assert backend.try_server_side_copy("oss://source/models/a.bin", "s3://dest/models/a.bin") is False+ assert backend._buckets == {}++ def test_same_region_copy_uses_destination_bucket(self) -> None:+ backend = OSSBackend()+ destination = FakeOSSBucket()+ backend._buckets["dest-bucket"] = destination++ assert (+ backend.try_server_side_copy(+ "oss://source-bucket/models/a.bin",+ "oss://dest-bucket/other/a.bin",+ )+ is True+ )+ assert destination.copies == [("source-bucket", "models/a.bin", "other/a.bin")]++ def test_provider_error_falls_back_without_exposing_secrets(self, caplog: Any) -> None:+ class SecretProviderError(Exception):+ status = 403+ code = "AccessDenied"++ def __str__(self) -> str:+ return "Authorization=secret-token request-id=private"++ backend = OSSBackend()+ destination = FakeOSSBucket()+ destination.error = SecretProviderError()+ backend._buckets["dest-bucket"] = destination++ assert (+ backend.try_server_side_copy(+ "oss://source-bucket/models/a.bin",+ "oss://dest-bucket/other/a.bin",+ )+ is False+ )+ assert "secret-token" not in caplog.text+ assert "request-id" not in caplog.text+++class FakeOSSBucket:+ def __init__(self) -> None:+ self.copies: list[tuple[str, str, str]] = []+ self.error: Exception | None = None++ def copy_object(self, source_bucket: str, source_key: str, destination_key: str) -> None:+ if self.error is not None:+ raise self.error+ self.copies.append((source_bucket, source_key, destination_key))++class TestBaseBackendDefault:def test_local_backend_reports_unsupported(self, tmp_path: Any) -> None:backend = LocalBackend()diff --git a/packages/sie_sdk/tests/test_storage_write.py b/packages/sie_sdk/tests/test_storage_write.pyindex 73cf27149..071a47883 100644--- a/packages/sie_sdk/tests/test_storage_write.py+++ b/packages/sie_sdk/tests/test_storage_write.py@@ -4,7 +4,7 @@ from pathlib import Pathfrom unittest.mock import MagicMockimport pytest-from sie_sdk.storage import AzureBlobBackend, GCSBackend, LocalBackend, S3Backend, StorageBackend+from sie_sdk.storage import AzureBlobBackend, GCSBackend, LocalBackend, OSSBackend, S3Backend, StorageBackendclass TestLocalBackendWriteText:@@ -89,6 +89,75 @@ class TestDeleteFile:container.get_blob_client.assert_called_once_with("models/test__model.yaml")container.get_blob_client.return_value.delete_blob.assert_called_once_with()+ def test_oss_delete_targets_exact_object_and_is_idempotent(self) -> None:+ class MissingObjectError(Exception):+ status = 404+ code = "NoSuchKey"++ backend = OSSBackend()+ bucket = MagicMock()+ bucket.delete_object.side_effect = [None, MissingObjectError()]+ backend._buckets["catalog"] = bucket++ backend.delete_file("oss://catalog/models/test__model.yaml")+ backend.delete_file("oss://catalog/models/test__model.yaml")++ assert [call.args for call in bucket.delete_object.call_args_list] == [+ ("models/test__model.yaml",),+ ("models/test__model.yaml",),+ ]+++class TestOSSBackendWrites:+ def test_write_text_and_upload_file_target_exact_keys(self, tmp_path: Path) -> None:+ backend = OSSBackend()+ bucket = MagicMock()+ backend._buckets["catalog"] = bucket+ source = tmp_path / "model.bin"+ source.write_bytes(b"model")++ backend.write_text("oss://catalog/config/model.yaml", "sie_id: org/model\n")+ backend.upload_file(source, "oss://catalog/models/model.bin")++ bucket.put_object.assert_called_once_with("config/model.yaml", b"sie_id: org/model\n")+ bucket.put_object_from_file.assert_called_once_with("models/model.bin", str(source))++ def test_upload_directory_preserves_recursive_posix_layout(self, tmp_path: Path) -> None:+ source = tmp_path / "source"+ (source / "snapshots" / "abc").mkdir(parents=True)+ (source / "refs").mkdir()+ (source / "snapshots" / "abc" / "config.json").write_text("{}")+ (source / "refs" / "main").write_text("abc")+ backend = OSSBackend()+ bucket = MagicMock()+ backend._buckets["catalog"] = bucket++ assert backend.upload_directory(source, "oss://catalog/models/org-model/") == 2++ calls = {call.args for call in bucket.put_object_from_file.call_args_list}+ assert calls == {+ ("models/org-model/snapshots/abc/config.json", str(source / "snapshots" / "abc" / "config.json")),+ ("models/org-model/refs/main", str(source / "refs" / "main")),+ }++ def test_write_failure_does_not_expose_provider_body(self) -> None:+ class ProviderError(Exception):+ status = 500+ code = "InternalError"++ def __str__(self) -> str:+ return "Authorization=secret request-body=private"++ backend = OSSBackend()+ bucket = MagicMock()+ bucket.put_object.side_effect = ProviderError()+ backend._buckets["catalog"] = bucket++ with pytest.raises(RuntimeError) as exc_info:+ backend.write_text("oss://catalog/config/model.yaml", "private")++ assert str(exc_info.value) == "Alibaba OSS write failed (status=500, code=InternalError)"+class TestLocalBackendWriteTextIfMatch:"""Tests for LocalBackend.write_text_if_match() (atomic CAS)."""diff --git a/packages/sie_sdk/tests/test_wire_contract.py b/packages/sie_sdk/tests/test_wire_contract.pyindex 111d6ad68..c40c150d5 100644--- a/packages/sie_sdk/tests/test_wire_contract.py+++ b/packages/sie_sdk/tests/test_wire_contract.py@@ -1,4 +1,4 @@-"""The Python SDK's wire enums must match the shared golden fixtures.+"""The Python SDK's wire types must match the shared golden fixtures.Round-trips ``packages/wire-fixtures/model_state.json`` against the SDK's typed``ModelState`` so drift (for example a state added on one side only) fails in CI@@ -11,8 +11,15 @@ import jsonfrom pathlib import Pathfrom typing import get_args-from sie_sdk.client._shared import parse_extract_results-from sie_sdk.types import ModelState+from sie_sdk.client._shared import REQUEST_USAGE_HEADERS, parse_extract_results+from sie_sdk.types import (+ DECLARED_USAGE_FIELDS,+ SETTLED_CHARGE_FIELDS,+ TERMINAL_UNIT_FIELDS,+ ModelInfo,+ ModelState,+ RequestUsage,+)_FIXTURES = Path(__file__).parents[2] / "wire-fixtures"@@ -26,6 +33,60 @@ def test_model_state_matches_golden_fixture() -> None:assert set(get_args(ModelState)) == set(fixture["model_states"])+def test_request_usage_partition_matches_golden_fixture() -> None:+ """The `usage` partition is one contract declared in three codebases (#3063).++ The Cloud gateway asserts the same fixture over the fields it injects, so a+ gateway that starts publishing a third settled field turns this red until+ the SDK declares it — which is what stops a consumer from silently nulling+ its meter readings on the managed path.+ """+ fixture = _load("request_usage.json")+ assert set(fixture["terminal_unit_fields"]) == TERMINAL_UNIT_FIELDS+ assert set(fixture["settled_charge_fields"]) == SETTLED_CHARGE_FIELDS+ assert fixture["usage_container"] == "usage"+++def test_request_usage_partition_covers_the_whole_block() -> None:+ """No `usage` field may belong to neither half, or to both.++ A field in neither half is invisible to every consumer that partitions the+ block; a field in both would be metered AND treated as an annotation.+ """+ assert TERMINAL_UNIT_FIELDS.isdisjoint(SETTLED_CHARGE_FIELDS)+ assert DECLARED_USAGE_FIELDS == TERMINAL_UNIT_FIELDS | SETTLED_CHARGE_FIELDS+ assert set(RequestUsage.__annotations__) == DECLARED_USAGE_FIELDS+++def test_every_terminal_unit_has_a_meter_header() -> None:+ """The metered half is exactly what the gateway reports in headers."""+ assert set(REQUEST_USAGE_HEADERS) == TERMINAL_UNIT_FIELDS+++def test_model_info_declares_every_typed_wire_field() -> None:+ """``ModelInfo`` must declare each key the gateway emits.++ An emitted-but-undeclared field is invisible to type checkers, so callers+ can't reach it without a cast — the drift that left ``state``,+ ``last_error``, ``profiles`` and ``pending_generation`` unusable.+ """+ fixture = _load("model_info.json")+ assert set(ModelInfo.__annotations__) == set(fixture["typed"])+++def test_model_info_omits_deliberately_excluded_wire_fields() -> None:+ """OpenAI-compat keys must stay out of the SIE ``ModelInfo`` type.++ ``GET /v1/models/{model}`` merges ``id``/``object``/``created``/``owned_by``+ in for vanilla OpenAI clients. Declaring them would advertise envelope+ scaffolding as SIE model metadata; the fixture records the reason per key.+ """+ fixture = _load("model_info.json")+ excluded = set(fixture["excluded"])+ assert excluded, "fixture must record why each excluded key is excluded"+ assert set(ModelInfo.__annotations__).isdisjoint(excluded)++def test_extract_parser_preserves_data_and_item_error() -> None:[result] = parse_extract_results([diff --git a/packages/sie_server/CONTRIBUTING.md b/packages/sie_server/CONTRIBUTING.mdindex aa2045624..dc3c21807 100644--- a/packages/sie_server/CONTRIBUTING.md+++ b/packages/sie_server/CONTRIBUTING.md@@ -14,12 +14,12 @@ mise trust && mise install## Running Tests```bash-mise run test packages/sie_server+mise run test -- packages/sie_server```## Code Style-- Format with `mise run lint -f`+- Format with `mise run lint -- -f`- Type check with `mise run typecheck`## Pull Requestsdiff --git a/packages/sie_server/Dockerfile.cuda12 b/packages/sie_server/Dockerfile.cuda12index 01f17b490..a3eca8e8f 100644--- a/packages/sie_server/Dockerfile.cuda12+++ b/packages/sie_server/Dockerfile.cuda12@@ -165,7 +165,7 @@ RUN .venv/bin/python -m sie_server.cli resolve-deps \## Per-bundle CUDA wheel index. SGLang's sgl-kernel/flashinfer wheels live on the# docs.sglang.ai cu129 index (not PyPI), so the SGLang-family bundles add it.-# The gemma bundle (sglang 0.5.13 / torch 2.11 / cu130, CUDA 13) is built by the+# The sglang-cu130 bundle (sglang 0.5.13 / torch 2.11 / cu130, CUDA 13) is built by the# separate ``cuda13`` platform — see Dockerfile.cuda13 — not here.RUN --mount=type=cache,target=/root/.cache/pip \--mount=type=cache,target=/root/.cache/uv \@@ -216,9 +216,9 @@ ENV CUDA_HOME=/usr/local/cuda \LD_LIBRARY_PATH="/usr/local/cuda/lib64:$LD_LIBRARY_PATH"FROM runtime-sglang AS runtime-sglang-embeddingFROM runtime-sglang AS runtime-sglang-vision-extract-# NOTE: the gemma bundle (CUDA 13 / sglang 0.5.13 / torch 2.11 cu130) is built by+# NOTE: the sglang-cu130 bundle (CUDA 13 / sglang 0.5.13 / torch 2.11 cu130) is built by# the separate ``cuda13`` platform — packages/sie_server/Dockerfile.cuda13 — so-# this CUDA-12 image never produces a (mislabelled) CUDA-13 ``cuda12-gemma``+# this CUDA-12 image never produces a (mislabelled) CUDA-13 ``cuda12-sglang-cu130``# image. See #1415.FROM runtime-${BUNDLE} AS runtime@@ -294,7 +294,8 @@ COPY --link --from=base --chown=1000:1000 /app/bundles /app/bundles# A `.pth` file in the shared venv puts /app/bundle-libs at sys.path[0] at startup.COPY --link --from=builder --chown=1000:1000 /app/bundle-libs /app/bundle-libs-RUN mkdir -p /app/evals /app/.cache/huggingface && chown -R sie:sie /app/evals /app/.cache+RUN mkdir -p /app/evals /app/.cache/huggingface /app/.cache/sie-kernels \+ && chown -R sie:sie /app/evals /app/.cache# Declare the BUNDLE arg only here, where it is first used (LABEL + ENV),# so every RUN/COPY layer above is bundle-agnostic in its cache key and the@@ -309,6 +310,7 @@ ENV PATH="/app/.venv/bin:$PATH" \PYTHONUNBUFFERED=1 \PYTHONDONTWRITEBYTECODE=1 \HF_HOME=/app/.cache/huggingface \+ SIE_SGLANG_KERNEL_CACHE_ROOT=/app/.cache/sie-kernels \NVIDIA_VISIBLE_DEVICES=all \NVIDIA_DRIVER_CAPABILITIES=compute,utility \SIE_BUNDLE="${BUNDLE}"diff --git a/packages/sie_server/Dockerfile.cuda13 b/packages/sie_server/Dockerfile.cuda13index b359aff25..09f624ca9 100644--- a/packages/sie_server/Dockerfile.cuda13+++ b/packages/sie_server/Dockerfile.cuda13@@ -1,13 +1,13 @@# syntax=docker/dockerfile:1-# SIE Server - CUDA 13 Image (Gemma 4 / cu130 bundles)+# SIE Server - CUDA 13 Image (SGLang cu130 bundles)# Build from repo root:-# docker build -f packages/sie_server/Dockerfile.cuda13 --build-arg BUNDLE=gemma -t sie-server:cuda13-gemma .+# docker build -f packages/sie_server/Dockerfile.cuda13 --build-arg BUNDLE=sglang-cu130 -t sie-server:cuda13-sglang-cu130 .#-# WHY A SEPARATE PLATFORM: the gemma bundle needs sglang 0.5.13, which pins+# WHY A SEPARATE PLATFORM: the sglang-cu130 bundle needs sglang 0.5.13, which pins# torch==2.11.0 (cu130) + transformers 5.8.x and JIT-compiles cu130 kernels# (flashinfer / tvm_ffi) through nvcc on first decode — so it requires a CUDA 13# devel runtime. Keeping it here (platform ``cuda13``) instead of inside-# Dockerfile.cuda12 means a ``cuda13-gemma`` image is honestly labelled CUDA 13,+# Dockerfile.cuda12 means a ``cuda13-sglang-cu130`` image is honestly labelled CUDA 13,# not a CUDA-13 image hiding under a ``cuda12-*`` tag (see #1415).## STRUCTURE: mirrors Dockerfile.cuda12's deps→base→builder→runtime stages so the@@ -18,18 +18,18 @@# cu130 bundle), so there is no per-bundle runtime indirection.## DUAL-TORCH CARRY: the shared base venv still installs torch 2.9 (cu129) from-# pyproject, and the gemma bundle overlays torch 2.11 (cu130) into bundle-libs+# pyproject, and the sglang-cu130 bundle overlays torch 2.11 (cu130) into bundle-libs# (~+3 GB). Slimming torch out of sie-server core to drop the carry is a tracked# follow-up (#1415).-ARG BUNDLE=gemma+ARG BUNDLE=sglang-cu130ARG UV_VERSION=0.9.28-# Build the internal Rust extension from checked-in source; it is not published+# Build the native Rust extension from checked-in source; it is not published# to PyPI.FROM ghcr.io/pyo3/maturin:v1.13.3 AS audio-prep-builderWORKDIR /io-# The crate is a Cargo workspace member (#2339): its pins live in the root+# The crate is a Cargo workspace member: its pins live in the root# Cargo.lock, and loading the workspace needs every member's manifest+sources.COPY Cargo.toml Cargo.lock ./COPY packages/sie_audio_prep/ packages/sie_audio_prep/@@ -119,7 +119,7 @@ RUN .venv/bin/python -c "import sie_audio_prep, torch; print(torch.__version__)"# Register bundle-libs on sys.path via a .pth executed by site.py at startup.# sys.path.insert(0, ...) puts bundle-libs at position 0 so bundle-specific-# versions SHADOW the shared venv (the gemma cu130 torch/transformers/sglang+# versions SHADOW the shared venv (the cu130 torch/transformers/sglang# overlay). Content is identical for every bundle, so writing it here keeps the# shared venv layer byte-identical.RUN echo "import sys; sys.path.insert(0, '/app/bundle-libs')" \@@ -155,16 +155,16 @@ RUN .venv/bin/python -m sie_server.cli resolve-deps \&& cat /tmp/bundle-requirements.txt# cu130 bundle deps go into a separate site-packages tree (``bundle-libs``,-# prepended to sys.path via the .pth above). The gemma bundle needs torch 2.11+# prepended to sys.path via the .pth above). The sglang-cu130 bundle needs torch 2.11# from the cu130 PyTorch index, where the only ``2.11.0`` is the ``+cu130``# local-version wheel; pip's multi-index resolution does not reliably prefer it# over PyPI's default-CUDA build, so cuda13 bundles resolve with ``uv`` and# ``--index-strategy unsafe-best-match`` against the cu130 PyTorch + sglang# indexes (so torch 2.11 + sgl-kernel/flashinfer land for cu130). This uv +-# cu130-index resolution was validated by a manual Modal GPU session (sglang-# 0.5.13 / torch 2.11 / cu130 in a fresh venv).+# cu130-index resolution was validated with sglang 0.5.13, torch 2.11, and a+# cu130 runtime in a fresh GPU environment.#-# COVERAGE NOTE: the cuda13 image CI smoke (.github/workflows/gemma-image.yml)+# COVERAGE NOTE: the cuda13 image CI smoke (.github/workflows/sglang-cu130-image.yml)# builds this image and asserts on CPU that the bundle-libs cu130 overlay# SHADOWS the base venv (import torch -> 2.11+cu130, transformers 5.x). It does# NOT exercise GPU init: the cu12 base venv + cu130 bundle-libs both expose the@@ -268,7 +268,8 @@ COPY --link --from=base --chown=1000:1000 /app/bundles /app/bundles# Bundle-specific extras — last layer so shared layers above stay cached.COPY --link --from=builder --chown=1000:1000 /app/bundle-libs /app/bundle-libs-RUN mkdir -p /app/evals /app/.cache/huggingface && chown -R sie:sie /app/evals /app/.cache+RUN mkdir -p /app/evals /app/.cache/huggingface /app/.cache/sie-kernels \+ && chown -R sie:sie /app/evals /app/.cache# Declare BUNDLE only here (LABEL + ENV) so layers above are bundle-agnostic.ARG BUNDLE@@ -281,6 +282,7 @@ ENV PATH="/app/.venv/bin:$PATH" \PYTHONUNBUFFERED=1 \PYTHONDONTWRITEBYTECODE=1 \HF_HOME=/app/.cache/huggingface \+ SIE_SGLANG_KERNEL_CACHE_ROOT=/app/.cache/sie-kernels \NVIDIA_VISIBLE_DEVICES=all \NVIDIA_DRIVER_CAPABILITIES=compute,utility \SIE_BUNDLE="${BUNDLE}"diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex 452f157ed..5434a7b50 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -67,7 +67,7 @@ auto-retries; see `packages/sie_sdk/README.md` for client-side controls.| Env var | Default | Effect ||--|--|--|| `SIE_MAX_BATCH_REQUESTS` | `64` | Maximum number of items per batched inference call. |-| `SIE_MAX_BATCH_WAIT_MS` | `10` | How long the batch-former waits for additional items before dispatching. |+| `SIE_MAX_BATCH_WAIT_MS` | `15.0` | Initial value for the adaptive first-request batch timeout. At runtime the PI batching controller steers it between `SIE_ADAPTIVE_BATCHING__MIN_WAIT_MS` and `SIE_ADAPTIVE_BATCHING__MAX_WAIT_MS`, so it is a starting point rather than a fixed wait. || `SIE_MAX_CONCURRENT_REQUESTS` | `512` | Per-worker queue size; admission control returns `QUEUE_FULL` above this. || `SIE_MAX_LORAS_PER_MODEL` | `10` | Maximum concurrent LoRA adapters per base model. |diff --git a/packages/sie_server/bundles/default.yaml b/packages/sie_server/bundles/default.yamlindex 02701943f..52385ae7e 100644--- a/packages/sie_server/bundles/default.yaml+++ b/packages/sie_server/bundles/default.yaml@@ -59,8 +59,17 @@ deps:sentence-transformers: '>=5.0,<6'# bge_m3_flagFlagEmbedding: '>=1.3'- # grounding_dino- pillow: '>=11,<12'+ # grounding_dino. EXACT, not a range. `uv run --with-requirements` resolves the+ # overlay live from PyPI, and `--frozen`/`--no-sync` govern only the project+ # env, so any unbounded range here is re-resolved on every eval. The old+ # `>=11,<12` (94430893c) was accidentally stable because the 11.x line is+ # closed, but it contradicted sie-server's own `pillow>=12.2.0` since the+ # security bump (27fd2063d), so every default-bundle eval served the superseded+ # major. A bare `>=12.2.0` would fix that while making the pin float, which+ # trades a stale-but-stable closure for a moving one.+ # Pinned to the version the project lock holds, so overlay and lock agree.+ # Changing this re-measures 13 gating floors (naver/v-splade-quality, docling).+ pillow: '==12.3.0'# grounding_dinorequests: ''# gliner, gliner_bidiff --git a/packages/sie_server/bundles/gemma.yaml b/packages/sie_server/bundles/sglang-cu130.yamlsimilarity index 82%rename from packages/sie_server/bundles/gemma.yamlrename to packages/sie_server/bundles/sglang-cu130.yamlindex e7b495e26..0f4fa3937 100644--- a/packages/sie_server/bundles/gemma.yaml+++ b/packages/sie_server/bundles/sglang-cu130.yaml@@ -1,15 +1,14 @@-name: gemma+name: sglang-cu130priority: 20default: false# GPU platform this bundle targets — selects packages/sie_server/Dockerfile.cuda13-# and tags images ``cuda13-gemma`` (not ``cuda12-*``). Gemma 4 needs sglang+# and tags images ``cuda13-sglang-cu130`` (not ``cuda12-*``). Gemma 4 needs sglang# 0.5.13 / torch 2.11 cu130 on a CUDA 13 devel runtime (see below). Read by the-# docker build task (tools/mise_tasks/docker_task.py) and mirrored by the release-# matrix (.github/release-matrix.json). Bundles without this field default to-# ``cuda12``.+# image build. Bundles without this field default to ``cuda12``.platform: cuda13-# CUDA 13 SGLang worker image, introduced for Google Gemma 4 (see issue #1415)-# and reused by profiles that require newer generic engine features.+# General CUDA 13 / cu130 SGLang worker image, introduced for Google Gemma 4+# (see issue #1415) and shared by every profile that requires this newer engine+# and toolchain closure, including Qwen3.6 and Qwen3.8 native-window profiles.## VALIDATED on a Modal L4 (driver 580.95.05 / CUDA 13.0) on 2026-06-18:# google/gemma-4-E2B-it serves end-to-end on sglang 0.5.13 — the gemma4@@ -17,8 +16,8 @@ platform: cuda13# and /v1/chat/completions returns 200 (with --disable-cuda-graph, which the# model configs set via adapter_options.loadtime.disable_cuda_graph).#-# Kept SEPARATE from the `sglang` bundle so its Qwen3.x default/non-thinking-# profiles stay on sglang 0.5.10.post1 / torch 2.9.1. Qwen3.6-27B native-window+# Kept SEPARATE from the `sglang` bundle so its older Qwen3.x profiles stay on+# sglang 0.5.10.post1 / torch 2.9.1. Qwen3.6-27B native-window# variants opt into this image through the generic CUDA 13 adapter; their# thinking variants add the strict-thinking behavior. The rest of the Qwen# catalog remains untouched.@@ -32,7 +31,7 @@ platform: cuda13# this bundle's image carries torch 2.11 (cu130) on a CUDA 13 base — built by# the dedicated ``cuda13`` platform (packages/sie_server/Dockerfile.cuda13),# selected via the ``platform: cuda13`` field above. The shared base venv still-# ships torch 2.9.1, so the gemma image carries two torches (~+3 GB); slimming+# ships torch 2.9.1, so the cu130 image carries two torches (~+3 GB); slimming# torch out of sie-server core would remove that (tracked follow-up in #1415).## Distinct thin adapter modules scope routing here because bundle compatibility@@ -47,7 +46,8 @@ deps:# sglang 0.5.13 = the validated Gemma 4 engine (0.5.11 has the activation.cuh# JIT bug above). Verified transitive resolution on the Modal L4 cu130 image:# torch==2.11.0 (cu130), transformers==5.8.1, kernels==0.14.1,- # sglang-kernel + flashinfer-python (0.5.13 builds).+ # sgl-deep-gemm==0.1.2, sglang-kernel==0.4.3, and+ # flashinfer-python==0.6.12 (the exact SGLang 0.5.13 closure).# These resolve from the cu130 wheel indexes at build/serve time# (download.pytorch.org/whl/cu130 + https://docs.sglang.ai/whl/cu130/),# supplied by the build (Dockerfile.cuda13 / Modal image). torch,diff --git a/packages/sie_server/bundles/sglang-embedding.yaml b/packages/sie_server/bundles/sglang-embedding.yamlindex f89244a3b..312c90007 100644--- a/packages/sie_server/bundles/sglang-embedding.yaml+++ b/packages/sie_server/bundles/sglang-embedding.yaml@@ -20,9 +20,8 @@ deps:# a pre-release-only requirement. PyPI's ``flash-attn-4`` also publishes a# stable ``0.0.1`` placeholder, which disables uv's "allow pre-releases# when a package has nothing but pre-releases" rule, so a resolution that- # only names ``sglang`` is unsatisfiable (nightly quality-adapter 7B lanes- # died on this for weeks — #1684). Declaring the dep here with an explicit- # pre-release specifier re-enables pre-releases for exactly this package.+ # only names ``sglang`` is unsatisfiable. Declaring the dep here with an+ # explicit pre-release specifier re-enables pre-releases for exactly this package.# Runtime-inert for us: sglang's default attention backend is flashinfer;# fa4 only needs to be importable to satisfy the dependency.flash-attn-4: '==4.0.0b19'diff --git a/packages/sie_server/models/Alibaba-NLP__gte-multilingual-base.yaml b/packages/sie_server/models/Alibaba-NLP__gte-multilingual-base.yamlindex 9796c05f0..58e648f58 100644--- a/packages/sie_server/models/Alibaba-NLP__gte-multilingual-base.yaml+++ b/packages/sie_server/models/Alibaba-NLP__gte-multilingual-base.yaml@@ -1,5 +1,6 @@sie_id: Alibaba-NLP/gte-multilingual-basehf_id: Alibaba-NLP/gte-multilingual-base+hf_revision: 9bbca17d9273fd0d03d5725c7a4b0f6b45142062inputs:text: trueimage: falsediff --git a/packages/sie_server/models/BAAI__bge-reranker-large.yaml b/packages/sie_server/models/BAAI__bge-reranker-large.yamlindex eb43a879b..87b7ce480 100644--- a/packages/sie_server/models/BAAI__bge-reranker-large.yaml+++ b/packages/sie_server/models/BAAI__bge-reranker-large.yaml@@ -1,5 +1,6 @@sie_id: BAAI/bge-reranker-largehf_id: BAAI/bge-reranker-large+hf_revision: 55611d7bca2a7133960a6d3b71e083071bbfc312inputs:text: trueimage: falsediff --git a/packages/sie_server/models/EmergentMethods__gliner_large_news-v2.1.yaml b/packages/sie_server/models/EmergentMethods__gliner_large_news-v2.1.yamlindex ac6a450bd..b138cfa00 100644--- a/packages/sie_server/models/EmergentMethods__gliner_large_news-v2.1.yaml+++ b/packages/sie_server/models/EmergentMethods__gliner_large_news-v2.1.yaml@@ -1,5 +1,6 @@sie_id: EmergentMethods/gliner_large_news-v2.1hf_id: EmergentMethods/gliner_large_news-v2.1+hf_revision: 1af0cd2ce3b4a2c660849f6c3a10c7a7bac3c6c6inputs:text: trueimage: falsediff --git a/packages/sie_server/models/GritLM__GritLM-7B.yaml b/packages/sie_server/models/GritLM__GritLM-7B.yamlindex 262aa7cb6..482afaafb 100644--- a/packages/sie_server/models/GritLM__GritLM-7B.yaml+++ b/packages/sie_server/models/GritLM__GritLM-7B.yaml@@ -1,5 +1,6 @@sie_id: GritLM/GritLM-7Bhf_id: GritLM/GritLM-7B+hf_revision: cb7f7ffb99c0c24ca2c325d798d7ef5c455d5339inputs:text: trueimage: falsediff --git a/packages/sie_server/models/Ihor__gliner-biomed-large-v1.0.yaml b/packages/sie_server/models/Ihor__gliner-biomed-large-v1.0.yamlindex 465e8aa48..7e389a441 100644--- a/packages/sie_server/models/Ihor__gliner-biomed-large-v1.0.yaml+++ b/packages/sie_server/models/Ihor__gliner-biomed-large-v1.0.yaml@@ -1,5 +1,6 @@sie_id: Ihor/gliner-biomed-large-v1.0hf_id: Ihor/gliner-biomed-large-v1.0+hf_revision: f79771210ab2111a2081ef31620fdb7342f602e9inputs:text: trueimage: falsediff --git a/packages/sie_server/models/Linq-AI-Research__Linq-Embed-Mistral.yaml b/packages/sie_server/models/Linq-AI-Research__Linq-Embed-Mistral.yamlindex 8614d2e48..05552711a 100644--- a/packages/sie_server/models/Linq-AI-Research__Linq-Embed-Mistral.yaml+++ b/packages/sie_server/models/Linq-AI-Research__Linq-Embed-Mistral.yaml@@ -1,5 +1,6 @@sie_id: Linq-AI-Research/Linq-Embed-Mistralhf_id: Linq-AI-Research/Linq-Embed-Mistral+hf_revision: 0c1a0b0589177079acc552433cad51d7c9132379inputs:text: trueimage: 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.yamlindex c1c41cf35..8866d366e 100644--- a/packages/sie_server/models/MoritzLaurer__ModernBERT-base-zeroshot-v2.0.yaml+++ b/packages/sie_server/models/MoritzLaurer__ModernBERT-base-zeroshot-v2.0.yaml@@ -1,5 +1,6 @@sie_id: MoritzLaurer/ModernBERT-base-zeroshot-v2.0hf_id: MoritzLaurer/ModernBERT-base-zeroshot-v2.0+hf_revision: d421c4545a438fd006fb43f8b981c5d908faa1e1inputs:text: trueimage: falsediff --git a/packages/sie_server/models/MoritzLaurer__deberta-v3-base-zeroshot-v2.0.yaml b/packages/sie_server/models/MoritzLaurer__deberta-v3-base-zeroshot-v2.0.yamlindex 6e7b04960..565739b39 100644--- a/packages/sie_server/models/MoritzLaurer__deberta-v3-base-zeroshot-v2.0.yaml+++ b/packages/sie_server/models/MoritzLaurer__deberta-v3-base-zeroshot-v2.0.yaml@@ -1,5 +1,6 @@sie_id: MoritzLaurer/deberta-v3-base-zeroshot-v2.0hf_id: MoritzLaurer/deberta-v3-base-zeroshot-v2.0+hf_revision: 8e7e5af5983a0ddb1a5b45a38b129ab69e2258e8inputs:text: trueimage: falsediff --git a/packages/sie_server/models/MoritzLaurer__deberta-v3-large-zeroshot-v2.0.yaml b/packages/sie_server/models/MoritzLaurer__deberta-v3-large-zeroshot-v2.0.yamlindex abaffb44e..bc0883e1f 100644--- a/packages/sie_server/models/MoritzLaurer__deberta-v3-large-zeroshot-v2.0.yaml+++ b/packages/sie_server/models/MoritzLaurer__deberta-v3-large-zeroshot-v2.0.yaml@@ -1,5 +1,6 @@sie_id: MoritzLaurer/deberta-v3-large-zeroshot-v2.0hf_id: MoritzLaurer/deberta-v3-large-zeroshot-v2.0+hf_revision: cf44676c28ba7312e5c5f8f8d2c22b3e0c9cdae2inputs:text: trueimage: falsediff --git a/packages/sie_server/models/NovaSearch__stella_en_400M_v5.yaml b/packages/sie_server/models/NovaSearch__stella_en_400M_v5.yamlindex 9e05ca332..ecfa0f6df 100644--- a/packages/sie_server/models/NovaSearch__stella_en_400M_v5.yaml+++ b/packages/sie_server/models/NovaSearch__stella_en_400M_v5.yaml@@ -1,5 +1,6 @@sie_id: NovaSearch/stella_en_400M_v5hf_id: NovaSearch/stella_en_400M_v5+hf_revision: ffeb2b7ee715c226d4ffe5e4619f7dbb48624c20inputs:text: trueimage: falsediff --git a/packages/sie_server/models/PaddlePaddle__PaddleOCR-VL-1.6.yaml b/packages/sie_server/models/PaddlePaddle__PaddleOCR-VL-1.6.yamldeleted file mode 100644index c4a1dd3ea..000000000--- a/packages/sie_server/models/PaddlePaddle__PaddleOCR-VL-1.6.yaml+++ /dev/null@@ -1,54 +0,0 @@-sie_id: PaddlePaddle/PaddleOCR-VL-1.6-hf_id: PaddlePaddle/PaddleOCR-VL-1.6-hf_revision: cdc88f5feff0e4079e75863205053a68358e52f7-inputs:- text: false- image: true- audio: false- video: false-tasks:- encode: null- score: null- extract: {}-max_sequence_length: 16384-profiles:- transformers:- max_batch_tokens: 16384- compute_precision: bfloat16- adapter_path: sie_server.adapters.paddleocr_vl:PaddleOCRVLAdapter- adapter_options:- loadtime:- trust_remote_code: true- default_task: ocr- runtime:- task: ocr- max_new_tokens: 4096- num_beams: 1- default:- max_batch_tokens: 16384- compute_precision: bfloat16- adapter_path: sie_server.adapters.sglang_vision_extract.adapter:SGLangVisionExtractAdapter- adapter_options:- loadtime:- trust_remote_code: true- mem_fraction_static: 0.85- served_model_name: PaddlePaddle/PaddleOCR-VL-1.6- max_concurrent_requests: 16- processor_use_fast: false- extra_launch_args:- - --disable-fast-image-processor- default_task: ocr- task_prompts:- ocr: "OCR:"- table: "Table Recognition:"- formula: "Formula Recognition:"- chart: "Chart Recognition:"- spotting: "Spotting:"- seal: "Seal Recognition:"- task_labels:- spotting: spotting- seal: seal- runtime:- task: ocr- max_new_tokens: 4096- num_beams: 1diff --git a/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml b/packages/sie_server/models/Qwen__Qwen3-0.6B.yamlindex 93fc0b994..fdff9c12a 100644--- a/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml@@ -15,11 +15,9 @@ tasks:# to fit the full generation benchmark pack (casehold prompts reach ~1.8k# tokens, gpqa ~1.3k) so the model is comparable to the rest of the fleet on# every task, while KV stays trivial at this size (112 KB/token → 4096 ≈- # 0.46 GB). The validation/co-residency harness, which packs two SGLang- # instances onto a single 22 GiB L4, does NOT depend on this default — it- # passes an explicit ``--max-seq-length``/``--context-length`` (see- # tools/bench_generation_matrix.py + run_generation_smoke.py) and caps itself- # to 1024 for that case.+ # 0.46 GB). A deployment packing two SGLang instances onto one 22 GiB L4+ # does NOT depend on this default: it passes an explicit+ # ``--max-seq-length``/``--context-length`` and caps itself to 1024.## ``context_length``, ``max_sequence_length``, and ``max_batch_tokens`` are# three independent knobs (per-request context, SGLang --context-length,@@ -39,8 +37,8 @@ max_sequence_length: 4096# KV-cache memory math (Qwen3-0.6B, bf16):# layers=28, kv_heads=8, head_dim=128, bytes_per_elem=2# kv_bytes_per_token = 2 × 28 × 8 × 128 × 2 = 114,688 B ≈ 112 KB-# At ctx=4096 a single request's KV is ~0.46 GB — negligible. The co-residency-# harness still caps context explicitly when it has to share a card.+# At ctx=4096 a single request's KV is ~0.46 GB — negligible. Co-resident+# deployments can still cap context explicitly when sharing a card.profiles:default:max_batch_tokens: 4096@@ -49,9 +47,8 @@ profiles:kv_budget_tokens: 8192adapter_options:loadtime:- # 0.8 leaves headroom on a 22 GiB L4 for a second SGLang instance- # (the validation harness co-residents worker + baseline). If the- # 0.6B is the only model on the card, 0.9 is fine.+ # 0.8 leaves headroom on a 22 GiB L4 for a second SGLang instance. If+ # the 0.6B is the only model on the card, 0.9 is fine.mem_fraction_static: 0.8served_model_name: Qwen/Qwen3-0.6B# Modal sandbox lacks flashinfer's JIT prerequisites; switch backends.diff --git a/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml b/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yamlindex 5f11e3fe8..26fb45e3e 100644--- a/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml+++ b/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml@@ -38,8 +38,7 @@ tasks:# them on ``delta.tool_calls`` for SSE and on# ``message.tool_calls`` for non-streaming requests.tools: true- # Validated for code generation — MEASURED HumanEval 0.866 / MBPP 0.74 on- # Modal A100 (see benchmarks/generation/.../code/measured_baseline.json).+ # Validated for code generation before enabling the code alias.# Backs the model="code" alias. Informational (not request-gated).code: true# Backs the model="sql" alias. NOTE: this profile runs the outlinesdiff --git a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml b/packages/sie_server/models/Qwen__Qwen3.5-4B.yamlindex b9d4890c1..57e3513c0 100644--- a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml@@ -31,8 +31,7 @@ tasks:# NOTE: scoped to what the production backend (``outlines``, set# per-profile under ``adapter_options.loadtime``) actually supports# on SGLang. SGLang's outlines_backend explicitly skips ebnf with- # ``Skip unsupported key_type='ebnf'`` — confirmed on A100 smoke- # 2026-05-26 (see ``benchmarks/generation/qwen35-outlines-smoke/``).+ # ``Skip unsupported key_type='ebnf'`` — confirmed by a compatibility smoke.# If an operator switches a Qwen3.5 profile to ``grammar_backend:# xgrammar`` they should re-add ``"ebnf"`` here — xgrammar smoke on# the same hardware passed all three modes (regex/json_schema/ebnf).@@ -109,9 +108,8 @@ max_sequence_length: 8192# effective_max_running_requests_per_dp = 48## ``kv_budget_tokens`` is sized at ``token_capacity / 4``, matching the-# pattern set by Qwen3-4B-Instruct-2507. Re-calibrate via the smoke-# tool ``tools/smoke_qwen35_4b.py`` if SGLang version or-# ``mem_fraction_static`` changes.+# pattern set by Qwen3-4B-Instruct-2507. Re-calibrate with an SGLang capacity+# probe if its version or ``mem_fraction_static`` changes.profiles:# The bare model is the measured production A100-40GB shape. The# ``a100-40gb`` alias below preserves the resolved profile identity used by@@ -266,8 +264,8 @@ profiles:max_batch_tokens: 65536compute_precision: bfloat16adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter- # Analytical estimate — re-calibrate via ``tools/smoke_qwen35_4b.py``- # once H100 access is set up. Scales ~2× off the A100-40GB number+ # Analytical estimate — re-calibrate with an SGLang capacity probe once+ # H100 access is set up. Scales ~2× off the A100-40GB number# (80 GB / 40 GB), so ~420k tokens at context=32768.kv_budget_tokens: 421888adapter_options:diff --git a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml b/packages/sie_server/models/Qwen__Qwen3.6-27B.yamlindex a4d885af5..71063a9d1 100644--- a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml@@ -31,19 +31,18 @@ tasks:grammar: ["json_schema", "regex"]streaming: truetools: true- # Validated on code + text-to-SQL — MEASURED on Modal H100 (bf16 no-spec,- # greedy+min_tokens=10; accuracy is GPU-invariant + FP8≈BF16 per ADR- # 0001): HumanEval 0.933, MBPP 0.81 (beats the 4B code default 0.866/0.74),- # Spider exec-acc 0.693. See code_sql_tools/measured_baseline.json.+ # Validated on code + text-to-SQL — measured on H100 (bf16 no-spec,+ # greedy+min_tokens=10). BF16 benchmark: HumanEval 0.933, MBPP 0.81+ # (beats the 4B code default 0.866/0.74), Spider exec-acc 0.693.# Informational (not request-gated); surfaces the high-end code/SQL option.code: true# CAVEAT: this flag is precision-agnostic, but FP8 weight quant regresses# SQL ~13pts (Spider 0.71 BF16 -> 0.58 FP8, same-subset control; see the- # ADR + baseline). Code/tools/MC are FP8-safe. The RTX FP8 profile below is+ # same-subset measurements). Code/tools/MC are FP8-safe. The RTX FP8 profile below is# for code/tools/general. Route SQL-critical traffic to the BF16 profile# or a BF16 bundle-qualified alias, e.g.# SIE_GATEWAY_MODEL_ALIASES={"sql":"<bf16-bundle>:/Qwen/Qwen3.6-27B"}- # (gateway resolve_model_spec_with_aliases; see ADR 0001).+ # (gateway resolve_model_spec_with_aliases).sql: true# Qwen3.6 emits ``<think>...</think>`` reasoning by default. We# disable it for the OpenAI-compat path so visible output is the@@ -217,8 +216,8 @@ profiles:# over H100 plus the FP8 weight saving is what makes 3/4 fit here.## ACCURACY CONTRACT: FP8 is lossy. This profile is validated to within the- # Wilson 95% CI of the *BF16* baseline on all four generation tasks (see- # docs/adr/0001). If FP8 misses parity after bounded tuning, fall back to+ # Wilson 95% CI of the *BF16* baseline on all four generation tasks. If FP8+ # misses parity after bounded tuning, fall back to# BF16 + NEXTN 3/4 (drop the ``--quantization fp8`` pair below; the 96 GB# still fits the 3/4 draft in BF16). KV cache stays BF16 here — add# ``--kv-cache-dtype fp8_e4m3`` only if memory/throughput needs it ANDdiff --git a/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml b/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yamlnew file mode 100644index 000000000..9f46fa3cf--- /dev/null+++ b/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml@@ -0,0 +1,360 @@+sie_id: Qwen/Qwen3.8-27B-FP8+hf_id: Qwen/Qwen3.8-27B-FP8+hf_revision: 017b9c7af6b5689d5dd426a76e0bc077eb5ca20a+# Official first-party blockwise FP8 checkpoint. The pinned config declares+# Qwen3_5ForConditionalGeneration, 64 layers in the same 48 GDN + 16 full-+# attention layout as Qwen3.6-27B, and a native 262,144-token window. Its+# quantization_config is dynamic FP8 with 128x128 weight blocks, so SGLang+# detects the checkpoint quantization directly; no online --quantization flag+# belongs in these profiles.+inputs:+ text: true+ image: true+ audio: false+ # Qwen documents native video understanding, but video is not yet wired+ # through the SIE generation request surface.+ video: false+tasks:+ generate:+ # Keep the bare route conservative. Native context is exposed only through+ # exact-hardware profiles whose admission and launch shapes are smoke-tested.+ context_length: 8192+ max_output_tokens: 4096+ capabilities:+ grammar: ["json_schema", "regex"]+ streaming: true+ tools: true+ # Qwen3.8 defaults to thinking. The initial SIE contract is answer-only;+ # reasoning profiles can be added after their parser/output behavior is+ # tested independently.+ chat_template_kwargs:+ enable_thinking: false+ prewarm_grammars:+ - name: yes_no+ kind: regex+ value: "(yes|no)"+ - name: short_answer+ kind: json_schema+ value:+ type: object+ properties:+ answer:+ type: string+ required: [answer]+max_sequence_length: 8192+profiles:+ # Correctness-first bare route: official FP8 weights, BF16 KV, FP32 GDN+ # state, no speculation, CUDA graphs disabled, and an 8K admission window.+ default:+ max_batch_tokens: 16384+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangCuda13Adapter+ kv_budget_tokens: 8192+ adapter_options:+ loadtime:+ mem_fraction_static: 0.85+ served_model_name: Qwen/Qwen3.8-27B-FP8+ disable_cuda_graph: true+ attention_backend: flashinfer+ grammar_backend: xgrammar+ tool_call_parser: qwen3_coder+ speculative:+ enabled: false+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--kv-cache-dtype"+ - "bfloat16"+ - "--mamba-ssm-dtype"+ - "float32"+ runtime:+ first_chunk_timeout_s: 90+ inter_chunk_timeout_s: 15+ overall_timeout_s: 600+ # Official Qwen3.8 non-thinking sampling recipe.+ default_sampling:+ temperature: 0.7+ top_p: 0.8+ top_k: 20+ presence_penalty: 1.5+ stop_tokens:+ - "<|im_end|>"++ # H100-80GB: one native-window admission with in-checkpoint MTP. FA3 plus+ # BF16 GDN state is the measured SM90 batch-one winner. Profile-scoped+ # DeepGEMM fast warmup covers every decode M through 1024 and samples the+ # prefill range through the explicit 32K boundary. The matching no-spec+ # profile is the grammar-safe fallback. Every native-window pair uses the+ # synchronous scheduler: pinned SGLang speculative V2 has a request-dependent+ # overlap-path crash on hybrid Mamba, while these profiles admit only one+ # running request and have no useful batch to overlap.+ h100-256k:+ max_output_tokens: 32768+ max_batch_tokens: 262144+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangCuda13Adapter+ grammar_profile: h100-256k-no-spec+ kv_budget_tokens: 262144+ adapter_options:+ loadtime:+ max_seq_length: 262144+ mem_fraction_static: 0.85+ served_model_name: Qwen/Qwen3.8-27B-FP8+ attention_backend: fa3+ grammar_backend: xgrammar+ tool_call_parser: qwen3_coder+ extra_env:+ SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"+ speculative:+ enabled: true+ algorithm: eagle+ num_steps: 3+ eagle_topk: 1+ num_draft_tokens: 4+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--kv-cache-dtype"+ - "bfloat16"+ - "--mamba-ssm-dtype"+ - "bfloat16"+ - "--mamba-scheduler-strategy"+ - "extra_buffer"+ - "--disable-overlap-schedule"+ - "--page-size"+ - "64"+ - "--chunked-prefill-size"+ - "32768"+ - "--max-prefill-tokens"+ - "32768"+ - "--max-running-requests"+ - "1"+ - "--cuda-graph-max-bs"+ - "1"+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 0.7+ top_p: 0.8+ top_k: 20+ presence_penalty: 1.5+ stop_tokens:+ - "<|im_end|>"+ h100-256k-no-spec:+ extends: h100-256k+ adapter_options:+ loadtime:+ max_seq_length: 262144+ mem_fraction_static: 0.85+ served_model_name: Qwen/Qwen3.8-27B-FP8+ attention_backend: fa3+ grammar_backend: xgrammar+ tool_call_parser: qwen3_coder+ extra_env:+ SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"+ speculative:+ enabled: false+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--kv-cache-dtype"+ - "bfloat16"+ - "--mamba-ssm-dtype"+ - "bfloat16"+ - "--mamba-scheduler-strategy"+ - "extra_buffer"+ - "--disable-overlap-schedule"+ - "--page-size"+ - "64"+ - "--chunked-prefill-size"+ - "32768"+ - "--max-prefill-tokens"+ - "32768"+ - "--max-running-requests"+ - "1"+ - "--cuda-graph-max-bs"+ - "1"++ # H200-141GB: deliberately retain the measured H100 SM90 recipe and+ # one-admission launch shape; the larger card provides more memory headroom+ # without a second tuning surface.+ h200-256k:+ max_output_tokens: 32768+ max_batch_tokens: 262144+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangCuda13Adapter+ grammar_profile: h200-256k-no-spec+ kv_budget_tokens: 262144+ adapter_options:+ loadtime:+ max_seq_length: 262144+ mem_fraction_static: 0.85+ served_model_name: Qwen/Qwen3.8-27B-FP8+ attention_backend: fa3+ grammar_backend: xgrammar+ tool_call_parser: qwen3_coder+ extra_env:+ SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"+ speculative:+ enabled: true+ algorithm: eagle+ num_steps: 3+ eagle_topk: 1+ num_draft_tokens: 4+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--kv-cache-dtype"+ - "bfloat16"+ - "--mamba-ssm-dtype"+ - "bfloat16"+ - "--mamba-scheduler-strategy"+ - "extra_buffer"+ - "--disable-overlap-schedule"+ - "--page-size"+ - "64"+ - "--chunked-prefill-size"+ - "32768"+ - "--max-prefill-tokens"+ - "32768"+ - "--max-running-requests"+ - "1"+ - "--cuda-graph-max-bs"+ - "1"+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 0.7+ top_p: 0.8+ top_k: 20+ presence_penalty: 1.5+ stop_tokens:+ - "<|im_end|>"+ h200-256k-no-spec:+ extends: h200-256k+ adapter_options:+ loadtime:+ max_seq_length: 262144+ mem_fraction_static: 0.85+ served_model_name: Qwen/Qwen3.8-27B-FP8+ attention_backend: fa3+ grammar_backend: xgrammar+ tool_call_parser: qwen3_coder+ extra_env:+ SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"+ speculative:+ enabled: false+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--kv-cache-dtype"+ - "bfloat16"+ - "--mamba-ssm-dtype"+ - "bfloat16"+ - "--mamba-scheduler-strategy"+ - "extra_buffer"+ - "--disable-overlap-schedule"+ - "--page-size"+ - "64"+ - "--chunked-prefill-size"+ - "32768"+ - "--max-prefill-tokens"+ - "32768"+ - "--max-running-requests"+ - "1"+ - "--cuda-graph-max-bs"+ - "1"++ # RTX PRO 6000 96GB (SM120): retain FlashInfer and 2K prefill chunks from the+ # official Blackwell recipe while sharing the measured BF16 GDN state and+ # profile-scoped DeepGEMM fast warmup. Both RTX profiles deliberately leave+ # --max-prefill-tokens at SGLang's pinned default; only the chunk granularity+ # is overridden here, and the Stage-5 full-window smoke guards that pairing.+ rtx-pro-6000-256k:+ max_output_tokens: 32768+ max_batch_tokens: 262144+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangCuda13Adapter+ grammar_profile: rtx-pro-6000-256k-no-spec+ kv_budget_tokens: 262144+ adapter_options:+ loadtime:+ max_seq_length: 262144+ mem_fraction_static: 0.85+ served_model_name: Qwen/Qwen3.8-27B-FP8+ attention_backend: flashinfer+ grammar_backend: xgrammar+ tool_call_parser: qwen3_coder+ extra_env:+ SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"+ speculative:+ enabled: true+ algorithm: eagle+ num_steps: 3+ eagle_topk: 1+ num_draft_tokens: 4+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--kv-cache-dtype"+ - "bfloat16"+ - "--mamba-ssm-dtype"+ - "bfloat16"+ - "--mamba-scheduler-strategy"+ - "extra_buffer"+ - "--disable-overlap-schedule"+ - "--page-size"+ - "64"+ - "--chunked-prefill-size"+ - "2048"+ - "--max-running-requests"+ - "1"+ - "--cuda-graph-max-bs"+ - "1"+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 0.7+ top_p: 0.8+ top_k: 20+ presence_penalty: 1.5+ stop_tokens:+ - "<|im_end|>"+ rtx-pro-6000-256k-no-spec:+ extends: rtx-pro-6000-256k+ adapter_options:+ loadtime:+ max_seq_length: 262144+ mem_fraction_static: 0.85+ served_model_name: Qwen/Qwen3.8-27B-FP8+ attention_backend: flashinfer+ grammar_backend: xgrammar+ tool_call_parser: qwen3_coder+ extra_env:+ SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"+ speculative:+ enabled: false+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--kv-cache-dtype"+ - "bfloat16"+ - "--mamba-ssm-dtype"+ - "bfloat16"+ - "--mamba-scheduler-strategy"+ - "extra_buffer"+ - "--disable-overlap-schedule"+ - "--page-size"+ - "64"+ - "--chunked-prefill-size"+ - "2048"+ - "--max-running-requests"+ - "1"+ - "--cuda-graph-max-bs"+ - "1"diff --git a/packages/sie_server/models/Salesforce__SFR-Embedding-2_R.yaml b/packages/sie_server/models/Salesforce__SFR-Embedding-2_R.yamlindex 379d57247..c0c801101 100644--- a/packages/sie_server/models/Salesforce__SFR-Embedding-2_R.yaml+++ b/packages/sie_server/models/Salesforce__SFR-Embedding-2_R.yaml@@ -1,5 +1,6 @@sie_id: Salesforce/SFR-Embedding-2_Rhf_id: Salesforce/SFR-Embedding-2_R+hf_revision: f62d15f411ca97b66acc0f34da2a65f3420b55b0inputs:text: trueimage: falsediff --git a/packages/sie_server/models/Salesforce__SFR-Embedding-Mistral.yaml b/packages/sie_server/models/Salesforce__SFR-Embedding-Mistral.yamlindex 8f9b74c4d..03ab93570 100644--- a/packages/sie_server/models/Salesforce__SFR-Embedding-Mistral.yaml+++ b/packages/sie_server/models/Salesforce__SFR-Embedding-Mistral.yaml@@ -1,5 +1,6 @@sie_id: Salesforce/SFR-Embedding-Mistralhf_id: Salesforce/SFR-Embedding-Mistral+hf_revision: 33a60fe7b5e00b9414981280c571e8a4f9f42f1binputs:text: trueimage: falsediff --git a/packages/sie_server/models/cross-encoder__ms-marco-MiniLM-L-12-v2.yaml b/packages/sie_server/models/cross-encoder__ms-marco-MiniLM-L-12-v2.yamlindex 9fc9fe310..f9806906d 100644--- a/packages/sie_server/models/cross-encoder__ms-marco-MiniLM-L-12-v2.yaml+++ b/packages/sie_server/models/cross-encoder__ms-marco-MiniLM-L-12-v2.yaml@@ -1,5 +1,6 @@sie_id: cross-encoder/ms-marco-MiniLM-L-12-v2hf_id: cross-encoder/ms-marco-MiniLM-L-12-v2+hf_revision: 7b0235231ca2674cb8ca8f022859a6eba2b1c968inputs:text: trueimage: falsediff --git a/packages/sie_server/models/cross-encoder__nli-deberta-v3-base.yaml b/packages/sie_server/models/cross-encoder__nli-deberta-v3-base.yamlindex ef07511d5..55a1e6d80 100644--- a/packages/sie_server/models/cross-encoder__nli-deberta-v3-base.yaml+++ b/packages/sie_server/models/cross-encoder__nli-deberta-v3-base.yaml@@ -1,5 +1,6 @@sie_id: cross-encoder/nli-deberta-v3-basehf_id: cross-encoder/nli-deberta-v3-base+hf_revision: 6c749ce3425cd33b46d187e45b92bbf96ee12ec7inputs:text: trueimage: falsediff --git a/packages/sie_server/models/defog__sqlcoder-7b-2.yaml b/packages/sie_server/models/defog__sqlcoder-7b-2.yamlindex 40e856487..dc7c9fc2e 100644--- a/packages/sie_server/models/defog__sqlcoder-7b-2.yaml+++ b/packages/sie_server/models/defog__sqlcoder-7b-2.yaml@@ -23,8 +23,7 @@ hf_id: defog/sqlcoder-7b-2# still LOSES to general Qwen3-4B-Instruct at 0.70 on Spider exec-acc, so the# model="sql" alias STAYS on Qwen3-4B-Instruct. (The card recommends# num_beams=4; SGLang serves greedy, so 0.467 is a lower bound, but beam-# search is a serving change and would still likely trail.) See-# benchmarks/generation/Qwen__Qwen3-4B-Instruct-2507/sql/measured_baseline.json.+# search is a serving change and would still likely trail.)inputs:text: trueimage: falsediff --git a/packages/sie_server/models/facebook__bart-large-mnli.yaml b/packages/sie_server/models/facebook__bart-large-mnli.yamlindex 577779294..fdd17f637 100644--- a/packages/sie_server/models/facebook__bart-large-mnli.yaml+++ b/packages/sie_server/models/facebook__bart-large-mnli.yaml@@ -1,5 +1,6 @@sie_id: facebook/bart-large-mnlihf_id: facebook/bart-large-mnli+hf_revision: d7645e127eaf1aefc7862fd59a17a5aa8558b8ceinputs:text: trueimage: falsediff --git a/packages/sie_server/models/gliner-community__gliner_large-v2.5.yaml b/packages/sie_server/models/gliner-community__gliner_large-v2.5.yamlindex 2a5750fb4..35f5b35f5 100644--- a/packages/sie_server/models/gliner-community__gliner_large-v2.5.yaml+++ b/packages/sie_server/models/gliner-community__gliner_large-v2.5.yaml@@ -1,5 +1,6 @@sie_id: gliner-community/gliner_large-v2.5hf_id: gliner-community/gliner_large-v2.5+hf_revision: 3d6d1760be1c591069f85f207fced9214df8b15finputs:text: trueimage: falsediff --git a/packages/sie_server/models/gliner-community__gliner_medium-v2.5.yaml b/packages/sie_server/models/gliner-community__gliner_medium-v2.5.yamlindex 1b75de6c5..ed0471bdf 100644--- a/packages/sie_server/models/gliner-community__gliner_medium-v2.5.yaml+++ b/packages/sie_server/models/gliner-community__gliner_medium-v2.5.yaml@@ -1,5 +1,6 @@sie_id: gliner-community/gliner_medium-v2.5hf_id: gliner-community/gliner_medium-v2.5+hf_revision: 88c3b98b57ad5e7d66fb209ed61c53f4b1fd05dainputs:text: trueimage: falsediff --git a/packages/sie_server/models/google__gemma-4-26B-A4B-it.yaml b/packages/sie_server/models/google__gemma-4-26B-A4B-it.yamlindex b2f377f04..8340c9abe 100644--- a/packages/sie_server/models/google__gemma-4-26B-A4B-it.yaml+++ b/packages/sie_server/models/google__gemma-4-26B-A4B-it.yaml@@ -2,8 +2,8 @@ sie_id: google/gemma-4-26B-A4B-ithf_id: google/gemma-4-26B-A4B-it# ── Engine (see issue #1415) ──#-# Served by the dedicated ``gemma`` bundle (packages/sie_server/bundles/-# gemma.yaml): sglang 0.5.13 + torch 2.11 (cu130) on a CUDA 13 base. 0.5.13 is+# Served by the shared ``sglang-cu130`` bundle (packages/sie_server/bundles/+# sglang-cu130.yaml): sglang 0.5.13 + torch 2.11 (cu130) on a CUDA 13 base. 0.5.13 is# the validated engine; 0.5.11 (first release with Gemma 4) has a JIT-kernel# compile bug. Smoke-validated on a Modal H100-80GB 2026-06-19: the ``default``# profile shape (BF16, mem_fraction 0.90, --disable-cuda-graph) loads the MoEdiff --git a/packages/sie_server/models/google__gemma-4-31B-it.yaml b/packages/sie_server/models/google__gemma-4-31B-it.yamlindex 7ce80bcc7..406cace8f 100644--- a/packages/sie_server/models/google__gemma-4-31B-it.yaml+++ b/packages/sie_server/models/google__gemma-4-31B-it.yaml@@ -1,7 +1,7 @@sie_id: google/gemma-4-31B-ithf_id: google/gemma-4-31B-ithf_revision: 842da3794eaa0b77d5f08bae87a17459d91ff475-# Gemma 4 dense 31B is served by the dedicated ``gemma`` bundle+# Gemma 4 dense 31B is served by the shared ``sglang-cu130`` bundle# (SGLang 0.5.13 / transformers 5.8 / CUDA 13). The BF16 checkpoint is# 58.25 GiB, so the requested single-H100-80GB shape uses SGLang online FP8# weight quantization while retaining the checkpoint's bfloat16 compute dtype.diff --git a/packages/sie_server/models/google__gemma-4-E2B-it.yaml b/packages/sie_server/models/google__gemma-4-E2B-it.yamlindex f90538f17..895870fe7 100644--- a/packages/sie_server/models/google__gemma-4-E2B-it.yaml+++ b/packages/sie_server/models/google__gemma-4-E2B-it.yaml@@ -2,8 +2,8 @@ sie_id: google/gemma-4-E2B-ithf_id: google/gemma-4-E2B-it# ── Engine (see issue #1415) ──#-# Served by the dedicated ``gemma`` bundle (packages/sie_server/bundles/-# gemma.yaml): sglang 0.5.13 + torch 2.11 (cu130) on a CUDA 13 base. 0.5.13 is+# Served by the shared ``sglang-cu130`` bundle (packages/sie_server/bundles/+# sglang-cu130.yaml): sglang 0.5.13 + torch 2.11 (cu130) on a CUDA 13 base. 0.5.13 is# the validated engine; 0.5.11 (first release with Gemma 4) has a JIT-kernel# compile bug. E2B was smoke-validated on a Modal L4 2026-06-18 (serves +# /v1/chat/completions 200). ``kv_budget_tokens`` / ``mem_fraction_static`` /diff --git a/packages/sie_server/models/google__gemma-4-E4B-it.yaml b/packages/sie_server/models/google__gemma-4-E4B-it.yamlindex d7ec3d104..94748f502 100644--- a/packages/sie_server/models/google__gemma-4-E4B-it.yaml+++ b/packages/sie_server/models/google__gemma-4-E4B-it.yaml@@ -2,8 +2,8 @@ sie_id: google/gemma-4-E4B-ithf_id: google/gemma-4-E4B-it# ── Engine (see issue #1415) ──#-# Served by the dedicated ``gemma`` bundle (packages/sie_server/bundles/-# gemma.yaml): sglang 0.5.13 + torch 2.11 (cu130) on a CUDA 13 base. 0.5.13 is+# Served by the shared ``sglang-cu130`` bundle (packages/sie_server/bundles/+# sglang-cu130.yaml): sglang 0.5.13 + torch 2.11 (cu130) on a CUDA 13 base. 0.5.13 is# the validated engine; 0.5.11 (first release with Gemma 4) has a JIT-kernel# compile bug. Smoke-validated on a Modal H100 2026-06-19 (serves +# /v1/chat/completions generates correctly; E2B was likewise validated on andiff --git a/packages/sie_server/models/google__siglip-base-patch16-256.yaml b/packages/sie_server/models/google__siglip-base-patch16-256.yamlnew file mode 100644index 000000000..7089f8acd--- /dev/null+++ b/packages/sie_server/models/google__siglip-base-patch16-256.yaml@@ -0,0 +1,26 @@+sie_id: google/siglip-base-patch16-256+hf_id: google/siglip-base-patch16-256+hf_revision: b078df89e446d623010d890864d4207fe6399f61+inputs:+ text: true+ image: true+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 64+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: float16+ adapter_path: sie_server.adapters.siglip.adapter:SiglipAdapter+ adapter_options:+ loadtime: {}+ runtime:+ normalize: falsediff --git a/packages/sie_server/models/google__siglip-so400m-patch14-224.yaml b/packages/sie_server/models/google__siglip-so400m-patch14-224.yamlindex c0f250a95..6edc0bbcb 100644--- a/packages/sie_server/models/google__siglip-so400m-patch14-224.yaml+++ b/packages/sie_server/models/google__siglip-so400m-patch14-224.yaml@@ -1,5 +1,6 @@sie_id: google/siglip-so400m-patch14-224hf_id: google/siglip-so400m-patch14-224+hf_revision: d04cf29fca7b6374f74d8bea1969314492266b5einputs:text: trueimage: truediff --git a/packages/sie_server/models/ibm-granite__granite-embedding-english-r2.yaml b/packages/sie_server/models/ibm-granite__granite-embedding-english-r2.yamlindex 2a8401793..d27b3543b 100644--- a/packages/sie_server/models/ibm-granite__granite-embedding-english-r2.yaml+++ b/packages/sie_server/models/ibm-granite__granite-embedding-english-r2.yaml@@ -1,5 +1,6 @@sie_id: ibm-granite/granite-embedding-english-r2hf_id: ibm-granite/granite-embedding-english-r2+hf_revision: 47ea694b257b703fee9253d75c2b1f2985180498inputs:text: trueimage: falsediff --git a/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml b/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yamlindex 664366eaf..49f246dd3 100644--- a/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml+++ b/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml@@ -1,5 +1,6 @@sie_id: ibm-granite/granite-embedding-small-english-r2hf_id: ibm-granite/granite-embedding-small-english-r2+hf_revision: 2ab6fa8ea2d674564defd37171ae19079b864b33inputs:text: trueimage: falsediff --git a/packages/sie_server/models/intfloat__e5-large-v2.yaml b/packages/sie_server/models/intfloat__e5-large-v2.yamlindex 194e366d8..bf7143e52 100644--- a/packages/sie_server/models/intfloat__e5-large-v2.yaml+++ b/packages/sie_server/models/intfloat__e5-large-v2.yaml@@ -1,5 +1,6 @@sie_id: intfloat/e5-large-v2hf_id: intfloat/e5-large-v2+hf_revision: f169b11e22de13617baa190a028a32f3493550b6inputs:text: trueimage: falsediff --git a/packages/sie_server/models/intfloat__e5-mistral-7b-instruct.yaml b/packages/sie_server/models/intfloat__e5-mistral-7b-instruct.yamlindex 7d9d32f5b..b1da93670 100644--- a/packages/sie_server/models/intfloat__e5-mistral-7b-instruct.yaml+++ b/packages/sie_server/models/intfloat__e5-mistral-7b-instruct.yaml@@ -1,5 +1,6 @@sie_id: intfloat/e5-mistral-7b-instructhf_id: intfloat/e5-mistral-7b-instruct+hf_revision: d62cc4417be0e3289c03dd459d1ef2d137e2554einputs:text: trueimage: falsediff --git a/packages/sie_server/models/intfloat__multilingual-e5-large-instruct.yaml b/packages/sie_server/models/intfloat__multilingual-e5-large-instruct.yamlindex ba932f938..016e94bcb 100644--- a/packages/sie_server/models/intfloat__multilingual-e5-large-instruct.yaml+++ b/packages/sie_server/models/intfloat__multilingual-e5-large-instruct.yaml@@ -1,5 +1,6 @@sie_id: intfloat/multilingual-e5-large-instructhf_id: intfloat/multilingual-e5-large-instruct+hf_revision: 274baa43b0e13e37fafa6428dbc7938e62e5c439inputs:text: trueimage: falsediff --git a/packages/sie_server/models/intfloat__multilingual-e5-large.yaml b/packages/sie_server/models/intfloat__multilingual-e5-large.yamlindex be75b9ab1..a92659148 100644--- a/packages/sie_server/models/intfloat__multilingual-e5-large.yaml+++ b/packages/sie_server/models/intfloat__multilingual-e5-large.yaml@@ -1,5 +1,6 @@sie_id: intfloat/multilingual-e5-largehf_id: intfloat/multilingual-e5-large+hf_revision: 3d7cfbdacd47fdda877c5cd8a79fbcc4f2a574f3inputs:text: trueimage: falsediff --git a/packages/sie_server/models/intfloat__multilingual-e5-small.yaml b/packages/sie_server/models/intfloat__multilingual-e5-small.yamlindex e6a5dbe8b..874cce20d 100644--- a/packages/sie_server/models/intfloat__multilingual-e5-small.yaml+++ b/packages/sie_server/models/intfloat__multilingual-e5-small.yaml@@ -1,5 +1,6 @@sie_id: intfloat/multilingual-e5-smallhf_id: intfloat/multilingual-e5-small+hf_revision: 614241f622f53c4eeff9890bdc4f31cfecc418b3inputs:text: trueimage: falsediff --git a/packages/sie_server/models/jackboyla__glirel-large-v0.yaml b/packages/sie_server/models/jackboyla__glirel-large-v0.yamlindex 47c9bae20..6227b08dd 100644--- a/packages/sie_server/models/jackboyla__glirel-large-v0.yaml+++ b/packages/sie_server/models/jackboyla__glirel-large-v0.yaml@@ -1,5 +1,6 @@sie_id: jackboyla/glirel-large-v0hf_id: jackboyla/glirel-large-v0+hf_revision: 40a523e12a8432d6da364cf2a195a28755ff04d3inputs:text: trueimage: falsediff --git a/packages/sie_server/models/knowledgator__gliclass-base-v1.0.yaml b/packages/sie_server/models/knowledgator__gliclass-base-v1.0.yamlindex 4426c6d92..5099ea39e 100644--- a/packages/sie_server/models/knowledgator__gliclass-base-v1.0.yaml+++ b/packages/sie_server/models/knowledgator__gliclass-base-v1.0.yaml@@ -1,5 +1,6 @@sie_id: knowledgator/gliclass-base-v1.0hf_id: knowledgator/gliclass-base-v1.0+hf_revision: aa3ac24a77860a033c9e9a3aa90d5872722cb7bfinputs:text: trueimage: falsediff --git a/packages/sie_server/models/knowledgator__gliclass-small-v1.0.yaml b/packages/sie_server/models/knowledgator__gliclass-small-v1.0.yamlindex 7e87baa1d..5f18c4a81 100644--- a/packages/sie_server/models/knowledgator__gliclass-small-v1.0.yaml+++ b/packages/sie_server/models/knowledgator__gliclass-small-v1.0.yaml@@ -1,5 +1,6 @@sie_id: knowledgator/gliclass-small-v1.0hf_id: knowledgator/gliclass-small-v1.0+hf_revision: 21edefaf7951f68c68c505f9139ba536d3b448f7inputs:text: trueimage: falsediff --git a/packages/sie_server/models/knowledgator__gliner-bi-base-v2.0.yaml b/packages/sie_server/models/knowledgator__gliner-bi-base-v2.0.yamlindex 79e8aa98d..1ac17321b 100644--- a/packages/sie_server/models/knowledgator__gliner-bi-base-v2.0.yaml+++ b/packages/sie_server/models/knowledgator__gliner-bi-base-v2.0.yaml@@ -1,5 +1,6 @@sie_id: knowledgator/gliner-bi-base-v2.0hf_id: knowledgator/gliner-bi-base-v2.0+hf_revision: 3fdae58db008a8b4e0a803a920ce9bf6566aceedinputs:text: trueimage: falsediff --git a/packages/sie_server/models/knowledgator__modern-gliner-bi-base-v1.0.yaml b/packages/sie_server/models/knowledgator__modern-gliner-bi-base-v1.0.yamlindex 43836ccc4..66eb52276 100644--- a/packages/sie_server/models/knowledgator__modern-gliner-bi-base-v1.0.yaml+++ b/packages/sie_server/models/knowledgator__modern-gliner-bi-base-v1.0.yaml@@ -1,5 +1,6 @@sie_id: knowledgator/modern-gliner-bi-base-v1.0hf_id: knowledgator/modern-gliner-bi-base-v1.0+hf_revision: 2d73e4c02b52f96e2926baffc67b5e78532fc39cinputs:text: trueimage: falsediff --git a/packages/sie_server/models/microsoft__Florence-2-base.yaml b/packages/sie_server/models/microsoft__Florence-2-base.yamlindex ff417f013..ab81b8089 100644--- a/packages/sie_server/models/microsoft__Florence-2-base.yaml+++ b/packages/sie_server/models/microsoft__Florence-2-base.yaml@@ -21,7 +21,7 @@ profiles:runtime:# Default task is object detection: Florence-2-base is measured on COCO# detection (its model-card metric, like Florence-2-base-ft / large; #1437).- # The same model is also the sie_tools image OCR fallback — that call+ # The same model is also used as an image OCR fallback — that call# passes options={"task": "<OCR>"} explicitly, so one model serves both OD# and OCR. This default only sets the no-task-specified behaviour.task: <OD>diff --git a/packages/sie_server/models/mixedbread-ai__mxbai-rerank-large-v2.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-rerank-large-v2.yamlindex e20bcf311..d0b1817de 100644--- a/packages/sie_server/models/mixedbread-ai__mxbai-rerank-large-v2.yaml+++ b/packages/sie_server/models/mixedbread-ai__mxbai-rerank-large-v2.yaml@@ -1,5 +1,6 @@sie_id: mixedbread-ai/mxbai-rerank-large-v2hf_id: mixedbread-ai/mxbai-rerank-large-v2+hf_revision: ca7e1ee484c37c0ddd8d178a9a5c33cec575c5e6inputs:text: trueimage: falsediff --git a/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-cord-v2.yaml b/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-cord-v2.yamlindex df31dadca..45917bc09 100644--- a/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-cord-v2.yaml+++ b/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-cord-v2.yaml@@ -1,5 +1,6 @@sie_id: naver-clova-ix/donut-base-finetuned-cord-v2hf_id: naver-clova-ix/donut-base-finetuned-cord-v2+hf_revision: 8003d433113256b4ce3a0f5bf604b29ff78a7451inputs:text: falseimage: truediff --git a/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-docvqa.yaml b/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-docvqa.yamlindex 3e43b18c6..2f867f3f0 100644--- a/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-docvqa.yaml+++ b/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-docvqa.yaml@@ -1,5 +1,6 @@sie_id: naver-clova-ix/donut-base-finetuned-docvqahf_id: naver-clova-ix/donut-base-finetuned-docvqa+hf_revision: b19d2e332684b0e2d35d9144ce34047767335cf8inputs:text: falseimage: truediff --git a/packages/sie_server/models/naver__splade-cocondenser-selfdistil.yaml b/packages/sie_server/models/naver__splade-cocondenser-selfdistil.yamlindex fcc75a32d..40ea4a2f4 100644--- a/packages/sie_server/models/naver__splade-cocondenser-selfdistil.yaml+++ b/packages/sie_server/models/naver__splade-cocondenser-selfdistil.yaml@@ -1,5 +1,6 @@sie_id: naver/splade-cocondenser-selfdistilhf_id: naver/splade-cocondenser-selfdistil+hf_revision: 31f3eb4b5aae648cde974db3b7b44bf2d095106binputs:text: trueimage: falsediff --git a/packages/sie_server/models/naver__splade-v3.yaml b/packages/sie_server/models/naver__splade-v3.yamlindex bb8a1159d..4a7313725 100644--- a/packages/sie_server/models/naver__splade-v3.yaml+++ b/packages/sie_server/models/naver__splade-v3.yaml@@ -1,5 +1,6 @@sie_id: naver/splade-v3hf_id: naver/splade-v3+hf_revision: fdfeceb91d7b9de7985b38addd3ba9f53a59a355inputs:text: trueimage: falsediff --git a/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml b/packages/sie_server/models/nomic-ai__modernbert-embed-base.yamlindex ae008b82d..735573874 100644--- a/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml+++ b/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml@@ -1,5 +1,6 @@sie_id: nomic-ai/modernbert-embed-basehf_id: nomic-ai/modernbert-embed-base+hf_revision: d556a88e332558790b210f7bdbe87da2fa94a8d8inputs:text: trueimage: falsediff --git a/packages/sie_server/models/numind__NuNER_Zero-span.yaml b/packages/sie_server/models/numind__NuNER_Zero-span.yamlindex 5e9f0a120..aaeb94239 100644--- a/packages/sie_server/models/numind__NuNER_Zero-span.yaml+++ b/packages/sie_server/models/numind__NuNER_Zero-span.yaml@@ -1,5 +1,6 @@sie_id: numind/NuNER_Zero-spanhf_id: numind/NuNER_Zero-span+hf_revision: 063b4dec1aaf626058e7c071657b15d52abffca0inputs:text: trueimage: falsediff --git a/packages/sie_server/models/nvidia__llama-nemoretriever-colembed-3b-v1.yaml b/packages/sie_server/models/nvidia__llama-nemoretriever-colembed-3b-v1.yamlindex 640b46aff..e944513ed 100644--- a/packages/sie_server/models/nvidia__llama-nemoretriever-colembed-3b-v1.yaml+++ b/packages/sie_server/models/nvidia__llama-nemoretriever-colembed-3b-v1.yaml@@ -1,5 +1,6 @@sie_id: nvidia/llama-nemoretriever-colembed-3b-v1hf_id: nvidia/llama-nemoretriever-colembed-3b-v1+hf_revision: 75f7e7311c7a5965c535587fd5e563c5e4a3c583inputs:text: trueimage: truediff --git a/packages/sie_server/models/nvidia__nemotron-colembed-vl-4b-v2.yaml b/packages/sie_server/models/nvidia__nemotron-colembed-vl-4b-v2.yamlindex eb686405a..450fdd702 100644--- a/packages/sie_server/models/nvidia__nemotron-colembed-vl-4b-v2.yaml+++ b/packages/sie_server/models/nvidia__nemotron-colembed-vl-4b-v2.yaml@@ -1,5 +1,6 @@sie_id: nvidia/nemotron-colembed-vl-4b-v2hf_id: nvidia/nemotron-colembed-vl-4b-v2+hf_revision: 0ed152d91f8ad4c5d48296b51c220f686641a398inputs:text: trueimage: truediff --git a/packages/sie_server/models/openai__clip-vit-large-patch14.yaml b/packages/sie_server/models/openai__clip-vit-large-patch14.yamlindex 3bccfb329..43070e42a 100644--- a/packages/sie_server/models/openai__clip-vit-large-patch14.yaml+++ b/packages/sie_server/models/openai__clip-vit-large-patch14.yaml@@ -1,5 +1,6 @@sie_id: openai/clip-vit-large-patch14hf_id: openai/clip-vit-large-patch14+hf_revision: 32bd64288804d66eefd0ccbe215aa642df71cc41inputs:text: trueimage: truediff --git a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v2-distill.yaml b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v2-distill.yamlindex afda23803..c27007e1d 100644--- a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v2-distill.yaml+++ b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v2-distill.yaml@@ -1,5 +1,6 @@sie_id: opensearch-project/opensearch-neural-sparse-encoding-doc-v2-distillhf_id: opensearch-project/opensearch-neural-sparse-encoding-doc-v2-distill+hf_revision: 8921a26c78b8559d6604eb1f5c0b74c079bee38finputs:text: trueimage: falsediff --git a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v2-mini.yaml b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v2-mini.yamlindex 486bff768..550388799 100644--- a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v2-mini.yaml+++ b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v2-mini.yaml@@ -1,5 +1,6 @@sie_id: opensearch-project/opensearch-neural-sparse-encoding-doc-v2-minihf_id: opensearch-project/opensearch-neural-sparse-encoding-doc-v2-mini+hf_revision: 4af867a426867dfdd744097531046f4289a32fddinputs:text: trueimage: falsediff --git a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-v1.yaml b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-v1.yamlindex 179c0a77d..c78890b7c 100644--- a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-v1.yaml+++ b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-v1.yaml@@ -1,5 +1,6 @@sie_id: opensearch-project/opensearch-neural-sparse-encoding-v1hf_id: opensearch-project/opensearch-neural-sparse-encoding-v1+hf_revision: 708f7e68f4aada15c2d59144a5187c521da6d8dbinputs:text: trueimage: falsediff --git a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-v2-distill.yaml b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-v2-distill.yamlindex c2cf9d91d..a7d2d7dde 100644--- a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-v2-distill.yaml+++ b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-v2-distill.yaml@@ -1,5 +1,6 @@sie_id: opensearch-project/opensearch-neural-sparse-encoding-v2-distillhf_id: opensearch-project/opensearch-neural-sparse-encoding-v2-distill+hf_revision: 269e6638b2c4f648996691f6d751495285d8f330inputs:text: trueimage: falsediff --git a/packages/sie_server/models/rasyosef__splade-mini.yaml b/packages/sie_server/models/rasyosef__splade-mini.yamlindex 5b1381f9c..5790ba1d1 100644--- a/packages/sie_server/models/rasyosef__splade-mini.yaml+++ b/packages/sie_server/models/rasyosef__splade-mini.yaml@@ -1,5 +1,6 @@sie_id: rasyosef/splade-minihf_id: rasyosef/splade-mini+hf_revision: 98cb9db1eb2af3399c0bee30a6edca3fe9c0c057inputs:text: trueimage: falsediff --git a/packages/sie_server/models/sentence-transformers__all-MiniLM-L6-v2.yaml b/packages/sie_server/models/sentence-transformers__all-MiniLM-L6-v2.yamlindex c4f1864f7..2c9ba2d44 100644--- a/packages/sie_server/models/sentence-transformers__all-MiniLM-L6-v2.yaml+++ b/packages/sie_server/models/sentence-transformers__all-MiniLM-L6-v2.yaml@@ -1,5 +1,6 @@sie_id: sentence-transformers/all-MiniLM-L6-v2hf_id: sentence-transformers/all-MiniLM-L6-v2+hf_revision: 1110a243fdf4706b3f48f1d95db1a4f5529b4d41inputs:text: trueimage: falsediff --git a/packages/sie_server/models/urchade__gliner_large-v2.1.yaml b/packages/sie_server/models/urchade__gliner_large-v2.1.yamlindex 7c417a373..40195a4b8 100644--- a/packages/sie_server/models/urchade__gliner_large-v2.1.yaml+++ b/packages/sie_server/models/urchade__gliner_large-v2.1.yaml@@ -1,5 +1,6 @@sie_id: urchade/gliner_large-v2.1hf_id: urchade/gliner_large-v2.1+hf_revision: abd49a1f1ebc12af1be84d06f6848221cf96dcadinputs:text: trueimage: falsediff --git a/packages/sie_server/models/urchade__gliner_medium-v2.1.yaml b/packages/sie_server/models/urchade__gliner_medium-v2.1.yamlindex 9325413e5..3d5c526b5 100644--- a/packages/sie_server/models/urchade__gliner_medium-v2.1.yaml+++ b/packages/sie_server/models/urchade__gliner_medium-v2.1.yaml@@ -1,5 +1,6 @@sie_id: urchade/gliner_medium-v2.1hf_id: urchade/gliner_medium-v2.1+hf_revision: 40ec419335d09393f298636f471328b722c6da9einputs:text: trueimage: falsediff --git a/packages/sie_server/models/vidore__colpali-v1.3-hf.yaml b/packages/sie_server/models/vidore__colpali-v1.3-hf.yamlindex 56613091f..020ee2753 100644--- a/packages/sie_server/models/vidore__colpali-v1.3-hf.yaml+++ b/packages/sie_server/models/vidore__colpali-v1.3-hf.yaml@@ -1,5 +1,6 @@sie_id: vidore/colpali-v1.3-hfhf_id: vidore/colpali-v1.3-hf+hf_revision: 133a9eb02947310513f52f8f0d39d622e0eab8dcinputs:text: trueimage: truediff --git a/packages/sie_server/models/vidore__colqwen2.5-v0.2.yaml b/packages/sie_server/models/vidore__colqwen2.5-v0.2.yamlindex b8085c7a5..1b5c012c7 100644--- a/packages/sie_server/models/vidore__colqwen2.5-v0.2.yaml+++ b/packages/sie_server/models/vidore__colqwen2.5-v0.2.yaml@@ -1,5 +1,6 @@sie_id: vidore/colqwen2.5-v0.2hf_id: vidore/colqwen2.5-v0.2+hf_revision: 6f6fcdfd1a114dfe365f529701b33d66b9349014inputs:text: trueimage: truediff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex fa554acf6..e58e197e0 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.7.1"+ "version": "0.7.2"},"paths": {"/healthz": {@@ -32,7 +32,7 @@"health"],"summary": "Livez",- "description": "GPU-aware liveness probe.\n\nUnlike /healthz (process-alive only), this exercises the GPU with a tiny CUDA\nsync. A wedged CUDA context (``device-side assert``) is unrecoverable in\nPyTorch, so failing liveness lets the kubelet restart the pod \u2014 the only path\nback to a serving worker (see issue #1025).\n\nIt deliberately does NOT consult the lifecycle ready flag, so graceful\nshutdown draining (when the worker marks itself not-ready) never trips a\nrestart. Wire this to the K8s ``livenessProbe`` with a tolerant\n``failureThreshold`` so a momentarily busy GPU is not mistaken for a wedge.\n\nReturns:\n 200 OK with \"ok\" body if the GPU can run a kernel (or this is a CPU\n worker). 503 Service Unavailable with \"gpu unhealthy\" if wedged.",+ "description": "GPU-aware liveness probe.\n\nUnlike /healthz (process-alive only), this exercises the GPU with a tiny CUDA\nsync. A wedged CUDA context (``device-side assert``) is unrecoverable in\nPyTorch, so failing liveness lets the kubelet restart the pod \u2014 the only path\nback to a serving worker.\n\nIt deliberately does NOT consult the lifecycle ready flag, so graceful\nshutdown draining (when the worker marks itself not-ready) never trips a\nrestart. Wire this to the K8s ``livenessProbe`` with a tolerant\n``failureThreshold`` so a momentarily busy GPU is not mistaken for a wedge.\n\nReturns:\n 200 OK with \"ok\" body if the GPU can run a kernel (or this is a CPU\n worker). 503 Service Unavailable with \"gpu unhealthy\" if wedged.","operationId": "livez_livez_get","responses": {"200": {@@ -52,7 +52,7 @@"health"],"summary": "Readyz",- "description": "Readiness probe.\n\nReturns 200 if the server is ready to accept traffic.\nUsed by Kubernetes to determine if traffic should be routed to this pod.\n\nReadiness has two conditions:\n- Lifecycle state, managed by the lifespan handler: ready after startup\n completes, not ready during shutdown (draining in-flight requests).\n- GPU health: a tiny CUDA sync confirms the device can still run kernels. A\n wedged CUDA context (``device-side assert``) keeps returning sticky errors\n from every inference while a process-alive check stays green, so without\n this the gateway would keep routing to a dead worker (see issue #1025).\n\nReturns:\n 200 OK with \"ok\" body if ready.\n 503 Service Unavailable if starting up / shutting down (\"not ready\") or\n the GPU context is wedged (\"gpu unhealthy\").",+ "description": "Readiness probe.\n\nReturns 200 if the server is ready to accept traffic.\nUsed by Kubernetes to determine if traffic should be routed to this pod.\n\nReadiness has two conditions:\n- Lifecycle state, managed by the lifespan handler: ready after startup\n completes, not ready during shutdown (draining in-flight requests).\n- GPU health: a tiny CUDA sync confirms the device can still run kernels. A\n wedged CUDA context (``device-side assert``) keeps returning sticky errors\n from every inference while a process-alive check stays green, so without\n this the gateway would keep routing to a dead worker.\n\nReturns:\n 200 OK with \"ok\" body if ready.\n 503 Service Unavailable if starting up / shutting down (\"not ready\") or\n the GPU context is wedged (\"gpu unhealthy\").","operationId": "readyz_readyz_get","responses": {"200": {@@ -136,7 +136,7 @@"description": "Model not found"},"502": {- "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry. See sie-test#85."+ "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry."},"503": {"description": "Model not loaded or service unavailable"@@ -239,7 +239,7 @@"description": "Model not found"},"502": {- "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry. See sie-test#85."+ "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry."},"503": {"description": "Model not loaded or service unavailable"@@ -449,7 +449,7 @@"description": "Model not found"},"502": {- "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry. See sie-test#85."+ "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry."},"503": {"description": "Model not loaded or service unavailable"@@ -668,7 +668,7 @@"openai-compat"],"summary": "Create Embeddings",- "description": "Create embeddings using OpenAI-compatible API.\n\nThis endpoint is compatible with OpenAI's /v1/embeddings API, allowing\ndrop-in replacement for any OpenAI SDK or client.\n\nArgs:\n request: OpenAI-format embedding request.\n http_request: FastAPI request (for app state).\n x_machine_profile: Machine profile header for routing validation.\n\nReturns:\n OpenAI-format embedding response with embeddings and usage info.",+ "description": "Create embeddings using OpenAI-compatible API.\n\nThis endpoint is compatible with OpenAI's /v1/embeddings API, allowing\ndrop-in replacement for any OpenAI SDK or client. Route-generated errors\nare emitted as top-level OpenAI ``{\"error\": {...}}`` envelopes, matching\n``/v1/completions``. The one exception is 422 request-body validation,\nwhich still returns FastAPI's ``HTTPValidationError`` ``{\"detail\": [...]}``\nshape (out of scope for this route's error handling; known residual).\n\nArgs:\n request: OpenAI-format embedding request.\n http_request: FastAPI request (for app state).\n x_machine_profile: Machine profile header for routing validation.\n\nReturns:\n OpenAI-format embedding response with embeddings and usage info.","operationId": "create_embeddings_v1_embeddings_post","parameters": [{@@ -716,10 +716,33 @@"description": "Model not found"},"502": {- "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry. See sie-test#85."+ "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the top-level OpenAI ``error`` envelope, whose object adds the model-load extras ``error_class``, ``permanent``, and ``attempts`` to ``{message, type, param, code}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIEmbeddingsModelLoadFailedErrorResponse"+ }+ }+ }},"503": {- "description": "Service unavailable"+ "description": "Service unavailable (retryable). A cold model starts a background load and returns ``MODEL_LOADING`` with a ``Retry-After`` header immediately instead of blocking the request \u2014 clients should retry after the indicated delay. Also returned while unloading, on a full queue, and under transient resource exhaustion. The body is the top-level OpenAI ``error`` envelope.",+ "headers": {+ "Retry-After": {+ "description": "Seconds to wait before retrying the MODEL_LOADING request.",+ "schema": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIEmbeddingsErrorResponse"+ }+ }+ }},"422": {"description": "Validation Error",@@ -976,6 +999,17 @@}],"description": "Request timing breakdown"+ },+ "usage": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/UsageModel"+ },+ {+ "type": "null"+ }+ ],+ "description": "Authoritative usage when the worker reported counts"}},"type": "object",@@ -1139,6 +1173,17 @@"type": "array","title": "Items","description": "Extraction results for each input item"+ },+ "usage": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/UsageModel"+ },+ {+ "type": "null"+ }+ ],+ "description": "Authoritative usage when the worker reported counts"}},"type": "object",@@ -1792,7 +1837,7 @@}],"title": "Dimensions",- "description": "Number of dimensions (not supported by SIE, ignored)"+ "description": "Requested embedding width. SIE always returns the model's native dense width, so this is accepted only when it equals that width; any other value is rejected with 400 `unsupported_field` rather than ignored."},"user": {"anyOf": [@@ -1851,6 +1896,130 @@"title": "OpenAIEmbeddingResponse","description": "OpenAI-compatible embedding response."},+ "OpenAIEmbeddingsErrorModel": {+ "properties": {+ "message": {+ "type": "string",+ "title": "Message",+ "description": "Client-safe error message"+ },+ "type": {+ "type": "string",+ "title": "Type",+ "description": "OpenAI error type, e.g. 'server_error'"+ },+ "param": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Param",+ "description": "Offending request field, when known"+ },+ "code": {+ "type": "string",+ "title": "Code",+ "description": "Stable SIE error code, e.g. 'MODEL_LOADING'"+ }+ },+ "type": "object",+ "required": [+ "message",+ "type",+ "code"+ ],+ "title": "OpenAIEmbeddingsErrorModel",+ "description": "Inner object of the top-level OpenAI ``{\"error\": {...}}`` envelope that\n``/v1/embeddings`` route-generated errors emit (e.g. a retryable 503\n``MODEL_LOADING``). Matches the shape ``/v1/completions`` returns."+ },+ "OpenAIEmbeddingsErrorResponse": {+ "properties": {+ "error": {+ "$ref": "#/components/schemas/OpenAIEmbeddingsErrorModel"+ }+ },+ "type": "object",+ "required": [+ "error"+ ],+ "title": "OpenAIEmbeddingsErrorResponse",+ "description": "Top-level OpenAI error envelope for a retryable ``/v1/embeddings`` error."+ },+ "OpenAIEmbeddingsModelLoadFailedErrorModel": {+ "properties": {+ "message": {+ "type": "string",+ "title": "Message",+ "description": "Client-safe error message"+ },+ "type": {+ "type": "string",+ "title": "Type",+ "description": "OpenAI error type ('server_error')"+ },+ "param": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Param",+ "description": "Unused for this error; always null"+ },+ "code": {+ "type": "string",+ "const": "MODEL_LOAD_FAILED",+ "title": "Code",+ "description": "Stable error code"+ },+ "error_class": {+ "type": "string",+ "title": "Error Class",+ "description": "Classified model-load failure category"+ },+ "permanent": {+ "type": "boolean",+ "title": "Permanent",+ "description": "Whether operator action is required before retrying"+ },+ "attempts": {+ "type": "integer",+ "minimum": 1.0,+ "title": "Attempts",+ "description": "Number of failed model-load attempts"+ }+ },+ "type": "object",+ "required": [+ "message",+ "type",+ "code",+ "error_class",+ "permanent",+ "attempts"+ ],+ "title": "OpenAIEmbeddingsModelLoadFailedErrorModel",+ "description": "Inner error object for a terminal ``/v1/embeddings`` model-load failure,\ncarrying the terminal-failure short-circuit fields alongside the OpenAI shape."+ },+ "OpenAIEmbeddingsModelLoadFailedErrorResponse": {+ "properties": {+ "error": {+ "$ref": "#/components/schemas/OpenAIEmbeddingsModelLoadFailedErrorModel"+ }+ },+ "type": "object",+ "required": [+ "error"+ ],+ "title": "OpenAIEmbeddingsModelLoadFailedErrorResponse",+ "description": "Top-level OpenAI error envelope for a terminal ``/v1/embeddings`` model-load failure."+ },"OpenAIResponseOutputMessageModel": {"properties": {"type": {@@ -2256,6 +2425,35 @@"title": "TimingInfoModel","description": "Request timing breakdown."},+ "UsageModel": {+ "properties": {+ "input_tokens": {+ "type": "integer",+ "minimum": 0.0,+ "title": "Input Tokens",+ "description": "Post-truncation input tokens processed"+ },+ "images": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 0.0+ },+ {+ "type": "null"+ }+ ],+ "title": "Images",+ "description": "Images processed across the request's items"+ }+ },+ "type": "object",+ "required": [+ "input_tokens"+ ],+ "title": "UsageModel",+ "description": "Authoritative worker-emitted usage.\n\nPost-tokenization counts, never a character estimate. A reported 0 is a\nmeasurement (a video-only encode reads no text); an absent block means the\ncounts were unavailable on this path."+ },"ValidationError": {"properties": {"loc": {@@ -2296,12 +2494,55 @@],"title": "ValidationError"},+ "AudioInputModel": {+ "description": "Audio input for audio models.",+ "properties": {+ "data": {+ "contentEncoding": "base64",+ "description": "Audio data. Base64-encoded on the JSON path; native binary on the msgpack path.",+ "title": "Data",+ "type": "string"+ },+ "format": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Audio format: 'wav', 'mp3', etc.",+ "title": "Format"+ },+ "sample_rate": {+ "anyOf": [+ {+ "exclusiveMinimum": 0,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Sample rate in Hz. Must be positive.",+ "title": "Sample Rate"+ }+ },+ "required": [+ "data"+ ],+ "title": "AudioInputModel",+ "type": "object"+ },"DocumentInputModel": {"description": "Document input for composite-document extractors (PDF, DOCX, HTML, ...).","properties": {"data": {- "description": "Document bytes (raw file content)",- "format": "binary",+ "contentEncoding": "base64",+ "description": "Document bytes (raw file content). Base64-encoded on the JSON path; native binary on the msgpack path.","title": "Data","type": "string"},@@ -2403,8 +2644,8 @@"description": "Image input for multimodal models.","properties": {"data": {- "description": "Image data as bytes",- "format": "binary",+ "contentEncoding": "base64",+ "description": "Image data. Base64-encoded on the JSON path; native binary on the msgpack path.","title": "Data","type": "string"},@@ -2477,6 +2718,30 @@"description": "Images for multimodal models","title": "Images"},+ "audio": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/AudioInputModel"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Audio for audio models"+ },+ "video": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/VideoInputModel"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Video for video models"+ },"document": {"anyOf": [{@@ -2507,6 +2772,35 @@"title": "ItemModel","type": "object"},+ "VideoInputModel": {+ "description": "Video input for video models.",+ "properties": {+ "data": {+ "contentEncoding": "base64",+ "description": "Video data. Base64-encoded on the JSON path; native binary on the msgpack path.",+ "title": "Data",+ "type": "string"+ },+ "format": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Video format: 'mp4', 'webm', etc.",+ "title": "Format"+ }+ },+ "required": [+ "data"+ ],+ "title": "VideoInputModel",+ "type": "object"+ },"EncodeRequestModel": {"description": "Request body for encode endpoint.","examples": [@@ -2559,6 +2853,7 @@"items": {"type": "string"},+ "maxItems": 1000,"type": "array"},{diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex c4752b577..aa1eeea61 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.7.1"+version = "0.7.2"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 6ceace549..0aaaf56db 100644--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py@@ -149,13 +149,18 @@ class GenerationResult:Used by callers that don't yet consume the chunk iterator — currentlythe local-dev ``/v1/generate`` HTTP route and unit tests for theblocking adapter shape. The async iterator is the canonical contract;- this aggregate is built from it.+ this aggregate is built from it. ``error_code`` / ``error_message``+ mirror the terminal chunk's typed error fields (e.g.+ ``empty_model_output``) so buffered consumers can fail closed with the+ same semantics as the streaming path (#3104/#3136)."""text: strfinish_reason: Literal["stop", "length", "error", "cancelled"]prompt_tokens: intcompletion_tokens: int+ error_code: str | None = None+ error_message: str | None = Noneclass ThinkingBlockStripper:@@ -247,6 +252,13 @@ def _strip_complete_thinking_blocks(return stripper.feed(text) + stripper.finish()+def _candidates_have_visible_text(candidates: tuple[dict[str, Any], ...] | None) -> bool:+ """Return whether any ``n > 1`` candidate aggregate carries visible text."""+ if not candidates:+ return False+ return any(isinstance(text := candidate.get("text"), str) and text.strip() for candidate in candidates)++async def suppress_thinking_blocks(chunks: AsyncIterator[GenerationChunk],*,@@ -269,9 +281,20 @@ async def suppress_thinking_blocks(Closing the wrapper eagerly closes the upstream adapter iterator so clientcancellation still reaches SGLang's ``/abort_request`` cleanup.++ A stream that terminates without ever producing meaningful visible output+ (no non-whitespace text on any choice or candidate, no tool calls) is+ stamped with ``error_code="empty_model_output"`` on the terminal chunk —+ e.g. when private reasoning consumed the entire generation budget. Without+ the stamp such a request settles as a nominally successful but unusable+ response that clients cannot distinguish from a real answer (#3104/#3136).+ Cancelled and already-errored terminals are left untouched."""states: dict[int, ThinkingBlockStripper] = {}emitted_visible_text = False+ emitted_meaningful_text = False+ emitted_tool_call = False+ hid_reasoning = Falsetry:async for chunk in chunks:rewritten_candidates = chunk.candidates@@ -289,6 +312,7 @@ async def suppress_thinking_blocks(if visible != text:item["text"] = visibleitem["logprobs"] = None+ hid_reasoning = Truecandidate_items.append(item)rewritten_candidates = tuple(candidate_items)@@ -304,6 +328,9 @@ async def suppress_thinking_blocks(is_first = bool(visible_delta) and not emitted_visible_textemitted_visible_text = emitted_visible_text or bool(visible_delta)+ emitted_meaningful_text = emitted_meaningful_text or bool(visible_delta.strip())+ emitted_tool_call = emitted_tool_call or chunk.tool_call_delta is not None+ hid_reasoning = hid_reasoning or text_changed or was_insiderewritten = replace(chunk,text_delta=visible_delta,@@ -312,6 +339,21 @@ async def suppress_thinking_blocks(candidates=rewritten_candidates,)+ if (+ rewritten.done+ and not emitted_meaningful_text+ and not emitted_tool_call+ and rewritten.error_code is None+ and rewritten.finish_reason in ("stop", "length")+ and not _candidates_have_visible_text(rewritten.candidates)+ ):+ reason = " (private reasoning consumed the generation budget)" if hid_reasoning else ""+ rewritten = replace(+ rewritten,+ error_code="empty_model_output",+ error_message=f"model produced no visible output text{reason}",+ )+# Reasoning-only engine deltas have no wire-visible information.# Keep terminals, per-choice finish markers, tool/error chunks, and# non-streaming candidate aggregates intact.@@ -402,12 +444,17 @@ async def collect_generation(Convenience for the local-dev ``/v1/generate`` route and unit-test codepaths that historically consumed the blocking shape. The terminalchunk's ``finish_reason`` / token counts are propagated; missing- counts default to 0.+ counts default to 0. Terminal ``error_code`` / ``error_message``+ (e.g. ``empty_model_output``, which keeps a ``stop``/``length``+ finish_reason) are carried verbatim so buffered consumers can fail+ closed instead of settling as a nominal success (#3104/#3136)."""parts: list[str] = []finish_reason: FinishReason = "stop"prompt_tokens = 0completion_tokens = 0+ error_code: str | None = None+ error_message: str | None = Noneasync for chunk in chunks:if chunk.text_delta:parts.append(chunk.text_delta)@@ -417,12 +464,16 @@ async def collect_generation(prompt_tokens = chunk.prompt_tokensif chunk.completion_tokens is not None:completion_tokens = chunk.completion_tokens+ error_code = chunk.error_code+ error_message = chunk.error_messagebreakreturn GenerationResult(text="".join(parts),finish_reason=cast("Any", finish_reason),prompt_tokens=prompt_tokens,completion_tokens=completion_tokens,+ error_code=error_code,+ error_message=error_message,)diff --git a/packages/sie_server/src/sie_server/adapters/clip/__init__.py b/packages/sie_server/src/sie_server/adapters/clip/__init__.pyindex 6133bb386..2270c22ba 100644--- a/packages/sie_server/src/sie_server/adapters/clip/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/clip/__init__.py@@ -19,7 +19,6 @@ Example configuration:from __future__ import annotations-import ioimport loggingimport osimport threading@@ -28,14 +27,14 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVarimport torch-from PIL import Imagefrom torch.nn import functionalfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.core.inference_output import EncodeOutput-from sie_server.types.inputs import media_bytes+from sie_server.core.preprocessor import ImagePreprocessor+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:from transformers import CLIPModel, CLIPProcessor@@ -261,7 +260,7 @@ class CLIPAdapter(BaseAdapter):embeddings: list[Any] = [None] * len(items)if image_indices:- image_vecs = self._encode_image_items([items[i] for i in image_indices])+ image_vecs = self._encode_image_items([items[i] for i in image_indices], image_indices)for slot, i in enumerate(image_indices):embeddings[i] = image_vecs[slot]@@ -314,49 +313,62 @@ class CLIPAdapter(BaseAdapter):self._preprocess_pool = poolreturn pool- def _preprocess_one(self, img_input: Any) -> torch.Tensor:+ def _preprocess_one(+ self, img_input: Any, *, item_index: int | None = None, image_index: int | None = None+ ) -> torch.Tensor:"""Decode + preprocess a single image input into a ``[C, H, W]`` tensor.Stateless per call — the HF image processor and PIL release the GIL onthe heavy work, so this is safe to fan across the preprocessing pool.+ ``item_index``/``image_index`` name the request-local position in the+ typed decode error."""assert self._processor is not None- img_bytes = media_bytes(img_input, kind="image")- pil_img = Image.open(io.BytesIO(img_bytes))- # Convert to RGB if necessary (CLIP expects RGB)- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads; CLIP expects RGB.+ pil_img = decode_image(img_input, item_index=item_index, image_index=image_index)processed = self._processor(images=pil_img, return_tensors="pt")return processed["pixel_values"][0]- def _preprocess_image_batch(self, img_inputs: list[Any]) -> torch.Tensor:- """Preprocess a flat list of image inputs into a ``[N, C, H, W]`` tensor.+ def _preprocess_image_batch(self, jobs: list[tuple[int, int, Any]]) -> torch.Tensor:+ """Preprocess flat ``(item_index, image_index, image_input)`` jobs into ``[N, C, H, W]``.Per-image preprocessing is independent, so a single stacked tensor isbit-identical to preprocessing each image on its own — it is only fanned- across threads to overlap the CPU-bound decode/resize.+ across threads to overlap the CPU-bound decode/resize. Each job carries+ its request-local indices so a decode failure names the exact field."""- if len(img_inputs) == 1:- tensors = [self._preprocess_one(img_inputs[0])]++ def run(job: tuple[int, int, Any]) -> torch.Tensor:+ item_index, image_index, img_input = job+ return self._preprocess_one(img_input, item_index=item_index, image_index=image_index)++ if len(jobs) == 1:+ tensors = [run(jobs[0])]else:pool = self._get_preprocess_pool()- tensors = list(pool.map(self._preprocess_one, img_inputs))+ tensors = list(pool.map(run, jobs))return torch.stack(tensors, dim=0)- def _encode_image_items(self, items: list[Item]) -> Any:+ def _encode_image_items(self, items: list[Item], item_indices: list[int]) -> Any:"""Encode image items as one stacked forward, mean-pooling per item.- Returns a ``[len(items), dim]`` float32 array, one row per item.+ ``item_indices`` maps each entry of ``items`` back to its request-local+ position (the partition in ``encode`` filters to image items), so a+ decode failure names the original item. Returns a ``[len(items), dim]``+ float32 array, one row per item."""assert self._model is not None# Flatten every image across the items, remembering per-item counts so# the stacked features can be split back and mean-pooled per item.counts = [len(item.images or []) for item in items]- flat_inputs = [img for item in items for img in (item.images or [])]+ flat_jobs = [+ (item_indices[slot], j, img) for slot, item in enumerate(items) for j, img in enumerate(item.images or [])+ ]- pixel_values = self._preprocess_image_batch(flat_inputs).to(self._device)+ pixel_values = self._preprocess_image_batch(flat_jobs).to(self._device)with torch.inference_mode():image_features = _feature_tensor(self._model.get_image_features(pixel_values=pixel_values))@@ -422,18 +434,28 @@ class CLIPAdapter(BaseAdapter):msg = f"Unsupported output types: {unsupported}. CLIP only supports 'dense'."raise ValueError(msg)- def get_preprocessor(self) -> Any | None:- """Return an ImagePreprocessor for CPU/GPU overlap.+ def get_preprocessor(self) -> Any:+ """Return text AND image preprocessors (registered by modality).++ Registering ONLY the image preprocessor left text-only requests with+ no ``"text"`` preprocessor, so they fell through to the unbatched+ direct-call path in ``EncodePipeline`` — per-request threads spinning+ on the adapter's ``_tokenizer_lock`` with no batch formation, which is+ worse than serial under concurrency (#2874). The base+ ``CharCountPreprocessor`` (cost-only; the adapter still owns its own+ tokenization) routes text requests through ``ModelWorker`` batching,+ where ``_encode_texts`` runs the fused batch as one forward. Same+ pattern as NemoColEmbed (#1163) and the SigLIP twin.Returns:- ImagePreprocessor wrapping the CLIPProcessor, or None if not loaded.+ ``[CharCountPreprocessor, ImagePreprocessor]``, or just the text+ preprocessor if the image processor is unavailable."""+ text_preprocessor = super().get_preprocessor()if self._processor is None:- return None-- from sie_server.core.preprocessor import ImagePreprocessor+ return text_preprocessor- return ImagePreprocessor(self._processor, self._model_name_or_path)+ return [text_preprocessor, ImagePreprocessor(self._processor, self._model_name_or_path)]def unload(self) -> None:"""Shut down the preprocessing pool, then unload model weights."""diff --git a/packages/sie_server/src/sie_server/adapters/colpali/__init__.py b/packages/sie_server/src/sie_server/adapters/colpali/__init__.pyindex f2240209b..73e32f72f 100644--- a/packages/sie_server/src/sie_server/adapters/colpali/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colpali/__init__.py@@ -18,7 +18,6 @@ See: https://huggingface.co/vidore/colpali-v1.3-hffrom __future__ import annotations-import ioimport loggingimport threadingfrom pathlib import Path@@ -33,7 +32,7 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecisionfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:from PIL import Image@@ -368,18 +367,9 @@ class ColPaliAdapter(BaseAdapter):Returns:List of PIL Images."""- from PIL import Image-- pil_images = []- for img_input in item.images or []:- img_bytes = media_bytes(img_input, kind="image")- pil_img = Image.open(io.BytesIO(img_bytes))- # Convert to RGB if necessary- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")- pil_images.append(pil_img)-- return pil_images+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ return [decode_image(img_input, image_index=j) for j, img_input in enumerate(item.images or [])]def _encode_images(self, images: list[Image.Image]) -> np.ndarray:"""Encode document images into multi-vector embeddings.@@ -626,14 +616,27 @@ class ColPaliAdapter(BaseAdapter):config = MuveraConfig(**self._muvera_config) if self._muvera_config else MuveraConfig()return {"muvera": MuveraPostprocessor(token_dim=self._multivector_dim, config=config)}- def get_preprocessor(self) -> Any | None:- """Return an ImagePreprocessor for CPU/GPU overlap.+ def get_preprocessor(self) -> Any:+ """Return text AND image preprocessors (registered by modality).++ Registering ONLY the image preprocessor left text queries with no+ ``"text"`` preprocessor, so they fell through to the unbatched+ direct-call path in ``EncodePipeline`` — per-request threads+ serializing on ``_forward_lock``/``_tokenizer_lock`` with no batch+ formation, worse than serial under concurrency (#2874). The base+ ``CharCountPreprocessor`` (cost-only; the adapter still owns its own+ tokenization) routes text queries through ``ModelWorker`` batching,+ whose single inference thread makes the locks uncontended. Same+ pattern as NemoColEmbed (#1163).Returns:- ImagePreprocessor wrapping the ColPaliProcessor, or None if not loaded.+ ``[CharCountPreprocessor, ImagePreprocessor]`` (the latter+ wrapping the ColPaliProcessor), or just the text preprocessor if+ the image processor is not loaded."""+ text_preprocessor = super().get_preprocessor()if self._processor is None:- return None+ return text_preprocessorfrom transformers import ColPaliProcessor@@ -650,8 +653,11 @@ class ColPaliAdapter(BaseAdapter):# the race without a pool-wide lock (which collapsed eval throughput).return ColPaliProcessor.from_pretrained(model_name_or_path, **load_kwargs)- return ImagePreprocessor(- self._processor,- self._model_name_or_path,- processor_factory=_make_processor,- )+ return [+ text_preprocessor,+ ImagePreprocessor(+ self._processor,+ self._model_name_or_path,+ processor_factory=_make_processor,+ ),+ ]diff --git a/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py b/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.pyindex 3fa2329f8..68291a562 100644--- a/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py@@ -21,7 +21,6 @@ See: https://huggingface.co/vidore/colqwen2.5-v0.2from __future__ import annotations-import ioimport loggingimport threadingfrom pathlib import Path@@ -38,7 +37,7 @@ from sie_server.adapters._types import ComputePrecisionfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:from PIL import Image@@ -237,7 +236,16 @@ class ColQwen2Adapter(BaseAdapter):if attn_impl is not None:load_kwargs["attn_implementation"] = attn_implif self._revision is not None:- load_kwargs["revision"] = self._revision+ # The checkpoint is a PEFT adapter repo: transformers resolves+ # adapter_config.json, swaps the load target to its+ # base_model_name_or_path, and applies the TOP-LEVEL revision to+ # that base-weights download - where this repo's sha does not+ # exist (run 32963263930: "vidore/colqwen2.5-base does not appear+ # to have a file named ... model.safetensors"). adapter_kwargs+ # scopes the pin to the adapter repo's config and weights; the+ # base stays on its own default branch, exactly as it did before+ # the pin existed.+ load_kwargs["adapter_kwargs"] = {"revision": self._revision}self._model = ColQwen2_5.from_pretrained( # ty: ignore[unresolved-attribute]self._model_name_or_path,@@ -343,15 +351,9 @@ class ColQwen2Adapter(BaseAdapter):# ------------------------------------------------------------------def _load_images(self, item: Any) -> list[Image.Image]:- from PIL import Image-- pil_images = []- for img_input in item.images or []:- pil_img = Image.open(io.BytesIO(media_bytes(img_input, kind="image")))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")- pil_images.append(pil_img)- return pil_images+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ return [decode_image(img_input, image_index=j) for j, img_input in enumerate(item.images or [])]def _encode_images(self, images: list[Image.Image]) -> np.ndarray:"""Encode images using ColQwen2.5 visual prompt pattern."""@@ -498,8 +500,13 @@ class ColQwen2Adapter(BaseAdapter):config = MuveraConfig(**self._muvera_config) if self._muvera_config else MuveraConfig()return {"muvera": MuveraPostprocessor(token_dim=self._multivector_dim, config=config)}- def get_preprocessor(self) -> Any | None:+ def get_preprocessor(self) -> Any:# ColQwen2.5 handles image processing internally via _encode_images()# because Qwen2VLProcessor requires text alongside images (visual prompt prefix).- # The generic ImagePreprocessor doesn't support this pattern.- return None+ # The generic ImagePreprocessor doesn't support this pattern; image+ # batches reach the worker through the pipeline's passthrough path.+ # The base CharCountPreprocessor (cost-only; the adapter still owns its+ # own tokenization) is required so TEXT queries route through+ # ModelWorker batching instead of the unbatched direct-call path that+ # serialized per-request threads on _forward_lock (#2874).+ return super().get_preprocessor()diff --git a/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.pyindex a4ae9fa96..cd338a838 100644--- a/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py@@ -1,6 +1,5 @@from __future__ import annotations-import ioimport loggingimport threadingfrom pathlib import Path@@ -17,7 +16,7 @@ from sie_server.adapters._types import ComputePrecisionfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:from PIL import Image as PILImage@@ -275,15 +274,9 @@ class ColQwen3Adapter(BaseAdapter):# ------------------------------------------------------------------def _load_images(self, item: Any) -> list[PILImage.Image]:- from PIL import Image-- pil_images: list[PILImage.Image] = []- for img_input in item.images or []:- pil_img = Image.open(io.BytesIO(media_bytes(img_input, kind="image")))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")- pil_images.append(pil_img)- return pil_images+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ return [decode_image(img_input, image_index=j) for j, img_input in enumerate(item.images or [])]def _encode_images(self, images: list[PILImage.Image]) -> list[np.ndarray]:"""Encode a batch of images and return per-image multi-vectors."""@@ -394,8 +387,13 @@ class ColQwen3Adapter(BaseAdapter):config = MuveraConfig(**self._muvera_config) if self._muvera_config else MuveraConfig()return {"muvera": MuveraPostprocessor(token_dim=self._multivector_dim, config=config)}- def get_preprocessor(self) -> Any | None:+ def get_preprocessor(self) -> Any:# ColQwen3 uses a custom processor that handles both text and images# internally via the ColQwen3Processor; the generic ImagePreprocessor- # does not match the (text-only / image-only) call pattern.- return None+ # does not match the (text-only / image-only) call pattern, and image+ # batches reach the worker through the pipeline's passthrough path.+ # The base CharCountPreprocessor (cost-only; the adapter still owns its+ # own tokenization) is required so TEXT queries route through+ # ModelWorker batching instead of the unbatched direct-call path that+ # serialized per-request threads on _forward_lock (#2874).+ return super().get_preprocessor()diff --git a/packages/sie_server/src/sie_server/adapters/colsmol/__init__.py b/packages/sie_server/src/sie_server/adapters/colsmol/__init__.pyindex 22dcccdbb..3ca7e6e21 100644--- a/packages/sie_server/src/sie_server/adapters/colsmol/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colsmol/__init__.py@@ -29,7 +29,6 @@ See: https://huggingface.co/vidore/colSmol-256Mfrom __future__ import annotations-import ioimport loggingimport threadingfrom pathlib import Path@@ -45,7 +44,7 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecisionfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:from PIL import Image as PILImage@@ -323,15 +322,9 @@ class ColSmolAdapter(BaseAdapter):# ------------------------------------------------------------------def _load_images(self, item: Any) -> list[PILImage.Image]:- from PIL import Image-- pil_images: list[PILImage.Image] = []- for img_input in item.images or []:- pil_img = Image.open(io.BytesIO(media_bytes(img_input, kind="image")))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")- pil_images.append(pil_img)- return pil_images+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ return [decode_image(img_input, image_index=j) for j, img_input in enumerate(item.images or [])]def _encode_images(self, images: list[PILImage.Image]) -> list[np.ndarray]:"""Encode a batch of images and return per-image multi-vectors."""@@ -443,8 +436,13 @@ class ColSmolAdapter(BaseAdapter):config = MuveraConfig(**self._muvera_config) if self._muvera_config else MuveraConfig()return {"muvera": MuveraPostprocessor(token_dim=self._multivector_dim, config=config)}- def get_preprocessor(self) -> Any | None:+ def get_preprocessor(self) -> Any:# ColSmol uses the Idefics3Processor, which requires the visual prompt# text alongside images; the generic ImagePreprocessor does not match- # that call pattern (same as colqwen2/colqwen3).- return None+ # that call pattern (same as colqwen2/colqwen3), and image batches+ # reach the worker through the pipeline's passthrough path.+ # The base CharCountPreprocessor (cost-only; the adapter still owns its+ # own tokenization) is required so TEXT queries route through+ # ModelWorker batching instead of the unbatched direct-call path that+ # serialized per-request threads on _forward_lock (#2874).+ return super().get_preprocessor()diff --git a/packages/sie_server/src/sie_server/adapters/docling/adapter.py b/packages/sie_server/src/sie_server/adapters/docling/adapter.pyindex 7a10d808e..81636d573 100644--- a/packages/sie_server/src/sie_server/adapters/docling/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/docling/adapter.py@@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any, ClassVarfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.core.inference_output import ExtractItemError, ExtractOutput-from sie_server.types.inputs import is_document_input, is_image_input+from sie_server.types.inputs import InvalidMediaError, is_image_input, media_bytesfrom sie_server.types.responses import ErrorCodeif TYPE_CHECKING:@@ -48,6 +48,12 @@ _ERR_EXACTLY_ONE_IMAGE = "Docling OCR requires exactly one image per item"_ERR_CONVERSION_FAILED = "Document conversion failed"_ERR_EXPORT_FAILED = "Document export failed"+# The retained PP-OCRv4 detector covers the compact, wide catalog fixture that+# the English PP-OCRv3 detector truncates after its first word. Keep English+# recognition for word boundaries while selecting that detector from the same+# immutable artifact root.+_RAPIDOCR_PP_OCRV4_DETECTOR = Path("RapidOcr/onnx/PP-OCRv4/det/ch_PP-OCRv4_det_mobile.onnx")+def _positive_int(name: str, value: Any) -> int:if isinstance(value, bool) or not isinstance(value, int) or value <= 0:@@ -293,8 +299,18 @@ class DoclingAdapter(BaseAdapter):# that Docling's pipeline exploits; an image is the rasterized# fallback for callers that only have a page render.document = item.document- if is_document_input(document):- payload = document["data"]+ if document is not None:+ # Route document bytes through the typed media boundary rather than+ # reading ``document["data"]`` raw. ``is_document_input`` gated on+ # ``isinstance(data, bytes)``, so a base64-str ``data`` (e.g. the+ # queue path, which builds Item from an unvalidated dict) silently+ # fell to the image branch and returned the contradictory "Document+ # or image input is required". ``media_bytes`` maps that to a+ # correct typed 400 (INVALID_INPUT on both HTTP and queue paths).+ try:+ payload = media_bytes(document, kind="document")+ except InvalidMediaError as exc:+ return {}, 0, ExtractItemError(code=ErrorCode.INVALID_INPUT.value, message=str(exc))format_hint = document.get("format")else:images = item.images or []@@ -405,12 +421,15 @@ class DoclingAdapter(BaseAdapter):# pages came back word-joined ("Documentreference"). The pinned artifact# revision ships BOTH language sets, so this stays a one-line flip if the# served traffic mix ever argues for CJK.+ artifacts_path = self._artifacts_path or self._package_artifact_root+ ocr_kwargs: dict[str, Any] = {"lang": ["en"]}+ if artifacts_path is not None:+ ocr_kwargs["det_model_path"] = str(artifacts_path / _RAPIDOCR_PP_OCRV4_DETECTOR)pdf_kwargs: dict[str, Any] = {"do_ocr": ocr_enabled,"document_timeout": self._document_timeout_s,- "ocr_options": RapidOcrOptions(lang=["en"]),+ "ocr_options": RapidOcrOptions(**ocr_kwargs),}- artifacts_path = self._artifacts_path or self._package_artifact_rootif artifacts_path is not None:pdf_kwargs["artifacts_path"] = artifacts_pathif accelerator_options is not None:diff --git a/packages/sie_server/src/sie_server/adapters/donut/__init__.py b/packages/sie_server/src/sie_server/adapters/donut/__init__.pyindex 714c19f88..6ef6ce89b 100644--- a/packages/sie_server/src/sie_server/adapters/donut/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/donut/__init__.py@@ -20,7 +20,6 @@ Paper: https://arxiv.org/abs/2111.15664from __future__ import annotations-import ioimport jsonimport loggingimport re@@ -33,7 +32,7 @@ from sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.core.inference_output import EncodeOutput, ExtractOutput-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imagefrom sie_server.types.responses import Entityif TYPE_CHECKING:@@ -261,13 +260,14 @@ class DonutAdapter(BaseAdapter):# Fallback to inline preprocessingall_entities = []- for item in items:+ for i, item in enumerate(items):entities = self._extract_single(item,task=task,instruction=instruction,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)all_entities.append(entities)@@ -316,6 +316,7 @@ class DonutAdapter(BaseAdapter):instruction=None,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)all_entities.append(entities)continue@@ -369,6 +370,7 @@ class DonutAdapter(BaseAdapter):instruction: str | None,max_new_tokens: int,num_beams: int,+ item_index: int | None = None,) -> list[Entity]:"""Extract from a single item.@@ -382,18 +384,14 @@ class DonutAdapter(BaseAdapter):Returns:List of entities extracted from the item."""- from PIL import Image as PILImage-# Validate inputimages = item.imagesif not images or len(images) == 0:raise ValueError(_ERR_NO_IMAGES)- # Load image- img_bytes = media_bytes(images[0], kind="image")- pil_img = PILImage.open(io.BytesIO(img_bytes))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")+ # Load image; decode_image raises InvalidMediaError (-> 400+ # INVALID_INPUT) on non-bytes or undecodable payloads.+ pil_img = decode_image(images[0], item_index=item_index, image_index=0)# Build decoder input promptprompt = self._build_prompt(task, instruction)diff --git a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py b/packages/sie_server/src/sie_server/adapters/florence2/__init__.pyindex 958bdb486..e62070112 100644--- a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/florence2/__init__.py@@ -17,7 +17,6 @@ See: https://huggingface.co/microsoft/Florence-2-basefrom __future__ import annotations-import ioimport loggingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVar@@ -30,7 +29,7 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.core.inference_output import EncodeOutput, ExtractOutputfrom sie_server.core.preprocessor.vision import resolve_florence2_prompt-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imagefrom sie_server.types.responses import DetectedObject, Entityif TYPE_CHECKING:@@ -357,13 +356,14 @@ class Florence2Adapter(BaseAdapter):# Fallback to inline preprocessingall_entities = []all_objects = []- for item in items:+ for i, item in enumerate(items):entities, objects = self._extract_single(item,prompt=prompt,task=effective_task,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)all_entities.append(entities)all_objects.append(objects)@@ -418,6 +418,7 @@ class Florence2Adapter(BaseAdapter):task=task,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)all_entities.append(entities)all_objects.append(objects)@@ -493,6 +494,7 @@ class Florence2Adapter(BaseAdapter):task: str,max_new_tokens: int,num_beams: int,+ item_index: int | None = None,) -> tuple[list[Entity], list[DetectedObject]]:"""Extract from a single item.@@ -506,18 +508,14 @@ class Florence2Adapter(BaseAdapter):Returns:Tuple of (entities, detected_objects) extracted from the item."""- from PIL import Image as PILImage-# Validate inputimages = item.imagesif not images or len(images) == 0:raise ValueError(_ERR_NO_IMAGES)- # Load image- img_bytes = media_bytes(images[0], kind="image")- pil_img = PILImage.open(io.BytesIO(img_bytes))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")+ # Load image; decode_image raises InvalidMediaError (-> 400+ # INVALID_INPUT) on non-bytes or undecodable payloads.+ pil_img = decode_image(images[0], item_index=item_index, image_index=0)image_size = (pil_img.width, pil_img.height)diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.pyindex 1cd46a135..18e1fde31 100644--- a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py@@ -146,7 +146,7 @@ class GLiClassAdapter(BaseAdapter):# cap inputs at the model's position-embedding limit. Without this the# library defaults to 1024, which exceeds the 512-token capacity of the# current GLiClass models and causes argmax-on-empty-tensor crashes for- # long inputs (see sie-test#88, sie-test#89).+ # long inputs.pipeline_kwargs: dict[str, Any] = {"model": model,"tokenizer": self._tokenizer,@@ -303,7 +303,7 @@ class GLiClassAdapter(BaseAdapter):# signatures as InputTooLongError (validation) instead of leaking as# 500 INFERENCE_ERROR. Match must be specific to avoid swallowing# unrelated errors. Catalog of caught signatures:- # - RuntimeError "argmax(): ... numel() == 0" (sie-test#89 / #848)+ # - RuntimeError "argmax(): ... numel() == 0"# torch.argmax on an empty tensor inside the classification head.# - IndexError "index N is out of bounds for dimension D with size N"# (index == size: off-by-one / exhausted dimension). Covers both thediff --git a/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py b/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.pyindex 803ca504c..8e9fc2435 100644--- a/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py@@ -1,7 +1,6 @@from __future__ import annotationsimport gc-import ioimport loggingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal@@ -11,7 +10,7 @@ import torchfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDimsfrom sie_server.core.inference_output import EncodeOutput, ExtractOutput-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imagefrom sie_server.types.responses import Entityif TYPE_CHECKING:@@ -260,12 +259,13 @@ class GlmOcrAdapter(ModelAdapter):)all_entities = []- for item in items:+ for i, item in enumerate(items):entities = self._extract_single(item,instruction=instruction,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)all_entities.append(entities)@@ -306,6 +306,7 @@ class GlmOcrAdapter(ModelAdapter):instruction=None,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)all_entities.append(entities)continue@@ -339,6 +340,7 @@ class GlmOcrAdapter(ModelAdapter):instruction: str | None,max_new_tokens: int,num_beams: int,+ item_index: int | None = None,) -> list[Entity]:"""Extract from a single item.@@ -351,16 +353,13 @@ class GlmOcrAdapter(ModelAdapter):Returns:List of entities extracted from the item."""- from PIL import Image as PILImage-images = item.imagesif not images or len(images) == 0:raise ValueError(_ERR_NO_IMAGES)- img_bytes = media_bytes(images[0], kind="image")- pil_img = PILImage.open(io.BytesIO(img_bytes))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads.+ pil_img = decode_image(images[0], item_index=item_index, image_index=0)text = instruction or self._user_textmessages = [diff --git a/packages/sie_server/src/sie_server/adapters/grounding_dino/adapter.py b/packages/sie_server/src/sie_server/adapters/grounding_dino/adapter.pyindex a2a11840c..4ab2dcc30 100644--- a/packages/sie_server/src/sie_server/adapters/grounding_dino/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/grounding_dino/adapter.py@@ -28,12 +28,10 @@ See: https://huggingface.co/docs/transformers/model_doc/grounding-dinofrom __future__ import annotationsimport logging-from io import BytesIOfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVarimport torch-from PIL import Image as PILImagefrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpec@@ -41,7 +39,7 @@ from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.core.inference_output import EncodeOutput, ExtractOutputfrom sie_server.core.preprocessor import DetectionPreprocessorfrom sie_server.core.preprocessor.vision import collect_detection_prepared_items-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imagefrom sie_server.types.responses import DetectedObjectif TYPE_CHECKING:@@ -234,7 +232,7 @@ class GroundingDINOAdapter(BaseAdapter):image_indices: list[int] = []for idx, item in enumerate(items):- img = self._extract_image(item)+ img = self._extract_image(item, item_index=idx)if img is not None:images.append(img)image_indices.append(idx)@@ -378,7 +376,7 @@ class GroundingDINOAdapter(BaseAdapter):return objects- def _extract_image(self, item: Item) -> Image | None:+ def _extract_image(self, item: Item, *, item_index: int | None = None) -> Image | None:"""Extract PIL Image from item.Expects ImageInput format (SDK wire format with .data bytes).@@ -393,10 +391,9 @@ class GroundingDINOAdapter(BaseAdapter):if not isinstance(img, dict) or "data" not in img:return None- pil_img = PILImage.open(BytesIO(media_bytes(img, kind="image")))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")- return pil_img+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ return decode_image(img, item_index=item_index, image_index=0)def get_preprocessor(self) -> Any | None:"""Return preprocessor for CPU/GPU overlap.diff --git a/packages/sie_server/src/sie_server/adapters/lighton_ocr/adapter.py b/packages/sie_server/src/sie_server/adapters/lighton_ocr/adapter.pyindex 5a66a00e9..923a9e631 100644--- a/packages/sie_server/src/sie_server/adapters/lighton_ocr/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/lighton_ocr/adapter.py@@ -1,7 +1,6 @@from __future__ import annotationsimport gc-import ioimport loggingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal@@ -13,7 +12,7 @@ from sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDimsfrom sie_server.core.inference_output import EncodeOutput, ExtractOutputfrom sie_server.core.prepared import LightOnOCRPayload, PreparedItemfrom sie_server.core.preprocessor import LightOnOCRPreprocessor-from sie_server.types.inputs import InvalidMediaError, media_bytes+from sie_server.types.inputs import InvalidMediaError, decode_imagefrom sie_server.types.responses import Entityif TYPE_CHECKING:@@ -282,12 +281,13 @@ class LightOnOCRAdapter(ModelAdapter):)all_entities = []- for item in items:+ for i, item in enumerate(items):entities = self._extract_single(item,instruction=instruction,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)all_entities.append(entities)@@ -337,6 +337,7 @@ class LightOnOCRAdapter(ModelAdapter):instruction=None,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)# Sub-batch to bound KV-cache / vision-activation memory (issue #33, decoder-batching KV-OOM): a large@@ -434,6 +435,7 @@ class LightOnOCRAdapter(ModelAdapter):instruction: str | None,max_new_tokens: int,num_beams: int,+ item_index: int | None = None,) -> list[Entity]:"""Extract from a single item.@@ -446,16 +448,13 @@ class LightOnOCRAdapter(ModelAdapter):Returns:List of entities extracted from the item."""- from PIL import Image as PILImage-images = item.imagesif not images or len(images) == 0:raise ValueError(_ERR_NO_IMAGES)- img_bytes = media_bytes(images[0], kind="image")- pil_img = PILImage.open(io.BytesIO(img_bytes))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads.+ pil_img = decode_image(images[0], item_index=item_index, image_index=0)messages = self._build_messages(instruction)diff --git a/packages/sie_server/src/sie_server/adapters/mineru_vl/__init__.py b/packages/sie_server/src/sie_server/adapters/mineru_vl/__init__.pyindex d8371c8ac..e95f121c9 100644--- a/packages/sie_server/src/sie_server/adapters/mineru_vl/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/mineru_vl/__init__.py@@ -1,6 +1,5 @@from __future__ import annotations-import ioimport loggingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVar@@ -11,7 +10,7 @@ from sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.core.inference_output import EncodeOutput, ExtractOutput-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imagefrom sie_server.types.responses import Entityif TYPE_CHECKING:@@ -292,13 +291,14 @@ class MinerUVLAdapter(BaseAdapter):)all_entities = []- for item in items:+ for i, item in enumerate(items):entities = self._extract_single(item,task=task,instruction=instruction,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)all_entities.append(entities)return ExtractOutput(entities=all_entities)@@ -326,6 +326,7 @@ class MinerUVLAdapter(BaseAdapter):instruction=instruction,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,))continue@@ -362,17 +363,15 @@ class MinerUVLAdapter(BaseAdapter):instruction: str | None,max_new_tokens: int,num_beams: int,+ item_index: int | None = None,) -> list[Entity]:- from PIL import Image as PILImage-images = item.imagesif not images:raise ValueError(_ERR_NO_IMAGES)- img_bytes = media_bytes(images[0], kind="image")- pil_img = PILImage.open(io.BytesIO(img_bytes))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads.+ pil_img = decode_image(images[0], item_index=item_index, image_index=0)messages = self._build_messages(task=task, instruction=instruction)text = self._processor.apply_chat_template(diff --git a/packages/sie_server/src/sie_server/adapters/mlx/_server.py b/packages/sie_server/src/sie_server/adapters/mlx/_server.pyindex 9e0100dff..24b355eb8 100644--- a/packages/sie_server/src/sie_server/adapters/mlx/_server.py+++ b/packages/sie_server/src/sie_server/adapters/mlx/_server.py@@ -60,6 +60,7 @@ STARTUP_TIMEOUT_ENV_VARS = (HEALTH_CHECK_INTERVAL_S = 2.0ERR_SERVER_STARTUP = "MLX server failed to start within timeout"+ERR_SERVER_CRASH = "MLX server process exited during startup"ERR_WARMUP_FAILED = "MLX server started but the model failed to warm up (could not serve a test completion)"@@ -124,6 +125,21 @@ def find_free_port(start_port: int = BASE_PORT) -> int:raise RuntimeError(msg)+def release_port(port: int | None) -> None:+ """Return a port handed out by :func:`find_free_port` to the pool.++ Adapters call this from every teardown seam — ``unload()`` and the+ failed-load abort paths — once the MLX child no longer owns the port.+ Idempotent and tolerant: releasing ``None`` or a never-reserved port is+ a no-op, so teardown paths can call it unconditionally. Mirrors+ ``sglang/_server.py``.+ """+ if port is None:+ return+ with _RESERVED_PORTS_LOCK:+ _RESERVED_PORTS.discard(port)++def open_output_log(prefix: str = "mlx_") -> tempfile._TemporaryFileWrapper:"""Open a named temp file for capturing subprocess stdout/stderr."""return tempfile.NamedTemporaryFile(mode="w", prefix=prefix, suffix=".log", delete=False)diff --git a/packages/sie_server/src/sie_server/adapters/mlx/generation.py b/packages/sie_server/src/sie_server/adapters/mlx/generation.pyindex b5a988261..4080a9668 100644--- a/packages/sie_server/src/sie_server/adapters/mlx/generation.py+++ b/packages/sie_server/src/sie_server/adapters/mlx/generation.py@@ -11,7 +11,7 @@ Metal-memory isolation.Selection is automatic: :meth:`SGLangGenerationAdapter.create_for_device`swaps to this adapter on any non-CUDA device, so unsuffixed generation models-"just work" on a Mac (served via ``mise run serve -b sglang``).+"just work" on a Mac (served via ``mise run serve -- -b sglang``).Streaming async-iterator contract (same as the SGLang adapter). The adapteropens an HTTP streaming connection to the child's OpenAI-compatible@@ -149,6 +149,7 @@ class MLXGenerationAdapter(GenerationAdapter):self._process: subprocess.Popen[bytes] | None = Noneself._server_url: str | None = None+ self._port: int | None = Noneself._device: str | None = Noneself._output_file: tempfile._TemporaryFileWrapper | None = None# Single-flight lock: mlx_lm.server is single-tenant and the cancellation@@ -200,7 +201,7 @@ class MLXGenerationAdapter(GenerationAdapter):raise RuntimeError("mlx-lm is not installed in this environment; the Apple-Silicon generation ""backend requires it. Serve generation with the 'sglang' bundle "- "(`mise run serve -b sglang`), which installs mlx-lm on macOS."+ "(`mise run serve -- -b sglang`), which installs mlx-lm on macOS.")# Defensive: a prior load that left a live subprocess would be orphaned (it# survives in its own session, holding its port + Metal memory). Tear it down@@ -209,44 +210,60 @@ class MLXGenerationAdapter(GenerationAdapter):self.unload()self._device = deviceport = _server.find_free_port()+ self._port = portself._server_url = f"http://127.0.0.1:{port}"- cmd = _server.build_launch_command(mlx_repo=mlx_repo, port=port)- logger.info(- "Starting MLX generation server for %s (repo=%s) on device=%s at port %d",- self._model_name_or_path,- self._mlx_repo,- device,- port,- )- logger.info("Loading model %s via MLX (first run downloads weights — this can take minutes)…", self._mlx_repo)-- self._output_file = _server.open_output_log()- self._process = _server.launch_mlx_server(cmd, output_file=self._output_file)-- # One budget covers BOTH health-readiness and the model-load warmup below, so a- # slow health bind can't let warmup tack on a second full timeout.- budget = _server.resolve_startup_timeout(self._startup_timeout_s)- started = time.monotonic()- if not _server.wait_for_server(- self._server_url,- self._process,- output_file=self._output_file,- timeout_s=budget,- ):- self._abort_failed_load()- raise RuntimeError(_server.ERR_SERVER_STARTUP)-- # mlx_lm.server answers /health as soon as httpd is up, possibly before the model- # finishes loading. Warm it up with a 1-token request so the cold model load- # completes inside load() (deterministic readiness) and the user's first real request- # is fast. Use the REMAINING budget so wait+warmup stay within one timeout. A failed- # warmup means the child bound the port but cannot serve the model, so treat it as a- # load failure rather than reporting "ready" and handing the error to the first request.- warmup_budget = max(30.0, budget - (time.monotonic() - started))- if not _server.warmup_model(self._server_url, mlx_repo, timeout_s=warmup_budget):+ # Everything past the port reservation runs under abort-on-failure: the+ # port (and, once opened, the log fd) belong to this adapter from here+ # on, and a raise anywhere below — a full /tmp in open_output_log, a+ # failed exec, a cancelled load — must hand them back rather than leak+ # one slot of the 100-port span per attempt.+ try:+ cmd = _server.build_launch_command(mlx_repo=mlx_repo, port=port)+ logger.info(+ "Starting MLX generation server for %s (repo=%s) on device=%s at port %d",+ self._model_name_or_path,+ self._mlx_repo,+ device,+ port,+ )+ logger.info(+ "Loading model %s via MLX (first run downloads weights — this can take minutes)…", self._mlx_repo+ )++ self._output_file = _server.open_output_log()+ self._process = _server.launch_mlx_server(cmd, output_file=self._output_file)++ # One budget covers BOTH health-readiness and the model-load warmup below, so a+ # slow health bind can't let warmup tack on a second full timeout.+ budget = _server.resolve_startup_timeout(self._startup_timeout_s)+ started = time.monotonic()+ if not _server.wait_for_server(+ self._server_url,+ self._process,+ output_file=self._output_file,+ timeout_s=budget,+ ):+ # A child that died is a crash, not a timeout: keep the+ # messages distinct so the loader's timeout reclassification+ # never stamps a crash's elapsed time as the configured budget.+ crash_exit_code = self._process.poll()+ if crash_exit_code is not None:+ raise RuntimeError(f"{_server.ERR_SERVER_CRASH} (exit code {crash_exit_code})")+ raise RuntimeError(_server.ERR_SERVER_STARTUP)++ # mlx_lm.server answers /health as soon as httpd is up, possibly before the model+ # finishes loading. Warm it up with a 1-token request so the cold model load+ # completes inside load() (deterministic readiness) and the user's first real request+ # is fast. Use the REMAINING budget so wait+warmup stay within one timeout. A failed+ # warmup means the child bound the port but cannot serve the model, so treat it as a+ # load failure rather than reporting "ready" and handing the error to the first request.+ warmup_budget = max(30.0, budget - (time.monotonic() - started))+ if not _server.warmup_model(self._server_url, mlx_repo, timeout_s=warmup_budget):+ raise RuntimeError(_server.ERR_WARMUP_FAILED)+ except BaseException:self._abort_failed_load()- raise RuntimeError(_server.ERR_WARMUP_FAILED)+ raiselogger.info("MLX generation server ready: %s at %s", self._model_name_or_path, self._server_url)@@ -254,11 +271,14 @@ class MLXGenerationAdapter(GenerationAdapter):"""Tear down a partially-started child + reset state after a failed load.The registry does not call unload() on a failed load, so this mirrors unload():- terminate the child, drop the temp log, and clear _server_url/_device so the adapter- does not look "loaded" (_check_loaded() gates only on _server_url).+ terminate the child, release its reserved port, drop the temp log, and clear+ _server_url/_device so the adapter does not look "loaded" (_check_loaded()+ gates only on _server_url)."""_server.terminate_process(self._process)self._process = None+ _server.release_port(self._port)+ self._port = Noneself._server_url = Noneself._device = Noneself._cleanup_output_log()@@ -268,6 +288,10 @@ class MLXGenerationAdapter(GenerationAdapter):logger.info("Shutting down MLX generation server for %s", self._model_name_or_path)_server.terminate_process(self._process)self._process = None+ # Release only after the child is down so a concurrent load can't be+ # handed a port the dying child still holds bound.+ _server.release_port(self._port)+ self._port = Noneself._server_url = Noneself._device = Noneself._cleanup_output_log()diff --git a/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py b/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.pyindex bd5ed0449..c9e1f4a40 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@@ -24,7 +24,6 @@ See: https://huggingface.co/nvidia/llama-nemoretriever-colembed-3b-v1from __future__ import annotations-import ioimport loggingimport threadingfrom pathlib import Path@@ -40,7 +39,7 @@ from sie_server.adapters._types import ComputePrecisionfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.postprocessor import MuveraConfig, MuveraPostprocessor-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:from sie_server.types.inputs import Item@@ -491,20 +490,16 @@ class NemoColEmbedAdapter(BaseAdapter):Returns:EncodeOutput with multivector embeddings."""- from PIL import Image-# Item is a TypedDict (dict) - no instance check neededpil_images = []- for item in items:+ for i, item in enumerate(items):if not item.images or len(item.images) == 0:raise ValueError(_ERR_NO_INPUT)- # Load first image from each item (ImageInput is also a TypedDict)- img_bytes = media_bytes(item.images[0], kind="image")- pil_img = Image.open(io.BytesIO(img_bytes))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")- pil_images.append(pil_img)+ # Load first image from each item; decode_image raises+ # InvalidMediaError (-> 400 INVALID_INPUT) on non-bytes or+ # undecodable payloads, and converts to RGB.+ pil_images.append(decode_image(item.images[0], item_index=i, image_index=0))# v2 exposes ``forward_images`` (Qwen3-VL backbone); v1 exposes ``forward_passages``.forward = getattr(self._model, "forward_images", None) or self._model.forward_passagesdiff --git a/packages/sie_server/src/sie_server/adapters/owlv2/adapter.py b/packages/sie_server/src/sie_server/adapters/owlv2/adapter.pyindex c9dc0818c..b556217db 100644--- a/packages/sie_server/src/sie_server/adapters/owlv2/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/owlv2/adapter.py@@ -29,12 +29,10 @@ See: https://huggingface.co/docs/transformers/model_doc/owlv2from __future__ import annotationsimport logging-from io import BytesIOfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVarimport torch-from PIL import Image as PILImagefrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpec@@ -42,7 +40,7 @@ from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.core.inference_output import EncodeOutput, ExtractOutputfrom sie_server.core.preprocessor import DetectionPreprocessorfrom sie_server.core.preprocessor.vision import collect_detection_prepared_items-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imagefrom sie_server.types.responses import DetectedObjectif TYPE_CHECKING:@@ -228,7 +226,7 @@ class Owlv2Adapter(BaseAdapter):image_indices: list[int] = []for idx, item in enumerate(items):- img = self._extract_image(item)+ img = self._extract_image(item, item_index=idx)if img is not None:images.append(img)image_indices.append(idx)@@ -391,7 +389,7 @@ class Owlv2Adapter(BaseAdapter):return objects- def _extract_image(self, item: Item) -> Image | None:+ def _extract_image(self, item: Item, *, item_index: int | None = None) -> Image | None:"""Extract PIL Image from item.Expects ImageInput format (SDK wire format with .data bytes).@@ -406,10 +404,9 @@ class Owlv2Adapter(BaseAdapter):if not isinstance(img, dict) or "data" not in img:return None- pil_img = PILImage.open(BytesIO(media_bytes(img, kind="image")))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")- return pil_img+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ return decode_image(img, item_index=item_index, image_index=0)def get_preprocessor(self) -> Any | None:"""Return preprocessor for CPU/GPU overlap.diff --git a/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py b/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.pyindex e5193a957..023cd00e6 100644--- a/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py@@ -1,6 +1,5 @@from __future__ import annotations-import ioimport loggingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVar@@ -13,7 +12,7 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutput, ExtractOutput-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imagefrom sie_server.types.responses import Entityif TYPE_CHECKING:@@ -25,7 +24,7 @@ _ERR_NO_IMAGES = "PaddleOCRVLAdapter requires image input for extraction"_ERR_ENCODE_NOT_SUPPORTED = "PaddleOCRVLAdapter does not support encode(). Use extract() instead."_ERR_FP16_UNSUPPORTED = "PaddleOCR-VL does not support float16 on CUDA (config pins bfloat16); use bfloat16 or float32."-# Canonical task -> prompt mapping from the PaddleOCR-VL model card.+# Canonical task -> prompt mapping from the PaddleOCR-VL-1.5 model card.# Keep in sync with preprocessor/vision.py::_PADDLEOCR_VL_TASK_PROMPTS._TASK_PROMPTS: dict[str, str] = {"ocr": "OCR:",@@ -44,8 +43,8 @@ _COMPAT_PATCHED_ATTR = "_sie_paddleocr_vl_compat_patched"def _apply_transformers_compat_shim() -> None:"""Bridge a parameter rename so PaddleOCR-VL's modeling code loads.- PaddleOCR-VL's custom modeling code (byte-identical across the pinned 1.5- and 1.6 revisions) calls+ PaddleOCR-VL-1.5's custom modeling code (pinned at revision+ 6819afc8509ac9afa50e91b34627a7cf8f7900bb) calls``transformers.masking_utils.create_causal_mask(inputs_embeds=...)``,but the signature in transformers 4.57.x uses ``input_embeds`` (singular).Without this shim, ``model.generate()`` raises:@@ -76,9 +75,9 @@ def _apply_transformers_compat_shim() -> None:class PaddleOCRVLAdapter(BaseAdapter):- """Adapter for the PaddlePaddle/PaddleOCR-VL OCR VLMs (1.5, 1.6).+ """Adapter for PaddlePaddle/PaddleOCR-VL-1.5 OCR VLM.- PaddleOCR-VL is a 0.9B-param autoregressive VLM combining a NaViT-style+ PaddleOCR-VL-1.5 is a 0.9B-param autoregressive VLM combining a NaViT-styleSigLIP vision encoder with an ERNIE-4.5-0.3B decoder. Supports 109languages and six task modes: ocr, table, formula, chart, spotting, seal.@@ -280,13 +279,14 @@ class PaddleOCRVLAdapter(BaseAdapter):)all_entities = []- for item in items:+ for i, item in enumerate(items):entities = self._extract_single(item,task=task,instruction=instruction,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,)all_entities.append(entities)return ExtractOutput(entities=all_entities)@@ -314,6 +314,7 @@ class PaddleOCRVLAdapter(BaseAdapter):instruction=instruction,max_new_tokens=max_new_tokens,num_beams=num_beams,+ item_index=i,))continue@@ -349,17 +350,15 @@ class PaddleOCRVLAdapter(BaseAdapter):instruction: str | None,max_new_tokens: int,num_beams: int,+ item_index: int | None = None,) -> list[Entity]:- from PIL import Image as PILImage-images = item.imagesif not images:raise ValueError(_ERR_NO_IMAGES)- img_bytes = media_bytes(images[0], kind="image")- pil_img = PILImage.open(io.BytesIO(img_bytes))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads.+ pil_img = decode_image(images[0], item_index=item_index, image_index=0)messages = self._build_messages(task=task, instruction=instruction)text = self._processor.apply_chat_template(diff --git a/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.pyindex 92dbdc6d8..352680bfa 100644--- a/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py@@ -1,6 +1,5 @@from __future__ import annotations-import ioimport loggingimport unicodedatafrom pathlib import Path@@ -16,7 +15,7 @@ from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.video_frames import extract_frames-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:from PIL import Image@@ -428,18 +427,11 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):# ------------------------------------------------------------------def _load_images(self, item: Any) -> list[Image.Image]:- from PIL import Image-- pil_images = []- for idx, img_input in enumerate(item.images or []):- try:- pil_img = Image.open(io.BytesIO(media_bytes(img_input, kind="image")))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")- pil_images.append(pil_img)- except (OSError, KeyError) as exc:- logger.warning("Failed to load image %d: %s", idx, exc)- return pil_images+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB. Faulting+ # matches the video half (an undecodable video raises VideoDecodeError)+ # instead of silently embedding without the image the caller sent.+ return [decode_image(img_input, image_index=j) for j, img_input in enumerate(item.images or [])]def _extract_video_frames(self, item: Any) -> list[Image.Image]:"""Sample frames from the item's video, as image content parts.@@ -500,9 +492,14 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):counts[position] = countreturn counts- def get_preprocessor(self) -> Any | None:+ def get_preprocessor(self) -> Any:# Qwen3-VL processor requires text alongside images (for chat template# token insertion). The generic ImagePreprocessor calls processor(images=...)- # without text, which crashes Qwen3VLProcessor. Return None to use the- # direct adapter call path where we handle the conversation template.- return None+ # without text, which crashes Qwen3VLProcessor — so no image+ # preprocessor; image batches reach the worker through the pipeline's+ # passthrough path and the adapter handles the conversation template.+ # The base CharCountPreprocessor (cost-only; the adapter still owns its+ # own tokenization) is required so TEXT requests route through+ # ModelWorker batching instead of the unbatched direct-call path+ # (#2874).+ return super().get_preprocessor()diff --git a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/adapter.py b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/adapter.pyindex 0f7029f45..cbecf1272 100644--- a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/adapter.py@@ -1,7 +1,6 @@from __future__ import annotationsimport inspect-import ioimport loggingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVar@@ -14,7 +13,7 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecisionfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import ScoreOutput-from sie_server.types.inputs import InvalidInputError, InvalidMediaError, media_bytes+from sie_server.types.inputs import InvalidInputError, InvalidMediaError, decode_imageif TYPE_CHECKING:from PIL import Image@@ -710,17 +709,9 @@ class Qwen3VLRerankerAdapter(BaseAdapter):raise InvalidInputError(_ERR_NO_INPUT)def _load_first_image(self, item: Any) -> Image.Image:- from PIL import Image-- img_input = item.images[0]- try:- with Image.open(io.BytesIO(media_bytes(img_input, kind="image"))) as source:- source.load()- return source.convert("RGB") if source.mode != "RGB" else source.copy()- except InvalidMediaError:- raise- except (OSError, ValueError) as exc:- raise InvalidMediaError("image input must contain a valid decodable image") from exc+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ return decode_image(item.images[0], image_index=0)def get_preprocessor(self) -> Any | None:# Qwen3-VL processor requires text alongside images (for chat templatediff --git a/packages/sie_server/src/sie_server/adapters/sglang/_server.py b/packages/sie_server/src/sie_server/adapters/sglang/_server.pyindex 0e651b077..1c74db9b3 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/_server.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/_server.py@@ -12,6 +12,8 @@ lifecycle of a single SGLang HTTP server child process.from __future__ import annotations+import hashlib+import importlib.metadataimport loggingimport mathimport os@@ -19,6 +21,7 @@ import randomimport signalimport socketimport subprocess+import sysimport tempfileimport threadingimport time@@ -54,14 +57,114 @@ STARTUP_TIMEOUT_ENV_VARS = ("SIE_SERVER_STARTUP_TIMEOUT_S",)LIVENESS_BUDGET_ENV_VAR = "SIE_WORKER_LIVENESS_BUDGET_S"+KERNEL_CACHE_ROOT_ENV_VAR = "SIE_SGLANG_KERNEL_CACHE_ROOT"STARTUP_TIMEOUT_S = DEFAULT_STARTUP_TIMEOUT_SHEALTH_CHECK_INTERVAL_S = 2.0BASE_PORT = 30000 # Starting port for SGLang serversERR_SERVER_STARTUP = "SGLang server failed to start within timeout"+ERR_SERVER_CRASH = "SGLang server process exited during startup"STARTUP_LOG_TAIL_CHARS = 5000LOAD_HEADROOM_BYTES = 1024**3+_KERNEL_CACHE_LAYOUT_VERSION = "v1"+_JIT_ABI_PACKAGES = (+ "apache-tvm-ffi",+ "cuda-python",+ "flashinfer-cubin",+ "flashinfer-python",+ "nvidia-cuda-nvrtc-cu12",+ "nvidia-cuda-nvrtc-cu13",+ "nvidia-cuda-runtime-cu12",+ "nvidia-cuda-runtime-cu13",+ "sgl-deep-gemm",+ "sglang",+ "sglang-kernel",+ "torch",+ "triton",+ "xgrammar",+)+_KERNEL_CACHE_DIRS = {+ "CUDA_CACHE_PATH": "cuda",+ "CUTE_DSL_CACHE_DIR": "cutlass",+ "FLASHINFER_WORKSPACE_BASE": "flashinfer",+ "SGLANG_CACHE_DIR": "sglang",+ "SGLANG_DG_CACHE_DIR": "deep-gemm",+ "TORCHINDUCTOR_CACHE_DIR": "torchinductor",+ "TRITON_CACHE_DIR": "triton",+ "XDG_CACHE_HOME": "xdg",+}+++def _installed_jit_abi_key() -> str:+ components = [f"python={sys.version_info.major}.{sys.version_info.minor}"]+ for package in _JIT_ABI_PACKAGES:+ try:+ version = importlib.metadata.version(package)+ except importlib.metadata.PackageNotFoundError:+ version = "missing"+ components.append(f"{package}={version}")+ return hashlib.sha256("\n".join(components).encode()).hexdigest()[:20]+++def _gpu_cache_key(device_index: int) -> str | None:+ try:+ result = subprocess.run(+ ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], # noqa: S607+ capture_output=True,+ check=True,+ text=True,+ timeout=5,+ )+ device_names = [line.strip() for line in result.stdout.splitlines() if line.strip()]+ device_name = device_names[device_index]+ except (FileNotFoundError, IndexError, OSError, subprocess.SubprocessError) as exc:+ logger.warning(+ "SGLang kernel cache disabled: could not identify cuda:%d without CUDA init: %s", device_index, exc+ )+ return None++ device_digest = hashlib.sha256(device_name.encode()).hexdigest()[:12]+ return f"gpu-{device_digest}"+++def _kernel_cache_env(env: dict[str, str], *, device_index: int) -> dict[str, str]:+ """Return missing upstream cache variables for one persistent cache root.++ Cache namespaces include the installed JIT ABI and exact GPU product name. This+ prevents a retained local/PVC cache from serving artifacts compiled by a+ different SGLang/Torch/CUDA closure or GPU class. Explicit upstream cache+ variables always win, and any cache setup failure falls back to SGLang's+ ordinary container-local compilation path.+ """+ raw_root = env.get(KERNEL_CACHE_ROOT_ENV_VAR, "").strip()+ if not raw_root:+ return {}++ root = Path(raw_root).expanduser()+ if not root.is_absolute():+ logger.warning("SGLang kernel cache disabled: %s must be an absolute path", KERNEL_CACHE_ROOT_ENV_VAR)+ return {}++ gpu_key = _gpu_cache_key(device_index)+ if gpu_key is None:+ return {}++ namespace = root / _KERNEL_CACHE_LAYOUT_VERSION / _installed_jit_abi_key() / gpu_key / f"device-{device_index}"+ defaults = {name: str(namespace / suffix) for name, suffix in _KERNEL_CACHE_DIRS.items() if not env.get(name)}+ if not defaults:+ return {}+ try:+ for path in defaults.values():+ Path(path).mkdir(parents=True, exist_ok=True)+ with tempfile.NamedTemporaryFile(dir=namespace, prefix=".sie-write-probe-"):+ pass+ except OSError as exc:+ logger.warning("SGLang kernel cache disabled: cannot prepare %s: %s", namespace, exc)+ return {}+ logger.info("SGLang kernel cache enabled at %s", namespace)+ return defaults+def _resolve_liveness_budget() -> float | None:raw = os.environ.get(LIVENESS_BUDGET_ENV_VAR)@@ -133,9 +236,11 @@ def find_free_port(start_port: int = BASE_PORT) -> int:the same port in the same order. The race against *external* processes(outside this interpreter) remains inherent — there is no way toatomically reserve a TCP port without holding it open — but the common- in-process collision is closed. Reserved ports leak intentionally:- once handed out a port stays excluded for the process lifetime (the- range is 100 ports; a worker hosts a handful of SGLang servers).+ in-process collision is closed. Callers must return the port via+ :func:`release_port` once the child no longer owns it (unload or a+ failed launch); otherwise the 100-port span exhausts under the+ registry's LRU eviction→reload churn and every subsequent load fails+ until the process restarts."""span = 100offset = random.randrange(span) # noqa: S311 — port selection, not crypto@@ -155,6 +260,20 @@ def find_free_port(start_port: int = BASE_PORT) -> int:raise RuntimeError(msg)+def release_port(port: int | None) -> None:+ """Return a port handed out by :func:`find_free_port` to the pool.++ Adapters call this from every teardown seam — ``unload()`` and the+ failed-load abort paths — once the SGLang child no longer owns the port.+ Idempotent and tolerant: releasing ``None`` or a never-reserved port is+ a no-op, so teardown paths can call it unconditionally.+ """+ if port is None:+ return+ with _RESERVED_PORTS_LOCK:+ _RESERVED_PORTS.discard(port)++def parse_device_index(device: str) -> int:"""Parse device index from device string (e.g. ``"cuda:0"`` → ``0``)."""if device in {"cuda", "cpu"}:@@ -203,6 +322,8 @@ def launch_sglang_server(env["CUDA_VISIBLE_DEVICES"] = str(device_index)if extra_env:env.update(extra_env)+ for name, value in _kernel_cache_env(env, device_index=device_index).items():+ env.setdefault(name, value)logger.info("SGLang subprocess output will be logged to: %s", output_file.name)return subprocess.Popen( # noqa: S603 — intentional subprocess callcmd,@@ -276,12 +397,24 @@ def read_subprocess_output_tail(output_file: tempfile._TemporaryFileWrapper | Noreturn f"<failed to read SGLang log: {exc}>"-def startup_failure_error(output_file: tempfile._TemporaryFileWrapper | None) -> RuntimeError:+def startup_failure_error(+ output_file: tempfile._TemporaryFileWrapper | None,+ crash_exit_code: int | None = None,+) -> RuntimeError:+ """Build the startup-failure error, keeping crash and timeout distinct.++ A child process that died must not be reported as a timeout: the loader+ reclassifies timeout-shaped messages as ModelLoadTimeoutError stamped with+ the elapsed time, so a 16.5s engine crash surfaces as "configured=16s"+ while the real budget was 1800s (run 32945082497) and every triage starts+ from a fictional number. Callers pass the pre-terminate ``poll()`` result+ as ``crash_exit_code``; None means the health poll genuinely timed out.+ """+ prefix = f"{ERR_SERVER_CRASH} (exit code {crash_exit_code})" if crash_exit_code is not None else ERR_SERVER_STARTUPoutput = read_subprocess_output_tail(output_file).strip()- if output:- if is_oom_error(RuntimeError(output)):- return RuntimeError(f"{ERR_SERVER_STARTUP}: out of memory detected in startup log")- return RuntimeError(ERR_SERVER_STARTUP)+ if output and is_oom_error(RuntimeError(output)):+ return RuntimeError(f"{prefix}: out of memory detected in startup log")+ return RuntimeError(prefix)def estimate_load_required_memory_bytes(diff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.pyindex 9d0405ca3..45dff3feb 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py@@ -16,6 +16,7 @@ Engine API to avoid event loop conflicts with uvicorn/uvloop.from __future__ import annotations+import contextlibimport loggingimport mathimport os@@ -191,6 +192,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):self._process: subprocess.Popen[bytes] | None = Noneself._server_url: str | None = None+ self._port: int | None = None# Shared HTTP client + thread pool for concurrent POSTs to SGLang. Only# populated (in ``load``) when concurrency > 1; a single-post encode# keeps using module-level ``requests.post`` so the concurrency=1 A/B@@ -239,6 +241,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):device_index = _server.parse_device_index(device)port = _server.find_free_port()+ self._port = portself._server_url = f"http://localhost:{port}"logger.info(@@ -293,18 +296,29 @@ class SGLangEmbeddingAdapter(BaseAdapter):list(self._lora_paths.keys()),)- self._output_file = _server.open_output_log()- self._process = _server.launch_sglang_server(cmd, device_index=device_index, output_file=self._output_file)-- if not _server.wait_for_server(- self._server_url,- self._process,- output_file=self._output_file,- timeout_s=self._startup_timeout_s,- ):- _server.terminate_process(self._process)- self._process = None- raise _server.startup_failure_error(self._output_file)+ # The port (and, once opened, the log fd) belong to this adapter from+ # the reservation above onward, so every raise below hands them back+ # rather than leaking one slot of the 100-port span per attempt: a full+ # /tmp in open_output_log, a failed exec, or a cancelled load included.+ try:+ self._output_file = _server.open_output_log()+ self._process = _server.launch_sglang_server(cmd, device_index=device_index, output_file=self._output_file)++ if not _server.wait_for_server(+ self._server_url,+ self._process,+ output_file=self._output_file,+ timeout_s=self._startup_timeout_s,+ ):+ # Capture crash-vs-timeout before terminate makes poll() ambiguous.+ crash_exit_code = self._process.poll()+ _server.terminate_process(self._process)+ self._process = None+ # Build the error before the abort deletes the log it reads.+ raise _server.startup_failure_error(self._output_file, crash_exit_code=crash_exit_code)+ except BaseException:+ self._abort_failed_load()+ raise# Concurrent-POST fan-out: a keep-alive session with a connection pool# sized to the concurrency and a matching thread pool, so a sharded@@ -329,6 +343,22 @@ class SGLangEmbeddingAdapter(BaseAdapter):self._embed_concurrency,)+ def _abort_failed_load(self) -> None:+ """Tear down a partially-started child + reset state after a failed load.++ The registry does not call unload() on a failed load, so this mirrors+ unload(): terminate the child, release the reserved port, drop the temp+ log, and clear _server_url/_device so the adapter does not look "loaded".+ Mirrors the generation siblings (SGLang + MLX).+ """+ _server.terminate_process(self._process)+ self._process = None+ _server.release_port(self._port)+ self._port = None+ self._server_url = None+ self._device = None+ self._cleanup_output_log()+def unload(self) -> None:"""Unload the model by stopping SGLang server subprocess."""if self._post_executor is not None:@@ -342,9 +372,28 @@ class SGLangEmbeddingAdapter(BaseAdapter):_server.terminate_process(self._process)self._process = None+ # Release only after the child is down so a concurrent load can't be+ # handed a port the dying child still holds bound.+ _server.release_port(self._port)+ self._port = Noneself._server_url = Noneself._device = Noneself._dense_dim = self._configured_dense_dim+ self._cleanup_output_log()++ def _cleanup_output_log(self) -> None:+ """Close + delete the subprocess stdout/stderr log (best-effort, idempotent).++ Without this, one ``sglang_*.log`` leaks into /tmp per load — unbounded+ under LRU-eviction / hot-reload churn — and the open fd is held for the+ subprocess lifetime. Mirrors the MLX sibling's cleanup.+ """+ if self._output_file is not None:+ with contextlib.suppress(OSError):+ self._output_file.close()+ with contextlib.suppress(OSError):+ Path(self._output_file.name).unlink()+ self._output_file = Nonedef memory_footprint(self) -> int:"""Return the GPU memory usage in bytes.diff --git a/packages/sie_server/src/sie_server/adapters/sglang/gemma.py b/packages/sie_server/src/sie_server/adapters/sglang/gemma.pyindex 237fc1968..0e3427b5d 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/gemma.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/gemma.py@@ -10,7 +10,7 @@ class SGLangGemmaAdapter(SGLangGenerationAdapter):subclass exists is routing: bundle compatibility keys on the adapter*module* path, and the ``sglang`` bundle declares only``sie_server.adapters.sglang.generation``. Giving Gemma 4 a distinct- module lets the ``gemma`` bundle (sglang 0.5.13 + transformers 5.8) own+ module lets the ``sglang-cu130`` bundle (sglang 0.5.13 + transformers 5.8) ownit without making every Qwen3.x model compatible with that bundle too —so the Qwen serving stack on the ``sglang`` bundle stays untouched."""diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 1ff19c218..6ba11e848 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -33,6 +33,7 @@ import tempfileimport threadingimport uuidfrom collections.abc import AsyncIterator+from pathlib import Pathfrom typing import Any, castimport httpx@@ -73,9 +74,8 @@ _ABORT_REQUEST_TIMEOUT_S = float(os.environ.get("SIE_SGLANG_ABORT_REQUEST_TIMEOU# distribution. A guard's verdict usually sits at position 0, but a leading# whitespace/punctuation/preamble token can push it back a slot — so we scan# the first few positions for the first one that carries a Yes/No top_logprobs-# distribution. Mirrors the eval runner's ``content[:3]`` scan-# (``sie_bench.eval.generation_runner._p_unsafe_from_logprobs``) so serving and-# eval agree on which position the verdict is read from.+# distribution. The first-three-position scan keeps serving aligned with the+# evaluation convention for locating the verdict._GUARD_VERDICT_SCAN_POSITIONS = 3@@ -338,6 +338,7 @@ class SGLangGenerationAdapter(GenerationAdapter):self._process: subprocess.Popen[bytes] | None = Noneself._server_url: str | None = None+ self._port: int | None = Noneself._device: str | None = Noneself._output_file: tempfile._TemporaryFileWrapper | None = None# Shared httpx client. Opened lazily on the first ``generate()`` call@@ -446,12 +447,30 @@ class SGLangGenerationAdapter(GenerationAdapter):self._device = devicedevice_index = _server.parse_device_index(device)port = _server.find_free_port()+ self._port = portself._server_url = f"http://localhost:{port}"+ # The port (and, once opened, the log fd) belong to this adapter from+ # the reservation above onward, so every raise below hands them back+ # rather than leaking one slot of the 100-port span per attempt: a full+ # /tmp in open_output_log, a failed exec, the pre-launch speculative+ # validation, or a cancelled load included.+ try:+ self._start_server(port=port, device_index=device_index, server_url=self._server_url)+ except BaseException:+ self._abort_failed_load()+ raise++ def _start_server(self, *, port: int, device_index: int, server_url: str) -> None:+ """Launch the SGLang child and block until it serves the model.++ Always called under ``load``'s abort-on-failure guard, so it raises+ without cleaning up the port or log itself.+ """logger.info("Starting SGLang generation server for %s on device=%s (gpu_id=%d) at port %d",self._model_name_or_path,- device,+ self._device,device_index,port,)@@ -558,18 +577,21 @@ class SGLangGenerationAdapter(GenerationAdapter):)if not _server.wait_for_server(- self._server_url,+ server_url,self._process,output_file=self._output_file,timeout_s=self._startup_timeout_s,):+ # Capture crash-vs-timeout before terminate makes poll() ambiguous.+ crash_exit_code = self._process.poll()log_path = getattr(self._output_file, "name", None)if log_path:logger.error("SGLang failed to reach health. log_path=%s", log_path)logger.error("SGLang startup log tail:\n%s", _tail_file(str(log_path)))_server.terminate_process(self._process)self._process = None- raise _server.startup_failure_error(self._output_file)+ # Build the error before `load`'s abort deletes the log it reads.+ raise _server.startup_failure_error(self._output_file, crash_exit_code=crash_exit_code)# Best-effort runtime verification that the# ``--grammar-backend`` flag actually took effect. SGLang's@@ -589,6 +611,22 @@ class SGLangGenerationAdapter(GenerationAdapter):self._server_url,)+ def _abort_failed_load(self) -> None:+ """Tear down a partially-started child + reset state after a failed load.++ The registry does not call unload() on a failed load, so this mirrors+ unload(): terminate the child, release the reserved port, drop the temp+ log, and clear _server_url/_device so the adapter does not look "loaded"+ (_check_loaded() gates only on _server_url). Mirrors the MLX sibling.+ """+ _server.terminate_process(self._process)+ self._process = None+ _server.release_port(self._port)+ self._port = None+ self._server_url = None+ self._device = None+ self._cleanup_output_log()+def _verify_grammar_backend_log(self) -> None:"""Scan ``self._output_file`` for evidence SGLang accepted the``--grammar-backend`` flag. Best-effort; never raises.@@ -891,8 +929,27 @@ class SGLangGenerationAdapter(GenerationAdapter):logger.info("Shutting down SGLang generation server for %s", self._model_name_or_path)_server.terminate_process(self._process)self._process = None+ # Release only after the child is down so a concurrent load can't be+ # handed a port the dying child still holds bound.+ _server.release_port(self._port)+ self._port = Noneself._server_url = Noneself._device = None+ self._cleanup_output_log()++ def _cleanup_output_log(self) -> None:+ """Close + delete the subprocess stdout/stderr log (best-effort, idempotent).++ Without this, one ``sglang_*.log`` leaks into /tmp per load — unbounded+ under LRU-eviction / hot-reload churn — and the open fd is held for the+ subprocess lifetime. Mirrors the MLX sibling's cleanup.+ """+ if self._output_file is not None:+ with contextlib.suppress(OSError):+ self._output_file.close()+ with contextlib.suppress(OSError):+ Path(self._output_file.name).unlink()+ self._output_file = Nonedef memory_footprint(self) -> int:# SGLang pre-allocates in the subprocess; let the registry measure GPU.diff --git a/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.py b/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.pyindex fa579fb67..9a3d7ac71 100644--- a/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.py@@ -326,7 +326,9 @@ class SGLangVisionExtractAdapter(SGLangGenerationAdapter):results = await asyncio.gather(*(generate_one(image) for image in images))for result in results:- if result.finish_reason == "error":+ # A typed terminal ``error_code`` is a failure even when the+ # finish_reason stayed ``stop``/``length`` (#3104/#3136).+ if result.finish_reason == "error" or result.error_code is not None:msg = "SGLang OCR generation failed"raise RuntimeError(msg)return resultsdiff --git a/packages/sie_server/src/sie_server/adapters/siglip/adapter.py b/packages/sie_server/src/sie_server/adapters/siglip/adapter.pyindex 206ad11d9..fea4249c3 100644--- a/packages/sie_server/src/sie_server/adapters/siglip/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/siglip/adapter.py@@ -39,7 +39,6 @@ Example configuration (open_clip backend):from __future__ import annotations-import ioimport jsonimport loggingimport os@@ -52,7 +51,6 @@ from typing import TYPE_CHECKING, Any, ClassVar, Literalimport numpy as npimport torch-from PIL import Imagefrom torch.nn import functionalfrom sie_server.adapters._base_adapter import BaseAdapter@@ -60,7 +58,7 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecisionfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.preprocessor.image import ImagePreprocessor, OpenCLIPImagePreprocessor-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:from sie_server.types.inputs import Item@@ -572,17 +570,19 @@ class SiglipAdapter(BaseAdapter):self._preprocess_pool = poolreturn pool- def _preprocess_one(self, img_input: Any) -> torch.Tensor:+ def _preprocess_one(+ self, img_input: Any, *, item_index: int | None = None, image_index: int | None = None+ ) -> torch.Tensor:"""Decode + preprocess a single image input into a ``[C, H, W]`` tensor.Stateless per call (PIL / processor / val_preproc release the GIL onthe heavy work), so this is safe to fan across the preprocessing pool.+ ``item_index``/``image_index`` name the request-local position in the+ typed decode error."""- img_bytes = media_bytes(img_input, kind="image")- pil_img = Image.open(io.BytesIO(img_bytes))- # Convert to RGB if necessary- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ pil_img = decode_image(img_input, item_index=item_index, image_index=image_index)if self._backend == "open_clip":assert self._open_clip_preprocess is not Nonereturn self._open_clip_preprocess(pil_img)@@ -606,7 +606,9 @@ class SiglipAdapter(BaseAdapter):"""# Build the flat list of preprocessing jobs in stacked order. A job is# either a ready ``[C, H, W]`` tensor (open_clip prepared fast path) or- # a raw image input to decode + preprocess.+ # a raw image input to decode + preprocess, tagged with its+ # request-local (item, image) indices so a decode failure names the+ # exact field.jobs: list[tuple[str, Any]] = []counts: list[int] = []for slot, item in enumerate(items):@@ -617,11 +619,14 @@ class SiglipAdapter(BaseAdapter):if prepared is not None and len(item_images) == 1:jobs.append(("ready", prepared))else:- jobs.extend(("decode", img_input) for img_input in item_images)+ jobs.extend(("decode", (orig_index, j, img_input)) for j, img_input in enumerate(item_images))def run(job: tuple[str, Any]) -> torch.Tensor:kind, payload = job- return payload if kind == "ready" else self._preprocess_one(payload)+ if kind == "ready":+ return payload+ item_index, image_index, img_input = payload+ return self._preprocess_one(img_input, item_index=item_index, image_index=image_index)if len(jobs) == 1:tensors = [run(jobs[0])]@@ -732,25 +737,39 @@ class SiglipAdapter(BaseAdapter):msg = f"Unsupported output types: {unsupported}. SigLIP only supports 'dense'."raise ValueError(msg)- def get_preprocessor(self) -> Any | None:- """Return an ImagePreprocessor for CPU/GPU overlap.+ def get_preprocessor(self) -> Any:+ """Return text AND image preprocessors (registered by modality).++ Registering ONLY the image preprocessor left text-only requests with+ no ``"text"`` preprocessor, so they fell through to the unbatched+ direct-call path in ``EncodePipeline`` — per-request threads spinning+ on the adapter's ``_tokenizer_lock`` with no batch formation, which is+ worse than serial under concurrency (#2874). The base+ ``CharCountPreprocessor`` (cost-only; the adapter still owns its own+ tokenization) routes text requests through ``ModelWorker`` batching,+ where ``_encode_texts`` runs the fused batch as one forward. Same+ pattern as NemoColEmbed (#1163).Returns:- ``ImagePreprocessor`` wrapping the SiglipProcessor on the- transformers backend, ``OpenCLIPImagePreprocessor`` wrapping the- open_clip ``val_preproc`` callable on the open_clip backend, or- ``None`` if not loaded.+ ``[CharCountPreprocessor, <image preprocessor>]`` — the image+ entry is the ``ImagePreprocessor`` wrapping the SiglipProcessor on+ the transformers backend or ``OpenCLIPImagePreprocessor`` wrapping+ the open_clip ``val_preproc`` callable — or just the text+ preprocessor if the image processor is unavailable."""+ text_preprocessor = super().get_preprocessor()if self._backend == "open_clip":if self._open_clip_preprocess is None:- return None-- return OpenCLIPImagePreprocessor(self._open_clip_preprocess, self._model_name_or_path)+ return text_preprocessor+ return [+ text_preprocessor,+ OpenCLIPImagePreprocessor(self._open_clip_preprocess, self._model_name_or_path),+ ]if self._processor is None:- return None+ return text_preprocessor- return ImagePreprocessor(self._processor, self._model_name_or_path)+ return [text_preprocessor, ImagePreprocessor(self._processor, self._model_name_or_path)]def unload(self) -> None:"""Shut down the preprocessing pool, then unload model weights."""diff --git a/packages/sie_server/src/sie_server/adapters/st_sparse_vision/adapter.py b/packages/sie_server/src/sie_server/adapters/st_sparse_vision/adapter.pyindex ba78fad4d..853eeb337 100644--- a/packages/sie_server/src/sie_server/adapters/st_sparse_vision/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/st_sparse_vision/adapter.py@@ -11,7 +11,6 @@ on the sentence-transformers 5.0 line the default bundle pins.from __future__ import annotations-import ioimport sysfrom pathlib import Pathfrom typing import Any, cast@@ -19,7 +18,6 @@ from typing import Any, castimport numpy as npimport torchfrom huggingface_hub import snapshot_download-from PIL import Imagefrom sentence_transformers import SparseEncoderfrom sie_server.adapters._base_adapter import BaseAdapter@@ -28,7 +26,7 @@ from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.adapters._utils import validate_output_typesfrom sie_server.core.inference_output import EncodeOutput, SparseVectorfrom sie_server.core.loader import is_immutable_revision-from sie_server.types.inputs import Item, media_bytes+from sie_server.types.inputs import Item, decode_imageERR_REQUIRES_TEXT_OR_IMAGE = "SparseEncoderVisionAdapter requires text or image input per item"@@ -191,7 +189,7 @@ class SparseEncoderVisionAdapter(BaseAdapter):validate_output_types(output_types, {"sparse"}, type(self).__name__)- inputs = [self._extract_input(item) for item in items]+ inputs = [self._extract_input(item, item_index=i) for i, item in enumerate(items)]with torch.inference_mode():# SparseEncoder has separate methods for query vs document@@ -232,14 +230,12 @@ class SparseEncoderVisionAdapter(BaseAdapter):is_query=is_query,)- def _extract_input(self, item: Item) -> Any:+ def _extract_input(self, item: Item, *, item_index: int | None = None) -> Any:"""Return the SparseEncoder input for an item: PIL image or text."""if item.images:- img_bytes = media_bytes(item.images[0], kind="image")- pil_img = Image.open(io.BytesIO(img_bytes))- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")- return pil_img+ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ return decode_image(item.images[0], item_index=item_index, image_index=0)if item.text is not None:return item.textraise ValueError(ERR_REQUIRES_TEXT_OR_IMAGE)diff --git a/packages/sie_server/src/sie_server/api/encode.py b/packages/sie_server/src/sie_server/api/encode.pyindex 1c7440d2d..3aa407e44 100644--- a/packages/sie_server/src/sie_server/api/encode.py+++ b/packages/sie_server/src/sie_server/api/encode.py@@ -6,18 +6,21 @@ from fastapi import APIRouter, Header, HTTPException, Request, statusfrom fastapi.responses import JSONResponsefrom sie_sdk.types import DEFAULT_OUTPUT_DTYPE, DType, OutputDType, np_to_dtype+from sie_server.adapters.errors import InputTooLongErrorfrom sie_server.api.helpers import (InferenceErrorHandler,ModelStateChecker,RequestParser,ResponseBuilder,oom_retry_after_from_registry,+ validated_total,)from sie_server.api.options import resolve_runtime_options_with_profilefrom sie_server.api.serialization import MsgPackResponsefrom sie_server.api.validation import validate_machine_profile_headerfrom sie_server.config.model import ModelConfigfrom sie_server.core.encode_pipeline import EncodePipeline, resolve_encode_output_types+from sie_server.core.timing import RequestTimingfrom sie_server.core.worker import QueueFullErrorfrom sie_server.observability.tracing import tracerfrom sie_server.observability.worker_telemetry import worker_telemetry, worker_telemetry_enabled@@ -25,13 +28,37 @@ from sie_server.types.inputs import Itemfrom sie_server.types.openapi import EncodeResponseModelfrom sie_server.types.outputs import DenseVector, EncodeResult, MultiVector, SparseVectorfrom sie_server.types.requests import EncodeRequest-from sie_server.types.responses import EncodeResponse, ErrorCode, TimingInfo+from sie_server.types.responses import EncodeResponse, ErrorCode, TimingInfo, Usagelogger = logging.getLogger(__name__)router = APIRouter(prefix="/v1", tags=["encode"])+def encode_usage_from_timing(timing: RequestTiming | None, item_count: int) -> Usage | None:+ """Return exact post-tokenization encode usage, never a character estimate.++ The counterpart of ``score.score_usage_from_output``: the reported number is+ the worker's own ``input_token_counts``, the number telemetry meters from,+ so a caller can reconcile what they read with what they are billed.++ A total of ``0`` IS reported — a video-only encode consumes exactly zero+ text tokens, and that measured zero must not read as "unknown". Absent+ counts yield ``None`` and the response simply carries no ``usage``, which+ is the only honest rendering of "this path could not count".+ """+ if timing is None:+ return None+ total_tokens = validated_total(timing.input_token_counts, item_count)+ if total_tokens is None:+ return None+ usage = Usage(input_tokens=total_tokens)+ images = validated_total(timing.input_image_counts, item_count)+ if images is not None:+ usage["images"] = images+ return usage++def _format_dense(embedding: np.ndarray,config: ModelConfig,@@ -176,7 +203,7 @@ def _build_response_items("Terminal model-load failure (MODEL_LOAD_FAILED). ""Carried in the ``detail`` envelope: ``{code, message, ""error_class, permanent, attempts}``. No ``Retry-After`` "- "header — clients MUST NOT auto-retry. See sie-test#85."+ "header — clients MUST NOT auto-retry."),},503: {"description": "Model not loaded or service unavailable"},@@ -362,6 +389,8 @@ async def encode()except QueueFullError as e:raise error_handler.handle_queue_full(e) from e+ except InputTooLongError as e:+ raise error_handler.handle_input_too_long(e) from eexcept ValueError as e:raise error_handler.handle_value_error(e) from eexcept Exception as e:@@ -391,24 +420,28 @@ async def encode(response = EncodeResponse(model=model, items=response_items, timing=timing_info)+ # What the caller is TOLD they used. Same worker counts the telemetry+ # block below meters from, rendered without the metering-specific+ # zero-drop: reporting is not billing, and a measured zero is a fact the+ # caller is entitled to read.+ usage = encode_usage_from_timing(timing, len(items))+ if usage is not None:+ response["usage"] = usage+if worker_telemetry_enabled():units: dict[str, int] | None = None- if timing is not None and timing.input_token_counts is not None:- counts = timing.input_token_counts- if len(counts) == len(items) and all(- isinstance(count, int) and not isinstance(count, bool) for count in counts- ):- # Non-zero, exactly like the image branch below. A- # video-only encode scatters `0` text tokens to its items,- # and a reported zero is indistinguishable from "this- # dimension does not apply to this item" — which is why the- # queue seam's `_encode_units` drops it and the gateway's- # `validate_dimensions` faults on one outright. Emitting it- # here made the two ingresses report different dimension- # sets for the same batch.- total_tokens = sum(counts)- if total_tokens > 0:- units = {"input_tokens": total_tokens}+ if timing is not None:+ # Non-zero, exactly like the image branch below. A+ # video-only encode scatters `0` text tokens to its items,+ # and a reported zero is indistinguishable from "this+ # dimension does not apply to this item" — which is why the+ # queue seam's `_encode_units` drops it and the gateway's+ # `validate_dimensions` faults on one outright. Emitting it+ # here made the two ingresses report different dimension+ # sets for the same batch.+ total_tokens = validated_total(timing.input_token_counts, len(items))+ if total_tokens:+ units = {"input_tokens": total_tokens}# §7 "$ per image": the adapter's authoritative count of images and# sampled video frames it actually processed. Independent of tokens# — a video encode reports images with no token count at all.diff --git a/packages/sie_server/src/sie_server/api/extract.py b/packages/sie_server/src/sie_server/api/extract.pyindex 7e52effae..bfc6ee35d 100644--- a/packages/sie_server/src/sie_server/api/extract.py+++ b/packages/sie_server/src/sie_server/api/extract.py@@ -11,6 +11,7 @@ from sie_server.api.helpers import (RequestParser,ResponseBuilder,oom_retry_after_from_registry,+ validated_total,)from sie_server.api.options import resolve_runtime_optionsfrom sie_server.api.serialization import MsgPackResponse@@ -34,6 +35,7 @@ from sie_server.types.responses import (ExtractResponse,ExtractResult,Relation,+ Usage,)if TYPE_CHECKING:@@ -269,7 +271,7 @@ def _build_response("Terminal model-load failure (MODEL_LOAD_FAILED). ""Carried in the ``detail`` envelope: ``{code, message, ""error_class, permanent, attempts}``. No ``Retry-After`` "- "header — clients MUST NOT auto-retry. See sie-test#85."+ "header — clients MUST NOT auto-retry."),},503: {"description": "Model not loaded or service unavailable"},@@ -404,6 +406,13 @@ async def extract(# Build responseresponse = _build_response(model, items, extraction_results)+ # Same worker counts the telemetry block below meters from, reported to+ # the caller so `usage` and the bill can be reconciled. Absent counts+ # leave `usage` off rather than substituting an estimate.+ extract_tokens = validated_total(extract_output.input_token_counts, len(items))+ if extract_tokens is not None:+ response["usage"] = Usage(input_tokens=extract_tokens)+if worker_telemetry_enabled():units: dict[str, int] = {}token_counts = extract_output.input_token_countsdiff --git a/packages/sie_server/src/sie_server/api/generate.py b/packages/sie_server/src/sie_server/api/generate.pyindex c6d2433b3..860f5dc82 100644--- a/packages/sie_server/src/sie_server/api/generate.py+++ b/packages/sie_server/src/sie_server/api/generate.py@@ -9,7 +9,7 @@ transport differs.Why ship a direct route at all? Two reasons:1. End-to-end viability checking: a developer can run- ``mise run serve -m Qwen/Qwen3-4B-Instruct -b sglang`` and immediately+ ``mise run serve -- -m Qwen/Qwen3-4B-Instruct -b sglang`` and immediatelycurl ``/v1/generate/...`` against the worker to confirm theadapter + registry + model config plumbing works against a real GPU,without needing to boot the Rust gateway and NATS first.@@ -1160,14 +1160,22 @@ async def generate(# answer HTTP 200 with truncated output. Map the failure terminators# to non-2xx, keeping the OpenAI-shaped error body the route uses# elsewhere. (``stop`` / ``length`` are the normal success- # terminators and fall through to the 200 response.)- if result.finish_reason == "error":- logger.warning("generate produced terminal finish_reason=error for %s", model)+ # terminators and fall through to the 200 response.) A typed+ # terminal ``error_code`` (e.g. ``empty_model_output``, which keeps+ # a ``stop``/``length`` finish_reason) is an error too, and its+ # code/message are surfaced verbatim — mirroring the streaming+ # path's terminal-error semantics (#3104/#3136).+ if result.finish_reason == "error" or result.error_code is not None:+ logger.warning(+ "generate produced terminal error code=%s for %s",+ result.error_code or "inference_error",+ model,+ )raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail={- "code": "inference_error",- "message": "generation terminated with an upstream error",+ "code": result.error_code or "inference_error",+ "message": result.error_message or "generation terminated with an upstream error",},)if result.finish_reason == "cancelled":diff --git a/packages/sie_server/src/sie_server/api/health.py b/packages/sie_server/src/sie_server/api/health.pyindex 41137ec7b..243720d44 100644--- a/packages/sie_server/src/sie_server/api/health.py+++ b/packages/sie_server/src/sie_server/api/health.py@@ -34,7 +34,7 @@ async def livez() -> Response:Unlike /healthz (process-alive only), this exercises the GPU with a tiny CUDAsync. A wedged CUDA context (``device-side assert``) is unrecoverable inPyTorch, so failing liveness lets the kubelet restart the pod — the only path- back to a serving worker (see issue #1025).+ back to a serving worker.It deliberately does NOT consult the lifecycle ready flag, so gracefulshutdown draining (when the worker marks itself not-ready) never trips a@@ -63,7 +63,7 @@ async def readyz() -> Response:- GPU health: a tiny CUDA sync confirms the device can still run kernels. Awedged CUDA context (``device-side assert``) keeps returning sticky errorsfrom every inference while a process-alive check stays green, so without- this the gateway would keep routing to a dead worker (see issue #1025).+ this the gateway would keep routing to a dead worker.Returns:200 OK with "ok" body if ready.diff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.pyindex 9602084a2..f24386055 100644--- a/packages/sie_server/src/sie_server/api/helpers.py+++ b/packages/sie_server/src/sie_server/api/helpers.py@@ -1,4 +1,5 @@import logging+import mathimport timefrom importlib.metadata import PackageNotFoundErrorfrom importlib.metadata import version as pkg_version@@ -10,9 +11,11 @@ from fastapi.responses import JSONResponsefrom sie_server.adapters.errors import InputTooLongErrorfrom sie_server.api.serialization import MsgPackResponse, _convert_for_json+from sie_server.core.model_suggestions import suggestion_suffixfrom sie_server.core.oom import is_oom_errorfrom sie_server.core.timing import RequestTimingfrom sie_server.core.worker import QueueFullError+from sie_server.core.worker.types import WorkerDrainedErrorfrom sie_server.observability.tracing import get_current_trace_idfrom sie_server.observability.worker_telemetry import worker_telemetry, worker_telemetry_enabledfrom sie_server.types.responses import ErrorCode@@ -29,6 +32,18 @@ if TYPE_CHECKING:# ``engine_config.oom_recovery.retry_after_s`` (env: SIE_OOM_RECOVERY__RETRY_AFTER_S)._OOM_DEFAULT_RETRY_AFTER_S = 5+# Retry-After (seconds) for transient 503 QUEUE_FULL responses. The queue+# drains at inference speed, so pressure typically clears within a second+# or two — much faster than a model load, hence smaller than the+# MODEL_LOADING/OOM values.+_QUEUE_FULL_RETRY_AFTER_S = 1++# Retry-After (seconds) for a request that was still queued when its model+# was evicted (``WorkerDrainedError``). Matches the ``MODEL_LOADING``+# Retry-After the state checks above already emit: the client's next attempt+# will re-trigger the load, so the wait it should expect is a model load.+WORKER_DRAINED_RETRY_AFTER_S = 5+def oom_retry_after_from_registry(registry: "ModelRegistry | None") -> int:"""Resolve the OOM ``Retry-After`` value from a registry's engine config.@@ -183,6 +198,47 @@ class RequestParser:) from e+def openai_error_response(exc: HTTPException) -> JSONResponse:+ """Re-emit an ``HTTPException`` as a top-level OpenAI error envelope.++ FastAPI serializes ``HTTPException.detail`` under a ``{"detail": ...}``+ wrapper, which OpenAI clients cannot parse. The direct OpenAI-compat+ surfaces catch the exception and return a top-level+ ``{"error": {"message", "type", "param", "code"}}`` object instead — the+ shape ``/v1/completions`` and ``/v1/audio/transcriptions`` already emit.++ Status code, headers, error codes, and messages are preserved verbatim;+ auxiliary detail fields (e.g. ``error_class``/``permanent``/``attempts``+ on ``MODEL_LOAD_FAILED``) are carried inside the error+ object so SDK short-circuits keep working.+ """+ detail = exc.detail+ param: str | None = None+ error_type: Any = None+ extras: dict[str, Any] = {}+ if isinstance(detail, dict):+ nested = detail.get("error")+ source: dict[str, Any] = nested if isinstance(nested, dict) else detail+ message = str(source.get("message", "request failed"))+ code = str(source.get("code", "invalid_request"))+ raw_param = source.get("param")+ param = raw_param if isinstance(raw_param, str) else None+ error_type = source.get("type")+ extras = {key: value for key, value in source.items() if key not in {"message", "type", "param", "code"}}+ else:+ message = str(detail)+ code = "invalid_request"+ if not isinstance(error_type, str):+ error_type = (+ "invalid_request_error" if exc.status_code < status.HTTP_500_INTERNAL_SERVER_ERROR else "server_error"+ )+ return JSONResponse(+ status_code=exc.status_code,+ content={"error": {"message": message, "type": error_type, "param": param, "code": code, **extras}},+ headers=dict(exc.headers) if exc.headers is not None else None,+ )++class ModelStateChecker:"""Validates model state before inference."""@@ -210,7 +266,9 @@ class ModelStateChecker:status_code=status.HTTP_404_NOT_FOUND,detail={"code": ErrorCode.MODEL_NOT_FOUND.value,- "message": f"Model '{self.model}' not found",+ "message": (+ f"Model '{self.model}' not found{suggestion_suffix(self.model, self.registry.model_names)}"+ ),},)@@ -257,7 +315,7 @@ class ModelStateChecker:bypass its 5-minute ``MODEL_LOADING`` retry budget and surfacea :class:`ModelLoadFailedError` to the caller immediately.- This is the symptom-side fix for sie-test#85: previously a+ This is the symptom-side fix for terminal model-load failures: previously agated/dep-missing model would loop the SDK for 5 minutes; nowthe server tells the SDK "don't bother" the first time it asks.@@ -308,7 +366,7 @@ class ModelStateChecker:# another doomed background load. Without this guard, every# request would retrigger ``start_load_async`` and the SDK# would burn its 5-minute MODEL_LOADING budget on a known-bad- # configuration (sie-test#85).+ # configuration.self.check_not_failed()logger.info("Starting background load for model %s on device %s", self.model, device)@@ -408,20 +466,48 @@ class InferenceErrorHandler:def handle_queue_full(self, error: QueueFullError) -> HTTPException:"""Handle queue full backpressure error.+ Two distinct situations arrive here (usability sweep — the old+ mapping returned ``503 MODEL_NOT_LOADED`` for both, which was+ wrong on every axis: the model *is* loaded, and a request larger+ than the queue's total capacity can never succeed no matter how+ often it is retried):++ - The request's own item count exceeds the queue capacity limit+ (``error.requested > error.limit``): a permanent client error →+ ``400 INVALID_INPUT`` naming the per-request limit.+ - Genuine transient pressure (queue occupied by other work) →+ ``503 QUEUE_FULL`` with a ``Retry-After`` header so clients+ back off briefly and retry.+Args:error: QueueFullError from worker.Returns:- HTTPException with 503 status.+ HTTPException with 400 (oversized request) or 503 (transient)."""+ if error.requested is not None and error.limit is not None and error.requested > error.limit:+ self.span.set_attribute("error", "invalid_input")+ self._record_completion("error")+ return HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={+ "code": ErrorCode.INVALID_INPUT.value,+ "message": (+ f"Request has {error.requested} items but the queue accepts at most "+ f"{error.limit} items per request for model '{self.model}'; "+ f"split the request into batches of {error.limit} or fewer"+ ),+ },+ )self.span.set_attribute("error", "queue_full")self._record_completion("retry")return HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,detail={- "code": ErrorCode.MODEL_NOT_LOADED.value,+ "code": ErrorCode.QUEUE_FULL.value,"message": str(error),},+ headers={"Retry-After": str(_QUEUE_FULL_RETRY_AFTER_S)},)def handle_value_error(self, error: ValueError) -> HTTPException:@@ -458,7 +544,9 @@ class InferenceErrorHandler:"""Handle generic inference errors.OOM errors are mapped to 503 ``RESOURCE_EXHAUSTED`` with a- ``Retry-After`` header so the SDK can auto-retry. Everything else+ ``Retry-After`` header so the SDK can auto-retry. A request the+ worker drained on eviction never ran at all, so it maps to the+ existing retryable 503 ``MODEL_LOADING`` shape. Everything elsekeeps the legacy 500 ``INFERENCE_ERROR`` mapping.Args:@@ -466,8 +554,30 @@ class InferenceErrorHandler:operation: Operation name for error message (Inference, Extraction, Scoring).Returns:- HTTPException with 503 (OOM) or 500 (other).+ HTTPException with 503 (OOM, drained) or 500 (other)."""+ # A drained request was evicted out of the queue before inference+ # started. Reuse ``MODEL_LOADING`` rather than minting a new code:+ # the SDK and the gateway already treat it as retryable, and the+ # client's retry will re-trigger exactly the load that code names.+ if isinstance(error, WorkerDrainedError):+ logger.info(+ "%s request drained on eviction for model %s, returning 503 MODEL_LOADING: %s",+ operation,+ self.model,+ error,+ )+ self.span.set_attribute("error", "model_loading")+ self._record_completion("retry")+ return HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail={+ "code": ErrorCode.MODEL_LOADING.value,+ "message": f"Model '{self.model}' was evicted before this request ran, please retry",+ },+ headers={"Retry-After": str(WORKER_DRAINED_RETRY_AFTER_S)},+ )+# Recognise both the worker's ``ResourceExhaustedError`` (recovery# exhausted) and any OOM that escaped without recovery (recovery# disabled or a code path the executor doesn't wrap). Both deserve@@ -502,6 +612,53 @@ class InferenceErrorHandler:)+def ensure_finite_scores(scores: list[float], model: str) -> None:+ """Fail closed when a model produces non-finite (NaN/inf) scores.++ A cross-encoder that emits ``NaN``/``inf`` scores (observed on+ ``cross-encoder/ms-marco-MiniLM-L-6-v2`` on CPU) corrupts the response on+ BOTH content types: the JSON path crashes ``json.dumps`` ("Out of range+ float values are not JSON compliant: nan") into a bare 500 with no error+ envelope, while the msgpack path returns HTTP 200 with the ``NaN`` ranked+ as if it were a real score — silent corruption for any msgpack client.++ Detect the non-finite output before serialization and raise a typed,+ enveloped ``500 INFERENCE_ERROR`` that names the model, so ``/v1/score``+ and ``/v1/rerank`` fail closed identically on JSON and msgpack. The 500 /+ ``INFERENCE_ERROR`` mapping matches the repo precedent for a model that+ produces invalid output (the generation terminal-error path). Applied at+ the shared ``list[float]`` seam both score paths pass through, so it covers+ every float-output reranker uniformly. (pass-2 audit A2)++ Raises:+ HTTPException: 500 ``INFERENCE_ERROR`` if any score is not finite.+ """+ if all(math.isfinite(score) for score in scores):+ return+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail={+ "code": ErrorCode.INFERENCE_ERROR.value,+ "message": f"Model '{model}' produced non-finite scores",+ },+ )+++def validated_total(counts: list[int] | None, item_count: int) -> int | None:+ """Sum authoritative per-item counts, or ``None`` when they are unusable.++ A partition that is misaligned with the batch or holds non-``int`` entries+ is not a measurement, so it is dropped rather than mis-attributed — the same+ rule ``encode_pipeline._validated_counts`` applies upstream. ``0`` is a+ legitimate total and is returned as such; only ``None`` means "unknown".+ """+ if counts is None or len(counts) != item_count:+ return None+ if not all(isinstance(count, int) and not isinstance(count, bool) for count in counts):+ return None+ return sum(counts)++class ResponseBuilder:"""Builds HTTP responses with common headers."""diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.pyindex 9f8ed6b7e..759d25af7 100644--- a/packages/sie_server/src/sie_server/api/models.py+++ b/packages/sie_server/src/sie_server/api/models.py@@ -3,6 +3,7 @@ from typing import TYPE_CHECKING, Any, Literalfrom fastapi import APIRouter, HTTPException, Request, statusfrom pydantic import BaseModel+from sie_server.core.model_suggestions import suggestion_suffixfrom sie_server.types.responses import ErrorCodeif TYPE_CHECKING:@@ -234,7 +235,7 @@ async def get_model(model: str, http_request: Request) -> ModelInfo:status_code=status.HTTP_404_NOT_FOUND,detail={"code": ErrorCode.MODEL_NOT_FOUND.value,- "message": f"Model '{model}' not found",+ "message": f"Model '{model}' not found{suggestion_suffix(model, registry.model_names)}",},)diff --git a/packages/sie_server/src/sie_server/api/openai_compat.py b/packages/sie_server/src/sie_server/api/openai_compat.pyindex 05ed0d3ee..7248e194b 100644--- a/packages/sie_server/src/sie_server/api/openai_compat.py+++ b/packages/sie_server/src/sie_server/api/openai_compat.py@@ -16,22 +16,38 @@ from __future__ import annotationsimport base64import loggingimport time-from typing import Annotated, Literal+from typing import TYPE_CHECKING, Annotated, Literalimport numpy as npfrom fastapi import APIRouter, Header, HTTPException, Request, status+from fastapi.responses import JSONResponsefrom pydantic import BaseModel, ConfigDict, Field-from sie_server.api.helpers import check_sdk_version, oom_retry_after_from_registry+from sie_server.api.helpers import (+ WORKER_DRAINED_RETRY_AFTER_S,+ ModelStateChecker,+ check_sdk_version,+ oom_retry_after_from_registry,+ openai_error_response,+)from sie_server.api.validation import validate_machine_profile_headerfrom sie_server.core.encode_pipeline import EncodePipeline+from sie_server.core.model_suggestions import suggestion_suffixfrom sie_server.core.oom import is_oom_errorfrom sie_server.core.worker import QueueFullError+from sie_server.core.worker.types import WorkerDrainedErrorfrom sie_server.observability.tracing import tracerfrom sie_server.observability.worker_telemetry import worker_telemetry, worker_telemetry_enabledfrom sie_server.types.inputs import Item+from sie_server.types.openapi import (+ OpenAIEmbeddingsErrorResponse,+ OpenAIEmbeddingsModelLoadFailedErrorResponse,+)from sie_server.types.responses import ErrorCode+if TYPE_CHECKING:+ from sie_server.core.registry import ModelRegistry+logger = logging.getLogger(__name__)router = APIRouter(prefix="/v1", tags=["openai-compat"])@@ -64,7 +80,14 @@ class OpenAIEmbeddingRequest(BaseModel):]dimensions: Annotated[int | None,- Field(default=None, description="Number of dimensions (not supported by SIE, ignored)"),+ Field(+ default=None,+ description=(+ "Requested embedding width. SIE always returns the model's native dense "+ "width, so this is accepted only when it equals that width; any other "+ "value is rejected with 400 `unsupported_field` rather than ignored."+ ),+ ),]user: Annotated[str | None,@@ -204,25 +227,71 @@ def _decode_tokens(tokens: list[int], registry: object, model: str) -> str:return f"[{len(tokens)} tokens]"-async def _load_model_if_needed(registry: object, model: str, device: str, span: object) -> None:- """Load model if not already loaded."""- if not registry.is_loaded(model): # type: ignore- try:- logger.info("Loading model %s on device %s", model, device)- await registry.load_async(model, device=device) # type: ignore- except Exception as e:- logger.exception("Failed to load model %s", model)- span.set_attribute("error", "model_load_failed") # type: ignore- raise HTTPException(- status_code=status.HTTP_503_SERVICE_UNAVAILABLE,- detail={- "error": {- "code": "model_not_available",- "message": f"Failed to load model: {e}",- "type": "server_error",- }- },- ) from e+def _openai_state_error(error: HTTPException) -> HTTPException:+ """Re-wrap a native model-state ``detail`` in this surface's OpenAI envelope.++ :class:`ModelStateChecker` raises the SIE-native ``{code, message, ...}``+ detail shape served by the native routes. This surface keeps errors+ OpenAI-parseable, so rebuild the detail as ``{"error": {...}}`` while+ preserving the SIE-native ``code`` (``MODEL_LOADING`` /+ ``MODEL_LOAD_FAILED``) plus auxiliary fields (``error_class``,+ ``permanent``, ``attempts``) — the SDK's ``get_error_code`` and+ ``raise_if_model_load_failed`` branch on exactly those. Headers are+ preserved verbatim: ``Retry-After`` presence/absence carries the+ retryability contract (present on 503 ``MODEL_LOADING``, absent on the+ terminal 502 ``MODEL_LOAD_FAILED``).+ """+ detail = error.detail if isinstance(error.detail, dict) else {}+ if "error" in detail:+ return error+ inner: dict[str, object] = dict(detail)+ inner.setdefault("message", "service unavailable")+ inner["type"] = "server_error"+ return HTTPException(status_code=error.status_code, detail={"error": inner}, headers=error.headers)+++def _validate_dimensions(requested: int | None, registry: ModelRegistry, model: str) -> None:+ """Reject a ``dimensions`` value this model cannot honour.++ In OpenAI's API ``dimensions`` truncates the embedding (Matryoshka), so a+ client migrating from ``text-embedding-3-*`` may legitimately send it. SIE+ always returns the model's native dense width. Ignoring the field — as this+ endpoint used to — means such a client silently receives vectors of a width+ it never asked for and writes them into a vector store. That surfaces much+ later, either as a dimension error on insert or, worse, as a silently+ wrong index built against the wrong width.++ Failing loudly matches ``/v1/completions``, which already rejects fields it+ cannot honour with ``400 unsupported_field``. An exact match is accepted so+ a client that simply pins its model's real width keeps working.++ Raises:+ HTTPException: 400 when the value cannot be honoured.+ """+ if requested is None:+ return++ native = registry.get_config(model).dims.get("dense")+ if native is not None and requested == native:+ return++ detail = (+ f"'dimensions' is not supported by this endpoint: model '{model}' returns "+ f"{native}-dimensional embeddings and SIE does not truncate them."+ if native is not None+ else f"'dimensions' is not supported by this endpoint: model '{model}' declares no dense embedding width."+ )+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={+ "error": {+ "code": "unsupported_field",+ "message": f"{detail} Omit 'dimensions', or set it to {native}." if native is not None else detail,+ "type": "invalid_request_error",+ "param": "dimensions",+ }+ },+ )def _build_embeddings_response(@@ -293,6 +362,7 @@ def _build_embeddings_response(@router.post("/embeddings",+ response_model=OpenAIEmbeddingResponse,responses={200: {"description": "Embeddings generated successfully"},400: {"description": "Invalid request"},@@ -300,23 +370,47 @@ def _build_embeddings_response(502: {"description": ("Terminal model-load failure (MODEL_LOAD_FAILED). "- "Carried in the ``detail`` envelope: ``{code, message, "- "error_class, permanent, attempts}``. No ``Retry-After`` "- "header — clients MUST NOT auto-retry. See sie-test#85."+ "Carried in the top-level OpenAI ``error`` envelope, whose "+ "object adds the model-load extras ``error_class``, "+ "``permanent``, and ``attempts`` to ``{message, type, param, "+ "code}``. No ``Retry-After`` header — clients MUST NOT "+ "auto-retry."+ ),+ "model": OpenAIEmbeddingsModelLoadFailedErrorResponse,+ },+ 503: {+ "description": (+ "Service unavailable (retryable). A cold model starts a "+ "background load and returns ``MODEL_LOADING`` with a "+ "``Retry-After`` header immediately instead of blocking the "+ "request — clients should retry after the indicated delay. "+ "Also returned while unloading, on a full queue, and under "+ "transient resource exhaustion. The body is the top-level "+ "OpenAI ``error`` envelope."),+ "model": OpenAIEmbeddingsErrorResponse,+ "headers": {+ "Retry-After": {+ "description": "Seconds to wait before retrying the MODEL_LOADING request.",+ "schema": {"type": "integer", "minimum": 1},+ }+ },},- 503: {"description": "Service unavailable"},},)async def create_embeddings(request: OpenAIEmbeddingRequest,http_request: Request,x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,-) -> OpenAIEmbeddingResponse:+) -> OpenAIEmbeddingResponse | JSONResponse:"""Create embeddings using OpenAI-compatible API.This endpoint is compatible with OpenAI's /v1/embeddings API, allowing- drop-in replacement for any OpenAI SDK or client.+ drop-in replacement for any OpenAI SDK or client. Route-generated errors+ are emitted as top-level OpenAI ``{"error": {...}}`` envelopes, matching+ ``/v1/completions``. The one exception is 422 request-body validation,+ which still returns FastAPI's ``HTTPValidationError`` ``{"detail": [...]}``+ shape (out of scope for this route's error handling; known residual).Args:request: OpenAI-format embedding request.@@ -326,6 +420,17 @@ async def create_embeddings(Returns:OpenAI-format embedding response with embeddings and usage info."""+ try:+ return await _create_embeddings(request, http_request, x_machine_profile)+ except HTTPException as exc:+ return openai_error_response(exc)+++async def _create_embeddings(+ request: OpenAIEmbeddingRequest,+ http_request: Request,+ x_machine_profile: str | None,+) -> OpenAIEmbeddingResponse:# Validate machine profile headervalidate_machine_profile_header(x_machine_profile)check_sdk_version(http_request)@@ -346,12 +451,16 @@ async def create_embeddings(detail={"error": {"code": "model_not_found",- "message": f"Model '{model}' not found",+ "message": f"Model '{model}' not found{suggestion_suffix(model, registry.model_names)}","type": "invalid_request_error",}},)+ # Validated before any load work: an unhonourable 'dimensions' must not+ # cost the caller a cold model load first.+ _validate_dimensions(request.dimensions, registry, model)+# Check if model is being unloadedif registry.is_unloading(model):span.set_attribute("error", "model_unloading")@@ -372,14 +481,33 @@ async def create_embeddings(if not texts:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,- detail={"code": "invalid_request_error", "message": "Input cannot be empty"},+ detail={+ "error": {+ "code": "invalid_request",+ "message": "Input cannot be empty",+ "type": "invalid_request_error",+ "param": "input",+ }+ },)span.set_attribute("batch_size", len(texts))- # Load model if needed+ # Model load states: mirror the native routes' ModelStateChecker+ # contract instead of blocking the request on a cold load. A recorded+ # terminal failure short-circuits as 502 MODEL_LOAD_FAILED with no+ # Retry-After (and, critically, no re-triggered doomed load); a cold+ # model kicks off a background load and returns 503 MODEL_LOADING ++ # Retry-After immediately so clients retry instead of hanging. This is+ # single-node parity with the gateway's /v1/embeddings behavior.device = registry.device- await _load_model_if_needed(registry, model, device, span)+ checker = ModelStateChecker(registry, model, span)+ try:+ checker.check_not_failed()+ checker.check_not_loading()+ await checker.ensure_loaded(device)+ except HTTPException as error:+ raise _openai_state_error(error) from error# Get config and convert texts to SIE Itemsconfig = registry.get_config(model)@@ -420,6 +548,33 @@ async def create_embeddings(}},) from e+ except WorkerDrainedError as e:+ # The model was evicted while this request sat in the worker+ # queue, so it never ran. Mirror the native endpoints' retryable+ # 503 MODEL_LOADING — in the OpenAI envelope — so the SDK retries+ # (and re-triggers the load) instead of seeing a terminal 500.+ logger.info("Embeddings request drained on eviction for model %s: %s", model, e)+ span.set_attribute("error", "model_loading")+ if inference_started is not None:+ worker_telemetry().item_completed(+ operation="embeddings",+ outcome="retry",+ model=model,+ profile="default",+ duration_s=time.perf_counter() - inference_started,+ item_count=len(items),+ )+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail={+ "error": {+ "code": ErrorCode.MODEL_LOADING.value,+ "message": f"Model '{model}' was evicted before this request ran, please retry",+ "type": "server_error",+ }+ },+ headers={"Retry-After": str(WORKER_DRAINED_RETRY_AFTER_S)},+ ) from eexcept Exception as e:if is_oom_error(e):# Transient memory pressure (worker ResourceExhaustedError afterdiff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex 71dce87ba..5363a1d39 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -42,7 +42,7 @@ from sie_server.adapters._generation_base import ()from sie_server.adapters.mlx.generation import MLXGenerationAdapter, normalize_mlx_seedfrom sie_server.adapters.sglang.generation import SGLangGenerationAdapter-from sie_server.api.helpers import ModelStateChecker+from sie_server.api.helpers import ModelStateChecker, ensure_finite_scores, openai_error_responsefrom sie_server.api.options import resolve_runtime_optionsfrom sie_server.api.score import score_usage_from_outputfrom sie_server.api.validation import validate_machine_profile_header, validate_signed_i64@@ -759,7 +759,20 @@ async def chat_completions(MLX remains the non-CUDA backend. CUDA profiles proxy to the exact SGLangsubprocess the registry loaded for the requested model/profile. The childURL and served model name always come from that adapter, never the body.++ Errors are emitted as top-level OpenAI ``{"error": {...}}`` envelopes+ (never FastAPI's ``{"detail": ...}`` wrapper), matching ``/v1/completions``."""+ try:+ return await _chat_completions(http_request, x_machine_profile)+ except HTTPException as exc:+ return openai_error_response(exc)+++async def _chat_completions(+ http_request: Request,+ x_machine_profile: str | None,+) -> Response | StreamingResponse:validate_machine_profile_header(x_machine_profile)body = await _read_json_body(http_request)@@ -984,7 +997,20 @@ async def rerank(Request: ``{model, query, documents: [str], top_n?, return_documents?}``.Response: ``{model, results: [{index, relevance_score, document?}], usage}``sorted by descending relevance.++ Errors are emitted as top-level OpenAI ``{"error": {...}}`` envelopes+ (never FastAPI's ``{"detail": ...}`` wrapper), matching ``/v1/completions``."""+ try:+ return await _rerank(http_request, x_machine_profile)+ except HTTPException as exc:+ return openai_error_response(exc)+++async def _rerank(+ http_request: Request,+ x_machine_profile: str | None,+) -> JSONResponse:validate_machine_profile_header(x_machine_profile)body = await _read_json_body(http_request)@@ -1065,6 +1091,9 @@ async def rerank(score_output: ScoreOutput = worker_result.outputscores = [float(score_output.scores[i]) for i in range(score_output.batch_size)]+ # Fail closed on non-finite (NaN/inf) model output before serialization;+ # the HTTPException is re-emitted as the OpenAI error envelope by rerank().+ ensure_finite_scores(scores, model)usage = score_usage_from_output(score_output)if usage is None:raise HTTPException(diff --git a/packages/sie_server/src/sie_server/api/score.py b/packages/sie_server/src/sie_server/api/score.pyindex 2f913dd70..478c649fa 100644--- a/packages/sie_server/src/sie_server/api/score.py+++ b/packages/sie_server/src/sie_server/api/score.py@@ -4,11 +4,13 @@ from typing import TYPE_CHECKING, Annotated, Anyfrom fastapi import APIRouter, Header, HTTPException, Request, statusfrom fastapi.responses import JSONResponse+from sie_server.adapters.errors import InputTooLongErrorfrom sie_server.api.helpers import (InferenceErrorHandler,ModelStateChecker,RequestParser,ResponseBuilder,+ ensure_finite_scores,oom_retry_after_from_registry,)from sie_server.api.options import resolve_runtime_options@@ -146,7 +148,7 @@ async def _score_via_worker("Terminal model-load failure (MODEL_LOAD_FAILED). ""Carried in the ``detail`` envelope: ``{code, message, ""error_class, permanent, attempts}``. No ``Retry-After`` "- "header — clients MUST NOT auto-retry. See sie-test#85."+ "header — clients MUST NOT auto-retry."),},503: {"description": "Model not loaded or service unavailable"},@@ -266,11 +268,19 @@ async def score(timing = worker_result.timingexcept QueueFullError as e:raise error_handler.handle_queue_full(e) from e+ except InputTooLongError as e:+ raise error_handler.handle_input_too_long(e) from eexcept ValueError as e:raise error_handler.handle_value_error(e) from eexcept Exception as e:raise error_handler.handle_inference_error(e) from e+ # Fail closed on non-finite (NaN/inf) model output before it reaches+ # serialization: JSON would 500 un-enveloped and msgpack would silently+ # return 200 with the NaN ranked as valid. Checked after the inference+ # try/except so the typed 500 is not re-wrapped by handle_inference_error.+ ensure_finite_scores(scores, model)+# Build responsequery_id = query.idresponse = _build_response(model, query_id, items, scores, score_usage_from_output(score_output))diff --git a/packages/sie_server/src/sie_server/api/serialization.py b/packages/sie_server/src/sie_server/api/serialization.pyindex 83d4c007f..d92802ecc 100644--- a/packages/sie_server/src/sie_server/api/serialization.py+++ b/packages/sie_server/src/sie_server/api/serialization.py@@ -10,13 +10,9 @@ Serialization behavior:from typing import Any-import msgpack-import msgpack_numpy as mimport numpy as npfrom fastapi import Response--# Patch msgpack for numpy support-m.patch()+from sie_sdk._msgpack import packb as pack_msgpackclass MsgPackResponse(Response):@@ -35,9 +31,9 @@ class MsgPackResponse(Response):media_type: str | None = None,background: Any = None,) -> None:- # Serialize directly — TypedDicts are plain dicts and msgpack-numpy- # handles numpy arrays natively, so no pre-processing is needed.- body = msgpack.packb(content, use_bin_type=True)+ # Serialize directly — TypedDicts are plain dicts and the numeric-only+ # codec handles NumPy arrays without process-global MessagePack hooks.+ body = pack_msgpack(content, use_bin_type=True)super().__init__(content=body,status_code=status_code,diff --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 869dda6ad..52deaf472 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@@ -23,7 +23,7 @@ class AppStateConfig:"""models_dir: Path | str | None = None- """Path to models directory (local path, s3://, gs://, abfs://, or abfss://). If None, registry starts empty."""+ """Path to models directory (local path, s3://, gs://, abfs(s)://, or oss://). 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 9b4b65dab..f452b7303 100644--- a/packages/sie_server/src/sie_server/cli.py+++ b/packages/sie_server/src/sie_server/cli.py@@ -25,10 +25,13 @@ if sys.platform == "darwin":import hashlibimport logging+from collections.abc import Iterablefrom pathlib import Pathfrom typing import Annotated+import clickimport typer+from click.core import ParameterSourcefrom sie_sdk.bundle_utils import (ModelAdapterInventory,find_bundle_for_model_adapters,@@ -50,6 +53,8 @@ from sie_server.app.app_state_config import (from sie_server.config.model import ModelConfigfrom sie_server.core.deps import collect_bundle_depsfrom sie_server.core.loader import load_model_configs+from sie_server.core.logging import configure_logging, is_valid_log_level, valid_log_levels+from sie_server.core.model_suggestions import suggest_modelsfrom sie_server.main import run_serverlogger = logging.getLogger(__name__)@@ -106,6 +111,34 @@ def parse_devices(value: str | None) -> list[str] | None:return devices or None+def _echo_suggestions(unknown: Iterable[str], known: Iterable[str]) -> None:+ """Print a ``did you mean`` line per unresolved id, when one is confident.++ Silent when nothing is close enough — a wrong guess is worse than none.+ """+ known = list(known)+ for name in unknown:+ suggestions = suggest_models(name, known)+ if suggestions:+ typer.echo(f" '{name}': did you mean {', '.join(suggestions)}?", err=True)+++def _came_from_command_line(param: str) -> bool:+ """Whether ``param`` was typed on the command line rather than defaulted.++ Options carrying ``envvar=`` reach the handler populated from the+ environment, indistinguishable from a typed flag by value alone. Click+ records where each value came from, so ask it.++ Returns ``False`` when there is no active Click context (direct calls in+ tests), which keeps the lenient path — the strict one is opt-in.+ """+ ctx = click.get_current_context(silent=True)+ if ctx is None:+ return False+ return ctx.get_parameter_source(param) == ParameterSource.COMMANDLINE++def _canonical_model_id(value: str) -> str:"""Normalize model IDs consistently with registry pin matching."""base, separator, profile = value.strip().lower().partition(":")@@ -291,7 +324,7 @@ def serve(models_dir: str = typer.Option(DEFAULT_MODELS_DIR,"--models-dir",- help="Models directory (local path, s3://, gs://, abfs://, or abfss://)",+ help="Models directory (local path, s3://, gs://, abfs(s)://, or oss://)",),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"),@@ -299,7 +332,7 @@ def serve(cluster_cache: str | None = typer.Option(None,"--cluster-cache",- help="Cluster cache URL (s3://, gs://, abfs://, or abfss://)",+ help="Cluster cache URL (s3://, gs://, abfs(s)://, or oss://)",),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"),@@ -321,7 +354,21 @@ def serve("""Start the SIE inference server."""from sie_sdk.storage import is_cloud_path- from sie_server.core.logging import configure_logging+ # An explicit --log-level typo is an immediate, cheap-to-fix mistake at the+ # command line, so reject it rather than starting a server that quietly+ # ignores the flag. A bad SIE_LOG_LEVEL takes the softer path inside+ # configure_logging (a loud warning, no crash) because it comes from a Helm+ # value and must not crash-loop a pod.+ #+ # The parameter is bound to both, so the source has to be asked for+ # explicitly: `envvar="SIE_LOG_LEVEL"` means an unset flag still arrives+ # here carrying the environment's value.+ if _came_from_command_line("log_level") and not is_valid_log_level(log_level):+ typer.echo(+ f"Error: Invalid --log-level {log_level!r}. Valid levels: {', '.join(valid_log_levels())}",+ err=True,+ )+ raise typer.Exit(1)# Configure logging (supports JSON format for Loki compatibility)configure_logging(verbose=verbose, json_format=json_logs or None, level_name=log_level)@@ -399,7 +446,16 @@ def serve(unknown = [m for m in model_filter if m not in all_configs]if unknown:typer.echo(f"Error: Unknown model(s): {', '.join(unknown)}", err=True)- typer.echo(f"Available models: {', '.join(sorted(all_configs.keys())[:10])}...", err=True)+ # The old fallback printed the first ten ids alphabetically, which+ # for this catalog is always the same Alibaba-NLP/BAAI block — no+ # help at all for a mistyped Qwen id. Suggest per unknown id instead.+ _echo_suggestions(unknown, all_configs)+ # Deliberately does not echo --models-dir: it accepts cloud URLs+ # (s3://, abfss://, ...) which can carry a SAS token or embedded+ # credentials, and stderr is collected by CI and container log+ # shippers. The caller just supplied the value, so naming the count+ # is enough.+ typer.echo(f"The configured models directory has {len(all_configs)} model configs.", err=True)raise typer.Exit(1)# Augment the filter with explicitly-allowed extra model ids (opt-in via@@ -419,12 +475,13 @@ def serve(unknown_extra = [m for m in extras if m not in all_configs]if unknown_extra:typer.echo(f"Error: SIE_EXTRA_MODELS unknown model(s): {', '.join(unknown_extra)}", err=True)+ _echo_suggestions(unknown_extra, all_configs)raise typer.Exit(1)model_filter = sorted(set(model_filter) | set(extras))typer.echo(f"Extra models added to filter: {', '.join(extras)}")# Explicit selectors must not escape a release image's dependency boundary.- # Local ``mise run serve -m ...`` has no initial known bundle and keeps the+ # Local ``mise run serve -- -m ...`` has no initial known bundle and keeps the# ad-hoc dependency-resolution path in tools/mise_tasks/serve.bash.if baked_bundle and model_filter is not None:if model_adapters is not None:@@ -559,6 +616,7 @@ def serve(invalid = [m for m in preload_models if m not in model_filter]if invalid:typer.echo(f"Error: Preload model(s) not in model filter: {', '.join(invalid)}", err=True)+ _echo_suggestions(invalid, model_filter)raise typer.Exit(1)typer.echo(f"Preload: {len(preload_models)} models will be loaded at startup")else:@@ -570,6 +628,7 @@ def serve(invalid = [m for m in preload_models if m not in model_filter]if invalid:typer.echo(f"Error: Preload model(s) not in model filter: {', '.join(invalid)}", err=True)+ _echo_suggestions(invalid, model_filter)raise typer.Exit(1)typer.echo(f"Preload (from env): {len(preload_models)} models will be loaded at startup")@@ -583,6 +642,7 @@ def serve(]if invalid:typer.echo(f"Error: Pinned model(s) not in model filter: {', '.join(invalid)}", err=True)+ _echo_suggestions(invalid, model_filter)raise typer.Exit(1)typer.echo(f"Pinned (from env): {len(pinned_models)} models will be kept resident")diff --git a/packages/sie_server/src/sie_server/config/engine.py b/packages/sie_server/src/sie_server/config/engine.pyindex a9dfc854f..ac3aede46 100644--- a/packages/sie_server/src/sie_server/config/engine.py+++ b/packages/sie_server/src/sie_server/config/engine.py@@ -298,6 +298,21 @@ class EngineConfig(BaseSettings):),),] = 0.5+ idle_coalesce_ms: Annotated[+ float,+ Field(+ ge=0.0,+ description=(+ "Accumulation window for the FIRST batch after a worker was "+ "idle (#2874). An idle worker used to dispatch immediately "+ "with whatever was pending, shredding bursty arrivals into a "+ "train of small serialized forwards. With this window the "+ "batcher coalesces until arrivals have been quiet for this "+ "long (bounded by max_batch_wait_ms), so a lone request waits "+ "at most this window. 0 restores immediate idle dispatch."+ ),+ ),+ ] = 3.0max_concurrent_requests: Annotated[int,Field(description="Maximum concurrent requests (queue size)"),diff --git a/packages/sie_server/src/sie_server/core/batcher.py b/packages/sie_server/src/sie_server/core/batcher.pyindex fe45f76dd..9678ffb7c 100644--- a/packages/sie_server/src/sie_server/core/batcher.py+++ b/packages/sie_server/src/sie_server/core/batcher.py@@ -26,8 +26,8 @@ Cost semantics vary by modality (modality-native units):These units are NOT commensurable across modalities, so ``total_cost`` is onlymeaningful within a single modality (the common case — a model's batch is-single-modality). See docs/adr/0004 for why cost is kept modality-native-rather than unified onto a canonical unit.+single-modality), so cost remains modality-native rather than being unified+onto a misleading canonical unit."""from __future__ import annotations@@ -247,7 +247,21 @@ class BatchFormer[I: HasCost, T]:elapsed_ms = (time.monotonic() - self._first_request_time) * 1000return elapsed_ms >= self._config.max_batch_wait_ms- def _coalesce_expired(self) -> bool:+ def _effective_coalesce_ms(self, coalesce_cap_ms: float | None) -> float:+ """Coalesce window for the current wait, optionally capped by the caller.++ ``coalesce_cap_ms`` is the idle-dispatch accumulation window (#2874):+ a worker that was idle passes a small cap so the first batch after+ idleness still coalesces burst-mates instead of dispatching a+ degenerate batch-of-1, while a lone request only ever waits the cap+ rather than the full busy-path coalesce window.+ """+ effective = self._config.effective_coalesce_ms+ if coalesce_cap_ms is not None:+ effective = min(effective, coalesce_cap_ms)+ return effective++ def _coalesce_expired(self, coalesce_cap_ms: float | None = None) -> bool:"""Check if the coalescing window has expired (no new items recently).Returns True when items are pending and no new items have arrived@@ -257,17 +271,18 @@ class BatchFormer[I: HasCost, T]:Uses effective_coalesce_ms which scales proportionally withmax_batch_wait_ms to stay relevant across the adaptive range.+ ``coalesce_cap_ms`` additionally caps the window (idle dispatch, #2874)."""if self._last_submit_time is None or not self._pending:return Falseelapsed_ms = (time.monotonic() - self._last_submit_time) * 1000- return elapsed_ms >= self._config.effective_coalesce_ms+ return elapsed_ms >= self._effective_coalesce_ms(coalesce_cap_ms)- def _should_yield_batch(self) -> bool:+ def _should_yield_batch(self, coalesce_cap_ms: float | None = None) -> bool:"""Check if batch should be yielded (full, timeout, or coalesced)."""if len(self._pending) == 0:return False- return self._batch_is_full() or self._batch_timeout_expired() or self._coalesce_expired()+ return self._batch_is_full() or self._batch_timeout_expired() or self._coalesce_expired(coalesce_cap_ms)async def submit(self, item: I, metadata: T) -> None:"""Submit an item for batching.@@ -310,18 +325,32 @@ class BatchFormer[I: HasCost, T]:if self._should_yield_batch() or is_first_request:self._batch_ready.set()- async def get_batch(self, *, immediate: bool = False) -> FormattedBatch[I, T]:+ async def get_batch(+ self,+ *,+ immediate: bool = False,+ coalesce_cap_ms: float | None = None,+ ) -> FormattedBatch[I, T]:"""Wait for and return the next batch.Blocks until:- Batch is full (cost or request limit reached), OR- Timeout expires after first request, OR+ - Coalesce window (optionally capped) expires, OR- immediate=True and any items are pendingArgs:immediate: If True, yield immediately when any items are pendingwithout waiting for timeout. Used when the worker was idleto eliminate unnecessary batch wait at low concurrency.+ coalesce_cap_ms: Optional cap on the coalesce window for THIS+ wait. The idle-dispatch accumulation window (#2874): the+ worker passes a small single-digit-ms cap after idleness so+ bursty arrivals fuse into one batch instead of a train of+ immediate batch-of-1 dispatches, while a lone request never+ waits longer than the cap once arrivals stop. The+ ``max_batch_wait_ms`` first-request timeout still bounds the+ total wait.Returns:FormattedBatch with items sorted by cost (ascending).@@ -329,12 +358,12 @@ class BatchFormer[I: HasCost, T]:"""while True:async with self._lock:- if self._should_yield_batch() or (immediate and len(self._pending) > 0):+ if self._should_yield_batch(coalesce_cap_ms) or (immediate and len(self._pending) > 0):# _extract_batch already sorts by cost and respects limits- return self._extract_batch()+ return self._extract_batch(coalesce_cap_ms=coalesce_cap_ms)# Wait for batch ready signal or timeout- timeout_s = self._get_wait_timeout()+ timeout_s = self._get_wait_timeout(coalesce_cap_ms)with contextlib.suppress(TimeoutError):await asyncio.wait_for(self._batch_ready.wait(),@@ -344,13 +373,14 @@ class BatchFormer[I: HasCost, T]:# Clear event for next batchself._batch_ready.clear()- def _get_wait_timeout(self) -> float | None:+ def _get_wait_timeout(self, coalesce_cap_ms: float | None = None) -> float | None:"""Calculate how long to wait for more requests.Returns the shorter of:- Time remaining in the batch formation window (max_batch_wait_ms)- - Time remaining until the coalesce window expires (based on when the- last item was submitted, not a fixed polling interval)+ - Time remaining until the (optionally capped) coalesce window+ expires (based on when the last item was submitted, not a fixed+ polling interval)This ensures precise coalesce detection: the sleep duration is exactlythe time until coalesce fires, rather than polling every coalesce_ms.@@ -363,7 +393,7 @@ class BatchFormer[I: HasCost, T]:batch_remaining_ms = max(0, self._config.max_batch_wait_ms - elapsed_ms)# Compute actual time remaining until coalesce fires- coalesce_ms = self._config.effective_coalesce_ms+ coalesce_ms = self._effective_coalesce_ms(coalesce_cap_ms)if self._last_submit_time is not None:since_last_submit_ms = (now - self._last_submit_time) * 1000coalesce_remaining_ms = max(0, coalesce_ms - since_last_submit_ms)@@ -373,7 +403,11 @@ class BatchFormer[I: HasCost, T]:effective_ms = min(batch_remaining_ms, coalesce_remaining_ms)return effective_ms / 1000 # Convert to seconds- def _extract_batch(self, max_items: int | None = None) -> FormattedBatch[I, T]:+ def _extract_batch(+ self,+ max_items: int | None = None,+ coalesce_cap_ms: float | None = None,+ ) -> FormattedBatch[I, T]:"""Extract an optimal sub-batch from pending requests.Algorithm:@@ -389,11 +423,15 @@ class BatchFormer[I: HasCost, T]:continuous-batch drain to a caller-held snapshot budget sopost-snapshot arrivals are not swept in ahead of the next FCFSselection. See #1606.+ coalesce_cap_ms: The coalesce cap the caller used to decide the+ yield (#2874), threaded through so the logged trigger matches+ the actual yield reason (a capped-coalesce dispatch logs+ ``coalesced``, not ``immediate``)."""# Track why batch was triggered (must check BEFORE extracting items)was_full = self._batch_is_full()was_timeout = self._batch_timeout_expired()- was_coalesced = self._coalesce_expired()+ was_coalesced = self._coalesce_expired(coalesce_cap_ms)pending_before = len(self._pending)cost_before = self._total_cost@@ -472,6 +510,28 @@ class BatchFormer[I: HasCost, T]:return self._extract_batch()return None+ def drain_pending(self) -> list[T]:+ """Remove every pending request and return their metadata.++ Used by ``ModelWorker.stop()`` to fail the futures of work that will+ never run because the worker is going away. Returns one entry per+ pending *item*; a multi-item request appears once per item, so+ callers that act on the metadata must deduplicate.++ Deliberately synchronous, and deliberately does not take ``_lock``.+ It runs on the event loop, and every ``_lock`` critical section in+ this class is await-free, so no lock holder can be suspended+ mid-mutation for this call to interleave with. Taking the lock would+ require an ``await``, which is exactly what a caller unwinding a+ cancellation cannot do.+ """+ metadata = [request.metadata for request in self._pending]+ self._pending = []+ self._total_cost = 0+ self._first_request_time = None+ self._last_submit_time = None+ return metadata+async def try_drain(self, max_items: int | None = None) -> FormattedBatch[I, T] | None:"""Drain accumulated items immediately, bypassing batch timeout.diff --git a/packages/sie_server/src/sie_server/core/disk_cache.py b/packages/sie_server/src/sie_server/core/disk_cache.pyindex d91a3ee12..b2fca2300 100644--- a/packages/sie_server/src/sie_server/core/disk_cache.py+++ b/packages/sie_server/src/sie_server/core/disk_cache.py@@ -19,6 +19,10 @@ import shutilfrom collections.abc import Callablefrom dataclasses import dataclass, fieldfrom pathlib import Path+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from huggingface_hub import HFCacheInfologger = logging.getLogger(__name__)@@ -169,26 +173,51 @@ class ModelDiskCacheManager:stats = self.get_stats()return stats.usage_ratio > self._threshold- def get_cached_models(self) -> list[CachedModelInfo]:- """Get all cached models sorted by last access time (oldest first).+ def _scan_cache(self) -> HFCacheInfo | None:+ """Walk the whole cache directory once.- Uses huggingface_hub's scan_cache_dir() to inspect the cache.+ This is the expensive operation in this module: it stats every blob of+ every repo, so callers should scan once and reuse the result.Returns:- List of CachedModelInfo sorted by last_accessed (LRU order).+ The scan result, or None if huggingface_hub is unavailable or the+ scan failed."""try:from huggingface_hub import scan_cache_direxcept ImportError:logger.warning("huggingface_hub not available, cannot scan cache")- return []+ return Nonetry:- cache_info = scan_cache_dir(self._cache_dir)+ return scan_cache_dir(self._cache_dir)except Exception as e: # noqa: BLE001 — huggingface_hub scan errors are variedlogger.warning("Failed to scan cache at %s: %s", self._cache_dir, e)+ return None++ def get_cached_models(self) -> list[CachedModelInfo]:+ """Get all cached models sorted by last access time (oldest first).++ Uses huggingface_hub's scan_cache_dir() to inspect the cache.++ Returns:+ List of CachedModelInfo sorted by last_accessed (LRU order).+ """+ cache_info = self._scan_cache()+ if cache_info is None:return []+ return self._models_from_scan(cache_info)++ @staticmethod+ def _models_from_scan(cache_info: HFCacheInfo) -> list[CachedModelInfo]:+ """Project a cache scan into model infos sorted LRU-first.++ Args:+ cache_info: A scan result from :meth:`_scan_cache`.+ Returns:+ List of CachedModelInfo sorted by last_accessed (LRU order).+ """models: list[CachedModelInfo] = []for repo in cache_info.repos:@@ -242,13 +271,18 @@ class ModelDiskCacheManager:return None- def evict_model(self, model: CachedModelInfo) -> int:+ def evict_model(self, model: CachedModelInfo, cache_info: HFCacheInfo | None = None) -> int:"""Delete a model from the disk cache.Uses huggingface_hub's delete_revisions() for safe deletion.Args:model: The model to evict.+ cache_info: Optional cache scan the delete strategy is computed+ from. Pass a scan that already covers ``model`` to avoid a+ second full cache walk; omit it to scan now. A scan that has+ gone stale is safe: unknown revisions are skipped with a+ warning and already-deleted paths are ignored.Returns:Number of bytes freed.@@ -257,15 +291,18 @@ class ModelDiskCacheManager:logger.warning("No commit hashes for model %s, cannot evict", model.repo_id)return 0- try:- from huggingface_hub import scan_cache_dir- except ImportError:- logger.warning("huggingface_hub not available, cannot evict")- return 0+ if cache_info is None:+ cache_info = self._scan_cache()+ if cache_info is None:+ return 0try:- cache_info = scan_cache_dir(self._cache_dir)delete_strategy = cache_info.delete_revisions(*model.commit_hashes)+ if delete_strategy.expected_freed_size == 0:+ # The scan named revisions the cache no longer has (deleted+ # concurrently, or already evicted), so there is nothing to free.+ logger.debug("Nothing left to free for model %s, skipping", model.repo_id)+ return 0logger.info("Evicting model '%s' from disk cache (will free %s)",@@ -303,8 +340,30 @@ class ModelDiskCacheManager:if self._pinned_provider is not None:exclude |= self._pinned_provider()+ # Scanning the cache walks and stats every blob, so it happens at most+ # once per call: victims are taken from that LRU-ordered snapshot and+ # only the cheap disk_usage check runs between evictions. Deletions are+ # reflected by that check, so freed space needs no rescan. The snapshot+ # going stale is safe — the cursor only moves forward (so the loop can+ # never spin), and a model that vanished concurrently frees nothing and+ # is skipped like any other failed eviction.+ candidates: list[CachedModelInfo] | None = None+ cache_info: HFCacheInfo | None = None+ cursor = 0+while self.check_pressure():- lru_model = self.get_lru_model(exclude=exclude)+ if candidates is None:+ cache_info = self._scan_cache()+ candidates = [] if cache_info is None else self._models_from_scan(cache_info)++ lru_model: CachedModelInfo | None = None+ while cursor < len(candidates):+ candidate = candidates[cursor]+ cursor += 1+ if candidate.repo_id not in exclude:+ lru_model = candidate+ break+if lru_model is None:# No more models to evictstats = self.get_stats()@@ -314,7 +373,7 @@ class ModelDiskCacheManager:)break- freed = self.evict_model(lru_model)+ freed = self.evict_model(lru_model, cache_info=cache_info)if freed > 0:evicted.append(lru_model.repo_id)logger.info(@@ -322,9 +381,6 @@ class ModelDiskCacheManager:lru_model.repo_id,_format_bytes(freed),)- else:- # Failed to evict, add to exclude to avoid infinite loop- exclude.add(lru_model.repo_id)return evicteddiff --git a/packages/sie_server/src/sie_server/core/extract_cost.py b/packages/sie_server/src/sie_server/core/extract_cost.pyindex 66e177f6b..84bacc8b1 100644--- a/packages/sie_server/src/sie_server/core/extract_cost.py+++ b/packages/sie_server/src/sie_server/core/extract_cost.py@@ -32,7 +32,7 @@ adopt it without coordinating on a calibration table.from __future__ import annotations-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Finalfrom sie_server.core.prepared import ExtractPreparedItemfrom sie_server.types.inputs import is_document_input@@ -40,6 +40,12 @@ from sie_server.types.inputs import is_document_inputif TYPE_CHECKING:from sie_server.types.inputs import Item+# Upper bound on the number of entity labels a single extract request may carry.+# GLiNER-family adapters run one forward pass per label, so an unbounded label+# list is an uncapped compute vector on a public endpoint. Mirrors the score /+# rerank candidate cap (``MAX_SCORE_ITEMS``) in magnitude and named-400 shape.+MAX_EXTRACT_LABELS: Final[int] = 1000+def extract_item_cost(item: Item,diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.pyindex 1785373ef..4142e1903 100644--- a/packages/sie_server/src/sie_server/core/loader.py+++ b/packages/sie_server/src/sie_server/core/loader.py@@ -117,7 +117,7 @@ def load_model_configs(models_dir: Path | str, *, require_pinned_revision: bool"""Load all model configs from a directory (local or cloud).Args:- models_dir: Path to the models directory (local path, s3://, gs://, abfs://, or abfss://).+ models_dir: Path to the models directory (local path, s3://, gs://, abfs(s)://, or oss://).require_pinned_revision: When True, reject any HF-backed config that does not pin animmutable ``hf_revision``. Off by default so the full dev catalog(which carries an unpinned long tail) still loads; the managed serving/stagingdiff --git a/packages/sie_server/src/sie_server/core/logging.py b/packages/sie_server/src/sie_server/core/logging.pyindex 0e779d726..675828773 100644--- a/packages/sie_server/src/sie_server/core/logging.py+++ b/packages/sie_server/src/sie_server/core/logging.py@@ -71,13 +71,62 @@ class TextFormatter(logging.Formatter):)-def _resolve_log_level(*, verbose: bool, level_name: str | None) -> int:- """Pick root log level: ``--verbose`` wins, then explicit name, then ``SIE_LOG_LEVEL`` env."""+# The single source of truth for both validation and resolution. Deliberately+# narrower than ``logging.getLevelNamesMapping()``, which also carries NOTSET+# and the deprecated WARN/FATAL aliases: validating against the wider set while+# advertising this one would accept names the CLI help does not document, and+# NOTSET on the root logger means "inherit", not a severity.+_LEVELS: dict[str, int] = {+ "DEBUG": logging.DEBUG,+ "INFO": logging.INFO,+ "WARNING": logging.WARNING,+ "ERROR": logging.ERROR,+ "CRITICAL": logging.CRITICAL,+}++# A rejected value is arbitrary caller/environment input, so it is truncated and+# stripped of anything but plain identifier characters before being logged — a+# level name never needs more, and an operator who accidentally pointed+# SIE_LOG_LEVEL at a secret must not have it copied into the log sink.+_REJECTED_MAX_LEN = 20+++def valid_log_levels() -> list[str]:+ """Accepted level names, in ascending severity order."""+ return list(_LEVELS)+++def is_valid_log_level(name: str) -> bool:+ """Whether ``name`` is one of the advertised levels (case-insensitive)."""+ return name.strip().upper() in _LEVELS+++def _safe_for_log(value: str) -> str:+ """Render a rejected level name without echoing arbitrary input."""+ cleaned = "".join(char if char.isalnum() or char in "-_" else "?" for char in value.strip())+ if len(cleaned) > _REJECTED_MAX_LEN:+ return cleaned[:_REJECTED_MAX_LEN] + "..."+ return cleaned or "(empty)"+++def _resolve_log_level(*, verbose: bool, level_name: str | None) -> tuple[int, str | None]:+ """Pick root log level: ``--verbose`` wins, then explicit name, then ``SIE_LOG_LEVEL`` env.++ Returns:+ ``(level, rejected_name)``. ``rejected_name`` is the caller's value when+ it is not an advertised level, so :func:`configure_logging` can say so+ once logging is actually running. Silently defaulting to INFO is the+ worst outcome: an operator who set ``DEBUG`` and mistyped it sees a+ normal-looking server with none of the output they asked for, and no+ indication why.+ """if verbose:- return logging.DEBUG+ return logging.DEBUG, Noneraw = (level_name or os.environ.get("SIE_LOG_LEVEL") or "INFO").strip()- mapping = logging.getLevelNamesMapping()- return mapping.get(raw.upper(), logging.INFO)+ resolved = _LEVELS.get(raw.upper())+ if resolved is None:+ return logging.INFO, raw+ return resolved, Nonedef configure_logging(@@ -93,7 +142,7 @@ def configure_logging(json_format: Use JSON format. If None, reads from SIE_LOG_JSON env var.level_name: Log level name (e.g. ``DEBUG``, ``INFO``). When None, uses ``SIE_LOG_LEVEL``."""- log_level = _resolve_log_level(verbose=verbose, level_name=level_name)+ log_level, rejected = _resolve_log_level(verbose=verbose, level_name=level_name)# Determine format (env var takes precedence if json_format not explicitly set)if json_format is None:@@ -121,6 +170,16 @@ def configure_logging(# Set sie_server modules to appropriate levellogging.getLogger("sie_server").setLevel(log_level)+ # Emitted only now, with handlers installed, so the warning is actually+ # visible. WARNING is above the INFO fallback, so it survives the very+ # downgrade it is reporting.+ if rejected is not None:+ logging.getLogger(__name__).warning(+ "Ignoring unknown log level %r; falling back to INFO. Valid levels: %s.",+ _safe_for_log(rejected),+ ", ".join(valid_log_levels()),+ )+# Reduce noise from third-party librarieslogging.getLogger("uvicorn.access").setLevel(logging.WARNING)logging.getLogger("httpx").setLevel(logging.WARNING)diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.pyindex 96d5a3704..ec8fdf967 100644--- a/packages/sie_server/src/sie_server/core/model_loader.py+++ b/packages/sie_server/src/sie_server/core/model_loader.py@@ -136,6 +136,7 @@ class ModelLoader:max_batch_wait_ms: float | None = None,coalesce_ms: float | None = None,coalesce_ratio: float | None = None,+ idle_coalesce_ms: float | None = None,max_queue_size: int | None = None,instrumentation: bool = False,max_loras_per_model: int = DEFAULT_MAX_LORAS,@@ -162,6 +163,7 @@ class ModelLoader:self._max_batch_wait_ms = max_batch_wait_msself._coalesce_ms = coalesce_msself._coalesce_ratio = coalesce_ratio+ self._idle_coalesce_ms = idle_coalesce_msself._max_queue_size = max_queue_sizeself._instrumentation = instrumentationself._max_loras_per_model = max_loras_per_model@@ -610,6 +612,9 @@ class ModelLoader:max_batch_requests=self._max_batch_requests or WorkerConfig().max_batch_requests,max_batch_wait_ms=self._max_batch_wait_ms or WorkerConfig().max_batch_wait_ms,coalesce_ms=self._coalesce_ms if self._coalesce_ms is not None else WorkerConfig().coalesce_ms,+ idle_coalesce_ms=(+ self._idle_coalesce_ms if self._idle_coalesce_ms is not None else WorkerConfig().idle_coalesce_ms+ ),coalesce_ratio=self._coalesce_ratio if self._coalesce_ratio is not None else WorkerConfig().coalesce_ratio,max_queue_size=self._max_queue_size or WorkerConfig().max_queue_size,instrumentation=self._instrumentation,@@ -830,6 +835,13 @@ def _raise_if_adapter_startup_timeout(name: str, started: float, exc: RuntimeErrfrom its subprocess health poll. Pattern-match on the message; narrow enoughto not bucket genuine runtime failures as timeouts. Other adapters that growtheir own startup timeouts should follow the same convention.++ A child process that CRASHED during startup deliberately does not match:+ the adapters raise the distinct "... process exited during startup" message+ for that case, which stays a plain load failure. On the genuine-timeout+ path ``timeout_s=elapsed`` below is an approximation that only holds+ because the health poll ran the budget out (run 32945082497 showed the+ old crash-as-timeout labeling reporting a 16.5s crash as configured=16s)."""msg = str(exc).lower()if "failed to start within timeout" not in msg and "startup timeout" not in msg:diff --git a/packages/sie_server/src/sie_server/core/model_suggestions.py b/packages/sie_server/src/sie_server/core/model_suggestions.pynew file mode 100644index 000000000..9351d3266--- /dev/null+++ b/packages/sie_server/src/sie_server/core/model_suggestions.py@@ -0,0 +1,87 @@+"""Near-match suggestions for unknown model ids.++The catalog carries ~160 models keyed by their full canonical id+(``BAAI/bge-m3``, ``Alibaba-NLP/gte-Qwen2-1.5B-instruct``). There is no+short-name aliasing, so a caller who drops the org prefix, mistypes a case,+or misremembers a suffix gets an exact-match miss. "Model 'X' not found" then+leaves them to guess against a list they cannot see.++Two lookup mistakes dominate, and plain edit distance only catches one:++- **a missing or wrong org prefix** (``bge-m3`` for ``BAAI/bge-m3``) — handled+ by matching the part after the last ``/`` as well as the whole id, so a+ short name still surfaces its owner;+- **a typo or case slip** (``BAAI/bge-M3``, ``qwen/Qwen3-0.6B``) — handled by+ case-insensitive fuzzy matching.++Suggestions are advisory: they only ever add a sentence to an error that is+raised regardless.+"""++from __future__ import annotations++import difflib+from collections.abc import Iterable++# Below this similarity the "suggestion" is noise; the caller is better served+# by the bare "not found" than by a confidently wrong guess.+_SIMILARITY_CUTOFF = 0.6++MAX_SUGGESTIONS = 3+++def _basename(model_id: str) -> str:+ """The id without its org prefix (``BAAI/bge-m3`` -> ``bge-m3``)."""+ return model_id.rpartition("/")[2]+++def suggest_models(unknown: str, known: Iterable[str], *, limit: int = MAX_SUGGESTIONS) -> list[str]:+ """Return catalog ids closest to ``unknown``, best first.++ Args:+ unknown: The id the caller asked for.+ known: Every id the catalog serves.+ limit: Maximum suggestions to return.++ Returns:+ Up to ``limit`` ids from ``known``, ordered best-match first. Empty+ when nothing is close enough to be worth printing.+ """+ query = unknown.strip().lower()+ if not query or limit <= 0:+ return []++ candidates = [model_id for model_id in known if model_id]+ if not candidates:+ return []++ # Score each id on its best reading: the whole id, or just its basename.+ # A bare "bge-m3" scores 1.0 against BAAI/bge-m3's basename, so the exact+ # model the caller meant sorts above coincidentally similar full ids.+ scored: list[tuple[float, str]] = []+ query_base = _basename(query)+ for model_id in candidates:+ lowered = model_id.lower()+ score = max(+ difflib.SequenceMatcher(None, query, lowered).ratio(),+ difflib.SequenceMatcher(None, query_base, _basename(lowered)).ratio(),+ )+ if score >= _SIMILARITY_CUTOFF:+ scored.append((score, model_id))++ # Sort by descending score, then by id so equal scores stay deterministic.+ scored.sort(key=lambda pair: (-pair[0], pair[1]))+ return [model_id for _score, model_id in scored[:limit]]+++def suggestion_suffix(unknown: str, known: Iterable[str], *, limit: int = MAX_SUGGESTIONS) -> str:+ """A ``. Did you mean ...?`` fragment to append to a not-found message.++ Returns an empty string when there is no confident suggestion, so callers+ can append it unconditionally.+ """+ matches = suggest_models(unknown, known, limit=limit)+ if not matches:+ return ""+ quoted = ", ".join(f"'{model_id}'" for model_id in matches)+ return f" Did you mean {quoted}?"diff --git a/packages/sie_server/src/sie_server/core/prepared.py b/packages/sie_server/src/sie_server/core/prepared.pyindex 57042de08..2cfa3828e 100644--- a/packages/sie_server/src/sie_server/core/prepared.py+++ b/packages/sie_server/src/sie_server/core/prepared.py@@ -85,7 +85,7 @@ class PreparedItem[T: Payload]:cost: Per-modality batching budget in modality-native units (text =token count, image = 1, tiled vision = tile count). NOT comparableacross modalities; the BatchFormer sum is only meaningful within- one modality. See docs/adr/0004.+ one modality.original_index: Position in original request for result reordering."""@@ -301,7 +301,7 @@ LightOnOCRPreparedItem = PreparedItem[LightOnOCRPayload]class PaddleOCRVLPayload(Payload):"""Preprocessed PaddleOCR-VL input ready for extraction.- PaddleOCR-VL combines a NaViT-style SigLIP vision encoder with an+ PaddleOCR-VL-1.5 combines a NaViT-style SigLIP vision encoder with anERNIE-4.5-0.3B decoder. The processor tokenizes a chat-template promptand emits a Qwen-VL-style ``image_grid_thw`` alongside ``pixel_values``."""diff --git a/packages/sie_server/src/sie_server/core/preprocessor/image.py b/packages/sie_server/src/sie_server/core/preprocessor/image.pyindex 8b33eae79..2b8903123 100644--- a/packages/sie_server/src/sie_server/core/preprocessor/image.py+++ b/packages/sie_server/src/sie_server/core/preprocessor/image.py@@ -6,13 +6,12 @@ image-text models like CLIP and SigLIP that take single images.from __future__ import annotations-import ioimport threadingfrom collections.abc import Callablefrom typing import TYPE_CHECKING, Anyfrom sie_server.core.prepared import ImagePayload, PreparedBatch, PreparedItem-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:import torch@@ -104,8 +103,6 @@ class ImagePreprocessor:Returns:PreparedBatch with ImagePayload items."""- from PIL import Image as PILImage-prepared_items: list[PreparedItem[ImagePayload]] = []total_cost = 0@@ -115,18 +112,29 @@ class ImagePreprocessor:for i, item in enumerate(items):if not item.images:- # Skip items without images (they may be text-only)+ # Text-only items pass through with an empty payload (the same+ # shape the no-preprocessor fallback emits) so the prepared+ # batch stays aligned 1:1 with the request items. Dropping them+ # starves the worker's per-item completion check and the+ # request future never resolves (#3136); adapters that+ # partition by modality (CLIP/SigLIP) encode them via the text+ # tower.+ prepared_items.append(+ PreparedItem(+ payload=ImagePayload(pixel_values=None, original_size=(0, 0)),+ cost=1,+ original_index=i,+ )+ )+ total_cost += 1continue- # Load first image from bytes+ # Load first image from bytes; undecodable or non-bytes payloads+ # raise InvalidMediaError (-> 400 INVALID_INPUT) naming the item.img_input = item.images[0]- pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))+ pil_img = decode_image(img_input, item_index=i, image_index=0)original_size = pil_img.size- # Convert to RGB if needed- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")-# Process through HuggingFace processorprocessed = processor(images=pil_img, return_tensors="pt")pixel_values = processed["pixel_values"].squeeze(0) # Remove batch dim@@ -162,13 +170,13 @@ class ImagePreprocessor:"""import torch- if not prepared:+ # Text passthrough entries carry no tensor (#3136); collation covers+ # the image payloads only, in prepared order.+ tensors = [p.payload.pixel_values for p in prepared if p.payload.pixel_values is not None]+ if not tensors:return {"pixel_values": torch.tensor([])}- # Stack pixel values into batch- pixel_values = torch.stack([p.payload.pixel_values for p in prepared])-- return {"pixel_values": pixel_values.to(device)}+ return {"pixel_values": torch.stack(tensors).to(device)}class OpenCLIPImagePreprocessor:@@ -236,25 +244,30 @@ class OpenCLIPImagePreprocessor:Returns:PreparedBatch with ImagePayload items."""- from PIL import Image as PILImage-prepared_items: list[PreparedItem[ImagePayload]] = []total_cost = 0for i, item in enumerate(items):if not item.images:- # Skip items without images (they may be text-only)+ # Text-only items pass through with an empty payload — same+ # aligned-batch contract as ``ImagePreprocessor.prepare``+ # (#3136).+ prepared_items.append(+ PreparedItem(+ payload=ImagePayload(pixel_values=None, original_size=(0, 0)),+ cost=1,+ original_index=i,+ )+ )+ total_cost += 1continue- # Load first image from bytes+ # Load first image from bytes; undecodable or non-bytes payloads+ # raise InvalidMediaError (-> 400 INVALID_INPUT) naming the item.img_input = item.images[0]- pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))+ pil_img = decode_image(img_input, item_index=i, image_index=0)original_size = pil_img.size- # Convert to RGB if needed- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")-# open_clip val_preproc returns a [C, H, W] tensor (no batch dim)pixel_values = self._val_preproc(pil_img)@@ -289,10 +302,10 @@ class OpenCLIPImagePreprocessor:"""import torch- if not prepared:+ # Text passthrough entries carry no tensor (#3136); collation covers+ # the image payloads only, in prepared order.+ tensors = [p.payload.pixel_values for p in prepared if p.payload.pixel_values is not None]+ if not tensors:return {"pixel_values": torch.tensor([])}- # Stack pixel values into batch- pixel_values = torch.stack([p.payload.pixel_values for p in prepared])-- return {"pixel_values": pixel_values.to(device)}+ return {"pixel_values": torch.stack(tensors).to(device)}diff --git a/packages/sie_server/src/sie_server/core/preprocessor/vision.py b/packages/sie_server/src/sie_server/core/preprocessor/vision.pyindex e9b8446aa..b268f56fd 100644--- a/packages/sie_server/src/sie_server/core/preprocessor/vision.py+++ b/packages/sie_server/src/sie_server/core/preprocessor/vision.py@@ -9,7 +9,6 @@ This module contains specialized vision preprocessors for:from __future__ import annotations-import ioimport loggingfrom typing import TYPE_CHECKING, Any@@ -26,7 +25,7 @@ from sie_server.core.prepared import (PreparedItem,)from sie_server.core.preprocessor.base import get_image_executor-from sie_server.types.inputs import media_bytes+from sie_server.types.inputs import decode_imageif TYPE_CHECKING:import torch@@ -76,20 +75,18 @@ def collect_detection_prepared_items(return pixel_values, pixel_mask, original_sizes, image_indices-def _load_rgb(media: object) -> PILImage.Image:+def _load_rgb(media: object, *, item_index: int | None = None) -> PILImage.Image:"""Decode a wire image input into an RGB PIL image.- Centralizes the ``PILImage.open(io.BytesIO(media_bytes(...)))`` + RGB-convert- idiom that every vision preprocessor repeated. ``media_bytes`` raises- ``InvalidMediaError`` (-> 400 INVALID_INPUT) on a non-bytes payload rather- than hitting a raw ``TypeError`` deep in the decode. See issue #1540.+ Thin wrapper over :func:`sie_server.types.inputs.decode_image`, which owns+ the decode + RGB-convert idiom that every vision preprocessor repeated+ (#1540) and raises ``InvalidMediaError`` (-> 400 INVALID_INPUT) on a+ non-bytes payload or undecodable image bytes rather than hitting a raw+ ``TypeError``/``UnidentifiedImageError`` deep in the decode. Every caller+ decodes the item's first image, so the JSON path names ``images[0]``;+ ``item_index`` is the request-local item index when the caller knows it."""- from PIL import Image as PILImage # deferred: PIL is an optional dependency-- img = PILImage.open(io.BytesIO(media_bytes(media, kind="image")))- if img.mode != "RGB":- img = img.convert("RGB")- return img+ return decode_image(media, kind="image", item_index=item_index, image_index=0)def _find_closest_aspect_ratio(@@ -295,7 +292,7 @@ class NemoColEmbedPreprocessor:# Load image from bytesimg_input = item.images[0]- pil_img = _load_rgb(img_input)+ pil_img = _load_rgb(img_input, item_index=i)original_size = pil_img.size# Dynamic tiling@@ -572,7 +569,7 @@ class Florence2Preprocessor:# Load image from bytes - PIL releases GIL during decodeimg_input = item.images[0]- pil_img = _load_rgb(img_input)+ pil_img = _load_rgb(img_input, item_index=index)original_size = (pil_img.width, pil_img.height)# Process through Florence-2 processor (CPU-bound, releases GIL)@@ -760,7 +757,7 @@ class DonutPreprocessor:# Load image from bytes - PIL releases GIL during decodeimg_input = item.images[0]- pil_img = _load_rgb(img_input)+ pil_img = _load_rgb(img_input, item_index=index)original_size = (pil_img.width, pil_img.height)# Process image through Donut processor (CPU-bound, releases GIL)@@ -965,7 +962,7 @@ class LightOnOCRPreprocessor:return Noneimg_input = item.images[0]- pil_img = _load_rgb(img_input)+ pil_img = _load_rgb(img_input, item_index=index)original_size = (pil_img.width, pil_img.height)inputs = self._processor(@@ -1141,7 +1138,7 @@ class GlmOcrPreprocessor:return Noneimg_input = item.images[0]- pil_img = _load_rgb(img_input)+ pil_img = _load_rgb(img_input, item_index=index)original_size = (pil_img.width, pil_img.height)text = instruction or self._user_text@@ -1314,10 +1311,11 @@ class DetectionPreprocessor:return Noneimg = item.images[0]- # Load image from bytes - PIL releases GIL during decode. media_bytes- # raises InvalidMediaError (-> 400 INVALID_INPUT) on a non-bytes payload- # rather than silently dropping the item or hitting a raw TypeError.- pil_img = _load_rgb(img)+ # Load image from bytes - PIL releases GIL during decode. _load_rgb+ # raises InvalidMediaError (-> 400 INVALID_INPUT) on a non-bytes or+ # undecodable payload rather than silently dropping the item or hitting+ # a raw TypeError.+ pil_img = _load_rgb(img, item_index=index)original_size = (pil_img.width, pil_img.height)# Run image_processor to produce tensor (resize, normalize)@@ -1416,7 +1414,7 @@ class DetectionPreprocessor:}-# Canonical task -> prompt mapping from the PaddleOCR-VL model card+# Canonical task -> prompt mapping from the PaddleOCR-VL-1.5 model card# (PROMPTS dict in the README; trailing colons included). Keep in sync with# PaddleOCRVLAdapter._VALID_TASKS._PADDLEOCR_VL_TASK_PROMPTS: dict[str, str] = {@@ -1490,7 +1488,7 @@ class PaddleOCRVLPreprocessor:return Noneimg_input = item.images[0]- pil_img = _load_rgb(img_input)+ pil_img = _load_rgb(img_input, item_index=index)original_size = (pil_img.width, pil_img.height)inputs = self._processor(@@ -1659,7 +1657,7 @@ class MinerUVLPreprocessor:return Noneimg_input = item.images[0]- pil_img = _load_rgb(img_input)+ pil_img = _load_rgb(img_input, item_index=index)original_size = (pil_img.width, pil_img.height)inputs = self._processor(diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex 8d548e526..6e7fa5d6a 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -13,6 +13,7 @@ Model loading workflow is delegated to ModelLoader.from __future__ import annotationsimport asyncio+import contextlibimport hashlibimport jsonimport logging@@ -184,7 +185,7 @@ class ModelRegistry:"""Initialize the registry.Args:- models_dir: Path to models directory (local path, s3://, gs://, abfs://, or abfss://).+ models_dir: Path to models directory (local path, s3://, gs://, abfs(s)://, or oss://).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.@@ -338,6 +339,7 @@ class ModelRegistry:max_batch_wait_ms=engine_config.max_batch_wait_ms if engine_config else None,coalesce_ms=engine_config.coalesce_ms if engine_config else None,coalesce_ratio=engine_config.coalesce_ratio if engine_config else None,+ idle_coalesce_ms=engine_config.idle_coalesce_ms if engine_config else None,max_queue_size=engine_config.max_concurrent_requests if engine_config else None,instrumentation=engine_config.instrumentation if engine_config else False,max_loras_per_model=engine_config.max_loras_per_model if engine_config else DEFAULT_MAX_LORAS,@@ -1278,6 +1280,35 @@ class ModelRegistry:cleared += 1return cleared+ async def _run_adapter_unload(self, adapter: ModelAdapter, name: str) -> None:+ """Run the blocking ``adapter.unload()`` on a worker thread.++ Shielded, and awaited again if we are cancelled. Once teardown has+ begun it must be allowed to finish: ``_do_unload``'s ``finally``+ drops the model's MemoryManager entry and the load lock is released+ as the exception unwinds, so returning early would expose a window+ in which a concurrent load sizes itself against VRAM this adapter+ has not released yet. A second cancellation is only reachable at+ process exit, where the accounting no longer matters.++ Adapters that need the event loop for teardown expose+ ``aclose_client()``, which the caller has already driven to+ completion above; ``unload()`` itself is a synchronous contract on+ every adapter and is safe off the loop.+ """+ loop = asyncio.get_running_loop()+ unload_future = loop.run_in_executor(None, adapter.unload)+ try:+ await asyncio.shield(unload_future)+ except asyncio.CancelledError:+ logger.warning(+ "Unload of '%s' was cancelled mid-teardown; waiting for it to finish before releasing the load lock",+ name,+ )+ with contextlib.suppress(BaseException):+ await asyncio.shield(unload_future)+ raise+async def _do_unload(self, name: str, *, reason: str = "other") -> None:"""Unload a model safely (drains worker first).@@ -1341,8 +1372,23 @@ class ModelRegistry:except Exception: # noqa: BLE001 - close is best-effortlogger.warning("aclose_client() failed during unload of '%s'", name, exc_info=True)- # Adapter.unload() handles gc.collect + empty_cache- loaded.adapter.unload()+ # Adapter.unload() handles gc.collect + empty_cache, and for+ # subprocess-backed adapters a SIGTERM/SIGKILL wait of up to+ # 15s. All of it is blocking, and running it inline froze the+ # event loop for the duration: every other coroutine —+ # health probes, in-flight responses on models that are not+ # being evicted, the metrics endpoint — stopped, not merely+ # the load path the lock already serialises (design proposal+ # ``settlement-and-queue-scalability.md``, B6 part one; same+ # class as the #1600 scar above).+ #+ # The load lock stays held across this on purpose. The+ # ``finally`` below drops this model's MemoryManager entry,+ # and until ``unload()`` returns the VRAM is not actually+ # free, so a load admitted against the freed accounting+ # would size itself against memory the dying adapter still+ # holds. A slow unload beats an OOM.+ await self._run_adapter_unload(loaded.adapter, name)finally:# Always run, even if adapter teardown above raised, so a# failed unload can never leave a ghost behind (#1600).@@ -2095,7 +2141,7 @@ class ModelRegistry:logger.debug("No models_dir, skipping hot reload")return- # Don't watch cloud URLs (s3://, gs://, abfs(s)://)+ # Don't watch cloud URLs (s3://, gs://, abfs(s)://, oss://)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/core/video_frames.py b/packages/sie_server/src/sie_server/core/video_frames.pyindex af3913f24..306e5d22e 100644--- a/packages/sie_server/src/sie_server/core/video_frames.py+++ b/packages/sie_server/src/sie_server/core/video_frames.py@@ -10,11 +10,10 @@ depend on.Three invariants hold here:- **Bounded.** :data:`MAX_SAMPLED_FRAMES` caps the frames one item can ever- yield. The managed gateway reserves ``images`` for a video item from that- same constant (``VIDEO_MAX_SAMPLED_FRAMES`` in- ``packages/sie_cloud/gateway/src/dispatcher.rs``), and settlement rejects a- worker count above its reservation ceiling — so this budget is a billing- contract, deliberately NOT environment-tunable.+ yield. The cluster admission layer mirrors the same constant when reserving+ ``images`` for a video item, and settlement rejects a worker count above its+ reservation ceiling — so this budget is a billing contract, deliberately+ NOT environment-tunable.- **Fail-closed.** Every decode failure raises :class:`VideoDecodeError`(an :class:`~sie_server.types.inputs.InvalidInputError`, surfaced as``INVALID_INPUT`` / HTTP 400 on both the HTTP and queue paths). A missing or@@ -34,7 +33,7 @@ co-scheduled request. The residual costs are one seek per sampled framecontainers that report no usable metadata, the one grab-only counting passunder :data:`_MAX_SCANNED_FRAMES`.-TODO(#2433): move extraction off the inference executor entirely — decode in+TODO: move extraction off the inference executor entirely — decode inper-item preprocessing (``EncodePipeline._prepare_batch``) and hand the framesto the adapter through ``PreparedItem.payload``, so the GPU thread only eversees decoded frames. That needs a prepared-item payload the video-capable@@ -58,9 +57,9 @@ from sie_server.types.inputs import InvalidInputError, media_byteslogger = logging.getLogger(__name__)# Billing contract — see the module docstring. Raising this without raising the-# gateway's `VIDEO_MAX_SAMPLED_FRAMES` would let a settled frame count exceed-# its reservation ceiling and turn a successful encode into a billing fault, so-# it is a constant rather than an environment knob.+# admission layer's mirrored budget would let a settled frame count exceed its+# reservation ceiling and turn a successful encode into a billing fault, so it+# is a constant rather than an environment knob.MAX_SAMPLED_FRAMES: Final[int] = 32@@ -68,7 +67,7 @@ MAX_SAMPLED_FRAMES: Final[int] = 32# Generous by design — a minute of 1080p H.264 sits far below the byte cap.## Unlike MAX_SAMPLED_FRAMES these ARE env knobs, but only LOWERING the byte cap-# is meaningful behind the managed gateway: it mirrors this default as the+# is meaningful behind a metered gateway: it mirrors this default as the# compile-time `METERED_VIDEO_INPUT_BYTE_CAP` and rejects an over-cap payload# pre-reservation, so raising SIE_MAX_VIDEO_BYTES past 256 MiB changes nothing# there and only widens what self-hosted deployments accept. The duration capdiff --git a/packages/sie_server/src/sie_server/core/worker/model_worker.py b/packages/sie_server/src/sie_server/core/worker/model_worker.pyindex dc211cd25..4d802e9a6 100644--- a/packages/sie_server/src/sie_server/core/worker/model_worker.py+++ b/packages/sie_server/src/sie_server/core/worker/model_worker.py@@ -39,6 +39,7 @@ from sie_server.core.worker.types import (QueueFullError,RequestMetadata,WorkerConfig,+ WorkerDrainedError,WorkerResult,WorkerStats,)@@ -75,6 +76,39 @@ class PreformedScoreRequest:timing: RequestTiming | None = None+@dataclass(slots=True)+class _InFlightBatch:+ """A batch that has left its batcher but has not yet completed.++ Between extraction and completion the batch's metadata lives only in+ ``_process_batch``'s locals, so ``BatchFormer.drain_pending()`` cannot+ see it and ``stop()``'s drain would miss it. This registration is the+ handle that makes it reachable.++ ``owner`` is the task running the dispatch. It is what distinguishes a+ batch nothing will ever finish from one that is merely still running:+ the sidecar's pre-formed path dispatches from a request task of its+ own, concurrently with (and unaffected by) a ``stop()`` on the engine+ loop, and failing *its* futures would be collateral damage.+ """++ token: int+ metadata: list[RequestMetadata]+ owner: asyncio.Task[Any] | None+ orphaned: bool = False++ def is_abandoned(self) -> bool:+ """True when no dispatch will ever complete these futures."""+ if self.orphaned:+ return True+ owner = self.owner+ # ``cancelling() > 0`` covers the window where ``stop()`` has+ # cancelled the process task but the cancellation has not finished+ # unwinding — reachable because ``_do_unload`` runs ``stop()`` under+ # ``asyncio.wait_for``, whose timeout can fire first.+ return owner is None or owner.done() or owner.cancelling() > 0++class ModelWorker:"""Worker that batches and processes inference requests for a single model.@@ -228,6 +262,11 @@ class ModelWorker:self._process_task: asyncio.Task[None] | None = Noneself._stats = WorkerStats()+ # Batches currently between "extracted from a batcher" and+ # "futures completed". See ``_InFlightBatch``.+ self._in_flight: dict[int, _InFlightBatch] = {}+ self._in_flight_seq = 0+# Reactive OOM recovery — wraps the per-config-group dispatch. The# per-group dispatch closure is built inside ``_process_batch`` (it# captures the config_key); the executor itself is constructed once.@@ -327,20 +366,47 @@ class ModelWorker:async def stop(self) -> None:"""Stop the background processing task.- Waits for pending batches to complete before returning.+ Cancels the batch-processing loop, then fails every request the+ worker still owes an answer — both work still queued in a batcher+ and the batch that was in flight when the cancellation landed — so+ each awaiter gets a fast retryable error instead of hanging on a+ promise nothing will ever keep (see ``_fail_queued_requests``).++ The executor join at the end is a *blocking* wait on the inference+ thread. It runs off the event loop (see+ ``_join_inference_executor``) so an eviction cannot stall unrelated+ coroutines — health probes included."""if not self._running:returnself._running = False- if self._process_task is not None:- self._process_task.cancel()- with contextlib.suppress(asyncio.CancelledError):- await self._process_task- self._process_task = None-- self._inference_executor.shutdown(wait=True)+ try:+ if self._process_task is not None:+ self._process_task.cancel()+ # The ``await`` is for its side effect: it lets the+ # cancellation we just requested finish unwinding — which is+ # what marks the in-flight batch orphaned — before teardown+ # continues. ``suppress`` is deliberately broad. Re-raising a+ # drain-timeout cancellation from here would skip the+ # executor join and let ``_do_unload`` free VRAM under a live+ # forward pass; see ``_join_inference_executor``.+ with contextlib.suppress(asyncio.CancelledError):+ await self._process_task+ self._process_task = None+ finally:+ # ``finally``, and before the executor join, for two reasons.+ # The await above is a cancellation point: ``_do_unload`` runs+ # ``stop()`` under ``asyncio.wait_for``, so a drain-timeout+ # cancellation lands here as a ``CancelledError`` — a+ # ``BaseException`` that no ``except Exception`` on the way out+ # would catch. And the join below still waits for the inference+ # thread, so draining after it would make every awaiter wait out+ # a join it was never going to benefit from.+ self._fail_queued_requests()++ await self._join_inference_executor()logger.info("ModelWorker stopped (batches=%d, items=%d, tokens=%d)",self._stats.batches_processed,@@ -348,6 +414,142 @@ class ModelWorker:self._stats.total_tokens_processed,)+ async def _join_inference_executor(self) -> None:+ """Shut the inference pool down, waiting for its thread off-loop.++ ``ThreadPoolExecutor.shutdown(wait=True)`` is a thread join. Called+ directly it blocks the event loop for as long as the in-flight+ forward pass takes, so *every* coroutine stops — health probes,+ in-flight responses on other models, the metrics endpoint — not just+ the model being evicted (design proposal+ ``settlement-and-queue-scalability.md``, B6 part one).++ Two steps, deliberately:++ - ``shutdown(wait=False)`` first. It returns immediately and is the+ part that actually matters for correctness: the pool stops+ accepting new work right away, even if the join below never+ completes.+ - the join itself on a worker thread. ``shutdown`` is idempotent, so+ calling it twice is safe.++ The join is shielded, and re-awaited if we are cancelled. Moving it+ off the loop must not also make it *skippable*: ``_do_unload`` calls+ ``adapter.unload()`` right after ``stop()`` returns, and that frees+ VRAM. A synchronous join could never be interrupted, so teardown was+ ordered strictly after the last forward pass by construction; an+ unshielded ``await`` would hand that guarantee back, letting a+ drain-timeout cancellation start freeing device memory while the+ inference thread is still inside a forward pass. The shield keeps+ the ordering the blocking version gave for free.++ Consequently this join is *not* bounded by ``drain_timeout_s``, by+ design. Bounding it would mean tearing the adapter down underneath+ running GPU work, which is a worse failure than a slow unload.+ """+ self._inference_executor.shutdown(wait=False)+ loop = asyncio.get_running_loop()+ join = loop.run_in_executor(None, functools.partial(self._inference_executor.shutdown, wait=True))+ try:+ await asyncio.shield(join)+ except asyncio.CancelledError:+ with contextlib.suppress(BaseException):+ await asyncio.shield(join)+ raise++ def _fail_queued_requests(self) -> int:+ """Fail every request the worker still owes an answer. Returns the count.++ Two populations, both unreachable by the paths that normally+ complete a future with an exception (the malformed-preformed-request+ path, the per-batch error fan-out and OOM recovery all sit+ downstream of a batch that was actually dispatched):++ - **Queued.** Work still sitting in a ``BatchFormer``. ``stop()``+ cancels the loop before it is ever selected. Every batcher is+ drained, not just the base-model one — each LoRA holds its own+ queue.+ - **In flight.** A batch already extracted from its batcher when the+ cancellation arrived. Its metadata lives only in+ ``_process_batch``'s locals, and ``CancelledError`` is a+ ``BaseException`` that unwinds straight past the ``except+ Exception`` fan-out, so those futures were left unbroken too.+ ``_process_batch`` hands ownership over by leaving its+ registration in ``_in_flight``.++ The awaiter would otherwise block until an outer timeout fires+ (design proposal ``settlement-and-queue-scalability.md``, B6).++ A multi-item request occupies one queue slot per item but has a+ single future, so metadata is deduplicated by identity — across both+ populations, since a request can have items in each.+ Already-completed futures are left untouched, which keeps the call+ idempotent and safe against a batch that resolved concurrently.++ Synchronous by design: it is called from a ``finally`` that may be+ unwinding a cancellation, where awaiting is not an option.+ """+ seen: set[int] = set()+ failed = 0++ for batcher in self._batchers.values():+ for metadata in batcher.drain_pending():+ failed += self._fail_one(metadata, seen)++ for registration in self._take_abandoned_in_flight():+ for metadata in registration.metadata:+ failed += self._fail_one(metadata, seen)++ if failed:+ logger.warning(+ "ModelWorker drain failed %d in-flight/queued request(s) for model '%s'",+ failed,+ self._model_name or "unknown",+ )+ return failed++ def _fail_one(self, metadata: RequestMetadata, seen: set[int]) -> int:+ """Fail one request's future if it is new and not already done.++ Returns 1 when a future transitioned to failed, 0 otherwise, so+ callers can accumulate a count without re-deriving the dedup.+ """+ meta_id = id(metadata)+ if meta_id in seen:+ return 0+ seen.add(meta_id)+ if metadata.future.done():+ return 0+ metadata.future.set_exception(+ WorkerDrainedError(f"Model '{self._model_name or 'unknown'}' stopped before this request ran; retry")+ )+ return 1++ def _register_in_flight(self, batch: FormattedBatch[HasCost, RequestMetadata]) -> _InFlightBatch:+ """Record a batch as in flight and return its registration."""+ self._in_flight_seq += 1+ registration = _InFlightBatch(+ token=self._in_flight_seq,+ metadata=list(batch.metadata),+ owner=asyncio.current_task(),+ )+ self._in_flight[registration.token] = registration+ return registration++ def _take_abandoned_in_flight(self) -> list[_InFlightBatch]:+ """Remove and return the in-flight batches nothing will complete.++ A registration whose owner is still alive and uncancelled is left+ alone: the sidecar's pre-formed path dispatches from its own task+ and may legitimately be mid-forward while the engine loop is being+ stopped. Failing its futures would turn a request that is about to+ succeed into a spurious retry.+ """+ abandoned = [registration for registration in self._in_flight.values() if registration.is_abandoned()]+ for registration in abandoned:+ self._in_flight.pop(registration.token, None)+ return abandoned+# =========================================================================# Submit Methods (Public API - unchanged signatures)# =========================================================================@@ -702,7 +904,7 @@ class ModelWorker:new_count = current_pending + n_itemsif new_count > max_queue:msg = f"Queue full: {current_pending} items pending, cannot add {n_items} more (limit: {max_queue})"- raise QueueFullError(msg)+ raise QueueFullError(msg, pending=current_pending, requested=n_items, limit=max_queue)def _create_future_and_timing(self,@@ -832,16 +1034,20 @@ class ModelWorker:Selects the batcher whose first pending request has waited the longest.This ensures fairness across LoRAs - no LoRA starves even with low traffic.- When the worker was idle (had to poll for requests), dispatches- immediately without waiting for batch timeout. This eliminates- unnecessary latency at low concurrency while preserving batching- efficiency when requests arrive during inference.+ When the worker was idle (had to poll for requests), a short+ accumulation window (``idle_coalesce_ms``, #2874) caps the coalesce+ wait instead of dispatching immediately: bursty arrivals at an idle+ worker fuse into one batch rather than degenerating into a train of+ small serialized forwards, while a lone request only waits the small+ cap once arrivals stop. Setting ``idle_coalesce_ms=0`` restores the+ legacy immediate dispatch.Args:was_idle: Whether the worker was idle before this call. When True,- dispatches immediately without waiting for batch formation.- When False, uses the normal timeout/coalesce mechanism to- accumulate a proper batch.+ dispatches after the capped idle accumulation window (or+ immediately when the window is 0). When False, uses the+ normal timeout/coalesce mechanism to accumulate a proper+ batch.Returns:Tuple of (lora_name, batch, was_idle) where lora_name is None for@@ -863,7 +1069,11 @@ class ModelWorker:if oldest_lora is not None or (oldest_lora is None and self._batchers[None].pending_count > 0):# Found a batcher with pending items - get batch from itselected_lora = oldest_lora if oldest_lora is not None else None- batch = await self._batchers[selected_lora].get_batch(immediate=was_idle)+ idle_window_ms = self._config.idle_coalesce_ms+ if was_idle and idle_window_ms > 0:+ batch = await self._batchers[selected_lora].get_batch(coalesce_cap_ms=idle_window_ms)+ else:+ batch = await self._batchers[selected_lora].get_batch(immediate=was_idle)return selected_lora, batch, was_idle# No batchers have pending items - worker is idle@@ -990,7 +1200,9 @@ class ModelWorker:# Record instrumentation if enabledif self._stats.instrumentation_enabled:- # Lists are guaranteed to exist when instrumentation is enabled+ # Series are guaranteed to exist when instrumentation is enabled.+ # Each is a bounded deque, so these appends evict the oldest+ # sample instead of growing for the life of the process.assert self._stats.batch_sizes is not Noneassert self._stats.batch_tokens is not Noneassert self._stats.batch_wait_ms is not None@@ -1068,7 +1280,54 @@ class ModelWorker:*,engine_queue_owned: bool = False,) -> None:- """Process a single batch of requests.+ """Process a single batch, tracking it as in flight while it runs.++ The tracking is the whole point of this wrapper. Once a batch has+ been extracted from its ``BatchFormer`` its metadata exists nowhere+ else, so ``stop()``'s drain cannot reach it. A cancellation here —+ the eviction path, where ``stop()`` cancels the process loop — is a+ ``BaseException``: it unwinds past ``BatchExecutor``'s ``except+ Exception`` fan-out without failing a single future, and the awaiter+ hangs (design proposal ``settlement-and-queue-scalability.md``, B6).++ So when the worker is stopping, the registration is deliberately+ *not* popped on the cancellation path. That is an ownership handoff:+ this dispatch is over and will complete nothing, and ``stop()``'s+ ``_fail_queued_requests`` — which runs after the cancellation+ finishes unwinding — becomes responsible for the futures.++ The handoff is conditional on a stop actually being in progress, and+ that condition is load-bearing rather than decorative. The sidecar's+ pre-formed path reaches here on an IPC request task, and+ ``IpcServer`` cancels its in-flight request tasks when its own drain+ deadline expires (``ipc_server.py``). A cancellation on a *live*+ worker has no ``stop()`` coming to collect after it, so retaining the+ registration would pin an ``_InFlightBatch``, its metadata, the+ prepared items and the future for the life of the process, once per+ cancelled request. ``stop()`` clears ``_running`` before it cancels+ anything, so the flag is already false for every cancellation the+ handoff is meant to cover.+ """+ if batch.size == 0:+ return++ registration = self._register_in_flight(batch)+ try:+ await self._dispatch_batch(batch, engine_queue_owned=engine_queue_owned)+ except asyncio.CancelledError:+ registration.orphaned = not self._running+ raise+ finally:+ if not registration.orphaned:+ self._in_flight.pop(registration.token, None)++ async def _dispatch_batch(+ self,+ batch: FormattedBatch[HasCost, RequestMetadata],+ *,+ engine_queue_owned: bool = False,+ ) -> None:+ """Run one batch: group, dispatch per config, fan results out.Items from different requests are batched together for inference if theyshare the same configuration. Delegates to operation handlers for the@@ -1077,9 +1336,6 @@ class ModelWorker:Args:batch: Formatted batch ready for inference."""- if batch.size == 0:- return-logger.debug("Processing batch: size=%d, tokens=%d",batch.size,diff --git a/packages/sie_server/src/sie_server/core/worker/types.py b/packages/sie_server/src/sie_server/core/worker/types.pyindex 134240338..a40fe0eb6 100644--- a/packages/sie_server/src/sie_server/core/worker/types.py+++ b/packages/sie_server/src/sie_server/core/worker/types.py@@ -6,6 +6,7 @@ Contains request metadata, configuration, and statistics types.from __future__ import annotationsimport asyncio+from collections import dequefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any, Literal@@ -19,6 +20,16 @@ if TYPE_CHECKING:# Type alias for worker output unionWorkerOutput = EncodeOutput | ScoreOutput | ExtractOutput+# Detailed instrumentation (``SIE_INSTRUMENTATION=1`` / ``WorkerConfig.instrumentation``)+# records five samples per batch. It is a debugging aid, but a flag left on in a+# long-lived deployment would otherwise grow those series without bound for the+# life of the process — and ``WorkerStats.summary`` runs min/max/mean/median over+# the whole history, so it would also get progressively slower. Each series is a+# bounded ring buffer instead: the newest N samples are kept, older ones drop off.+# N is deliberately generous (a busy worker at ~50 batches/s covers the last few+# minutes) because the summary is a shape check, not an exact audit trail.+INSTRUMENTATION_HISTORY_LIMIT = 10_000+@dataclassclass WorkerResult:@@ -82,7 +93,50 @@ class RequestMetadata:class QueueFullError(Exception):- """Raised when the worker queue is full and cannot accept more requests."""+ """Raised when the worker queue is full and cannot accept more requests.++ Carries the structured counts from the capacity check so the HTTP+ layer can distinguish a request that can *never* fit (``requested >+ limit`` — a client error) from genuine transient pressure (queue+ occupied by other work — retryable). All fields are optional so+ legacy raise sites that only pass a message keep working; without+ them the HTTP layer conservatively treats the error as transient.++ Attributes:+ pending: Items already queued when the check ran.+ requested: Items this request tried to add.+ limit: The worker's ``max_queue_size``.+ """++ def __init__(+ self,+ message: str,+ *,+ pending: int | None = None,+ requested: int | None = None,+ limit: int | None = None,+ ) -> None:+ super().__init__(message)+ self.pending = pending+ self.requested = requested+ self.limit = limit+++class WorkerDrainedError(RuntimeError):+ """Raised on a request that was still queued when its worker stopped.++ ``ModelWorker.stop()`` cancels the batch-processing loop, so anything+ still sitting in a ``BatchFormer`` will never run. Without an explicit+ failure those awaiters hang until some outer timeout fires — the model+ is gone, but the promise is never broken (the eviction-drain contract's+ second stage).++ The condition is transient and the work was never started, so this is a+ *retryable* error: the HTTP surface maps it onto the existing 503+ ``MODEL_LOADING`` shape (with ``Retry-After``) and the queue surface+ maps it onto a ``nak_retry`` redelivery — the same answers both paths+ already give for "this model is not available right now".+ """@dataclass@@ -145,6 +199,16 @@ class WorkerConfig:# instead of being shredded into several half-full ones.coalesce_ms: float = 15.0coalesce_ratio: float = 0.5+ # Idle-dispatch accumulation window (#2874). An idle worker used to+ # dispatch IMMEDIATELY with whatever was pending, so a burst arriving at+ # an idle worker degenerated into a train of small serialized forwards+ # (many batch-of-1 dispatches instead of one fused batch). With this+ # window, the first batch after idleness coalesces arrivals until the+ # queue has been quiet for ``idle_coalesce_ms`` (or the batch fills, or+ # ``max_batch_wait_ms`` elapses since the first request). A lone request+ # therefore waits at most this window — single-digit ms — before+ # dispatch, and ``0`` restores the legacy immediate dispatch.+ idle_coalesce_ms: float = 3.0max_queue_size: int = 1000 # Maximum pending items in queue (0 = unlimited)instrumentation: bool = Falseadaptive_batching: AdaptiveBatchingParams = field(default_factory=AdaptiveBatchingParams)@@ -166,20 +230,21 @@ class WorkerStats:# callers can read counters without conditional checks.oom_recoveries: OomRecoveryStats = field(default_factory=OomRecoveryStats)- # Detailed instrumentation (for performance analysis)- batch_sizes: list[int] | None = None # Items per batch- batch_tokens: list[int] | None = None # Tokens per batch- batch_wait_ms: list[float] | None = None # Time waiting for batch to form- inference_ms: list[float] | None = None # GPU inference time per batch- requests_per_batch: list[int] | None = None # Unique requests combined per batch-- def enable_instrumentation(self) -> None:- """Enable detailed instrumentation tracking."""- self.batch_sizes = []- self.batch_tokens = []- self.batch_wait_ms = []- self.inference_ms = []- self.requests_per_batch = []+ # Detailed instrumentation (for performance analysis). Bounded ring buffers,+ # each capped at INSTRUMENTATION_HISTORY_LIMIT samples — see that constant.+ batch_sizes: deque[int] | None = None # Items per batch+ batch_tokens: deque[int] | None = None # Tokens per batch+ batch_wait_ms: deque[float] | None = None # Time waiting for batch to form+ inference_ms: deque[float] | None = None # GPU inference time per batch+ requests_per_batch: deque[int] | None = None # Unique requests combined per batch++ def enable_instrumentation(self, history_limit: int = INSTRUMENTATION_HISTORY_LIMIT) -> None:+ """Enable detailed instrumentation tracking over a bounded sample window."""+ self.batch_sizes = deque(maxlen=history_limit)+ self.batch_tokens = deque(maxlen=history_limit)+ self.batch_wait_ms = deque(maxlen=history_limit)+ self.inference_ms = deque(maxlen=history_limit)+ self.requests_per_batch = deque(maxlen=history_limit)@propertydef instrumentation_enabled(self) -> bool:diff --git a/packages/sie_server/src/sie_server/observability/worker_telemetry.py b/packages/sie_server/src/sie_server/observability/worker_telemetry.pyindex 69c531a12..7827b0ae2 100644--- a/packages/sie_server/src/sie_server/observability/worker_telemetry.py+++ b/packages/sie_server/src/sie_server/observability/worker_telemetry.py@@ -92,6 +92,7 @@ ADAPTIVE_COST_METRIC_NAME: Final = "sie.worker.scheduler.adaptive.cost"ADAPTIVE_P50_METRIC_NAME: Final = "sie.worker.scheduler.adaptive.p50"STARVATION_RESETS_METRIC_NAME: Final = "sie.worker.scheduler.starvation.resets"GENERATION_TTFT_METRIC_NAME: Final = "sie.worker.generation.ttft"+GENERATION_WORKER_WAIT_METRIC_NAME: Final = "sie.worker.generation.worker_wait"GENERATION_TPOT_METRIC_NAME: Final = "sie.worker.generation.tpot"GENERATION_TOKENS_METRIC_NAME: Final = "sie.worker.generation.tokens"GENERATION_INFLIGHT_METRIC_NAME: Final = "sie.worker.generation.inflight"@@ -346,6 +347,8 @@ class WorkerTelemetryFacade(Protocol):def first_token_observed(self, *, model: object, grammar: object, duration_s: object) -> None: ...+ def worker_wait_observed(self, *, model: object, grammar: object, duration_s: object) -> None: ...+def stream_finished(self,*,@@ -432,6 +435,9 @@ class _NoopWorkerTelemetry:def first_token_observed(self, **_: Any) -> None:return+ def worker_wait_observed(self, **_: Any) -> None:+ return+def stream_finished(self, **_: Any) -> None:return@@ -573,6 +579,14 @@ class WorkerTelemetry:unit="s",description="Adapter-observed generation time to first non-empty token",)+ self._generation_worker_wait = meter.create_histogram(+ GENERATION_WORKER_WAIT_METRIC_NAME,+ unit="s",+ description=(+ "Work receipt to adapter dispatch: validation, chat-template render,"+ " and admission/capacity wait spent worker-side before the engine"+ ),+ )self._generation_tpot = meter.create_histogram(GENERATION_TPOT_METRIC_NAME,unit="s",@@ -893,6 +907,19 @@ class WorkerTelemetry:if (duration := _nonnegative_float(duration_s)) is not None:self._generation_ttft.record(duration, self._generation_stream_attributes(model, grammar))+ def worker_wait_observed(self, *, model: object, grammar: object, duration_s: object) -> None:+ """Record the worker-side pre-adapter phase of one generation request.++ Together with the adapter-side TTFT (``first_token_observed``, which+ covers the engine's grammar preparation + prefill) and TPOT, this+ splits the client-observed time-to-first-token into worker wait vs+ engine pre-first-token vs decode — the phase evidence #3136 requires+ for the structured-output stall. The ``grammar`` label lets dashboards+ compare grammar-constrained cohorts against the ``none`` baseline.+ """+ if (duration := _nonnegative_float(duration_s)) is not None:+ self._generation_worker_wait.record(duration, self._generation_stream_attributes(model, grammar))+def stream_finished(self,*,@@ -1129,6 +1156,7 @@ def metric_views() -> list[View]:(INFERENCE_DURATION_METRIC_NAME, INFERENCE_DURATION_BUCKETS_S),(MODEL_LOAD_DURATION_METRIC_NAME, MODEL_LOAD_DURATION_BUCKETS_S),(GENERATION_TTFT_METRIC_NAME, TTFT_TPOT_BUCKETS_S),+ (GENERATION_WORKER_WAIT_METRIC_NAME, TTFT_TPOT_BUCKETS_S),(GENERATION_TPOT_METRIC_NAME, TTFT_TPOT_BUCKETS_S),(GRAMMAR_COMPILE_DURATION_METRIC_NAME, TTFT_TPOT_BUCKETS_S),)@@ -1168,6 +1196,7 @@ def metric_names() -> frozenset[str]:ADAPTIVE_P50_METRIC_NAME,STARVATION_RESETS_METRIC_NAME,GENERATION_TTFT_METRIC_NAME,+ GENERATION_WORKER_WAIT_METRIC_NAME,GENERATION_TPOT_METRIC_NAME,GENERATION_TOKENS_METRIC_NAME,GENERATION_INFLIGHT_METRIC_NAME,@@ -1187,6 +1216,7 @@ def generation_metric_names() -> frozenset[str]:return frozenset({GENERATION_TTFT_METRIC_NAME,+ GENERATION_WORKER_WAIT_METRIC_NAME,GENERATION_TPOT_METRIC_NAME,GENERATION_TOKENS_METRIC_NAME,GENERATION_INFLIGHT_METRIC_NAME,diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 68032fbd4..8d2bd8237 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -109,7 +109,6 @@ _GRAMMAR_FOLLOWER_TIMEOUT_S = 30.0# use — for debugging schema-rejection problems or slow compiles in a# controlled environment. Not recommended for production traffic.#-# See ``docs/adr/0002-sglang-owns-request-time-grammar.md``._GRAMMAR_PREFLIGHT_DEBUG_ENV = "SIE_GRAMMAR_PREFLIGHT_DEBUG"@@ -1346,6 +1345,7 @@ class StreamingProcessor:# -- Main entry point ----------------------------------------------------async def process(self, msg: Any, model_id: str) -> None:+ received_at = time.perf_counter()try:wi: WorkItem = msgpack.unpackb(msg.data, raw=False)except Exception: # noqa: BLE001@@ -1404,7 +1404,7 @@ class StreamingProcessor:"sie.adapter": "streaming",},):- await self._process_inner(msg, model_id, wi, reply_subject, request_id, attempt_id)+ await self._process_inner(msg, model_id, wi, reply_subject, request_id, attempt_id, received_at)finally:self._completion_by_attempt.pop(attempt_id, None)@@ -1416,6 +1416,7 @@ class StreamingProcessor:reply_subject: str,request_id: str,attempt_id: str,+ received_at: float,) -> None:"""Process a generate work item with all trace context already attached.@@ -1449,6 +1450,7 @@ class StreamingProcessor:request_id=request_id,attempt_id=attempt_id,cancel_event=cancel_event,+ received_at=received_at,)finally:self._unregister_cancel(request_id, attempt_id)@@ -1463,6 +1465,7 @@ class StreamingProcessor:request_id: str,attempt_id: str,cancel_event: asyncio.Event,+ received_at: float,) -> None:"""Body of :meth:`_process_inner`, run with the cancel handle live.@@ -1749,8 +1752,7 @@ class StreamingProcessor:# SGLang's server-side grammar backend (the single grammar# authority on the request hot path). The worker-side Outlines# preflight is preserved behind ``SIE_GRAMMAR_PREFLIGHT_DEBUG=1``- # for diagnostic use only — see ``_grammar_preflight_debug_enabled``- # and ``docs/adr/0002-sglang-owns-request-time-grammar.md``.+ # for diagnostic use only; see ``_grammar_preflight_debug_enabled``.## One bounded request event always runs so operators see structured-# output traffic regardless of the debug flag.@@ -1841,9 +1843,11 @@ class StreamingProcessor:await self._stream_generate(msg=msg,adapter=adapter,+ model_id=model_id,reply_subject=reply_subject,request_id=request_id,attempt_id=attempt_id,+ received_at=received_at,prompt=prompt_str,max_new_tokens=params.max_new_tokens,temperature=params.temperature,@@ -1898,9 +1902,11 @@ class StreamingProcessor:*,msg: Any,adapter: GenerationAdapter,+ model_id: str,reply_subject: str,request_id: str,attempt_id: str,+ received_at: float,prompt: str,max_new_tokens: int,temperature: float,@@ -2002,6 +2008,19 @@ class StreamingProcessor:# requests (and adapters that don't accept the kwarg) are unaffected.if images:gen_kwargs["images"] = images+ # Worker-side phase boundary (#3136): everything between work receipt+ # and this adapter dispatch — deserialization, validation, model load,+ # chat-template render, context checks, and KV-admission wait — is the+ # "worker wait" phase. The adapter's own stream timer picks up from+ # here (engine grammar preparation + prefill as TTFT, then decode as+ # TPOT), so the two histograms decompose the client-observed+ # time-to-first-token by phase and by grammar mode.+ if _metrics.worker_telemetry_enabled():+ _metrics.worker_telemetry().worker_wait_observed(+ model=model_id,+ grammar="none" if grammar is None else grammar.kind,+ duration_s=time.perf_counter() - received_at,+ )chunks_iter = cast("AsyncGenerator[GenerationChunk, None]",adapter.generate(**gen_kwargs),diff --git a/packages/sie_server/src/sie_server/processors/tool_call_grammar.py b/packages/sie_server/src/sie_server/processors/tool_call_grammar.pyindex 859963270..bda1cf15b 100644--- a/packages/sie_server/src/sie_server/processors/tool_call_grammar.py+++ b/packages/sie_server/src/sie_server/processors/tool_call_grammar.py@@ -17,8 +17,7 @@ small and predictable; both are supported by the xgrammar backend.GPU-VERIFY: the patterns here are correct by construction and unit-testedfor shape, but have NOT been run end-to-end against xgrammar + Qwen3.5 on-GPU. One verification pass (see ``deploy/demo-gcp/PRODUCTION_READINESS.md``-§1) should confirm the backend accepts the pattern and the model+GPU. One verification pass should confirm the backend accepts the pattern and the modelterminates cleanly before relying on forced ``tool_choice`` inproduction. The failure mode if a pattern is rejected is a clean``grammar_compile_failed`` terminal chunk, not a crash.diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex c41fd9a86..e6b44b05e 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -8,9 +8,9 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Final-import msgpackimport msgspecimport yaml+from sie_sdk._msgpack import packb as pack_msgpackfrom sie_server.api.ws import compute_bundle_config_hash_cachedfrom sie_server.config.model import ModelConfig@@ -24,6 +24,7 @@ from sie_server.core.score_cost import build_score_prepared_items_timedfrom sie_server.core.timing import RequestTimingfrom sie_server.core.worker.handlers.extract import ExtractHandlerfrom sie_server.core.worker.model_worker import PreformedExtractRequest, PreformedScoreRequest+from sie_server.core.worker.types import WorkerDrainedErrorfrom sie_server.ipc_types import (ApplyModelConfigRequest,ApplyModelConfigResponse,@@ -857,7 +858,7 @@ class QueueExecutor:@staticmethoddef _options_key(options: dict[str, Any] | None) -> bytes:- return msgpack.packb(options, use_bin_type=True) if options else b""+ return pack_msgpack(options, use_bin_type=True) if options else b""@staticmethoddef _batch_profile(items: list[Any]) -> str:@@ -926,7 +927,7 @@ class QueueExecutor:# rejects it just like the HTTP ingress. Only an absent value# receives the public dense default.output_types = tuple(bi.output_types) if bi.output_types is not None else ("dense",)- options_key = msgpack.packb(bi.options, use_bin_type=True) if bi.options else b""+ options_key = pack_msgpack(bi.options, use_bin_type=True) if bi.options else b""key = (output_types,bi.instruction,@@ -1146,7 +1147,7 @@ class QueueExecutor:item_id = server_items[idx].idif item_id is not None:output = {"id": item_id, **output}- result_msgpack = msgpack.packb(output, use_bin_type=True)+ result_msgpack = pack_msgpack(output, use_bin_type=True)outcomes[bi.work_item_id] = ItemOutcome(work_item_id=bi.work_item_id,request_id=bi.request_id,@@ -1943,7 +1944,7 @@ def _extract_success_outcome(# error instead of publishing an object the client reads as success.return _error_outcome(bi, _INFERENCE_ERROR_CODE, "adapter returned no extraction results")item_id = server_item.id if server_item.id is not None else f"item-{bi.item_index}"- result_msgpack = msgpack.packb({**extraction_results[0], "id": item_id}, use_bin_type=True)+ result_msgpack = pack_msgpack({**extraction_results[0], "id": item_id}, use_bin_type=True)return ItemOutcome(work_item_id=bi.work_item_id,@@ -1991,6 +1992,14 @@ def _inference_exception_outcome() -> ItemOutcome:if is_oom_error(exc):return _oom_nak_outcome(bi)+ if isinstance(exc, WorkerDrainedError):+ # The model was evicted before this item ran. Same answer as the+ # "model evicted mid-batch" checks above: NAK so the work is+ # redelivered, rather than publishing a terminal ``inference_error``+ # for work that never started. The sidecar's preformed path does not+ # park items in a batcher today, so this arm is a contract guard+ # against a future caller that submits through the queueing path.+ return _nak_outcome(bi)if isinstance(exc, (InvalidInputError, msgspec.ValidationError)):# A typed-decode failure (decode_item) or a media contract violation;# both surface as INVALID_INPUT (HTTP 400), matching the HTTP path.diff --git a/packages/sie_server/src/sie_server/types/inputs.py b/packages/sie_server/src/sie_server/types/inputs.pyindex fe2262624..c53d663b2 100644--- a/packages/sie_server/src/sie_server/types/inputs.py+++ b/packages/sie_server/src/sie_server/types/inputs.py@@ -8,10 +8,14 @@ Mapping-shaped media uses TypedDict where permissive compatibility is required;audio uses a strict msgspec struct because it crosses a bounded binary boundary."""-from typing import Any, Literal, TypedDict, TypeGuard, cast, overload+import io+from typing import TYPE_CHECKING, Any, Literal, TypedDict, TypeGuard, cast, overloadimport msgspec+if TYPE_CHECKING:+ from PIL import Image as PILImage+class ImageInput(TypedDict, total=False):"""Image input for multimodal models (wire format).@@ -257,6 +261,60 @@ def media_bytes(media: object, *, kind: str = "media") -> bytes:)+def decode_image(+ media: object,+ *,+ kind: str = "image",+ item_index: int | None = None,+ image_index: int | None = None,+) -> "PILImage.Image":+ """Decode a media input's bytes into an RGB PIL image.++ Centralizes the ``Image.open(io.BytesIO(media_bytes(...)))`` + RGB-convert+ idiom every image consumer repeated, and closes the error-mapping gap it+ left open: PIL raises ``UnidentifiedImageError`` (an ``OSError`` subclass)+ on bytes that are valid base64 but not a decodable image, which missed the+ ``ValueError`` -> 400 INVALID_INPUT mapping and surfaced as a 500+ ``INFERENCE_ERROR`` leaking a ``BytesIO`` repr. Routing every user-input+ ``Image.open`` through this helper turns undecodable bytes into a typed+ :class:`InvalidMediaError` (-> 400 on both the HTTP and queue paths, see+ that class), phrased in the same JSON-path style msgspec uses for corrupt+ base64 ("Invalid base64 encoded string - at `$.items[0].images[0].data`").++ Args:+ media: The media input mapping (e.g. an :class:`ImageInput`).+ kind: Human label used in the error message.+ item_index: Request-local item index, used in the error's JSON path+ when the call site knows it (``*`` placeholder otherwise).+ image_index: Index within the item's ``images`` list, when known.++ Returns:+ The decoded image, converted to RGB when needed.++ Raises:+ InvalidMediaError: If ``media`` violates the bytes contract (see+ :func:`media_bytes`) or its bytes are not a decodable image.+ """+ from PIL import Image as PILImage # noqa: PLC0415 — deferred: PIL is an optional dependency++ data = media_bytes(media, kind=kind)+ try:+ img = PILImage.open(io.BytesIO(data))+ # Force the full decode: PIL is lazy, so truncated bytes behind a+ # valid header would otherwise fail later, inside a processor, as an+ # untyped OSError (-> 500).+ img.load()+ except (OSError, ValueError, SyntaxError) as exc:+ item = "*" if item_index is None else str(item_index)+ image = "*" if image_index is None else str(image_index)+ raise InvalidMediaError(+ f"{kind} data is not a decodable image - at `$.items[{item}].images[{image}].data`"+ ) from exc+ if img.mode != "RGB":+ img = img.convert("RGB")+ return img++# =============================================================================# Validated item decode# =============================================================================diff --git a/packages/sie_server/src/sie_server/types/openapi.py b/packages/sie_server/src/sie_server/types/openapi.pyindex 3ad1ccb4c..2cfbdd70d 100644--- a/packages/sie_server/src/sie_server/types/openapi.py+++ b/packages/sie_server/src/sie_server/types/openapi.py@@ -11,21 +11,68 @@ from typing import Annotated, Any, Literalfrom pydantic import BaseModel, Field+from sie_server.core.extract_cost import MAX_EXTRACT_LABELSfrom sie_server.core.score_cost import MAX_SCORE_ITEMS+def _base64_media_bytes(schema: dict[str, Any]) -> None:+ """Describe native media bytes as the base64 string the JSON path accepts.++ Pydantic renders a bare ``bytes`` as ``format: binary``, which in OpenAPI+ means raw octets — the shape a multipart file upload carries, not the one+ this API takes. On the JSON path msgspec base64-decodes ``data`` (matching+ the msgpack path's native binary), so a client that followed+ ``format: binary`` and sent raw bytes inside a JSON string would fail+ validation. ``contentEncoding`` is the OpenAPI 3.1 spelling for "this+ string is base64", and it is what a generated client can actually produce.+ """+ schema.pop("format", None)+ schema["contentEncoding"] = "base64"+++_MEDIA_BYTES_DESCRIPTION = "Base64-encoded on the JSON path; native binary on the msgpack path."++# Request modelsclass ImageInputModel(BaseModel):"""Image input for multimodal models."""- data: bytes = Field(..., description="Image data as bytes")+ data: bytes = Field(+ ..., description=f"Image data. {_MEDIA_BYTES_DESCRIPTION}", json_schema_extra=_base64_media_bytes+ )format: str | None = Field(default=None, description="Image format hint: 'jpeg', 'png', etc.")+class AudioInputModel(BaseModel):+ """Audio input for audio models."""++ data: bytes = Field(+ ..., description=f"Audio data. {_MEDIA_BYTES_DESCRIPTION}", json_schema_extra=_base64_media_bytes+ )+ format: str | None = Field(default=None, description="Audio format: 'wav', 'mp3', etc.")+ # The audio preprocessor rejects a non-positive rate outright+ # ("audio.sample_rate must be a positive integer or null"), so the bound+ # belongs in the published contract rather than only in the error path.+ sample_rate: int | None = Field(default=None, gt=0, description="Sample rate in Hz. Must be positive.")+++class VideoInputModel(BaseModel):+ """Video input for video models."""++ data: bytes = Field(+ ..., description=f"Video data. {_MEDIA_BYTES_DESCRIPTION}", json_schema_extra=_base64_media_bytes+ )+ format: str | None = Field(default=None, description="Video format: 'mp4', 'webm', etc.")++class DocumentInputModel(BaseModel):"""Document input for composite-document extractors (PDF, DOCX, HTML, ...)."""- data: bytes = Field(..., description="Document bytes (raw file content)")+ data: bytes = Field(+ ...,+ description=f"Document bytes (raw file content). {_MEDIA_BYTES_DESCRIPTION}",+ json_schema_extra=_base64_media_bytes,+ )format: str | None = Field(default=None, description="Document format hint: 'pdf', 'docx', 'html', etc.")@@ -35,6 +82,8 @@ class ItemModel(BaseModel):id: str | None = Field(default=None, description="Optional identifier for this item. Returned in response.")text: str | None = Field(default=None, description="Text content to encode", examples=["Hello, world!"])images: list[ImageInputModel] | None = Field(default=None, description="Images for multimodal models")+ audio: AudioInputModel | None = Field(default=None, description="Audio for audio models")+ video: VideoInputModel | None = Field(default=None, description="Video for video models")document: DocumentInputModel | None = Field(default=None, description="Document for composite-document extractors (PDF, DOCX, HTML, ...)")@@ -119,19 +168,34 @@ class TimingInfoModel(BaseModel):postprocessing_ms: float | None = Field(default=None, description="Postprocessing time")+class UsageModel(BaseModel):+ """Authoritative worker-emitted usage.++ Post-tokenization counts, never a character estimate. A reported 0 is a+ measurement (a video-only encode reads no text); an absent block means the+ counts were unavailable on this path.+ """++ input_tokens: int = Field(..., ge=0, description="Post-truncation input tokens processed")+ images: int | None = Field(default=None, ge=0, description="Images processed across the request's items")++class EncodeResponseModel(BaseModel):"""Response from encode endpoint."""model: str = Field(..., description="Model used for encoding")items: list[EncodeResultModel] = Field(..., description="Encoding results for each input item")timing: TimingInfoModel | None = Field(default=None, description="Request timing breakdown")+ usage: UsageModel | None = Field(default=None, description="Authoritative usage when the worker reported counts")# Extract endpoint modelsclass ExtractParamsModel(BaseModel):"""Parameters for extract requests."""- labels: list[str] | None = Field(default=None, description="Entity labels to extract")+ labels: list[str] | None = Field(+ default=None, max_length=MAX_EXTRACT_LABELS, description="Entity labels to extract"+ )output_schema: dict[str, Any] | None = Field(default=None, description="Schema for structured extraction")instruction: str | None = Field(default=None, description="Task instruction")options: dict[str, Any] | None = Field(@@ -220,6 +284,7 @@ class ExtractResponseModel(BaseModel):model: str = Field(..., description="Model used for extraction")items: list[ExtractResultModel] = Field(..., description="Extraction results for each input item")+ usage: UsageModel | None = Field(default=None, description="Authoritative usage when the worker reported counts")# Score endpoint models@@ -582,6 +647,44 @@ class GenerateModelLoadFailedErrorResponse(BaseModel):detail: GenerateModelLoadFailedDetailModel+class OpenAIEmbeddingsErrorModel(BaseModel):+ """Inner object of the top-level OpenAI ``{"error": {...}}`` envelope that+ ``/v1/embeddings`` route-generated errors emit (e.g. a retryable 503+ ``MODEL_LOADING``). Matches the shape ``/v1/completions`` returns.+ """++ message: str = Field(..., description="Client-safe error message")+ type: str = Field(..., description="OpenAI error type, e.g. 'server_error'")+ param: str | None = Field(default=None, description="Offending request field, when known")+ code: str = Field(..., description="Stable SIE error code, e.g. 'MODEL_LOADING'")+++class OpenAIEmbeddingsErrorResponse(BaseModel):+ """Top-level OpenAI error envelope for a retryable ``/v1/embeddings`` error."""++ error: OpenAIEmbeddingsErrorModel+++class OpenAIEmbeddingsModelLoadFailedErrorModel(BaseModel):+ """Inner error object for a terminal ``/v1/embeddings`` model-load failure,+ carrying the terminal-failure short-circuit fields alongside the OpenAI shape.+ """++ message: str = Field(..., description="Client-safe error message")+ type: str = Field(..., description="OpenAI error type ('server_error')")+ param: str | None = Field(default=None, description="Unused for this error; always null")+ code: Literal["MODEL_LOAD_FAILED"] = Field(..., description="Stable error code")+ error_class: str = Field(..., description="Classified model-load failure category")+ permanent: bool = Field(..., description="Whether operator action is required before retrying")+ attempts: int = Field(..., ge=1, description="Number of failed model-load attempts")+++class OpenAIEmbeddingsModelLoadFailedErrorResponse(BaseModel):+ """Top-level OpenAI error envelope for a terminal ``/v1/embeddings`` model-load failure."""++ error: OpenAIEmbeddingsModelLoadFailedErrorModel++class GenerateChunkErrorModel(BaseModel):"""Terminal error carried by a generation SSE event."""diff --git a/packages/sie_server/src/sie_server/types/requests.py b/packages/sie_server/src/sie_server/types/requests.pyindex 3e4b172b4..3195e26f4 100644--- a/packages/sie_server/src/sie_server/types/requests.py+++ b/packages/sie_server/src/sie_server/types/requests.py@@ -2,6 +2,7 @@ from typing import Anyimport msgspec+from sie_server.core.extract_cost import MAX_EXTRACT_LABELSfrom sie_server.core.score_cost import MAX_SCORE_ITEMSfrom sie_server.types.inputs import Item@@ -54,6 +55,10 @@ class ExtractParams(msgspec.Struct):instruction: str | None = Noneoptions: dict[str, Any] | None = None+ def __post_init__(self) -> None:+ if self.labels is not None and len(self.labels) > MAX_EXTRACT_LABELS:+ raise msgspec.ValidationError(f"Field 'labels' must contain at most {MAX_EXTRACT_LABELS} labels")+class ExtractRequest(msgspec.Struct):items: list[Item]diff --git a/packages/sie_server/src/sie_server/types/responses.py b/packages/sie_server/src/sie_server/types/responses.pyindex b847bb5db..9bb9b60ab 100644--- a/packages/sie_server/src/sie_server/types/responses.py+++ b/packages/sie_server/src/sie_server/types/responses.py@@ -28,6 +28,22 @@ class TimingInfo(TypedDict, total=False):postprocessing_ms: float | None+class Usage(TypedDict):+ """Authoritative post-tokenization usage, never a character estimate.++ ``input_tokens`` is the sum of the worker's per-item token counts. A+ reported ``0`` is a MEASUREMENT — a video-only encode consumes exactly zero+ text tokens — and is distinct from an absent ``usage`` block, which means+ the counts were unavailable on this path.++ Score shipped this shape first (:class:`ScoreUsage`); encode and extract+ report the same field names so the surfaces agree.+ """++ input_tokens: Required[int]+ images: NotRequired[int]++class EncodeResponse(TypedDict, total=False):"""Response body for POST /v1/encode/{model}.@@ -35,11 +51,13 @@ class EncodeResponse(TypedDict, total=False):model: Model name used for encoding.items: Encoded results, one per input item.timing: Server-side timing breakdown.+ usage: Authoritative usage; omitted when the counts are unavailable."""model: stritems: list[EncodeResult]timing: TimingInfo | None+ usage: Usageclass ScoreEntry(TypedDict):@@ -56,6 +74,8 @@ class ScoreEntry(TypedDict):rank: int+# Kept as its own name for existing importers and for the published+# ``ScoreUsageModel`` schema; structurally identical to :class:`Usage`.class ScoreUsage(TypedDict):input_tokens: Required[int]images: NotRequired[int]@@ -177,10 +197,12 @@ class ExtractResponse(TypedDict, total=False):Attributes:model: Model name used for extraction.items: Extraction results, one per input item.+ usage: Authoritative usage; omitted when the counts are unavailable."""model: stritems: list[ExtractResult]+ usage: Usageclass ErrorCode(StrEnum):diff --git a/packages/sie_server/tests/adapters/test_bge_m3_flash.py b/packages/sie_server/tests/adapters/test_bge_m3_flash.pyindex b7cc8e384..ca7d72ad4 100644--- a/packages/sie_server/tests/adapters/test_bge_m3_flash.py+++ b/packages/sie_server/tests/adapters/test_bge_m3_flash.py@@ -83,8 +83,8 @@ class TestBGEM3YamlConfig:return ModelConfig(**raw)def test_score_task_enabled(self, config: ModelConfig) -> None:- # Regression guard for sie-internal#728: bge-m3 was advertised as a- # scoring model but the YAML had `score: null`, causing /v1/score+ # Regression guard: bge-m3 was advertised as a scoring model but the+ # YAML had `score: null`, causing /v1/score# requests to be rejected before reaching the adapter.assert config.tasks.score is not Nonediff --git a/packages/sie_server/tests/adapters/test_clip.py b/packages/sie_server/tests/adapters/test_clip.pyindex b02f67a0c..e666011df 100644--- a/packages/sie_server/tests/adapters/test_clip.py+++ b/packages/sie_server/tests/adapters/test_clip.py@@ -384,3 +384,32 @@ class TestCLIPAdapter:cos = float(np.dot(got, expected) / denom)assert cos >= 0.9999, f"item {i} cosine {cos}"assert np.allclose(got, expected, atol=1e-5), f"item {i} value mismatch"+++def test_preprocess_one_rejects_undecodable_bytes_with_typed_error() -> None:+ """Non-image bytes are a typed InvalidMediaError (-> 400), not a PIL OSError 500."""+ from sie_server.types.inputs import InvalidMediaError++ adapter = CLIPAdapter("openai/clip-vit-base-patch32")+ adapter._processor = _FakeVisionProcessor()++ with pytest.raises(InvalidMediaError, match="image data is not a decodable image"):+ adapter._preprocess_one({"data": b"valid base64, but not an image"})+++def test_undecodable_bytes_name_the_original_item_index() -> None:+ """The flattened preprocessing jobs keep each image's request-local indices.++ encode() partitions to image items (here original positions 0 and 2); the+ decode failure must name the request-local index 2, not subset slot 1.+ """+ from sie_server.types.inputs import InvalidMediaError++ adapter = CLIPAdapter("openai/clip-vit-base-patch32")+ adapter._model = MagicMock()+ adapter._processor = _FakeVisionProcessor()+ good = Item(images=[{"data": _png_bytes((1, 2, 3)), "format": "png"}])+ bad = Item(images=[{"data": b"valid base64, but not an image"}])++ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[2\]\.images\[0\]\.data`"):+ adapter._encode_image_items([good, bad], [0, 2])diff --git a/packages/sie_server/tests/adapters/test_colqwen2_revision.py b/packages/sie_server/tests/adapters/test_colqwen2_revision.pynew file mode 100644index 000000000..dbb726d51--- /dev/null+++ b/packages/sie_server/tests/adapters/test_colqwen2_revision.py@@ -0,0 +1,56 @@+"""The colqwen2 revision pin must scope to the adapter repo, not the base.++vidore/colqwen2.5-v0.2 is a PEFT adapter repo: transformers resolves its+adapter_config.json, swaps the load target to base_model_name_or_path+(vidore/colqwen2.5-base), and applies a TOP-LEVEL ``revision`` kwarg to that+base-weights download - where the adapter repo's sha does not exist. Run+32963263930 failed every colqwen cell exactly this way after #3753 pinned+the top-level revision. The pin must ride in ``adapter_kwargs`` instead,+which transformers threads to adapter-config resolution and+``model.load_adapter`` only. The processor is a single-repo load, so its+top-level revision stays.+"""++from unittest.mock import MagicMock, patch++from sie_server.adapters.colqwen2 import ColQwen2Adapter++_PIN = "6f6fcdfd1a114dfe365f529701b33d66b9349014"+++def _load_with(revision: str | None) -> tuple[MagicMock, MagicMock]:+ """Run adapter.load with mocked model/processor; return the two mocks."""+ model_cls = MagicMock()+ model_cls.from_pretrained.return_value = MagicMock(dim=128)+ processor = MagicMock()+ with (+ patch("sie_server.adapters.colqwen2._make_colqwen2_5_cls", return_value=model_cls),+ patch(+ "transformers.models.qwen2_vl.processing_qwen2_vl.Qwen2VLProcessor.from_pretrained",+ processor,+ ),+ patch("sie_server.adapters.colqwen2.rebind_vision_patch_embed"),+ ):+ adapter = ColQwen2Adapter("vidore/colqwen2.5-v0.2", revision=revision)+ adapter.load("cpu")+ return model_cls.from_pretrained, processor+++def test_pinned_revision_scopes_to_adapter_kwargs() -> None:+ model_call, processor_call = _load_with(_PIN)++ model_kwargs = model_call.call_args.kwargs+ assert "revision" not in model_kwargs+ assert model_kwargs["adapter_kwargs"] == {"revision": _PIN}+ # The processor is a single-repo load on the adapter repo: top-level+ # revision is correct there (verified live against the pin in #3753).+ assert processor_call.call_args.kwargs["revision"] == _PIN+++def test_unpinned_load_passes_no_revision_anywhere() -> None:+ model_call, processor_call = _load_with(None)++ model_kwargs = model_call.call_args.kwargs+ assert "revision" not in model_kwargs+ assert "adapter_kwargs" not in model_kwargs+ assert "revision" not in processor_call.call_args.kwargsdiff --git a/packages/sie_server/tests/adapters/test_docling.py b/packages/sie_server/tests/adapters/test_docling.pyindex f3e600168..e17f7c87f 100644--- a/packages/sie_server/tests/adapters/test_docling.py+++ b/packages/sie_server/tests/adapters/test_docling.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom pathlib import Pathfrom types import SimpleNamespace-from typing import Any+from typing import Any, castfrom unittest.mock import MagicMock, patchimport pytest@@ -288,6 +288,28 @@ class TestDoclingExtract:# have produced ``document.png``.assert out.data[0]["document"] == {"name": "document.pdf"}+ def test_document_with_non_bytes_data_yields_typed_invalid_input(self) -> None:+ # A base64-str ``document.data`` (the queue path builds Item from an+ # unvalidated dict, so a str can slip past the wire boundary) must+ # surface a typed 400 describing the bytes-contract violation — NOT the+ # contradictory image-branch "Document or image input is required",+ # which denies the document the caller actually sent.+ adapter, factory = _make_adapter()++ # A str where the DocumentInput contract wants bytes; cast keeps the+ # test type-correct while still exercising the queue-path violation.+ malformed = cast("Any", {"data": "%PDF-1.4 base64-str-not-bytes", "format": "pdf"})+ out = adapter.extract([Item(document=malformed)])++ assert out.data == [{}]+ assert out.errors is not None+ assert out.errors[0] is not None+ assert out.errors[0].code == "INVALID_INPUT"+ assert "bytes" in out.errors[0].message+ assert out.errors[0].message != "Document or image input is required"+ # The item never reaches conversion, so no converter is built.+ factory.assert_not_called()+def test_neither_document_nor_image_yields_per_item_error(self) -> None:adapter, factory = _make_adapter()@@ -569,6 +591,7 @@ class TestDoclingMakeConverter:# #2919: the recogniser language is pinned, never docling's ["chinese"]# default — word-joined English output was a defect on a billed profile.assert kwargs["ocr_options"].lang == ["en"]+ assert kwargs["ocr_options"].det_model_path is Nonemock_fmt_opt.assert_called_once()mock_cls.assert_called_once()assert "format_options" in mock_cls.call_args.kwargs@@ -591,6 +614,7 @@ class TestDoclingMakeConverter:# #2919: the OCR profile serves the English RapidOCR set from the pinned# artifact revision; both language sets ship, so this stays a data flip.assert kwargs["ocr_options"].lang == ["en"]+ assert kwargs["ocr_options"].det_model_path is Nonemock_fmt_opt.assert_called_once()mock_cls.assert_called_once()assert "format_options" in mock_cls.call_args.kwargs@@ -607,6 +631,9 @@ class TestDoclingMakeConverter:adapter._make_converter(ocr_enabled=False)assert mock_opts.call_args.kwargs["artifacts_path"] == tmp_path+ assert mock_opts.call_args.kwargs["ocr_options"].det_model_path == str(+ tmp_path / "RapidOcr/onnx/PP-OCRv4/det/ch_PP-OCRv4_det_mobile.onnx"+ )def test_make_converter_passes_resolved_ordinary_artifact_root(self, tmp_path: Path) -> None:adapter = DoclingAdapter(model_name_or_path=tmp_path)@@ -621,6 +648,9 @@ class TestDoclingMakeConverter:adapter._make_converter(ocr_enabled=True)assert mock_opts.call_args.kwargs["artifacts_path"] == tmp_path.resolve()+ assert mock_opts.call_args.kwargs["ocr_options"].det_model_path == str(+ tmp_path.resolve() / "RapidOcr/onnx/PP-OCRv4/det/ch_PP-OCRv4_det_mobile.onnx"+ )def test_make_converter_no_ocr_uses_accelerator_options_when_device_set(self) -> None:adapter = DoclingAdapter()diff --git a/packages/sie_server/tests/adapters/test_docling_smoke.py b/packages/sie_server/tests/adapters/test_docling_smoke.pyindex 01506d2fc..13e770456 100644--- a/packages/sie_server/tests/adapters/test_docling_smoke.py+++ b/packages/sie_server/tests/adapters/test_docling_smoke.py@@ -1,5 +1,7 @@from __future__ import annotations+import base64+import hashlibimport iofrom collections.abc import Callablefrom pathlib import Path@@ -72,6 +74,34 @@ _PROSE = ("peeped into the book her sister was reading")+# Byte-identical to the catalog acceptance fixture. This compact,+# wide line caught the English-only PP-OCRv3 detector dropping every word after+# "SIE" while the larger prose fixture below still passed.+_COMPACT_OCR_PNG_B64 = (+ "iVBORw0KGgoAAAANSUhEUgAAAwAAAAB4CAAAAABgc8pjAAAFgElEQVR4nO3dXailVRkH8N+YH6QOzYUlRnlpTGmaH8lMil8I"+ "KaIEWUqCYxiJmoqgEyFZGFkqipAko4zmlUWhRhEZhkIieBGj4gfqRUiFFFIQhfmVF4uFa3jPu9njGXSm5/+7OAxrr73ed+0z"+ "//PCw1prr/mfiLr2eL9vIOL9lABEaQlAlJYARGkJQJSWAERpCUCUlgBEaQlAlJYARGkJQJSWAERpCUCUlgBEaQlAlJYARGkJ"+ "QJSWAERpCUCUlgBEaQlAlJYARGkJQJSWAERpCUCUlgBEaQlAlJYARGkJQJS259wLfwTfBK8PXbeCj4N14J/Du/YFn52Mdia4"+ "ctJ+B/gxWAv2B7cPVxndCS4BL4EDwX3g1qHnH8BxQ8ul4IsLx2nWYft5Td0FfgT2Bq+By8D5Q88twxX3HMZv7R+bGX/8JNsJ"+ "3v8Ct4ATJn1G00978XzHcdYMc/ka2ASeAV8GT2D7v51Hg7vBoStNZ5eVJ0CUlgBEaQlAlJYARGkJQJS2Zu47wo4Av0KvVPwC"+ "/Az8FCtVS6Ytc34Hrge/Bh8EvwE3gYcm7zoLHAI+CS6YGX/xnSweZ/F7fwuuQ/98xv5ngO+gV29uBr8Ee4Efgt8Po01N7+Ep"+ "8BXw5BL3OdrR+f4bvZp0ETgbnDuMdg767+4e9P8Vu5c8AaK0BCBKSwCitAQgSksAorTZtUB/A68OLa0m8JGddOFW5/k+ev2n"+ "OQ19bU9bg9QqJ/9Br05cCL6F+SrQnNWPc+Pwc93Q3v59A7gW/a/L99Bn0VwMHgNvgg8scd22xuYvS99n8+7mux/6XC5HrwJ9"+ "G3xp+NnqeFt28K52HXkCRGkJQJSWAERpCUCUlgBEabNVoFafOR6cDs4DJ+2kCz8NPjPz6rSq0NbMfB58AvwJfe/S3ktfd/Xj"+ "PIv5Oz8Sff9U21316Umftvft/iWuNXoQnLyD71rNfNudvzi0rB/avw4ORl9ftDvKEyBKSwCitAQgSksAorQEIEqbrQJtQt/7"+ "cz+4AnwBfcfTVKstnDhpbytGNgwtby51e+94AGwDPwd/BY+AU9/zcea0XWCt/vPG5NVxd9jL4LmZccZP8vWh59MzfUbjp72a"+ "+bb732vS3lYEtcrPMwtH2PXlCRClJQBRWgIQpSUAUVoCEKWtUAX6O3gBbETfPdROvDkM81Wgtrbk4SUu3M6o2QaOHdpbFWUT"+ "+Al6vej5oX/TVrm0k3mWqd7srHFa9aOdnr1x8mpr/xT6bqx2hs8x6Cc2fxUctPAq00+y7c+6G/3U7sWf9urn+zj6b3zU1hSt"+ "Hf69+8oTIEpLAKK0BCBKSwCitAQgSluhCtTWsbRTX9rZNe27ul5B3wG0eu1snGvQKxL7gHvBf4eej4LDJyO03WpXLH3FnTXO"+ "VeBq9LORP4R+uvJm8F30VTdt5cx4OvRtWO4soFGr2Fy3dP/VzPcf6HP5wdJX3B3lCRClJQBRWgIQpSUAUVoCEKWtUAU6AP1k"+ "nnYmcDu9uVUtti4cbm6PUtuddP3Q0r5zvK04Ogp8GP306duGnm1P0/Q8nH2H/u2snvUL7235cdosjpv0/Bz6N3z9Gf2UpH2G"+ "d30DnIK+rqmN2c7S+Sj6CUuzm/FmtFU3bWXRW8MVT5z03DC8uvx82zitBtj2oG2eGf//SZ4AUVoCEKUlAFFaAhClJQBR2uw3"+ "xUdUkCdAlJYARGkJQJSWAERpCUCUlgBEaQlAlJYARGkJQJSWAERpCUCUlgBEaQlAlJYARGkJQJSWAERpCUCUlgBEaQlAlJYA"+ "RGkJQJSWAERpCUCUlgBEaQlAlJYARGkJQJSWAERpCUCUlgBEaQlAlJYARGkJQJSWAERpCUCUlgBEaQlAlJYARGkJQJSWAERp"+ "CUCU9jZ9MtgcKlsBIwAAAABJRU5ErkJggg=="+)+_COMPACT_OCR_PNG = base64.b64decode(_COMPACT_OCR_PNG_B64, validate=True)+def _make_prose_image_bytes() -> bytes:pil = pytest.importorskip("PIL")@@ -89,9 +119,44 @@ def _make_prose_image_bytes() -> bytes:return buf.getvalue()[email protected](scope="module")+def artifact_backed_adapter() -> DoclingAdapter:+ yaml = pytest.importorskip("yaml")+ model_yaml = Path(__file__).resolve().parents[2] / "models" / "docling.yaml"+ pinned = yaml.safe_load(model_yaml.read_text())++ adapter = DoclingAdapter(+ model_name_or_path=pinned["hf_id"],+ revision=pinned["hf_revision"],+ )+ adapter.load("cpu")+ return adapter+++def test_served_ocr_recognizes_compact_catalog_fixture(artifact_backed_adapter: DoclingAdapter) -> None:+ assert hashlib.sha256(_COMPACT_OCR_PNG).hexdigest() == (+ "a9c82ded9169cdb69bbf3a2096e89a662cf93cb03dfd2cc01acf44acfc42cb9a"+ )+ out = artifact_backed_adapter.extract(+ [Item(images=[{"data": _COMPACT_OCR_PNG, "format": "png"}])],+ options={"ocr": True},+ )++ assert out.errors is None+ assert out.data is not None+ item = out.data[0]+ assert "error" not in item, f"adapter reported error: {item.get('error')}"+ words = {+ "".join(character for character in word if character.isalnum()) for word in item["markdown"].casefold().split()+ }+ assert {"sie", "catalog", "ready"} <= words, item["markdown"]+ assert out.pages == [1]++@pytest.mark.integration-def test_served_ocr_output_keeps_word_boundaries() -> None:- """#2919: end-to-end sanity of the ARTIFACT-BACKED served OCR path.+def test_served_ocr_output_keeps_word_boundaries(artifact_backed_adapter: DoclingAdapter) -> None:+ """End-to-end sanity of the artifact-backed served OCR path.This exercises the real pinned artifact revision end to end: it proves therevision resolves a usable RapidOCR set on the served path and returns@@ -108,32 +173,14 @@ def test_served_ocr_output_keeps_word_boundaries() -> None:(0.2296 vs 0.1290). Threshold-fitting a synthetic image would buy a flakytest, not a guard.- What actually holds the language pin is- ``test_docling.py::TestDoclingMakeConverter`` (both cases assert- ``ocr_options.lang == ["en"]``; flipping the adapter fails them in the- default suite). What catches DEGRADED-but-segmented output on real pages is- the quality floor now committed at- ``benchmarks/ocr__Teklia__IAM-line/docling/quality/target.ocr.extract.json``- (#2919): over 2,915 real pages the ocr profile scores mean_similarity- 0.3878 with the English recogniser and 0.3743 with the Chinese one, so a- ``lang=["ch"]`` flip lands 3.49% under the floor and reds the gate. The- same holds on olmOCR-bench (0.3458 vs 0.3347, -3.22%).- ``test_benchmark_repository_contracts.py`` replays both and fails if either- floor stops rejecting the defect.+ The unit cases in ``test_docling.py::TestDoclingMakeConverter`` hold the+ language pin by asserting ``ocr_options.lang == ["en"]``. This served-path+ smoke only checks that the pinned artifact returns segmented text.So: keep this as a served-path smoke over the pinned revision. Do not readit as evidence that the language is correct."""- yaml = pytest.importorskip("yaml")- model_yaml = Path(__file__).resolve().parents[2] / "models" / "docling.yaml"- pinned = yaml.safe_load(model_yaml.read_text())-- adapter = DoclingAdapter(- model_name_or_path=pinned["hf_id"],- revision=pinned["hf_revision"],- )- adapter.load("cpu")- out = adapter.extract(+ out = artifact_backed_adapter.extract([Item(images=[{"data": _make_prose_image_bytes(), "format": "png"}])],options={"ocr": True},)diff --git a/packages/sie_server/tests/adapters/test_donut.py b/packages/sie_server/tests/adapters/test_donut.pyindex f2e77c8c4..9f175e66b 100644--- a/packages/sie_server/tests/adapters/test_donut.py+++ b/packages/sie_server/tests/adapters/test_donut.py@@ -168,3 +168,30 @@ class TestDonutAdapter:assert "menu[0].price" in labelsassert "menu[1].nm" in labelsassert "total.total_price" in labels+++def test_extract_single_rejects_undecodable_bytes_with_typed_error() -> None:+ """Non-image bytes are a typed InvalidMediaError (-> 400), not a PIL OSError 500.++ Representative of the OCR/document-extract adapter family (donut,+ florence2, glm_ocr, lighton_ocr, mineru_vl, paddleocr_vl), which all+ decode via the shared ``decode_image`` seam.+ """+ from sie_server.adapters.donut import DonutAdapter+ from sie_server.types.inputs import InvalidMediaError++ adapter = DonutAdapter("naver-clova-ix/donut-base-finetuned-cord-v2")++ # extract() enumerates items and passes each one's request-local index, so+ # a NON-first item's failure names that item, not `$.items[*]`.+ with pytest.raises(+ InvalidMediaError, match=r"image data is not a decodable image - at `\$\.items\[2\]\.images\[0\]\.data`"+ ):+ adapter._extract_single(+ Item(images=[{"data": b"valid base64, not an image", "format": "png"}]),+ task="cord",+ instruction=None,+ max_new_tokens=8,+ num_beams=1,+ item_index=2,+ )diff --git a/packages/sie_server/tests/adapters/test_florence2.py b/packages/sie_server/tests/adapters/test_florence2.pyindex 7ee898221..2575f38bd 100644--- a/packages/sie_server/tests/adapters/test_florence2.py+++ b/packages/sie_server/tests/adapters/test_florence2.py@@ -277,7 +277,8 @@ class TestFlorence2CpuInference:Guards the transformers-4.57 native-processor regression at the level thatactually failed on staging: load the pinned checkpoint via the adapter and run- a real OCR + OD forward. Run with ``mise run test -- -m model``.+ a real OCR + OD forward. Run this file with pytest's ``-m model`` marker+ through the locked root project."""REVISION = "5ca5edf5bd017b9919c05d08aebef5e4c7ac3bac"diff --git a/packages/sie_server/tests/adapters/test_generation_base.py b/packages/sie_server/tests/adapters/test_generation_base.pyindex d0b565b37..4a66a5bb2 100644--- a/packages/sie_server/tests/adapters/test_generation_base.py+++ b/packages/sie_server/tests/adapters/test_generation_base.py@@ -5,6 +5,8 @@ from collections.abc import AsyncIteratorimport pytestfrom sie_server.adapters._generation_base import (GenerationChunk,+ ToolCallDelta,+ collect_generation,reasoning_starts_in_prompt,suppress_thinking_blocks,)@@ -273,3 +275,160 @@ async def test_suppress_thinking_blocks_closes_upstream_on_client_cancel() -> Noawait normalized.aclose()assert closed is True+++async def test_reasoning_consuming_the_whole_budget_stamps_empty_output_error() -> None:+ """#3104/#3136: budget exhausted inside a think block -> only whitespace is+ visible and the terminal chunk must carry the typed empty-output error.+ """+ source = _chunks(+ GenerationChunk(text_delta="\n\n", is_first=True),+ GenerationChunk(text_delta="<think>"),+ GenerationChunk(text_delta="private reasoning that never closes"),+ GenerationChunk(text_delta="", done=True, finish_reason="length", completion_tokens=32),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source)]++ assert "".join(chunk.text_delta for chunk in normalized) == "\n\n"+ terminal = normalized[-1]+ assert terminal.done is True+ assert terminal.finish_reason == "length"+ assert terminal.error_code == "empty_model_output"+ assert terminal.error_message is not None+ assert "reasoning" in terminal.error_message+++async def test_whitespace_only_output_without_reasoning_stamps_empty_output_error() -> None:+ source = _chunks(+ GenerationChunk(text_delta="\n\n", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", completion_tokens=2),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source)]++ terminal = normalized[-1]+ assert terminal.error_code == "empty_model_output"+ assert terminal.error_message is not None+ assert "reasoning" not in terminal.error_message+++async def test_visible_answer_is_not_stamped() -> None:+ source = _chunks(+ GenerationChunk(text_delta="<think>hidden</think>", is_first=True),+ GenerationChunk(text_delta="Visible answer"),+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source)]++ assert normalized[-1].error_code is None+ assert "".join(chunk.text_delta for chunk in normalized) == "Visible answer"+++async def test_tool_call_only_stream_is_not_stamped() -> None:+ """A tool-call response legitimately has no visible prose."""+ source = _chunks(+ GenerationChunk(+ text_delta="",+ tool_call_delta=ToolCallDelta(index=0, id="call_1", function_name="lookup"),+ ),+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source)]++ assert normalized[-1].error_code is None+++async def test_cancelled_stream_is_not_stamped() -> None:+ source = _chunks(+ GenerationChunk(text_delta="<think>partial", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="cancelled"),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source)]++ assert normalized[-1].error_code is None+++async def test_candidates_with_visible_text_are_not_stamped() -> None:+ """Non-streaming n>1: visible candidate text counts as usable output."""+ terminal = GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ candidates=(+ {"index": 0, "text": "<think>hidden</think>Answer A", "finish_reason": "stop"},+ {"index": 1, "text": "Answer B", "finish_reason": "stop"},+ ),+ )++ [normalized] = [chunk async for chunk in suppress_thinking_blocks(_chunks(terminal))]++ assert normalized.error_code is None+++async def test_candidates_all_reasoning_are_stamped() -> None:+ """Non-streaming n>1 where every candidate was reasoning-only."""+ terminal = GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="length",+ candidates=(+ {"index": 0, "text": "<think>truncated reasoning", "finish_reason": "length"},+ {"index": 1, "text": "<think>more truncated reasoning", "finish_reason": "length"},+ ),+ )++ [normalized] = [chunk async for chunk in suppress_thinking_blocks(_chunks(terminal))]++ assert normalized.error_code == "empty_model_output"+ assert normalized.error_message is not None+ assert "reasoning" in normalized.error_message+++async def test_collect_generation_carries_terminal_error_fields() -> None:+ """#3104/#3136: buffered aggregation must not drop the terminal chunk's+ typed error — ``empty_model_output`` keeps a ``stop``/``length``+ finish_reason, so the fields are the only failure signal.+ """+ source = _chunks(+ GenerationChunk(text_delta="\n\n", is_first=True),+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="length",+ completion_tokens=2,+ error_code="empty_model_output",+ error_message="model produced no visible output text",+ ),+ )++ result = await collect_generation(source)++ assert result.finish_reason == "length"+ assert result.error_code == "empty_model_output"+ assert result.error_message == "model produced no visible output text"+++async def test_collect_generation_defaults_error_fields_to_none_on_success() -> None:+ source = _chunks(+ GenerationChunk(text_delta="Visible answer", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=1, completion_tokens=2),+ )++ result = await collect_generation(source)++ assert result.text == "Visible answer"+ assert result.error_code is None+ assert result.error_message is Nonediff --git a/packages/sie_server/tests/adapters/test_grounding_dino.py b/packages/sie_server/tests/adapters/test_grounding_dino.pyindex 378f47aba..8b9170c40 100644--- a/packages/sie_server/tests/adapters/test_grounding_dino.py+++ b/packages/sie_server/tests/adapters/test_grounding_dino.py@@ -391,3 +391,26 @@ class TestGroundingDINOIntegration:assert "bbox" in objif obj["bbox"]:assert len(obj["bbox"]) == 4+++def test_extract_image_rejects_undecodable_bytes_with_typed_error() -> None:+ """Non-image bytes are a typed InvalidMediaError (-> 400), not a PIL OSError 500."""+ from sie_server.types.inputs import InvalidMediaError++ adapter = GroundingDINOAdapter("IDEA-Research/grounding-dino-tiny")++ with pytest.raises(InvalidMediaError, match="image data is not a decodable image"):+ adapter._extract_image(Item(images=[ImageInput(data=b"valid base64, not an image", format="jpeg")]))+++def test_extract_fallback_names_the_offending_item_index() -> None:+ """The inline-decode fallback loop passes each item's request-local index."""+ from sie_server.types.inputs import InvalidMediaError++ adapter = GroundingDINOAdapter("IDEA-Research/grounding-dino-tiny")+ adapter._model = MagicMock()+ adapter._processor = MagicMock()+ items = [Item(), Item(), Item(images=[ImageInput(data=b"valid base64, not an image", format="png")])]++ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[2\]\.images\[0\]\.data`"):+ adapter.extract(items, labels=["cat"])diff --git a/packages/sie_server/tests/adapters/test_image_decode_errors.py b/packages/sie_server/tests/adapters/test_image_decode_errors.pynew file mode 100644index 000000000..ef12b270a--- /dev/null+++ b/packages/sie_server/tests/adapters/test_image_decode_errors.py@@ -0,0 +1,56 @@+"""Undecodable image bytes raise a typed error across the col-family adapters.++Fix-the-class sweep: every adapter that opens user image bytes with PIL routes+through ``sie_server.types.inputs.decode_image``, which maps PIL's+``UnidentifiedImageError`` (an ``OSError`` subclass that misses the+``ValueError`` -> 400 INVALID_INPUT mapping) to ``InvalidMediaError`` with a+JSON-path message. These adapters have no dedicated test module, so their+loader seams are pinned here.+"""++from __future__ import annotations++import io++import pytest+from PIL import Image+from sie_server.adapters.colpali import ColPaliAdapter+from sie_server.adapters.colqwen2 import ColQwen2Adapter+from sie_server.adapters.colqwen3 import ColQwen3Adapter+from sie_server.adapters.colsmol import ColSmolAdapter+from sie_server.adapters.nemo_colembed import NemoColEmbedAdapter+from sie_server.types.inputs import InvalidMediaError, Item++_NOT_AN_IMAGE = b"valid base64 decoded to these bytes, but they are not an image"+++def _png_stub() -> dict[str, bytes]:+ buf = io.BytesIO()+ Image.new("RGB", (2, 2)).save(buf, format="PNG")+ return {"data": buf.getvalue()}+++ "adapter_cls",+ [ColPaliAdapter, ColQwen2Adapter, ColQwen3Adapter, ColSmolAdapter],+)+def test_col_family_load_images_rejects_undecodable_bytes(adapter_cls: type) -> None:+ adapter = adapter_cls("unused")++ with pytest.raises(InvalidMediaError, match=r"not a decodable image - at `\$\.items\[\*\]\.images\[0\]\.data`"):+ adapter._load_images(Item(images=[{"data": _NOT_AN_IMAGE}]))+++def test_col_family_names_the_offending_image_index() -> None:+ adapter = ColPaliAdapter("unused")++ with pytest.raises(InvalidMediaError, match=r"\.images\[1\]\.data"):+ adapter._load_images(Item(images=[_png_stub(), {"data": _NOT_AN_IMAGE}]))+++def test_nemo_colembed_encode_images_names_the_item() -> None:+ adapter = NemoColEmbedAdapter("unused")+ items = [Item(images=[_png_stub()]), Item(images=[{"data": _NOT_AN_IMAGE}])]++ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[1\]\.images\[0\]\.data`"):+ adapter._encode_images(items, is_query=False)diff --git a/packages/sie_server/tests/adapters/test_lora_integration.py b/packages/sie_server/tests/adapters/test_lora_integration.pyindex f596786a2..333b17213 100644--- a/packages/sie_server/tests/adapters/test_lora_integration.py+++ b/packages/sie_server/tests/adapters/test_lora_integration.py@@ -5,7 +5,7 @@ Tests validate that LoRA profiles work correctly through the full server stack:- Interleaved requests with different LoRAs- Base model + LoRA coexistence-Mark: integration (run with `mise run test -i packages/sie_server/tests/test_lora_integration.py`)+Mark: integration (run with `mise run test -- -i packages/sie_server/tests/adapters/test_lora_integration.py`)"""from __future__ import annotationsdiff --git a/packages/sie_server/tests/adapters/test_mlx_generation.py b/packages/sie_server/tests/adapters/test_mlx_generation.pyindex a001cb2d5..07ebfef2b 100644--- a/packages/sie_server/tests/adapters/test_mlx_generation.py+++ b/packages/sie_server/tests/adapters/test_mlx_generation.py@@ -8,11 +8,14 @@ SSE parsing, and cover the device-swap factory, the kwarg translation, and thefrom __future__ import annotations+import socket+from pathlib import Pathfrom typing import Any, Selffrom unittest.mock import patchimport pytestfrom sie_server.adapters._generation_base import collect_generation+from sie_server.adapters.mlx import _serverfrom sie_server.adapters.mlx.generation import MLXGenerationAdapterfrom sie_server.adapters.sglang.generation import (SGLangGenerationAdapter,@@ -120,12 +123,15 @@ def test_load_aborts_when_warmup_fails(adapter: MLXGenerationAdapter) -> None:patch("sie_server.adapters.mlx.generation._server.wait_for_server", return_value=True),patch("sie_server.adapters.mlx.generation._server.warmup_model", return_value=False),patch("sie_server.adapters.mlx.generation._server.terminate_process") as term,+ patch("sie_server.adapters.mlx.generation._server.release_port") as release,pytest.raises(RuntimeError, match="warm up"),):adapter.load("mps")assert adapter._server_url is Noneassert adapter._process is None+ assert adapter._port is Noneterm.assert_called_once()+ release.assert_called_once_with(30210)# -- generate(): OpenAI /v1/completions SSE parsing ---------------------------@@ -244,6 +250,102 @@ def test_unload_terminates_subprocess(adapter: MLXGenerationAdapter) -> None:assert adapter._server_url is None+def test_output_log_failure_releases_port(adapter: MLXGenerationAdapter) -> None:+ """The port is reserved before the log is opened, so a /tmp failure must+ still hand it back — otherwise repeated failures exhaust the span.+ """+ adapter._process = None+ with (+ patch("sie_server.adapters.mlx.generation._server.mlx_lm_available", return_value=True),+ patch("sie_server.adapters.mlx.generation._server.find_free_port", return_value=30210),+ patch(+ "sie_server.adapters.mlx.generation._server.open_output_log",+ side_effect=OSError("no space left on device"),+ ),+ patch("sie_server.adapters.mlx.generation._server.release_port") as release,+ pytest.raises(OSError, match="no space left on device"),+ ):+ adapter.load("mps")+ assert adapter._server_url is None+ assert adapter._port is None+ release.assert_called_once_with(30210)+++def test_launch_failure_releases_port(adapter: MLXGenerationAdapter) -> None:+ """A failed exec must release the port and drop the log it opened."""+ adapter._process = None+ fake_log = type("L", (), {"name": "/tmp/mlx_launch_test_does_not_exist.log", "close": lambda self: None})() # noqa: S108 — fake path; unlink is suppressed+ with (+ patch("sie_server.adapters.mlx.generation._server.mlx_lm_available", return_value=True),+ patch("sie_server.adapters.mlx.generation._server.find_free_port", return_value=30210),+ patch("sie_server.adapters.mlx.generation._server.open_output_log", return_value=fake_log),+ patch(+ "sie_server.adapters.mlx.generation._server.launch_mlx_server",+ side_effect=OSError("exec format error"),+ ),+ patch("sie_server.adapters.mlx.generation._server.terminate_process"),+ patch("sie_server.adapters.mlx.generation._server.release_port") as release,+ pytest.raises(OSError, match="exec format error"),+ ):+ adapter.load("mps")+ assert adapter._server_url is None+ assert adapter._port is None+ release.assert_called_once_with(30210)+++def test_unload_releases_port_and_cleans_output_log(adapter: MLXGenerationAdapter) -> None:+ """Unload returns the reserved port to the pool and removes the temp log."""+ adapter._process = None+ adapter._port = 30210+ adapter._output_file = _server.open_output_log(prefix="sie_test_mlx_")+ log_path = Path(adapter._output_file.name)++ with patch("sie_server.adapters.mlx.generation._server.release_port") as mock_release:+ adapter.unload()++ mock_release.assert_called_once_with(30210)+ assert adapter._port is None+ assert adapter._output_file is None+ assert not log_path.exists()+++# -- Port reservation (mirrors sglang/_server.py — see test_sglang.py) ---------+++def test_release_returns_reserved_port_to_pool(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(_server, "_RESERVED_PORTS", set())+ port = _server.find_free_port()+ assert port in _server._RESERVED_PORTS+ _server.release_port(port)+ assert port not in _server._RESERVED_PORTS+++def test_exhausted_span_recovers_after_release(monkeypatch: pytest.MonkeyPatch) -> None:+ """Releasing one port un-bricks allocation after the span exhausts.++ LRU eviction→reload churn scenario: without release_port the reserved set+ only grows, and once all 100 ports are reserved every MLX generation load+ fails until a full process restart.+ """+ # Anchor the scan on a port the OS just proved bindable, so the test+ # doesn't depend on the state of the real MLX range (30200-30299).+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.bind(("127.0.0.1", 0))+ anchor = s.getsockname()[1]+ monkeypatch.setattr(_server, "_RESERVED_PORTS", set(range(anchor, anchor + 100)))+ with pytest.raises(RuntimeError, match="Could not find free port"):+ _server.find_free_port(anchor)+ _server.release_port(anchor)+ assert _server.find_free_port(anchor) == anchor+++def test_release_tolerates_none_and_unreserved_ports(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(_server, "_RESERVED_PORTS", set())+ _server.release_port(None)+ _server.release_port(54321) # never reserved — must be a no-op+ assert not _server._RESERVED_PORTS++def test_memory_footprint_zero(adapter: MLXGenerationAdapter) -> None:assert adapter.memory_footprint() == 0diff --git a/packages/sie_server/tests/adapters/test_owlv2.py b/packages/sie_server/tests/adapters/test_owlv2.pyindex 857901c21..1f62edf1c 100644--- a/packages/sie_server/tests/adapters/test_owlv2.py+++ b/packages/sie_server/tests/adapters/test_owlv2.py@@ -204,3 +204,26 @@ def test_fused_requests_map_prepared_results_positionally() -> None:detect_batch.call_args.kwargs["pixel_values"],torch.stack([prepared[0].payload.pixel_values, prepared[1].payload.pixel_values]),)+++def test_extract_image_rejects_undecodable_bytes_with_typed_error() -> None:+ """Non-image bytes are a typed InvalidMediaError (-> 400), not a PIL OSError 500."""+ from sie_server.types.inputs import InvalidMediaError++ adapter = Owlv2Adapter("google/owlv2-base-patch16-ensemble")++ with pytest.raises(InvalidMediaError, match="image data is not a decodable image"):+ adapter._extract_image(Item(images=[{"data": b"valid base64, not an image", "format": "jpeg"}]))+++def test_extract_fallback_names_the_offending_item_index() -> None:+ """The inline-decode fallback loop passes each item's request-local index."""+ from sie_server.types.inputs import InvalidMediaError++ adapter = Owlv2Adapter("google/owlv2-base-patch16-ensemble")+ adapter._model = MagicMock()+ adapter._processor = MagicMock()+ items = [Item(), Item(), Item(images=[{"data": b"valid base64, not an image", "format": "png"}])]++ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[2\]\.images\[0\]\.data`"):+ adapter.extract(items, labels=["object"])diff --git a/packages/sie_server/tests/adapters/test_paddleocr_vl.py b/packages/sie_server/tests/adapters/test_paddleocr_vl.pyindex 9ede4c659..99b819f13 100644--- a/packages/sie_server/tests/adapters/test_paddleocr_vl.py+++ b/packages/sie_server/tests/adapters/test_paddleocr_vl.py@@ -15,14 +15,7 @@ _ = transformers.AutoProcessor_ = transformers.AutoModelForCausalLM_ = transformers.masking_utils.create_causal_mask-_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"--# Both catalog versions share this adapter: their custom modeling code is-# byte-identical upstream, so each pinned revision must keep resolving.-_CATALOG_VERSIONS = [- ("PaddlePaddle/PaddleOCR-VL-1.5", "6819afc8509ac9afa50e91b34627a7cf8f7900bb"),- ("PaddlePaddle/PaddleOCR-VL-1.6", "cdc88f5feff0e4079e75863205053a68358e52f7"),-]+_MODEL_PATH = Path(__file__).resolve().parents[2] / "models" / "PaddlePaddle__PaddleOCR-VL-1.5.yaml"class TestPaddleOCRVLAdapter:@@ -334,26 +327,21 @@ class TestPaddleOCRVLAdapter:assert mock_model.generate.call_args.kwargs["use_cache"] is True- @pytest.mark.parametrize(("sie_id", "hf_revision"), _CATALOG_VERSIONS)- def test_yaml_config_loads(self, sie_id: str, hf_revision: str) -> None:+ def test_yaml_config_loads(self) -> None:"""The shipped model YAML parses and resolves an adapter path."""import yamlfrom sie_server.config.model import ModelConfig- yaml_path = _MODELS_DIR / f"{sie_id.replace('/', '__')}.yaml"- with yaml_path.open() as f:+ with _MODEL_PATH.open() as f:data = yaml.safe_load(f)config = ModelConfig(**data)- assert config.sie_id == sie_id- assert config.hf_id == sie_id- assert config.hf_revision == hf_revision+ assert config.sie_id == "PaddlePaddle/PaddleOCR-VL-1.5"+ assert config.hf_id == "PaddlePaddle/PaddleOCR-VL-1.5"+ assert config.hf_revision == "6819afc8509ac9afa50e91b34627a7cf8f7900bb"assert config.inputs.image is Trueresolved = config.resolve_profile("default")assert resolved.adapter_path == "sie_server.adapters.sglang_vision_extract.adapter:SGLangVisionExtractAdapter"assert resolved.compute_precision == "bfloat16"- # A stale served_model_name silently serves the wrong weights under the- # right id, so pin it to sie_id rather than leaving it to review.- assert resolved.loadtime["served_model_name"] == sie_idfallback = config.resolve_profile("transformers")assert fallback.adapter_path == "sie_server.adapters.paddleocr_vl:PaddleOCRVLAdapter"assert fallback.compute_precision == "bfloat16"diff --git a/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.py b/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.pyindex 1a629ba51..469e199b5 100644--- a/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.py+++ b/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.py@@ -364,10 +364,11 @@ class TestVideoFramesBillAsImages:adapter.encode([item], ["dense"])def test_unreadable_images_are_not_billed(self, monkeypatch: pytest.MonkeyPatch) -> None:- # ``_load_images`` drops an image it cannot decode with only a warning,- # so counting SUBMITTED images would bill three for the one the model- # actually saw — the same silent over-bill the video half forbids. Both- # halves of the count are processed-based.+ # ``_load_images`` now faults on an undecodable image (InvalidMediaError+ # -> 400, matching the video half), so a decode failure can no longer+ # shrink the loaded set. The processed-based count stays as+ # defense-in-depth: if fewer images than submitted ever reach the model,+ # billing follows what was processed, not what was submitted.adapter = self._adapter()monkeypatch.setattr(Qwen3VLEmbeddingAdapter,@@ -439,3 +440,14 @@ class TestVideoFramesBillAsImages:# Both ingress paths map InvalidInputError to INVALID_INPUT / HTTP 400,# so an undecodable video is a 4xx and never a generic 500.assert issubclass(VideoDecodeError, InvalidInputError)++ def test_undecodable_image_faults_instead_of_being_dropped(self) -> None:+ # Mirrors the video half: an image the model never saw must fault as a+ # typed 400, not be silently dropped from the embedding.+ from sie_server.types.inputs import InvalidMediaError++ adapter = Qwen3VLEmbeddingAdapter("unused")+ item = SimpleNamespace(images=[{"data": b"valid base64, not an image"}])++ with pytest.raises(InvalidMediaError, match="image data is not a decodable image"):+ adapter._load_images(item)diff --git a/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.py b/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.pyindex 8fd2e14ae..63ffd61a8 100644--- a/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.py+++ b/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.py@@ -126,7 +126,7 @@ def test_vl_reranker_allows_image_only_and_text_plus_image_items() -> None:def test_vl_reranker_rejects_undecodable_image_with_typed_error() -> None:adapter = Qwen3VLRerankerAdapter("unused")- with pytest.raises(InvalidMediaError, match="valid decodable image"):+ with pytest.raises(InvalidMediaError, match="image data is not a decodable image"):adapter._load_first_image(Item(images=[{"data": b"not-an-image"}]))diff --git a/packages/sie_server/tests/adapters/test_runtime_options.py b/packages/sie_server/tests/adapters/test_runtime_options.pyindex fd076e6ce..b905e1620 100644--- a/packages/sie_server/tests/adapters/test_runtime_options.py+++ b/packages/sie_server/tests/adapters/test_runtime_options.py@@ -956,7 +956,7 @@ class TestExtractRuntimeOptions:def test_gliclass_load_bounds_tokenizer_max_length(self, monkeypatch: pytest.MonkeyPatch) -> None:"""``load()`` clamps ``tokenizer.model_max_length`` to ``max_seq_length``.- Regression for sie-test#88 / sie-test#89: long inputs crashed inside the+ Regression for long-input handling: inputs crashed inside thegliclass pipeline because the library default ``max_length=1024``exceeds the 512-token position-embedding capacity of these models."""@@ -1020,7 +1020,7 @@ class TestExtractRuntimeOptions:"""The infamous ``argmax(): ... numel() == 0`` crash is surfaced asValueError (validation), not RuntimeError (500 INFERENCE_ERROR).- Regression for sie-test#88 / sie-test#89.+ Regression for long-input handling."""from unittest.mock import MagicMock@@ -1121,7 +1121,7 @@ class TestExtractRuntimeOptions:"""A 6 KB Lorem-ipsum-style input flows through the adapter without crashingwhen the pipeline is properly bounded by max_seq_length.- Regression for sie-test#89: 54x repeated ``Lorem ipsum dolor sit amet,+ Long-input regression: 54x repeated ``Lorem ipsum dolor sit amet,consectetur adipiscing elit. `` with a single label ``Electronics``."""from unittest.mock import MagicMockdiff --git a/packages/sie_server/tests/adapters/test_sglang.py b/packages/sie_server/tests/adapters/test_sglang.pyindex cded52adb..9fac1cef9 100644--- a/packages/sie_server/tests/adapters/test_sglang.py+++ b/packages/sie_server/tests/adapters/test_sglang.py@@ -1,6 +1,8 @@"""Tests for SGLang embedding adapter (HTTP server mode)."""+import socketfrom concurrent.futures import ThreadPoolExecutor+from pathlib import Pathfrom unittest.mock import MagicMock, patchimport numpy as np@@ -309,6 +311,138 @@ class TestSGLangEmbeddingAdapter:assert adapter._server_url is Noneassert adapter._process is None+ @patch("sie_server.adapters.sglang._server.os.getpgid")+ @patch("sie_server.adapters.sglang._server.os.killpg")+ def test_unload_releases_port_and_cleans_output_log(+ self,+ mock_killpg: MagicMock,+ mock_getpgid: MagicMock,+ ) -> None:+ """Unload returns the reserved port to the pool and removes the temp log."""+ mock_process = MagicMock()+ mock_process.pid = 12345+ mock_process.wait.return_value = None+ mock_getpgid.return_value = 12345++ adapter = SGLangEmbeddingAdapter("test-model")+ adapter._process = mock_process+ adapter._server_url = "http://localhost:30000"+ adapter._port = 30000+ adapter._output_file = _server.open_output_log(prefix="sie_test_sglang_")+ log_path = Path(adapter._output_file.name)++ # Order matters: releasing the port before the child is down would hand+ # a live port to a concurrent load, so record both calls on one list.+ events: list[str] = []+ with (+ patch(+ "sie_server.adapters.sglang._server.terminate_process",+ side_effect=lambda *_args, **_kwargs: events.append("terminate"),+ ),+ patch(+ "sie_server.adapters.sglang._server.release_port",+ side_effect=lambda port: events.append(f"release:{port}"),+ ),+ ):+ adapter.unload()++ assert events == ["terminate", "release:30000"]+ assert adapter._port is None+ assert adapter._output_file is None+ assert not log_path.exists()++ @patch("sie_server.adapters.sglang._server.os.getpgid")+ @patch("sie_server.adapters.sglang._server.os.killpg")+ @patch("sie_server.adapters.sglang._server.wait_for_server", return_value=False)+ @patch("sie_server.adapters.sglang._server.subprocess.Popen")+ @patch("sie_server.adapters.sglang._server.find_free_port")+ def test_load_failure_releases_port_and_cleans_output_log(+ self,+ mock_find_port: MagicMock,+ mock_popen: MagicMock,+ mock_wait: MagicMock,+ mock_killpg: MagicMock,+ mock_getpgid: MagicMock,+ ) -> None:+ """A startup-health failure must not leak the reserved port or the temp log."""+ mock_find_port.return_value = 30000+ mock_process = MagicMock()+ mock_process.pid = 12345+ mock_process.poll.return_value = None # Process running but not healthy (timeout path)+ mock_popen.return_value = mock_process+ mock_getpgid.return_value = 12345++ # A real temp file, so the assertion below is "gone from disk" rather+ # than the weaker "attribute was reset".+ real_log = _server.open_output_log(prefix="sie_test_sglang_")+ log_path = Path(real_log.name)++ adapter = SGLangEmbeddingAdapter("test-model")+ with (+ patch("sie_server.adapters.sglang._server.open_output_log", return_value=real_log),+ patch("sie_server.adapters.sglang._server.release_port") as mock_release,+ pytest.raises(RuntimeError, match="failed to start"),+ ):+ adapter.load("cuda:0")++ mock_release.assert_called_once_with(30000)+ assert adapter._port is None+ assert adapter._server_url is None+ assert adapter._output_file is None+ assert not log_path.exists()++ @patch("sie_server.adapters.sglang._server.open_output_log", side_effect=OSError("no space left on device"))+ @patch("sie_server.adapters.sglang._server.find_free_port")+ def test_output_log_failure_releases_port(+ self,+ mock_find_port: MagicMock,+ mock_open_log: MagicMock,+ ) -> None:+ """The port is reserved before the log is opened, so a /tmp failure must+ still hand it back — otherwise repeated failures exhaust the span.+ """+ mock_find_port.return_value = 30000++ adapter = SGLangEmbeddingAdapter("test-model")+ with (+ patch("sie_server.adapters.sglang._server.release_port") as mock_release,+ pytest.raises(OSError, match="no space left on device"),+ ):+ adapter.load("cuda:0")++ mock_release.assert_called_once_with(30000)+ assert adapter._port is None+ assert adapter._server_url is None++ @patch("sie_server.adapters.sglang._server.subprocess.Popen", side_effect=OSError("exec format error"))+ @patch("sie_server.adapters.sglang._server.find_free_port")+ def test_launch_failure_releases_port_and_cleans_output_log(+ self,+ mock_find_port: MagicMock,+ mock_popen: MagicMock,+ ) -> None:+ """A failed exec must release the port and delete the log it opened."""+ mock_find_port.return_value = 30000++ # A real temp file, so the assertion below is "gone from disk" rather+ # than the weaker "attribute was reset".+ real_log = _server.open_output_log(prefix="sie_test_sglang_")+ log_path = Path(real_log.name)++ adapter = SGLangEmbeddingAdapter("test-model")+ with (+ patch("sie_server.adapters.sglang._server.open_output_log", return_value=real_log),+ patch("sie_server.adapters.sglang._server.release_port") as mock_release,+ pytest.raises(OSError, match="exec format error"),+ ):+ adapter.load("cuda:0")++ mock_release.assert_called_once_with(30000)+ assert adapter._port is None+ assert adapter._server_url is None+ assert adapter._output_file is None+ assert not log_path.exists()+def test_encode_before_load_raises(self) -> None:"""Encode before load raises error."""adapter = SGLangEmbeddingAdapter("test-model")@@ -634,3 +768,124 @@ class TestSGLangLoRA:adapter.set_active_lora("legal")with pytest.raises(ValueError, match=r"LoRA 'legal' not loaded.*Available: \[\]"):adapter.encode(items, output_types=["dense"])+++class TestPortReservation:+ """find_free_port reserves ports; release_port returns them to the pool."""++ def test_release_returns_reserved_port_to_pool(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(_server, "_RESERVED_PORTS", set())+ port = _server.find_free_port()+ assert port in _server._RESERVED_PORTS+ _server.release_port(port)+ assert port not in _server._RESERVED_PORTS++ def test_exhausted_span_recovers_after_release(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Releasing one port un-bricks allocation after the span exhausts.++ This is the LRU eviction→reload churn scenario: without release_port+ the reserved set only grows, and once all 100 ports are reserved every+ generation-model load fails until a full process restart.+ """+ # Anchor the scan on a port the OS just proved bindable, so the test+ # doesn't depend on the state of the real SGLang range (30000-30099).+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.bind(("localhost", 0))+ anchor = s.getsockname()[1]+ monkeypatch.setattr(_server, "_RESERVED_PORTS", set(range(anchor, anchor + 100)))+ with pytest.raises(RuntimeError, match="Could not find free port"):+ _server.find_free_port(anchor)+ _server.release_port(anchor)+ assert _server.find_free_port(anchor) == anchor++ def test_release_tolerates_none_and_unreserved_ports(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(_server, "_RESERVED_PORTS", set())+ _server.release_port(None)+ _server.release_port(54321) # never reserved — must be a no-op+ assert not _server._RESERVED_PORTS+++class TestKernelCacheEnvironment:+ def test_disabled_without_root(self) -> None:+ assert _server._kernel_cache_env({}, device_index=0) == {}++ @patch("sie_server.adapters.sglang._server.subprocess.run")+ def test_gpu_key_uses_driver_inventory_without_initializing_cuda(self, mock_run: MagicMock) -> None:+ mock_run.return_value = MagicMock(stdout="NVIDIA H100 80GB HBM3\nNVIDIA H200\n")++ first_key = _server._gpu_cache_key(0)+ second_key = _server._gpu_cache_key(1)++ assert first_key is not None+ assert first_key.startswith("gpu-")+ assert second_key is not None+ assert second_key.startswith("gpu-")+ assert first_key != second_key+ assert mock_run.call_args.args[0] == [+ "nvidia-smi",+ "--query-gpu=name",+ "--format=csv,noheader",+ ]++ def test_scopes_upstream_caches_by_abi_and_gpu(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(_server, "_installed_jit_abi_key", lambda: "abi123")+ monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_index: "sm120-gpu123")++ env = {_server.KERNEL_CACHE_ROOT_ENV_VAR: str(tmp_path)}+ cache_env = _server._kernel_cache_env(env, device_index=0)++ namespace = tmp_path / "v1" / "abi123" / "sm120-gpu123" / "device-0"+ assert cache_env["SGLANG_DG_CACHE_DIR"] == str(namespace / "deep-gemm")+ assert cache_env["FLASHINFER_WORKSPACE_BASE"] == str(namespace / "flashinfer")+ assert cache_env["CUTE_DSL_CACHE_DIR"] == str(namespace / "cutlass")+ assert cache_env["TRITON_CACHE_DIR"] == str(namespace / "triton")+ assert all(Path(path).is_dir() for path in cache_env.values())++ def test_explicit_upstream_path_wins(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(_server, "_installed_jit_abi_key", lambda: "abi123")+ monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_index: "sm90-gpu123")+ explicit = tmp_path / "operator-deep-gemm"+ env = {+ _server.KERNEL_CACHE_ROOT_ENV_VAR: str(tmp_path / "managed"),+ "SGLANG_DG_CACHE_DIR": str(explicit),+ }++ cache_env = _server._kernel_cache_env(env, device_index=0)++ assert "SGLANG_DG_CACHE_DIR" not in cache_env+ assert not explicit.exists()+ assert "TRITON_CACHE_DIR" in cache_env++ def test_invalid_or_unwritable_root_falls_back(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(_server, "_installed_jit_abi_key", lambda: "abi123")+ monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_index: "sm90-gpu123")+ blocker = tmp_path / "not-a-directory"+ blocker.write_text("x")++ assert _server._kernel_cache_env({_server.KERNEL_CACHE_ROOT_ENV_VAR: "relative"}, device_index=0) == {}+ assert _server._kernel_cache_env({_server.KERNEL_CACHE_ROOT_ENV_VAR: str(blocker)}, device_index=0) == {}++ with patch(+ "sie_server.adapters.sglang._server.tempfile.NamedTemporaryFile",+ side_effect=OSError("read-only cache"),+ ):+ assert (+ _server._kernel_cache_env(+ {_server.KERNEL_CACHE_ROOT_ENV_VAR: str(tmp_path / "read-only")},+ device_index=0,+ )+ == {}+ )+++def test_startup_failure_error_distinguishes_crash_from_timeout() -> None:+ """A dead child is a crash, not a timeout: the loader reclassifies+ timeout-shaped messages as ModelLoadTimeoutError stamped with elapsed+ time, so the crash message must never match that pattern.+ """+ timeout_error = _server.startup_failure_error(None)+ assert "failed to start within timeout" in str(timeout_error)++ crash_error = _server.startup_failure_error(None, crash_exit_code=-9)+ assert "process exited during startup (exit code -9)" in str(crash_error)+ assert "failed to start within timeout" not in str(crash_error)diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex 4f702908d..5f5ef2819 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -22,6 +22,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom sie_server.adapters._generation_base import GenerationChunk, collect_generation, suppress_thinking_blocks+from sie_server.adapters.sglang import _serverfrom sie_server.adapters.sglang.cuda13 import SGLangStrictThinkingAdapterfrom sie_server.adapters.sglang.generation import (SGLangGenerationAdapter,@@ -1056,6 +1057,100 @@ def test_unload_terminates_process(mock_killpg: MagicMock, mock_getpgid: MagicMoassert adapter._server_url is None+@patch("sie_server.adapters.sglang._server.os.getpgid")+@patch("sie_server.adapters.sglang._server.os.killpg")+def test_unload_releases_port_and_cleans_output_log(+ mock_killpg: MagicMock,+ mock_getpgid: MagicMock,+ adapter,+) -> None:+ """Unload returns the reserved port to the pool and removes the temp log."""+ mock_process = MagicMock()+ mock_process.pid = 12345+ mock_process.wait.return_value = None+ mock_getpgid.return_value = 12345++ adapter._process = mock_process+ adapter._server_url = "http://localhost:30005"+ adapter._device = "cuda:0"+ adapter._port = 30005+ adapter._output_file = _server.open_output_log(prefix="sie_test_sglang_")+ log_path = Path(adapter._output_file.name)++ with patch("sie_server.adapters.sglang._server.release_port") as mock_release:+ adapter.unload()++ mock_release.assert_called_once_with(30005)+ assert adapter._port is None+ assert adapter._output_file is None+ assert not log_path.exists()+++@patch("sie_server.adapters.sglang._server.os.getpgid")+@patch("sie_server.adapters.sglang._server.os.killpg")+@patch("sie_server.adapters.sglang._server.wait_for_server", return_value=False)+@patch("sie_server.adapters.sglang._server.subprocess.Popen")+@patch("sie_server.adapters.sglang._server.find_free_port")+def test_failed_startup_releases_port_and_cleans_output_log(+ mock_find_port: MagicMock,+ mock_popen: MagicMock,+ mock_wait: MagicMock,+ mock_killpg: MagicMock,+ mock_getpgid: MagicMock,+ adapter,+) -> None:+ """A startup-health failure must not leak the reserved port or the temp log."""+ mock_find_port.return_value = 30006+ mock_process = MagicMock()+ mock_process.pid = 12345+ mock_process.poll.return_value = None # Process running but not healthy (timeout path)+ mock_popen.return_value = mock_process+ mock_getpgid.return_value = 12345++ with (+ patch("sie_server.adapters.sglang._server.release_port") as mock_release,+ pytest.raises(RuntimeError, match="failed to start"),+ ):+ adapter.load("cuda:0")++ mock_release.assert_called_once_with(30006)+ assert adapter._port is None+ assert adapter._server_url is None+ assert adapter._output_file is None+++@patch("sie_server.adapters.sglang._server.subprocess.Popen")+@patch("sie_server.adapters.sglang._server.find_free_port")+def test_speculative_guard_abort_releases_port_and_cleans_output_log(+ mock_find_port: MagicMock,+ mock_popen: MagicMock,+) -> None:+ """The pre-launch extra_buffer validation abort must not leak the port or log.++ The guard raises after the port was reserved and the temp log opened but+ before the subprocess launches — a distinct abort seam from the+ startup-health failure above.+ """+ mock_find_port.return_value = 30007+ adapter = SGLangGenerationAdapter(+ model_name_or_path="Qwen/Qwen3.5-4B",+ served_model_name="Qwen/Qwen3.5-4B",+ speculative={"enabled": True, "algorithm": "nextn"},+ )++ with (+ patch("sie_server.adapters.sglang._server.release_port") as mock_release,+ pytest.raises(RuntimeError, match="extra_buffer"),+ ):+ adapter.load("cuda:0")++ mock_release.assert_called_once_with(30007)+ assert adapter._port is None+ assert adapter._server_url is None+ assert adapter._output_file is None+ mock_popen.assert_not_called()++@patch("sie_server.adapters.sglang.generation.asyncio.new_event_loop")@patch("sie_server.adapters.sglang._server.os.getpgid")@patch("sie_server.adapters.sglang._server.os.killpg")diff --git a/packages/sie_server/tests/adapters/test_siglip.py b/packages/sie_server/tests/adapters/test_siglip.pyindex 07854b751..7e95f39eb 100644--- a/packages/sie_server/tests/adapters/test_siglip.py+++ b/packages/sie_server/tests/adapters/test_siglip.py@@ -509,6 +509,53 @@ class TestSiglipAdapter:assert output.dense is not Nonenp.testing.assert_array_equal(output.dense, np.array([[1.0] * 3, [2.0] * 3]))+ def test_mixed_batch_uses_prepared_images_and_text_tower(self) -> None:+ """Text items ride the prepared list as empty payloads (#3136): the+ image tower keeps its positionally aligned prepared tensors and the+ text item still encodes via the text tower.+ """+ adapter = SiglipAdapter("google/siglip2-base-patch16-224", normalize=False)+ model = MagicMock()+ model.get_image_features.side_effect = lambda pixel_values: pixel_values[:, :, 0, 0]+ model.get_text_features.side_effect = lambda **kw: torch.full((1, 3), 9.0)+ processor = MagicMock()+ processor.return_value = {"input_ids": torch.tensor([[1, 2]])}+ adapter._model = model+ adapter._processor = processor+ adapter._device = "cpu"+ adapter._dense_dim = 3++ prepared = [+ PreparedItem(+ payload=ImagePayload(pixel_values=None, original_size=(0, 0)),+ cost=1,+ original_index=0,+ ),+ PreparedItem(+ payload=ImagePayload(pixel_values=torch.full((3, 1, 1), 1.0), original_size=(1, 1)),+ cost=1,+ original_index=1,+ ),+ PreparedItem(+ payload=ImagePayload(pixel_values=torch.full((3, 1, 1), 2.0), original_size=(1, 1)),+ cost=1,+ original_index=2,+ ),+ ]+ items = [+ Item(id="query", text="a red square"),+ _img_item("first", [(1, 1, 1)]),+ _img_item("second", [(2, 2, 2)]),+ ]++ output = adapter.encode(items, ["dense"], prepared_items=prepared)++ assert output.dense is not None+ np.testing.assert_array_equal(output.dense[0], np.array([9.0] * 3))+ np.testing.assert_array_equal(output.dense[1], np.array([1.0] * 3))+ np.testing.assert_array_equal(output.dense[2], np.array([2.0] * 3))+ assert output.extra["text_tower_skipped"] == [False, True, True]+@pytest.mark.parametrize("invalid", [0, -1])def test_rejects_non_positive_max_length(self, invalid: int) -> None:with pytest.raises(ValueError, match="max_seq_length must be positive"):@@ -637,3 +684,30 @@ class TestSiglipAdapter:output.dense,np.array([[1.0] * 3, [2.0] * 3, [3.0] * 3, [4.0] * 3]),)+++def test_preprocess_one_rejects_undecodable_bytes_with_typed_error() -> None:+ """Non-image bytes are a typed InvalidMediaError (-> 400), not a PIL OSError 500."""+ from sie_server.types.inputs import InvalidMediaError++ adapter = SiglipAdapter("google/siglip-base-patch16-224")++ with pytest.raises(InvalidMediaError, match="image data is not a decodable image"):+ adapter._preprocess_one({"data": b"valid base64, but not an image"})+++def test_undecodable_bytes_name_the_original_item_index() -> None:+ """The decode jobs carry request-local indices through the stacked batch.++ ``image_indices`` maps the image-item subset back to original positions+ (here 0 and 2); the decode failure must name index 2, not subset slot 1.+ """+ from sie_server.types.inputs import InvalidMediaError++ adapter = SiglipAdapter("google/siglip-base-patch16-224")+ adapter._processor = _FakeVisionProcessor()+ good = _img_item("good", [(1, 2, 3)])+ bad = Item(images=[{"data": b"valid base64, but not an image"}])++ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[2\]\.images\[0\]\.data`"):+ adapter._preprocess_image_batch([0, 2], [good, bad], {})diff --git a/packages/sie_server/tests/adapters/test_siglip_integration.py b/packages/sie_server/tests/adapters/test_siglip_integration.pynew file mode 100644index 000000000..5681206c2--- /dev/null+++ b/packages/sie_server/tests/adapters/test_siglip_integration.py@@ -0,0 +1,187 @@+"""API-level integration regression for mixed text+image encode batches (#3136).++The Image Search Playground (console/BFF) sends ONE ``/v1/encode`` request+carrying 1 text item + 4 image items against the catalog visual-search model+(``google/siglip2-base-patch16-224``). Before #3138 the image preprocessor+dropped text-only items, the worker future never resolved for the full batch,+and the request hung until the client timed out.++The unit fix is covered at the preprocessor/worker/adapter seams+(``tests/core/test_preprocessor.py``, ``tests/core/test_worker_core.py``,+``tests/adapters/test_siglip.py``). #3136 additionally requires the HTTP API+seam: real request decode -> ``EncodePipeline.run_encode`` -> worker, for both+request shapes:++- the exact console/BFF wire shape: JSON body with base64 ``data`` images+- the native SDK shape: ``SIEClient.encode`` with raw image bytes++Raw ``httpx`` is used deliberately for the console/BFF shape — the regression+is about the wire-level request decode, which the SDK would paper over.++Mark: integration (run with ``mise run test -- -i``). Downloads SigLIP2-base+weights on first run; CPU inference is supported (the adapter forces float32+off-CUDA).+"""++from __future__ import annotations++import base64+import io+import math+import socket+import time+from collections.abc import Generator+from typing import Any++import httpx+import numpy as np+import pytest+from PIL import Image+from sie_sdk import SIEClient++pytestmark = pytest.mark.integration++# The exact catalog model behind the visual-search task in #3136.+MODEL = "google/siglip2-base-patch16-224"+DENSE_DIM = 768++# First request lazy-loads the model (non-blocking 503 MODEL_LOADING while+# weights download + load); this bounds the retry loop, not a single request.+_LOAD_DEADLINE_S = 600.0+# Bounded per-request timeout: the #3136 hang surfaces as a ReadTimeout+# failure here instead of wedging the suite.+_REQUEST_TIMEOUT_S = 120.0+_WARM_TIMEOUT_S = 60.0+++def _find_free_port(start: int = 8500, end: int = 8600) -> int:+ for port in range(start, end):+ try:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ s.bind(("127.0.0.1", port))+ return port+ except OSError:+ continue+ msg = f"No free port found in range {start}-{end}"+ raise RuntimeError(msg)++[email protected](scope="module")+def siglip_server(device: str, sie_server_process_factory: type[Any]) -> Generator[str]:+ # The probe socket is closed before the child binds, so a concurrent+ # process can steal the port in between. Retry with a fresh port instead+ # of failing the whole module on that race.+ last_error: Exception | None = None+ for _ in range(3):+ server = sie_server_process_factory(+ port=_find_free_port(),+ models_dir="packages/sie_server/models",+ )+ try:+ server.start(MODEL, device)+ server.wait_ready(timeout_s=600.0)+ except Exception as exc: # noqa: BLE001 - port stolen or failed boot; retry fresh+ server.stop()+ last_error = exc+ continue+ try:+ yield server.get_url()+ finally:+ server.stop()+ return+ msg = "sie-server failed to start on 3 candidate ports"+ raise RuntimeError(msg) from last_error+++def _png_bytes(color: tuple[int, int, int]) -> bytes:+ buf = io.BytesIO()+ Image.new("RGB", (16, 16), color=color).save(buf, format="PNG")+ return buf.getvalue()+++def _mixed_json_items(tag: str) -> list[dict[str, Any]]:+ """The console/BFF shape: 1 text item + 4 base64 image items, one request."""+ items: list[dict[str, Any]] = [{"id": f"{tag}-text-0", "text": f"a red square ({tag})"}]+ for index in range(4):+ png = _png_bytes((255, 4 * index, 0))+ items.append(+ {+ "id": f"{tag}-image-{index + 1}",+ "images": [{"data": base64.b64encode(png).decode("ascii"), "format": "png"}],+ }+ )+ return items+++def _post_encode_json(url: str, items: list[dict[str, Any]], *, timeout_s: float) -> httpx.Response:+ """POST the JSON encode request, retrying only the non-blocking lazy-load 503.++ ``/v1/encode`` returns ``503 MODEL_LOADING`` immediately while the model+ loads; each actual inference attempt stays bounded by ``timeout_s`` so a+ reintroduced #3136 hang fails fast instead of wedging the run.+ """+ deadline = time.monotonic() + _LOAD_DEADLINE_S+ while True:+ response = httpx.post(+ f"{url}/v1/encode/{MODEL}",+ json={"items": items},+ headers={"Accept": "application/json"},+ timeout=timeout_s,+ )+ if response.status_code != 503:+ return response+ detail = response.json().get("detail", {})+ if detail.get("code") != "MODEL_LOADING" or time.monotonic() >= deadline:+ return response+ time.sleep(2.0)+++class TestMixedTextImageEncodeApi:+ """One request, ``items = [{text}, {image} x4]`` — the #3136 failure shape."""++ def test_mixed_text_image_single_request_completes(self, siglip_server: str) -> None:+ """Console/BFF JSON shape: 200 with 5 aligned embeddings, no hang."""+ items = _mixed_json_items("cold")+ response = _post_encode_json(siglip_server, items, timeout_s=_REQUEST_TIMEOUT_S)++ assert response.status_code == 200, response.text+ data = response.json()+ assert data["model"] == MODEL+ assert len(data["items"]) == len(items)+ # Original order preserved: text item first, then the four images.+ assert [result["id"] for result in data["items"]] == [item["id"] for item in items]+ for result in data["items"]:+ dense = result["dense"]+ assert dense is not None, f"missing dense for {result['id']}"+ assert dense["dims"] == DENSE_DIM+ assert len(dense["values"]) == DENSE_DIM+ assert all(math.isfinite(value) for value in dense["values"])++ def test_mixed_text_image_warm_repeat_completes(self, siglip_server: str) -> None:+ """A warm second mixed request succeeds within a tight bound."""+ # Prime the model (and absorb the lazy load) with the first shape.+ first = _post_encode_json(siglip_server, _mixed_json_items("prime"), timeout_s=_REQUEST_TIMEOUT_S)+ assert first.status_code == 200, first.text++ warm = _post_encode_json(siglip_server, _mixed_json_items("warm"), timeout_s=_WARM_TIMEOUT_S)+ assert warm.status_code == 200, warm.text+ assert len(warm.json()["items"]) == 5++ def test_mixed_text_image_sdk_batch_completes(self, siglip_server: str) -> None:+ """Native SDK shape: raw image bytes through ``SIEClient.encode``."""+ client = SIEClient(siglip_server, timeout_s=float(_LOAD_DEADLINE_S))+ sdk_items: list[dict[str, Any]] = [{"id": "sdk-text-0", "text": "a red square (sdk)"}]+ sdk_items.extend(+ {"id": f"sdk-image-{index + 1}", "images": [_png_bytes((0, 4 * index, 255))]} for index in range(4)+ )++ results = client.encode(MODEL, sdk_items)++ assert isinstance(results, list)+ assert len(results) == len(sdk_items)+ assert [result.get("id") for result in results] == [item["id"] for item in sdk_items]+ for result in results:+ assert isinstance(result["dense"], np.ndarray)+ assert result["dense"].shape == (DENSE_DIM,)+ assert np.isfinite(result["dense"]).all()diff --git a/packages/sie_server/tests/adapters/test_st_sparse_vision.py b/packages/sie_server/tests/adapters/test_st_sparse_vision.pyindex 7129ba1ab..da0aab2e8 100644--- a/packages/sie_server/tests/adapters/test_st_sparse_vision.py+++ b/packages/sie_server/tests/adapters/test_st_sparse_vision.py@@ -361,3 +361,23 @@ class TestSparseEncoderVisionAdapter:assert adapter.dims.sparse == VOCABadapter.unload()assert adapter.dims.sparse is None+++def test_extract_input_rejects_undecodable_bytes_with_typed_error() -> None:+ """Non-image bytes are a typed InvalidMediaError (-> 400), not a PIL OSError 500."""+ from sie_server.types.inputs import InvalidMediaError, Item++ adapter = SparseEncoderVisionAdapter("org/model")++ with pytest.raises(InvalidMediaError, match="image data is not a decodable image"):+ adapter._extract_input(Item(images=[{"data": b"valid base64, but not an image"}]))+++def test_extract_input_names_the_enclosing_item_index() -> None:+ """encode() enumerates items into _extract_input, so a NON-first item is named."""+ from sie_server.types.inputs import InvalidMediaError, Item++ adapter = SparseEncoderVisionAdapter("org/model")++ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[2\]\.images\[0\]\.data`"):+ adapter._extract_input(Item(images=[{"data": b"valid base64, but not an image"}]), item_index=2)diff --git a/packages/sie_server/tests/api/test_encode_dtype.py b/packages/sie_server/tests/api/test_encode_dtype.pyindex 8a7285017..03c6b3d05 100644--- a/packages/sie_server/tests/api/test_encode_dtype.py+++ b/packages/sie_server/tests/api/test_encode_dtype.py@@ -1,5 +1,5 @@from typing import Any-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchimport msgpackimport msgpack_numpy as m@@ -8,6 +8,7 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom sie_server.api.encode import router as encode_router+from sie_server.api.serialization import MsgPackResponsefrom sie_server.config.model import (AdapterOptions,EmbeddingDim,@@ -25,6 +26,16 @@ m.patch()JSON_HEADERS = {"Accept": "application/json"}+def test_msgpack_response_rejects_object_arrays_without_pickling() -> None:+ unsafe = np.array([object()], dtype=object)++ with patch("msgpack_numpy.pickle.dumps") as pickle_dumps:+ with pytest.raises(ValueError, match="allowed numeric dtype"):+ MsgPackResponse({"values": unsafe})++ pickle_dumps.assert_not_called()++def _mock_encode_impl(items: list[Any], output_types: list[str], **kwargs: Any) -> Any:"""Implementation for mock encode - returns EncodeOutput."""from sie_server.core.inference_output import EncodeOutput, SparseVectordiff --git a/packages/sie_server/tests/api/test_encode_endpoint.py b/packages/sie_server/tests/api/test_encode_endpoint.pyindex 72738180c..8205ceef0 100644--- a/packages/sie_server/tests/api/test_encode_endpoint.py+++ b/packages/sie_server/tests/api/test_encode_endpoint.py@@ -251,7 +251,7 @@ class TestEncodeEndpoint:def test_encode_returns_model_load_failed_when_terminal(self, client: TestClient, mock_registry: MagicMock) -> None:"""A registry-recorded terminal failure returns 502 MODEL_LOAD_FAILED.- Regression for sie-test#85: previously the API returned 503+ Terminal-failure regression: previously the API returned 503MODEL_LOADING for any not-loaded model, which the SDK retried for5 minutes even on permanent gated/dependency failures. The newcontract returns 502 MODEL_LOAD_FAILED with no Retry-After headerdiff --git a/packages/sie_server/tests/api/test_encode_validation.py b/packages/sie_server/tests/api/test_encode_validation.pyindex 9aa023bed..6916726f3 100644--- a/packages/sie_server/tests/api/test_encode_validation.py+++ b/packages/sie_server/tests/api/test_encode_validation.py@@ -1,3 +1,4 @@+import base64from typing import Anyfrom unittest.mock import MagicMock@@ -226,3 +227,45 @@ class TestMachineProfileValidation:headers={**JSON_HEADERS, "X-SIE-MACHINE-PROFILE": "l4-spot"},)assert response.status_code == 200+++class TestUndecodableImageValidation:+ """Undecodable image bytes are a 400 INVALID_INPUT, never a 500.++ Valid base64 that decodes to non-image bytes used to raise PIL's+ ``UnidentifiedImageError`` (an ``OSError``) inside the adapter, missing the+ ``ValueError`` -> 400 mapping and surfacing as a 500 ``INFERENCE_ERROR``+ with a leaked ``BytesIO`` repr. Adapters now decode through+ ``sie_server.types.inputs.decode_image``, whose ``InvalidMediaError``+ reaches the client as 400 INVALID_INPUT with the same JSON-path message+ style as the corrupt-base64 ingress error.+ """++ def test_undecodable_image_bytes_return_400_with_json_path(+ self, client: TestClient, mock_adapter: MagicMock+ ) -> None:+ from sie_server.types.inputs import decode_image++ def _decode_like_a_real_adapter(items: list[Any], output_types: list[str], **kwargs: Any) -> Any:+ # Mirrors every image adapter/preprocessor: user bytes are opened+ # via the shared decode_image seam, which raises here.+ for i, item in enumerate(items):+ for j, img in enumerate(item.images or []):+ decode_image(img, item_index=i, image_index=j)+ raise AssertionError("expected decode_image to reject the payload")++ mock_adapter.encode.side_effect = _decode_like_a_real_adapter++ not_an_image = base64.b64encode(b"valid base64, but not an image").decode()+ response = client.post(+ "/v1/encode/test-model",+ json={"items": [{"images": [{"data": not_an_image}]}]},+ headers=JSON_HEADERS,+ )++ assert response.status_code == 400+ detail = response.json()["detail"]+ assert detail["code"] == "INVALID_INPUT"+ assert "image data is not a decodable image" in detail["message"]+ assert "$.items[0].images[0].data" in detail["message"]+ assert "BytesIO" not in detail["message"]diff --git a/packages/sie_server/tests/api/test_error_code_hygiene.py b/packages/sie_server/tests/api/test_error_code_hygiene.pynew file mode 100644index 000000000..7c1c1861b--- /dev/null+++ b/packages/sie_server/tests/api/test_error_code_hygiene.py@@ -0,0 +1,257 @@+# Contract tests for the usability-sweep error-code hygiene fixes.+#+# 1. ``InferenceErrorHandler.handle_queue_full`` — the old mapping returned+# ``503 MODEL_NOT_LOADED`` for every ``QueueFullError``, which was wrong on+# every axis: the model IS loaded, a request larger than the queue's total+# capacity can never succeed no matter how often it is retried, and genuine+# transient pressure carried no ``Retry-After`` hint. New contract:+#+# - request item count alone exceeds the queue limit → ``400 INVALID_INPUT``+# naming the per-request limit (permanent client error, no Retry-After);+# - queue occupied by other work → ``503 QUEUE_FULL`` + ``Retry-After``;+# - a legacy ``QueueFullError`` without structured counts is conservatively+# treated as transient.+#+# 2. encode/score ``InputTooLongError`` — ``InputTooLongError`` subclasses+# ``ValueError``, and encode/score lacked the dedicated except arm that+# extract/audio already had, so token-budget overruns degraded to the+# generic ``400 INVALID_INPUT`` instead of ``400 INPUT_TOO_LONG`` (which+# the SDKs key their short-circuit behaviour on).+#+# Fixture patterns mirror ``test_extract_oom.py`` (failing worker future) and+# ``test_encode_endpoint.py`` (direct adapter path).++from __future__ import annotations++import asyncio+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import msgpack_numpy as m+from fastapi import FastAPI+from fastapi.testclient import TestClient+from sie_server.adapters.base import ModelCapabilities, ModelDims+from sie_server.adapters.errors import InputTooLongError+from sie_server.api.encode import router as encode_router+from sie_server.api.score import router as score_router+from sie_server.config.model import (+ EmbeddingDim,+ EncodeTask,+ ModelConfig,+ ProfileConfig,+ ScoreTask,+ Tasks,+)+from sie_server.core.registry import ModelRegistry+from sie_server.core.worker import QueueFullError++m.patch() # numpy <-> msgpack++JSON_HEADERS = {"Accept": "application/json"}+++def _base_registry(config: ModelConfig, adapter: MagicMock) -> MagicMock:+ registry = MagicMock(spec=ModelRegistry)+ registry.has_model.return_value = True+ registry.is_loaded.return_value = True+ registry.is_loading.return_value = False+ registry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = None+ registry.get.return_value = adapter+ registry.get_config.return_value = config+ registry.model_names = [config.sie_id]+ registry.device = "cpu"+ # ``oom_retry_after_from_registry`` falls back to the module default+ # when engine_config is None (see test_extract_oom.py).+ registry.engine_config = None+ return registry+++def _build_encode_client(failure: BaseException) -> TestClient:+ """Encode client whose direct adapter call raises ``failure``.++ Uses the no-tokenizer direct path (as in ``test_encode_endpoint.py``)+ so the exception surfaces through the endpoint's except arms without+ a worker in the loop.+ """+ adapter = MagicMock()+ adapter.encode = MagicMock(side_effect=failure)+ config = ModelConfig(+ sie_id="test-model",+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=3))),+ profiles={"default": ProfileConfig(adapter_path="test:TestAdapter", max_batch_tokens=8192)},+ )+ registry = _base_registry(config, adapter)+ preprocessor_registry = MagicMock()+ preprocessor_registry.has_tokenizer.return_value = False+ preprocessor_registry.has_preprocessor.return_value = False+ registry.preprocessor_registry = preprocessor_registry++ app = FastAPI()+ app.include_router(encode_router)+ app.state.registry = registry+ return TestClient(app)+++def _build_score_client(failure: BaseException) -> TestClient:+ """Score client whose worker future fails with ``failure``."""+ adapter = MagicMock()+ adapter.capabilities = ModelCapabilities(inputs=["text"], outputs=[])+ adapter.dims = ModelDims()++ worker = MagicMock()++ async def _failing_submit(*_args: Any, **_kwargs: Any) -> asyncio.Future[Any]:+ loop = asyncio.get_running_loop()+ future: asyncio.Future[Any] = loop.create_future()+ future.set_exception(failure)+ return future++ worker.submit_score = _failing_submit++ config = ModelConfig(+ sie_id="test-reranker",+ hf_id="org/test-reranker",+ tasks=Tasks(encode=EncodeTask(), score=ScoreTask()),+ profiles={"default": ProfileConfig(adapter_path="test:TestCrossEncoderAdapter", max_batch_tokens=8192)},+ )+ registry = _base_registry(config, adapter)+ registry.start_worker = AsyncMock(return_value=worker)++ app = FastAPI()+ app.include_router(score_router)+ app.state.registry = registry+ return TestClient(app)+++def _post_encode(client: TestClient) -> Any:+ return client.post(+ "/v1/encode/test-model",+ json={"items": [{"text": "hello"}]},+ headers=JSON_HEADERS,+ )+++def _post_score(client: TestClient) -> Any:+ return client.post(+ "/v1/score/test-reranker",+ json={"query": {"text": "q"}, "items": [{"text": "doc"}]},+ headers=JSON_HEADERS,+ )+++def _detail(response: Any) -> dict[str, Any]:+ body = response.json()+ return body.get("detail", body) # FastAPI wraps HTTPException in 'detail'+++class TestQueueFullMapping:+ """handle_queue_full: 400 for can-never-fit, 503 QUEUE_FULL for pressure."""++ def test_over_capacity_request_maps_to_400_invalid_input(self) -> None:+ """A request bigger than the whole queue is a permanent client error."""+ failure = QueueFullError(+ "Queue full: 0 items pending, cannot add 1000 more (limit: 512)",+ pending=0,+ requested=1000,+ limit=512,+ )+ response = _post_encode(_build_encode_client(failure))++ assert response.status_code == 400, response.text+ # Never invite a retry for a request that can never fit.+ assert "Retry-After" not in response.headers+ detail = _detail(response)+ assert detail["code"] == "INVALID_INPUT"+ # The message names the per-request limit and the offending count.+ assert "512" in detail["message"]+ assert "1000" in detail["message"]++ def test_transient_pressure_maps_to_503_queue_full_with_retry_after(self) -> None:+ """Queue occupied by other work: retryable, and says so."""+ failure = QueueFullError(+ "Queue full: 500 items pending, cannot add 100 more (limit: 512)",+ pending=500,+ requested=100,+ limit=512,+ )+ response = _post_encode(_build_encode_client(failure))++ assert response.status_code == 503, response.text+ assert response.headers.get("Retry-After") == "1"+ detail = _detail(response)+ # Regression guard: was MODEL_NOT_LOADED, which is false (the model+ # IS loaded) and not in any SDK retryable set.+ assert detail["code"] == "QUEUE_FULL"+ assert "Queue full" in detail["message"]++ def test_legacy_queue_full_without_counts_is_treated_as_transient(self) -> None:+ """A message-only QueueFullError conservatively maps to 503 QUEUE_FULL."""+ response = _post_encode(_build_encode_client(QueueFullError("Queue full")))++ assert response.status_code == 503, response.text+ assert response.headers.get("Retry-After") == "1"+ assert _detail(response)["code"] == "QUEUE_FULL"++ def test_score_transient_pressure_maps_to_503_queue_full(self) -> None:+ """The score endpoint shares the same queue-full contract."""+ failure = QueueFullError(+ "Queue full: 512 items pending, cannot add 1 more (limit: 512)",+ pending=512,+ requested=1,+ limit=512,+ )+ response = _post_score(_build_score_client(failure))++ assert response.status_code == 503, response.text+ assert response.headers.get("Retry-After") == "1"+ assert _detail(response)["code"] == "QUEUE_FULL"++ def test_score_over_capacity_request_maps_to_400(self) -> None:+ failure = QueueFullError(+ "Queue full: 0 items pending, cannot add 600 more (limit: 512)",+ pending=0,+ requested=600,+ limit=512,+ )+ response = _post_score(_build_score_client(failure))++ assert response.status_code == 400, response.text+ detail = _detail(response)+ assert detail["code"] == "INVALID_INPUT"+ assert "512" in detail["message"]+++class TestInputTooLongMapping:+ """encode/score must map InputTooLongError to INPUT_TOO_LONG, not INVALID_INPUT."""++ def test_encode_input_too_long_maps_to_input_too_long_code(self) -> None:+ response = _post_encode(_build_encode_client(InputTooLongError("input of 9000 tokens exceeds budget")))++ assert response.status_code == 400, response.text+ detail = _detail(response)+ # Regression guard: InputTooLongError subclasses ValueError, and+ # without the dedicated arm it degraded to INVALID_INPUT.+ assert detail["code"] == "INPUT_TOO_LONG"+ assert "9000" in detail["message"]++ def test_score_input_too_long_maps_to_input_too_long_code(self) -> None:+ response = _post_score(_build_score_client(InputTooLongError("pair of 9000 tokens exceeds budget")))++ assert response.status_code == 400, response.text+ assert _detail(response)["code"] == "INPUT_TOO_LONG"++ def test_encode_plain_value_error_still_maps_to_invalid_input(self) -> None:+ """The generic ValueError arm keeps its INVALID_INPUT mapping."""+ response = _post_encode(_build_encode_client(ValueError("bad input")))++ assert response.status_code == 400, response.text+ assert _detail(response)["code"] == "INVALID_INPUT"++ def test_score_plain_value_error_still_maps_to_invalid_input(self) -> None:+ response = _post_score(_build_score_client(ValueError("bad input")))++ assert response.status_code == 400, response.text+ assert _detail(response)["code"] == "INVALID_INPUT"diff --git a/packages/sie_server/tests/api/test_extract.py b/packages/sie_server/tests/api/test_extract.pyindex c4264389c..a5fd3580f 100644--- a/packages/sie_server/tests/api/test_extract.py+++ b/packages/sie_server/tests/api/test_extract.py@@ -19,7 +19,11 @@ from sie_server.config.model import (ProfileConfig,Tasks,)-from sie_server.core.extract_cost import build_extract_prepared_items, extract_item_cost+from sie_server.core.extract_cost import (+ MAX_EXTRACT_LABELS,+ build_extract_prepared_items,+ extract_item_cost,+)from sie_server.core.inference_output import ExtractItemError, ExtractOutputfrom sie_server.core.registry import ModelRegistryfrom sie_server.core.timing import RequestTiming@@ -381,6 +385,39 @@ class TestExtractEndpoint:)assert response.status_code == 400 # Custom validation error (not Pydantic)+ def test_extract_over_cap_labels_rejected(self, client: TestClient) -> None:+ """A labels list past the cap is a typed 400 naming the limit.++ GLiNER-family adapters run one forward pass per label, so an unbounded+ labels list is an uncapped compute vector — mirror the score/rerank+ candidate cap with a named 400 rather than letting it through.+ """+ response = client.post(+ "/v1/extract/test-extractor",+ json={+ "items": [{"text": "Apple Inc."}],+ "params": {"labels": [f"label-{i}" for i in range(MAX_EXTRACT_LABELS + 1)]},+ },+ headers=JSON_HEADERS,+ )+ assert response.status_code == 400+ data = response.json()+ assert data["detail"]["code"] == "INVALID_INPUT"+ assert str(MAX_EXTRACT_LABELS) in data["detail"]["message"]+ assert "labels" in data["detail"]["message"]++ def test_extract_at_cap_labels_accepted(self, client: TestClient) -> None:+ """A labels list exactly at the cap is accepted."""+ response = client.post(+ "/v1/extract/test-extractor",+ json={+ "items": [{"text": "Apple Inc."}],+ "params": {"labels": [f"label-{i}" for i in range(MAX_EXTRACT_LABELS)]},+ },+ headers=JSON_HEADERS,+ )+ assert response.status_code == 200+def test_extract_non_dict_items_rejected(self, client: TestClient) -> None:"""Non-dict items return 400, not 500."""response = client.post(diff --git a/packages/sie_server/tests/api/test_extract_integration.py b/packages/sie_server/tests/api/test_extract_integration.pyindex 97af70df9..bb5e18904 100644--- a/packages/sie_server/tests/api/test_extract_integration.py+++ b/packages/sie_server/tests/api/test_extract_integration.py@@ -5,7 +5,7 @@ These tests verify end-to-end behavior including:- Large extract requests are sub-batched correctly- Backpressure returns 503 when queue is full-Mark: integration (run with `mise run test -m integration`)+Mark: integration (run with `mise run test -- -i packages/sie_server/tests/api/test_extract_integration.py`)"""from __future__ import annotationsdiff --git a/packages/sie_server/tests/api/test_generate.py b/packages/sie_server/tests/api/test_generate.pyindex 542c25278..67f9934b6 100644--- a/packages/sie_server/tests/api/test_generate.py+++ b/packages/sie_server/tests/api/test_generate.py@@ -63,6 +63,10 @@ class _FakeGenAdapter(GenerationAdapter):# exercise the route's error/cancelled → non-200 mapping (BUG: a# terminal error/cancelled chunk must NOT become an HTTP 200).finish_reason: str = "stop"+ # Typed terminal error fields; tests set these to exercise the+ # route's verbatim-code fail-closed mapping (#3104/#3136).+ error_code: str | None = None+ error_message: str | None = Noneasync def generate(self,@@ -112,6 +116,8 @@ class _FakeGenAdapter(GenerationAdapter):finish_reason=self.finish_reason, # type: ignore[arg-type]prompt_tokens=len(prompt.split()),completion_tokens=2,+ error_code=self.error_code,+ error_message=self.error_message,)@@ -1234,6 +1240,46 @@ class TestGenerateEndpoint:assert response.status_code == 500, response.textassert response.json()["detail"]["code"] == "inference_error"+ def test_terminal_empty_model_output_returns_500_with_verbatim_code(+ self, client: TestClient, fake_adapter: _FakeGenAdapter+ ) -> None:+ """#3104/#3136: an ``empty_model_output`` terminal keeps a+ ``stop``/``length`` finish_reason, so the buffered route must key on+ the typed ``error_code`` — not answer HTTP 200 with empty text — and+ surface the code/message verbatim, exactly like the streaming shape.+ """+ fake_adapter.finish_reason = "length"+ fake_adapter.error_code = "empty_model_output"+ fake_adapter.error_message = "model produced no visible output text"+ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )+ assert response.status_code == 500, response.text+ detail = response.json()["detail"]+ assert detail["code"] == "empty_model_output"+ assert detail["message"] == "model produced no visible output text"+ assert "retry-after" not in {k.lower() for k in response.headers}++ def test_terminal_error_with_typed_code_is_not_flattened_to_inference_error(+ self, client: TestClient, fake_adapter: _FakeGenAdapter+ ) -> None:+ """A parser-style ``finish_reason="error"`` terminal that carries its+ own typed code must surface that code verbatim, not the hardcoded+ ``inference_error`` fallback (#3136).+ """+ fake_adapter.finish_reason = "error"+ fake_adapter.error_code = "tool_call_parse_error"+ fake_adapter.error_message = "model emitted a malformed tool call"+ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )+ assert response.status_code == 500, response.text+ detail = response.json()["detail"]+ assert detail["code"] == "tool_call_parse_error"+ assert detail["message"] == "model emitted a malformed tool call"+def test_terminal_cancelled_finish_reason_returns_503(self, client: TestClient, fake_adapter: _FakeGenAdapter) -> None:diff --git a/packages/sie_server/tests/api/test_openai_compat.py b/packages/sie_server/tests/api/test_openai_compat.pyindex 5e878491c..83d029026 100644--- a/packages/sie_server/tests/api/test_openai_compat.py+++ b/packages/sie_server/tests/api/test_openai_compat.py@@ -1,5 +1,6 @@"""Tests for OpenAI-compatible embeddings endpoint."""+import timefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patch@@ -9,6 +10,7 @@ from fastapi import FastAPIfrom fastapi.testclient import TestClientfrom sie_server.api.openai_compat import router as openai_routerfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.load_errors import LoadErrorClass, LoadFailurefrom sie_server.core.oom import ResourceExhausted, ResourceExhaustedErrorfrom sie_server.core.registry import ModelRegistry@@ -181,8 +183,32 @@ class TestOpenAIEmbeddings:assert response.status_code == 404data = response.json()- assert "error" in data["detail"]- assert data["detail"]["error"]["code"] == "model_not_found"+ # Top-level OpenAI envelope — no FastAPI {"detail": ...} wrapper.+ assert "detail" not in data+ error = data["error"]+ assert error["code"] == "model_not_found"+ assert error["type"] == "invalid_request_error"+ assert "message" in error++ def test_model_not_found_suggests_a_near_match(self, client: TestClient, mock_registry: MagicMock) -> None:+ """A near miss must name the id the caller probably meant."""+ mock_registry.has_model.return_value = False+ mock_registry.model_names = ["text-embedding-3-small", "BAAI/bge-m3"]++ response = client.post("/v1/embeddings", json={"model": "bge-m3", "input": "Hello"})++ assert response.status_code == 404+ assert "Did you mean 'BAAI/bge-m3'?" in response.json()["error"]["message"]++ def test_model_not_found_stays_terse_with_no_near_match(self, client: TestClient, mock_registry: MagicMock) -> None:+ """No confident suggestion must add nothing to the message."""+ mock_registry.has_model.return_value = False+ mock_registry.model_names = ["text-embedding-3-small"]++ response = client.post("/v1/embeddings", json={"model": "xyzzy-nothing-alike", "input": "Hello"})++ assert response.status_code == 404+ assert "Did you mean" not in response.json()["error"]["message"]def test_empty_input_rejected(self, client: TestClient) -> None:"""Test 400 when input is empty."""@@ -195,22 +221,83 @@ class TestOpenAIEmbeddings:)assert response.status_code == 400+ data = response.json()+ assert "detail" not in data+ error = data["error"]+ assert error["code"] == "invalid_request"+ assert error["type"] == "invalid_request_error"+ assert error["param"] == "input"+ assert error["message"] == "Input cannot be empty"++ def test_unhonourable_dimensions_rejected(self, client: TestClient) -> None:+ """A width SIE cannot produce must fail, not be silently ignored.++ This endpoint used to accept ``dimensions`` and drop it, so a client+ migrating from ``text-embedding-3-*`` asked for 256 and received the+ model's native width with a 200 — vectors of the wrong width, written+ into a vector store with nothing to signal the mismatch.+ """+ response = client.post(+ "/v1/embeddings",+ json={+ "model": "text-embedding-3-small",+ "input": "Hello",+ "dimensions": 256,+ },+ )- def test_dimensions_ignored(self, client: TestClient) -> None:- """Test that dimensions parameter is ignored (not supported)."""+ assert response.status_code == 400+ error = response.json()["error"]+ assert error["code"] == "unsupported_field"+ assert error["param"] == "dimensions"+ assert error["type"] == "invalid_request_error"+ # The message must name the real width so the caller can act on it.+ # Asserted as the full phrase: a bare "3" also matches the model name+ # text-embedding-3-small, so it would pass on a wrong width too.+ assert "3-dimensional embeddings" in error["message"]+ assert "set it to 3" in error["message"]++ def test_matching_dimensions_accepted(self, client: TestClient) -> None:+ """Pinning the model's real width is a no-op, not an error."""response = client.post("/v1/embeddings",json={"model": "text-embedding-3-small","input": "Hello",- "dimensions": 256, # Should be ignored+ "dimensions": 3,},)assert response.status_code == 200- # Still returns original dimensions (3)assert len(response.json()["data"][0]["embedding"]) == 3+ def test_omitted_dimensions_still_works(self, client: TestClient) -> None:+ """The overwhelmingly common case stays untouched."""+ response = client.post(+ "/v1/embeddings",+ json={"model": "text-embedding-3-small", "input": "Hello"},+ )++ assert response.status_code == 200+ assert len(response.json()["data"][0]["embedding"]) == 3++ def test_dimensions_rejected_before_any_model_load(self, client: TestClient, mock_registry: MagicMock) -> None:+ """A bad 'dimensions' must not cost the caller a cold load first."""+ mock_registry.is_loaded.return_value = False+ mock_registry.start_load_async = AsyncMock()++ response = client.post(+ "/v1/embeddings",+ json={+ "model": "text-embedding-3-small",+ "input": "Hello",+ "dimensions": 1536,+ },+ )++ assert response.status_code == 400+ mock_registry.start_load_async.assert_not_awaited()+def test_user_field_ignored(self, client: TestClient) -> None:"""Test that user field is accepted but ignored."""response = client.post(@@ -237,6 +324,116 @@ class TestOpenAIEmbeddings:)assert response.status_code == 503+ data = response.json()+ assert "detail" not in data+ error = data["error"]+ assert error["code"] == "model_not_available"+ assert error["type"] == "server_error"+ assert "message" in error++ def test_inference_error_returns_top_level_openai_500(self, client: TestClient, mock_registry: MagicMock) -> None:+ """A generic inference failure emits a top-level OpenAI 500 envelope."""+ with patch(+ "sie_server.api.openai_compat.EncodePipeline.run_encode",+ new_callable=AsyncMock,+ side_effect=RuntimeError("boom"),+ ):+ response = client.post(+ "/v1/embeddings",+ json={"model": "text-embedding-3-small", "input": "hello"},+ )++ assert response.status_code == 500+ data = response.json()+ assert "detail" not in data+ error = data["error"]+ assert error["code"] == "inference_error"+ assert error["type"] == "server_error"+ assert "message" in error+++class TestOpenAIEmbeddingsModelLoadStates:+ """/v1/embeddings must mirror the native routes' non-blocking load contract.++ Previously a cold model BLOCKED the request on ``load_async`` (observed+ 77s on large checkpoints) and a failed-load model re-ran the doomed+ blocking load on every request, returning a generic 503. The endpoint now+ uses ``ModelStateChecker``: instant 503 MODEL_LOADING + Retry-After for a+ cold model, terminal 502 MODEL_LOAD_FAILED (no Retry-After, no re-load)+ for a recorded failure — in the OpenAI-shaped error envelope, matching+ the gateway's /v1/embeddings so the same URL behaves identically+ single-node and clustered.+ """++ def test_cold_model_returns_503_model_loading(self, client: TestClient, mock_registry: MagicMock) -> None:+ """A cold model starts a background load and returns 503 immediately."""+ mock_registry.is_loaded.return_value = False+ mock_registry.is_loading.return_value = False+ mock_registry.device = "cpu"++ async def start_load_async_success(*args: Any, **kwargs: Any) -> bool:+ return True++ mock_registry.start_load_async = MagicMock(side_effect=start_load_async_success)+ mock_registry.load_async = MagicMock()++ response = client.post(+ "/v1/embeddings",+ json={"model": "text-embedding-3-small", "input": "Hello"},+ )++ # Non-blocking loading returns 503 + MODEL_LOADING immediately+ assert response.status_code == 503, response.text+ assert response.headers.get("Retry-After") == "5"+ error = response.json()["error"]+ assert error["code"] == "MODEL_LOADING"+ assert error["type"] == "server_error"+ assert "loading" in error["message"].lower()+ mock_registry.start_load_async.assert_called_once_with("text-embedding-3-small", device="cpu")+ # The old blocking path must be gone.+ mock_registry.load_async.assert_not_called()++ def test_failed_model_returns_terminal_502_without_reload(+ self, client: TestClient, mock_registry: MagicMock+ ) -> None:+ """A registry-recorded terminal failure returns 502 MODEL_LOAD_FAILED.++ Mirrors the native-route terminal-failure contract: no Retry-After header+ (the SDK uses its absence to short-circuit the MODEL_LOADING retry+ budget) and crucially NO repeated load attempt for a known-bad model.+ """+ failure = LoadFailure(+ error_class=LoadErrorClass.GATED,+ message="GatedModelError: HF_TOKEN missing or invalid for org/test",+ attempts=1,+ last_attempt_ts=time.monotonic(),+ cooldown_s=None,+ )+ mock_registry.is_loaded.return_value = False+ mock_registry.is_failed.return_value = True+ mock_registry.get_failure.return_value = failure++ # Should NOT trigger any load attempt, background or blocking.+ mock_registry.start_load_async = MagicMock()+ mock_registry.load_async = MagicMock()++ response = client.post(+ "/v1/embeddings",+ json={"model": "text-embedding-3-small", "input": "Hello"},+ )++ assert response.status_code == 502, response.text+ error = response.json()["error"]+ assert error["code"] == "MODEL_LOAD_FAILED"+ assert error["type"] == "server_error"+ assert error["error_class"] == "GATED"+ assert error["permanent"] is True+ assert error["attempts"] == 1+ # Critical: no Retry-After header so clients do not loop.+ assert "retry-after" not in {k.lower() for k in response.headers}+ # And no load of any kind was kicked off for the known-bad model.+ mock_registry.start_load_async.assert_not_called()+ mock_registry.load_async.assert_not_called()class TestOpenAIResponseFormat:@@ -317,6 +514,8 @@ class TestOpenAIEmbeddingsOom:assert response.status_code == 503, response.textassert response.headers.get("Retry-After") == "5"- error = response.json()["detail"]["error"]+ data = response.json()+ assert "detail" not in data+ error = data["error"]assert error["code"] == "RESOURCE_EXHAUSTED"assert error["type"] == "server_error"diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.pyindex d500bdc78..6893f57e0 100644--- a/packages/sie_server/tests/api/test_openai_local.py+++ b/packages/sie_server/tests/api/test_openai_local.py@@ -11,9 +11,10 @@ import jsonfrom collections.abc import AsyncIterator, Callablefrom types import SimpleNamespacefrom typing import Any-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport httpx+import numpy as npimport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -22,6 +23,9 @@ from sie_server.adapters.mlx.generation import MLXGenerationAdapterfrom sie_server.adapters.sglang.generation import SGLangGenerationAdapterfrom sie_server.api import openai_localfrom sie_server.api.openai_local import _validate_mlx_seed, router+from sie_server.core.inference_output import ScoreOutput+from sie_server.core.timing import RequestTiming+from sie_server.core.worker import WorkerResult_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"_GEMMA_CLOSE = "<" + "channel|" + ">"@@ -156,13 +160,13 @@ def test_chat_requires_object_body() -> None:def test_chat_requires_model() -> None:r = _client().post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "hi"}]})assert r.status_code == 400- assert r.json()["detail"]["param"] == "model"+ assert r.json()["error"]["param"] == "model"def test_chat_requires_nonempty_messages() -> None:r = _client().post("/v1/chat/completions", json={"model": "m", "messages": []})assert r.status_code == 400- assert r.json()["detail"]["param"] == "messages"+ assert r.json()["error"]["param"] == "messages"@pytest.mark.parametrize(@@ -185,7 +189,7 @@ def test_chat_rejects_malformed_message_structure_before_model_load(response = client.post("/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "messages": messages})assert response.status_code == 400- assert response.json()["detail"]["param"] == param+ assert response.json()["error"]["param"] == paramregistry.get_config.assert_not_called()registry.get.assert_not_called()@@ -199,14 +203,14 @@ def test_chat_rejects_non_generation_model_before_load() -> None:"/v1/chat/completions", json={"model": "embed-model", "messages": [{"role": "user", "content": "hi"}]})assert r.status_code == 400- assert "generation" in r.json()["detail"]["message"].lower()+ assert "generation" in r.json()["error"]["message"].lower()def test_chat_rejects_non_bool_stream() -> None:msgs = [{"role": "user", "content": "hi"}]r = _client().post("/v1/chat/completions", json={"model": "m", "messages": msgs, "stream": "false"})assert r.status_code == 400- assert r.json()["detail"]["param"] == "stream"+ assert r.json()["error"]["param"] == "stream"def test_chat_rejects_invalid_max_tokens() -> None:@@ -214,7 +218,7 @@ def test_chat_rejects_invalid_max_tokens() -> None:for bad in (0, -5, "100", True):r = _client().post("/v1/chat/completions", json={"model": "m", "messages": msgs, "max_tokens": bad})assert r.status_code == 400, bad- assert r.json()["detail"]["param"] == "max_tokens"+ assert r.json()["error"]["param"] == "max_tokens"@pytest.mark.parametrize(@@ -231,10 +235,11 @@ def test_chat_rejects_invalid_seed(bad: object, message: str) -> None:msgs = [{"role": "user", "content": "hi"}]r = _client().post("/v1/chat/completions", json={"model": "m", "messages": msgs, "seed": bad})assert r.status_code == 400, bad- assert r.json()["detail"] == {+ assert r.json()["error"] == {"code": "INVALID_INPUT","message": message,"param": "seed",+ "type": "invalid_request_error",}@@ -369,10 +374,11 @@ def test_mlx_chat_rejects_child_process_controls_before_model_load()assert response.status_code == 400- assert response.json()["detail"] == {+ assert response.json()["error"] == {"code": "unsupported_field","message": "field 'draft_model' is not supported","param": "draft_model",+ "type": "invalid_request_error",}registry.is_loaded.assert_not_called()registry.get.assert_not_called()@@ -407,8 +413,8 @@ def test_chat_rejects_unbounded_template_kwargs_before_model_load()assert response.status_code == 400- assert response.json()["detail"]["code"] == code- assert response.json()["detail"]["param"] == "chat_template_kwargs"+ assert response.json()["error"]["code"] == code+ assert response.json()["error"]["param"] == "chat_template_kwargs"registry.is_loaded.assert_not_called()registry.get.assert_not_called()@@ -805,10 +811,11 @@ def test_cuda_chat_rejects_engine_control_and_output_above_model_cap(json={"model": "Qwen/Qwen3.5-4B", "messages": messages, "routed_dp_rank": 2},)assert response.status_code == 400- assert response.json()["detail"] == {+ assert response.json()["error"] == {"code": "unsupported_field","message": "field 'routed_dp_rank' is not supported","param": "routed_dp_rank",+ "type": "invalid_request_error",}response = client.post(@@ -816,7 +823,7 @@ def test_cuda_chat_rejects_engine_control_and_output_above_model_cap(json={"model": "Qwen/Qwen3.5-4B", "messages": messages, "max_completion_tokens": 33},)assert response.status_code == 400- assert response.json()["detail"]["param"] == "max_completion_tokens"+ assert response.json()["error"]["param"] == "max_completion_tokens"def test_mlx_chat_rejects_output_above_model_cap(monkeypatch: pytest.MonkeyPatch) -> None:@@ -837,7 +844,7 @@ def test_mlx_chat_rejects_output_above_model_cap(monkeypatch: pytest.MonkeyPatch)assert response.status_code == 400- assert response.json()["detail"]["param"] == "max_completion_tokens"+ assert response.json()["error"]["param"] == "max_completion_tokens"def test_cuda_chat_rejects_remote_media_before_model_load(monkeypatch: pytest.MonkeyPatch) -> None:@@ -865,7 +872,7 @@ def test_cuda_chat_rejects_remote_media_before_model_load(monkeypatch: pytest.Mo)assert response.status_code == 400- assert response.json()["detail"]["param"] == "messages[0].content[1].image_url"+ assert response.json()["error"]["param"] == "messages[0].content[1].image_url"registry.get.assert_not_called()@@ -924,13 +931,13 @@ def test_cuda_chat_preserves_visible_logprobs_when_reasoning_is_null(def test_rerank_requires_model() -> None:r = _client().post("/v1/rerank", json={"query": "q", "documents": ["a"]})assert r.status_code == 400- assert r.json()["detail"]["param"] == "model"+ assert r.json()["error"]["param"] == "model"def test_rerank_requires_query() -> None:r = _client().post("/v1/rerank", json={"model": "m", "documents": ["a"]})assert r.status_code == 400- assert r.json()["detail"]["param"] == "query"+ assert r.json()["error"]["param"] == "query"def test_rerank_rejects_blank_model_and_query() -> None:@@ -940,37 +947,185 @@ def test_rerank_rejects_blank_model_and_query() -> None:]:r = _client().post("/v1/rerank", json=body)assert r.status_code == 400- assert r.json()["detail"]["param"] == param+ assert r.json()["error"]["param"] == paramdef test_rerank_requires_nonempty_string_documents() -> None:for docs in ([], "not-a-list", [1, 2], ["ok", 3], [" "]):r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": docs})assert r.status_code == 400, docs- assert r.json()["detail"]["param"] == "documents"+ assert r.json()["error"]["param"] == "documents"def test_rerank_top_n_must_be_positive_int() -> None:for bad in (0, -1, "3", True):r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"], "top_n": bad})assert r.status_code == 400, bad- assert r.json()["detail"]["param"] == "top_n"+ assert r.json()["error"]["param"] == "top_n"def test_rerank_rejects_too_many_documents() -> None:docs = ["d"] * (openai_local._MAX_RERANK_DOCS + 1)r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": docs})assert r.status_code == 400- assert r.json()["detail"]["param"] == "documents"+ assert r.json()["error"]["param"] == "documents"def test_rerank_rejects_non_bool_return_documents() -> None:r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"], "return_documents": "true"})assert r.status_code == 400- assert r.json()["detail"]["param"] == "return_documents"+ assert r.json()["error"]["param"] == "return_documents"def test_rerank_rejects_unknown_fields() -> None:r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"], "priority": 1})assert r.status_code == 400- assert r.json()["detail"]["param"] == "priority"+ assert r.json()["error"]["param"] == "priority"+++# -- top-level OpenAI error envelope (no {"detail": ...} wrapper) -------------+++def test_chat_unknown_model_returns_top_level_openai_error() -> None:+ client = _client()+ client.app.state.registry.has_model.return_value = False+ r = client.post(+ "/v1/chat/completions",+ json={"model": "missing-model", "messages": [{"role": "user", "content": "hi"}]},+ )+ assert r.status_code == 404+ body = r.json()+ assert "detail" not in body+ error = body["error"]+ assert error["code"] == "MODEL_NOT_FOUND"+ assert error["type"] == "invalid_request_error"+ assert "message" in error+++def test_chat_invalid_input_returns_top_level_openai_error() -> None:+ r = _client().post("/v1/chat/completions", json={"model": "m", "messages": []})+ assert r.status_code == 400+ body = r.json()+ assert "detail" not in body+ error = body["error"]+ assert error["param"] == "messages"+ assert error["type"] == "invalid_request_error"+ assert error["code"] == "INVALID_INPUT"+ assert "message" in error+++def test_chat_unloading_model_returns_top_level_openai_server_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ client, registry = _cuda_chat_client(+ monkeypatch,+ lambda _request: pytest.fail("unloading model must not reach upstream"),+ )+ registry.is_unloading.return_value = True+ r = client.post(+ "/v1/chat/completions",+ json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "hi"}]},+ )+ assert r.status_code == 503+ body = r.json()+ assert "detail" not in body+ error = body["error"]+ assert error["code"] == "MODEL_NOT_LOADED"+ assert error["type"] == "server_error"+ assert "message" in error+++def _rerank_client() -> tuple[TestClient, MagicMock]:+ """Rerank client whose registry passes all model-state checks."""+ profile = SimpleNamespace(runtime={}, loadtime={})+ config = SimpleNamespace(+ tasks=SimpleNamespace(generate=None, score=SimpleNamespace()),+ resolve_profile=MagicMock(return_value=profile),+ )+ registry = MagicMock()+ registry.device = "cpu"+ registry.has_model.return_value = True+ registry.get_config.return_value = config+ registry.is_failed.return_value = False+ registry.is_unloading.return_value = False+ registry.is_loading.return_value = False+ registry.is_loaded.return_value = True+ client = _client()+ client.app.state.registry = registry+ return client, registry+++def test_rerank_unknown_model_returns_top_level_openai_error() -> None:+ client = _client()+ client.app.state.registry.has_model.return_value = False+ r = client.post("/v1/rerank", json={"model": "missing-model", "query": "q", "documents": ["a"]})+ assert r.status_code == 404+ body = r.json()+ assert "detail" not in body+ error = body["error"]+ assert error["code"] == "MODEL_NOT_FOUND"+ assert error["type"] == "invalid_request_error"+ assert "message" in error+++def test_rerank_invalid_input_returns_top_level_openai_error() -> None:+ r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": []})+ assert r.status_code == 400+ body = r.json()+ assert "detail" not in body+ error = body["error"]+ assert error["param"] == "documents"+ assert error["type"] == "invalid_request_error"+ assert error["code"] == "INVALID_INPUT"+ assert "message" in error+++def test_rerank_inference_error_returns_top_level_openai_500() -> None:+ client, registry = _rerank_client()++ async def _boom() -> None:+ raise RuntimeError("boom")++ worker = MagicMock()+ worker.submit_score = AsyncMock(return_value=_boom())+ registry.start_worker = AsyncMock(return_value=worker)++ r = client.post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"]})+ assert r.status_code == 500+ body = r.json()+ assert "detail" not in body+ error = body["error"]+ assert error["code"] == "inference_error"+ assert error["type"] == "server_error"+ assert error["message"] == "boom"++[email protected]("bad", [float("nan"), float("inf"), float("-inf")])+def test_rerank_non_finite_scores_return_top_level_openai_500(bad: float) -> None:+ """NaN/inf model scores fail closed as an enveloped 500 naming the model.++ Regression for pass-2 audit A2: on this JSON-only surface a NaN score+ crashed json.dumps ("Out of range float values are not JSON compliant")+ into a bare, un-enveloped 500 with no OpenAI error object.+ """+ client, registry = _rerank_client()++ async def _result() -> WorkerResult:+ return WorkerResult(+ output=ScoreOutput(scores=np.array([0.9, bad], dtype=np.float32)),+ timing=RequestTiming(),+ )++ worker = MagicMock()+ worker.submit_score = AsyncMock(return_value=_result())+ registry.start_worker = AsyncMock(return_value=worker)++ r = client.post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a", "b"]})+ assert r.status_code == 500+ body = r.json()+ assert "detail" not in body # enveloped OpenAI error, not FastAPI's {"detail": ...}+ error = body["error"]+ assert error["code"] == "INFERENCE_ERROR"+ assert error["type"] == "server_error"+ assert "m" in error["message"]+ assert "non-finite" in error["message"]diff --git a/packages/sie_server/tests/api/test_score.py b/packages/sie_server/tests/api/test_score.pyindex c0bfd463d..41913dad9 100644--- a/packages/sie_server/tests/api/test_score.py+++ b/packages/sie_server/tests/api/test_score.py@@ -749,3 +749,58 @@ class TestScoreProfileResolution:headers=JSON_HEADERS,)assert response.status_code == 200+++class TestScoreNonFiniteGuard:+ """Non-finite (NaN/inf) model output must fail closed on both wire formats.++ Regression for pass-2 audit A2: a cross-encoder emitting NaN/inf scores+ (observed on cross-encoder/ms-marco-MiniLM-L-6-v2 on CPU) crashed+ json.dumps into a bare un-enveloped 500 on the JSON path, and returned+ HTTP 200 with the NaN ranked as a valid score on the msgpack path (silent+ corruption for any msgpack client). Both now fail closed with a typed,+ enveloped 500 INFERENCE_ERROR naming the model.+ """++ @pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")])+ @pytest.mark.parametrize("accept", ["application/json", "application/msgpack"])+ def test_non_finite_scores_fail_closed(+ self, client: TestClient, mock_adapter: MagicMock, bad: float, accept: str+ ) -> None:+ # One valid score, one non-finite: the bad value must abort the response.+ mock_adapter.score.side_effect = None+ mock_adapter.score.return_value = [0.9, bad]++ response = client.post(+ "/v1/score/test-reranker",+ json={+ "query": {"text": "Query"},+ "items": [{"text": "Doc A"}, {"text": "Doc B"}],+ },+ headers={"Accept": accept},+ )++ # Never HTTP 200 with a NaN ranked as valid; never a bare 500 without+ # an error envelope. Errors are always emitted as JSON detail envelopes+ # regardless of the requested Accept.+ assert response.status_code == 500+ detail = response.json()["detail"]+ assert detail["code"] == "INFERENCE_ERROR"+ assert "test-reranker" in detail["message"]+ assert "non-finite" in detail["message"]++ def test_all_finite_scores_still_succeed(self, client: TestClient, mock_adapter: MagicMock) -> None:+ """The guard does not reject ordinary finite scores (incl. negatives/zero)."""+ mock_adapter.score.side_effect = None+ mock_adapter.score.return_value = [-3.5, 0.0, 2.1]++ response = client.post(+ "/v1/score/test-reranker",+ json={+ "query": {"text": "Query"},+ "items": [{"text": "A"}, {"text": "B"}, {"text": "C"}],+ },+ headers=JSON_HEADERS,+ )+ assert response.status_code == 200+ assert len(response.json()["scores"]) == 3diff --git a/packages/sie_server/tests/api/test_usage_reporting.py b/packages/sie_server/tests/api/test_usage_reporting.pynew file mode 100644index 000000000..a2260de95--- /dev/null+++ b/packages/sie_server/tests/api/test_usage_reporting.py@@ -0,0 +1,224 @@+"""What `usage` reports on /v1/encode and /v1/extract.++The reported number must be the worker's own post-tokenization count — the same+basis telemetry meters from — never a character estimate, and a measured zero+must be reported as `0` rather than read as "unknown".+"""++import asyncio+from concurrent.futures import ThreadPoolExecutor+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import numpy as np+import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from sie_server.api.encode import router as encode_router+from sie_server.api.extract import router as extract_router+from sie_server.api.helpers import validated_total+from sie_server.config.model import (+ EmbeddingDim,+ EncodeTask,+ ExtractTask,+ ModelConfig,+ ProfileConfig,+ Tasks,+)+from sie_server.core.inference_output import EncodeOutput, ExtractOutput+from sie_server.core.postprocessor_registry import PostprocessorRegistry+from sie_server.core.registry import ModelRegistry+from sie_server.core.timing import RequestTiming+from sie_server.core.worker import WorkerResult++JSON_HEADERS = {"Accept": "application/json"}++# 48 characters. The OpenAI-compat layer's character estimate for this input is+# 48 / 4 = 12, so a reported 12 would prove the estimate leaked through.+LONG_TEXT = "x" * 48+WORKER_TOKEN_COUNT = 7+++def _encode_registry(extra: dict[str, Any]) -> MagicMock:+ """Registry whose adapter stamps `extra` on its EncodeOutput.++ `extra["input_token_counts"]` is the authoritative per-item basis the+ flash adapters expose; the encode pipeline lifts it onto the request+ timing, which is where both telemetry and `usage` read it from.+ """++ def encode_impl(items: list[Any], output_types: list[str], **kwargs: Any) -> EncodeOutput:+ output = EncodeOutput(+ dense=np.array([[0.1, 0.2, 0.3]] * len(items), dtype=np.float32),+ batch_size=len(items),+ dense_dim=3,+ )+ output.extra.update(extra)+ return output++ adapter = MagicMock()+ adapter.encode = MagicMock(side_effect=encode_impl)+ # A real adapter's `count_input_tokens` is the pipeline's next fallback;+ # returning None keeps these tests on the `extra` basis they are about.+ adapter.count_input_tokens = MagicMock(return_value=None)++ registry = MagicMock(spec=ModelRegistry)+ registry.has_model.return_value = True+ registry.is_loaded.return_value = True+ registry.is_loading.return_value = False+ registry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = None+ registry.get.return_value = adapter+ registry.get_config.return_value = ModelConfig(+ sie_id="test-model",+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=3))),+ profiles={"default": ProfileConfig(adapter_path="test:TestAdapter", max_batch_tokens=8192)},+ )+ registry.model_names = ["test-model"]+ registry.device = "cpu"+ preprocessor_registry = MagicMock()+ preprocessor_registry.has_tokenizer.return_value = False+ preprocessor_registry.has_preprocessor.return_value = False+ registry.preprocessor_registry = preprocessor_registry+ registry.postprocessor_registry = PostprocessorRegistry(ThreadPoolExecutor(max_workers=1))+ return registry+++def _encode_client(extra: dict[str, Any]) -> TestClient:+ app = FastAPI()+ app.include_router(encode_router)+ app.state.registry = _encode_registry(extra)+ return TestClient(app)+++def _encode(client: TestClient, items: list[dict[str, Any]]) -> dict[str, Any]:+ response = client.post("/v1/encode/test-model", json={"items": items}, headers=JSON_HEADERS)+ assert response.status_code == 200, response.text+ return response.json()+++class TestEncodeUsage:+ def test_reports_the_worker_count_not_a_character_estimate(self) -> None:+ body = _encode(+ _encode_client({"input_token_counts": [WORKER_TOKEN_COUNT]}),+ [{"text": LONG_TEXT}],+ )+ assert body["usage"]["input_tokens"] == WORKER_TOKEN_COUNT+ assert body["usage"]["input_tokens"] != len(LONG_TEXT) // 4++ def test_sums_the_worker_counts_across_the_batch(self) -> None:+ body = _encode(+ _encode_client({"input_token_counts": [3, 11]}),+ [{"text": "first"}, {"text": "second"}],+ )+ assert body["usage"]["input_tokens"] == 14++ def test_reports_an_authoritative_zero(self) -> None:+ """A media-only encode reads no text: `0` is the measurement.++ The metering seam deliberately drops that zero (it is only meaningful+ there under an image witness), but a caller reading `usage` must be able+ to tell "measured nothing" from "could not measure".+ """+ body = _encode(+ _encode_client({"input_token_counts": [0], "input_image_counts": [4]}),+ [{"image": {"url": "https://example.invalid/cat.png"}}],+ )+ assert body["usage"]["input_tokens"] == 0+ assert body["usage"]["images"] == 4++ def test_omits_usage_when_no_authoritative_count_exists(self) -> None:+ """Omission, not an estimate. An absent block means "unknown"."""+ body = _encode(_encode_client({}), [{"text": LONG_TEXT}])+ assert "usage" not in body++ def test_omits_usage_when_the_counts_are_misaligned_with_the_batch(self) -> None:+ body = _encode(+ _encode_client({"input_token_counts": [3]}),+ [{"text": "first"}, {"text": "second"}],+ )+ assert "usage" not in body+++def _extract_client(input_token_counts: list[int] | None) -> TestClient:+ output = ExtractOutput(entities=[[]], batch_size=1, input_token_counts=input_token_counts)+ timing = RequestTiming()+ timing.start_tokenization()+ timing.end_tokenization()+ timing.start_queue()+ timing.start_inference()+ timing.end_inference()+ timing.finish()++ async def submit_extract(prepared_items: Any, items: Any, **kwargs: Any) -> Any:+ future: asyncio.Future[WorkerResult] = asyncio.get_running_loop().create_future()+ future.set_result(WorkerResult(output=output, timing=kwargs.get("timing") or timing))+ return future++ worker = MagicMock()+ worker.submit_extract = submit_extract++ registry = MagicMock(spec=ModelRegistry)+ registry.has_model.return_value = True+ registry.is_loaded.return_value = True+ registry.is_loading.return_value = False+ registry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = None+ registry.get.return_value = MagicMock()+ registry.get_config.return_value = ModelConfig(+ sie_id="test-model",+ hf_id="org/test",+ tasks=Tasks(extract=ExtractTask()),+ profiles={"default": ProfileConfig(adapter_path="test:TestAdapter", max_batch_tokens=8192)},+ )+ registry.model_names = ["test-model"]+ registry.device = "cpu"+ registry.start_worker = AsyncMock(return_value=worker)++ app = FastAPI()+ app.include_router(extract_router)+ app.state.registry = registry+ return TestClient(app)+++def _extract(client: TestClient) -> dict[str, Any]:+ response = client.post(+ "/v1/extract/test-model",+ json={"items": [{"text": LONG_TEXT}], "params": {"labels": ["person"]}},+ headers=JSON_HEADERS,+ )+ assert response.status_code == 200, response.text+ return response.json()+++class TestExtractUsage:+ def test_reports_the_worker_count(self) -> None:+ body = _extract(_extract_client([WORKER_TOKEN_COUNT]))+ assert body["usage"]["input_tokens"] == WORKER_TOKEN_COUNT++ def test_reports_an_authoritative_zero(self) -> None:+ body = _extract(_extract_client([0]))+ assert body["usage"]["input_tokens"] == 0++ def test_omits_usage_when_no_authoritative_count_exists(self) -> None:+ body = _extract(_extract_client(None))+ assert "usage" not in body+++ ("counts", "item_count", "expected"),+ [+ ([5, 6], 2, 11),+ ([0, 0], 2, 0),+ (None, 2, None),+ ([5], 2, None),+ ([True, 1], 2, None),+ ],+)+def test_validated_total_keeps_zero_and_drops_the_unusable(+ counts: list[int] | None, item_count: int, expected: int | None+) -> None:+ assert validated_total(counts, item_count) == expecteddiff --git a/packages/sie_server/tests/config/test_bundle_coverage.py b/packages/sie_server/tests/config/test_bundle_coverage.pyindex ce69684e9..429f06a70 100644--- a/packages/sie_server/tests/config/test_bundle_coverage.py+++ b/packages/sie_server/tests/config/test_bundle_coverage.py@@ -141,7 +141,6 @@ def test_candle_bundle_only_exposes_profile_variants() -> None:[("lightonai/LightOnOCR-2-1B", "transformers5.yaml"),("PaddlePaddle/PaddleOCR-VL-1.5", "default.yaml"),- ("PaddlePaddle/PaddleOCR-VL-1.6", "default.yaml"),("zai-org/GLM-OCR", "transformers5.yaml"),],)diff --git a/packages/sie_server/tests/config/test_qwen38_generation_profiles.py b/packages/sie_server/tests/config/test_qwen38_generation_profiles.pynew file mode 100644index 000000000..e1de3522c--- /dev/null+++ b/packages/sie_server/tests/config/test_qwen38_generation_profiles.py@@ -0,0 +1,165 @@+from __future__ import annotations++from pathlib import Path++from sie_server.core.loader import expand_profile_variants, load_model_config++_MODEL_ID = "Qwen/Qwen3.8-27B-FP8"+_MODEL_PATH = Path(__file__).resolve().parents[2] / "models" / "Qwen__Qwen3.8-27B-FP8.yaml"+_REVISION = "017b9c7af6b5689d5dd426a76e0bc077eb5ca20a"+_ADAPTER = "sie_server.adapters.sglang.cuda13:SGLangCuda13Adapter"+_NATIVE_CONTEXT = 262144+_NATIVE_OUTPUT_CAP = 32768+_SPECULATIVE = {+ "enabled": True,+ "algorithm": "eagle",+ "num_steps": 3,+ "eagle_topk": 1,+ "num_draft_tokens": 4,+}+_HARDWARE_PROFILES = {+ "h100-256k": "h100-256k-no-spec",+ "h200-256k": "h200-256k-no-spec",+ "rtx-pro-6000-256k": "rtx-pro-6000-256k-no-spec",+}+++def test_qwen38_uses_the_pinned_official_fp8_checkpoint() -> None:+ config = load_model_config(_MODEL_PATH)++ assert config.sie_id == config.hf_id == _MODEL_ID+ assert config.hf_revision == _REVISION+ assert config.inputs.model_dump() == {+ "text": True,+ "document": False,+ "image": True,+ "audio": False,+ "video": False,+ }+ assert config.tasks.generate is not None+ assert config.tasks.generate.context_length == 8192+ assert config.tasks.generate.max_output_tokens == 4096+ assert config.tasks.generate.chat_template_kwargs == {"enable_thinking": False}+ assert set(config.profiles) == {+ "default",+ "h100-256k",+ "h100-256k-no-spec",+ "h200-256k",+ "h200-256k-no-spec",+ "rtx-pro-6000-256k",+ "rtx-pro-6000-256k-no-spec",+ }+++def test_qwen38_default_is_a_conservative_non_speculative_route() -> None:+ config = load_model_config(_MODEL_PATH)+ default = config.resolve_profile("default")++ assert default.adapter_path == _ADAPTER+ assert default.max_batch_tokens == 16384+ assert default.kv_budget_tokens == 8192+ assert default.loadtime["mem_fraction_static"] == 0.85+ assert default.loadtime["disable_cuda_graph"] is True+ assert default.loadtime["speculative"] == {"enabled": False}+ assert default.loadtime["attention_backend"] == "flashinfer"+ assert "extra_env" not in default.loadtime+ default_args = default.loadtime["extra_launch_args"]+ assert default_args[default_args.index("--mamba-ssm-dtype") + 1] == "float32"+ # Qwen3 structured output is not constrained when thinking is disabled+ # while the reasoning parser waits for a think terminator. These profiles+ # are explicitly answer-only, so they must not launch that parser.+ assert "reasoning_parser" not in default.loadtime+ assert default.loadtime["tool_call_parser"] == "qwen3_coder"+ assert "--quantization" not in default.loadtime["extra_launch_args"]+++def test_qwen38_hardware_profiles_materialize_the_native_context() -> None:+ configs = expand_profile_variants([load_model_config(_MODEL_PATH)])+ bare = configs[_MODEL_ID]++ assert bare.tasks.generate is not None+ assert bare.tasks.generate.context_length == 8192+ assert bare.max_sequence_length == 8192+ assert bare.resolve_profile("default").kv_budget_tokens == 8192++ for profile_name in (*_HARDWARE_PROFILES, *_HARDWARE_PROFILES.values()):+ variant = configs[f"{_MODEL_ID}:{profile_name}"]+ profile = variant.resolve_profile("default")++ assert variant.tasks.generate is not None+ assert variant.tasks.generate.context_length == _NATIVE_CONTEXT+ assert variant.tasks.generate.max_output_tokens == _NATIVE_OUTPUT_CAP+ assert variant.max_sequence_length == _NATIVE_CONTEXT+ assert variant.tasks.generate.chat_template_kwargs == {"enable_thinking": False}+ assert profile.adapter_path == _ADAPTER+ assert profile.max_batch_tokens == _NATIVE_CONTEXT+ assert profile.kv_budget_tokens == _NATIVE_CONTEXT+ assert profile.compute_precision == "bfloat16"+ assert profile.loadtime["max_seq_length"] == _NATIVE_CONTEXT+ assert profile.loadtime["mem_fraction_static"] == 0.85+ assert "reasoning_parser" not in profile.loadtime+++def test_qwen38_hardware_profiles_use_mtp_with_exact_grammar_twins() -> None:+ config = load_model_config(_MODEL_PATH)++ for source_name, fallback_name in _HARDWARE_PROFILES.items():+ source = config.resolve_profile(source_name)+ fallback = config.resolve_profile(fallback_name)++ assert source.grammar_profile == fallback_name+ assert fallback.grammar_profile is None+ assert source.loadtime["speculative"] == _SPECULATIVE+ assert fallback.loadtime["speculative"] == {"enabled": False}+ assert source.loadtime | {"speculative": None} == fallback.loadtime | {"speculative": None}+ assert fallback.runtime == source.runtime+ assert fallback.runtime["first_chunk_timeout_s"] == 900+ assert fallback.runtime["inter_chunk_timeout_s"] == 30+ assert fallback.runtime["overall_timeout_s"] == 1800+ assert fallback.runtime["default_sampling"] == {+ "temperature": 0.7,+ "top_p": 0.8,+ "top_k": 20,+ "presence_penalty": 1.5,+ }+ assert fallback.runtime["stop_tokens"] == ["<|im_end|>"]+ assert source.adapter_path == fallback.adapter_path == _ADAPTER+ assert source.compute_precision == fallback.compute_precision == "bfloat16"+ assert source.max_batch_tokens == fallback.max_batch_tokens == _NATIVE_CONTEXT+ assert source.kv_budget_tokens == fallback.kv_budget_tokens == _NATIVE_CONTEXT+++def test_qwen38_hardware_launches_keep_fp8_weights_with_tuned_state_precision() -> None:+ config = load_model_config(_MODEL_PATH)++ for profile_name in (*_HARDWARE_PROFILES, *_HARDWARE_PROFILES.values()):+ profile = config.resolve_profile(profile_name)+ args = profile.loadtime["extra_launch_args"]++ assert "--quantization" not in args+ assert args[args.index("--kv-cache-dtype") + 1] == "bfloat16"+ assert args[args.index("--mamba-ssm-dtype") + 1] == "bfloat16"+ assert args[args.index("--mamba-scheduler-strategy") + 1] == "extra_buffer"+ assert args.count("--disable-overlap-schedule") == 1+ assert args[args.index("--page-size") + 1] == "64"+ assert args[args.index("--max-running-requests") + 1] == "1"+ assert args[args.index("--cuda-graph-max-bs") + 1] == "1"+ assert profile.loadtime["extra_env"] == {"SGLANG_JIT_DEEPGEMM_FAST_WARMUP": "1"}++ for profile_name in (+ "h100-256k",+ "h100-256k-no-spec",+ "h200-256k",+ "h200-256k-no-spec",+ ):+ profile = config.resolve_profile(profile_name)+ args = profile.loadtime["extra_launch_args"]+ assert profile.loadtime["attention_backend"] == "fa3"+ assert args[args.index("--chunked-prefill-size") + 1] == "32768"+ assert args[args.index("--max-prefill-tokens") + 1] == "32768"+ for profile_name in ("rtx-pro-6000-256k", "rtx-pro-6000-256k-no-spec"):+ rtx_profile = config.resolve_profile(profile_name)+ rtx_args = rtx_profile.loadtime["extra_launch_args"]+ assert rtx_profile.loadtime["attention_backend"] == "flashinfer"+ assert rtx_args[rtx_args.index("--chunked-prefill-size") + 1] == "2048"+ assert "--max-prefill-tokens" not in rtx_argsdiff --git a/packages/sie_server/tests/conftest.py b/packages/sie_server/tests/conftest.pyindex e2e9f3230..388a408b4 100644--- a/packages/sie_server/tests/conftest.py+++ b/packages/sie_server/tests/conftest.py@@ -440,7 +440,8 @@ def sie_docker_server() -> Generator[str]:Set SIE_DOCKER_IMAGE env var to use a pre-built image (skips build).- Regression test for: https://github.com/superlinked/sie-internal/issues/10+ Without SIE_DOCKER_IMAGE this guards the full container build and startup+ path; with a pre-built image it guards startup only."""docker_client = _get_docker_client()diff --git a/packages/sie_server/tests/core/test_batcher.py b/packages/sie_server/tests/core/test_batcher.pyindex d183eaf43..2333509a8 100644--- a/packages/sie_server/tests/core/test_batcher.py+++ b/packages/sie_server/tests/core/test_batcher.py@@ -495,6 +495,75 @@ class TestImmediateDispatch:assert batch.items[2].cost == 5+class TestCoalesceCap:+ """Tests for the idle-dispatch coalesce cap in get_batch() (#2874)."""++ @pytest.mark.asyncio+ async def test_cap_bounds_lone_item_wait(self) -> None:+ """A lone item waits only the cap, not the full coalesce/batch window."""+ config = BatchConfig(max_batch_wait_ms=1000, max_batch_requests=64, coalesce_ms=800, coalesce_ratio=1.0)+ batcher: BatchFormer[TextPreparedItem, str] = BatchFormer(config)++ await batcher.submit(make_text_item([1, 2, 3]), "req-1")++ start = time.monotonic()+ batch = await asyncio.wait_for(batcher.get_batch(coalesce_cap_ms=10), timeout=2.0)+ elapsed_ms = (time.monotonic() - start) * 1000++ assert batch.size == 1+ # Coalesce fires at ~10ms of quiet, far below the 800ms coalesce+ # window and the 1000ms batch timeout.+ assert elapsed_ms < 400++ @pytest.mark.asyncio+ async def test_cap_still_accumulates_a_burst(self) -> None:+ """Arrivals inside the cap keep extending accumulation (burst fuses)."""+ config = BatchConfig(max_batch_wait_ms=1000, max_batch_requests=64, coalesce_ms=800, coalesce_ratio=1.0)+ batcher: BatchFormer[TextPreparedItem, str] = BatchFormer(config)++ batch_task = asyncio.create_task(batcher.get_batch(coalesce_cap_ms=60))+ for i in range(5):+ await batcher.submit(make_text_item([1, 2, 3], 0), f"req-{i}")+ await asyncio.sleep(0.005) # gaps well inside the 60ms cap++ batch = await asyncio.wait_for(batch_task, timeout=2.0)++ assert batch.size == 5++ @pytest.mark.asyncio+ async def test_batch_timeout_still_bounds_capped_wait(self) -> None:+ """A cap larger than the batch window cannot extend the total wait."""+ config = BatchConfig(max_batch_wait_ms=30, max_batch_requests=64, coalesce_ms=1_000, coalesce_ratio=1.0)+ batcher: BatchFormer[TextPreparedItem, str] = BatchFormer(config)++ await batcher.submit(make_text_item([1, 2, 3]), "req-1")++ start = time.monotonic()+ batch = await asyncio.wait_for(batcher.get_batch(coalesce_cap_ms=10_000), timeout=2.0)+ elapsed_ms = (time.monotonic() - start) * 1000++ assert batch.size == 1+ # Neither the large cap nor the 1000ms coalesce window can extend the+ # 30ms batch timeout — the batch window is the binding bound here.+ assert elapsed_ms < 500++ @pytest.mark.asyncio+ async def test_no_cap_keeps_existing_behavior(self) -> None:+ """Without a cap the coalesce window is unchanged."""+ config = BatchConfig(max_batch_wait_ms=200, max_batch_requests=64, coalesce_ms=40, coalesce_ratio=1.0)+ batcher: BatchFormer[TextPreparedItem, str] = BatchFormer(config)++ await batcher.submit(make_text_item([1, 2, 3]), "req-1")++ start = time.monotonic()+ batch = await asyncio.wait_for(batcher.get_batch(), timeout=2.0)+ elapsed_ms = (time.monotonic() - start) * 1000++ assert batch.size == 1+ # Coalesce fires at ~40ms of quiet — not immediately.+ assert elapsed_ms >= 30++class TestSubBatching:"""Tests for sub-batching behavior (splitting large batches)."""diff --git a/packages/sie_server/tests/core/test_disk_cache.py b/packages/sie_server/tests/core/test_disk_cache.pyindex 3007e6466..1922e16cb 100644--- a/packages/sie_server/tests/core/test_disk_cache.py+++ b/packages/sie_server/tests/core/test_disk_cache.py@@ -3,11 +3,13 @@from __future__ import annotationsimport os+import shutilimport timefrom pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytest+from huggingface_hub import scan_cache_dir as real_scan_cache_dirfrom sie_server.core.disk_cache import (CachedModelInfo,DiskCacheConfig,@@ -350,6 +352,30 @@ class TestModelDiskCacheManager:models_after = manager.get_cached_models()assert len(models_after) == 0+ def test_evict_model_reuses_supplied_scan(self, manager: ModelDiskCacheManager, cache_dir: Path) -> None:+ """Passing a scan in deletes the model without walking the cache again."""+ model_dir = create_hf_cache_model(cache_dir, "test/model-to-evict", commit_hash="evict123")+ cache_info = real_scan_cache_dir(cache_dir)+ model = manager.get_cached_models()[0]++ with patch("huggingface_hub.scan_cache_dir", wraps=real_scan_cache_dir) as scan_spy:+ freed = manager.evict_model(model, cache_info=cache_info)++ assert freed > 0+ assert scan_spy.call_count == 0+ assert not model_dir.exists()++ def test_evict_model_revisions_missing_from_scan(self, manager: ModelDiskCacheManager, cache_dir: Path) -> None:+ """A scan that no longer knows the model's revisions frees nothing."""+ model_dir = create_hf_cache_model(cache_dir, "test/gone", commit_hash="gone123")+ model = manager.get_cached_models()[0]++ # The model disappears, then we hand eviction a scan taken afterwards.+ shutil.rmtree(model_dir)+ cache_info = real_scan_cache_dir(cache_dir)++ assert manager.evict_model(model, cache_info=cache_info) == 0+def test_evict_model_no_commit_hashes(self, manager: ModelDiskCacheManager) -> None:"""Test evicting a model with no commit hashes does nothing."""model = CachedModelInfo(@@ -497,6 +523,127 @@ class TestModelDiskCacheManager:assert not model2.exists()assert model3.exists() # Newest should remain+ def test_ensure_space_scans_cache_once_for_multiple_evictions(+ self, manager: ModelDiskCacheManager, cache_dir: Path+ ) -> None:+ """The whole eviction loop walks the cache exactly once, whatever the victim count."""+ base_time = time.time()+ model1 = create_hf_cache_model(cache_dir, "oldest/model", commit_hash="aaa", access_time=base_time - 3600)+ model2 = create_hf_cache_model(cache_dir, "middle/model", commit_hash="bbb", access_time=base_time - 1800)+ model3 = create_hf_cache_model(cache_dir, "newest/model", commit_hash="ccc", access_time=base_time)++ call_count = [0]++ def mock_disk_usage(_path: Path) -> MagicMock:+ call_count[0] += 1+ mock = MagicMock()+ mock.used = 90 * (1024**3) if call_count[0] <= 2 else 70 * (1024**3)+ mock.total = 100 * (1024**3)+ return mock++ with (+ patch("shutil.disk_usage", side_effect=mock_disk_usage),+ patch("huggingface_hub.scan_cache_dir", wraps=real_scan_cache_dir) as scan_spy,+ ):+ evicted = manager.ensure_space_before_download("brand-new/model")++ # One scan for two evictions (was one per get_lru_model plus one per evict_model).+ assert scan_spy.call_count == 1+ # Victim order is still LRU, and eviction still stops as soon as pressure drops.+ assert evicted == ["oldest/model", "middle/model"]+ assert not model1.exists()+ assert not model2.exists()+ assert model3.exists()++ def test_ensure_space_does_not_scan_without_pressure(self, manager: ModelDiskCacheManager, cache_dir: Path) -> None:+ """Below the threshold the cache is never walked at all."""+ create_hf_cache_model(cache_dir, "test/model", commit_hash="abc123")++ mock_usage = MagicMock()+ mock_usage.used = 50 * (1024**3)+ mock_usage.total = 100 * (1024**3)++ with (+ patch("shutil.disk_usage", return_value=mock_usage),+ patch("huggingface_hub.scan_cache_dir", wraps=real_scan_cache_dir) as scan_spy,+ ):+ evicted = manager.ensure_space_before_download("new/model")++ assert evicted == []+ assert scan_spy.call_count == 0++ def test_ensure_space_stops_when_snapshot_exhausted(self, manager: ModelDiskCacheManager, cache_dir: Path) -> None:+ """Sustained pressure evicts every candidate once, then stops (no rescan, no spin)."""+ base_time = time.time()+ model1 = create_hf_cache_model(cache_dir, "oldest/model", commit_hash="aaa", access_time=base_time - 3600)+ model2 = create_hf_cache_model(cache_dir, "newest/model", commit_hash="bbb", access_time=base_time)++ mock_usage = MagicMock()+ mock_usage.used = 90 * (1024**3) # Never drops below the threshold+ mock_usage.total = 100 * (1024**3)++ with (+ patch("shutil.disk_usage", return_value=mock_usage),+ patch("huggingface_hub.scan_cache_dir", wraps=real_scan_cache_dir) as scan_spy,+ ):+ evicted = manager.ensure_space_before_download("new/model")++ assert evicted == ["oldest/model", "newest/model"]+ assert scan_spy.call_count == 1+ assert not model1.exists()+ assert not model2.exists()++ def test_ensure_space_nothing_evictable_scans_once(self, cache_dir: Path) -> None:+ """With every candidate excluded, the single scan is still the only one."""+ pinned_dir = create_hf_cache_model(cache_dir, "pinned/model", commit_hash="pin", access_time=time.time() - 3600)++ config = DiskCacheConfig(cache_dir=cache_dir, pressure_threshold=0.85)+ manager = ModelDiskCacheManager(config, pinned_provider=lambda: {"pinned/model"})++ mock_usage = MagicMock()+ mock_usage.used = 90 * (1024**3)+ mock_usage.total = 100 * (1024**3)++ with (+ patch("shutil.disk_usage", return_value=mock_usage),+ patch("huggingface_hub.scan_cache_dir", wraps=real_scan_cache_dir) as scan_spy,+ ):+ evicted = manager.ensure_space_before_download("new/model")++ assert evicted == []+ assert scan_spy.call_count == 1+ assert pinned_dir.exists()++ def test_ensure_space_survives_model_vanishing_mid_loop(+ self, manager: ModelDiskCacheManager, cache_dir: Path+ ) -> None:+ """A model deleted behind the snapshot's back neither crashes nor hangs the loop."""+ base_time = time.time()+ first = create_hf_cache_model(cache_dir, "first/model", commit_hash="aaa", access_time=base_time - 3600)+ second = create_hf_cache_model(cache_dir, "second/model", commit_hash="bbb", access_time=base_time - 1800)+ third = create_hf_cache_model(cache_dir, "third/model", commit_hash="ccc", access_time=base_time)++ def mock_disk_usage(_path: Path) -> MagicMock:+ # Once the first victim is gone, a concurrent actor removes the next one.+ if not first.exists() and second.exists():+ shutil.rmtree(second)+ mock = MagicMock()+ mock.used = 90 * (1024**3) # Sustained pressure: walk the whole snapshot+ mock.total = 100 * (1024**3)+ return mock++ with (+ patch("shutil.disk_usage", side_effect=mock_disk_usage),+ patch("huggingface_hub.scan_cache_dir", wraps=real_scan_cache_dir) as scan_spy,+ ):+ evicted = manager.ensure_space_before_download("new/model")++ assert scan_spy.call_count == 1+ # The vanished model does not derail the loop: the later victim is still evicted.+ assert evicted[0] == "first/model"+ assert evicted[-1] == "third/model"+ assert not third.exists()+def test_touch_updates_directory_mtime(self, manager: ModelDiskCacheManager, cache_dir: Path) -> None:"""Test touching updates model directory mtime."""model_dir = create_hf_cache_model(cache_dir, "BAAI/bge-m3", commit_hash="touch123")diff --git a/packages/sie_server/tests/core/test_encode_worker_batching.py b/packages/sie_server/tests/core/test_encode_worker_batching.pynew file mode 100644index 000000000..361e21f00--- /dev/null+++ b/packages/sie_server/tests/core/test_encode_worker_batching.py@@ -0,0 +1,299 @@+"""#2874: text requests to preprocessor-less multimodal encoders must batch.++The negative-return admission diagnosis (issue #2874, Layer A) showed a family+of encode paths where batching never engaged: models without a registered+``"text"`` preprocessor bypassed ``ModelWorker`` entirely and ran one+``asyncio.to_thread`` adapter call per request, serialized across N threads on+the adapters' ``_forward_lock``/``_tokenizer_lock`` — worse than serial under+concurrency (the c=1-peak sweep cells). Affected: the colpali/colqwen/+qwen3-vl-embedding family (no preprocessor at all) and SigLIP/CLIP text+requests (image-only preprocessor registered).++These tests drive the REAL adapter ``get_preprocessor()`` through the same+modality registration ``ModelLoader._finish_load`` performs, then push N+concurrent requests through ``EncodePipeline.run_encode`` with a REAL+``ModelWorker``. They fail if the adapters stop registering a text+preprocessor (reverting to the unbatched fallback makes every adapter call a+batch-of-1, so the fused-batch assertions below trip) — that is the mutation+this suite exists to kill.+"""++from __future__ import annotations++import asyncio+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import numpy as np+import pytest+from sie_server.adapters.clip import CLIPAdapter+from sie_server.adapters.colpali import ColPaliAdapter+from sie_server.adapters.colqwen2 import ColQwen2Adapter+from sie_server.adapters.colqwen3 import ColQwen3Adapter+from sie_server.adapters.colsmol import ColSmolAdapter+from sie_server.adapters.qwen3_vl_embedding import Qwen3VLEmbeddingAdapter+from sie_server.adapters.siglip.adapter import SiglipAdapter+from sie_server.core.encode_pipeline import EncodePipeline+from sie_server.core.preprocessor.text import CharCountPreprocessor+from sie_server.core.preprocessor_registry import PreprocessorRegistry+from sie_server.core.timing import RequestTiming+from sie_server.core.worker import ModelWorker, WorkerConfig+from sie_server.types.inputs import Item++MODEL = "stub/model-2874"+++def _register_by_modality(preproc_registry: PreprocessorRegistry, name: str, adapter: Any) -> None:+ """Mirror ``ModelLoader._finish_load``'s modality registration loop.++ Registration is driven by the REAL ``adapter.get_preprocessor()`` so these+ tests fail when an adapter stops advertising a text preprocessor.+ """+ preprocessors = adapter.get_preprocessor()+ if not isinstance(preprocessors, list):+ preprocessors = [preprocessors]+ for preprocessor in preprocessors:+ if preprocessor is None:+ continue+ modality = getattr(preprocessor, "modality", None)+ if modality in ("text", "audio"):+ preproc_registry.register(name, preprocessor)+ elif modality == "image":+ preproc_registry.register_image(name, preprocessor)+++def _pipeline_registry(adapter: Any, worker: ModelWorker, preproc_registry: PreprocessorRegistry) -> MagicMock:+ """Registry facade wiring a real preprocessor registry + real worker."""+ reg = MagicMock()+ reg.preprocessor_registry = preproc_registry+ reg.postprocessor_registry.transform_sync.return_value = 0.0+ reg.get.return_value = adapter+ reg.start_worker = AsyncMock(return_value=worker)+ return reg+++def _worker_for(adapter: Any) -> ModelWorker:+ """Worker with windows generous enough to fuse a gathered burst."""+ return ModelWorker(+ adapter,+ WorkerConfig(+ max_batch_tokens=100_000,+ max_batch_requests=64,+ max_batch_wait_ms=200.0,+ coalesce_ms=100.0,+ coalesce_ratio=0.5,+ idle_coalesce_ms=50.0,+ ),+ model_name=MODEL,+ )+++def _record_encode_calls(adapter: Any) -> list[int]:+ """Wrap the real ``encode`` to record per-call fused batch sizes."""+ calls: list[int] = []+ real_encode = adapter.encode++ def recording_encode(items: list[Item], *args: Any, **kwargs: Any) -> Any:+ calls.append(len(items))+ return real_encode(items, *args, **kwargs)++ adapter.encode = recording_encode+ return calls+++async def _run_concurrent(+ adapter: Any,+ *,+ n_requests: int,+ output_types: list[str],+ is_query: bool,+) -> tuple[list[int], ModelWorker]:+ preproc_registry = PreprocessorRegistry(max_workers=2)+ _register_by_modality(preproc_registry, MODEL, adapter)+ worker = _worker_for(adapter)+ await worker.start()+ calls = _record_encode_calls(adapter)+ reg = _pipeline_registry(adapter, worker, preproc_registry)+ config = MagicMock()+ config.inputs.image = True++ async def _one(i: int) -> Any:+ return await EncodePipeline.run_encode(+ registry=reg,+ model=MODEL,+ items=[Item(text=f"query number {i}")],+ output_types=output_types,+ instruction=None,+ config=config,+ is_query=is_query,+ options={},+ )++ try:+ results = await asyncio.gather(*[_one(i) for i in range(n_requests)])+ finally:+ await worker.stop()++ assert len(results) == n_requests+ for formatted, _timing in results:+ assert len(formatted) == 1+ return calls, worker+++class TestColFamilyTextQueriesBatchThroughWorker:+ """N concurrent text queries fuse into worker batches, not N direct calls."""++ @pytest.mark.asyncio+ async def test_colqwen2_text_queries_fuse(self) -> None:+ adapter = ColQwen2Adapter("stub/colqwen2")+ adapter._model = object()+ adapter._processor = object()+ adapter._device = "cpu"+ adapter._encode_text = lambda text: np.zeros((3, 4), dtype=np.float32) # type: ignore[method-assign]++ calls, worker = await _run_concurrent(adapter, n_requests=6, output_types=["multivector"], is_query=True)++ # The unbatched fallback makes exactly 6 direct batch-of-1 calls;+ # the worker path fuses concurrent arrivals into fewer, larger calls.+ assert sum(calls) == 6+ assert len(calls) < 6, f"expected fused worker batches, got per-request calls: {calls}"+ assert max(calls) >= 2, f"expected at least one fused batch, got: {calls}"+ assert worker.stats.batches_processed >= 1++ @pytest.mark.asyncio+ async def test_colpali_text_queries_fuse(self) -> None:+ adapter = ColPaliAdapter("stub/colpali")+ adapter._model = object()+ adapter._processor = object()+ adapter._device = "cpu"+ adapter._encode_text = lambda text: np.zeros((3, 4), dtype=np.float32) # type: ignore[method-assign]++ calls, worker = await _run_concurrent(adapter, n_requests=6, output_types=["multivector"], is_query=True)++ assert sum(calls) == 6+ assert len(calls) < 6+ assert max(calls) >= 2+ assert worker.stats.batches_processed >= 1+++class TestTwinTowerTextPathBatches:+ """SigLIP/CLIP text-only requests fuse AND run as one text-tower forward."""++ @staticmethod+ def _patch_text_tower(adapter: Any) -> list[list[str]]:+ tower_calls: list[list[str]] = []++ def fake_encode_texts(texts: list[str]) -> tuple[list[np.ndarray], list[int]]:+ tower_calls.append(list(texts))+ return [np.zeros(4, dtype=np.float32) for _ in texts], [len(t.split()) for t in texts]++ adapter._encode_texts = fake_encode_texts+ return tower_calls++ @pytest.mark.asyncio+ async def test_siglip_text_requests_fuse_into_one_tower_forward(self) -> None:+ adapter = SiglipAdapter("stub/siglip")+ adapter._model = object()+ adapter._processor = MagicMock()+ tower_calls = self._patch_text_tower(adapter)++ calls, worker = await _run_concurrent(adapter, n_requests=6, output_types=["dense"], is_query=False)++ assert sum(calls) == 6+ assert len(calls) < 6+ assert max(calls) >= 2+ # The fused sub-batch is ONE stacked text-tower forward, not a+ # per-item loop: some tower call carries >= 2 texts.+ assert max(len(texts) for texts in tower_calls) >= 2+ assert worker.stats.batches_processed >= 1++ @pytest.mark.asyncio+ async def test_clip_text_requests_fuse_into_one_tower_forward(self) -> None:+ adapter = CLIPAdapter("stub/clip")+ adapter._model = object()+ adapter._processor = MagicMock()+ tower_calls = self._patch_text_tower(adapter)++ calls, worker = await _run_concurrent(adapter, n_requests=6, output_types=["dense"], is_query=False)++ assert sum(calls) == 6+ assert len(calls) < 6+ assert max(calls) >= 2+ assert max(len(texts) for texts in tower_calls) >= 2+ assert worker.stats.batches_processed >= 1+++class TestAffectedAdaptersRegisterTextPreprocessor:+ """Every #2874 Layer-A adapter must advertise a text-modality preprocessor.++ ``_prepare_batch`` routes text-only requests through the worker IFF a+ ``"text"`` preprocessor is registered; without one the request takes the+ unbatched direct path. ``CharCountPreprocessor`` is cost-only, so the+ adapters keep owning their tokenization and the unit meter's bases are+ unchanged (it is skipped by ``_record_input_token_counts``).+ """++ @pytest.mark.parametrize(+ "adapter_factory",+ [+ lambda: ColPaliAdapter("stub/colpali"),+ lambda: ColQwen2Adapter("stub/colqwen2"),+ lambda: ColQwen3Adapter("stub/colqwen3"),+ lambda: ColSmolAdapter("stub/colsmol"),+ lambda: Qwen3VLEmbeddingAdapter("stub/qwen3-vl-embedding"),+ lambda: SiglipAdapter("stub/siglip"),+ lambda: CLIPAdapter("stub/clip"),+ ],+ ids=["colpali", "colqwen2", "colqwen3", "colsmol", "qwen3_vl_embedding", "siglip", "clip"],+ )+ def test_text_preprocessor_registered(self, adapter_factory: Any) -> None:+ adapter = adapter_factory()+ registry = PreprocessorRegistry(max_workers=1)+ _register_by_modality(registry, MODEL, adapter)+ assert registry.has_preprocessor(MODEL, "text"), (+ f"{type(adapter).__name__} must register a text preprocessor so text "+ "requests take the batched ModelWorker path (#2874)"+ )+ text_preprocessor = registry.get_preprocessor(MODEL, "text")+ assert isinstance(text_preprocessor, CharCountPreprocessor)++ @pytest.mark.parametrize(+ "adapter_factory",+ [+ lambda: _loaded(ColPaliAdapter("stub/colpali")),+ lambda: _loaded(SiglipAdapter("stub/siglip")),+ lambda: _loaded(CLIPAdapter("stub/clip")),+ ],+ ids=["colpali", "siglip", "clip"],+ )+ def test_image_preprocessor_still_registered(self, adapter_factory: Any) -> None:+ """Adding the text entry must not drop the existing image entry."""+ adapter = adapter_factory()+ registry = PreprocessorRegistry(max_workers=1)+ _register_by_modality(registry, MODEL, adapter)+ assert registry.has_preprocessor(MODEL, "image")++ @pytest.mark.asyncio+ async def test_prepare_batch_routes_text_to_worker_path(self) -> None:+ """With the text preprocessor registered, ``_prepare_batch`` returns a+ PreparedBatch (worker path) instead of None (direct fallback).+ """+ adapter = ColQwen2Adapter("stub/colqwen2")+ preproc_registry = PreprocessorRegistry(max_workers=1)+ _register_by_modality(preproc_registry, MODEL, adapter)+ reg = MagicMock()+ reg.preprocessor_registry = preproc_registry+ config = MagicMock()+ config.inputs.image = True++ prepared = await EncodePipeline._prepare_batch(+ reg, MODEL, [Item(text="a query")], config, True, RequestTiming()+ )+ assert prepared is not None+ assert len(prepared.items) == 1+++def _loaded(adapter: Any) -> Any:+ """Stub just enough load state for image-preprocessor construction."""+ adapter._processor = MagicMock()+ return adapterdiff --git a/packages/sie_server/tests/core/test_load_rgb.py b/packages/sie_server/tests/core/test_load_rgb.pyindex a86ec0236..e8660cb54 100644--- a/packages/sie_server/tests/core/test_load_rgb.py+++ b/packages/sie_server/tests/core/test_load_rgb.py@@ -46,3 +46,14 @@ def test_non_bytes_payload_raises_invalid_media() -> None:def test_missing_data_raises_invalid_media() -> None:with pytest.raises(InvalidMediaError):_load_rgb({})+++def test_undecodable_bytes_raise_invalid_media() -> None:+ """Valid base64-decoded bytes that are not an image are a typed 400, not a 500."""+ with pytest.raises(InvalidMediaError, match=r"not a decodable image - at `\$\.items\[\*\]\.images\[0\]\.data`"):+ _load_rgb({"data": b"not an image at all"})+++def test_undecodable_bytes_name_the_item_when_index_is_known() -> None:+ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[3\]\.images\[0\]\.data`"):+ _load_rgb({"data": b"not an image at all"}, item_index=3)diff --git a/packages/sie_server/tests/core/test_logging.py b/packages/sie_server/tests/core/test_logging.pyindex 4caefa001..24cd4d26d 100644--- a/packages/sie_server/tests/core/test_logging.py+++ b/packages/sie_server/tests/core/test_logging.py@@ -6,7 +6,13 @@ import jsonimport loggingimport pytest-from sie_server.core.logging import JSONFormatter, TextFormatter, configure_logging+from sie_server.core.logging import (+ JSONFormatter,+ TextFormatter,+ configure_logging,+ is_valid_log_level,+ valid_log_levels,+)class TestJSONFormatter:@@ -181,3 +187,132 @@ class TestConfigureLogging:root = logging.getLogger()assert root.level == logging.INFO++ def test_invalid_log_level_says_so(+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+ ) -> None:+ """The fallback must be announced, not silent.++ An operator who sets DEBUG and mistypes it otherwise gets a+ normal-looking server with none of the output they asked for and+ nothing anywhere explaining why.++ Asserted against real stdout rather than ``caplog``: ``configure_logging``+ replaces every root handler (including the one caplog installs), and+ stdout is what the operator actually reads.+ """+ monkeypatch.delenv("SIE_LOG_JSON", raising=False)+ monkeypatch.setenv("SIE_LOG_LEVEL", "DEBIG")++ configure_logging(json_format=False)+ logging.getLogger().handlers[0].flush()++ out = capsys.readouterr().out+ assert "DEBIG" in out+ assert "falling back to INFO" in out+ # The message must list what would have worked.+ assert "DEBUG" in out++ def test_warning_outranks_the_fallback_level(+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+ ) -> None:+ """WARNING is above the INFO fallback, so the notice survives it."""+ monkeypatch.delenv("SIE_LOG_JSON", raising=False)+ monkeypatch.setenv("SIE_LOG_LEVEL", "nope")++ configure_logging(json_format=False)+ logging.getLogger().handlers[0].flush()++ assert "WARNING" in capsys.readouterr().out+ assert logging.getLogger().level == logging.INFO++ def test_valid_level_warns_about_nothing(+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+ ) -> None:+ monkeypatch.delenv("SIE_LOG_JSON", raising=False)+ monkeypatch.setenv("SIE_LOG_LEVEL", "warning") # lowercase still resolves++ configure_logging(json_format=False)+ logging.getLogger().handlers[0].flush()++ assert "falling back" not in capsys.readouterr().out+ assert logging.getLogger().level == logging.WARNING++ def test_verbose_is_never_reported_as_invalid(+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+ ) -> None:+ """--verbose short-circuits resolution, so a stale env value is moot."""+ monkeypatch.delenv("SIE_LOG_JSON", raising=False)+ monkeypatch.setenv("SIE_LOG_LEVEL", "garbage")++ configure_logging(verbose=True, json_format=False)+ logging.getLogger().handlers[0].flush()++ assert "falling back" not in capsys.readouterr().out+ assert logging.getLogger().level == logging.DEBUG+++class TestLogLevelHelpers:+ """The validity check backing the CLI's eager `--log-level` rejection."""++ @pytest.mark.parametrize("name", ["DEBUG", "info", " Warning ", "ERROR", "critical"])+ def test_accepts_real_levels_case_and_space_insensitively(self, name: str) -> None:+ assert is_valid_log_level(name)++ @pytest.mark.parametrize("name", ["DEBIG", "verbose", "", " ", "trace"])+ def test_rejects_unknown_levels(self, name: str) -> None:+ assert not is_valid_log_level(name)++ @pytest.mark.parametrize("name", ["NOTSET", "WARN", "FATAL"])+ def test_rejects_names_python_knows_but_we_do_not_advertise(self, name: str) -> None:+ """Validation and the advertised list must be the same set.++ `logging.getLevelNamesMapping()` also carries NOTSET and the deprecated+ WARN/FATAL aliases. Accepting them while `--help` documents five names+ would let a value through that the documented contract does not cover,+ and NOTSET on the root logger means "inherit", not a severity.+ """+ assert name in logging.getLevelNamesMapping()+ assert not is_valid_log_level(name)+ assert name not in valid_log_levels()++ def test_advertised_levels_are_all_real(self) -> None:+ """The list printed in the error must not itself contain a bad name."""+ assert all(is_valid_log_level(name) for name in valid_log_levels())+++class TestRejectedValueIsNotEchoedRaw:+ """A rejected level is arbitrary input and must not reach the sink verbatim."""++ def test_long_value_is_truncated(self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:+ secret = "A" * 200+ monkeypatch.delenv("SIE_LOG_JSON", raising=False)+ monkeypatch.setenv("SIE_LOG_LEVEL", secret)++ configure_logging(json_format=False)+ logging.getLogger().handlers[0].flush()++ out = capsys.readouterr().out+ assert secret not in out+ assert "..." in out++ def test_punctuation_is_masked(self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:+ """Anything that could carry a token shape is replaced, not echoed."""+ monkeypatch.delenv("SIE_LOG_JSON", raising=False)+ monkeypatch.setenv("SIE_LOG_LEVEL", "tok=abc.def/ghi")++ configure_logging(json_format=False)+ logging.getLogger().handlers[0].flush()++ out = capsys.readouterr().out+ assert "tok=abc.def/ghi" not in out+ assert "falling back to INFO" in out++ def test_empty_value_is_labelled(self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:+ monkeypatch.delenv("SIE_LOG_JSON", raising=False)+ monkeypatch.setenv("SIE_LOG_LEVEL", "!!!")++ configure_logging(json_format=False)+ logging.getLogger().handlers[0].flush()++ assert "falling back to INFO" in capsys.readouterr().outdiff --git a/packages/sie_server/tests/core/test_model_load_timeout.py b/packages/sie_server/tests/core/test_model_load_timeout.pyindex 3adda115e..dd48b01e9 100644--- a/packages/sie_server/tests/core/test_model_load_timeout.py+++ b/packages/sie_server/tests/core/test_model_load_timeout.py@@ -1,4 +1,4 @@-"""Tests for the post-download model-load timeout introduced in sie-internal#846.+"""Tests for the post-download model-load timeout.Covers:- ``_resolve_load_timeout`` precedence (kwarg > env > default).diff --git a/packages/sie_server/tests/core/test_model_suggestions.py b/packages/sie_server/tests/core/test_model_suggestions.pynew file mode 100644index 000000000..aab10c665--- /dev/null+++ b/packages/sie_server/tests/core/test_model_suggestions.py@@ -0,0 +1,87 @@+"""Near-match suggestions for unknown model ids."""++from __future__ import annotations++import pytest+from sie_server.core.model_suggestions import suggest_models, suggestion_suffix++# A representative slice of the shipped catalog, including the near-collisions+# that make naive matching dangerous (three bge rerankers, two gte-Qwen2 sizes).+CATALOG = [+ "Alibaba-NLP/gte-Qwen2-1.5B-instruct",+ "Alibaba-NLP/gte-Qwen2-7B-instruct",+ "BAAI/bge-m3",+ "BAAI/bge-reranker-base",+ "BAAI/bge-reranker-large",+ "BAAI/bge-reranker-v2-m3",+ "Qwen/Qwen3-0.6B",+ "Qwen/Qwen3-4B-Instruct-2507",+ "jinaai/jina-colbert-v2",+ "sentence-transformers/all-MiniLM-L6-v2",+]+++def test_missing_org_prefix_is_the_headline_case() -> None:+ """`bge-m3` must resolve to `BAAI/bge-m3`.++ The catalog has no short-name aliasing, so dropping the org prefix is the+ single most likely way to miss — including from the SDK's own docstrings.+ """+ assert suggest_models("bge-m3", CATALOG)[0] == "BAAI/bge-m3"+++def test_case_slip_is_matched() -> None:+ assert suggest_models("baai/BGE-M3", CATALOG)[0] == "BAAI/bge-m3"+++def test_wrong_org_prefix_still_finds_the_model() -> None:+ assert suggest_models("huggingface/bge-m3", CATALOG)[0] == "BAAI/bge-m3"+++def test_typo_in_the_basename_is_matched() -> None:+ assert "Qwen/Qwen3-0.6B" in suggest_models("Qwen/Qwen3-0.6b", CATALOG)+++def test_partial_reranker_name_suggests_rerankers() -> None:+ """`bge-reranker-v2` (a real docs typo) should surface the v2 variant."""+ matches = suggest_models("bge-reranker-v2", CATALOG)+ assert "BAAI/bge-reranker-v2-m3" in matches+++def test_nothing_close_returns_nothing() -> None:+ """A confidently wrong guess is worse than no guess."""+ assert suggest_models("completely-unrelated-xyzzy", CATALOG) == []+++def test_limit_is_respected() -> None:+ assert len(suggest_models("bge-reranker", CATALOG, limit=2)) == 2+++def test_results_are_deterministic() -> None:+ """Equal scores must not reorder between runs."""+ assert suggest_models("bge-reranker", CATALOG) == suggest_models("bge-reranker", CATALOG)++[email protected]("empty", ["", " "])+def test_empty_query_returns_nothing(empty: str) -> None:+ assert suggest_models(empty, CATALOG) == []+++def test_empty_catalog_returns_nothing() -> None:+ assert suggest_models("bge-m3", []) == []+++def test_zero_limit_returns_nothing() -> None:+ assert suggest_models("bge-m3", CATALOG, limit=0) == []+++def test_suffix_is_appendable_prose() -> None:+ suffix = suggestion_suffix("bge-m3", CATALOG)+ assert suffix.startswith(" Did you mean ")+ assert "'BAAI/bge-m3'" in suffix+ assert suffix.endswith("?")+++def test_suffix_is_empty_when_there_is_no_match() -> None:+ """Callers append unconditionally, so "no suggestion" must add nothing."""+ assert suggestion_suffix("completely-unrelated-xyzzy", CATALOG) == ""diff --git a/packages/sie_server/tests/core/test_preprocessor.py b/packages/sie_server/tests/core/test_preprocessor.pyindex 4a8761b64..4fae76ac5 100644--- a/packages/sie_server/tests/core/test_preprocessor.py+++ b/packages/sie_server/tests/core/test_preprocessor.py@@ -626,8 +626,12 @@ class TestImagePreprocessor:indices = [item.original_index for item in batch.items]assert indices == [0, 1, 2]- def test_prepare_skips_items_without_images(self, mock_processor, mock_config, sample_image_bytes):- """Items without images are skipped."""+ def test_prepare_text_items_pass_through_aligned(self, mock_processor, mock_config, sample_image_bytes):+ """Text-only items yield empty-payload entries so the batch stays 1:1.++ Dropping them starved the worker's per-item completion check and a+ mixed text+image request hung forever (#3136).+ """preprocessor = ImagePreprocessor(mock_processor, "test-model")items: list[Item] = [@@ -638,10 +642,34 @@ class TestImagePreprocessor:batch = preprocessor.prepare(items, config=mock_config)- assert batch.size == 1- assert batch.total_cost == 1- # Only item at index 1 has image- assert batch.items[0].original_index == 1+ assert batch.size == 3+ assert batch.total_cost == 3+ assert [item.original_index for item in batch.items] == [0, 1, 2]+ assert batch.items[0].payload.pixel_values is None+ assert batch.items[1].payload.pixel_values is not None+ assert batch.items[2].payload.pixel_values is None++ def test_collate_skips_text_passthrough_entries(self, mock_processor, mock_config, sample_image_bytes):+ """collate() stacks only image payloads from a mixed prepared batch (#3136)."""+ preprocessor = ImagePreprocessor(mock_processor, "test-model")+ items: list[Item] = [+ Item(text="text only"),+ Item(images=[ImageInput(data=sample_image_bytes, format="jpeg")]),+ ]+ batch = preprocessor.prepare(items, config=mock_config)++ result = preprocessor.collate(batch.items, device="cpu")++ assert result["pixel_values"].shape[0] == 1++ def test_collate_all_text_passthrough_returns_empty_tensor(self, mock_processor, mock_config):+ """A prepared batch of only passthrough entries collates to an empty tensor."""+ preprocessor = ImagePreprocessor(mock_processor, "test-model")+ batch = preprocessor.prepare([Item(text="text only")], config=mock_config)++ result = preprocessor.collate(batch.items, device="cpu")++ assert result["pixel_values"].numel() == 0def test_prepare_rejects_str_image_data(self, mock_processor, mock_config):"""Non-bytes image data raises a structured error (defense-in-depth, #1026).@@ -658,6 +686,26 @@ class TestImagePreprocessor:with pytest.raises(InvalidMediaError, match="image data must be bytes, got str"):preprocessor.prepare(items, config=mock_config)+ def test_prepare_rejects_undecodable_image_bytes_naming_the_item(self, mock_processor, mock_config):+ """Valid base64-decoded non-image bytes raise a typed error naming the item.++ PIL's UnidentifiedImageError is an OSError, which missed the+ ValueError -> 400 INVALID_INPUT mapping and surfaced as a 500+ INFERENCE_ERROR leaking a BytesIO repr. decode_image maps it to+ InvalidMediaError with the msgspec-style JSON path.+ """+ preprocessor = ImagePreprocessor(mock_processor, "test-model")+ items = [+ Item(text="fine"),+ Item(images=[ImageInput(data=b"valid base64, not an image", format="png")]),+ ]++ with pytest.raises(+ InvalidMediaError,+ match=r"image data is not a decodable image - at `\$\.items\[1\]\.images\[0\]\.data`",+ ):+ preprocessor.prepare(items, config=mock_config)+def test_prepare_rgba_conversion(self, mock_processor, mock_config):"""RGBA images are converted to RGB."""# Create RGBA image@@ -790,8 +838,19 @@ class TestOpenCLIPImagePreprocessor:assert item.payload.pixel_values[0, 0, 0].item() == 640.0assert item.payload.pixel_values[1, 0, 0].item() == 480.0- def test_prepare_skips_text_only_items(self, fake_val_preproc, mock_config, sample_image_bytes):- """Items without images are skipped; original_index of image items is preserved."""+ def test_prepare_rejects_undecodable_image_bytes_naming_the_item(self, fake_val_preproc, mock_config):+ """Same typed-400 contract as ImagePreprocessor for the open_clip path."""+ preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")+ items = [Item(images=[ImageInput(data=b"valid base64, not an image", format="png")])]++ with pytest.raises(+ InvalidMediaError,+ match=r"image data is not a decodable image - at `\$\.items\[0\]\.images\[0\]\.data`",+ ):+ preprocessor.prepare(items, config=mock_config)++ def test_prepare_text_items_pass_through_aligned(self, fake_val_preproc, mock_config, sample_image_bytes):+ """Text-only items yield empty-payload entries so the batch stays 1:1 (#3136)."""preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")items: list[Item] = [Item(text="text only"),@@ -801,9 +860,25 @@ class TestOpenCLIPImagePreprocessor:batch = preprocessor.prepare(items, config=mock_config)- assert batch.size == 1- assert batch.total_cost == 1- assert batch.items[0].original_index == 1+ assert batch.size == 3+ assert batch.total_cost == 3+ assert [item.original_index for item in batch.items] == [0, 1, 2]+ assert batch.items[0].payload.pixel_values is None+ assert batch.items[1].payload.pixel_values is not None+ assert batch.items[2].payload.pixel_values is None++ def test_collate_skips_text_passthrough_entries(self, fake_val_preproc, mock_config, sample_image_bytes):+ """collate() stacks only image payloads from a mixed prepared batch (#3136)."""+ preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")+ items: list[Item] = [+ Item(text="text only"),+ Item(images=[ImageInput(data=sample_image_bytes, format="jpeg")]),+ ]+ batch = preprocessor.prepare(items, config=mock_config)++ result = preprocessor.collate(batch.items, device="cpu")++ assert result["pixel_values"].shape[0] == 1def test_prepare_rgba_conversion(self, fake_val_preproc, mock_config):"""RGBA images are converted to RGB before val_preproc."""diff --git a/packages/sie_server/tests/core/test_registry_failed_state.py b/packages/sie_server/tests/core/test_registry_failed_state.pyindex 38bd2a5ce..5e43a58b4 100644--- a/packages/sie_server/tests/core/test_registry_failed_state.py+++ b/packages/sie_server/tests/core/test_registry_failed_state.py@@ -1,6 +1,6 @@"""Tests for the terminal ``failed`` state machine in ModelRegistry.-Covers the regression tracked in sie-test#85: a load failure (gated repo,+Covers a terminal load-failure regression: a load failure (gated repo,missing dependency, etc.) used to silently return the model to``available``, producing an infinite retry loop. The registry now recordsa :class:`LoadFailure` and short-circuits ``start_load_async`` while thediff --git a/packages/sie_server/tests/core/test_unload_off_event_loop.py b/packages/sie_server/tests/core/test_unload_off_event_loop.pynew file mode 100644index 000000000..ea42ea51e--- /dev/null+++ b/packages/sie_server/tests/core/test_unload_off_event_loop.py@@ -0,0 +1,186 @@+"""Eviction must not stop the event loop.++Two blocking calls used to run directly on the loop while the global load+lock was held: ``ThreadPoolExecutor.shutdown(wait=True)`` in+``ModelWorker.stop()`` and ``adapter.unload()`` (``gc.collect`` + a CUDA+cache flush, and for subprocess-backed adapters a SIGTERM/SIGKILL wait) in+``RegistryManager._do_unload``. Because they were synchronous, *no* other+coroutine ran for their duration — health probes and in-flight responses on+models that were not being evicted included. This is the first stage of the+eviction-drain contract.++The assertion in each test is the same: a concurrent coroutine must make+progress while the eviction is happening. Both fail against the pre-fix code+rather than hanging — the blocking work is a bounded ``time.sleep``, so a+regression reports a starved loop instead of stalling the suite.+"""++import asyncio+import time+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.registry import ModelRegistry+from sie_server.core.worker import ModelWorker, WorkerConfig++# How long the blocking teardown takes. Long enough that a starved loop is+# unambiguous, short enough to keep the suite quick.+_BLOCKING_S = 0.6++# Ticker period. ~60 ticks are expected over ``_BLOCKING_S`` on a healthy+# loop; a loop blocked by the teardown manages zero. The floor is an order+# of magnitude below the healthy value so a loaded CI machine cannot flake+# it — a busy runner was measured stalling a *healthy* loop for 0.61 s in+# one shot, so the margin here is deliberately generous.+#+# Note this counts ticks rather than measuring the largest gap between+# them: a max over a noisy sample is exactly the statistic that runner+# jitter corrupts, whereas a cumulative count barely moves for one hiccup.+_TICK_S = 0.01+_MIN_TICKS = 5++_AWAIT_TIMEOUT_S = 5.0+++class _Ticker:+ """Counts event-loop turns, standing in for a health probe."""++ def __init__(self) -> None:+ self.ticks = 0+ self._stop = False++ async def run(self) -> None:+ while not self._stop:+ self.ticks += 1+ await asyncio.sleep(_TICK_S)++ def stop(self) -> None:+ self._stop = True+++async def _start_ticker() -> tuple[_Ticker, asyncio.Task[None]]:+ """Start a ticker and reset its count once it is actually running."""+ ticker = _Ticker()+ task = asyncio.create_task(ticker.run())+ await asyncio.sleep(0)+ ticker.ticks = 0+ return ticker, task+++async def _stop_ticker(ticker: _Ticker, task: asyncio.Task[None]) -> int:+ ticker.stop()+ await asyncio.wait_for(task, timeout=_AWAIT_TIMEOUT_S)+ return ticker.ticks+++def _make_config(name: str = "test-model") -> ModelConfig:+ return ModelConfig(+ sie_id=name,+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),+ profiles={+ "default": ProfileConfig(+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",+ max_batch_tokens=8192,+ )+ },+ )++[email protected](autouse=True)+def patch_ensure_model_cached():+ with patch("sie_sdk.cache.ensure_model_cached") as mock:+ mock.return_value = Path("/fake/cache/models--org--test")+ yield mock+++class TestAdapterUnloadDoesNotStarveTheLoop:+ @pytest.mark.asyncio+ async def test_concurrent_coroutine_progresses_during_a_slow_unload(self) -> None:+ """``adapter.unload()`` runs off-loop, so probes keep being served."""+ registry = ModelRegistry()+ registry.add_config(_make_config())++ with patch("sie_server.core.model_loader.load_adapter") as mock_load:+ adapter = MagicMock()+ adapter.memory_footprint.return_value = 1000+ del adapter.aclose_client # embedding-style adapter+ adapter.unload = MagicMock(side_effect=lambda: time.sleep(_BLOCKING_S))+ mock_load.return_value = adapter++ await registry.load_async("test-model", "cpu")++ ticker, ticker_task = await _start_ticker()+ await asyncio.wait_for(registry.unload_async("test-model"), timeout=_AWAIT_TIMEOUT_S)+ ticks = await _stop_ticker(ticker, ticker_task)++ adapter.unload.assert_called_once()+ assert not registry.is_loaded("test-model")+ assert ticks >= _MIN_TICKS, f"event loop was starved during unload ({ticks} ticks)"++ @pytest.mark.asyncio+ async def test_unload_still_completes_before_the_lock_is_released(self) -> None:+ """Ordering is unchanged: teardown finishes before accounting drops.++ Moving the call to a thread must not let ``unload_async`` return+ while VRAM is still held — a load admitted against the freed+ accounting would size itself against memory the dying adapter has+ not released. The load lock stays held across the whole teardown on+ purpose.+ """+ registry = ModelRegistry()+ registry.add_config(_make_config())+ order: list[str] = []++ with patch("sie_server.core.model_loader.load_adapter") as mock_load:+ adapter = MagicMock()+ adapter.memory_footprint.return_value = 1000+ del adapter.aclose_client++ def _slow_unload() -> None:+ time.sleep(_BLOCKING_S)+ order.append("unload-finished")++ adapter.unload = MagicMock(side_effect=_slow_unload)+ mock_load.return_value = adapter++ await registry.load_async("test-model", "cpu")+ await asyncio.wait_for(registry.unload_async("test-model"), timeout=_AWAIT_TIMEOUT_S)+ order.append("unload_async-returned")++ assert order == ["unload-finished", "unload_async-returned"]+++class TestExecutorJoinDoesNotStarveTheLoop:+ @pytest.mark.asyncio+ async def test_concurrent_coroutine_progresses_while_the_inference_thread_drains(self) -> None:+ """``stop()``'s executor join is a thread join; it belongs off-loop."""+ adapter = MagicMock()+ worker = ModelWorker(adapter, WorkerConfig(), model_name="test-model")+ await worker.start()++ # Occupy the single inference thread so the join has something real+ # to wait for, exactly as an in-progress forward pass would.+ worker._inference_executor.submit(time.sleep, _BLOCKING_S)++ ticker, ticker_task = await _start_ticker()+ await asyncio.wait_for(worker.stop(), timeout=_AWAIT_TIMEOUT_S)+ ticks = await _stop_ticker(ticker, ticker_task)++ assert ticks >= _MIN_TICKS, f"event loop was starved during the executor join ({ticks} ticks)"++ @pytest.mark.asyncio+ async def test_stop_waits_for_the_inference_thread(self) -> None:+ """Off-loop is not fire-and-forget: the thread is still joined."""+ adapter = MagicMock()+ worker = ModelWorker(adapter, WorkerConfig(), model_name="test-model")+ await worker.start()++ finished: list[str] = []+ worker._inference_executor.submit(lambda: (time.sleep(_BLOCKING_S), finished.append("thread"))[1])++ await asyncio.wait_for(worker.stop(), timeout=_AWAIT_TIMEOUT_S)++ assert finished == ["thread"]diff --git a/packages/sie_server/tests/core/test_video_frames.py b/packages/sie_server/tests/core/test_video_frames.pyindex 684b8c5db..fbfd325b0 100644--- a/packages/sie_server/tests/core/test_video_frames.py+++ b/packages/sie_server/tests/core/test_video_frames.py@@ -372,23 +372,3 @@ class TestAdmissionCaps:monkeypatch.setattr(video_frames, "_MAX_SCANNED_FRAMES", 4)with pytest.raises(VideoDecodeError, match="scan cap"):extract_frames(_video(_make_video(tmp_path, frames=12)))---class TestBillingContractStaysInSyncWithTheGateway:- """The managed reservation ceiling is a hand-mirrored copy of the budget.-- Settlement rejects a worker count above its reservation ceiling, so a- Python budget raised past the gateway constant would turn every successful- video encode into a billing fault. Nothing but this test binds the two.- """-- def test_gateway_ceiling_covers_the_worker_budget(self) -> None:- repo_root = Path(__file__).resolve().parents[4]- dispatcher = repo_root / "packages" / "sie_cloud" / "gateway" / "src" / "dispatcher.rs"- if not dispatcher.is_file(): # pragma: no cover - checkout without the gateway crate- pytest.skip("gateway crate not present in this checkout")- marker = "const VIDEO_MAX_SAMPLED_FRAMES: usize = "- declarations = [line for line in dispatcher.read_text().splitlines() if marker in line]- assert len(declarations) == 1, "expected exactly one gateway frame-budget constant"- gateway_budget = int(declarations[0].split(marker)[1].split(";")[0].strip())- assert gateway_budget >= MAX_SAMPLED_FRAMESdiff --git a/packages/sie_server/tests/core/test_worker_core.py b/packages/sie_server/tests/core/test_worker_core.pyindex 2f0ad3773..d85682e22 100644--- a/packages/sie_server/tests/core/test_worker_core.py+++ b/packages/sie_server/tests/core/test_worker_core.py@@ -1,11 +1,15 @@import asyncio+import ioimport timefrom unittest.mock import MagicMockimport numpy as npimport pytest+import torch+from PIL import Image as PILImagefrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.prepared import TextPreparedItem, make_text_item+from sie_server.core.preprocessor import ImagePreprocessorfrom sie_server.core.timing import RequestTimingfrom sie_server.core.worker import ModelWorker, RequestMetadata, WorkerConfig, WorkerResult, WorkerStatsfrom sie_server.core.worker import model_worker as model_worker_module@@ -72,6 +76,9 @@ class TestWorkerConfig:assert config.max_batch_wait_ms == 15assert config.coalesce_ms == 15.0assert config.coalesce_ratio == 0.5+ # Idle accumulation window (#2874): single-digit ms by default so an+ # idle worker fuses bursts without materially delaying lone requests.+ assert config.idle_coalesce_ms == 3.0def test_custom_values(self) -> None:"""Can set custom config values."""@@ -98,6 +105,75 @@ class TestWorkerStats:assert stats.total_tokens_processed == 0assert stats.inference_errors == 0+ def test_instrumentation_series_are_bounded(self) -> None:+ """Instrumentation must not grow for the life of the process.++ ``SIE_INSTRUMENTATION=1`` left on in a long-lived deployment appends+ five samples per batch per worker. Unbounded, that is a leak that also+ makes ``summary()`` progressively slower, since it runs min/max/mean/+ median over the whole history. Each series is a bounded ring buffer+ that keeps the NEWEST samples.+ """+ limit = 8+ stats = WorkerStats()+ stats.enable_instrumentation(history_limit=limit)+ assert stats.instrumentation_enabled++ series = (+ stats.batch_sizes,+ stats.batch_tokens,+ stats.batch_wait_ms,+ stats.inference_ms,+ stats.requests_per_batch,+ )+ for sample in range(limit * 5):+ for entries in series:+ assert entries is not None+ entries.append(sample)++ for entries in series:+ assert entries is not None+ assert len(entries) == limit+ # Oldest samples evicted, newest retained.+ assert list(entries) == list(range(limit * 5 - limit, limit * 5))++ def test_instrumentation_summary_shape_is_unchanged(self) -> None:+ """``summary()`` output must stay byte-identical in shape for consumers."""+ stats = WorkerStats(batches_processed=2, items_processed=6, total_tokens_processed=90)+ stats.enable_instrumentation()+ assert stats.batch_sizes is not None+ assert stats.batch_tokens is not None+ assert stats.batch_wait_ms is not None+ assert stats.inference_ms is not None+ assert stats.requests_per_batch is not None+ for size, tokens, wait, infer, requests in ((2, 30, 1.0, 10.0, 2), (4, 60, 3.0, 20.0, 3)):+ stats.batch_sizes.append(size)+ stats.batch_tokens.append(tokens)+ stats.batch_wait_ms.append(wait)+ stats.inference_ms.append(infer)+ stats.requests_per_batch.append(requests)++ summary = stats.summary()+ assert "Batches processed: 2" in summary+ assert "=== Batch Size Stats ===" in summary+ assert "Items/batch: min=2, max=4, mean=3.0, median=3.0" in summary+ assert "Tokens/batch: min=30, max=60, mean=45.0" in summary+ assert "Requests/batch: min=2, max=3, mean=2.5" in summary+ assert "=== Timing Stats ===" in summary+ assert "Batch wait (ms): min=1.0, max=3.0, mean=2.0, p50=2.0" in summary+ assert "Inference (ms): min=10.0, max=20.0, mean=15.0, p50=15.0" in summary++ def test_summary_without_instrumentation_omits_detail(self) -> None:+ """The non-instrumented summary keeps its four-line shape."""+ summary = WorkerStats().summary()++ assert summary.splitlines() == [+ "Batches processed: 0",+ "Items processed: 0",+ "Tokens processed: 0",+ "Inference errors: 0",+ ]+class TestModelWorker:"""Tests for ModelWorker."""@@ -240,6 +316,43 @@ class TestModelWorker:finally:await worker.stop()+ @pytest.mark.asyncio+ async def test_mixed_text_image_batch_completes(self, mock_adapter: MagicMock) -> None:+ """A mixed text+image request must resolve its future (#3136).++ Submits exactly what ``EncodePipeline.run_encode`` submits for a mixed+ batch on an image-preprocessor model: the ImagePreprocessor-prepared+ list plus the full original item list. When the preprocessor dropped+ text-only items, ``_complete_requests`` never saw a result for every+ item and the request hung until an outer timeout.+ """+ buf = io.BytesIO()+ PILImage.new("RGB", (4, 4), color=(255, 0, 0)).save(buf, format="PNG")+ png = buf.getvalue()++ items = [+ Item(text="a red square"),+ *[Item(images=[{"data": png, "format": "png"}]) for _ in range(4)],+ ]+ processor = MagicMock(return_value={"pixel_values": torch.zeros(1, 3, 4, 4)})+ prepared_batch = ImagePreprocessor(processor, "test-model").prepare(items, config=MagicMock())++ worker = ModelWorker(+ mock_adapter,+ WorkerConfig(max_batch_tokens=100, max_batch_requests=1, max_batch_wait_ms=1),+ )+ await worker.start()+ try:+ future = await worker.submit(+ prepared_items=prepared_batch.items,+ items=items,+ output_types=["dense"],+ )+ worker_result = await asyncio.wait_for(future, timeout=3.0)+ assert worker_result.output.batch_size == len(items)+ finally:+ await worker.stop()+@pytest.mark.asyncioasync def test_direct_queue_release_emits_once_at_engine_dequeue(self,@@ -471,6 +584,146 @@ class TestModelWorker:finally:await worker.stop()+ @pytest.mark.asyncio+ async def test_staggered_burst_fuses_with_idle_window(self, mock_adapter: MagicMock) -> None:+ """#2874: a burst arriving at an IDLE worker fuses into one batch.++ Before the idle accumulation window, an idle worker dispatched+ immediately with whatever was pending, so staggered arrivals became a+ train of serialized batch-of-1 forwards (the was_idle degeneracy).+ """+ call_sizes: list[int] = []++ def counting_encode(items, output_types, **kwargs):+ call_sizes.append(len(items))+ return EncodeOutput(+ dense=np.array([[0.1, 0.2, 0.3]] * len(items)),+ batch_size=len(items),+ )++ mock_adapter.encode.side_effect = counting_encode++ config = WorkerConfig(+ max_batch_tokens=1000,+ max_batch_requests=64,+ max_batch_wait_ms=500,+ coalesce_ms=200,+ coalesce_ratio=0.5,+ idle_coalesce_ms=60,+ )+ worker = ModelWorker(mock_adapter, config)+ await worker.start()++ try:+ futures = []+ for i in range(4):+ future = await worker.submit(+ [make_text_item([1, 2], 0)],+ [Item(text=f"text {i}")],+ ["dense"],+ )+ futures.append(future)+ # Stagger arrivals well inside the 60ms idle window.+ await asyncio.sleep(0.005)++ await asyncio.gather(*futures)++ # All four staggered requests fused into a single forward.+ assert sum(call_sizes) == 4+ assert call_sizes == [4], f"expected one fused batch, got: {call_sizes}"++ finally:+ await worker.stop()++ @pytest.mark.asyncio+ async def test_staggered_burst_shreds_without_idle_window(self, mock_adapter: MagicMock) -> None:+ """Contrast for the test above: ``idle_coalesce_ms=0`` restores the+ legacy immediate idle dispatch, and the same staggered burst shreds+ into multiple small forwards. This is the mutation the idle window+ exists to kill — if the window stops being applied, the fusing test+ above degrades into THIS shape and fails.+ """+ call_sizes: list[int] = []++ def counting_encode(items, output_types, **kwargs):+ call_sizes.append(len(items))+ return EncodeOutput(+ dense=np.array([[0.1, 0.2, 0.3]] * len(items)),+ batch_size=len(items),+ )++ mock_adapter.encode.side_effect = counting_encode++ config = WorkerConfig(+ max_batch_tokens=1000,+ max_batch_requests=64,+ max_batch_wait_ms=500,+ coalesce_ms=200,+ coalesce_ratio=0.5,+ idle_coalesce_ms=0,+ )+ worker = ModelWorker(mock_adapter, config)+ await worker.start()++ try:+ futures = []+ for i in range(4):+ future = await worker.submit(+ [make_text_item([1, 2], 0)],+ [Item(text=f"text {i}")],+ ["dense"],+ )+ futures.append(future)+ await asyncio.sleep(0.005)++ await asyncio.gather(*futures)++ assert sum(call_sizes) == 4+ # The first arrival dispatches alone (immediate idle dispatch), so+ # the burst cannot land in a single forward.+ assert len(call_sizes) >= 2, f"expected shredded batches without the window, got: {call_sizes}"++ finally:+ await worker.stop()++ @pytest.mark.asyncio+ async def test_lone_request_waits_only_the_idle_window(self, mock_adapter: MagicMock) -> None:+ """A lone request must not wait the busy-path coalesce/batch windows —+ only the small idle accumulation window bounds its dispatch latency.+ """+ mock_adapter.encode.return_value = EncodeOutput(+ dense=np.array([[0.1, 0.2, 0.3]]),+ batch_size=1,+ )++ config = WorkerConfig(+ max_batch_tokens=1000,+ max_batch_requests=64,+ max_batch_wait_ms=500,+ coalesce_ms=400,+ coalesce_ratio=1.0,+ idle_coalesce_ms=5,+ )+ worker = ModelWorker(mock_adapter, config)+ await worker.start()++ try:+ start = time.monotonic()+ future = await worker.submit(+ [make_text_item([1, 2, 3], 0)],+ [Item(text="hello")],+ ["dense"],+ )+ await asyncio.wait_for(future, timeout=2.0)+ elapsed_ms = (time.monotonic() - start) * 1000++ # ~5ms idle window + mock inference; far below the 400ms coalesce+ # and 500ms batch windows.+ assert elapsed_ms < 200++ finally:+ await worker.stop()+@pytest.mark.asyncioasync def test_concurrent_requests_still_batch(self, mock_adapter: MagicMock) -> None:"""Concurrent requests are still batched together when worker is busy."""diff --git a/packages/sie_server/tests/core/test_worker_drain.py b/packages/sie_server/tests/core/test_worker_drain.pynew file mode 100644index 000000000..320b0aca1--- /dev/null+++ b/packages/sie_server/tests/core/test_worker_drain.py@@ -0,0 +1,414 @@+"""Eviction drain: interrupted requests must fail fast, not hang.++``ModelWorker.stop()`` cancels the batch loop, so anything still sitting in a+``BatchFormer`` will never run. Before the drain, none of the three paths that+complete a queued future with an exception (malformed preformed request, the+per-batch error fan-out, OOM recovery) ran on the eviction path, so an awaiter+blocked until some outer timeout fired. This is the second stage of the+eviction-drain contract.++Two populations, covered in that order below: work still *queued* in a+batcher, and a batch already extracted and *in flight* when the cancellation+landed. The second has its metadata only in ``_process_batch``'s locals, and+``CancelledError`` unwinds past every ``except Exception`` on the way out, so+it needs the worker to hand the registration to ``stop()``.++Every wait here is bounded by a short ``asyncio.wait_for`` so a regression+fails the suite fast instead of stalling it.+"""++import asyncio+import contextlib+import threading+import time+from typing import Any+from unittest.mock import MagicMock++import numpy as np+import pytest+from fastapi import status+from sie_server.api.helpers import WORKER_DRAINED_RETRY_AFTER_S, InferenceErrorHandler+from sie_server.core.inference_output import EncodeOutput+from sie_server.core.prepared import TextPreparedItem, make_text_item+from sie_server.core.timing import RequestTiming+from sie_server.core.worker import ModelWorker, WorkerConfig+from sie_server.core.worker.types import WorkerDrainedError, WorkerResult+from sie_server.ipc_types import EncodeBatchItem+from sie_server.queue_executor import _inference_exception_outcome+from sie_server.types.inputs import Item+from sie_server.types.responses import ErrorCode++# Bounded so a hang regression fails rather than stalls.+_AWAIT_TIMEOUT_S = 2.0+++def _parked_config() -> WorkerConfig:+ """Config whose batcher never yields a batch during a test.++ Every dispatch trigger (cost limit, request limit, first-request timeout,+ coalesce window, idle accumulation window) is pushed far out of reach, so+ submitted items stay queued in the ``BatchFormer`` for the whole test and+ the drain is the only thing that can complete them. This is the state a+ real worker is in whenever it is evicted with a backlog.+ """+ return WorkerConfig(+ max_batch_tokens=10**6,+ max_batch_requests=10**6,+ max_batch_wait_ms=600_000,+ coalesce_ms=600_000,+ idle_coalesce_ms=600_000,+ max_queue_size=0,+ )+++def _dispatching_config() -> WorkerConfig:+ """Opposite of ``_parked_config``: form and dispatch a batch at once.++ Used by the in-flight tests, which need the batch *out* of the batcher+ (so ``drain_pending`` can no longer see it) and sitting in the inference+ executor when the cancellation arrives.+ """+ return WorkerConfig(+ max_batch_tokens=10**6,+ max_batch_requests=10**6,+ max_batch_wait_ms=1,+ coalesce_ms=0,+ idle_coalesce_ms=0,+ max_queue_size=0,+ )+++def mock_adapter() -> MagicMock:+ mock = MagicMock()+ mock.encode.side_effect = lambda items, *args, **kwargs: EncodeOutput(+ dense=np.array([[0.1, 0.2, 0.3]] * len(items)),+ batch_size=len(items),+ )+ return mock+++class _BlockingEncode:+ """An ``encode`` that parks the inference thread until released.++ ``started`` fires once the forward pass is genuinely running on the+ executor thread, which is the only reliable signal that the batch has+ left its batcher. ``release`` lets the thread finish so the test does+ not leak it.+ """++ def __init__(self) -> None:+ self.started = threading.Event()+ self.release = threading.Event()++ def __call__(self, items: list[Any], *args: Any, **kwargs: Any) -> EncodeOutput:+ self.started.set()+ self.release.wait(timeout=_AWAIT_TIMEOUT_S * 2)+ return EncodeOutput(+ dense=np.array([[0.1, 0.2, 0.3]] * len(items)),+ batch_size=len(items),+ )+++async def _await_started(blocking: _BlockingEncode) -> None:+ """Yield to the loop until the forward pass has begun. Bounded."""+ deadline = time.monotonic() + _AWAIT_TIMEOUT_S+ while not blocking.started.is_set():+ assert time.monotonic() < deadline, "inference thread never started"+ await asyncio.sleep(0.005)+++def _item(index: int = 0) -> TextPreparedItem:+ return make_text_item([1, 2, 3, 4, 5], index)+++async def _submit(+ worker: ModelWorker,+ *,+ count: int = 1,+ options: dict[str, Any] | None = None,+) -> asyncio.Future[WorkerResult]:+ """Queue one request of ``count`` items and let the process loop park."""+ future = await worker.submit(+ [_item(i) for i in range(count)],+ [Item(text=f"hello-{i}") for i in range(count)],+ ["dense"],+ options=options,+ )+ # Give the process loop a chance to start and block on the batcher, so+ # the drain is exercised against a live (not merely un-started) loop.+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ return future+++class TestStopDrainsQueuedRequests:+ @pytest.mark.asyncio+ async def test_queued_request_fails_with_retryable_error(self, mock_adapter: MagicMock) -> None:+ """A queued request on an evicted model fails instead of hanging."""+ worker = ModelWorker(mock_adapter, _parked_config(), model_name="test-model")+ await worker.start()+ future = await _submit(worker)+ assert worker.pending_count == 1+ assert not future.done()++ await worker.stop()++ with pytest.raises(WorkerDrainedError, match="test-model"):+ await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S)++ @pytest.mark.asyncio+ async def test_no_item_is_left_pending_in_any_batcher(self, mock_adapter: MagicMock) -> None:+ """Every batcher is drained, not just the base-model one.++ Each LoRA gets its own ``BatchFormer``; a drain that only walked the+ base-model queue would leave every LoRA request hanging.+ """+ worker = ModelWorker(mock_adapter, _parked_config(), model_name="test-model")+ await worker.start()+ base = await _submit(worker)+ lora_a = await _submit(worker, options={"lora": "adapter-a"})+ lora_b = await _submit(worker, options={"lora": "adapter-b"})+ assert set(worker._batchers) == {None, "adapter-a", "adapter-b"}+ assert worker.pending_count == 3++ await worker.stop()++ for future in (base, lora_a, lora_b):+ with pytest.raises(WorkerDrainedError):+ await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S)+ assert worker.pending_count == 0+ assert worker.pending_tokens == 0+ assert all(batcher.pending_count == 0 for batcher in worker._batchers.values())++ @pytest.mark.asyncio+ async def test_multi_item_request_fails_its_single_future_once(self, mock_adapter: MagicMock) -> None:+ """One request occupying N queue slots shares one future.++ Metadata is deduplicated by identity, so the drain must not try to+ set an exception on the same future once per item.+ """+ worker = ModelWorker(mock_adapter, _parked_config(), model_name="test-model")+ await worker.start()+ future = await _submit(worker, count=4)+ assert worker.pending_count == 4++ await worker.stop()++ with pytest.raises(WorkerDrainedError):+ await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S)+ assert worker.pending_count == 0++ @pytest.mark.asyncio+ async def test_already_completed_future_is_not_touched(self, mock_adapter: MagicMock) -> None:+ """The drain is idempotent against a future that already resolved."""+ worker = ModelWorker(mock_adapter, _parked_config(), model_name="test-model")+ await worker.start()+ future = await _submit(worker)++ already_resolved = WorkerResult(+ output=EncodeOutput(dense=np.array([[0.1, 0.2, 0.3]]), batch_size=1),+ timing=RequestTiming(),+ )+ future.set_result(already_resolved)++ await worker.stop()++ assert await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S) is already_resolved++ @pytest.mark.asyncio+ async def test_drain_is_idempotent_across_repeated_stops(self, mock_adapter: MagicMock) -> None:+ worker = ModelWorker(mock_adapter, _parked_config(), model_name="test-model")+ await worker.start()+ future = await _submit(worker)++ await worker.stop()+ await worker.stop()++ with pytest.raises(WorkerDrainedError):+ await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S)+++class TestDrainIsCancellationSafe:+ @pytest.mark.asyncio+ async def test_drain_runs_when_process_task_already_cancelled(self, mock_adapter: MagicMock) -> None:+ """A loop cancelled before ``stop()`` still gets its queue drained.++ ``CancelledError`` is a ``BaseException``, so the ``except Exception``+ fan-out in ``oom_recovery`` never covered this; only an explicit+ drain does.+ """+ worker = ModelWorker(mock_adapter, _parked_config(), model_name="test-model")+ await worker.start()+ future = await _submit(worker)++ assert worker._process_task is not None+ worker._process_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await worker._process_task+ assert not future.done()++ await worker.stop()++ with pytest.raises(WorkerDrainedError):+ await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S)++ @pytest.mark.asyncio+ async def test_drain_runs_when_stop_itself_is_cancelled(self, mock_adapter: MagicMock) -> None:+ """``_do_unload`` runs ``stop()`` under a drain timeout.++ When that timeout fires, the cancellation lands on ``stop()``'s own+ await. The drain lives in a ``finally`` so it still runs.+ """+ worker = ModelWorker(mock_adapter, _parked_config(), model_name="test-model")+ await worker.start()+ future = await _submit(worker)++ stop_task = asyncio.create_task(worker.stop())+ await asyncio.sleep(0) # let stop() reach its await on the process task+ stop_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await stop_task++ with pytest.raises(WorkerDrainedError):+ await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S)+++class TestStopDrainsInFlightBatch:+ """A batch already extracted from its batcher when the loop is cancelled.++ ``BatchFormer.drain_pending()`` cannot reach it — the metadata lives only+ in ``_process_batch``'s locals — and ``CancelledError`` unwinds past+ ``BatchExecutor``'s ``except Exception`` fan-out without failing a single+ future. The worker therefore registers the batch while it is in flight+ and hands that registration to ``stop()`` on cancellation.+ """++ @pytest.mark.asyncio+ async def test_in_flight_request_fails_with_retryable_error(self, mock_adapter: MagicMock) -> None:+ blocking = _BlockingEncode()+ mock_adapter.encode.side_effect = blocking+ worker = ModelWorker(mock_adapter, _dispatching_config(), model_name="test-model")+ await worker.start()+ try:+ future = await worker.submit([_item()], [Item(text="hello")], ["dense"])+ await _await_started(blocking)++ # The batch is out of the batcher: nothing the part-two drain+ # walks can see it any more. This is what makes the test+ # discriminate against the queued-only drain.+ assert worker.pending_count == 0+ assert worker._in_flight, "in-flight batch was not tracked"++ stop_task = asyncio.create_task(worker.stop())+ with pytest.raises(WorkerDrainedError, match="test-model"):+ await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S)+ finally:+ blocking.release.set()++ await asyncio.wait_for(stop_task, timeout=_AWAIT_TIMEOUT_S)++ @pytest.mark.asyncio+ async def test_registration_is_released_after_a_normal_batch(self, mock_adapter: MagicMock) -> None:+ """A live worker accumulates nothing: only cancellation retains."""+ worker = ModelWorker(mock_adapter, _dispatching_config(), model_name="test-model")+ await worker.start()+ try:+ future = await worker.submit([_item()], [Item(text="hello")], ["dense"])+ await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S)++ assert worker._in_flight == {}+ finally:+ await worker.stop()++ @pytest.mark.asyncio+ async def test_cancelling_a_live_preformed_request_retains_nothing(self, mock_adapter: MagicMock) -> None:+ """A cancellation with no ``stop()`` behind it must not accumulate.++ The ownership handoff is only correct when someone is coming to+ collect. ``IpcServer`` cancels its in-flight request tasks when its+ drain deadline expires while the worker is still running, and each+ retained registration would pin an ``_InFlightBatch``, its metadata,+ the prepared items and the future for the life of the process.+ """+ blocking = _BlockingEncode()+ mock_adapter.encode.side_effect = blocking+ worker = ModelWorker(mock_adapter, _parked_config(), model_name="test-model")+ await worker.start()++ for _ in range(3):+ request = asyncio.create_task(worker.submit_preformed([_item()], [Item(text="hello")], ["dense"]))+ await _await_started(blocking)+ assert worker._in_flight, "pre-formed batch was not tracked"++ request.cancel()+ blocking.release.set()+ with contextlib.suppress(asyncio.CancelledError):+ await asyncio.wait_for(request, timeout=_AWAIT_TIMEOUT_S)++ # The worker is still running, so nothing will ever drain this.+ assert worker.is_running+ assert worker._in_flight == {}, "a cancelled live request retained its registration"+ blocking.started.clear()+ blocking.release.clear()++ await worker.stop()++ @pytest.mark.asyncio+ async def test_stop_leaves_a_live_preformed_batch_alone(self, mock_adapter: MagicMock) -> None:+ """The sidecar's pre-formed path dispatches from its own task.++ It bypasses the batchers and is not cancelled by ``stop()``, so its+ forward pass is still going to produce a result. Failing its futures+ would turn a request that is about to succeed into a spurious retry,+ which is why the drain checks the owning task rather than simply+ failing everything registered.+ """+ blocking = _BlockingEncode()+ mock_adapter.encode.side_effect = blocking+ worker = ModelWorker(mock_adapter, _parked_config(), model_name="test-model")+ await worker.start()++ preformed = asyncio.create_task(worker.submit_preformed([_item()], [Item(text="hello")], ["dense"]))+ await _await_started(blocking)+ assert worker._in_flight, "pre-formed batch was not tracked"++ # Drain directly: ``stop()`` would join the executor and block until+ # the forward pass finishes, hiding the ordering under test.+ assert worker._fail_queued_requests() == 0+ assert worker._in_flight, "a live pre-formed batch must not be reaped"++ blocking.release.set()+ future = await asyncio.wait_for(preformed, timeout=_AWAIT_TIMEOUT_S)+ result = await asyncio.wait_for(future, timeout=_AWAIT_TIMEOUT_S)+ assert result.output.batch_size == 1+ await worker.stop()+++class TestDrainedErrorSurfaces:+ """A drained request must read as retryable on both ingress paths."""++ def test_http_path_maps_to_retryable_model_loading(self) -> None:+ handler = InferenceErrorHandler("test-model", "encode", MagicMock())++ exc = handler.handle_inference_error(WorkerDrainedError("stopped before this request ran"))++ assert exc.status_code == status.HTTP_503_SERVICE_UNAVAILABLE+ assert isinstance(exc.detail, dict)+ assert exc.detail["code"] == ErrorCode.MODEL_LOADING.value+ assert exc.headers == {"Retry-After": str(WORKER_DRAINED_RETRY_AFTER_S)}++ def test_queue_path_maps_to_nak_retry(self) -> None:+ batch_item = EncodeBatchItem(+ work_item_id="req-1.0",+ request_id="req-1",+ item_index=0,+ total_items=1,+ timestamp=time.time(),+ item={"text": "hi"},+ )++ outcome = _inference_exception_outcome(batch_item, WorkerDrainedError("evicted"))++ assert outcome.disposition == "nak_retry"+ assert outcome.error_code is Nonediff --git a/packages/sie_server/tests/fake_stack/test_model_loading_race.py b/packages/sie_server/tests/fake_stack/test_model_loading_race.pyindex a9df9ca75..071c5e1a5 100644--- a/packages/sie_server/tests/fake_stack/test_model_loading_race.py+++ b/packages/sie_server/tests/fake_stack/test_model_loading_race.py@@ -2,12 +2,15 @@Boots a real server with the fake bundle (zero downloads) and a slow-loadfault, then races concurrent first-touch requests into the cold model.-Characterizes both lazy-load lanes (#1726 asymmetry):-- rerank/score/generate: NON-BLOCKING — every racer gets a fast- 503 MODEL_LOADING with Retry-After; no request rides the load.-- /v1/embeddings: BLOCKING — the first touch holds the connection and- returns 200 only after the load completes.+Both lazy-load lanes are now NON-BLOCKING (the #1726 asymmetry is closed):++- rerank/score/generate: every racer gets a fast 503 MODEL_LOADING with+ Retry-After; no request rides the load.+- /v1/embeddings: the first touch also returns a fast 503 MODEL_LOADING+ with Retry-After instead of holding the connection through the cold+ load — single-node parity with the gateway's /v1/embeddings. Retrying+ eventually returns 200 once the model is resident."""from __future__ import annotations@@ -22,13 +25,19 @@ from .conftest import SLOW_LOAD_S as _SLOW_LOAD_Spytestmark = [pytest.mark.fake_stack, pytest.mark.integration]-# Raw httpx (not SIEClient) is deliberate here — AGENTS.md's raw-HTTP-# exception for debugging transport behavior applies: these tests assert the+# Raw httpx (not SIEClient) is deliberate here: these tests assert the# 503/Retry-After wire semantics that the SDK exists to hide (it auto-retries# MODEL_LOADING). The SDK-layer view of the same server lives in# test_sdk_surface.py.+def _assert_valid_retry_after(response: httpx.Response) -> None:+ """Every 503 MODEL_LOADING must carry a positive numeric Retry-After hint."""+ retry_after = {k.lower(): v for k, v in response.headers.items()}.get("retry-after")+ assert retry_after is not None, "MODEL_LOADING must carry a Retry-After hint"+ assert float(retry_after) > 0, f"Retry-After must be positive, got {retry_after!r}"++def _rerank_once(base: str) -> httpx.Response:return httpx.post(f"{base}/v1/rerank",@@ -69,17 +78,48 @@ def test_model_loading_race_nonblocking_lane(fake_server: str) -> None:assert len(body["results"]) == 1-def test_model_loading_blocking_embeddings_lane(fake_server: str) -> None:- """The /v1/embeddings first touch BLOCKS through the cold load (the- documented asymmetry): one request, ~slow-load latency, straight 200.+def test_model_loading_nonblocking_embeddings_lane(fake_server: str) -> None:+ """The /v1/embeddings first touch is NON-BLOCKING: it returns a FAST 503+ MODEL_LOADING with a Retry-After hint (OpenAI-shaped body on this surface)+ instead of riding the cold load, then a retry loop returns 200 once the+ model is resident — mirroring the rerank/score cold-load lanes.++ This is the regression guard for the usability fix: the previous+ behavior blocked the connection through the whole slow load and returned+ a straight 200, which this test used to assert. See PR #3183."""start = time.monotonic()- response = httpx.post(+ first = httpx.post(f"{fake_server}/v1/embeddings",json={"model": "sie-fake", "input": ["hello"]},timeout=_SLOW_LOAD_S * 10,)- elapsed = time.monotonic() - start- assert response.status_code == 200, response.text- assert elapsed >= _SLOW_LOAD_S * 0.9, "blocking lane must ride the cold load"+ first_touch_s = time.monotonic() - start++ # Fast, retryable 503 — the request must NOT have ridden the cold load.+ assert first.status_code == 503, first.text+ assert first_touch_s < _SLOW_LOAD_S, "non-blocking lane must not ride the cold load"+ _assert_valid_retry_after(first)+ # Top-level OpenAI-shaped envelope on this surface: {"error": {...}} (#3184).+ error = first.json()["error"]+ assert error["code"] == "MODEL_LOADING", first.text+ assert error["type"] == "server_error"++ # Retrying (as the SDK does transparently) eventually succeeds once loaded.+ deadline = time.monotonic() + _SLOW_LOAD_S * 10+ while True:+ response = httpx.post(+ f"{fake_server}/v1/embeddings",+ json={"model": "sie-fake", "input": ["hello"]},+ timeout=_SLOW_LOAD_S * 10,+ )+ if response.status_code == 200:+ break+ assert response.status_code == 503, response.text+ assert response.json()["error"]["code"] == "MODEL_LOADING", response.text+ # Retry-After must be present and valid on EVERY 503, not just the first.+ _assert_valid_retry_after(response)+ if time.monotonic() >= deadline:+ pytest.fail("model never finished loading")+ time.sleep(0.5)assert len(response.json()["data"][0]["embedding"]) == 384diff --git a/packages/sie_server/tests/fake_stack/test_registry_races.py b/packages/sie_server/tests/fake_stack/test_registry_races.pyindex 97c6fcf9d..5e2dcec7c 100644--- a/packages/sie_server/tests/fake_stack/test_registry_races.py+++ b/packages/sie_server/tests/fake_stack/test_registry_races.py@@ -114,18 +114,26 @@ async def test_concurrent_cross_model_load_under_pressure(monkeypatch: pytest.Mo# -- Scenario: teardown hang -------------------------------------------------------async def test_teardown_hang_starves_event_loop_but_leaves_no_ghost(+async def test_teardown_hang_does_not_starve_event_loop_and_leaves_no_ghost(monkeypatch: pytest.MonkeyPatch,) -> None:"""Characterizes the unload/teardown seam (#1600 ghost-model class,- registry.py:1280-1310). Pinned current contract, measured with a real- hung ``unload()``: ``adapter.unload()`` runs synchronously ON the event- loop inside ``_do_unload``, so a hung teardown starves the ENTIRE loop- for the hang duration — no other request, health probe, or residency op- can run. Pinned so a future fix (unload in a thread) flips this- assertion consciously. Post-conditions: the eviction completes, the- model is fully unregistered (no ghost accounting), and the registry- accepts new loads immediately.+ registry.py:1280-1310), measured with a real hung ``unload()``.++ **This is the conscious flip the previous version of this test asked+ for.** It used to assert the opposite — that a hung teardown starves+ the ENTIRE event loop, because ``adapter.unload()`` ran synchronously+ on it inside ``_do_unload`` — and said so explicitly: "pinned so a+ future fix (unload in a thread) flips this assertion consciously".+ That fix moves teardown onto a worker thread, so the event loop remains+ schedulable while teardown hangs.++ Everything else about the contract is unchanged and still asserted:+ the hang is really exercised (the eviction still takes the full+ teardown duration, because the load lock is deliberately still held+ across it), the eviction completes, the model is fully unregistered+ with no ghost accounting, and the registry accepts new loads+ immediately afterwards."""monkeypatch.setenv(SIE_FAKE_MEMORY_BUDGET_ENV, "1GiB")monkeypatch.setenv(@@ -136,35 +144,44 @@ async def test_teardown_hang_starves_event_loop_but_leaves_no_ghost(await registry.load_async("sie-fake", device="cpu")await registry.load_async("sie-fake:small-a", device="cpu")- # Heartbeat task: measures the longest gap between loop iterations while- # the eviction runs. A blocked loop shows up as one giant gap.- max_gap = 0.0+ # Heartbeat task: counts loop iterations completed while the eviction+ # runs. A blocked loop simply stops counting.+ #+ # Counting beats rather than measuring the largest inter-wakeup gap is+ # deliberate. The gap is a max over a noisy sample: a busy CI runner+ # produced 0.61 s on a *healthy* loop here, which is meaningless as a+ # signal but sits well inside any threshold tight enough to catch the+ # 1 s block. The count is cumulative, so one scheduler hiccup barely+ # moves it and the two populations stay decisively apart.+ beats = 0async def _heartbeat() -> None:- nonlocal max_gap- last = time.monotonic()+ nonlocal beatswhile True:await asyncio.sleep(0.01)- now = time.monotonic()- max_gap = max(max_gap, now - last)- last = now+ beats += 1beat = asyncio.create_task(_heartbeat())await asyncio.sleep(0.05) # let the heartbeat establish a baseline+ beats = 0# Evicting from embed's perspective selects generate (the LRU) — whose- # teardown hangs 1 s, synchronously, on the loop.+ # teardown hangs 1 s, now on a worker thread rather than on the loop.start = time.monotonic()result = await registry.evict_lru_excluding("sie-fake:small-a", timeout_s=5.0)elapsed = time.monotonic() - start- # Give the heartbeat one post-hang wakeup so the starvation gap is- # recorded before we cancel it (the main coroutine resumes first).- await asyncio.sleep(0.05)+ # Cancelled immediately, with no settling sleep: every beat counted+ # below was therefore serviced *during* the hang, which is the whole+ # question. A post-eviction wakeup would credit the blocked case too.beat.cancel()assert result is EvictionResult.EVICTEDassert elapsed >= 1.0, "the teardown hang must actually be exercised"- assert max_gap >= 0.9, "characterization: a hung sync unload starves the event loop today"+ # The flip. On the loop, the 1 s teardown yields nothing at all and+ # this lands at 0; off the loop the heartbeat keeps its ~10 ms cadence+ # for the whole second and lands near 100. The threshold sits an order+ # of magnitude from both, so a loaded runner cannot flake it.+ assert beats >= 20, f"a hung unload must no longer starve the event loop ({beats} beats during {elapsed:.2f}s)"manager = registry.memory_manager# No ghost: the hung teardown still unregisters its memory accounting.diff --git a/packages/sie_server/tests/observability/test_generation_diagnostics.py b/packages/sie_server/tests/observability/test_generation_diagnostics.pyindex d9965a755..86bc2211e 100644--- a/packages/sie_server/tests/observability/test_generation_diagnostics.py+++ b/packages/sie_server/tests/observability/test_generation_diagnostics.py@@ -48,6 +48,7 @@ def test_typed_generation_events_emit_bounded_contract_points(reader, _ = active_generationtelemetry = wt.worker_telemetry()telemetry.first_token_observed(model="catalog/gen", grammar="json_schema", duration_s=0.25)+ telemetry.worker_wait_observed(model="catalog/gen", grammar="json_schema", duration_s=0.75)telemetry.stream_finished(model="catalog/gen",grammar="json_schema",@@ -77,7 +78,11 @@ def test_typed_generation_events_emit_bounded_contract_points(by_name = _metric_map(reader.get_metrics_data())assert set(by_name) == wt.generation_metric_names()- for name in (wt.GENERATION_TTFT_METRIC_NAME, wt.GENERATION_TPOT_METRIC_NAME):+ for name in (+ wt.GENERATION_TTFT_METRIC_NAME,+ wt.GENERATION_WORKER_WAIT_METRIC_NAME,+ wt.GENERATION_TPOT_METRIC_NAME,+ ):point = _points(by_name[name])[0]assert tuple(point.explicit_bounds) == wt.TTFT_TPOT_BUCKETS_Sassert dict(point.attributes) == {diff --git a/packages/sie_server/tests/observability/test_worker_telemetry.py b/packages/sie_server/tests/observability/test_worker_telemetry.pyindex 9e64f7590..643960aa6 100644--- a/packages/sie_server/tests/observability/test_worker_telemetry.py+++ b/packages/sie_server/tests/observability/test_worker_telemetry.py@@ -557,6 +557,7 @@ def test_metric_inventory_is_exact() -> None:"sie.worker.scheduler.adaptive.p50","sie.worker.scheduler.starvation.resets","sie.worker.generation.ttft",+ "sie.worker.generation.worker_wait","sie.worker.generation.tpot","sie.worker.generation.tokens","sie.worker.generation.inflight",diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.pyindex 698617c77..8dc1b7c91 100644--- a/packages/sie_server/tests/processors/test_streaming.py+++ b/packages/sie_server/tests/processors/test_streaming.py@@ -236,6 +236,14 @@ async def test_streaming_publishes_per_chunk_with_terminal(monkeypatch: pytest.M# ACK happened.msg.ack.assert_awaited()_assert_one_generation_completion(telemetry, outcome="success")+ # Worker-side phase boundary (#3136): one worker-wait observation per+ # dispatched request, labeled with the grammar mode ("none" here) so the+ # structured-output stall decomposes into worker wait vs engine TTFT.+ telemetry.worker_wait_observed.assert_called_once()+ wait_kwargs = telemetry.worker_wait_observed.call_args.kwargs+ assert wait_kwargs["model"] == "test/model"+ assert wait_kwargs["grammar"] == "none"+ assert wait_kwargs["duration_s"] >= 0@pytest.mark.asyncio@@ -993,6 +1001,33 @@ async def test_grammar_compile_runs_once_per_schema(monkeypatch: pytest.MonkeyPaassert len(calls) == 1, f"expected exactly one compile, got {len(calls)}"+async def test_worker_wait_phase_is_labeled_with_grammar_mode(monkeypatch: pytest.MonkeyPatch) -> None:+ """Grammar dispatches stamp their kind on the worker-wait phase metric so+ the #3136 structured-output stall decomposes by cohort.+ """+ telemetry = _capture_worker_completion(monkeypatch)+ script = [+ GenerationChunk(text_delta="ok", is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=1, completion_tokens=1),+ ]+ nc = AsyncMock()+ proc = StreamingProcessor(nc=nc, registry=_make_registry(_FakeGenAdapter(script)), worker_id="w1")++ grammar_payload = {+ "kind": "json_schema",+ "value": {"type": "object", "properties": {"x": {"type": "integer"}}},+ }+ wi = _make_work_item(generate={"prompt": "Hi", "max_new_tokens": 8, "grammar": grammar_payload})+ await proc.process(_make_msg(wi), "test/model")++ telemetry.worker_wait_observed.assert_called_once()+ kwargs = telemetry.worker_wait_observed.call_args.kwargs+ assert kwargs["model"] == "test/model"+ assert kwargs["grammar"] == "json_schema"+ assert kwargs["duration_s"] >= 0++@pytest.mark.asyncioasync def test_grammar_compile_timeout_surfaces_grammar_compile_failed(monkeypatch: pytest.MonkeyPatch,diff --git a/packages/sie_server/tests/test_all_models.py b/packages/sie_server/tests/test_all_models.pyindex 0ccb21ca4..e8b1578f1 100644--- a/packages/sie_server/tests/test_all_models.py+++ b/packages/sie_server/tests/test_all_models.py@@ -223,7 +223,7 @@ def test_google_embeddinggemma_300m_dense() -> None:# Architecture support: ``Gemma3TextModel`` requires transformers>=4.56.# Older versions raise ImportError/ValueError during ``AutoModel.from_pretrained``;# gate the test rather than letting numerical-equivalence drift mask the- # underlying problem (sie-test#85).+ # underlying problem.pytest.importorskip("transformers", minversion="4.56.0")# Reference is the sentence-transformers pipeline output (incl. the Dense# projection head) for "test" encoded as a document, on CPU/fp32.diff --git a/packages/sie_server/tests/test_cli_log_level.py b/packages/sie_server/tests/test_cli_log_level.pynew file mode 100644index 000000000..9fe5ca6f0--- /dev/null+++ b/packages/sie_server/tests/test_cli_log_level.py@@ -0,0 +1,92 @@+"""`sie-server serve --log-level` rejects a typo instead of ignoring it.++The parameter is bound to both a flag and `SIE_LOG_LEVEL`, and the two get+different treatment on purpose: a typed flag is an immediate, cheap-to-fix+mistake, while a bad environment value comes from a rendered Helm value and+must not crash-loop a pod.+"""++from __future__ import annotations++from typing import Any++import pytest+from sie_server import cli+from typer.testing import CliRunner+++def no_server(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:+ """Stub the server so `serve` returns instead of binding a port."""+ started: dict[str, Any] = {}++ def fake_run_server(**kwargs: Any) -> None:+ started["kwargs"] = kwargs++ monkeypatch.setattr(cli, "run_server", fake_run_server)+ monkeypatch.delenv("SIE_LOG_LEVEL", raising=False)+ monkeypatch.delenv("SIE_PRELOAD_MODELS", raising=False)+ monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)+ monkeypatch.delenv("SIE_EXTRA_MODELS", raising=False)+ return started+++def test_invalid_flag_is_rejected_before_startup(no_server: dict[str, Any]) -> None:+ """A mistyped flag must not start a server that silently ignores it."""+ result = CliRunner().invoke(cli.app, ["serve", "--log-level", "DEBIG"])++ assert result.exit_code == 1+ assert "Invalid --log-level 'DEBIG'" in result.output+ # The error must name the levels that would have worked.+ assert "DEBUG" in result.output+ assert "kwargs" not in no_server, "server started despite an invalid log level"+++def test_undocumented_level_name_is_rejected(no_server: dict[str, Any]) -> None:+ """NOTSET resolves in Python's mapping but is not an advertised level."""+ result = CliRunner().invoke(cli.app, ["serve", "--log-level", "NOTSET"])++ assert result.exit_code == 1+ assert "Invalid --log-level 'NOTSET'" in result.output+++def test_invalid_environment_value_does_not_stop_the_server(+ no_server: dict[str, Any], monkeypatch: pytest.MonkeyPatch+) -> None:+ """A bad SIE_LOG_LEVEL degrades loudly; it must never crash-loop a pod."""+ monkeypatch.setenv("SIE_LOG_LEVEL", "DEBIG")++ result = CliRunner().invoke(cli.app, ["serve"])++ assert result.exit_code == 0, result.output+ assert "kwargs" in no_server, "an environment typo prevented startup"+ # configure_logging reports it and falls back.+ assert no_server["kwargs"]["uvicorn_log_level"] == "info"+++def test_verbose_wins_over_an_invalid_environment_value(+ no_server: dict[str, Any], monkeypatch: pytest.MonkeyPatch+) -> None:+ """--verbose must still reach DEBUG regardless of a stale env value."""+ monkeypatch.setenv("SIE_LOG_LEVEL", "garbage")++ result = CliRunner().invoke(cli.app, ["serve", "--verbose"])++ assert result.exit_code == 0, result.output+ assert no_server["kwargs"]["uvicorn_log_level"] == "debug"+++def test_valid_flag_starts_normally(no_server: dict[str, Any]) -> None:+ result = CliRunner().invoke(cli.app, ["serve", "--log-level", "warning"])++ assert result.exit_code == 0, result.output+ assert no_server["kwargs"]["uvicorn_log_level"] == "warning"+++def test_valid_environment_value_starts_normally(no_server: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_LOG_LEVEL", "error")++ result = CliRunner().invoke(cli.app, ["serve"])++ assert result.exit_code == 0, result.output+ assert no_server["kwargs"]["uvicorn_log_level"] == "error"diff --git a/packages/sie_server/tests/test_docker_integration.py b/packages/sie_server/tests/test_docker_integration.pyindex 2106cfd86..734b655f1 100644--- a/packages/sie_server/tests/test_docker_integration.py+++ b/packages/sie_server/tests/test_docker_integration.py@@ -6,8 +6,6 @@ These tests build and run the actual SIE Docker image to verify:- Model downloads work (cache directory permissions)- Basic inference works-Regression test for: https://github.com/superlinked/sie-internal/issues/10-Run with: pytest -m "docker""""diff --git a/packages/sie_server/tests/test_documented_model_ids.py b/packages/sie_server/tests/test_documented_model_ids.pynew file mode 100644index 000000000..1e182252c--- /dev/null+++ b/packages/sie_server/tests/test_documented_model_ids.py@@ -0,0 +1,101 @@+"""Model ids in user-facing examples must exist in the shipped catalog.++An example is a promise that the snippet runs. The registry matches ids+exactly — ``has_model`` is ``name in self._configs``, keyed by each config's+``sie_id`` — and there is no short-name aliasing, so an example that drops the+org prefix (``bge-m3`` for ``BAAI/bge-m3``) does not degrade: it 404s.++This guards the copy-paste path in both SDKs and the docs. It deliberately+scans only calls on a ``client`` receiver, so ``"text".encode("utf-8")`` and+similar non-SIE calls are not mistaken for model ids.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest+import yaml++_REPO_ROOT = Path(__file__).parents[3]+_MODELS_DIR = _REPO_ROOT / "packages" / "sie_server" / "models"++# Only calls on a `client` receiver: `client.encode("X"`, `await client.score("X"`.+#+# The model id is frequently on the line after the open paren, and that line+# carries the surrounding block's continuation marker — `...` in a Python+# doctest, `*` in a JSDoc comment — which is not whitespace. Allowing for it is+# what makes multi-line examples visible to this guard at all.+_CLIENT_CALL = re.compile(+ r"""+ client \s* \. \s* (?: encode | score | extract | generate ) \s* \( \s*+ (?: \n [ \t]* (?: \* | \.\.\. | >>> | // )? [ \t]* )?+ ["'] ([^"'\n]+) ["']+ """,+ re.VERBOSE,+)++# Files whose examples a user is expected to copy and run.+_SCANNED = (+ "packages/sie_sdk/src",+ "packages/sie_ts_sdk/src",+ "integrations",+ "docs",+ "README.md",+)++_SUFFIXES = {".py", ".ts", ".md"}++# Placeholders that are obviously not catalog ids.+_PLACEHOLDERS = frozenset({"model", "MODEL", "your-model", "<model>"})+++def _catalog_ids() -> set[str]:+ ids: set[str] = set()+ for path in _MODELS_DIR.glob("*.yaml"):+ data = yaml.safe_load(path.read_text())+ if isinstance(data, dict) and isinstance(data.get("sie_id"), str):+ ids.add(data["sie_id"])+ return ids+++def _documented_ids() -> list[tuple[str, str]]:+ """(model_id, "path:line") for every model id in a documented client call."""+ found: list[tuple[str, str]] = []+ for rel in _SCANNED:+ root = _REPO_ROOT / rel+ if not root.exists():+ continue+ paths = [root] if root.is_file() else [p for p in root.rglob("*") if p.suffix in _SUFFIXES]+ for path in paths:+ if "__pycache__" in path.parts or "node_modules" in path.parts:+ continue+ try:+ text = path.read_text()+ except (OSError, UnicodeDecodeError):+ continue+ for match in _CLIENT_CALL.finditer(text):+ model_id = match.group(1)+ if model_id in _PLACEHOLDERS or any(ch in model_id for ch in "{}$<>"):+ continue+ line = text[: match.start()].count("\n") + 1+ found.append((model_id, f"{path.relative_to(_REPO_ROOT)}:{line}"))+ return found++[email protected](not _MODELS_DIR.is_dir(), reason="model catalog not present in this checkout")+def test_catalog_is_readable() -> None:+ """Guard the guard: an empty catalog would make the check below vacuous."""+ assert len(_catalog_ids()) > 100++[email protected](not _MODELS_DIR.is_dir(), reason="model catalog not present in this checkout")+def test_every_documented_model_id_exists() -> None:+ """A documented id that is not in the catalog 404s when copy-pasted."""+ catalog = _catalog_ids()+ documented = _documented_ids()+ assert documented, "scanner found no documented model ids — the pattern has rotted"++ unknown = sorted({f"{model_id!r} at {where}" for model_id, where in documented if model_id not in catalog})+ assert not unknown, "model ids in user-facing examples that are not in the catalog:\n " + "\n ".join(unknown)diff --git a/packages/sie_server/tests/test_metering_units.py b/packages/sie_server/tests/test_metering_units.pyindex 2cfa1bcd5..93a17a78b 100644--- a/packages/sie_server/tests/test_metering_units.py+++ b/packages/sie_server/tests/test_metering_units.py@@ -1819,7 +1819,9 @@ class TestVisionTextTokenStamp:# still derives its per-text counts from the shared base counter over# the processor tokenizer (the real metering path), returning matching# zero vectors; the image tower returns zero vectors.- adapter._encode_image_items = lambda items: np.zeros((len(items), 4), dtype=np.float32) # type: ignore[method-assign]+ adapter._encode_image_items = lambda items, item_indices: np.zeros( # type: ignore[method-assign]+ (len(items), 4), dtype=np.float32+ )def fake_encode_texts(texts: list[str]) -> tuple[Any, list[int] | None]:counts = adapter._token_counts_or_none(adapter._processor.tokenizer, list(texts), expected_len=len(texts))diff --git a/packages/sie_server/tests/test_model_yaml_filenames.py b/packages/sie_server/tests/test_model_yaml_filenames.pyindex bb7442b7d..085a3736b 100644--- a/packages/sie_server/tests/test_model_yaml_filenames.py+++ b/packages/sie_server/tests/test_model_yaml_filenames.py@@ -1,11 +1,10 @@"""Regression tests for model YAML filenames in packages/sie_server/models/.-sie_bench's `EvalRunner._get_local_model_info(model_name)` looks up a YAML by-converting `model_name` to `model_name.replace("/", "__").replace(":", "__") + ".yaml"`.+The model lookup contract maps a model name to+`model_name.replace("/", "__").replace(":", "__") + ".yaml"`.On a case-sensitive filesystem (Linux CI), any case mismatch between the filename-and `sie_id` makes the lookup return `{}`, which silently downgrades the-dispatched MTEB wrapper to text-only and trips the modality precheck. See-issue #1058.+and `sie_id` makes the lookup return `{}`, so instruction-aware callers cannot+load the model's modality metadata."""from __future__ import annotations@@ -40,11 +39,9 @@ def test_instruction_template_has_placeholder(yaml_path: Path) -> None:"""An ``Instruct:``-prefixed ``query_template`` must contain the ``{instruction}``placeholder.- Otherwise the eval harness's instruction gating- (``EvalRunner._model_uses_instruction``, added in #1432) treats the model as- non-instruction-following and silently drops the per-task MTEB prompt, so the- model is measured with a hardcoded generic instruction instead of each task's- instruction. This is the stella_en_*_v5 regression (#1340).+ Otherwise instruction-aware evaluation callers treat the model as+ non-instruction-following and silently drop the per-task prompt, so the model+ is measured with a hardcoded generic instruction instead of each task's."""with yaml_path.open() as f:config = yaml.safe_load(f) or {}@@ -62,6 +59,7 @@ def test_instruction_template_has_placeholder(yaml_path: Path) -> None:offenders.append(profile_name)assert not offenders, (f"{yaml_path.name}: profile(s) {offenders} hardcode an 'Instruct:' instruction "- f"without a '{{instruction}}' placeholder; the eval harness drops the per-task "- f"MTEB instruction (#1340). Use 'Instruct: {{instruction}}' + 'default_instruction'."+ f"without a '{{instruction}}' placeholder; instruction-aware evaluation "+ f"callers drop the per-task instruction. Use 'Instruct: {{instruction}}' + "+ f"'default_instruction'.")diff --git a/packages/sie_server/tests/test_openapi_export.py b/packages/sie_server/tests/test_openapi_export.pyindex a216315ab..0ce3d4808 100644--- a/packages/sie_server/tests/test_openapi_export.py+++ b/packages/sie_server/tests/test_openapi_export.py@@ -170,6 +170,45 @@ def test_openapi_audio_timestamp_contract() -> None:assert granularities["items"]["enum"] == ["word", "segment"]+def test_openapi_documents_media_bytes_as_base64_strings() -> None:+ """Every media `data` field advertises the one JSON encoding the API accepts.++ On the JSON path msgspec base64-decodes `data` (matching the msgpack+ path's native binary), so the schema has to say `contentEncoding: base64`.+ Pydantic's default rendering of `bytes` is `format: binary`, which in+ OpenAPI means raw octets -- a generated client that believed it would send+ bytes that never decode.+ """+ result = runner.invoke(app, ["openapi"])+ assert result.exit_code == 0, result.output+ schemas = json.loads(result.output)["components"]["schemas"]+ for name in ["ImageInputModel", "AudioInputModel", "VideoInputModel", "DocumentInputModel"]:+ data = schemas[name]["properties"]["data"]+ assert data["type"] == "string", f"{name}.data must be a string: {data}"+ assert data["contentEncoding"] == "base64", f"{name}.data must declare base64 encoding: {data}"+ assert "format" not in data, f"{name}.data must not claim `format` (binary means raw octets): {data}"+++def test_openapi_documents_positive_audio_sample_rate() -> None:+ """`sample_rate` must advertise the positive bound the preprocessor enforces."""+ result = runner.invoke(app, ["openapi"])+ assert result.exit_code == 0, result.output+ schemas = json.loads(result.output)["components"]["schemas"]+ sample_rate = schemas["AudioInputModel"]["properties"]["sample_rate"]+ integer_branch = next(branch for branch in sample_rate["anyOf"] if branch.get("type") == "integer")+ assert integer_branch["exclusiveMinimum"] == 0, f"sample_rate must be positive: {sample_rate}"+++def test_openapi_item_accepts_all_media_inputs() -> None:+ """The item schema exposes every media input the worker `Item` accepts."""+ result = runner.invoke(app, ["openapi"])+ assert result.exit_code == 0, result.output+ schemas = json.loads(result.output)["components"]["schemas"]+ properties = schemas["ItemModel"]["properties"]+ for field in ["images", "audio", "video", "document"]:+ assert field in properties, f"ItemModel must document `{field}`"++def test_openapi_output_file(tmp_path: Path) -> None:"""CLI writes spec to a file when --output is given."""out = tmp_path / "spec.json"diff --git a/packages/sie_server/tests/test_sparse_integration.py b/packages/sie_server/tests/test_sparse_integration.pyindex 1d03aa37b..436097b97 100644--- a/packages/sie_server/tests/test_sparse_integration.py+++ b/packages/sie_server/tests/test_sparse_integration.py@@ -4,7 +4,7 @@ These tests validate that SIE's sparse adapter produces outputs that matchsentence-transformers SparseEncoder directly.Requires: Real model weights (downloaded on first run)-Mark: integration (run with `mise run test -m integration`)+Mark: integration (run with `mise run test -- -i packages/sie_server/tests/test_sparse_integration.py`)"""import numpy as npdiff --git a/packages/sie_server/tests/type_defs/test_decode_image.py b/packages/sie_server/tests/type_defs/test_decode_image.pynew file mode 100644index 000000000..225a1448f--- /dev/null+++ b/packages/sie_server/tests/type_defs/test_decode_image.py@@ -0,0 +1,87 @@+"""Tests for the shared image decoder ``decode_image``.++``decode_image`` is the single seam every user-input ``PIL.Image.open`` routes+through. Valid base64 that is NOT decodable image bytes used to raise PIL's+``UnidentifiedImageError`` (an ``OSError`` subclass), which missed the+``ValueError`` -> 400 INVALID_INPUT mapping and surfaced as a 500+``INFERENCE_ERROR`` leaking a ``BytesIO`` repr. The helper must raise a typed+``InvalidMediaError`` whose message names the offending field in the same+JSON-path style msgspec uses for corrupt base64+("Invalid base64 encoded string - at `$.items[0].images[0].data`").+"""++import io++import pytest+from PIL import Image as PILImage+from sie_server.types.inputs import InvalidMediaError, decode_image++_NOT_AN_IMAGE = b"valid base64 decoded to these bytes, but they are not an image"+++def _png_bytes(mode: str, size: tuple[int, int] = (7, 5)) -> bytes:+ buf = io.BytesIO()+ PILImage.new(mode, size).save(buf, format="PNG")+ return buf.getvalue()+++class TestDecodeImageAccepts:+ """Decodable payloads come back as RGB PIL images."""++ def test_rgb_passthrough_preserves_size(self) -> None:+ img = decode_image({"data": _png_bytes("RGB", (7, 5))})+ assert img.mode == "RGB"+ assert img.size == (7, 5)++ def test_converts_grayscale_to_rgb(self) -> None:+ img = decode_image({"data": _png_bytes("L", (4, 9))})+ assert img.mode == "RGB"+ assert img.size == (4, 9)++ def test_converts_rgba_to_rgb(self) -> None:+ img = decode_image({"data": _png_bytes("RGBA", (3, 3))})+ assert img.mode == "RGB"+++class TestDecodeImageRejectsUndecodable:+ """Non-image bytes raise InvalidMediaError (-> 400), never an OSError 500."""++ def test_non_image_bytes_raise_invalid_media(self) -> None:+ with pytest.raises(InvalidMediaError, match="image data is not a decodable image"):+ decode_image({"data": _NOT_AN_IMAGE})++ def test_message_has_wildcard_json_path_without_indices(self) -> None:+ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[\*\]\.images\[\*\]\.data`"):+ decode_image({"data": _NOT_AN_IMAGE})++ def test_message_names_item_and_image_index_when_known(self) -> None:+ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[2\]\.images\[1\]\.data`"):+ decode_image({"data": _NOT_AN_IMAGE}, item_index=2, image_index=1)++ def test_message_never_leaks_a_bytesio_repr(self) -> None:+ with pytest.raises(InvalidMediaError) as excinfo:+ decode_image({"data": _NOT_AN_IMAGE}, item_index=0, image_index=0)+ assert "BytesIO" not in str(excinfo.value)++ def test_truncated_image_bytes_raise_invalid_media(self) -> None:+ # A valid header with the tail cut off decodes lazily in PIL; the+ # eager load() must surface it as the same typed error.+ truncated = _png_bytes("RGB", (32, 32))[:40]+ with pytest.raises(InvalidMediaError, match="not a decodable image"):+ decode_image({"data": truncated})++ def test_error_is_a_value_error(self) -> None:+ """ValueError subclassing is what routes it to HTTP 400 INVALID_INPUT."""+ assert issubclass(InvalidMediaError, ValueError)+++class TestDecodeImageRejectsNonBytes:+ """The media_bytes contract still applies before any PIL decode."""++ def test_str_data_is_rejected(self) -> None:+ with pytest.raises(InvalidMediaError, match="image data must be bytes, got str"):+ decode_image({"data": "aGVsbG8="})++ def test_missing_data_is_rejected(self) -> None:+ with pytest.raises(InvalidMediaError):+ decode_image({})diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex 0c0844868..91f663bde 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.7.1"+version = "0.7.2"edition = "2021"publish = falsedescription = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."@@ -15,7 +15,7 @@ path = "src/main.rs"[dependencies]sie-audio-prep = { path = "../sie_audio_prep", features = ["msgpack"] }-# Shared OTLP transport/proxy/resource/propagation plumbing (#2339).+# Shared OTLP transport/proxy/resource/propagation plumbing.sie-telemetry = { path = "../sie_telemetry" }tokio = { version = "1", features = ["full"] }async-nats = "0.49"@@ -24,7 +24,7 @@ futures-util = "0.3"serde = { version = "1", features = ["derive"] }# `float_roundtrip` switches serde_json to its IEEE-754 correctly-rounded# f64 parser. Required for bit-exact parity with the Python adaptive-# controller in `scripts/perf/replay-scheduler-trace.py` — without it,+# controller exercised by `examples/replay_controller_trace.rs` — without it,# serde_json's default "fast" parser can be 1 ULP off for some decimals# (e.g. "14.394267984578837" parses 1 bit low), which breaks the# shadow-trace ULP diff. Do not drop this feature.@@ -71,7 +71,7 @@ tracing-opentelemetry = "0.33"async-trait = "0.1"bytes = "1"uuid = { version = "1", features = ["v4"] }-reqwest = { version = "0.13", default-features = false, features = ["blocking", "json", "rustls"] }+reqwest = { version = "0.13", default-features = false, features = ["blocking", "json", "rustls", "stream"] }rustls = { version = "0.23", default-features = false, features = ["ring"] }rustix = { version = "1", features = ["fs"] }@@ -79,10 +79,15 @@ rustix = { version = "1", features = ["fs"] }hyper = { version = "1", features = ["server", "http1"] }hyper-util = { version = "0.1", features = ["tokio"] }http-body-util = "0.1"+http = "1"# Cloud payload store backends (opt-in, same shape as gateway)object_store = { version = "0.14", optional = true, features = ["aws", "gcp", "azure"] }url = { version = "2", optional = true }+reqsign-aliyun-oss = { version = "=3.1.5", optional = true }+reqsign-core = { version = "=3.3.1", optional = true }+reqsign-file-read-tokio = { version = "=3.0.6", optional = true }+reqsign-http-send-reqwest = { version = "=4.0.6", optional = true }# HF fast-tokenizers. Used by `src/tokenize/` to verify the# adapter-provided `tokenizer.json` materialised at the path@@ -99,10 +104,18 @@ blake3 = "1"[features]default = []-cloud-storage = ["dep:object_store", "dep:url"]+cloud-storage = [+ "dep:object_store",+ "dep:reqsign-aliyun-oss",+ "dep:reqsign-core",+ "dep:reqsign-file-read-tokio",+ "dep:reqsign-http-send-reqwest",+ "dep:url",+][dev-dependencies]tempfile = "3"+wiremock = "0.6"# `testing` unlocks the in-memory exporter used to verify exact canonical metric# names, types, units, and bounded attributes without a live collector.opentelemetry_sdk = { version = "0.32", features = ["testing"] }diff --git a/packages/sie_server_sidecar/Dockerfile b/packages/sie_server_sidecar/Dockerfileindex 9351386db..96eb27c44 100644--- a/packages/sie_server_sidecar/Dockerfile+++ b/packages/sie_server_sidecar/Dockerfile@@ -9,12 +9,12 @@# The published image is ghcr.io/superlinked/sie-server-sidecar; the runtime# binary inside the image is /sie-server-sidecar.#-# The build runs at the Cargo workspace root (#2339): the root+# The build runs at the Cargo workspace root: the root# Cargo.toml/Cargo.lock plus every member's manifest+sources must be present# for cargo to load the workspace, and the binary is selected with# `-p sie-server-sidecar`.#-# The only Cargo feature today is `cloud-storage` (S3/GCS payload modes),+# The only Cargo feature today is `cloud-storage` (S3/GCS/Azure/OSS payload modes),# which is the default for `ARG FEATURES` below. CI can override with# `--build-arg FEATURES=` if you want a leaner build with no remote# payload support.@@ -131,4 +131,4 @@ ENTRYPOINT ["/sie-server-sidecar"]LABEL org.opencontainers.image.title="sie-server-sidecar" \org.opencontainers.image.description="SIE server sidecar - NATS JetStream consumer + Python IPC forwarder." \- org.opencontainers.image.source="https://github.com/superlinked/sie-internal"+ org.opencontainers.image.source="https://github.com/superlinked/sie"diff --git a/packages/sie_server_sidecar/README.md b/packages/sie_server_sidecar/README.mdindex f5f2fb7b1..95b3442f6 100644--- a/packages/sie_server_sidecar/README.md+++ b/packages/sie_server_sidecar/README.md@@ -38,5 +38,10 @@ authentication protocol. The listener restricts its socket node, validates adomain-separated request digest and route identity, caps frame/media/requestsizes, and rejects unresolved payload references.+With the `cloud-storage` feature, payload reads support S3, GCS, Azure Blob,+and native `oss://` Alibaba OSS Signature V4. OSS requires `SIE_OSS_REGION` and+uses explicit environment credentials or ACK RRSA OIDC only; node metadata,+profiles, and credential-file fallbacks are excluded.+See [`docs/architecture-guide.md`](docs/architecture-guide.md) for the runtimecontract and deployment caveats.diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 264ee959c..ffed2079d 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -15,8 +15,6 @@ gateway -> NATS JetStream -> worker-sidecar -> UDS IPC -> worker backendReferences:-- [Worker runtime](../../../product/design/worker-runtime.md)-- [Deployment topologies](../../../product/design/deployment-topologies.md)- [Gateway architecture guide](../../sie_gateway/docs/architecture-guide.md)- [Sidecar README](../README.md)@@ -231,7 +229,7 @@ The Rust and Python protocol copies define the same method names:- `ReplaceModelConfigs`- `Drain`-`tools/ci/check_ipc_types_parity.py` checks the Rust protocol schema against+`tools/check_ipc_types_parity.py` checks the Rust protocol schema against`packages/sie_server/src/sie_server/ipc_types.py`.Non-streaming backend responses use one physical frame while the serialized@@ -318,6 +316,12 @@ pins the configured directory and uses `openat2` without symlink traversal.Non-Linux hosts, kernels older than 5.6, and sandboxes that block `openat2` failclosed; cloud object-store payload resolution is unaffected.+Alibaba `oss://` payload references use a native region-scoped Signature V4+client. It accepts only a safe plain key or the exact full reference below the+configured bucket/prefix, derives the public or VPC-internal HTTPS endpoint from+`SIE_OSS_REGION`, and authenticates with explicit environment credentials or+ACK RRSA OIDC. ECS metadata and file/profile credential sources are absent.+The backend retokenizes when prepared tokens are absent or the tokenizer hashdoes not match. Score pair construction stays backend-owned. Extracttokenization stays backend-owned.@@ -452,6 +456,6 @@ Source: [`config_subscriber.rs`](../src/config_subscriber.rs),- Package summary: [README](../README.md)- Helm values: [`deploy/helm/sie-cluster/values.yaml`](../../../deploy/helm/sie-cluster/values.yaml)- Runtime config parsing: [`config.rs`](../src/config.rs) and [`main.rs`](../src/main.rs)-- IPC schema parity check: [`tools/ci/check_ipc_types_parity.py`](../../../tools/ci/check_ipc_types_parity.py)-- response-chunk v1 envelope/limit pin: [`tools/ci/check_response_chunk_protocol.py`](../../../tools/ci/check_response_chunk_protocol.py)+- IPC schema parity check: [`tools/check_ipc_types_parity.py`](../../../tools/check_ipc_types_parity.py)+- response-chunk v1 envelope/limit pin: [`tools/check_response_chunk_protocol.py`](../../../tools/check_response_chunk_protocol.py)- Gateway queue contract: [gateway architecture guide](../../sie_gateway/docs/architecture-guide.md)diff --git a/packages/sie_server_sidecar/examples/replay_controller_trace.rs b/packages/sie_server_sidecar/examples/replay_controller_trace.rsindex 77ee3bf35..32ed45abc 100644--- a/packages/sie_server_sidecar/examples/replay_controller_trace.rs+++ b/packages/sie_server_sidecar/examples/replay_controller_trace.rs@@ -2,9 +2,9 @@//! [`AdaptiveBatchController`] and emit one `step` output per line on//! stdout.//!-//! Used by `scripts/perf/replay-scheduler-trace.py` to validate that-//! the Rust controller produces byte-identical (actually ULP-identical)-//! outputs to Python on captured traces.+//! Used to validate that the Rust controller produces floating-point outputs+//! that are identical ULP-for-ULP to a reference implementation on captured+//! traces.//!//! ## Trace format (JSONL on stdin)//!diff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rsindex 2cb052495..77673eef3 100644--- a/packages/sie_server_sidecar/src/config.rs+++ b/packages/sie_server_sidecar/src/config.rs@@ -54,7 +54,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://…` / `abfs://…` /- /// `abfss://…` use cloud stores when built with `--features cloud-storage`.+ /// `abfss://…` / `oss://…` 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 bd9133969..e612f7f2c 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -63,7 +63,7 @@ const MODEL_LOADING_ERROR_CODE: &str = "MODEL_LOADING";/// executor reports [`ReadinessState::Failed`] (registry holds a PERMANENT/// `LoadFailure`). The gateway maps this code to a typed HTTP 502 via/// `build_model_load_failed_response` (unary/batch path) — the fast-path twin-/// of the #1786 `run_batch` mapping. Kept byte-identical to the gateway+/// of the `run_batch` mapping. Kept byte-identical to the gateway/// constant `sie_gateway::handlers::proxy::MODEL_LOAD_FAILED_ERROR_CODE` and/// the Python `ErrorCode.MODEL_LOAD_FAILED`.const MODEL_LOAD_FAILED_ERROR_CODE: &str = "MODEL_LOAD_FAILED";@@ -759,6 +759,13 @@ impl Dispatcher {let state = Arc::new(Mutex::new(LocalGenerateState::default()));let callback_state = Arc::clone(&state);+ // The local-ingest streaming lane's execution-commit point, past its+ // own bundle-hash barrier above. Local ingest bypasses the broker, so+ // these observations are normally near zero — which is the correct+ // answer for this lane, not a reason to omit it. Omitting it would+ // rebuild the blind spot this metric was fixed for: a generation path+ // that executes real work and reports nothing.+ record_work_item_ages(&self.runtime_state.telemetry, std::iter::once(&wi));let _inflight_guard = InflightBatchGuard::enter(Arc::clone(&self.runtime_state));let result = self.worker_pool@@ -1439,7 +1446,7 @@ impl Dispatcher {}ReadinessState::Failed => {// Terminal load failure (permanent cooldown). Re-driving would- // hang the streaming client forever (#1786 fast-path gap), so+ // hang the streaming client forever, so// publish a terminal MODEL_LOAD_FAILED chunk + ACK — the// gateway's streaming collector maps the code to a typed// failure exactly like the batch path.@@ -1736,6 +1743,11 @@ impl Dispatcher {let msg_for_events = Arc::clone(&msg);let delivery_log_for_events = Arc::clone(&delivery_log);let telemetry_for_events = self.runtime_state.telemetry.clone();+ // Generation's execution-commit point. It never reaches+ // `apply_outcome`, so without this call the most expensive operation in+ // the system — and the one B2 singles out as excluded from+ // cancellation — would be entirely absent from the age distribution.+ record_work_item_ages(&self.runtime_state.telemetry, std::iter::once(&wi));self.runtime_state.inflight_batches.inc();let result = self.worker_pool@@ -1864,7 +1876,7 @@ impl Dispatcher {if readiness_resp.state == ReadinessState::Failed {// Terminal load failure (permanent cooldown on the Python// registry). Re-driving `EnsureModelReady` would loop forever- // and hang the client (#1786 fast-path gap), so dead-letter+ // and hang the client, so dead-letter// the whole group as `MODEL_LOAD_FAILED` — the gateway maps// that code to a typed 502, exactly like the batch/`run_batch`// path. ACK each item after publishing its error so JetStream@@ -2189,6 +2201,10 @@ impl Dispatcher {if resolved.is_empty() {return Ok(());}+ record_work_item_ages(+ &self.runtime_state.telemetry,+ resolved.iter().map(|(wi, _, _, _, _)| wi),+ );let batch_items: Vec<EncodeBatchItem> = resolved.iter()@@ -2353,6 +2369,10 @@ impl Dispatcher {if prepared.is_empty() {return Ok(());}+ record_work_item_ages(+ &self.runtime_state.telemetry,+ prepared.iter().map(|(wi, _, _, _, _)| wi),+ );// Rust-tokenisation wire-noop on score: Python's// `_process_single_score` does not consume `prepared_tokens`@@ -2544,6 +2564,10 @@ impl Dispatcher {if resolved.is_empty() {return Ok(());}+ record_work_item_ages(+ &self.runtime_state.telemetry,+ resolved.iter().map(|(wi, _, _, _, _)| wi),+ );let mut batch_items = Vec::with_capacity(resolved.len());for (wi, _, item, prepared_audio, fm) in &mut resolved {@@ -2714,6 +2738,11 @@ impl Dispatcher {Disposition::PublishAndAck | Disposition::PublishErrorAndAck => {if should_publish(&outcome.disposition) {let queue_ms = queue_ms_from(wi.timestamp);+ // NOTE: `sie.worker.work_item.age` is NOT recorded here.+ // It is recorded at each execution-commit point (see+ // [`record_work_item_ages`]) so that every operation shares+ // one definition and generation, which never reaches this+ // function, is not silently missing from the distribution.let timings = Some(Timings {queue_ms,payload_fetch_ms,@@ -2901,7 +2930,7 @@ impl Dispatcher {/// Dead-letter a whole (op, model) group on a TERMINAL load failure:/// publish a typed `MODEL_LOAD_FAILED` error `WorkResult` for every item/// and ACK it. This is the [`ReadinessState::Failed`] fast-path twin of- /// the batch/`run_batch` `MODEL_LOAD_FAILED` mapping (#1786) — the gateway+ /// the batch/`run_batch` `MODEL_LOAD_FAILED` mapping — the gateway/// turns the code into an HTTP 502 so the client fails fast instead of/// blocking while the sidecar re-drives a doomed model forever.///@@ -3694,6 +3723,79 @@ whereout}+/// Record the transport-queue age of every work item this worker is COMMITTING+/// TO EXECUTE, measured from the gateway publish timestamp on each envelope.+///+/// Call this at an execution-commit point: after the cancellation filter has+/// removed abandoned items, AFTER the bundle-config execution barrier, and+/// immediately before the batch (or the generation stream) is handed to the+/// backend. There are six such points — the three batch handlers, the scheduler+/// drain, the NATS generation lane, and the local-ingest generation lane — and+/// every one of them must call this, because `sie.worker.work_item.age` exists+/// to answer "how much work does this cluster execute after its client gave up"+/// and a missing path silently biases that distribution toward zero.+///+/// The barrier ordering is load-bearing in the other direction. A bundle-hash+/// change NAKs the whole batch without ever calling the backend, so recording+/// before the barrier would count redelivered work as executed. Hash changes+/// land during a config rollout, which is also when backlog builds, so that+/// over-count would land exactly where the number has to be trustworthy.+///+/// Age at execution START is deliberate, and it is the reason this is not+/// recorded next to the result publish in [`Dispatcher::apply_outcome`]:+///+/// - Generation never passes through `apply_outcome` at all. It streams from+/// its own task, so a publish-time observation would omit the single most+/// expensive operation to run for nobody — which is precisely the case the+/// measurement exists to size.+/// - Age at publish is age at execution start PLUS execution time. For an+/// embedding batch that difference is milliseconds, but for generation it is+/// tens of seconds, so mixing the two would make the per-operation+/// comparison meaningless.+/// - Age at execution start is the quantity a deadline check would actually+/// evaluate: it is what a worker knows at the instant it decides whether+/// spending GPU on this item is still worth anything.+///+/// Items that never execute are deliberately NOT observed: cancellation+/// ack-drops, payload-fetch failures, unknown-operation rejections,+/// bundle-hash mismatches, and NAK-for-redelivery all leave before this point.+/// Counting them would answer a different question ("how long do items sit in+/// the queue") with a series whose name promises this one. A NAK'd item that is+/// later redelivered and does execute is observed then, carrying its full age+/// since the original gateway publish, which is the correct and more alarming+/// number.+///+/// One caveat for readers of the resulting distribution: broker-delivered work+/// and local-ingest work share a series when one sidecar serves both. Local+/// ingest has no broker hop, so it contributes near-zero ages and pulls the p50+/// down. That is an accurate statement about the work this process ran, but it+/// is not a statement about broker staleness alone.+///+/// One clock read covers the whole batch: a 4096-item request would otherwise+/// pay 4096 `SystemTime::now()` calls for a diagnostic.+fn record_work_item_ages<'a>(+ telemetry: &crate::observability::metrics::SidecarTelemetry,+ items: impl IntoIterator<Item = &'a WorkItem>,+) {+ if !telemetry.is_enabled() {+ return;+ }+ let Ok(now) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) else {+ return;+ };+ let now_s = now.as_secs_f64();+ for wi in items {+ // A zero/absent publish timestamp has no measurable age. Recording 0+ // would plant a false spike in the lowest bucket rather than admitting+ // the envelope carried nothing. Negative and non-finite deltas (clock+ // skew) are dropped by the facade for the same reason.+ if wi.timestamp <= 0.0 {+ continue;+ }+ telemetry.work_item_age_observed(&wi.operation, now_s - wi.timestamp);+ }+}+fn queue_ms_from(timestamp_s: f64) -> f64 {if timestamp_s <= 0.0 {return 0.0;@@ -4647,6 +4749,20 @@ async fn process_scheduler_batch(None};+ // AFTER the config execution barrier above, not before it. The barrier can+ // still NAK the whole batch for a bundle-hash change, and a NAK'd batch+ // never reaches `run_batch` — counting it here would report work as+ // executed that was only redelivered. That matters more than it sounds:+ // hash changes land during a config rollout, which is also when backlog+ // builds, so the over-count would bias the distribution exactly under the+ // conditions B2 needs it to be trustworthy. The three batch handlers and+ // both generation paths clear their barrier before recording for the same+ // reason.+ record_work_item_ages(+ &dispatcher.runtime_state.telemetry,+ batch.metadata.iter().map(|meta| &meta.wi),+ );+// Capture this monotonic boundary immediately before the backend RPC. The// enqueue→dispatch histogram therefore includes time parked behind the// scheduler pipeline permit, config execution barrier, and local request@@ -5906,6 +6022,109 @@ mod tests {assert_eq!(truncate("café", 4), "café");}+ /// Every point that hands work to the backend must record work-item age.+ ///+ /// This is a tripwire for a real defect, not a style rule: the first+ /// version of `sie.worker.work_item.age` recorded only at the batch result+ /// publish, so generation — which streams from its own task and never+ /// reaches `apply_outcome` — was entirely absent from the distribution.+ /// The metric exists to size how much work runs after its client gave up,+ /// and generation is the most expensive case of exactly that, so the+ /// omission biased the number toward zero precisely where it mattered.+ ///+ /// Only production code is counted — the test module below calls the+ /// recorder too — and the needle is assembled at compile time so this test+ /// does not match itself.+ #[test]+ fn every_execution_commit_point_records_work_item_age() {+ let source = include_str!("dispatcher.rs");+ let production = source+ .split("\nmod tests {")+ .next()+ .expect("dispatcher.rs must have a production section");+ let needle = concat!("record_work_item_ages", "(");+ assert_eq!(+ production.matches(needle).count(),+ 6,+ "expected exactly six execution-commit call sites (encode, score, extract, \+ scheduler drain, NATS generate, local-ingest generate). If you added a path that \+ hands work to the backend, record the age there too and update this count — a \+ missing path silently biases sie.worker.work_item.age toward zero for that \+ operation."+ );+ }++ /// Every recording site must sit AFTER its bundle-config execution+ /// barrier, because a hash mismatch NAKs the batch without ever calling the+ /// backend. Recording first would count redelivered work as executed, and+ /// hash changes land during config rollouts — exactly when backlog builds+ /// and the number has to be trustworthy.+ ///+ /// Checked structurally rather than by driving each handler: the ordering+ /// is the invariant, and a positional assertion catches a future+ /// reordering that a behavioural test on one handler would miss.+ #[test]+ fn work_item_age_is_recorded_after_every_config_execution_barrier() {+ let source = include_str!("dispatcher.rs");+ let production = source+ .split("\nmod tests {")+ .next()+ .expect("dispatcher.rs must have a production section");+ let record = concat!("record_work_item_ages", "(");+ let barrier = concat!("unknown_bundle_config_hash", "(");+ let accepts = concat!("accepts_bundle_config_hash", "(");++ // Pair each barrier with the next recording site and require that the+ // barrier comes first. Five of the six sites sit behind a barrier; the+ // sixth (local-ingest generate) uses the `accepts_` spelling.+ let mut barriers: Vec<usize> = production.match_indices(barrier).map(|(i, _)| i).collect();+ barriers.extend(production.match_indices(accepts).map(|(i, _)| i));+ barriers.sort_unstable();+ let records: Vec<usize> = production.match_indices(record).map(|(i, _)| i).collect();+ assert_eq!(records.len(), 6, "expected six recording sites");++ for &site in &records {+ let preceding_barrier = barriers.iter().rev().find(|&&b| b < site);+ assert!(+ preceding_barrier.is_some(),+ "a recording site at byte {site} has no config barrier before it — \+ a bundle-hash NAK would be counted as executed work"+ );+ // No recording site may be the first thing after a barrier's own+ // NAK-and-return: require the barrier and the record to be in the+ // same neighbourhood rather than separated by another record.+ let intervening = records+ .iter()+ .filter(|&&r| r > *preceding_barrier.unwrap() && r < site)+ .count();+ assert_eq!(+ intervening, 0,+ "recording site at byte {site} does not pair 1:1 with its barrier"+ );+ }+ }++ /// Hostile envelope timestamps must cost a dropped observation, never a+ /// panic on the execution path. A disabled facade must not even look.+ #[test]+ fn recording_work_item_ages_tolerates_absent_and_skewed_timestamps() {+ let telemetry = crate::observability::metrics::SidecarTelemetry::default();+ assert!(!telemetry.is_enabled());+ let far_future = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs_f64()+ + 86_400.0;+ let mut absent = wi("r", 0, "m", "encode");+ absent.timestamp = 0.0;+ let mut negative = wi("r", 1, "m", "generate");+ negative.timestamp = -1.0;+ let mut skewed = wi("r", 2, "m", "encode");+ skewed.timestamp = far_future;+ let items = [absent, negative, skewed];+ record_work_item_ages(&telemetry, items.iter());+ }+#[test]fn queue_ms_from_zero_timestamp_is_zero() {assert_eq!(queue_ms_from(0.0), 0.0);diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rsindex 90b954ef1..48f6fbc7a 100644--- a/packages/sie_server_sidecar/src/health_publisher.rs+++ b/packages/sie_server_sidecar/src/health_publisher.rs@@ -8,8 +8,8 @@//! `202 provisioning` for every request.//!//! See `packages/sie_gateway/src/discovery/nats_health.rs` for the-//! consumer side and `docs/queue-based-routing.md` for the routing-//! contract.+//! consumer side and `packages/sie_gateway/docs/architecture-guide.md`+//! for the routing contract.//!//! # What the gateway actually reads//!@@ -33,8 +33,8 @@//! signal. Backends that need explicit residency, such as Candle, must only//! publish models here after their readiness handshake has made them serveable.//!-//! [`WorkerStatusMessage`]: https://github.com/search?q=WorkerStatusMessage+repo%3Asie-internal-//! [`resolve_queue_route`]: https://github.com/search?q=resolve_queue_route+repo%3Asie-internal+//! [`WorkerStatusMessage`]: https://github.com/superlinked/sie/blob/main/packages/sie_gateway/src/types/worker.rs+//! [`resolve_queue_route`]: https://github.com/superlinked/sie/blob/main/packages/sie_gateway/src/state/worker_registry.rsuse std::sync::Arc;use std::sync::RwLock;diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex da20daad3..ea5e44f13 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -23,6 +23,8 @@ pub mod local_ingest;pub mod log_util;pub mod nats_consumer;pub mod observability;+#[cfg(feature = "cloud-storage")]+pub mod oss_payload_store;pub mod output;pub mod payload_store;pub mod pinned_reconciler;diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rsindex 77d3a8bf0..8f3f77db0 100644--- a/packages/sie_server_sidecar/src/nats_consumer.rs+++ b/packages/sie_server_sidecar/src/nats_consumer.rs@@ -65,6 +65,43 @@ fn stream_max_age_secs() -> u64 {.unwrap_or(DEFAULT_STREAM_MAX_AGE_SECS)}+/// Env-overridable JetStream storage backing for the work-queue streams,+/// wired by Helm as `SIE_STREAM_STORAGE` (`memory` — the default and the+/// only historical behaviour — or `file`).+///+/// `Memory` keeps queued and delivered-but-unacknowledged work only in the+/// broker's RAM: a restart of the NATS pod (an OOM kill, a NATS rollout, or a+/// node drain that evicts that pod specifically) erases it, along with the+/// `DEAD_LETTERS` record that would have named it. `file` persists it across a+/// broker restart at the cost of disk and publish latency.+///+/// MUST match the gateway's `SIE_STREAM_STORAGE` — whoever creates the+/// stream first wins, and JetStream does not permit changing an existing+/// stream's storage type in place. An unrecognized value falls back to the+/// default rather than failing the worker.+fn stream_storage() -> StorageType {+ match std::env::var("SIE_STREAM_STORAGE")+ .unwrap_or_default()+ .trim()+ .to_ascii_lowercase()+ .as_str()+ {+ "file" | "disk" => StorageType::File,+ _ => StorageType::Memory,+ }+}++/// Env-overridable JetStream replica count (`SIE_STREAM_REPLICAS`, default+/// 1). Above 1 requires a clustered NATS deployment. Unlike the storage+/// type, this IS reconcilable on an existing stream.+fn stream_num_replicas() -> usize {+ std::env::var("SIE_STREAM_REPLICAS")+ .ok()+ .and_then(|s| s.parse::<usize>().ok())+ .filter(|&n| n > 0)+ .unwrap_or(1)+}+/// Env-overridable `max_ack_pending`. Python hardcodes 1000 for now but/// exposing the knob keeps the option open without a code change.fn max_ack_pending() -> i64 {@@ -210,6 +247,116 @@ async fn reconcile_stream_max_age(Ok(())}+/// Repair pre-existing streams created without `DiscardPolicy::New` (the+/// gateway's `ensure_stream` historically left the async-nats default,+/// `Old`), which silently discards the oldest queued work at the+/// `max_messages` cap instead of rejecting the new publish.+async fn reconcile_stream_discard(+ js: &JsContext,+ stream: &mut JsStream,+ stream_name: &str,+) -> Result<(), NatsSetupError> {+ let observed_discard = stream.cached_info().config.discard;+ if observed_discard == DiscardPolicy::New {+ return Ok(());+ }++ let mut updated = stream.cached_info().config.clone();+ updated.discard = DiscardPolicy::New;+ js.update_stream(updated)+ .await+ .map_err(|e| NatsSetupError::EnsureStream {+ name: stream_name.to_string(),+ source: e.into(),+ })?;+ *stream = js+ .get_stream(stream_name)+ .await+ .map_err(|e| NatsSetupError::EnsureStream {+ name: stream_name.to_string(),+ source: e.into(),+ })?;+ info!(+ stream = %stream_name,+ observed_discard = ?observed_discard,+ "reconciled NATS stream discard policy to New (reject publishes at cap)"+ );+ Ok(())+}++/// Bring an existing stream's replica count to the configured+/// `SIE_STREAM_REPLICAS`. JetStream supports changing `num_replicas` on a+/// live stream (this is how an R1 stream is scaled to R3), so unlike the+/// storage type this is genuinely reconcilable.+///+/// NATS does not validate the count against the real topology — a single-node+/// server accepts R3 and reports it (verified against nats-server 2.12.6) —+/// so guarding `streamReplicas` against the deployed NATS cluster size is the+/// Helm chart's job, not the broker's.+async fn reconcile_stream_replicas(+ js: &JsContext,+ stream: &mut JsStream,+ stream_name: &str,+ desired_replicas: usize,+) -> Result<(), NatsSetupError> {+ let observed_replicas = stream.cached_info().config.num_replicas;+ if observed_replicas == desired_replicas {+ return Ok(());+ }++ let mut updated = stream.cached_info().config.clone();+ updated.num_replicas = desired_replicas;+ js.update_stream(updated)+ .await+ .map_err(|e| NatsSetupError::EnsureStream {+ name: stream_name.to_string(),+ source: e.into(),+ })?;+ *stream = js+ .get_stream(stream_name)+ .await+ .map_err(|e| NatsSetupError::EnsureStream {+ name: stream_name.to_string(),+ source: e.into(),+ })?;+ info!(+ stream = %stream_name,+ observed_replicas,+ desired_replicas,+ "reconciled NATS stream num_replicas"+ );+ Ok(())+}++/// Report — but do NOT try to repair — a storage-type divergence.+///+/// NATS rejects an `update_stream` that changes `storage` (err_code 10052,+/// "stream configuration update can not change storage type"), because the+/// stream's message store is already materialized in RAM or on disk.+/// "Repairing" it would mean deleting and recreating the stream, destroying+/// exactly the queued work that durability is meant to protect. So an+/// operator flipping `SIE_STREAM_STORAGE` on a cluster with live streams+/// gets a loud warning and keeps their work; the streams take the new+/// storage once the pool is drained and they are recreated.+fn warn_on_stream_storage_mismatch(+ stream: &JsStream,+ stream_name: &str,+ desired_storage: StorageType,+) {+ let observed_storage = stream.cached_info().config.storage;+ if observed_storage == desired_storage {+ return;+ }+ warn!(+ stream = %stream_name,+ observed_storage = ?observed_storage,+ desired_storage = ?desired_storage,+ "NATS stream storage type differs from SIE_STREAM_STORAGE and CANNOT be changed in \+ place; the stream keeps its existing storage until an operator drains the pool and \+ recreates it"+ );+}+/// Predicate used by [`cleanup_overlapping_consumers`]. Returns true/// iff any of the consumer's configured filter(s) overlaps the/// worker's intended `desired_subject` per NATS wildcard semantics.@@ -420,14 +567,16 @@ pub async fn ensure_worker_stream_and_consumer(let consumer_name = config.worker_consumer_name();let desired_max_age = Duration::from_secs(generation_stream_max_age_secs());+ let desired_storage = stream_storage();+ let desired_replicas = stream_num_replicas();let stream_cfg = StreamConfig {name: stream_name.clone(),subjects: vec![subject.clone()],retention: RetentionPolicy::WorkQueue,- storage: StorageType::Memory,+ storage: desired_storage,max_age: desired_max_age,max_messages: STREAM_MAX_MSGS,- num_replicas: 1,+ num_replicas: desired_replicas,discard: DiscardPolicy::New,..Default::default()};@@ -444,6 +593,9 @@ pub async fn ensure_worker_stream_and_consumer(})?;reconcile_stream_subjects(js, &mut stream, &stream_name, &subject).await?;reconcile_stream_max_age(js, &mut stream, &stream_name, desired_max_age).await?;+ reconcile_stream_discard(js, &mut stream, &stream_name).await?;+ reconcile_stream_replicas(js, &mut stream, &stream_name, desired_replicas).await?;+ warn_on_stream_storage_mismatch(&stream, &stream_name, desired_storage);cleanup_overlapping_consumers(&stream, &consumer_name, &subject).await;@@ -508,14 +660,16 @@ async fn ensure_stream_and_consumer_inner(let subject = config.subject_filter();let consumer_name = config.consumer_name();+ let desired_storage = stream_storage();+ let desired_replicas = stream_num_replicas();let stream_cfg = StreamConfig {name: stream_name.clone(),subjects: vec![stream_subject.clone()],retention: RetentionPolicy::WorkQueue,- storage: StorageType::Memory,+ storage: desired_storage,max_age: Duration::from_secs(stream_max_age_secs()),max_messages: STREAM_MAX_MSGS,- num_replicas: 1,+ num_replicas: desired_replicas,discard: DiscardPolicy::New,..Default::default()};@@ -534,6 +688,9 @@ async fn ensure_stream_and_consumer_inner(})?;reconcile_stream_subjects(js, &mut stream, &stream_name, &stream_subject).await?;reconcile_stream_max_age(js, &mut stream, &stream_name, desired_max_age).await?;+ reconcile_stream_discard(js, &mut stream, &stream_name).await?;+ reconcile_stream_replicas(js, &mut stream, &stream_name, desired_replicas).await?;+ warn_on_stream_storage_mismatch(&stream, &stream_name, desired_storage);// Self-heal stale durables whose filters overlap this concrete// `(pool, machine_profile, bundle)` lane. Without this, NATS rejects@@ -722,6 +879,17 @@ mod tests {if std::env::var("SIE_MAX_ACK_PENDING").is_err() {assert_eq!(max_ack_pending(), DEFAULT_MAX_ACK_PENDING);}+ // The shipped default stays memory-backed / single-replica: this+ // knob makes durability configurable, it does not flip the+ // production posture. Must also match the gateway's default+ // (`SIE_STREAM_STORAGE` in packages/sie_gateway/src/config.rs) —+ // whoever creates the stream first wins.+ if std::env::var("SIE_STREAM_STORAGE").is_err() {+ assert_eq!(stream_storage(), StorageType::Memory);+ }+ if std::env::var("SIE_STREAM_REPLICAS").is_err() {+ assert_eq!(stream_num_replicas(), 1);+ }}#[test]diff --git a/packages/sie_server_sidecar/src/observability/metrics.rs b/packages/sie_server_sidecar/src/observability/metrics.rsindex 6f6019e78..96803df9d 100644--- a/packages/sie_server_sidecar/src/observability/metrics.rs+++ b/packages/sie_server_sidecar/src/observability/metrics.rs@@ -18,6 +18,7 @@ use opentelemetry::{global, KeyValue};pub const QUEUE_DURATION_METRIC_NAME: &str = "sie.worker.queue.duration";pub const QUEUE_DEPTH_METRIC_NAME: &str = "sie.worker.queue.depth";+pub const WORK_ITEM_AGE_METRIC_NAME: &str = "sie.worker.work_item.age";pub const SCHEDULER_REQUEST_BATCH_DISPATCH_WAIT_METRIC_NAME: &str ="sie.worker.scheduler.request_batch.dispatch_wait";pub const SCHEDULER_REQUEST_BATCH_TOTAL_METRIC_NAME: &str =@@ -98,6 +99,12 @@ const SHUTDOWN_DRAIN_OUTCOME_SERIES: usize = 3;pub(crate) const SIDECAR_QUEUE_CARDINALITY_LIMIT: usize =OPERATION_SERIES * SIDECAR_CATALOG_PAIR_SERIES;+/// `sie.worker.work_item.age` carries only `operation` and the process-fixed+/// `lane`. It deliberately omits the catalog `(model, profile)` pair that the+/// scheduler-local queue families carry: the question it answers ("how stale is+/// the work this worker is executing?") is a transport-queue property, and+/// multiplying it by 257 catalog pairs would buy no extra answer.+pub(crate) const SIDECAR_WORK_ITEM_AGE_CARDINALITY_LIMIT: usize = OPERATION_SERIES;pub(crate) const SIDECAR_BATCH_FILL_CARDINALITY_LIMIT: usize =SIDECAR_QUEUE_CARDINALITY_LIMIT * FLUSH_REASON_SERIES;pub(crate) const SIDECAR_IPC_CARDINALITY_LIMIT: usize = IPC_METHOD_SERIES * IPC_OUTCOME_SERIES;@@ -131,6 +138,7 @@ pub(crate) fn sidecar_metric_cardinality_limit(name: &str) -> Option<usize> {| SCHEDULER_REQUEST_BATCH_TOTAL_METRIC_NAME| BATCH_SIZE_METRIC_NAME| BATCH_COST_METRIC_NAME => Some(SIDECAR_QUEUE_CARDINALITY_LIMIT),+ WORK_ITEM_AGE_METRIC_NAME => Some(SIDECAR_WORK_ITEM_AGE_CARDINALITY_LIMIT),BATCH_FILL_RATIO_METRIC_NAME => Some(SIDECAR_BATCH_FILL_CARDINALITY_LIMIT),IPC_REQUESTS_METRIC_NAME | IPC_REQUEST_DURATION_METRIC_NAME => {Some(SIDECAR_IPC_CARDINALITY_LIMIT)@@ -173,6 +181,23 @@ const QUEUE_DURATION_BUCKETS: &[f64] = &[0.000_1, 0.000_25, 0.000_5, 0.001, 0.002_5, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5,5.0, 10.0, 30.0,];+/// Transport-queue age spans a much wider range than the scheduler-local+/// families, so it gets its own boundaries rather than reusing+/// [`QUEUE_DURATION_BUCKETS`] (which tops out at 30s and would pile every+/// interesting observation into one overflow bucket).+///+/// The upper boundaries are the system's own time constants, so a reader can+/// answer the B2 question directly off bucket counts instead of an interpolated+/// quantile: 120s is the client-facing ceiling+/// (`packages/sie_gateway/src/config.rs`), 300s is the generation-pool ack+/// wait, 600s is the default redelivery envelope (30s × 20 deliveries), and+/// 1800s is stream retention (`packages/sie_server_sidecar/src/nats_consumer.rs`).+/// Everything at or above the 120s boundary began executing after its client+/// could still have been waiting.+const WORK_ITEM_AGE_BUCKETS: &[f64] = &[+ 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0,+ 1800.0,+];const BATCH_SIZE_BUCKETS: &[f64] = &[1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0];const BATCH_COST_BUCKETS: &[f64] = &[128.0, 512.0, 1024.0, 2048.0, 4096.0, 8192.0, 16_384.0, 32_768.0, 65_536.0, 131_072.0,@@ -441,6 +466,13 @@ impl TelemetryContext {]}+ fn work_item_age_attributes(&self, operation: &'static str) -> [KeyValue; 2] {+ [+ KeyValue::new("operation", operation),+ KeyValue::new("lane", self.lane.to_string()),+ ]+ }+fn batch_attributes(&self,operation: &'static str,@@ -579,6 +611,7 @@ impl ResultTransportOutcome {pub struct EnabledSidecarTelemetry {queue_duration: Histogram<f64>,queue_depth: Gauge<u64>,+ work_item_age: Histogram<f64>,scheduler_request_batch_dispatch_wait: Histogram<f64>,scheduler_request_batch_total: Histogram<f64>,batch_size: Histogram<u64>,@@ -698,6 +731,14 @@ impl SidecarTelemetry {.with_unit("s").with_boundaries(QUEUE_DURATION_BUCKETS.to_vec()).build();+ let work_item_age = meter+ .f64_histogram(WORK_ITEM_AGE_METRIC_NAME)+ .with_description(+ "Age of a work item when the worker commits to executing it, from the gateway publish timestamp on its envelope.",+ )+ .with_unit("s")+ .with_boundaries(WORK_ITEM_AGE_BUCKETS.to_vec())+ .build();let scheduler_request_batch_dispatch_wait = meter.f64_histogram(SCHEDULER_REQUEST_BATCH_DISPATCH_WAIT_METRIC_NAME).with_description(@@ -905,6 +946,7 @@ impl SidecarTelemetry {EnabledSidecarTelemetry {queue_duration,queue_depth,+ work_item_age,scheduler_request_batch_dispatch_wait,scheduler_request_batch_total,batch_size,@@ -1081,6 +1123,40 @@ impl SidecarTelemetry {);}+ /// Record the age of one work item at the instant the worker commits to+ /// executing it, measured from the gateway publish timestamp carried on its+ /// envelope.+ ///+ /// This is the transport-queue observation the scheduler-local+ /// `sie.worker.queue.duration` cannot make: it spans broker enqueue,+ /// redelivery, pull, payload fetch, and scheduling, so it is the only+ /// series that says how stale the work a worker takes on actually is.+ /// Compare its upper buckets against the client-facing request ceiling to+ /// read off how much work is started after its caller could still be+ /// waiting.+ ///+ /// Callers must record this at an execution-commit point for EVERY+ /// operation, generation included; the dispatcher's `record_work_item_ages`+ /// documents where those points are and why a missing one biases the+ /// distribution toward zero.+ ///+ /// Takes plain seconds rather than a [`Duration`] on purpose: the caller's+ /// value is a wall-clock delta between two `SystemTime` reads, and+ /// `Duration::from_secs_f64` PANICS on a negative, NaN, or overflowing+ /// input. A skewed or corrupt envelope timestamp must cost this worker a+ /// dropped observation, never an aborted request. Non-finite and negative+ /// ages are therefore dropped here rather than poisoning the series.+ pub fn work_item_age_observed(&self, operation: &str, age_seconds: f64) {+ if self.inner.is_none() || !age_seconds.is_finite() || age_seconds < 0.0 {+ return;+ }+ let operation = bounded_operation(operation);+ self.work_item_age.record(+ age_seconds,+ &self.context.work_item_age_attributes(operation),+ );+ }+/// Record the two scheduler-local intervals for one successful request ID/// in one completed backend batch. The call site owns success filtering/// and batch-local request-ID deduplication; this facade owns bounded@@ -2509,6 +2585,7 @@ mod tests {let names = [QUEUE_DURATION_METRIC_NAME,QUEUE_DEPTH_METRIC_NAME,+ WORK_ITEM_AGE_METRIC_NAME,SCHEDULER_REQUEST_BATCH_DISPATCH_WAIT_METRIC_NAME,SCHEDULER_REQUEST_BATCH_TOTAL_METRIC_NAME,BATCH_SIZE_METRIC_NAME,@@ -2551,6 +2628,8 @@ mod tests {.all(|name| sidecar_metric_cardinality_limit(name).is_some()));assert!(sidecar_metric_cardinality_limit("not-a-contract-metric").is_none());assert_eq!(SIDECAR_QUEUE_CARDINALITY_LIMIT, 7 * 257);+ // Operation alone; `lane` is fixed for the process lifetime.+ assert_eq!(SIDECAR_WORK_ITEM_AGE_CARDINALITY_LIMIT, 7);assert_eq!(SIDECAR_BATCH_FILL_CARDINALITY_LIMIT, 7 * 257 * 8);assert_eq!(SIDECAR_IPC_RESPONSE_CHUNK_CARDINALITY_LIMIT, 3);assert_eq!(SIDECAR_RESULT_TRANSPORT_CARDINALITY_LIMIT, 4 * 4);@@ -2716,6 +2795,7 @@ mod tests {telemetry.adaptive_snapshot("model-a", None, 5.0, 4096, Some(12.0), Some(20.0), 1);telemetry.generation_model_loading_response("model-a", None, "loading_started", "success");telemetry.shutdown_drain_completed("success", Duration::from_millis(1));+ telemetry.work_item_age_observed("encode", 1.5);provider.force_flush().expect("force_flush");let resource_metrics = exporter.get_finished_metrics().expect("finished metrics");@@ -2731,6 +2811,65 @@ mod tests {assert_eq!(telemetry.queue_depth_for_tests("encode", "model-a"), 0);}+ /// The work-item age series must carry exactly `operation` and `lane`, must+ /// bound an unknown operation rather than minting a series for it, and must+ /// drop a clock delta it cannot represent instead of poisoning the+ /// histogram.+ #[test]+ fn work_item_age_is_bounded_by_operation_and_drops_unrepresentable_ages() {+ let exporter = InMemoryMetricExporter::default();+ let reader = PeriodicReader::builder(exporter.clone()).build();+ let provider = SdkMeterProvider::builder().with_reader(reader).build();+ let meter = provider.meter("work-item-age-test");+ let telemetry = test_metrics(&meter, &["model-a"]);++ telemetry.work_item_age_observed("encode", 0.25);+ telemetry.work_item_age_observed("caller-defined-operation", 900.0);+ // Neither of these may reach the SDK.+ telemetry.work_item_age_observed("encode", -1.0);+ telemetry.work_item_age_observed("encode", f64::NAN);+ telemetry.work_item_age_observed("encode", f64::INFINITY);++ provider.force_flush().expect("force_flush");+ let resource_metrics = exporter.get_finished_metrics().expect("finished metrics");+ let exported: Vec<_> = resource_metrics+ .iter()+ .flat_map(|resource| resource.scope_metrics())+ .flat_map(|scope| scope.metrics())+ .filter(|metric| metric.name() == WORK_ITEM_AGE_METRIC_NAME)+ .collect();+ assert_eq!(exported.len(), 1);+ let metric = exported[0];+ assert_eq!(metric.unit(), "s");+ let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = metric.data() else {+ panic!("work item age must be an f64 histogram");+ };+ let mut observed: Vec<(String, u64)> = histogram+ .data_points()+ .map(|point| {+ let attributes: HashMap<&str, String> = point+ .attributes()+ .map(|attribute| (attribute.key.as_str(), attribute.value.as_str().to_string()))+ .collect();+ assert_eq!(+ attributes.keys().copied().collect::<HashSet<_>>(),+ HashSet::from(["operation", "lane"]),+ "work item age must carry exactly operation and lane"+ );+ assert_eq!(attributes["lane"], "default|l4|default");+ (attributes["operation"].clone(), point.count())+ })+ .collect();+ observed.sort();+ // The unknown operation collapsed to `other` rather than minting its+ // own series, and the three unrepresentable ages were dropped, so+ // `encode` counts one observation and not four.+ assert_eq!(+ observed,+ vec![("encode".to_string(), 1), ("other".to_string(), 1)]+ );+ }+#[test]fn exports_exact_dotted_contract_with_bounded_attributes() {let exporter = InMemoryMetricExporter::default();@@ -2742,6 +2881,7 @@ mod tests {metrics.queue_enqueued("encode", "model-a", Some("fast"));metrics.queue_released("encode", "model-a", Some("fast"), Duration::from_millis(5));+ metrics.work_item_age_observed("encode", 42.5);metrics.scheduler_request_batch_completed(SchedulerRequestBatchObservation {operation: "encode",model: "model-a",@@ -2832,6 +2972,7 @@ mod tests {HashSet::from([QUEUE_DURATION_METRIC_NAME.to_string(),QUEUE_DEPTH_METRIC_NAME.to_string(),+ WORK_ITEM_AGE_METRIC_NAME.to_string(),SCHEDULER_REQUEST_BATCH_DISPATCH_WAIT_METRIC_NAME.to_string(),SCHEDULER_REQUEST_BATCH_TOTAL_METRIC_NAME.to_string(),BATCH_SIZE_METRIC_NAME.to_string(),diff --git a/packages/sie_server_sidecar/src/observability/tracing.rs b/packages/sie_server_sidecar/src/observability/tracing.rsindex 6f931051c..e3a5e61bc 100644--- a/packages/sie_server_sidecar/src/observability/tracing.rs+++ b/packages/sie_server_sidecar/src/observability/tracing.rs@@ -48,8 +48,8 @@ pub fn metrics_provider_enabled() -> bool {METER_PROVIDER.get().is_some()}-// The OTLP transport/proxy/resource plumbing is shared via `sie-telemetry`-// (#2339); the imports below keep every historical call-site and test name+// The OTLP transport/proxy/resource plumbing is shared via `sie-telemetry`;+// the imports below keep every historical call-site and test name// resolvable inside this module.use sie_telemetry::env::{cleaned_env, sie_tracing_enabled};use sie_telemetry::exporters::build_span_exporter;@@ -222,10 +222,10 @@ fn sidecar_service_name(configured: Option<&str>) -> String {}}-/// Build the resource attributes shared with the gateway and managed lanes.+/// Build the resource attributes shared with the gateway and other runtimes./// The sidecar's historical shape: no `service.version` attribute and no/// `SIE_DEPLOYMENT_ENV` / `AWS_REGION` fallbacks (unlike gateway + worker —-/// drift flagged in #2339, deliberately not normalized here).+/// deliberately not normalized here).fn otlp_resource(service_name: &str) -> Resource {otlp_resource_from_values(service_name,diff --git a/packages/sie_server_sidecar/src/oss_payload_store.rs b/packages/sie_server_sidecar/src/oss_payload_store.rsnew file mode 100644index 000000000..45a08c291--- /dev/null+++ b/packages/sie_server_sidecar/src/oss_payload_store.rs@@ -0,0 +1,769 @@+//! Native Alibaba OSS payload reader.+//!+//! This mirrors the gateway's bounded native OSS client but exposes only GET.+//! All requests use Signature V4 and an exclusive environment-or-ACK-RRSA+//! credential source that deliberately excludes ECS metadata and file/profile fallbacks.++use std::time::Duration;++use async_trait::async_trait;+use futures_util::StreamExt;+use reqsign_aliyun_oss::{+ AssumeRoleWithOidcCredentialProvider, Credential, EnvCredentialProvider, RequestSigner,+ SigningVersion,+};+use reqsign_core::{Context, OsEnv, ProvideCredential, Signer};+use reqsign_file_read_tokio::TokioFileRead;+use reqsign_http_send_reqwest::ReqwestHttpSend;+use reqwest::{Client, Method, StatusCode};+use url::Url;++use crate::payload_store::{PayloadError, PayloadStore};++const MAX_ATTEMPTS: usize = 3;+const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);+const MAX_PAYLOAD_BYTES: u64 = crate::prep::media::MAX_OFFLOADED_PAYLOAD_BYTES as u64;++#[derive(Clone, Debug, PartialEq, Eq)]+struct OssLocation {+ bucket: String,+ prefix: String,+}++#[derive(Debug)]+struct OssCredentialProvider {+ source: OssCredentialSource,+}++impl OssCredentialProvider {+ fn new(source: OssCredentialSource) -> Self {+ Self { source }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum OssCredentialSource {+ Environment,+ Oidc,+}++impl ProvideCredential for OssCredentialProvider {+ type Credential = Credential;++ async fn provide_credential(+ &self,+ context: &Context,+ ) -> reqsign_core::Result<Option<Self::Credential>> {+ match self.source {+ OssCredentialSource::Environment => {+ EnvCredentialProvider::new()+ .provide_credential(context)+ .await+ }+ OssCredentialSource::Oidc => {+ AssumeRoleWithOidcCredentialProvider::new()+ .provide_credential(context)+ .await+ }+ }+ }+}++impl OssLocation {+ fn parse(value: &str) -> Result<Self, PayloadError> {+ if value.contains('%') {+ return Err(invalid_ref(+ "OSS payload-store URL must not contain percent-encoded components",+ ));+ }+ let rest = value+ .strip_prefix("oss://")+ .ok_or_else(|| invalid_ref("OSS payload-store URL must use oss://"))?;+ let (raw_authority, raw_path) = rest.split_once('/').unwrap_or((rest, ""));+ if !valid_bucket(raw_authority) {+ return Err(invalid_ref("OSS payload-store bucket is invalid or empty"));+ }+ let prefix = validate_raw_prefix(raw_path)?;+ let parsed = Url::parse(value).map_err(|_| invalid_ref("invalid OSS payload-store URL"))?;+ if parsed.scheme() != "oss" {+ return Err(invalid_ref("OSS payload-store URL must use oss://"));+ }+ if !parsed.username().is_empty() || parsed.password().is_some() {+ return Err(invalid_ref(+ "OSS payload-store URL must not contain credentials",+ ));+ }+ if parsed.query().is_some() || parsed.fragment().is_some() || parsed.port().is_some() {+ return Err(invalid_ref(+ "OSS payload-store URL must not contain a port, query, or fragment",+ ));+ }+ let bucket = parsed+ .host_str()+ .filter(|bucket| valid_bucket(bucket))+ .ok_or_else(|| invalid_ref("OSS payload-store bucket is invalid or empty"))?+ .to_owned();+ Ok(Self { bucket, prefix })+ }++ fn object_key(&self, key: &str) -> String {+ if self.prefix.is_empty() {+ key.to_owned()+ } else {+ format!("{}/{key}", self.prefix)+ }+ }++ fn canonical_prefix(&self) -> String {+ if self.prefix.is_empty() {+ format!("oss://{}", self.bucket)+ } else {+ format!("oss://{}/{}", self.bucket, self.prefix)+ }+ }++ fn relative_key<'a>(&self, payload_ref: &'a str) -> Result<&'a str, PayloadError> {+ let key = if payload_ref.starts_with("oss://") {+ let prefix = self.canonical_prefix();+ let rest = payload_ref+ .strip_prefix(&prefix)+ .and_then(|rest| rest.strip_prefix('/'))+ .ok_or_else(|| {+ invalid_ref("OSS payload reference is outside the configured store")+ })?;+ if rest.starts_with('/') {+ return Err(invalid_ref("OSS payload reference is malformed"));+ }+ rest+ } else if super::payload_store::is_known_object_store_ref(payload_ref) {+ return Err(invalid_ref(+ "payload reference uses a different object-store scheme",+ ));+ } else {+ payload_ref+ };+ validate_payload_key(key)?;+ Ok(key)+ }+}++/// Native OSS V4 GET implementation used by the worker sidecar.+pub struct OssPayloadStore {+ client: Client,+ signer: Signer<Credential>,+ location: OssLocation,+ endpoint: Url,+}++impl OssPayloadStore {+ pub fn from_url(value: &str) -> Result<Self, PayloadError> {+ let location = OssLocation::parse(value)?;+ let region = required_region()?;+ let credential_source = credential_source_from_environment()?;+ let internal = internal_endpoint_enabled()?;+ let suffix = if internal { "-internal" } else { "" };+ let endpoint = Url::parse(&format!(+ "https://{}.oss-{}{}.aliyuncs.com",+ location.bucket, region, suffix+ ))+ .map_err(|_| unsupported("failed to derive OSS endpoint"))?;+ let client = Client::builder()+ .timeout(REQUEST_TIMEOUT)+ .build()+ .map_err(|_| unsupported("failed to build OSS HTTP client"))?;+ let provider = OssCredentialProvider::new(credential_source);+ Ok(Self::new_with_provider(+ location, region, endpoint, client, provider,+ ))+ }++ fn new_with_provider(+ location: OssLocation,+ region: String,+ endpoint: Url,+ client: Client,+ provider: impl ProvideCredential<Credential = Credential>,+ ) -> Self {+ let context = Context::new()+ .with_file_read(TokioFileRead)+ .with_http_send(ReqwestHttpSend::new(client.clone()))+ .with_env(OsEnv);+ let request_signer = RequestSigner::new(&location.bucket)+ .with_region(region)+ .with_signing_version(SigningVersion::V4);+ Self {+ client,+ signer: Signer::new(context, provider, request_signer),+ location,+ endpoint,+ }+ }++ fn object_url(&self, key: &str) -> Result<Url, PayloadError> {+ let mut url = self.endpoint.clone();+ {+ let mut segments = url+ .path_segments_mut()+ .map_err(|_| object_error("GET", None, None))?;+ segments.clear();+ for segment in self.location.object_key(key).split('/') {+ segments.push(segment);+ }+ }+ Ok(url)+ }++ async fn get_object(&self, key: &str) -> Result<Vec<u8>, PayloadError> {+ 'attempts: for attempt in 0..MAX_ATTEMPTS {+ let url = self.object_url(key)?;+ let request = http::Request::builder()+ .method(Method::GET)+ .uri(url.as_str())+ .header(http::header::CONTENT_LENGTH, 0)+ .body(reqwest::Body::from(Vec::new()))+ .map_err(|_| object_error("GET", None, None))?;+ let (mut parts, body) = request.into_parts();+ self.signer+ .sign(&mut parts, None)+ .await+ .map_err(|_| unsupported("OSS GET credential or signing failed"))?;+ let request = http::Request::from_parts(parts, body)+ .try_into()+ .map_err(|_| object_error("GET", None, None))?;++ match self.client.execute(request).await {+ Ok(response) if response.status().is_success() => {+ if let Some(size) = response.content_length() {+ if size > MAX_PAYLOAD_BYTES {+ return Err(PayloadError::TooLarge {+ actual: size,+ max: MAX_PAYLOAD_BYTES,+ });+ }+ }+ let mut stream = response.bytes_stream();+ let mut bytes = Vec::new();+ while let Some(chunk) = stream.next().await {+ let chunk = match chunk {+ Ok(chunk) => chunk,+ Err(_) if attempt + 1 < MAX_ATTEMPTS => {+ retry_delay(attempt).await;+ continue 'attempts;+ }+ Err(_) => {+ return Err(PayloadError::ObjectStore(+ "OSS GET transport failed after retry".to_owned(),+ ));+ }+ };+ let actual = bytes.len() as u64 + chunk.len() as u64;+ if actual > MAX_PAYLOAD_BYTES {+ return Err(PayloadError::TooLarge {+ actual,+ max: MAX_PAYLOAD_BYTES,+ });+ }+ bytes.extend_from_slice(&chunk);+ }+ return Ok(bytes);+ }+ Ok(response) if response.status() == StatusCode::NOT_FOUND => {+ return Err(invalid_ref("OSS payload reference was not found"));+ }+ Ok(response) => {+ let status = response.status();+ if retryable_status(status) && attempt + 1 < MAX_ATTEMPTS {+ retry_delay(attempt).await;+ continue;+ }+ let code = provider_error_code(&response);+ return Err(object_error("GET", Some(status), code.as_deref()));+ }+ Err(_) if attempt + 1 < MAX_ATTEMPTS => retry_delay(attempt).await,+ Err(_) => {+ return Err(PayloadError::ObjectStore(+ "OSS GET transport failed after retry".to_owned(),+ ));+ }+ }+ }+ Err(PayloadError::ObjectStore(+ "OSS GET failed after retry".to_owned(),+ ))+ }+}++#[async_trait]+impl PayloadStore for OssPayloadStore {+ async fn get(&self, payload_ref: &str) -> Result<Vec<u8>, PayloadError> {+ let key = self.location.relative_key(payload_ref)?;+ self.get_object(key).await+ }+}++fn required_region() -> Result<String, PayloadError> {+ let region = std::env::var("SIE_OSS_REGION")+ .map_err(|_| unsupported("SIE_OSS_REGION is required for oss:// payload storage"))?;+ if !valid_region(®ion) {+ return Err(unsupported("SIE_OSS_REGION is invalid"));+ }+ Ok(region)+}++fn internal_endpoint_enabled() -> Result<bool, PayloadError> {+ match std::env::var("SIE_OSS_USE_INTERNAL_ENDPOINT") {+ Ok(value) if value.eq_ignore_ascii_case("true") || value == "1" => Ok(true),+ Ok(value) if value.eq_ignore_ascii_case("false") || value == "0" => Ok(false),+ Ok(_) => Err(unsupported(+ "SIE_OSS_USE_INTERNAL_ENDPOINT must be true, false, 1, or 0",+ )),+ Err(std::env::VarError::NotPresent) => Ok(false),+ Err(_) => Err(unsupported("SIE_OSS_USE_INTERNAL_ENDPOINT is invalid")),+ }+}++fn credential_source_from_environment() -> Result<OssCredentialSource, PayloadError> {+ if std::env::var_os("ALIBABA_CLOUD_STS_ENDPOINT").is_some() {+ return Err(unsupported(+ "custom Alibaba STS endpoints are not supported",+ ));+ }+ let alibaba_static = validate_pair(+ "ALIBABA_CLOUD_ACCESS_KEY_ID",+ "ALIBABA_CLOUD_ACCESS_KEY_SECRET",+ )?;+ let oss_static = validate_pair("OSS_ACCESS_KEY_ID", "OSS_ACCESS_KEY_SECRET")?;+ if optional_token_is_invalid("ALIBABA_CLOUD_SECURITY_TOKEN", alibaba_static)+ || optional_token_is_invalid("OSS_SESSION_TOKEN", oss_static)+ || (alibaba_static && oss_static)+ {+ return Err(unsupported(+ "Alibaba static credential configuration is ambiguous or incomplete",+ ));+ }+ let oidc_names = [+ "ALIBABA_CLOUD_ROLE_ARN",+ "ALIBABA_CLOUD_OIDC_PROVIDER_ARN",+ "ALIBABA_CLOUD_OIDC_TOKEN_FILE",+ ];+ let oidc_present = oidc_names.map(|name| std::env::var_os(name).is_some());+ let oidc = oidc_names.map(environment_value_is_nonempty);+ if oidc_present.iter().any(|set| *set) && !oidc.iter().all(|set| *set) {+ return Err(unsupported("Alibaba RRSA configuration is incomplete"));+ }+ select_credential_source(alibaba_static || oss_static, oidc).map_err(unsupported)+}++fn optional_token_is_invalid(name: &str, base_credentials_configured: bool) -> bool {+ !optional_token_configuration_is_valid(+ base_credentials_configured,+ std::env::var_os(name).is_some(),+ environment_value_is_nonempty(name),+ )+}++fn optional_token_configuration_is_valid(+ base_configured: bool,+ token_present: bool,+ token_nonempty: bool,+) -> bool {+ !token_present || (base_configured && token_nonempty)+}++fn select_credential_source(+ static_configured: bool,+ oidc: [bool; 3],+) -> Result<OssCredentialSource, &'static str> {+ if oidc.iter().any(|set| *set) && !oidc.iter().all(|set| *set) {+ return Err("Alibaba RRSA configuration is incomplete");+ }+ if oidc.iter().all(|set| *set) {+ if static_configured {+ return Err("Alibaba static credentials and RRSA must not be configured together");+ }+ return Ok(OssCredentialSource::Oidc);+ }+ Ok(OssCredentialSource::Environment)+}++fn validate_pair(first: &str, second: &str) -> Result<bool, PayloadError> {+ let first_present = std::env::var_os(first).is_some();+ let second_present = std::env::var_os(second).is_some();+ let first_set = environment_value_is_nonempty(first);+ let second_set = environment_value_is_nonempty(second);+ if first_present != second_present || first_present != first_set || second_present != second_set+ {+ return Err(unsupported(+ "Alibaba static credential configuration is incomplete",+ ));+ }+ Ok(first_set)+}++fn environment_value_is_nonempty(name: &str) -> bool {+ std::env::var(name).is_ok_and(|value| !value.trim().is_empty())+}++fn validate_payload_key(key: &str) -> Result<(), PayloadError> {+ if key.is_empty()+ || key.contains("..")+ || !key+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))+ {+ return Err(invalid_ref("OSS payload key is invalid"));+ }+ Ok(())+}++fn validate_raw_prefix(raw_path: &str) -> Result<String, PayloadError> {+ if raw_path.is_empty() {+ return Ok(String::new());+ }+ if raw_path.starts_with('/')+ || raw_path.contains("//")+ || raw_path.contains('\\')+ || raw_path.split('/').any(|segment| {+ segment == "."+ || segment == ".."+ || !segment+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))+ })+ {+ return Err(invalid_ref("OSS payload-store prefix is malformed"));+ }+ Ok(raw_path.strip_suffix('/').unwrap_or(raw_path).to_owned())+}++fn valid_bucket(bucket: &str) -> bool {+ (3..=63).contains(&bucket.len())+ && bucket+ .bytes()+ .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')+ && bucket+ .as_bytes()+ .first()+ .is_some_and(u8::is_ascii_alphanumeric)+ && bucket+ .as_bytes()+ .last()+ .is_some_and(u8::is_ascii_alphanumeric)+}++fn valid_region(region: &str) -> bool {+ !region.is_empty()+ && region+ .bytes()+ .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')+ && region+ .as_bytes()+ .first()+ .is_some_and(u8::is_ascii_alphanumeric)+ && region+ .as_bytes()+ .last()+ .is_some_and(u8::is_ascii_alphanumeric)+}++fn retryable_status(status: StatusCode) -> bool {+ status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error()+}++async fn retry_delay(attempt: usize) {+ tokio::time::sleep(Duration::from_millis(50 * (attempt as u64 + 1))).await;+}++fn provider_error_code(response: &reqwest::Response) -> Option<String> {+ response+ .headers()+ .get("x-oss-error-code")+ .and_then(|value| value.to_str().ok())+ .and_then(clean_error_code)+}++fn clean_error_code(value: &str) -> Option<String> {+ if value.is_empty()+ || value.len() > 64+ || !value+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))+ {+ return None;+ }+ Some(value.to_owned())+}++fn object_error(operation: &str, status: Option<StatusCode>, code: Option<&str>) -> PayloadError {+ let mut message = format!("OSS {operation} failed");+ if let Some(status) = status {+ message.push_str(&format!(": status={}", status.as_u16()));+ }+ if let Some(code) = code {+ message.push_str(&format!(" code={code}"));+ }+ PayloadError::ObjectStore(message)+}++fn invalid_ref(message: &str) -> PayloadError {+ PayloadError::InvalidRef(message.to_owned())+}++fn unsupported(message: &str) -> PayloadError {+ PayloadError::Unsupported(message.to_owned())+}++#[cfg(test)]+mod tests {+ use super::*;+ use reqsign_aliyun_oss::StaticCredentialProvider;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::sync::Arc;+ use wiremock::matchers::{header_regex, method, path};+ use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};++ fn loopback_store(server: &MockServer) -> OssPayloadStore {+ let client = Client::builder().timeout(REQUEST_TIMEOUT).build().unwrap();+ OssPayloadStore::new_with_provider(+ OssLocation::parse("oss://sie-test-bucket/payloads").unwrap(),+ "eu-central-1".to_owned(),+ Url::parse(&server.uri()).unwrap(),+ client,+ StaticCredentialProvider::new("test-access-key", "test-secret-key"),+ )+ }++ #[derive(Clone)]+ struct RetryThenOk(Arc<AtomicUsize>);++ impl Respond for RetryThenOk {+ fn respond(&self, _request: &Request) -> ResponseTemplate {+ if self.0.fetch_add(1, Ordering::SeqCst) == 0 {+ ResponseTemplate::new(429)+ } else {+ ResponseTemplate::new(200).set_body_bytes(b"payload")+ }+ }+ }++ #[test]+ fn exact_full_ref_and_plain_key_contract() {+ let location = OssLocation::parse("oss://sie-test-bucket/payloads").unwrap();+ assert_eq!(+ location.relative_key("request_0.bin").unwrap(),+ "request_0.bin"+ );+ assert_eq!(+ location+ .relative_key("oss://sie-test-bucket/payloads/request_0.bin")+ .unwrap(),+ "request_0.bin"+ );+ for payload_ref in [+ "oss://other-bucket/payloads/request_0.bin",+ "oss://sie-test-bucket/other/request_0.bin",+ "s3://sie-test-bucket/payloads/request_0.bin",+ "../request_0.bin",+ "nested/request_0.bin",+ ] {+ assert!(location.relative_key(payload_ref).is_err(), "{payload_ref}");+ }+ }++ #[test]+ fn strict_location_contract() {+ for invalid_value in [+ "oss:///payloads",+ "oss://user@sie-test-bucket/payloads",+ "oss://sie-test-bucket/payloads?x=1",+ "oss://sie-test-bucket/payloads#fragment",+ "oss://sie-test-bucket/a//b",+ "oss://sie-test-bucket/a/%2e%2e/b",+ "oss://sie-test-bucket/a/../b",+ "oss://sie-test-bucket/a/./b",+ "oss://sie-test-bucket//payloads",+ "oss://sie-test-bucket/payloads//",+ "oss://SIE-test-bucket/payloads",+ ] {+ assert!(+ OssLocation::parse(invalid_value).is_err(),+ "{invalid_value}"+ );+ }+ }++ #[test]+ fn rrsa_is_exclusive_and_cannot_be_masked_by_static_credentials() {+ assert_eq!(+ select_credential_source(false, [true, true, true]),+ Ok(OssCredentialSource::Oidc)+ );+ assert!(select_credential_source(true, [true, true, true]).is_err());+ assert!(select_credential_source(false, [true, false, true]).is_err());+ assert_eq!(+ select_credential_source(true, [false, false, false]),+ Ok(OssCredentialSource::Environment)+ );+ assert!(!optional_token_configuration_is_valid(true, true, false));+ assert!(!optional_token_configuration_is_valid(false, true, true));+ assert!(optional_token_configuration_is_valid(true, true, true));+ }++ #[test]+ fn errors_expose_only_closed_fields() {+ let error = object_error(+ "GET",+ Some(StatusCode::FORBIDDEN),+ clean_error_code("AccessDenied").as_deref(),+ )+ .to_string();+ assert_eq!(+ error,+ "object store: OSS GET failed: status=403 code=AccessDenied"+ );+ for secret in ["Authorization", "SecurityToken", "AccessKey", "RequestId"] {+ assert!(!error.contains(secret));+ }+ }++ #[test]+ fn loads_shared_wire_fixture() {+ let fixture: serde_json::Value =+ serde_json::from_str(include_str!("../../wire-fixtures/oss_payload_store.json"))+ .unwrap();+ let configured = format!(+ "oss://{}/{}",+ fixture["bucket"].as_str().unwrap(),+ fixture["prefix"].as_str().unwrap()+ );+ let location = OssLocation::parse(&configured).unwrap();+ let key = fixture["plain_key"].as_str().unwrap();+ assert_eq!(location.object_key(key), fixture["object_key"]);+ assert_eq!(+ location+ .relative_key(fixture["full_reference"].as_str().unwrap())+ .unwrap(),+ key+ );+ }++ #[tokio::test]+ async fn loopback_get_uses_v4_and_retries() {+ let server = MockServer::start().await;+ let attempts = Arc::new(AtomicUsize::new(0));+ Mock::given(method("GET"))+ .and(path("/payloads/request_0.bin"))+ .and(header_regex("authorization", "^OSS4-HMAC-SHA256 "))+ .respond_with(RetryThenOk(attempts.clone()))+ .expect(2)+ .mount(&server)+ .await;++ let store = loopback_store(&server);+ assert_eq!(store.get("request_0.bin").await.unwrap(), b"payload");+ assert_eq!(attempts.load(Ordering::SeqCst), 2);+ }++ #[tokio::test]+ async fn mid_body_transport_failure_rebuilds_and_resigns() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ for attempt in 0..2 {+ let (mut stream, _) = listener.accept().await.unwrap();+ let mut request = Vec::new();+ loop {+ let mut chunk = [0; 1024];+ let read = stream.read(&mut chunk).await.unwrap();+ if read == 0 {+ break;+ }+ request.extend_from_slice(&chunk[..read]);+ if request.windows(4).any(|window| window == b"\r\n\r\n") {+ break;+ }+ }+ let request = String::from_utf8(request).unwrap().to_ascii_lowercase();+ assert!(request+ .lines()+ .any(|line| line.starts_with("authorization: oss4-hmac-sha256 ")));+ if attempt == 0 {+ stream+ .write_all(+ b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\npay",+ )+ .await+ .unwrap();+ } else {+ stream+ .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\npayload")+ .await+ .unwrap();+ }+ stream.shutdown().await.unwrap();+ }+ });++ let client = Client::builder().timeout(REQUEST_TIMEOUT).build().unwrap();+ let store = OssPayloadStore::new_with_provider(+ OssLocation::parse("oss://sie-test-bucket/payloads").unwrap(),+ "eu-central-1".to_owned(),+ Url::parse(&format!("http://{address}")).unwrap(),+ client,+ StaticCredentialProvider::new("test-access-key", "test-secret-key"),+ );+ assert_eq!(store.get("request_0.bin").await.unwrap(), b"payload");+ server.await.unwrap();+ }++ #[tokio::test]+ async fn loopback_get_enforces_metadata_size_and_404() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/payloads/large.bin"))+ .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![+ 0;+ MAX_PAYLOAD_BYTES as usize+ + 1+ ]))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/payloads/missing.bin"))+ .respond_with(ResponseTemplate::new(404))+ .mount(&server)+ .await;++ let store = loopback_store(&server);+ assert!(matches!(+ store.get("large.bin").await,+ Err(PayloadError::TooLarge { .. })+ ));+ assert!(matches!(+ store.get("missing.bin").await,+ Err(PayloadError::InvalidRef(_))+ ));+ }++ #[tokio::test]+ async fn access_denied_error_is_sanitized() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/payloads/denied.bin"))+ .respond_with(+ ResponseTemplate::new(403)+ .set_body_string("AccessDenied raw-id must never be surfaced"),+ )+ .mount(&server)+ .await;+ let error = loopback_store(&server)+ .get("denied.bin")+ .await+ .unwrap_err()+ .to_string();+ assert_eq!(error, "object store: OSS GET failed: status=403");+ assert!(!error.contains("raw-id"));+ }+}diff --git a/packages/sie_server_sidecar/src/payload_store.rs b/packages/sie_server_sidecar/src/payload_store.rsindex 45daadf59..e22ba9ae2 100644--- a/packages/sie_server_sidecar/src/payload_store.rs+++ b/packages/sie_server_sidecar/src/payload_store.rs@@ -9,7 +9,7 @@//! (absolute paths are only accepted when they are inside `base_dir`;//! relative paths are resolved against it). When no `base_dir` is//! configured the reader is disabled for safety.-//! - cloud: `s3://…` / `gs://…` / `abfs://…` / `abfss://…` URL+//! - cloud: `s3://…` / `gs://…` / `abfs://…` / `abfss://…` / `oss://…` URL//! (handled when the `cloud-storage` feature is enabled)//!//! Security: on Linux, the configured directory is pinned as a file@@ -41,7 +41,7 @@ use futures_util::StreamExt;#[cfg(feature = "cloud-storage")]use object_store::ObjectStoreExt;-const OBJECT_STORE_SCHEMES: &[&str] = &["s3://", "gs://", "abfs://", "abfss://"];+const OBJECT_STORE_SCHEMES: &[&str] = &["s3://", "gs://", "abfs://", "abfss://", "oss://"];#[cfg(any(target_os = "linux", feature = "cloud-storage"))]const MAX_PAYLOAD_BYTES: u64 = crate::prep::media::MAX_OFFLOADED_PAYLOAD_BYTES as u64;@@ -52,6 +52,11 @@ fn object_store_scheme(url: &str) -> Option<&'static str> {.find(|scheme| url.starts_with(scheme))}+#[cfg(feature = "cloud-storage")]+pub(crate) fn is_known_object_store_ref(value: &str) -> bool {+ object_store_scheme(value).is_some()+}+#[derive(Debug, Error)]pub enum PayloadError {#[error("io: {0}")]@@ -537,7 +542,7 @@ impl PayloadStore for ObjectPayloadStore {/// 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://…` / `abfs://…` / `abfss://…` with the+/// * `s3://…` / `gs://…` / `abfs://…` / `abfss://…` / `oss://…` 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@@ -550,13 +555,18 @@ impl PayloadStore for ObjectPayloadStore {pub async fn create_payload_store(url: Option<&str>,) -> Result<std::sync::Arc<dyn PayloadStore>, PayloadError> {- let Some(url) = url.filter(|u| !u.is_empty()) else {+ let Some(url) = url.map(str::trim).filter(|url| !url.is_empty()) else {return Ok(std::sync::Arc::new(LocalPayloadStore::new(None::<PathBuf>)));};if let Some(scheme) = object_store_scheme(url) {#[cfg(feature = "cloud-storage")]{+ if url.starts_with("oss://") {+ return Ok(std::sync::Arc::new(+ crate::oss_payload_store::OssPayloadStore::from_url(url)?,+ ));+ }if let Some(rest) = url.strip_prefix("s3://") {return Ok(std::sync::Arc::new(ObjectPayloadStore::new_s3(rest)?));}@@ -1345,4 +1355,22 @@ mod tests {),}}++ #[cfg(not(feature = "cloud-storage"))]+ #[tokio::test]+ async fn factory_oss_without_feature_errors_loudly() {+ match create_payload_store(Some("oss://bucket/payloads")).await {+ Ok(_) => panic!("expected Unsupported for oss:// without cloud-storage feature"),+ Err(error) => assert!(matches!(error, PayloadError::Unsupported(_))),+ }+ }++ #[cfg(not(feature = "cloud-storage"))]+ #[tokio::test]+ async fn factory_trims_before_scheme_classification() {+ match create_payload_store(Some(" oss://bucket/payloads ")).await {+ Ok(_) => panic!("expected trimmed oss:// to require cloud-storage feature"),+ Err(error) => assert!(matches!(error, PayloadError::Unsupported(_))),+ }+ }}diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex 9b2fb45e7..6982098ee 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -9,9 +9,9 @@//! shared Python/Rust package: adapters are standalone deliverables, and//! we want adapter authors to vendor the protocol like any other API client.//! General sidecar/Python schema parity is checked by-//! `tools/ci/check_ipc_types_parity.py`; the response-chunk v1 subset and its-//! limits are pinned across all three peers by-//! `tools/ci/check_response_chunk_protocol.py`.+//! `tools/check_ipc_types_parity.py`; the response-chunk v1 subset and its+//! limits are pinned across the public IPC and NATS peers by+//! `tools/check_response_chunk_protocol.py`.//!//! Wire format: `[4-byte BE length][msgpack body]`, where `body` is a//! msgpack **map** encoding `RequestEnvelope` / `ResponseEnvelope`.@@ -204,9 +204,8 @@ pub enum ReadinessState {/// Terminal, non-retryable load failure. The Python executor/// reports this when the registry holds a PERMANENT `LoadFailure`/// (`cooldown=permanent`: `GATED` / `NOT_FOUND` / `DEPENDENCY` /- /// `UNKNOWN`) — the same classification the direct-HTTP- /// `check_not_failed` gate and the Modal lane's- /// `worker_runtime._terminal_load_failure` use for #1786. It exists+ /// `UNKNOWN`) — the same classification used by the gateway+ /// readiness gate. It exists/// so the sidecar can DISTINGUISH "still loading" (retry) from/// "dead on arrival" (dead-letter): on `Failed` the dispatcher stops/// re-driving `EnsureModelReady` and publishes a typeddiff --git a/packages/sie_server_sidecar/src/protocol/mod.rs b/packages/sie_server_sidecar/src/protocol/mod.rsindex 899c8dd30..04938baab 100644--- a/packages/sie_server_sidecar/src/protocol/mod.rs+++ b/packages/sie_server_sidecar/src/protocol/mod.rs@@ -2,7 +2,7 @@//!//! The Rust IPC schema is intentionally kept in one module and checked against//! `packages/sie_server/src/sie_server/ipc_types.py` by-//! `tools/ci/check_ipc_types_parity.py`.+//! `tools/check_ipc_types_parity.py`.pub mod ipc_types;pub(crate) mod response_chunks;diff --git a/packages/sie_server_sidecar/src/scheduler/adaptive.rs b/packages/sie_server_sidecar/src/scheduler/adaptive.rsindex 9c2272b9a..f533be988 100644--- a/packages/sie_server_sidecar/src/scheduler/adaptive.rs+++ b/packages/sie_server_sidecar/src/scheduler/adaptive.rs@@ -344,8 +344,8 @@ impl AdaptiveBatchController {/// low module-level defaults. If Rust falls back to those bare/// values, the PI loop flushes tiny batches too eagerly under/// saturation. Restoring the model-derived floors here is the- /// equivalent of the Python production constructor and is what every- /// deployed `ModelWorker` in `sie-internal` already runs.+ /// equivalent of the Python production constructor used by deployed+ /// `ModelWorker` instances.////// Env vars (`SIE_ADAPTIVE_BATCH_*`) are then applied on top of/// the production-derived defaults — operators can still pin@@ -548,8 +548,7 @@ impl AdaptiveBatchController {/// [`Instant::now`] by advancing an internal virtual f64-seconds/// clock by `dt_s` before running the controller. Intended/// **exclusively** for shadow-trace replay — see- /// `examples/replay_controller_trace.rs` and- /// `scripts/perf/replay-scheduler-trace.py`.+ /// `examples/replay_controller_trace.rs`.////// The virtual clock advances on **every** call (including calls/// that early-return under `update_interval`), matching the Pythondiff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rsindex 64285ae98..36db10ae4 100644--- a/packages/sie_server_sidecar/tests/integration_smoke.rs+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs@@ -1141,7 +1141,7 @@ async fn work_cancel_is_namespaced_acks_before_ipc_and_excludes_generation() {/// answers `ProcessGenerate` with the same event sequence a real/// StreamingProcessor would use: progress ACK, raw publish, final ACK.///-/// This is intentionally below the full Tilt/SGLang layer. It proves+/// This is intentionally below the full gateway/backend integration layer. It proves/// the sidecar-only contract that endpoint tests cannot isolate:/// worker-specific stream creation, direct generation subject routing,/// streaming IPC frames, raw NATS publish, and JetStream settlement.@@ -2924,3 +2924,105 @@ async fn smoke_scheduler_coalesces_concurrent_encodes() {let _ = sock;sleep(Duration::from_millis(200)).await;}++/// Stream discard-policy reconcile (architecture-review finding B3).+///+/// A `WORK_POOL_{pool}` / `WORK_WORKER_{worker_id}` stream created by a+/// pre-fix gateway carries the async-nats default `DiscardPolicy::Old`,+/// which silently discards the OLDEST queued work at the `max_messages`+/// cap. Both sidecar ensure paths must repair such streams to `New` so a+/// full work queue rejects the new publish loudly instead.+///+/// Only needs `nats-server` (no Python harness / worker binary), so the+/// skip gate is intentionally narrower than `skip_unless_tools_available`.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn ensure_paths_reconcile_stream_discard_policy_to_new() {+ if which("nats-server").is_none() {+ eprintln!("integration_smoke: skipping — missing tools on $PATH: nats-server");+ return;+ }+ let _guard = smoke_test_guard().await;++ let nats = NatsHarness::start().await;+ eprintln!("nats: {} (port {})", nats.url, nats.port);++ let (_client, js) = sie_server_sidecar::nats_consumer::connect(&nats.url)+ .await+ .expect("connect JetStream");++ let config = sie_server_sidecar::config::WorkerConfig {+ nats_url: Some(nats.url.clone()),+ local_socket_path: None,+ pool: "discardsmoke".into(),+ bundle: "default".into(),+ ipc_socket_path: PathBuf::from("/tmp/discard-smoke.sock"),+ ipc_socket_paths: vec![PathBuf::from("/tmp/discard-smoke.sock")],+ ipc_pool_size: 1,+ ipc_request_timeout_s: 60,+ model_ready_timeout_s: 900,+ payload_store_url: None,+ gateway_url: None,+ gateway_api_key: None,+ pool_admission_enabled: false,+ pool_admission_check_interval_ms: 5_000,+ pool_admission_pause_ms: 1_000,+ pool_admission_stale_after_ms: 30_000,+ probe_port: 9095,+ worker_id: "discard-worker".into(),+ ping_interval_ms: 2000,+ ready_stale_mult: 3,+ machine_profile: "l4".into(),+ gpu_count: 1,+ bundle_config_hash: String::new(),+ config_service_url: None,+ config_service_token: None,+ config_poll_interval_ms: 30_000,+ config_full_export_interval_ms: 300_000,+ nats_config_trusted_producers: vec!["sie-config".into()],+ health_publish_interval_ms: 5_000,+ };++ // Pre-create both streams exactly as a pre-fix gateway did: no+ // `discard` field, so the async-nats default (`Old`) sticks.+ for (name, subject) in [+ (config.stream_name(), config.stream_subject_filter()),+ (config.worker_stream_name(), config.worker_subject_filter()),+ ] {+ let mut legacy = js+ .get_or_create_stream(async_nats::jetstream::stream::Config {+ name: name.clone(),+ subjects: vec![subject],+ retention: async_nats::jetstream::stream::RetentionPolicy::WorkQueue,+ storage: async_nats::jetstream::stream::StorageType::Memory,+ max_age: Duration::from_secs(1_800),+ max_messages: 100_000,+ num_replicas: 1,+ ..Default::default()+ })+ .await+ .expect("create legacy stream");+ assert_eq!(+ legacy.info().await.expect("legacy info").config.discard,+ async_nats::jetstream::stream::DiscardPolicy::Old,+ "precondition: {name} must carry the Old default"+ );+ }++ sie_server_sidecar::nats_consumer::ensure_stream_and_consumer(&js, &config)+ .await+ .expect("ensure pool stream and consumer");+ sie_server_sidecar::nats_consumer::ensure_worker_stream_and_consumer(&js, &config)+ .await+ .expect("ensure worker stream and consumer");++ for name in [config.stream_name(), config.worker_stream_name()] {+ let mut stream = js.get_stream(&name).await.expect("get reconciled stream");+ assert_eq!(+ stream.info().await.expect("stream info").config.discard,+ async_nats::jetstream::stream::DiscardPolicy::New,+ "{name} must be repaired to DiscardPolicy::New"+ );+ }++ drop(nats);+}diff --git a/packages/sie_telemetry/src/lib.rs b/packages/sie_telemetry/src/lib.rsindex e64884fea..c8fedf025 100644--- a/packages/sie_telemetry/src/lib.rs+++ b/packages/sie_telemetry/src/lib.rs@@ -1,8 +1,8 @@-//! Shared OpenTelemetry *plumbing* for the SIE Rust crates (#2339).+//! Shared OpenTelemetry *plumbing* for the SIE Rust crates.//!//! Extracted from the three copy-forked `observability/` stacks-//! (`sie_gateway`, `sie_server_sidecar`, `sie_server_rust`): OTLP-//! transport/endpoint/protocol resolution, Modal proxy authentication,+//! (`sie_gateway`, `sie_server_sidecar`, and the native worker): OTLP+//! transport/endpoint/protocol resolution, authenticated proxy headers,//! resource identity, exporter construction, env helpers, and W3C trace//! propagation. Extraction preserved each consumer's behavior — the crate//! exposes `_from_values` seams and parameters (e.g. `service_version`)diff --git a/packages/sie_telemetry/src/transport.rs b/packages/sie_telemetry/src/transport.rsindex 0e6b62d7a..1a2a36f62 100644--- a/packages/sie_telemetry/src/transport.rs+++ b/packages/sie_telemetry/src/transport.rs@@ -101,7 +101,7 @@ pub fn trace_export_config_from_values(}/// Resolve the metric exporter config from the standard OTEL variables,-/// gated on the caller-provided enable flag (the `sie_server_rust` shape;+/// gated on the caller-provided enable flag (the native-worker shape;/// gateway/sidecar resolve metrics via [`configured_signal_endpoints`]).pub fn metric_export_config(enabled: bool) -> Result<Option<SignalExportConfig>, String> {metric_export_config_from_values(diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.mdnew file mode 100644index 000000000..4ffc06d71--- /dev/null+++ b/packages/sie_ts_sdk/README.md@@ -0,0 +1,137 @@+# @superlinked/sie-sdk++Official TypeScript SDK for SIE (Search Inference Engine). Async-only,+built on native `fetch`, works in Node.js (>= 22) and the browser.++## Installation++```bash+npm install @superlinked/sie-sdk+```++## Creating a client++```typescript+import { SIEClient } from "@superlinked/sie-sdk";++// Local server+const client = new SIEClient("http://localhost:8080");++// Managed SIE gateway: pass the gateway URL and your API key+// (sent as a Bearer token). Server-side code only — see below.+const managed = new SIEClient("https://your-gateway.example.com", {+ apiKey: "YOUR_API_KEY",+});+```++> **Warning:** only pass `apiKey` in server-side code. Shipping it in a+> browser bundle exposes the bearer key to anyone who loads the page.+> For browser apps, route requests through a backend proxy that holds+> the key.++## Encoding++```typescript+// Single item — result.dense is a Float32Array+const result = await client.encode("BAAI/bge-m3", { text: "Hello world" });+console.log(result.dense?.length); // 1024++// Batch — results come back in input order+const results = await client.encode("BAAI/bge-m3", [+ { text: "First document" },+ { text: "Second document" },+]);+```++## Scoring (reranking)++```typescript+const scored = await client.score(+ "BAAI/bge-reranker-v2-m3",+ { text: "What is machine learning?" },+ [+ { id: "doc-1", text: "Machine learning is a subfield of AI." },+ { id: "doc-2", text: "Python is a programming language." },+ ],+);+// Sorted by relevance (rank 0 = most relevant)+console.log(scored.scores[0].itemId, scored.scores[0].score);+```++## Generation++```typescript+// Aggregated result+const gen = await client.generate(+ "Qwen/Qwen3-4B-Instruct-2507",+ "Write a haiku about the sea.",+ { maxNewTokens: 64, temperature: 0.7 },+);+console.log(gen.text, gen.finishReason, gen.usage);++// Streaming (SSE) — chunks as they arrive (Node.js example;+// process.stdout is not available in the browser)+for await (const chunk of client.streamGenerate(+ "Qwen/Qwen3-4B-Instruct-2507",+ "Write a haiku about the sea.",+ { maxNewTokens: 64 },+)) {+ process.stdout.write(chunk.text_delta);+ if (chunk.done && chunk.ttft_ms !== undefined) {+ console.log(`\nTTFT: ${chunk.ttft_ms}ms`);+ }+}+```++## Error handling++All errors extend `SIEError` and are exported from the package root.+Server-reported errors carry `.code` and `.statusCode`, plus+`.requestId` (the gateway `x-sie-request-id`) when the gateway included+one in the response — check it before using it.++```typescript+import {+ ModelLoadingError,+ RequestError,+ ResourceExhaustedError,+ ServerError,+ SIEStreamError,+} from "@superlinked/sie-sdk";++try {+ const res = await client.encode("BAAI/bge-m3", { text: "Hello" });+} catch (error) {+ if (error instanceof RequestError) {+ console.error(`Bad request (${error.code}):`, error.message);+ } else if (error instanceof ServerError) {+ const correlation = error.requestId ? ` [request ${error.requestId}]` : "";+ console.error(`Server error (${error.code})${correlation}:`, error.message);+ }+}+```++Retry semantics for transient `503` codes:++- `PROVISIONING` — the cluster is scaling capacity from zero. Retried+ automatically while `waitForCapacity: true` (the default); with+ `waitForCapacity: false` it throws `ProvisioningError` immediately.+- `MODEL_LOADING` — the worker is cold-loading the model. The SDK+ retries automatically until `provisionTimeout` (default 900000 ms),+ then throws `ModelLoadingError`.+- `LORA_LOADING` — the requested LoRA adapter is still loading. Retried+ a bounded number of times, then throws `LoraLoadingError`.+- `RESOURCE_EXHAUSTED` — server-side GPU OOM. Retried with bounded+ exponential backoff; throws `ResourceExhaustedError` (a `ServerError`+ subclass) when retries run out.++Streaming calls throw `SIEStreamError` for mid-stream error chunks —+the HTTP connection was healthy but the worker or gateway emitted an+error envelope partway through. Branch on `error.code` (for example+`empty_model_output`, a terminal generation that produced no visible+text) and, when `error.requestId` is present, use it to correlate with+gateway logs.++## License++MITdiff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex 69de1fab9..37e0a9393 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.7.1",+ "version": "0.7.2","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",@@ -28,10 +28,7 @@}}},- "files": [- "dist",- "README.md"- ],+ "files": ["dist", "README.md"],"scripts": {"build": "tsup","typecheck": "tsc --noEmit && tsc -p tsconfig.type-tests.json",@@ -47,20 +44,12 @@"engines": {"node": ">=22.0.0"},- "keywords": [- "embeddings",- "vector",- "search",- "inference",- "reranking",- "colbert",- "maxsim"- ],+ "keywords": ["embeddings", "vector", "search", "inference", "reranking", "colbert", "maxsim"],"author": "SIE Team","license": "MIT","repository": {"type": "git",- "url": "https://github.com/superlinked/sie-internal.git",+ "url": "https://github.com/superlinked/sie.git","directory": "packages/sie_ts_sdk"},"publishConfig": {diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.tsindex c24c0c265..7b8bf5dc8 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -8,18 +8,18 @@* const client = new SIEClient("http://localhost:8080");** // Encode single item- * const result = await client.encode("bge-m3", { text: "Hello world" });+ * const result = await client.encode("BAAI/bge-m3", { text: "Hello world" });* console.log(result.dense); // Float32Array** // Batch encode- * const results = await client.encode("bge-m3", [+ * const results = await client.encode("BAAI/bge-m3", [* { text: "First document" },* { text: "Second document" },* ]);** // With GPU routing and auto-retry for capacity* const resultWithGpu = await client.encode(- * "bge-m3",+ * "BAAI/bge-m3",* { text: "Hello" },* { gpu: "l4", waitForCapacity: true },* );@@ -29,7 +29,9 @@*/import {+ JobFailedError,LoraLoadingError,+ MalformedChunkError,ModelLoadingError,PoolError,ProvisioningError,@@ -79,8 +81,14 @@ import {throwIfEstimateUnroutable,throwIfInputTooLong,throwIfModelLoadFailed,+ validateBatchResultCount,+ validateRequestId,} from "./internal/parsing.js";-import { nextOomRetryDelay, withProvisioningRetry } from "./internal/provisioning.js";+import {+ admissionRetryDelay,+ nextOomRetryDelay,+ withProvisioningRetry,+} from "./internal/provisioning.js";import { applyRetryJitter } from "./internal/retry.js";import {type JobResultItem,@@ -134,12 +142,65 @@ import type {ScoreResult,StatusMessage,StreamGenerateOptions,+ WireModelInfo,} from "./types.js";import { SDK_VERSION } from "./version.js";const JOB_RESULT_NOT_FOUND_ERROR_CODE = "RESULT_NOT_FOUND";const JOB_RESULT_REF_MAX_REFRESHES = 3;+/**+ * `jobs.results()` decodes chunk refs into per-item results. A non-terminal job+ * has no stable result set: its ref list is still growing, so decoding one would+ * return a partial subset indistinguishable from a partial-FAILURE subset. The+ * SDK refuses with this code rather than return a misleading partial.+ */+const JOB_NOT_TERMINAL_ERROR_CODE = "job_not_terminal";++/**+ * Wire keys `GET /v1/models/{model}` merges in for vanilla OpenAI+ * "retrieve model" clients. They are OpenAI-envelope scaffolding, not SIE+ * model metadata (`id` duplicates `name`; `object`/`owned_by` are constants;+ * `created` is a fixed sentinel), so `ModelInfo` neither declares nor carries+ * them. Pinned as deliberately excluded in+ * `packages/wire-fixtures/model_info.json`.+ */+type OpenAiCompatModelKeys = Partial<Record<"id" | "object" | "created" | "owned_by", unknown>>;++/**+ * Map a wire `/v1/models` entry to the client-facing shape.+ *+ * Total by construction: every key except the three camelCase renames and the+ * OpenAI-compat keys flows through the rest spread, so a field added to the+ * endpoint reaches callers without a code change here — only `ModelInfo` and+ * `WireModelInfo` need to declare it. The previous hardcoded allowlist silently+ * dropped everything it did not name.+ */+function toModelInfo(wire: WireModelInfo): ModelInfo {+ const {+ max_sequence_length,+ last_error,+ pending_generation,+ aliases,+ id: _id,+ object: _object,+ created: _created,+ owned_by: _ownedBy,+ ...rest+ } = wire as WireModelInfo & OpenAiCompatModelKeys;++ return {+ ...rest,+ // The one normalized field. A gateway always sends `aliases`, but a single+ // SIE server omits it entirely, and the rest spread would then hand the+ // caller `undefined` for a field `ModelInfo` declares as always present.+ aliases: aliases ?? [],+ ...(max_sequence_length !== undefined ? { maxSequenceLength: max_sequence_length } : {}),+ ...(last_error !== undefined ? { lastError: last_error } : {}),+ ...(pending_generation !== undefined ? { pendingGeneration: pending_generation } : {}),+ };+}+/** The `client.jobs` batch namespace. */export interface JobsNamespace {/** Submit a batch job; exact connector replays may return current status. */@@ -159,14 +220,36 @@ export interface JobsNamespace {recoveryAttemptOrdinal: number,idempotencyKey: string,): Promise<JobStatus>;- /** Retrieve a finished job's chunk refs and decode the per-item results. */+ /**+ * Retrieve a terminal job's chunk refs and decode the per-item results.+ *+ * Every chunk that published a ref is read — including a `failed` chunk,+ * whose ref carries its SUCCESSFUL (already-billed) siblings alongside the+ * per-item failures; only chunks with no ref at all are skipped. Each item's+ * `success` and `error` distinguish the two.+ *+ * Throws a `job_not_terminal` `RequestError` (409) when the job has not+ * reached a terminal state — decoding one then would return a partial subset+ * indistinguishable from a partial-failure subset. Warns (via `console.warn`)+ * when fewer items are retrieved than `total_items`, and separately when a+ * chunk ref's bytes could not be decoded.+ */results(jobId: string): Promise<JobResults>;/*** Poll `get` until the job reaches a terminal state, then return its status.* Throws a `job_wait_timeout` `RequestError` if `timeoutMs` elapses first.* Mirrors the Python SDK's `jobs.wait` (default 600s timeout, 2s poll).+ *+ * With `raiseOnFailure: true` a non-successful terminal+ * (`failed`/`suspended`/`cancelled`) throws {@link JobFailedError} carrying+ * the status doc's `outcome`/`error_code`, so the failure is actionable+ * without re-reading the doc. The default is unchanged and back-compatible:+ * every terminal (and the `planned` plan phase) is returned as-is.*/- wait(jobId: string, options?: { timeoutMs?: number; pollMs?: number }): Promise<JobStatus>;+ wait(+ jobId: string,+ options?: { timeoutMs?: number; pollMs?: number; raiseOnFailure?: boolean },+ ): Promise<JobStatus>;}/** The `client.connections` namespace (org-scoped connector auth). */@@ -586,23 +669,109 @@ async function itemsForExtractWire(items: ExtractItem[]): Promise<ExtractItemFor* `SIEClient` state.*/function extractChatChunkError(chunk: ChatCompletionChunk): SIEStreamError | null {- const err = (- chunk as ChatCompletionChunk & {- error?: { message?: string; type?: string; param?: string | null; code?: string };- }- ).error;- if (!err) return null;- return new SIEStreamError(err.message ?? "stream error", {- code: err.code,- errorType: err.type,- param: err.param,+ const withError = chunk as ChatCompletionChunk & {+ error?: { message?: string; type?: string; param?: string | null; code?: string };+ request_id?: string;+ };+ if (!withError.error) return null;+ // The gateway request id rides in-band on the chat error chunk too (#3136)+ // — the `chatcmpl-*` id is not the correlation key gateway logs use, and+ // streamed responses have no terminal headers. Forward it for correlation.+ const requestId = validateRequestId(withError.request_id);+ return new SIEStreamError(withError.error.message ?? "stream error", {+ code: withError.error.code,+ errorType: withError.error.type,+ param: withError.error.param,+ requestId,+ });+}++/**+ * Return only the `scheme://host[:port]` origin of `url`.+ *+ * Path, query, fragment, and any `user:password@` userinfo are dropped, so a+ * baseUrl carrying embedded credentials OR a token query parameter never+ * reaches a log line. Logging uses only —+ * requests still target the real URL. Falls back to a placeholder if the URL+ * cannot be parsed, so a malformed value never leaks verbatim.+ */+function urlOriginForLogging(url: string): string {+ try {+ const parsed = new URL(url);+ // `parsed.host` is host[:port]; `parsed.origin` would work for http(s)+ // but is "null" for opaque origins, so build it explicitly.+ return `${parsed.protocol}//${parsed.host}`;+ } catch {+ return "<redacted-url>";+ }+}++/**+ * Convert a `fetch()` `TypeError` into a typed connection error.+ *+ * A URL-parse failure (e.g. a scheme-less baseUrl: Node throws+ * `TypeError: Failed to parse URL …` with `cause.code === "ERR_INVALID_URL"`)+ * is a permanent configuration error, NOT a transient network failure —+ * classify it as kind `"other"` so the connect-retry loops never spin on it,+ * and point at the fix. Every other fetch `TypeError` is a genuine+ * network-level connection failure and keeps kind `"connect"`.+ */+function connectionErrorFromFetchTypeError(error: TypeError): SIEConnectionError {+ const cause = (error as { cause?: { code?: unknown } }).cause;+ if (+ cause?.code === "ERR_INVALID_URL" ||+ error.message.includes("Failed to parse URL") ||+ error.message.includes("Invalid URL")+ ) {+ return new SIEConnectionError(+ `Invalid request URL (${error.message}). baseUrl must be an absolute http(s) URL, e.g. "http://localhost:8080".`,+ "other",+ );+ }+ return new SIEConnectionError(`Connection failed: ${error.message}`, "connect");+}++const MODAL_CONTINUATION_MAX_HOPS = 20;+const MODAL_ATTEMPT_TOKEN_QUERY_KEY = "__modal_attempt_token";++/** Resolve only Modal's documented result URL on the exact configured origin. */+function modalContinuationUrl(baseUrl: string, response: Response): string | undefined {+ if (response.status !== 303) return undefined;+ const location = response.headers.get("location");+ const hasControlCharacter = [...(location ?? "")].some((character) => {+ const codePoint = character.codePointAt(0) ?? 0;+ return codePoint <= 0x1f || codePoint === 0x7f;});+ if (!location || location.length > 8192 || hasControlCharacter) {+ return undefined;+ }+ try {+ const base = new URL(baseUrl);+ const resolved = new URL(location, `${baseUrl.replace(/\/$/, "")}/`);+ const tokens = resolved.searchParams.getAll(MODAL_ATTEMPT_TOKEN_QUERY_KEY);+ if (+ resolved.origin !== base.origin ||+ resolved.username !== "" ||+ resolved.password !== "" ||+ resolved.hash !== "" ||+ tokens.length !== 1 ||+ tokens[0] === ""+ ) {+ return undefined;+ }+ return resolved.toString();+ } catch {+ return undefined;+ }}/** SIE-native chunk variant — see `sse.rs::build_generate_chunk_event`. */function extractGenerateChunkError(chunk: GenerateChunk): SIEStreamError | null {if (!chunk.error) return null;- return new SIEStreamError(chunk.error.message, { code: chunk.error.code });+ // The gateway request id rides in-band on the error chunk (streamed+ // responses have no terminal headers), so forward it for correlation (#3136).+ const requestId = validateRequestId(chunk.request_id);+ return new SIEStreamError(chunk.error.message, { code: chunk.error.code, requestId });}/**@@ -619,7 +788,7 @@ function extractGenerateChunkError(chunk: GenerateChunk): SIEStreamError | null* await client.createPool("eval-bench", { l4: 2 });** // Use pool for requests- * await client.encode("bge-m3", { text: "Hello" }, { gpu: "eval-bench/l4" });+ * await client.encode("BAAI/bge-m3", { text: "Hello" }, { gpu: "eval-bench/l4" });** // Check pool status* const pool = await client.getPool("eval-bench");@@ -672,9 +841,35 @@ export class SIEClient {* @param options - Client options*/constructor(baseUrl: string, options: SIEClientOptions = {}) {+ // Validate eagerly: a scheme-less baseUrl ("localhost:8080") would+ // otherwise only surface at request time as a fetch `TypeError`.+ let parsed: URL | undefined;+ try {+ parsed = new URL(baseUrl);+ } catch {+ parsed = undefined;+ }+ // `new URL()` normalizes `http:/v1`, `http:///v1`, `https:///v1` to a+ // bogus host `"v1"` (WHATWG slash-coalescing), so those pass a `hostname`+ // check while silently targeting the wrong host. Require a real+ // `scheme://<authority>`: `https?://` immediately followed by a non-slash+ // authority character.+ const hasRealAuthority = /^https?:\/\/[^/]/i.test(baseUrl);+ if (+ !parsed ||+ (parsed.protocol !== "http:" && parsed.protocol !== "https:") ||+ !parsed.hostname ||+ !hasRealAuthority+ ) {+ throw new TypeError(+ `Invalid baseUrl "${baseUrl}": must be an absolute http(s) URL with a host, e.g. "http://localhost:8080".`,+ );+ }// Remove trailing slashthis.baseUrl = baseUrl.replace(/\/$/, "");- this.timeout = options.timeout ?? DEFAULT_TIMEOUT;+ // `timeoutMs` is the unit-encoded name; `timeout` is a deprecated alias+ // for the same MILLISECONDS value. `timeoutMs` wins if both are set.+ this.timeout = options.timeoutMs ?? options.timeout ?? DEFAULT_TIMEOUT;this.gpu = options.gpu;this.apiKey = options.apiKey;// BREAKING CHANGE (0.7): default flipped from `false` to `true` to match@@ -736,7 +931,7 @@ export class SIEClient {/*** Encode a single item.*- * @param model - Model name (e.g., "bge-m3")+ * @param model - Model name (e.g., "BAAI/bge-m3")* @param item - Item to encode* @param options - Encode options* @returns Encode result with embeddings@@ -746,7 +941,7 @@ export class SIEClient {/*** Encode multiple items.*- * @param model - Model name (e.g., "bge-m3")+ * @param model - Model name (e.g., "BAAI/bge-m3")* @param items - Items to encode* @param options - Encode options* @returns Array of encode results in same order as input@@ -811,6 +1006,18 @@ export class SIEClient {const data = unpackMessage<WireResponse>(new Uint8Array(await response.arrayBuffer()));const results = parseEncodeResults(data.items);+ // Guard the 1:1 input-to-output contract before any positional access+ // (`results[0]` below, or index-based reassembly in callers). The queue+ // path returns mixed-success batches as 200 with only the successful+ // items, so a desynced count would otherwise misalign every+ // zip-inputs-to-outputs consumer.+ validateBatchResultCount(+ results,+ itemsArray,+ model,+ "encode",+ response.headers.get("x-sie-request-id") ?? undefined,+ );attachRequestMetadata(results, response.headers, data);if (isSingleItem) {@@ -883,37 +1090,22 @@ export class SIEClient {const response = await this.requestJson("/v1/models", "GET");// Wire format response: {"models": [...]}- interface WireModelInfo {- name: string;- loaded: boolean;- inputs: string[];- outputs: string[];- dims?: { dense?: number; sparse?: number; multivector?: number };- max_sequence_length?: number;- }-interface WireModelsResponse {models: WireModelInfo[];}const data = (await response.json()) as WireModelsResponse;- return data.models.map((m) => ({- name: m.name,- loaded: m.loaded,- inputs: m.inputs,- outputs: m.outputs,- dims: m.dims,- maxSequenceLength: m.max_sequence_length,- }));+ return data.models.map(toModelInfo);}/*** Get details for a specific model.** Returns model metadata including dimensions, supported inputs/outputs,- * loaded status, and max sequence length. This is a lightweight call that- * reads from model config — it does not load the model or trigger inference.+ * lifecycle state, profiles, and capabilities. This is a lightweight call+ * that reads from model config — it does not load the model or trigger+ * inference.** @param name - Model name (e.g., "BAAI/bge-m3")* @returns Model information@@ -921,25 +1113,9 @@ export class SIEClient {async getModel(name: string): Promise<ModelInfo> {const response = await this.requestJson(`/v1/models/${encodeURIComponent(name)}`, "GET");- interface WireModelInfo {- name: string;- loaded: boolean;- inputs: string[];- outputs: string[];- dims?: { dense?: number; sparse?: number; multivector?: number };- max_sequence_length?: number;- }-const data = (await response.json()) as WireModelInfo;- return {- name: data.name,- loaded: data.loaded,- inputs: data.inputs,- outputs: data.outputs,- dims: data.dims,- maxSequenceLength: data.max_sequence_length,- };+ return toModelInfo(data);}/**@@ -1031,7 +1207,7 @@ export class SIEClient {/*** Score items against a query using a reranker model.*- * @param model - Model name (e.g., "bge-reranker-v2")+ * @param model - Model name (e.g., "BAAI/bge-reranker-v2-m3")* @param query - Query item* @param items - Items to score against the query* @param options - Score options@@ -1040,7 +1216,7 @@ export class SIEClient {* @example* ```typescript* const result = await client.score(- * "bge-reranker-v2",+ * "BAAI/bge-reranker-v2-m3",* { text: "What is machine learning?" },* [* { id: "doc-1", text: "Machine learning is..." },@@ -1055,15 +1231,15 @@ export class SIEClient {/*** Generate text from a prompt (walking-skeleton SDK surface).*- * The SDK does not currently expose streaming chunks. The worker streams- * to the gateway, the gateway aggregates, and the SDK returns the- * assembled result plus SIE-native timing metadata (TTFT, TPOT,- * attempt id).+ * Returns the aggregated outcome: the worker streams to the gateway,+ * the gateway aggregates, and the SDK returns the assembled result+ * plus SIE-native timing metadata (TTFT, TPOT, attempt id). To+ * consume chunks as they arrive, use {@link streamGenerate} instead.** @example* ```typescript* const result = await client.generate(- * "Qwen__Qwen3-4B-Instruct-2507",+ * "Qwen/Qwen3-4B-Instruct-2507",* "Write a haiku about the sea.",* { maxNewTokens: 64, temperature: 0.7 },* );@@ -1132,13 +1308,23 @@ export class SIEClient {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), this.timeout);try {- const response = await fetch(url, {+ let response = await fetch(url, {method: "POST",headers,body: JSON.stringify(body),signal: controller.signal,- redirect: "error",+ redirect: "manual",});+ for (let hop = 0; hop < MODAL_CONTINUATION_MAX_HOPS; hop += 1) {+ const continuationUrl = modalContinuationUrl(this.baseUrl, response);+ if (!continuationUrl) return response;+ response = await fetch(continuationUrl, {+ method: "GET",+ headers,+ signal: controller.signal,+ redirect: "manual",+ });+ }return response;} catch (err) {if (err instanceof Error && err.name === "AbortError") {@@ -1155,7 +1341,7 @@ export class SIEClient {// retry loop propagate it. The SAFE pre-execution capacity// signals (503 PROVISIONING / MODEL_LOADING) are HTTP statuses, not// exceptions, so the retry loop still handles them.- throw new SIEConnectionError(`Connection failed: ${err.message}`, "connect");+ throw connectionErrorFromFetchTypeError(err);}throw err;} finally {@@ -1449,7 +1635,7 @@ export class SIEClient {throw new SIEConnectionError(`Stream open timeout after ${this.timeout}ms`, "timeout");}if (error instanceof TypeError) {- throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");+ throw connectionErrorFromFetchTypeError(error);}throw error;} finally {@@ -1642,7 +1828,7 @@ export class SIEClient {/*** Extract entities from a single item.*- * @param model - Model name (e.g., "gliner-multi-v2.1")+ * @param model - Model name (e.g., "urchade/gliner_multi-v2.1")* @param item - Item to extract from* @param options - Extract options with labels* @returns Extract result with entities@@ -1652,7 +1838,7 @@ export class SIEClient {/*** Extract entities from multiple items.*- * @param model - Model name (e.g., "gliner-multi-v2.1")+ * @param model - Model name (e.g., "urchade/gliner_multi-v2.1")* @param items - Items to extract from* @param options - Extract options with labels* @returns Array of extract results in same order as input@@ -1669,7 +1855,7 @@ export class SIEClient {* @example* ```typescript* const result = await client.extract(- * "gliner-multi-v2.1",+ * "urchade/gliner_multi-v2.1",* { text: "Apple was founded by Steve Jobs." },* { labels: ["person", "organization"] },* );@@ -1728,6 +1914,16 @@ export class SIEClient {const data = unpackMessage<WireResponse>(new Uint8Array(await response.arrayBuffer()));const results = parseExtractResults(data.items);+ // Same positional contract as encode: `results[0]` below and index-based+ // reassembly in batch callers both assume one result per input, and the+ // queue path drops failed items from a 200 body.+ validateBatchResultCount(+ results,+ itemsArray,+ model,+ "extract",+ response.headers.get("x-sie-request-id") ?? undefined,+ );attachRequestMetadata(results, response.headers, data);if (isSingleItem) {@@ -1782,11 +1978,11 @@ export class SIEClient {* await client.createPool("eval-bench", { l4: 2 }, undefined, undefined, {* bundle: "default",* minimumWorkerCount: 1,- * pinnedModels: ["bge-m3"],+ * pinnedModels: ["BAAI/bge-m3"],* });** // Use the pool for requests- * await client.encode("bge-m3", { text: "Hello" }, { gpu: "eval-bench/l4" });+ * await client.encode("BAAI/bge-m3", { text: "Hello" }, { gpu: "eval-bench/l4" });** // Clean up when done* await client.deletePool("eval-bench");@@ -2168,7 +2364,7 @@ export class SIEClient {* console.log(`Ready with ${capacity.workerCount} L4 workers`);** // Wait and pre-load a model- * const capacityWithModel = await client.waitForCapacity("l4", { model: "bge-m3" });+ * const capacityWithModel = await client.waitForCapacity("l4", { model: "BAAI/bge-m3" });* ```*/async waitForCapacity(@@ -2245,6 +2441,10 @@ export class SIEClient {// Retry counter for server-side OOM (RESOURCE_EXHAUSTED). Bounded so a// stuck-at-OOM server cannot cause unbounded blocking.let oomRetries = 0;+ // First connect-retry is surfaced via `console.warn` (the SDK's existing+ // logging seam, cf. the version-skew warning) so a user does not silently+ // wait out the whole provision budget against an unreachable server.+ let warnedConnectRetry = false;while (true) {let response: Response;@@ -2255,6 +2455,13 @@ export class SIEClient {if (waitForCapacity && err instanceof SIEConnectionError && err.kind === "connect") {const elapsed = Date.now() - startTime;if (elapsed < this.provisionTimeout) {+ if (!warnedConnectRetry) {+ warnedConnectRetry = true;+ console.warn(+ `[SIE SDK] Connection to ${urlOriginForLogging(this.baseUrl)} failed (${err.message}); ` ++ `retrying for up to ${this.provisionTimeout}ms`,+ );+ }const remaining = this.provisionTimeout - elapsed;const delay = Math.min(DEFAULT_RETRY_DELAY, remaining);await sleep(delay);@@ -2264,7 +2471,7 @@ export class SIEClient {throw err;}- // Short-circuit terminal load failures (sie-test#85). The server+ // Short-circuit terminal load failures. The server// emits 502 MODEL_LOAD_FAILED for permanent classes (gated repos,// missing dependencies, unrecognised architectures); we must// surface the error immediately rather than burn the@@ -2362,6 +2569,21 @@ export class SIEClient {}}+ // Retryable pre-execution admission backpressure (pass-2 audit B1/B2/B7):+ // a 429 RATE_LIMIT, or a retryable 503 (BILLING_CAPACITY_UNAVAILABLE /+ // QUEUE_FULL) the ladder above did not match. No work was published, so+ // retry within the provision-timeout budget honoring Retry-After; a+ // give-up throws a typed RateLimitError (429) or the server's terminal+ // 503. 402/403 credit/account errors are terminal and NOT handled here.+ const admissionDelay = await admissionRetryDelay(response, {+ startTime,+ provisionTimeoutMs: this.provisionTimeout,+ });+ if (admissionDelay !== undefined) {+ await sleep(admissionDelay);+ continue;+ }+// Handle 504 (gateway timeout): queued work was published, but the// gateway did not receive a worker result before its deadline.// Encode/score/extract are idempotent, so callers that opted into@@ -2438,7 +2660,7 @@ export class SIEClient {throw new SIEConnectionError(`Request timeout after ${this.timeout}ms`, "timeout");}if (error instanceof TypeError) {- throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");+ throw connectionErrorFromFetchTypeError(error);}throw error;} finally {@@ -2483,7 +2705,7 @@ export class SIEClient {throw new SIEConnectionError(`Request timeout after ${this.timeout}ms`, "timeout");}if (error instanceof TypeError) {- throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");+ throw connectionErrorFromFetchTypeError(error);}throw error;} finally {@@ -2543,7 +2765,7 @@ export class SIEClient {throw new SIEConnectionError(`Request timeout after ${timeoutMs}ms`, "timeout");}if (error instanceof TypeError) {- throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");+ throw connectionErrorFromFetchTypeError(error);}throw error;} finally {@@ -2624,13 +2846,35 @@ export class SIEClient {let refreshes = 0;for (;;) {const job = await this.jobGet(jobId);+ const state = job.state;+ if (!state || !TERMINAL_JOB_STATES.has(state)) {+ throw new RequestError(+ `job ${jobId} is ${JSON.stringify(state)}, not terminal; results are decodable only after the job reaches a terminal state (succeeded/failed/suspended/cancelled)`,+ JOB_NOT_TERMINAL_ERROR_CODE,+ 409,+ );+ }const chunks = jobChunks(job);const items: JobResultItem[] = [];try {for (const chunk of chunks) {- if (chunk.state !== "succeeded" || !chunk.ref) continue;+ // A `failed` chunk still carries a ref with its SUCCESSFUL siblings+ // (which are billed) plus the per-item failures, so its ref is read+ // too — only chunks with no ref at all are skipped. Each item's+ // `success`/`error` distinguishes the two.+ if (!chunk.ref) continue;const raw = await this.readRef(chunk.ref);- items.push(...decodeChunkBytes(raw));+ try {+ items.push(...decodeChunkBytes(raw));+ } catch (error) {+ // Garbage bytes are a DECODE fault, not proof of failed+ // publication/billing — confine it and flag it distinctly rather+ // than folding it into the neutral incompleteness warning below.+ if (!(error instanceof MalformedChunkError)) throw error;+ console.warn(+ `[SIE SDK] job ${jobId} chunk (seq=${chunk.seq}) ref could not be decoded (malformed bytes); its items are omitted from the results`,+ );+ }}} catch (error) {const refreshable =@@ -2644,13 +2888,24 @@ export class SIEClient {throw error;}const withDims = items.find((it) => it.dims != null);+ const retrieved = items.length;+ const totalItems = job.total_items;+ if (totalItems != null && retrieved < totalItems) {+ // Neutral: state only what is known (fewer items decoded than the job's+ // item count). Do NOT assert a cause — the shortfall may be an+ // unpublished chunk OR an undecodable ref, and this call cannot prove+ // billing from the status doc.+ console.warn(+ `[SIE SDK] job ${jobId} results are incomplete: retrieved ${retrieved} of ${totalItems} items`,+ );+ }return {job_id: job.id ?? jobId,- state: job.state,- total_items: job.total_items,+ state,+ total_items: totalItems,settled_credits: job.settled_credits,chunks,- retrieved: items.length,+ retrieved,dims: withDims ? withDims.dims : null,items,};@@ -2659,14 +2914,30 @@ export class SIEClient {private async jobWait(jobId: string,- options?: { timeoutMs?: number; pollMs?: number },+ options?: { timeoutMs?: number; pollMs?: number; raiseOnFailure?: boolean },): Promise<JobStatus> {const timeoutMs = options?.timeoutMs ?? DEFAULT_JOB_WAIT_TIMEOUT;const pollMs = options?.pollMs ?? DEFAULT_JOB_WAIT_POLL;const deadline = Date.now() + timeoutMs;for (;;) {const job = await this.jobGet(jobId);- if ((job.state && TERMINAL_JOB_STATES.has(job.state)) || job.phase === "planned") {+ if (job.phase === "planned") return job;+ const state = job.state;+ if (state && TERMINAL_JOB_STATES.has(state)) {+ if (options?.raiseOnFailure && state !== "succeeded") {+ const outcome = job.outcome;+ const errorCode = job.error_code;+ const reason =+ outcome || errorCode+ ? ` (outcome=${JSON.stringify(outcome)}, error_code=${JSON.stringify(errorCode)})`+ : "";+ throw new JobFailedError(`job ${jobId} terminated ${JSON.stringify(state)}${reason}`, {+ jobId: job.id ?? jobId,+ state,+ outcome,+ errorCode,+ });+ }return job;}if (Date.now() >= deadline) {@@ -2706,7 +2977,7 @@ export class SIEClient {throw new SIEConnectionError(`Request timeout after ${this.timeout}ms`, "timeout");}if (error instanceof TypeError) {- throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");+ throw connectionErrorFromFetchTypeError(error);}throw error;} finally {@@ -2815,7 +3086,7 @@ export class SIEClient {throw new SIEConnectionError(`Request timeout after ${timeoutMs}ms`, "timeout");}if (error instanceof TypeError) {- throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");+ throw connectionErrorFromFetchTypeError(error);}throw error;} finally {@@ -2851,7 +3122,7 @@ export class SIEClient {throw new SIEConnectionError(`Request timeout after ${this.timeout}ms`, "timeout");}if (error instanceof TypeError) {- throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");+ throw connectionErrorFromFetchTypeError(error);}throw error;} finally {diff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.tsindex 6b518ca3f..199ffba86 100644--- a/packages/sie_ts_sdk/src/errors.ts+++ b/packages/sie_ts_sdk/src/errors.ts@@ -75,12 +75,19 @@ export class RequestError extends SIEError {readonly code: string | undefined;/** HTTP status code, when the failure came from a terminal response. */readonly statusCode: number | undefined;+ /**+ * Gateway request id (`x-sie-request-id` header) when the terminal+ * response carried one. Mirrors the Python SDK's `RequestError.request.id`+ * so failures stay correlatable with gateway logs (#3136).+ */+ readonly requestId: string | undefined;- constructor(message: string, code?: string, statusCode?: number) {+ constructor(message: string, code?: string, statusCode?: number, requestId?: string) {super(message);this.name = "RequestError";this.code = code;this.statusCode = statusCode;+ this.requestId = requestId;}}@@ -98,12 +105,19 @@ export class ServerError extends SIEError {readonly code: string | undefined;/** HTTP status code (500-599) */readonly statusCode: number | undefined;+ /**+ * Gateway request id (`x-sie-request-id` header) when the terminal+ * response carried one. Mirrors the Python SDK's `ServerError.request.id`+ * so failures stay correlatable with gateway logs (#3136).+ */+ readonly requestId: string | undefined;- constructor(message: string, code?: string, statusCode?: number) {+ constructor(message: string, code?: string, statusCode?: number, requestId?: string) {super(message);this.name = "ServerError";this.code = code;this.statusCode = statusCode;+ this.requestId = requestId;}}@@ -242,22 +256,30 @@ export class ResourceExhaustedError extends ServerError {* gateway emitted an error envelope partway through generation.*/export class SIEStreamError extends SIEError {- /** SIE-native error code (e.g. `context_exceeded`, `cancelled`). */+ /** SIE-native error code (e.g. `context_exceeded`, `empty_model_output`, `cancelled`). */readonly code: string | undefined;/** OpenAI-style error type (e.g. `context_length_exceeded`, `server_error`). */readonly errorType: string | undefined;/** Offending field name when known (chat shape only). */readonly param: string | null | undefined;+ /**+ * Gateway request id carried in-band by the error chunk (SIE-native+ * generate shape only — streamed responses have no terminal headers).+ * Lets callers correlate typed terminal errors like `empty_model_output`+ * with gateway logs (#3136).+ */+ readonly requestId: string | undefined;constructor(message: string,- options?: { code?: string; errorType?: string; param?: string | null },+ options?: { code?: string; errorType?: string; param?: string | null; requestId?: string },) {super(message);this.name = "SIEStreamError";this.code = options?.code;this.errorType = options?.errorType;this.param = options?.param;+ this.requestId = options?.requestId;}}@@ -268,7 +290,7 @@ export class SIEStreamError extends SIEError {* response (no retry budget consumed) when the server returns HTTP* `502 MODEL_LOAD_FAILED`. The server uses this code for permanent-class* failures (gated repos, missing dependencies, unrecognised model- * architectures) where retrying would waste time. See sie-test#85.+ * architectures) where retrying would waste time.** Permanent failures will not auto-clear; an operator must fix the* underlying cause (e.g. set `HF_TOKEN`, accept the model license on@@ -330,6 +352,129 @@ export class InputTooLongError extends RequestError {}}+/**+ * A successful (HTTP 200) batch response dropped or added items.+ *+ * The gateway's queue path returns mixed-success batches as `200` carrying+ * only the successful items — a per-item failure is dropped from the body, not+ * surfaced as an error envelope. Batch responses are positional (item `id` is+ * optional), so a shortened body silently shifts every item after the dropped+ * one: a zip-inputs-to-outputs consumer would store results against the wrong+ * inputs. The SDK guards the 1:1 input-to-output contract on every batch+ * response and throws this instead of returning a desynced array.+ *+ * Subclass of {@link ServerError} — the server violated the response-shape+ * contract even though the HTTP status was 200 — so existing `ServerError`+ * handlers keep working. `statusCode` is 200 for the same reason: the response+ * was not an HTTP error. Catch this specifically to retry item-wise+ * (single-item batches get per-item error visibility), using {@link missingIds}+ * when the submitted items carried ids. Mirrors the Python SDK's+ * `IncompleteBatchError`.+ */+export class IncompleteBatchError extends ServerError {+ /** Number of items submitted in this HTTP request. */+ readonly expected: number;++ /** Number of items the response body carried. */+ readonly received: number;++ /** The model that was requested. */+ readonly model: string | undefined;++ /**+ * Ids of submitted items absent from the response.+ *+ * Only populated when ids identify every position on both sides (every+ * submitted item carried an `id` and every returned item echoed one);+ * `undefined` otherwise, since the set difference could otherwise mislabel a+ * present-but-unnamed item as missing.+ */+ readonly missingIds: string[] | undefined;++ constructor(+ message: string,+ options: {+ expected: number;+ received: number;+ code?: string;+ model?: string;+ missingIds?: string[];+ requestId?: string;+ },+ ) {+ super(message, options.code, 200, options.requestId);+ this.name = "IncompleteBatchError";+ this.expected = options.expected;+ this.received = options.received;+ this.model = options.model;+ this.missingIds = options.missingIds;+ }+}++/**+ * A job reached a non-successful terminal state (`failed`/`suspended`/`cancelled`).+ *+ * Thrown by {@link SIEClient.jobs}`.wait` only when called with+ * `raiseOnFailure: true`; the default remains back-compatible and returns the+ * terminal status doc unchanged. The gateway's terminal reason rides `outcome`+ * / `error_code` on the status doc, so this surfaces them and a caller can+ * branch on the failure without re-reading the doc. Mirrors the Python SDK's+ * `JobFailedError`.+ */+export class JobFailedError extends SIEError {+ /** The job that failed. */+ readonly jobId: string | undefined;++ /** The terminal state (`failed`, `suspended`, or `cancelled`). */+ readonly state: string | undefined;++ /**+ * The gateway's terminal outcome (e.g. `reexecution_required`), or+ * `null`/`undefined` when the status doc carried none.+ */+ readonly outcome: string | null | undefined;++ /**+ * The gateway's terminal error code (e.g. `RESULT_HANDLE_EXPIRED`), or+ * `null`/`undefined` when absent.+ */+ readonly errorCode: string | null | undefined;++ constructor(+ message: string,+ options: {+ jobId?: string;+ state?: string;+ outcome?: string | null;+ errorCode?: string | null;+ } = {},+ ) {+ super(message);+ this.name = "JobFailedError";+ this.jobId = options.jobId;+ this.state = options.state;+ this.outcome = options.outcome;+ this.errorCode = options.errorCode;+ }+}++/**+ * A chunk ref's bytes could not be decoded as a msgpack `WorkResult` array.+ *+ * Distinct from a chunk that published no ref at all: the bytes exist but are+ * garbage (not msgpack, or not a list). That is a DECODE fault, not evidence of+ * failed publication or billing, so `jobs.results` confines it (one bad chunk+ * cannot sink the whole call) and flags it separately, never conflating it with+ * a genuinely-unpublished, already-billed chunk. Mirrors the Python SDK's+ * `MalformedChunkError`.+ */+export class MalformedChunkError extends SIEError {+ constructor(message: string) {+ super(message);+ this.name = "MalformedChunkError";+ }+}+/*** The gateway cannot PRICE the request, so it will not run it either.*@@ -352,3 +497,105 @@ export class EstimateUnroutableError extends ServerError {this.name = "EstimateUnroutableError";}}++/**+ * Error when the gateway rate-limits the caller and retries are exhausted.+ *+ * Thrown when the gateway returns HTTP `429 TOO_MANY_REQUESTS` (code+ * `RATE_LIMIT`, per-key or per-account, default-on) and the SDK's bounded,+ * `Retry-After`-honoring retry budget (capped by the provision timeout) is+ * spent. The SDK honors the server's `Retry-After` on each attempt before+ * giving up.+ *+ * Subclass of {@link RequestError} so existing 4xx handlers keep working; new+ * code can catch {@link RateLimitError} specifically to back off at a higher+ * level, shed load, or route elsewhere. Mirrors the Python SDK's+ * `RateLimitError`.+ */+export class RateLimitError extends RequestError {+ /** Last `Retry-After` hint the server supplied, in milliseconds. */+ readonly retryAfter: number | undefined;++ constructor(+ message: string,+ options?: { retryAfter?: number; code?: string; requestId?: string },+ ) {+ super(message, options?.code ?? "RATE_LIMIT", 429, options?.requestId);+ this.name = "RateLimitError";+ this.retryAfter = options?.retryAfter;+ }+}++/**+ * Error when the account has insufficient credits to run the request.+ *+ * Thrown when the gateway returns HTTP `402 PAYMENT_REQUIRED` with code+ * `INSUFFICIENT_CREDITS`. This is a TERMINAL billing failure — the SDK never+ * retries it, because retrying a credit failure would be wrong.+ *+ * Subclass of {@link RequestError} so existing 4xx handlers keep working.+ * Mirrors the Python SDK's `InsufficientCreditsError`.+ */+export class InsufficientCreditsError extends RequestError {+ constructor(message: string, options?: { requestId?: string }) {+ super(message, "INSUFFICIENT_CREDITS", 402, options?.requestId);+ this.name = "InsufficientCreditsError";+ }+}++/**+ * Error when the API key's configured spend limit is exceeded.+ *+ * Thrown when the gateway returns HTTP `402 PAYMENT_REQUIRED` with code+ * `KEY_SPEND_LIMIT_EXCEEDED`. This is a TERMINAL policy failure — the SDK+ * never retries it. Distinct from {@link InsufficientCreditsError}: the+ * account may have credits, but this key has hit its own spend cap.+ *+ * Subclass of {@link RequestError} so existing 4xx handlers keep working.+ * Mirrors the Python SDK's `SpendLimitError`.+ */+export class SpendLimitError extends RequestError {+ constructor(message: string, options?: { requestId?: string }) {+ super(message, "KEY_SPEND_LIMIT_EXCEEDED", 402, options?.requestId);+ this.name = "SpendLimitError";+ }+}++/**+ * Error when the account is not permitted to submit work.+ *+ * Thrown when the gateway returns HTTP `403 FORBIDDEN` with code+ * `ACCOUNT_SUSPENDED` or `ACCOUNT_PENDING_REVIEW`. This is a TERMINAL+ * account-state failure — the SDK never retries it, because the account must+ * be activated/reinstated out of band before work is accepted. Branch on+ * `code` to distinguish suspended vs pending review.+ *+ * Subclass of {@link RequestError} so existing 4xx handlers keep working.+ * Mirrors the Python SDK's `AccountInactiveError`.+ */+export class AccountInactiveError extends RequestError {+ constructor(message: string, code?: string, requestId?: string) {+ super(message, code, 403, requestId);+ this.name = "AccountInactiveError";+ }+}++/**+ * Error when the gateway cannot resolve the account's admission state.+ *+ * Thrown when the gateway returns HTTP `503` with code+ * `ACCOUNT_STATE_UNAVAILABLE` — a fail-closed infrastructure signal (the+ * control plane could not resolve account state), distinct from a customer+ * suspension. Surfaced as a typed TERMINAL error rather than being retried on+ * the SDK's admission ladder: a caller may re-issue the whole request, but the+ * SDK does not silently loop on an unresolved account state.+ *+ * Subclass of {@link ServerError} so existing 5xx handlers keep working.+ * Mirrors the Python SDK's `AccountStateUnavailableError`.+ */+export class AccountStateUnavailableError extends ServerError {+ constructor(message: string, requestId?: string) {+ super(message, "ACCOUNT_STATE_UNAVAILABLE", 503, requestId);+ this.name = "AccountStateUnavailableError";+ }+}diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.tsindex 81b98a029..41f85fc4f 100644--- a/packages/sie_ts_sdk/src/index.ts+++ b/packages/sie_ts_sdk/src/index.ts@@ -8,11 +8,11 @@* const client = new SIEClient("http://localhost:8080");** // Encode text to get embeddings- * const result = await client.encode("bge-m3", { text: "Hello world" });+ * const result = await client.encode("BAAI/bge-m3", { text: "Hello world" });* console.log(result.dense); // Float32Array** // Batch encode- * const results = await client.encode("bge-m3", [+ * const results = await client.encode("BAAI/bge-m3", [* { text: "First document" },* { text: "Second document" },* ]);@@ -50,6 +50,7 @@ export type {JobChunk,JobSubmitResult,JobStatus,+ JobItemErrorDetail,JobResultItem,JobResults,} from "./jobs.js";@@ -79,7 +80,12 @@ export type {ModelCapabilities,ModelDims,ModelInfo,+ ModelLoadError,ModelState,+ PendingGeneration,+ PendingGenerationGroup,+ ProfileInfo,+ WireModelInfo,WorkerInfo,CapacityInfo,ClusterSummary,@@ -178,6 +184,14 @@ export {SIEStreamError,InputTooLongError,EstimateUnroutableError,+ IncompleteBatchError,+ JobFailedError,+ MalformedChunkError,+ RateLimitError,+ InsufficientCreditsError,+ SpendLimitError,+ AccountInactiveError,+ AccountStateUnavailableError,} from "./errors.js";// Client-side scoring (MaxSim for ColBERT-style models)diff --git a/packages/sie_ts_sdk/src/internal/constants.ts b/packages/sie_ts_sdk/src/internal/constants.tsindex d99c67f1c..4c5f24919 100644--- a/packages/sie_ts_sdk/src/internal/constants.ts+++ b/packages/sie_ts_sdk/src/internal/constants.ts@@ -17,7 +17,7 @@ export const DEFAULT_TIMEOUT = 30_000; // 30 seconds// a large upload / connector preflight / batch creation does not abort while the// server keeps working. Matches the Python SDK's 120s floor.export const DEFAULT_LONG_RUNNING_TIMEOUT = 120_000; // 2 minutes-export const DEFAULT_PROVISION_TIMEOUT = 300_000; // 5 minutes (300s matches Python SDK)+export const DEFAULT_PROVISION_TIMEOUT = 900_000; // 15 minutes (900s matches the Python SDK's DEFAULT_PROVISION_TIMEOUT_S)export const DEFAULT_RETRY_DELAY = 5_000; // 5 seconds (matches Python SDK)export const DEFAULT_MAX_RETRY_DELAY = 30_000; // 30 secondsexport const DEFAULT_LEASE_RENEWAL_INTERVAL = 60_000; // 1 minute@@ -44,6 +44,40 @@ export const RESOURCE_EXHAUSTED_DEFAULT_DELAY = 5_000; // Base backoff (ms)export const RESOURCE_EXHAUSTED_MAX_DELAY = 30_000; // Backoff ceiling (ms)export const RESOURCE_EXHAUSTED_ERROR_CODE = "RESOURCE_EXHAUSTED"; // Error code from server+// Pre-execution admission backpressure / billing signals (pass-2 audit).+// Emitted BEFORE any work is published to the queue, so retrying is idempotent+// even on the non-idempotent generate paths. Retried on the admission ladder+// (`admissionRetryDelay`), bounded by the provision-timeout budget and the+// server's `Retry-After`. Mirrors the Python SDK+// (packages/sie_sdk/src/sie_sdk/client/_shared.py).+//+// B1 — 429 rate limit (rate_limit.rs): per-key/per-account, default-on.+export const HTTP_TOO_MANY_REQUESTS = 429;+export const RATE_LIMIT_ERROR_CODE = "RATE_LIMIT";+export const RATE_LIMIT_DEFAULT_DELAY = 1_000; // Fallback (ms) when the server omits Retry-After+// B2 — 503 BILLING_CAPACITY_UNAVAILABLE (slab_ledger.rs): a gateway-local+// billing-family cap, NOT customer credit exhaustion. B7 — 503 QUEUE_FULL+// (self-hosted server, #3180): transient queue backpressure. Both send+// Retry-After: 1 and were previously unmatched by the retry ladder.+export const BILLING_CAPACITY_UNAVAILABLE_ERROR_CODE = "BILLING_CAPACITY_UNAVAILABLE";+export const QUEUE_FULL_ERROR_CODE = "QUEUE_FULL";+export const BACKPRESSURE_503_ERROR_CODES: ReadonlySet<string> = new Set([+ BILLING_CAPACITY_UNAVAILABLE_ERROR_CODE,+ QUEUE_FULL_ERROR_CODE,+]);+export const BACKPRESSURE_503_DEFAULT_DELAY = 1_000; // Fallback (ms) when the server omits Retry-After++// Terminal credit / account errors (pass-2 audit B3) — NEVER retried. 402/403+// credit/account failures are mapped to typed exceptions in `handleError` and,+// having no arm on any retry ladder, surface on the first response.+export const HTTP_PAYMENT_REQUIRED = 402;+export const HTTP_FORBIDDEN = 403;+export const INSUFFICIENT_CREDITS_ERROR_CODE = "INSUFFICIENT_CREDITS";+export const KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE = "KEY_SPEND_LIMIT_EXCEEDED";+export const ACCOUNT_SUSPENDED_ERROR_CODE = "ACCOUNT_SUSPENDED";+export const ACCOUNT_PENDING_REVIEW_ERROR_CODE = "ACCOUNT_PENDING_REVIEW";+export const ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE = "ACCOUNT_STATE_UNAVAILABLE";+// Version negotiation headersexport const SDK_VERSION_HEADER = "X-SIE-SDK-Version";export const SERVER_VERSION_HEADER = "X-SIE-Server-Version";diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.tsindex e45de848e..39e443aaf 100644--- a/packages/sie_ts_sdk/src/internal/parsing.ts+++ b/packages/sie_ts_sdk/src/internal/parsing.ts@@ -3,12 +3,18 @@*/import {+ AccountInactiveError,+ AccountStateUnavailableError,EstimateUnroutableError,+ IncompleteBatchError,InputTooLongError,+ InsufficientCreditsError,ModelLoadFailedError,ProvisioningError,+ RateLimitError,RequestError,ServerError,+ SpendLimitError,} from "../errors.js";import { unpackMessage } from "../msgpack.js";import type {@@ -27,10 +33,18 @@ import type {WorkerInfo,} from "../types.js";import {+ ACCOUNT_PENDING_REVIEW_ERROR_CODE,+ ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE,+ ACCOUNT_SUSPENDED_ERROR_CODE,HTTP_CLIENT_ERROR_MAX,HTTP_CLIENT_ERROR_MIN,+ HTTP_FORBIDDEN,+ HTTP_PAYMENT_REQUIRED,HTTP_SERVER_ERROR_MAX,HTTP_SERVER_ERROR_MIN,+ HTTP_TOO_MANY_REQUESTS,+ INSUFFICIENT_CREDITS_ERROR_CODE,+ KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE,MSGPACK_CONTENT_TYPE,PROVISIONING_ERROR_CODE,} from "./constants.js";@@ -38,12 +52,42 @@ import {import { getRetryAfter as getRetryAfterFromHeader } from "./retry.js";const SIE_ERROR_CODE_HEADER = "X-SIE-Error-Code";+const REQUEST_ID_HEADER = "x-sie-request-id";function normalizeErrorCode(code: string | undefined): string | undefined {if (code === "provisioning") return PROVISIONING_ERROR_CODE;return code;}+/**+ * Read the gateway request id from a terminal response, applying the same+ * validation as `parseRequestMetadata` (non-empty visible ASCII, no+ * surrounding whitespace, bounded length). Returns `undefined` when absent+ * or malformed so errors never carry an attacker-shaped id (#3136).+ */+export function readRequestId(response: Response): string | undefined {+ return validateRequestId(response.headers.get(REQUEST_ID_HEADER));+}++/**+ * Validate one candidate request id (non-empty visible ASCII, no surrounding+ * whitespace, bounded length). Shared by the header path above and the+ * in-band stream error path so streamed ids obey the same rule and errors+ * never carry an attacker-shaped id (#3136).+ */+export function validateRequestId(value: unknown): string | undefined {+ if (+ typeof value === "string" &&+ value.length > 0 &&+ value.length <= 256 &&+ value === value.trim() &&+ /^[\x20-\x7e]+$/.test(value)+ ) {+ return value;+ }+ return undefined;+}+/*** Parse GPU parameter from "pool/gpu" format*/@@ -275,26 +319,54 @@ export async function handleError(response: Response, gpu?: string): Promise<nev}}code = response.headers.get(SIE_ERROR_CODE_HEADER) ?? normalizeErrorCode(code);+ const requestId = readRequestId(response);if (status === 503 && code === PROVISIONING_ERROR_CODE) {const retryAfter = getRetryAfter(response);throw new ProvisioningError(message, gpu, retryAfter);}+ // Rate limit (pass-2 audit B1). Retried on the admission ladder in the+ // buffered loops; a give-up there throws RateLimitError directly. This arm+ // covers the terminal paths (streaming, listModels, estimate, …) so a 429 is+ // always a typed RateLimitError rather than a generic RequestError.+ if (status === HTTP_TOO_MANY_REQUESTS) {+ throw new RateLimitError(message, { retryAfter: getRetryAfter(response), code, requestId });+ }++ // Terminal credit / account failures (pass-2 audit B3). 402/403 are NEVER+ // retried — they have no arm on any retry ladder, so they surface here on the+ // first response. Unrecognised 402/403 codes stay generic RequestError.+ if (status === HTTP_PAYMENT_REQUIRED) {+ if (code === INSUFFICIENT_CREDITS_ERROR_CODE)+ throw new InsufficientCreditsError(message, { requestId });+ if (code === KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE)+ throw new SpendLimitError(message, { requestId });+ }+ if (+ status === HTTP_FORBIDDEN &&+ (code === ACCOUNT_SUSPENDED_ERROR_CODE || code === ACCOUNT_PENDING_REVIEW_ERROR_CODE)+ ) {+ throw new AccountInactiveError(message, code, requestId);+ }+ if (status === 503 && code === ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE) {+ throw new AccountStateUnavailableError(message, requestId);+ }+if (status >= HTTP_CLIENT_ERROR_MIN && status <= HTTP_CLIENT_ERROR_MAX) {if (status === 400 && code === "INPUT_TOO_LONG") {// Fallback dispatch — ``model`` is only attached by the helper-style// short-circuit (``throwIfInputTooLong``) on the extract path.throw new InputTooLongError(message);}- throw new RequestError(message, code, status);+ throw new RequestError(message, code, status, requestId);}if (status >= HTTP_SERVER_ERROR_MIN && status <= HTTP_SERVER_ERROR_MAX) {- throw new ServerError(message, code, status);+ throw new ServerError(message, code, status, requestId);}- throw new ServerError(message, code, status);+ throw new ServerError(message, code, status, requestId);}// Wire format types (what server sends)@@ -434,6 +506,92 @@ export function parseEncodeResults(data: unknown[]): EncodeResult[] {return (data as WireEncodeResult[]).map(parseEncodeResult);}+/**+ * Best-effort ids of submitted items absent from a shortened response.+ *+ * Only computed when ids identify every position on both sides: every+ * submitted item carries a string `id` and every returned item echoes one.+ * Otherwise the set difference could mislabel a present-but-unnamed item as+ * missing, so the diagnostic degrades to `undefined` (positional counts only).+ *+ * Runs only while building an error, so it degrades rather than throwing.+ */+function missingResultIds(+ results: readonly unknown[],+ submitted: readonly unknown[],+): string[] | undefined {+ const idOf = (value: unknown): string | undefined => {+ if (typeof value !== "object" || value === null) {+ return undefined;+ }+ const id = (value as { id?: unknown }).id;+ return typeof id === "string" ? id : undefined;+ };++ const submittedIds = submitted.map(idOf);+ if (submittedIds.some((id) => id === undefined)) {+ return undefined;+ }+ const returnedIds = new Set<string>();+ for (const result of results) {+ const id = idOf(result);+ if (id === undefined) {+ return undefined;+ }+ returnedIds.add(id);+ }+ const missing = submittedIds.filter(+ (id): id is string => id !== undefined && !returnedIds.has(id),+ );+ return missing.length > 0 ? missing : undefined;+}++/**+ * Guard the positional batch contract: exactly one result per input item.+ *+ * Encode and extract are positional — both return `results[0]` for a+ * single-item request, and batch callers reassemble results by index. The+ * contract breaks on an HTTP 200 whose `items` list is *shorter* than the+ * request: the gateway returns mixed-success batches as `200` carrying only+ * the successful items (a per-item server-side failure — an input exceeding+ * the model's `max_sequence_length`, say — is dropped from the body, not+ * surfaced as an error envelope). Without this check the short list flows into+ * positional access and silently misaligns every result after the drop.+ *+ * Mirrors the Python SDK's `validate_batch_result_count`, including its error+ * codes, so both SDKs fail identically.+ *+ * @throws {IncompleteBatchError} If the counts differ.+ */+export function validateBatchResultCount(+ results: readonly unknown[],+ submitted: readonly unknown[],+ model: string,+ operation: "encode" | "extract",+ requestId?: string,+): void {+ if (results.length === submitted.length) {+ return;+ }+ const [label, noun, code] =+ operation === "encode"+ ? ["Encode", "embedding(s)", "ENCODE_RESULT_COUNT_MISMATCH"]+ : ["Extract", "extraction result(s)", "EXTRACT_RESULT_COUNT_MISMATCH"];+ const missingIds = missingResultIds(results, submitted);+ let message = `${label} response desync for model ${JSON.stringify(model)}: server returned ${results.length} ${noun} for ${submitted.length} input item(s); expected exactly one per input. An input may have failed server-side (e.g. exceeding the model's max_sequence_length) and been dropped from the batch.`;+ if (missingIds !== undefined) {+ message += ` Missing item id(s): ${missingIds.join(", ")}.`;+ }+ throw new IncompleteBatchError(message, {+ expected: submitted.length,+ received: results.length,+ code,+ model,+ missingIds,+ requestId,+ });+}+/*** Parse wire format to ScoreEntry*/diff --git a/packages/sie_ts_sdk/src/internal/provisioning.ts b/packages/sie_ts_sdk/src/internal/provisioning.tsindex f2543db09..6cf63c404 100644--- a/packages/sie_ts_sdk/src/internal/provisioning.ts+++ b/packages/sie_ts_sdk/src/internal/provisioning.ts@@ -2,12 +2,16 @@* Shared provisioning / retry loop for non-streaming POST endpoints.** Both {@link SIEClient.generate} and {@link SIEClient.chatCompletions}- * receive identical pre-execution capacity signals from the gateway —+ * receive the same pre-execution capacity signals from the gateway —* `503` with a known error code (`PROVISIONING`, `MODEL_LOADING` or- * `RESOURCE_EXHAUSTED`). They both need to retry those SAFE- * pre-execution signals while honouring a caller-supplied- * `waitForCapacity` flag plus a `provisionTimeout` budget. A `504` is- * post-publish and therefore terminal here (non-idempotent generation).+ * `RESOURCE_EXHAUSTED`) — and retry them under a `provisionTimeout`+ * budget. Only `503 PROVISIONING` is gated by the caller's+ * `waitForCapacity` flag; `503 MODEL_LOADING` and `503+ * RESOURCE_EXHAUSTED` are retried regardless (the worker already+ * accepted the request). A `504` is post-publish, and a rejected+ * `performFetch` may fire after the body was sent, so both are terminal+ * here — this loop serves non-idempotent generation and a retry could+ * double-bill.** This helper centralises that loop. Callers supply a `performFetch`* callback that issues a fresh `fetch` per attempt (the request must be@@ -23,20 +27,31 @@import {ModelLoadingError,ProvisioningError,+ RateLimitError,RequestError,ResourceExhaustedError,ServerError,} from "../errors.js";import {+ BACKPRESSURE_503_DEFAULT_DELAY,+ BACKPRESSURE_503_ERROR_CODES,DEFAULT_RETRY_DELAY,HTTP_GATEWAY_TIMEOUT,+ HTTP_TOO_MANY_REQUESTS,MODEL_LOADING_DEFAULT_DELAY,MODEL_LOADING_ERROR_CODE,PROVISIONING_ERROR_CODE,+ RATE_LIMIT_DEFAULT_DELAY,RESOURCE_EXHAUSTED_ERROR_CODE,RESOURCE_EXHAUSTED_MAX_RETRIES,} from "./constants.js";-import { getErrorCode, getRetryAfter, handleError, throwIfModelLoadFailed } from "./parsing.js";+import {+ getErrorCode,+ getRetryAfter,+ handleError,+ readRequestId,+ throwIfModelLoadFailed,+} from "./parsing.js";import { applyRetryJitter, computeOomBackoff } from "./retry.js";/** Options controlling the provisioning retry loop. */@@ -46,9 +61,20 @@ export interface ProvisioningOptions {/** GPU label passed through to `ProvisioningError`. May be `undefined`. */gpu: string | undefined;/**- * When `true`, the loop retries `503 PROVISIONING` / `503 MODEL_LOADING`- * until the provision budget is exhausted. When `false`, the first- * provisioning signal throws (the call-site opted out of waiting).+ * Controls `503 PROVISIONING` ONLY. When `true`, the loop retries a+ * `PROVISIONING` signal until `provisionTimeoutMs` is exhausted; when+ * `false`, the first `PROVISIONING` signal throws `ProvisioningError`+ * (the call-site opted out of capacity waiting). It does NOT gate any+ * other outcome:+ * - `503 MODEL_LOADING` and `503 RESOURCE_EXHAUSTED` are retried+ * regardless of this flag (each retry bounded by+ * `provisionTimeoutMs`; `RESOURCE_EXHAUSTED` additionally bounded by+ * `RESOURCE_EXHAUSTED_MAX_RETRIES`) because the worker already+ * accepted the request — matching the Python SDK.+ * - A `504` gateway timeout and any rejected `performFetch`+ * (fetch-level connection failure) are ALWAYS terminal here, never+ * retried under any flag value: this loop serves non-idempotent+ * generation, so a retry could double-bill.*/waitForCapacity: boolean;/**@@ -103,6 +129,83 @@ export function nextOomRetryDelay(opts: {return delay;}+/**+ * Delay (ms) before retrying a pre-execution admission rejection, or+ * `undefined` when the response is not a retryable admission signal (the+ * caller then falls through to its existing terminal handling).+ *+ * Handles the pass-2 audit backpressure/billing signals that are safe to retry+ * because NO work has been published to the queue yet — they are admission+ * decisions the gateway/self-hosted server makes *before* dispatch, so+ * retrying is idempotent even on the non-idempotent generate paths:+ *+ * - `429 TOO_MANY_REQUESTS` (code `RATE_LIMIT`, B1) — per-key/per-account rate+ * limiting. On give-up (provision-timeout budget spent) throws a typed+ * {@link RateLimitError} carrying the last `Retry-After`.+ * - `503 BILLING_CAPACITY_UNAVAILABLE` (B2 — a gateway-local billing-family+ * cap, NOT customer credit exhaustion) and `503 QUEUE_FULL` (B7 — self-hosted+ * queue backpressure, #3180). On give-up throws the server's terminal 503+ * verbatim via {@link handleError} (a {@link ServerError} preserving the code).+ *+ * Retry timing mirrors the PROVISIONING arm: the server-supplied `Retry-After`+ * is honored verbatim, and only the SDK's own fallback default is jittered.+ * Give-up mirrors `nextOomRetryDelay`: when the budget is spent OR the next+ * wait would consume the rest of it (leaving no room for the retried request to+ * run), the typed root cause is surfaced NOW instead of sleeping the budget+ * away and letting the outer loop mask it.+ *+ * IMPORTANT: 402/403 credit/account failures are deliberately NOT handled here.+ * They are terminal and must never be retried; {@link handleError} maps them to+ * typed exceptions on the first response. Mirrors the Python SDK's+ * `admission_retry_delay`.+ *+ * @internal+ */+export async function admissionRetryDelay(+ response: Response,+ opts: { startTime: number; provisionTimeoutMs: number },+): Promise<number | undefined> {+ const { startTime, provisionTimeoutMs } = opts;+ const { status } = response;++ if (status === HTTP_TOO_MANY_REQUESTS) {+ const retryAfter = getRetryAfter(response);+ const elapsed = Date.now() - startTime;+ const remaining = provisionTimeoutMs - elapsed;+ const delay = retryAfter ?? applyRetryJitter(Math.min(RATE_LIMIT_DEFAULT_DELAY, remaining));+ if (remaining <= 0 || delay >= remaining) {+ // Preserve the gateway request id from the final 429 so the typed+ // give-up stays correlatable with gateway logs, matching the direct+ // terminal 429 mapped by `handleError` (#3136).+ throw new RateLimitError(+ `Rate limited (429); retry budget (${provisionTimeoutMs}ms) exhausted after ${elapsed}ms`,+ { retryAfter, requestId: readRequestId(response) },+ );+ }+ return delay;+ }++ if (status === 503) {+ const code = await getErrorCode(response.clone());+ if (code !== undefined && BACKPRESSURE_503_ERROR_CODES.has(code)) {+ const retryAfter = getRetryAfter(response);+ const elapsed = Date.now() - startTime;+ const remaining = provisionTimeoutMs - elapsed;+ const delay =+ retryAfter ?? applyRetryJitter(Math.min(BACKPRESSURE_503_DEFAULT_DELAY, remaining));+ if (remaining <= 0 || delay >= remaining) {+ // Budget spent (or the next wait would consume it): surface the+ // server's terminal 503 (ServerError, code preserved). `handleError`+ // always throws.+ await handleError(response);+ }+ return delay;+ }+ }++ return undefined;+}+/*** Wrap a non-streaming POST attempt in the shared provisioning retry loop.*@@ -125,6 +228,15 @@ export async function withProvisioningRetry(let oomRetries = 0;while (true) {+ // INTENTIONAL divergence from the Python SDK: Python's generate() retries+ // `httpx.ConnectError` because httpx guarantees it fires *before* the+ // request body is sent. `fetch` offers no such distinction — a rejected+ // fetch promise (`TypeError`) can mean a pre-connect DNS/refused failure+ // OR a connection reset *after* the (non-idempotent, non-deduped) request+ // body was transmitted, when a worker may already be generating. Retrying+ // here could issue a second billable generation, so fetch-level failures+ // from `performFetch` are surfaced as terminal `SIEConnectionError`+ // instead of being retried.const response = await performFetch();// 502 MODEL_LOAD_FAILED is terminal — surface immediately.@@ -179,6 +291,22 @@ export async function withProvisioningRetry(}}+ // Retryable pre-execution admission backpressure (pass-2 audit B1/B2/B7):+ // a 429 RATE_LIMIT, or a retryable 503 (BILLING_CAPACITY_UNAVAILABLE /+ // QUEUE_FULL). These are admission rejections BEFORE the work is published,+ // so retrying is safe (unlike the post-publish 504 below). Honor+ // Retry-After within the provision-timeout budget; a give-up throws a typed+ // RateLimitError (429) or the server's terminal 503. 402/403 credit/account+ // errors are terminal and NOT handled here.+ const admissionDelay = await admissionRetryDelay(response, {+ startTime,+ provisionTimeoutMs: opts.provisionTimeoutMs,+ });+ if (admissionDelay !== undefined) {+ await sleep(admissionDelay);+ continue;+ }+// Do NOT retry 504. A 504 GATEWAY_TIMEOUT is a *post-publish* timeout:// the work item is already on the queue and a worker may be — or have// finished — generating. Generation is non-idempotent and carries nodiff --git a/packages/sie_ts_sdk/src/jobs.ts b/packages/sie_ts_sdk/src/jobs.tsindex d96567f1a..4d92ebf1c 100644--- a/packages/sie_ts_sdk/src/jobs.ts+++ b/packages/sie_ts_sdk/src/jobs.ts@@ -7,7 +7,7 @@* mirror the Python SDK's `sie_sdk.jobs`.*/-import { RequestError } from "./errors.js";+import { MalformedChunkError, RequestError } from "./errors.js";import { unpackMessage } from "./msgpack.js";/** Job lifecycle state (queued → running → terminal). */@@ -300,13 +300,38 @@ export interface JobStatus {output?: { kind?: string; chunks?: JobChunk[] };}-/** One decoded per-item result retrieved from a finished job's chunk refs. */+/**+ * Stable per-item job failure (mirrors the Python SDK's `JobItemErrorDetail`).+ *+ * Decoded from the failed item's `WorkResult` in a chunk ref: `code` is the+ * worker's `error_code` and `message` its free-text `error`. Either may be+ * absent, so both keys are optional.+ */+export interface JobItemErrorDetail {+ code?: string;+ message?: string;+}++/**+ * One decoded per-item result retrieved from a finished job's chunk refs.+ *+ * A `failed` chunk still writes a result ref carrying every item's+ * `WorkResult` — successful siblings AND the failures — so `success`+ * distinguishes them and `error` carries the failure reason when the item did+ * not succeed.+ */export interface JobResultItem {- id: string | null;+ /**+ * Per-item id echoed from the item's `WorkResult` (`id` or the wire's+ * `work_item_id`). Ids may be numbers, so `0` is a valid id, not absent.+ */+ id: string | number | null;success: boolean | null;units: unknown;dims: number | null;dense: number[] | Float32Array | null;+ /** Why this item failed; absent on a success (and on a bare-count chunk error). */+ error?: JobItemErrorDetail;}/** A finished job's decoded results — the chunk refs read and unpacked. */@@ -681,9 +706,43 @@ function denseInfo(dense: unknown): {return { dims: vector != null ? vector.length : null, vector };}-/** Decode one WorkResult map (from a chunk ref) into a per-item result. */-export function decodeResultItem(result: Record<string, unknown>): JobResultItem {- const payload = result.result_msgpack;+/**+ * Extract a per-item failure from a `WorkResult` map (`error`/`error_code`).+ *+ * The gateway writes every item's `WorkResult` into the chunk ref — including+ * failures, each carrying its own `error` (free text) and `error_code` — so a+ * caller can see WHY a specific item failed. Returns `undefined` when the item+ * reports no failure signal (a success, or a bare-count chunk error with no+ * per-item detail).+ */+function resultItemError(result: Record<string, unknown>): JobItemErrorDetail | undefined {+ const code = result.error_code;+ const message = result.error;+ if (code == null && message == null) return undefined;+ // Only strings reach the public shape. These values come off the wire+ // unvalidated, and this path now reads FAILED chunks too, so a non-string+ // `error_code` would otherwise be asserted straight through and violate+ // `JobItemErrorDetail` for the caller.+ const detail: JobItemErrorDetail = {};+ if (typeof code === "string") detail.code = code;+ if (typeof message === "string") detail.message = message;+ // A failure signalled only by non-string junk still counts as a failure;+ // returning `{}` keeps `error` present (truthy check) without lying about+ // the code or message.+ return detail;+}++/**+ * Decode one WorkResult map (from a chunk ref) into a per-item result.+ *+ * A failed item carries no `result_msgpack` but does carry `success: false`+ * plus an `error`/`error_code` pair, which surfaces as {@link+ * JobResultItem.error}.+ */+export function decodeResultItem(result: unknown): JobResultItem {+ const rec: Record<string, unknown> =+ result != null && typeof result === "object" ? (result as Record<string, unknown>) : {};+ const payload = rec.result_msgpack;let decoded: Record<string, unknown> | null = null;if (payload instanceof Uint8Array) {try {@@ -694,18 +753,48 @@ export function decodeResultItem(result: Record<string, unknown>): JobResultItem}const dense = decoded && typeof decoded === "object" ? decoded.dense : null;const { dims, vector } = denseInfo(dense);- return {- id: (result.id as string) ?? null,- success: (result.success as boolean) ?? null,- units: result.units ?? null,+ // The wire id is `work_item_id`; older/inline results use `id`. The bare-count+ // chunk error names no ids, so a per-item id comes only from the item's own+ // WorkResult (never fabricated). `??` (not `||`) so a falsy-but-valid id — the+ // number `0` or an empty string — is preserved rather than replaced.+ // Validated, not asserted: an id of `{}` or a `success` of `"false"` would+ // otherwise be cast straight into the public shape. Anything off-contract+ // degrades to `null` rather than misrepresenting the wire.+ const rawId = rec.id ?? rec.work_item_id ?? null;+ const id = typeof rawId === "string" || typeof rawId === "number" ? rawId : null;+ const item: JobResultItem = {+ id,+ success: typeof rec.success === "boolean" ? rec.success : null,+ units: rec.units ?? null,dims,dense: vector,};+ const error = resultItemError(rec);+ if (error !== undefined) item.error = error;+ return item;}-/** Decode a chunk ref's msgpack `WorkResult` array into per-item results. */+/**+ * Decode a chunk ref's msgpack `WorkResult` array into per-item results.+ *+ * @throws {MalformedChunkError} If the ref's bytes are not decodable msgpack or+ * do not decode to a list. The caller confines this (one bad chunk cannot sink+ * the whole `jobs.results()` call) and reports it as a decode fault, distinct+ * from an unpublished chunk. Per-item decoding stays defensive (see+ * {@link decodeResultItem}).+ */export function decodeChunkBytes(raw: Uint8Array): JobResultItem[] {- const results = unpackMessage<unknown>(raw);- if (!Array.isArray(results)) return [];- return results.map((r) => decodeResultItem(r as Record<string, unknown>));+ let results: unknown;+ try {+ results = unpackMessage<unknown>(raw);+ } catch (error) {+ // Normalize any decode failure to one signal.+ throw new MalformedChunkError(+ `chunk ref bytes are not decodable msgpack: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ if (!Array.isArray(results)) {+ throw new MalformedChunkError("chunk ref bytes did not decode to a WorkResult array");+ }+ return results.map((r) => decodeResultItem(r));}diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex 02094c1d6..ed314b1b6 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -218,26 +218,168 @@ export interface ModelCapabilities {guard?: boolean;}+/**+ * One entry of `ModelInfo.profiles`.+ *+ * Mirrors the server's `ProfileInfo` and the gateway's `ProfileInfoWire`.+ * `is_default` marks the profile served when a request names the bare model+ * id rather than `model@profile`.+ */+export interface ProfileInfo {+ /** Whether this profile is served for a bare (un-suffixed) model id */+ is_default?: boolean;+}++/**+ * Diagnostic detail for a recorded model load failure.+ *+ * Present as `ModelInfo.lastError` when the registry holds a sticky failure+ * (normally alongside `state === "failed"`), `null` otherwise.+ *+ * `permanent` is the field to branch on: `true` means the load will not+ * auto-retry and an operator must intervene, so a client should surface the+ * failure rather than poll.+ */+export interface ModelLoadError {+ /** Stable enum value ("GATED", "OOM", ...) for client routing */+ code: string;+ /** Human-readable summary, including the underlying exception */+ message: string;+ /** How many load attempts have failed so far */+ attempts: number;+ /** True when the failure will not auto-retry */+ permanent: boolean;+}++/** Queue-depth breakdown for one (model, pool) pair. */+export interface PendingGenerationGroup {+ model: string;+ display_model: string;+ pool: string;+ count: number;+ waiting_first_chunk: number;+ active_streams: number;+ republished: number;+ oldest_request_age_ms: number;+}++/**+ * In-flight generation work the gateway holds for a model.+ *+ * Gateway-only: a single `sie_server` has no queue and omits the field. This+ * is a point-in-time telemetry snapshot, not model metadata — for continuous+ * monitoring prefer `watch()` over polling `/v1/models`.+ */+export interface PendingGeneration {+ total: number;+ groups: PendingGenerationGroup[];+}+/*** Information about a model returned by listModels().+ *+ * Top-level keys are camelCased from the wire (see `WireModelInfo`); nested+ * objects keep their wire shape. The declared set is pinned by+ * `packages/wire-fixtures/model_info.json` and enforced in+ * `tests/wireContract.test.ts`. The OpenAI-compat keys id/object/created/+ * owned_by that `GET /v1/models/{model}` merges in are deliberately excluded+ * — see that fixture for why.*/export interface ModelInfo {/** Model name/identifier */name: string;- /** Whether the model is currently loaded in memory */+ /** Whether the model is currently loaded in memory. Prefer `state`. */loaded: boolean;+ /**+ * Lifecycle state, including the terminal "failed" branch.+ *+ * `loaded` cannot distinguish "available" from "loading" from "failed" —+ * all three report false.+ */+ state?: ModelState;+ /** Recorded load failure (when `state === "failed"`), else null */+ lastError?: ModelLoadError | null;/** Supported input types: ["text"], ["text", "image"], ["text", "document"], etc. */inputs: string[];/** Supported output types: ["dense"], ["dense", "sparse"], etc. */outputs: string[];/** Embedding dimensions for each output type */dims?: ModelDims;- /** Maximum sequence length the model supports */- maxSequenceLength?: number;- /** Advertised model capabilities (grammar, tools, code/sql/guard, LoRA adapters) */- capabilities?: ModelCapabilities;+ /** Maximum sequence length the model supports; null when the config pins none */+ maxSequenceLength?: number | null;+ /** Pinned HF commit SHA for the weights; null for unpinned/package-backed models */+ revision?: string | null;+ /** Servable profiles keyed by name; address one as "model@profile" */+ profiles?: Record<string, ProfileInfo>;+ /** Advertised model capabilities; null for models with no `generate` task */+ capabilities?: ModelCapabilities | null;+ /** Gateway-only queue snapshot; absent when talking to a single server */+ pendingGeneration?: PendingGeneration;+ /**+ * Short task-tier names that resolve to this model, e.g. ["rerank-fast"].+ * Send one anywhere a model id is accepted. The gateway's internal routing+ * defaults are never listed.+ *+ * Required, and empty when the model has none: `toModelInfo` normalizes a+ * missing wire value to `[]`. A single SIE server emits no aliases at all,+ * and making callers null-check for that would throw away the whole point+ * of the gateway always sending an explicit empty list.+ */+ aliases: string[];}+/**+ * A `/v1/models` entry exactly as the gateway emits it, before the client+ * camelCases the three renamed top-level keys.+ *+ * Declared once here (rather than inline per call site) so `listModels` and+ * `getModel` cannot drift apart, and so the emitted key set has a single+ * runtime witness for the golden-fixture test.+ */+export interface WireModelInfo {+ name: string;+ loaded: boolean;+ state?: ModelState;+ last_error?: ModelLoadError | null;+ inputs: string[];+ outputs: string[];+ dims?: ModelDims;+ max_sequence_length?: number | null;+ revision?: string | null;+ profiles?: Record<string, ProfileInfo>;+ capabilities?: ModelCapabilities | null;+ pending_generation?: PendingGeneration;+ aliases?: string[];+}++/**+ * Exhaustive by construction: `Record<keyof WireModelInfo, true>` rejects the+ * object literal if a wire key is missing, and excess-property checking+ * rejects a key that is not on `WireModelInfo`. So this stays in lockstep with+ * the interface, and `MODEL_INFO_WIRE_FIELDS` gives the wire-contract test a+ * runtime value to compare against the golden fixture.+ */+const MODEL_INFO_WIRE_FIELD_SET: Record<keyof WireModelInfo, true> = {+ aliases: true,+ capabilities: true,+ dims: true,+ inputs: true,+ last_error: true,+ loaded: true,+ max_sequence_length: true,+ name: true,+ outputs: true,+ pending_generation: true,+ profiles: true,+ revision: true,+ state: true,+};++/** Wire-side key names of a `/v1/models` entry the SDK declares. */+export const MODEL_INFO_WIRE_FIELDS = Object.keys(+ MODEL_INFO_WIRE_FIELD_SET,+) as (keyof WireModelInfo)[];+/*** A single score entry from reranking.*/@@ -597,21 +739,54 @@ export type StatusMessage = WorkerStatusMessage | ClusterStatusMessage;* Options for SIEClient constructor.*/export interface SIEClientOptions {- /** Request timeout in milliseconds (default: 30000) */+ /**+ * Per-request timeout in MILLISECONDS (default: 30000).+ *+ * Note the unit: the Python SDK's equivalent knob (`timeout_s`) is in+ * SECONDS, so a value ported verbatim is off by 1000x. Prefer the+ * unit-encoded `timeoutMs`, which reads identically but names the unit.+ */+ timeoutMs?: number;+ /**+ * @deprecated Use `timeoutMs` — same unit (MILLISECONDS), clearer name.+ * Kept as a back-compatible alias. If both are set, `timeoutMs` wins.+ */timeout?: number;/** Default GPU type for all requests (e.g., "l4", "a100-80gb") */gpu?: string;/** API key for authentication (sent as Bearer token) */apiKey?: string;/**- * Whether to auto-retry retryable capacity signals (503 PROVISIONING,- * idempotent 504 gateway timeouts, transient connect errors).+ * Default for whether the SDK waits out transient "no capacity yet"+ * signals (each retry capped by `provisionTimeout`) or fails fast. The+ * signals this flag controls differ by operation, because generation+ * is non-idempotent while the encode/score/extract queue paths are+ * idempotent:+ *+ * - `503 PROVISIONING` — controlled by this flag on EVERY operation:+ * `true` retries until `provisionTimeout` elapses; `false` throws+ * `ProvisioningError` on the first signal.+ * - `504` gateway-result timeout and connect-time `SIEConnectionError`+ * (`kind === "connect"`) — controlled by this flag on the idempotent+ * encode/score/extract paths ONLY: retried when `true`, thrown when+ * `false`. On the non-idempotent generate/chat paths a `504` and any+ * fetch-level connection failure are NEVER retried under any flag+ * value — the request may already be executing, so a retry could+ * double-bill a generation.+ * - `503 MODEL_LOADING` and `503 RESOURCE_EXHAUSTED` — retried on ALL+ * operations regardless of this flag (each retry bounded by+ * `provisionTimeout`; `RESOURCE_EXHAUSTED` additionally bounded by a+ * fixed retry count): the worker has already accepted the request.+ *+ * A read/pool `SIEConnectionError` (`kind === "timeout"`) is never+ * retried on any path.+ ** Default: `true`, matching the Python SDK's `wait_for_capacity=True`.* BREAKING (0.7): the default was previously `false` — pass `false`* explicitly to fail fast.*/waitForCapacity?: boolean;- /** Maximum time to wait for provisioning in milliseconds (default: 300000) */+ /** Maximum time to wait for provisioning in milliseconds (default: 900000, matching the Python SDK) */provisionTimeout?: number;/*** Control-plane base URL for the `connections` namespace (connector@@ -1174,18 +1349,28 @@ export interface ChatCompletionChunk {*/export interface ChatCompletionOptions {/**- * When `true`, retry the SAFE pre-execution capacity signals- * (`503 PROVISIONING`, `503 MODEL_LOADING`, `503 RESOURCE_EXHAUSTED`)- * until `provisionTimeoutMs` elapses. When `false`, the first- * provisioning signal throws (`ProvisioningError` / `ModelLoadingError`- * / `ServerError`). Defaults to the client's `waitForCapacity`- * (true unless the constructor opted out).+ * Controls `503 PROVISIONING` only: when `true`, retry it until+ * `provisionTimeoutMs` elapses; when `false`, the first `PROVISIONING`+ * signal throws `ProvisioningError`. Chat runs the non-idempotent+ * generate path, so the remaining outcomes do NOT depend on this flag:+ *+ * - `503 MODEL_LOADING` and `503 RESOURCE_EXHAUSTED` are ALWAYS retried+ * (each retry bounded by `provisionTimeoutMs`; `RESOURCE_EXHAUSTED`+ * additionally bounded by a fixed retry count): the worker already+ * accepted the request.+ * - `504` gateway timeouts and every fetch-level connection failure are+ * ALWAYS terminal — never retried under any flag value — because the+ * request may already be executing and a retry could double-bill a+ * generation.+ *+ * Defaults to the client's `waitForCapacity` (true unless the+ * constructor opted out).*/waitForCapacity?: boolean;/*** Total cumulative wall-clock budget (ms) for provisioning retries.* Independent of the per-attempt `timeout`. Defaults to the client's- * `provisionTimeout` (typically 5 minutes).+ * `provisionTimeout` (typically 15 minutes).*/provisionTimeoutMs?: number;}diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 6bc7e555c..baa4e1ede 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.7.1"; // x-release-please-version+export const SDK_VERSION = "0.7.2"; // x-release-please-versiondiff --git a/packages/sie_ts_sdk/tests/backpressureBilling.test.ts b/packages/sie_ts_sdk/tests/backpressureBilling.test.tsnew file mode 100644index 000000000..44dc74dca--- /dev/null+++ b/packages/sie_ts_sdk/tests/backpressureBilling.test.ts@@ -0,0 +1,273 @@+/**+ * Tests for the pass-2 audit backpressure / billing signals the gateway emits+ * that the SDK previously discarded:+ *+ * B1 — 429 RATE_LIMIT -> retried (Retry-After), typed RateLimitError on give-up+ * B2 — 503 BILLING_CAPACITY_UNAVAILABLE -> retried (Retry-After), terminal ServerError on give-up+ * B7 — 503 QUEUE_FULL -> retried (Retry-After)+ * B3 — 402/403 credit & account failures -> TERMINAL, typed, NEVER retried (single attempt)+ *+ * Mirrors the harness in `client.test.ts`: mock `fetch` with a canned response+ * sequence and drive the fake timer to release the retry sleeps. Covers the+ * inline buffered loop (encode), the shared `withProvisioningRetry` loop+ * (generate), and the terminal `handleError` mapping.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SIEClient } from "../src/client.js";+import {+ AccountInactiveError,+ AccountStateUnavailableError,+ InsufficientCreditsError,+ RateLimitError,+ RequestError,+ ServerError,+ SpendLimitError,+} from "../src/errors.js";+import { handleError } from "../src/internal/parsing.js";+import { packMessage } from "../src/msgpack.js";++const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);++function detailResponse(+ status: number,+ code: string,+ headers: Record<string, string> = {},+): Response {+ return new Response(JSON.stringify({ detail: { code, message: code.toLowerCase() } }), {+ status,+ headers: { "Content-Type": "application/json", ...headers },+ });+}++function encodeSuccess(): Response {+ return new Response(packMessage({ items: [{ dense: { values: new Float32Array([0.1]) } }] }), {+ status: 200,+ headers: { "Content-Type": "application/msgpack" },+ });+}++describe("backpressure & billing signals (pass-2 audit B1/B2/B7/B3)", () => {+ beforeEach(() => {+ // mockReset (not mockClear) drains any leftover `mockResolvedValueOnce`+ // queue so an unconsumed success from a "does not retry" test cannot leak+ // into the next test.+ mockFetch.mockReset();+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ // ── B1: 429 rate limit ──────────────────────────────────────────────++ it("retries 429 RATE_LIMIT honoring Retry-After, then succeeds", async () => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 30_000,+ provisionTimeout: 60_000,+ });+ mockFetch+ .mockResolvedValueOnce(+ detailResponse(429, "RATE_LIMIT", { "Retry-After": "2", "X-SIE-Error-Code": "RATE_LIMIT" }),+ )+ .mockResolvedValueOnce(encodeSuccess());++ const promise = client.encode("bge-m3", { text: "test" });++ // Retry-After (2s) honored verbatim — no retry before the full 2s.+ await vi.advanceTimersByTimeAsync(1_999);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1);++ const result = await promise;+ expect(result.dense).toBeInstanceOf(Float32Array);+ expect(mockFetch).toHaveBeenCalledTimes(2);+ await client.close();+ });++ it("throws RateLimitError after the retry budget is exhausted", async () => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 5_000,+ provisionTimeout: 1_000,+ });+ mockFetch.mockResolvedValue(detailResponse(429, "RATE_LIMIT", { "Retry-After": "1" }));++ const promise = client.encode("bge-m3", { text: "test" });+ const expectation = expect(promise).rejects.toThrow(RateLimitError);+ await vi.advanceTimersByTimeAsync(1_000);+ await expectation;+ await client.close();+ });++ it("exposes the server Retry-After on the thrown RateLimitError", async () => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 5_000,+ provisionTimeout: 1_000,+ });+ mockFetch.mockResolvedValue(detailResponse(429, "RATE_LIMIT", { "Retry-After": "1" }));++ const promise = client.encode("bge-m3", { text: "test" }).catch((e: unknown) => e);+ await vi.advanceTimersByTimeAsync(1_000);+ const err = await promise;+ expect(err).toBeInstanceOf(RateLimitError);+ expect((err as RateLimitError).retryAfter).toBe(1_000); // ms+ expect((err as RateLimitError).statusCode).toBe(429);+ await client.close();+ });++ it("preserves the gateway request id on the exhausted-429 give-up", async () => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 5_000,+ provisionTimeout: 1_000,+ });+ // The give-up must carry x-sie-request-id from the final 429, matching the+ // direct terminal 429 mapped by handleError (#3136).+ mockFetch.mockResolvedValue(+ detailResponse(429, "RATE_LIMIT", { "Retry-After": "1", "x-sie-request-id": "req-abc123" }),+ );++ const promise = client.encode("bge-m3", { text: "test" }).catch((e: unknown) => e);+ await vi.advanceTimersByTimeAsync(1_000);+ const err = await promise;+ expect(err).toBeInstanceOf(RateLimitError);+ expect((err as RateLimitError).requestId).toBe("req-abc123");+ await client.close();+ });++ // ── B2 / B7: retryable 503 backpressure ─────────────────────────────++ it.each(["BILLING_CAPACITY_UNAVAILABLE", "QUEUE_FULL"])(+ "retries 503 %s honoring Retry-After, then succeeds",+ async (code) => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 30_000,+ provisionTimeout: 60_000,+ });+ mockFetch+ .mockResolvedValueOnce(detailResponse(503, code, { "Retry-After": "1" }))+ .mockResolvedValueOnce(encodeSuccess());++ const promise = client.encode("bge-m3", { text: "test" });+ await vi.advanceTimersByTimeAsync(1_000);+ const result = await promise;++ expect(result.dense).toBeInstanceOf(Float32Array);+ expect(mockFetch).toHaveBeenCalledTimes(2);+ await client.close();+ },+ );++ it("throws ServerError (code preserved) when the backpressure 503 budget is spent", async () => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 5_000,+ provisionTimeout: 1_000,+ });+ mockFetch.mockResolvedValue(+ detailResponse(503, "BILLING_CAPACITY_UNAVAILABLE", { "Retry-After": "1" }),+ );++ const promise = client.encode("bge-m3", { text: "test" }).catch((e: unknown) => e);+ await vi.advanceTimersByTimeAsync(1_000);+ const err = await promise;++ expect(err).toBeInstanceOf(ServerError);+ expect(err).not.toBeInstanceOf(RateLimitError);+ expect((err as ServerError).code).toBe("BILLING_CAPACITY_UNAVAILABLE");+ expect((err as ServerError).statusCode).toBe(503);+ await client.close();+ });++ // ── B3: terminal credit / account failures (NEVER retried) ──────────++ it.each([+ [402, "INSUFFICIENT_CREDITS", InsufficientCreditsError],+ [402, "KEY_SPEND_LIMIT_EXCEEDED", SpendLimitError],+ [403, "ACCOUNT_SUSPENDED", AccountInactiveError],+ [403, "ACCOUNT_PENDING_REVIEW", AccountInactiveError],+ [503, "ACCOUNT_STATE_UNAVAILABLE", AccountStateUnavailableError],+ ] as const)(+ "maps %s %s to a terminal typed error and does not retry",+ async (status, code, ctor) => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 30_000,+ provisionTimeout: 60_000,+ });+ // A success is queued AFTER the failure to prove the SDK never reaches it.+ mockFetch+ .mockResolvedValueOnce(detailResponse(status, code))+ .mockResolvedValueOnce(encodeSuccess());++ await expect(client.encode("bge-m3", { text: "test" })).rejects.toBeInstanceOf(ctor);+ // Single attempt — no retry.+ expect(mockFetch).toHaveBeenCalledTimes(1);+ await client.close();+ },+ );++ // ── withProvisioningRetry parity (generate path) ────────────────────++ it("retries 429 on the generate path (withProvisioningRetry), then succeeds", async () => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 30_000,+ provisionTimeout: 60_000,+ });+ mockFetch+ .mockResolvedValueOnce(detailResponse(429, "RATE_LIMIT", { "Retry-After": "1" }))+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ model: "m",+ text: "hi",+ finish_reason: "stop",+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ attempt_id: "a",+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );++ const promise = client.generate("m", "Hi", { maxNewTokens: 8 });+ await vi.advanceTimersByTimeAsync(1_000);+ const result = await promise;++ expect(result.text).toBe("hi");+ expect(mockFetch).toHaveBeenCalledTimes(2);+ await client.close();+ });++ it("does not retry 402 on the generate path", async () => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 30_000,+ provisionTimeout: 60_000,+ });+ mockFetch.mockResolvedValue(detailResponse(402, "INSUFFICIENT_CREDITS"));++ await expect(client.generate("m", "Hi", { maxNewTokens: 8 })).rejects.toBeInstanceOf(+ InsufficientCreditsError,+ );+ expect(mockFetch).toHaveBeenCalledTimes(1);+ await client.close();+ });+});++// handleError runs under real timers — it never sleeps.+describe("handleError billing/backpressure mapping", () => {+ it.each([+ [429, "RATE_LIMIT", RateLimitError],+ [402, "INSUFFICIENT_CREDITS", InsufficientCreditsError],+ [402, "KEY_SPEND_LIMIT_EXCEEDED", SpendLimitError],+ [403, "ACCOUNT_SUSPENDED", AccountInactiveError],+ [403, "ACCOUNT_PENDING_REVIEW", AccountInactiveError],+ [503, "ACCOUNT_STATE_UNAVAILABLE", AccountStateUnavailableError],+ ] as const)("maps %s %s", async (status, code, ctor) => {+ await expect(handleError(detailResponse(status, code))).rejects.toBeInstanceOf(ctor);+ });++ it("leaves an unrecognized 403 code as a generic RequestError", async () => {+ const err = await handleError(detailResponse(403, "INVALID_KEY")).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(RequestError);+ expect(err).not.toBeInstanceOf(AccountInactiveError);+ });+});diff --git a/packages/sie_ts_sdk/tests/chat.test.ts b/packages/sie_ts_sdk/tests/chat.test.tsindex 42896c04a..8af734b73 100644--- a/packages/sie_ts_sdk/tests/chat.test.ts+++ b/packages/sie_ts_sdk/tests/chat.test.ts@@ -85,7 +85,7 @@ describe("SIEClient.chatCompletions", () => {const [url, init] = mockFetch.mock.calls[0];expect(url).toBe("http://localhost:8080/v1/chat/completions");expect(init.method).toBe("POST");- expect(init.redirect).toBe("error");+ expect(init.redirect).toBe("manual");expect(init.headers["Content-Type"]).toBe("application/json");expect(init.headers.Accept).toBe("application/json");const body = JSON.parse(init.body);diff --git a/packages/sie_ts_sdk/tests/client.test.ts b/packages/sie_ts_sdk/tests/client.test.tsindex f76248143..3c9890cf4 100644--- a/packages/sie_ts_sdk/tests/client.test.ts+++ b/packages/sie_ts_sdk/tests/client.test.ts@@ -20,6 +20,7 @@ import {ServerError,} from "../src/errors.js";import { packMessage, unpackMessage } from "../src/msgpack.js";+import type { SIEClientOptions } from "../src/types.js";// Mock fetch globallyconst mockFetch = vi.fn();@@ -75,6 +76,30 @@ describe("SIEClient construction", () => {expect(client.getBaseUrl()).toBe("http://localhost:8080");});+ it("rejects a baseUrl without an http(s) scheme or host at construction", () => {+ // Previously `new SIEClient("localhost:8080")` surfaced only at request+ // time as a fetch TypeError — silently retried for the whole provision+ // budget with zero logging. Hostless inputs like `http://:8080` throw in+ // `new URL()` and are rejected. `new URL()` also NORMALIZES `http:/v1`,+ // `http:///v1`, `https:///v1` to a bogus host "v1" (WHATWG slash+ // coalescing), so the constructor additionally requires a real+ // `scheme://<authority>` — those wrong-host inputs are rejected too.+ for (const bad of [+ "localhost:8080",+ "example.com",+ "ftp://host:21",+ "not a url",+ "",+ "http://:8080",+ "https://:443",+ "http:/v1",+ "http:///v1",+ "https:///v1",+ ]) {+ expect(() => new SIEClient(bad)).toThrow(/absolute http\(s\) URL with a host/);+ }+ });+it("should normalize base URL by removing trailing slash", async () => {const client = new SIEClient("http://localhost:8080/");@@ -134,6 +159,71 @@ describe("SIEClient construction", () => {});});+describe("SIEClient construction - timeout unit (timeoutMs vs timeout)", () => {+ beforeEach(() => {+ mockFetch.mockReset();+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ // A fetch that never resolves until its AbortSignal fires, then rejects with+ // an AbortError — the way a real per-request timeout surfaces. The client's+ // internal `setTimeout(abort, timeout)` (faked here) drives the abort, so the+ // effective timeout is observable via the "Request timeout after <n>ms"+ // message the client raises.+ function mockHangingFetch(): void {+ mockFetch.mockImplementation(+ (_url: string, init?: RequestInit) =>+ new Promise((_resolve, reject) => {+ init?.signal?.addEventListener("abort", () => {+ reject(Object.assign(new Error("The user aborted a request."), { name: "AbortError" }));+ });+ }),+ );+ }++ // Drive one encode to its timeout abort and return the ms value the client+ // actually aborted at, parsed from the timeout message.+ async function effectiveTimeoutMs(options: SIEClientOptions): Promise<number> {+ mockHangingFetch();+ const client = new SIEClient("http://localhost:8080", options);+ // Attach the handler synchronously so advancing timers cannot surface an+ // unhandled rejection before we await the result.+ const settled = client.encode("bge-m3", { text: "test" }, { waitForCapacity: false }).then(+ () => {+ throw new Error("expected a timeout rejection");+ },+ (err: unknown) => err as Error,+ );+ await vi.advanceTimersByTimeAsync(1_000_000);+ const err = await settled;+ await client.close();+ const match = /Request timeout after (\d+)ms/.exec(err.message);+ if (!match) {+ throw new Error(`unexpected error message: ${err.message}`);+ }+ return Number(match[1]);+ }++ it("applies timeoutMs as the milliseconds timeout", async () => {+ expect(await effectiveTimeoutMs({ timeoutMs: 1234 })).toBe(1234);+ });++ it("treats the deprecated timeout alias as the same milliseconds value", async () => {+ // Same numeric value under either key must yield the same effective abort.+ expect(await effectiveTimeoutMs({ timeout: 1234 })).toBe(+ await effectiveTimeoutMs({ timeoutMs: 1234 }),+ );+ });++ it("prefers timeoutMs over the deprecated timeout when both are set", async () => {+ expect(await effectiveTimeoutMs({ timeoutMs: 1234, timeout: 9999 })).toBe(1234);+ });+});+describe("SIEClient.encode() - basic usage", () => {let client: SIEClient;@@ -670,6 +760,91 @@ describe("SIEClient retry on connection errors and provisioning 503s", () => {await client.close();});+ it("should NOT retry a URL-parse TypeError (permanent config error)", async () => {+ // A malformed request URL is not a transient network failure: retrying+ // it silently for the whole provision budget can never succeed.+ const client = new SIEClient("http://localhost:8080", {+ timeout: 30_000,+ provisionTimeout: 60_000,+ });++ const parseError = new TypeError("Failed to parse URL from localhost:8080/v1/encode/bge-m3");+ (parseError as TypeError & { cause?: { code: string } }).cause = { code: "ERR_INVALID_URL" };+ mockFetch.mockRejectedValueOnce(parseError);++ const err = await client+ .encode("bge-m3", { text: "test" }, { waitForCapacity: true })+ .catch((e: unknown) => e);++ expect(err).toBeInstanceOf(SIEConnectionError);+ expect((err as SIEConnectionError).kind).toBe("other");+ expect((err as SIEConnectionError).message).toContain("absolute http(s) URL");+ expect(mockFetch).toHaveBeenCalledTimes(1);++ await client.close();+ });++ it("should warn once on the first connect retry", async () => {+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});+ const client = new SIEClient("http://localhost:8080", {+ timeout: 30_000,+ provisionTimeout: 60_000,+ });++ mockFetch+ .mockRejectedValueOnce(new TypeError("fetch failed"))+ .mockRejectedValueOnce(new TypeError("fetch failed"))+ .mockResolvedValueOnce(+ createMsgpackResponse({+ items: [{ dense: { values: new Float32Array([0.1, 0.2]) } }],+ }),+ );++ const promise = client.encode("bge-m3", { text: "test" }, { waitForCapacity: true });+ // Two retries at DEFAULT_RETRY_DELAY = 5_000ms each.+ await vi.advanceTimersByTimeAsync(10_000);+ await promise;++ expect(warnSpy).toHaveBeenCalledTimes(1);+ expect(String(warnSpy.mock.calls[0]?.[0])).toContain("http://localhost:8080");++ warnSpy.mockRestore();+ await client.close();+ });++ it("logs only the origin (no credentials, path, or query) in the connect-retry warning", async () => {+ // A baseUrl carrying `user:secret@` AND a+ // `?access_token=` query param must leak neither — only scheme://host:port.+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});+ const client = new SIEClient(+ "https://user:[email protected]:8443/v1?access_token=querysecret",+ {+ timeout: 30_000,+ provisionTimeout: 60_000,+ },+ );++ mockFetch.mockRejectedValueOnce(new TypeError("fetch failed")).mockResolvedValueOnce(+ createMsgpackResponse({+ items: [{ dense: { values: new Float32Array([0.1, 0.2]) } }],+ }),+ );++ const promise = client.encode("bge-m3", { text: "test" }, { waitForCapacity: true });+ await vi.advanceTimersByTimeAsync(5_000);+ await promise;++ const warned = String(warnSpy.mock.calls[0]?.[0]);+ expect(warned).not.toContain("s3cr3t-token");+ expect(warned).not.toContain("querysecret");+ expect(warned).not.toContain("user:");+ expect(warned).not.toContain("access_token");+ expect(warned).toContain("https://gateway.example.test:8443");++ warnSpy.mockRestore();+ await client.close();+ });+it("should NOT retry on per-request timeout even when waitForCapacity is true", async () => {// Pin the kind === "timeout" no-retry contract; see requestWithRetry docstring.const client = new SIEClient("http://localhost:8080", {diff --git a/packages/sie_ts_sdk/tests/generate.test.ts b/packages/sie_ts_sdk/tests/generate.test.tsindex e2b3a5c94..932682a23 100644--- a/packages/sie_ts_sdk/tests/generate.test.ts+++ b/packages/sie_ts_sdk/tests/generate.test.ts@@ -101,7 +101,7 @@ describe("SIEClient.generate", () => {const [url, init] = mockFetch.mock.calls[0];expect(url).toBe("http://localhost:8080/v1/generate/m");expect(init.method).toBe("POST");- expect(init.redirect).toBe("error");+ expect(init.redirect).toBe("manual");expect(init.headers["Content-Type"]).toBe("application/json");expect(init.headers.Accept).toBe("application/json");const body = JSON.parse(init.body);@@ -359,19 +359,64 @@ describe("SIEClient.generate retry semantics (B1c)", () => {expect(mockFetch).toHaveBeenCalledOnce();});- it("refuses redirects as a terminal single-shot transport error", async () => {- const client = new SIEClient("http://localhost:8080", {+ it.each([+ "https://redirect.example/private-token?__modal_attempt_token=opaque",+ "https://gateway.example.test.attacker.example/result?__modal_attempt_token=opaque",+ "http://gateway.example.test/result?__modal_attempt_token=opaque",+ "https://[email protected]/result?__modal_attempt_token=opaque",+ "/result",+ "/result?__modal_attempt_token=one&__modal_attempt_token=two",+ "/result?__modal_attempt_token=opaque#fragment",+ ])("refuses an unsafe continuation without following or reposting: %s", async (location) => {+ const client = new SIEClient("https://gateway.example.test", {timeout: 30_000,provisionTimeout: 60_000,});- mockFetch.mockRejectedValueOnce(new TypeError("fetch failed"));+ mockFetch.mockResolvedValueOnce(+ new Response(null, {+ status: 303,+ headers: { Location: location },+ }),+ );await expect(client.generate("m", "hi", { maxNewTokens: 8, waitForCapacity: true }),- ).rejects.toBeInstanceOf(SIEConnectionError);+ ).rejects.toBeInstanceOf(ServerError);expect(mockFetch).toHaveBeenCalledOnce();- expect(mockFetch.mock.calls[0]?.[1].redirect).toBe("error");+ expect(mockFetch.mock.calls[0]?.[1].redirect).toBe("manual");+ });++ it("consumes a same-origin Modal continuation by GET without reposting", async () => {+ mockFetch+ .mockResolvedValueOnce(+ new Response(null, {+ status: 303,+ headers: { Location: "/v1/generate/m?__modal_attempt_token=opaque" },+ }),+ )+ .mockResolvedValueOnce(+ jsonResponse({+ model: "m",+ text: "ok",+ finish_reason: "stop",+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ attempt_id: "a",+ }),+ );++ const client = new SIEClient("https://gateway.example.test", { apiKey: "secret" });+ const result = await client.generate("m", "hi", { maxNewTokens: 8 });++ expect(result.text).toBe("ok");+ expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(mockFetch.mock.calls[0]?.[1].method).toBe("POST");+ expect(mockFetch.mock.calls[1]?.[0]).toBe(+ "https://gateway.example.test/v1/generate/m?__modal_attempt_token=opaque",+ );+ expect(mockFetch.mock.calls[1]?.[1].method).toBe("GET");+ expect(mockFetch.mock.calls[1]?.[1].headers.Authorization).toBe("Bearer secret");+ expect(mockFetch.mock.calls[1]?.[1].redirect).toBe("manual");});it("does NOT retry a mid-flight TypeError when waitForCapacity is false", async () => {diff --git a/packages/sie_ts_sdk/tests/incompleteBatch.test.ts b/packages/sie_ts_sdk/tests/incompleteBatch.test.tsnew file mode 100644index 000000000..698ebf41b--- /dev/null+++ b/packages/sie_ts_sdk/tests/incompleteBatch.test.ts@@ -0,0 +1,189 @@+/**+ * Positional batch-contract guard (architecture-review finding U1).+ *+ * The gateway's queue path answers a mixed-success batch with `200` carrying+ * only the *successful* items, and batch results are positional (item `id` is+ * optional). A shortened body therefore shifts every result after the dropped+ * item, so a zip-inputs-to-outputs consumer stores results against the wrong+ * inputs — silently. Both `encode` and `extract` guard the 1:1 contract and+ * throw {@link IncompleteBatchError} instead of returning a desynced array.+ *+ * Mirrors the Python SDK's `test_incomplete_batch.py`, including error codes.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SIEClient } from "../src/client.js";+import { IncompleteBatchError, SIEError, ServerError } from "../src/errors.js";+import { packMessage } from "../src/msgpack.js";++const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);++function msgpackResponse(body: unknown, headers: Record<string, string> = {}): Response {+ return new Response(packMessage(body), {+ status: 200,+ headers: { "Content-Type": "application/msgpack", ...headers },+ });+}++function dense(value: number): { dense: { values: Float32Array } } {+ return { dense: { values: new Float32Array([value, value]) } };+}++describe("IncompleteBatchError class", () => {+ it("is a ServerError and SIEError", () => {+ const error = new IncompleteBatchError("desync", { expected: 2, received: 1 });+ expect(error).toBeInstanceOf(ServerError);+ expect(error).toBeInstanceOf(SIEError);+ expect(error).toBeInstanceOf(Error);+ expect(error.name).toBe("IncompleteBatchError");+ });++ it("carries the counts and a 200 status (the response was not an HTTP error)", () => {+ const error = new IncompleteBatchError("desync", {+ expected: 3,+ received: 2,+ model: "bge-m3",+ code: "ENCODE_RESULT_COUNT_MISMATCH",+ });+ expect(error.expected).toBe(3);+ expect(error.received).toBe(2);+ expect(error.model).toBe("bge-m3");+ expect(error.statusCode).toBe(200);+ expect(error.missingIds).toBeUndefined();+ });+});++describe("encode batch guard", () => {+ let client: SIEClient;++ beforeEach(() => {+ client = new SIEClient("http://localhost:8080");+ });++ afterEach(() => {+ mockFetch.mockReset();+ });++ it("throws when the response drops an item", async () => {+ mockFetch.mockResolvedValueOnce(+ msgpackResponse({ items: [dense(0.1)] }, { "x-sie-request-id": "req-drop" }),+ );++ await expect(+ client.encode("bge-m3", [{ text: "ok" }, { text: "over-length" }]),+ ).rejects.toThrow(IncompleteBatchError);+ });++ it("reports counts, model, code, and request id", async () => {+ mockFetch.mockResolvedValueOnce(+ msgpackResponse({ items: [dense(0.1)] }, { "x-sie-request-id": "req-drop" }),+ );++ try {+ await client.encode("bge-m3", [{ text: "ok" }, { text: "over-length" }]);+ expect.unreachable("expected IncompleteBatchError");+ } catch (error) {+ expect(error).toBeInstanceOf(IncompleteBatchError);+ const incomplete = error as IncompleteBatchError;+ expect(incomplete.expected).toBe(2);+ expect(incomplete.received).toBe(1);+ expect(incomplete.model).toBe("bge-m3");+ expect(incomplete.code).toBe("ENCODE_RESULT_COUNT_MISMATCH");+ expect(incomplete.requestId).toBe("req-drop");+ expect(incomplete.message).toContain("1 embedding(s) for 2 input item(s)");+ }+ });++ it("names the dropped ids when every item carries one", async () => {+ mockFetch.mockResolvedValueOnce(+ msgpackResponse({+ items: [+ { id: "doc-a", ...dense(0.1) },+ { id: "doc-c", ...dense(0.3) },+ ],+ }),+ );++ try {+ await client.encode("bge-m3", [+ { id: "doc-a", text: "a" },+ { id: "doc-b", text: "b" },+ { id: "doc-c", text: "c" },+ ]);+ expect.unreachable("expected IncompleteBatchError");+ } catch (error) {+ const incomplete = error as IncompleteBatchError;+ expect(incomplete.missingIds).toEqual(["doc-b"]);+ expect(incomplete.message).toContain("doc-b");+ }+ });++ it("degrades to counts only when ids are absent", async () => {+ mockFetch.mockResolvedValueOnce(msgpackResponse({ items: [dense(0.1)] }));++ try {+ await client.encode("bge-m3", [{ text: "a" }, { text: "b" }]);+ expect.unreachable("expected IncompleteBatchError");+ } catch (error) {+ expect((error as IncompleteBatchError).missingIds).toBeUndefined();+ }+ });++ it("passes through when the counts match", async () => {+ mockFetch.mockResolvedValueOnce(msgpackResponse({ items: [dense(0.1), dense(0.2)] }));++ const results = await client.encode("bge-m3", [{ text: "a" }, { text: "b" }]);+ expect(results).toHaveLength(2);+ });+});++describe("extract batch guard", () => {+ let client: SIEClient;++ beforeEach(() => {+ client = new SIEClient("http://localhost:8080");+ });++ afterEach(() => {+ mockFetch.mockReset();+ });++ it("throws with the extract-specific code and wording", async () => {+ mockFetch.mockResolvedValueOnce(+ msgpackResponse({+ items: [{ entities: [{ text: "Apple", label: "org", score: 0.9, start: 0, end: 5 }] }],+ }),+ );++ try {+ await client.extract("gliner", [{ text: "Apple info" }, { text: "Tesla info" }], {+ labels: ["org"],+ });+ expect.unreachable("expected IncompleteBatchError");+ } catch (error) {+ expect(error).toBeInstanceOf(IncompleteBatchError);+ const incomplete = error as IncompleteBatchError;+ expect(incomplete.code).toBe("EXTRACT_RESULT_COUNT_MISMATCH");+ expect(incomplete.message).toContain("extraction result(s)");+ }+ });++ it("passes through when the counts match", async () => {+ mockFetch.mockResolvedValueOnce(+ msgpackResponse({+ items: [+ { entities: [{ text: "Apple", label: "org", score: 0.9, start: 0, end: 5 }] },+ { entities: [{ text: "Tesla", label: "org", score: 0.95, start: 0, end: 5 }] },+ ],+ }),+ );++ const results = await client.extract(+ "gliner",+ [{ text: "Apple info" }, { text: "Tesla info" }],+ { labels: ["org"] },+ );+ expect(results).toHaveLength(2);+ });+});diff --git a/packages/sie_ts_sdk/tests/integration/client.integration.test.ts b/packages/sie_ts_sdk/tests/integration/client.integration.test.tsindex 1ca8c135a..da5399338 100644--- a/packages/sie_ts_sdk/tests/integration/client.integration.test.ts+++ b/packages/sie_ts_sdk/tests/integration/client.integration.test.ts@@ -5,10 +5,9 @@* The server is started automatically via globalSetup.ts.** To run integration tests:- * mise run ts test-integration+ * mise run ts -- test-integration*- * These tests mirror the Python SDK integration tests in:- * packages/sie_sdk/tests/test_integration.py+ * These tests exercise the same public surface as the Python SDK integration coverage.*/import { readFileSync } from "node:fs";diff --git a/packages/sie_ts_sdk/tests/integration/globalSetup.ts b/packages/sie_ts_sdk/tests/integration/globalSetup.tsindex 5dc35200f..b574f7d2b 100644--- a/packages/sie_ts_sdk/tests/integration/globalSetup.ts+++ b/packages/sie_ts_sdk/tests/integration/globalSetup.ts@@ -2,7 +2,7 @@* Global setup for integration tests.** Starts the SIE server before running integration tests.- * Mirrors the pattern from packages/sie_sdk/tests/conftest.py+ * Uses the same server-lifecycle contract as the Python SDK integration coverage.** Note: Uses a temp file to communicate server info to tests since globalSetup* runs in a separate process from the tests when using vitest's fork pool.diff --git a/packages/sie_ts_sdk/tests/internal.test.ts b/packages/sie_ts_sdk/tests/internal.test.tsindex 647ce1ffb..977570d57 100644--- a/packages/sie_ts_sdk/tests/internal.test.ts+++ b/packages/sie_ts_sdk/tests/internal.test.ts@@ -9,6 +9,7 @@*/import { describe, expect, it } from "vitest";+import { DEFAULT_PROVISION_TIMEOUT } from "../src/internal/constants.js";import {getErrorCode,handleError,@@ -19,6 +20,15 @@ import {} from "../src/internal/parsing.js";import { computeBackoffWithJitter, getRetryAfter } from "../src/internal/retry.js";+describe("Default provision timeout", () => {+ it("matches the Python SDK's DEFAULT_PROVISION_TIMEOUT_S (900s)", () => {+ // Parity with packages/sie_sdk/src/sie_sdk/client/_shared.py —+ // cold loads / scale-from-zero can take 5-15 minutes; a shorter TS+ // budget made requests fail in TS that succeed in Python.+ expect(DEFAULT_PROVISION_TIMEOUT).toBe(900_000);+ });+});+describe("Retry logic - exponential backoff with jitter", () => {it("should return delay within expected range for first attempt", () => {// First attempt (attempt=0) should have delay between 0 and baseDelay@@ -251,6 +261,24 @@ describe("handleError (gateway / FastAPI bodies)", () => {});});+ it("carries the x-sie-request-id header onto typed errors (#3136)", async () => {+ const res = new Response(+ JSON.stringify({+ detail: { code: "empty_model_output", message: "model produced no visible output text" },+ }),+ {+ status: 500,+ headers: { "Content-Type": "application/json", "x-sie-request-id": "req-http-1" },+ },+ );+ await expect(handleError(res)).rejects.toMatchObject({+ name: "ServerError",+ code: "empty_model_output",+ statusCode: 500,+ requestId: "req-http-1",+ });+ });+it("reads 503 PROVISIONING error envelope", async () => {const res = new Response(JSON.stringify({diff --git a/packages/sie_ts_sdk/tests/jobsPartialFailure.test.ts b/packages/sie_ts_sdk/tests/jobsPartialFailure.test.tsnew file mode 100644index 000000000..02c3bf066--- /dev/null+++ b/packages/sie_ts_sdk/tests/jobsPartialFailure.test.ts@@ -0,0 +1,329 @@+/**+ * Job result surfacing and terminal-state guard (architecture-review finding U2).+ *+ * A `failed` chunk still publishes a result ref carrying its SUCCESSFUL —+ * already billed — siblings alongside the per-item failures, so dropping the+ * whole chunk discards work the caller paid for. And a still-running job's ref+ * list is still growing, so decoding it returns a partial subset+ * indistinguishable from a partial-FAILURE subset.+ *+ * Mirrors the Python SDK's `test_jobs.py` (PR #3219), including error codes.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SIEClient } from "../src/client.js";+import { JobFailedError, MalformedChunkError, SIEError } from "../src/errors.js";+import { decodeChunkBytes, decodeResultItem } from "../src/jobs.js";+import { packMessage } from "../src/msgpack.js";++const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++/** One chunk ref carrying a successful item AND a failed sibling (both billed). */+function mixedChunk(): Uint8Array {+ return packMessage([+ {+ success: true,+ id: "ok-1",+ units: { input_tokens: 5 },+ result_msgpack: packMessage({ dense: { dims: 2, values: [0.1, 0.2] } }),+ },+ {+ success: false,+ id: "bad-1",+ error: "tokenization failed",+ error_code: "INFERENCE_ERROR",+ },+ ]);+}++/** A terminal `failed` job: chunk 0 published a ref; chunk 1 lost its results. */+function partialFailureJob() {+ return {+ id: "job-1",+ state: "failed",+ total_items: 3,+ settled_credits: 5,+ output: {+ kind: "refs",+ chunks: [+ {+ seq: 0,+ items: 2,+ state: "failed",+ ref: "http://refs.local/chunk-0",+ error: "1 of 2 items failed",+ },+ { seq: 1, items: 1, state: "failed", ref: null, error: "result publication failed" },+ ],+ },+ };+}++describe("JobFailedError class", () => {+ it("is an SIEError carrying the terminal reason", () => {+ const error = new JobFailedError("job job-1 terminated", {+ jobId: "job-1",+ state: "failed",+ outcome: "reexecution_required",+ errorCode: "RESULT_HANDLE_EXPIRED",+ });+ expect(error).toBeInstanceOf(SIEError);+ expect(error).toBeInstanceOf(Error);+ expect(error.name).toBe("JobFailedError");+ expect(error.jobId).toBe("job-1");+ expect(error.state).toBe("failed");+ expect(error.outcome).toBe("reexecution_required");+ expect(error.errorCode).toBe("RESULT_HANDLE_EXPIRED");+ });+});++describe("decodeResultItem", () => {+ it("populates error and surfaces the wire work_item_id", () => {+ const ok = decodeResultItem({+ success: true,+ id: "a",+ result_msgpack: packMessage({ dense: { dims: 2, values: [0.1, 0.2] } }),+ });+ expect(ok.success).toBe(true);+ expect(ok.error).toBeUndefined(); // a success carries no failure detail++ const bad = decodeResultItem({+ success: false,+ work_item_id: "b",+ error: "boom",+ error_code: "INFERENCE_ERROR",+ });+ expect(bad.success).toBe(false);+ // id surfaced from the wire `work_item_id`, never fabricated+ expect(bad.id).toBe("b");+ expect(bad.error).toEqual({ code: "INFERENCE_ERROR", message: "boom" });+ });++ it("preserves a falsy-but-valid id", () => {+ // Item ids can be numbers: id 0 (and an empty-string id) are VALID and must+ // not be replaced by work_item_id via a truthiness fallback.+ expect(decodeResultItem({ success: true, id: 0, work_item_id: "wi-9" }).id).toBe(0);+ expect(decodeResultItem({ success: true, id: "", work_item_id: "wi-9" }).id).toBe("");+ // The work_item_id fallback only applies when id is genuinely absent.+ expect(decodeResultItem({ success: false, work_item_id: "wi-9" }).id).toBe("wi-9");+ });++ it("tolerates malformed payloads", () => {+ // A non-object element degrades to a null result rather than throwing out of+ // the per-chunk decode loop.+ const item = decodeResultItem(42);+ expect(item.id).toBeNull();+ expect(item.success).toBeNull();+ expect(item.error).toBeUndefined();+ // A record whose result_msgpack is garbage still decodes (vector is null).+ const garbage = decodeResultItem({+ success: true,+ id: "x",+ result_msgpack: new Uint8Array([0xc1, 0xc1, 0xc1]),+ });+ expect(garbage.id).toBe("x");+ expect(garbage.dense).toBeNull();+ });+});++describe("decodeChunkBytes", () => {+ it("signals malformed refs distinctly", () => {+ // Garbage bytes → a distinct MalformedChunkError, not a silent empty list, so+ // the caller can tell a decode fault from an unpublished chunk.+ expect(() => decodeChunkBytes(new Uint8Array([0xc1, 0xc1, 0xc1]))).toThrow(MalformedChunkError);+ // Valid msgpack that is not a list of results is also malformed.+ expect(() => decodeChunkBytes(packMessage({ not: "a list" }))).toThrow(MalformedChunkError);+ // A well-formed list still decodes normally.+ expect(decodeChunkBytes(mixedChunk()).map((it) => it.id)).toEqual(["ok-1", "bad-1"]);+ });+});++describe("jobs.results partial-failure surfacing", () => {+ let client: SIEClient;+ let warn: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ client = new SIEClient("http://gw:8080");+ warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ });++ afterEach(() => {+ mockFetch.mockReset();+ warn.mockRestore();+ });++ it("surfaces a failed chunk's billed successful items and per-item errors", async () => {+ mockFetch+ .mockResolvedValueOnce(jsonResponse(partialFailureJob()))+ .mockResolvedValueOnce(new Response(mixedChunk(), { status: 200 }));++ const results = await client.jobs.results("job-1");++ // The `failed` chunk's ref is READ (not dropped); the ref-less chunk is skipped.+ expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(mockFetch.mock.calls[1][0]).toBe("http://refs.local/chunk-0");+ expect(results.state).toBe("failed");+ expect(results.retrieved).toBe(2);++ const [ok, bad] = results.items;+ expect([ok.id, ok.success]).toEqual(["ok-1", true]);+ expect(Array.from(ok.dense as number[])).toEqual([0.1, 0.2]);+ expect(ok.error).toBeUndefined();+ expect([bad.id, bad.success]).toEqual(["bad-1", false]);+ expect(bad.error).toEqual({ code: "INFERENCE_ERROR", message: "tokenization failed" });++ // The incompleteness warning is NEUTRAL — it claims no cause.+ const messages = warn.mock.calls.map((call) => String(call[0]));+ expect(messages.some((m) => m.includes("incomplete: retrieved 2 of 3"))).toBe(true);+ expect(messages.some((m) => m.includes("billed") || m.includes("publishing"))).toBe(false);+ });++ it("throws job_not_terminal on a running job without reading any ref", async () => {+ mockFetch.mockResolvedValueOnce(+ jsonResponse({+ id: "job-1",+ state: "running",+ total_items: 3,+ output: { kind: "refs", chunks: [{ seq: 0, items: 1, ref: "http://refs.local/c0" }] },+ }),+ );++ await expect(client.jobs.results("job-1")).rejects.toMatchObject({+ code: "job_not_terminal",+ statusCode: 409,+ });+ // Only the status GET happened — no ref was read.+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it("confines a garbage chunk ref without sinking the whole call", async () => {+ mockFetch+ .mockResolvedValueOnce(+ jsonResponse({+ id: "job-1",+ state: "failed",+ total_items: 3,+ settled_credits: 5,+ output: {+ kind: "refs",+ chunks: [+ { seq: 0, items: 2, state: "failed", ref: "http://refs.local/good" },+ { seq: 1, items: 1, state: "succeeded", ref: "http://refs.local/garbage" },+ ],+ },+ }),+ )+ .mockResolvedValueOnce(new Response(mixedChunk(), { status: 200 }))+ .mockResolvedValueOnce(new Response(new Uint8Array([0xc1, 0xc1, 0xc1]), { status: 200 }));++ const results = await client.jobs.results("job-1");++ // The good chunk's 2 items survive; the garbage ref contributes none.+ expect(results.retrieved).toBe(2);+ expect(results.items.map((it) => it.id)).toEqual(["ok-1", "bad-1"]);+ const messages = warn.mock.calls.map((call) => String(call[0]));+ // The malformed ref is flagged distinctly (a decode fault)...+ expect(messages.some((m) => m.includes("could not be decoded"))).toBe(true);+ // ...and the neutral incompleteness warning still fires.+ expect(messages.some((m) => m.includes("incomplete: retrieved 2 of 3"))).toBe(true);+ });+});++describe("jobs.wait raiseOnFailure", () => {+ let client: SIEClient;++ beforeEach(() => {+ client = new SIEClient("http://gw:8080");+ });++ afterEach(() => {+ mockFetch.mockReset();+ });++ it("throws JobFailedError carrying the terminal outcome", async () => {+ const failed = {+ id: "job-1",+ state: "failed",+ outcome: "reexecution_required",+ error_code: "RESULT_HANDLE_EXPIRED",+ };+ // A fresh Response per call — a body can only be read once.+ mockFetch.mockImplementation(() => Promise.resolve(jsonResponse(failed)));++ try {+ await client.jobs.wait("job-1", { pollMs: 0, raiseOnFailure: true });+ expect.unreachable("expected JobFailedError");+ } catch (error) {+ expect(error).toBeInstanceOf(JobFailedError);+ const jobFailed = error as JobFailedError;+ expect(jobFailed.jobId).toBe("job-1");+ expect(jobFailed.state).toBe("failed");+ expect(jobFailed.outcome).toBe("reexecution_required");+ expect(jobFailed.errorCode).toBe("RESULT_HANDLE_EXPIRED");+ expect(jobFailed.message).toContain("reexecution_required");+ }++ // Default stays back-compatible: the terminal doc is returned, not thrown.+ expect((await client.jobs.wait("job-1", { pollMs: 0 })).state).toBe("failed");+ });++ it("returns a succeeded terminal unchanged", async () => {+ mockFetch.mockResolvedValue(jsonResponse({ id: "job-1", state: "succeeded", total_items: 2 }));+ const job = await client.jobs.wait("job-1", { pollMs: 0, raiseOnFailure: true });+ expect(job.state).toBe("succeeded");+ });++ it("returns a stable planned connector phase without raising", async () => {+ mockFetch.mockResolvedValue(+ jsonResponse({ id: "job-plan-1", state: "queued", execution: "plan", phase: "planned" }),+ );+ const job = await client.jobs.wait("job-plan-1", { pollMs: 0, raiseOnFailure: true });+ expect(job.phase).toBe("planned");+ });+});++describe("decodeResultItem scalar validation", () => {+ // These values arrive off the wire unvalidated, and `results()` now reads+ // FAILED chunks too, so off-contract scalars must degrade rather than be+ // asserted straight into the public shape.+ it("normalizes a non-scalar id to null", () => {+ expect(decodeResultItem({ id: {}, success: true }).id).toBeNull();+ expect(decodeResultItem({ work_item_id: [1], success: true }).id).toBeNull();+ });++ it("preserves falsy-but-valid ids", () => {+ expect(decodeResultItem({ id: 0, success: true }).id).toBe(0);+ expect(decodeResultItem({ id: "", success: true }).id).toBe("");+ });++ it("normalizes a non-boolean success to null", () => {+ expect(decodeResultItem({ id: "a", success: "false" }).success).toBeNull();+ expect(decodeResultItem({ id: "a", success: 0 }).success).toBeNull();+ expect(decodeResultItem({ id: "a", success: false }).success).toBe(false);+ });++ it("omits non-string error fields but keeps the failure signal", () => {+ const item = decodeResultItem({ id: "a", success: false, error_code: 1, error: {} });+ expect(item.error).toBeDefined();+ expect(item.error?.code).toBeUndefined();+ expect(item.error?.message).toBeUndefined();+ });++ it("keeps well-formed error fields", () => {+ const item = decodeResultItem({+ id: "a",+ success: false,+ error_code: "OOM",+ error: "out of memory",+ });+ expect(item.error).toEqual({ code: "OOM", message: "out of memory" });+ });+});diff --git a/packages/sie_ts_sdk/tests/modelLoadFailed.test.ts b/packages/sie_ts_sdk/tests/modelLoadFailed.test.tsindex 61bfed0d0..570912296 100644--- a/packages/sie_ts_sdk/tests/modelLoadFailed.test.ts+++ b/packages/sie_ts_sdk/tests/modelLoadFailed.test.ts@@ -1,5 +1,5 @@/**- * Tests for the ``ModelLoadFailedError`` short-circuit (sie-test#85).+ * Tests for the ``ModelLoadFailedError`` short-circuit.** A 502 ``MODEL_LOAD_FAILED`` response must:* - throw {@link ModelLoadFailedError} immediately on the first responsediff --git a/packages/sie_ts_sdk/tests/streaming.test.ts b/packages/sie_ts_sdk/tests/streaming.test.tsindex a2dd571e7..af40dca31 100644--- a/packages/sie_ts_sdk/tests/streaming.test.ts+++ b/packages/sie_ts_sdk/tests/streaming.test.ts@@ -273,6 +273,46 @@ describe("SIEClient.streamChatCompletions", () => {expect(streamErr.code).toBe("context_exceeded");expect(streamErr.errorType).toBe("context_length_exceeded");expect(streamErr.message).toBe("prompt too long");+ // Pre-#3136 gateways omit request_id on chat error chunks; the SDK+ // must tolerate its absence.+ expect(streamErr.requestId).toBeUndefined();+ }+ });++ it("surfaces the in-band gateway request id on chat error chunks (#3136)", async () => {+ // The chat error chunk now carries the gateway request id as an additive+ // top-level member (the `chatcmpl-*` id is not the correlation key gateway+ // logs use, and streamed responses have no terminal headers).+ const errorChunkBody = {+ id: "chatcmpl-x",+ object: "chat.completion.chunk" as const,+ created: 1_700_000_000,+ model: "m",+ system_fingerprint: null,+ choices: [{ index: 0, delta: {}, finish_reason: null, logprobs: null }],+ error: {+ message: "Generation aborted: first_chunk timeout",+ type: "server_error",+ param: null,+ code: "first_chunk_timeout",+ },+ request_id: "req-chat-1",+ };+ mockFetch.mockResolvedValueOnce(sseResponse([JSON.stringify(errorChunkBody)]));++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamChatCompletions({+ model: "m",+ messages: [{ role: "user", content: "hi" }],+ });+ try {+ await gen.next();+ throw new Error("expected SIEStreamError");+ } catch (err) {+ expect(err).toBeInstanceOf(SIEStreamError);+ const streamErr = err as SIEStreamError;+ expect(streamErr.code).toBe("first_chunk_timeout");+ expect(streamErr.requestId).toBe("req-chat-1");}});@@ -492,6 +532,65 @@ describe("SIEClient.streamGenerate", () => {expect(err).toBeInstanceOf(SIEStreamError);expect((err as SIEStreamError).code).toBe("cancelled");expect((err as SIEStreamError).message).toBe("client closed");+ expect((err as SIEStreamError).requestId).toBe("req-1");+ }+ });++ it("surfaces the empty_model_output terminal code and request id (#3136)", async () => {+ // PR #3139: a stream that ends with no meaningful visible output carries+ // error_code="empty_model_output" on the terminal chunk. The caller must+ // be able to read the typed code AND the in-band gateway request id —+ // streamed responses have no terminal headers to fall back on.+ mockFetch.mockResolvedValueOnce(+ sseResponse([+ generateChunk(0, "", {+ done: true,+ finish_reason: "error",+ usage: { prompt_tokens: 5, completion_tokens: 7, total_tokens: 12 },+ error: {+ code: "empty_model_output",+ message: "model produced no visible output text",+ },+ }),+ ]),+ );++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamGenerate("m", "hi", { maxNewTokens: 8 });+ try {+ await gen.next();+ throw new Error("expected SIEStreamError");+ } catch (err) {+ expect(err).toBeInstanceOf(SIEStreamError);+ const streamErr = err as SIEStreamError;+ expect(streamErr.code).toBe("empty_model_output");+ expect(streamErr.message).toBe("model produced no visible output text");+ expect(streamErr.requestId).toBe("req-1");+ }+ });++ it("drops a malformed in-band request id instead of exposing it (#3136)", async () => {+ // Same validation rule as the HTTP header path: non-ASCII or padded ids+ // must never surface on SIEStreamError.requestId.+ mockFetch.mockResolvedValueOnce(+ sseResponse([+ generateChunk(0, "", {+ done: true,+ finish_reason: "error",+ request_id: " r\u00e9q-bad ",+ error: { code: "empty_model_output", message: "m" },+ }),+ ]),+ );++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamGenerate("m", "hi", { maxNewTokens: 8 });+ try {+ await gen.next();+ throw new Error("expected SIEStreamError");+ } catch (err) {+ expect(err).toBeInstanceOf(SIEStreamError);+ expect((err as SIEStreamError).requestId).toBeUndefined();}});diff --git a/packages/sie_ts_sdk/tests/typecheck/model-info-nullable.ts b/packages/sie_ts_sdk/tests/typecheck/model-info-nullable.tsnew file mode 100644index 000000000..518ea6938--- /dev/null+++ b/packages/sie_ts_sdk/tests/typecheck/model-info-nullable.ts@@ -0,0 +1,40 @@+import type { ModelInfo, WireModelInfo } from "../../src/types.js";++// Four `/v1/models` fields are emitted as an explicit null rather than omitted:+// the gateway hardcodes `last_error: null` and serializes `max_sequence_length`+// / `revision` as `Option<_>` with no skip_serializing_if; the server declares+// `last_error`, `max_sequence_length`, `revision` and `capabilities` as+// `X | None`, and pydantic emits each as null.+//+// `?:` alone only permits omission, so both contracts must admit null on each+// of the four. Reverting any of them to a bare `?: T` fails this file.+const wireWithExplicitNulls: WireModelInfo = {+ name: "BAAI/bge-m3",+ loaded: false,+ state: "available",+ inputs: ["text"],+ outputs: ["dense"],+ last_error: null,+ max_sequence_length: null,+ revision: null,+ capabilities: null,+};++const modelWithExplicitNulls: ModelInfo = {+ name: "BAAI/bge-m3",+ loaded: false,+ state: "available",+ inputs: ["text"],+ outputs: ["dense"],+ lastError: null,+ maxSequenceLength: null,+ revision: null,+ capabilities: null,+ // Required (not nullable): `toModelInfo` normalizes a missing wire value to+ // `[]`, so every `ModelInfo` carries a list. Present here only to satisfy the+ // contract — this file pins the four NULLABLE fields above.+ aliases: [],+};++void wireWithExplicitNulls;+void modelWithExplicitNulls;diff --git a/packages/sie_ts_sdk/tests/wireContract.test.ts b/packages/sie_ts_sdk/tests/wireContract.test.tsindex cec4b4003..0a85f916a 100644--- a/packages/sie_ts_sdk/tests/wireContract.test.ts+++ b/packages/sie_ts_sdk/tests/wireContract.test.ts@@ -1,15 +1,24 @@/**- * The TS SDK's wire enums must match the shared golden fixtures.+ * The TS SDK's wire types must match the shared golden fixtures.*- * Round-trips packages/wire-fixtures/model_state.json against the runtime- * MODEL_STATES array (the single source the ModelState type is derived from),- * so drift fails in CI rather than shipping. See- * packages/wire-fixtures/README.md.+ * Round-trips packages/wire-fixtures/*.json against the runtime witnesses the+ * types are derived from (MODEL_STATES, MODEL_INFO_WIRE_FIELDS), so drift fails+ * in CI rather than shipping. See packages/wire-fixtures/README.md.+ *+ * ModelInfo needs a second check the Python SDK does not: the Python client+ * returns the parsed body as-is, while this one re-maps it. A field can be+ * correctly declared on the type and still never reach a caller, so the last+ * test drives a full wire entry through the real client.*/import { readFileSync } from "node:fs";import { fileURLToPath } from "node:url";-import { describe, expect, it } from "vitest";-import { MODEL_STATES } from "../src/types.js";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SIEClient } from "../src/client.js";+import type { ModelInfo } from "../src/types.js";+import { MODEL_INFO_WIRE_FIELDS, MODEL_STATES } from "../src/types.js";++const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);const fixturesDir = fileURLToPath(new URL("../../wire-fixtures/", import.meta.url));@@ -17,10 +26,242 @@ function loadFixture(name: string): Record<string, unknown> {return JSON.parse(readFileSync(`${fixturesDir}${name}`, "utf8"));}+function jsonResponse(body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+}++/** The three top-level keys the client camelCases; everything else passes through. */+const WIRE_TO_CLIENT_KEY: Record<string, string> = {+ max_sequence_length: "maxSequenceLength",+ last_error: "lastError",+ pending_generation: "pendingGeneration",+};++/**+ * Assert the mapper carried every field in the fixture's typed set.+ *+ * Derived from `MODEL_INFO_WIRE_FIELDS` rather than a hand-written list — a+ * hand-written list is exactly what let the mapper drop fields in the first+ * place, and would let a newly typed field slip through unasserted. Shared by+ * the `getModel` and `listModels` tests for the same reason the two call sites+ * share one mapper: the original bug was two copies of the same list drifting.+ */+function expectEveryTypedFieldPresent(model: ModelInfo | undefined): void {+ expect(model).toBeDefined();+ for (const wireKey of MODEL_INFO_WIRE_FIELDS) {+ const clientKey = WIRE_TO_CLIENT_KEY[wireKey] ?? wireKey;+ expect({ key: clientKey, present: Object.hasOwn(model ?? {}, clientKey) }).toEqual({+ key: clientKey,+ present: true,+ });+ }+}++/** A `/v1/models/{model}` body with every emitted key populated. */+const FULL_WIRE_ENTRY = {+ name: "BAAI/bge-m3",+ loaded: true,+ state: "loaded",+ last_error: null,+ inputs: ["text"],+ outputs: ["dense", "sparse"],+ dims: { dense: 1024, sparse: 250002 },+ max_sequence_length: 8192,+ revision: "5617a9f61b028005a4858fdac845db406aefb181",+ profiles: { default: { is_default: true }, fp8: { is_default: false } },+ capabilities: { grammar: ["json_schema"], tools: true, code: false, sql: false, guard: false },+ pending_generation: { total: 0, groups: [] },+ aliases: ["sparse-embeddings-best"],+ // OpenAI retrieve-model compat keys, merged in by the detail endpoint.+ id: "BAAI/bge-m3",+ object: "model",+ created: 1_700_000_000,+ owned_by: "sie",+};+describe("wire contract golden fixtures", () => {it("ModelState matches the golden fixture", () => {const fixture = loadFixture("model_state.json");const states = fixture.model_states as string[];expect([...MODEL_STATES].sort()).toEqual([...states].sort());});++ it("ModelInfo declares every typed wire field", () => {+ const fixture = loadFixture("model_info.json");+ const typed = fixture.typed as string[];+ expect([...MODEL_INFO_WIRE_FIELDS].sort()).toEqual([...typed].sort());+ });++ it("ModelInfo omits the deliberately excluded wire fields", () => {+ const fixture = loadFixture("model_info.json");+ const excluded = Object.keys(fixture.excluded as Record<string, string>);+ expect(excluded.length).toBeGreaterThan(0);+ expect(MODEL_INFO_WIRE_FIELDS.filter((field) => excluded.includes(field))).toEqual([]);+ });+});++describe("getModel wire mapping", () => {+ let client: SIEClient;++ beforeEach(() => {+ mockFetch.mockClear();+ client = new SIEClient("http://localhost:8080");+ });++ afterEach(async () => {+ await client.close();+ });++ it("surfaces every typed wire field to callers", async () => {+ // Regression: the mapper used to rebuild the object from a hardcoded+ // six-field allowlist, so state/last_error/profiles/pending_generation+ // were dropped on the floor even once the type declared them.+ mockFetch.mockResolvedValueOnce(jsonResponse(FULL_WIRE_ENTRY));++ const model = await client.getModel("BAAI/bge-m3");++ expectEveryTypedFieldPresent(model);++ // Values, so a mapper that passes the right keys with the wrong contents+ // still fails. Object-valued fields are compared whole against the fixture+ // rather than by spot-checking one member — a spot-check leaves every other+ // member of that object unpinned, which is the same gap one level down.+ expect(model.name).toBe(FULL_WIRE_ENTRY.name);+ expect(model.loaded).toBe(true);+ expect(model.state).toBe("loaded");+ expect(model.aliases).toEqual(FULL_WIRE_ENTRY.aliases);+ expect(model.lastError).toBeNull();+ expect(model.inputs).toEqual(FULL_WIRE_ENTRY.inputs);+ expect(model.outputs).toEqual(FULL_WIRE_ENTRY.outputs);+ expect(model.dims).toEqual(FULL_WIRE_ENTRY.dims);+ expect(model.revision).toBe(FULL_WIRE_ENTRY.revision);+ expect(model.profiles).toEqual(FULL_WIRE_ENTRY.profiles);+ expect(model.capabilities).toEqual(FULL_WIRE_ENTRY.capabilities);+ expect(model.pendingGeneration).toEqual(FULL_WIRE_ENTRY.pending_generation);+ expect(model.maxSequenceLength).toBe(FULL_WIRE_ENTRY.max_sequence_length);+ });++ it("strips the OpenAI compat keys instead of leaking them onto ModelInfo", async () => {+ mockFetch.mockResolvedValueOnce(jsonResponse(FULL_WIRE_ENTRY));++ const model = await client.getModel("BAAI/bge-m3");++ const fixture = loadFixture("model_info.json");+ const excluded = Object.keys(fixture.excluded as Record<string, string>);+ expect(Object.keys(model).filter((key) => excluded.includes(key))).toEqual([]);+ });++ it("passes through a field the SDK does not yet know about", async () => {+ // The mapper is total by construction (rest spread), so a newly added+ // endpoint field reaches callers before the SDK ships a type for it.+ mockFetch.mockResolvedValueOnce(+ jsonResponse({ ...FULL_WIRE_ENTRY, some_future_field: "present" }),+ );++ const model = await client.getModel("BAAI/bge-m3");++ expect((model as Record<string, unknown>).some_future_field).toBe("present");+ });++ it("passes explicit nulls through instead of coercing them", async () => {+ // The emitters send `null` rather than omitting these four: the gateway+ // hardcodes `last_error: null` and serializes max_sequence_length/revision+ // as Option<_> with no skip_serializing_if; the server declares all four+ // as `X | None`. A null must survive the mapper as null — collapsing it to+ // undefined would hide "explicitly no value" behind "field not sent".+ mockFetch.mockResolvedValueOnce(+ jsonResponse({+ name: "m",+ loaded: false,+ state: "available",+ inputs: ["text"],+ outputs: ["dense"],+ last_error: null,+ max_sequence_length: null,+ revision: null,+ capabilities: null,+ }),+ );++ const model = await client.getModel("m");++ expect(model.lastError).toBeNull();+ expect(model.maxSequenceLength).toBeNull();+ expect(model.revision).toBeNull();+ expect(model.capabilities).toBeNull();+ });++ it("surfaces a load failure with its diagnostic detail", async () => {+ const loadError = {+ code: "GATED",+ message: "Access to model is restricted",+ attempts: 3,+ permanent: true,+ };+ mockFetch.mockResolvedValueOnce(+ jsonResponse({ ...FULL_WIRE_ENTRY, loaded: false, state: "failed", last_error: loadError }),+ );++ const model = await client.getModel("BAAI/bge-m3");++ expect(model.state).toBe("failed");+ // Whole-object equality pins all four members of ModelLoadError, including+ // `permanent` — the field callers branch on to decide whether retrying is+ // pointless — without leaving message/attempts unasserted.+ expect(model.lastError).toEqual(loadError);+ });+});++describe("listModels wire mapping", () => {+ let client: SIEClient;++ beforeEach(() => {+ mockFetch.mockClear();+ client = new SIEClient("http://localhost:8080");+ });++ afterEach(async () => {+ await client.close();+ });++ it("normalizes a missing alias list to an empty array", async () => {+ // A single SIE server emits no `aliases` key at all. `ModelInfo` declares+ // the field as always present, so the mapper must supply `[]` rather than+ // let `undefined` reach a caller — presence alone would not catch this,+ // because Object.hasOwn is satisfied by an own property set to undefined.+ const { aliases: _omitted, ...withoutAliases } = FULL_WIRE_ENTRY;+ mockFetch.mockResolvedValueOnce(jsonResponse({ models: [withoutAliases] }));++ const [model] = await client.listModels();++ expect(model?.aliases).toEqual([]);+ });++ it("applies the same mapping as getModel", async () => {+ // listModels and getModel each had their own copy of the allowlist; they+ // now share one mapper, and this pins that they stay in step.+ mockFetch.mockResolvedValueOnce(jsonResponse({ models: [FULL_WIRE_ENTRY] }));++ const [model] = await client.listModels();++ expectEveryTypedFieldPresent(model);++ expect(model?.name).toBe(FULL_WIRE_ENTRY.name);+ expect(model?.loaded).toBe(true);+ expect(model?.state).toBe("loaded");+ expect(model?.aliases).toEqual(FULL_WIRE_ENTRY.aliases);+ expect(model?.lastError).toBeNull();+ expect(model?.inputs).toEqual(FULL_WIRE_ENTRY.inputs);+ expect(model?.outputs).toEqual(FULL_WIRE_ENTRY.outputs);+ expect(model?.dims).toEqual(FULL_WIRE_ENTRY.dims);+ expect(model?.revision).toBe(FULL_WIRE_ENTRY.revision);+ expect(model?.profiles).toEqual(FULL_WIRE_ENTRY.profiles);+ expect(model?.capabilities).toEqual(FULL_WIRE_ENTRY.capabilities);+ expect(model?.pendingGeneration).toEqual(FULL_WIRE_ENTRY.pending_generation);+ expect(model?.maxSequenceLength).toBe(FULL_WIRE_ENTRY.max_sequence_length);+ expect(model?.maxSequenceLength).toBe(8192);+ });});diff --git a/packages/sie_ts_sdk/vitest.integration.config.ts b/packages/sie_ts_sdk/vitest.integration.config.tsindex a1c631681..22712f68f 100644--- a/packages/sie_ts_sdk/vitest.integration.config.ts+++ b/packages/sie_ts_sdk/vitest.integration.config.ts@@ -5,7 +5,7 @@* The server is started automatically via globalSetup.** Usage:- * mise run ts test-integration+ * mise run ts -- test-integration* # or directly:* pnpm test:integration*/diff --git a/packages/wire-fixtures/README.md b/packages/wire-fixtures/README.mdindex 6213d2fee..8f4c9ad54 100644--- a/packages/wire-fixtures/README.md+++ b/packages/wire-fixtures/README.md@@ -10,6 +10,33 @@ executable.- `model_state.json` — the canonical `ModelState` values (`available`,`loading`, `loaded`, `unloading`, `failed`).+- `request_usage.json` — how the response `usage` block is partitioned. The+ gateway is the only writer of `settled_charge_fields`; everything a consumer+ meters lives in `terminal_unit_fields`. The two sets are disjoint and their+ union is the WHOLE block, which is what lets a consumer reject an undeclared+ key — a silently renamed meter — without also rejecting the settled charge+ that legitimately rides alongside it. See issue #3063 for the failure this+ exists to prevent.+- `model_info.json` — the field set of one `/v1/models` entry, split into+ `typed` (an SDK `ModelInfo` MUST declare it) and `excluded` (an SDK MUST NOT+ declare it, with the reason recorded per key).+- `oss_payload_store.json` — the cross-language Alibaba OSS payload contract.+ The gateway writes `prefix/plain_key`, the queue retains `plain_key`, and the+ sidecar accepts that key or the exact `full_reference`; Python and both Rust+ binaries load the same fixture to prevent prefix drift.++### Why `model_info.json` has two buckets++A "covered set" alone only catches fields an SDK forgot. It says nothing about+fields an SDK left out *on purpose*, so the next reader cannot tell an omission+from a decision — which is how `state`, `last_error`, `profiles` and+`pending_generation` sat undeclared in both SDKs for several releases. Listing+both buckets makes a new wire field fail the tests until someone consciously+puts it in one of them.++Today `excluded` holds only the OpenAI retrieve-model compat keys+(`id`/`object`/`created`/`owned_by`) that `GET /v1/models/{model}` merges in for+vanilla OpenAI clients.## Adding a consumer@@ -17,14 +44,27 @@ Point a test at the JSON and assert the implementation's enum/type matches thefixture set. Current consumers:- Python SDK — `packages/sie_sdk/tests/test_wire_contract.py` (asserts- `typing.get_args(ModelState)` matches the fixture).+ `typing.get_args(ModelState)` and `ModelInfo.__annotations__` match the+ fixtures, and that+ `RequestUsage`/`TERMINAL_UNIT_FIELDS`/`SETTLED_CHARGE_FIELDS` match+ `request_usage.json`).- TypeScript SDK — `packages/sie_ts_sdk/tests/wireContract.test.ts` (asserts the- runtime `MODEL_STATES` array — the single source the `ModelState` type is- derived from — matches the fixture).+ runtime `MODEL_STATES` and `MODEL_INFO_WIRE_FIELDS` arrays — the single+ sources the `ModelState` type and `WireModelInfo` interface are checked+ against — match the fixtures).+- Downstream gateways assert that the members they inject are exactly+ `settled_charge_fields`, so a gateway that starts publishing a third field+ cannot reach production before every consumer has declared it.++The TS SDK carries extra tests the Python SDK does not need: its client re-maps+the `/v1/models` response (camelCasing three top-level keys), so a field can be+declared on the type and still never reach a caller. Those tests drive a fully+populated wire entry through `getModel`/`listModels`.## Scope-This is the first slice (issue #1637): `ModelState` only. Extend the same-fixture file (and the two tests) with `ModelCapabilities`, error codes, and-status messages as they are pinned. Codegen can come later if fixtures prove+This started as one slice (issue #1637): `ModelState` only. `request_usage.json`+(issue #3063) is the second, `model_info.json` (issue #3126) the third. Extend+the same directory with `ModelCapabilities` values, error codes, and status+messages as they are pinned. Codegen can come later if fixtures proveinsufficient.diff --git a/packages/wire-fixtures/model_info.json b/packages/wire-fixtures/model_info.jsonnew file mode 100644index 000000000..3a0e2418b--- /dev/null+++ b/packages/wire-fixtures/model_info.json@@ -0,0 +1,42 @@+{+ "_comment": [+ "Golden field set for one `/v1/models` (and `/v1/models/{model}`) entry.",+ "`typed` is every key the gateway emits that an SDK ModelInfo type MUST",+ "declare; `excluded` is every key it emits that an SDK MUST NOT declare,",+ "each with the reason. A new wire field fails both SDK tests until it is",+ "consciously placed in one bucket or the other \u2014 that is the point.",+ "Emitters: packages/sie_gateway/src/types/model.rs::to_model_info_value",+ "plus attach_model_revision/attach_pending_generation in",+ "packages/sie_gateway/src/handlers/models.rs; schema of record is",+ "packages/sie_gateway/src/openapi.rs::ModelInfoWire. The single-server",+ "emitter is packages/sie_server/src/sie_server/api/models.py::ModelInfo,",+ "which is a subset (no pending_generation)."+ ],+ "typed": [+ "aliases",+ "capabilities",+ "dims",+ "inputs",+ "last_error",+ "loaded",+ "max_sequence_length",+ "name",+ "outputs",+ "pending_generation",+ "profiles",+ "revision",+ "state"+ ],+ "excluded": {+ "created": "OpenAI retrieve-model compat only. Fixed sentinel epoch (SIE has no per-model creation time); OpenAI clients use it for display/sorting. Carries no SIE meaning.",+ "id": "OpenAI retrieve-model compat only. Byte-identical to `name`; typing both would imply they can differ.",+ "object": "OpenAI retrieve-model compat only. Constant \"model\" discriminator for the OpenAI envelope.",+ "owned_by": "OpenAI retrieve-model compat only. Constant \"sie\"."+ },+ "notes": {+ "excluded_scope": "The four excluded keys are merged in by GET /v1/models/{model} for vanilla OpenAI 'retrieve model' clients; on GET /v1/models they live in the sibling `data` array instead, never on a `models` entry.",+ "optionality": "Python marks every typed key optional (`total=False`). TypeScript requires `name`, `loaded`, `inputs` and `outputs` on both `ModelInfo` and `WireModelInfo`; its remaining keys are optional. `pending_generation` is gateway-only. `last_error`/`max_sequence_length`/`revision`/`capabilities` are the four the emitters can send as an explicit null, so the SDK types admit null on each. The fixture pins which keys are declarable, not which are always present.",+ "ts_renames": "The TS SDK camelCases three top-level keys \u2014 max_sequence_length -> maxSequenceLength, last_error -> lastError, pending_generation -> pendingGeneration \u2014 and leaves nested objects wire-shaped. Its consumer test checks the wire-side names listed here.",+ "aliases": "Short task-tier names resolving to this model. Always emitted, empty when the model has none, so callers can distinguish 'no aliases' from an older gateway. Only catalog- or operator-declared names appear; the gateway's compiled-in routing defaults are not public API and are never listed."+ }+}diff --git a/packages/wire-fixtures/oss_payload_store.json b/packages/wire-fixtures/oss_payload_store.jsonnew file mode 100644index 000000000..7b126e49a--- /dev/null+++ b/packages/wire-fixtures/oss_payload_store.json@@ -0,0 +1,9 @@+{+ "version": 1,+ "scheme": "oss",+ "bucket": "sie-wire-fixture",+ "prefix": "payloads",+ "plain_key": "request_00000000_0.bin",+ "object_key": "payloads/request_00000000_0.bin",+ "full_reference": "oss://sie-wire-fixture/payloads/request_00000000_0.bin"+}diff --git a/packages/wire-fixtures/request_usage.json b/packages/wire-fixtures/request_usage.jsonnew file mode 100644index 000000000..1ea9424b8--- /dev/null+++ b/packages/wire-fixtures/request_usage.json@@ -0,0 +1,12 @@+{+ "usage_container": "usage",+ "terminal_unit_fields": [+ "audio_ms",+ "images",+ "input_tokens",+ "output_tokens",+ "pages",+ "pairs"+ ],+ "settled_charge_fields": ["credits_charged", "rate_book_version"]+}diff --git a/pyproject.toml b/pyproject.tomlindex 94f90f313..0d4371428 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -98,7 +98,7 @@ markers = ["eks: tests that require a real EKS cluster","generation: tests that exercise generation endpoint contracts or a real generation worker","observability: tests that require optional local observability components",- "idle_rerank: opt-in Tilt e2e for idle-eviction behavior",+ "idle_rerank: opt-in end-to-end idle-eviction behavior","model: model regression tests that download real weights","fake_stack: deterministic weightless Fake Engine regression tests",]diff --git a/telemetry/README.md b/telemetry/README.mdindex b4d8b877b..0df561dae 100644--- a/telemetry/README.md+++ b/telemetry/README.md@@ -12,10 +12,10 @@ conditionally owned queue/adaptive-scheduler surfaces. Only authoritative lanelifecycle signals remain excluded until a deployed producer owns them;undeclared new instruments are not permitted.-The current inventory is 117 application families: 115 may reach the remote+The current inventory is 122 application families: 120 may reach the remoteOTLP branch and two remain Prometheus-only controls. Nine additional,exact collector-self families form a separate operational allowlist. The-Better Stack dashboard code therefore covers 124 remotely eligible families+Better Stack dashboard code therefore covers 129 remotely eligible familieswithout turning collector self-telemetry into a version-dependent wildcard.`sie.gateway.pool.pinned_model.loaded` is intentionally Prometheus-only. Its@@ -276,11 +276,14 @@ For the sidecar's six declared queue operations, the budget isEvery sidecar instrument nevertheless has an explicit SDK view derived fromits full checked-in attribute domains. Batch size/cost omit `flush.reason`because it does not change their batch-shape semantics; fill ratio retains it.-The resulting high-product ceilings are 14,392 fill-ratio series and 4,112-generation-loading series, while all other sidecar ceilings are at or below-1,799. These are upper bounds on retained SDK series, not expected steady-state-usage or byte-size claims; the machine-checked formulas live in-`contract.yaml`.+`sie.worker.work_item.age` omits the catalog pair entirely and costs seven+series: transport-queue age is a property of the queue rather than of the+model on the far side of it, so the catalog factor would multiply the series+count without adding an answer. The resulting high-product ceilings are 14,392+fill-ratio series and 4,112 generation-loading series, while all other sidecar+ceilings are at or below 1,799. These are upper bounds on retained SDK series,+not expected steady-state usage or byte-size claims; the machine-checked+formulas live in `contract.yaml`.## KEDA is a control API@@ -355,8 +358,7 @@ Helm uses `lookup` to render each existing Deployment or StatefulSet's liveHelm resource patch from resetting the observed HPA-controlled replica count and leaves nopermanent replica-pin data in values, annotations, or release history.-The `0.6.20` boundary is one supervised maintenance-window upgrade, documented-in the [deployment runbook](../deploy/upgrade-runbook.md).+The `0.6.20` boundary requires one supervised maintenance-window upgrade.Stop external traffic and topology/config writes, keep the effective namespace,lane catalog, names, scale targets, Prometheus backend, and KEDA ownershipunchanged, and run one normaldiff --git a/telemetry/contract.yaml b/telemetry/contract.yamlindex cdb5259d7..585466d82 100644--- a/telemetry/contract.yaml+++ b/telemetry/contract.yaml@@ -1,5 +1,5 @@schema_version: 1-contract_version: "2026-07-20"+contract_version: "2026-08-14"# This is the machine-readable telemetry source of truth. A request path emits# one typed semantic event; the owning facade is the only code allowed to turn@@ -257,6 +257,10 @@ cardinality_budgets:- sie.worker.scheduler.request_batch.totalformula: operation * catalog_series_pairslimit: 1799+ work_item_age:+ metrics: [sie.worker.work_item.age]+ formula: operation * lane_per_process+ limit: 7batch_fill:metrics: [sie.worker.batch.fill_ratio]formula: operation * catalog_series_pairs * flush_reason@@ -369,6 +373,25 @@ cardinality_budgets:- sie.gateway.active_lease.gpus- sie.gateway.pool.warm_floor- sie.gateway.rejected.requests+ # Per-lane queue admission reuses the same deployment-owned lane tuple and+ # the same fail-closed rules as the KEDA control domain, but is not itself a+ # KEDA control signal: its Prometheus spelling is not a scaler API.+ gateway_lane_admission_domain:+ source: SIE_GATEWAY_CONFIGURED_PHYSICAL_LANES+ tuple: [pool, machine_profile, bundle]+ normalization: trim_then_lowercase+ allowed_characters: "^[A-Za-z0-9_-]+$"+ maximum_component_length: 63+ maximum_configured_lanes: 1024+ emission: exact_catalog_members_only+ unresolved_lane_behavior: omit_decision_metric+ synthetic_fallback_lane: forbidden+ sdk_stream_cardinality:+ # 1024 configured lanes x 3 lane_admission_outcome values.+ lane_admission_decisions: 3072+ overflow_series: forbidden+ applies_to:+ - sie.gateway.queue.lane_admission.decisionsscope:included: all_production_metrics_keda_control_signals_and_privacy_approved_managed_logs@@ -439,34 +462,44 @@ resource_attributes:- service.versionservices:+ control_plane:+ service_name: sie-control-plane+ managed_collector: control_planegateway:service_name: sie-gateway+ managed_collector: regionalruntimes:- packages/sie_gateway- packages/sie_cloud/gatewaydispatcher:service_name: sie-dispatcher+ managed_collector: regionalruntimes:- packages/sie_cloud/dispatcherconfig:service_name: sie-config+ managed_collector: regionalruntimes:- packages/sie_configworker_sidecar:service_name: sie-worker-sidecar+ managed_collector: regionalruntimes:- packages/sie_server_sidecarworker_engine:service_name: sie-worker+ managed_collector: regionalruntimes:- packages/sie_server- packages/sie_server_rustworker_python_engine:service_name: sie-worker+ managed_collector: regionalruntimes:- packages/sie_serverworker_rust_engine:service_name: sie-worker+ managed_collector: regionalruntimes:- packages/sie_server_rust@@ -662,6 +695,8 @@ traces:enums:operation: [encode, score, extract, embeddings, moderations, generate, other]+ activity_window: [1h, 24h]+ launch_credit_status: [pending, approved, rejected, other]request_outcome: [success, redirect, client_error, server_error, other]admission_outcome:- admitted@@ -675,6 +710,14 @@ enums:- key_spend_limit_exceeded- rate_limited- other+ # `discarded` is a 200 whose snapshot body did not strictly advance the held+ # version, so the replica parsed and then dropped it. Keeping it distinct from+ # `installed` is the point of the family: a bare 200-vs-304 split cannot tell+ # a useful fetch from a wasted one.+ key_snapshot_poll_outcome: [not_modified, installed, discarded, error]+ # `skipped` is the no-reservation branch, which issues no control-plane call+ # and therefore contributes no duration observation.+ settlement_confirm_outcome: [success, error, skipped]gateway_dispatch_path: [i6pn, modal, other]dispatcher_path: [modal_remote, modal_stream, modal_spawn, generation_ws, other]dispatch_outcome: [success, error, timeout, cancelled, not_found, other]@@ -756,6 +799,14 @@ enums:- decodequeue_event: [publish_ack, dlq_forward, payload_offload]queue_event_outcome: [success, ack_error, error, deduplicated]+ # `shed_shadow` is the decision the per-lane check would have taken with+ # enforcement on. It never changes admission.+ lane_admission_outcome: [admitted, shed_shadow, shed_enforced]+ # Fixed set of keyed worker pools on the inbox path. `inbox` backpressures+ # when saturated because dropping a result or chunk is a correctness fault;+ # `cleanup` sheds because the expiry reconcile already recovers the key.+ queue_worker_pool: [inbox, payload_cleanup]+ queue_worker_pool_event: [saturated, shed]provisioning_surface: [native, openai]generation_event: [cancellation, chunk, nak]generation_event_reason:@@ -914,6 +965,12 @@ attribute_domains:bundle: {type: release_manifest_value, invalid: other}attribute_sets:+ control_plane_operation:+ operation: operation+ control_plane_activity:+ window: activity_window+ control_plane_launch_credit:+ status: launch_credit_statusgateway_request:operation: operationoutcome: request_outcome@@ -944,6 +1001,14 @@ attribute_sets:gateway_queue_event:event: queue_eventoutcome: queue_event_outcome+ gateway_lane_admission:+ pool: pool+ machine_profile: machine_profile+ bundle: bundle+ outcome: lane_admission_outcome+ gateway_queue_worker_pool:+ pool: queue_worker_pool+ event: queue_worker_pool_eventgateway_provisioning:surface: provisioning_surfacehttp.status_code: http.status_code@@ -951,6 +1016,10 @@ attribute_sets:event: generation_eventreason: generation_event_reasonoutcome: generation_event_outcome+ gateway_key_snapshot_poll:+ outcome: key_snapshot_poll_outcome+ gateway_settlement_confirm:+ outcome: settlement_confirm_outcomegateway_generation_completion:operation: operationgateway_generation_tokens:@@ -991,6 +1060,12 @@ attribute_sets:lane: lanemodel: modelprofile: profile+ # Transport-queue age is a property of the queue, not of the model that+ # happens to be on the other side of it, so this set deliberately omits the+ # catalog (model, profile) pair the scheduler-local queue families carry.+ worker_work_item_age:+ operation: operation+ lane: laneworker_batch:operation: operationlane: lane@@ -1204,6 +1279,11 @@ histogram_buckets:gateway_queue_publish_seconds: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0]gateway_queue_publish_items: [1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61]gateway_queue_result_wait_seconds: [0.01, 0.025, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0, 2.0, 5.0, 10.0, 30.0]+ # Shares gateway_request_seconds' boundaries below 1.0 so the confirm's share+ # of buffered response latency is readable off the two histograms directly.+ # The 20.0 boundary is the documented worst case: four attempts under a+ # five-second client timeout each.+ gateway_settlement_confirm_seconds: [0.0005, 0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0]dispatcher_invocation_seconds: [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0]# Sealed staging is fetch + seal + first model load, NOT a request: the measured# cold start is ~130 s, so the interesting resolution is tens-to-hundreds of@@ -1212,6 +1292,11 @@ histogram_buckets:dispatcher_sealed_stage_seconds: [1.0, 5.0, 10.0, 30.0, 60.0, 120.0, 180.0, 300.0, 450.0, 600.0, 900.0]config_request_seconds: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0]worker_queue_seconds: [0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0]+ # Transport-queue age spans far past the scheduler-local 30s ceiling. The+ # upper boundaries are the system's own constants — 120s client ceiling, 300s+ # generation ack wait, 600s redelivery envelope, 1800s stream retention — so+ # "executed after its client gave up" is a bucket count, not an interpolation.+ worker_work_item_age_seconds: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0]worker_request_seconds: [0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0]worker_model_load_seconds: [0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 900.0]worker_ipc_seconds: [0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 300.0, 900.0]@@ -1230,6 +1315,78 @@ histogram_buckets:# Prometheus exporter. Histograms add _bucket/_sum/_count. These names are a# tested wire contract, not a second producer API.metrics:+ - name: sie.control_plane.signup.activated+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{account}"+ attributes: none+ prometheus_name: sie_control_plane_signup_activated+ export: [otlp]+ - name: sie.control_plane.starter.credits+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{credit}"+ attributes: none+ prometheus_name: sie_control_plane_starter_credits+ export: [otlp]+ - name: sie.control_plane.terminal.requests+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{request}"+ attributes: control_plane_operation+ prometheus_name: sie_control_plane_terminal_requests+ export: [otlp]+ - name: sie.control_plane.metered.credits+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{credit}"+ attributes: control_plane_operation+ prometheus_name: sie_control_plane_metered_credits+ export: [otlp]+ - name: sie.control_plane.active.accounts+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{account}"+ attributes: control_plane_activity+ prometheus_name: sie_control_plane_active_accounts+ export: [otlp]+ - name: sie.control_plane.wallet.balance+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{credit}"+ attributes: none+ prometheus_name: sie_control_plane_wallet_balance+ export: [otlp]+ - name: sie.control_plane.launch_credit.applications+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{application}"+ attributes: control_plane_launch_credit+ prometheus_name: sie_control_plane_launch_credit_applications+ export: [otlp]+ - name: sie.control_plane.outbox.pending+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{event}"+ attributes: none+ prometheus_name: sie_control_plane_outbox_pending+ export: [otlp]+ - name: sie.control_plane.outbox.lag+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: s+ attributes: none+ prometheus_name: sie_control_plane_outbox_lag_seconds+ export: [otlp]- name: sie.gateway.requestsowner: gatewayfacade_event: gateway.request_completed@@ -1330,6 +1487,19 @@ metrics:buckets: gateway_queue_publish_itemsprometheus_name: sie_gateway_queue_publish_itemsexport: [prometheus, otlp]+ - name: sie.gateway.queue.worker_pool.events+ owner: gateway+ facade_event: gateway.queue_worker_pool_event+ type: counter+ unit: "{event}"+ attributes: gateway_queue_worker_pool+ prometheus_name: sie_gateway_queue_worker_pool_events_total+ # A local saturation diagnostic for the inbox decode pools, not a remote+ # dashboard series: it answers "is this replica's decode path backing up"+ # while reading the replica's own logs and pprof. Keeping it local also+ # avoids owing a Better Stack query and a collector route for a counter+ # that is expected to sit at zero.+ export: [prometheus]- name: sie.gateway.queue.result_waitsowner: gatewayfacade_event: gateway.queue_result_wait_completed@@ -1355,6 +1525,17 @@ metrics:attributes: gateway_queue_eventprometheus_name: sie_gateway_queue_events_totalexport: [prometheus, otlp]+ # Per-lane queue admission (design: settlement-and-queue-scalability B5).+ # `shed_shadow` is recorded while enforcement is off so the new decision can+ # be evaluated against production traffic before it sheds anything.+ - name: sie.gateway.queue.lane_admission.decisions+ owner: gateway+ facade_event: gateway.queue_lane_admission_decided+ type: counter+ unit: "{decision}"+ attributes: gateway_lane_admission+ prometheus_name: sie_gateway_queue_lane_admission_decisions_total+ export: [prometheus, otlp]- name: sie.gateway.queue.result_chunks.receivedowner: gatewayfacade_event: gateway.queue_result_chunk_received@@ -1463,6 +1644,35 @@ metrics:prometheus_name: sie_gateway_generation_tokens_totalexport: [prometheus, otlp]+ # Conditional-GET effectiveness of the managed key-snapshot poll, counted at+ # the only conditional caller. Answers whether the 304 fast path actually+ # hits under production traffic.+ - name: sie.gateway.key_snapshot.polls+ owner: gateway+ facade_event: gateway.key_snapshot_poll_completed+ type: counter+ unit: "{poll}"+ attributes: gateway_key_snapshot_poll+ prometheus_name: sie_gateway_key_snapshot_polls_total+ export: [prometheus, otlp]+ # What a buffered managed response waits on before it is returned.+ - name: sie.gateway.settlement.confirms+ owner: gateway+ facade_event: gateway.settlement_confirm_completed+ type: counter+ unit: "{confirm}"+ attributes: gateway_settlement_confirm+ prometheus_name: sie_gateway_settlement_confirms_total+ export: [prometheus, otlp]+ - name: sie.gateway.settlement.confirm.duration+ owner: gateway+ facade_event: gateway.settlement_confirm_completed+ type: histogram+ unit: s+ attributes: gateway_settlement_confirm+ buckets: gateway_settlement_confirm_seconds+ prometheus_name: sie_gateway_settlement_confirm_duration_seconds+ export: [prometheus, otlp]- name: sie.dispatcher.invocationsowner: dispatcherfacade_event: dispatcher.invocation_completed@@ -1621,6 +1831,22 @@ metrics:attributes: worker_queueprometheus_name: sie_worker_queue_depthexport: [prometheus, otlp]+ # Transport-queue age at execution commit, which the scheduler-local queue+ # families above cannot see. Recorded at every execution-commit point (the+ # three batch handlers, the scheduler drain, and generation) so no operation+ # is silently absent; items that never execute are deliberately not observed.+ # Owned by the sidecar alone: the Modal-native Python lane has no broker+ # between the gateway and the engine, so there is no second producer of this+ # observation to conflict with.+ - name: sie.worker.work_item.age+ owner: worker_sidecar+ facade_event: worker.work_item_age_observed+ type: histogram+ unit: s+ attributes: worker_work_item_age+ buckets: worker_work_item_age_seconds+ prometheus_name: sie_worker_work_item_age_seconds+ export: [prometheus, otlp]- name: sie.worker.scheduler.request_batch.dispatch_waitowner: worker_sidecarfacade_event: worker.scheduler_request_batch_completed@@ -2054,6 +2280,20 @@ metrics:buckets: generation_secondsprometheus_name: sie_worker_generation_ttft_secondsexport: [prometheus, otlp]+ # Worker-side phase boundary for #3136: receipt -> adapter dispatch+ # (validation, model load, chat-template render, admission/capacity wait).+ # Complements ttft (engine grammar preparation + prefill) and tpot (decode)+ # so the client-observed time-to-first-token decomposes by phase per+ # grammar mode.+ - name: sie.worker.generation.worker_wait+ owner: worker_python_engine+ facade_event: worker.generation_worker_wait_observed+ type: histogram+ unit: s+ attributes: generation_stream+ buckets: generation_seconds+ prometheus_name: sie_worker_generation_worker_wait_seconds+ export: [prometheus, otlp]- name: sie.worker.generation.tpotowner: worker_python_enginefacade_event: worker.generation_stream_completeddiff --git a/tools/check_ipc_types_parity.py b/tools/check_ipc_types_parity.pynew file mode 100755index 000000000..07429de42--- /dev/null+++ b/tools/check_ipc_types_parity.py@@ -0,0 +1,425 @@+#!/usr/bin/env python3+"""IPC types parity check across the sidecar boundary.++The IPC wire contract is declared twice:++* ``packages/sie_server_sidecar/src/protocol/ipc_types.rs`` (Rust —+ owned by the worker-sidecar; ``src/ipc_types.rs`` re-exports it so+ existing sidecar call sites use the same types)+* ``packages/sie_server/src/sie_server/ipc_types.py`` (Python adapter)++Each declaration is independent — there is no codegen — and every+field travels over msgpack as a named map entry, so a unilateral+rename or new field on either side silently breaks the round-trip on+the other. Run this script to catch that drift before integration.++What we check:++* **Constants** (``IPC_VERSION``, ``METHOD_*``): name and value parity+ across both sources.+* **Struct / class field parity**: for every type whose name appears in+ any of the sources, the set of field names must match across every+ source that declares it. Types that legitimately exist on only one+ side (e.g. ``RequestEnvelope`` is generic-only in Rust and absent+ from Python) are tolerated, but anything declared on both sides+ must agree on field names.+* **Enum variant parity**: same shape as struct fields.++What we deliberately do NOT check:++* **Field types**. Rust ``u32`` ↔ Python ``int`` drift would need a+ per-language type-equivalence table that adds a lot of fragile+ mapping code for no win — type drift surfaces as a msgpack-decode+ error in the integration tests within seconds and the parity tests+ catch the wire-shape end of it. This script guards the+ much-easier-to-miss ``forgot to rename a field`` case.+* **Field order**. msgpack maps are key-addressed; ordering is+ cosmetic.+* **Doc comments**. They differ by intent (Rust uses ``///``, Python+ uses inline ``#``).++Invocation:++ mise exec -- uv run --no-project python tools/check_ipc_types_parity.py++Returns ``0`` on parity, ``1`` on drift with a human-readable diff.+"""++from __future__ import annotations++import ast+import re+import sys+from dataclasses import dataclass, field+from pathlib import Path++# ---------------------------------------------------------------------------+# Source locations — single source of truth for the schema files.+# ---------------------------------------------------------------------------++REPO_ROOT = Path(__file__).resolve().parents[1]++RUST_PROTOCOL_IPC = REPO_ROOT / "packages" / "sie_server_sidecar" / "src" / "protocol" / "ipc_types.rs"+PY_SERVER_IPC = REPO_ROOT / "packages" / "sie_server" / "src" / "sie_server" / "ipc_types.py"++# Types that are intentionally one-sided. Adding a name to this set+# encodes a deliberate decision; anything not on the list and not+# present on every side is reported as drift.+#+# `RequestEnvelope` is generic-only in Rust (carries the body type+# parameter); the Python server reads request frames as raw dicts in+# `ipc_server._dispatch_frame`, so there is no mirror class to match.+#+# `ResponseEnvelope` IS declared on the Python side (typed) but the+# Rust side carries it generic over the body — both sides agree on the+# named fields, so we keep it in the parity check.+#+# `DrainRequest` is declared in Rust but only via the wire on Python+# (Python reads `deadline_ms` as a dict key in `_handle_drain` and never+# builds a typed struct). Tolerate.+ONE_SIDED_NAMES: frozenset[str] = frozenset(+ {+ "RequestEnvelope",+ "DrainRequest",+ # `RunBatchOp` is a Python `Literal[...]` mirror of the+ # `op` discriminator string. Rust intentionally types `op`+ # as `String` and validates the value at dispatch time, so+ # there is no Rust enum to align against. The valid set is+ # co-tested by the parity fixtures in `tests/parity/`.+ "RunBatchOp",+ }+)+++# ---------------------------------------------------------------------------+# Parsed schema model — the shape we normalise each source into so the+# comparator is language-agnostic.+# ---------------------------------------------------------------------------+++@dataclass+class TypeDecl:+ """Either a struct/class with field names, or an enum with variant+ names. Stored uniformly: ``fields`` doubles as the variant set for+ enums (msgpack rename_all serialises Rust enums as strings, so the+ Python `Literal[...]` on the other side mirrors the variant set).+ """++ name: str+ kind: str # "struct" | "enum"+ fields: set[str] = field(default_factory=set)+ location: str = "" # "<filename>:<line>" for diagnostics+++@dataclass+class Schema:+ label: str+ constants: dict[str, str] = field(default_factory=dict)+ types: dict[str, TypeDecl] = field(default_factory=dict)+++# ---------------------------------------------------------------------------+# Rust parser — regex-based, deliberately scoped to ``ipc_types.rs`` files+# whose shape is uniform (every struct has `#[derive(...)]\npub struct ...`+# and every field is `pub field_name: Type,`). This is not a general-purpose+# Rust parser; if these files start using more exotic syntax, lean on+# `syn` instead.+# ---------------------------------------------------------------------------+++def parse_rust(path: Path, label: str) -> Schema:+ src = path.read_text()+ schema = Schema(label=label)++ # Constants: `pub const NAME: TYPE = VALUE;` on a single line.+ # Captures the literal value as a string so we can equality-check+ # numeric and string constants without parsing types.+ for match in re.finditer(+ r"^pub const (?P<name>[A-Z_][A-Z0-9_]*)\s*:\s*[^=]+=\s*(?P<value>.+?);",+ src,+ flags=re.MULTILINE,+ ):+ schema.constants[match.group("name")] = match.group("value").strip()++ # Strip block doc-comments and field-level attributes inside struct+ # bodies before slicing out fields. This keeps the field regex+ # simple — match `pub <name>:` only.+ #+ # We capture preceding `#[...]` attribute lines so we can pluck+ # `#[serde(rename_all = "snake_case")]` off enums and apply the+ # rename to variant names — without it, Rust `Ready` ≠ Python+ # `"ready"` even though they are the SAME wire string.+ type_re = re.compile(+ r"(?P<attrs>(?:#\[[^\]]+\]\s*)*)"+ r"pub (?P<kind>struct|enum) (?P<name>[A-Za-z_][A-Za-z0-9_]*)"+ # optional generics like `<'a, B: Serialize>` — we don't care+ # about their content, just need to skip past them.+ r"(?:<[^>]*>)?"+ r"\s*\{(?P<body>.*?)\n\}",+ flags=re.DOTALL,+ )+ field_re = re.compile(+ r"^\s*pub (?P<name>[A-Za-z_][A-Za-z0-9_]*)\s*:",+ flags=re.MULTILINE,+ )+ enum_variant_re = re.compile(+ r"^\s*(?P<name>[A-Z][A-Za-z0-9_]*)\s*[,({]",+ flags=re.MULTILINE,+ )+ rename_all_re = re.compile(r'#\[serde\([^)]*rename_all\s*=\s*"(?P<style>[^"]+)"[^)]*\)\]')++ for match in type_re.finditer(src):+ name = match.group("name")+ kind = match.group("kind")+ body = match.group("body")+ attrs = match.group("attrs") or ""+ line = src[: match.start()].count("\n") + 1+ decl = TypeDecl(name=name, kind=kind, location=f"{path.name}:{line}")+ if kind == "struct":+ decl.fields = {m.group("name") for m in field_re.finditer(body)}+ else:+ variants = {m.group("name") for m in enum_variant_re.finditer(body)}+ rm = rename_all_re.search(attrs)+ if rm is not None:+ decl.fields = {_apply_serde_rename(v, rm.group("style")) for v in variants}+ else:+ decl.fields = variants+ schema.types[name] = decl++ return schema+++def _apply_serde_rename(name: str, style: str) -> str:+ """Mirror serde's `rename_all` for the styles this codebase uses+ (today: `snake_case` only). Adding a new style on either side is a+ one-liner here; we keep the supported set narrow so an unfamiliar+ style fails the check loudly instead of silently letting a rename+ drift through.+ """+ if style == "snake_case":+ # Rust variant names are `UpperCamelCase` (enforced by the+ # compiler). Convert to snake_case the way serde does:+ # insert `_` between an upper run and the next word, then+ # lowercase. `LoadingStarted` → `loading_started`,+ # `RetryLater` → `retry_later`. Acronym-aware logic is+ # unnecessary here — none of the IPC enums use them.+ out: list[str] = []+ for i, ch in enumerate(name):+ if ch.isupper() and i > 0:+ out.append("_")+ out.append(ch.lower())+ return "".join(out)+ raise ValueError(+ f"unsupported serde rename_all style {style!r} on enum (extend "+ "_apply_serde_rename in tools/check_ipc_types_parity.py to teach "+ "the parity check about this style)"+ )+++# ---------------------------------------------------------------------------+# Python parser — `ast`-based. Captures top-level constants+# (`Name = value` and `Name: type = value`) plus `msgspec.Struct` /+# `msgspec.Struct(tag=...)` subclasses with their annotated fields,+# plus `Literal[...]` aliases (treated as enum variant sets so Python+# mirror types like `ReadinessState` line up with Rust enums).+# ---------------------------------------------------------------------------+++def _is_msgspec_struct_class(node: ast.ClassDef) -> bool:+ """True if `class Foo(msgspec.Struct[...])` — covers both the+ plain inheritance and the tagged variant Python uses for the+ response envelope.+ """+ for base in node.bases:+ if isinstance(base, ast.Attribute) and base.attr == "Struct":+ return True+ if isinstance(base, ast.Name) and base.id == "Struct":+ return True+ if isinstance(base, ast.Call):+ # Defensive: msgspec.Struct used as a metaclass-like+ # expression. Not used in this codebase today but cheap+ # to support.+ if isinstance(base.func, ast.Attribute) and base.func.attr == "Struct":+ return True+ return False+++def _literal_variants(node: ast.expr) -> set[str] | None:+ """If `node` is `Literal["a", "b", ...]`, return {"a", "b", ...}+ in their Python wire-string form (kept verbatim — they are the+ msgpack values, not Python identifiers). Otherwise return None+ so the caller skips the binding.+ """+ if not isinstance(node, ast.Subscript):+ return None+ value = node.value+ is_literal = (isinstance(value, ast.Name) and value.id == "Literal") or (+ isinstance(value, ast.Attribute) and value.attr == "Literal"+ )+ if not is_literal:+ return None+ variants: set[str] = set()+ slice_node = node.slice+ elts = slice_node.elts if isinstance(slice_node, ast.Tuple) else [slice_node]+ for elt in elts:+ if isinstance(elt, ast.Constant) and isinstance(elt.value, str):+ variants.add(elt.value)+ else:+ return None+ return variants+++def parse_python(path: Path, label: str) -> Schema:+ src = path.read_text()+ tree = ast.parse(src, filename=str(path))+ schema = Schema(label=label)++ for node in tree.body:+ # Top-level constants: METHOD_FOO = "Foo", IPC_VERSION = 1+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):+ name = node.target.id+ if name.isupper() and node.value is not None:+ schema.constants[name] = ast.unparse(node.value).strip()+ elif isinstance(node, ast.Assign) and len(node.targets) == 1:+ tgt = node.targets[0]+ if isinstance(tgt, ast.Name) and tgt.id.isupper():+ schema.constants[tgt.id] = ast.unparse(node.value).strip()+ # Literal[...] type aliases — the Python mirror for Rust+ # `enum X { ... }` with `#[serde(rename_all="snake_case")]`.+ elif isinstance(tgt, ast.Name) and not tgt.id.isupper():+ variants = _literal_variants(node.value)+ if variants is not None:+ line = node.lineno+ schema.types[tgt.id] = TypeDecl(+ name=tgt.id,+ kind="enum",+ fields=variants,+ location=f"{path.name}:{line}",+ )++ elif isinstance(node, ast.ClassDef) and _is_msgspec_struct_class(node):+ fields_set: set[str] = set()+ for stmt in node.body:+ # `field_name: type = default` → AnnAssign with target=Name+ if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):+ fields_set.add(stmt.target.id)+ # `field_name: type` (no default) — same shape, also annassign.+ schema.types[node.name] = TypeDecl(+ name=node.name,+ kind="struct",+ fields=fields_set,+ location=f"{path.name}:{node.lineno}",+ )++ return schema+++# ---------------------------------------------------------------------------+# Comparator — emits one drift line per disagreement so automated logs are+# easy to scan; returns the number of drift findings so the caller+# can pass it through as the exit code.+# ---------------------------------------------------------------------------+++def compare(schemas: list[Schema]) -> list[str]:+ drift: list[str] = []++ # Constants must match in name and value across every schema that+ # declares them. (We allow a constant to be missing on the Python+ # side iff that side is the Python schema and the constant is+ # marked as ignored — none today.) Keep both directions: a Python+ # rename has to agree with a Rust rename and vice versa.+ all_const_names = {n for s in schemas for n in s.constants}+ for cname in sorted(all_const_names):+ present: list[tuple[str, object]] = []+ for s in schemas:+ if cname not in s.constants:+ drift.append(+ f"[const] {cname!r} is missing from {s.label} but "+ f"present elsewhere ({', '.join(o.label for o in schemas if cname in o.constants)})."+ )+ continue+ raw_value = s.constants[cname]+ try:+ # Rust and Python spell string literals with different quote+ # styles. Compare their literal values, not source spelling.+ value: object = ast.literal_eval(raw_value)+ except (SyntaxError, ValueError):+ value = raw_value+ present.append((s.label, value))+ if present and any(value != present[0][1] for _, value in present[1:]):+ drift.append(+ f"[const] {cname!r} value drift: " + ", ".join(f"{label}={value!r}" for label, value in present)+ )++ # Type-name parity. We tolerate the names on `ONE_SIDED_NAMES`;+ # everything else must appear on every schema or appear on none.+ all_type_names = {n for s in schemas for n in s.types}+ for tname in sorted(all_type_names):+ if tname in ONE_SIDED_NAMES:+ continue+ present_in = [s for s in schemas if tname in s.types]+ if len(present_in) != len(schemas):+ missing = ", ".join(s.label for s in schemas if tname not in s.types)+ present = ", ".join(s.label for s in present_in)+ drift.append(+ f"[type] {tname!r} present in [{present}] but missing from [{missing}]. "+ f"Add it on the missing side(s) or list it in ONE_SIDED_NAMES with a comment."+ )+ continue++ # Field / variant set must match.+ labelled_decls = [(schema.label, schema.types[tname]) for schema in schemas]+ first_label, first_decl = labelled_decls[0]+ first_fields = first_decl.fields+ for other_label, declaration in labelled_decls[1:]:+ if declaration.fields != first_fields:+ only_first = sorted(first_fields - declaration.fields)+ only_other = sorted(declaration.fields - first_fields)+ drift.append(+ f"[fields] {tname!r} drift between {first_decl.location} "+ f"({first_label}) and {declaration.location} ({other_label}):"+ + (f"\n only in {first_label}: {only_first}" if only_first else "")+ + (f"\n only in {other_label}: {only_other}" if only_other else "")+ )+ # Don't emit a second diff for the same name — first+ # one tells the operator what to fix.+ break++ return drift+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+++def main() -> int:+ schemas = [+ parse_rust(RUST_PROTOCOL_IPC, label="worker-sidecar"),+ parse_python(PY_SERVER_IPC, label="python-server"),+ ]++ drift = compare(schemas)+ if not drift:+ # Print a small breadcrumb so automated logs show that the check ran.+ print(f"ipc-types parity: OK ({len(schemas[0].types)} types, {len(schemas[0].constants)} constants)")+ return 0++ print(+ "ipc-types parity DRIFT detected. The IPC wire contract is declared on both sides and they have diverged:",+ file=sys.stderr,+ )+ print(file=sys.stderr)+ for entry in drift:+ print(f" - {entry}", file=sys.stderr)+ print(file=sys.stderr)+ print(+ f"Sources:\n - {RUST_PROTOCOL_IPC.relative_to(REPO_ROOT)}\n - {PY_SERVER_IPC.relative_to(REPO_ROOT)}",+ file=sys.stderr,+ )+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tools/check_response_chunk_protocol.py b/tools/check_response_chunk_protocol.pynew file mode 100755index 000000000..435174dfb--- /dev/null+++ b/tools/check_response_chunk_protocol.py@@ -0,0 +1,687 @@+#!/usr/bin/env python3+"""Pin the independently deployed response-chunk v1 wire contracts.++The IPC and NATS result transports are separate protocols with separate+negotiation and limit domains. Their declarations intentionally remain local+to independently built peers, so this checker makes v1 drift a validation+failure.++Values are pinned to v1, not merely compared pairwise: changing every current+peer under the same v1 discriminator would still break rolling compatibility+with an older image.+"""++from __future__ import annotations++import ast+import re+import sys+from collections.abc import Mapping+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]++IPC_FIELDS = {+ "version",+ "request_id",+ "transfer_digest",+ "chunk_index",+ "chunk_count",+ "total_bytes",+ "payload",+ "kind",+}+RESULT_FIELDS = {+ "kind",+ "work_item_id",+ "request_id",+ "item_index",+ "transfer_digest",+ "chunk_index",+ "chunk_count",+ "total_bytes",+ "payload",+}++IPC_KIND_V1 = "ipc_response_chunk_v1"+IPC_VERSION_V1 = 1+IPC_LEGACY_FRAME_BYTES_V1 = 32 * 1024 * 1024+IPC_CHUNK_PAYLOAD_BYTES_V1 = 4 * 1024 * 1024+IPC_MAX_RESPONSE_BYTES_V1 = 128 * 1024 * 1024+IPC_MAX_CHUNKS_V1 = 64++RESULT_KIND_V1 = "result_chunk_v1"+RESULT_MAX_BYTES_V1 = 16 * 1024 * 1024+RESULT_MAX_CHUNKS_V1 = 64+TRANSFER_DIGEST_BYTES_V1 = 32++IPC_CHUNK_CAPABILITY_V1 = "accepts_ipc_response_chunks_v1"+RESULT_CHUNK_CAPABILITY_V1 = "accepts_result_chunks"++SIDECAR_IPC_TYPES = "packages/sie_server_sidecar/src/protocol/ipc_types.rs"+PYTHON_IPC_TYPES = "packages/sie_server/src/sie_server/ipc_types.py"+PYTHON_IPC_SERVER = "packages/sie_server/src/sie_server/ipc_server.py"+SIDECAR_IPC_CLIENT = "packages/sie_server_sidecar/src/ipc_client.rs"+SIDECAR_IPC_MUX = "packages/sie_server_sidecar/src/ipc_mux.rs"+SIDECAR_IPC_CHUNKS = "packages/sie_server_sidecar/src/protocol/response_chunks.rs"+SIDECAR_WORK_TYPES = "packages/sie_server_sidecar/src/work_types.rs"+SIDECAR_PUBLISHER = "packages/sie_server_sidecar/src/publisher.rs"+GATEWAY_PUBLISHER = "packages/sie_gateway/src/queue/publisher.rs"+++def _read(relative_path: str, overrides: Mapping[str, str] | None) -> str:+ if overrides is not None and relative_path in overrides:+ return overrides[relative_path]+ return (REPO_ROOT / relative_path).read_text()+++def _eval_int_expr(expr: str) -> int:+ node = ast.parse(expr.strip(), mode="eval").body++ def evaluate(current: ast.expr) -> int:+ if isinstance(current, ast.Constant) and type(current.value) is int:+ return current.value+ if isinstance(current, ast.UnaryOp) and isinstance(current.op, ast.USub):+ return -evaluate(current.operand)+ if isinstance(current, ast.BinOp):+ left = evaluate(current.left)+ right = evaluate(current.right)+ if isinstance(current.op, ast.Mult):+ return left * right+ if isinstance(current.op, ast.Add):+ return left + right+ if isinstance(current.op, ast.Sub):+ return left - right+ if isinstance(current.op, ast.LShift):+ return left << right+ raise ValueError(f"unsupported integer constant expression: {expr!r}")++ return evaluate(node)+++def _rust_const(source: str, name: str) -> str:+ match = re.search(+ rf"^(?:pub(?:\([^)]*\))?\s+)?const\s+{re.escape(name)}\s*:\s*[^=]+\s*=\s*(?P<value>[^;]+);",+ source,+ flags=re.MULTILINE,+ )+ if match is None:+ raise ValueError(f"Rust constant {name} not found")+ return match.group("value").strip()+++def _python_const(source: str, name: str) -> str:+ tree = ast.parse(source)+ for node in tree.body:+ if isinstance(node, ast.Assign) and len(node.targets) == 1:+ target = node.targets[0]+ if isinstance(target, ast.Name) and target.id == name:+ return ast.unparse(node.value)+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):+ if node.target.id == name and node.value is not None:+ return ast.unparse(node.value)+ raise ValueError(f"Python constant {name} not found")+++def _rust_struct_body(source: str, name: str) -> str:+ match = re.search(+ rf"(?:#\[[^\]]+\]\s*)*(?:pub(?:\([^)]*\))?\s+)?struct\s+{re.escape(name)}"+ rf"(?:<[^>]*>)?\s*\{{(?P<body>.*?)\n\}}",+ source,+ flags=re.DOTALL,+ )+ if match is None:+ raise ValueError(f"Rust struct {name} not found")+ return match.group("body")+++def _rust_struct_fields(source: str, name: str) -> set[str]:+ return {+ field.group("name")+ for field in re.finditer(+ r"^\s*(?:pub\s+)?(?P<name>[a-z_][a-z0-9_]*)\s*:",+ _rust_struct_body(source, name),+ flags=re.MULTILINE,+ )+ }+++def _rust_field_attributes(source: str, struct_name: str, field_name: str) -> str:+ body = _rust_struct_body(source, struct_name)+ match = re.search(+ rf"(?P<attrs>(?:\s*#\[[^\]]+\]\s*)*)\s*(?:pub\s+)?\b{re.escape(field_name)}\s*:",+ body,+ )+ if match is None:+ raise ValueError(f"Rust field {struct_name}.{field_name} not found")+ return re.sub(r"\s+", "", match.group("attrs"))+++def _rust_field_has_serde_option(source: str, struct_name: str, field_name: str, option: str) -> bool:+ attributes = _rust_field_attributes(source, struct_name, field_name)+ return "#[serde(" in attributes and option in attributes+++def _python_struct_fields(source: str, name: str) -> set[str]:+ tree = ast.parse(source)+ for node in tree.body:+ if isinstance(node, ast.ClassDef) and node.name == name:+ return {+ statement.target.id+ for statement in node.body+ if isinstance(statement, ast.AnnAssign) and isinstance(statement.target, ast.Name)+ }+ raise ValueError(f"Python class {name} not found")+++def _python_field_annotation(source: str, class_name: str, field_name: str) -> str:+ tree = ast.parse(source)+ for node in tree.body:+ if not isinstance(node, ast.ClassDef) or node.name != class_name:+ continue+ for statement in node.body:+ if (+ isinstance(statement, ast.AnnAssign)+ and isinstance(statement.target, ast.Name)+ and statement.target.id == field_name+ ):+ return ast.unparse(statement.annotation)+ raise ValueError(f"Python field annotation {class_name}.{field_name} not found")+++def _python_has_exact_true_lookup(source: str, key: str) -> bool:+ tree = ast.parse(source)+ for node in ast.walk(tree):+ if not (+ isinstance(node, ast.Compare)+ and len(node.ops) == 1+ and isinstance(node.ops[0], ast.Is)+ and len(node.comparators) == 1+ and isinstance(node.comparators[0], ast.Constant)+ and node.comparators[0].value is True+ and isinstance(node.left, ast.Call)+ and isinstance(node.left.func, ast.Attribute)+ and node.left.func.attr == "get"+ and len(node.left.args) == 1+ and isinstance(node.left.args[0], ast.Constant)+ and node.left.args[0].value == key+ ):+ continue+ return True+ return False+++def _python_field_default(source: str, class_name: str, field_name: str) -> object:+ tree = ast.parse(source)+ for node in tree.body:+ if not isinstance(node, ast.ClassDef) or node.name != class_name:+ continue+ for statement in node.body:+ if (+ isinstance(statement, ast.AnnAssign)+ and isinstance(statement.target, ast.Name)+ and statement.target.id == field_name+ and statement.value is not None+ ):+ return ast.literal_eval(statement.value)+ raise ValueError(f"Python field default {class_name}.{field_name} not found")+++def _check(errors: list[str], label: str, actual: object, expected: object) -> None:+ if actual != expected:+ errors.append(f"{label}: expected {expected!r}, found {actual!r}")+++def _check_source_pattern(errors: list[str], label: str, source: str, pattern: str) -> None:+ _check(+ errors,+ label,+ re.search(pattern, source, flags=re.MULTILINE | re.DOTALL) is not None,+ True,+ )+++_RUST_CFG_TEST_ATTRIBUTE = re.compile(+ r"^[ \t]*#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]",+ flags=re.MULTILINE,+)+_RUST_ITEM_TRIVIA = r"(?:(?:[ \t\r\n]+)|(?://[^\r\n]*(?:\r?\n|$))|(?:/\*.*?\*/))*"+_RUST_ADDITIONAL_ATTRIBUTES = rf"(?:#\[[^\]\r\n]*\]{_RUST_ITEM_TRIVIA})*"+_RUST_TEST_MODULE_ITEM = re.compile(+ rf"^{_RUST_ITEM_TRIVIA}{_RUST_ADDITIONAL_ATTRIBUTES}"+ r"(?:(?:pub(?:\s*\([^)]*\))?)[ \t\r\n]+)?"+ r"mod[ \t\r\n]+(?:r#)?[A-Za-z_][A-Za-z0-9_]*[ \t\r\n]*\{",+ flags=re.DOTALL,+)+_RUST_MODULE_ITEM_PREFIX = re.compile(+ rf"^{_RUST_ITEM_TRIVIA}{_RUST_ADDITIONAL_ATTRIBUTES}"+ r"(?:(?:pub(?:\s*\([^)]*\))?)[ \t\r\n]+)?mod\b",+ flags=re.DOTALL,+)+_RUST_TEST_HELPER_METHOD = re.compile(+ rf"^{_RUST_ITEM_TRIVIA}{_RUST_ADDITIONAL_ATTRIBUTES}"+ r"(?:(?:pub(?:\s*\([^)]*\))?)[ \t\r\n]+)?"+ r"(?:(?:async|const|unsafe)[ \t\r\n]+)*"+ r"fn[ \t\r\n]+(?:r#)?[A-Za-z_][A-Za-z0-9_]*\b[^;{}]*\{",+ flags=re.DOTALL,+)+_RUST_RAW_STRING_START = re.compile(r'(?:b)?r(?P<hashes>#{0,255})"')+_RUST_CHAR_LITERAL = re.compile(r"'(?:\\(?:x[0-9A-Fa-f]{2}|u\{[0-9A-Fa-f_]{1,6}\}|.)|[^\\'\r\n])'")+++def _rust_non_code_end(source: str, index: int) -> int | None:+ if source.startswith("//", index):+ newline = source.find("\n", index + 2)+ return len(source) if newline < 0 else newline + 1+ if source.startswith("/*", index):+ comment_depth = 1+ cursor = index + 2+ while cursor < len(source) and comment_depth:+ if source.startswith("/*", cursor):+ comment_depth += 1+ cursor += 2+ elif source.startswith("*/", cursor):+ comment_depth -= 1+ cursor += 2+ else:+ cursor += 1+ if comment_depth:+ raise ValueError("Rust source has an unterminated block comment")+ return cursor+ raw_string = _RUST_RAW_STRING_START.match(source, index)+ if raw_string:+ terminator = f'"{raw_string.group("hashes")}'+ end = source.find(terminator, raw_string.end())+ if end < 0:+ raise ValueError("Rust source has an unterminated raw string")+ return end + len(terminator)+ if source[index] == '"':+ cursor = index + 1+ while cursor < len(source):+ if source[cursor] == "\\":+ cursor += 2+ elif source[cursor] == '"':+ return cursor + 1+ else:+ cursor += 1+ raise ValueError("Rust source has an unterminated string")+ char_literal = _RUST_CHAR_LITERAL.match(source, index)+ return char_literal.end() if char_literal else None+++def _rust_code_mask(source: str) -> str:+ """Blank comments and literals while preserving source offsets and lines."""+ masked = list(source)+ index = 0+ while index < len(source):+ if (non_code_end := _rust_non_code_end(source, index)) is None:+ index += 1+ continue+ for cursor in range(index, non_code_end):+ if masked[cursor] not in "\r\n":+ masked[cursor] = " "+ index = non_code_end+ return "".join(masked)+++def _rust_nesting_depth(source: str, stop: int) -> int | None:+ depth = 0+ index = 0+ while index < stop:+ if (non_code_end := _rust_non_code_end(source, index)) is not None:+ if non_code_end > stop:+ return None+ index = non_code_end+ continue+ if source[index] == "{":+ depth += 1+ elif source[index] == "}":+ depth -= 1+ if depth < 0:+ raise ValueError("Rust source has an unmatched closing brace")+ index += 1+ return depth+++def _rust_braced_item_end(source: str, opening_brace: int) -> int:+ depth = 0+ index = opening_brace+ while index < len(source):+ if (non_code_end := _rust_non_code_end(source, index)) is not None:+ index = non_code_end+ continue+ if source[index] == "{":+ depth += 1+ elif source[index] == "}":+ depth -= 1+ if depth == 0:+ return index + 1+ index += 1+ raise ValueError("Rust cfg(test) helper has an unterminated body")+++def _blank_rust_ranges(source: str, ranges: list[tuple[int, int]]) -> str:+ result = source+ for start, end in reversed(ranges):+ blank = "".join("\n" if character == "\n" else " " for character in result[start:end])+ result = result[:start] + blank + result[end:]+ return result+++def _rust_without_nested_test_helpers(source: str) -> str:+ helper_ranges: list[tuple[int, int]] = []+ masked_source = _rust_code_mask(source)+ for attribute in _RUST_CFG_TEST_ATTRIBUTE.finditer(masked_source):+ if any(start <= attribute.start() < end for start, end in helper_ranges):+ continue+ nesting_depth = _rust_nesting_depth(source, attribute.start())+ if nesting_depth is None:+ continue+ following = masked_source[attribute.end() :]+ if nesting_depth > 0 and (helper := _RUST_TEST_HELPER_METHOD.match(following)):+ # A few scanned impls expose test-only helpers before their terminal+ # test module. Remove only a lexically balanced nested method before+ # the strict production/test-module split runs.+ opening_brace = attribute.end() + helper.end() - 1+ helper_ranges.append((attribute.start(), _rust_braced_item_end(source, opening_brace)))+ return _blank_rust_ranges(source, helper_ranges)+++def _rust_production(source: str) -> str:+ boundaries: list[int] = []+ masked_source = _rust_code_mask(source)+ for attribute in _RUST_CFG_TEST_ATTRIBUTE.finditer(masked_source):+ nesting_depth = _rust_nesting_depth(source, attribute.start())+ if nesting_depth is None:+ continue+ following = masked_source[attribute.end() :]+ if _RUST_TEST_MODULE_ITEM.match(following):+ if nesting_depth:+ raise ValueError("Rust cfg(test) module boundary is nested and unsupported")+ boundaries.append(attribute.start())+ elif _RUST_MODULE_ITEM_PREFIX.match(following):+ raise ValueError("Rust cfg(test) module boundary is malformed or unsupported")+ else:+ raise ValueError("Rust cfg(test) item is not a recognized inline module boundary")++ if len(boundaries) > 1:+ raise ValueError("Rust cfg(test) module boundary is ambiguous: multiple modules found")+ return source[: boundaries[0]] if boundaries else source+++def _rust_production_source(source: str) -> str:+ return _rust_production(_rust_without_nested_test_helpers(source))+++def validate_protocol(overrides: Mapping[str, str] | None = None) -> list[str]:+ errors: list[str] = []++ ipc_struct_sites = (+ ("IPC sidecar envelope", SIDECAR_IPC_TYPES, "rust"),+ ("IPC Python envelope", PYTHON_IPC_TYPES, "python"),+ )+ for label, path, language in ipc_struct_sites:+ source = _read(path, overrides)+ fields = (+ _python_struct_fields(source, "IpcResponseChunkV1")+ if language == "python"+ else _rust_struct_fields(source, "IpcResponseChunkV1")+ )+ _check(errors, f"{label} fields", fields, IPC_FIELDS)++ sidecar_producer_fields = _rust_struct_fields(_read(SIDECAR_PUBLISHER, overrides), "ResultChunkV1Ref")+ _check(errors, "NATS sidecar producer fields", sidecar_producer_fields, RESULT_FIELDS)++ result_struct_sites = (+ ("NATS sidecar envelope", SIDECAR_WORK_TYPES),+ ("NATS gateway envelope", GATEWAY_PUBLISHER),+ )+ for label, path in result_struct_sites:+ fields = _rust_struct_fields(_read(path, overrides), "ResultChunkV1")+ _check(errors, f"{label} fields", fields, RESULT_FIELDS)++ for label, path, struct_name in (+ ("IPC sidecar envelope", SIDECAR_IPC_TYPES, "IpcResponseChunkV1"),+ ("NATS sidecar envelope", SIDECAR_WORK_TYPES, "ResultChunkV1"),+ ("NATS gateway envelope", GATEWAY_PUBLISHER, "ResultChunkV1"),+ ("NATS sidecar producer", SIDECAR_PUBLISHER, "ResultChunkV1Ref"),+ ):+ source = _read(path, overrides)+ for field_name in ("transfer_digest", "payload"):+ _check(+ errors,+ f'{label} {field_name} serde(with = "serde_bytes")',+ _rust_field_has_serde_option(+ source,+ struct_name,+ field_name,+ 'with="serde_bytes"',+ ),+ True,+ )++ python_ipc_source = _read(PYTHON_IPC_TYPES, overrides)+ for field_name in ("transfer_digest", "payload"):+ _check(+ errors,+ f"IPC Python envelope {field_name} annotation",+ _python_field_annotation(python_ipc_source, "IpcResponseChunkV1", field_name),+ "bytes",+ )++ # `serde_bytes`/`bytes` only pins the MessagePack representation. Pin the+ # actual v1 integrity semantics too: producers hash the complete logical+ # result with SHA-256, consumers hash the reassembled payload and compare+ # it, and every peer enforces SHA-256's exact 32-byte output length.+ python_ipc_producer = _read(PYTHON_IPC_SERVER, overrides)+ _check_source_pattern(+ errors,+ "IPC Python producer computes SHA-256 over the complete response",+ python_ipc_producer,+ r"^[ \t]*digest[ \t]*=[ \t]*hashlib\.sha256\([ \t]*payload[ \t]*\)"+ r"\.digest\([ \t]*\)[ \t]*$",+ )+ _check_source_pattern(+ errors,+ "IPC Python producer publishes the computed SHA-256 digest",+ python_ipc_producer,+ r"\btransfer_digest\s*=\s*digest\b",+ )++ sidecar_ipc_consumer = _rust_production_source(_read(SIDECAR_IPC_CHUNKS, overrides))+ _check_source_pattern(+ errors,+ "IPC sidecar consumer requires an exact 32-byte digest",+ sidecar_ipc_consumer,+ rf"\bchunk\.transfer_digest\.len\(\s*\)\s*!=\s*{TRANSFER_DIGEST_BYTES_V1}\b",+ )+ _check_source_pattern(+ errors,+ "IPC sidecar consumer stores an exact 32-byte digest",+ sidecar_ipc_consumer,+ rf"\blet\s+digest\s*:\s*\[\s*u8\s*;\s*{TRANSFER_DIGEST_BYTES_V1}\s*\]"+ r"\s*=\s*chunk\s*\.transfer_digest\s*\.as_slice\(\s*\)\s*\.try_into\(\s*\)",+ )+ _check_source_pattern(+ errors,+ "IPC sidecar consumer verifies reassembled bytes with SHA-256",+ sidecar_ipc_consumer,+ rf"\blet\s+actual_digest\s*:\s*\[\s*u8\s*;\s*{TRANSFER_DIGEST_BYTES_V1}\s*\]"+ r"\s*=\s*completed\.hasher\.finalize\(\s*\)\.into\(\s*\)\s*;"+ r"\s*if\s+actual_digest\s*!=\s*completed\.digest",+ )+ _check_source_pattern(+ errors,+ "IPC sidecar consumer hashes each payload with SHA-256",+ sidecar_ipc_consumer,+ r"\bhasher\s*:\s*Sha256\b.*\bhasher\s*:\s*Sha256::new\(\s*\)"+ r".*\bstate\.hasher\.update\(\s*&chunk\.payload\s*\)",+ )++ sidecar_nats_producer = _rust_production_source(_read(SIDECAR_PUBLISHER, overrides))+ _check_source_pattern(+ errors,+ "NATS sidecar producer computes SHA-256 over the complete result",+ sidecar_nats_producer,+ rf"\blet\s+transfer_digest\s*:\s*\[\s*u8\s*;\s*{TRANSFER_DIGEST_BYTES_V1}\s*\]"+ r"\s*=\s*Sha256::digest\(\s*&result_bytes\s*\)\.into\(\s*\)",+ )+ _check_source_pattern(+ errors,+ "NATS sidecar producer publishes the computed SHA-256 digest",+ sidecar_nats_producer,+ r"\btransfer_digest\s*:\s*&transfer_digest\b",+ )++ gateway_nats_consumer = _rust_production_source(_read(GATEWAY_PUBLISHER, overrides))+ _check_source_pattern(+ errors,+ "NATS gateway consumer requires an exact 32-byte digest",+ gateway_nats_consumer,+ rf"\blet\s+transfer_digest\s*:\s*\[\s*u8\s*;\s*{TRANSFER_DIGEST_BYTES_V1}\s*\]"+ r"\s*=\s*chunk\s*\.transfer_digest\s*\.as_slice\(\s*\)\s*\.try_into\(\s*\)",+ )+ _check_source_pattern(+ errors,+ "NATS gateway consumer verifies reassembled bytes with SHA-256",+ gateway_nats_consumer,+ r"\blet\s+mut\s+transfer_hasher\s*=\s*Sha256::new\(\s*\)\s*;"+ r".*\btransfer_hasher\.update\(\s*&payload\s*\)"+ r".*\blet\s+actual_digest\s*=\s*transfer_hasher\.finalize\(\s*\)\s*;"+ r"\s*if\s+actual_digest\[\.\.\]\s*!=\s*partial\.transfer_digest",+ )++ for label, path, struct_name, capability in (+ ("IPC sidecar request", SIDECAR_IPC_TYPES, "RequestEnvelope", IPC_CHUNK_CAPABILITY_V1),+ ("NATS gateway work item", GATEWAY_PUBLISHER, "WorkItemRef", RESULT_CHUNK_CAPABILITY_V1),+ ("NATS sidecar work item", SIDECAR_WORK_TYPES, "WorkItem", RESULT_CHUNK_CAPABILITY_V1),+ ):+ fields = _rust_struct_fields(_read(path, overrides), struct_name)+ _check(errors, f"{label} capability field", capability in fields, True)++ _check(+ errors,+ "NATS sidecar work item capability defaults false when absent",+ _rust_field_has_serde_option(+ _read(SIDECAR_WORK_TYPES, overrides),+ "WorkItem",+ RESULT_CHUNK_CAPABILITY_V1,+ "default",+ ),+ True,+ )++ _check(+ errors,+ "IPC Python capability requires exact true",+ _python_has_exact_true_lookup(_read(PYTHON_IPC_SERVER, overrides), IPC_CHUNK_CAPABILITY_V1),+ True,+ )++ sidecar_client_production = _rust_production_source(_read(SIDECAR_IPC_CLIENT, overrides))+ _check(+ errors,+ "IPC sidecar advertises chunk capability",+ len(re.findall(rf"\b{IPC_CHUNK_CAPABILITY_V1}\s*:\s*true\b", sidecar_client_production)),+ 1,+ )+ gateway_production = _rust_production_source(_read(GATEWAY_PUBLISHER, overrides))+ _check(+ errors,+ "NATS gateway advertises chunk capability on every producer",+ len(re.findall(rf"\b{RESULT_CHUNK_CAPABILITY_V1}\s*:\s*true\b", gateway_production)),+ 3,+ )++ for label, path, language in ipc_struct_sites:+ source = _read(path, overrides)+ raw = _python_const(source, "IPC_VERSION") if language == "python" else _rust_const(source, "IPC_VERSION")+ _check(errors, f"{label} IPC_VERSION", _eval_int_expr(raw), IPC_VERSION_V1)++ _check(+ errors,+ "IPC Python kind",+ _python_field_default(_read(PYTHON_IPC_TYPES, overrides), "IpcResponseChunkV1", "kind"),+ IPC_KIND_V1,+ )+ for label, path, name in (+ ("IPC sidecar kind", SIDECAR_IPC_CHUNKS, "IPC_RESPONSE_CHUNK_KIND_V1"),+ ("NATS sidecar kind", SIDECAR_PUBLISHER, "RESULT_CHUNK_KIND"),+ ("NATS gateway kind", GATEWAY_PUBLISHER, "RESULT_CHUNK_KIND"),+ ):+ expected = IPC_KIND_V1 if label.startswith("IPC") else RESULT_KIND_V1+ _check(errors, label, ast.literal_eval(_rust_const(_read(path, overrides), name)), expected)++ for label, path, name, language in (+ ("IPC Python legacy frame", PYTHON_IPC_SERVER, "_MAX_FRAME_BYTES", "python"),+ ("IPC sidecar pool frame", SIDECAR_IPC_CLIENT, "MAX_FRAME_BYTES", "rust"),+ ("IPC sidecar mux frame", SIDECAR_IPC_MUX, "MAX_FRAME_BYTES", "rust"),+ (+ "IPC sidecar reassembly legacy frame",+ SIDECAR_IPC_CHUNKS,+ "LEGACY_IPC_RESPONSE_FRAME_BYTES",+ "rust",+ ),+ ):+ source = _read(path, overrides)+ raw = _python_const(source, name) if language == "python" else _rust_const(source, name)+ _check(errors, label, _eval_int_expr(raw), IPC_LEGACY_FRAME_BYTES_V1)++ for expected, sites in (+ (+ IPC_CHUNK_PAYLOAD_BYTES_V1,+ (+ ("IPC Python chunk payload", PYTHON_IPC_SERVER, "_IPC_RESPONSE_CHUNK_PAYLOAD_BYTES", "python"),+ ("IPC sidecar chunk payload", SIDECAR_IPC_CHUNKS, "IPC_RESPONSE_CHUNK_PAYLOAD_BYTES", "rust"),+ ),+ ),+ (+ IPC_MAX_RESPONSE_BYTES_V1,+ (+ ("IPC Python maximum response", PYTHON_IPC_SERVER, "_MAX_CHUNKED_IPC_RESPONSE_BYTES", "python"),+ ("IPC sidecar maximum response", SIDECAR_IPC_CHUNKS, "MAX_CHUNKED_IPC_RESPONSE_BYTES", "rust"),+ ),+ ),+ (+ IPC_MAX_CHUNKS_V1,+ (+ ("IPC Python maximum chunks", PYTHON_IPC_SERVER, "_MAX_IPC_RESPONSE_CHUNKS", "python"),+ ("IPC sidecar maximum chunks", SIDECAR_IPC_CHUNKS, "MAX_IPC_RESPONSE_CHUNKS", "rust"),+ ),+ ),+ (+ RESULT_MAX_BYTES_V1,+ (+ ("NATS sidecar maximum result", SIDECAR_PUBLISHER, "MAX_CHUNKED_RESULT_BYTES", "rust"),+ ("NATS gateway maximum result", GATEWAY_PUBLISHER, "MAX_RESULT_CHUNK_ITEM_BYTES", "rust"),+ ),+ ),+ (+ RESULT_MAX_CHUNKS_V1,+ (+ ("NATS sidecar maximum chunks", SIDECAR_PUBLISHER, "MAX_RESULT_CHUNKS", "rust"),+ ("NATS gateway maximum chunks", GATEWAY_PUBLISHER, "MAX_RESULT_CHUNKS_PER_ITEM", "rust"),+ ),+ ),+ ):+ for label, path, name, language in sites:+ source = _read(path, overrides)+ raw = _python_const(source, name) if language == "python" else _rust_const(source, name)+ _check(errors, label, _eval_int_expr(raw), expected)++ return errors+++def main() -> int:+ errors = validate_protocol()+ if not errors:+ print("response-chunk protocol v1: OK (IPC 2 peers, NATS 2 peers)")+ return 0+ print("response-chunk protocol v1 DRIFT detected:", file=sys.stderr)+ for error in errors:+ print(f" - {error}", file=sys.stderr)+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tools/init.sh b/tools/init.shnew file mode 100755index 000000000..37374a7fe--- /dev/null+++ b/tools/init.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+cd "$ROOT"++if ! command -v mise >/dev/null 2>&1; then+ echo "mise is required. Install it from https://mise.jdx.dev/getting-started.html and rerun this script."+ exit 1+fi++echo "Trusting mise config..."+mise trust++echo "Installing mise tools and deps..."+mise install+mise run full-sync++if ! command -v cmake >/dev/null 2>&1; then+ echo "Note: cmake not found. The default sync skips the native audio package, so nothing is needed now."+ echo "To build it from source, install cmake and run: mise exec -- uv sync --frozen --project . --all-packages --all-extras"+fi++echo "Init complete."diff --git a/tools/mise_tasks/common/__init__.py b/tools/mise_tasks/common/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tools/mise_tasks/common/colors.py b/tools/mise_tasks/common/colors.pynew file mode 100644index 000000000..4d1c705bc--- /dev/null+++ b/tools/mise_tasks/common/colors.py@@ -0,0 +1,89 @@+"""Terminal color utilities for consistent output formatting."""++from __future__ import annotations++import sys+++class Colors:+ """ANSI color codes for terminal output."""++ RED = "\033[0;31m"+ GREEN = "\033[0;32m"+ YELLOW = "\033[1;33m"+ BLUE = "\033[0;34m"+ MAGENTA = "\033[0;35m"+ CYAN = "\033[0;36m"+ WHITE = "\033[0;37m"+ BOLD = "\033[1m"+ NC = "\033[0m" # No Color / Reset++ @classmethod+ def disable(cls) -> None:+ """Disable colors (for non-TTY output)."""+ cls.RED = ""+ cls.GREEN = ""+ cls.YELLOW = ""+ cls.BLUE = ""+ cls.MAGENTA = ""+ cls.CYAN = ""+ cls.WHITE = ""+ cls.BOLD = ""+ cls.NC = ""+++# Auto-disable colors if not a TTY+if not sys.stdout.isatty():+ Colors.disable()+++def log(msg: str, color: str = "") -> None:+ """Print a message with optional color.++ Args:+ msg: The message to print.+ color: Optional ANSI color code (use Colors.* constants).+ """+ if color:+ print(f"{color}{msg}{Colors.NC}")+ else:+ print(msg)+++def log_step(msg: str) -> None:+ """Print a step header with visual separator.++ Args:+ msg: The step description.+ """+ separator = "=" * 60+ log(f"\n{separator}", Colors.CYAN)+ log(f" {msg}", Colors.CYAN)+ log(separator, Colors.CYAN)+++def log_success(msg: str) -> None:+ """Print a success message in green.++ Args:+ msg: The success message.+ """+ log(f"✓ {msg}", Colors.GREEN)+++def log_warning(msg: str) -> None:+ """Print a warning message in yellow.++ Args:+ msg: The warning message.+ """+ log(f"⚠ {msg}", Colors.YELLOW)+++def log_error(msg: str) -> None:+ """Print an error message in red.++ Args:+ msg: The error message.+ """+ log(f"✗ {msg}", Colors.RED)diff --git a/tools/mise_tasks/common/env.py b/tools/mise_tasks/common/env.pynew file mode 100644index 000000000..996dae8d5--- /dev/null+++ b/tools/mise_tasks/common/env.py@@ -0,0 +1,142 @@+"""Environment variable parsing for mise task arguments.++Mise converts CLI flags to environment variables with the `usage_` prefix.+For example: `--port 8080` becomes `usage_port=8080`.+"""++from __future__ import annotations++import os+from pathlib import Path+++def _get_usage_value(name: str) -> str:+ """Fetch usage_* value, supporting both '-' and '_' flag names."""+ value = os.environ.get(f"usage_{name}", "")+ if not value and "-" in name:+ value = os.environ.get(f"usage_{name.replace('-', '_')}", "")+ return value+++def get_usage_flag(name: str, default: str | None = None) -> str | None:+ """Get a mise usage flag value from environment.++ Args:+ name: The flag name without 'usage_' prefix.+ default: Default value if not set.++ Returns:+ The flag value, or default if not set.++ Example:+ # For `--port 8080`:+ port = get_usage_flag("port", "8080")+ """+ value = _get_usage_value(name)+ return value or default+++def get_usage_bool(name: str, default: bool = False) -> bool:+ """Get a boolean mise usage flag.++ Args:+ name: The flag name without 'usage_' prefix.+ default: Default value if not set.++ Returns:+ True if the flag is "true" (case-insensitive), default otherwise.++ Example:+ # For `--verbose`:+ verbose = get_usage_bool("verbose")+ """+ value = _get_usage_value(name)+ if not value:+ return default+ normalized = value.strip().lower()+ if normalized in {"1", "true", "yes", "y", "on"}:+ return True+ if normalized in {"0", "false", "no", "n", "off"}:+ return False+ return default+++def get_usage_int(name: str, default: int) -> int:+ """Get an integer mise usage flag.++ Args:+ name: The flag name without 'usage_' prefix.+ default: Default value if not set or invalid.++ Returns:+ The integer value, or default if not set or invalid.++ Example:+ # For `--port 8080`:+ port = get_usage_int("port", 8080)+ """+ value = _get_usage_value(name)+ if not value:+ return default+ try:+ return int(value)+ except ValueError:+ return default+++def get_usage_list(name: str, separator: str = ",") -> list[str]:+ """Get a list mise usage flag (comma-separated by default).++ Args:+ name: The flag name without 'usage_' prefix.+ separator: The separator character.++ Returns:+ List of values, empty list if not set.++ Example:+ # For `--models bge-m3,e5-base`:+ models = get_usage_list("models") # ["bge-m3", "e5-base"]+ """+ value = _get_usage_value(name)+ if not value:+ return []+ return [item.strip() for item in value.split(separator) if item.strip()]+++def resolve_project_root() -> Path:+ """Resolve the repo root for the current worktree."""+ cwd = Path.cwd()+ env_root = os.environ.get("MISE_PROJECT_ROOT")+ if env_root:+ env_path = Path(env_root)+ if cwd.is_relative_to(env_path):+ return env_path+ for candidate in [cwd, *cwd.parents]:+ if (candidate / "mise.toml").exists():+ return candidate+ return cwd+++def get_mise_env(project_root: Path | None = None) -> dict[str, str]:+ """Return environment with worktree-safe mise settings."""+ root = project_root or resolve_project_root()+ env = os.environ.copy()+ env.setdefault("MISE_PROJECT_ROOT", str(root))+ trusted = env.get("MISE_TRUSTED_CONFIG_PATHS", "")+ if trusted:+ paths = trusted.split(os.pathsep)+ if str(root) not in paths:+ env["MISE_TRUSTED_CONFIG_PATHS"] = os.pathsep.join([*paths, str(root)])+ else:+ env["MISE_TRUSTED_CONFIG_PATHS"] = str(root)+ # Prevent auto-install side effects during tasks.+ env.setdefault("MISE_AUTO_INSTALL", "0")+ env.setdefault("MISE_TASK_RUN_AUTO_INSTALL", "0")+ env.setdefault("MISE_EXEC_AUTO_INSTALL", "0")+ return env+++def apply_mise_env(project_root: Path | None = None) -> None:+ """Apply worktree-safe mise settings to current process env."""+ os.environ.update(get_mise_env(project_root))diff --git a/tools/mise_tasks/full-sync.bash b/tools/mise_tasks/full-sync.bashnew file mode 100755index 000000000..b68a6be25--- /dev/null+++ b/tools/mise_tasks/full-sync.bash@@ -0,0 +1,14 @@+#!/usr/bin/env bash+#MISE description="Run full local developer environment sync"++set -eu -o pipefail++[ -n "${CI:-}" ] && exit 0 || true++mise run sync+if [ -d packages/sie_ts_sdk ]; then+ (+ cd packages/sie_ts_sdk+ mise exec -- pnpm install --frozen-lockfile+ )+fidiff --git a/tools/mise_tasks/gateway-build.bash b/tools/mise_tasks/gateway-build.bashnew file mode 100755index 000000000..6cd3b359a--- /dev/null+++ b/tools/mise_tasks/gateway-build.bash@@ -0,0 +1,14 @@+#!/usr/bin/env bash+#MISE description="Build Rust gateway"+#USAGE flag "-r --release" help="Build the release binary"++set -euo pipefail++ARGS=(build --locked --manifest-path packages/sie_gateway/Cargo.toml)++if [[ "${usage_release:-}" == "true" ]]; then+ ARGS+=("--release")+fi++echo "## Building sie-gateway"+mise exec -- cargo "${ARGS[@]}"diff --git a/tools/mise_tasks/gateway-check.bash b/tools/mise_tasks/gateway-check.bashnew file mode 100755index 000000000..a45afe134--- /dev/null+++ b/tools/mise_tasks/gateway-check.bash@@ -0,0 +1,14 @@+#!/usr/bin/env bash+#MISE description="Check Rust gateway compiles"+#USAGE flag "-r --release" help="Run cargo check in release mode"++set -euo pipefail++ARGS=(check --locked --all-targets --manifest-path packages/sie_gateway/Cargo.toml)++if [[ "${usage_release:-}" == "true" ]]; then+ ARGS+=("--release")+fi++echo "## Running cargo check for sie-gateway"+mise exec -- cargo "${ARGS[@]}"diff --git a/tools/mise_tasks/gateway-clippy.bash b/tools/mise_tasks/gateway-clippy.bashnew file mode 100755index 000000000..dd97c3b5a--- /dev/null+++ b/tools/mise_tasks/gateway-clippy.bash@@ -0,0 +1,7 @@+#!/usr/bin/env bash+#MISE description="Lint Rust gateway with clippy"++set -euo pipefail++echo "## Running clippy for sie-gateway"+mise exec --no-deps -- cargo clippy --locked --manifest-path packages/sie_gateway/Cargo.toml --all-targets -- -D warningsdiff --git a/tools/mise_tasks/gateway-coverage.bash b/tools/mise_tasks/gateway-coverage.bashnew file mode 100755index 000000000..cd1ec0978--- /dev/null+++ b/tools/mise_tasks/gateway-coverage.bash@@ -0,0 +1,34 @@+#!/usr/bin/env bash+#MISE description="Generate test coverage report for sie-gateway with cargo-llvm-cov"+#USAGE flag "--lcov" help="Emit LCOV report to target/llvm-cov/lcov.info (in addition to the text table)"+#USAGE flag "--html" help="Emit HTML report under target/llvm-cov/html/"+#USAGE arg "[filter]" help="Optional cargo test filter"++set -euo pipefail++# cargo-llvm-cov needs the `llvm-tools-preview` rustup component, which+# mise.toml declares alongside the rust toolchain pin so `mise install`+# provisions it on every dev machine and CI runner.+#+# Default invocation prints a per-file coverage table with a TOTAL row at+# the bottom -- exactly what we want piped into CI logs, no extra flags+# needed. (`--summary-only` is intentionally not exposed: cargo-llvm-cov+# only honors it together with --json/--lcov/--cobertura, and silently+# ignores it otherwise, which is misleading.)++GATEWAY_TARGET="target" # workspace root target directory+ARGS=(llvm-cov --locked --manifest-path packages/sie_gateway/Cargo.toml --all-features)++if [[ "${usage_lcov:-}" == "true" ]]; then+ mkdir -p "${GATEWAY_TARGET}/llvm-cov"+ ARGS+=(--lcov --output-path "${GATEWAY_TARGET}/llvm-cov/lcov.info")+fi+if [[ "${usage_html:-}" == "true" ]]; then+ ARGS+=(--html --output-dir "${GATEWAY_TARGET}/llvm-cov/html")+fi+if [[ -n "${usage_filter:-}" ]]; then+ ARGS+=(-- "${usage_filter}")+fi++echo "## Running cargo-llvm-cov for sie-gateway"+mise exec cargo:cargo-llvm-cov -- cargo-llvm-cov "${ARGS[@]}"diff --git a/tools/mise_tasks/gateway-deny.bash b/tools/mise_tasks/gateway-deny.bashnew file mode 100755index 000000000..2508390dc--- /dev/null+++ b/tools/mise_tasks/gateway-deny.bash@@ -0,0 +1,43 @@+#!/usr/bin/env bash+#MISE description="Audit workspace Rust dependencies with cargo-deny"+#USAGE arg "[checks]" help="Comma-separated subset of checks (advisories,licenses,bans,sources)"++set -euo pipefail++CHECKS="${usage_checks-all}"+if [[ -z "$CHECKS" || "$CHECKS" == ,* || "$CHECKS" == *, || "$CHECKS" == *,,* ]]; then+ echo "ERROR: checks must be a non-empty comma-separated list." >&2+ exit 2+fi+IFS=',' read -r -a CHECK_ARGS <<< "$CHECKS"+SEEN_CHECKS=" "+for check in "${CHECK_ARGS[@]}"; do+ case "$check" in+ advisories|licenses|bans|sources|all) ;;+ *)+ echo "ERROR: unknown cargo-deny check: $check" >&2+ exit 2+ ;;+ esac+ if [[ "$SEEN_CHECKS" == *" $check "* ]]; then+ echo "ERROR: duplicate cargo-deny check: $check" >&2+ exit 2+ fi+ SEEN_CHECKS+="$check "+done+if (( ${#CHECK_ARGS[@]} > 1 )) && [[ "$SEEN_CHECKS" == *" all "* ]]; then+ echo "ERROR: cargo-deny check 'all' cannot be combined with individual checks." >&2+ exit 2+fi++echo "## Running cargo-deny check (${CHECKS}) for the Rust workspace"+# One sweep over the public Rust workspace using the root policy and lockfile.+# --config is set explicitly: cargo-deny would auto-discover deny.toml from+# the manifest dir, but pinning it makes the contract obvious + works+# regardless of cwd if the script is invoked from elsewhere.+mise exec cargo:cargo-deny -- cargo-deny \+ --workspace \+ --all-features \+ --config deny.toml \+ check \+ "${CHECK_ARGS[@]}"diff --git a/tools/mise_tasks/gateway-fmt.bash b/tools/mise_tasks/gateway-fmt.bashnew file mode 100755index 000000000..84a04fc4e--- /dev/null+++ b/tools/mise_tasks/gateway-fmt.bash@@ -0,0 +1,13 @@+#!/usr/bin/env bash+#MISE description="Format Rust gateway"+#USAGE flag "-c --check" help="Check formatting without writing changes (inverse of default)"++set -euo pipefail++if [[ "${usage_check:-}" == "true" ]]; then+ echo "## Checking sie-gateway formatting"+ mise exec --no-deps -- cargo fmt --manifest-path packages/sie_gateway/Cargo.toml --all --check+else+ echo "## Formatting sie-gateway"+ mise exec --no-deps -- cargo fmt --manifest-path packages/sie_gateway/Cargo.toml --all+fidiff --git a/tools/mise_tasks/gateway-test.bash b/tools/mise_tasks/gateway-test.bashnew file mode 100755index 000000000..2b4a7d631--- /dev/null+++ b/tools/mise_tasks/gateway-test.bash@@ -0,0 +1,65 @@+#!/usr/bin/env bash+#MISE description="Run Rust gateway tests"+#USAGE arg "[filter]" help="Optional cargo test filter"++set -euo pipefail++NATS_CONTAINER=""+cleanup() {+ if [[ -n "$NATS_CONTAINER" ]]; then+ docker rm -f "$NATS_CONTAINER" >/dev/null 2>&1 || true+ fi+}+trap cleanup EXIT++# The publisher's >1 MiB wire/cleanup regression must traverse real JetStream,+# not silently skip in the normal gate. Respect an operator-supplied NATS_URL;+# otherwise create one exact, ephemeral, memory-backed NATS 2.12 container.+if [[ -z "${NATS_URL:-}" ]]; then+ command -v docker >/dev/null || {+ echo "gateway-test requires Docker or an explicit NATS_URL for mandatory JetStream coverage" >&2+ exit 1+ }+ NATS_CONTAINER="sie-gateway-test-nats-$$"+ docker run --rm -d \+ --name "$NATS_CONTAINER" \+ -p 127.0.0.1::4222 \+ "nats:2.12-alpine@sha256:b270f5e2428354c0335612694d7dd2fb588148e567a5757fdff325ef9c9332e6" \+ -js >/dev/null+ NATS_PORT="$(docker port "$NATS_CONTAINER" 4222/tcp | sed -n 's/.*://p' | head -1)"+ if [[ -z "$NATS_PORT" ]]; then+ echo "failed to resolve ephemeral NATS port" >&2+ exit 1+ fi+ NATS_READY=false+ # Cold Docker hosts can take several seconds to start the pinned image.+ # Preserve the exact log readiness check with a twelve-second budget.+ for _ in $(seq 1 120); do+ if docker logs "$NATS_CONTAINER" 2>&1 | grep -q "Server is ready"; then+ NATS_READY=true+ break+ fi+ sleep 0.1+ done+ if [[ "$NATS_READY" != true ]]; then+ echo "ephemeral NATS did not become ready" >&2+ exit 1+ fi+ export NATS_URL="nats://127.0.0.1:${NATS_PORT}"+fi+export SIE_RUN_NATS_PUBLISHER_TEST=1++BASE_ARGS=(test --locked --manifest-path packages/sie_gateway/Cargo.toml)+DEFAULT_ARGS=("${BASE_ARGS[@]}")+CLOUD_ARGS=("${BASE_ARGS[@]}" --features cloud-storage)++if [[ -n "${usage_filter:-}" ]]; then+ DEFAULT_ARGS+=("${usage_filter}")+ CLOUD_ARGS+=("${usage_filter}")+fi++echo "## Running sie-gateway tests"+mise exec -- cargo "${DEFAULT_ARGS[@]}"++echo "## Running sie-gateway tests with cloud-storage feature"+mise exec -- cargo "${CLOUD_ARGS[@]}"diff --git a/tools/mise_tasks/helm.py b/tools/mise_tasks/helm.pynew file mode 100755index 000000000..edecfafc1--- /dev/null+++ b/tools/mise_tasks/helm.py@@ -0,0 +1,310 @@+#!/usr/bin/env python3+# fmt: off+#MISE description="Helm chart operations for SIE cluster deployment"+#USAGE arg "[command]" help="Command: lint, template, install, upgrade, uninstall, status"+#USAGE arg "[args]..." help="Additional arguments to pass to helm"+# fmt: on++"""Helm chart operations for SIE cluster deployment.++This task handles:+- Linting the Helm chart+- Rendering templates locally+- Installing/upgrading/uninstalling releases+"""++from __future__ import annotations++import fcntl+import hashlib+import os+import shutil+import stat+import subprocess+import sys+import tempfile+from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path++from common.colors import (+ log,+ log_error,+ log_success,+)+from common.env import apply_mise_env, get_usage_flag, resolve_project_root++apply_mise_env()++# Configuration+CHART_DIR = Path("deploy/helm/sie-cluster")+RELEASE_NAME = os.environ.get("SIE_HELM_RELEASE", "sie")+NAMESPACE = os.environ.get("SIE_HELM_NAMESPACE", "sie")+++@contextmanager+def _helm_config_sync_lock() -> Iterator[None]:+ """Serialize chart file sync because Helm reads those dirs during render."""+ root = resolve_project_root()+ digest = hashlib.sha256(str(root).encode()).hexdigest()[:12]+ lock_path = Path(tempfile.gettempdir()) / f"sie-helm-config-sync-{digest}.lock"+ lock_path.parent.mkdir(parents=True, exist_ok=True)+ flags = os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC+ lock_fd = os.open(lock_path, flags, 0o600)+ try:+ if not stat.S_ISREG(os.fstat(lock_fd).st_mode):+ raise RuntimeError(f"Helm config lock is not a regular file: {lock_path}")+ fcntl.flock(lock_fd, fcntl.LOCK_EX)+ try:+ yield+ finally:+ fcntl.flock(lock_fd, fcntl.LOCK_UN)+ finally:+ os.close(lock_fd)+++def _sync_configs_to_helm() -> None:+ """Copy bundle and model configs into the Helm chart's files/ directory.++ The embeddedConfigs feature uses .Files.Glob to generate ConfigMaps from+ files/bundles/*.yaml and files/models/*.yaml. These files are gitignored+ and must be copied from packages/sie_server/ before any helm operation+ that renders templates (template, install, upgrade, lint).+ """+ root = resolve_project_root()+ src_bundles = root / "packages" / "sie_server" / "bundles"+ src_models = root / "packages" / "sie_server" / "models"+ helm_files = root / "deploy" / "helm" / "sie-cluster" / "files"+ dst_bundles = helm_files / "bundles"+ dst_models = helm_files / "models"++ # Clean and re-copy bundles+ if dst_bundles.exists():+ shutil.rmtree(dst_bundles)+ dst_bundles.mkdir(parents=True, exist_ok=True)+ for f in src_bundles.glob("*.yaml"):+ shutil.copy2(f, dst_bundles / f.name)++ # Clean and re-copy models+ if dst_models.exists():+ shutil.rmtree(dst_models)+ dst_models.mkdir(parents=True, exist_ok=True)+ for f in src_models.glob("*.yaml"):+ shutil.copy2(f, dst_models / f.name)+++def _cleanup_helm_configs() -> None:+ """Remove copied configs from Helm chart files/ directory."""+ root = resolve_project_root()+ helm_files = root / "deploy" / "helm" / "sie-cluster" / "files"+ for d in (helm_files / "bundles", helm_files / "models"):+ if d.exists():+ shutil.rmtree(d)+++def check_helm() -> bool:+ """Check if helm is available."""+ result = subprocess.run(["mise", "exec", "--", "helm", "version"], capture_output=True, check=False) # noqa: S607 — intentional partial path+ if result.returncode != 0:+ log_error("helm not found. Run: mise install")+ return False+ return True+++def run_helm(args: list[str]) -> int:+ """Run helm command."""+ result = subprocess.run(["mise", "exec", "--", "helm", *args], check=False) # noqa: S607, S603 — intentional partial path+ return result.returncode+++def show_help() -> None:+ """Show usage information."""+ log("SIE Helm Chart Operations")+ log("")+ log("Usage: mise run helm -- <command> [options]")+ log("")+ log("Commands:")+ log(" lint Lint the Helm chart")+ log(" template Render templates locally")+ log(" install Install to cluster (dry-run by default)")+ log(" install --apply Actually install to cluster")+ log(" upgrade Upgrade existing installation")+ log(" uninstall Remove from cluster")+ log(" status Show release status")+ log("")+ log("Environment variables:")+ log(f" SIE_HELM_RELEASE Release name (default: {RELEASE_NAME})")+ log(f" SIE_HELM_NAMESPACE Namespace (default: {NAMESPACE})")+ log("")+ log("Examples:")+ log(" mise run helm -- lint")+ log(" mise run helm -- template --set gateway.replicas=3")+ log(" mise run helm -- install --apply --set workers.pools.l4.enabled=true")+++def cmd_lint(extra_args: list[str]) -> int:+ """Lint the Helm chart."""+ log(f"[helm] Linting chart: {CHART_DIR}")+ if run_helm(["lint", str(CHART_DIR), *extra_args]) != 0:+ return 1+ log_success("Lint passed!")+ return 0+++def cmd_template(extra_args: list[str]) -> int:+ """Render templates locally."""+ log(f"[helm] Rendering templates for: {CHART_DIR}")+ return run_helm(+ [+ "template",+ RELEASE_NAME,+ str(CHART_DIR),+ "--namespace",+ NAMESPACE,+ *extra_args,+ ]+ )+++def cmd_install(extra_args: list[str]) -> int:+ """Install to cluster."""+ apply = "--apply" in extra_args+ filtered_args = [a for a in extra_args if a != "--apply"]++ if not apply:+ log("[helm] Dry-run install (add --apply to actually install)")+ return run_helm(+ [+ "install",+ RELEASE_NAME,+ str(CHART_DIR),+ "--namespace",+ NAMESPACE,+ "--create-namespace",+ "--dry-run",+ *filtered_args,+ ]+ )++ log(f"[helm] Installing {RELEASE_NAME} to namespace {NAMESPACE}")+ if (+ run_helm(+ [+ "install",+ RELEASE_NAME,+ str(CHART_DIR),+ "--namespace",+ NAMESPACE,+ "--create-namespace",+ "--wait",+ "--timeout=15m",+ *filtered_args,+ ]+ )+ != 0+ ):+ return 1+ log_success("Installation complete!")+ return 0+++def cmd_upgrade(extra_args: list[str]) -> int:+ """Upgrade existing installation."""+ log(f"[helm] Upgrading {RELEASE_NAME} in namespace {NAMESPACE}")+ if (+ run_helm(+ [+ "upgrade",+ RELEASE_NAME,+ str(CHART_DIR),+ "--namespace",+ NAMESPACE,+ "--wait",+ "--timeout=15m",+ *extra_args,+ ]+ )+ != 0+ ):+ return 1+ log_success("Upgrade complete!")+ return 0+++def cmd_uninstall(extra_args: list[str]) -> int:+ """Uninstall from cluster."""+ log(f"[helm] Uninstalling {RELEASE_NAME} from namespace {NAMESPACE}")+ if (+ run_helm(+ [+ "uninstall",+ RELEASE_NAME,+ "--namespace",+ NAMESPACE,+ *extra_args,+ ]+ )+ != 0+ ):+ return 1+ log_success("Uninstall complete!")+ return 0+++def cmd_status(extra_args: list[str]) -> int:+ """Show release status."""+ log(f"[helm] Status of {RELEASE_NAME}")+ return run_helm(+ [+ "status",+ RELEASE_NAME,+ "--namespace",+ NAMESPACE,+ *extra_args,+ ]+ )+++def main() -> int:+ """Main entry point for the helm task."""+ if not check_helm():+ return 1++ command = get_usage_flag("command")++ # Get extra args from sys.argv (after the command)+ extra_args = sys.argv[2:]++ if not command or command in ("-h", "--help", "help"):+ show_help()+ return 0++ commands = {+ "lint": cmd_lint,+ "template": cmd_template,+ "install": cmd_install,+ "upgrade": cmd_upgrade,+ "uninstall": cmd_uninstall,+ "status": cmd_status,+ }++ handler = commands.get(command)+ if not handler:+ log_error(f"Unknown command: {command}")+ show_help()+ return 1++ # Commands that render templates need bundle/model configs in files/+ needs_configs = command in ("lint", "template", "install", "upgrade")+ if needs_configs:+ with _helm_config_sync_lock():+ _sync_configs_to_helm()+ try:+ return handler(extra_args)+ finally:+ _cleanup_helm_configs()+ return handler(extra_args)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/mise_tasks/install_buildx.py b/tools/mise_tasks/install_buildx.pynew file mode 100644index 000000000..3d6d8980f--- /dev/null+++ b/tools/mise_tasks/install_buildx.py@@ -0,0 +1,206 @@+"""Install docker buildx into ~/.docker/cli-plugins.++Builder creation is an explicit opt-in because it pulls a BuildKit image and+changes Docker's active global builder.+"""++from __future__ import annotations++import argparse+import hashlib+import os+import platform+import shutil+import stat+import subprocess+import sys+import tempfile+from collections.abc import Sequence+from pathlib import Path+from urllib.request import urlopen++BUILDX_VERSION = os.environ.get("BUILDX_VERSION", "0.29.1")+DOWNLOAD_TIMEOUT_SECONDS = 30+MAX_BINARY_BYTES = 128 * 1024 * 1024+MAX_CHECKSUM_BYTES = 1024 * 1024+CHECKSUM_FIELD_COUNT = 2+SHA256_HEX_LENGTH = 64+++def detect_arch() -> str:+ machine = platform.machine().lower()+ if machine in {"x86_64", "amd64"}:+ return "amd64"+ if machine in {"aarch64", "arm64"}:+ return "arm64"+ raise RuntimeError(f"Unsupported architecture for buildx: {machine}")+++def detect_os() -> str:+ system = platform.system().lower()+ if system == "linux":+ return "linux"+ if system == "darwin":+ return "darwin"+ raise RuntimeError(f"Unsupported operating system for buildx: {system}")+++def buildx_asset_name() -> str:+ return f"buildx-v{BUILDX_VERSION}.{detect_os()}-{detect_arch()}"+++def docker_available() -> bool:+ return shutil.which("docker") is not None+++def buildx_installed() -> bool:+ result = subprocess.run(+ ["docker", "buildx", "version"], # noqa: S607 — intentional partial path+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ check=False,+ )+ return result.returncode == 0+++def builder_exists(name: str) -> bool:+ """Check if a buildx builder with the given name exists."""+ result = subprocess.run( # noqa: S603 — intentional subprocess call+ ["docker", "buildx", "inspect", name], # noqa: S607 — intentional partial path+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ check=False,+ )+ return result.returncode == 0+++def ensure_docker_container_builder() -> None:+ """Create a docker-container builder if one doesn't exist.++ The docker-container driver is required for cache export/import,+ which significantly speeds up repeated builds.+ """+ builder_name = "sie-builder"++ if builder_exists(builder_name):+ print(f"Builder '{builder_name}' already exists.")+ # Ensure it's the active builder+ subprocess.run(["docker", "buildx", "use", builder_name], check=False) # noqa: S607, S603 — intentional partial path+ return++ print(f"Creating docker-container builder '{builder_name}'...")+ result = subprocess.run( # noqa: S603 — intentional subprocess call+ [ # noqa: S607 — intentional partial path+ "docker",+ "buildx",+ "create",+ "--name",+ builder_name,+ "--driver",+ "docker-container",+ "--use",+ ],+ check=False,+ )+ if result.returncode != 0:+ print("Warning: Failed to create docker-container builder")+ print("Cache export will not work, but builds will still succeed")+ return++ # Bootstrap the builder (pulls the buildkit image)+ print("Bootstrapping builder...")+ subprocess.run(["docker", "buildx", "inspect", "--bootstrap"], check=False) # noqa: S607 — intentional partial path+ print(f"Builder '{builder_name}' created and activated.")+++def download_bytes(url: str, *, max_bytes: int) -> bytes:+ """Download at most ``max_bytes`` from one trusted release URL."""+ with urlopen( # noqa: S310 — caller supplies a pinned GitHub release URL.+ url,+ timeout=DOWNLOAD_TIMEOUT_SECONDS,+ ) as response:+ data = response.read(max_bytes + 1)+ if len(data) > max_bytes:+ raise RuntimeError(f"Download exceeds the {max_bytes}-byte safety limit: {url}")+ return data+++def checksum_for_asset(checksums: str, asset_name: str) -> str:+ """Return the SHA256 for an exact checksum-manifest filename."""+ for line in checksums.splitlines():+ parts = line.split()+ if len(parts) != CHECKSUM_FIELD_COUNT:+ continue+ digest, filename = parts+ if filename.lstrip("*") == asset_name and len(digest) == SHA256_HEX_LENGTH:+ return digest+ raise RuntimeError(f"Could not find checksum for {asset_name} in checksums.txt")+++def install_verified_binary(plugin_path: Path, data: bytes) -> None:+ """Atomically replace the plugin without following an existing symlink."""+ file_descriptor, temporary_name = tempfile.mkstemp(prefix=".docker-buildx.", dir=plugin_path.parent)+ temporary_path = Path(temporary_name)+ try:+ with os.fdopen(file_descriptor, "wb") as temporary_file:+ temporary_file.write(data)+ temporary_file.flush()+ os.fsync(temporary_file.fileno())+ temporary_path.chmod(temporary_path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)+ temporary_path.replace(plugin_path)+ finally:+ temporary_path.unlink(missing_ok=True)+++def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--configure-builder",+ action="store_true",+ help="create/activate the global sie-builder and bootstrap BuildKit",+ )+ return parser.parse_args(argv)+++def main(argv: Sequence[str] | None = None) -> int:+ args = parse_args(argv)+ if not docker_available():+ print("Docker is not installed; skipping optional buildx setup.")+ return 0++ if buildx_installed():+ print("buildx already installed.")+ if args.configure_builder:+ ensure_docker_container_builder()+ return 0++ plugin_dir = Path.home() / ".docker" / "cli-plugins"+ plugin_dir.mkdir(parents=True, exist_ok=True)+ plugin_path = plugin_dir / "docker-buildx"++ binary_name = buildx_asset_name()+ url = f"https://github.com/docker/buildx/releases/download/v{BUILDX_VERSION}/{binary_name}"+ print(f"Downloading buildx v{BUILDX_VERSION} ({binary_name})...")+ data = download_bytes(url, max_bytes=MAX_BINARY_BYTES)++ # Verify SHA256 checksum (buildx uses a single checksums.txt file)+ checksums_url = f"https://github.com/docker/buildx/releases/download/v{BUILDX_VERSION}/checksums.txt"+ print("Verifying SHA256 checksum...")+ checksums = download_bytes(checksums_url, max_bytes=MAX_CHECKSUM_BYTES).decode()+ expected_hash = checksum_for_asset(checksums, binary_name)+ actual_hash = hashlib.sha256(data).hexdigest()+ if actual_hash != expected_hash:+ raise RuntimeError(+ f"SHA256 checksum mismatch for buildx download.\n Expected: {expected_hash}\n Actual: {actual_hash}"+ )++ install_verified_binary(plugin_path, data)+ print(f"Installed buildx to {plugin_path}")++ if args.configure_builder:+ ensure_docker_container_builder()+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/mise_tasks/jaeger.bash b/tools/mise_tasks/jaeger.bashnew file mode 100755index 000000000..8d67d43dd--- /dev/null+++ b/tools/mise_tasks/jaeger.bash@@ -0,0 +1,67 @@+#!/usr/bin/env bash+#MISE description="Start Jaeger for local tracing"+#USAGE flag "-s --stop" help="Stop Jaeger container" default="false"++set -euo pipefail++CONTAINER_NAME="sie-jaeger"+JAEGER_IMAGE="jaegertracing/all-in-one:1.76.0@sha256:ab6f1a1f0fb49ea08bcd19f6b84f6081d0d44b364b6de148e1798eb5816bacac"++# Helper to run docker commands, using sg docker if needed for group permissions+run_docker() {+ if docker info &>/dev/null; then+ docker "$@"+ elif sg docker -c "docker info" &>/dev/null; then+ local command="docker"+ local arg+ for arg in "$@"; do+ printf -v command '%s %q' "$command" "$arg"+ done+ sg docker -c "$command"+ else+ echo "Error: Cannot connect to Docker daemon."+ echo ""+ echo "Please ensure Docker is installed and you have permissions:"+ echo " 1. Install Docker: sudo apt-get install docker.io"+ echo " 2. Add user to docker group: sudo usermod -aG docker \$USER"+ echo " 3. Apply group: newgrp docker (or log out and back in)"+ exit 1+ fi+}++if [[ "${usage_stop}" == "true" ]]; then+ echo "## Stopping Jaeger..."+ run_docker stop "${CONTAINER_NAME}" 2>/dev/null || true+ run_docker rm "${CONTAINER_NAME}" 2>/dev/null || true+ echo "Jaeger stopped"+ exit 0+fi++# Check if already running+if run_docker ps --format '{{.Names}}' 2>/dev/null | grep -q "^${CONTAINER_NAME}$"; then+ echo "## Jaeger already running"+ echo "UI: http://localhost:16686"+ echo "OTLP gRPC: localhost:4317"+ echo ""+ echo "To stop: mise run jaeger -- --stop"+ exit 0+fi++# Remove stopped container if exists+run_docker rm "${CONTAINER_NAME}" 2>/dev/null || true++echo "## Starting Jaeger..."+run_docker run -d --name "${CONTAINER_NAME}" \+ -p 16686:16686 \+ -p 4317:4317 \+ -p 4318:4318 \+ "$JAEGER_IMAGE"++echo ""+echo "Jaeger started successfully!"+echo "UI: http://localhost:16686"+echo "OTLP gRPC: localhost:4317"+echo "OTLP HTTP: localhost:4318"+echo ""+echo "Start server with tracing: mise run serve -- --tracing"+echo "To stop Jaeger: mise run jaeger -- --stop"diff --git a/tools/mise_tasks/lint.bash b/tools/mise_tasks/lint.bashnew file mode 100755index 000000000..fa8531aac--- /dev/null+++ b/tools/mise_tasks/lint.bash@@ -0,0 +1,26 @@+#!/usr/bin/env bash+#MISE description="Lint Python sources"+#USAGE flag "-f --fix" help="Fix issues instead of just checking"++set -euo pipefail++PUBLIC_PATHS=(+ packages/sie_audio_prep+ packages/sie_config+ packages/sie_mcp+ packages/sie_sdk+ packages/sie_server+ integrations+)++mise exec -- uv lock --check --project .++if [[ "${usage_fix:-}" == "true" ]]; then+ echo "## Running ruff fix and format"+ mise exec -- uv run --frozen --project . ruff check --fix "${PUBLIC_PATHS[@]}"+ mise exec -- uv run --frozen --project . ruff format "${PUBLIC_PATHS[@]}"+else+ echo "## Running ruff check and format check"+ mise exec -- uv run --frozen --project . ruff format --check "${PUBLIC_PATHS[@]}"+ mise exec -- uv run --frozen --project . ruff check "${PUBLIC_PATHS[@]}"+fidiff --git a/tools/mise_tasks/mac-smoke.bash b/tools/mise_tasks/mac-smoke.bashnew file mode 100755index 000000000..6dab99585--- /dev/null+++ b/tools/mise_tasks/mac-smoke.bash@@ -0,0 +1,203 @@+#!/usr/bin/env bash+#MISE description="Mac (Apple-Silicon) end-to-end smoke: default (embed/rerank) + sglang (generation) bundles + OpenAI surfaces"+#+# The Apple-Silicon acceptance gate. The bundles are device-agnostic, so the Mac+# story is the same as Linux: `serve` (default bundle) serves embeddings ++# reranking on torch-MPS, and `mise run serve -- -b sglang` serves generation on MLX. Their+# transformers pins differ, so they are SEPARATE servers — this smoke runs each+# in turn on the same port:+# Phase 0 (fake): weightless surface contract (zero downloads) —+# /docs, embeddings (+determinism), rerank, score,+# generate (blocking + streaming)+# Phase 1 (default): /docs, /v1/embeddings (+throughput), /v1/rerank, /v1/score+# Phase 2 (sglang): /v1/generate (blocking + streaming), /v1/chat/completions+# (streaming + non-streaming, +MLX tok/s)+# Tears each server down before the next and exits non-zero on any failure.+#+# This script owns only the Mac-specific server lifecycle (start/teardown of the+# two local servers, phase sequencing, MLX/MPS timeouts); the probes themselves+# are the shared endpoint-agnostic primitives in+# tools/mise_tasks/smoketest.py. MODEL_LOADING retry semantics live there (SDK+# wait_for_capacity on native surfaces, the raw-HTTP loading-retry helper on the+# OpenAI surfaces).+#+# Model overrides:+# MAC_SMOKE_EMBED_MODEL (default BAAI/bge-m3)+# MAC_SMOKE_RERANK_MODEL (default BAAI/bge-reranker-v2-m3)+# MAC_SMOKE_GEN_MODEL (default Qwen/Qwen3.5-4B)+# MAC_SMOKE_PORT (default 8090)+set -euo pipefail++PORT="${MAC_SMOKE_PORT:-8090}"+EMBED_MODEL="${MAC_SMOKE_EMBED_MODEL:-BAAI/bge-m3}"+RERANK_MODEL="${MAC_SMOKE_RERANK_MODEL:-BAAI/bge-reranker-v2-m3}"+GEN_MODEL="${MAC_SMOKE_GEN_MODEL:-Qwen/Qwen3.5-4B}"+if [[ ! "$PORT" =~ ^[0-9]+$ || ${#PORT} -gt 5 ]]; then+ echo "ERROR: MAC_SMOKE_PORT must be a decimal integer between 1 and 65535." >&2+ exit 2+fi+if (( 10#$PORT < 1 || 10#$PORT > 65535 )); then+ echo "ERROR: MAC_SMOKE_PORT must be a decimal integer between 1 and 65535." >&2+ exit 2+fi+PORT=$((10#$PORT))+BASE="http://127.0.0.1:${PORT}"+# Cold first-run downloads multi-GB weights; give loads plenty of room.+export SIE_MODEL_READY_TIMEOUT_S="${SIE_MODEL_READY_TIMEOUT_S:-1800}"+export SIE_MLX_STARTUP_TIMEOUT_S="${SIE_MLX_STARTUP_TIMEOUT_S:-1800}"+export UV_HTTP_TIMEOUT="${UV_HTTP_TIMEOUT:-300}"++if [[ "$(uname)" != "Darwin" ]]; then+ echo "mac-smoke is Apple-Silicon only (uname=$(uname)); skipping." >&2+ exit 0+fi++SERVER_PID=""+SERVER_LOG_ROOT="${RUNNER_TEMP:-${TMPDIR:-/tmp}}"+SERVER_LOG="$(mktemp "${SERVER_LOG_ROOT%/}/mac-smoke-serve.XXXXXX")"+# Our serve chain's command-line signature (uv/python argv both contain it).+# The port is anchored so e.g. -p 80901 can't match a sweep of 8090.+SERVE_CMD_PAT="sie_server\.cli serve.*-p ${PORT}([^0-9]|\$)"+# sweep_port — reap OUR serve chain if it still holds tcp:$PORT (TERM, then KILL).+# Kills by command-line signature, never by bare port ownership, so an unrelated+# local service on $PORT is never touched; start_server surfaces occupancy loudly.+sweep_port() {+ lsof -ti "tcp:${PORT}" -sTCP:LISTEN >/dev/null 2>&1 || return 0+ # Single TERM: uvicorn force-quits on a second signal, which would cut the+ # graceful model unload short. Escalate only after the wait loop.+ pkill -f "$SERVE_CMD_PAT" 2>/dev/null || true+ for _ in $(seq 1 20); do+ lsof -ti "tcp:${PORT}" -sTCP:LISTEN >/dev/null 2>&1 || return 0+ pgrep -f "$SERVE_CMD_PAT" >/dev/null 2>&1 || return 0+ sleep 0.5+ done+ pkill -KILL -f "$SERVE_CMD_PAT" 2>/dev/null || true+ sleep 0.5+}++stop_server() {+ if [[ -n "$SERVER_PID" ]]; then+ # SIGTERM lets the server unload models (terminates the MLX subprocess).+ kill -TERM "$SERVER_PID" 2>/dev/null || true+ for _ in $(seq 1 20); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.5; done+ kill -KILL "$SERVER_PID" 2>/dev/null || true+ SERVER_PID=""+ fi+ # TERM on the mise wrapper does not reach the python server at the end of the+ # mise->bash->uv chain (the orphan keeps $PORT and answers+ # the next phase's readyz for the WRONG bundle), so reap our chain by cmdline.+ sweep_port+}++cleanup() {+ local status=$?+ stop_server+ # Keep CI failures for the workflow artifact upload. Successful runs and+ # local failures clean up their randomized, symlink-safe temp file.+ if (( status == 0 )) || [[ "${CI:-}" != "true" ]]; then+ rm -f -- "$SERVER_LOG"+ else+ echo "Preserving failed server log at $SERVER_LOG" >&2+ fi+ return "$status"+}+trap cleanup EXIT++# start_server <serve-args...> — launch `mise run serve -- <args> -p $PORT` and wait for /readyz.+start_server() {+ echo "=== Starting serve $* on :${PORT} ==="+ # Anything already listening here would fake readiness for the WRONG bundle+ # (stale server) or break the bind; fail fast and loud. lsof rather than a+ # readyz probe so a non-HTTP listener is caught too.+ if lsof -ti "tcp:${PORT}" -sTCP:LISTEN >/dev/null 2>&1; then+ echo "FAIL: something is already listening on :${PORT} before launch" >&2+ exit 1+ fi+ # A startup DEATH is retried: each mise invocation re-syncs the rustup channel+ # over the network, and a flaked sync kills the whole serve task before python+ # even starts. A live-but-never-ready server is a real hang and fails hard.+ local attempt+ for attempt in 1 2 3; do+ mise run serve -- "$@" -p "$PORT" >"$SERVER_LOG" 2>&1 &+ SERVER_PID=$!+ for i in $(seq 1 120); do+ if ! kill -0 "$SERVER_PID" 2>/dev/null; then+ echo "server exited during startup (attempt ${attempt}/3):" >&2+ tail -40 "$SERVER_LOG" >&2 || true+ SERVER_PID=""+ break+ fi+ if [[ "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/readyz" 2>/dev/null)" == "200" ]]; then+ echo "ready after ~$((i * 2))s"+ return 0+ fi+ sleep 2+ done+ if [[ -n "$SERVER_PID" ]]; then+ echo "FAIL: server not ready after ~240s" >&2+ tail -40 "$SERVER_LOG" >&2 || true+ exit 1+ fi+ # Reap any half-started child that survived the wrapper's death and took the port.+ sweep_port+ sleep 5+ done+ echo "FAIL: server failed to start after 3 attempts" >&2+ exit 1+}++# ===========================================================================+# Phase 0 — fake bundle (weightless surface contract, zero downloads)+#+# Boots the deterministic sie-fake models and asserts+# the surface contract — endpoints up, shapes right, MODEL_LOADING retry+# handling — before any real backend is involved. Failure attribution: a red+# Phase 0 with green real phases means orchestration broke; green fake+# checks with a red real phase means the MPS/MLX backend broke, not the+# orchestration. Chat-completions is intentionally absent here: weightless+# models have no chat-template tokenizer.+# ===========================================================================+start_server -b fake++mise run smoketest -- "$BASE" -t 120 \+ --check-docs \+ --model sie-fake --score-model sie-fake --rerank-model sie-fake \+ --openai-embeddings --embeddings-determinism --skip-extract \+ --generate --generate-model sie-fake --generate-mode native --generate-streaming \+ --generate-tokens 24++stop_server+echo "=== Phase 0 (fake) passed — any later failure is a real-backend issue ==="++# ===========================================================================+# Phase 1 — embeddings + reranking (default bundle, torch-MPS)+# ===========================================================================+start_server -b default++# First touch of /v1/embeddings blocks on the lazy load, so the smoketest's+# request timeout must absorb it.+mise run smoketest -- "$BASE" -t "$SIE_MODEL_READY_TIMEOUT_S" \+ --check-docs \+ --model "$EMBED_MODEL" --score-model "$RERANK_MODEL" --rerank-model "$RERANK_MODEL" \+ --openai-embeddings --embeddings-batch 32 --skip-extract++stop_server++# ===========================================================================+# Phase 2 — generation (sglang bundle, MLX subprocess)+# ===========================================================================+start_server -b sglang++# First touch of the MLX gen model is a non-blocking lazy load (subprocess+# spin-up + weight download): 503 MODEL_LOADING until ready, retried inside+# the smoketest primitives.+mise run smoketest -- "$BASE" -t "$SIE_MLX_STARTUP_TIMEOUT_S" \+ --only-generate --generate-model "$GEN_MODEL" --generate-mode both --generate-streaming \+ --generate-tokens 48++stop_server++echo ""+echo "============================================"+echo " mac-smoke: ALL CHECKS PASSED"+echo "============================================"diff --git a/tools/mise_tasks/mcp-plugin-pack.bash b/tools/mise_tasks/mcp-plugin-pack.bashnew file mode 100755index 000000000..b3f68e267--- /dev/null+++ b/tools/mise_tasks/mcp-plugin-pack.bash@@ -0,0 +1,6 @@+#!/usr/bin/env bash+#MISE description="Build a Superlinked MCP plugin install pack for a hosted or self-hosted cluster"+set -euo pipefail++mise exec -- uv lock --check --project .+mise exec -- uv run --frozen --project . --package sie-mcp python -m sie_mcp.cli plugin-pack "$@"diff --git a/tools/mise_tasks/mcp-serve.bash b/tools/mise_tasks/mcp-serve.bashnew file mode 100755index 000000000..57615887d--- /dev/null+++ b/tools/mise_tasks/mcp-serve.bash@@ -0,0 +1,8 @@+#!/usr/bin/env bash+#MISE description="Start the SIE MCP edge service"+set -euo pipefail++# Scope execution to the explicit public workspace package so its optional MCP+# dependencies and sources are installed in a fresh development environment.+mise exec -- uv lock --check --project .+mise exec -- uv run --frozen --project . --package sie-mcp python -m sie_mcp.cli serve "$@"diff --git a/tools/mise_tasks/mcp-skill-zip.bash b/tools/mise_tasks/mcp-skill-zip.bashnew file mode 100755index 000000000..0fa7fbd61--- /dev/null+++ b/tools/mise_tasks/mcp-skill-zip.bash@@ -0,0 +1,6 @@+#!/usr/bin/env bash+#MISE description="Package the claude.ai Superlinked Agent Skill as an uploadable ZIP"+set -euo pipefail++mise exec -- uv lock --check --project .+mise exec -- uv run --frozen --project . --package sie-mcp python -m sie_mcp.cli skill-zip "$@"diff --git a/tools/mise_tasks/models.py b/tools/mise_tasks/models.pynew file mode 100755index 000000000..430f8510f--- /dev/null+++ b/tools/mise_tasks/models.py@@ -0,0 +1,169 @@+#!/usr/bin/env -S uv run --frozen --project . --package sie-sdk python+# fmt: off+#MISE description="Inspect model catalog and bundle assignments"+#USAGE flag "-a --adapter <adapter>" help="Filter by adapter type (e.g., sglang, sentence_transformer)"+#USAGE flag "-b --bundle <bundle>" help="Filter by bundle name"+#USAGE flag "-m --model <model>" help="Show details for specific model"+#USAGE flag "--missing" help="Show models missing from all bundles"+#USAGE flag "--json" help="Output as JSON"+#USAGE flag "-v --verbose" help="Show full adapter paths"+# fmt: on++"""Model catalog inspection tool.++Shows models, their adapters, bundles, and compatibility information.+"""++from __future__ import annotations++import json+import os+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).parent))++from common.env import apply_mise_env, resolve_project_root++apply_mise_env()+try:+ import yaml+except ImportError:+ print("Error: PyYAML required. Run: mise exec -- uv sync")+ sys.exit(1)+++def get_project_root() -> Path:+ """Get the project root directory."""+ return resolve_project_root()+++def load_bundles(bundles_dir: Path, models_dir: Path) -> dict[str, list[str]]:+ """Load all bundle definitions."""+ from sie_sdk.bundle_utils import match_bundle_models++ bundles: dict[str, list[str]] = {}+ for bundle_file in bundles_dir.glob("*.yaml"):+ with open(bundle_file) as f:+ data = yaml.safe_load(f) or {}+ bundle_name = data.get("name", bundle_file.stem)+ bundles[bundle_name] = match_bundle_models(bundle_file, models_dir)+ return bundles+++def load_model_configs(models_dir: Path) -> dict[str, dict]:+ """Load all model configurations."""+ configs: dict[str, dict] = {}+ for config_file in models_dir.glob("*.yaml"):+ with open(config_file) as f:+ cfg = yaml.safe_load(f)+ if not cfg:+ continue+ # Model configs use sie_id (e.g., "BAAI/bge-m3"), fall back to name or filename+ model_name = cfg.get("sie_id") or cfg.get("name") or config_file.stem.replace("__", "/")+ configs[model_name] = cfg+ return configs+++def get_adapter_short_name(adapter: str) -> str:+ """Extract short adapter name from full path."""+ if ":" in adapter:+ return adapter.rsplit(":", maxsplit=1)[-1]+ return adapter.rsplit(".", maxsplit=1)[-1]+++def get_bundles_for_model(model_name: str, bundles: dict[str, list[str]]) -> list[str]:+ """Find which bundles contain a model."""+ return [bundle_name for bundle_name, models in bundles.items() if model_name in models]+++def main() -> int:+ """Main entry point."""+ # Parse flags from environment+ filter_adapter = os.environ.get("usage_adapter")+ filter_bundle = os.environ.get("usage_bundle")+ filter_model = os.environ.get("usage_model")+ show_missing = os.environ.get("usage_missing", "false").lower() == "true"+ output_json = os.environ.get("usage_json", "false").lower() == "true"+ verbose = os.environ.get("usage_verbose", "false").lower() == "true"++ project_root = get_project_root()+ models_dir = project_root / "packages" / "sie_server" / "models"+ bundles_dir = project_root / "packages" / "sie_server" / "bundles"++ # Load data+ bundles = load_bundles(bundles_dir, models_dir)+ configs = load_model_configs(models_dir)++ # Build model info+ model_info = []+ for name, cfg in sorted(configs.items()):+ # Get adapter from first profile's adapter_path+ profiles = cfg.get("profiles", {})+ first_profile = next(iter(profiles.values()), {}) if profiles else {}+ adapter_full = first_profile.get("adapter_path", "unknown")+ adapter_short = get_adapter_short_name(adapter_full)+ model_bundles = get_bundles_for_model(name, bundles)+ inputs = cfg.get("inputs", [])+ outputs = cfg.get("tasks", [])++ info = {+ "name": name,+ "adapter": adapter_short if not verbose else adapter_full,+ "bundles": model_bundles,+ "inputs": inputs,+ "outputs": outputs,+ }++ # Apply filters+ if filter_adapter and filter_adapter.lower() not in adapter_short.lower():+ continue+ if filter_bundle and filter_bundle not in model_bundles:+ continue+ if filter_model and filter_model.lower() not in name.lower():+ continue+ if show_missing and model_bundles:+ continue++ model_info.append(info)++ # Output+ if output_json:+ print(json.dumps(model_info, indent=2))+ return 0++ # Table output+ if not model_info:+ print("No models found matching filters.")+ return 0++ # Calculate column widths+ name_width = max(len(m["name"]) for m in model_info)+ adapter_width = max(len(m["adapter"]) for m in model_info)++ # Header+ print(f"{'Model':<{name_width}} {'Adapter':<{adapter_width}} Bundles")+ print("-" * (name_width + adapter_width + 30))++ # Rows+ for m in model_info:+ bundles_str = ", ".join(m["bundles"]) if m["bundles"] else "(none)"+ print(f"{m['name']:<{name_width}} {m['adapter']:<{adapter_width}} {bundles_str}")++ print()+ print(f"Total: {len(model_info)} models")++ # Summary by adapter+ if not filter_adapter:+ print("\nBy adapter:")+ adapter_counts: dict[str, int] = {}+ for m in model_info:+ adapter_counts[m["adapter"]] = adapter_counts.get(m["adapter"], 0) + 1+ for adapter, count in sorted(adapter_counts.items(), key=lambda x: -x[1]):+ print(f" {adapter}: {count}")++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/mise_tasks/openapi.bash b/tools/mise_tasks/openapi.bashnew file mode 100755index 000000000..e3fe63dec--- /dev/null+++ b/tools/mise_tasks/openapi.bash@@ -0,0 +1,19 @@+#!/usr/bin/env bash+#MISE description="Regenerate the static OpenAPI spec"+#USAGE flag "--server-only" help="Regenerate only the Python server spec"+#USAGE flag "--gateway-only" help="Regenerate only the Rust gateway spec"+set -euo pipefail++if [[ "${usage_server_only:-}" == "true" && "${usage_gateway_only:-}" == "true" ]]; then+ echo "error: --server-only and --gateway-only are mutually exclusive" >&2+ exit 2+fi++if [[ "${usage_gateway_only:-}" != "true" ]]; then+ mise exec -- uv lock --check --project .+ mise exec -- uv run --frozen --project . --package sie-server \+ sie-server openapi --output packages/sie_server/openapi.json+fi+if [[ "${usage_server_only:-}" != "true" ]]; then+ mise exec -- cargo run --quiet --manifest-path packages/sie_gateway/Cargo.toml -- openapi --output packages/sie_gateway/openapi.json+fidiff --git a/tools/mise_tasks/rust-build.bash b/tools/mise_tasks/rust-build.bashnew file mode 100755index 000000000..d57f8b012--- /dev/null+++ b/tools/mise_tasks/rust-build.bash@@ -0,0 +1,13 @@+#!/usr/bin/env bash+#MISE description="Build every Rust workspace crate"+#USAGE flag "-r --release" help="Build release binaries"++set -euo pipefail++ARGS=(build --locked --workspace)+if [[ "${usage_release:-}" == "true" ]]; then+ ARGS+=(--release)+fi++echo "## Building the Rust workspace"+mise exec -- cargo "${ARGS[@]}"diff --git a/tools/mise_tasks/rust-check.bash b/tools/mise_tasks/rust-check.bashnew file mode 100755index 000000000..758b8120a--- /dev/null+++ b/tools/mise_tasks/rust-check.bash@@ -0,0 +1,13 @@+#!/usr/bin/env bash+#MISE description="Check every Rust workspace crate"+#USAGE flag "-r --release" help="Run cargo check in release mode"++set -euo pipefail++ARGS=(check --locked --workspace --all-targets)+if [[ "${usage_release:-}" == "true" ]]; then+ ARGS+=(--release)+fi++echo "## Checking the Rust workspace"+mise exec -- cargo "${ARGS[@]}"diff --git a/tools/mise_tasks/rust-clippy.bash b/tools/mise_tasks/rust-clippy.bashnew file mode 100755index 000000000..7a9bceba9--- /dev/null+++ b/tools/mise_tasks/rust-clippy.bash@@ -0,0 +1,7 @@+#!/usr/bin/env bash+#MISE description="Lint every Rust workspace crate with clippy"++set -euo pipefail++echo "## Running clippy for the Rust workspace"+mise exec -- cargo clippy --locked --workspace --all-targets --all-features -- -D warningsdiff --git a/tools/mise_tasks/rust-coverage.bash b/tools/mise_tasks/rust-coverage.bashnew file mode 100755index 000000000..c72676ca8--- /dev/null+++ b/tools/mise_tasks/rust-coverage.bash@@ -0,0 +1,22 @@+#!/usr/bin/env bash+#MISE description="Generate test coverage for the Rust workspace"+#USAGE flag "--lcov" help="Emit LCOV output to target/llvm-cov/lcov.info"+#USAGE flag "--html" help="Emit HTML output under target/llvm-cov/html/"+#USAGE arg "[filter]" help="Optional cargo test filter"++set -euo pipefail++ARGS=(llvm-cov --locked --workspace --all-features)+if [[ "${usage_lcov:-}" == "true" ]]; then+ mkdir -p target/llvm-cov+ ARGS+=(--lcov --output-path target/llvm-cov/lcov.info)+fi+if [[ "${usage_html:-}" == "true" ]]; then+ ARGS+=(--html --output-dir target/llvm-cov/html)+fi+if [[ -n "${usage_filter:-}" ]]; then+ ARGS+=(-- "${usage_filter}")+fi++echo "## Running coverage for the Rust workspace"+mise exec cargo:cargo-llvm-cov -- cargo-llvm-cov "${ARGS[@]}"diff --git a/tools/mise_tasks/rust-fmt.bash b/tools/mise_tasks/rust-fmt.bashnew file mode 100755index 000000000..f032a75b6--- /dev/null+++ b/tools/mise_tasks/rust-fmt.bash@@ -0,0 +1,13 @@+#!/usr/bin/env bash+#MISE description="Format every Rust workspace crate"+#USAGE flag "-c --check" help="Check formatting without writing changes"++set -euo pipefail++ARGS=(fmt --all)+if [[ "${usage_check:-}" == "true" ]]; then+ ARGS+=(--check)+fi++echo "## Formatting the Rust workspace"+mise exec -- cargo "${ARGS[@]}"diff --git a/tools/mise_tasks/rust-test.bash b/tools/mise_tasks/rust-test.bashnew file mode 100755index 000000000..5da23b160--- /dev/null+++ b/tools/mise_tasks/rust-test.bash@@ -0,0 +1,13 @@+#!/usr/bin/env bash+#MISE description="Run tests for every Rust workspace crate"+#USAGE arg "[filter]" help="Optional cargo test filter"++set -euo pipefail++ARGS=(test --locked --workspace)+if [[ -n "${usage_filter:-}" ]]; then+ ARGS+=("${usage_filter}")+fi++echo "## Testing the Rust workspace"+mise exec -- cargo "${ARGS[@]}"diff --git a/tools/mise_tasks/serve.bash b/tools/mise_tasks/serve.bashnew file mode 100755index 000000000..ef96ee35b--- /dev/null+++ b/tools/mise_tasks/serve.bash@@ -0,0 +1,113 @@+#!/usr/bin/env bash+#MISE description="Start the SIE server"+set -euo pipefail++# Tag local sie-server heartbeats as development traffic so they+# don't land in the "unknown" bucket on the telemetry dashboard. Devs can+# override by exporting SIE_DEPLOYMENT_ENV before invoking mise run serve.+export SIE_DEPLOYMENT_ENV="${SIE_DEPLOYMENT_ENV:-development}"+mise exec -- uv lock --check --project .++# Inspect a copy of every argument so dependency resolution is independent of+# option order and the original argv reaches the server unchanged.+SERVER_ARGS=("$@")+BUNDLE=""+MODELS=""+for ((i = 0; i < ${#SERVER_ARGS[@]}; i++)); do+ arg="${SERVER_ARGS[$i]}"+ case "$arg" in+ -b|--bundle)+ if ((i + 1 >= ${#SERVER_ARGS[@]})) || [[ "${SERVER_ARGS[$((i + 1))]}" == -* ]]; then+ echo "ERROR: $arg requires a bundle name." >&2+ exit 2+ fi+ BUNDLE="${SERVER_ARGS[$((i + 1))]}"+ i=$((i + 1))+ ;;+ --bundle=*)+ BUNDLE="${arg#*=}"+ if [[ -z "$BUNDLE" ]]; then+ echo "ERROR: --bundle requires a bundle name." >&2+ exit 2+ fi+ ;;+ -m|--models)+ if ((i + 1 >= ${#SERVER_ARGS[@]})) || [[ "${SERVER_ARGS[$((i + 1))]}" == -* ]]; then+ echo "ERROR: $arg requires one or more model names." >&2+ exit 2+ fi+ MODELS="${SERVER_ARGS[$((i + 1))]}"+ i=$((i + 1))+ ;;+ --models=*)+ MODELS="${arg#*=}"+ if [[ -z "$MODELS" ]]; then+ echo "ERROR: --models requires one or more model names." >&2+ exit 2+ fi+ ;;+ esac+done++# Bundle dependency overlays must use the same CUDA wheel channel as the+# checked-in worker image. Gemma declares ``platform: cuda13`` and needs+# SGLang's prerelease flash-attn-4 dependency plus the cu130 torch/kernel+# indexes; without these flags an otherwise-correct CUDA 13 workstation fails+# dependency resolution before the server can start.+UV_BUNDLE_ARGS=()+if [[ -n "$BUNDLE" && -f "packages/sie_server/bundles/$BUNDLE.yaml" ]]; then+ BUNDLE_PLATFORM="$({+ mise exec -- python -c '+import re+import sys+from pathlib import Path++text = Path(sys.argv[1]).read_text(encoding="utf-8")+match = re.search(r"(?m)^platform:\s*([A-Za-z0-9_-]+)\s*$", text)+print(match.group(1) if match else "cuda12")+' "packages/sie_server/bundles/$BUNDLE.yaml"+ })"+ if [[ "$BUNDLE_PLATFORM" == "cuda13" ]]; then+ UV_BUNDLE_ARGS=(+ --index-strategy unsafe-best-match+ --prerelease=allow+ --extra-index-url https://download.pytorch.org/whl/cu130+ --extra-index-url https://docs.sglang.ai/whl/cu130/+ )+ fi+fi++# Device selection is automatic (cli.py picks mps on Apple Silicon). Bundles are+# device-agnostic: `default` serves embeddings/reranking (the flash adapters swap+# to torch-MPS on non-CUDA, flash-attn is linux-marked), and `sglang` serves+# generation (SGLangGenerationAdapter.create_for_device swaps to an MLX subprocess+# on non-CUDA). So on Mac, `mise run serve` gives embed/rerank and+# `mise run serve -- -b sglang` gives generation — same bundles as Linux.+if [[ "$(uname)" == "Darwin" && -z "$BUNDLE" && -z "$MODELS" ]]; then+ echo "Apple Silicon (mps): serving the 'default' bundle (embed/rerank). For generation use -b sglang."+fi++# Resolve dependencies using sie-server resolve-deps+REQS_FILE=$(mktemp)+trap 'rm -f "$REQS_FILE"' EXIT++if [[ -n "$BUNDLE" ]]; then+ mise exec -- uv run --frozen --project . --package sie-server \+ sie-server resolve-deps -b "$BUNDLE" > "$REQS_FILE"+elif [[ -n "$MODELS" ]]; then+ mise exec -- uv run --frozen --project . --package sie-server \+ sie-server resolve-deps -m "$MODELS" > "$REQS_FILE"+else+ mise exec -- uv run --frozen --project . --package sie-server \+ sie-server resolve-deps -b default > "$REQS_FILE"+fi++# Run with extra deps if any were resolved+if [[ -s "$REQS_FILE" ]]; then+ echo "Syncing adapter dependencies..."+ mise exec -- uv run --frozen --project . --package sie-server \+ "${UV_BUNDLE_ARGS[@]}" \+ --with-requirements "$REQS_FILE" python -m sie_server.cli serve "${SERVER_ARGS[@]}"+else+ mise exec -- uv run --frozen --project . --package sie-server python -m sie_server.cli serve "${SERVER_ARGS[@]}"+fidiff --git a/tools/mise_tasks/server-sidecar-build.bash b/tools/mise_tasks/server-sidecar-build.bashnew file mode 100755index 000000000..212698fcd--- /dev/null+++ b/tools/mise_tasks/server-sidecar-build.bash@@ -0,0 +1,14 @@+#!/usr/bin/env bash+#MISE description="Build SIE server sidecar"+#USAGE flag "-r --release" help="Build the release binary"++set -euo pipefail++ARGS=(build --locked --manifest-path packages/sie_server_sidecar/Cargo.toml)++if [[ "${usage_release:-}" == "true" ]]; then+ ARGS+=("--release")+fi++echo "## Building SIE server sidecar"+mise exec -- cargo "${ARGS[@]}"diff --git a/tools/mise_tasks/server-sidecar-check.bash b/tools/mise_tasks/server-sidecar-check.bashnew file mode 100755index 000000000..4ad0e61bd--- /dev/null+++ b/tools/mise_tasks/server-sidecar-check.bash@@ -0,0 +1,14 @@+#!/usr/bin/env bash+#MISE description="Check SIE server sidecar compiles"+#USAGE flag "-r --release" help="Run cargo check in release mode"++set -euo pipefail++ARGS=(check --locked --all-targets --manifest-path packages/sie_server_sidecar/Cargo.toml)++if [[ "${usage_release:-}" == "true" ]]; then+ ARGS+=("--release")+fi++echo "## Running cargo check for SIE server sidecar"+mise exec -- cargo "${ARGS[@]}"diff --git a/tools/mise_tasks/server-sidecar-clippy.bash b/tools/mise_tasks/server-sidecar-clippy.bashnew file mode 100755index 000000000..ccb3f0f1d--- /dev/null+++ b/tools/mise_tasks/server-sidecar-clippy.bash@@ -0,0 +1,7 @@+#!/usr/bin/env bash+#MISE description="Lint SIE server sidecar with clippy"++set -euo pipefail++echo "## Running clippy for SIE server sidecar"+mise exec --no-deps -- cargo clippy --locked --manifest-path packages/sie_server_sidecar/Cargo.toml --all-targets -- -D warningsdiff --git a/tools/mise_tasks/server-sidecar-coverage.bash b/tools/mise_tasks/server-sidecar-coverage.bashnew file mode 100755index 000000000..8942a4f1d--- /dev/null+++ b/tools/mise_tasks/server-sidecar-coverage.bash@@ -0,0 +1,26 @@+#!/usr/bin/env bash+#MISE description="Run SIE server sidecar tests with cargo-llvm-cov coverage (both feature configs, merged report)"+#USAGE flag "--lcov" help="Emit LCOV report to target/llvm-cov/lcov.info (in addition to the text table)"++set -euo pipefail++# Mirrors server-sidecar-test.bash: the suite runs twice (default features and+# --features cloud-storage). --no-report keeps the raw profiles so the final+# `report` merges both configurations into one table / lcov file.++SIDECAR_MANIFEST="packages/sie_server_sidecar/Cargo.toml"+SIDECAR_TARGET="target" # workspace root target directory++echo "## Running SIE server sidecar tests with coverage (default features)"+mise exec -- cargo-llvm-cov llvm-cov --no-report --locked --manifest-path "${SIDECAR_MANIFEST}"++echo "## Running SIE server sidecar tests with coverage (cloud-storage feature)"+mise exec -- cargo-llvm-cov llvm-cov --no-report --locked --manifest-path "${SIDECAR_MANIFEST}" --features cloud-storage++if [[ "${usage_lcov:-}" == "true" ]]; then+ mkdir -p "${SIDECAR_TARGET}/llvm-cov"+ mise exec -- cargo-llvm-cov llvm-cov report --manifest-path "${SIDECAR_MANIFEST}" --lcov --output-path "${SIDECAR_TARGET}/llvm-cov/lcov.info"+fi++echo "## SIE server sidecar coverage report"+mise exec -- cargo-llvm-cov llvm-cov report --manifest-path "${SIDECAR_MANIFEST}"diff --git a/tools/mise_tasks/server-sidecar-fmt.bash b/tools/mise_tasks/server-sidecar-fmt.bashnew file mode 100755index 000000000..be986dcf1--- /dev/null+++ b/tools/mise_tasks/server-sidecar-fmt.bash@@ -0,0 +1,13 @@+#!/usr/bin/env bash+#MISE description="Format SIE server sidecar"+#USAGE flag "-c --check" help="Check formatting without writing changes (inverse of default)"++set -euo pipefail++if [[ "${usage_check:-}" == "true" ]]; then+ echo "## Checking SIE server sidecar formatting"+ mise exec --no-deps -- cargo fmt --manifest-path packages/sie_server_sidecar/Cargo.toml --all --check+else+ echo "## Formatting SIE server sidecar"+ mise exec --no-deps -- cargo fmt --manifest-path packages/sie_server_sidecar/Cargo.toml --all+fidiff --git a/tools/mise_tasks/server-sidecar-test.bash b/tools/mise_tasks/server-sidecar-test.bashnew file mode 100755index 000000000..e80c076ef--- /dev/null+++ b/tools/mise_tasks/server-sidecar-test.bash@@ -0,0 +1,20 @@+#!/usr/bin/env bash+#MISE description="Run SIE server sidecar tests"+#USAGE arg "[filter]" help="Optional cargo test filter"++set -euo pipefail++BASE_ARGS=(test --locked --manifest-path packages/sie_server_sidecar/Cargo.toml)+DEFAULT_ARGS=("${BASE_ARGS[@]}")+CLOUD_ARGS=("${BASE_ARGS[@]}" --features cloud-storage)++if [[ -n "${usage_filter:-}" ]]; then+ DEFAULT_ARGS+=("${usage_filter}")+ CLOUD_ARGS+=("${usage_filter}")+fi++echo "## Running SIE server sidecar tests"+mise exec -- cargo "${DEFAULT_ARGS[@]}"++echo "## Running SIE server sidecar tests with cloud-storage feature"+mise exec -- cargo "${CLOUD_ARGS[@]}"diff --git a/tools/mise_tasks/smoketest.py b/tools/mise_tasks/smoketest.pynew file mode 100755index 000000000..3b4085bf7--- /dev/null+++ b/tools/mise_tasks/smoketest.py@@ -0,0 +1,973 @@+#!/usr/bin/env -S uv run --frozen --project . --package sie-sdk python+# fmt: off+#MISE description="Smoke test a SIE cluster (encode, score, extract, optional generate) and measure cold-start latency"+#USAGE arg "<endpoint>" help="Cluster endpoint URL (e.g. http://localhost:8080 or LB URL)"+#USAGE flag "--gpu <gpu>" help="GPU/machine profile to route to (e.g. g5, l4)" default=""+#USAGE flag "--model <model>" help="Encode model to test" default="sentence-transformers/all-MiniLM-L6-v2"+#USAGE flag "--score-model <model>" help="Score model to test" default="cross-encoder/ms-marco-MiniLM-L-6-v2"+#USAGE flag "--extract-model <model>" help="Extract model to test" default="urchade/gliner_small-v2.1"+#USAGE flag "--generate" help="Also test the generate endpoint" default="false"+#USAGE flag "--only-generate" help="Skip encode/score/extract and only test generate" default="false"+#USAGE flag "--generate-model <model>" help="Generate model to test (required with --generate or --only-generate)" default=""+#USAGE flag "--generate-prompt <prompt>" help="Prompt for the generate test" default="Say hi in one sentence."+#USAGE flag "--generate-tokens <n>" help="Maximum new tokens for the generate test" default="64"+#USAGE flag "--generate-mode <mode>" help="Generate test mode: native, chat, or both" default="native"+#USAGE flag "--gpu-agnostic-chat-probe" help="Send a no-GPU chat-completions provisioning probe before generate" default="false"+#USAGE flag "--only-capacity-probe" help="Only send the gpu-agnostic chat provisioning probe; do not wait for generation" default="false"+#USAGE flag "--check-docs" help="Probe that GET /docs answers 200 before the API tests" default="false"+#USAGE flag "--skip-extract" help="Skip the extract test (for deployments without an extract model)" default="false"+#USAGE flag "--rerank-model <model>" help="Also test the OpenAI/Cohere /v1/rerank surface with this model" default=""+#USAGE flag "--openai-embeddings" help="Also test the OpenAI-compatible /v1/embeddings surface (encode model)" default="false"+#USAGE flag "--embeddings-determinism" help="Assert two identical /v1/embeddings calls return identical vectors" default="false"+#USAGE flag "--embeddings-batch <n>" help="Batch size for an informational /v1/embeddings throughput probe (0 = skip)" default="0"+#USAGE flag "--generate-streaming" help="Also exercise streaming for the selected generate mode(s)" default="false"+#USAGE flag "-n --iterations <n>" help="Number of iterations to run" default="1"+#USAGE flag "-t --timeout <seconds>" help="Request timeout in seconds (increase for cold start)" default="600"+#USAGE flag "-v --verbose" help="Show query details and full result data" default="false"+# fmt: on++"""Smoke test a SIE cluster and measure time to first response.++Runs encode, score, extract, and optional generate requests against a live cluster.+Measures wall-clock time (including node scale-up and model loading)+and reports server-side timing breakdown.++Usage:+ mise run smoketest -- http://localhost:8080+ mise run smoketest -- http://my-cluster.elb.amazonaws.com --gpu g5+ mise run smoketest -- http://my-cluster.elb.amazonaws.com --gpu g5 -n 5+ mise run smoketest -- http://my-cluster.elb.amazonaws.com --gpu g5 -n 3 -v+ mise run smoketest -- http://my-cluster.elb.amazonaws.com --generate --generate-model Qwen/Qwen3.6-27B:rtx-pro-6000+ mise run smoketest -- http://my-cluster.elb.amazonaws.com --only-generate --generate-model Qwen/Qwen3.6-27B:rtx-pro-6000+ mise run smoketest -- http://my-cluster.elb.amazonaws.com --only-generate --gpu rtx6000 --generate-mode both --gpu-agnostic-chat-probe --generate-model Qwen/Qwen3.6-27B+ mise run smoketest -- http://my-cluster.elb.amazonaws.com --only-capacity-probe --generate-model Qwen/Qwen3.6-27B+"""+from __future__ import annotations++import dataclasses+import os+import sys+import time+from collections.abc import Callable+from pathlib import Path+from typing import Any++import httpx++sys.path.insert(0, str(Path(__file__).parent))++from common.colors import log_error+from common.env import apply_mise_env, get_usage_bool, get_usage_flag, get_usage_int++apply_mise_env()++from sie_sdk import SIEClient+from sie_sdk.types import ChatMessage, Item++# ---------------------------------------------------------------------------+# ANSI + formatting+# ---------------------------------------------------------------------------++BOLD, DIM, RESET = "\033[1m", "\033[2m", "\033[0m"+GREEN, RED, YELLOW, CYAN = "\033[32m", "\033[31m", "\033[33m", "\033[36m"+++def _ft(s: float) -> str:+ """Format seconds for display."""+ return f"{s / 60:.1f}min" if s >= 60 else f"{s:.1f}s"+++def _fms(ms: float | None) -> str:+ """Format milliseconds for display."""+ if ms is None:+ return "-"+ return f"{ms / 1000:.1f}s" if ms >= 1000 else f"{ms:.0f}ms"+++# ---------------------------------------------------------------------------+# Test definitions+# ---------------------------------------------------------------------------++ENCODE_QUERY = Item(text="A spaceship is traveling from Earth to Mars.")+SCORE_QUERY = Item(text="Where should we land on Mars?")+SCORE_ITEMS = [+ Item(id="relevant", text="Flat regions near the equator with low elevation are ideal."),+ Item(id="irrelevant", text="Saturn has beautiful rings made of ice."),+]+EXTRACT_QUERY = Item(text="Captain Kirk commands the starship Enterprise for Starfleet.")+EXTRACT_LABELS = ["person", "organization", "ship"]+GENERATE_PROMPT = "Say hi in one sentence."+GENERATE_MODES = {"native", "chat", "both"}+OPENAI_CAPACITY_PROBE_CODES = {+ "provisioning": "PROVISIONING",+ "MODEL_LOADING": "MODEL_LOADING",+ "RESOURCE_EXHAUSTED": "RESOURCE_EXHAUSTED",+}+OPENAI_PROVISIONING_RETRY_AFTER = "60"+EMBEDDINGS_INPUTS = ["hello world", "apple silicon"]+RERANK_QUERY = "apple silicon"+RERANK_DOCUMENTS = ["M-series chips", "the weather today", "Metal GPU inference"]+# Raw-HTTP loading markers: lazy loading is non-blocking on most paths — the+# first touch returns 503 with one of these codes plus Retry-After and expects+# the client to retry. The SDK's wait_for_capacity does this for the+# native surfaces; these markers mirror it for the OpenAI surfaces the SDK+# does not wrap (/v1/embeddings, /v1/rerank).+LOADING_RETRY_MARKERS = ("MODEL_LOADING", "PROVISIONING", "LORA_LOADING")+LOADING_RETRY_MAX_DELAY_S = 5.0+++class TestResult:+ name: str+ wall_s: float+ ok: bool+ lines: list[str] = dataclasses.field(default_factory=list)+ error: str = ""+++def _run(name: str, fn: Callable[[], dict[str, Any]], verbose: bool) -> TestResult:+ """Run a single test, capture wall time, return structured result."""+ t0 = time.monotonic()+ try:+ data = fn()+ wall_s = time.monotonic() - t0+ lines = _format_result(name, data, wall_s, verbose)+ return TestResult(name, wall_s, True, lines)+ except Exception as e: # noqa: BLE001 — smoketest must capture all failures+ wall_s = time.monotonic() - t0+ return TestResult(name, wall_s, False, [f" {RED}FAILED: {e}{RESET}"], str(e))+++def _chat_messages(prompt: str) -> list[ChatMessage]:+ """Build the OpenAI-compatible chat request payload."""+ return [{"role": "user", "content": prompt}]+++def _validated_generate(data: dict[str, Any], prompt: str) -> dict[str, Any]:+ """Assert the blocking-generate contract: non-empty text, clean finish."""+ text = data.get("text")+ if not isinstance(text, str) or not text:+ msg = "generate returned no text"+ raise ValueError(msg)+ finish_reason = data.get("finish_reason")+ if finish_reason not in ("stop", "length"):+ msg = f"unexpected finish_reason: {finish_reason!r}"+ raise ValueError(msg)+ return {**data, "_prompt": prompt}+++def _validated_chat_completion(data: dict[str, Any], prompt: str) -> dict[str, Any]:+ """Assert the chat-completion contract before the lenient formatting."""+ choices = data.get("choices") or []+ if not choices or not isinstance(choices[0], dict) or "message" not in choices[0]:+ msg = "chat completion returned no choices[0].message"+ raise ValueError(msg)+ return _format_chat_completion(data, prompt)+++def _format_chat_completion(data: dict[str, Any], prompt: str) -> dict[str, Any]:+ """Normalize an OpenAI-compatible chat completion for smoke output."""+ choices = data.get("choices") or []+ message = choices[0].get("message", {}) if choices and isinstance(choices[0], dict) else {}+ content = message.get("content") if isinstance(message, dict) else ""+ return {+ "text": content or "",+ "usage": data.get("usage"),+ "_prompt": prompt,+ }+++def _gpu_agnostic_route(gpu: str | None) -> str | None:+ """Drop the machine profile while preserving an explicit pool route."""+ if not gpu or "/" not in gpu:+ return None+ pool_name, _machine_profile = gpu.split("/", 1)+ return f"{pool_name}/" if pool_name else None+++def _openai_probe_headers(api_key: str | None, gpu_route: str | None) -> dict[str, str]:+ """Build raw HTTP headers for the OpenAI-compatible capacity probe."""+ headers = {"content-type": "application/json", "accept": "application/json"}+ if api_key:+ headers["Authorization"] = f"Bearer {api_key}"+ if not gpu_route:+ return headers+ if "/" in gpu_route:+ pool_name, machine_profile = gpu_route.split("/", 1)+ if pool_name:+ headers["X-SIE-Pool"] = pool_name+ if machine_profile:+ headers["X-SIE-MACHINE-PROFILE"] = machine_profile+ else:+ headers["X-SIE-MACHINE-PROFILE"] = gpu_route+ return headers+++def _validate_openai_capacity_probe_response(response: httpx.Response) -> tuple[str, str, str]:+ """Validate the non-2xx OpenAI-compatible not-ready wire contract."""+ if response.status_code == 202:+ msg = "Gateway returned deprecated HTTP 202 provisioning; expected HTTP 503"+ raise ValueError(msg)+ if response.status_code != 503:+ msg = f"Expected HTTP 200 or 503 from chat capacity probe, got {response.status_code}"+ raise ValueError(msg)+ try:+ data = response.json()+ except ValueError as e:+ msg = "Expected JSON OpenAI error envelope from chat capacity probe"+ raise ValueError(msg) from e+ if not isinstance(data, dict) or "detail" in data:+ msg = "Expected OpenAI error envelope without native detail field"+ raise ValueError(msg)+ error = data.get("error")+ if not isinstance(error, dict):+ msg = "Expected OpenAI error object in chat capacity probe response"+ raise ValueError(msg)+ code = error.get("code")+ if not isinstance(code, str) or code not in OPENAI_CAPACITY_PROBE_CODES:+ msg = f"Unexpected OpenAI capacity probe error code: {code!r}"+ raise ValueError(msg)+ expected_header_code = OPENAI_CAPACITY_PROBE_CODES[code]+ header_code = response.headers.get("X-SIE-Error-Code")+ if header_code != expected_header_code:+ msg = f"Expected X-SIE-Error-Code={expected_header_code}, got {header_code!r}"+ raise ValueError(msg)+ retry_after = response.headers.get("Retry-After")+ if not retry_after:+ msg = "Expected Retry-After on OpenAI-compatible not-ready response"+ raise ValueError(msg)+ if code == "provisioning" and retry_after != OPENAI_PROVISIONING_RETRY_AFTER:+ msg = f"Expected provisioning Retry-After={OPENAI_PROVISIONING_RETRY_AFTER}, got {retry_after!r}"+ raise ValueError(msg)+ return code, header_code, retry_after+++def _run_gpu_agnostic_chat_probe(+ endpoint: str,+ api_key: str | None,+ gpu_route: str | None,+ model: str,+ prompt: str,+ generate_tokens: int,+ timeout: float,+ verbose: bool,+) -> TestResult:+ """Exercise the OpenAI-compatible scale-from-zero wire contract without waiting for generation."""+ name = f"generate/chat capacity-probe(any) · {model}"+ t0 = time.monotonic()+ try:+ response = httpx.post(+ f"{endpoint.rstrip('/')}/v1/chat/completions",+ json={+ "model": model,+ "messages": _chat_messages(prompt),+ "max_tokens": generate_tokens,+ "stream": False,+ },+ headers=_openai_probe_headers(api_key, gpu_route),+ timeout=min(timeout, 30.0),+ )+ wall_s = time.monotonic() - t0+ if response.status_code == 200:+ data = response.json()+ lines = _format_result(name, _format_chat_completion(data, prompt), wall_s, verbose)+ lines.insert(1, f" probe: {GREEN}warm capacity returned HTTP 200{RESET}")+ return TestResult(name, wall_s, True, lines)++ code, header_code, retry_after = _validate_openai_capacity_probe_response(response)+ lines = [+ f" wall: {BOLD}{_ft(wall_s)}{RESET}",+ f" probe: {GREEN}not-ready contract observed{RESET} via HTTP 503",+ f" error: code={code}, x-sie-error-code={header_code}",+ f" retry-after: {retry_after}s",+ ]+ if verbose:+ lines.append(f" {DIM}prompt: {prompt!r}{RESET}")+ lines.append(f" {DIM}body: {response.text}{RESET}")+ lines.append(f" {GREEN}OK{RESET}")+ return TestResult(name, wall_s, True, lines)+ except Exception as e: # noqa: BLE001 — smoketest must capture all failures+ wall_s = time.monotonic() - t0+ return TestResult(name, wall_s, False, [f" {RED}FAILED: {e}{RESET}"], str(e))+++def _loading_retry_delay(response: httpx.Response) -> float | None:+ """Return the retry delay for a retryable not-ready 503, else None."""+ if response.status_code != 503 or not any(marker in response.text for marker in LOADING_RETRY_MARKERS):+ return None+ retry_after = response.headers.get("Retry-After")+ try:+ delay = float(retry_after) if retry_after else LOADING_RETRY_MAX_DELAY_S+ except ValueError:+ delay = LOADING_RETRY_MAX_DELAY_S+ return max(0.0, min(delay, LOADING_RETRY_MAX_DELAY_S))+++def _post_json_ready(+ endpoint: str,+ path: str,+ payload: dict[str, Any],+ api_key: str | None,+ timeout_s: float,+) -> httpx.Response:+ """POST to an OpenAI-compatible surface, retrying while the model loads.++ Any response other than a retryable loading 503 (including terminal errors+ like MODEL_LOAD_FAILED) is returned immediately for the caller's assertion;+ a genuinely stuck load fails via the timeout bound.+ """+ headers = {"content-type": "application/json", "accept": "application/json"}+ if api_key:+ headers["Authorization"] = f"Bearer {api_key}"+ deadline = time.monotonic() + timeout_s+ while True:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ msg = f"{path} still not ready after {timeout_s:.0f}s"+ raise TimeoutError(msg)+ response = httpx.post(f"{endpoint.rstrip('/')}{path}", json=payload, headers=headers, timeout=remaining)+ delay = _loading_retry_delay(response)+ if delay is None:+ return response+ time.sleep(min(delay, remaining))+++def _fetch_openai_embeddings(+ endpoint: str, api_key: str | None, model: str, inputs: list[str], timeout_s: float+) -> list[list[float]]:+ """Fetch /v1/embeddings vectors, asserting the response shape."""+ response = _post_json_ready(endpoint, "/v1/embeddings", {"model": model, "input": inputs}, api_key, timeout_s)+ if response.status_code != 200:+ msg = f"HTTP {response.status_code}: {response.text[:300]}"+ raise ValueError(msg)+ rows = response.json().get("data") or []+ if len(rows) != len(inputs) or any(not row.get("embedding") for row in rows):+ msg = f"expected {len(inputs)} non-empty vectors, got {len(rows)}"+ raise ValueError(msg)+ dims = {len(row["embedding"]) for row in rows}+ if len(dims) != 1:+ msg = f"embedding dimensions disagree within one batch: {sorted(dims)}"+ raise ValueError(msg)+ return [row["embedding"] for row in rows]+++def _run_check_docs(endpoint: str, verbose: bool) -> TestResult:+ """Probe that GET /docs answers 200."""++ def fn() -> dict[str, Any]:+ response = httpx.get(f"{endpoint.rstrip('/')}/docs", timeout=30.0)+ if response.status_code != 200:+ msg = f"HTTP {response.status_code}"+ raise ValueError(msg)+ return {}++ return _run("GET /docs", fn, verbose)+++def _run_openai_embeddings(+ endpoint: str,+ api_key: str | None,+ model: str,+ timeout_s: float,+ verbose: bool,+ determinism: bool,+ batch: int,+) -> list[TestResult]:+ """Probe the OpenAI /v1/embeddings surface: shape, optional determinism + throughput."""+ results: list[TestResult] = []+ first: list[list[float]] = []++ def fetch() -> dict[str, Any]:+ first.extend(_fetch_openai_embeddings(endpoint, api_key, model, EMBEDDINGS_INPUTS, timeout_s))+ return {"dense": first[0]}++ shape = _run(f"embeddings(openai) · {model}", fetch, verbose)+ results.append(shape)++ if determinism and shape.ok:++ def refetch() -> dict[str, Any]:+ again = _fetch_openai_embeddings(endpoint, api_key, model, EMBEDDINGS_INPUTS, timeout_s)+ if again != first:+ msg = "identical inputs returned different vectors"+ raise ValueError(msg)+ return {"dense": again[0]}++ results.append(_run(f"embeddings(openai)/determinism · {model}", refetch, verbose))++ if batch > 0 and shape.ok:+ name = f"embeddings(openai)/throughput · {model}"+ inputs = [f"doc {i} about search and apple silicon inference" for i in range(batch)]+ t0 = time.monotonic()+ try:+ _fetch_openai_embeddings(endpoint, api_key, model, inputs, timeout_s)+ wall_s = time.monotonic() - t0+ docs_s = batch / max(wall_s, 1e-9)+ lines = [+ f" wall: {BOLD}{_ft(wall_s)}{RESET}",+ f" throughput: {batch} docs -> {docs_s:.0f} docs/s",+ f" {GREEN}OK{RESET}",+ ]+ results.append(TestResult(name, wall_s, True, lines))+ except Exception as e: # noqa: BLE001 — smoketest must capture all failures+ wall_s = time.monotonic() - t0+ results.append(TestResult(name, wall_s, False, [f" {RED}FAILED: {e}{RESET}"], str(e)))+ return results+++def _run_openai_rerank(endpoint: str, api_key: str | None, model: str, timeout_s: float, verbose: bool) -> TestResult:+ """Probe the OpenAI/Cohere /v1/rerank surface: two ranked results, descending."""+ name = f"rerank(openai) · {model}"+ t0 = time.monotonic()+ try:+ response = _post_json_ready(+ endpoint,+ "/v1/rerank",+ {"model": model, "query": RERANK_QUERY, "documents": RERANK_DOCUMENTS, "top_n": 2},+ api_key,+ timeout_s,+ )+ wall_s = time.monotonic() - t0+ if response.status_code != 200:+ msg = f"HTTP {response.status_code}: {response.text[:300]}"+ raise ValueError(msg)+ ranked = response.json().get("results") or []+ if len(ranked) != 2:+ msg = f"expected 2 reranked results, got {len(ranked)}"+ raise ValueError(msg)+ if ranked[0]["relevance_score"] < ranked[1]["relevance_score"]:+ msg = "rerank results are not sorted by relevance_score"+ raise ValueError(msg)+ scores = ", ".join(f"[{r.get('index')}]={r['relevance_score']:.4f}" for r in ranked)+ lines = [f" wall: {BOLD}{_ft(wall_s)}{RESET}", f" ranking: {scores}"]+ if verbose:+ lines.append(f" {DIM}query: {RERANK_QUERY!r}{RESET}")+ for doc in RERANK_DOCUMENTS:+ lines.append(f" {DIM} doc: {doc!r}{RESET}")+ lines.append(f" {GREEN}OK{RESET}")+ return TestResult(name, wall_s, True, lines)+ except Exception as e: # noqa: BLE001 — smoketest must capture all failures+ wall_s = time.monotonic() - t0+ return TestResult(name, wall_s, False, [f" {RED}FAILED: {e}{RESET}"], str(e))+++def _run_stream_generate(+ client: SIEClient, model: str, prompt: str, generate_tokens: int, timeout: float, verbose: bool+) -> TestResult:+ """Consume the SIE-native /v1/generate SSE stream and assert its contract."""+ name = f"generate/native-stream · {model}"+ t0 = time.monotonic()+ try:+ parts: list[str] = []+ terminal: dict[str, Any] = {}+ for chunk in client.stream_generate(+ model, prompt, max_new_tokens=generate_tokens, wait_for_capacity=True, provision_timeout_s=timeout+ ):+ if chunk.get("text_delta"):+ parts.append(chunk["text_delta"])+ if chunk.get("done"):+ terminal = chunk+ wall_s = time.monotonic() - t0+ text = "".join(parts)+ if not text:+ msg = "stream produced no text"+ raise ValueError(msg)+ if not terminal:+ msg = "stream ended without a terminal done chunk"+ raise ValueError(msg)+ finish_reason = terminal.get("finish_reason")+ if finish_reason not in ("stop", "length"):+ msg = f"unexpected finish_reason: {finish_reason!r}"+ raise ValueError(msg)+ data: dict[str, Any] = {"text": text, "usage": terminal.get("usage"), "_prompt": prompt}+ if terminal.get("ttft_ms") is not None:+ data["ttft_ms"] = terminal["ttft_ms"]+ return TestResult(name, wall_s, True, _format_result(name, data, wall_s, verbose))+ except Exception as e: # noqa: BLE001 — smoketest must capture all failures+ wall_s = time.monotonic() - t0+ return TestResult(name, wall_s, False, [f" {RED}FAILED: {e}{RESET}"], str(e))+++def _run_stream_chat(+ client: SIEClient, model: str, prompt: str, generate_tokens: int, timeout: float, verbose: bool+) -> TestResult:+ """Consume the OpenAI chat SSE stream; report tok/s from the usage event."""+ name = f"generate/chat-stream · {model}"+ t0 = time.monotonic()+ try:+ parts: list[str] = []+ usage: dict[str, Any] | None = None+ for chunk in client.stream_chat_completions(+ model,+ _chat_messages(prompt),+ max_tokens=generate_tokens,+ stream_options={"include_usage": True},+ wait_for_capacity=True,+ provision_timeout_s=timeout,+ ):+ choices = chunk.get("choices") or []+ if choices and isinstance(choices[0], dict):+ delta = choices[0].get("delta") or {}+ # Thinking models (e.g. Qwen3.5) stream `reasoning` deltas+ # before any `content`; a short smoke budget can finish inside+ # the reasoning phase, so both count as streamed output.+ if isinstance(delta, dict):+ for field in ("content", "reasoning"):+ if delta.get(field):+ parts.append(delta[field])+ if isinstance(chunk.get("usage"), dict):+ usage = chunk["usage"]+ wall_s = time.monotonic() - t0+ text = "".join(parts)+ if not text:+ msg = "chat stream produced no content or reasoning deltas"+ raise ValueError(msg)+ lines = _format_result(name, {"text": text, "usage": usage, "_prompt": prompt}, wall_s, verbose)+ completion_tokens = (usage or {}).get("completion_tokens")+ if completion_tokens:+ tok_s = completion_tokens / max(wall_s, 1e-9)+ lines.insert(-1, f" generation: {completion_tokens} tokens -> {tok_s:.1f} tok/s (incl. network)")+ else:+ lines.insert(-1, f" {DIM}generation: (no usage event from child){RESET}")+ return TestResult(name, wall_s, True, lines)+ except Exception as e: # noqa: BLE001 — smoketest must capture all failures+ wall_s = time.monotonic() - t0+ return TestResult(name, wall_s, False, [f" {RED}FAILED: {e}{RESET}"], str(e))+++def _format_result(name: str, data: dict[str, Any], wall_s: float, verbose: bool) -> list[str]:+ """Build display lines from a result dict."""+ lines = [f" wall: {BOLD}{_ft(wall_s)}{RESET}"]++ # Timing (encode only)+ timing = data.get("timing")+ if timing:+ server_ms = timing.get("total_ms")+ if server_ms is not None:+ parts = [+ f"{k.replace('_ms', '')}={_fms(timing[k])}"+ for k in ("queue_ms", "tokenization_ms", "inference_ms")+ if timing.get(k) is not None+ ]+ lines.append(f" server: {_fms(server_ms)} ({', '.join(parts)})")+ overhead = wall_s - server_ms / 1000+ if overhead > 1.0:+ lines.append(f" {YELLOW}overhead: {_ft(overhead)} (scale-up + model load + network){RESET}")++ # Encode output shape+ if "dense" in data:+ parts = [f"dense={len(data['dense'])}d"]+ if "sparse" in data:+ parts.append("sparse")+ if "multivector" in data:+ s = data["multivector"].shape+ parts.append(f"multivector={s[0]}x{s[1]}")+ lines.append(f" output: {', '.join(parts)}")++ # Score results+ scores = data.get("scores")+ if scores:+ ranked = ", ".join(f"{s['item_id']}={s['score']:.4f}" for s in scores)+ ok = scores[0]["item_id"] == "relevant"+ check = f"{GREEN}correct{RESET}" if ok else f"{YELLOW}unexpected{RESET}"+ lines.append(f" ranking: {check} ({ranked})")++ # Extract results+ entities = data.get("entities")+ if entities:+ ents = ", ".join(f"{e['text']}[{e['label']}]" for e in entities)+ lines.append(f" entities: {ents}")++ # Generate results+ text = data.get("text")+ usage = data.get("usage")+ if isinstance(text, str):+ preview = " ".join(text.split())+ if len(preview) > 120:+ preview = f"{preview[:117]}..."+ lines.append(f" text: {preview!r}")+ if isinstance(usage, dict):+ parts = [+ f"{name}={usage[name]}"+ for name in ("prompt_tokens", "completion_tokens", "total_tokens")+ if usage.get(name) is not None+ ]+ if parts:+ lines.append(f" usage: {', '.join(parts)}")+ timing_parts = [f"{name}={_fms(data[name])}" for name in ("ttft_ms", "tpot_ms") if data.get(name) is not None]+ if timing_parts:+ lines.append(f" generation: {', '.join(timing_parts)}")++ # Verbose: query details+ if verbose:+ if "dense" in data:+ lines.append(f" {DIM}query: {ENCODE_QUERY['text']!r}{RESET}")+ elif scores:+ lines.append(f" {DIM}query: {SCORE_QUERY['text']!r}{RESET}")+ for item in SCORE_ITEMS:+ lines.append(f" {DIM} item[{item['id']}]: {item['text']!r}{RESET}")+ elif entities:+ lines.append(f" {DIM}query: {EXTRACT_QUERY['text']!r}{RESET}")+ lines.append(f" {DIM}labels: {EXTRACT_LABELS}{RESET}")+ elif isinstance(text, str):+ prompt = data.get("_prompt", GENERATE_PROMPT)+ lines.append(f" {DIM}prompt: {prompt!r}{RESET}")++ lines.append(f" {GREEN}OK{RESET}")+ return lines+++# ---------------------------------------------------------------------------+# Iteration runner+# ---------------------------------------------------------------------------+++def run_iteration(+ client: SIEClient,+ endpoint: str,+ api_key: str | None,+ gpu_agnostic_route: str | None,+ models: dict[str, str],+ timeout: float,+ verbose: bool,+ include_generate: bool,+ only_generate: bool,+ generate_prompt: str,+ generate_tokens: int,+ generate_mode: str,+ gpu_agnostic_chat_probe: bool,+ only_capacity_probe: bool,+ check_docs: bool,+ skip_extract: bool,+ rerank_model: str,+ openai_embeddings: bool,+ embeddings_determinism: bool,+ embeddings_batch: int,+ generate_streaming: bool,+) -> list[TestResult]:+ """Run one smoke-test pass, optionally including or limiting to generate."""+ results: list[TestResult] = []+ if check_docs:+ results.append(_run_check_docs(endpoint, verbose))+ if not only_generate:+ # The raw-HTTP OpenAI probes run BEFORE their SDK siblings so they make+ # the cold first touch of each model: /v1/embeddings exercises the+ # blocking lazy load and /v1/rerank the 503 MODEL_LOADING retry loop+ # After an SDK probe the model would be warm and the retry+ # path dead in every live run.+ if openai_embeddings or embeddings_determinism or embeddings_batch > 0:+ results.extend(+ _run_openai_embeddings(+ endpoint,+ api_key,+ models["encode"],+ timeout,+ verbose,+ embeddings_determinism,+ embeddings_batch,+ )+ )+ results.append(+ _run(+ f"encode · {models['encode']}",+ lambda: client.encode(+ models["encode"],+ ENCODE_QUERY,+ wait_for_capacity=True,+ provision_timeout_s=timeout,+ ),+ verbose,+ )+ )+ if rerank_model:+ results.append(_run_openai_rerank(endpoint, api_key, rerank_model, timeout, verbose))+ results.append(+ _run(+ f"score · {models['score']}",+ lambda: client.score(+ models["score"],+ SCORE_QUERY,+ SCORE_ITEMS,+ wait_for_capacity=True,+ provision_timeout_s=timeout,+ ),+ verbose,+ )+ )+ if not skip_extract:+ results.append(+ _run(+ f"extract · {models['extract']}",+ lambda: client.extract(+ models["extract"],+ EXTRACT_QUERY,+ labels=EXTRACT_LABELS,+ wait_for_capacity=True,+ provision_timeout_s=timeout,+ ),+ verbose,+ )+ )+ if include_generate:+ if gpu_agnostic_chat_probe:+ results.append(+ _run_gpu_agnostic_chat_probe(+ endpoint,+ api_key,+ gpu_agnostic_route,+ models["generate"],+ generate_prompt,+ generate_tokens,+ timeout,+ verbose,+ )+ )+ if only_capacity_probe:+ return results+ if generate_mode in {"native", "both"}:+ results.append(+ _run(+ f"generate/native · {models['generate']}",+ lambda: _validated_generate(+ client.generate(+ models["generate"],+ generate_prompt,+ max_new_tokens=generate_tokens,+ wait_for_capacity=True,+ provision_timeout_s=timeout,+ ),+ generate_prompt,+ ),+ verbose,+ )+ )+ if generate_streaming:+ results.append(+ _run_stream_generate(client, models["generate"], generate_prompt, generate_tokens, timeout, verbose)+ )+ if generate_mode in {"chat", "both"}:+ results.append(+ _run(+ f"generate/chat · {models['generate']}",+ lambda: _validated_chat_completion(+ client.chat_completions(+ models["generate"],+ _chat_messages(generate_prompt),+ max_tokens=generate_tokens,+ wait_for_capacity=True,+ provision_timeout_s=timeout,+ ),+ generate_prompt,+ ),+ verbose,+ )+ )+ if generate_streaming:+ results.append(+ _run_stream_chat(client, models["generate"], generate_prompt, generate_tokens, timeout, verbose)+ )+ return results+++# ---------------------------------------------------------------------------+# Summary+# ---------------------------------------------------------------------------+++def print_summary(all_iterations: list[list[TestResult]], total_s: float) -> int:+ """Print summary table across all iterations. Returns exit code."""+ n_iter = len(all_iterations)+ passed = failed = 0++ print(f"\n{BOLD}{'=' * 65}{RESET}")+ print(f"{BOLD}Summary ({n_iter} iteration{'s' if n_iter > 1 else ''}){RESET}")+ print(f"{'=' * 65}")++ if n_iter == 1:+ for r in all_iterations[0]:+ s = f"{GREEN}PASS{RESET}" if r.ok else f"{RED}FAIL{RESET}"+ print(f" {s} {r.name:<45} {_ft(r.wall_s):>8}")+ passed += r.ok+ failed += not r.ok+ else:+ # Group by test name across iterations. Ordered union rather than just+ # iteration 0: conditional probes (determinism/throughput run only when+ # the shape probe passed) may be absent from any one iteration.+ test_names = list(dict.fromkeys(r.name for it in all_iterations for r in it))+ for name in test_names:+ times = [r.wall_s for it in all_iterations for r in it if r.name == name and r.ok]+ fails = sum(1 for it in all_iterations for r in it if r.name == name and not r.ok)+ passed += len(times)+ failed += fails+ if times:+ avg = sum(times) / len(times)+ mn, mx = min(times), max(times)+ stats = f"avg={_ft(avg)} min={_ft(mn)} max={_ft(mx)}"+ print(f" {GREEN}PASS{RESET} {name:<40} {stats}")+ if fails:+ print(f" {RED}FAIL{RESET} {name:<40} ({fails} failures)")++ print(f"{'─' * 65}")+ print(f" total: {BOLD}{_ft(total_s)}{RESET}")++ # Cold start info from first iteration+ # The /docs probe is a readiness check, not a model request — skip it so+ # the cold-start metric reflects the first real inference call.+ first = next((r for r in all_iterations[0] if r.name != "GET /docs"), all_iterations[0][0])+ if first.ok:+ print(f" first request: {BOLD}{_ft(first.wall_s)}{RESET} (includes cold start)")++ if n_iter > 1:+ warm = [r.wall_s for it in all_iterations[1:] for r in it if r.ok]+ if warm:+ print(f" warm avg: {_ft(sum(warm) / len(warm))}")++ status = (+ f"{GREEN}{passed} passed{RESET}" if not failed else f"{GREEN}{passed} passed{RESET} {RED}{failed} failed{RESET}"+ )+ print(f"\n {BOLD}{status}{RESET}")+ return 1 if failed else 0+++# ---------------------------------------------------------------------------+# Main+# ---------------------------------------------------------------------------+++def main() -> int:+ endpoint = get_usage_flag("endpoint") or ""+ gpu = get_usage_flag("gpu") or None+ iterations = get_usage_int("iterations", 1)+ timeout = float(get_usage_int("timeout", 600))+ if iterations < 1:+ log_error("--iterations must be >= 1")+ return 1+ if timeout < 1:+ log_error("--timeout must be >= 1")+ return 1+ verbose = get_usage_bool("verbose")+ include_generate = get_usage_bool("generate")+ only_generate = get_usage_bool("only_generate")+ only_capacity_probe = get_usage_bool("only_capacity_probe")+ if only_generate:+ include_generate = True+ if only_capacity_probe:+ include_generate = True+ only_generate = True+ gpu_agnostic_chat_probe = get_usage_bool("gpu_agnostic_chat_probe") or only_capacity_probe+ check_docs = get_usage_bool("check_docs")+ skip_extract = get_usage_bool("skip_extract")+ rerank_model = get_usage_flag("rerank_model") or ""+ embeddings_determinism = get_usage_bool("embeddings_determinism")+ embeddings_batch = get_usage_int("embeddings_batch", 0)+ openai_embeddings = get_usage_bool("openai_embeddings") or embeddings_determinism or embeddings_batch > 0+ generate_streaming = get_usage_bool("generate_streaming")+ generate_model = get_usage_flag("generate_model") or ""+ generate_prompt = get_usage_flag("generate_prompt") or GENERATE_PROMPT+ generate_mode = (get_usage_flag("generate_mode") or "native").strip().lower()+ if generate_mode not in GENERATE_MODES:+ log_error("--generate-mode must be one of: native, chat, both")+ return 1+ generate_tokens_raw = get_usage_flag("generate_tokens") or "64"+ try:+ generate_tokens = int(generate_tokens_raw)+ except ValueError:+ log_error("--generate-tokens must be a positive integer")+ return 1+ if include_generate and generate_tokens < 1:+ log_error("--generate-tokens must be >= 1")+ return 1+ if include_generate and not generate_model:+ log_error("--generate-model is required when using --generate, --only-generate, or --only-capacity-probe")+ return 1+ models = {+ "encode": get_usage_flag("model") or "sentence-transformers/all-MiniLM-L6-v2",+ "score": get_usage_flag("score_model") or "cross-encoder/ms-marco-MiniLM-L-6-v2",+ "extract": get_usage_flag("extract_model") or "urchade/gliner_small-v2.1",+ "generate": generate_model,+ }++ if not endpoint:+ log_error("Endpoint URL is required")+ return 1++ print(f"{BOLD}SIE Cluster Smoke Test{RESET}")+ print(f" endpoint: {endpoint}")+ print(f" gpu: {gpu or '(any)'}")+ print(f" iterations: {iterations}")+ print(f" timeout: {timeout:.0f}s")+ print(f" auth: {'SIE_API_KEY' if os.environ.get('SIE_API_KEY') else '(none)'}")+ if rerank_model:+ print(f" rerank: {rerank_model} (OpenAI /v1/rerank)")+ if openai_embeddings:+ extras = [+ part+ for part, on in (+ ("determinism", embeddings_determinism),+ (f"batch={embeddings_batch}", embeddings_batch > 0),+ )+ if on+ ]+ note = f" (+{', '.join(extras)})" if extras else ""+ print(f" embeddings: {models['encode']} (OpenAI /v1/embeddings){note}")+ if include_generate:+ streaming_note = " +streaming" if generate_streaming else ""+ print(f" generate: {models['generate']} ({generate_tokens} tokens, {generate_mode}{streaming_note})")+ if gpu_agnostic_chat_probe:+ probe_route = _gpu_agnostic_route(gpu)+ pool_note = f", pool={probe_route[:-1]}" if probe_route else ""+ print(f" chat probe: gpu-agnostic{pool_note}, OpenAI HTTP not-ready contract")+ if only_capacity_probe:+ print(" mode: capacity probe only")+ if only_generate:+ print(" mode: generate only")+ if verbose:+ print(" verbose: on")+ print(f" {DIM}(will wait for capacity if cluster is scaling up){RESET}")++ api_key = os.environ.get("SIE_API_KEY")+ gpu_agnostic_route = _gpu_agnostic_route(gpu)+ client = SIEClient(endpoint, timeout_s=timeout, gpu=gpu, api_key=api_key)+ all_iterations: list[list[TestResult]] = []++ t_start = time.monotonic()+ for i in range(iterations):+ if iterations > 1:+ print(f"\n{BOLD}── Iteration {i + 1}/{iterations} ──{RESET}")++ results = run_iteration(+ client,+ endpoint,+ api_key,+ gpu_agnostic_route,+ models,+ timeout,+ verbose,+ include_generate,+ only_generate,+ generate_prompt,+ generate_tokens,+ generate_mode,+ gpu_agnostic_chat_probe,+ only_capacity_probe,+ check_docs,+ skip_extract,+ rerank_model,+ openai_embeddings,+ embeddings_determinism,+ embeddings_batch,+ generate_streaming,+ )+ all_iterations.append(results)++ for r in results:+ print(f"\n{BOLD}{CYAN}[{r.name}]{RESET}")+ for line in r.lines:+ print(line)++ total_s = time.monotonic() - t_start+ return print_summary(all_iterations, total_s)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/mise_tasks/sync.bash b/tools/mise_tasks/sync.bashnew file mode 100755index 000000000..01582ba04--- /dev/null+++ b/tools/mise_tasks/sync.bash@@ -0,0 +1,12 @@+#!/usr/bin/env bash+#MISE description="Sync dependencies on local machine"++set -eu -o pipefail++# sie-audio-prep is a maturin workspace member whose source build needs cmake+# (opusic-sys bundles libopus). Skip installing it by default so machines+# without a native toolchain can sync, test, and typecheck.+# Opt in with: mise exec -- uv sync --frozen --project . --all-packages --all-extras+# (requires cmake).+mise exec -- uv lock --check --project .+mise exec -- uv sync --project . --all-packages --all-extras --frozen --no-install-package sie-audio-prepdiff --git a/tools/mise_tasks/test-integrations.bash b/tools/mise_tasks/test-integrations.bashnew file mode 100755index 000000000..db825b9c9--- /dev/null+++ b/tools/mise_tasks/test-integrations.bash@@ -0,0 +1,42 @@+#!/usr/bin/env bash+#MISE description="Run integration SDK surface tests (Python + TypeScript, no server required)"++set -euo pipefail++rc=0+mise exec -- uv lock --check --project .+mise exec -- uv sync --frozen --project . --all-packages --no-install-package sie-audio-prep++echo "## Python integration SDK tests"+echo ""++# Run each integration separately to avoid conftest.py conflicts+# (each integration has its own conftest with framework-specific fixtures).+# The root pyproject.toml addopts filter out @pytest.mark.integration tests+# so only fast, mocked-SIE-server tests run here.+for dir in integrations/sie_{chroma,crewai,dspy,haystack,lancedb,langchain,llamaindex,qdrant,weaviate}/tests; do+ name=$(echo "$dir" | cut -d/ -f2)+ echo "--- ${name} ---"+ if ! mise exec -- uv run --frozen --project . --no-sync pytest -c pyproject.toml "${dir}" -q; then+ rc=1+ fi+ echo ""+done++echo "## TypeScript integration SDK tests"+echo ""++# Build SDK first (integrations import from dist/)+echo "--- build ---"+if ! mise exec -- pnpm run -r build; then+ echo "FAILED: TypeScript build"+ exit 1+fi+echo ""++echo "--- test ---"+if ! mise exec -- pnpm run -r test; then+ rc=1+fi++exit $rcdiff --git a/tools/mise_tasks/test.bash b/tools/mise_tasks/test.bashnew file mode 100755index 000000000..b7771e3c2--- /dev/null+++ b/tools/mise_tasks/test.bash@@ -0,0 +1,79 @@+#!/usr/bin/env bash+#MISE description="Run tests"+#USAGE flag "-c --coverage" help="Run with coverage report"+#USAGE flag "-i --integration" help="Run integration tests (requires running server)"+#USAGE flag "-d --docker" help="Run Docker integration tests (slow, builds Docker image)"+#USAGE flag "-l --collect-only" help="Only collect and list test names, don't run them"+#USAGE flag "-k --filter <filter>" help="Filter tests by name expression (passed to pytest -k)"+#USAGE flag "-m --model <model>" help="Run model tests for a model ID (e.g. BAAI/bge-m3) or 'all' for all models"+#USAGE arg "<path>" help="Optional path to test" default=""++set -euo pipefail++ARGS=()++if [[ "${usage_collect_only:-}" == "true" ]]; then+ ARGS+=("--collect-only" "-q")+fi++if [[ "${usage_coverage:-}" == "true" ]]; then+ # Bare --cov defers to .coveragerc [run] source_pkgs so never-imported+ # modules stay in the denominator (a --cov=<dir> scan misses src layouts).+ ARGS+=("--cov" "--cov-report=term-missing" "--cov-report=xml")+fi++if [[ -n "${usage_filter:-}" ]]; then+ ARGS+=("-k" "${usage_filter}")+fi++if [[ "${usage_docker:-}" == "true" ]]; then+ ARGS+=("-m" "docker" "-s" "-o" "log_cli=true" "-o" "log_cli_level=INFO")+elif [[ "${usage_integration:-}" == "true" ]]; then+ ARGS+=("-m" "integration" "-s" "-o" "log_cli=true" "-o" "log_cli_level=INFO")+fi++if [[ -n "${usage_path:-}" ]]; then+ ARGS+=("${usage_path}")+fi++if [[ -n "${usage_model:-}" && -n "${usage_path:-}" ]]; then+ echo "ERROR: --model selects the server model suite and cannot be combined with an explicit test path." >&2+ exit 1+fi++echo "## Checking public workspace lock"+mise exec -- uv lock --check --project .++# A root-project sync installs only the root project. Tests import every public+# workspace member, so fresh environments must request them explicitly instead+# of relying on packages left in an existing environment.+echo "## Syncing public workspace"+mise exec -- uv sync --frozen --project . --all-packages --no-install-package sie-audio-prep++if [[ -n "${usage_model:-}" ]]; then+ ARGS+=("packages/sie_server/tests/test_all_models.py" "-m" "model")+ if [[ "${usage_model}" != "all" ]]; then+ sanitized=$(echo "${usage_model}" | sed 's/[^a-zA-Z0-9]/_/g' | tr '[:upper:]' '[:lower:]')+ # Test names may not include the full model ID; trim from right until matches exist.+ all_tests=$(mise exec -- uv run --frozen --project . --no-sync pytest -c pyproject.toml \+ packages/sie_server/tests/test_all_models.py -m model --collect-only -q 2>/dev/null || true)+ while [[ -n "$sanitized" ]]; do+ if echo "$all_tests" | grep -qi "$sanitized"; then+ break+ fi+ sanitized="${sanitized%_*}"+ done+ if [[ -n "$sanitized" ]]; then+ ARGS+=("-k" "${sanitized}")+ else+ echo "WARNING: no tests found matching model '${usage_model}'" >&2+ fi+ fi+fi++echo "## Running public workspace tests"+if [[ ${#ARGS[@]} -eq 0 ]]; then+ mise exec -- uv run --frozen --project . --no-sync pytest -c pyproject.toml+else+ mise exec -- uv run --frozen --project . --no-sync pytest -c pyproject.toml "${ARGS[@]}"+fidiff --git a/tools/mise_tasks/ts.py b/tools/mise_tasks/ts.pynew file mode 100755index 000000000..edc472bc6--- /dev/null+++ b/tools/mise_tasks/ts.py@@ -0,0 +1,366 @@+#!/usr/bin/env python3+# fmt: off+#MISE description="TypeScript SDK tasks"+#USAGE arg "<cmd>" help="Command: build, test, test-integration, test-node22, test-node24, test-browser, test-matrix, lint, lint-fix, typecheck"+# fmt: on++"""TypeScript SDK tasks.++This task handles:+- Building the SDK and integrations+- Running unit tests, integration tests, browser tests+- Multi-Node version testing (Node 22, 24)+- Linting and type checking+"""++from __future__ import annotations++import atexit+import os+import signal+import socket+import subprocess+import sys+import time+import urllib.error+import urllib.request+from pathlib import Path++# Add common to path for imports+sys.path.insert(0, str(Path(__file__).parent))++from common.colors import (+ log,+ log_error,+ log_success,+)+from common.env import apply_mise_env, get_usage_flag++apply_mise_env()++SDK_DIR = Path("packages/sie_ts_sdk")+INTEGRATIONS_DIR = Path("integrations")+HTTP_OK = 200+++def is_port_in_use(port: int) -> bool:+ """Return whether any localhost TCP address cannot bind the port."""+ try:+ addresses = socket.getaddrinfo(+ "localhost",+ port,+ family=socket.AF_UNSPEC,+ type=socket.SOCK_STREAM,+ proto=socket.IPPROTO_TCP,+ )+ except OSError:+ return True++ seen: set[tuple[int, tuple[object, ...]]] = set()+ for family, socktype, proto, _canonname, sockaddr in addresses:+ if family not in {socket.AF_INET, socket.AF_INET6}:+ continue+ key = (family, sockaddr)+ if key in seen:+ continue+ seen.add(key)+ try:+ with socket.socket(family, socktype, proto) as probe:+ probe.bind(sockaddr)+ except OSError:+ return True++ return not seen+++def run_pnpm(args: list[str], cwd: Path | None = None) -> int:+ """Run pnpm command."""+ result = subprocess.run(["mise", "exec", "--", "pnpm", *args], cwd=cwd, check=False) # noqa: S607, S603 — intentional partial path+ return result.returncode+++def cmd_build() -> int:+ """Build TypeScript SDK and integrations."""+ log("## Building TypeScript SDK and integrations")+ return run_pnpm(["run", "-r", "build"])+++def cmd_test() -> int:+ """Run TypeScript SDK and integration unit tests."""+ log("## Running TypeScript SDK and integration unit tests")+ return run_pnpm(["run", "-r", "test"])+++def wait_for_server(url: str, timeout: int = 180) -> bool:+ """Wait for server to be ready.++ Args:+ url: Health check URL.+ timeout: Maximum seconds to wait.++ Returns:+ True if server is ready, False if timeout.+ """+ for _ in range(timeout):+ try:+ with urllib.request.urlopen(url, timeout=1) as response: # noqa: S310 — intentional HTTP health check+ if response.status == HTTP_OK:+ return True+ except (urllib.error.URLError, TimeoutError, OSError):+ pass+ time.sleep(1)+ return False+++def cmd_test_integration() -> int:+ """Run TypeScript integration tests (starts SIE server)."""+ log("## Running TypeScript integration tests (SDK + frameworks)")+ log(" This starts a SIE server and runs tests against it.")+ log("")++ test_port = int(os.environ.get("SIE_TEST_PORT", "8081"))+ server_process: subprocess.Popen | None = None++ def cleanup() -> None:+ """Clean up server process."""+ nonlocal server_process+ log("")+ log("Stopping SIE server...")++ if server_process is not None:+ try:+ # Send SIGTERM to process group+ pgid = os.getpgid(server_process.pid)+ os.killpg(pgid, signal.SIGTERM)+ except (ProcessLookupError, OSError):+ log(" Server process group already stopped.")+ log(" Server cleanup complete.")+ return++ try:+ server_process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ pass++ try:+ os.killpg(pgid, signal.SIGKILL)+ except (ProcessLookupError, OSError):+ pass+ else:+ try:+ server_process.wait(timeout=5)+ except (ProcessLookupError, subprocess.TimeoutExpired):+ pass++ log(" Server cleanup complete.")++ atexit.register(cleanup)++ # Start server if not already running+ health_url = f"http://localhost:{test_port}/readyz"+ if not is_port_in_use(test_port):+ log(f"Starting SIE server on port {test_port}...")++ # Start server in new process group so we can kill it cleanly+ server_process = subprocess.Popen( # noqa: S603 — intentional subprocess call+ ["mise", "run", "serve", "--", "-p", str(test_port)], # noqa: S607 — intentional partial path+ start_new_session=True,+ )++ log(" Waiting for server to start...")++ if not wait_for_server(health_url, timeout=180):+ # Check if process died+ if server_process.poll() is not None:+ log_error("Server process died")+ return 1+ log_error("Server failed to start within 180s")+ return 1++ log_success(f"Server ready at http://localhost:{test_port}")+ else:+ if not wait_for_server(health_url, timeout=10):+ log_error(f"Port {test_port} is in use, but {health_url} is not ready")+ return 1+ log(f"Using existing ready server on port {test_port}")++ log("")+ os.environ["SIE_SERVER_URL"] = f"http://localhost:{test_port}"++ # Run SDK integration tests+ log("### SDK integration tests")+ if run_pnpm(["run", "test:integration"], cwd=SDK_DIR) != 0:+ return 1++ # Run framework integration tests+ for integration in sorted(INTEGRATIONS_DIR.glob("sie_ts_*")):+ config_file = integration / "vitest.integration.config.ts"+ if integration.is_dir() and config_file.exists():+ test_files = list((integration / "tests" / "integration").glob("**/*.integration.test.ts"))+ if not test_files:+ log("")+ log(f"### {integration.name} integration tests")+ log(" Skipping: no integration test files")+ continue++ log("")+ log(f"### {integration.name} integration tests")+ if run_pnpm(["run", "test:integration"], cwd=integration) != 0:+ return 1++ log("")+ log_success("All integration tests passed!")+ return 0+++def cmd_test_node22() -> int:+ """Run TypeScript SDK unit tests with Node.js 22."""+ log("## Running TypeScript SDK unit tests with Node.js 22")+ result = subprocess.run(+ ["mise", "exec", "node@22", "--", "pnpm", "run", "test"], # noqa: S607 — intentional partial path+ cwd=SDK_DIR,+ check=False,+ )+ if result.returncode == 0:+ log_success("Node.js 22 tests passed!")+ return result.returncode+++def cmd_test_node24() -> int:+ """Run TypeScript SDK unit tests with Node.js 24."""+ log("## Running TypeScript SDK unit tests with Node.js 24")+ result = subprocess.run(+ ["mise", "exec", "node@24", "--", "pnpm", "run", "test"], # noqa: S607 — intentional partial path+ cwd=SDK_DIR,+ check=False,+ )+ if result.returncode == 0:+ log_success("Node.js 24 tests passed!")+ return result.returncode+++def cmd_test_browser() -> int:+ """Run TypeScript SDK browser compatibility tests."""+ log("## Running TypeScript SDK browser compatibility tests")+ log(" Using Playwright to test in real browser environment")+ log("")++ # Build SDK first (browser tests load from dist/)+ log("### Building SDK...")+ if run_pnpm(["run", "build"], cwd=SDK_DIR) != 0:+ return 1++ # Check if Playwright is installed+ result = subprocess.run(+ ["mise", "exec", "--", "pnpm", "exec", "playwright", "--version"], # noqa: S607 — intentional partial path+ cwd=SDK_DIR,+ capture_output=True,+ check=False,+ )+ if result.returncode != 0:+ log("### Installing Playwright...")+ if run_pnpm(["exec", "playwright", "install", "chromium"], cwd=SDK_DIR) != 0:+ return 1++ log("")+ log("### Running browser tests...")+ if run_pnpm(["run", "test:browser"], cwd=SDK_DIR) != 0:+ return 1++ log("")+ log_success("Browser tests passed!")+ return 0+++def cmd_test_matrix() -> int:+ """Run full test matrix (Node 22, Node 24, Browser)."""+ log("## Running full test matrix (Node 22, Node 24, Browser)")+ log("")++ log("=== Node.js 22 ===")+ if cmd_test_node22() != 0:+ return 1+ log("")++ log("=== Node.js 24 ===")+ if cmd_test_node24() != 0:+ return 1+ log("")++ log("=== Browser (Chromium) ===")+ if cmd_test_browser() != 0:+ return 1+ log("")++ log_success("All environment tests passed!")+ return 0+++def cmd_lint() -> int:+ """Lint TypeScript SDK and integrations."""+ log("## Linting TypeScript SDK and integrations")+ return run_pnpm(["run", "-r", "lint"])+++def cmd_lint_fix() -> int:+ """Fix TypeScript SDK and integration lint issues."""+ log("## Fixing TypeScript SDK and integration lint issues")+ return run_pnpm(["run", "-r", "lint-fix"])+++def cmd_typecheck() -> int:+ """Type check TypeScript SDK and integrations."""+ log("## Type checking TypeScript SDK and integrations")+ return run_pnpm(["run", "-r", "typecheck"])+++def show_usage() -> None:+ """Show usage information."""+ log("Usage: mise run ts -- <command>")+ log("")+ log("Commands:")+ log(" build Build SDK and integrations (ESM + CJS + types)")+ log(" test Run unit tests for SDK and integrations (mocked, fast)")+ log(" test-integration Run integration tests (starts real SIE server)")+ log(" test-node22 Run SDK unit tests with Node.js 22")+ log(" test-node24 Run SDK unit tests with Node.js 24")+ log(" test-browser Run SDK browser compatibility tests (Playwright)")+ log(" test-matrix Run full test matrix (Node 22 + Node 24 + Browser)")+ log(" lint Check linting for SDK and integrations")+ log(" lint-fix Fix lint issues")+ log(" typecheck Run TypeScript type checker")+++COMMANDS = {+ "build": cmd_build,+ "test": cmd_test,+ "test-integration": cmd_test_integration,+ "test-node22": cmd_test_node22,+ "test-node24": cmd_test_node24,+ "test-browser": cmd_test_browser,+ "test-matrix": cmd_test_matrix,+ "lint": cmd_lint,+ "lint-fix": cmd_lint_fix,+ "typecheck": cmd_typecheck,+}+++def main() -> int:+ """Main entry point for the ts task."""+ cmd = get_usage_flag("cmd")++ if not cmd:+ show_usage()+ return 1++ handler = COMMANDS.get(cmd)+ if not handler:+ log_error(f"Unknown command: {cmd}")+ show_usage()+ return 1++ return handler()+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/mise_tasks/typecheck.bash b/tools/mise_tasks/typecheck.bashnew file mode 100755index 000000000..ec09e0fa4--- /dev/null+++ b/tools/mise_tasks/typecheck.bash@@ -0,0 +1,27 @@+#!/usr/bin/env bash+#MISE description="Type check Python sources with ty (Astral)"+#USAGE arg "[path]" help="Path to check (default: packages/)"++set -euo pipefail++if [[ -n "${usage_path:-}" ]]; then+ PATHS_TO_CHECK=("${usage_path}")+else+ PATHS_TO_CHECK=(+ packages/sie_config+ packages/sie_mcp+ packages/sie_sdk+ packages/sie_server+ )+fi++echo "## Running ty type checker on ${PATHS_TO_CHECK[*]}"++# Install every member of the explicitly public workspace for import checking.+# sie-audio-prep is skipped: installing it compiles the native crate (needs+# cmake) and ty cannot see into the binary module anyway.+# `uv run` has no --no-install-package, so sync explicitly first (--inexact+# preserves uv run's keep-extraneous behavior), then run without re-syncing.+mise exec --no-deps [email protected] [email protected] -- uv lock --check --project .+mise exec --no-deps [email protected] [email protected] -- uv sync --project . --all-packages --frozen --inexact --no-install-package sie-audio-prep+mise exec --no-deps [email protected] [email protected] -- uv run --project . --no-sync ty check "${PATHS_TO_CHECK[@]}"diff --git a/uv.lock b/uv.lockindex 8050fe1ea..50d2dba9f 100644--- a/uv.lock+++ b/uv.lock@@ -47,6 +47,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/7e/46/02ac5e262d4af18054b3e922b2baedbb2a03289ee792162de60a865defc5/accelerate-1.13.0-py3-none-any.whl", hash = "sha256:cf1a3efb96c18f7b152eb0fa7490f3710b19c3f395699358f08decca2b8b62e0", size = 383744 },]+[[package]]+name = "aiofiles"+version = "24.1.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/0b/03/a88171e277e8caa88a4c77808c20ebb04ba74cc4681bf1e9416c862de237/aiofiles-24.1.0.tar.gz", hash = "sha256:22a075c9e5a3810f0c2e48f3008c94d68c65d763b9b03857924c99e57355166c", size = 30247 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a5/45/30bb92d442636f570cb5651bc661f52b610e2eec3f891a5dc3a4c3667db0/aiofiles-24.1.0-py3-none-any.whl", hash = "sha256:b4ec55f4195e3eb5d7abd1bf7e061763e864dd4954231fb8539a0ef8bb8260e5", size = 15896 },+]+[[package]]name = "aiohappyeyeballs"version = "2.6.1"@@ -128,6 +137,64 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d2/29/6533c317b74f707ea28f8d633734dbda2119bbadfc61b2f3640ba835d0f7/alembic-1.18.4-py3-none-any.whl", hash = "sha256:a5ed4adcf6d8a4cb575f3d759f071b03cd6e5c7618eb796cb52497be25bfe19a", size = 263893 },]+[[package]]+name = "alibabacloud-credentials"+version = "1.0.12"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "aiofiles" },+ { name = "alibabacloud-credentials-api" },+ { name = "alibabacloud-tea" },+ { name = "apscheduler" },+]+sdist = { url = "https://files.pythonhosted.org/packages/25/19/bc359efb0c12f400a89783f8dc87a7261a955d73acc7b766a736e5597851/alibabacloud_credentials-1.0.12.tar.gz", hash = "sha256:87da41ea3ffb146b44d999c62c160c2b96b0c30275ae35205bcdfe79ba0c4119", size = 43203 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/89/40/8efa0f2efb400876f9355bde104fe98b621648182d4f076150f26c64e770/alibabacloud_credentials-1.0.12-py3-none-any.whl", hash = "sha256:c09afcf579663374df056c20482fc1397240d20b4ccb143d23c287f3f8a91109", size = 52000 },+]++[[package]]+name = "alibabacloud-credentials-api"+version = "1.0.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/89/7e/6145e2d132752f0de72701df556304c59dda311405a252a598ad6fd9b4de/alibabacloud_credentials_api-1.0.1.tar.gz", hash = "sha256:8ea0668a6558f6956b8d20b2e561d19a80ea29c22cf56a3004d434b24a981b36", size = 2314 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/0b/49/ff401af96d77d40ab918096d831bd3360f3eec60f10e65125e5789c4e617/alibabacloud_credentials_api-1.0.1-py3-none-any.whl", hash = "sha256:5f27889113214fc53493b3e918eb26d73dfab2022e22bdaac262849b8e58cbc0", size = 2230 },+]++[[package]]+name = "alibabacloud-tea"+version = "0.4.3"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "aiohttp" },+ { name = "requests" },+]+sdist = { url = "https://files.pythonhosted.org/packages/9a/7d/b22cb9a0d4f396ee0f3f9d7f26b76b9ed93d4101add7867a2c87ed2534f5/alibabacloud-tea-0.4.3.tar.gz", hash = "sha256:ec8053d0aa8d43ebe1deb632d5c5404339b39ec9a18a0707d57765838418504a", size = 8785 }++[[package]]+name = "aliyun-python-sdk-core"+version = "2.16.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "cryptography" },+ { name = "jmespath" },+]+wheels = [+ { url = "https://files.pythonhosted.org/packages/ea/38/eb3be49159d6442e68189f21a2205a199b51ca46cf42a3f874e695ff0ba9/aliyun_python_sdk_core-2.16.1-py3-none-any.whl", hash = "sha256:0f25a6e8ec1ea29c76610278cff81cbff85149a6e692bf2398a6f9b77e5e7424", size = 521331 },+]++[[package]]+name = "aliyun-python-sdk-kms"+version = "2.16.5"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "aliyun-python-sdk-core" },+]+sdist = { url = "https://files.pythonhosted.org/packages/a8/2c/9877d0e6b18ecf246df671ac65a5d1d9fecbf85bdcb5d43efbde0d4662eb/aliyun-python-sdk-kms-2.16.5.tar.gz", hash = "sha256:f328a8a19d83ecbb965ffce0ec1e9930755216d104638cd95ecd362753b813b3", size = 12018 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/11/5c/0132193d7da2c735669a1ed103b142fd63c9455984d48c5a88a1a516efaa/aliyun_python_sdk_kms-2.16.5-py2.py3-none-any.whl", hash = "sha256:24b6cdc4fd161d2942619479c8d050c63ea9cd22b044fe33b60bbb60153786f0", size = 99495 },+]+[[package]]name = "annotated-doc"version = "0.0.4"@@ -174,6 +241,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/3b/00/2344469e2084fb287c2e0b57b72910309874c3245463acd6cf5e3db69324/appdirs-1.4.4-py2.py3-none-any.whl", hash = "sha256:a841dacd6b99318a741b166adb07e19ee71a274450e68237b4650ca1055ab128", size = 9566 },]+[[package]]+name = "apscheduler"+version = "3.11.3"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "tzlocal" },+]+sdist = { url = "https://files.pythonhosted.org/packages/8c/6b/eeff360196bb20b312c9e762a820fd1b2c6d809466c755ef57863478e454/apscheduler-3.11.3.tar.gz", hash = "sha256:cd2fcc9330039a81a5893472ad49facf23a6d5604cbe1d918c835c6de7834d5a", size = 110312 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/42/c9/8638db32514dbb9157b3d82680c6faea89283523edf9ed2415ea3884f2ae/apscheduler-3.11.3-py3-none-any.whl", hash = "sha256:bbeb2ec02d23d3c06a6c07ed7f0f3939ada6680eb121fae809a69bb42c537a30", size = 66024 },+]+[[package]]name = "asgiref"version = "3.11.1"@@ -640,6 +719,12 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/9e/ee/a4cf96b8ce1e566ed238f0659ac2d3f007ed1d14b181bcb684e19561a69a/coverage-7.13.5-py3-none-any.whl", hash = "sha256:34b02417cf070e173989b3db962f7ed56d2f644307b2cf9d5a0f258e13084a61", size = 211346 },]+[[package]]+name = "crcmod"+version = "1.7"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/6b/b0/e595ce2a2527e169c3bcd6c33d2473c1918e0b7f6826a043ca1245dd4e5b/crcmod-1.7.tar.gz", hash = "sha256:dc7051a0db5f2bd48665a990d3ec1cc305a466a77358ca4492826f41f283601e", size = 89670 }+[[package]]name = "crewai"version = "0.95.0"@@ -3227,6 +3312,20 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/cc/47/5aaf54524a7a4a0dd09dd778f3fa65dd2108290615b652e23d944152bc8e/orjson-3.11.8-cp312-cp312-win_arm64.whl", hash = "sha256:48854463b0572cc87dac7d981aa72ed8bf6deedc0511853dc76b8bbd5482d36d", size = 127364 },]+[[package]]+name = "oss2"+version = "2.19.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "aliyun-python-sdk-core" },+ { name = "aliyun-python-sdk-kms" },+ { name = "crcmod" },+ { name = "pycryptodome" },+ { name = "requests" },+ { name = "six" },+]+sdist = { url = "https://files.pythonhosted.org/packages/df/b5/f2cb1950dda46ac2284d6c950489fdacd0e743c2d79a347924d3cc44b86f/oss2-2.19.1.tar.gz", hash = "sha256:a8ab9ee7eb99e88a7e1382edc6ea641d219d585a7e074e3776e9dec9473e59c1", size = 298845 }+[[package]]name = "overrides"version = "7.7.0"@@ -3613,6 +3712,25 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172 },]+[[package]]+name = "pycryptodome"+version = "3.23.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/8e/a6/8452177684d5e906854776276ddd34eca30d1b1e15aa1ee9cefc289a33f5/pycryptodome-3.23.0.tar.gz", hash = "sha256:447700a657182d60338bab09fdb27518f8856aecd80ae4c6bdddb67ff5da44ef", size = 4921276 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/db/6c/a1f71542c969912bb0e106f64f60a56cc1f0fabecf9396f45accbe63fa68/pycryptodome-3.23.0-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:187058ab80b3281b1de11c2e6842a357a1f71b42cb1e15bce373f3d238135c27", size = 2495627 },+ { url = "https://files.pythonhosted.org/packages/6e/4e/a066527e079fc5002390c8acdd3aca431e6ea0a50ffd7201551175b47323/pycryptodome-3.23.0-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:cfb5cd445280c5b0a4e6187a7ce8de5a07b5f3f897f235caa11f1f435f182843", size = 1640362 },+ { url = "https://files.pythonhosted.org/packages/50/52/adaf4c8c100a8c49d2bd058e5b551f73dfd8cb89eb4911e25a0c469b6b4e/pycryptodome-3.23.0-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:67bd81fcbe34f43ad9422ee8fd4843c8e7198dd88dd3d40e6de42ee65fbe1490", size = 2182625 },+ { url = "https://files.pythonhosted.org/packages/5f/e9/a09476d436d0ff1402ac3867d933c61805ec2326c6ea557aeeac3825604e/pycryptodome-3.23.0-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c8987bd3307a39bc03df5c8e0e3d8be0c4c3518b7f044b0f4c15d1aa78f52575", size = 2268954 },+ { url = "https://files.pythonhosted.org/packages/f9/c5/ffe6474e0c551d54cab931918127c46d70cab8f114e0c2b5a3c071c2f484/pycryptodome-3.23.0-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:aa0698f65e5b570426fc31b8162ed4603b0c2841cbb9088e2b01641e3065915b", size = 2308534 },+ { url = "https://files.pythonhosted.org/packages/18/28/e199677fc15ecf43010f2463fde4c1a53015d1fe95fb03bca2890836603a/pycryptodome-3.23.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:53ecbafc2b55353edcebd64bf5da94a2a2cdf5090a6915bcca6eca6cc452585a", size = 2181853 },+ { url = "https://files.pythonhosted.org/packages/ce/ea/4fdb09f2165ce1365c9eaefef36625583371ee514db58dc9b65d3a255c4c/pycryptodome-3.23.0-cp37-abi3-musllinux_1_2_i686.whl", hash = "sha256:156df9667ad9f2ad26255926524e1c136d6664b741547deb0a86a9acf5ea631f", size = 2342465 },+ { url = "https://files.pythonhosted.org/packages/22/82/6edc3fc42fe9284aead511394bac167693fb2b0e0395b28b8bedaa07ef04/pycryptodome-3.23.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:dea827b4d55ee390dc89b2afe5927d4308a8b538ae91d9c6f7a5090f397af1aa", size = 2267414 },+ { url = "https://files.pythonhosted.org/packages/59/fe/aae679b64363eb78326c7fdc9d06ec3de18bac68be4b612fc1fe8902693c/pycryptodome-3.23.0-cp37-abi3-win32.whl", hash = "sha256:507dbead45474b62b2bbe318eb1c4c8ee641077532067fec9c1aa82c31f84886", size = 1768484 },+ { url = "https://files.pythonhosted.org/packages/54/2f/e97a1b8294db0daaa87012c24a7bb714147c7ade7656973fd6c736b484ff/pycryptodome-3.23.0-cp37-abi3-win_amd64.whl", hash = "sha256:c75b52aacc6c0c260f204cbdd834f76edc9fb0d8e0da9fbf8352ef58202564e2", size = 1799636 },+ { url = "https://files.pythonhosted.org/packages/18/3d/f9441a0d798bf2b1e645adc3265e55706aead1255ccdad3856dbdcffec14/pycryptodome-3.23.0-cp37-abi3-win_arm64.whl", hash = "sha256:11eeeb6917903876f134b56ba11abe95c0b0fd5e3330def218083c7d98bbcb3c", size = 1703675 },+]+[[package]]name = "pydantic"version = "2.12.5"@@ -4388,12 +4506,12 @@ dev = [[[package]]name = "sie-audio-prep"-version = "0.7.1"+version = "0.7.2"source = { editable = "packages/sie_audio_prep" }[[package]]name = "sie-chroma"-version = "0.7.1"+version = "0.7.2"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -4473,7 +4591,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.7.1"+version = "0.7.2"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -4498,7 +4616,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.7.1"+version = "0.7.2"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -4523,7 +4641,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.7.1"+version = "0.7.2"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -4550,7 +4668,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.7.1"+version = "0.7.2"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -4577,7 +4695,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.7.1"+version = "0.7.2"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -4604,7 +4722,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.7.1"+version = "0.7.2"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -4670,7 +4788,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.7.1"+version = "0.7.2"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -4693,7 +4811,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.7.1"+version = "0.7.2"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -4717,16 +4835,19 @@ llamaindex = [{ name = "llama-index-core" },]storage = [+ { name = "alibabacloud-credentials" },{ name = "azure-identity" },{ name = "azure-storage-blob" },{ name = "boto3" },{ name = "google-cloud-storage" },{ name = "huggingface-hub", extra = ["hf-transfer"] },+ { name = "oss2" },][package.metadata]requires-dist = [{ name = "aiohttp", specifier = ">=3.9,<4" },+ { name = "alibabacloud-credentials", marker = "extra == 'storage'", specifier = ">=1.0.12,<2" },{ 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" },@@ -4739,6 +4860,7 @@ requires-dist = [{ name = "msgpack", specifier = ">=1.2.1,<2" },{ name = "msgpack-numpy", specifier = ">=0.4,<1" },{ name = "numpy", specifier = ">=2,<3" },+ { name = "oss2", marker = "extra == 'storage'", specifier = ">=2.19.1,<3" },{ name = "pillow", specifier = ">=12.2.0" },{ name = "pyyaml", specifier = ">=6,<7" },{ name = "websockets", specifier = ">=14,<15" },@@ -4746,7 +4868,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.7.1"+version = "0.7.2"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -4875,7 +4997,7 @@ dev = [][[package]]name = "sie-weaviate"-version = "0.7.1"+version = "0.7.2"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },@@ -5507,6 +5629,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ce/e4/dccd7f47c4b64213ac01ef921a1337ee6e30e8c6466046018326977efd95/tzdata-2026.2-py2.py3-none-any.whl", hash = "sha256:bbe9af844f658da81a5f95019480da3a89415801f6cc966806612cc7169bffe7", size = 349321 },]+[[package]]+name = "tzlocal"+version = "5.4.4"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "tzdata", marker = "sys_platform == 'win32'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/81/5b/879b2f932adfa7a053c360d50bc896c977fa6426109185f7c12ebdd0cb9d/tzlocal-5.4.4.tar.gz", hash = "sha256:8dbb8660838688a7b6ba4fed31d18dedf842afb4d47ca050d6d891c2c15f3be4", size = 31170 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/9e/a4/017a7a6cbe387d961a688ec31364ae60a5c4e22c96ae9921b79a947c855d/tzlocal-5.4.4-py3-none-any.whl", hash = "sha256:aae09f0126a8a86fa736be266eb4a471380d26a0de3bc14844e7821fee3e2a15", size = 18115 },+]+[[package]]name = "uc-micro-py"version = "2.0.0"