Skip to content

armgit / sie

Public Imported from GitHub
0

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

release: v0.6.25

github-actions[bot]4c497942241b
diff --git a/.gitignore b/.gitignore
index d233fce36..e0b33048f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -256,6 +256,13 @@ override.tf.json
# 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-edge/.terraform.lock.hcl
+!deploy/cloud/terraform/examples/staging/.terraform.lock.hcl
+!deploy/cloud/terraform/examples/prod-us/.terraform.lock.hcl
# Keep .terraform.lock.hcl for reproducibility (provider versions)
# Node.js
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 51257d8d6..de73b803c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,74 @@
# Changelog
+## v0.6.25
+
+- chore(main): release 0.6.25
+- docs(gateway): regenerate embeddings OpenAPI
+- fix(server): bill SigLIP padded text work
+- fix(gateway): cap embeddings requests at 256 inputs
+- fix(cloud): close metering GA review findings
+- fix(cloud): scope authoritative zero evidence
+- fix(cloud): close final metering review faults
+- test(cloud): lock the wrapper's other forwards and the refuse-before-seal order (#2542)
+- fix(cloud): make the witnessed zero reach the wire and cover both rails (#2538)
+- feat(telemetry): export the sealed cold-start metric remotely and chart it
+- fix(cloud): make the response cap operative, unbilled, and honest (#2617)
+- fix(cloud): bound the sealed resolver cache and cap proxy response bodies (#2617)
+- fix(cloud): close the CodeRabbit round on the integration head
+- fix(cloud): observe the sealed cold-start metric; scope it to the prometheus path
+- docs(cloud): flag the sealed rate correction at activation; close telemetry contract
+- fix(cloud): address the CodeRabbit round on the metering GA integration
+- docs(design): state the fail-closed rule for a missing video frame count
+- fix(cloud): treat an explicitly null video as absent, not as a video
+- docs(design): state when a video rejection actually precedes the hold
+- fix(cloud): address the second CodeRabbit round on /v1/estimate (#2435)
+- fix(cloud): close the second CodeRabbit round on the credit surfaces (#2434)
+- fix(server): bound isolation fan-out and close the NaN decode escapes
+- fix(cloud): claim the hold before releasing it, and fold case like the registry
+- feat(models): onboard Qwen/Qwen3-Embedding-8B (scaffolded)
+- fix(cloud): address CodeRabbit review on the /v1/estimate dry run (#2435)
+- fix(server): address CodeRabbit review on the video meter
+- fix(cloud): address CodeRabbit review on the settled-charge surfaces (#2434)
+- fix(cloud): route expected no-charge stream releases off the fault alerts
+- fix(cloud): close the gate findings on the resolution-seam verdict (#2542)
+- style(server): ruff formatting for the #2538 test block
+- fix(cloud): admit an image-witnessed authoritative zero at settlement (#2538)
+- docs(design): record the §6.5 verdict at the resolution seam (#2542)
+- test(cloud): lock the alias + serving-selector bypasses at the resolution seam (#2542)
+- test(cloud): cover authoritative-zero settlement across the claim boundary (#2538)
+- docs(sdk): note the routability 404 on estimate() in both SDKs (#2435)
+- fix(cloud): close six gate findings on the /v1/estimate dry run (#2435)
+- feat(cloud): move the license exclusion verdict to the registry resolution seam (#2542)
+- feat(cloud): carry an authoritative-dimension claim set on UnitCounts (#2538)
+- feat(sdk): estimate() on both SDKs for the /v1/estimate dry run (#2435)
+- test(cloud): parity, zero-side-effect, fail-closed and abuse tests for /v1/estimate (#2435)
+- fix(catalog): bound GLiNER sequence lengths
+- feat(cloud): POST /v1/estimate dry-run cost endpoint (#2435)
+- fix(cloud): publish a committed charge even when settlement then faults (#2434)
+- fix(cloud): bind the charge-slot backstop to the stream, not the disconnect grace (#2434)
+- fix(gateway): preserve self-host grammar routing
+- fix(gateway): harden governed generation dispatch
+- feat(cloud): unify the settled-charge name across jobs, batches, and SDKs (#2434)
+- feat(gateway): add optional governed generation routing seam
+- test(cloud): pin the realtime and stream credit surfaces (#2434)
+- feat(cloud): carry the settled charge into realtime usage blocks (#2434)
+- fix(cloud): release the hold when the gateway cannot deliver the result
+- fix(cloud): parse the multipart model under the route's real body limit
+- feat(cloud): unfence OpenAI-compat /v1/audio/transcriptions (#2430)
+- feat(gateway): carry output_tokens on the per-item result-units path
+- test(server): pin the batched-path, sampling and isolation invariants
+- fix(cloud): close three adversarial-review findings on metered streaming
+- fix(server): survive the batched encode path and bound video decode
+- feat(cloud): response-final settlement for streaming generation
+- feat(server): bill sampled video frames as images
+- fix(cloud): cold-start rail review fixes — refunds, honest ceiling, quiet 429
+- fix(gateway): surface the cold-start quota refusal as 429
+- chore(cloud): address combined review feedback
+- fix(generation): reconcile profile minimum with request maximum
+- feat(sdk): add files and batches cursor lifecycle
+- fix(gateway): make first-chunk republish capability explicit
+- feat(cloud): gpu_second sealed billing regime (wip: CP class endpoint pending)
+
## v0.6.24
- chore(main): release 0.6.24
diff --git a/Cargo.lock b/Cargo.lock
index 3ea95d651..4ef0b0df0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3583,7 +3583,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "sie-audio-prep"
-version = "0.6.24"
+version = "0.6.25"
dependencies = [
"audioadapter-buffers",
"opusic-sys",
@@ -3597,7 +3597,7 @@ dependencies = [
[[package]]
name = "sie-gateway"
-version = "0.6.24"
+version = "0.6.25"
dependencies = [
"arc-swap",
"async-nats",
@@ -3610,6 +3610,7 @@ dependencies = [
"fs2",
"futures-util",
"http",
+ "http-body-util",
"hyper",
"hyper-util",
"k8s-openapi",
@@ -3654,7 +3655,7 @@ dependencies = [
[[package]]
name = "sie-server-sidecar"
-version = "0.6.24"
+version = "0.6.25"
dependencies = [
"anyhow",
"async-nats",
diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yaml
index 12efc004c..6c8f28ff4 100644
--- a/deploy/helm/sie-cluster/Chart.yaml
+++ b/deploy/helm/sie-cluster/Chart.yaml
@@ -4,8 +4,8 @@ description: >-
SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,
and observability
type: application
-version: 0.6.24 # x-release-please-version
-appVersion: v0.6.24 # x-release-please-version
+version: 0.6.25 # x-release-please-version
+appVersion: v0.6.25 # x-release-please-version
keywords:
- inference
- embedding
diff --git a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json b/deploy/helm/sie-cluster/files/dashboards/queue-routing.json
index ed7e12b9d..2ecabdb98 100644
--- a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json
+++ b/deploy/helm/sie-cluster/files/dashboards/queue-routing.json
@@ -1515,6 +1515,47 @@
"refId": "A"
}
]
+ },
+ {
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 0,
+ "y": 101
+ },
+ "id": 114,
+ "type": "timeseries",
+ "title": "Sealed cold-start subsidy seconds by GPU class",
+ "description": "GPU time spent WAKING scaled-to-zero sealed models (fetch + seal + model load). A cold start is free to the customer by design, so this is the platform-subsidised share of sealed GPU time - the signal to watch when tuning SIE_SEALED_MAX_COLD_STARTS_PER_ACCOUNT_HOUR. Broken out by GPU class because that is what converts seconds into dollars. Neither neighbour answers this: sealed staging duration is a latency histogram with no summable total, and sealed sole-tenant GPU seconds covers the whole residency without separating the wake from the serving.",
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s",
+ "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 (gpu_class) (rate(sie_dispatcher_sealed_cold_start_seconds_total{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-dispatcher\"}[$rate_window]))",
+ "legendFormat": "{{gpu_class}}",
+ "refId": "A"
+ }
+ ]
}
],
"refresh": "10s",
diff --git a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl b/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl
index 3498c28cb..df1f573f6 100644
--- a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl
+++ b/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl
@@ -95,9 +95,9 @@ processors:
error_mode: propagate
metrics:
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[.]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[.]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-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)$")'
+ - '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)$")'
@@ -121,7 +121,7 @@ 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[.]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[.]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, "{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)$")'
@@ -174,6 +174,7 @@ processors:
- '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)$")'
- 'keep_keys(attributes, []) where IsMatch(metric.name, "^(sie[.]dispatcher[.]sealed[.]resident|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds)$")'
+ - 'keep_keys(attributes, ["gpu_class"]) where IsMatch(metric.name, "^(sie[.]dispatcher[.]sealed[.]cold_start[.]seconds)$")'
- 'keep_keys(attributes, ["http.method", "http.route", "http.status_code"]) where IsMatch(metric.name, "^(sie[.]config[.]requests|sie[.]config[.]request[.]duration)$")'
- 'keep_keys(attributes, ["source"]) where metric.name == "sie.config.models"'
- 'keep_keys(attributes, ["operation", "lane", "model", "profile"]) where IsMatch(metric.name, "^(sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]queue[.]depth|sie[.]worker[.]queue[.]pending_at_dispatch)$")'
@@ -279,9 +280,9 @@ processors:
error_mode: propagate
metrics:
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[.]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[.]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-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)$")'
+ - '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)$")'
diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.toml
index 1a08e11af..0619d29f4 100644
--- a/integrations/sie_chroma/pyproject.toml
+++ b/integrations/sie_chroma/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-chroma"
-version = "0.6.24"
+version = "0.6.25"
description = "SIE integration for ChromaDB"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.toml
index 0338adf87..b76a2a9fb 100644
--- a/integrations/sie_crewai/pyproject.toml
+++ b/integrations/sie_crewai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-crewai"
-version = "0.6.24"
+version = "0.6.25"
description = "SIE integration for CrewAI"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.toml
index fef7557c8..81ca34ebc 100644
--- a/integrations/sie_dspy/pyproject.toml
+++ b/integrations/sie_dspy/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-dspy"
-version = "0.6.24"
+version = "0.6.25"
description = "SIE integration for DSPy"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.toml
index d6708d6f7..a2b1f2083 100644
--- a/integrations/sie_haystack/pyproject.toml
+++ b/integrations/sie_haystack/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-haystack"
-version = "0.6.24"
+version = "0.6.25"
description = "SIE integration for Haystack"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.toml
index f72c4348a..4d166ba88 100644
--- a/integrations/sie_lancedb/pyproject.toml
+++ b/integrations/sie_lancedb/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-lancedb"
-version = "0.6.24"
+version = "0.6.25"
description = "SIE integration for LanceDB"
requires-python = ">=3.12"
dependencies = [
diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.toml
index 2352578f9..dca443c3d 100644
--- a/integrations/sie_langchain/pyproject.toml
+++ b/integrations/sie_langchain/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-langchain"
-version = "0.6.24"
+version = "0.6.25"
description = "SIE integration for LangChain"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.toml
index e75b34883..0dac6f43c 100644
--- a/integrations/sie_llamaindex/pyproject.toml
+++ b/integrations/sie_llamaindex/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-llamaindex"
-version = "0.6.24"
+version = "0.6.25"
description = "SIE integration for LlamaIndex"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.toml
index 7ace48594..cee016a07 100644
--- a/integrations/sie_qdrant/pyproject.toml
+++ b/integrations/sie_qdrant/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-qdrant"
-version = "0.6.24"
+version = "0.6.25"
description = "SIE integration for Qdrant"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.json
index c4402d9d7..620fc8740 100644
--- a/integrations/sie_ts_chroma/package.json
+++ b/integrations/sie_ts_chroma/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-chroma",
- "version": "0.6.24",
+ "version": "0.6.25",
"description": "SIE embedding function for ChromaDB",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.json
index 5c06a6283..1e9256707 100644
--- a/integrations/sie_ts_lancedb/package.json
+++ b/integrations/sie_ts_lancedb/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-lancedb",
- "version": "0.6.24",
+ "version": "0.6.25",
"description": "SIE embedding function and reranker for LanceDB",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.json
index f559272de..5b4198f54 100644
--- a/integrations/sie_ts_langchain/package.json
+++ b/integrations/sie_ts_langchain/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-langchain",
- "version": "0.6.24",
+ "version": "0.6.25",
"description": "SIE embeddings integration for LangChain.js",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.json
index 2a749d161..de846c151 100644
--- a/integrations/sie_ts_llamaindex/package.json
+++ b/integrations/sie_ts_llamaindex/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-llamaindex",
- "version": "0.6.24",
+ "version": "0.6.25",
"description": "SIE embeddings integration for LlamaIndex.TS",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.toml
index 3ae13ec80..e28454412 100644
--- a/integrations/sie_weaviate/pyproject.toml
+++ b/integrations/sie_weaviate/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-weaviate"
-version = "0.6.24"
+version = "0.6.25"
description = "SIE integration for Weaviate"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/packages/sie_audio_prep/Cargo.toml b/packages/sie_audio_prep/Cargo.toml
index cf957d0cc..e649f4985 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.6.24"
+version = "0.6.25"
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.py
index 08d4138c6..615be899c 100644
--- a/packages/sie_audio_prep/build_wheel.py
+++ b/packages/sie_audio_prep/build_wheel.py
@@ -16,7 +16,7 @@ import zipfile
from pathlib import Path
MATURIN_VERSION = "1.13.3"
-AUDIO_PREP_VERSION = "0.6.24" # x-release-please-version
+AUDIO_PREP_VERSION = "0.6.25" # x-release-please-version
AUDIO_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.toml
index d9404ce60..9690512bb 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.6.24"
+version = "0.6.25"
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_gateway/Cargo.toml b/packages/sie_gateway/Cargo.toml
index 5317e6aa1..722c2c0a1 100644
--- a/packages/sie_gateway/Cargo.toml
+++ b/packages/sie_gateway/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-gateway"
-version = "0.6.24"
+version = "0.6.25"
edition = "2021"
publish = false
@@ -15,6 +15,11 @@ tokio = { version = "1", features = ["full"] }
tokio-stream = { version = "0.1", features = ["sync"] }
hyper = { version = "1", features = ["full"] }
hyper-util = { version = "0.1", features = ["tokio"] }
+# Already in the lock transitively (axum's `to_bytes` IS `Limited::collect`).
+# Direct so the compat wrapper can downcast `LengthLimitError` and tell "the
+# body exceeded the read bound" apart from "the stream broke" — two conditions
+# `axum::Error` otherwise collapses into one opaque value (#2617).
+http-body-util = "0.1"
reqwest = { version = "0.13", default-features = false, features = ["blocking", "json", "stream", "rustls"] }
rustls = { version = "0.23", default-features = false, features = ["ring"] }
tokio-tungstenite = "0.29"
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index 620114d5f..bb2b7cace 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -44,7 +44,7 @@ Key terms used throughout this document:
- `POST /v1/encode/{*model}`
- `POST /v1/score/{*model}`
- `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`**.
+ - `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.
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.
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json
index 9ef1bc0a0..af254e8c8 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -2341,7 +2341,7 @@
"items": {
"type": "string"
},
- "maxItems": 4096,
+ "maxItems": 256,
"type": "array"
}
]
@@ -3686,7 +3686,7 @@
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
},
"title": "SIE Gateway",
- "version": "0.6.24"
+ "version": "0.6.25"
},
"openapi": "3.1.0",
"paths": {
diff --git a/packages/sie_gateway/src/handlers/audio.rs b/packages/sie_gateway/src/handlers/audio.rs
index 7020a20dc..685be97f7 100644
--- a/packages/sie_gateway/src/handlers/audio.rs
+++ b/packages/sie_gateway/src/handlers/audio.rs
@@ -15,7 +15,7 @@ use serde_json::{json, Map, Value};
use crate::http_error::{
code as err_code, embeddings_error, json_openai_error, openai_code as oai_code,
- openai_type as oai_type,
+ openai_type as oai_type, GatewayOwnedFault,
};
use crate::server::AppState;
@@ -25,9 +25,23 @@ use super::proxy::{
};
const MAX_AUDIO_FILE_BYTES: usize = 24 * 1024 * 1024;
-pub(crate) const MAX_MULTIPART_BYTES: usize = MAX_AUDIO_FILE_BYTES + 1024 * 1024;
+/// Whole-body ingress bound for the multipart transcription upload: the audio
+/// file cap plus 1 MiB of form scaffolding and text fields.
+///
+/// `pub` because a downstream composition crate must be able to bound its own
+/// read of this body at exactly the same number. The managed edge buffers the
+/// body ahead of this handler to gate the multipart-carried `model` against its
+/// licensing overlay (#2430); if the two bounds could drift, the managed gate
+/// would either reject bodies this handler accepts or admit bodies it rejects.
+pub const MAX_MULTIPART_BYTES: usize = MAX_AUDIO_FILE_BYTES + 1024 * 1024;
const MAX_TEXT_FIELD_BYTES: usize = 8 * 1024;
-const MAX_FORM_FIELDS: usize = 16;
+/// Field-count bound for the multipart transcription form.
+///
+/// `pub` for the same reason as [`MAX_MULTIPART_BYTES`]: the managed edge scans
+/// this form to gate its `model` part, and if its scan bound were lower than
+/// this one, a form whose `model` sits past the edge's cap would be rejected by
+/// the gate while this handler would have accepted it.
+pub const MAX_FORM_FIELDS: usize = 16;
const MAX_NATIVE_RESPONSE_BYTES: usize = 34 * 1024 * 1024;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -661,33 +675,28 @@ pub async fn proxy_openai_transcription(
return native_response;
}
+ // From here the worker has already run and reported its units. Every failure
+ // below is OURS — a successful transcription this handler could not render
+ // into the client's requested shape — and the client gets nothing for it.
+ // Each is marked so a metered composition releases the hold instead of
+ // charging for an undelivered result (see [`GatewayOwnedFault`]).
let native_headers = native_response.headers().clone();
let bytes = match to_bytes(native_response.into_body(), MAX_NATIVE_RESPONSE_BYTES).await {
Ok(bytes) => bytes,
Err(_) => {
- return (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(embeddings_error(
- err_code::INTERNAL_ERROR,
- None,
- "failed to read native extract response",
- )),
- )
- .into_response();
+ return translation_fault(
+ "read_native_response",
+ "failed to read native extract response",
+ );
}
};
let parsed: Value = match serde_json::from_slice(&bytes) {
Ok(value) => value,
Err(_) => {
- return (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(embeddings_error(
- err_code::INTERNAL_ERROR,
- None,
- "native extract response is not valid JSON",
- )),
- )
- .into_response();
+ return translation_fault(
+ "decode_native_response",
+ "native extract response is not valid JSON",
+ );
}
};
let data = parsed
@@ -697,30 +706,37 @@ pub async fn proxy_openai_transcription(
.and_then(|items| items[0].get("data"))
.and_then(Value::as_object);
let Some(data) = data else {
- return (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(embeddings_error(
- err_code::INTERNAL_ERROR,
- None,
- "native extract response is missing one transcription result",
- )),
- )
- .into_response();
+ return translation_fault(
+ "native_response_shape",
+ "native extract response is missing one transcription result",
+ );
};
let mut response = match format_transcription_response(data, &form) {
Ok(response) => response,
- Err(message) => {
- return (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(embeddings_error(err_code::INTERNAL_ERROR, None, message)),
- )
- .into_response();
- }
+ Err(message) => return translation_fault("format_transcription", message),
};
copy_native_response_headers(&native_headers, response.headers_mut());
response
}
+/// A 500 for a post-dispatch translation failure, marked as gateway-owned.
+///
+/// The worker already produced a valid result; this handler is what could not
+/// turn it into the requested response shape. The most reachable case is
+/// `response_format=srt`/`vtt` over a segment whose `end` timestamp Whisper left
+/// open — an ordinary, upstream-documented output shape, not a corrupt result.
+/// Without the marker that 500 still debits the full accepted duration, so the
+/// customer pays for a transcript they never receive.
+fn translation_fault(stage: &'static str, message: &str) -> Response {
+ GatewayOwnedFault::new(stage).mark(
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(embeddings_error(err_code::INTERNAL_ERROR, None, message)),
+ )
+ .into_response(),
+ )
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 4dc833d50..76eade82a 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -15,7 +15,7 @@ use tracing::{debug, error, info, warn};
use crate::endpoint::InferenceEndpoint;
use crate::http_error::{
code as err_code, embeddings_error, json_detail, json_detail_merge, json_openai_error,
- openai_code as oai_code, openai_type as oai_type,
+ openai_code as oai_code, openai_type as oai_type, GatewayOwnedFault,
};
use crate::observability::metrics as telemetry;
use crate::queue::dispatch::{
@@ -24,7 +24,9 @@ use crate::queue::dispatch::{
use crate::queue::publisher;
use crate::queue::streaming::is_lower_sha256;
-use crate::server::AppState;
+use crate::server::{
+ AppState, GenerationRequestIntent, GovernedGenerationRoute, ModelAccessPolicy,
+};
use crate::state::demand_tracker::PhysicalLane;
use crate::state::model_registry::{ModelRegistry, ResolveError};
use crate::state::pool_manager::{normalize_pool_name, PoolManager, DEFAULT_POOL_NAME};
@@ -34,7 +36,23 @@ use crate::types::AuditEntry;
use crate::middleware::auth::{extract_bearer_token, mask_token};
const GATEWAY_VERSION: &str = env!("CARGO_PKG_VERSION");
-const MAX_PROXY_BODY: usize = 16 * 1024 * 1024;
+
+/// The ONE ingress bound every JSON body-bearing route accepts.
+///
+/// 16 MiB: enough headroom for multimodal content parts (base64 images) while
+/// closing the trivial OOM-under-concurrency vector the legacy 256 MiB cap left
+/// open. `/v1/encode`, `/v1/score`, `/v1/embeddings`, `/v1/chat/completions`,
+/// `/v1/completions` and `/v1/responses` all derive from it; only the two
+/// routes that carry inline native MEDIA (`generate`'s images, `extract`'s
+/// audio) raise it, and they say why below.
+///
+/// `pub` and singular on purpose: a gate, a probe, or a second surface that
+/// buffers a body on a route's behalf must pin to the route's own number.
+/// Smaller and it denies legitimate traffic the route would have served; larger
+/// and it is a way around the rail. Both mistakes have shipped here before.
+pub const MAX_JSON_BODY_BYTES: usize = 16 * 1024 * 1024;
+
+const MAX_PROXY_BODY: usize = MAX_JSON_BODY_BYTES;
// Native generate accepts bounded inline images. A 16 MiB decoded image grows
// to ~21.4 MiB in base64; leave room for the prompt and JSON envelope while
// still bounding aggregate request memory at ingress.
@@ -45,6 +63,227 @@ const MAX_GENERATE_IMAGE_BASE64_CHARS: usize = 4 * MAX_GENERATE_IMAGE_BYTES.div_
// The audio preprocessor accepts 24 MiB of encoded media. Base64 expands that
// to exactly 32 MiB; leave bounded room for the surrounding native JSON item.
const MAX_EXTRACT_BODY: usize = 34 * 1024 * 1024;
+
+/// The ingress body cap for ONE native queue endpoint (`encode` / `score` /
+/// `extract` / `generate`).
+///
+/// Public so a surface that carries a native body without being the native
+/// route — the managed cost-estimate dry run's `{endpoint, request}` envelope
+/// (#2435) — bounds that body at the SAME number the route itself does. The
+/// caps are abuse rails on planner/ingress work; a second surface that accepts
+/// a larger body than the route it prices is a way around the rail.
+pub fn native_request_body_limit(endpoint: &str) -> usize {
+ match endpoint {
+ "generate" => MAX_GENERATE_BODY,
+ "extract" => MAX_EXTRACT_BODY,
+ _ => MAX_PROXY_BODY,
+ }
+}
+
+/// The ingress body cap for ONE OpenAI-compatible route.
+///
+/// Public for the same reason as [`native_request_body_limit`], and separate
+/// from it because the compat generation routes do NOT take the 24 MiB native
+/// `generate` cap: their bodies carry no inline native media array, so they sit
+/// on the shared [`MAX_JSON_BODY_BYTES`] bound. An estimate that bounded a chat
+/// body at the native number would accept 1.5x what the route it prices
+/// accepts — the exact way around the rail this helper exists to prevent
+/// (#2435).
+pub fn compat_request_body_limit(_path: &str) -> usize {
+ MAX_JSON_BODY_BYTES
+}
+
+/// The bound on an inner NATIVE response an OpenAI-compatible wrapper must
+/// buffer whole before it can reshape it.
+///
+/// # Why it is separate from the request cap
+///
+/// This bound used to be `compat_request_body_limit("/v1/embeddings")`. Reusing
+/// a REQUEST cap for a RESPONSE is wrong regardless of the number: `/v1/embeddings`
+/// is the one compat surface whose reply is an *amplification* of its request —
+/// N short texts in, N × `dim` floats out — so the two quantities are unrelated,
+/// and a future change to the ingress cap would silently move this bound.
+/// Owning the constant separately is the actual fix; the value below is a second,
+/// independent decision.
+///
+/// # Why the value is 16 MiB, and why it is CHOSEN rather than derived
+///
+/// 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):
+///
+/// 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
+/// limit, so the payload it authorises is ~21.3 MiB, not 64 MiB.
+/// 2. The rail is not even on this path. Embedding item results are ~4 KiB, far
+/// under `PAYLOAD_OFFLOAD_THRESHOLD` (1 MiB), so they never chunk. The
+/// per-request number is also only safe because of a process-wide budget that
+/// has no analogue here — nothing counts the compat wrapper's allocation.
+///
+/// There is no honest derivation available, because **no bound both admits every
+/// reply this surface can produce AND fits the container.** At the queue maximum
+/// (`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.
+///
+/// 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.
+///
+/// # What this deliberately does NOT fix
+///
+/// The 256-item ingress cap on `/v1/embeddings` prevents known-undeliverable
+/// large batches from reaching this post-dispatch rail. This cap remains the
+/// fail-closed backstop for output amplification, unexpected model dimensions,
+/// and any future response-shape growth.
+const MAX_COMPAT_RESPONSE_BODY: usize = 16 * 1024 * 1024;
+
+/// Outcome of buffering an inner native response under
+/// [`MAX_COMPAT_RESPONSE_BODY`].
+///
+/// The two failure arms are deliberately distinct because they earn different
+/// caller-facing verdicts — but note that both are GATEWAY-OWNED faults for
+/// billing: the worker has already run and reported its units by the time this
+/// runs, and the customer receives no embeddings either way.
+#[derive(Debug)]
+pub(crate) enum CompatResponseBody {
+ Buffered(axum::body::Bytes),
+ /// The reply exceeded [`MAX_COMPAT_RESPONSE_BODY`]. Carries the observed
+ /// length when the body announced one, so the caller can scale their batch
+ /// by a known factor instead of guessing.
+ TooLarge {
+ observed: Option<u64>,
+ },
+ /// The body could not be read at all — a genuine stream failure, NOT a size
+ /// condition.
+ Unreadable,
+}
+
+/// Buffer an inner native response, classifying over-cap separately from
+/// unreadable.
+///
+/// # Why this is not simply `to_bytes(body, CAP + 1)` and a length comparison
+///
+/// That was the first attempt and it was inoperative (#2617). `axum::body::to_bytes`
+/// IS `Limited::new(body, limit).collect()`, and `Limited` yields
+/// `LengthLimitError` the moment a frame would push the running total past the
+/// limit — it does not collect the body and then check. So `Ok` can never carry
+/// a length ABOVE the limit, and a `len() > CAP` guard over a `CAP + 1` limit
+/// matches at exactly ONE size: `CAP + 1`. Every genuinely oversized reply took
+/// the error arm and returned the opaque 500 the change existed to replace.
+/// `compat_response_cap_classifies_sizes_past_the_boundary` pins `CAP + 2` and a
+/// 4× oversize precisely because the old shape passed a `CAP`/`CAP + 1` test
+/// while the branch was dead.
+///
+/// Two stages, so every body shape lands correctly:
+///
+/// 1. **Size hint first.** An in-process reply (which is what `proxy_request`
+/// returns — a complete `Vec<u8>`) announces its exact length, so an oversized
+/// body is refused WITHOUT allocating it. That is the whole point of checking
+/// first: buffering 90 MB in order to discard it is the memory spike this cap
+/// exists to prevent.
+/// 2. **Downcast the limit error.** For a body that announces nothing, buffer to
+/// the cap and recover the distinction from the error's source chain. This is
+/// why `http-body-util` is a direct dependency.
+pub(crate) async fn buffer_compat_response_body(body: Body) -> CompatResponseBody {
+ use hyper::body::Body as _;
+
+ // `lower()` is a guaranteed minimum, so exceeding the cap here is proof, not
+ // an estimate. Unknown-length bodies report 0 and fall through to stage 2.
+ let announced = body.size_hint().lower();
+ if announced > MAX_COMPAT_RESPONSE_BODY as u64 {
+ return CompatResponseBody::TooLarge {
+ observed: Some(announced),
+ };
+ }
+ match to_bytes(body, MAX_COMPAT_RESPONSE_BODY).await {
+ Ok(bytes) => CompatResponseBody::Buffered(bytes),
+ Err(error) if is_length_limit_error(&error) => {
+ CompatResponseBody::TooLarge { observed: None }
+ }
+ Err(_) => CompatResponseBody::Unreadable,
+ }
+}
+
+/// A terminal `/v1/embeddings` error for a POST-DISPATCH failure, marked as
+/// gateway-owned so a metered composition releases the hold.
+///
+/// The worker already ran and the meter already holds its units by the time any
+/// caller of this runs (the dispatcher records authoritative units *before*
+/// fulfilling the result channel). Without the marker, the managed edge falls
+/// through to `settle_planned_request`, which bills every recorded dispatch
+/// regardless of the response status — so the customer pays in full for a
+/// response carrying zero embeddings. That is the defect class of #2641, and it
+/// is what [`GatewayOwnedFault`]'s own doc names: "a response body larger than
+/// the read bound".
+///
+/// The status is the CALLER's verdict (retry or don't); the marker is the
+/// BILLING verdict (charge or don't). A terminal 4xx and a gateway-owned fault
+/// are not in tension: the caller must change their request, and they still owe
+/// nothing for the batch that produced no output.
+fn compat_translation_fault(
+ stage: &'static str,
+ status: StatusCode,
+ code: &str,
+ param: Option<&str>,
+ message: String,
+) -> Response {
+ GatewayOwnedFault::new(stage)
+ .mark((status, Json(embeddings_error(code, param, message))).into_response())
+}
+
+/// Is this `axum::Error` the length-limit condition rather than a broken stream?
+///
+/// `to_bytes` boxes `LengthLimitError` behind `axum::Error`, so the discriminator
+/// is only reachable by walking the source chain. Matching on the Display string
+/// would work today and rot silently on any upstream wording change; the downcast
+/// cannot.
+///
+/// `pub` so the managed composition's own `to_bytes` call sites reuse this exact
+/// discriminator rather than restating the downcast — the same reason the size
+/// bounds themselves are imported rather than copied.
+pub fn is_length_limit_error(error: &axum::Error) -> bool {
+ let mut source: Option<&(dyn std::error::Error + 'static)> = Some(error);
+ while let Some(current) = source {
+ if current
+ .downcast_ref::<http_body_util::LengthLimitError>()
+ .is_some()
+ {
+ return true;
+ }
+ source = std::error::Error::source(current);
+ }
+ false
+}
+
+/// The largest [`native_request_body_limit`] across every native endpoint —
+/// the bound an envelope that can carry ANY of them must buffer to.
+///
+/// `dead_code`-allowed because the `sie-gateway` BINARY compiles this module
+/// tree independently of the library (see the note in `lib.rs`), and only the
+/// downstream composition crate reads this constant.
+#[allow(dead_code)]
+pub const MAX_NATIVE_REQUEST_BODY: usize = {
+ let generate_or_proxy = if MAX_GENERATE_BODY > MAX_PROXY_BODY {
+ MAX_GENERATE_BODY
+ } else {
+ MAX_PROXY_BODY
+ };
+ if MAX_EXTRACT_BODY > generate_or_proxy {
+ MAX_EXTRACT_BODY
+ } else {
+ generate_or_proxy
+ }
+};
static GATEWAY_VERSION_MINOR: std::sync::LazyLock<u32> =
std::sync::LazyLock::new(|| env!("CARGO_PKG_VERSION_MINOR").parse().unwrap_or(0));
@@ -111,6 +350,12 @@ const BACKPRESSURE_RETRY_AFTER: &str = RetryAfter::DEFAULT.backpressure;
const GATEWAY_TIMEOUT_RETRY_AFTER: &str = RetryAfter::DEFAULT.gateway_timeout;
const MODEL_LOADING_RETRY_AFTER: &str = RetryAfter::DEFAULT.model_loading;
const MODEL_LOADING_ERROR_CODE: &str = "MODEL_LOADING";
+/// Sealed cold-start wake quota refused (#2426): the org exceeded its
+/// cold-starts-per-hour ceiling, so the dispatcher declined to buy a wake.
+/// A deliberate quota refusal, surfaced as 429 — terminal, and deliberately
+/// absent from the retryable lists: an hourly quota must not invite SDK
+/// auto-retry storms the way MODEL_LOADING's short Retry-After does.
+const COLD_START_RATE_LIMITED_ERROR_CODE: &str = "COLD_START_RATE_LIMITED";
/// Server-side OOM recovery exhausted. Workers stamp this on
/// ``WorkResult.error_code`` when the per-batch ``cache_clear → evict_lru
/// → split_batch`` strategy still runs out of GPU memory; the gateway
@@ -1091,9 +1336,17 @@ pub async fn proxy_generate(state: State<Arc<AppState>>, req: Request) -> impl I
/// inline code produced — model-not-found 404, bundle-routing-conflict 409, or
/// the unknown-model 404 when the registry is populated. With an empty registry
/// it falls back to the caller's bundle override (or `"default"`).
+///
+/// `requested` is the string the CALLER sent; `model_name` is what it resolved
+/// to. The unknown-model 404 echoes `requested`, never `model_name` (#2542): a
+/// resolved id can be a registry alias's target, and a 404 that names it hands
+/// 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.
fn resolve_bundle_for_request(
registry: &ModelRegistry,
model_name: &str,
+ requested: &str,
bundle_override: &str,
engine_pin: Option<&str>,
endpoint: &str,
@@ -1147,7 +1400,7 @@ fn resolve_bundle_for_request(
oai_type::MODEL_NOT_FOUND,
oai_code::MODEL_NOT_FOUND,
Some("model"),
- format!("Model '{}' not found", model_name),
+ format!("Model '{}' not found", requested),
)));
} else if bundle_override.is_empty() {
"default".to_string()
@@ -1174,12 +1427,93 @@ struct ProfilePoolRoute {
/// their exact status / code / param wire shape; this enum only carries the
/// labels both callers need for the rejection metric.
enum ProfilePoolError {
+ /// A caller-supplied routing header is not valid UTF-8.
+ InvalidHeader { header: &'static str },
/// Caller-supplied pool failed the strict `[A-Za-z0-9_-]` allowlist.
InvalidPool,
/// Model is assigned to a different pool than the request targeted.
PoolMismatch { message: String },
}
+/// Parse only caller-supplied profile/pool overrides.
+///
+/// Deployment-governed generation uses this raw override view to validate a
+/// caller pin against the exact compiled route. Registry-driven routing calls
+/// [`resolve_profile_and_pool`] below, which additionally applies the model's
+/// default pool. Keeping those steps separate prevents an absent header from
+/// being mistaken for an explicit request that conflicts with desired state.
+fn parse_profile_and_pool_overrides(
+ state: &AppState,
+ headers: &HeaderMap,
+) -> Result<ProfilePoolRoute, ProfilePoolError> {
+ let mut gpu = match headers.get("x-sie-machine-profile") {
+ Some(value) => {
+ value
+ .to_str()
+ .map(str::to_owned)
+ .map_err(|_| ProfilePoolError::InvalidHeader {
+ header: "X-SIE-MACHINE-PROFILE",
+ })?
+ }
+ None => String::new(),
+ };
+ let mut pool_name = match headers.get("x-sie-pool") {
+ Some(value) => {
+ value
+ .to_str()
+ .map(str::to_owned)
+ .map_err(|_| ProfilePoolError::InvalidHeader {
+ header: "X-SIE-Pool",
+ })?
+ }
+ None => String::new(),
+ };
+
+ // Parse pool from GPU param (e.g., "eval-l4/l4").
+ if let Some((inline_pool, inline_gpu)) = gpu
+ .split_once('/')
+ .map(|(pool, profile)| (pool.to_string(), profile.to_string()))
+ {
+ if inline_pool.is_empty() || inline_gpu.is_empty() {
+ return Err(ProfilePoolError::InvalidPool);
+ }
+ if !pool_name.is_empty() && !pool_name.eq_ignore_ascii_case(&inline_pool) {
+ return Err(ProfilePoolError::PoolMismatch {
+ message: format!(
+ "X-SIE-Pool '{}' conflicts with pool '{}' in X-SIE-MACHINE-PROFILE",
+ pool_name, inline_pool
+ ),
+ });
+ }
+ pool_name = inline_pool;
+ gpu = inline_gpu;
+ }
+
+ if !pool_name.is_empty() && !is_valid_pool_name(&pool_name) {
+ return Err(ProfilePoolError::InvalidPool);
+ }
+ if !pool_name.is_empty() {
+ pool_name = normalize_pool_name(&pool_name);
+ }
+
+ if !gpu.is_empty() {
+ gpu = resolve_machine_profile(&gpu, &state.config.gpu_profile_map);
+ }
+
+ let gpu_configured = gpu.is_empty()
+ || state
+ .config
+ .configured_gpus
+ .iter()
+ .any(|configured| configured.eq_ignore_ascii_case(&gpu));
+
+ Ok(ProfilePoolRoute {
+ gpu,
+ pool_name,
+ gpu_configured,
+ })
+}
+
/// Resolve the machine-profile + pool routing carried by the request headers.
///
/// Parses `X-SIE-MACHINE-PROFILE` (optionally a combined
@@ -1198,32 +1532,11 @@ async fn resolve_profile_and_pool(
headers: &HeaderMap,
model_name: &str,
) -> Result<ProfilePoolRoute, ProfilePoolError> {
- // Parse GPU from X-SIE-MACHINE-PROFILE header
- let mut gpu = headers
- .get("x-sie-machine-profile")
- .and_then(|v| v.to_str().ok())
- .unwrap_or("")
- .to_string();
-
- let mut pool_name = headers
- .get("x-sie-pool")
- .and_then(|v| v.to_str().ok())
- .unwrap_or("")
- .to_string();
-
- // Parse pool from GPU param (e.g., "eval-l4/l4")
- if !gpu.is_empty() && gpu.contains('/') {
- let parts: Vec<&str> = gpu.splitn(2, '/').collect();
- pool_name = parts[0].to_string();
- gpu = parts[1].to_string();
- }
-
- if !pool_name.is_empty() && !is_valid_pool_name(&pool_name) {
- return Err(ProfilePoolError::InvalidPool);
- }
- if !pool_name.is_empty() {
- pool_name = normalize_pool_name(&pool_name);
- }
+ let ProfilePoolRoute {
+ gpu,
+ mut pool_name,
+ gpu_configured,
+ } = parse_profile_and_pool_overrides(state, headers)?;
let model_pool = state.model_registry.get_model_pool_name(model_name);
if let Err(message) = apply_model_pool_default(
@@ -1236,23 +1549,6 @@ async fn resolve_profile_and_pool(
return Err(ProfilePoolError::PoolMismatch { message });
}
- // Resolve bare GPU to its configured canonical profile. An empty catalog
- // is fail-closed: it never turns arbitrary caller input into a routable or
- // scale-driving machine profile.
- if !gpu.is_empty() {
- gpu = resolve_machine_profile(&gpu, &state.config.gpu_profile_map);
- }
-
- // Validate GPU is configured. Compute this *before* tagging the metric
- // label slot so an arbitrary, unconfigured, caller-supplied GPU never
- // reaches a Prometheus label (unbounded cardinality / DoS).
- let gpu_configured = gpu.is_empty()
- || state
- .config
- .configured_gpus
- .iter()
- .any(|cg| cg.eq_ignore_ascii_case(&gpu));
-
Ok(ProfilePoolRoute {
gpu,
pool_name,
@@ -1260,10 +1556,182 @@ async fn resolve_profile_and_pool(
})
}
+fn governed_generation_route_failure(
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+ detail: &str,
+) -> Response {
+ error!(
+ customer_model,
+ intent = ?intent,
+ detail,
+ "deployment-governed generation route is unavailable"
+ );
+ (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(json_openai_error(
+ "Generation route is unavailable for this deployment".to_string(),
+ oai_type::SERVER_ERROR,
+ None,
+ oai_code::TRANSPORT_FAILURE,
+ )),
+ )
+ .into_response()
+}
+
+/// Resolve the optional deployment-owned generation route.
+///
+/// `None` means the OSS composition installed no policy. Once a policy is
+/// present, every model/intent pair must resolve and the returned route must be
+/// self-consistent; any miss or drift fails closed instead of falling back to
+/// registry insertion order or a sibling GPU lane.
+#[allow(clippy::result_large_err)]
+fn governed_generation_route(
+ state: &AppState,
+ customer_model: &str,
+ dispatch_model: &str,
+ intent: GenerationRequestIntent,
+) -> Result<Option<GovernedGenerationRoute>, Response> {
+ let Some(policy) = state
+ .model_access_policy
+ .as_deref()
+ .and_then(ModelAccessPolicy::generation_route_policy)
+ else {
+ return Ok(None);
+ };
+ let Some(route) = policy.resolve(customer_model, intent) else {
+ return Err(governed_generation_route_failure(
+ customer_model,
+ intent,
+ "missing model/intent mapping",
+ ));
+ };
+ if route.model != dispatch_model {
+ return Err(governed_generation_route_failure(
+ customer_model,
+ intent,
+ "compiled physical model disagrees with registry intent rewrite",
+ ));
+ }
+ if route.bundle.trim().is_empty()
+ || route.pool.trim().is_empty()
+ || route.machine_profile.trim().is_empty()
+ {
+ return Err(governed_generation_route_failure(
+ customer_model,
+ intent,
+ "route contains an empty physical coordinate",
+ ));
+ }
+ if !state
+ .config
+ .configured_gpus
+ .iter()
+ .any(|configured| configured.eq_ignore_ascii_case(&route.machine_profile))
+ {
+ return Err(governed_generation_route_failure(
+ customer_model,
+ intent,
+ "route machine profile is absent from the configured GPU catalog",
+ ));
+ }
+ Ok(Some(route))
+}
+
+/// Validate caller overrides against one exact deployment-owned route.
+///
+/// An omitted header adopts the governed coordinate. An explicit, conflicting
+/// header is a client error; it never causes a registry search that could pick
+/// a sibling lane for the same model.
+#[allow(clippy::result_large_err)]
+fn governed_profile_and_pool(
+ state: &AppState,
+ headers: &HeaderMap,
+ route: &GovernedGenerationRoute,
+) -> Result<ProfilePoolRoute, Response> {
+ let overrides = match parse_profile_and_pool_overrides(state, headers) {
+ Ok(overrides) => overrides,
+ Err(ProfilePoolError::InvalidHeader { header }) => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ format!("{header} header must be valid UTF-8"),
+ oai_type::INVALID_REQUEST,
+ Some(header),
+ oai_code::INVALID_REQUEST,
+ )),
+ )
+ .into_response());
+ }
+ Err(ProfilePoolError::InvalidPool) => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ "Invalid pool name: only [A-Za-z0-9_-] are allowed (max 128 chars)".to_string(),
+ oai_type::INVALID_REQUEST,
+ Some("X-SIE-Pool"),
+ oai_code::INVALID_REQUEST,
+ )),
+ )
+ .into_response());
+ }
+ Err(ProfilePoolError::PoolMismatch { message }) => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ message,
+ oai_type::INVALID_REQUEST,
+ Some("X-SIE-Pool"),
+ oai_code::INVALID_REQUEST,
+ )),
+ )
+ .into_response());
+ }
+ };
+
+ if !overrides.pool_name.is_empty() && !overrides.pool_name.eq_ignore_ascii_case(&route.pool) {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ format!(
+ "X-SIE-Pool '{}' conflicts with the deployment route for this model",
+ overrides.pool_name
+ ),
+ oai_type::INVALID_REQUEST,
+ Some("X-SIE-Pool"),
+ oai_code::INVALID_REQUEST,
+ )),
+ )
+ .into_response());
+ }
+ if !overrides.gpu.is_empty() && !overrides.gpu.eq_ignore_ascii_case(&route.machine_profile) {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ format!(
+ "X-SIE-MACHINE-PROFILE '{}' conflicts with the deployment route for this model",
+ overrides.gpu
+ ),
+ oai_type::INVALID_REQUEST,
+ Some("X-SIE-MACHINE-PROFILE"),
+ oai_code::INVALID_REQUEST,
+ )),
+ )
+ .into_response());
+ }
+
+ Ok(ProfilePoolRoute {
+ gpu: route.machine_profile.clone(),
+ pool_name: route.pool.clone(),
+ gpu_configured: true,
+ })
+}
+
/// The routing decision for a request: canonical model name, serving bundle,
/// and engine. Produced by [`resolve_routing`].
struct RoutingResult {
model_name: String,
+ dispatch_model: String,
bundle: String,
engine: String,
gpu: String,
@@ -1284,6 +1752,7 @@ async fn resolve_routing(
ext: &axum::http::Extensions,
path: &str,
endpoint: &str,
+ generation_intent: Option<GenerationRequestIntent>,
) -> Result<RoutingResult, Box<Response>> {
// Extract model from path: /v1/{endpoint}/{model...}
let prefix = format!("/v1/{}/", endpoint);
@@ -1327,6 +1796,14 @@ async fn resolve_routing(
// for an unknown model — so there is no cross-org existence oracle. Decided on
// the RESOLVED id (alias/`__`/case already folded), so the gate can never
// diverge from the dispatcher. No-op in OSS self-host (policy is None).
+ //
+ // The body echoes the CALLER's string and uses the unknown-model template
+ // verbatim (#2542). Rendering `model_name` here was a naming oracle: an
+ // operator alias whose target sits in another org's reserved namespace made
+ // `POST /v1/encode/<alias>` answer with that org's custom-model id, to a
+ // caller who owns nothing. It also gave the refusal its own wording, which
+ // by itself distinguished "hidden from you" from "does not exist" — the one
+ // thing this 404 exists to prevent.
if state
.model_access_policy
.as_ref()
@@ -1339,9 +1816,25 @@ async fn resolve_routing(
oai_type::MODEL_NOT_FOUND,
oai_code::MODEL_NOT_FOUND,
Some("model"),
- format!("Model not found: {model_name}"),
+ format!("Model '{}' not found", 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
+ // licence exclusion). It runs HERE, not only at the edge, because an edge
+ // gate compares the caller's raw string and a registry ALIAS can point that
+ // string at a refused model — post-resolution is the only place the refusal
+ // sees what will actually dispatch. Ordered after the visibility gate so the
+ // no-oracle 404 still wins, and before the sealed branch so a refused model
+ // cannot reach a lane. The policy owns the whole response (status, code,
+ // envelope). No-op in OSS self-host (policy is None / default `None`).
+ if let Some(refusal) = state
+ .model_access_policy
+ .as_ref()
+ .and_then(|p| p.serving_refusal(&model_name, ext))
+ {
+ return Err(Box::new(refusal));
+ }
// #1841 bundle-less sealed dispatch: an org-registered custom model is served
// from its own sealed sandbox, not a catalog bundle, so there is no bundle to
// resolve — the normal path below would dead-end at MODEL_NOT_FOUND. The
@@ -1358,6 +1851,7 @@ async fn resolve_routing(
{
debug_assert_eq!(route.engine, "sealed");
return Ok(RoutingResult {
+ dispatch_model: model_name.clone(),
model_name,
bundle: route.bundle,
engine: route.engine,
@@ -1401,23 +1895,79 @@ async fn resolve_routing(
}
};
- // Try model registry resolution. Three cases:
- // 1. Model is known → resolve bundle (404 on BundleConflict, etc.)
- // 2. Model unknown, registry populated → 404 (fail fast; avoids queueing
- // requests for typo'd model ids).
- // 3. Model unknown, registry empty → fall back to caller's bundle
- // override or "default". This is the pre-bootstrap / no-config
- // deployment path; workers may still match on bundle+gpu alone.
- let bundle = resolve_bundle_for_request(
- &state.model_registry,
- &model_name,
- &bundle_override,
- engine_pin.as_deref(),
- endpoint,
- )?;
+ let mut dispatch_model = model_name.clone();
+ if generation_intent == Some(GenerationRequestIntent::Grammar) {
+ route_grammar_to_profile(&state.model_registry, &mut dispatch_model);
+ }
+ let governed_route = if let Some(intent) = generation_intent {
+ match governed_generation_route(state, &model_name, &dispatch_model, intent) {
+ Ok(route) => route,
+ Err(response) => return Err(Box::new(response)),
+ }
+ } else {
+ None
+ };
- let engine = state
- .model_registry
+ if let Some(route) = governed_route.as_ref() {
+ if !bundle_override.is_empty() && bundle_override != route.bundle {
+ return Err(Box::new(
+ (
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ format!(
+ "Bundle override '{}' conflicts with the deployment route for this model",
+ bundle_override
+ ),
+ oai_type::INVALID_REQUEST,
+ Some("model"),
+ oai_code::INVALID_REQUEST,
+ )),
+ )
+ .into_response(),
+ ));
+ }
+ match state
+ .model_registry
+ .resolve_bundle(&route.model, Some(&route.bundle))
+ {
+ Ok(resolved) if resolved == route.bundle => {}
+ _ => {
+ return Err(Box::new(governed_generation_route_failure(
+ &model_name,
+ generation_intent.expect("governed generation has request intent"),
+ "compiled bundle is incompatible with the physical model",
+ )));
+ }
+ }
+ }
+
+ // Try model registry resolution. Three cases:
+ // 1. Model is known → resolve bundle (404 on BundleConflict, etc.)
+ // 2. Model unknown, registry populated → 404 (fail fast; avoids queueing
+ // requests for typo'd model ids).
+ // 3. Model unknown, registry empty → fall back to caller's bundle
+ // override or "default". This is the pre-bootstrap / no-config
+ // deployment path; workers may still match on bundle+gpu alone.
+ let bundle_model = governed_route
+ .as_ref()
+ .map_or(model_name.as_str(), |route| route.model.as_str());
+ let effective_bundle_override = governed_route
+ .as_ref()
+ .map_or(bundle_override.as_str(), |route| route.bundle.as_str());
+ let bundle = resolve_bundle_for_request(
+ &state.model_registry,
+ bundle_model,
+ // The CALLER's string, for the not-found body only (#2542) — never the
+ // resolved/governed id, which can be an alias target in another org's
+ // reserved namespace.
+ &model,
+ effective_bundle_override,
+ engine_pin.as_deref(),
+ endpoint,
+ )?;
+
+ let engine = state
+ .model_registry
.get_bundle_info(&bundle)
.map(|info| info.engine)
.or_else(|| engine_pin.clone())
@@ -1430,34 +1980,53 @@ async fn resolve_routing(
gpu,
pool_name,
gpu_configured,
- } = match resolve_profile_and_pool(state, headers, &model_name).await {
- Ok(route) => route,
- Err(ProfilePoolError::InvalidPool) => {
- return Err(Box::new(endpoint_error_response(
- endpoint,
- StatusCode::BAD_REQUEST,
- err_code::INVALID_REQUEST,
- oai_type::INVALID_REQUEST,
- oai_code::INVALID_REQUEST,
- Some("pool"),
- "Invalid pool name: only [A-Za-z0-9_-] are allowed (max 128 chars)",
- )));
+ } = if let Some(route) = governed_route.as_ref() {
+ match governed_profile_and_pool(state, headers, route) {
+ Ok(route) => route,
+ Err(response) => return Err(Box::new(response)),
}
- Err(ProfilePoolError::PoolMismatch { message }) => {
- return Err(Box::new(endpoint_error_response(
- endpoint,
- StatusCode::BAD_REQUEST,
- err_code::INVALID_REQUEST,
- oai_type::INVALID_REQUEST,
- oai_code::INVALID_REQUEST,
- Some("pool"),
- message,
- )));
+ } else {
+ match resolve_profile_and_pool(state, headers, &model_name).await {
+ Ok(route) => route,
+ Err(ProfilePoolError::InvalidHeader { header }) => {
+ return Err(Box::new(endpoint_error_response(
+ endpoint,
+ StatusCode::BAD_REQUEST,
+ err_code::INVALID_REQUEST,
+ oai_type::INVALID_REQUEST,
+ oai_code::INVALID_REQUEST,
+ Some(header),
+ format!("{header} header must be valid UTF-8"),
+ )));
+ }
+ Err(ProfilePoolError::InvalidPool) => {
+ return Err(Box::new(endpoint_error_response(
+ endpoint,
+ StatusCode::BAD_REQUEST,
+ err_code::INVALID_REQUEST,
+ oai_type::INVALID_REQUEST,
+ oai_code::INVALID_REQUEST,
+ Some("pool"),
+ "Invalid pool name: only [A-Za-z0-9_-] are allowed (max 128 chars)",
+ )));
+ }
+ Err(ProfilePoolError::PoolMismatch { message }) => {
+ return Err(Box::new(endpoint_error_response(
+ endpoint,
+ StatusCode::BAD_REQUEST,
+ err_code::INVALID_REQUEST,
+ oai_type::INVALID_REQUEST,
+ oai_code::INVALID_REQUEST,
+ Some("pool"),
+ message,
+ )));
+ }
}
};
Ok(RoutingResult {
model_name,
+ dispatch_model,
bundle,
engine,
gpu,
@@ -1468,7 +2037,7 @@ async fn resolve_routing(
pub(crate) async fn proxy_request(
State(state): State<Arc<AppState>>,
- req: Request,
+ mut req: Request,
endpoint: &str,
) -> Response {
// SDK version skew detection
@@ -1516,8 +2085,59 @@ pub(crate) async fn proxy_request(
Some(managed_request_parent(&req))
};
+ // Native generation routing depends on request intent (default vs grammar),
+ // including in the no-policy OSS composition where grammar selects a
+ // profile-qualified model. Inspect the bounded body once before worker
+ // lookup and preserve the typed parse for the dispatch driver.
+ let mut governed_generate_body = None;
+ let mut governed_generate_parsed = None;
+ let generation_intent = if endpoint == "generate" {
+ let is_msgpack = req
+ .headers()
+ .get("content-type")
+ .and_then(|value| value.to_str().ok())
+ .is_some_and(|content_type| content_type.contains("msgpack"));
+ let (parts, body) = req.into_parts();
+ let body_bytes = match axum::body::to_bytes(body, MAX_GENERATE_BODY).await {
+ Ok(body) => body,
+ Err(error) => {
+ warn!(error = %error, limit = MAX_GENERATE_BODY, "request body too large or read error");
+ return endpoint_error_response(
+ endpoint,
+ StatusCode::PAYLOAD_TOO_LARGE,
+ err_code::PAYLOAD_TOO_LARGE,
+ oai_type::INVALID_REQUEST,
+ oai_code::INVALID_REQUEST,
+ None,
+ format!("Request body too large (max {} bytes)", MAX_GENERATE_BODY),
+ );
+ }
+ };
+ req = Request::from_parts(parts, Body::empty());
+ let (items, params) = match parse_queue_request(&body_bytes, is_msgpack, endpoint) {
+ Ok(parsed) => parsed,
+ Err(error) => return queue_parse_error_response(endpoint, error),
+ };
+ let intent = if params
+ .generate
+ .as_ref()
+ .and_then(|generate| generate.grammar.as_ref())
+ .is_some()
+ {
+ GenerationRequestIntent::Grammar
+ } else {
+ GenerationRequestIntent::Default
+ };
+ governed_generate_body = Some(body_bytes);
+ governed_generate_parsed = Some((items, params));
+ Some(intent)
+ } else {
+ None
+ };
+
let RoutingResult {
model_name,
+ dispatch_model,
bundle,
engine,
gpu,
@@ -1529,6 +2149,7 @@ pub(crate) async fn proxy_request(
req.extensions(),
req.uri().path(),
endpoint,
+ generation_intent,
)
.await
{
@@ -1600,7 +2221,7 @@ pub(crate) async fn proxy_request(
let (bundle_config_hash, model_revision) =
state
.model_registry
- .bundle_execution_evidence(&bundle, &hash_pool, &model_name);
+ .bundle_execution_evidence(&bundle, &hash_pool, &dispatch_model);
// Resolve the effective pool in one shot. `resolve_effective_pool`
// folds the demand-tracking probe ("was there an exact
@@ -1732,24 +2353,24 @@ pub(crate) async fn proxy_request(
// (encode / score) get the same text-appropriate 16 MiB cap as the
// chat / embeddings paths. Extract accepts bounded binary media, so
// its cap covers the maximum legal audio after JSON base64 expansion.
- let body_limit = match endpoint {
- "generate" => MAX_GENERATE_BODY,
- "extract" => MAX_EXTRACT_BODY,
- _ => MAX_PROXY_BODY,
- };
- let body_bytes = match axum::body::to_bytes(req.into_body(), body_limit).await {
- Ok(b) => b,
- Err(e) => {
- warn!(error = %e, limit = body_limit, "request body too large or read error");
- return endpoint_error_response(
- endpoint,
- StatusCode::PAYLOAD_TOO_LARGE,
- err_code::PAYLOAD_TOO_LARGE,
- oai_type::INVALID_REQUEST,
- oai_code::INVALID_REQUEST,
- None,
- format!("Request body too large (max {} bytes)", body_limit),
- );
+ let body_limit = native_request_body_limit(endpoint);
+ let body_bytes = if let Some(body) = governed_generate_body {
+ body
+ } else {
+ match axum::body::to_bytes(req.into_body(), body_limit).await {
+ Ok(b) => b,
+ Err(e) => {
+ warn!(error = %e, limit = body_limit, "request body too large or read error");
+ return endpoint_error_response(
+ endpoint,
+ StatusCode::PAYLOAD_TOO_LARGE,
+ err_code::PAYLOAD_TOO_LARGE,
+ oai_type::INVALID_REQUEST,
+ oai_code::INVALID_REQUEST,
+ None,
+ format!("Request body too large (max {} bytes)", body_limit),
+ );
+ }
}
};
@@ -1758,12 +2379,14 @@ pub(crate) async fn proxy_request(
Arc::clone(work_publisher),
endpoint,
&model_name,
+ &dispatch_model,
&bundle,
&engine,
effective_machine_profile,
effective_pool,
&admission_pool,
&body_bytes,
+ governed_generate_parsed,
is_msgpack_in,
use_msgpack_out,
&token_id,
@@ -1841,11 +2464,27 @@ fn managed_request_parent(req: &Request) -> opentelemetry::Context {
/// harvested from the registry snapshot — route resolution filters out
/// empty pool names and machine profiles). We therefore don't need to
/// re-query the registry inside this function.
+fn queue_parse_error_response(endpoint: &str, error: QueueParseError) -> Response {
+ match error {
+ QueueParseError::Generic(message) => endpoint_error_response(
+ endpoint,
+ StatusCode::BAD_REQUEST,
+ err_code::INVALID_REQUEST,
+ oai_type::INVALID_REQUEST,
+ oai_code::INVALID_REQUEST,
+ None,
+ format!("Failed to parse request body: {message}"),
+ ),
+ QueueParseError::PreBuilt(response) => response,
+ }
+}
+
#[allow(clippy::too_many_arguments)]
async fn queue_mode_proxy(
state: &AppState,
work_publisher: Arc<dyn WorkDispatcher>,
endpoint: &str,
+ display_model: &str,
model: &str,
bundle: &str,
engine: &str,
@@ -1853,6 +2492,7 @@ async fn queue_mode_proxy(
pool: &str,
admission_pool: &str,
body_bytes: &[u8],
+ preparsed: Option<(Vec<rmpv::Value>, publisher::WorkParams)>,
is_msgpack_in: bool,
use_msgpack_out: bool,
token_id: &str,
@@ -1864,26 +2504,12 @@ async fn queue_mode_proxy(
physical_lane: &PhysicalLane,
) -> Response {
// Parse body once, extract items + params (avoids double parse)
- let (items, params) = match parse_queue_request(body_bytes, is_msgpack_in, endpoint) {
- Ok(r) => r,
- Err(QueueParseError::Generic(e)) => {
- return endpoint_error_response(
- endpoint,
- StatusCode::BAD_REQUEST,
- err_code::INVALID_REQUEST,
- oai_type::INVALID_REQUEST,
- oai_code::INVALID_REQUEST,
- None,
- format!("Failed to parse request body: {}", e),
- );
- }
- Err(QueueParseError::PreBuilt(resp)) => {
- // The pre-built path is currently grammar-only
- // — surface a precise rejection reason so dashboards can
- // separate it from generic body-parse failures. Future
- // pre-built paths should pick their own reason code.
- return resp;
- }
+ let (items, params) = match preparsed {
+ Some(parsed) => parsed,
+ None => match parse_queue_request(body_bytes, is_msgpack_in, endpoint) {
+ Ok(parsed) => parsed,
+ Err(error) => return queue_parse_error_response(endpoint, error),
+ },
};
if items.is_empty() && endpoint != "score" && endpoint != "generate" {
@@ -1927,34 +2553,6 @@ async fn queue_mode_proxy(
.into_response();
}
- // Grammar routing: a grammar-constrained generate request runs on the
- // model's declared non-speculative ``grammar_profile`` variant (see
- // ``route_grammar_to_profile``). Resolve it HERE — before the capability and
- // profile-scoped LoRA gates below and the dispatch — and shadow ``model`` so
- // every gate validates against, and the work item dispatches to, the profile
- // the request will actually execute on. Non-generate / non-grammar requests
- // leave ``model`` unchanged (no allocation).
- let routed_model: Option<String> = if endpoint == "generate"
- && params
- .generate
- .as_ref()
- .and_then(|p| p.grammar.as_ref())
- .is_some()
- {
- let mut routed = model.to_string();
- route_grammar_to_profile(&state.model_registry, &mut routed);
- Some(routed)
- } else {
- None
- };
- // Preserve the requested (base) id for the DISPLAY surfaces — response body,
- // ``record_generation_success``, audit log. ``model`` below shadows to the
- // DISPATCH id (the routed variant); only that id changes which worker-loaded
- // model serves the request (NATS subject + work item). They are equal unless
- // routing fired.
- let display_model = model.to_string();
- let model: &str = routed_model.as_deref().unwrap_or(model);
-
// Grammar capability gate. After ``parse_grammar`` has accepted
// the wire shape and enforced the safety caps, check the model's
// YAML-declared ``capabilities.grammar`` list. Rejecting here (not
@@ -1971,8 +2569,7 @@ async fn queue_mode_proxy(
// Look the capabilities up on the DISPATCH variant, but name the
// requested (DISPLAY) model in the rejection so the client never
// sees the internal ``:no-spec`` id (mirrors the chat path).
- if let Err(resp) = super::grammar::check_capability(g, caps.as_deref(), &display_model)
- {
+ if let Err(resp) = super::grammar::check_capability(g, caps.as_deref(), display_model) {
return resp;
}
}
@@ -2071,43 +2668,29 @@ async fn queue_mode_proxy(
)
.into_response();
};
- // Streaming branch — when the SIE-native generate body carries
- // `stream: true`, switch to the SSE response builder. The body
- // was already parsed once above; we re-decode the small
- // `stream` flag here rather than thread a new parameter
- // through `parse_queue_request` (which is shared with
- // encode/score/extract, where `stream` has no meaning).
- // The reject-on-bad-type path is handled here too: an unparsable
- // body falls back to the existing non-streaming code path,
- // which surfaces the same 400 as before.
- let stream_flag = stream_flag_from_body(body_bytes, is_msgpack_in);
- match stream_flag {
- Ok(true) => {
- return super::sse::build_sse_response(super::sse::SseParams {
- state,
- work_publisher: work_publisher_arc,
- physical_lane: physical_lane.clone(),
- model: display_model.clone(),
- dispatch_model: model.to_string(),
- bundle: bundle.to_string(),
- engine: engine.to_string(),
- gpu: gpu.to_string(),
- pool: pool.to_string(),
- admission_pool: admission_pool.to_string(),
- bundle_config_hash: bundle_config_hash.to_string(),
- work_params: params,
- endpoint: super::sse::SseEndpoint::Generate,
- })
- .await;
- }
- Ok(false) => {}
- Err(resp) => return resp,
+ if params.generate.as_ref().is_some_and(|params| params.stream) {
+ return super::sse::build_sse_response(super::sse::SseParams {
+ state,
+ work_publisher: work_publisher_arc,
+ physical_lane: physical_lane.clone(),
+ model: display_model.to_string(),
+ dispatch_model: model.to_string(),
+ bundle: bundle.to_string(),
+ engine: engine.to_string(),
+ gpu: gpu.to_string(),
+ pool: pool.to_string(),
+ admission_pool: admission_pool.to_string(),
+ bundle_config_hash: bundle_config_hash.to_string(),
+ work_params: params,
+ endpoint: super::sse::SseEndpoint::Generate,
+ })
+ .await;
}
return queue_mode_streaming_generate(
state,
work_publisher_arc,
physical_lane,
- display_model.as_str(),
+ display_model,
model,
bundle,
engine,
@@ -2831,6 +3414,31 @@ pub(crate) enum StreamingDriverErr {
},
}
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum FirstChunkDeadlineAction {
+ RepublishToPool,
+ WaitForOverall,
+ SurfaceTimeout,
+}
+
+pub(crate) fn first_chunk_deadline_action(
+ supports_pool_republish: bool,
+ was_direct_dispatched: bool,
+ republish_already_attempted: bool,
+ single_consumer_lane_at_dispatch: bool,
+) -> FirstChunkDeadlineAction {
+ if !supports_pool_republish {
+ return FirstChunkDeadlineAction::WaitForOverall;
+ }
+ if was_direct_dispatched && !republish_already_attempted && !single_consumer_lane_at_dispatch {
+ return FirstChunkDeadlineAction::RepublishToPool;
+ }
+ if was_direct_dispatched && !republish_already_attempted && single_consumer_lane_at_dispatch {
+ return FirstChunkDeadlineAction::WaitForOverall;
+ }
+ FirstChunkDeadlineAction::SurfaceTimeout
+}
+
/// Streaming driver: publish a generate work item, wait
/// for a terminal aggregated :class:`StreamOutcome` under the three-tier
/// timeout taxonomy, and propagate cancel signals on client disconnect.
@@ -3030,6 +3638,7 @@ pub(crate) async fn run_streaming_generate(
// `republished` field on `StreamCollector`) so the two paths
// cannot double-publish.
let mut republished_for_first_chunk = false;
+ let supports_first_chunk_pool_republish = work_publisher.supports_first_chunk_pool_republish();
// Capture the exact pool-fallback lane size at dispatch time so
// the H9 single-worker suppression below is scoped to
// `(pool,machine_profile,bundle)` and still counts healthy cold
@@ -3095,10 +3704,13 @@ pub(crate) async fn run_streaming_generate(
// the original attempt gets the legitimate end-to-end
// budget; if the worker really is dead the
// overall_timeout path will surface that.
- if was_direct_dispatched
- && !republished_for_first_chunk
- && !single_consumer_lane_at_dispatch
- {
+ let deadline_action = first_chunk_deadline_action(
+ supports_first_chunk_pool_republish,
+ was_direct_dispatched,
+ republished_for_first_chunk,
+ single_consumer_lane_at_dispatch,
+ );
+ if deadline_action == FirstChunkDeadlineAction::RepublishToPool {
republished_for_first_chunk = true;
// At-least-once-execution hazard: the original
// direct-dispatched worker may simply be SLOW (cold
@@ -3146,26 +3758,21 @@ pub(crate) async fn run_streaming_generate(
}
}
}
- if single_consumer_lane_at_dispatch
- && was_direct_dispatched
- && !republished_for_first_chunk
- {
- // Single-worker fallback skip: don't surface
- // first_chunk_timeout to the client — the only worker
- // is the one we're already waiting on, and the
- // overall_timeout path will catch a genuinely dead
- // worker. Mark republished so this branch doesn't
- // re-trigger on subsequent ticks, and push the
- // first_chunk_deadline to the overall_deadline so
- // tokio's select arm at line ~1824 stops firing.
+ if deadline_action == FirstChunkDeadlineAction::WaitForOverall {
+ // A single-worker NATS lane has no alternate worker, and a
+ // dispatcher may declare that it has no safe retained
+ // payload / pool fallback at all. In either case, keep the
+ // original attempt alive for its governed overall budget.
+ // No cancel is sent at the first-chunk boundary.
republished_for_first_chunk = true;
first_chunk_deadline = overall_deadline;
tracing::debug!(
- request_id = %request_id,
- pool = %pool,
- machine_profile = %gpu,
- bundle = %bundle,
- "first_chunk_timeout - single-worker lane, suppressing republish; continuing on overall_timeout"
+ request_id = %request_id,
+ pool = %pool,
+ machine_profile = %gpu,
+ bundle = %bundle,
+ supports_pool_republish = supports_first_chunk_pool_republish,
+ "first_chunk_timeout - pool republish unavailable; continuing on overall_timeout"
);
continue;
}
@@ -3330,6 +3937,7 @@ pub(crate) fn worker_error_http_status(code: &str) -> StatusCode {
"transport_failure" => StatusCode::SERVICE_UNAVAILABLE,
"cancelled" => StatusCode::REQUEST_TIMEOUT,
"rate_limit_exceeded" => StatusCode::TOO_MANY_REQUESTS,
+ COLD_START_RATE_LIMITED_ERROR_CODE => StatusCode::TOO_MANY_REQUESTS,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
@@ -3343,6 +3951,7 @@ pub(crate) fn worker_error_openai_type(code: &str) -> &'static str {
}
"context_exceeded" => oai_type::CONTEXT_LENGTH_EXCEEDED,
"rate_limit_exceeded" => oai_type::RATE_LIMIT,
+ COLD_START_RATE_LIMITED_ERROR_CODE => oai_type::RATE_LIMIT,
_ => oai_type::SERVER_ERROR,
}
}
@@ -3487,6 +4096,7 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {
"transport_failure" => oai_code::TRANSPORT_FAILURE,
"cancelled" => oai_code::CANCELLED,
"rate_limit_exceeded" => oai_code::RATE_LIMIT_EXCEEDED,
+ COLD_START_RATE_LIMITED_ERROR_CODE => COLD_START_RATE_LIMITED_ERROR_CODE,
_ => "inference_error",
};
let mut body = json_openai_error(message.clone(), err_type, None, stable_code);
@@ -3506,9 +4116,13 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {
HeaderValue::from_str(request_id).unwrap_or_else(|_| HeaderValue::from_static("")),
);
// 429 responses get a ``Retry-After: 1`` header per the
- // OpenAI contract so SDKs retry with bounded backoff
- // instead of hammering the still-saturated pool.
- if status == StatusCode::TOO_MANY_REQUESTS {
+ // OpenAI contract so SDKs retry with bounded backoff instead of
+ // hammering the still-saturated pool — EXCEPT the cold-start
+ // quota refusal, whose whole point is an HOURLY ceiling: a
+ // 1-second retry hint would re-create the auto-retry hot loop
+ // the rail exists to prevent (review finding).
+ if status == StatusCode::TOO_MANY_REQUESTS && code != COLD_START_RATE_LIMITED_ERROR_CODE
+ {
resp.headers_mut().insert(
HeaderName::from_static("retry-after"),
HeaderValue::from_static("1"),
@@ -3791,6 +4405,60 @@ struct ChatRequestParams {
lora_adapter: Option<String>,
}
+impl ChatRequestParams {
+ /// The EXACT `WorkParams` a validated chat body dispatches with.
+ ///
+ /// Extracted from the handler body (not copied) so the managed
+ /// cost-estimate dry run (#2435) can derive a chat request's dispatch
+ /// params through the same mapping the live route uses. Anything that
+ /// influences the reservation ceiling — the messages, the output cap, the
+ /// `n`/`best_of` fan-out, the tool schemas, the template kwargs — is
+ /// therefore produced ONCE, and an estimate cannot drift from the price the
+ /// same body is admitted at.
+ ///
+ /// Thread the routing hints into both `GenerateParams` (where the HRW
+ /// resolver reads them) and `WorkParams` (where they were already carried
+ /// since the chat/grammar surfaces for the worker's inert hint path). Clone
+ /// is one allocation each and avoids either reader having to fall back on
+ /// the other.
+ fn into_work_params(self) -> publisher::WorkParams {
+ publisher::WorkParams {
+ generate: Some(publisher::GenerateParams {
+ input: publisher::GenerateInput::Messages {
+ messages: self.messages,
+ },
+ max_new_tokens: self.max_new_tokens,
+ temperature: self.temperature,
+ top_p: self.top_p,
+ stop: self.stop,
+ frequency_penalty: self.frequency_penalty,
+ presence_penalty: self.presence_penalty,
+ top_k: self.top_k,
+ repetition_penalty: self.repetition_penalty,
+ min_tokens: self.min_tokens,
+ chat_template_kwargs: self.chat_template_kwargs,
+ grammar: self.grammar,
+ routing_key: self.routing_key.clone(),
+ prompt_cache_key: self.prompt_cache_key.clone(),
+ tools: self.tools,
+ tool_choice: self.tool_choice,
+ parallel_tool_calls: self.parallel_tool_calls,
+ seed: self.seed,
+ logit_bias: self.logit_bias,
+ logprobs: self.logprobs,
+ top_logprobs: self.top_logprobs,
+ n: self.n,
+ best_of: self.best_of,
+ stream: self.stream,
+ lora_adapter: self.lora_adapter.clone(),
+ }),
+ routing_key: self.routing_key,
+ prompt_cache_key: self.prompt_cache_key,
+ ..Default::default()
+ }
+ }
+}
+
/// Outcome of :func:`chat_params_from_json`. Errors carry an
/// already-built OpenAI-envelope response so the caller can return
/// directly.
@@ -3800,6 +4468,32 @@ enum ChatParamsResult {
Err(Response),
}
+/// The `(model, WorkParams)` a `/v1/chat/completions` body dispatches with —
+/// the read-only seam the managed cost-estimate dry run (#2435) prices from.
+///
+/// A composition of the two pieces the live handler itself runs
+/// ([`chat_params_from_json`] then [`ChatRequestParams::into_work_params`]), so
+/// there is no second parser to keep in sync: a body the estimate prices is
+/// validated and normalized by exactly the code that would admit it. Errors are
+/// the handler's own pre-built OpenAI envelopes, so a malformed body estimates
+/// with the same status/`param`/`code` it would be rejected with.
+///
+/// `dead_code`-allowed because the `sie-gateway` BINARY compiles this module
+/// tree independently of the library (see the note in `lib.rs`), and only the
+/// downstream composition crate calls this seam.
+#[allow(clippy::result_large_err, dead_code)]
+pub fn chat_completions_dispatch_inputs(
+ body: &serde_json::Value,
+) -> Result<(String, publisher::WorkParams), Response> {
+ match chat_params_from_json(body) {
+ ChatParamsResult::Ok(params) => {
+ let model = params.model.clone();
+ Ok((model, params.into_work_params()))
+ }
+ ChatParamsResult::Err(response) => Err(response),
+ }
+}
+
/// Extract an inline OpenAI ``image_url`` value into ``(base64, format)``.
///
/// Only base64 ``data:`` URIs are accepted — the gateway never fetches
@@ -5522,8 +6216,10 @@ pub(crate) fn resolve_model_and_bundle(
};
// #1841 org-scoped visibility (mirrors resolve_routing for the OpenAI body
// routes): a custom model hidden from this caller is treated as absent — the
- // identical MODEL_NOT_FOUND 404 the block below emits — so there is no
- // cross-org existence oracle. Gates the RESOLVED id. No-op in OSS (policy None).
+ // identical MODEL_NOT_FOUND 404 the block below emits, echoing the CALLER's
+ // string under the same template so neither the id nor the wording can tell
+ // "hidden from you" apart from "does not exist" (#2542). Gates the RESOLVED
+ // id. No-op in OSS (policy None).
if state
.model_access_policy
.as_ref()
@@ -5532,7 +6228,7 @@ pub(crate) fn resolve_model_and_bundle(
return Err((
StatusCode::NOT_FOUND,
Json(json_openai_error(
- format!("Model not found: {model_name}"),
+ format!("Model '{model_spec}' not found"),
oai_type::MODEL_NOT_FOUND,
Some("model"),
oai_code::MODEL_NOT_FOUND,
@@ -5540,6 +6236,19 @@ pub(crate) fn resolve_model_and_bundle(
)
.into_response());
}
+ // #2542 deployment serving policy on the RESOLVED id (mirrors `resolve_routing`
+ // for the OpenAI body routes): the authoritative refusal for a model this
+ // deployment does not serve. Decided post-alias/`__`/case, so a registry alias
+ // pointing at a refused model cannot slip past an edge gate that only ever saw
+ // the caller's raw string. After `visible` (the no-oracle 404 wins), before the
+ // sealed branch. No-op in OSS (policy None).
+ if let Some(refusal) = state
+ .model_access_policy
+ .as_ref()
+ .and_then(|p| p.serving_refusal(&model_name, ext))
+ {
+ return Err(refusal);
+ }
// #1841 sealed dispatch (OpenAI body routes): an org-registered custom model
// has no catalog bundle, so short-circuit with the synthetic sealed bundle
// rather than dead-ending at MODEL_NOT_FOUND below. The engine/pool override
@@ -5587,7 +6296,9 @@ pub(crate) fn resolve_model_and_bundle(
return Err((
StatusCode::NOT_FOUND,
Json(json_openai_error(
- format!("Model '{model_name}' not found"),
+ // The caller's string, never the resolved one — see the
+ // visibility gate above (#2542).
+ format!("Model '{model_spec}' not found"),
oai_type::MODEL_NOT_FOUND,
Some("model"),
oai_code::MODEL_NOT_FOUND,
@@ -5607,6 +6318,7 @@ pub(crate) fn resolve_model_and_bundle(
/// publisher, plus audit fields. Produced by [`resolve_generation_route`].
struct ResolvedRoute {
physical_lane: PhysicalLane,
+ bundle: String,
gpu: String,
engine: String,
admission_pool: String,
@@ -5623,12 +6335,15 @@ struct ResolvedRoute {
/// pool (or surface an OpenAI-shaped 503 provisioning response), and bind the
/// work publisher. Shared by the chat + completions handlers; the OpenAI-shaped
/// errors are identical across both.
-#[allow(clippy::result_large_err)]
+#[allow(clippy::result_large_err, clippy::too_many_arguments)]
async fn resolve_generation_route(
state: &AppState,
hdr: &HeaderMap,
bundle: &str,
- model_name: &str,
+ customer_model: &str,
+ dispatch_model: &str,
+ request_intent: GenerationRequestIntent,
+ explicit_bundle_override: &str,
ext: &axum::http::Extensions,
metric_labels_slot: Option<&telemetry::MetricLabelsSlot>,
) -> Result<ResolvedRoute, Response> {
@@ -5645,7 +6360,45 @@ async fn resolve_generation_route(
let sealed = state
.model_access_policy
.as_ref()
- .and_then(|p| p.sealed_route(model_name, ext));
+ .and_then(|p| p.sealed_route(customer_model, ext));
+ let governed = if sealed.is_none() {
+ governed_generation_route(state, customer_model, dispatch_model, request_intent)?
+ } else {
+ None
+ };
+ if let Some(route) = governed.as_ref() {
+ if !explicit_bundle_override.is_empty() && explicit_bundle_override != route.bundle {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ format!(
+ "Bundle override '{}' conflicts with the deployment route for this model",
+ explicit_bundle_override
+ ),
+ oai_type::INVALID_REQUEST,
+ Some("model"),
+ oai_code::INVALID_REQUEST,
+ )),
+ )
+ .into_response());
+ }
+ match state
+ .model_registry
+ .resolve_bundle(&route.model, Some(&route.bundle))
+ {
+ Ok(resolved) if resolved == route.bundle => {}
+ _ => {
+ return Err(governed_generation_route_failure(
+ customer_model,
+ request_intent,
+ "compiled bundle is incompatible with the physical model",
+ ));
+ }
+ }
+ }
+ let bundle = governed
+ .as_ref()
+ .map_or_else(|| bundle.to_string(), |route| route.bundle.clone());
// Machine-profile + pool resolution, shared with the primitive path via
// `resolve_profile_and_pool`. Errors are rendered here in the OpenAI
// envelope (`json_openai_error`), preserving the compat surface.
@@ -5653,13 +6406,28 @@ async fn resolve_generation_route(
// so it short-circuits catalog profile/pool resolution entirely.
let (gpu, pool_name, gpu_configured) = if let Some(route) = &sealed {
(route.machine_profile.clone(), route.pool.clone(), true)
+ } else if let Some(route) = governed.as_ref() {
+ let route = governed_profile_and_pool(state, hdr, route)?;
+ (route.gpu, route.pool_name, route.gpu_configured)
} else {
- match resolve_profile_and_pool(state, hdr, model_name).await {
+ match resolve_profile_and_pool(state, hdr, customer_model).await {
Ok(ProfilePoolRoute {
gpu,
pool_name,
gpu_configured,
}) => (gpu, pool_name, gpu_configured),
+ Err(ProfilePoolError::InvalidHeader { header }) => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ format!("{header} header must be valid UTF-8"),
+ oai_type::INVALID_REQUEST,
+ Some(header),
+ oai_code::INVALID_REQUEST,
+ )),
+ )
+ .into_response());
+ }
Err(ProfilePoolError::InvalidPool) => {
return Err((
StatusCode::BAD_REQUEST,
@@ -5722,23 +6490,24 @@ async fn resolve_generation_route(
ProvisioningSurface::OpenAiCompat,
));
};
- let (bundle_config_hash, model_revision) = state
- .model_registry
- .bundle_execution_evidence(bundle, &hash_pool, model_name);
+ let (bundle_config_hash, model_revision) =
+ state
+ .model_registry
+ .bundle_execution_evidence(&bundle, &hash_pool, dispatch_model);
// #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 {
Some(route) => route.engine.clone(),
None => state
.model_registry
- .get_bundle_info(bundle)
+ .get_bundle_info(&bundle)
.map(|info| info.engine)
.unwrap_or_else(|| crate::types::bundle::DEFAULT_ENGINE.to_string()),
};
let lookup = resolve_effective_pool(
&state.registry,
Some(&state.pool_manager),
- bundle,
+ &bundle,
&gpu,
&pool_name,
&bundle_config_hash,
@@ -5750,7 +6519,7 @@ async fn resolve_generation_route(
for profile in &pending_demand_profiles {
if let Some(lane) = state
.demand_tracker
- .resolve_lane(&demand_pool, profile, bundle)
+ .resolve_lane(&demand_pool, profile, &bundle)
{
state.demand_tracker.record(&lane);
}
@@ -5764,7 +6533,7 @@ async fn resolve_generation_route(
));
}
PoolResolution::Provisioning => {
- return Err(build_openai_provisioning_response(&gpu, bundle));
+ return Err(build_openai_provisioning_response(&gpu, &bundle));
}
};
let effective_pool = effective_route.pool_name;
@@ -5772,12 +6541,12 @@ async fn resolve_generation_route(
let Some(physical_lane) =
state
.demand_tracker
- .resolve_lane(&demand_pool, &effective_machine_profile, bundle)
+ .resolve_lane(&demand_pool, &effective_machine_profile, &bundle)
else {
error!(
pool = %demand_pool,
machine_profile = %effective_machine_profile,
- bundle = %bundle,
+ bundle = %bundle,
"resolved generation route is absent from configured physical KEDA lane catalog"
);
return Err((
@@ -5807,7 +6576,7 @@ async fn resolve_generation_route(
&admission_pool,
&demand_pool,
&effective_machine_profile,
- bundle,
+ &bundle,
ProvisioningSurface::OpenAiCompat,
)
.await
@@ -5826,6 +6595,7 @@ async fn resolve_generation_route(
Ok(ResolvedRoute {
physical_lane,
+ bundle,
gpu,
engine,
admission_pool,
@@ -5867,7 +6637,13 @@ async fn resolve_generation_route(
/// routed variant. This is safe because grammar capabilities are model/task-level
/// (identical across a model's profiles), so the gate verdict is the same on the
/// base and the routed variant.
-fn route_grammar_to_profile(
+/// `pub` so the managed cost-estimate dry run (#2435) applies the SAME rewrite
+/// before rating. `profile` is a rate-key dimension and this rewrite decides it
+/// for every grammar-constrained generation, so an estimate that skipped it
+/// would quote `profile="default"` for a request admission holds under
+/// `profile="{grammar_profile}"` — a different price, or a confident 200 for a
+/// request the live path finds unpriced.
+pub fn route_grammar_to_profile(
registry: &crate::state::model_registry::ModelRegistry,
model: &mut String,
) {
@@ -5947,15 +6723,10 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
}
let _chat_span_guard = chat_span.enter();
- // `/v1/chat/completions` is text generation; mirror the `generate`
- // hardening rather than the legacy 256 MiB cap, which let concurrent
- // oversized chat bodies OOM the gateway. 16 MiB leaves comfortable
- // headroom for multimodal content parts (base64 images) while closing
- // the trivial OOM-under-concurrency vector.
- const MAX_CHAT_BODY: usize = 16 * 1024 * 1024;
+ let max_chat_body = compat_request_body_limit("/v1/chat/completions");
let hdr = req.headers().clone();
let (parts, body) = req.into_parts(); // keep extensions (caller identity) for the #1841 gate
- let body_bytes = match to_bytes(body, MAX_CHAT_BODY).await {
+ let body_bytes = match to_bytes(body, max_chat_body).await {
Ok(b) => b,
Err(e) => {
return (
@@ -6002,6 +6773,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
Ok(mb) => mb,
Err(resp) => return resp,
};
+ let (explicit_bundle_override, _) = parse_model_spec(&params.model);
// Grammar routing (follow-up: chat-path gate ordering). Resolve the model's
// declared ``grammar_profile`` variant and compute the DISPATCH id BEFORE the
@@ -6179,6 +6951,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
// Shared with /v1/completions via resolve_generation_route.
let ResolvedRoute {
physical_lane,
+ bundle,
gpu,
engine,
admission_pool,
@@ -6194,6 +6967,13 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
&hdr,
&bundle,
&model_name,
+ &dispatch_model,
+ if params.grammar.is_some() {
+ GenerationRequestIntent::Grammar
+ } else {
+ GenerationRequestIntent::Default
+ },
+ &explicit_bundle_override,
&parts.extensions,
metric_labels_slot.as_ref(),
)
@@ -6204,45 +6984,10 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
};
let start = Instant::now();
- // Thread the routing hints into both `GenerateParams`
- // (where the HRW resolver reads them) and `WorkParams` (where
- // they were already carried since the chat/grammar surfaces for the worker's
- // inert hint path). Clone is one allocation each and avoids
- // either reader having to fall back on the other.
- let work_params = publisher::WorkParams {
- generate: Some(publisher::GenerateParams {
- input: publisher::GenerateInput::Messages {
- messages: params.messages,
- },
- max_new_tokens: params.max_new_tokens,
- temperature: params.temperature,
- top_p: params.top_p,
- stop: params.stop,
- frequency_penalty: params.frequency_penalty,
- presence_penalty: params.presence_penalty,
- top_k: params.top_k,
- repetition_penalty: params.repetition_penalty,
- min_tokens: params.min_tokens,
- chat_template_kwargs: params.chat_template_kwargs,
- grammar: params.grammar,
- routing_key: params.routing_key.clone(),
- prompt_cache_key: params.prompt_cache_key.clone(),
- tools: params.tools,
- tool_choice: params.tool_choice,
- parallel_tool_calls: params.parallel_tool_calls,
- seed: params.seed,
- logit_bias: params.logit_bias,
- logprobs: params.logprobs,
- top_logprobs: params.top_logprobs,
- n: params.n,
- best_of: params.best_of,
- stream: params.stream,
- lora_adapter: params.lora_adapter.clone(),
- }),
- routing_key: params.routing_key,
- prompt_cache_key: params.prompt_cache_key,
- ..Default::default()
- };
+ // Copied out BEFORE the params are consumed into `WorkParams` below.
+ let stream = params.stream;
+ let stream_include_usage = params.stream_include_usage;
+ let work_params = params.into_work_params();
// SSE branch — when `stream: true` we hand off to the SSE
// response builder. The non-streaming aggregating path below is
@@ -6252,7 +6997,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
// republish-to-pool) but installs a broadcast tap on the
// collector so each chunk is forwarded to the HTTP client as it
// arrives instead of being aggregated.
- if params.stream {
+ if stream {
return super::sse::build_sse_response(super::sse::SseParams {
state: state.as_ref(),
work_publisher: work_publisher_arc,
@@ -6267,7 +7012,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
bundle_config_hash: bundle_config_hash.clone(),
work_params,
endpoint: super::sse::SseEndpoint::Chat {
- include_usage: params.stream_include_usage,
+ include_usage: stream_include_usage,
},
})
.await;
@@ -6374,6 +7119,34 @@ struct CompletionsParams {
presence_penalty: Option<f64>,
seed: Option<i64>,
stream: bool,
+ /// OpenAI ``stream_options.include_usage`` — when ``true`` the SSE stream
+ /// emits a trailing usage-only ``text_completion`` chunk before ``[DONE]``.
+ /// Unknown / non-boolean ``stream_options`` are rejected by the parser.
+ stream_include_usage: bool,
+}
+
+impl CompletionsParams {
+ /// The EXACT `WorkParams` a validated `/v1/completions` body dispatches
+ /// with. Extracted (not copied) for the same reason as
+ /// [`ChatRequestParams::into_work_params`] — see #2435.
+ fn into_work_params(self) -> publisher::WorkParams {
+ publisher::WorkParams {
+ generate: Some(publisher::GenerateParams {
+ input: publisher::GenerateInput::Prompt {
+ prompt: self.prompt,
+ },
+ max_new_tokens: self.max_new_tokens,
+ temperature: self.temperature,
+ top_p: self.top_p,
+ stop: self.stop,
+ frequency_penalty: self.frequency_penalty,
+ presence_penalty: self.presence_penalty,
+ seed: self.seed,
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+ }
}
enum CompletionsParamsResult {
@@ -6381,6 +7154,21 @@ enum CompletionsParamsResult {
Err(Response),
}
+/// The `(model, WorkParams)` a `/v1/completions` body dispatches with. See
+/// [`chat_completions_dispatch_inputs`], including the `dead_code` note.
+#[allow(clippy::result_large_err, dead_code)]
+pub fn completions_dispatch_inputs(
+ body: &serde_json::Value,
+) -> Result<(String, publisher::WorkParams), Response> {
+ match completions_params_from_json(body) {
+ CompletionsParamsResult::Ok(params) => {
+ let model = params.model.clone();
+ Ok((model, params.into_work_params()))
+ }
+ CompletionsParamsResult::Err(response) => Err(response),
+ }
+}
+
/// Parse + validate a `/v1/completions` body. MVP scope: a single `prompt`
/// string (or 1-element array), non-streaming, single-candidate; `echo`,
/// `suffix`, `logprobs`, `best_of` are out of scope. Errors use the OpenAI
@@ -6478,6 +7266,40 @@ fn completions_params_from_json(body: &serde_json::Value) -> CompletionsParamsRe
);
}
};
+ // ``stream_options.include_usage`` — same contract as chat: the only
+ // recognised key, boolean, and OpenAI-legal (ignored) with ``stream:false``.
+ let mut stream_include_usage = false;
+ if let Some(opts) = obj.get("stream_options") {
+ if !opts.is_null() {
+ let Some(opts_obj) = opts.as_object() else {
+ return bad(
+ "'stream_options' must be a JSON object",
+ Some("stream_options"),
+ oai_code::INVALID_REQUEST,
+ );
+ };
+ for key in opts_obj.keys() {
+ if key != "include_usage" {
+ return bad(
+ &format!("'stream_options.{key}' is not supported by this endpoint"),
+ Some(&format!("stream_options.{key}")),
+ oai_code::UNSUPPORTED_FIELD,
+ );
+ }
+ }
+ match opts_obj.get("include_usage") {
+ None | Some(serde_json::Value::Null) => {}
+ Some(serde_json::Value::Bool(b)) => stream_include_usage = *b,
+ Some(_) => {
+ return bad(
+ "'stream_options.include_usage' must be a boolean",
+ Some("stream_options.include_usage"),
+ oai_code::INVALID_REQUEST,
+ );
+ }
+ }
+ }
+ }
// ``n``: single-candidate only on this endpoint. Reject any non-integer
// and any value outside ``n == 1``. ``n=1`` is accepted as a no-op
// (it is the implicit default).
@@ -6631,6 +7453,7 @@ fn completions_params_from_json(body: &serde_json::Value) -> CompletionsParamsRe
"presence_penalty",
"seed",
"stream",
+ "stream_options",
"n",
];
for key in obj.keys() {
@@ -6654,6 +7477,7 @@ fn completions_params_from_json(body: &serde_json::Value) -> CompletionsParamsRe
presence_penalty,
seed,
stream,
+ stream_include_usage,
})
}
@@ -6726,10 +7550,10 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
.get::<telemetry::MetricLabelsSlot>()
.cloned();
- const MAX_COMPLETIONS_BODY: usize = 16 * 1024 * 1024;
+ let max_completions_body = compat_request_body_limit("/v1/completions");
let hdr = req.headers().clone();
let (parts, body) = req.into_parts(); // keep extensions (caller identity) for the #1841 gate
- let body_bytes = match to_bytes(body, MAX_COMPLETIONS_BODY).await {
+ let body_bytes = match to_bytes(body, max_completions_body).await {
Ok(b) => b,
Err(e) => {
return (
@@ -6770,9 +7594,11 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
Ok(mb) => mb,
Err(resp) => return resp,
};
+ let (explicit_bundle_override, _) = parse_model_spec(&params.model);
let ResolvedRoute {
physical_lane,
+ bundle,
gpu,
engine,
admission_pool,
@@ -6788,6 +7614,9 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
&hdr,
&bundle,
&model_name,
+ &model_name,
+ GenerationRequestIntent::Default,
+ &explicit_bundle_override,
&parts.extensions,
metric_labels_slot.as_ref(),
)
@@ -6798,26 +7627,14 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
};
let start = Instant::now();
- let work_params = publisher::WorkParams {
- generate: Some(publisher::GenerateParams {
- input: publisher::GenerateInput::Prompt {
- prompt: params.prompt,
- },
- max_new_tokens: params.max_new_tokens,
- temperature: params.temperature,
- top_p: params.top_p,
- stop: params.stop,
- frequency_penalty: params.frequency_penalty,
- presence_penalty: params.presence_penalty,
- seed: params.seed,
- ..Default::default()
- }),
- ..Default::default()
- };
+ // Copied out BEFORE the params are consumed into `WorkParams` below.
+ let stream = params.stream;
+ let stream_include_usage = params.stream_include_usage;
+ let work_params = params.into_work_params();
// SSE streaming → emit `text_completion` chunks. Single-candidate
// (completions rejects n>1), so no per-candidate interleave.
- if params.stream {
+ if stream {
return super::sse::build_sse_response(super::sse::SseParams {
state: state.as_ref(),
work_publisher: work_publisher_arc,
@@ -6833,7 +7650,9 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
admission_pool: admission_pool.clone(),
bundle_config_hash: bundle_config_hash.clone(),
work_params,
- endpoint: super::sse::SseEndpoint::Completion,
+ endpoint: super::sse::SseEndpoint::Completion {
+ include_usage: stream_include_usage,
+ },
})
.await;
}
@@ -6925,11 +7744,45 @@ struct ResponsesParams {
seed: Option<i64>,
}
+impl ResponsesParams {
+ /// The EXACT `WorkParams` a validated `/v1/responses` body dispatches with.
+ /// Extracted (not copied) for the same reason as
+ /// [`ChatRequestParams::into_work_params`] — see #2435.
+ fn into_work_params(self) -> publisher::WorkParams {
+ publisher::WorkParams {
+ generate: Some(publisher::GenerateParams {
+ input: self.input,
+ max_new_tokens: self.max_new_tokens,
+ temperature: self.temperature,
+ top_p: self.top_p,
+ seed: self.seed,
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+ }
+}
+
enum ResponsesParamsResult {
Ok(ResponsesParams),
Err(Response),
}
+/// The `(model, WorkParams)` a `/v1/responses` body dispatches with. See
+/// [`chat_completions_dispatch_inputs`], including the `dead_code` note.
+#[allow(clippy::result_large_err, dead_code)]
+pub fn responses_dispatch_inputs(
+ body: &serde_json::Value,
+) -> Result<(String, publisher::WorkParams), Response> {
+ match responses_params_from_json(body) {
+ ResponsesParamsResult::Ok(params) => {
+ let model = params.model.clone();
+ Ok((model, params.into_work_params()))
+ }
+ ResponsesParamsResult::Err(response) => Err(response),
+ }
+}
+
/// Parse + validate a `/v1/responses` body. MVP: a string `input` or a
/// list of role/content messages, non-streaming. Out of scope per
/// ADR-0001: tools, stateful threading (`previous_response_id`), reasoning,
@@ -7303,10 +8156,10 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
.get::<telemetry::MetricLabelsSlot>()
.cloned();
- const MAX_RESPONSES_BODY: usize = 16 * 1024 * 1024;
+ let max_responses_body = compat_request_body_limit("/v1/responses");
let hdr = req.headers().clone();
let (parts, body) = req.into_parts(); // keep extensions (caller identity) for the #1841 gate
- let body_bytes = match to_bytes(body, MAX_RESPONSES_BODY).await {
+ let body_bytes = match to_bytes(body, max_responses_body).await {
Ok(b) => b,
Err(e) => {
return (
@@ -7347,8 +8200,10 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
Ok(mb) => mb,
Err(resp) => return resp,
};
+ let (explicit_bundle_override, _) = parse_model_spec(&params.model);
let ResolvedRoute {
physical_lane,
+ bundle,
gpu,
engine,
admission_pool,
@@ -7364,6 +8219,9 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
&hdr,
&bundle,
&model_name,
+ &model_name,
+ GenerationRequestIntent::Default,
+ &explicit_bundle_override,
&parts.extensions,
metric_labels_slot.as_ref(),
)
@@ -7374,17 +8232,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
};
let start = Instant::now();
- let work_params = publisher::WorkParams {
- generate: Some(publisher::GenerateParams {
- input: params.input,
- max_new_tokens: params.max_new_tokens,
- temperature: params.temperature,
- top_p: params.top_p,
- seed: params.seed,
- ..Default::default()
- }),
- ..Default::default()
- };
+ let work_params = params.into_work_params();
let driver = run_streaming_generate(
&state,
@@ -7761,6 +8609,10 @@ fn unanimous_terminal_client_error(
PAYLOAD_TOO_LARGE_ERROR_CODE => {
(StatusCode::PAYLOAD_TOO_LARGE, PAYLOAD_TOO_LARGE_ERROR_CODE)
}
+ COLD_START_RATE_LIMITED_ERROR_CODE => (
+ StatusCode::TOO_MANY_REQUESTS,
+ COLD_START_RATE_LIMITED_ERROR_CODE,
+ ),
_ => return None,
};
errors
@@ -8117,7 +8969,18 @@ fn alias_model_target(target: &str, requested_profile: Option<&str>) -> String {
/// precision/profile bundle for a job alias — e.g. map `sql` to a BF16 bundle
/// that avoids the FP8 SQL-accuracy regression (ADR 0001). An explicit caller
/// bundle (`somebundle:/sql`) always wins over the alias's bundle.
-pub(crate) fn resolve_model_spec_with_aliases(
+/// `pub` because it is THE definition of "which model does this string denote"
+/// for this gateway, and two surfaces outside the route need that definition:
+///
+/// - the managed cost-estimate dry run (#2435) rates a caller-supplied id, and
+/// model is a rate-key dimension, so an estimate that skipped the `__`->`/`,
+/// case, and alias folding would quote a different identity than admission
+/// holds (or, as it did, 503 on the very path spelling the SDKs emit);
+/// - a surface that must DECIDE something about a model with no routing seam of
+/// its own (the managed async jobs/batches ingress, #2542) has to reach the
+/// same identity this function produces, or its decision is about a spelling
+/// rather than about a model.
+pub fn resolve_model_spec_with_aliases(
aliases: &std::collections::HashMap<String, String>,
spec: &str,
canonicalize: impl Fn(&str) -> Option<String>,
@@ -8139,7 +9002,10 @@ pub(crate) fn resolve_model_spec_with_aliases(
(req_bundle, model_name)
}
-fn decode_model_path(raw: &str) -> Result<String, String> {
+/// `pub` for the same reason as [`resolve_model_spec_with_aliases`]: the
+/// estimate receives a target PATH and must decode its model segment the way
+/// the route does before rating it.
+pub fn decode_model_path(raw: &str) -> Result<String, String> {
percent_decode_str(raw)
.decode_utf8()
.map(|decoded| decoded.into_owned())
@@ -8391,6 +9257,12 @@ pub(crate) fn is_openai_compat_inner_request_header(name: &str) -> bool {
/// text, never request content or raw upstream internals); unparseable
/// bodies fall back to a generic message, never the raw bytes.
pub(crate) async fn translate_inner_compat_error(resp: Response) -> Response {
+ // Deliberately NOT [`MAX_COMPAT_RESPONSE_BODY`]. This buffers an ERROR
+ // envelope — a code and a sanitized message, kilobytes at the outside — so
+ // 16 MiB is already orders of magnitude above any real body here and the
+ // amplification that forced the embeddings cap up does not exist. Raising
+ // it by symmetry would only widen the buffer an unhealthy upstream can make
+ // the gateway hold.
const MAX: usize = 16 * 1024 * 1024;
let status = resp.status();
let headers = resp.headers().clone();
@@ -8743,7 +9615,7 @@ fn check_sdk_version(headers: &HeaderMap) {
/// envelope so grammar safety violations can surface with
/// their precise ``param`` / ``code`` rather than being re-wrapped.
#[derive(Debug)]
-pub(crate) enum QueueParseError {
+pub enum QueueParseError {
/// Caller surfaces as a generic 400 with the message body.
Generic(String),
/// Caller returns the response verbatim (already 400 with the
@@ -8765,7 +9637,7 @@ impl From<String> for QueueParseError {
// would force every caller to dereference at the recovery site and
// match the pre-existing ``ChatParamsResult::Err(Response)`` shape.
#[allow(clippy::result_large_err)]
-fn parse_queue_request(
+pub fn parse_queue_request(
body: &[u8],
is_msgpack: bool,
endpoint: &str,
@@ -8780,6 +9652,7 @@ fn parse_queue_request(
}
pub(crate) const MAX_SCORE_ITEMS: usize = 1000;
+pub(crate) const MAX_EMBEDDING_INPUTS: usize = 256;
/// Reject queue-request bodies whose per-item / query shapes the worker
/// cannot consume, at ingress, instead of forwarding them to a GPU lane
@@ -9364,76 +10237,6 @@ fn work_params_from_json(
})
}
-/// Extract just the ``stream: bool`` flag from a SIE-native
-/// ``/v1/generate/{model}`` request body. The full body has already
-/// been parsed once into :class:`WorkParams`; this helper does a
-/// second light-touch decode purely to read the streaming flag,
-/// which is **not** part of the work envelope (the worker never
-/// sees it — the gateway switches response shape based on it).
-///
-/// Returns:
-///
-/// * `Ok(true)` — `stream: true` is set, switch to the SSE branch.
-/// * `Ok(false)` — flag is absent / null / false, use the
-/// aggregating path.
-/// * `Err(Response)` — flag is present but the wrong type
-/// (e.g. a string); surface a 400 with the OpenAI envelope.
-///
-/// A body that fails to decode entirely is silently treated as
-/// "no stream flag" — the existing aggregating-path body parser
-/// (`parse_queue_request`) is the authoritative validator and
-/// already surfaces the precise error.
-///
-/// The `Err`-variant carries a fully-built 400 response (the
-/// OpenAI envelope is shaped at the call site, matching the
-/// pattern used by `chat_params_from_json`). We accept the
-/// `clippy::result_large_err` allow here for the same reason the
-/// pre-existing :class:`QueueParseError::PreBuilt` arm does: boxing
-/// the response forces every caller to dereference at the recovery
-/// site for negligible gain.
-#[allow(clippy::result_large_err)]
-fn stream_flag_from_body(body: &[u8], is_msgpack: bool) -> Result<bool, Response> {
- let bad_type = || -> Response {
- (
- StatusCode::BAD_REQUEST,
- Json(json_openai_error(
- "'stream' must be a boolean".to_string(),
- oai_type::INVALID_REQUEST,
- Some("stream"),
- oai_code::INVALID_REQUEST,
- )),
- )
- .into_response()
- };
- if is_msgpack {
- let Ok(rmpv::Value::Map(entries)) = rmp_serde::from_slice::<rmpv::Value>(body) else {
- return Ok(false);
- };
- for (k, v) in entries.iter() {
- if rmpv_key_eq(k, "stream") {
- return match v {
- rmpv::Value::Boolean(b) => Ok(*b),
- rmpv::Value::Nil => Ok(false),
- _ => Err(bad_type()),
- };
- }
- }
- Ok(false)
- } else {
- let Ok(v): Result<serde_json::Value, _> = serde_json::from_slice(body) else {
- return Ok(false);
- };
- let Some(obj) = v.as_object() else {
- return Ok(false);
- };
- match obj.get("stream") {
- None | Some(serde_json::Value::Null) => Ok(false),
- Some(serde_json::Value::Bool(b)) => Ok(*b),
- Some(_) => Err(bad_type()),
- }
- }
-}
-
/// Maximum number of entries in a ``logit_bias`` map. Mirrors the cap
/// enforced inline by :func:`chat_params_from_json` so the two routes
/// share an identical DoS-prevention budget.
@@ -11189,6 +11992,28 @@ fn estimate_embedding_tokens(texts: &[String]) -> u64 {
u64::max(1, (total / 4) as u64)
}
+/// The native `/v1/encode/{model}` body ONE `/v1/embeddings` request rewrites
+/// itself into before the in-process re-dispatch.
+///
+/// `/v1/embeddings` is not dispatched directly: the handler normalizes its
+/// `input` into native encode items and re-issues the request against
+/// `/v1/encode/{model}`, so the reservation the live path takes is the
+/// reservation for THIS body, not for the compat one. The managed
+/// cost-estimate dry run (#2435) must therefore price the same rewritten body —
+/// which it does by calling this function, the one the handler itself calls.
+/// A private second rewrite here is exactly how an estimate would come to price
+/// a request shape that never reaches the planner.
+pub fn openai_embeddings_encode_body(input: &Value) -> Result<(Value, u64), String> {
+ let OpenAiEmbeddingInput { texts, token_count } = openai_embedding_input_to_texts(input)?;
+ Ok((
+ json!({
+ "items": texts.iter().map(|t| json!({"text": t})).collect::<Vec<_>>(),
+ "params": {"output_types": ["dense"]},
+ }),
+ token_count,
+ ))
+}
+
fn openai_embedding_input_to_texts(input: &Value) -> Result<OpenAiEmbeddingInput, String> {
match input {
Value::String(s) => {
@@ -11200,6 +12025,11 @@ fn openai_embedding_input_to_texts(input: &Value) -> Result<OpenAiEmbeddingInput
}
Value::Array(a) if a.is_empty() => Err("input array is empty".to_string()),
Value::Array(a) if a.iter().all(|x| x.is_string()) => {
+ if a.len() > MAX_EMBEDDING_INPUTS {
+ return Err(format!(
+ "input must contain at most {MAX_EMBEDDING_INPUTS} texts; split the request into smaller batches"
+ ));
+ }
let texts: Vec<String> = a
.iter()
.filter_map(|x| x.as_str().map(String::from))
@@ -11306,10 +12136,10 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Re
// multimodal payloads — so it gets the same text-appropriate cap as
// the chat path (16 MiB) rather than the legacy 256 MiB, which left a
// trivial OOM-under-concurrency vector open.
- const MAX: usize = 16 * 1024 * 1024;
+ let max_body = compat_request_body_limit("/v1/embeddings");
let hdr = req.headers().clone();
let (parts, body) = req.into_parts();
- let body_bytes = match to_bytes(body, MAX).await {
+ let body_bytes = match to_bytes(body, max_body).await {
Ok(b) => b,
Err(e) => {
return (
@@ -11378,8 +12208,8 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Re
.into_response();
}
let input = parsed.get("input").cloned().unwrap_or(Value::Null);
- let normalized_input = match openai_embedding_input_to_texts(&input) {
- Ok(input) => input,
+ let (encode_body, token_count) = match openai_embeddings_encode_body(&input) {
+ Ok(normalized) => normalized,
Err(msg) => {
return (
StatusCode::BAD_REQUEST,
@@ -11392,11 +12222,12 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Re
.into_response();
}
};
- let OpenAiEmbeddingInput { texts, token_count } = normalized_input;
- let encode_body = json!({
- "items": texts.iter().map(|t| json!({"text": t})).collect::<Vec<_>>(),
- "params": {"output_types": ["dense"]},
- });
+ // One encode item per normalized input text — the count the response
+ // assembler pads/validates its `data` array against.
+ let input_count = encode_body
+ .get("items")
+ .and_then(Value::as_array)
+ .map_or(0, Vec::len);
let encode_bytes = match serde_json::to_vec(&encode_body) {
Ok(b) => b,
Err(e) => {
@@ -11479,54 +12310,104 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Re
}
return resp;
}
+ // From here the worker has already run and reported its units, so EVERY
+ // failure below is the gateway's: a successful encode this handler could not
+ // render into the client's shape, with the client receiving none of it.
+ // EVERY such arm is marked [`GatewayOwnedFault`] — the two buffering ones
+ // and the three translation ones after them — so a metered composition
+ // releases the hold instead of debiting for an undelivered result, the same
+ // treatment `audio.rs` gives all four of its equivalents. The buffering and
+ // translation arms are one class: "the worker delivered, we could not", and
+ // marking only the half nearest the read would bill the other half in full.
let enc_headers = resp.headers().clone();
- let rb = match to_bytes(resp.into_body(), MAX).await {
- Ok(b) => b,
- Err(_) => {
- return (
+ // NOT `max_body`. That is the REQUEST cap, and this body is the encode
+ // reply — an amplification of the request, not a copy of it. See
+ // [`MAX_COMPAT_RESPONSE_BODY`].
+ let rb = match buffer_compat_response_body(resp.into_body()).await {
+ CompatResponseBody::Buffered(b) => b,
+ CompatResponseBody::TooLarge { observed } => {
+ // Terminal, and deliberately not 503: the identical request yields
+ // the identical oversized reply, so a retryable surface would have
+ // SDK retry loops hammering a permanent condition forever. 413 is
+ // already this route's documented terminal size verdict and carries
+ // no `Retry-After`.
+ //
+ // The status is terminal AND the fault is gateway-owned; those are
+ // orthogonal. The status tells the caller not to retry unchanged;
+ // the marker tells billing not to charge for zero embeddings.
+ warn!(
+ limit = MAX_COMPAT_RESPONSE_BODY,
+ observed_bytes = observed,
+ "encode response exceeds the compat response cap"
+ );
+ // Only ONE remedy is named, because only one works. An earlier
+ // revision also offered `encoding_format="base64"`; that is inert
+ // here — the field is never forwarded to `/v1/encode` (see
+ // `openai_embeddings_encode_body`) and base64 is applied afterwards,
+ // when the OUTER response is assembled from this very buffer. A
+ // caller who followed it paid for a second identical encode and got
+ // a byte-identical rejection (#2617).
+ let detail = match observed {
+ Some(bytes) => format!(
+ "the embedding response for this request is {bytes} bytes, over the \
+ {MAX_COMPAT_RESPONSE_BODY}-byte limit; send fewer inputs per request"
+ ),
+ None => format!(
+ "the embedding response for this request exceeds the \
+ {MAX_COMPAT_RESPONSE_BODY}-byte limit; send fewer inputs per request"
+ ),
+ };
+ return compat_translation_fault(
+ "read_encode_response_too_large",
+ StatusCode::PAYLOAD_TOO_LARGE,
+ err_code::PAYLOAD_TOO_LARGE,
+ Some("input"),
+ detail,
+ );
+ }
+ CompatResponseBody::Unreadable => {
+ // Pre-existing 500, now marked. It billed in full before this change
+ // for exactly the same reason the 413 would have.
+ return compat_translation_fault(
+ "read_encode_response",
StatusCode::INTERNAL_SERVER_ERROR,
- Json(embeddings_error(
- err_code::INTERNAL_ERROR,
- None,
- "failed to read encode response body",
- )),
- )
- .into_response();
+ err_code::INTERNAL_ERROR,
+ None,
+ "failed to read encode response body".to_string(),
+ );
}
};
let enc: Value = match serde_json::from_slice(&rb) {
Ok(v) => v,
Err(e) => {
- return (
+ return compat_translation_fault(
+ "decode_encode_response",
StatusCode::INTERNAL_SERVER_ERROR,
- Json(embeddings_error(
- err_code::INTERNAL_ERROR,
- None,
- format!("encode JSON: {}", e),
- )),
- )
- .into_response();
+ err_code::INTERNAL_ERROR,
+ None,
+ format!("encode JSON: {}", e),
+ );
}
};
let Some(items) = enc.get("items").and_then(|i| i.as_array()) else {
- return (
+ return compat_translation_fault(
+ "encode_response_shape",
StatusCode::INTERNAL_SERVER_ERROR,
- Json(embeddings_error(
- err_code::INTERNAL_ERROR,
- None,
- "encode response missing items",
- )),
- )
- .into_response();
+ err_code::INTERNAL_ERROR,
+ None,
+ "encode response missing items".to_string(),
+ );
};
- let data = match openai_embedding_items_to_data(items, texts.len(), enc_fmt) {
+ let data = match openai_embedding_items_to_data(items, input_count, enc_fmt) {
Ok(data) => data,
Err(msg) => {
- return (
+ return compat_translation_fault(
+ "format_embeddings",
StatusCode::INTERNAL_SERVER_ERROR,
- Json(embeddings_error(err_code::INTERNAL_ERROR, None, msg)),
- )
- .into_response();
+ err_code::INTERNAL_ERROR,
+ None,
+ msg,
+ );
}
};
let token_est = token_count;
@@ -11813,7 +12694,29 @@ fn rerank_error(status: StatusCode, message: impl Into<String>) -> Response {
(status, Json(json!({"message": message.into()}))).into_response()
}
+/// A `/v1/rerank` 500 for a POST-DISPATCH failure, marked as gateway-owned.
+///
+/// The `score` counterpart of [`compat_translation_fault`] and `audio.rs`'s
+/// `translation_fault`. Once `proxy_request` has returned 200 the worker has run
+/// and the meter already holds its units, so a failure to read, decode, or
+/// reshape that reply is OURS: the client receives zero rerank results and,
+/// without this marker, the managed edge falls through to
+/// `settle_planned_request` and debits the hold in full.
+///
+/// Deliberately NOT folded into [`rerank_error`], which also serves
+/// `translate_inner_rerank_error` — that path carries the WORKER's own verdict on
+/// a request that never produced billable output through this handler, and
+/// marking it would change a settlement this change has no business touching.
+fn rerank_translation_fault(stage: &'static str, message: impl Into<String>) -> Response {
+ GatewayOwnedFault::new(stage).mark(rerank_error(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ message.into(),
+ ))
+}
+
async fn translate_inner_rerank_error(resp: Response) -> Response {
+ // An error envelope, like `translate_inner_compat_error` — see the note
+ // there for why this stays at the request-shaped bound.
const MAX: usize = 16 * 1024 * 1024;
let status = resp.status();
let headers = resp.headers().clone();
@@ -11901,6 +12804,11 @@ async fn proxy_rerank_inner(
req: Request,
) -> Response {
check_sdk_version(req.headers());
+ // Bounds BOTH the rerank request and the inner `score` reply below, and
+ // that symmetry is sound here where it was not for embeddings: a score
+ // reply is `{index, relevance_score}` per document, capped at
+ // [`MAX_RERANK_DOCUMENTS`] (1000) — tens of KiB, with no per-item vector to
+ // amplify. The response is smaller than the request that produced it.
const MAX: usize = 16 * 1024 * 1024;
let headers = req.headers().clone();
let (parts, body) = req.into_parts();
@@ -11972,20 +12880,24 @@ async fn proxy_rerank_inner(
return translate_inner_rerank_error(response).await;
}
+ // From here the worker has already run and reported its units, so every
+ // failure below is the gateway's, exactly as on the embeddings and audio
+ // surfaces: the client receives zero rerank results and must not be
+ // debited for them. Each arm is marked [`GatewayOwnedFault`].
let response_headers = response.headers().clone();
let native: Value = match to_bytes(response.into_body(), MAX).await {
Ok(body) => match serde_json::from_slice(&body) {
Ok(value) => value,
Err(error) => {
- return rerank_error(
- StatusCode::INTERNAL_SERVER_ERROR,
+ return rerank_translation_fault(
+ "decode_score_response",
format!("score response is not valid JSON: {error}"),
);
}
},
Err(_) => {
- return rerank_error(
- StatusCode::INTERNAL_SERVER_ERROR,
+ return rerank_translation_fault(
+ "read_score_response",
"failed to read score response body",
);
}
@@ -11997,7 +12909,7 @@ async fn proxy_rerank_inner(
normalized.return_documents,
) {
Ok(output) => output,
- Err(message) => return rerank_error(StatusCode::INTERNAL_SERVER_ERROR, message),
+ Err(message) => return rerank_translation_fault("format_rerank", message),
};
let mut output = (StatusCode::OK, Json(output)).into_response();
for (name, value) in response_headers.iter() {
@@ -12167,6 +13079,50 @@ mod tests {
}
}
+ #[test]
+ fn dispatcher_defaults_to_no_first_chunk_pool_republish() {
+ let dispatcher = AbandonmentProbe::default();
+ assert!(!dispatcher.supports_first_chunk_pool_republish());
+ }
+
+ #[test]
+ fn enabled_first_chunk_capability_preserves_initial_republish_and_pool_timeout_decisions() {
+ assert_eq!(
+ first_chunk_deadline_action(true, true, false, false),
+ FirstChunkDeadlineAction::RepublishToPool
+ );
+ assert_eq!(
+ first_chunk_deadline_action(true, false, false, false),
+ FirstChunkDeadlineAction::SurfaceTimeout
+ );
+ }
+
+ #[test]
+ fn enabled_first_chunk_capability_waits_for_overall_on_single_consumer_lane() {
+ assert_eq!(
+ first_chunk_deadline_action(true, true, false, true),
+ FirstChunkDeadlineAction::WaitForOverall
+ );
+ }
+
+ #[test]
+ fn enabled_first_chunk_capability_surfaces_after_republish_was_already_attempted() {
+ assert_eq!(
+ first_chunk_deadline_action(true, true, true, false),
+ FirstChunkDeadlineAction::SurfaceTimeout
+ );
+ }
+
+ #[test]
+ fn no_republish_capability_waits_for_overall_without_cancel_or_first_chunk_timeout() {
+ for was_direct_dispatched in [false, true] {
+ assert_eq!(
+ first_chunk_deadline_action(false, was_direct_dispatched, false, false,),
+ FirstChunkDeadlineAction::WaitForOverall
+ );
+ }
+ }
+
#[tokio::test]
async fn pending_work_guard_drop_claims_and_finishes_once() {
let probe = Arc::new(AbandonmentProbe::default());
@@ -12478,13 +13434,20 @@ mod tests {
let registry = ModelRegistry::new(bundles_dir.path(), models_dir.path(), true);
assert!(!registry.has_any_models());
- let default = resolve_bundle_for_request(&registry, "org/model", "", None, "encode")
- .expect("empty registry + no override resolves");
+ let default =
+ resolve_bundle_for_request(&registry, "org/model", "org/model", "", None, "encode")
+ .expect("empty registry + no override resolves");
assert_eq!(default, "default");
- let overridden =
- resolve_bundle_for_request(&registry, "org/model", "custom-bundle", None, "encode")
- .expect("empty registry preserves caller bundle");
+ let overridden = resolve_bundle_for_request(
+ &registry,
+ "org/model",
+ "org/model",
+ "custom-bundle",
+ None,
+ "encode",
+ )
+ .expect("empty registry preserves caller bundle");
assert_eq!(overridden, "custom-bundle");
}
@@ -12884,31 +13847,1192 @@ mod tests {
}
}
- /// 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
- /// managed crate.
- struct SealedTestPolicy {
- visible: bool,
+ struct FixedGenerationRoutePolicy {
+ customer_model: &'static str,
+ intent: GenerationRequestIntent,
+ route: GovernedGenerationRoute,
+ }
+
+ struct PermissiveModelAccessPolicy {
+ generation: Arc<dyn crate::server::GenerationRoutePolicy>,
+ }
+
+ impl crate::server::ModelAccessPolicy for PermissiveModelAccessPolicy {
+ fn visible(&self, _resolved_model: &str, _ext: &axum::http::Extensions) -> bool {
+ true
+ }
+
+ fn generation_route_policy(&self) -> Option<&dyn crate::server::GenerationRoutePolicy> {
+ Some(self.generation.as_ref())
+ }
+ }
+
+ fn install_generation_policy(
+ state: &mut AppState,
+ policy: Arc<dyn crate::server::GenerationRoutePolicy>,
+ ) {
+ state.model_access_policy =
+ Some(Arc::new(PermissiveModelAccessPolicy { generation: policy }));
+ }
+
+ impl crate::server::GenerationRoutePolicy for FixedGenerationRoutePolicy {
+ fn resolve(
+ &self,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ (customer_model == self.customer_model && intent == self.intent)
+ .then(|| self.route.clone())
+ }
+ }
+
+ fn fixed_generation_route(
+ model: &str,
+ intent: GenerationRequestIntent,
+ ) -> FixedGenerationRoutePolicy {
+ FixedGenerationRoutePolicy {
+ customer_model: "vendor/model",
+ intent,
+ route: GovernedGenerationRoute {
+ model: model.to_string(),
+ bundle: "default".to_string(),
+ pool: "default".to_string(),
+ machine_profile: "l4".to_string(),
+ },
+ }
+ }
+
+ #[derive(Default)]
+ struct RecordingGenerationRoutePolicy {
+ calls: std::sync::Mutex<Vec<(String, GenerationRequestIntent)>>,
+ }
+
+ impl RecordingGenerationRoutePolicy {
+ fn take_calls(&self) -> Vec<(String, GenerationRequestIntent)> {
+ std::mem::take(&mut *self.calls.lock().expect("route-policy call lock"))
+ }
+ }
+
+ impl crate::server::GenerationRoutePolicy for RecordingGenerationRoutePolicy {
+ fn resolve(
+ &self,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ self.calls
+ .lock()
+ .expect("route-policy call lock")
+ .push((customer_model.to_string(), intent));
+ let model = match intent {
+ GenerationRequestIntent::Default => customer_model.to_string(),
+ GenerationRequestIntent::Grammar => format!("{customer_model}:no-spec"),
+ };
+ Some(GovernedGenerationRoute {
+ model,
+ bundle: "default".to_string(),
+ pool: "default".to_string(),
+ machine_profile: "l4".to_string(),
+ })
+ }
+ }
+
+ async fn recording_generation_state() -> (Arc<AppState>, Arc<RecordingGenerationRoutePolicy>) {
+ 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 policy = Arc::new(RecordingGenerationRoutePolicy::default());
+ install_generation_policy(&mut state, policy.clone());
+ (Arc::new(state), policy)
+ }
+
+ struct EmptyGenerationRoutePolicy;
+
+ impl crate::server::GenerationRoutePolicy for EmptyGenerationRoutePolicy {
+ fn resolve(
+ &self,
+ _customer_model: &str,
+ _intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ None
+ }
+ }
+
+ struct MappedGenerationRoutePolicy {
+ routes:
+ std::collections::HashMap<(String, GenerationRequestIntent), GovernedGenerationRoute>,
+ }
+
+ impl crate::server::GenerationRoutePolicy for MappedGenerationRoutePolicy {
+ fn resolve(
+ &self,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ self.routes
+ .get(&(customer_model.to_string(), intent))
+ .cloned()
+ }
+ }
+
+ #[derive(Default)]
+ struct GenerationTargetProbe {
+ targets: std::sync::Mutex<Vec<(String, PublishTarget)>>,
+ }
+
+ impl GenerationTargetProbe {
+ fn take_target(&self) -> (String, PublishTarget) {
+ self.targets
+ .lock()
+ .expect("target probe lock")
+ .pop()
+ .expect("generation publish target")
+ }
+ }
+
+ #[async_trait::async_trait]
+ impl WorkDispatcher for GenerationTargetProbe {
+ async fn publish_work(
+ self: Arc<Self>,
+ _target: PublishTarget,
+ _admission_pool: &str,
+ _endpoint: &str,
+ _model: &str,
+ _engine: &str,
+ _bundle_config_hash: &str,
+ _items: Vec<rmpv::Value>,
+ _params: &WorkParams,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<Vec<WorkResult>>,
+ DispatchDurability,
+ ),
+ DispatchError,
+ > {
+ unreachable!("generation target probe only accepts generation")
+ }
+
+ async fn publish_generate_streaming(
+ &self,
+ target: PublishTarget,
+ display_model: &str,
+ _engine: &str,
+ _bundle_config_hash: &str,
+ _params: &WorkParams,
+ _admission_pool: &str,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<StreamOutcome>,
+ Arc<Notify>,
+ DispatchDurability,
+ ),
+ String,
+ > {
+ self.targets
+ .lock()
+ .expect("target probe lock")
+ .push((display_model.to_string(), target));
+ let (tx, rx) = oneshot::channel();
+ tx.send(StreamOutcome {
+ text: "ok".to_string(),
+ finish_reason: "stop".to_string(),
+ usage: Some(crate::queue::streaming::UsageBlock {
+ prompt_tokens: 1,
+ completion_tokens: 1,
+ total_tokens: 2,
+ }),
+ attempt_id: "attempt-1".to_string(),
+ ttft_ms: None,
+ tpot_ms: None,
+ error: None,
+ tool_calls: None,
+ logprobs: None,
+ candidates: Vec::new(),
+ executed_bundle_config_hash: None,
+ execution_identity_sha256: None,
+ })
+ .expect("target probe outcome receiver");
+ Ok((
+ "request-1".to_string(),
+ rx,
+ Arc::new(Notify::new()),
+ DispatchDurability::accepted(),
+ ))
+ }
+
+ async fn publish_generate_streaming_sse(
+ &self,
+ _target: PublishTarget,
+ _display_model: &str,
+ _engine: &str,
+ _bundle_config_hash: &str,
+ _params: &WorkParams,
+ _admission_pool: &str,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<StreamOutcome>,
+ broadcast::Receiver<ChunkEnvelope>,
+ DispatchDurability,
+ ),
+ String,
+ > {
+ unreachable!("bounded target proof uses non-streaming requests")
+ }
+
+ async fn publish_cancel(&self, _request_id: &str) {}
+
+ fn begin_work_abandonment(&self, _request_id: &str) -> bool {
+ true
+ }
+
+ async fn finish_work_abandonment(&self, _request_id: &str) {}
+
+ async fn republish_to_pool(
+ &self,
+ _request_id: &str,
+ _reason: &'static str,
+ ) -> Result<bool, String> {
+ Ok(false)
+ }
+
+ async fn republish_pending_result_to_pool(
+ &self,
+ _request_id: &str,
+ _reason: &'static str,
+ ) -> Result<bool, String> {
+ Ok(false)
+ }
+
+ fn drop_pending_stream(&self, _request_id: &str) {}
+
+ fn pending_generation_snapshot(&self) -> PendingGenerationSnapshot {
+ PendingGenerationSnapshot::default()
+ }
+
+ fn pending_generation_for_model(&self, _model_id: &str) -> PendingGenerationSnapshot {
+ PendingGenerationSnapshot::default()
+ }
+
+ fn stream_observed_first_chunk(&self, _request_id: &str) -> bool {
+ false
+ }
+
+ fn stream_chunk_timing(
+ &self,
+ _request_id: &str,
+ ) -> Option<(Option<Instant>, Option<Instant>)> {
+ None
+ }
+ }
+
+ fn mixed_governed_registry() -> crate::state::model_registry::ModelRegistry {
+ use crate::types::model::{ModelConfig, ProfileConfig};
+
+ let registry = grammar_routed_registry();
+ let mut profiles = std::collections::HashMap::new();
+ profiles.insert(
+ "default".to_string(),
+ ProfileConfig {
+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
+ max_batch_tokens: Some(4096),
+ compute_precision: None,
+ adapter_options: None,
+ extends: None,
+ },
+ );
+ let tasks: serde_yaml::Value =
+ serde_yaml::from_str("generate:\n capabilities:\n grammar: [json_schema]\n")
+ .expect("generation task");
+ registry
+ .add_model_config(ModelConfig {
+ name: "org/h".to_string(),
+ hf_revision: None,
+ adapter_module: None,
+ default_bundle: None,
+ pool: None,
+ profiles,
+ inputs: None,
+ max_sequence_length: None,
+ tasks: Some(tasks),
+ })
+ .expect("h100 test model");
+ registry
+ }
+
+ async fn mixed_governed_generation_state(
+ reverse_insertion: bool,
+ ) -> (Arc<AppState>, Arc<GenerationTargetProbe>) {
+ let profiles = vec![
+ "l4".to_string(),
+ "a100-80gb".to_string(),
+ "h100".to_string(),
+ ];
+ let pool_manager = Arc::new(PoolManager::new(profiles.clone()));
+ pool_manager.create_default_pool().await;
+ let mut state = admission_test_state(pool_manager);
+ state.model_registry = Arc::new(mixed_governed_registry());
+
+ let physical_lanes = crate::state::demand_tracker::PhysicalLaneCatalog::try_from_raw(
+ profiles.iter().map(|profile| {
+ (
+ "default".to_string(),
+ profile.clone(),
+ "default".to_string(),
+ )
+ }),
+ )
+ .expect("mixed physical lanes");
+ let config = Arc::make_mut(&mut state.config);
+ config.configured_gpus = profiles.clone();
+ config.gpu_profile_map = profiles
+ .iter()
+ .map(|profile| (profile.clone(), profile.clone()))
+ .collect();
+ config.configured_physical_lanes = physical_lanes.clone();
+ state.demand_tracker = Arc::new(crate::state::demand_tracker::DemandTracker::new(
+ physical_lanes,
+ ));
+
+ let mut routes = vec![
+ (
+ ("org/g".to_string(), GenerationRequestIntent::Default),
+ GovernedGenerationRoute {
+ model: "org/g".to_string(),
+ bundle: "default".to_string(),
+ pool: "default".to_string(),
+ machine_profile: "l4".to_string(),
+ },
+ ),
+ (
+ ("org/g".to_string(), GenerationRequestIntent::Grammar),
+ GovernedGenerationRoute {
+ model: "org/g:no-spec".to_string(),
+ bundle: "default".to_string(),
+ pool: "default".to_string(),
+ machine_profile: "a100-80gb".to_string(),
+ },
+ ),
+ (
+ ("org/h".to_string(), GenerationRequestIntent::Default),
+ GovernedGenerationRoute {
+ model: "org/h".to_string(),
+ bundle: "default".to_string(),
+ pool: "default".to_string(),
+ machine_profile: "h100".to_string(),
+ },
+ ),
+ ];
+ if reverse_insertion {
+ routes.reverse();
+ }
+ install_generation_policy(
+ &mut state,
+ Arc::new(MappedGenerationRoutePolicy {
+ routes: routes.into_iter().collect(),
+ }),
+ );
+
+ let (bundle_hash, _) = state
+ .model_registry
+ .bundle_execution_evidence("default", "default", "org/g");
+ let mut worker_profiles = profiles;
+ if reverse_insertion {
+ worker_profiles.reverse();
+ }
+ for profile in worker_profiles {
+ let mut status = worker_msg("default", &profile, "default");
+ status.name = format!("worker-{profile}");
+ status.bundle_config_hash = bundle_hash.clone();
+ state
+ .registry
+ .update_worker(&format!("http://worker-{profile}:8080"), status)
+ .await;
+ }
+
+ let probe = Arc::new(GenerationTargetProbe::default());
+ state.work_publisher = Some(probe.clone());
+ (Arc::new(state), probe)
+ }
+
+ fn assert_generation_target(
+ target: (String, PublishTarget),
+ display_model: &str,
+ model: &str,
+ profile: &str,
+ ) {
+ assert_eq!(target.0, display_model);
+ let (pool, machine_profile, bundle, dispatch_model) = match target.1 {
+ PublishTarget::Worker {
+ pool,
+ machine_profile,
+ bundle,
+ model,
+ ..
+ }
+ | PublishTarget::Pool {
+ pool,
+ machine_profile,
+ bundle,
+ model,
+ } => (pool, machine_profile, bundle, model),
+ };
+ assert_eq!(
+ (
+ pool.as_str(),
+ machine_profile.as_str(),
+ bundle.as_str(),
+ dispatch_model.as_str()
+ ),
+ ("default", profile, "default", model)
+ );
+ }
+
+ fn json_request(uri: &str, body: serde_json::Value) -> Request {
+ Request::builder()
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&body).expect("request JSON")))
+ .expect("request")
+ }
+
+ #[tokio::test]
+ async fn governed_native_generate_routes_default_and_grammar_before_worker_lookup() {
+ for (body, expected_intent) in [
+ (
+ serde_json::json!({"prompt": "hello", "max_new_tokens": 4}),
+ GenerationRequestIntent::Default,
+ ),
+ (
+ serde_json::json!({
+ "prompt": "hello",
+ "max_new_tokens": 4,
+ "grammar": {"json_schema": {"type": "object"}}
+ }),
+ GenerationRequestIntent::Grammar,
+ ),
+ ] {
+ let (state, policy) = recording_generation_state().await;
+ let response = proxy_request(
+ State(state),
+ json_request("/v1/generate/org%2Fg", body),
+ "generate",
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(
+ policy.take_calls(),
+ vec![("org/g".to_string(), expected_intent)]
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn governed_openai_generation_routes_chat_completions_and_responses() {
+ let cases = [
+ (
+ "/v1/chat/completions",
+ serde_json::json!({
+ "model": "org/g",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 4
+ }),
+ GenerationRequestIntent::Default,
+ ),
+ (
+ "/v1/chat/completions",
+ serde_json::json!({
+ "model": "org/g",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 4,
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "answer",
+ "schema": {"type": "object"}
+ }
+ }
+ }),
+ GenerationRequestIntent::Grammar,
+ ),
+ (
+ "/v1/completions",
+ serde_json::json!({
+ "model": "org/g",
+ "prompt": "hello",
+ "max_tokens": 4
+ }),
+ GenerationRequestIntent::Default,
+ ),
+ (
+ "/v1/responses",
+ serde_json::json!({
+ "model": "org/g",
+ "input": "hello",
+ "max_output_tokens": 4
+ }),
+ GenerationRequestIntent::Default,
+ ),
+ ];
+
+ for (uri, body, expected_intent) in cases {
+ let (state, policy) = recording_generation_state().await;
+ let request = json_request(uri, body);
+ let response = match uri {
+ "/v1/chat/completions" => proxy_chat(State(state), request).await,
+ "/v1/completions" => proxy_completions(State(state), request).await,
+ "/v1/responses" => proxy_responses(State(state), request).await,
+ _ => unreachable!("bounded OpenAI generation test surface"),
+ };
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(
+ policy.take_calls(),
+ vec![("org/g".to_string(), expected_intent)],
+ "governed route lookup for {uri}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn governed_generation_dispatch_targets_are_exact_and_order_independent() {
+ for reverse_insertion in [false, true] {
+ let (state, probe) = mixed_governed_generation_state(reverse_insertion).await;
+
+ let response = 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!(response.status(), StatusCode::OK);
+ assert_generation_target(probe.take_target(), "org/g", "org/g", "l4");
+
+ let response = proxy_request(
+ State(Arc::clone(&state)),
+ json_request(
+ "/v1/generate/org%2Fg",
+ serde_json::json!({
+ "prompt": "hello",
+ "max_new_tokens": 4,
+ "grammar": {"json_schema": {"type": "object"}}
+ }),
+ ),
+ "generate",
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_generation_target(probe.take_target(), "org/g", "org/g:no-spec", "a100-80gb");
+
+ let response = proxy_chat(
+ State(Arc::clone(&state)),
+ json_request(
+ "/v1/chat/completions",
+ serde_json::json!({
+ "model": "org/h",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 4
+ }),
+ ),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_generation_target(probe.take_target(), "org/h", "org/h", "h100");
+
+ let response = proxy_chat(
+ State(Arc::clone(&state)),
+ json_request(
+ "/v1/chat/completions",
+ serde_json::json!({
+ "model": "org/g",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 4,
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "answer",
+ "schema": {"type": "object"}
+ }
+ }
+ }),
+ ),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_generation_target(probe.take_target(), "org/g", "org/g:no-spec", "a100-80gb");
+
+ let response = proxy_completions(
+ State(Arc::clone(&state)),
+ json_request(
+ "/v1/completions",
+ serde_json::json!({
+ "model": "org/g",
+ "prompt": "hello",
+ "max_tokens": 4
+ }),
+ ),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_generation_target(probe.take_target(), "org/g", "org/g", "l4");
+
+ let response = proxy_responses(
+ State(Arc::clone(&state)),
+ json_request(
+ "/v1/responses",
+ serde_json::json!({
+ "model": "org/h",
+ "input": "hello",
+ "max_output_tokens": 4
+ }),
+ ),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_generation_target(probe.take_target(), "org/h", "org/h", "h100");
+ }
+ }
+
+ #[tokio::test]
+ async fn self_hosted_native_grammar_dispatches_profile_variant_after_one_parse() {
+ let (state, probe) = mixed_governed_generation_state(false).await;
+ let mut state = Arc::try_unwrap(state).unwrap_or_else(|_| panic!("unique test state"));
+ state.model_access_policy = None;
+ let state = Arc::new(state);
+ let mut request = json_request(
+ "/v1/generate/org%2Fg",
+ serde_json::json!({
+ "prompt": "hello",
+ "max_new_tokens": 4,
+ "grammar": {"json_schema": {"type": "object"}}
+ }),
+ );
+ request.headers_mut().insert(
+ "x-sie-machine-profile",
+ HeaderValue::from_static("a100-80gb"),
+ );
+
+ let response = proxy_request(State(state), request, "generate").await;
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_generation_target(probe.take_target(), "org/g", "org/g:no-spec", "a100-80gb");
+ }
+
+ #[tokio::test]
+ async fn installed_empty_generation_policy_fails_native_and_openai_closed() {
+ 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());
+ install_generation_policy(&mut state, Arc::new(EmptyGenerationRoutePolicy));
+ let state = Arc::new(state);
+
+ let native = 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!(native.status(), StatusCode::SERVICE_UNAVAILABLE);
+
+ let chat = proxy_chat(
+ State(state),
+ json_request(
+ "/v1/chat/completions",
+ serde_json::json!({
+ "model": "org/g",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 4
+ }),
+ ),
+ )
+ .await;
+ assert_eq!(chat.status(), StatusCode::SERVICE_UNAVAILABLE);
+ }
+
+ #[test]
+ fn governed_generation_route_is_exact_and_missing_keys_fail_closed() {
+ let pool_manager = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ let mut state = admission_test_state(pool_manager);
+ install_generation_policy(
+ &mut state,
+ Arc::new(fixed_generation_route(
+ "vendor/model:no-spec",
+ GenerationRequestIntent::Grammar,
+ )),
+ );
+
+ let route = governed_generation_route(
+ &state,
+ "vendor/model",
+ "vendor/model:no-spec",
+ GenerationRequestIntent::Grammar,
+ )
+ .expect("matching governed route")
+ .expect("installed policy route");
+ assert_eq!(route.machine_profile, "l4");
+ assert_eq!(route.model, "vendor/model:no-spec");
+
+ let missing = governed_generation_route(
+ &state,
+ "vendor/model",
+ "vendor/model",
+ GenerationRequestIntent::Default,
+ )
+ .expect_err("a governed mapping miss must not fall back");
+ assert_eq!(missing.status(), StatusCode::SERVICE_UNAVAILABLE);
+ }
+
+ #[test]
+ fn governed_generation_route_adopts_omitted_headers_and_rejects_wrong_gpu() {
+ let pool_manager = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ let state = admission_test_state(pool_manager);
+ let route = fixed_generation_route("vendor/model", GenerationRequestIntent::Default).route;
+
+ let adopted = governed_profile_and_pool(&state, &HeaderMap::new(), &route)
+ .expect("omitted overrides adopt the compiled route");
+ assert_eq!(adopted.gpu, "l4");
+ assert_eq!(adopted.pool_name, "default");
+
+ let mut headers = HeaderMap::new();
+ headers.insert("x-sie-machine-profile", HeaderValue::from_static("h100"));
+ let rejected = match governed_profile_and_pool(&state, &headers, &route) {
+ Err(response) => response,
+ Ok(_) => panic!("a conflicting GPU pin must not select a sibling lane"),
+ };
+ assert_eq!(rejected.status(), StatusCode::BAD_REQUEST);
+
+ let mut conflicting_pool_headers = HeaderMap::new();
+ conflicting_pool_headers.insert(
+ "x-sie-machine-profile",
+ HeaderValue::from_static("default/l4"),
+ );
+ conflicting_pool_headers.insert("x-sie-pool", HeaderValue::from_static("other"));
+ let rejected = match governed_profile_and_pool(&state, &conflicting_pool_headers, &route) {
+ Err(response) => response,
+ Ok(_) => panic!("conflicting inline and explicit pool pins must fail"),
+ };
+ assert_eq!(rejected.status(), StatusCode::BAD_REQUEST);
+
+ for header in ["x-sie-machine-profile", "x-sie-pool"] {
+ let mut invalid_utf8 = HeaderMap::new();
+ invalid_utf8.insert(
+ header,
+ HeaderValue::from_bytes(b"\xff").expect("opaque header"),
+ );
+ let rejected = match governed_profile_and_pool(&state, &invalid_utf8, &route) {
+ Err(response) => response,
+ Ok(_) => panic!("invalid UTF-8 routing headers must fail"),
+ };
+ assert_eq!(rejected.status(), StatusCode::BAD_REQUEST);
+ }
+ }
+
+ #[tokio::test]
+ async fn governed_native_route_rejects_incompatible_compiled_bundle() {
+ let pool_manager = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ let mut state = admission_test_state(pool_manager);
+ let mut policy = fixed_generation_route("vendor/model", GenerationRequestIntent::Default);
+ policy.route.bundle = "missing-bundle".to_string();
+ install_generation_policy(&mut state, Arc::new(policy));
+
+ let result = resolve_routing(
+ &state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ "/v1/generate/vendor%2Fmodel",
+ "generate",
+ Some(GenerationRequestIntent::Default),
+ )
+ .await;
+
+ match result {
+ Ok(_) => panic!("incompatible compiled bundle must fail closed"),
+ Err(response) => assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE),
+ }
+ }
+
+ /// 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
+ /// managed crate.
+ struct SealedTestPolicy {
+ visible: bool,
+ }
+ impl crate::server::ModelAccessPolicy for SealedTestPolicy {
+ fn visible(&self, _resolved_model: &str, _ext: &axum::http::Extensions) -> bool {
+ self.visible
+ }
+ fn sealed_route(
+ &self,
+ resolved_model: &str,
+ _ext: &axum::http::Extensions,
+ ) -> Option<crate::server::SealedRoute> {
+ resolved_model
+ .starts_with("org-")
+ .then(|| crate::server::SealedRoute {
+ engine: "sealed".to_string(),
+ bundle: "sealed".to_string(),
+ pool: "sealed".to_string(),
+ machine_profile: "sealed".to_string(),
+ })
+ }
+ }
+
+ /// A #2542 test policy: refuses one model outright and records every id it
+ /// was asked about, so a test can prove WHICH string the seam consults —
+ /// the caller's, or the one the registry resolved.
+ struct RefusingTestPolicy {
+ refuse: &'static str,
+ visible: bool,
+ asked: Arc<std::sync::Mutex<Vec<String>>>,
+ }
+ impl RefusingTestPolicy {
+ fn new(refuse: &'static str) -> Self {
+ Self {
+ refuse,
+ visible: true,
+ asked: Arc::new(std::sync::Mutex::new(Vec::new())),
+ }
+ }
+ fn asked(&self) -> Vec<String> {
+ self.asked.lock().expect("asked lock").clone()
+ }
+ }
+ impl crate::server::ModelAccessPolicy for RefusingTestPolicy {
+ fn visible(&self, _resolved_model: &str, _ext: &axum::http::Extensions) -> bool {
+ self.visible
+ }
+ fn serving_refusal(
+ &self,
+ resolved_model: &str,
+ _ext: &axum::http::Extensions,
+ ) -> Option<Response> {
+ self.asked
+ .lock()
+ .expect("asked lock")
+ .push(resolved_model.to_string());
+ (resolved_model == self.refuse)
+ .then(|| (StatusCode::FORBIDDEN, "refused").into_response())
+ }
+ /// Seals every `org-` id, exactly like [`SealedTestPolicy`], so ONE
+ /// stub can both refuse and seal the same model — the only way to
+ /// observe which of the two branches `resolve_routing` reaches first.
+ fn sealed_route(
+ &self,
+ resolved_model: &str,
+ _ext: &axum::http::Extensions,
+ ) -> Option<crate::server::SealedRoute> {
+ resolved_model
+ .starts_with("org-")
+ .then(|| crate::server::SealedRoute {
+ engine: "sealed".to_string(),
+ bundle: "sealed".to_string(),
+ pool: "sealed".to_string(),
+ machine_profile: "sealed".to_string(),
+ })
+ }
+ }
+
+ fn state_with_alias(alias: &str, target: &str) -> AppState {
+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ let mut state = admission_test_state(pm);
+ let mut config = (*state.config).clone();
+ config
+ .model_aliases
+ .insert(alias.to_string(), target.to_string());
+ state.config = Arc::new(config);
+ state
+ }
+
+ /// A registry holding exactly one real model, in temp dirs the CALLER owns.
+ ///
+ /// `admission_test_state`'s dirs are dropped with it, so its registry is
+ /// permanently empty — which silently routes an unknown model to the
+ /// empty-registry bundle fallback instead of the `has_any_models` 404. The
+ /// #2542 no-oracle tests compare against that 404, so they need a registry
+ /// that is populated and stays on disk.
+ fn populated_registry() -> (Arc<ModelRegistry>, tempfile::TempDir, tempfile::TempDir) {
+ let bundles_dir = tempfile::TempDir::new().unwrap();
+ let models_dir = tempfile::TempDir::new().unwrap();
+ std::fs::write(
+ bundles_dir.path().join("default.yaml"),
+ "name: default\nadapters:\n - module\ndefault: true\n",
+ )
+ .unwrap();
+ std::fs::write(
+ models_dir.path().join("known.yaml"),
+ "sie_id: known/model\nprofiles:\n default:\n adapter_path: sie_server.adapters.sentence_transformer:Adapter\n",
+ )
+ .unwrap();
+ let registry = Arc::new(ModelRegistry::new(
+ bundles_dir.path(),
+ models_dir.path(),
+ true,
+ ));
+ assert!(registry.has_any_models());
+ (registry, bundles_dir, models_dir)
+ }
+
+ fn hiding_policy() -> Arc<RefusingTestPolicy> {
+ Arc::new(RefusingTestPolicy {
+ refuse: "nothing-is-refused-here",
+ visible: false,
+ asked: Arc::new(std::sync::Mutex::new(Vec::new())),
+ })
+ }
+
+ /// #2542: the seam asks about the model the ALIAS resolves to, not the string
+ /// the caller sent. An edge gate can only ever see `fast`, so this is the
+ /// vantage point that makes the refusal authoritative.
+ #[tokio::test]
+ async fn resolve_routing_refuses_a_model_the_policy_will_not_serve() {
+ let mut state = state_with_alias("fast", "vendor/refused");
+ let policy = Arc::new(RefusingTestPolicy::new("vendor/refused"));
+ state.model_access_policy =
+ Some(Arc::clone(&policy) as Arc<dyn crate::server::ModelAccessPolicy>);
+ let result = resolve_routing(
+ &state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ "/v1/encode/fast",
+ "encode",
+ None,
+ )
+ .await;
+ match result {
+ Ok(_) => panic!("a refused model must never reach a lane"),
+ Err(resp) => assert_eq!(resp.status(), StatusCode::FORBIDDEN),
+ }
+ assert_eq!(policy.asked(), vec!["vendor/refused".to_string()]);
+ }
+
+ /// The other direction: an alias onto a model the policy serves resolves and
+ /// routes normally, so the verdict is a decision and not a blanket deny.
+ #[tokio::test]
+ async fn resolve_routing_serves_an_alias_the_policy_allows() {
+ let mut state = state_with_alias("quick", "vendor/served");
+ let policy = Arc::new(RefusingTestPolicy::new("vendor/refused"));
+ state.model_access_policy =
+ Some(Arc::clone(&policy) as Arc<dyn crate::server::ModelAccessPolicy>);
+ let routing = resolve_routing(
+ &state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ "/v1/encode/quick",
+ "encode",
+ None,
+ )
+ .await
+ .expect("an allowed alias must route");
+ assert_eq!(routing.model_name, "vendor/served");
+ assert_eq!(policy.asked(), vec!["vendor/served".to_string()]);
+ }
+
+ /// Ordering lock (#1841 × #2542): a caller who may not SEE the model is
+ /// answered the flat 404 and the serving verdict is never consulted, so a
+ /// refusal shape can never become a cross-org existence oracle.
+ #[tokio::test]
+ async fn resolve_routing_runs_the_visibility_gate_before_the_serving_refusal() {
+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ let mut state = admission_test_state(pm);
+ let mut policy = RefusingTestPolicy::new("org-7/support-embedder");
+ policy.visible = false;
+ let policy = Arc::new(policy);
+ state.model_access_policy =
+ Some(Arc::clone(&policy) as Arc<dyn crate::server::ModelAccessPolicy>);
+ let result = resolve_routing(
+ &state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ "/v1/encode/org-7/support-embedder",
+ "encode",
+ None,
+ )
+ .await;
+ match result {
+ Ok(_) => panic!("a hidden model must 404"),
+ Err(resp) => assert_eq!(resp.status(), StatusCode::NOT_FOUND),
+ }
+ assert!(
+ policy.asked().is_empty(),
+ "the serving verdict must not run for a model the caller cannot see"
+ );
+ }
+
+ /// The OTHER half of that ordering (#2542): the refusal runs BEFORE the
+ /// sealed branch, so a refused model cannot reach a lane.
+ ///
+ /// The sealed branch returns `Ok(RoutingResult)` — a dispatch — so a
+ /// reorder would not merely change a status code, it would serve a model
+ /// the deployment refuses. One policy that both refuses and seals the same
+ /// `org-N/` id is the only way to observe which branch wins; separate
+ /// stubs, each exercising its own branch, would pass either way.
+ #[tokio::test]
+ async fn resolve_routing_refuses_before_it_seals() {
+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ let mut state = admission_test_state(pm);
+ let policy = Arc::new(RefusingTestPolicy::new("org-7/support-embedder"));
+ state.model_access_policy =
+ Some(Arc::clone(&policy) as Arc<dyn crate::server::ModelAccessPolicy>);
+ let result = resolve_routing(
+ &state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ "/v1/encode/org-7/support-embedder",
+ "encode",
+ None,
+ )
+ .await;
+ match result {
+ Ok(routing) => panic!("a refused model reached the {} lane", routing.engine),
+ Err(resp) => assert_eq!(resp.status(), StatusCode::FORBIDDEN),
+ }
+
+ // The control: the SAME policy still seals an org id it does not
+ // refuse, so the assertion above is about ordering and not about the
+ // sealed branch having been disabled.
+ let sealed = resolve_routing(
+ &state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ "/v1/encode/org-7/other-embedder",
+ "encode",
+ None,
+ )
+ .await
+ .expect("an unrefused org model still seals");
+ assert_eq!(sealed.engine, "sealed");
+ }
+
+ /// #2542 no-oracle rendering, native surface. An operator alias whose target
+ /// sits in another org's namespace must not be readable out of the 404 body,
+ /// and the refusal must be **byte-identical** to the one an absent model
+ /// gets — otherwise the wording alone tells a tenant that something is there
+ /// and hidden. Both halves are asserted, because fixing only the id would
+ /// leave the message template as the oracle.
+ #[tokio::test]
+ async fn resolve_routing_cross_org_404_reveals_nothing_the_caller_did_not_send() {
+ let (registry, _bundles, _models) = populated_registry();
+
+ let mut hidden_state = state_with_alias("support", "org-42/support-gen");
+ hidden_state.model_registry = Arc::clone(&registry);
+ hidden_state.model_access_policy =
+ Some(hiding_policy() as Arc<dyn crate::server::ModelAccessPolicy>);
+ let hidden = match resolve_routing(
+ &hidden_state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ "/v1/encode/support",
+ "encode",
+ None,
+ )
+ .await
+ {
+ Ok(_) => panic!("a hidden model must 404"),
+ Err(resp) => *resp,
+ };
+ assert_eq!(hidden.status(), StatusCode::NOT_FOUND);
+ let hidden_body = to_bytes(hidden.into_body(), 64 * 1024).await.expect("body");
+ let hidden_body = String::from_utf8(hidden_body.to_vec()).expect("utf8");
+ assert!(
+ !hidden_body.contains("org-42"),
+ "the alias target must not appear in the 404 body: {hidden_body}"
+ );
+ assert!(hidden_body.contains("support"), "{hidden_body}");
+
+ // The SAME request with no policy installed, against the same populated
+ // registry: `support` resolves to a model that simply is not there. The
+ // two responses must be one response — otherwise the wording alone tells
+ // the caller that something exists and is hidden from them.
+ let mut absent_state = state_with_alias("support", "org-42/support-gen");
+ absent_state.model_registry = registry;
+ absent_state.model_access_policy = None;
+ let absent = match resolve_routing(
+ &absent_state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ "/v1/encode/support",
+ "encode",
+ None,
+ )
+ .await
+ {
+ Ok(_) => panic!("an absent model must 404 against a populated registry"),
+ Err(resp) => *resp,
+ };
+ assert_eq!(absent.status(), StatusCode::NOT_FOUND);
+ let absent_body = to_bytes(absent.into_body(), 64 * 1024).await.expect("body");
+ assert_eq!(
+ hidden_body,
+ String::from_utf8(absent_body.to_vec()).expect("utf8"),
+ "hidden and absent must be one response"
+ );
}
- impl crate::server::ModelAccessPolicy for SealedTestPolicy {
- fn visible(&self, _resolved_model: &str, _ext: &axum::http::Extensions) -> bool {
- self.visible
- }
- fn sealed_route(
- &self,
- resolved_model: &str,
- _ext: &axum::http::Extensions,
- ) -> Option<crate::server::SealedRoute> {
- resolved_model
- .starts_with("org-")
- .then(|| crate::server::SealedRoute {
- engine: "sealed".to_string(),
- bundle: "sealed".to_string(),
- pool: "sealed".to_string(),
- machine_profile: "sealed".to_string(),
- })
- }
+
+ /// The same rule on the OpenAI body seam, and the same
+ /// hidden-vs-absent equality — this time against a REAL populated registry,
+ /// so the comparison is with the live `has_any_models` 404 rather than a
+ /// fallback branch.
+ #[tokio::test]
+ async fn resolve_model_and_bundle_cross_org_404_is_the_absent_model_404() {
+ // A populated registry so the unknown-model arm (not the empty-registry
+ // fallback) is what an absent model reaches.
+ let (registry, _bundles, _models) = populated_registry();
+
+ let mut state = state_with_alias("support", "org-42/support-gen");
+ state.model_registry = Arc::clone(&registry);
+ state.model_access_policy =
+ Some(hiding_policy() as Arc<dyn crate::server::ModelAccessPolicy>);
+ let hidden = resolve_model_and_bundle(&state, "support", &axum::http::Extensions::new())
+ .expect_err("a hidden model must 404");
+ assert_eq!(hidden.status(), StatusCode::NOT_FOUND);
+
+ let mut open = state_with_alias("support", "org-42/support-gen");
+ open.model_registry = registry;
+ open.model_access_policy = None;
+ let absent = resolve_model_and_bundle(&open, "support", &axum::http::Extensions::new())
+ .expect_err("an unresolvable model must 404");
+ assert_eq!(absent.status(), StatusCode::NOT_FOUND);
+
+ let hidden = to_bytes(hidden.into_body(), 64 * 1024).await.expect("body");
+ let absent = to_bytes(absent.into_body(), 64 * 1024).await.expect("body");
+ let hidden = String::from_utf8(hidden.to_vec()).expect("utf8");
+ assert!(
+ !hidden.contains("org-42"),
+ "the alias target must not appear in the 404 body: {hidden}"
+ );
+ assert_eq!(
+ hidden,
+ String::from_utf8(absent.to_vec()).expect("utf8"),
+ "hidden and absent must be one response"
+ );
+ }
+
+ /// The OpenAI body-model seam carries the same verdict on the same resolved
+ /// id — one hook, both routing entry points, no per-surface copy.
+ #[test]
+ fn resolve_model_and_bundle_refuses_a_model_the_policy_will_not_serve() {
+ let mut state = state_with_alias("fast", "vendor/refused");
+ let policy = Arc::new(RefusingTestPolicy::new("vendor/refused"));
+ state.model_access_policy =
+ Some(Arc::clone(&policy) as Arc<dyn crate::server::ModelAccessPolicy>);
+ let err = resolve_model_and_bundle(&state, "fast", &axum::http::Extensions::new())
+ .expect_err("a refused model must never resolve to a bundle");
+ assert_eq!(err.status(), StatusCode::FORBIDDEN);
+ assert_eq!(policy.asked(), vec!["vendor/refused".to_string()]);
+
+ let (model, _bundle) =
+ resolve_model_and_bundle(&state, "vendor/served", &axum::http::Extensions::new())
+ .expect("an allowed model still resolves");
+ assert_eq!(model, "vendor/served");
}
#[tokio::test]
@@ -12922,6 +15046,7 @@ mod tests {
&axum::http::Extensions::new(),
"/v1/encode/org-7/support-embedder",
"encode",
+ None,
)
.await
.expect("a visible sealed model must route, not error");
@@ -12948,6 +15073,7 @@ mod tests {
&axum::http::Extensions::new(),
"/v1/encode/org-7/support-embedder",
"encode",
+ None,
)
.await;
match result {
@@ -15323,6 +17449,20 @@ mod tests {
assert!(err.contains("token-array embeddings input is not supported"));
}
+ #[test]
+ fn test_openai_embeddings_item_cap_accepts_256_and_rejects_257() {
+ let accepted = json!(vec!["text"; MAX_EMBEDDING_INPUTS]);
+ let normalized =
+ openai_embedding_input_to_texts(&accepted).expect("256 inputs are accepted");
+ assert_eq!(normalized.texts.len(), MAX_EMBEDDING_INPUTS);
+
+ let rejected = json!(vec!["text"; MAX_EMBEDDING_INPUTS + 1]);
+ let error =
+ openai_embedding_input_to_texts(&rejected).expect_err("257 inputs are rejected");
+ assert!(error.contains("at most 256 texts"));
+ assert!(error.contains("split the request"));
+ }
+
#[test]
fn test_openai_embeddings_forwarded_headers_include_encode_timings() {
for name in [
@@ -19303,6 +21443,39 @@ mod tests {
}
}
+ /// ``stream_options.include_usage`` on /v1/completions. A streamed response
+ /// cannot carry usage in headers, so this flag is the only surface on which
+ /// a streamed completion reports what it consumed.
+ #[test]
+ fn test_completions_params_accepts_stream_options_include_usage() {
+ let mut body = _completions_body_min("m");
+ assert!(matches!(
+ completions_params_from_json(&body),
+ CompletionsParamsResult::Ok(ref p) if !p.stream_include_usage
+ ));
+ body["stream"] = serde_json::json!(true);
+ body["stream_options"] = serde_json::json!({"include_usage": true});
+ match completions_params_from_json(&body) {
+ CompletionsParamsResult::Ok(p) => {
+ assert!(p.stream);
+ assert!(p.stream_include_usage);
+ }
+ CompletionsParamsResult::Err(_) => panic!("expected Ok"),
+ }
+ }
+
+ #[tokio::test]
+ async fn test_completions_rejects_stream_options_unknown_keys_and_types() {
+ let mut body = _completions_body_min("m");
+ body["stream_options"] = serde_json::json!({"foo": 1});
+ let v = _completions_err(body.clone()).await;
+ assert_eq!(v["error"]["param"], "stream_options.foo");
+
+ body["stream_options"] = serde_json::json!({"include_usage": "yes"});
+ let v = _completions_err(body).await;
+ assert_eq!(v["error"]["param"], "stream_options.include_usage");
+ }
+
#[tokio::test]
async fn test_completions_missing_model() {
let v = _completions_err(serde_json::json!({"prompt": "hi"})).await;
@@ -20283,6 +22456,31 @@ mod tests {
assert_eq!(value["error"]["attempt_id"], "att-large-1");
}
+ /// The cold-start quota refusal must reach the wire with NO Retry-After:
+ /// the blanket 429 header block previously stamped `Retry-After: 1` on it,
+ /// re-creating the exact auto-retry hot loop the hourly ceiling exists to
+ /// prevent (review finding) — and the envelope code must be the typed
+ /// refusal, never a generic `inference_error`.
+ #[tokio::test]
+ async fn test_streaming_cold_start_refusal_is_429_without_retry_after() {
+ let err = StreamingDriverErr::WorkerError {
+ code: COLD_START_RATE_LIMITED_ERROR_CODE.to_string(),
+ message: "org exceeded its sealed cold-starts-per-hour ceiling".to_string(),
+ request_id: "req-cold-1".to_string(),
+ attempt_id: "att-cold-1".to_string(),
+ };
+ let resp = build_streaming_error_response(&err);
+
+ assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
+ assert!(resp.headers().get("retry-after").is_none());
+ 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::RATE_LIMIT);
+ assert_eq!(v["error"]["code"], COLD_START_RATE_LIMITED_ERROR_CODE);
+ }
+
async fn assert_streaming_worker_error_is_retryable(
code: &'static str,
retry_after: &'static str,
@@ -20338,6 +22536,23 @@ mod tests {
);
}
+ /// The sealed cold-start quota refusal (#2426) is a deliberate 429 with
+ /// a rate-limit envelope type — never a generic server error — and stays
+ /// off the retryable lists (no Retry-After: an hourly quota must not
+ /// invite auto-retry storms).
+ #[test]
+ fn test_cold_start_rate_limited_maps_to_429_not_500() {
+ assert_eq!(
+ worker_error_http_status(COLD_START_RATE_LIMITED_ERROR_CODE),
+ StatusCode::TOO_MANY_REQUESTS
+ );
+ assert_eq!(
+ worker_error_openai_type(COLD_START_RATE_LIMITED_ERROR_CODE),
+ oai_type::RATE_LIMIT
+ );
+ assert!(worker_error_retry_after(COLD_START_RATE_LIMITED_ERROR_CODE).is_none());
+ }
+
/// Envelope ``type`` mapping unit test.
#[test]
fn test_worker_error_openai_type_rate_limit() {
@@ -20373,66 +22588,6 @@ mod tests {
assert_eq!(worker_error_retry_after("transport_failure"), None);
}
- // ── SSE: generate-endpoint `stream` flag extraction ────────────
-
- /// JSON body without ``stream`` → ``Ok(false)``. The aggregating
- /// path stays unchanged.
- #[test]
- fn test_stream_flag_from_body_absent_is_false() {
- let body = br#"{"prompt": "Hi", "max_new_tokens": 8}"#;
- assert_eq!(stream_flag_from_body(body, false).ok(), Some(false));
- }
-
- #[test]
- fn test_stream_flag_from_body_true() {
- let body = br#"{"prompt": "Hi", "max_new_tokens": 8, "stream": true}"#;
- assert_eq!(stream_flag_from_body(body, false).ok(), Some(true));
- }
-
- #[test]
- fn test_stream_flag_from_body_false_explicit() {
- let body = br#"{"prompt": "Hi", "max_new_tokens": 8, "stream": false}"#;
- assert_eq!(stream_flag_from_body(body, false).ok(), Some(false));
- }
-
- #[test]
- fn test_stream_flag_from_body_null_is_false() {
- let body = br#"{"prompt": "Hi", "max_new_tokens": 8, "stream": null}"#;
- assert_eq!(stream_flag_from_body(body, false).ok(), Some(false));
- }
-
- #[tokio::test]
- async fn test_stream_flag_from_body_non_bool_rejects_400() {
- let body = br#"{"prompt": "Hi", "max_new_tokens": 8, "stream": "yes"}"#;
- let err = stream_flag_from_body(body, false).expect_err("non-bool");
- assert_eq!(err.status(), StatusCode::BAD_REQUEST);
- let bytes = axum::body::to_bytes(err.into_body(), 4096).await.unwrap();
- let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
- assert_eq!(v["error"]["param"], "stream");
- assert_eq!(v["error"]["code"], "invalid_request");
- }
-
- /// Body that fails to decode silently maps to ``Ok(false)``: the
- /// authoritative validator is the existing ``parse_queue_request``
- /// path, which surfaces the precise error on the aggregating
- /// branch. This guard prevents double-rejection from the SSE
- /// short-circuit.
- #[test]
- fn test_stream_flag_from_body_bad_json_falls_back_to_false() {
- let body = b"not-json";
- assert_eq!(stream_flag_from_body(body, false).ok(), Some(false));
- }
-
- /// msgpack twin: a msgpack body with ``stream: true`` parses too.
- #[test]
- fn test_stream_flag_from_body_msgpack_true() {
- let body = rmp_serde::to_vec_named(&serde_json::json!({
- "prompt": "Hi", "max_new_tokens": 8, "stream": true,
- }))
- .unwrap();
- assert_eq!(stream_flag_from_body(&body, true).ok(), Some(true));
- }
-
/// Regression guard: the non-streaming aggregating path (the
/// `stream: false` default) still composes the OpenAI
/// ``chat.completion`` body exactly as before, character for
@@ -20550,6 +22705,8 @@ mod tests {
images: Some(2),
audio_ms: None,
pairs: None,
+ gpu_second: None,
+ output_tokens: None,
}),
);
for use_msgpack in [false, true] {
@@ -20575,6 +22732,8 @@ mod tests {
images: None,
audio_ms: None,
pairs: None,
+ gpu_second: None,
+ output_tokens: None,
}),
);
let body = build_queue_success_body("score", "reranker", &[&result], false);
@@ -20593,6 +22752,8 @@ mod tests {
images: Some(1),
audio_ms: None,
pairs: None,
+ gpu_second: None,
+ output_tokens: None,
}),
);
let missing_tokens = successful_score_result(
@@ -20603,6 +22764,8 @@ mod tests {
images: Some(1),
audio_ms: None,
pairs: None,
+ gpu_second: None,
+ output_tokens: None,
}),
);
assert!(aggregate_score_usage(&[&complete, &missing_tokens]).is_none());
@@ -20618,6 +22781,8 @@ mod tests {
images: None,
audio_ms: None,
pairs: None,
+ gpu_second: None,
+ output_tokens: None,
}),
);
let one = successful_score_result(
@@ -20628,6 +22793,8 @@ mod tests {
images: None,
audio_ms: None,
pairs: None,
+ gpu_second: None,
+ output_tokens: None,
}),
);
assert!(aggregate_score_usage(&[&maximum, &one]).is_none());
@@ -20906,4 +23073,343 @@ mod tests {
LoraValidation::UnknownAdapter,
);
}
+
+ // ---- `/v1/embeddings` response cap (#2617) --------------------------------
+ //
+ // These exist because the FIRST version of this cap shipped a test that
+ // "certified the mechanism while never exercising it": it probed only `CAP`
+ // and `CAP + 1`, and `CAP + 1` happened to be the single size at which the
+ // over-cap branch could fire. Everything larger — i.e. every real oversized
+ // reply — fell into the error arm and returned the opaque 500 the change
+ // existed to remove, with the suite green throughout.
+ //
+ // So the rule for this block: never probe only the boundary. Every test here
+ // covers `CAP + 2` and a realistic multiple, and the classification tests are
+ // written so that reverting `buffer_compat_response_body` to the old
+ // `to_bytes(body, CAP + 1)` shape makes them fail.
+
+ /// A realistic `/v1/encode` dense reply, serialized the way the inner
+ /// handler serializes it. `dims` floats per item, values in the range real
+ /// normalized embeddings occupy so `serde_json`'s shortest-roundtrip
+ /// formatting produces realistic byte counts rather than `0.0`.
+ fn encode_reply_bytes(items: usize, dims: usize) -> Vec<u8> {
+ let vector: Vec<f64> = (0..dims)
+ .map(|i| {
+ // f32-representable, sign-alternating, ~1e-2 magnitude — the
+ // shape a normalized embedding coordinate actually has.
+ let raw = ((i % 977) as f32) / 30011.0;
+ let signed = if i % 2 == 0 { raw } else { -raw };
+ signed as f64
+ })
+ .collect();
+ let reply = json!({
+ "items": (0..items)
+ .map(|_| json!({ "dense": vector }))
+ .collect::<Vec<_>>(),
+ });
+ serde_json::to_vec(&reply).expect("serialize encode reply")
+ }
+
+ #[tokio::test]
+ async fn compat_response_cap_admits_a_realistic_large_encode_reply() {
+ // 700 inputs at 1024 dims (bge-m3's dense width): a real bulk-embedding
+ // batch, far inside `MAX_QUEUE_REQUEST_ITEMS` (4096), that must keep
+ // being served. This is the "realistic large response still passes" case.
+ let reply = encode_reply_bytes(700, 1024);
+ assert!(
+ reply.len() > 8 * 1024 * 1024,
+ "fixture is meant to be genuinely large; got {} bytes",
+ reply.len(),
+ );
+ assert!(
+ reply.len() < MAX_COMPAT_RESPONSE_BODY,
+ "a realistic batch must still fit; got {} bytes",
+ reply.len(),
+ );
+
+ match buffer_compat_response_body(Body::from(reply.clone())).await {
+ CompatResponseBody::Buffered(bytes) => assert_eq!(bytes.len(), reply.len()),
+ other => panic!("a realistic large reply must pass, got {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn compat_response_cap_classifies_sizes_past_the_boundary() {
+ // THE regression test for the vacuous-boundary defect. `CAP` and
+ // `CAP + 1` alone were not enough: the broken implementation passed both
+ // and mis-classified everything else. `CAP + 2` is the smallest size that
+ // exposed it, and the two larger sizes are what production actually
+ // produces.
+ match buffer_compat_response_body(Body::from(vec![b'x'; MAX_COMPAT_RESPONSE_BODY])).await {
+ CompatResponseBody::Buffered(bytes) => {
+ assert_eq!(bytes.len(), MAX_COMPAT_RESPONSE_BODY)
+ }
+ other => panic!("a body exactly at the cap must pass, got {other:?}"),
+ }
+ // Classification first, across every size — so a regression reports
+ // WHICH size it mis-classified rather than tripping on a detail of the
+ // first one. Under the old implementation this names cap+2 directly.
+ let mut misclassified = Vec::new();
+ let mut unannounced = Vec::new();
+ for over in [1usize, 2, 4096, MAX_COMPAT_RESPONSE_BODY] {
+ let len = MAX_COMPAT_RESPONSE_BODY + over;
+ match buffer_compat_response_body(Body::from(vec![b'x'; len])).await {
+ CompatResponseBody::TooLarge { observed } => {
+ // The size hint is exact for an in-process body, so the
+ // caller-facing message can quote a real number.
+ if observed != Some(len as u64) {
+ unannounced.push(over);
+ }
+ }
+ other => misclassified.push(format!("cap+{over} -> {other:?}")),
+ }
+ }
+ assert!(
+ misclassified.is_empty(),
+ "every oversized body must be TooLarge; these were not: {misclassified:?}",
+ );
+ assert!(
+ unannounced.is_empty(),
+ "an in-process body announces its length; these did not report it: {unannounced:?}",
+ );
+ }
+
+ #[tokio::test]
+ async fn compat_response_cap_refuses_a_realistic_oversized_encode_reply() {
+ // The concrete production case the gate raised: a max-size batch at the
+ // queue's own item ceiling. This is the shape that returned an opaque
+ // 500 under the first implementation.
+ let reply = encode_reply_bytes(1400, 1024);
+ assert!(
+ reply.len() > MAX_COMPAT_RESPONSE_BODY + 1,
+ "fixture must be genuinely oversized, not boundary-sized; got {} bytes",
+ reply.len(),
+ );
+ match buffer_compat_response_body(Body::from(reply)).await {
+ CompatResponseBody::TooLarge { observed } => assert!(observed.is_some()),
+ other => panic!("a realistic oversized reply must be TooLarge, got {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn compat_response_cap_refuses_an_oversized_body_that_announces_no_length() {
+ // A body with no size hint cannot be pre-checked, so it must be caught by
+ // the `LengthLimitError` downcast instead. Without that second stage this
+ // case would be reported as an unreadable stream — a 500 for what is
+ // really a size condition. `lower()` is 0 here, which is what makes the
+ // downcast load-bearing rather than belt-and-braces.
+ let chunk = vec![b'y'; 1024 * 1024];
+ let chunks = (MAX_COMPAT_RESPONSE_BODY / chunk.len()) + 4;
+ let stream = futures_util::stream::iter(
+ (0..chunks).map(move |_| Ok::<_, std::io::Error>(vec![b'y'; 1024 * 1024])),
+ );
+ let body = Body::from_stream(stream);
+ {
+ use hyper::body::Body as _;
+ assert_eq!(
+ body.size_hint().lower(),
+ 0,
+ "the streamed fixture must be un-pre-checkable for this test to mean anything",
+ );
+ }
+ match buffer_compat_response_body(body).await {
+ CompatResponseBody::TooLarge { observed } => {
+ assert_eq!(observed, None, "an unannounced body has no length to quote")
+ }
+ other => panic!("an oversized unannounced body must be TooLarge, got {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn a_broken_stream_stays_unreadable_rather_than_too_large() {
+ // The other half of the classification: the two failures must not be
+ // collapsed back together. A stream that ERRORS below the cap is a
+ // plumbing fault, not a size verdict, and must keep the 500.
+ let stream = futures_util::stream::iter(vec![
+ Ok::<_, std::io::Error>(vec![b'z'; 16]),
+ Err(std::io::Error::other("upstream went away")),
+ ]);
+ match buffer_compat_response_body(Body::from_stream(stream)).await {
+ CompatResponseBody::Unreadable => {}
+ other => panic!("a broken stream must stay Unreadable, got {other:?}"),
+ }
+ }
+
+ /// Every post-dispatch terminal arm must carry [`GatewayOwnedFault`].
+ ///
+ /// The worker has already run and the meter already holds its units by the
+ /// time any of them fires, so an unmarked response is billed in full for zero
+ /// delivered embeddings (#2641's defect class).
+ ///
+ /// This drives the two SHARED constructors the arms return through, which is
+ /// what makes marking a property of the constructor rather than of each call
+ /// site. It does NOT drive the handlers end to end — that needs a live queue
+ /// — so the guarantee that every arm uses these constructors rather than
+ /// building a bare response is held by
+ /// `no_post_dispatch_arm_builds_an_unmarked_response` below, not by this.
+ #[test]
+ fn every_post_dispatch_fault_is_marked_gateway_owned() {
+ let too_large = compat_translation_fault(
+ "read_encode_response_too_large",
+ StatusCode::PAYLOAD_TOO_LARGE,
+ err_code::PAYLOAD_TOO_LARGE,
+ Some("input"),
+ "oversized".to_string(),
+ );
+ assert_eq!(too_large.status(), StatusCode::PAYLOAD_TOO_LARGE);
+ assert_eq!(
+ too_large.extensions().get::<GatewayOwnedFault>(),
+ Some(&GatewayOwnedFault::new("read_encode_response_too_large")),
+ "an over-cap reply must not bill: the customer receives no embeddings",
+ );
+ // Terminal means no retry hint — a retryable surface here would have SDK
+ // loops hammering a permanent condition (#2443).
+ assert!(
+ too_large.headers().get("retry-after").is_none(),
+ "the over-cap verdict is terminal and must carry no Retry-After",
+ );
+
+ let unreadable = compat_translation_fault(
+ "read_encode_response",
+ StatusCode::INTERNAL_SERVER_ERROR,
+ err_code::INTERNAL_ERROR,
+ None,
+ "failed".to_string(),
+ );
+ assert_eq!(
+ unreadable.extensions().get::<GatewayOwnedFault>(),
+ Some(&GatewayOwnedFault::new("read_encode_response")),
+ "the pre-existing unreadable 500 billed in full too; it is marked now",
+ );
+
+ // The three TRANSLATION arms after the buffering pair. They are the same
+ // class — worker delivered, we could not render it — and were billing in
+ // full until they were routed through this constructor.
+ for stage in [
+ "decode_encode_response",
+ "encode_response_shape",
+ "format_embeddings",
+ ] {
+ let response = compat_translation_fault(
+ stage,
+ StatusCode::INTERNAL_SERVER_ERROR,
+ err_code::INTERNAL_ERROR,
+ None,
+ "translation failed".to_string(),
+ );
+ assert_eq!(
+ response.extensions().get::<GatewayOwnedFault>(),
+ Some(&GatewayOwnedFault::new(stage)),
+ "{stage}: zero embeddings delivered must mean nothing billed",
+ );
+ }
+
+ // `/v1/rerank` runs the identical sequence against `score` and had NO
+ // marked arm at all before this change.
+ for stage in [
+ "read_score_response",
+ "decode_score_response",
+ "format_rerank",
+ ] {
+ let response = rerank_translation_fault(stage, "translation failed");
+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(
+ response.extensions().get::<GatewayOwnedFault>(),
+ Some(&GatewayOwnedFault::new(stage)),
+ "{stage}: zero rerank results delivered must mean nothing billed",
+ );
+ }
+ }
+
+ /// No post-dispatch arm builds a bare response instead of going through a
+ /// marked constructor.
+ ///
+ /// The constructors above are only load-bearing if every arm actually uses
+ /// one. This reads the two handlers' own source between the point the worker
+ /// reply is in hand and the success return, and fails on any early return
+ /// that is not routed through its marking constructor — which is exactly how
+ /// the three embeddings arms and all three rerank arms went unmarked while
+ /// their siblings were fixed.
+ #[test]
+ fn no_post_dispatch_arm_builds_an_unmarked_response() {
+ let source = include_str!("proxy.rs");
+ for (marker, end, marked_constructor) in [
+ (
+ "// From here the worker has already run and reported its units, so EVERY",
+ "let token_est = token_count;",
+ "return compat_translation_fault(",
+ ),
+ (
+ "// From here the worker has already run and reported its units, so every",
+ "let mut output = (StatusCode::OK, Json(output)).into_response();",
+ "return rerank_translation_fault(",
+ ),
+ ] {
+ let start = source
+ .find(marker)
+ .unwrap_or_else(|| panic!("post-dispatch region marker not found: {marker}"));
+ let stop = source[start..]
+ .find(end)
+ .unwrap_or_else(|| panic!("post-dispatch region end not found: {end}"));
+ let region = &source[start..start + stop];
+ let unmarked: Vec<&str> = region
+ .lines()
+ .filter(|line| line.trim_start().starts_with("return "))
+ .filter(|line| !line.contains(marked_constructor))
+ .collect();
+ assert!(
+ unmarked.is_empty(),
+ "post-dispatch arm builds a response outside a marking constructor, so it \
+ bills in full for an undelivered result: {unmarked:?}",
+ );
+ }
+ }
+
+ /// The over-cap message must name only remedies that actually work.
+ ///
+ /// `encoding_format="base64"` was named in the first revision and is inert:
+ /// it is never forwarded to `/v1/encode`, and base64 is applied afterwards to
+ /// the OUTER response assembled from the very buffer that was refused. A
+ /// caller who followed it paid for a second identical encode and received a
+ /// byte-identical rejection.
+ #[test]
+ fn the_over_cap_message_does_not_name_the_inert_base64_remedy() {
+ let body = embeddings_error(
+ err_code::PAYLOAD_TOO_LARGE,
+ Some("input"),
+ format!(
+ "the embedding response for this request is {} bytes, over the \
+ {MAX_COMPAT_RESPONSE_BODY}-byte limit; send fewer inputs per request",
+ MAX_COMPAT_RESPONSE_BODY + 1
+ ),
+ );
+ let rendered = serde_json::to_string(&body).expect("serialize");
+ assert!(
+ !rendered.contains("base64"),
+ "base64 cannot shrink the capped body; naming it sends the caller \
+ into a paid loop: {rendered}",
+ );
+ assert!(rendered.contains("send fewer inputs per request"));
+ }
+
+ /// `encoding_format` provably cannot change the body the cap measures.
+ ///
+ /// This is the structural reason the remedy above was removed, pinned so a
+ /// future change that re-adds the advice has to make it true first: the inner
+ /// encode body is built from `input` alone.
+ #[test]
+ fn encoding_format_never_reaches_the_inner_encode_request() {
+ let input = json!(["alpha", "beta"]);
+ let (float_body, _) = openai_embeddings_encode_body(&input).expect("encode body");
+ // There is no second builder that takes the format — the same call is
+ // the only path for both `float` and `base64` callers, so the inner
+ // reply, and therefore the capped buffer, is byte-identical.
+ let (again, _) = openai_embeddings_encode_body(&input).expect("encode body");
+ assert_eq!(float_body, again);
+ let rendered = serde_json::to_string(&float_body).expect("serialize");
+ assert!(
+ !rendered.contains("encoding_format") && !rendered.contains("base64"),
+ "the inner encode request carries no encoding hint: {rendered}",
+ );
+ }
}
diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rs
index 8c67e3cfa..77227f7c8 100644
--- a/packages/sie_gateway/src/handlers/sse.rs
+++ b/packages/sie_gateway/src/handlers/sse.rs
@@ -30,10 +30,18 @@
//! carries ``finish_reason`` and, when
//! ``stream_options.include_usage == true``, is followed by a
//! usage-only chunk. Always terminated by ``data: [DONE]\n\n``.
+//! * **Completion** (``/v1/completions`` with ``stream: true``): emits
+//! ``text_completion`` events with the same ``stream_options.include_usage``
+//! contract as chat.
//! * **Generate** (``/v1/generate/{model}`` with ``stream: true``):
//! emits the SIE-native shape
//! ``{request_id, seq, text_delta, done, usage?, finish_reason?, timing?}``.
-//! Same ``[DONE]`` terminator.
+//! Same ``[DONE]`` terminator; its terminal chunk carries ``usage`` inline,
+//! so it needs no separate usage-only chunk.
+//!
+//! A streamed response cannot carry usage in headers — they are flushed with
+//! the first byte — so the final chunk is the only surface on which a metered
+//! stream can report what it consumed.
//!
//! Error mid-stream: a worker-emitted error chunk (`ChunkEnvelope.error`)
//! is surfaced as a final event carrying an ``error`` block alongside
@@ -49,7 +57,7 @@ use axum::response::{IntoResponse, Response};
use serde_json::{json, Value};
use tokio::sync::broadcast;
use tokio_stream::wrappers::ReceiverStream;
-use tracing::{debug, warn};
+use tracing::{debug, info, warn};
use crate::observability::metrics as telemetry;
use crate::queue::dispatch::{PendingDispatchKind, WorkDispatcher};
@@ -70,7 +78,10 @@ pub enum SseEndpoint {
Generate,
/// OpenAI legacy Completions chunk shape (`object: "text_completion"`,
/// `choices[0].text`). Single-candidate (completions rejects `n>1`).
- Completion,
+ Completion {
+ /// Whether to emit a trailing usage-only chunk before ``[DONE]``.
+ include_usage: bool,
+ },
}
/// Parameters passed from the chat / generate handler to
@@ -377,6 +388,85 @@ struct SseDriverArgs {
pool_fallback_lane_worker_count: usize,
}
+/// How long a disconnected client's stream stays registered waiting for the
+/// worker's abort terminal.
+///
+/// A client disconnect cancels upstream, and the worker answers that cancel
+/// with an abort terminal carrying a CONSISTENT count-so-far — evidence a
+/// metered dispatcher bills exactly like a completed stream. Removing the
+/// collector at `publish_cancel` time threw that terminal away: every ordinary
+/// user stop billed zero AND raised the metered `lost_terminal_count` alert,
+/// which exists to catch compute SIE could not bill and is worthless once
+/// routine behaviour dominates it.
+///
+/// The window is the bound on how long a departed client's request-local state
+/// (collector entry, and on the managed plane the credit hold behind it)
+/// outlives the client. Five seconds covers the cancel round-trip plus the
+/// worker's in-flight decode step with room to spare, while keeping that
+/// lifetime short. On expiry the stream is torn down as a client disconnect —
+/// released without charge and WITHOUT the lost-terminal fault alert.
+const CLIENT_DISCONNECT_TERMINAL_GRACE: Duration = Duration::from_secs(5);
+
+/// Tear down a stream whose HTTP client went away.
+///
+/// Cancels upstream, then keeps the collector REGISTERED for
+/// [`CLIENT_DISCONNECT_TERMINAL_GRACE`] so the worker's abort terminal can
+/// still land and be settled. `publish_cancel` only awaits the transport's ACK
+/// of the cancel op, never the worker's terminal, so without this wait the
+/// count-so-far raced a teardown it almost always lost.
+///
+/// `outcome_rx` is `None` when the terminal already resolved — there is nothing
+/// left to wait for.
+///
+/// `stream_succeeded` follows the `#1602` discipline used by the `Lagged` arm:
+/// a request whose terminal outcome already resolved `Ok` has completed
+/// server-side, so there is nothing to cancel and the cancel would be a
+/// redundant wire op. Teardown still runs.
+async fn teardown_after_client_disconnect(
+ publisher: &Arc<dyn WorkDispatcher>,
+ request_id: &str,
+ outcome_rx: Option<std::pin::Pin<&mut tokio::sync::oneshot::Receiver<StreamOutcome>>>,
+ stream_succeeded: bool,
+) {
+ if !stream_succeeded {
+ publisher.publish_cancel(request_id).await;
+ }
+ let Some(outcome_rx) = outcome_rx else {
+ publisher.drop_pending_stream(request_id);
+ return;
+ };
+ // `Ok(Ok(_))` ONLY. `timeout(..).is_ok()` is also true for `Ok(Err(RecvError))`
+ // — the collector's sender dropped without ever sending a terminal — which
+ // is the opposite billing signal: no count-so-far was settled, so taking the
+ // fault-raising teardown there raises `lost_terminal_count` for exactly the
+ // ordinary client stop this grace window exists to keep quiet.
+ if matches!(
+ tokio::time::timeout(CLIENT_DISCONNECT_TERMINAL_GRACE, outcome_rx).await,
+ Ok(Ok(_))
+ ) {
+ // The terminal landed inside the window. The collector fired its
+ // outcome, so a metered dispatcher has already settled the
+ // worker-reported count-so-far; this removal is idempotent cleanup.
+ debug!(
+ request_id = %request_id,
+ "cancelled stream reached its worker terminal; count-so-far settled"
+ );
+ publisher.drop_pending_stream(request_id);
+ return;
+ }
+ // No terminal inside the window. Not a billing fault — the client left and
+ // the worker never reported. Release through the disconnect-specific path so
+ // metered dispatchers can drop the hold quietly instead of raising the
+ // lost-terminal alert.
+ info!(
+ request_id = %request_id,
+ grace_s = CLIENT_DISCONNECT_TERMINAL_GRACE.as_secs_f64(),
+ "cancelled stream produced no worker terminal within the grace window; \
+ releasing without charge"
+ );
+ publisher.drop_pending_stream_client_disconnect(request_id);
+}
+
#[derive(Debug, Eq, PartialEq)]
enum TerminalDurabilityWait {
Confirmed,
@@ -472,6 +562,7 @@ async fn run_sse_driver(args: SseDriverArgs) {
// ``finish_reason``/``logprobs``.
let mut multi_candidate_stream = false;
let mut republished_for_first_chunk = false;
+ let supports_first_chunk_pool_republish = publisher.supports_first_chunk_pool_republish();
let single_consumer_lane_at_dispatch = crate::routing::suppress_first_chunk_republish_for_lane(
was_direct_dispatched,
pool_fallback_lane_worker_count,
@@ -538,9 +629,13 @@ async fn run_sse_driver(args: SseDriverArgs) {
// `run_streaming_generate`). The broadcast receiver is
// already subscribed, so chunks from the republished
// attempt flow into this same loop.
- if was_direct_dispatched
- && !republished_for_first_chunk
- && !single_consumer_lane_at_dispatch
+ let deadline_action = crate::handlers::proxy::first_chunk_deadline_action(
+ supports_first_chunk_pool_republish,
+ was_direct_dispatched,
+ republished_for_first_chunk,
+ single_consumer_lane_at_dispatch,
+ );
+ if deadline_action == crate::handlers::proxy::FirstChunkDeadlineAction::RepublishToPool
{
republished_for_first_chunk = true;
// At-least-once-execution hazard (mirrors the non-SSE
@@ -582,18 +677,16 @@ async fn run_sse_driver(args: SseDriverArgs) {
}
}
}
- if single_consumer_lane_at_dispatch
- && was_direct_dispatched
- && !republished_for_first_chunk
- {
+ if deadline_action == crate::handlers::proxy::FirstChunkDeadlineAction::WaitForOverall {
republished_for_first_chunk = true;
first_chunk_deadline = overall_deadline;
tracing::debug!(
- request_id = %request_id,
- pool = %pool,
- machine_profile = %gpu,
- bundle = %bundle,
- "SSE: first_chunk_timeout - single-worker lane, suppressing republish; continuing on overall_timeout"
+ request_id = %request_id,
+ pool = %pool,
+ machine_profile = %gpu,
+ bundle = %bundle,
+ supports_pool_republish = supports_first_chunk_pool_republish,
+ "SSE: first_chunk_timeout - pool republish unavailable; continuing on overall_timeout"
);
continue;
}
@@ -708,8 +801,13 @@ async fn run_sse_driver(args: SseDriverArgs) {
telemetry::GenerationEventOutcome::Cancelled,
);
cancel_guard.defuse();
- publisher.publish_cancel(&request_id).await;
- publisher.drop_pending_stream(&request_id);
+ teardown_after_client_disconnect(
+ &publisher,
+ &request_id,
+ (!outcome_done).then_some(outcome_rx.as_mut()),
+ stream_succeeded,
+ )
+ .await;
return;
}
// Terminal outcome arm. Ordered before the chunk-tap recv so
@@ -892,6 +990,14 @@ async fn run_sse_driver(args: SseDriverArgs) {
send_done(&event_tx).await;
record_wait(telemetry::QueueResultOutcome::DurabilityError);
cancel_guard.defuse();
+ // Tear the stream down like the sibling durability arm
+ // below. This exit writes no usage surface, so it never
+ // reaches the terminal hook that would otherwise release
+ // per-stream transport state; leaving it registered strands
+ // that state until the transport's own backstop reclaims it
+ // and reports a stranded stream that was in fact torn down
+ // deliberately.
+ publisher.drop_pending_stream(&request_id);
return;
}
TerminalDurabilityWait::MonitorStopped => {
@@ -922,8 +1028,13 @@ async fn run_sse_driver(args: SseDriverArgs) {
telemetry::GenerationEventOutcome::Cancelled,
);
cancel_guard.defuse();
- publisher.publish_cancel(&request_id).await;
- publisher.drop_pending_stream(&request_id);
+ teardown_after_client_disconnect(
+ &publisher,
+ &request_id,
+ (!outcome_done).then_some(outcome_rx.as_mut()),
+ stream_succeeded,
+ )
+ .await;
return;
}
TerminalDurabilityWait::OverallTimeout => {
@@ -948,6 +1059,27 @@ async fn run_sse_driver(args: SseDriverArgs) {
}
}
+ // The transport's terminal-only usage members (see
+ // `WorkDispatcher::stream_terminal_usage_extras`). Fetched HERE — once,
+ // on the terminal, after the durability wait and BEFORE either usage
+ // surface is built — so a transport that finalises per-request
+ // accounting at stream end has finished doing so before the client is
+ // told anything, and nothing mid-stream can ever carry these members.
+ // An unmetered transport returns an empty vec and pays nothing.
+ //
+ // `carries_usage` is passed rather than used to skip the call: a stream
+ // that will emit no usage surface must not WAIT for members it would
+ // discard (this sits in front of the terminal content event and
+ // `[DONE]`), but it must still reach the transport so per-stream state
+ // is released here rather than by a leak backstop.
+ let terminal_usage_extras = if is_terminal {
+ publisher
+ .stream_terminal_usage_extras(&request_id, terminal_carries_usage(endpoint, &chunk))
+ .await
+ } else {
+ Vec::new()
+ };
+
// Detect streaming ``n>1``: any chunk past ``choice_index=0`` or any
// non-terminal chunk with ``finish_reason`` set is a per-choice
// marker. Latch the flag for the global-terminal suppression below.
@@ -973,8 +1105,8 @@ async fn run_sse_driver(args: SseDriverArgs) {
&chunk,
emit_role_for_this_chunk,
),
- SseEndpoint::Generate => build_generate_chunk_event(&chunk),
- SseEndpoint::Completion => {
+ SseEndpoint::Generate => build_generate_chunk_event(&chunk, &terminal_usage_extras),
+ SseEndpoint::Completion { .. } => {
build_text_completion_chunk_event(&stream_chat_id, created, &model, &chunk)
}
};
@@ -1000,35 +1132,27 @@ async fn run_sse_driver(args: SseDriverArgs) {
telemetry::GenerationEventOutcome::Cancelled,
);
cancel_guard.defuse();
- publisher.publish_cancel(&request_id).await;
- publisher.drop_pending_stream(&request_id);
+ teardown_after_client_disconnect(
+ &publisher,
+ &request_id,
+ (!outcome_done).then_some(outcome_rx.as_mut()),
+ stream_succeeded,
+ )
+ .await;
return;
}
}
if is_terminal {
- // Optional usage chunk for chat.
- if let SseEndpoint::Chat { include_usage } = endpoint {
- if include_usage {
- if let Some(usage) = chunk.usage.as_ref() {
- let fp = crate::handlers::proxy::system_fingerprint(&model);
- let body = json!({
- "id": stream_chat_id,
- "object": "chat.completion.chunk",
- "created": created,
- "model": model,
- "system_fingerprint": fp,
- "choices": [],
- "usage": {
- "prompt_tokens": usage.prompt_tokens,
- "completion_tokens": usage.completion_tokens,
- "total_tokens": usage.total_tokens,
- }
- });
- let _ =
- send_event(&event_tx, Event::default().data(body.to_string())).await;
- }
- }
+ if let Some(body) = build_usage_only_chunk_event(
+ endpoint,
+ &stream_chat_id,
+ created,
+ &model,
+ &chunk,
+ &terminal_usage_extras,
+ ) {
+ let _ = send_event(&event_tx, Event::default().data(body.to_string())).await;
}
send_done(&event_tx).await;
record_wait(if chunk.error.is_some() {
@@ -1185,8 +1309,93 @@ fn build_text_completion_chunk_event(
})
}
+/// Build the optional trailing usage-only chunk (OpenAI
+/// ``stream_options.include_usage``) emitted just before ``[DONE]``.
+///
+/// A streaming response cannot report usage in headers — they were flushed
+/// with the first byte — so this chunk is the surface on which a metered
+/// stream tells the caller what it actually consumed. Returns ``None`` when
+/// the endpoint did not ask for it, or when the terminal chunk carried no
+/// authoritative usage (never synthesise counts). ``Generate`` has no case
+/// here: its native terminal chunk already carries ``usage`` inline.
+///
+/// `terminal_extras` are the transport's terminal-only members (see
+/// [`WorkDispatcher::stream_terminal_usage_extras`]); they ride the same usage
+/// object. They are merged into an EXISTING block only — a terminal that
+/// reported no counts still emits no usage chunk, so the extras can never
+/// conjure one out of a stream that reported nothing.
+fn build_usage_only_chunk_event(
+ endpoint: SseEndpoint,
+ id: &str,
+ created: u64,
+ model: &str,
+ chunk: &ChunkEnvelope,
+ terminal_extras: &[(String, Value)],
+) -> Option<Value> {
+ let object = match endpoint {
+ SseEndpoint::Chat { include_usage } if include_usage => "chat.completion.chunk",
+ SseEndpoint::Completion { include_usage } if include_usage => "text_completion",
+ _ => return None,
+ };
+ let usage = chunk.usage.as_ref()?;
+ let mut usage_body = json!({
+ "prompt_tokens": usage.prompt_tokens,
+ "completion_tokens": usage.completion_tokens,
+ "total_tokens": usage.total_tokens,
+ });
+ merge_terminal_usage_extras(&mut usage_body, terminal_extras);
+ Some(json!({
+ "id": id,
+ "object": object,
+ "created": created,
+ "model": model,
+ "system_fingerprint": crate::handlers::proxy::system_fingerprint(model),
+ "choices": [],
+ "usage": usage_body,
+ }))
+}
+
+/// Whether this terminal will emit a usage surface at all.
+///
+/// Two independent reasons it will not, and both must be checked because the
+/// transport is made to WAIT whenever this says yes:
+///
+/// * The OpenAI surfaces publish usage only under `stream_options.include_usage`
+/// — omitted by default — and `build_usage_only_chunk_event` returns `None`
+/// without ever reading the transport's members for the rest.
+/// * The extras merge into an EXISTING usage block only, so a terminal whose
+/// worker reported no counts (an error terminal, an aborted run) emits no
+/// usage block on any surface — including native generate, whose inline
+/// block is itself gated on `chunk.usage`.
+fn terminal_carries_usage(endpoint: SseEndpoint, chunk: &ChunkEnvelope) -> bool {
+ if chunk.usage.is_none() {
+ return false;
+ }
+ match endpoint {
+ SseEndpoint::Generate => true,
+ SseEndpoint::Chat { include_usage } | SseEndpoint::Completion { include_usage } => {
+ include_usage
+ }
+ }
+}
+
+/// Merge a transport's terminal-only members into a usage block.
+///
+/// Additive only: a member whose key the worker's own usage block already
+/// carries is dropped rather than overwriting an authoritative count.
+fn merge_terminal_usage_extras(usage: &mut Value, extras: &[(String, Value)]) {
+ let Some(object) = usage.as_object_mut() else {
+ return;
+ };
+ for (key, value) in extras {
+ if !object.contains_key(key) {
+ object.insert(key.clone(), value.clone());
+ }
+ }
+}
+
/// SIE-native generate chunk shape.
-fn build_generate_chunk_event(chunk: &ChunkEnvelope) -> Value {
+fn build_generate_chunk_event(chunk: &ChunkEnvelope, terminal_extras: &[(String, Value)]) -> Value {
let mut body = json!({
"request_id": chunk.request_id,
"seq": chunk.seq,
@@ -1198,14 +1407,13 @@ fn build_generate_chunk_event(chunk: &ChunkEnvelope) -> Value {
obj.insert("finish_reason".to_string(), json!(fr));
}
if let Some(u) = chunk.usage.as_ref() {
- obj.insert(
- "usage".to_string(),
- json!({
- "prompt_tokens": u.prompt_tokens,
- "completion_tokens": u.completion_tokens,
- "total_tokens": u.total_tokens,
- }),
- );
+ let mut usage = json!({
+ "prompt_tokens": u.prompt_tokens,
+ "completion_tokens": u.completion_tokens,
+ "total_tokens": u.total_tokens,
+ });
+ merge_terminal_usage_extras(&mut usage, terminal_extras);
+ obj.insert("usage".to_string(), usage);
}
if let Some(t) = chunk.ttft_ms {
obj.insert("ttft_ms".to_string(), json!(t));
@@ -1272,7 +1480,7 @@ async fn send_error_chunk(
"finish_reason": "error",
"error": { "code": code, "message": message },
}),
- SseEndpoint::Completion => json!({
+ SseEndpoint::Completion { .. } => json!({
"id": chat_id,
"object": "text_completion",
"created": created,
@@ -1333,6 +1541,314 @@ mod tests {
ChunkEnvelope, ChunkError, ToolCallDeltaWire, ToolCallFunctionWire, UsageBlock,
};
+ mod client_disconnect_grace {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Arc;
+ use std::time::Instant;
+
+ use tokio::sync::{broadcast, oneshot};
+
+ use super::super::{teardown_after_client_disconnect, CLIENT_DISCONNECT_TERMINAL_GRACE};
+ use crate::queue::dispatch::WorkResult;
+ use crate::queue::dispatch::{
+ DispatchDurability, DispatchError, PendingGenerationSnapshot, WorkDispatcher,
+ };
+ use crate::queue::publisher::{PublishTarget, WorkParams};
+ use crate::queue::streaming::{ChunkEnvelope, StreamOutcome, UsageBlock};
+
+ /// Records exactly which teardown the SSE driver chose. The two are
+ /// transport-identical and differ only in the billing signal they emit,
+ /// so the choice IS the behaviour under test.
+ #[derive(Default)]
+ struct TeardownRecorder {
+ cancels: AtomicUsize,
+ plain_drops: AtomicUsize,
+ disconnect_drops: AtomicUsize,
+ }
+
+ #[async_trait::async_trait]
+ impl WorkDispatcher for TeardownRecorder {
+ async fn publish_work(
+ self: Arc<Self>,
+ _target: PublishTarget,
+ _admission_pool: &str,
+ _endpoint: &str,
+ _model: &str,
+ _engine: &str,
+ _bundle_config_hash: &str,
+ _items: Vec<rmpv::Value>,
+ _params: &WorkParams,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<Vec<WorkResult>>,
+ DispatchDurability,
+ ),
+ DispatchError,
+ > {
+ unreachable!("teardown test never publishes")
+ }
+
+ async fn publish_generate_streaming(
+ &self,
+ _target: PublishTarget,
+ _display_model: &str,
+ _engine: &str,
+ _bundle_config_hash: &str,
+ _params: &WorkParams,
+ _admission_pool: &str,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<StreamOutcome>,
+ Arc<tokio::sync::Notify>,
+ DispatchDurability,
+ ),
+ String,
+ > {
+ unreachable!("teardown test never publishes")
+ }
+
+ async fn publish_generate_streaming_sse(
+ &self,
+ _target: PublishTarget,
+ _display_model: &str,
+ _engine: &str,
+ _bundle_config_hash: &str,
+ _params: &WorkParams,
+ _admission_pool: &str,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<StreamOutcome>,
+ broadcast::Receiver<ChunkEnvelope>,
+ DispatchDurability,
+ ),
+ String,
+ > {
+ unreachable!("teardown test never publishes")
+ }
+
+ async fn publish_cancel(&self, _request_id: &str) {
+ self.cancels.fetch_add(1, Ordering::Relaxed);
+ }
+
+ fn begin_work_abandonment(&self, _request_id: &str) -> bool {
+ false
+ }
+
+ async fn finish_work_abandonment(&self, _request_id: &str) {}
+
+ async fn republish_to_pool(
+ &self,
+ _request_id: &str,
+ _reason: &'static str,
+ ) -> Result<bool, String> {
+ Ok(false)
+ }
+
+ async fn republish_pending_result_to_pool(
+ &self,
+ _request_id: &str,
+ _reason: &'static str,
+ ) -> Result<bool, String> {
+ Ok(false)
+ }
+
+ fn drop_pending_stream(&self, _request_id: &str) {
+ self.plain_drops.fetch_add(1, Ordering::Relaxed);
+ }
+
+ fn drop_pending_stream_client_disconnect(&self, _request_id: &str) {
+ self.disconnect_drops.fetch_add(1, Ordering::Relaxed);
+ }
+
+ fn pending_generation_snapshot(&self) -> PendingGenerationSnapshot {
+ PendingGenerationSnapshot::default()
+ }
+
+ fn pending_generation_for_model(&self, _model_id: &str) -> PendingGenerationSnapshot {
+ PendingGenerationSnapshot::default()
+ }
+
+ fn stream_observed_first_chunk(&self, _request_id: &str) -> bool {
+ false
+ }
+
+ fn stream_chunk_timing(
+ &self,
+ _request_id: &str,
+ ) -> Option<(Option<Instant>, Option<Instant>)> {
+ None
+ }
+ }
+
+ fn abort_terminal(completion_tokens: u32) -> StreamOutcome {
+ StreamOutcome {
+ text: "partial".to_string(),
+ // What the worker emits when it honours a cancel: a terminal
+ // whose usage is the count-so-far.
+ finish_reason: "cancelled".to_string(),
+ usage: Some(UsageBlock {
+ prompt_tokens: 5,
+ completion_tokens,
+ total_tokens: 5 + completion_tokens,
+ }),
+ attempt_id: "attempt-1".to_string(),
+ ttft_ms: None,
+ tpot_ms: None,
+ error: None,
+ tool_calls: None,
+ logprobs: None,
+ candidates: Vec::new(),
+ executed_bundle_config_hash: None,
+ execution_identity_sha256: None,
+ }
+ }
+
+ /// (a) The worker's abort terminal lands inside the grace window.
+ ///
+ /// Regression: teardown used to remove the collector immediately after
+ /// `publish_cancel` (which awaits only the transport ACK of the cancel
+ /// op, never the worker), so the terminal arrived with nowhere to go and
+ /// the count-so-far was discarded. The driver must instead keep the
+ /// stream registered and let the terminal resolve — the ordinary
+ /// teardown, whose metered settlement bills the partial output.
+ #[tokio::test(start_paused = true)]
+ async fn abort_terminal_inside_the_grace_window_reaches_settlement() {
+ let recorder = Arc::new(TeardownRecorder::default());
+ let publisher: Arc<dyn WorkDispatcher> = recorder.clone() as Arc<dyn WorkDispatcher>;
+ let (outcome_tx, mut outcome_rx) = oneshot::channel::<StreamOutcome>();
+
+ // The worker answers the cancel a beat later, well inside the window.
+ let worker_delay = CLIENT_DISCONNECT_TERMINAL_GRACE / 5;
+ tokio::spawn(async move {
+ tokio::time::sleep(worker_delay).await;
+ let _ = outcome_tx.send(abort_terminal(17));
+ });
+
+ let started = tokio::time::Instant::now();
+ teardown_after_client_disconnect(
+ &publisher,
+ "req-disconnect-billed",
+ Some(std::pin::Pin::new(&mut outcome_rx)),
+ false,
+ )
+ .await;
+ let waited = started.elapsed();
+
+ assert!(
+ waited >= worker_delay,
+ "teardown must keep the stream registered until the worker's abort \
+ terminal lands rather than racing it (waited {waited:?})"
+ );
+ assert!(
+ waited < CLIENT_DISCONNECT_TERMINAL_GRACE,
+ "and must finish on the terminal, not by timing out"
+ );
+ assert!(
+ matches!(
+ outcome_rx.try_recv(),
+ Err(oneshot::error::TryRecvError::Closed)
+ ),
+ "the abort terminal must have been consumed by the wait — i.e. \
+ delivered to the settlement path — not left to be dropped on the floor"
+ );
+ assert_eq!(
+ recorder.cancels.load(Ordering::Relaxed),
+ 1,
+ "the disconnect still cancels upstream"
+ );
+ assert_eq!(
+ recorder.disconnect_drops.load(Ordering::Relaxed),
+ 0,
+ "a terminal that arrived is not a terminal-less disconnect"
+ );
+ assert_eq!(
+ recorder.plain_drops.load(Ordering::Relaxed),
+ 1,
+ "the settled stream is torn down through the ordinary path"
+ );
+ }
+
+ /// (b) No terminal inside the window.
+ ///
+ /// The hold must still be released — but through the disconnect-specific
+ /// path, so a metered dispatcher does NOT raise the `lost_terminal_count`
+ /// billing-fault alert for what is ordinary user behaviour.
+ #[tokio::test(start_paused = true)]
+ async fn silent_worker_releases_without_raising_a_billing_fault() {
+ let recorder = Arc::new(TeardownRecorder::default());
+ let publisher: Arc<dyn WorkDispatcher> = recorder.clone() as Arc<dyn WorkDispatcher>;
+ // Held open for the whole test: the worker never reports.
+ let (_outcome_tx, mut outcome_rx) = oneshot::channel::<StreamOutcome>();
+
+ let started = tokio::time::Instant::now();
+ teardown_after_client_disconnect(
+ &publisher,
+ "req-disconnect-silent",
+ Some(std::pin::Pin::new(&mut outcome_rx)),
+ false,
+ )
+ .await;
+
+ assert!(
+ started.elapsed() >= CLIENT_DISCONNECT_TERMINAL_GRACE,
+ "the grace window is actually waited out"
+ );
+ assert_eq!(recorder.cancels.load(Ordering::Relaxed), 1);
+ assert_eq!(
+ recorder.disconnect_drops.load(Ordering::Relaxed),
+ 1,
+ "a terminal-less disconnect releases through the quiet path"
+ );
+ assert_eq!(
+ recorder.plain_drops.load(Ordering::Relaxed),
+ 0,
+ "the fault-raising teardown must not fire on an ordinary stop"
+ );
+ }
+
+ /// An already-resolved terminal needs no wait at all: tearing down is
+ /// immediate, and the grace window never delays the next request's
+ /// resources.
+ #[tokio::test(start_paused = true)]
+ async fn an_already_resolved_terminal_skips_the_wait() {
+ let recorder = Arc::new(TeardownRecorder::default());
+ let publisher: Arc<dyn WorkDispatcher> = recorder.clone() as Arc<dyn WorkDispatcher>;
+
+ let started = tokio::time::Instant::now();
+ teardown_after_client_disconnect(&publisher, "req-disconnect-done", None, false).await;
+
+ assert!(started.elapsed() < CLIENT_DISCONNECT_TERMINAL_GRACE);
+ assert_eq!(recorder.plain_drops.load(Ordering::Relaxed), 1);
+ assert_eq!(recorder.disconnect_drops.load(Ordering::Relaxed), 0);
+ }
+
+ /// A generation that already completed server-side has nothing to
+ /// cancel, so the disconnect teardown must not issue a redundant cancel
+ /// wire op — the same `#1602` discipline the `Lagged` arm follows.
+ #[tokio::test(start_paused = true)]
+ async fn an_already_succeeded_stream_is_not_cancelled_again() {
+ let recorder = Arc::new(TeardownRecorder::default());
+ let publisher: Arc<dyn WorkDispatcher> = recorder.clone() as Arc<dyn WorkDispatcher>;
+
+ teardown_after_client_disconnect(&publisher, "req-disconnect-late", None, true).await;
+
+ assert_eq!(
+ recorder.cancels.load(Ordering::Relaxed),
+ 0,
+ "a request that already completed server-side must not be cancelled"
+ );
+ assert_eq!(
+ recorder.plain_drops.load(Ordering::Relaxed),
+ 1,
+ "teardown still runs"
+ );
+ assert_eq!(recorder.disconnect_drops.load(Ordering::Relaxed), 0);
+ }
+ }
+
#[tokio::test]
async fn terminal_durability_ready_wins_over_closed_client_and_deadline() {
let (event_tx, event_rx) = tokio::sync::mpsc::channel(1);
@@ -1592,7 +2108,7 @@ mod tests {
#[test]
fn test_sse_generate_delta_shape() {
let chunk = _delta_chunk(3, "tok");
- let v = build_generate_chunk_event(&chunk);
+ let v = build_generate_chunk_event(&chunk, &[]);
assert_eq!(v["request_id"], "req-test");
assert_eq!(v["seq"], 3);
assert_eq!(v["text_delta"], "tok");
@@ -1609,7 +2125,7 @@ mod tests {
"bytes": [116, 111, 107],
"top_logprobs": [],
})]);
- let v = build_generate_chunk_event(&chunk);
+ let v = build_generate_chunk_event(&chunk, &[]);
assert_eq!(v["logprobs"][0]["token"], "tok");
assert_eq!(v["logprobs"][0]["logprob"], -0.25);
}
@@ -1624,7 +2140,7 @@ mod tests {
total_tokens: 17,
}),
);
- let v = build_generate_chunk_event(&chunk);
+ let v = build_generate_chunk_event(&chunk, &[]);
assert_eq!(v["done"], true);
assert_eq!(v["finish_reason"], "stop");
assert_eq!(v["usage"]["prompt_tokens"], 10);
@@ -1641,7 +2157,7 @@ mod tests {
code: "transport_failure".to_string(),
message: "upstream gone".to_string(),
});
- let v = build_generate_chunk_event(&chunk);
+ let v = build_generate_chunk_event(&chunk, &[]);
assert_eq!(v["error"]["code"], "transport_failure");
assert_eq!(v["error"]["message"], "upstream gone");
}
@@ -1799,36 +2315,255 @@ mod tests {
assert_eq!(v3["choices"][0]["finish_reason"], "stop");
}
- /// With ``stream_options.include_usage: true``, the SSE stream
- /// appends a usage-only chunk (``choices: []``) before ``[DONE]``.
- /// This test asserts the shape of that synthesised event using
- /// the same JSON the production loop builds.
+ /// With ``stream_options.include_usage: true``, the SSE stream appends a
+ /// usage-only chunk (``choices: []``) before ``[DONE]`` — on chat AND on
+ /// legacy completions, which is the only place a streamed request can
+ /// report what it consumed (headers are gone after the first byte).
#[test]
fn test_sse_response_emits_usage_chunk_when_requested() {
- let usage = UsageBlock {
- prompt_tokens: 5,
- completion_tokens: 7,
- total_tokens: 12,
- };
- let body = json!({
- "id": "chatcmpl-1",
- "object": "chat.completion.chunk",
- "created": 1700,
- "model": "m",
- "system_fingerprint": crate::handlers::proxy::system_fingerprint("m"),
- "choices": [],
- "usage": {
- "prompt_tokens": usage.prompt_tokens,
- "completion_tokens": usage.completion_tokens,
- "total_tokens": usage.total_tokens,
+ let terminal = _terminal_chunk(
+ "stop",
+ Some(UsageBlock {
+ prompt_tokens: 5,
+ completion_tokens: 7,
+ total_tokens: 12,
+ }),
+ );
+ for (endpoint, object) in [
+ (
+ SseEndpoint::Chat {
+ include_usage: true,
+ },
+ "chat.completion.chunk",
+ ),
+ (
+ SseEndpoint::Completion {
+ include_usage: true,
+ },
+ "text_completion",
+ ),
+ ] {
+ let body = build_usage_only_chunk_event(endpoint, "cmpl-1", 1700, "m", &terminal, &[])
+ .expect("include_usage with an authoritative terminal emits the usage-only chunk");
+ assert_eq!(body["object"], object);
+ assert!(body["choices"].as_array().unwrap().is_empty());
+ assert_eq!(body["usage"]["prompt_tokens"], 5);
+ assert_eq!(body["usage"]["completion_tokens"], 7);
+ assert_eq!(body["usage"]["total_tokens"], 12);
+ assert!(body["system_fingerprint"]
+ .as_str()
+ .unwrap()
+ .starts_with("fp_"));
+ }
+ }
+
+ /// No usage chunk without the opt-in, and never a synthesised one: a
+ /// terminal that carried no authoritative usage reports nothing.
+ #[test]
+ fn test_sse_usage_chunk_is_opt_in_and_never_synthesised() {
+ let terminal = _terminal_chunk(
+ "stop",
+ Some(UsageBlock {
+ prompt_tokens: 5,
+ completion_tokens: 7,
+ total_tokens: 12,
+ }),
+ );
+ for endpoint in [
+ SseEndpoint::Chat {
+ include_usage: false,
+ },
+ SseEndpoint::Completion {
+ include_usage: false,
+ },
+ SseEndpoint::Generate,
+ ] {
+ assert!(
+ build_usage_only_chunk_event(endpoint, "cmpl-1", 1700, "m", &terminal, &[])
+ .is_none()
+ );
+ }
+ let countless = _terminal_chunk("error", None);
+ assert!(build_usage_only_chunk_event(
+ SseEndpoint::Completion {
+ include_usage: true
+ },
+ "cmpl-1",
+ 1700,
+ "m",
+ &countless,
+ &[],
+ )
+ .is_none());
+ }
+
+ /// A transport's terminal-only members ride the same usage block the
+ /// worker's counts do — on the OpenAI usage-only chunk and on the native
+ /// generate terminal alike.
+ #[test]
+ fn terminal_usage_extras_ride_the_usage_block_on_every_stream_surface() {
+ let extras = vec![
+ ("credits_charged".to_string(), json!(42)),
+ ("rate_book_version".to_string(), json!("book-v1")),
+ ];
+ let terminal = _terminal_chunk(
+ "stop",
+ Some(UsageBlock {
+ prompt_tokens: 5,
+ completion_tokens: 7,
+ total_tokens: 12,
+ }),
+ );
+ for endpoint in [
+ SseEndpoint::Chat {
+ include_usage: true,
+ },
+ SseEndpoint::Completion {
+ include_usage: true,
+ },
+ ] {
+ let body =
+ build_usage_only_chunk_event(endpoint, "cmpl-1", 1700, "m", &terminal, &extras)
+ .expect("usage chunk");
+ assert_eq!(body["usage"]["credits_charged"], json!(42));
+ assert_eq!(body["usage"]["rate_book_version"], json!("book-v1"));
+ assert_eq!(body["usage"]["total_tokens"], json!(12));
+ }
+ let native = build_generate_chunk_event(&terminal, &extras);
+ assert_eq!(native["usage"]["credits_charged"], json!(42));
+ assert_eq!(native["usage"]["rate_book_version"], json!("book-v1"));
+ assert_eq!(native["usage"]["completion_tokens"], json!(7));
+ }
+
+ /// The extras are additive only. They never conjure a usage block for a
+ /// terminal that reported no counts, they never appear on a non-terminal
+ /// chunk, and they never overwrite a worker-authoritative count.
+ #[test]
+ fn terminal_usage_extras_never_fabricate_or_overwrite() {
+ let extras = vec![
+ ("credits_charged".to_string(), json!(42)),
+ ("prompt_tokens".to_string(), json!(999)),
+ ];
+
+ // No counts on the terminal → no usage surface at all, extras or not.
+ let countless = _terminal_chunk("error", None);
+ assert!(build_usage_only_chunk_event(
+ SseEndpoint::Chat {
+ include_usage: true
+ },
+ "cmpl-1",
+ 1700,
+ "m",
+ &countless,
+ &extras,
+ )
+ .is_none());
+ assert!(build_generate_chunk_event(&countless, &extras)
+ .get("usage")
+ .is_none());
+
+ // A mid-stream delta carries no usage block, so nothing can ride it.
+ let mut delta = _terminal_chunk("stop", None);
+ delta.done = false;
+ delta.text_delta = "hi".to_string();
+ assert!(build_generate_chunk_event(&delta, &extras)
+ .get("usage")
+ .is_none());
+
+ // A worker count always wins over a same-named extra.
+ let terminal = _terminal_chunk(
+ "stop",
+ Some(UsageBlock {
+ prompt_tokens: 5,
+ completion_tokens: 7,
+ total_tokens: 12,
+ }),
+ );
+ let body = build_usage_only_chunk_event(
+ SseEndpoint::Chat {
+ include_usage: true,
+ },
+ "cmpl-1",
+ 1700,
+ "m",
+ &terminal,
+ &extras,
+ )
+ .expect("usage chunk");
+ assert_eq!(
+ body["usage"]["prompt_tokens"],
+ json!(5),
+ "an extra must never overwrite an authoritative worker count"
+ );
+ assert_eq!(body["usage"]["credits_charged"], json!(42));
+ }
+
+ /// The transport is told whether its members can be published at all, so a
+ /// stream that emits no usage surface never makes the client wait for one.
+ /// This must agree exactly with `build_usage_only_chunk_event`'s own
+ /// `include_usage` gate — a disagreement either stalls `[DONE]` for nothing
+ /// or drops a charge the surface would have carried.
+ #[test]
+ fn terminal_carries_usage_agrees_with_the_surface_that_emits_it() {
+ let terminal = _terminal_chunk(
+ "stop",
+ Some(UsageBlock {
+ prompt_tokens: 5,
+ completion_tokens: 7,
+ total_tokens: 12,
+ }),
+ );
+ for include_usage in [true, false] {
+ for endpoint in [
+ SseEndpoint::Chat { include_usage },
+ SseEndpoint::Completion { include_usage },
+ ] {
+ assert_eq!(terminal_carries_usage(endpoint, &terminal), include_usage);
+ assert_eq!(
+ build_usage_only_chunk_event(endpoint, "cmpl-1", 1700, "m", &terminal, &[])
+ .is_some(),
+ include_usage,
+ "the wait must be paid exactly where a usage surface exists"
+ );
}
- });
- assert!(body["choices"].as_array().unwrap().is_empty());
- assert_eq!(body["usage"]["total_tokens"], 12);
- assert!(body["system_fingerprint"]
- .as_str()
- .unwrap()
- .starts_with("fp_"));
+ }
+ // Native generate carries usage inline on its terminal chunk.
+ assert!(terminal_carries_usage(SseEndpoint::Generate, &terminal));
+ assert!(build_generate_chunk_event(&terminal, &[])
+ .get("usage")
+ .is_some());
+
+ // A terminal whose worker reported NO counts emits no usage block on
+ // any surface, so nothing may wait for members it cannot publish.
+ let countless = _terminal_chunk("error", None);
+ for endpoint in [
+ SseEndpoint::Generate,
+ SseEndpoint::Chat {
+ include_usage: true,
+ },
+ SseEndpoint::Completion {
+ include_usage: true,
+ },
+ ] {
+ assert!(
+ !terminal_carries_usage(endpoint, &countless),
+ "a countless terminal has no usage surface to carry extras"
+ );
+ }
+ assert!(build_generate_chunk_event(&countless, &[])
+ .get("usage")
+ .is_none());
+ assert!(build_usage_only_chunk_event(
+ SseEndpoint::Chat {
+ include_usage: true
+ },
+ "cmpl-1",
+ 1700,
+ "m",
+ &countless,
+ &[],
+ )
+ .is_none());
}
/// A worker-emitted error chunk lands in the SSE stream as a
@@ -1852,7 +2587,7 @@ mod tests {
assert_eq!(v["error"]["code"], "rate_limit_exceeded");
assert_eq!(v["error"]["type"], "rate_limit_error");
// The SIE-native generate shape would carry it too.
- let g = build_generate_chunk_event(&got);
+ let g = build_generate_chunk_event(&got, &[]);
assert_eq!(g["error"]["code"], "rate_limit_exceeded");
assert_eq!(g["done"], true);
}
@@ -1875,7 +2610,7 @@ mod tests {
}),
));
let c1 = tap.recv().await.unwrap();
- let v1 = build_generate_chunk_event(&c1);
+ let v1 = build_generate_chunk_event(&c1, &[]);
assert_eq!(v1["text_delta"], "Tok-1");
assert_eq!(v1["done"], false);
assert!(
@@ -1884,7 +2619,7 @@ mod tests {
);
let c2 = tap.recv().await.unwrap();
- let v2 = build_generate_chunk_event(&c2);
+ let v2 = build_generate_chunk_event(&c2, &[]);
assert_eq!(v2["done"], true);
assert_eq!(v2["finish_reason"], "stop");
assert_eq!(v2["usage"]["total_tokens"], 2);
diff --git a/packages/sie_gateway/src/http_error.rs b/packages/sie_gateway/src/http_error.rs
index 0e28994c6..6db575b31 100644
--- a/packages/sie_gateway/src/http_error.rs
+++ b/packages/sie_gateway/src/http_error.rs
@@ -11,6 +11,51 @@
use serde_json::{json, Map, Value};
+/// Response-extension marker: this error response is a fault the GATEWAY owns,
+/// produced AFTER the worker already ran, and the client receives none of the
+/// work it paid for.
+///
+/// A handler that translates a successful worker result into a client-facing
+/// shape can fail on its own — a subtitle timestamp the model left open, a
+/// response body larger than the read bound, an unexpected item count. Those are
+/// SIE's bugs, not the customer's request, and unlike a partial worker failure
+/// there is no delivered output to bill for. Attaching this to the response lets
+/// a downstream billing composition tell the two apart; without it, "the
+/// response is non-2xx" is indistinguishable from "one item of a batch failed",
+/// which legitimately still settles its successful siblings.
+///
+/// The OSS gateway attaches it and does nothing else with it. `stage` names the
+/// translation step for the alert; keep it a small closed vocabulary.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct GatewayOwnedFault {
+ pub stage: &'static str,
+}
+
+impl GatewayOwnedFault {
+ pub const fn new(stage: &'static str) -> Self {
+ Self { stage }
+ }
+
+ /// Attach the marker to an already-built error response.
+ ///
+ /// **This marker must survive every layer between the handler that sets it
+ /// and the composition that reads it, and it fails toward CHARGING if it
+ /// does not.** A dropped marker is not a visible error — the response is
+ /// unchanged and the customer is simply billed for a result they never
+ /// received, which is the exact outcome the marker exists to prevent.
+ ///
+ /// Wrapping a response is safe: `Response::from_parts(parts, new_body)`
+ /// carries `parts.extensions` through, which is how the managed edge's
+ /// permit-body layer preserves it today. REBUILDING one is not — any layer
+ /// that constructs a fresh `Response` from a status and body, rather than
+ /// re-using the original's parts, silently discards it. A layer that must
+ /// rebuild has to copy the extensions across explicitly.
+ pub fn mark(self, mut response: axum::response::Response) -> axum::response::Response {
+ response.extensions_mut().insert(self);
+ response
+ }
+}
+
/// Stable ``detail.code`` values for gateway-generated errors.
pub mod code {
pub const MODEL_NOT_FOUND: &str = "MODEL_NOT_FOUND";
diff --git a/packages/sie_gateway/src/observability/metrics.rs b/packages/sie_gateway/src/observability/metrics.rs
index 1c26198e4..545ac48b4 100644
--- a/packages/sie_gateway/src/observability/metrics.rs
+++ b/packages/sie_gateway/src/observability/metrics.rs
@@ -136,6 +136,12 @@ pub enum AdmissionOutcome {
RegionMismatch,
LicenseExcluded,
PayloadTooLarge,
+ /// A policy gate refused the request because it could not read the field it
+ /// gates on — e.g. a `multipart/form-data` inference body whose `model`
+ /// part is absent, oversize, or unparseable. Distinct from `Admitted`
+ /// (which an unset slot defaults to) so a fail-closed ingress refusal is
+ /// never counted as an admitted request.
+ InvalidRequest,
InsufficientCredits,
KeySpendLimitExceeded,
RateLimited,
@@ -151,6 +157,7 @@ impl AdmissionOutcome {
Self::RegionMismatch => "region_mismatch",
Self::LicenseExcluded => "license_excluded",
Self::PayloadTooLarge => "payload_too_large",
+ Self::InvalidRequest => "invalid_request",
Self::InsufficientCredits => "insufficient_credits",
Self::KeySpendLimitExceeded => "key_spend_limit_exceeded",
Self::RateLimited => "rate_limited",
diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rs
index 56c4faa99..fe14909cf 100644
--- a/packages/sie_gateway/src/openapi.rs
+++ b/packages/sie_gateway/src/openapi.rs
@@ -411,7 +411,7 @@ fn patch_queue_request_batch_limits(value: &mut Value) {
{
for variant in variants {
if variant.get("type").and_then(Value::as_str) == Some("array") {
- variant["maxItems"] = queue_maximum.clone();
+ variant["maxItems"] = json!(crate::handlers::proxy::MAX_EMBEDDING_INPUTS);
}
}
}
@@ -3687,7 +3687,7 @@ mod tests {
.expect("embedding input must document the string-array form");
assert_eq!(
embedding_array["maxItems"],
- json!(crate::queue::publisher::MAX_QUEUE_REQUEST_ITEMS),
+ json!(crate::handlers::proxy::MAX_EMBEDDING_INPUTS),
);
for path in ["/v1/encode/{model}", "/v1/score/{model}"] {
diff --git a/packages/sie_gateway/src/queue/dispatch.rs b/packages/sie_gateway/src/queue/dispatch.rs
index 37133a721..153f70704 100644
--- a/packages/sie_gateway/src/queue/dispatch.rs
+++ b/packages/sie_gateway/src/queue/dispatch.rs
@@ -4,7 +4,7 @@
//! [`WorkDispatcher`] captures the exact handler-facing surface of
//! [`WorkPublisher`] — publish, cancel, republish, and pending-state
//! snapshots — so handlers depend on `Arc<dyn WorkDispatcher>` rather
-//! than the concrete NATS-backed publisher. NATS stays the only
+//! than the concrete NATS-backed publisher. NATS stays the default OSS
//! implementation; lifecycle methods (inbox subscription, backpressure
//! monitor, cleanup, drain) deliberately stay on the concrete type
//! owned by `main.rs`.
@@ -25,6 +25,10 @@ use super::publisher::WorkPublisher;
pub use super::publisher::{PendingGenerationSnapshot, PublishTarget, WorkParams, WorkResult};
pub use super::streaming::{ChunkEnvelope, StreamOutcome};
+fn nats_supports_first_chunk_pool_republish() -> bool {
+ true
+}
+
/// Transport-neutral completion of the dispatch durability boundary.
///
/// NATS resolves this only after every initial JetStream publish is durably
@@ -260,8 +264,72 @@ pub trait WorkDispatcher: Send + Sync {
reason: &'static str,
) -> Result<bool, String>;
+ /// Whether a first-chunk deadline can safely cancel the current attempt
+ /// and republish the retained generation work to a pool.
+ ///
+ /// The conservative default is false. A dispatcher with an equivalent
+ /// retained-payload and pool-fallback path must opt in explicitly; all
+ /// other generation drivers keep waiting until the governed overall
+ /// deadline instead of cancelling, republishing, or surfacing a premature
+ /// first-chunk timeout.
+ fn supports_first_chunk_pool_republish(&self) -> bool {
+ false
+ }
+
fn drop_pending_stream(&self, request_id: &str);
+ /// Extra members for the terminal event's `usage` block, contributed by the
+ /// transport, and the per-stream reclamation point for whatever state
+ /// produced them.
+ ///
+ /// A streamed response cannot report anything in headers — they were
+ /// flushed with the first byte — so the terminal usage block is the only
+ /// surface on which a transport that reaches its own per-request accounting
+ /// state at stream end can tell the caller what that state was. The SSE
+ /// driver calls this exactly ONCE per stream, on the worker terminal and
+ /// after the durability wait, and merges the returned members (in the
+ /// returned order) into the usage block it is about to write.
+ ///
+ /// `carries_usage` is the driver's answer to "will this stream emit a usage
+ /// surface at all?" — false for an OpenAI stream that did not opt into
+ /// `stream_options.include_usage`, where no usage event is written and any
+ /// members returned here are discarded unread. Contract for implementors:
+ ///
+ /// * **Never wait when `carries_usage` is false.** The call still happens so
+ /// per-request state is released on the normal terminal rather than by a
+ /// leak backstop, but producing a value nobody reads must cost the client
+ /// nothing — this call sits in front of the terminal content event and
+ /// `[DONE]`.
+ /// * **Bounded when it is true.** The driver awaits with the terminal event
+ /// already built; an unbounded wait stalls the client's `[DONE]`.
+ /// * **Terminal-only.** Return members only for state that is final. An
+ /// empty vec means "nothing final to add" and the usage block is written
+ /// exactly as the worker reported it — which is also the right answer for
+ /// a terminal whose accounting never completed.
+ ///
+ /// The default returns nothing, which is correct for every transport that
+ /// does no per-request accounting.
+ async fn stream_terminal_usage_extras(
+ &self,
+ _request_id: &str,
+ _carries_usage: bool,
+ ) -> Vec<(String, serde_json::Value)> {
+ Vec::new()
+ }
+
+ /// Client-disconnect variant of [`Self::drop_pending_stream`]: the caller
+ /// went away, upstream was cancelled, and the bounded grace window for the
+ /// worker's abort terminal expired without one arriving.
+ ///
+ /// Transport teardown is identical; the distinction is for BILLING. A
+ /// metered dispatcher releases the request's hold on this path quietly —
+ /// no compute evidence was lost to a defect, so it must not raise the
+ /// lost-terminal fault alert that ordinary teardown does. The default is
+ /// plain teardown, which is correct for every unmetered transport.
+ fn drop_pending_stream_client_disconnect(&self, request_id: &str) {
+ self.drop_pending_stream(request_id);
+ }
+
fn pending_generation_snapshot(&self) -> PendingGenerationSnapshot;
fn pending_generation_for_model(&self, model_id: &str) -> PendingGenerationSnapshot;
@@ -396,10 +464,18 @@ impl WorkDispatcher for WorkPublisher {
WorkPublisher::republish_pending_result_to_pool(self, request_id, reason).await
}
+ fn supports_first_chunk_pool_republish(&self) -> bool {
+ nats_supports_first_chunk_pool_republish()
+ }
+
fn drop_pending_stream(&self, request_id: &str) {
WorkPublisher::drop_pending_stream(self, request_id)
}
+ fn drop_pending_stream_client_disconnect(&self, request_id: &str) {
+ WorkPublisher::drop_pending_stream_client_disconnect(self, request_id)
+ }
+
fn pending_generation_snapshot(&self) -> PendingGenerationSnapshot {
WorkPublisher::pending_generation_snapshot(self)
}
@@ -454,7 +530,12 @@ impl WorkDispatcherExt for Arc<dyn WorkDispatcher> {
#[cfg(test)]
mod durability_tests {
- use super::DispatchDurability;
+ use super::{nats_supports_first_chunk_pool_republish, DispatchDurability};
+
+ #[test]
+ fn concrete_nats_publisher_explicitly_opts_into_first_chunk_pool_republish() {
+ assert!(nats_supports_first_chunk_pool_republish());
+ }
#[tokio::test]
async fn immediate_transport_acceptance_resolves_successfully() {
diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rs
index 454a5bfb7..affe951a0 100644
--- a/packages/sie_gateway/src/queue/publisher.rs
+++ b/packages/sie_gateway/src/queue/publisher.rs
@@ -39,7 +39,14 @@ const PUBLISH_ACK_COMPLETION_TIMEOUT: Duration = Duration::from_secs(6);
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;
-const MAX_RESULT_CHUNK_RESERVED_BYTES_PER_REQUEST: usize = 64 * 1_024 * 1_024;
+/// The ceiling on result-transfer bytes ONE request may have reserved.
+///
+/// `pub(crate)` because it is also the anchor for
+/// `handlers::proxy::MAX_COMPAT_RESPONSE_BODY` (#2617): the OpenAI-compatible
+/// wrappers buffer an inner native reply whole, and they should bound that
+/// buffer at the number this crate already sizes single-request result state
+/// against rather than at a second, independently chosen one.
+pub(crate) const MAX_RESULT_CHUNK_RESERVED_BYTES_PER_REQUEST: usize = 64 * 1_024 * 1_024;
/// One eighth of the gateway's 2 GiB container limit. This leaves 1.75 GiB
/// for normal request/response buffers, JSON expansion, NATS, and allocator
/// headroom even when result chunk traffic is at its reservation ceiling.
@@ -699,6 +706,21 @@ pub struct UnitCounts {
/// preserve the legacy positional MessagePack field order.
#[serde(default)]
pub pairs: Option<u64>,
+ /// Host-measured GPU-time share for sole-tenant sealed custom serving,
+ /// in whole seconds (ceil, request minimum 1). Stamped by the trusted
+ /// dispatcher — never by in-jail code — and only on sealed lanes;
+ /// catalog workers never emit it. Appended like `pairs`.
+ #[serde(default)]
+ pub gpu_second: Option<u64>,
+ /// Generated tokens on the per-ITEM result path (#2432). The realtime
+ /// generate surface carries its counts on the terminal chunk's
+ /// ``UsageBlock`` instead; this field is how ONE buffered generation
+ /// item's authoritative `completion_tokens` reaches the jobs/batch
+ /// settle path, which rates every item from `WorkResult.units`.
+ /// Appended last, like `pairs`/`gpu_second`, so the legacy positional
+ /// MessagePack field order is preserved.
+ #[serde(default)]
+ pub output_tokens: Option<u64>,
}
struct CachedStreamInfo {
@@ -1409,6 +1431,18 @@ fn drop_pending_result_collector(
pending.remove(request_id).is_some()
}
+fn drop_disconnected_stream_collector(
+ pending: &DashMap<String, StreamCollector>,
+ request_id: &str,
+) -> bool {
+ let Some(collector) = pending.get(request_id) else {
+ return false;
+ };
+ collector.latch_client_disconnected();
+ drop(collector);
+ pending.remove(request_id).is_some()
+}
+
fn fail_pending_result_chunk_request(
pending_results: &DashMap<String, ResultCollector>,
request_id: &str,
@@ -3286,6 +3320,12 @@ impl WorkPublisher {
self.pending_streams.remove(request_id);
}
+ /// Drop a stream after its client-disconnect grace window and latch that
+ /// cause for every transport holder before the collector disappears.
+ pub fn drop_pending_stream_client_disconnect(&self, request_id: &str) {
+ drop_disconnected_stream_collector(&self.pending_streams, request_id);
+ }
+
/// Tear down collector and payload state after the initial JetStream
/// publish was submitted but its durable ACK later failed.
///
@@ -4687,6 +4727,34 @@ mod tests {
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]
@@ -5931,6 +5999,26 @@ mod tests {
assert_eq!(model_b.groups[0].pool, "l4");
}
+ #[test]
+ fn client_disconnect_latches_before_the_stream_collector_is_dropped() {
+ let pending = DashMap::new();
+ let (tx, _rx) = oneshot::channel();
+ let collector = StreamCollector::new(tx, "model-a".into(), "default".into());
+ let disconnected = collector.client_disconnected_handle();
+ pending.insert("req-disconnect".to_string(), collector);
+
+ assert!(drop_disconnected_stream_collector(
+ &pending,
+ "req-disconnect"
+ ));
+ assert!(disconnected.load(Ordering::Acquire));
+ assert!(!pending.contains_key("req-disconnect"));
+ assert!(!drop_disconnected_stream_collector(
+ &pending,
+ "req-disconnect"
+ ));
+ }
+
#[test]
fn test_normalize_model_id() {
assert_eq!(normalize_model_id("BAAI/bge-m3"), "BAAI__bge-m3");
@@ -6241,6 +6329,8 @@ mod tests {
pages: None,
images: None,
audio_ms: Some(1_001),
+ gpu_second: None,
+ output_tokens: None,
}),
worker_direct: true,
executed_bundle_config_hash: None,
diff --git a/packages/sie_gateway/src/queue/streaming.rs b/packages/sie_gateway/src/queue/streaming.rs
index 83908020b..94983721f 100644
--- a/packages/sie_gateway/src/queue/streaming.rs
+++ b/packages/sie_gateway/src/queue/streaming.rs
@@ -20,6 +20,7 @@
//! bumping lands with the routing rollout.
use std::collections::BTreeMap;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Instant;
@@ -366,6 +367,18 @@ pub struct StreamCollector {
/// latches. uuid4 attempt ids are never reused, so an incoming chunk whose
/// id equals this is unambiguously from the abandoned attempt.
pub abandoned_attempt_id: Option<String>,
+ /// Latched by the teardown that follows an HTTP client disconnect whose
+ /// bounded abort-terminal grace expired (see
+ /// `handlers::sse::CLIENT_DISCONNECT_TERMINAL_GRACE`).
+ ///
+ /// Set immediately BEFORE the collector is removed, and shared by `Arc` so
+ /// the terminal-side task — which learns of the removal only as a dropped
+ /// sender — can still tell "the client left and the worker never reported"
+ /// apart from a genuine lost terminal. The distinction is a billing one:
+ /// only the latter is a fault worth alerting on. Unread on transports with
+ /// no per-request billing.
+ #[allow(dead_code)] // Managed Modal dispatcher boundary.
+ pub client_disconnected: Arc<AtomicBool>,
/// Snapshot of the per-attempt state cleared by
/// [`Self::bump_attempt_generation`], consumed only by an
/// immediately-following [`Self::rewind_attempt_generation`]. When a
@@ -431,6 +444,7 @@ impl StreamCollector {
execution_identity_sha256: None,
execution_identity_consistent: true,
abandoned_attempt_id: None,
+ client_disconnected: Arc::new(AtomicBool::new(false)),
snapshot: None,
}
}
@@ -441,6 +455,23 @@ impl StreamCollector {
Arc::clone(&self.activity)
}
+ /// Clone the client-disconnect latch so a task that outlives this
+ /// collector's registration can still read it. See
+ /// [`Self::client_disconnected`].
+ #[allow(dead_code)] // Managed Modal dispatcher boundary.
+ pub fn client_disconnected_handle(&self) -> Arc<AtomicBool> {
+ Arc::clone(&self.client_disconnected)
+ }
+
+ /// Latch "the HTTP client disconnected and no worker terminal arrived
+ /// inside the grace window". Call immediately before removing the
+ /// collector, so every holder of a
+ /// [`Self::client_disconnected_handle`] observes it.
+ #[allow(dead_code)] // Managed Modal dispatcher boundary.
+ pub fn latch_client_disconnected(&self) {
+ self.client_disconnected.store(true, Ordering::Release);
+ }
+
/// Install a broadcast tap on this collector so every non-stale
/// chunk applied by :meth:`apply` is also fanned out to the
/// returned receiver. Returns the receiver the SSE handler will
diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rs
index 3cd6f7e34..e864ec511 100644
--- a/packages/sie_gateway/src/server.rs
+++ b/packages/sie_gateway/src/server.rs
@@ -56,6 +56,39 @@ pub trait ModelAccessPolicy: Send + Sync {
/// visible to the caller identified in `ext`. `false` ⇒ treat as not found.
fn visible(&self, resolved_model: &str, ext: &axum::http::Extensions) -> bool;
+ /// A deployment-wide refusal to SERVE `resolved_model` at all — returned as
+ /// the finished caller-facing response, or `None` to allow (#2542).
+ ///
+ /// Distinct from [`Self::visible`]: that one is CALLER-scoped and answers
+ /// "not found" so a tenant cannot probe another tenant's models; this one is
+ /// caller-independent ("we do not serve this model here") and owns its own
+ /// status/envelope, because the reason is a deployment policy the OSS crate
+ /// has no vocabulary for (the managed service answers `403 LICENSE_EXCLUDED`
+ /// for a model whose upstream license forbids hosted serving).
+ ///
+ /// **Why it lives here.** Like `visible`, it is consulted at the model
+ /// RESOLUTION seam, on the id the dispatcher will actually route — after
+ /// alias expansion, `__`→`/`, and case folding. A gate that decides on the
+ /// caller's raw string cannot see through a registry alias, so an alias
+ /// pointing at a refused model would dispatch it; deciding here is what
+ /// makes the verdict authoritative for every surface that resolves a model.
+ /// Edge gates upstream may still refuse early, but they are an optimisation,
+ /// not the decision.
+ ///
+ /// `ext` carries the request extensions, so an implementation can record the
+ /// refusal on whatever per-request observability slot the deployment
+ /// installed. Consulted AFTER `visible`, so a caller who may not see the
+ /// model has already been answered the not-found shape and this refusal can
+ /// never become a cross-tenant existence oracle. The default returns `None`,
+ /// so the OSS self-host build refuses nothing.
+ fn serving_refusal(
+ &self,
+ _resolved_model: &str,
+ _ext: &axum::http::Extensions,
+ ) -> Option<axum::response::Response> {
+ None
+ }
+
/// If `resolved_model` is served from a dedicated sandbox (a #1841 org custom
/// model) rather than a catalog bundle, return its [`SealedRoute`]. Consulted
/// ONLY after [`Self::visible`] has passed, so the caller already owns any
@@ -69,6 +102,53 @@ pub trait ModelAccessPolicy: Send + Sync {
) -> Option<SealedRoute> {
None
}
+
+ fn generation_route_policy(&self) -> Option<&dyn GenerationRoutePolicy> {
+ None
+ }
+}
+
+/// Customer-visible generation intent selected from a validated request.
+///
+/// Deployments may use a different physical model profile for structured
+/// output (for example a non-speculative sibling). Keeping the intent generic
+/// lets the OSS gateway expose one substrate-neutral routing seam without
+/// learning about any managed provider or commercial catalog.
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+pub enum GenerationRequestIntent {
+ Default,
+ Grammar,
+}
+
+/// Exact deployment-owned generation route selected before worker lookup.
+///
+/// The tuple is intentionally transport-neutral. Self-hosted compositions
+/// install no policy and retain registry-driven routing. A managed composition
+/// may install a policy compiled from its immutable desired state and route
+/// customer requests to one exact physical model/lane.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct GovernedGenerationRoute {
+ /// Physical model id dispatched to the worker (possibly a profile variant).
+ pub model: String,
+ /// Exact compatible worker bundle.
+ pub bundle: String,
+ /// Exact physical queue pool.
+ pub pool: String,
+ /// Exact machine profile.
+ pub machine_profile: String,
+}
+
+/// Optional deployment hook for exact generation routing.
+///
+/// The presence of a policy means generation is governed: returning `None`
+/// fails that request closed rather than falling back to registry insertion
+/// order. OSS/self-hosted gateways install no policy and remain unchanged.
+pub trait GenerationRoutePolicy: Send + Sync {
+ fn resolve(
+ &self,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute>;
}
pub struct AppState {
diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.toml
index 6c44578a2..3c9ff4a92 100644
--- a/packages/sie_sdk/pyproject.toml
+++ b/packages/sie_sdk/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-sdk"
-version = "0.6.24"
+version = "0.6.25"
description = "Search Inference Engine - Python SDK"
requires-python = ">=3.12"
license = { text = "Apache-2.0" }
diff --git a/packages/sie_sdk/src/sie_sdk/__init__.py b/packages/sie_sdk/src/sie_sdk/__init__.py
index ef73ae558..35b535e22 100644
--- a/packages/sie_sdk/src/sie_sdk/__init__.py
+++ b/packages/sie_sdk/src/sie_sdk/__init__.py
@@ -12,6 +12,7 @@ For ColBERT/late interaction models, use the scoring module:
"""
from sie_sdk.client import (
+ EstimateUnroutableError,
InputTooLongError,
LoraLoadingError,
ModelLoadFailedError,
@@ -37,6 +38,7 @@ from sie_sdk.files import resolve_upload
from sie_sdk.jobs import build_job_body, connection_name
from sie_sdk.types import (
# Response types
+ AppliedRate,
AssignedWorkerInfo,
Batch,
BatchList,
@@ -51,11 +53,13 @@ from sie_sdk.types import (
Connection,
ConnectionCreated,
ConnectionRevoked,
+ CostEstimate,
EncodeResult,
Entity,
ExtractResult,
File,
FileDeleted,
+ FileList,
GenerateChunk,
GenerateResult,
GenerationUsage,
@@ -77,6 +81,7 @@ from sie_sdk.types import (
PoolSpec,
PoolSpecResponse,
PoolStatusInfo,
+ RateIdentity,
ScoreResult,
SparseResult,
StatusMessage,
@@ -88,6 +93,7 @@ from sie_sdk.types import (
__version__ = "0.1.0"
__all__ = [
+ "AppliedRate",
"AssignedWorkerInfo",
"Batch",
"BatchList",
@@ -102,11 +108,14 @@ __all__ = [
"Connection",
"ConnectionCreated",
"ConnectionRevoked",
+ "CostEstimate",
"EncodeResult",
"Entity",
+ "EstimateUnroutableError",
"ExtractResult",
"File",
"FileDeleted",
+ "FileList",
"GenerateChunk",
"GenerateResult",
"GenerationUsage",
@@ -134,6 +143,7 @@ __all__ = [
"PoolSpecResponse",
"PoolStatusInfo",
"ProvisioningError",
+ "RateIdentity",
"RequestError",
"SIEAsyncClient",
"SIEClient",
diff --git a/packages/sie_sdk/src/sie_sdk/client/__init__.py b/packages/sie_sdk/src/sie_sdk/client/__init__.py
index f6493ee73..92c957f4f 100644
--- a/packages/sie_sdk/src/sie_sdk/client/__init__.py
+++ b/packages/sie_sdk/src/sie_sdk/client/__init__.py
@@ -5,6 +5,7 @@ Re-exports all client classes and errors for backwards compatibility.
from sie_sdk.client.async_ import SIEAsyncClient
from sie_sdk.client.errors import (
+ EstimateUnroutableError,
InputTooLongError,
LoraLoadingError,
ModelLoadFailedError,
@@ -19,6 +20,7 @@ from sie_sdk.client.errors import (
from sie_sdk.client.sync import SIEClient
__all__ = [
+ "EstimateUnroutableError",
"InputTooLongError",
"LoraLoadingError",
"ModelLoadFailedError",
diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.py
index fc81903e4..c02b4e848 100644
--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py
+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py
@@ -157,6 +157,7 @@ from sie_sdk.types import (
)
from .errors import (
+ EstimateUnroutableError,
InputTooLongError,
ModelLoadFailedError,
ModelLoadingError,
@@ -264,6 +265,69 @@ MODEL_LOAD_FAILED_ERROR_CODE = "MODEL_LOAD_FAILED"
# error codes by hand.
INPUT_TOO_LONG_ERROR_CODE = "INPUT_TOO_LONG"
+# ── cost-estimate dry run (POST /v1/estimate, #2435) ──────────────────────
+ESTIMATE_PATH = "/v1/estimate"
+# 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
+# (``BILLING_CAPACITY_UNAVAILABLE``) is a retryable gateway condition and stays
+# a plain ``ServerError``.
+ESTIMATE_UNROUTABLE_ERROR_CODES = frozenset({"QUEUE_UNAVAILABLE", "PROVISIONING"})
+
+
+def build_estimate_envelope(endpoint: str, request: Mapping[str, Any]) -> dict[str, Any]:
+ """The ``POST /v1/estimate`` envelope: the target path plus its verbatim body.
+
+ The gateway prices whatever ``request`` would have been sent to ``endpoint``,
+ so the SDK does NOT reshape it. Callers pass the exact body they would pass
+ to the real route; anything the SDK normalized on the way in would be
+ something the quote priced and the request never sent.
+
+ The returned mapping is a SHALLOW copy: rebinding a top-level key on the
+ caller's dict after this returns cannot change what is priced, but nested
+ containers are shared, so mutating one in place still can. Both clients
+ serialize the envelope immediately, so the window is a single call — and a
+ deep copy is deliberately not taken, because these bodies routinely carry
+ megabytes of base64 audio or image payloads.
+
+ Raises:
+ ValueError: If ``endpoint`` is not a non-empty path or ``request`` is
+ not a mapping. Both are caller mistakes about WHAT is being priced,
+ so they fail here rather than as a server-side 400.
+ """
+ if not isinstance(endpoint, str) or not endpoint.startswith("/"):
+ msg = f"estimate endpoint must be the exact target path (got {endpoint!r})"
+ raise ValueError(msg)
+ if not isinstance(request, Mapping):
+ msg = f"estimate request must be the target request body mapping (got {type(request).__name__})"
+ raise ValueError(msg)
+ return {"endpoint": endpoint, "request": dict(request)}
+
+
+def raise_if_estimate_unroutable(response: _HttpResponse) -> None:
+ """Raise :class:`EstimateUnroutableError` for an unpriceable estimate.
+
+ Short-circuits ``handle_error``'s generic 5xx dispatch so callers can catch
+ "this request is not sellable" specifically, without string-matching a code.
+ The message is the planner's own reason — it names the unpriced identity or
+ the dimension it could not bound.
+ """
+ if response.status_code != HTTP_SERVICE_UNAVAILABLE:
+ return
+ code = get_error_code(response)
+ if code not in ESTIMATE_UNROUTABLE_ERROR_CODES:
+ return
+ detail = get_error_detail(response)
+ message = None
+ if isinstance(detail, Mapping):
+ message = detail.get("message")
+ raise EstimateUnroutableError(
+ str(message or "the active rate book cannot price this request"),
+ code=code,
+ request=parse_request_metadata(response.headers),
+ )
+
+
# Resource-exhausted retry settings (server-side OOM recovery exhausted).
# Default backoff sequence: 5 -> 10 -> 20 s (capped at 30s). Three attempts
# is enough to cover the typical eviction + retry window without making
@@ -607,13 +671,45 @@ def _parse_nonnegative_meter_header(headers: Any, name: str) -> int | None:
return parsed if parsed <= _MAX_METER_VALUE else None
-def parse_request_metadata(headers: Any) -> RequestMetadata | None:
+def settled_charge_from_usage(usage: Any) -> tuple[int, str] | None:
+ """The settled charge carried by one ``usage`` block (#2434).
+
+ Returns ``(credits_charged, rate_book_version)`` only when the block
+ carries BOTH — a charge with no book version cannot be reconciled, and a
+ version with no charge describes nothing. Anything malformed is treated as
+ absent.
+ """
+ if not isinstance(usage, Mapping):
+ return None
+ credits = usage.get("credits_charged")
+ version = usage.get("rate_book_version")
+ if not isinstance(credits, int) or isinstance(credits, bool) or credits < 0:
+ return None
+ if not isinstance(version, str) or not version:
+ return None
+ return credits, version
+
+
+def _settled_charge_from_body(body: Any) -> tuple[int, str] | None:
+ """The settled charge from a response envelope's ``usage`` block (#2434)."""
+ if not isinstance(body, Mapping):
+ return None
+ return settled_charge_from_usage(body.get("usage"))
+
+
+def parse_request_metadata(headers: Any, body: Any = None) -> RequestMetadata | None:
"""Parse optional metadata from one terminal response.
Malformed fields are omitted independently. Integer meter headers must be
canonical non-negative unsigned decimal values; request ids must be
non-empty visible ASCII without surrounding whitespace. If no valid fields
remain, no metadata is attached.
+
+ ``body`` is the decoded response envelope, when the caller has one. The
+ settled charge is read from its ``usage`` block FIRST and falls back to the
+ ``x-sie-credits-debited`` header, which is the only source on a gateway
+ that predates in-body surfacing (#2434). The two always agree when both are
+ present; the body additionally names the rate book, which no header does.
"""
metadata: RequestMetadata = {}
@@ -646,13 +742,22 @@ def parse_request_metadata(headers: Any) -> RequestMetadata | None:
usage["output_tokens"] = output_tokens
if audio_ms is not None:
usage["audio_ms"] = audio_ms
+
+ settled = _settled_charge_from_body(body)
+ if settled is not None:
+ credits_charged, rate_book_version = settled
+ usage["credits_charged"] = credits_charged
+ usage["rate_book_version"] = rate_book_version
+ metadata["credits_debited"] = credits_charged
+ metadata["rate_book_version"] = rate_book_version
+ else:
+ credits_debited = _parse_nonnegative_meter_header(headers, CREDITS_DEBITED_HEADER)
+ if credits_debited is not None:
+ metadata["credits_debited"] = credits_debited
+
if usage:
metadata["usage"] = usage
- credits_debited = _parse_nonnegative_meter_header(headers, CREDITS_DEBITED_HEADER)
- if credits_debited is not None:
- metadata["credits_debited"] = credits_debited
-
execution_identity_sha256 = _header_value(headers, EXECUTION_IDENTITY_SHA256_HEADER)
if (
isinstance(execution_identity_sha256, str)
@@ -677,9 +782,14 @@ def parse_terminal_json_object(response: _HttpResponse, *, owner: str) -> dict[s
return data
-def attach_request_metadata(results: Sequence[Any], headers: Any) -> None:
- """Attach detached request-scoped metadata to one or more results."""
- metadata = parse_request_metadata(headers)
+def attach_request_metadata(results: Sequence[Any], headers: Any, body: Any = None) -> None:
+ """Attach detached request-scoped metadata to one or more results.
+
+ ``body`` is the decoded response envelope when the caller has one, so the
+ settled charge comes from its ``usage`` block rather than the header
+ (#2434).
+ """
+ metadata = parse_request_metadata(headers, body)
if metadata is None:
return
for result in results:
diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.py
index c0a397aff..0b11e4593 100644
--- a/packages/sie_sdk/src/sie_sdk/client/async_.py
+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py
@@ -50,6 +50,7 @@ from sie_sdk.images import ImageLike, convert_images_for_json, convert_item_imag
from sie_sdk.jobs import TERMINAL_JOB_STATES, build_job_body, decode_chunk_bytes, job_chunks
from sie_sdk.types import (
Batch,
+ BatchList,
CapacityInfo,
ChatCompletion,
ChatCompletionChunk,
@@ -57,14 +58,17 @@ from sie_sdk.types import (
Connection,
ConnectionCreated,
ConnectionRevoked,
+ CostEstimate,
EncodeResult,
ExtractResult,
File,
FileDeleted,
+ FileList,
GenerateChunk,
GenerateGrammar,
GenerateImage,
GenerateResult,
+ GenerationUsage,
Item,
JobResults,
JobStatus,
@@ -84,6 +88,7 @@ from sie_sdk.types import (
from ._shared import (
DEFAULT_LEASE_RENEWAL_INTERVAL_S,
DEFAULT_PROVISION_TIMEOUT_S,
+ ESTIMATE_PATH,
HTTP_CLIENT_ERROR,
HTTP_GATEWAY_TIMEOUT,
JSON_CONTENT_TYPE,
@@ -102,6 +107,7 @@ from ._shared import (
attach_request_metadata,
base_url_accepts_origin_credentials,
build_chat_body,
+ build_estimate_envelope,
build_responses_body,
check_version_skew,
compute_oom_backoff,
@@ -121,10 +127,12 @@ from ._shared import (
parse_score_result,
parse_terminal_json_object,
provisioning_retry_delay,
+ raise_if_estimate_unroutable,
raise_if_input_too_long,
raise_if_model_load_failed,
request_matches_base_url_origin,
retry_after_or_default,
+ settled_charge_from_usage,
sse_chunk_error,
sse_headers,
validate_encode_result_count,
@@ -223,11 +231,15 @@ def _parse_generate_result_async(
result["finish_reason"] = finish # type: ignore[typeddict-item]
usage = data.get("usage")
if isinstance(usage, dict):
- result["usage"] = {
+ parsed_usage: GenerationUsage = {
"prompt_tokens": _coerce_token_count(usage.get("prompt_tokens")),
"completion_tokens": _coerce_token_count(usage.get("completion_tokens")),
"total_tokens": _coerce_token_count(usage.get("total_tokens")),
}
+ settled = settled_charge_from_usage(usage)
+ if settled is not None:
+ parsed_usage["credits_charged"], parsed_usage["rate_book_version"] = settled
+ result["usage"] = parsed_usage
attempt_id = data.get("attempt_id")
if isinstance(attempt_id, str):
result["attempt_id"] = attempt_id
@@ -1425,7 +1437,7 @@ class SIEAsyncClient:
for result in results:
result["timing"] = timing
- attach_request_metadata(results, response.headers)
+ attach_request_metadata(results, response.headers, response_data)
# Return single result if single item was passed
return results[0] if single_item else results
@@ -1450,6 +1462,41 @@ class SIEAsyncClient:
data = response.json()
return data["models"]
+ async def estimate(
+ self,
+ endpoint: str,
+ request: Mapping[str, Any],
+ *,
+ # ASYNC109: the transport's own per-call timeout (aiohttp
+ # ClientTimeout), mirroring the sync twin's `timeout` keyword; not a
+ # caller-supplied cancellation budget.
+ timeout: float | None = None, # noqa: ASYNC109
+ ) -> CostEstimate:
+ """Async version of estimate(). See SIEClient.estimate() for details."""
+ body = build_estimate_envelope(endpoint, request)
+ try:
+ response = await self._post(
+ ESTIMATE_PATH,
+ json_data=body,
+ 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:
+ raise_if_estimate_unroutable(response)
+ handle_error(response)
+
+ return cast("CostEstimate", response.json())
+
async def get_model(self, model: str) -> ModelInfo:
"""Async version of get_model(). See SIEClient.get_model() for details."""
try:
@@ -1846,7 +1893,7 @@ class SIEAsyncClient:
response_data = msgpack.unpackb(response.content, raw=False)
result = parse_score_result(response_data)
- attach_request_metadata([result], response.headers)
+ attach_request_metadata([result], response.headers, response_data)
return result
async def generate(
@@ -2043,8 +2090,8 @@ class SIEAsyncClient:
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="generate")
- result = _parse_generate_result_async(data, request=parse_request_metadata(response.headers))
- attach_request_metadata([result], response.headers)
+ result = _parse_generate_result_async(data, request=parse_request_metadata(response.headers, data))
+ attach_request_metadata([result], response.headers, data)
return result
async def responses(
@@ -2140,7 +2187,7 @@ class SIEAsyncClient:
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="Responses")
- attach_request_metadata([data], response.headers)
+ attach_request_metadata([data], response.headers, data)
return cast("ResponseResult", data)
async def chat_completions(
@@ -2278,7 +2325,7 @@ class SIEAsyncClient:
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="chat completion")
- attach_request_metadata([data], response.headers)
+ attach_request_metadata([data], response.headers, data)
return cast("ChatCompletion", data)
async def stream_chat_completions(
@@ -2776,7 +2823,7 @@ class SIEAsyncClient:
results = parse_extract_results(response_data["items"])
- attach_request_metadata(results, response.headers)
+ attach_request_metadata(results, response.headers, response_data)
return results[0] if single_item else results
@@ -3038,6 +3085,50 @@ class _AsyncFiles(_AsyncNamespace):
"""Async ``files.retrieve`` (``GET /v1/files/{id}``)."""
return await self._request_json("GET", f"/v1/files/{file_id}")
+ async def list(
+ self,
+ *,
+ after: str | None = None,
+ limit: int | None = None,
+ order: Literal["asc", "desc"] | None = None,
+ purpose: str | None = None,
+ ) -> Sequence[File]:
+ """List the org's live files with OpenAI cursor/filter arguments."""
+ page = await self.list_page(after=after, limit=limit, order=order, purpose=purpose)
+ return page.get("data", [])
+
+ async def list_page(
+ self,
+ *,
+ after: str | None = None,
+ limit: int | None = None,
+ order: Literal["asc", "desc"] | None = None,
+ purpose: str | None = None,
+ ) -> FileList:
+ """Return one file cursor page, including pagination metadata."""
+ params = {
+ key: value
+ for key, value in {
+ "after": after,
+ "limit": limit,
+ "order": order,
+ "purpose": purpose,
+ }.items()
+ if value is not None
+ }
+ path = f"/v1/files?{urlencode(params)}" if params else "/v1/files"
+ data = await self._request_json("GET", path)
+ if isinstance(data, dict):
+ return cast("FileList", data)
+ files = data if isinstance(data, list) else []
+ return {
+ "object": "list",
+ "data": files,
+ "first_id": files[0].get("id") if files else None,
+ "last_id": files[-1].get("id") if files else None,
+ "has_more": False,
+ }
+
async def content(self, file_id: str) -> bytes:
"""Async ``files.content`` — download a file's raw bytes (``GET /v1/files/{id}/content``)."""
try:
@@ -3085,12 +3176,26 @@ class _AsyncBatches(_AsyncNamespace):
"""Async ``batches.retrieve`` (``GET /v1/batches/{id}``)."""
return await self._request_json("GET", f"/v1/batches/{batch_id}")
- async def list(self) -> Sequence[Batch]:
- """Async ``batches.list`` (``GET /v1/batches``; additive OpenAI-parity)."""
- data = await self._request_json("GET", "/v1/batches")
+ async def list(self, *, after: str | None = None, limit: int | None = None) -> Sequence[Batch]:
+ """List the org's batches while preserving the historical sequence return."""
+ page = await self.list_page(after=after, limit=limit)
+ return page.get("data", [])
+
+ async def list_page(self, *, after: str | None = None, limit: int | None = None) -> BatchList:
+ """Return one batch cursor page, including pagination metadata."""
+ params = {key: value for key, value in {"after": after, "limit": limit}.items() if value is not None}
+ path = f"/v1/batches?{urlencode(params)}" if params else "/v1/batches"
+ data = await self._request_json("GET", path)
if isinstance(data, dict):
- return data.get("data", [])
- return data if isinstance(data, list) else []
+ return cast("BatchList", data)
+ batches = data if isinstance(data, list) else []
+ return {
+ "object": "list",
+ "data": batches,
+ "first_id": batches[0].get("id") if batches else None,
+ "last_id": batches[-1].get("id") if batches else None,
+ "has_more": False,
+ }
async def cancel(self, batch_id: str) -> Batch:
"""Async ``batches.cancel`` (``POST /v1/batches/{id}/cancel``; additive OpenAI-parity)."""
diff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.py
index e2280b5ae..0c7a078a8 100644
--- a/packages/sie_sdk/src/sie_sdk/client/errors.py
+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py
@@ -239,6 +239,34 @@ class InputTooLongError(RequestError):
self.model = model
+class EstimateUnroutableError(ServerError):
+ """The gateway cannot PRICE the request, so it will not run it either.
+
+ Raised by :meth:`SIEClient.estimate` when the dry run answers ``503``:
+ the active rate book declares no rate for the request's
+ (model, profile, operation, region) identity, or the planner cannot bound
+ one of the dimensions that book DOES price (an unbounded generation input,
+ say, or a sealed lane whose GPU class is unresolved).
+
+ This is deliberately the same verdict the real request would get — the
+ estimate runs the live planner — so treat it as "this request is not
+ sellable right now", not as an estimator limitation. :attr:`args` carries
+ the planner's own reason, which names the unpriced identity or the
+ dimension it could not bound.
+
+ Subclass of :class:`ServerError` so existing 5xx handlers keep working.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ code: str | None = None,
+ request: RequestMetadata | None = None,
+ ) -> None:
+ super().__init__(message, code=code, status_code=503, request=request)
+
+
class ResourceExhaustedError(ServerError):
"""Error when the server has exhausted its OOM-recovery strategies.
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.py
index 94bb8ce52..30f6200e7 100644
--- a/packages/sie_sdk/src/sie_sdk/client/sync.py
+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py
@@ -58,6 +58,7 @@ from sie_sdk.images import ImageLike, convert_images_for_json, convert_item_imag
from sie_sdk.jobs import TERMINAL_JOB_STATES, build_job_body, decode_chunk_bytes, job_chunks
from sie_sdk.types import (
Batch,
+ BatchList,
CapacityInfo,
ChatCompletion,
ChatCompletionChunk,
@@ -65,14 +66,17 @@ from sie_sdk.types import (
Connection,
ConnectionCreated,
ConnectionRevoked,
+ CostEstimate,
EncodeResult,
ExtractResult,
File,
FileDeleted,
+ FileList,
GenerateChunk,
GenerateGrammar,
GenerateImage,
GenerateResult,
+ GenerationUsage,
Item,
JobResults,
JobStatus,
@@ -92,6 +96,7 @@ from sie_sdk.types import (
from ._shared import (
DEFAULT_LEASE_RENEWAL_INTERVAL_S,
DEFAULT_PROVISION_TIMEOUT_S,
+ ESTIMATE_PATH,
HTTP_CLIENT_ERROR,
HTTP_GATEWAY_TIMEOUT,
JSON_CONTENT_TYPE,
@@ -111,6 +116,7 @@ from ._shared import (
attach_request_metadata,
base_url_accepts_origin_credentials,
build_chat_body,
+ build_estimate_envelope,
build_responses_body,
check_version_skew,
compute_oom_backoff,
@@ -130,10 +136,12 @@ from ._shared import (
parse_score_result,
parse_terminal_json_object,
provisioning_retry_delay,
+ raise_if_estimate_unroutable,
raise_if_input_too_long,
raise_if_model_load_failed,
request_matches_base_url_origin,
retry_after_or_default,
+ settled_charge_from_usage,
sse_chunk_error,
sse_headers,
validate_encode_result_count,
@@ -208,11 +216,15 @@ def _parse_generate_result(
result["finish_reason"] = finish # type: ignore[typeddict-item]
usage = data.get("usage")
if isinstance(usage, dict):
- result["usage"] = {
+ parsed_usage: GenerationUsage = {
"prompt_tokens": _coerce_token_count(usage.get("prompt_tokens")),
"completion_tokens": _coerce_token_count(usage.get("completion_tokens")),
"total_tokens": _coerce_token_count(usage.get("total_tokens")),
}
+ settled = settled_charge_from_usage(usage)
+ if settled is not None:
+ parsed_usage["credits_charged"], parsed_usage["rate_book_version"] = settled
+ result["usage"] = parsed_usage
attempt_id = data.get("attempt_id")
if isinstance(attempt_id, str):
result["attempt_id"] = attempt_id
@@ -1428,7 +1440,7 @@ class SIEClient:
for result in results:
result["timing"] = timing
- attach_request_metadata(results, response.headers)
+ attach_request_metadata(results, response.headers, response_data)
# Return single result if single item was passed
return results[0] if single_item else results
@@ -1467,6 +1479,90 @@ class SIEClient:
data = response.json()
return data["models"]
+ def estimate(
+ self,
+ endpoint: str,
+ request: Mapping[str, Any],
+ *,
+ timeout: float | None = None,
+ ) -> CostEstimate:
+ """Price a request WITHOUT running it (``POST /v1/estimate``).
+
+ The gateway plans the request through the same reservation planner the
+ metered path runs, against the same active rate book, and returns the
+ plan instead of holding it: no dispatch, no reservation, no credits
+ consumed. The quote is the CONSERVATIVE ceiling the live path would
+ hold — settlement bills the authoritative counts against that plan and
+ releases the rest, so the real charge is at most ``estimated_credits``.
+
+ Args:
+ endpoint: The exact target path, e.g. ``"/v1/encode/BAAI/bge-m3"``
+ (native, model in the path) or ``"/v1/chat/completions"``
+ (OpenAI-compatible, model in ``request["model"]``).
+ request: The verbatim body you would send to ``endpoint``. Passed
+ through untouched — a body the SDK reshaped would be a quote
+ for a request you never send.
+ timeout: Per-call timeout override in seconds.
+
+ Returns:
+ :class:`~sie_sdk.types.CostEstimate` with the planned per-dimension
+ units, the applied rational rates, the credits, and the active rate
+ book's version + digest.
+
+ Raises:
+ ValueError: If the envelope arguments are malformed client-side.
+ EstimateUnroutableError: If the active book cannot price the
+ request. This is the same verdict the real request would get —
+ the message names the unpriced identity or the dimension the
+ planner could not bound.
+ RequestError: If the target body is invalid (4xx), with the same
+ status/code the target route itself would return. In particular
+ a ``404 MODEL_NOT_FOUND`` means this data plane does not serve
+ the model at all — the estimate checks routability, not just
+ priceability, so it never quotes a request that would 404.
+ SIEConnectionError: If unable to connect to the server.
+ ServerError: For other 5xx responses.
+
+ Example:
+ >>> quote = client.estimate(
+ ... "/v1/encode/BAAI/bge-m3",
+ ... {"items": [{"text": "Hello"}]},
+ ... )
+ >>> quote["estimated_credits"]
+ 1
+ >>> quote["rate_book_version"]
+ '2026-07-26-production-bootstrap-v2'
+ """
+ # Every other public method opens with this. Without it `estimate()`
+ # inherits whatever `last_retry_count` / `last_model_revision` the
+ # PREVIOUS call left on this thread, so a quote taken right after a
+ # retried `encode()` reports that encode's retries as its own —
+ # contradicting the properties' own "latest call in this thread".
+ self._reset_retry_count()
+ body = build_estimate_envelope(endpoint, request)
+ try:
+ response = self._client.post(
+ ESTIMATE_PATH,
+ json=body,
+ 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:
+ raise_if_estimate_unroutable(response)
+ handle_error(response)
+
+ return cast("CostEstimate", response.json())
+
def get_model(self, model: str) -> ModelInfo:
"""Get details for a specific model.
@@ -2028,7 +2124,7 @@ class SIEClient:
# Build ScoreResult
result = parse_score_result(response_data)
- attach_request_metadata([result], response.headers)
+ attach_request_metadata([result], response.headers, response_data)
return result
def generate(
@@ -2276,8 +2372,8 @@ class SIEClient:
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="generate")
- result = _parse_generate_result(data, request=parse_request_metadata(response.headers))
- attach_request_metadata([result], response.headers)
+ result = _parse_generate_result(data, request=parse_request_metadata(response.headers, data))
+ attach_request_metadata([result], response.headers, data)
return result
def responses(
@@ -2403,7 +2499,7 @@ class SIEClient:
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="Responses")
- attach_request_metadata([data], response.headers)
+ attach_request_metadata([data], response.headers, data)
return cast("ResponseResult", data)
def chat_completions(
@@ -2539,7 +2635,7 @@ class SIEClient:
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="chat completion")
- attach_request_metadata([data], response.headers)
+ attach_request_metadata([data], response.headers, data)
return cast("ChatCompletion", data)
def stream_chat_completions(
@@ -3132,7 +3228,7 @@ class SIEClient:
for result in results:
result["model"] = response_model
- attach_request_metadata(results, response.headers)
+ attach_request_metadata(results, response.headers, response_data)
# Return single result if single item was passed
return results[0] if single_item else results
@@ -3423,6 +3519,49 @@ class _SyncFiles(_SyncNamespace):
"""Fetch a file's metadata (``GET /v1/files/{id}``)."""
return self._request_json("GET", f"/v1/files/{file_id}")
+ def list(
+ self,
+ *,
+ after: str | None = None,
+ limit: int | None = None,
+ order: Literal["asc", "desc"] | None = None,
+ purpose: str | None = None,
+ ) -> Sequence[File]:
+ """List the org's live files with OpenAI cursor/filter arguments."""
+ return self.list_page(after=after, limit=limit, order=order, purpose=purpose).get("data", [])
+
+ def list_page(
+ self,
+ *,
+ after: str | None = None,
+ limit: int | None = None,
+ order: Literal["asc", "desc"] | None = None,
+ purpose: str | None = None,
+ ) -> FileList:
+ """Return one file cursor page, including pagination metadata."""
+ params = {
+ key: value
+ for key, value in {
+ "after": after,
+ "limit": limit,
+ "order": order,
+ "purpose": purpose,
+ }.items()
+ if value is not None
+ }
+ path = f"/v1/files?{urlencode(params)}" if params else "/v1/files"
+ data = self._request_json("GET", path)
+ if isinstance(data, dict):
+ return cast("FileList", data)
+ files = data if isinstance(data, list) else []
+ return {
+ "object": "list",
+ "data": files,
+ "first_id": files[0].get("id") if files else None,
+ "last_id": files[-1].get("id") if files else None,
+ "has_more": False,
+ }
+
def content(self, file_id: str) -> bytes:
"""Download a file's raw bytes (``GET /v1/files/{id}/content``)."""
try:
@@ -3483,12 +3622,25 @@ class _SyncBatches(_SyncNamespace):
"""Fetch a batch's status (``GET /v1/batches/{id}``)."""
return self._request_json("GET", f"/v1/batches/{batch_id}")
- def list(self) -> Sequence[Batch]:
- """List the org's batches (``GET /v1/batches``; additive OpenAI-parity)."""
- data = self._request_json("GET", "/v1/batches")
+ def list(self, *, after: str | None = None, limit: int | None = None) -> Sequence[Batch]:
+ """List the org's batches while preserving the historical sequence return."""
+ return self.list_page(after=after, limit=limit).get("data", [])
+
+ def list_page(self, *, after: str | None = None, limit: int | None = None) -> BatchList:
+ """Return one batch cursor page, including pagination metadata."""
+ params = {key: value for key, value in {"after": after, "limit": limit}.items() if value is not None}
+ path = f"/v1/batches?{urlencode(params)}" if params else "/v1/batches"
+ data = self._request_json("GET", path)
if isinstance(data, dict):
- return data.get("data", [])
- return data if isinstance(data, list) else []
+ return cast("BatchList", data)
+ batches = data if isinstance(data, list) else []
+ return {
+ "object": "list",
+ "data": batches,
+ "first_id": batches[0].get("id") if batches else None,
+ "last_id": batches[-1].get("id") if batches else None,
+ "has_more": False,
+ }
def cancel(self, batch_id: str) -> Batch:
"""Cancel a batch (``POST /v1/batches/{id}/cancel``; additive OpenAI-parity)."""
diff --git a/packages/sie_sdk/src/sie_sdk/jobs.py b/packages/sie_sdk/src/sie_sdk/jobs.py
index 677371156..82fa60b96 100644
--- a/packages/sie_sdk/src/sie_sdk/jobs.py
+++ b/packages/sie_sdk/src/sie_sdk/jobs.py
@@ -313,7 +313,8 @@ def job_chunks(job_doc: Mapping[str, Any]) -> list[JobChunk]:
"state": chunk.get("state"),
"ref": chunk.get("ref"),
"units": chunk.get("units"),
- "credits": chunk.get("credits"),
+ "credits_charged": chunk.get("credits_charged"),
+ "rate_book_version": chunk.get("rate_book_version"),
"error": chunk.get("error"),
}
for chunk in raw
diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.py
index 5f5959662..9a5fac592 100644
--- a/packages/sie_sdk/src/sie_sdk/types.py
+++ b/packages/sie_sdk/src/sie_sdk/types.py
@@ -143,7 +143,25 @@ class TimingInfo(TypedDict, total=False):
class RequestUsage(TypedDict, total=False):
- """Authoritative metered units for one completed inference request."""
+ """Authoritative metered units for one completed inference request.
+
+ ``credits_charged``/``rate_book_version`` are the SETTLED charge as this
+ response BODY reported it — never an estimate, never a reservation, and
+ never fabricated. They are published whenever the gateway could write them
+ into this body, including on a billing-fault response, where dispatches
+ that rated cleanly are burned before the fault is returned, so the charge
+ is real even though the result was not delivered. An explicit ``0`` is a
+ settlement that cost nothing.
+
+ Their ABSENCE means the body did not carry a settled charge — NOT that
+ nothing was charged. A body the gateway must leave byte-for-byte intact
+ (an opaque content type, one it cannot safely rewrite or buffer) still
+ settles and still charges, and reports the debit only in the
+ ``x-sie-credits-debited`` header. Read
+ :attr:`RequestMetadata.credits_debited` for the authoritative answer: the
+ SDK fills it from this block when present and from that header otherwise,
+ so it is absent only when nothing was charged.
+ """
input_tokens: int
pairs: int
@@ -151,6 +169,8 @@ class RequestUsage(TypedDict, total=False):
pages: int
output_tokens: int
audio_ms: int
+ credits_charged: int
+ rate_book_version: str
class RequestMetadata(TypedDict, total=False):
@@ -162,7 +182,18 @@ class RequestMetadata(TypedDict, total=False):
id: str
usage: RequestUsage
+ #: Exact committed debit — the authoritative charge for this request.
+ #: Body-first (``usage.credits_charged``), falling back to the
+ #: ``x-sie-credits-debited`` header, which the gateway sets on every
+ #: non-streamed response whose settlement committed (including
+ #: billing-fault responses and bodies it left untouched). The two always
+ #: agree when both are present. Absence here — unlike absence inside
+ #: ``usage`` — does mean nothing was charged. Streamed responses carry no
+ #: headers at all: their charge rides the terminal usage chunk.
credits_debited: int
+ #: Immutable rate-book version that rated ``credits_debited``, when the
+ #: response reported one.
+ rate_book_version: str
execution_identity_sha256: str
@@ -428,11 +459,30 @@ GenerateGrammar = JsonSchemaGrammar | RegexGrammar | EbnfGrammar
class GenerationUsage(TypedDict):
- """Token usage for a single generation call."""
+ """Token usage for a single generation call.
+
+ ``credits_charged``/``rate_book_version`` ride the same block on a settled
+ response — including the terminal chunk of a stream, the only place a
+ streamed request can report what it cost. An explicit ``0`` is a settlement
+ that cost nothing; nothing here is ever an estimate or a fabricated zero.
+
+ Absence means this block did not carry the charge, NOT that nothing was
+ charged. On a buffered call read :attr:`RequestMetadata.credits_debited`,
+ which also covers responses whose body the gateway left untouched. On a
+ stream there is no header to fall back to, and a chat/completions stream
+ carries the charge only when it opted into
+ ``stream_options.include_usage`` — without that there is no usage chunk at
+ all. Native generate always carries usage on its terminal chunk. A stream
+ whose terminal settle did not commit in time reports its tokens without a
+ charge rather than guessing one; ``GET /me/usage`` remains the balance
+ authority.
+ """
prompt_tokens: int
completion_tokens: int
total_tokens: int
+ credits_charged: NotRequired[int]
+ rate_book_version: NotRequired[str]
class GenerateResult(TypedDict, total=False):
@@ -1146,6 +1196,64 @@ class JobPreflight(TypedDict, total=False):
estimate_basis: str
+class AppliedRate(TypedDict):
+ """One priced dimension's exact rational rate from the active rate book.
+
+ Credits are integers, so rates are exact rationals rather than floats:
+ ``rate_numerator / rate_denominator`` credits per unit. Multiply and round
+ once, never per-unit, if you re-derive a total client-side.
+ """
+
+ unit: str
+ rate_numerator: int
+ rate_denominator: int
+
+
+class CostEstimate(TypedDict):
+ """A dispatch-free quote from ``POST /v1/estimate``.
+
+ The gateway prices the request through the SAME reservation planner the
+ metered path runs, against the SAME active rate book, and returns the plan
+ instead of holding it — no dispatch, no reservation, no credits consumed.
+
+ ``estimated_credits`` is the CONSERVATIVE ceiling the live path would hold.
+ Settlement bills the worker-authoritative counts against that plan and
+ releases the remainder, so the real charge is at most this number.
+
+ ``minimum_billed_units`` is present only for duration-priced (sealed custom
+ lane, ``gpu_second``) identities, where a dry run cannot know the request's
+ duration: there the quote is a rate card — ``applied_rates`` plus this
+ per-request floor — and ``unit_ceilings`` is the whole-window hold, not a
+ prediction. ``estimate_basis`` says which of the two you are looking at.
+
+ Every field except ``minimum_billed_units`` is always present: the gateway
+ serializes a whole ``ReservationPlan`` projection, so a partial quote is not
+ a shape the server can produce. Mirrors the TypeScript ``CostEstimate``.
+ """
+
+ endpoint: str
+ identity: RateIdentity
+ estimated_credits: int
+ unit_ceilings: dict[str, int]
+ applied_rates: list[AppliedRate]
+ rate_book_version: str
+ rate_book_sha256: str
+ rounding_rule: str
+ estimate_basis: str
+ # `null` on every non-duration-priced identity, so it is always serialized
+ # but never meaningful outside the sealed rate card.
+ minimum_billed_units: NotRequired[dict[str, int] | None]
+
+
+class RateIdentity(TypedDict):
+ """The rate-book row set a request is priced under."""
+
+ model: str
+ profile: str
+ operation: str
+ region: str
+
+
class JobChunk(TypedDict, total=False):
"""One spawned chunk's settle metadata (``output.chunks[]``; results-as-refs).
@@ -1158,7 +1266,13 @@ class JobChunk(TypedDict, total=False):
state: str
ref: str | None
units: int | None
- credits: int | None
+ #: Exact credits committed for this chunk, or ``None`` until the chunk's
+ #: settlement is acknowledged. A job settles per chunk, so these sum to the
+ #: job's ``settled_credits`` exactly.
+ credits_charged: int | None
+ #: Immutable rate-book version that rated ``credits_charged``. Present
+ #: exactly when ``credits_charged`` is.
+ rate_book_version: str | None
error: Any
@@ -1286,6 +1400,16 @@ class File(TypedDict, total=False):
expires_at: int
+class FileList(TypedDict, total=False):
+ """The listing envelope from ``GET /v1/files`` (OpenAI cursor page)."""
+
+ object: str
+ data: list[File]
+ first_id: str | None
+ last_id: str | None
+ has_more: bool
+
+
class FileDeleted(TypedDict, total=False):
"""The envelope from deleting a file (OpenAI ``FileDeleted``)."""
@@ -1344,6 +1468,6 @@ class BatchList(TypedDict, total=False):
object: str
data: list[Batch]
- first_id: str
- last_id: str
+ first_id: str | None
+ last_id: str | None
has_more: bool
diff --git a/packages/sie_sdk/tests/client/test_batches.py b/packages/sie_sdk/tests/client/test_batches.py
index a6b93a6bb..f518c4f15 100644
--- a/packages/sie_sdk/tests/client/test_batches.py
+++ b/packages/sie_sdk/tests/client/test_batches.py
@@ -112,6 +112,53 @@ def test_list_returns_data_array() -> None:
client.close()
+def test_list_encodes_cursor_arguments_and_preserves_sequence_return() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(
+ return_value=_resp(
+ 200,
+ {
+ "object": "list",
+ "data": [{"id": "batch-2"}],
+ "first_id": "batch-2",
+ "last_id": "batch-2",
+ "has_more": False,
+ },
+ )
+ )
+ client = SIEClient(GW, api_key=KEY)
+ batches = client.batches.list(after='batch/"a b"&limit=1', limit=9)
+ assert [batch["id"] for batch in batches] == ["batch-2"]
+ assert mock_client.return_value.request.call_args.args == (
+ "GET",
+ "/v1/batches?after=batch%2F%22a+b%22%26limit%3D1&limit=9",
+ )
+ client.close()
+
+
+def test_list_page_exposes_cursor_metadata() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(
+ return_value=_resp(
+ 200,
+ {
+ "object": "list",
+ "data": [{"id": "batch-1"}, {"id": "batch-2"}],
+ "first_id": "batch-1",
+ "last_id": "batch-2",
+ "has_more": True,
+ },
+ )
+ )
+ client = SIEClient(GW, api_key=KEY)
+ page = client.batches.list_page()
+ assert [batch["id"] for batch in page["data"]] == ["batch-1", "batch-2"]
+ assert page["first_id"] == "batch-1"
+ assert page["last_id"] == "batch-2"
+ assert page["has_more"] is True
+ client.close()
+
+
# ---------------------------------------------------------------------------
# async
# ---------------------------------------------------------------------------
@@ -155,3 +202,40 @@ async def test_async_retrieve_and_cancel() -> None:
assert out["status"] == "cancelling"
assert client._post.call_args.args[0] == "/v1/batches/batch-1/cancel"
await client.close()
+
+
+async def test_async_list_and_list_page_share_cursor_arguments() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._get = AsyncMock(
+ return_value=_FakeAio(
+ 200,
+ {
+ "object": "list",
+ "data": [{"id": "batch-2"}],
+ "first_id": "batch-2",
+ "last_id": "batch-2",
+ "has_more": True,
+ },
+ )
+ )
+ batches = await client.batches.list(after='batch/"a b"', limit=9)
+ assert [batch["id"] for batch in batches] == ["batch-2"]
+ assert client._get.call_args.args[0] == "/v1/batches?after=batch%2F%22a+b%22&limit=9"
+ page = await client.batches.list_page(limit=1)
+ assert page["first_id"] == "batch-2"
+ assert page["has_more"] is True
+ assert client._get.call_args.args[0] == "/v1/batches?limit=1"
+ await client.close()
+
+
+async def test_async_list_page_normalizes_empty_legacy_bare_array() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._get = AsyncMock(return_value=_FakeAio(200, []))
+ page = await client.batches.list_page()
+ assert page["data"] == []
+ assert page["first_id"] is None
+ assert page["last_id"] is None
+ assert page["has_more"] is False
+ await client.close()
diff --git a/packages/sie_sdk/tests/client/test_estimate.py b/packages/sie_sdk/tests/client/test_estimate.py
new file mode 100644
index 000000000..fc3c67c48
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_estimate.py
@@ -0,0 +1,342 @@
+"""Tests for the cost-estimate dry run (``POST /v1/estimate``, #2435).
+
+The SDK's job on this route is narrow and load-bearing:
+
+- send the target request VERBATIM inside ``{endpoint, request}`` — a body the
+ SDK reshaped would be a quote for a request the caller never sends;
+- return the gateway's projection unchanged, so the customer reads the same
+ ceiling the metered path would hold;
+- map "the book cannot price this" onto a typed
+ :class:`EstimateUnroutableError` rather than a generic 5xx, because that
+ verdict is the request's, not the estimator's.
+"""
+
+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._shared import build_estimate_envelope
+from sie_sdk.client.async_ import _AioResponse
+from sie_sdk.client.errors import EstimateUnroutableError, RequestError, ServerError
+
+QUOTE: dict[str, Any] = {
+ "endpoint": "/v1/encode/BAAI/bge-m3",
+ "identity": {
+ "model": "BAAI/bge-m3",
+ "profile": "default",
+ "operation": "encode",
+ "region": "us",
+ },
+ "estimated_credits": 261,
+ "unit_ceilings": {"input_tokens": 261},
+ "applied_rates": [
+ {"unit": "input_tokens", "rate_numerator": 1, "rate_denominator": 1},
+ ],
+ "rate_book_version": "2026-07-26-production-bootstrap-v2",
+ "rate_book_sha256": "a" * 64,
+ "rounding_rule": "ceil-once-per-terminal-event",
+ "estimate_basis": "rate-book 2026-07-26-production-bootstrap-v2 conservative pre-dispatch reservation ceiling",
+ "minimum_billed_units": None,
+}
+
+UNROUTABLE = {
+ "detail": {
+ "code": "QUEUE_UNAVAILABLE",
+ "message": 'missing rate for model="acme/unpriced", profile="default", operation="encode", region="us"',
+ }
+}
+
+
+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"})
+
+
+# ---------------------------------------------------------------------------
+# The envelope
+# ---------------------------------------------------------------------------
+
+
+class TestEstimateEnvelope:
+ def test_carries_the_target_body_verbatim(self) -> None:
+ request = {"items": [{"text": "Hello"}], "params": {"output_types": ["dense"]}}
+ envelope = build_estimate_envelope("/v1/encode/BAAI/bge-m3", request)
+ assert envelope == {"endpoint": "/v1/encode/BAAI/bge-m3", "request": request}
+
+ def test_detaches_the_caller_mapping(self) -> None:
+ """A caller mutating their dict after the call must not change what was priced."""
+ request: dict[str, Any] = {"items": [{"text": "Hello"}]}
+ envelope = build_estimate_envelope("/v1/encode/m", request)
+ request["items"] = []
+ assert envelope["request"]["items"] == [{"text": "Hello"}]
+
+ @pytest.mark.parametrize(
+ ("endpoint", "body"),
+ [
+ ("v1/encode/m", {"items": []}),
+ ("", {"items": []}),
+ ("/v1/encode/m", ["not", "a", "mapping"]),
+ ("/v1/encode/m", "not a mapping"),
+ ],
+ )
+ def test_rejects_a_malformed_envelope_client_side(self, endpoint: Any, body: Any) -> None:
+ with pytest.raises(ValueError, match="estimate"):
+ build_estimate_envelope(endpoint, body)
+
+
+# ---------------------------------------------------------------------------
+# Sync client
+# ---------------------------------------------------------------------------
+
+
+class TestSyncEstimate:
+ def test_posts_the_envelope_and_returns_the_quote(self) -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_resp(200, QUOTE))
+ client = SIEClient("http://localhost:8080")
+
+ quote = client.estimate("/v1/encode/BAAI/bge-m3", {"items": [{"text": "Hello"}]})
+
+ assert quote == QUOTE
+ assert quote["estimated_credits"] == 261
+ assert quote["unit_ceilings"] == {"input_tokens": 261}
+ assert quote["rate_book_version"] == "2026-07-26-production-bootstrap-v2"
+ assert quote["applied_rates"][0]["rate_denominator"] == 1
+
+ url, kwargs = mock_client.return_value.post.call_args[0], mock_client.return_value.post.call_args[1]
+ assert url[0] == "/v1/estimate"
+ assert kwargs["json"] == {
+ "endpoint": "/v1/encode/BAAI/bge-m3",
+ "request": {"items": [{"text": "Hello"}]},
+ }
+ client.close()
+
+ def test_compat_body_rides_through_untouched(self) -> None:
+ """The model stays in the BODY for an OpenAI-compatible target."""
+ body = {
+ "model": "Qwen/Qwen3.6-27B",
+ "messages": [{"role": "user", "content": "hi"}],
+ "max_tokens": 64,
+ "n": 3,
+ }
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_resp(200, QUOTE))
+ client = SIEClient("http://localhost:8080")
+ client.estimate("/v1/chat/completions", body)
+ sent = mock_client.return_value.post.call_args[1]["json"]
+ assert sent["endpoint"] == "/v1/chat/completions"
+ assert sent["request"] == body
+ client.close()
+
+ def test_unpriced_identity_raises_the_typed_unroutable_error(self) -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_resp(503, UNROUTABLE))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(EstimateUnroutableError) as excinfo:
+ client.estimate("/v1/encode/acme/unpriced", {"items": [{"text": "Hello"}]})
+
+ assert excinfo.value.code == "QUEUE_UNAVAILABLE"
+ assert excinfo.value.status_code == 503
+ # The planner's own reason survives to the caller — it names the
+ # identity, which is the whole point of a fail-closed estimate.
+ assert "acme/unpriced" in str(excinfo.value)
+ # Existing 5xx handlers keep working.
+ assert isinstance(excinfo.value, ServerError)
+ client.close()
+
+ def test_a_retryable_billing_capacity_503_stays_a_plain_server_error(self) -> None:
+ """Gateway capacity pressure is not an unroutable verdict about the request."""
+ capacity = {
+ "detail": {
+ "code": "BILLING_CAPACITY_UNAVAILABLE",
+ "message": "audio billing preflight is at capacity",
+ }
+ }
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_resp(503, capacity))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(ServerError) as excinfo:
+ client.estimate("/v1/extract/audio/asr", {"items": [{"text": "x"}]})
+
+ assert not isinstance(excinfo.value, EstimateUnroutableError)
+ assert excinfo.value.code == "BILLING_CAPACITY_UNAVAILABLE"
+ client.close()
+
+ def test_an_unroutable_model_is_a_404_not_a_quote(self) -> None:
+ """The gateway checks routability, not just priceability.
+
+ A model this data plane does not serve answers the live 404 even when
+ the rate book prices it — a regression turning that into a 200 quote
+ would otherwise pass unnoticed.
+ """
+ not_found = {"detail": {"code": "MODEL_NOT_FOUND", "message": 'Model "acme/absent" not found.'}}
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_resp(404, not_found))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(RequestError) as excinfo:
+ client.estimate("/v1/encode/acme/absent", {"items": [{"text": "Hello"}]})
+
+ assert not isinstance(excinfo.value, EstimateUnroutableError)
+ assert excinfo.value.status_code == 404
+ assert excinfo.value.code == "MODEL_NOT_FOUND"
+ client.close()
+
+ def test_a_malformed_target_body_is_a_request_error(self) -> None:
+ invalid = {"detail": {"code": "INVALID_REQUEST", "message": "'items' must be an array"}}
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_resp(400, invalid))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(RequestError) as excinfo:
+ client.estimate("/v1/encode/BAAI/bge-m3", {"items": "nope"})
+
+ assert excinfo.value.status_code == 400
+ assert excinfo.value.code == "INVALID_REQUEST"
+ client.close()
+
+ def test_a_sealed_rate_card_carries_its_minimum_billed_floor(self) -> None:
+ sealed = {
+ **QUOTE,
+ "endpoint": "/v1/generate/org-42/support-gen",
+ "identity": {
+ "model": "custom.l4",
+ "profile": "default",
+ "operation": "sealed",
+ "region": "us",
+ },
+ "unit_ceilings": {"gpu_second": 130},
+ "applied_rates": [
+ {"unit": "gpu_second", "rate_numerator": 7, "rate_denominator": 1},
+ ],
+ "estimated_credits": 910,
+ "minimum_billed_units": {"gpu_second": 1},
+ "estimate_basis": "sealed custom-lane rate card; duration is execution-dependent",
+ }
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_resp(200, sealed))
+ client = SIEClient("http://localhost:8080")
+
+ quote = client.estimate(
+ "/v1/generate/org-42/support-gen",
+ {"prompt": "hi", "max_new_tokens": 32},
+ )
+
+ assert quote["minimum_billed_units"] == {"gpu_second": 1}
+ assert quote["applied_rates"][0]["unit"] == "gpu_second"
+ assert "duration" in quote["estimate_basis"]
+ client.close()
+
+ def test_client_side_envelope_validation_never_reaches_the_network(self) -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock()
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(ValueError, match="estimate endpoint"):
+ client.estimate("v1/encode/m", {"items": []})
+
+ mock_client.return_value.post.assert_not_called()
+ client.close()
+
+
+# ---------------------------------------------------------------------------
+# Async client
+# ---------------------------------------------------------------------------
+
+
+class TestAsyncEstimate:
+ @pytest.mark.asyncio
+ async def test_posts_the_envelope_and_returns_the_quote(self) -> None:
+ with patch("sie_sdk.client.async_.aiohttp.ClientSession"):
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(return_value=_aio(200, QUOTE)) # type: ignore[method-assign]
+
+ quote = await client.estimate("/v1/encode/BAAI/bge-m3", {"items": [{"text": "Hello"}]})
+
+ assert quote == QUOTE
+ assert client._post.await_args[0][0] == "/v1/estimate"
+ assert client._post.await_args[1]["json_data"] == {
+ "endpoint": "/v1/encode/BAAI/bge-m3",
+ "request": {"items": [{"text": "Hello"}]},
+ }
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_unpriced_identity_raises_the_typed_unroutable_error(self) -> None:
+ with patch("sie_sdk.client.async_.aiohttp.ClientSession"):
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(return_value=_aio(503, UNROUTABLE)) # type: ignore[method-assign]
+
+ with pytest.raises(EstimateUnroutableError) as excinfo:
+ await client.estimate("/v1/encode/acme/unpriced", {"items": [{"text": "Hello"}]})
+
+ assert excinfo.value.code == "QUEUE_UNAVAILABLE"
+ assert "acme/unpriced" in str(excinfo.value)
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_an_unroutable_model_is_a_404_not_a_quote(self) -> None:
+ """The async client duplicates the sync error-dispatch block.
+
+ Without this the two could diverge on the routability contract and
+ nothing would notice.
+ """
+ not_found = {"detail": {"code": "MODEL_NOT_FOUND", "message": 'Model "acme/absent" not found.'}}
+ with patch("sie_sdk.client.async_.aiohttp.ClientSession"):
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(return_value=_aio(404, not_found)) # type: ignore[method-assign]
+
+ with pytest.raises(RequestError) as excinfo:
+ await client.estimate("/v1/encode/acme/absent", {"items": [{"text": "Hello"}]})
+
+ assert not isinstance(excinfo.value, EstimateUnroutableError)
+ assert excinfo.value.status_code == 404
+ assert excinfo.value.code == "MODEL_NOT_FOUND"
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_client_side_envelope_validation_never_reaches_the_network(self) -> None:
+ with patch("sie_sdk.client.async_.aiohttp.ClientSession"):
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock() # type: ignore[method-assign]
+
+ with pytest.raises(ValueError, match="estimate endpoint"):
+ await client.estimate("v1/encode/m", {"items": []})
+
+ client._post.assert_not_awaited()
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_sync_and_async_send_the_same_envelope(self) -> None:
+ """The two clients must not drift on WHAT they price."""
+ request = {"model": "m", "input": "hello"}
+ with patch("sie_sdk.client.async_.aiohttp.ClientSession"):
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(return_value=_aio(200, QUOTE)) # type: ignore[method-assign]
+ await client.estimate("/v1/embeddings", request)
+ async_body = client._post.await_args[1]["json_data"]
+ await client.close()
+
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_resp(200, QUOTE))
+ sync_client = SIEClient("http://localhost:8080")
+ sync_client.estimate("/v1/embeddings", request)
+ sync_body = mock_client.return_value.post.call_args[1]["json"]
+ sync_client.close()
+
+ assert async_body == sync_body
diff --git a/packages/sie_sdk/tests/client/test_files.py b/packages/sie_sdk/tests/client/test_files.py
index 7b1e23af4..fe116ba01 100644
--- a/packages/sie_sdk/tests/client/test_files.py
+++ b/packages/sie_sdk/tests/client/test_files.py
@@ -10,7 +10,7 @@ from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from sie_sdk import SIEAsyncClient, SIEClient
+from sie_sdk import FileList, SIEAsyncClient, SIEClient
from sie_sdk.files import resolve_upload
GW = "http://gw.test:8080"
@@ -59,6 +59,17 @@ class _FakeAio:
# ---------------------------------------------------------------------------
+def test_file_list_is_exported_from_public_package() -> None:
+ page: FileList = {
+ "object": "list",
+ "data": [_FILE],
+ "first_id": "file-abc",
+ "last_id": "file-abc",
+ "has_more": False,
+ }
+ assert page["data"][0]["id"] == "file-abc"
+
+
def test_resolve_upload_bytes_defaults_filename() -> None:
assert resolve_upload(b"hi") == (b"hi", "upload.jsonl")
assert resolve_upload(b"hi", "x.jsonl") == (b"hi", "x.jsonl")
@@ -145,6 +156,65 @@ def test_retrieve_and_delete_hit_expected_urls() -> None:
client.close()
+def test_list_encodes_openai_cursor_filters_and_preserves_sequence_return() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(
+ return_value=_json_resp(
+ 200,
+ {
+ "object": "list",
+ "data": [_FILE],
+ "first_id": "file-abc",
+ "last_id": "file-abc",
+ "has_more": True,
+ },
+ )
+ )
+ client = SIEClient(GW, api_key=KEY)
+ files = client.files.list(after='file/"a b"&purpose=x', limit=7, order="asc", purpose="batch")
+ assert [file["id"] for file in files] == ["file-abc"]
+ assert mock_client.return_value.request.call_args.args == (
+ "GET",
+ "/v1/files?after=file%2F%22a+b%22%26purpose%3Dx&limit=7&order=asc&purpose=batch",
+ )
+ client.close()
+
+
+def test_list_page_exposes_cursor_metadata() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(
+ return_value=_json_resp(
+ 200,
+ {
+ "object": "list",
+ "data": [_FILE],
+ "first_id": "file-abc",
+ "last_id": "file-abc",
+ "has_more": True,
+ },
+ )
+ )
+ client = SIEClient(GW, api_key=KEY)
+ page = client.files.list_page()
+ assert [file["id"] for file in page["data"]] == ["file-abc"]
+ assert page["first_id"] == "file-abc"
+ assert page["last_id"] == "file-abc"
+ assert page["has_more"] is True
+ client.close()
+
+
+def test_list_page_normalizes_legacy_bare_array() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_json_resp(200, [_FILE, {**_FILE, "id": "file-def"}]))
+ client = SIEClient(GW, api_key=KEY)
+ page = client.files.list_page()
+ assert [file["id"] for file in page["data"]] == ["file-abc", "file-def"]
+ assert page["first_id"] == "file-abc"
+ assert page["last_id"] == "file-def"
+ assert page["has_more"] is False
+ client.close()
+
+
def test_content_returns_raw_bytes() -> None:
payload = b'{"custom_id":"a","response":{"status_code":200}}\n'
with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
@@ -186,3 +256,28 @@ async def test_async_content_and_delete() -> None:
assert out["deleted"] is True
assert client._delete.call_args.args[0] == "/v1/files/file-1"
await client.close()
+
+
+async def test_async_list_and_list_page_share_cursor_arguments() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._get = AsyncMock(
+ return_value=_FakeAio(
+ 200,
+ {
+ "object": "list",
+ "data": [_FILE],
+ "first_id": "file-abc",
+ "last_id": "file-abc",
+ "has_more": False,
+ },
+ )
+ )
+ files = await client.files.list(after='file/"a b"', limit=7, order="desc", purpose="batch")
+ assert [file["id"] for file in files] == ["file-abc"]
+ assert client._get.call_args.args[0] == ("/v1/files?after=file%2F%22a+b%22&limit=7&order=desc&purpose=batch")
+ page = await client.files.list_page(limit=1)
+ assert page["first_id"] == "file-abc"
+ assert page["has_more"] is False
+ assert client._get.call_args.args[0] == "/v1/files?limit=1"
+ await client.close()
diff --git a/packages/sie_sdk/tests/client/test_settled_charge.py b/packages/sie_sdk/tests/client/test_settled_charge.py
new file mode 100644
index 000000000..f5069b98c
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_settled_charge.py
@@ -0,0 +1,123 @@
+"""The settled charge surfaced in a response's ``usage`` block (#2434).
+
+The gateway publishes ``usage.credits_charged`` + ``usage.rate_book_version``
+on every settled response, and keeps the ``x-sie-credits-debited`` header
+unchanged for compatibility. The SDK reads the body first — it is the only
+source that also names the rate book — and falls back to the header for a
+gateway that predates in-body surfacing.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sie_sdk.client._shared import parse_request_metadata
+from sie_sdk.client.async_ import _parse_generate_result_async
+from sie_sdk.client.sync import _parse_generate_result
+
+BOOK = "2026-07-22-production-bootstrap-v1"
+
+_GENERATE_PARSERS = (_parse_generate_result, _parse_generate_result_async)
+
+
[email protected]("parse", _GENERATE_PARSERS)
+def test_generate_usage_block_carries_the_settled_charge(parse) -> None:
+ """The parser rebuilds ``usage`` field-by-field; the charge must survive."""
+ result = parse(
+ {
+ "model": "m",
+ "text": "hi",
+ "usage": {
+ "prompt_tokens": 9,
+ "completion_tokens": 3,
+ "total_tokens": 12,
+ "credits_charged": 7,
+ "rate_book_version": BOOK,
+ },
+ },
+ request=None,
+ )
+
+ assert result["usage"]["credits_charged"] == 7
+ assert result["usage"]["rate_book_version"] == BOOK
+ assert result["usage"]["total_tokens"] == 12
+
+
[email protected]("parse", _GENERATE_PARSERS)
+def test_generate_usage_block_stays_charge_free_when_nothing_settled(parse) -> None:
+ result = parse(
+ {"model": "m", "text": "hi", "usage": {"prompt_tokens": 9, "completion_tokens": 3, "total_tokens": 12}},
+ request=None,
+ )
+
+ assert "credits_charged" not in result["usage"]
+ assert "rate_book_version" not in result["usage"]
+
+
+def test_body_is_the_source_of_the_settled_charge() -> None:
+ metadata = parse_request_metadata(
+ {"x-sie-request-id": "req-1", "x-sie-units-input-tokens": "11", "x-sie-credits-debited": "7"},
+ {"model": "m", "usage": {"input_tokens": 11, "credits_charged": 7, "rate_book_version": BOOK}},
+ )
+
+ assert metadata is not None
+ assert metadata["credits_debited"] == 7
+ assert metadata["rate_book_version"] == BOOK
+ assert metadata["usage"]["credits_charged"] == 7
+ assert metadata["usage"]["rate_book_version"] == BOOK
+ # The unit headers still describe the same request.
+ assert metadata["usage"]["input_tokens"] == 11
+
+
+def test_header_still_carries_the_charge_when_the_body_does_not() -> None:
+ """A gateway that predates in-body surfacing must keep working."""
+ metadata = parse_request_metadata(
+ {"x-sie-credits-debited": "7"},
+ {"model": "m", "usage": {"prompt_tokens": 4}},
+ )
+
+ assert metadata is not None
+ assert metadata["credits_debited"] == 7
+ assert "rate_book_version" not in metadata
+ # `usage` here mirrors the meter HEADERS, which this response has none of;
+ # the body's own token counts stay on the response envelope.
+ assert "usage" not in metadata
+
+
+def test_no_settlement_means_no_charge_anywhere() -> None:
+ """A billing fault surfaces neither a body charge nor a header one."""
+ metadata = parse_request_metadata({"x-sie-request-id": "req-fault"}, {"model": "m"})
+
+ assert metadata is not None
+ assert "credits_debited" not in metadata
+ assert "rate_book_version" not in metadata
+
+
+def test_a_zero_charge_is_a_charge() -> None:
+ metadata = parse_request_metadata({}, {"usage": {"credits_charged": 0, "rate_book_version": BOOK}})
+
+ assert metadata is not None
+ assert metadata["credits_debited"] == 0
+ assert metadata["usage"]["credits_charged"] == 0
+
+
+def test_half_a_charge_is_no_charge() -> None:
+ """Neither half is publishable alone, so a partial block falls back."""
+ for usage in (
+ {"credits_charged": 7},
+ {"rate_book_version": BOOK},
+ {"credits_charged": -1, "rate_book_version": BOOK},
+ {"credits_charged": "7", "rate_book_version": BOOK},
+ {"credits_charged": True, "rate_book_version": BOOK},
+ {"credits_charged": 7, "rate_book_version": ""},
+ ):
+ metadata = parse_request_metadata({"x-sie-credits-debited": "3"}, {"usage": usage})
+ assert metadata is not None, usage
+ assert metadata["credits_debited"] == 3, usage
+ assert "rate_book_version" not in metadata, usage
+
+
+def test_a_body_that_is_not_an_envelope_is_ignored() -> None:
+ for body in (None, [], "usage", {"usage": 3}):
+ metadata = parse_request_metadata({"x-sie-credits-debited": "5"}, body)
+ assert metadata is not None
+ assert metadata["credits_debited"] == 5
diff --git a/packages/sie_sdk/tests/test_jobs_body.py b/packages/sie_sdk/tests/test_jobs_body.py
index 511ce7f95..46b21869e 100644
--- a/packages/sie_sdk/tests/test_jobs_body.py
+++ b/packages/sie_sdk/tests/test_jobs_body.py
@@ -284,11 +284,20 @@ def test_decode_chunk_bytes_all_items() -> None:
def test_job_chunks_extracts_ref_metadata() -> None:
+ """#2434: a settled chunk carries its charge under the unified name."""
job = {
"output": {
"kind": "refs",
"chunks": [
- {"seq": 0, "items": 3, "state": "succeeded", "ref": "payload-store/c0", "units": 15, "credits": 15}
+ {
+ "seq": 0,
+ "items": 3,
+ "state": "succeeded",
+ "ref": "payload-store/c0",
+ "units": 15,
+ "credits_charged": 15,
+ "rate_book_version": "book-v1",
+ }
],
}
}
@@ -300,7 +309,21 @@ def test_job_chunks_extracts_ref_metadata() -> None:
"state": "succeeded",
"ref": "payload-store/c0",
"units": 15,
- "credits": 15,
+ "credits_charged": 15,
+ "rate_book_version": "book-v1",
"error": None,
}
]
+
+
+def test_job_chunks_leave_an_unsettled_chunk_uncharged() -> None:
+ """A chunk the control plane has not acked yet reports no charge at all."""
+ job = {
+ "output": {
+ "kind": "refs",
+ "chunks": [{"seq": 1, "items": 3, "state": "spawned", "ref": None, "units": None}],
+ }
+ }
+ (chunk,) = job_chunks(job)
+ assert chunk["credits_charged"] is None
+ assert chunk["rate_book_version"] is None
diff --git a/packages/sie_server/models/Qwen__Qwen3-Embedding-8B.yaml b/packages/sie_server/models/Qwen__Qwen3-Embedding-8B.yaml
new file mode 100644
index 000000000..4bb2201ed
--- /dev/null
+++ b/packages/sie_server/models/Qwen__Qwen3-Embedding-8B.yaml
@@ -0,0 +1,32 @@
+sie_id: Qwen/Qwen3-Embedding-8B
+hf_id: Qwen/Qwen3-Embedding-8B
+hf_revision: 1d8ad4ca9b3dd8059ad90a75d4983776a23d44af
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode:
+ dense:
+ dim: 4096
+ sparse: null
+ multivector: null
+ score: null
+ extract: null
+max_sequence_length: 40960
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: bfloat16
+ adapter_path: sie_server.adapters.qwen2_flash:Qwen2FlashAdapter
+ adapter_options:
+ loadtime:
+ causal: true
+ runtime:
+ pooling: last
+ normalize: true
+ query_template: |-
+ Instruct: {instruction}
+ Query:{text}
+ default_instruction: Given a web search query, retrieve relevant passages that answer the query
diff --git a/packages/sie_server/models/Qwen__Qwen3-VL-Embedding-2B.yaml b/packages/sie_server/models/Qwen__Qwen3-VL-Embedding-2B.yaml
index 8eb8296bc..7cd5d02d3 100644
--- a/packages/sie_server/models/Qwen__Qwen3-VL-Embedding-2B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3-VL-Embedding-2B.yaml
@@ -5,7 +5,7 @@ inputs:
text: true
image: true
audio: false
- video: false
+ video: true
tasks:
encode:
dense:
diff --git a/packages/sie_server/models/numind__NuNER_Zero.yaml b/packages/sie_server/models/numind__NuNER_Zero.yaml
index 3262a45e3..6af052591 100644
--- a/packages/sie_server/models/numind__NuNER_Zero.yaml
+++ b/packages/sie_server/models/numind__NuNER_Zero.yaml
@@ -12,6 +12,7 @@ tasks:
encode: null
score: null
extract: {}
+max_sequence_length: 384
profiles:
default:
max_batch_tokens: 16384
diff --git a/packages/sie_server/models/urchade__gliner_multi-v2.1.yaml b/packages/sie_server/models/urchade__gliner_multi-v2.1.yaml
index 0dcf11c52..231396724 100644
--- a/packages/sie_server/models/urchade__gliner_multi-v2.1.yaml
+++ b/packages/sie_server/models/urchade__gliner_multi-v2.1.yaml
@@ -12,6 +12,7 @@ tasks:
encode: null
score: null
extract: {}
+max_sequence_length: 384
profiles:
default:
max_batch_tokens: 16384
diff --git a/packages/sie_server/models/urchade__gliner_multi_pii-v1.yaml b/packages/sie_server/models/urchade__gliner_multi_pii-v1.yaml
index f8c230915..4688c098d 100644
--- a/packages/sie_server/models/urchade__gliner_multi_pii-v1.yaml
+++ b/packages/sie_server/models/urchade__gliner_multi_pii-v1.yaml
@@ -12,6 +12,7 @@ tasks:
encode: null
score: null
extract: {}
+max_sequence_length: 384
profiles:
default:
max_batch_tokens: 16384
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index 21ea11f00..71224f828 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -3,7 +3,7 @@
"info": {
"title": "SIE Server",
"description": "Search Inference Engine - GPU inference server for search workloads",
- "version": "0.6.24"
+ "version": "0.6.25"
},
"paths": {
"/": {
diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.toml
index 453b066de..4785fa39a 100644
--- a/packages/sie_server/pyproject.toml
+++ b/packages/sie_server/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-server"
-version = "0.6.24"
+version = "0.6.25"
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/clip/__init__.py b/packages/sie_server/src/sie_server/adapters/clip/__init__.py
index 1ed31318d..6133bb386 100644
--- a/packages/sie_server/src/sie_server/adapters/clip/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/clip/__init__.py
@@ -295,6 +295,11 @@ class CLIPAdapter(BaseAdapter):
# text (which also misses the open_clip / mixed-batch cases).
if per_item_token_counts is not None:
output.extra["input_token_counts"] = per_item_token_counts
+ # Modality routing as MEASURED (#2538) — see the SigLIP twin. An item
+ # carrying both text and images takes the image tower only, so its exact
+ # text-token count is zero; the pipeline reads this as the last-resort
+ # basis when no tokenizer could produce counts for the batch.
+ output.extra["text_tower_skipped"] = [i in set(image_indices) for i in range(len(items))]
return output
def _get_preprocess_pool(self) -> ThreadPoolExecutor:
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__.py
index 822cde740..92dbdc6d8 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
@@ -15,6 +15,7 @@ from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision
from sie_server.adapters._vision_patch_embed import rebind_vision_patch_embed
from sie_server.core.inference_output import EncodeOutput
+from sie_server.core.video_frames import extract_frames
from sie_server.types.inputs import media_bytes
if TYPE_CHECKING:
@@ -259,9 +260,16 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):
inst = _normalize_instruction(instruction or "") or _normalize_instruction(self._default_instruction)
embeddings_list: list[np.ndarray] = []
+ # Worker-authoritative §7 "$ per image" counts: submitted images plus
+ # the video frames this call actually sampled and fed to the model.
+ # Travels on ``extra`` (like ``input_token_counts``) so the count is
+ # bound to THIS batch rather than re-derived from the wire item, which
+ # cannot know how many frames a video decoded to.
+ image_counts: list[int] = []
for item in items:
- emb = self._encode_single_item(item, instruction=inst)
+ emb, images_processed = self._encode_single_item(item, instruction=inst)
embeddings_list.append(emb)
+ image_counts.append(images_processed)
# Free GPU memory once after the full batch rather than per item
if self._device and self._device.startswith("cuda"):
@@ -274,9 +282,10 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):
batch_size=len(items),
is_query=is_query,
dense_dim=self._dense_dim,
+ extra={"input_image_counts": image_counts},
)
- def _encode_single_item(self, item: Any, *, instruction: str) -> np.ndarray:
+ def _encode_single_item(self, item: Any, *, instruction: str) -> tuple[np.ndarray, int]:
has_text = item.text is not None
has_images = item.images is not None and len(item.images) > 0
has_video = item.video is not None
@@ -289,13 +298,16 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):
if has_images:
pil_images = self._load_images(item)
- # Extract video frames as images
+ # Extract video frames as images. An undecodable video raises
+ # ``VideoDecodeError`` (typed INVALID_INPUT) — it is never dropped, so a
+ # text+video item can no longer return a billed text-only success that
+ # silently ignored the customer's video.
video_frames: list[Image.Image] | None = None
if has_video:
video_frames = self._extract_video_frames(item)
- # If the input was visual-only but all images/frames failed to load,
- # reject rather than silently embedding an empty prompt.
+ # If the input was visual-only but all images failed to load, reject
+ # rather than silently embedding an empty prompt.
has_loaded_visuals = bool(pil_images) or bool(video_frames)
if not has_text and not has_loaded_visuals:
msg = (
@@ -312,7 +324,15 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):
instruction=instruction,
)
- return self._forward_conversation(conversation)
+ # Billable images = exactly the visual content parts handed to the
+ # model: the images that LOADED plus the frames actually sampled from
+ # the video. Both halves are processed-based, so an unreadable image
+ # that ``_load_images`` dropped with a warning is not billed — the same
+ # rule the video half establishes. This can only ever be at or below
+ # the wire-derived ``count_input_images`` basis the gateway reserves
+ # against, so it cannot push a settled count over its ceiling.
+ images_processed = len(pil_images or []) + len(video_frames or [])
+ return self._forward_conversation(conversation), images_processed
def _forward_conversation(self, conversation: list[dict[str, Any]]) -> np.ndarray:
"""Apply chat template, tokenize, run forward pass, extract embedding."""
@@ -422,41 +442,63 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):
return pil_images
def _extract_video_frames(self, item: Any) -> list[Image.Image]:
- """Extract frames from video input and return as PIL images.
-
- **Limitation**: This is a placeholder that only handles image-decodable
- inputs (e.g. animated GIF first frame) via ``PIL.Image.open`` /
- ``io.BytesIO``. True video files (mp4, webm, avi, etc.) are **not**
- decoded here and will return an empty list. Proper video support
- requires an external decoding library (cv2, av, decord, etc.) to
- extract and sample frames before passing them to the model.
- """
- from PIL import Image
+ """Sample frames from the item's video, as image content parts.
+ Delegates to the shared :mod:`sie_server.core.video_frames` seam, which
+ owns real mp4/webm decoding, the admission caps, and the
+ :data:`~sie_server.core.video_frames.MAX_SAMPLED_FRAMES` budget the
+ managed reservation ceiling is derived from.
+
+ Raises:
+ VideoDecodeError: The video is undecodable or violates a cap. Never
+ returns an empty list for a present video — that would bill a
+ success for input the model never saw.
+ """
video_input = item.video
if video_input is None:
return []
-
- try:
- video_bytes = media_bytes(video_input, kind="video")
- except (KeyError, TypeError) as exc:
- logger.warning("Failed to read video data: %s", exc)
- return []
-
- # Attempt to open as a PIL-decodable image (e.g. animated GIF).
- # Real video formats (mp4/webm) will fail here and return [].
- try:
- pil_img = Image.open(io.BytesIO(video_bytes))
- if pil_img.mode != "RGB":
- pil_img = pil_img.convert("RGB")
- return [pil_img]
- except (OSError, ValueError) as exc:
- logger.warning(
- "Could not decode video input as image via PIL.Image.open: %s "
- "(true video decoding requires cv2/av/decord)",
- exc,
- )
- return []
+ return extract_frames(video_input)
+
+ def count_input_tokens(self, items: list[Item]) -> list[int] | None:
+ """Per-item text-token counts that survive a MIXED batch.
+
+ The base hook is all-or-nothing: one non-text item and it returns
+ ``None`` for the whole batch. That is fine for a text-only encoder, but
+ this adapter accepts text, images and video, and the queue seam fuses
+ items from different API requests — so a text item co-batched with a
+ video item lost its token count, ``_encode_units`` then yielded no
+ units at all, and the gateway faulted the dispatch ("succeeded without
+ authoritative units") after the GPU was already spent.
+
+ Scatter instead, exactly like ``siglip``: real counts for the items
+ that carry text, ``0`` for the visual-only ones. ``_encode_units``
+ drops a zero rather than reporting it, so a visual-only item still
+ settles on ``images`` alone and the plan/terminal dimensions agree.
+
+ Counts the item's TEXT only — the image placeholder tokens the chat
+ template expands are visual input and bill through ``images``; counting
+ them here would charge the same content on two dimensions.
+ """
+ tokenizer = self._metering_tokenizer()
+ if tokenizer is None:
+ return None
+ texts: list[str] = []
+ positions: list[int] = []
+ for index, item in enumerate(items):
+ text = getattr(item, "text", None)
+ if isinstance(text, str) and text:
+ texts.append(text)
+ positions.append(index)
+ counts = [0] * len(items)
+ if not texts:
+ return counts
+ with self._tokenizer_guard():
+ measured = self._token_counts_or_none(tokenizer, texts, expected_len=len(texts))
+ if measured is None:
+ return None
+ for position, count in zip(positions, measured, strict=True):
+ counts[position] = count
+ return counts
def get_preprocessor(self) -> Any | None:
# Qwen3-VL processor requires text alongside images (for chat template
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
index de17ed733..fc16e6461 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -971,6 +971,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
# ``min_tokens`` knob (workaround for Qwen3.6's first-token-EOS
# bug under greedy decode).
if min_new_tokens is not None:
+ if min_new_tokens > max_new_tokens:
+ raise ValueError(f"min_new_tokens ({min_new_tokens}) must not exceed max_new_tokens ({max_new_tokens})")
sampling_params["min_new_tokens"] = min_new_tokens
# SGLang accepts both penalty knobs natively under
# ``sampling_params`` with the same names OpenAI uses. Pass them
@@ -997,6 +999,20 @@ class SGLangGenerationAdapter(GenerationAdapter):
# Merge default sampling from model config (request fields win).
for k, v in self._default_sampling.items():
sampling_params.setdefault(k, v)
+ # A profile-level minimum is a soft default, while the request's
+ # ``max_new_tokens`` is a hard caller limit. Cap the default to that
+ # limit so short health checks and legitimate one-token requests do
+ # not send SGLang an impossible ``min_new_tokens > max_new_tokens``
+ # combination. An explicit caller minimum is validated above instead
+ # of being silently rewritten.
+ if min_new_tokens is None:
+ default_min_new_tokens = sampling_params.get("min_new_tokens")
+ if (
+ isinstance(default_min_new_tokens, int)
+ and not isinstance(default_min_new_tokens, bool)
+ and default_min_new_tokens > max_new_tokens
+ ):
+ sampling_params["min_new_tokens"] = max_new_tokens
stop_list = list(stop or [])
stop_list.extend(s for s in self._stop_tokens if s not in stop_list)
diff --git a/packages/sie_server/src/sie_server/adapters/siglip/adapter.py b/packages/sie_server/src/sie_server/adapters/siglip/adapter.py
index d7fbea211..206ad11d9 100644
--- a/packages/sie_server/src/sie_server/adapters/siglip/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/siglip/adapter.py
@@ -68,50 +68,6 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-def _open_clip_token_counts(input_ids: Any) -> list[int] | None:
- """Per-row non-pad token counts for an ``open_clip`` tokenizer batch (§7.3).
-
- open_clip pads every text to the fixed context length with id ``0``, so the
- count of non-zero ids per row is the real billable length (content plus the
- sot/eot markers) the text tower encoded. Best-effort: any tensor quirk
- yields ``None`` so the meter falls back to its reserve estimate rather than
- mis-billing — metering must never fail inference.
- """
- try:
- return [int((row != 0).sum().item()) for row in input_ids]
- except Exception: # noqa: BLE001 — metering must never fail inference
- return None
-
-
-def _attention_mask_token_counts(
- input_ids: Any,
- attention_mask: Any,
- *,
- expected_len: int,
-) -> list[int] | None:
- """Count the exact tokens selected by a shape-valid binary attention mask.
-
- SigLIP tokenizers commonly use the same id for ``pad_token`` and
- ``eos_token``. Counting ids unequal to the pad id would therefore omit the
- real EOS token from every non-truncated input. The processor's attention
- mask is the unambiguous record of which positions the text tower encoded.
-
- Best-effort: malformed/custom processor output returns ``None`` so the
- caller can use the existing padding-free tokenizer recount. Metering must
- never fail inference or accept a malformed count as settlement evidence.
- """
- try:
- input_shape = tuple(input_ids.shape)
- mask_shape = tuple(attention_mask.shape)
- if len(input_shape) != 2 or mask_shape != input_shape or input_shape[0] != expected_len:
- return None
- if not bool(torch.logical_or(attention_mask == 0, attention_mask == 1).all().item()):
- return None
- return [int(row.sum().item()) for row in attention_mask]
- except Exception: # noqa: BLE001 — metering must never fail inference
- return None
-
-
# Cross-item preprocessing is CPU-bound (PIL decode + resize). Fan the flat
# image set across a small bounded thread pool so decode/resize overlaps.
_MAX_PREPROCESS_THREADS = 8
@@ -594,6 +550,14 @@ class SiglipAdapter(BaseAdapter):
# result path for metering (§P3.5).
if per_item_token_counts is not None:
output.extra["input_token_counts"] = per_item_token_counts
+ # Modality routing as MEASURED, not as inferred from the wire item
+ # (#2538). ``has_images`` wins over ``has_text`` above, so an item
+ # carrying BOTH never reaches the text tower and its exact text-token
+ # count is zero — a fact only this partition knows. The pipeline uses it
+ # as the last-resort token-count basis when nothing else could count,
+ # which is the difference between settling a wholly image-toward batch
+ # and faulting it as reserved-but-missing.
+ output.extra["text_tower_skipped"] = [i in set(image_indices) for i in range(len(items))]
return output
def _get_preprocess_pool(self) -> ThreadPoolExecutor:
@@ -721,10 +685,10 @@ class SiglipAdapter(BaseAdapter):
# Serialise tokenization: fast tokenizers are not thread-safe.
with self._tokenizer_lock:
input_ids = self._open_clip_tokenizer(list(texts))
- # Unit-meter seam (§7.3): open_clip pads to a fixed context
- # length with id 0, so the non-pad count per row is the real
- # billable length (content + sot/eot) the tower encoded.
- token_counts = _open_clip_token_counts(input_ids)
+ # Unit-meter seam (§7.3): SigLIP executes every text at the
+ # resolved fixed context length. Bill that padded work, not the
+ # content-dependent count of non-pad ids (#2629).
+ token_counts = [self._max_seq_length] * len(texts)
input_ids = input_ids.to(self._device)
with torch.inference_mode():
text_features = self._model.encode_text(input_ids, normalize=self._normalize)
@@ -744,20 +708,11 @@ class SiglipAdapter(BaseAdapter):
truncation=True,
max_length=self._max_seq_length,
)
- # Unit-meter seam (§7.3): the exact attention mask includes the
- # real EOS token even when it shares an id with padding (the
- # stock SigLIP tokenizer does this). Older/custom processors
- # without a shape-valid binary mask retain the conservative
- # padding-free recount fallback.
- token_counts = _attention_mask_token_counts(
- inputs.get("input_ids"),
- inputs.get("attention_mask"),
- expected_len=len(texts),
- )
- if token_counts is None:
- token_counts = self._token_counts_or_none(
- self._processor.tokenizer, list(texts), expected_len=len(texts)
- )
+ # The processor was explicitly asked for max-length padding,
+ # and load() clamps this value to the text tower's capacity.
+ # The attention-mask sum is intentionally irrelevant: short
+ # captions execute the same padded work as long ones (#2629).
+ token_counts = [self._max_seq_length] * len(texts)
inputs = {k: v.to(self._device) for k, v in inputs.items()}
with torch.inference_mode():
text_features = _feature_tensor(self._model.get_text_features(**inputs))
diff --git a/packages/sie_server/src/sie_server/api/encode.py b/packages/sie_server/src/sie_server/api/encode.py
index 884ab9be8..1c7440d2d 100644
--- a/packages/sie_server/src/sie_server/api/encode.py
+++ b/packages/sie_server/src/sie_server/api/encode.py
@@ -392,13 +392,30 @@ async def encode(
response = EncodeResponse(model=model, items=response_items, timing=timing_info)
if worker_telemetry_enabled():
- units = None
+ 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
):
- units = {"input_tokens": sum(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}
+ # §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.
+ if timing is not None and timing.input_image_counts is not None:
+ images = sum(timing.input_image_counts)
+ if images > 0:
+ units = {**(units or {}), "images": images}
worker_telemetry().item_completed(
operation="encode",
outcome="success",
diff --git a/packages/sie_server/src/sie_server/core/encode_pipeline.py b/packages/sie_server/src/sie_server/core/encode_pipeline.py
index 7c340c1e6..2f760cba5 100644
--- a/packages/sie_server/src/sie_server/core/encode_pipeline.py
+++ b/packages/sie_server/src/sie_server/core/encode_pipeline.py
@@ -82,6 +82,80 @@ def resolve_encode_output_types(
return adapter_output_types, response_output_types
+def _validated_counts(value: Any, expected_len: int, *, non_negative: bool = False) -> list[int] | None:
+ """Accept a per-item unit-count list only if it can be attributed exactly.
+
+ The single gate every metering basis passes through, so the contract lives
+ in one place as §7 dimensions are added. A value that is not a list, is
+ misaligned with the batch, or holds anything but real ints (``bool`` is an
+ ``int`` subclass and is rejected) yields ``None`` — the meter then falls
+ back to its reserve estimate rather than mis-attributing or approximating a
+ count. ``non_negative`` additionally rejects negatives; every §7 dimension
+ passes it, because a negative unit count is meaningless in all of them and
+ ``api/encode.py`` sums these straight into the reported usage.
+ """
+ if not isinstance(value, list) or len(value) != expected_len:
+ return None
+ for count in value:
+ if not isinstance(count, int) or isinstance(count, bool):
+ return None
+ if non_negative and count < 0:
+ return None
+ return [int(count) for count in value]
+
+
+def _wholly_skipped_text_tower_zeros(skipped: Any, items: list[Item]) -> list[int] | None:
+ """Authoritative per-item token zeros IFF a TEXT-BEARING batch wholly
+ skipped the text tower.
+
+ ``skipped`` is the adapter's own modality partition
+ (``extra["text_tower_skipped"]``, stamped by the SigLIP/CLIP twins). When it
+ says EVERY item in the batch took a non-text tower AND at least one of those
+ items carried text, the exact text-token count is zero — a measurement, not
+ an absent count — and the terminal can carry the dimension the gateway plan
+ reserved off text PRESENCE (``dispatcher::carries_tokenizable_text``)
+ instead of omitting it and faulting the whole dispatch as
+ reserved-but-missing (#2538).
+
+ ``None`` for anything else, which is what keeps today's billing intact:
+
+ * a partition that is malformed, misaligned with the batch, or holds
+ non-``bool`` entries is not a measurement and is dropped, exactly like
+ every other basis in `_validated_counts`;
+ * a partition with even ONE unskipped item is a batch that had text the
+ tokenizer should have counted. Returning zeros there would convert "bill
+ text the model read" into "bill nothing", which is a pricing decision
+ rather than a bug fix;
+ * an EMPTY partition vacuously satisfies ``all()``. It is rejected rather
+ than trusted: "no items took the text tower" is not a measurement of
+ anything, and letting it through would mint a bare unwitnessed zero — the
+ one shape the settlement witness exists to refuse;
+ * a batch with NO text at all — the pure-image request. ``text_tower_skipped``
+ is ``True`` for a pure-image item just as it is for a text+image one, so
+ without this clause the fallback would fire there too and put a
+ ``input_tokens = 0`` on the terminal of a request that never reserved the
+ dimension. That is the case the SigLIP/CLIP adapters already, deliberately,
+ keep off the token dimension (they stamp ``input_token_counts`` only when
+ at least one item reached the text tower), and #2538 must not quietly
+ reverse it. The text condition mirrors the gateway's reservation predicate
+ exactly: no reserved dimension, nothing to release.
+
+ Named and extracted so the rule can be exercised directly. Inline, its only
+ coverage was a source-text assertion about statement ORDER — which cannot
+ tell whether the branch computes the right thing, and passed unchanged with
+ the whole branch deleted.
+ """
+ if not isinstance(skipped, list) or len(skipped) != len(items):
+ return None
+ if not all(isinstance(flag, bool) for flag in skipped):
+ return None
+ if not skipped or not all(skipped):
+ return None
+ if not any(isinstance(getattr(item, "text", None), str) and item.text for item in items):
+ return None
+ return [0] * len(items)
+
+
class EncodePipeline:
@classmethod
async def run_encode(
@@ -175,13 +249,21 @@ class EncodePipeline:
# exist; malformed/misaligned values are dropped rather than
# mis-attributed — metering falls back to its reserve estimate.
if timing.input_token_counts is None:
- extra_counts = encode_output.extra.get("input_token_counts")
- if (
- isinstance(extra_counts, list)
- and len(extra_counts) == len(items)
- and all(isinstance(count, int) and not isinstance(count, bool) for count in extra_counts)
- ):
- timing.input_token_counts = [int(count) for count in extra_counts]
+ timing.input_token_counts = _validated_counts(
+ encode_output.extra.get("input_token_counts"), len(items), non_negative=True
+ )
+
+ # Worker-authoritative per-image counts (§7 "$ per image"). Adapters
+ # whose billable image count differs from what the wire item carries —
+ # today the video-capable encoders, which bill the frames they actually
+ # sampled out of compressed video bytes — stamp them on ``extra``. The
+ # wire-derived ``count_input_images`` hook cannot know that number, so
+ # this is the only basis on which sampled frames settle. Malformed or
+ # misaligned values are dropped rather than mis-attributed; the result
+ # path then falls back to the hook.
+ timing.input_image_counts = _validated_counts(
+ encode_output.extra.get("input_image_counts"), len(items), non_negative=True
+ )
# Shared metering seam: adapters that own their tokenization but do not
# pre-stamp ``extra`` (every flash text encoder — e5/bert_flash,
@@ -199,12 +281,26 @@ class EncodePipeline:
adapter = None
if adapter is not None:
counts = await asyncio.to_thread(adapter.count_input_tokens, items)
- if (
- isinstance(counts, list)
- and len(counts) == len(items)
- and all(isinstance(count, int) and not isinstance(count, bool) for count in counts)
- ):
- timing.input_token_counts = [int(count) for count in counts]
+ timing.input_token_counts = _validated_counts(counts, len(items), non_negative=True)
+
+ # LAST resort (#2538): every item in this batch took a non-text tower,
+ # as MEASURED by the adapter's own modality partition — so the exact
+ # text-token count is zero, not unknown. Without this the terminal omits
+ # a dimension the gateway plan reserved off text PRESENCE
+ # (``dispatcher::carries_tokenizable_text``) and settlement faults the
+ # whole dispatch as reserved-but-missing: a 500 with zero debit after
+ # the GPU already ran.
+ #
+ # Deliberately positioned AFTER the ``count_input_tokens`` fallback and
+ # gated on ALL items being skipped AND the batch carrying text, so it
+ # only fires where nothing else could count and the gateway actually
+ # reserved the dimension. Any batch where a real tokenizer produced
+ # numbers keeps them, a pure-image batch stays on the image dimension,
+ # and the billing of shapes that settle today is unchanged.
+ if timing.input_token_counts is None:
+ timing.input_token_counts = _wholly_skipped_text_tower_zeros(
+ encode_output.extra.get("text_tower_skipped"), items
+ )
formatted_output = EncodeHandler.format_output(
encode_output,
diff --git a/packages/sie_server/src/sie_server/core/runtime_options.py b/packages/sie_server/src/sie_server/core/runtime_options.py
index 9cd5dbe21..453ce1a45 100644
--- a/packages/sie_server/src/sie_server/core/runtime_options.py
+++ b/packages/sie_server/src/sie_server/core/runtime_options.py
@@ -143,6 +143,20 @@ def apply_generation_runtime_options(
runtime["default_sampling"] = {**profile_sampling, **request_sampling}
result = dict(generate_params)
+ # The typed request maximum is a hard caller limit. Reject an explicit
+ # minimum that contradicts it even when this profile has no sampler
+ # defaults; the adapter repeats this check before the engine boundary.
+ max_new_tokens = result.get("max_new_tokens")
+ has_integer_max = isinstance(max_new_tokens, int) and not isinstance(max_new_tokens, bool)
+ explicit_min_tokens = result.get("min_tokens")
+ if (
+ has_integer_max
+ and isinstance(explicit_min_tokens, int)
+ and not isinstance(explicit_min_tokens, bool)
+ and explicit_min_tokens > max_new_tokens
+ ):
+ raise ValueError(f"min_tokens ({explicit_min_tokens}) must not exceed max_new_tokens ({max_new_tokens})")
+
sampling = runtime.get("default_sampling")
if sampling is not None:
if not isinstance(sampling, dict):
@@ -165,9 +179,18 @@ def apply_generation_runtime_options(
valid = isinstance(value, int) and not isinstance(value, bool) and value >= 0
if not valid:
raise ValueError(f"'options.default_sampling.{key}' has an invalid value")
+
for source, target in _GENERATION_SAMPLING_KEYS.items():
if source in sampling and result.get(target) is None:
- result[target] = sampling[source]
+ value = sampling[source]
+ if source == "min_new_tokens" and has_integer_max and value > max_new_tokens:
+ if isinstance(request_sampling, dict) and source in request_sampling:
+ raise ValueError(
+ f"'options.default_sampling.min_new_tokens' ({value}) "
+ f"must not exceed max_new_tokens ({max_new_tokens})"
+ )
+ value = max_new_tokens
+ result[target] = value
stop_tokens = runtime.get("stop_tokens")
if stop_tokens is not None:
diff --git a/packages/sie_server/src/sie_server/core/timing.py b/packages/sie_server/src/sie_server/core/timing.py
index 166005ffb..4ab344006 100644
--- a/packages/sie_server/src/sie_server/core/timing.py
+++ b/packages/sie_server/src/sie_server/core/timing.py
@@ -45,6 +45,16 @@ class RequestTiming:
# not approximate).
input_token_counts: list[int] | None = field(default=None, repr=False)
+ # Authoritative per-item input-IMAGE counts (§7 "$ per image"), aligned with
+ # the request's item order; ``None`` when the adapter surfaced no count and
+ # the result path must fall back to the wire-derived ``count_input_images``
+ # hook. Only adapters that expand an input into a different number of
+ # billable images than the wire item carries need this: the video-capable
+ # encoders bill the frames they actually sampled, a number the wire item
+ # (raw compressed bytes) cannot express. Set by ``EncodePipeline.run_encode``
+ # from ``EncodeOutput.extra["input_image_counts"]``.
+ input_image_counts: list[int] | None = field(default=None, repr=False)
+
def start_tokenization(self) -> None:
"""Mark tokenization start."""
self._tokenize_start = time.monotonic()
diff --git a/packages/sie_server/src/sie_server/core/video_frames.py b/packages/sie_server/src/sie_server/core/video_frames.py
new file mode 100644
index 000000000..af3913f24
--- /dev/null
+++ b/packages/sie_server/src/sie_server/core/video_frames.py
@@ -0,0 +1,392 @@
+"""Video frame extraction and admission caps for the frames-as-images meter.
+
+Sampled video frames are the model's real visual input, so they bill as §7
+``images`` units on the count of frames the worker **actually processed** —
+never a request-declared or estimated number. This module is the single seam
+that turns wire ``VideoInput`` bytes into PIL frames, so exactly one place owns
+the sampling budget that both the biller and the managed reservation ceiling
+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.
+- **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
+ broken decoder in a GPU image can therefore never masquerade as a successful
+ zero-frame encode that silently drops the customer's video.
+- **Deterministic.** Sampling is evenly spaced over the stream and fills the
+ budget exactly, so the same bytes always yield the same frames and therefore
+ the same bill.
+
+Decode work is bounded by the frame budget, not by the stream length: sampling
+seeks to the target indices and decodes only those. That matters beyond
+latency — on the batched worker path ``adapter.encode`` runs on
+``ModelWorker._inference_executor``, a single-threaded pool that serializes the
+model's GPU work, so walking a long stream there would stall every
+co-scheduled request. The residual costs are one seek per sampled frame
+(FFmpeg decodes from the preceding keyframe, so at most one GOP each) and, for
+containers that report no usable metadata, the one grab-only counting pass
+under :data:`_MAX_SCANNED_FRAMES`.
+
+TODO(#2433): move extraction off the inference executor entirely — decode in
+per-item preprocessing (``EncodePipeline._prepare_batch``) and hand the frames
+to the adapter through ``PreparedItem.payload``, so the GPU thread only ever
+sees decoded frames. That needs a prepared-item payload the video-capable
+adapters actually read, which today they do not (``get_preprocessor`` returns
+``None``), so it is a follow-up rather than part of this seam.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+import os
+import tempfile
+from collections.abc import Callable
+from typing import Any, Final
+
+from PIL import Image
+
+from sie_server.types.inputs import InvalidInputError, media_bytes
+
+logger = 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.
+MAX_SAMPLED_FRAMES: Final[int] = 32
+
+
+# Admission caps: abuse rails bounding decode work per item, not model limits.
+# 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
+# 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 cap
+# has no gateway mirror at all (the gateway holds no decoder), so it is
+# authoritative on every path.
+#
+# Parsed defensively: these run at IMPORT time, so a typo in either knob would
+# raise out of `import sie_server` and take down startup for the whole server —
+# including every text-only path that never touches video. A malformed value
+# falls back to the default and logs, which keeps the blast radius at the knob.
+def _bounded_env[T: (int, float)](name: str, default: str, cast: Callable[[str], T]) -> T:
+ raw = os.environ.get(name, default)
+ try:
+ return cast(raw)
+ except (TypeError, ValueError):
+ logger.warning(
+ "%s=%r is not a valid number; falling back to the default %s",
+ name,
+ raw,
+ default,
+ )
+ return cast(default)
+
+
+MAX_VIDEO_BYTES: Final[int] = _bounded_env("SIE_MAX_VIDEO_BYTES", str(256 * 1024 * 1024), int)
+MAX_VIDEO_DURATION_S: Final[float] = _bounded_env("SIE_MAX_VIDEO_DURATION_S", "1800", float)
+
+# Containers without usable fps/frame-count metadata cannot be duration-checked
+# before decoding, so the duration cap degrades to this scan cap on decoded
+# frames (1800 s at 60 fps). Both are ceilings on the same abuse: unbounded
+# decode work for one item.
+_MAX_SCANNED_FRAMES: Final[int] = 108_000
+
+# Hard cap on ``grab()`` calls for the no-seek sampling fallback. Sampling is
+# seek-based: it decodes ONLY the target frames, so its cost is the frame budget
+# and not the stream length. A backend that cannot position the capture has to
+# walk forward instead, and that walk is bounded here rather than allowed to
+# scale with the stream — a decode holds a worker thread, and on the batched
+# path that thread is the model's single GPU-serialization executor, so an
+# unbounded walk stalls every co-scheduled request. Beyond the cap the item is
+# refused with a typed 400 instead of monopolising the worker. Sized for a
+# 2-minute 30 fps clip; only a backend with broken seeking ever reaches it.
+_MAX_SAMPLE_GRABS: Final[int] = 3_600
+
+_FORMAT_SUFFIXES: Final[dict[str, str]] = {
+ "mp4": ".mp4",
+ "m4v": ".mp4",
+ "mov": ".mov",
+ "webm": ".webm",
+ "mkv": ".mkv",
+ "avi": ".avi",
+ "gif": ".gif",
+}
+
+
+class VideoDecodeError(InvalidInputError):
+ """A video input could not be decoded, or violates an admission cap.
+
+ Subclasses :class:`~sie_server.types.inputs.InvalidInputError` so both
+ ingress paths surface it as structured ``INVALID_INPUT`` (HTTP 400): a
+ caller-controlled input that the worker refuses is a client error, and —
+ critically — never a billed success that quietly processed zero frames.
+ """
+
+
+def _suffix_for(video: Any) -> str:
+ """Map the wire ``format`` hint to a temp-file suffix for the decoder.
+
+ The hint is advisory: FFmpeg sniffs the container, and the suffix only
+ helps it pick a demuxer faster. An unknown hint falls back to ``.mp4``.
+ """
+ hint = video.get("format") if isinstance(video, dict) else None
+ if isinstance(hint, str):
+ return _FORMAT_SUFFIXES.get(hint.strip().lower().lstrip("."), ".mp4")
+ return ".mp4"
+
+
+def _bgr_to_pil(frame: Any) -> Image.Image:
+ """Convert one decoded OpenCV BGR frame to an RGB PIL image."""
+ return Image.fromarray(frame[:, :, ::-1])
+
+
+def extract_frames(video: Any, *, max_frames: int = MAX_SAMPLED_FRAMES) -> list[Image.Image]:
+ """Decode ``video`` and return up to ``max_frames`` uniformly sampled frames.
+
+ The returned list length is the item's authoritative billable frame count:
+ every frame here was handed to the model, and no frame reaches the model
+ without appearing here.
+
+ Args:
+ video: A wire :class:`~sie_server.types.inputs.VideoInput` mapping.
+ max_frames: Sampling budget; must not exceed :data:`MAX_SAMPLED_FRAMES`.
+
+ Returns:
+ The sampled frames as RGB PIL images, in stream order.
+
+ Raises:
+ VideoDecodeError: The bytes are empty, exceed an admission cap, or no
+ decoder could open/read them.
+ InvalidMediaError: ``video`` violates the wire media contract.
+ """
+ budget = min(max_frames, MAX_SAMPLED_FRAMES)
+ if budget < 1:
+ msg = f"video frame budget must be positive, got {max_frames}"
+ raise VideoDecodeError(msg)
+
+ data = media_bytes(video, kind="video")
+ if not data:
+ raise VideoDecodeError("video input carries no data")
+ if len(data) > MAX_VIDEO_BYTES:
+ msg = f"video input is {len(data)} bytes, exceeding the {MAX_VIDEO_BYTES}-byte admission cap"
+ raise VideoDecodeError(msg)
+
+ cv2 = _load_decoder()
+ # VideoCapture reads from a path, not memory. Delete-on-close is deferred to
+ # the context manager so the decoder can reopen the file by name on FFmpeg
+ # backends that re-open for seeking.
+ with tempfile.NamedTemporaryFile(suffix=_suffix_for(video)) as handle:
+ handle.write(data)
+ handle.flush()
+ capture = cv2.VideoCapture(handle.name)
+ try:
+ if not capture.isOpened():
+ raise VideoDecodeError("video input could not be opened by the decoder")
+ total = _validated_frame_total(cv2, capture)
+ return _sample(cv2, capture, total=total, budget=budget)
+ finally:
+ capture.release()
+
+
+def _load_decoder() -> Any:
+ """Import the OpenCV decoder, failing closed when the image lacks it.
+
+ cv2 is a declared ``sie_server`` dependency, but decoder wheels are known to
+ be broken in some GPU images (issue #2433). Importing at point of use keeps
+ a broken image from taking down server startup, and converts the breakage
+ into a typed 4xx rather than a silent zero-frame success.
+ """
+ try:
+ import cv2
+ except ImportError as exc: # pragma: no cover - dependency present in-tree
+ msg = f"no video decoder is available in this image: {exc}"
+ raise VideoDecodeError(msg) from exc
+ return cv2
+
+
+def _validated_frame_total(cv2: Any, capture: Any) -> int | None:
+ """Return the container's frame count, enforcing the duration cap.
+
+ ``None`` means the container reported unusable metadata; the caller then
+ counts frames itself under :data:`_MAX_SCANNED_FRAMES`.
+
+ Both properties are C doubles, so a container with a broken header can
+ report NaN or infinity. Those are truthy, so ``or 0`` does not filter them
+ and ``int()`` would raise ``ValueError`` / ``OverflowError`` — escaping this
+ module's typed-failure contract as a generic 500. They are checked for
+ finiteness BEFORE any conversion and treated as unusable metadata.
+ """
+ raw_count = float(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0.0)
+ fps = float(capture.get(cv2.CAP_PROP_FPS) or 0.0)
+ if not math.isfinite(raw_count) or raw_count <= 0 or not math.isfinite(fps) or fps <= 0.0:
+ return None
+ frame_count = int(raw_count)
+ duration_s = frame_count / fps
+ if duration_s > MAX_VIDEO_DURATION_S:
+ msg = f"video input is {duration_s:.1f}s long, exceeding the {MAX_VIDEO_DURATION_S}s admission cap"
+ raise VideoDecodeError(msg)
+ return frame_count
+
+
+def _count_frames(capture: Any) -> int:
+ """Count decodable frames with grab-only scanning (no pixel decode)."""
+ total = 0
+ while capture.grab():
+ total += 1
+ if total > _MAX_SCANNED_FRAMES:
+ msg = (
+ f"video input exceeds the {_MAX_SCANNED_FRAMES}-frame scan cap "
+ "(container reported no usable duration metadata)"
+ )
+ raise VideoDecodeError(msg)
+ return total
+
+
+def _target_indices(total: int, budget: int) -> list[int]:
+ """Evenly spaced source indices for one item's sampling budget.
+
+ Returns exactly ``min(total, budget)`` strictly increasing indices spread
+ over ``[0, total)``. A uniform *stride* (``ceil(total / budget)``) silently
+ under-fills the budget for nearly every length — 33 frames at budget 32
+ yields 17 — which halves both the visual context the model sees and the
+ customer's bill at a boundary invisible to them. Even spacing fills the
+ budget for every ``total >= budget`` and stays deterministic, so the same
+ bytes keep producing the same frames and therefore the same bill.
+ """
+ count = min(total, budget)
+ return [(index * total) // count for index in range(count)]
+
+
+def _sample(cv2: Any, capture: Any, *, total: int | None, budget: int) -> list[Image.Image]:
+ """Sample exactly ``min(total, budget)`` evenly spaced frames.
+
+ Decoding is seek-based (see :func:`_decode_targets`): only the target
+ frames are decoded, so the cost is the frame budget rather than the stream
+ length.
+ """
+ if total is None:
+ total = _count_frames(capture)
+ # Rewind for the decode pass. A backend that cannot seek leaves the
+ # capture exhausted, which the empty-result guard below catches.
+ capture.set(cv2.CAP_PROP_POS_FRAMES, 0)
+ if total <= 0:
+ raise VideoDecodeError("video input contains no decodable frames")
+
+ frames = _decode_targets(cv2, capture, _target_indices(total, budget))
+ if not frames:
+ raise VideoDecodeError("video input contains no decodable frames")
+ return frames
+
+
+def _seek_to(cv2: Any, capture: Any, index: int) -> int | None:
+ """Ask the backend to position the capture at ``index``.
+
+ Returns where the capture actually LANDED, which is not always ``index``:
+ a backend may snap backwards to the preceding keyframe, and one that
+ silently ignores the request keeps reporting its old position. The caller
+ must therefore resynchronise its logical cursor from the return value —
+ assuming the landing equals the request would decode the wrong frames.
+
+ ``None`` means the backend gave no usable position — ``set`` refused, or
+ the reported position is missing or non-finite (the property is a C double,
+ and ``int(nan)`` would raise mid-decode, escaping this module's typed
+ contract). The caller then keeps its existing cursor and walks the gap.
+ """
+ if not capture.set(cv2.CAP_PROP_POS_FRAMES, index):
+ return None
+ position = capture.get(cv2.CAP_PROP_POS_FRAMES)
+ if position is None or not math.isfinite(float(position)):
+ return None
+ return int(position)
+
+
+def _decode_targets(cv2: Any, capture: Any, targets: list[int]) -> list[Image.Image]:
+ """Decode exactly the frames at ``targets`` (strictly increasing).
+
+ Each gap between targets is crossed by seeking, so a normal stream costs
+ one seek and one pixel decode per sampled frame regardless of its length.
+
+ The cursor is always resynchronised from where the capture actually landed
+ (see :func:`_seek_to`), never from where the seek was aimed. A backend that
+ snaps backwards to a keyframe then pays a short forward ``grab()`` walk to
+ reach the target; one that refuses to seek at all walks the whole gap,
+ stickily, without re-asking. Either way the walk is bounded in total by
+ :data:`_MAX_SAMPLE_GRABS`, so no backend can turn one item into an
+ unbounded walk on the worker's inference thread.
+
+ A read that fails part-way through is a container that over-reported its
+ length (or a truncated tail): the frames already decoded are returned,
+ because those are the frames the model gets and therefore exactly what may
+ be billed.
+ """
+ frames: list[Image.Image] = []
+ next_index = 0 # source index the capture will return on the next read
+ seekable = True
+ grabs = 0
+ for target in targets:
+ if target != next_index and seekable:
+ landing = _seek_to(cv2, capture, target)
+ if landing is None:
+ # Refused: the capture did not move, so the cursor still holds
+ # and the walk below crosses the gap. Do not ask again.
+ seekable = False
+ elif landing > target:
+ # Overshot the target. Walking forward cannot come back, and
+ # reading here would silently sample the wrong frame, so stop
+ # and bill only the frames already decoded.
+ logger.warning(
+ "Video sampling stopped early: seek to frame %d landed at %d (overshoot); "
+ "billing the %d frame(s) decoded so far out of %d requested",
+ target,
+ landing,
+ len(frames),
+ len(targets),
+ )
+ return frames
+ else:
+ # Exact, or snapped back to a keyframe: adopt the real position
+ # and let the bounded walk cover whatever remains.
+ next_index = landing
+ while next_index < target:
+ grabs += 1
+ if grabs > _MAX_SAMPLE_GRABS:
+ msg = (
+ f"video input needs more than {_MAX_SAMPLE_GRABS} skipped frames to sample "
+ "(this decoder backend cannot seek accurately)"
+ )
+ raise VideoDecodeError(msg)
+ if not capture.grab(): # skip without paying the pixel-decode cost
+ logger.warning(
+ "Video sampling stopped early: stream ended while skipping to frame %d; "
+ "billing the %d frame(s) decoded so far out of %d requested",
+ target,
+ len(frames),
+ len(targets),
+ )
+ return frames
+ next_index += 1
+ ok, frame = capture.read()
+ if not ok:
+ logger.warning(
+ "Video sampling stopped early: frame %d could not be read (container over-reported "
+ "its length, or the tail is truncated); billing the %d frame(s) decoded so far "
+ "out of %d requested",
+ target,
+ len(frames),
+ len(targets),
+ )
+ break
+ frames.append(_bgr_to_pil(frame))
+ next_index = target + 1
+ return frames
diff --git a/packages/sie_server/src/sie_server/core/worker/handlers/encode.py b/packages/sie_server/src/sie_server/core/worker/handlers/encode.py
index 2533ab90e..359be89e5 100644
--- a/packages/sie_server/src/sie_server/core/worker/handlers/encode.py
+++ b/packages/sie_server/src/sie_server/core/worker/handlers/encode.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Final
import numpy as np
@@ -14,6 +14,25 @@ if TYPE_CHECKING:
from sie_server.core.worker.types import RequestMetadata
from sie_server.types.inputs import Item
+# ``EncodeOutput.extra`` keys whose values are per-item lists aligned 1:1 with
+# the batch, and which therefore MUST be sliced and reassembled with the item.
+# These are the unit meter's authoritative bases (§7): real tokenizer counts
+# from adapters that own their tokenization, and the images/video frames an
+# adapter actually processed — a number the wire item cannot express. Dropping
+# either here silently strips the meter's evidence whenever the worker fuses
+# several API requests into one GPU batch, which then bills the frames as zero
+# or faults settlement outright. Every other ``extra`` key has no defined
+# per-item semantics and is intentionally not propagated.
+# ``text_tower_skipped`` (#2538) is the third: the modality routing a vision
+# adapter actually applied, which is how the pipeline knows an item's zero text
+# tokens is a MEASUREMENT ("it took the image tower") and not an absent count.
+# It must be sliced with its item for the same reason the counts are.
+PER_ITEM_EXTRA_KEYS: Final[tuple[str, ...]] = (
+ "input_token_counts",
+ "input_image_counts",
+ "text_tower_skipped",
+)
+
class EncodeHandler(OperationHandler[EncodeOutput]):
"""Handler for encode (embedding) operations.
@@ -134,16 +153,13 @@ class EncodeHandler(OperationHandler[EncodeOutput]):
Returns:
Single-item EncodeOutput.
"""
- # Per-item unit counts (``extra["input_token_counts"]``, emitted by
- # adapters that own their tokenization) are positional like dense/
- # sparse, so they must be sliced with the item — dropping them here
- # would silently strip the meter's counts whenever the worker fuses
- # requests into one GPU batch. Other ``extra`` keys have no defined
- # per-item semantics and are intentionally not propagated.
+ # Per-item unit counts are positional like dense/sparse, so they must
+ # be sliced with the item — see ``PER_ITEM_EXTRA_KEYS``.
extra: dict[str, Any] = {}
- counts = output.extra.get("input_token_counts") if output.extra else None
- if isinstance(counts, list) and 0 <= index < len(counts):
- extra["input_token_counts"] = [counts[index]]
+ for key in PER_ITEM_EXTRA_KEYS:
+ counts = output.extra.get(key) if output.extra else None
+ if isinstance(counts, list) and 0 <= index < len(counts):
+ extra[key] = [counts[index]]
return EncodeOutput(
dense=output.dense[index : index + 1] if output.dense is not None else None,
sparse=[output.sparse[index]] if output.sparse is not None else None,
@@ -201,20 +217,23 @@ class EncodeHandler(OperationHandler[EncodeOutput]):
if first.multivector is not None:
multivector = [partials[i].multivector[0] for i in range(batch_size)] # ty: ignore[not-subscriptable]
- # Reassemble per-item unit counts (see slice_output). All-or-nothing:
- # a partial without a count means the meter cannot attribute the
- # request exactly, so no counts are surfaced (metering then falls
- # back to its reserve estimate rather than under-counting).
+ # Reassemble per-item unit counts (see slice_output). All-or-nothing
+ # per key: a partial without a count means the meter cannot attribute
+ # the request exactly, so that dimension is not surfaced (metering then
+ # falls back to its reserve estimate rather than under-counting). The
+ # keys are independent — a video encode carries image counts with no
+ # token counts at all.
extra: dict[str, Any] = {}
- assembled_counts: list[int] = []
- for i in range(batch_size):
- partial_counts = partials[i].extra.get("input_token_counts") if partials[i].extra else None
- if not (isinstance(partial_counts, list) and len(partial_counts) == 1):
- assembled_counts = []
- break
- assembled_counts.append(partial_counts[0])
- if assembled_counts:
- extra["input_token_counts"] = assembled_counts
+ for key in PER_ITEM_EXTRA_KEYS:
+ assembled_counts: list[int] = []
+ for i in range(batch_size):
+ partial_counts = partials[i].extra.get(key) if partials[i].extra else None
+ if not (isinstance(partial_counts, list) and len(partial_counts) == 1):
+ assembled_counts = []
+ break
+ assembled_counts.append(partial_counts[0])
+ if assembled_counts:
+ extra[key] = assembled_counts
return EncodeOutput(
dense=dense,
diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.py
index 3b4d776ad..5ee37301e 100644
--- a/packages/sie_server/src/sie_server/queue_executor.py
+++ b/packages/sie_server/src/sie_server/queue_executor.py
@@ -4,6 +4,7 @@ import asyncio
import logging
import os
import tempfile
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, Final
@@ -70,6 +71,19 @@ logger = logging.getLogger(__name__)
# do not "align" it to the HTTP enum or the gateway will fall through to its
# generic arm with a mismatched code.
_INFERENCE_ERROR_CODE: Final[str] = "inference_error"
+# Re-encode passes one encode batch may spend isolating malformed input before
+# it stops bisecting. Isolation exists for the INPUT-SPECIFIC failure — one
+# caller's undecodable video among many healthy requests — which costs about
+# 2*log2(R) passes and never comes near this budget. But the same
+# ``InvalidInputError`` is also raised by an ENVIRONMENTAL failure: a GPU image
+# whose OpenCV wheel is broken fails ``_load_decoder`` for EVERY video-carrying
+# request (#2433). Then both halves of every split fail, bisection degenerates
+# to ~2R passes, and an image-wide outage multiplies occupancy of the
+# single-threaded inference executor at exactly the moment the node is already
+# broken. Past this budget the remaining requests take the error directly —
+# which under a systemic failure is also the correct answer, because every one
+# of them was going to fail anyway.
+_MAX_ENCODE_ISOLATION_PASSES: Final[int] = 24
_CANONICAL_AUDIO_SAMPLE_RATE: Final[int] = 16_000
_MAX_AUDIO_CHANNELS: Final[int] = 2
_MIN_AUDIO_SAMPLE_RATE: Final[int] = 8_000
@@ -490,6 +504,25 @@ def _wrap_encode_output(output: dict, config: Any) -> dict:
# ---------------------------------------------------------------------------
+@dataclass
+class _IsolationBudget:
+ """Re-run passes one encode batch may still spend isolating bad input.
+
+ Shared across the batch's sub-groups so a systemic failure cannot pay the
+ bisection cost afresh in each one. See
+ :data:`_MAX_ENCODE_ISOLATION_PASSES`.
+ """
+
+ remaining: int
+
+ def spend(self) -> bool:
+ """Consume one split, or report that the budget is gone."""
+ if self.remaining <= 0:
+ return False
+ self.remaining -= 1
+ return True
+
+
class QueueExecutor:
"""NATS-free execution layer fronted by the IPC server for the worker-sidecar.
@@ -912,178 +945,348 @@ class QueueExecutor:
subgroup_sizes=(len(group) for group in groups.values()),
)
+ # One isolation budget for the whole batch: a systemic decoder failure
+ # would otherwise pay the bisection cost again in every sub-group.
+ isolation = _IsolationBudget(remaining=_MAX_ENCODE_ISOLATION_PASSES)
for group_key, group in groups.items():
- (output_types_t, instruction, is_query, options_key, _profile_id, _bundle_hash) = group_key
- output_types = list(output_types_t)
- options = msgpack.unpackb(options_key, raw=False) if options_key else {}
- # Validate each item against the typed Item contract at the seam
- # (parity with the HTTP path). A per-item decode failure is isolated
- # as an INVALID_INPUT outcome so one malformed item cannot fail its
- # whole sub-group. See decode_item / issue #1537.
- good_group: list[EncodeBatchItem] = []
- server_items: list[Item] = []
- for bi in group:
- try:
- server_items.append(decode_item(bi.item))
- except (msgspec.ValidationError, InvalidMediaError) as decode_exc:
- outcomes[bi.work_item_id] = _inference_exception_outcome(bi, decode_exc)
- continue
- good_group.append(bi)
- if not good_group:
- continue
- # Collect worker-sidecar prepared_tokens aligned with
- # ``server_items``. ``None`` per item is expected for the
- # v1 safety-rule skips (`is_query`, `instruction`,
- # non-text, empty text). The pipeline accepts the mix
- # per-item: items with usable Rust bytes skip Python
- # tokenisation, items with ``None`` are tokenised in
- # Python and spliced back — see
- # ``TextPreprocessor.try_prepare_from_prepared_tokens``
- # for the hybrid policy. Whole-batch fallback only fires
- # on correctness-critical drift (tokenizer_id mismatch,
- # malformed wire shape).
- prepared_tokens_per_item = [bi.prepared_tokens for bi in good_group]
- if not any(pt is not None for pt in prepared_tokens_per_item):
- # Not a single fast-path candidate — pass None so the
- # pipeline doesn't even bother looking up the
- # preprocessor's cached tokenizer_id.
- prepared_tokens_per_item = None
+ (output_types_t, instruction, is_query, _packed_options, _profile_id, _bundle_hash) = group_key
+ await self._run_encode_group(
+ model_id=model_id,
+ config=config,
+ group=group,
+ output_types=list(output_types_t),
+ instruction=instruction,
+ is_query=is_query,
+ # The group's own options, not a msgpack round-trip of the
+ # grouping key: every item in the group packed to the same
+ # bytes by construction, and re-decoding would turn any tuple
+ # into a list on the way back.
+ request_options=group[0].options or {},
+ outcomes=outcomes,
+ isolation=isolation,
+ )
+
+ return BatchOutcome(outcomes=[outcomes[bi.work_item_id] for bi in items])
+ async def _run_encode_group(
+ self,
+ *,
+ model_id: str,
+ config: Any,
+ group: list[EncodeBatchItem],
+ output_types: list[str],
+ instruction: str | None,
+ is_query: bool,
+ request_options: dict[str, Any],
+ outcomes: dict[str, ItemOutcome],
+ isolation: _IsolationBudget,
+ depth: int = 0,
+ ) -> None:
+ """Run one encode sub-group and record its per-item outcomes.
+
+ Split out of :meth:`process_encode_batch` so an adapter-level
+ ``InvalidInputError`` can be isolated by re-running narrower groups —
+ see :meth:`_isolate_encode_invalid_input`. ``isolation`` is the batch's
+ shared re-run budget and ``depth`` the current bisection depth, both
+ carried only for that path.
+ """
+ # Validate each item against the typed Item contract at the seam
+ # (parity with the HTTP path). A per-item decode failure is isolated
+ # as an INVALID_INPUT outcome so one malformed item cannot fail its
+ # whole sub-group. See decode_item / issue #1537.
+ good_group: list[EncodeBatchItem] = []
+ server_items: list[Item] = []
+ for bi in group:
try:
- # The Rust gateway publishes only the raw SDK options to the
- # queue, so — unlike the single-server HTTP path (api.encode) —
- # profile ``adapter_options.runtime`` defaults (query_template,
- # default_instruction, pooling, normalize, …) are not yet merged
- # in. Merge them here so the adapter sees the same effective
- # options regardless of ingress; without this, instruction-tuned
- # embedders silently lose their query template on the cluster
- # path (#1489). An unknown profile name raises ValueError, which
- # the surrounding except turns into per-item failures.
- request_options = options
- options, selected_profile = merge_runtime_options_with_profile(config, request_options)
- adapter_output_types, output_types = resolve_encode_output_types(
- config,
- output_types,
- selected_profile,
- options,
- )
- formatted_outputs, timing = await EncodePipeline.run_encode(
- registry=self._registry,
- model=model_id,
- items=server_items,
- output_types=adapter_output_types,
- instruction=instruction,
- config=config,
- is_query=is_query,
- options=options,
- prepared_tokens_per_item=prepared_tokens_per_item,
- response_output_types=output_types,
- preformed_batch=True,
- )
+ server_items.append(decode_item(bi.item))
+ except (msgspec.ValidationError, InvalidMediaError) as decode_exc:
+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, decode_exc)
+ continue
+ good_group.append(bi)
+ if not good_group:
+ return
+ # Collect worker-sidecar prepared_tokens aligned with
+ # ``server_items``. ``None`` per item is expected for the
+ # v1 safety-rule skips (`is_query`, `instruction`,
+ # non-text, empty text). The pipeline accepts the mix
+ # per-item: items with usable Rust bytes skip Python
+ # tokenisation, items with ``None`` are tokenised in
+ # Python and spliced back — see
+ # ``TextPreprocessor.try_prepare_from_prepared_tokens``
+ # for the hybrid policy. Whole-batch fallback only fires
+ # on correctness-critical drift (tokenizer_id mismatch,
+ # malformed wire shape).
+ prepared_tokens_per_item = [bi.prepared_tokens for bi in good_group]
+ if not any(pt is not None for pt in prepared_tokens_per_item):
+ # Not a single fast-path candidate — pass None so the
+ # pipeline doesn't even bother looking up the
+ # preprocessor's cached tokenizer_id.
+ prepared_tokens_per_item = None
- if len(formatted_outputs) != len(good_group):
- # Output/input length mismatch means the adapter
- # silently dropped items. Surface as a per-item error
- # rather than publishing empty success results.
- logger.warning(
- "Encode sub-batch for %s returned %d outputs for %d items — emitting per-item errors",
- model_id,
- len(formatted_outputs),
- len(good_group),
+ try:
+ # The Rust gateway publishes only the raw SDK options to the
+ # queue, so — unlike the single-server HTTP path (api.encode) —
+ # profile ``adapter_options.runtime`` defaults (query_template,
+ # default_instruction, pooling, normalize, …) are not yet merged
+ # in. Merge them here so the adapter sees the same effective
+ # options regardless of ingress; without this, instruction-tuned
+ # embedders silently lose their query template on the cluster
+ # path (#1489). An unknown profile name raises ValueError, which
+ # the surrounding except turns into per-item failures.
+ # The PROFILE, not the raw request options, is what
+ # `resolve_encode_output_types` needs: a profile may expose a
+ # postprocessed response type the adapter never emits (MuVERA
+ # returns dense over multivector). Resolving it here keeps the
+ # queue path identical to the HTTP one.
+ options, selected_profile = merge_runtime_options_with_profile(config, request_options)
+ adapter_output_types, response_output_types = resolve_encode_output_types(
+ config,
+ output_types,
+ selected_profile,
+ options,
+ )
+ formatted_outputs, timing = await EncodePipeline.run_encode(
+ registry=self._registry,
+ model=model_id,
+ items=server_items,
+ output_types=adapter_output_types,
+ instruction=instruction,
+ config=config,
+ is_query=is_query,
+ options=options,
+ prepared_tokens_per_item=prepared_tokens_per_item,
+ response_output_types=response_output_types,
+ preformed_batch=True,
+ )
+
+ if len(formatted_outputs) != len(good_group):
+ # Output/input length mismatch means the adapter
+ # silently dropped items. Surface as a per-item error
+ # rather than publishing empty success results.
+ logger.warning(
+ "Encode sub-batch for %s returned %d outputs for %d items — emitting per-item errors",
+ model_id,
+ len(formatted_outputs),
+ len(good_group),
+ )
+ for bi in good_group:
+ outcomes[bi.work_item_id] = _error_outcome(
+ bi,
+ _INFERENCE_ERROR_CODE,
+ "adapter returned fewer outputs than items",
)
- for bi in good_group:
- outcomes[bi.work_item_id] = _error_outcome(
- bi,
- _INFERENCE_ERROR_CODE,
- "adapter returned fewer outputs than items",
+ else:
+ # Authoritative unit counts for metering: per-item real
+ # tokenizer counts recorded by the pipeline during
+ # tokenization (see ``RequestTiming.input_token_counts``).
+ # ``None`` (image path / char-count estimators) leaves
+ # ``ItemOutcome.units`` unset so downstream usage consumers
+ # can reject missing evidence rather than consume estimates.
+ token_counts = timing.input_token_counts
+ if token_counts is not None and len(token_counts) != len(good_group):
+ token_counts = None # misaligned — never mis-attribute counts
+ # Authoritative per-image counts for the §7 "$ per image"
+ # dimension: any vision adapter (CLIP/SigLIP) inherits the
+ # base ``count_input_images`` hook, so an image-input encode
+ # bills per image the same way a text encode bills per
+ # token. ``None`` (adapter evicted, or an all-text batch)
+ # leaves ``images`` unset. Aligned 1:1 with ``server_items``
+ # (== ``good_group`` order).
+ try:
+ encode_adapter = self._registry.get(model_id)
+ except KeyError:
+ encode_adapter = None
+ image_counts = _encode_image_counts(
+ timing,
+ encode_adapter,
+ server_items,
+ len(good_group),
+ )
+ for idx, bi in enumerate(good_group):
+ raw_output: RawOutput | None = None
+ result_msgpack: bytes | None = None
+ # Dispatch by the single declared output type —
+ # the v1 wire contract is exactly one variant
+ # per ``RawOutput``. Multi-output items (no
+ # single key matches) and adapter outputs that
+ # don't pass the per-helper safety rules drop
+ # to the legacy ``_wrap_encode_output`` path
+ # below.
+ if response_output_types == ["dense"]:
+ raw_output = _maybe_dense_raw_output(
+ formatted_outputs[idx],
+ config,
+ response_output_types,
)
- else:
- # Authoritative unit counts for metering: per-item real
- # tokenizer counts recorded by the pipeline during
- # tokenization (see ``RequestTiming.input_token_counts``).
- # ``None`` (image path / char-count estimators) leaves
- # ``ItemOutcome.units`` unset so downstream usage consumers
- # can reject missing evidence rather than consume estimates.
- token_counts = timing.input_token_counts
- if token_counts is not None and len(token_counts) != len(good_group):
- token_counts = None # misaligned — never mis-attribute counts
- # Authoritative per-image counts for the §7 "$ per image"
- # dimension: any vision adapter (CLIP/SigLIP) inherits the
- # base ``count_input_images`` hook, so an image-input encode
- # bills per image the same way a text encode bills per
- # token. ``None`` (adapter evicted, or an all-text batch)
- # leaves ``images`` unset. Aligned 1:1 with ``server_items``
- # (== ``good_group`` order).
- try:
- encode_adapter = self._registry.get(model_id)
- except KeyError:
- encode_adapter = None
- image_counts = _per_item_image_counts(encode_adapter, server_items, len(good_group))
- for idx, bi in enumerate(good_group):
- raw_output: RawOutput | None = None
- result_msgpack: bytes | None = None
- # Dispatch by the single declared output type —
- # the v1 wire contract is exactly one variant
- # per ``RawOutput``. Multi-output items (no
- # single key matches) and adapter outputs that
- # don't pass the per-helper safety rules drop
- # to the legacy ``_wrap_encode_output`` path
- # below.
- if output_types == ["dense"]:
- raw_output = _maybe_dense_raw_output(
- formatted_outputs[idx],
- config,
- output_types,
- )
- elif output_types == ["sparse"]:
- raw_output = _maybe_sparse_raw_output(
- formatted_outputs[idx],
- config,
- output_types,
- )
- elif output_types == ["multivector"]:
- raw_output = _maybe_multivector_raw_output(
- formatted_outputs[idx],
- config,
- output_types,
- )
- if raw_output is None:
- output = _wrap_encode_output(formatted_outputs[idx], config)
- # Echo the caller's item id (G2b, P2.8 finding): the
- # HTTP path stamps ``result["id"] = item.id`` in
- # ``api.encode._build_response_items`` and the SDK
- # copies it back (``parse_encode_results``), but the
- # queue-path result blob dropped it. Bake it into the
- # legacy blob here so it round-trips like SCORE's
- # ``item_id``. The RawOutput fast paths carry the id
- # at framing time instead (frame_raw_output on the
- # lane); this branch is the multi-output / non-f32
- # fallback.
- item_id = server_items[idx].id
- if item_id is not None:
- output = {"id": item_id, **output}
- result_msgpack = msgpack.packb(output, use_bin_type=True)
- outcomes[bi.work_item_id] = ItemOutcome(
- work_item_id=bi.work_item_id,
- request_id=bi.request_id,
- item_index=bi.item_index,
- disposition="publish_and_ack",
- result_msgpack=result_msgpack,
- raw_output=raw_output,
- inference_ms=timing.inference_ms,
- tokenization_ms=timing.tokenization_ms if timing.tokenization_ms > 0 else None,
- postprocessing_ms=timing.postprocessing_ms if timing.postprocessing_ms > 0 else None,
- units=_encode_units(
- token_counts[idx] if token_counts is not None else None,
- image_counts[idx] if image_counts is not None else None,
- ),
+ elif response_output_types == ["sparse"]:
+ raw_output = _maybe_sparse_raw_output(
+ formatted_outputs[idx],
+ config,
+ response_output_types,
)
- except Exception as e: # noqa: BLE001
- logger.warning("Encode sub-batch failed for model %s: %s", model_id, e)
- for bi in good_group:
- outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)
+ elif response_output_types == ["multivector"]:
+ raw_output = _maybe_multivector_raw_output(
+ formatted_outputs[idx],
+ config,
+ response_output_types,
+ )
+ if raw_output is None:
+ output = _wrap_encode_output(formatted_outputs[idx], config)
+ # Echo the caller's item id (G2b, P2.8 finding): the
+ # HTTP path stamps ``result["id"] = item.id`` in
+ # ``api.encode._build_response_items`` and the SDK
+ # copies it back (``parse_encode_results``), but the
+ # queue-path result blob dropped it. Bake it into the
+ # legacy blob here so it round-trips like SCORE's
+ # ``item_id``. The RawOutput fast paths carry the id
+ # at framing time instead (frame_raw_output on the
+ # lane); this branch is the multi-output / non-f32
+ # fallback.
+ item_id = server_items[idx].id
+ if item_id is not None:
+ output = {"id": item_id, **output}
+ result_msgpack = msgpack.packb(output, use_bin_type=True)
+ outcomes[bi.work_item_id] = ItemOutcome(
+ work_item_id=bi.work_item_id,
+ request_id=bi.request_id,
+ item_index=bi.item_index,
+ disposition="publish_and_ack",
+ result_msgpack=result_msgpack,
+ raw_output=raw_output,
+ inference_ms=timing.inference_ms,
+ tokenization_ms=timing.tokenization_ms if timing.tokenization_ms > 0 else None,
+ postprocessing_ms=timing.postprocessing_ms if timing.postprocessing_ms > 0 else None,
+ units=_encode_units(
+ token_counts[idx] if token_counts is not None else None,
+ image_counts[idx] if image_counts is not None else None,
+ ),
+ )
+ except InvalidInputError as e:
+ # One caller's malformed input must not fail its co-batched
+ # siblings. A dynamic sub-group fuses items from DIFFERENT API
+ # requests, and an adapter-level validation error (an undecodable
+ # video, a broken decoder wheel) is raised for the whole
+ # ``run_encode`` call, so attributing it to every item would 400
+ # tenants whose input was fine.
+ await self._isolate_encode_invalid_input(
+ model_id=model_id,
+ config=config,
+ good_group=good_group,
+ output_types=output_types,
+ instruction=instruction,
+ is_query=is_query,
+ request_options=request_options,
+ outcomes=outcomes,
+ error=e,
+ isolation=isolation,
+ depth=depth,
+ )
+ except Exception as e: # noqa: BLE001
+ logger.warning("Encode sub-batch failed for model %s: %s", model_id, e)
+ for bi in good_group:
+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)
- return BatchOutcome(outcomes=[outcomes[bi.work_item_id] for bi in items])
+ async def _isolate_encode_invalid_input(
+ self,
+ *,
+ model_id: str,
+ config: Any,
+ good_group: list[EncodeBatchItem],
+ output_types: list[str],
+ instruction: str | None,
+ is_query: bool,
+ request_options: dict[str, Any],
+ outcomes: dict[str, ItemOutcome],
+ error: InvalidInputError,
+ isolation: _IsolationBudget,
+ depth: int,
+ ) -> None:
+ """Fail only the request that supplied the malformed input.
+
+ Mirrors ``BatchExecutor._isolate_invalid_input`` (core/worker/
+ oom_recovery.py), which gives the worker-batched path exactly this
+ guarantee. The direct-adapter path had no equivalent, so a single
+ undecodable video 400'd every co-batched tenant.
+
+ Split by request identity — a multi-item request stays atomic, matching
+ the worker-batched semantics — and re-run each half. The recursion
+ narrows onto the offending request, which alone takes the typed
+ INVALID_INPUT outcome; a group that is already one request is failed
+ directly, which is the terminal case.
+
+ Cost depends on WHY the input was rejected, and the two cases differ by
+ an order of magnitude:
+
+ * **Input-specific** (one caller's undecodable video) — only the half
+ containing it fails, so the recursion is a true binary search and
+ isolating one bad request out of ``R`` costs ~2*log2(R) passes. This
+ is the case isolation exists for.
+ * **Environmental** (``_load_decoder`` raising because the GPU image's
+ OpenCV wheel is broken) — EVERY video-carrying request fails, so both
+ halves fail at every level and unbounded bisection would degenerate
+ to ~2R passes, all serialized on the single-threaded inference
+ executor. Multiplying occupancy during an image-wide outage is the
+ opposite of useful.
+
+ ``isolation`` bounds that: the batch shares one re-run budget, and once
+ it is spent the remaining requests take the error directly. Under a
+ systemic failure that is also the correct outcome — every one of them
+ was going to fail — while the input-specific case never approaches the
+ budget. Each split logs its depth and the budget left, so the
+ amplification is measurable in production.
+ """
+ request_ids = list(dict.fromkeys(bi.request_id for bi in good_group))
+ if len(request_ids) <= 1:
+ for bi in good_group:
+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, error)
+ return
+
+ logger.warning(
+ "Invalid input in a fused encode sub-group for %s (%d requests, %d items, depth %d, "
+ "%d isolation passes left) — re-running both halves to isolate the offending "
+ "request: %s",
+ model_id,
+ len(request_ids),
+ len(good_group),
+ depth,
+ isolation.remaining,
+ error,
+ )
+ left_ids = set(request_ids[: len(request_ids) // 2])
+ halves = (
+ [bi for bi in good_group if bi.request_id in left_ids],
+ [bi for bi in good_group if bi.request_id not in left_ids],
+ )
+ for half in halves:
+ # One unit per RE-ENCODE PASS, which is the quantity that occupies
+ # the inference executor — not per split, which would licence twice
+ # as many.
+ if not isolation.spend():
+ logger.warning(
+ "Encode isolation budget exhausted for %s at depth %d — failing %d "
+ "request(s) (%d items) directly without re-encoding; the failure is not "
+ "input-specific: %s",
+ model_id,
+ depth,
+ len({bi.request_id for bi in half}),
+ len(half),
+ error,
+ )
+ for bi in half:
+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, error)
+ continue
+ await self._run_encode_group(
+ model_id=model_id,
+ config=config,
+ group=half,
+ output_types=output_types,
+ instruction=instruction,
+ is_query=is_query,
+ request_options=request_options,
+ outcomes=outcomes,
+ isolation=isolation,
+ depth=depth + 1,
+ )
# -- Score -------------------------------------------------------------
@@ -1339,20 +1542,89 @@ def _per_item_image_counts(adapter: Any, items: list[Item], expected_len: int) -
return None
+def _encode_image_counts(
+ timing: RequestTiming,
+ adapter: Any,
+ items: list[Item],
+ expected_len: int,
+) -> list[int | None] | None:
+ """Per-item billable image counts for one encode sub-batch (§7).
+
+ Prefers the count the adapter recorded for the frames/images it ACTUALLY
+ processed (``RequestTiming.input_image_counts``, stamped by the pipeline
+ from ``EncodeOutput.extra``): sampled video frames bill as ``images``, and
+ only the adapter knows how many frames compressed video bytes decoded to.
+ Falls back to the wire-derived ``count_input_images`` hook, which is exact
+ for every adapter whose billable images are its submitted images.
+
+ A video-carrying item is NOT such an item: the hook sees opaque compressed
+ bytes and would score the sampled frames as zero. So when the authoritative
+ stamp is missing, video items are left ``None`` (fail closed — settlement
+ then refuses the item for want of evidence) while every other item keeps
+ its exact wire-derived count.
+
+ A ZERO stamped for a video item is treated the same way, on BOTH branches.
+ Zero frames is not a billable count for a clip that was admitted against a
+ 32-frame budget — it is the absence of evidence, and it reaches
+ ``_encode_units`` as a dropped ``images`` dimension, which is exactly what
+ the reservation planned for. The two branches therefore state ONE rule
+ rather than two: "a video item bills only on a positive authoritative frame
+ count". The managed gateway happens to fault such a result closed anyway
+ (``meter.rs`` rejects a successful result with no authoritative units), but
+ this function must not lean on a guard that lives one process away and does
+ not cover every consumer of these counts.
+ """
+ counts = timing.input_image_counts
+ if counts is not None and len(counts) == expected_len:
+ return [
+ None if (count == 0 and item.video is not None) else count
+ for item, count in zip(items, counts, strict=True)
+ ]
+ wire_counts = _per_item_image_counts(adapter, items, expected_len)
+ if wire_counts is None:
+ return None
+ return [None if item.video is not None else count for item, count in zip(items, wire_counts, strict=True)]
+
+
def _encode_units(token_count: int | None, image_count: int | None) -> UnitCounts | None:
"""Assemble one encode item's ``UnitCounts`` from its authoritative token
and image counts.
- Each dimension is set only when present, and ``images`` only when ``> 0``
- (a text-only item never emits ``images=0``). An item with neither yields
- ``None`` so the metering edge falls back to its reserve estimate. Kept
- byte-identical to the prior ``UnitCounts(input_tokens=...)`` emitter when
- there are no images: ``images`` defaults to ``None`` on the struct.
+ ``images`` is set only when present and positive. ``input_tokens`` is set
+ when positive, and ALSO when it is an authoritative ZERO — a ``0`` on an
+ item that reports a positive image count (#2538).
+
+ That zero is the emitter half of the settlement witness. SigLIP/CLIP let
+ ``has_images`` win over ``has_text``, so an item carrying BOTH takes the
+ image tower and consumes exactly zero text tokens; but the gateway reserved
+ ``input_tokens`` for it off text PRESENCE
+ (``dispatcher::carries_tokenizable_text``). Dropping the zero here leaves
+ the dimension ABSENT from the terminal, and settlement then faults the whole
+ dispatch as reserved-but-missing — a 500 with zero debit after the GPU
+ already ran, which is the defect in #2538.
+
+ The zero is emitted ONLY under the image witness, byte for byte the rule
+ ``meter::zero_is_authoritative`` and the control plane's
+ ``_zero_is_authoritative`` apply on the other side of the boundary. A zero
+ with no images is still dropped, so a tokenizer that counted nothing on a
+ text item keeps failing closed exactly as before.
+
+ Nothing bills less: a zero contributes no credits either way, and the only
+ behaviour that changes is a settlement that used to FAULT (billing nothing)
+ now releasing that dimension and billing the images. An item with neither
+ dimension yields ``None`` so the metering edge falls back to its reserve
+ estimate.
"""
images = image_count if (image_count is not None and image_count > 0) else None
- if token_count is None and images is None:
+ if token_count is not None and token_count > 0:
+ tokens: int | None = token_count
+ elif token_count == 0 and images is not None:
+ tokens = 0
+ else:
+ tokens = None
+ if tokens is None and images is None:
return None
- return UnitCounts(input_tokens=token_count, images=images)
+ return UnitCounts(input_tokens=tokens, images=images)
def _with_images(units: UnitCounts | None, image_count: int | None) -> UnitCounts | None:
diff --git a/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.py b/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.py
index 01fb777c3..1a629ba51 100644
--- a/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.py
+++ b/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.py
@@ -8,11 +8,14 @@ from typing import Any
import pytest
import torch
+from PIL import Image
from sie_server.adapters.qwen3_vl_embedding import (
_DEFAULT_INSTRUCTION,
Qwen3VLEmbeddingAdapter,
_normalize_instruction,
)
+from sie_server.core.video_frames import MAX_SAMPLED_FRAMES, VideoDecodeError
+from sie_server.types.inputs import InvalidInputError
class TestNormalizeInstruction:
@@ -96,6 +99,32 @@ class _FakeProcessor:
return self._inputs
+class _WordTokenizer:
+ """Deterministic HF-shaped tokenizer: one token per word plus two specials.
+
+ The real ``AutoProcessor`` for Qwen3-VL bundles a tokenizer, which
+ ``_metering_tokenizer`` reaches through ``processor.tokenizer``; the fake
+ processor above has none, so the metering tests attach this.
+ """
+
+ model_max_length = 512
+
+ def __call__(
+ self,
+ text: list[str],
+ text_pair: list[str] | None = None,
+ *,
+ truncation: bool = False,
+ max_length: int | None = None,
+ **_: Any,
+ ) -> dict[str, list[list[int]]]:
+ _ = text_pair
+ lengths = [len(t.split()) + 2 for t in text]
+ if truncation and max_length is not None:
+ lengths = [min(n, max_length) for n in lengths]
+ return {"input_ids": [[0] * n for n in lengths]}
+
+
class _RaceDetectingProcessor(_FakeProcessor):
"""Emulate a fast tokenizer that raises on concurrent mutation."""
@@ -235,3 +264,178 @@ class TestInstructionResolution:
def test_non_empty_is_normalized_and_forwarded(self) -> None:
assert self._run("Find relevant passages") == "Find relevant passages."
+
+
+class TestVideoFramesBillAsImages:
+ """Sampled video frames are the model's real visual input, so they bill as
+ §7 ``images`` on a worker-authoritative count (issue #2433).
+
+ The count travels on ``EncodeOutput.extra["input_image_counts"]`` because
+ the wire item carries only compressed bytes — nothing downstream can derive
+ how many frames those bytes decoded to.
+ """
+
+ def _adapter(self) -> Qwen3VLEmbeddingAdapter:
+ adapter = Qwen3VLEmbeddingAdapter("Qwen/Qwen3-VL-Embedding-2B")
+ adapter._device = "cpu"
+ inputs = {"input_ids": torch.tensor([[1]]), "attention_mask": torch.tensor([[1]])}
+ adapter._model = _FakeCausalLM(torch.tensor([[[1.0, 0.0]]])) # ty: ignore[invalid-assignment]
+ adapter._processor = _FakeProcessor(inputs) # ty: ignore[invalid-assignment]
+ return adapter
+
+ @staticmethod
+ def _frames(count: int) -> list[Any]:
+ return [Image.new("RGB", (4, 4)) for _ in range(count)]
+
+ def test_video_only_item_bills_the_frames_it_processed(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter = self._adapter()
+ monkeypatch.setattr(
+ "sie_server.adapters.qwen3_vl_embedding.extract_frames",
+ lambda _video: self._frames(7),
+ )
+ item = SimpleNamespace(text=None, images=None, video={"data": b"mp4-bytes", "format": "mp4"})
+
+ out = adapter.encode([item], ["dense"])
+
+ # Seven frames processed -> seven billable images, not one video blob.
+ assert out.extra["input_image_counts"] == [7]
+
+ def test_frames_reach_the_model_as_image_content_parts(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter = self._adapter()
+ monkeypatch.setattr(
+ "sie_server.adapters.qwen3_vl_embedding.extract_frames",
+ lambda _video: self._frames(3),
+ )
+ item = SimpleNamespace(text="a caption", images=None, video={"data": b"mp4-bytes"})
+
+ adapter.encode([item], ["dense"])
+
+ processor: Any = adapter._processor
+ user_turn = processor.conversations[0][1]["content"]
+ assert sum(1 for part in user_turn if part["type"] == "image") == 3
+
+ def test_mixed_images_and_frames_sum_into_one_count(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter = self._adapter()
+ monkeypatch.setattr(
+ "sie_server.adapters.qwen3_vl_embedding.extract_frames",
+ lambda _video: self._frames(4),
+ )
+ png = b"\x89PNG\r\n\x1a\n"
+ monkeypatch.setattr(
+ Qwen3VLEmbeddingAdapter,
+ "_load_images",
+ lambda _self, _item: self._frames(2),
+ )
+ item = SimpleNamespace(text=None, images=[{"data": png}, {"data": png}], video={"data": b"mp4"})
+
+ out = adapter.encode([item], ["dense"])
+
+ assert out.extra["input_image_counts"] == [6]
+
+ def test_text_only_item_bills_no_images(self) -> None:
+ adapter = self._adapter()
+ item = SimpleNamespace(text="hi", images=None, video=None)
+ assert adapter.encode([item], ["dense"]).extra["input_image_counts"] == [0]
+
+ def test_per_item_counts_align_with_the_batch(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter = self._adapter()
+ monkeypatch.setattr(
+ "sie_server.adapters.qwen3_vl_embedding.extract_frames",
+ lambda _video: self._frames(5),
+ )
+ items = [
+ SimpleNamespace(text="text only", images=None, video=None),
+ SimpleNamespace(text=None, images=None, video={"data": b"mp4"}),
+ ]
+ assert adapter.encode(items, ["dense"]).extra["input_image_counts"] == [0, 5]
+
+ def test_undecodable_video_faults_instead_of_being_dropped(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Regression: a text+video item used to embed the text alone and return
+ # a billed success that silently ignored the video.
+ adapter = self._adapter()
+
+ def boom(_video: Any) -> list[Any]:
+ raise VideoDecodeError("video input could not be opened by the decoder")
+
+ monkeypatch.setattr("sie_server.adapters.qwen3_vl_embedding.extract_frames", boom)
+ item = SimpleNamespace(text="a caption", images=None, video={"data": b"garbage"})
+
+ with pytest.raises(VideoDecodeError):
+ 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.
+ adapter = self._adapter()
+ monkeypatch.setattr(
+ Qwen3VLEmbeddingAdapter,
+ "_load_images",
+ lambda _self, _item: self._frames(1), # two of the three failed to load
+ )
+ png = b"\x89PNG\r\n\x1a\n"
+ item = SimpleNamespace(text=None, images=[{"data": png}] * 3, video=None)
+
+ out = adapter.encode([item], ["dense"])
+
+ assert out.extra["input_image_counts"] == [1]
+
+ def test_the_processed_count_never_exceeds_the_reserved_basis(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # The gateway reserves `submitted_images + videos * 32`. A count built
+ # from loaded images plus sampled frames is bounded by that basis, so it
+ # can never push settlement over its ceiling.
+ adapter = self._adapter()
+ monkeypatch.setattr(
+ "sie_server.adapters.qwen3_vl_embedding.extract_frames",
+ lambda _video: self._frames(MAX_SAMPLED_FRAMES),
+ )
+ monkeypatch.setattr(
+ Qwen3VLEmbeddingAdapter,
+ "_load_images",
+ lambda _self, _item: self._frames(1),
+ )
+ png = b"\x89PNG\r\n\x1a\n"
+ item = SimpleNamespace(text=None, images=[{"data": png}] * 2, video={"data": b"mp4"})
+
+ processed = adapter.encode([item], ["dense"]).extra["input_image_counts"][0]
+
+ reserved = len(item.images) + 1 * MAX_SAMPLED_FRAMES
+ assert processed <= reserved
+ assert processed == 1 + MAX_SAMPLED_FRAMES
+
+ def test_token_counts_scatter_across_a_mixed_batch(self) -> None:
+ # The base hook is all-or-nothing: one non-text item and the WHOLE
+ # batch loses its token counts, which left the text item with no units
+ # at all and faulted the dispatch at the gateway. Video items are
+ # non-text by construction and the queue seam fuses requests, so this
+ # adapter scatters instead — real counts for text, 0 for visual-only.
+ adapter = self._adapter()
+ adapter._processor.tokenizer = _WordTokenizer() # ty: ignore[unresolved-attribute]
+ items = [
+ SimpleNamespace(text="alpha beta", images=None, video=None),
+ SimpleNamespace(text=None, images=None, video={"data": b"mp4"}),
+ SimpleNamespace(text="one two three", images=None, video=None),
+ ]
+
+ counts = adapter.count_input_tokens(items)
+
+ assert counts is not None
+ assert len(counts) == len(items)
+ assert counts[1] == 0 # visual-only item contributes no text tokens
+ assert counts[0] > 0
+ assert counts[2] > counts[0] # more words -> more tokens
+
+ def test_a_video_only_batch_reports_no_text_tokens(self) -> None:
+ # Nothing tokenizable: every count is zero, which ``_encode_units``
+ # drops, so the request settles on ``images`` alone — matching a plan
+ # that never reserved ``input_tokens`` for it.
+ adapter = self._adapter()
+ adapter._processor.tokenizer = _WordTokenizer() # ty: ignore[unresolved-attribute]
+ items = [SimpleNamespace(text=None, images=None, video={"data": b"mp4"})]
+ assert adapter.count_input_tokens(items) == [0]
+
+ def test_decode_failure_is_typed_invalid_input(self) -> None:
+ # 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)
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index 4d75eee3c..cc8d24073 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -667,6 +667,107 @@ def test_generate_forwards_top_k_and_repetition_penalty(mock_async_client: Magic
assert body["sampling_params"]["repetition_penalty"] == pytest.approx(1.1)
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_generate_caps_profile_default_min_new_tokens_to_request_max(mock_async_client: MagicMock) -> None:
+ sse_lines = [
+ 'data: {"text": "x", "meta_info": {"prompt_tokens": 1, "completion_tokens": 1, "finish_reason": {"type": "length"}}}',
+ ]
+ client_instance = _make_client_with_stream(_FakeStreamingResponse(sse_lines))
+ mock_async_client.return_value = client_instance
+ adapter = SGLangGenerationAdapter(
+ model_name_or_path="Qwen/Qwen3.6-27B",
+ served_model_name="Qwen/Qwen3.6-27B",
+ default_sampling={"min_new_tokens": 10},
+ )
+ adapter._server_url = "http://localhost:30005"
+
+ asyncio.run(collect_generation(adapter.generate(prompt="Hi", max_new_tokens=1)))
+
+ sampling_params = client_instance.stream.call_args.kwargs["json"]["sampling_params"]
+ assert sampling_params["max_new_tokens"] == 1
+ assert sampling_params["min_new_tokens"] == 1
+
+
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_generate_preserves_profile_default_min_new_tokens_below_request_max(mock_async_client: MagicMock) -> None:
+ sse_lines = [
+ 'data: {"text": "ok", "meta_info": {"prompt_tokens": 1, "completion_tokens": 2, "finish_reason": {"type": "stop"}}}',
+ ]
+ client_instance = _make_client_with_stream(_FakeStreamingResponse(sse_lines))
+ mock_async_client.return_value = client_instance
+ adapter = SGLangGenerationAdapter(
+ model_name_or_path="Qwen/Qwen3.6-27B",
+ served_model_name="Qwen/Qwen3.6-27B",
+ default_sampling={"min_new_tokens": 10},
+ )
+ adapter._server_url = "http://localhost:30005"
+
+ asyncio.run(collect_generation(adapter.generate(prompt="Hi", max_new_tokens=64)))
+
+ sampling_params = client_instance.stream.call_args.kwargs["json"]["sampling_params"]
+ assert sampling_params["max_new_tokens"] == 64
+ assert sampling_params["min_new_tokens"] == 10
+
+
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_generate_rejects_explicit_min_new_tokens_above_max_before_sglang(
+ mock_async_client: MagicMock,
+) -> None:
+ adapter = SGLangGenerationAdapter(
+ model_name_or_path="Qwen/Qwen3.6-27B",
+ served_model_name="Qwen/Qwen3.6-27B",
+ default_sampling={"min_new_tokens": 10},
+ )
+ adapter._server_url = "http://localhost:30005"
+
+ with pytest.raises(
+ ValueError,
+ match=r"min_new_tokens \(10\) must not exceed max_new_tokens \(1\)",
+ ):
+ asyncio.run(
+ collect_generation(
+ adapter.generate(
+ prompt="Hi",
+ max_new_tokens=1,
+ min_new_tokens=10,
+ )
+ )
+ )
+
+ mock_async_client.assert_not_called()
+
+
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_generate_explicit_min_new_tokens_overrides_profile_default_when_valid(
+ mock_async_client: MagicMock,
+) -> None:
+ sse_lines = [
+ 'data: {"text": "ok", "meta_info": {"prompt_tokens": 1, "completion_tokens": 2, "finish_reason": {"type": "stop"}}}',
+ ]
+ client_instance = _make_client_with_stream(_FakeStreamingResponse(sse_lines))
+ mock_async_client.return_value = client_instance
+ adapter = SGLangGenerationAdapter(
+ model_name_or_path="Qwen/Qwen3.6-27B",
+ served_model_name="Qwen/Qwen3.6-27B",
+ default_sampling={"min_new_tokens": 10},
+ )
+ adapter._server_url = "http://localhost:30005"
+
+ asyncio.run(
+ collect_generation(
+ adapter.generate(
+ prompt="Hi",
+ max_new_tokens=8,
+ min_new_tokens=2,
+ )
+ )
+ )
+
+ sampling_params = client_instance.stream.call_args.kwargs["json"]["sampling_params"]
+ assert sampling_params["max_new_tokens"] == 8
+ assert sampling_params["min_new_tokens"] == 2
+
+
@pytest.mark.parametrize("seed", [-1, 0, 1])
@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
def test_generate_maps_seed_to_sglang_sampling_seed(mock_async_client: MagicMock, adapter, seed: int) -> None:
diff --git a/packages/sie_server/tests/adapters/test_siglip.py b/packages/sie_server/tests/adapters/test_siglip.py
index e81acfd09..07854b751 100644
--- a/packages/sie_server/tests/adapters/test_siglip.py
+++ b/packages/sie_server/tests/adapters/test_siglip.py
@@ -422,13 +422,15 @@ class TestSiglipAdapter:
}
]
- def test_encode_text_counts_from_primary_attention_mask_when_pad_equals_eos(self) -> None:
- adapter = SiglipAdapter("google/siglip2-base-patch16-224", normalize=False)
+ @pytest.mark.parametrize(
+ "model_id",
+ ["google/siglip-so400m-patch14-384", "google/siglip2-base-patch16-224"],
+ )
+ def test_encode_text_bills_fixed_padded_length(self, model_id: str) -> None:
+ adapter = SiglipAdapter(model_id, normalize=False)
model = MagicMock()
model.get_text_features.return_value = torch.zeros((2, 8))
tokenizer = MagicMock()
- tokenizer.pad_token_id = 1
- tokenizer.eos_token_id = 1
tokenizer.side_effect = AssertionError("padding-free recount must not run")
processor = MagicMock()
processor.tokenizer = tokenizer
@@ -452,25 +454,15 @@ class TestSiglipAdapter:
_embeddings, counts = adapter._encode_texts(["first", "second"])
- assert counts == [3, 2]
+ assert counts == [64, 64]
tokenizer.assert_not_called()
- @pytest.mark.parametrize(
- "attention_mask",
- [
- torch.tensor([[1, 1, 1], [1, 1, 0]]),
- torch.tensor([[1, 1, 2, 0], [1, 1, 0, 0]]),
- ],
- ids=["wrong-shape", "non-binary"],
- )
- def test_encode_text_recounts_when_primary_attention_mask_is_malformed(self, attention_mask: torch.Tensor) -> None:
- adapter = SiglipAdapter("google/siglip2-base-patch16-224", normalize=False)
+ def test_encode_text_bills_configured_padded_length(self) -> None:
+ adapter = SiglipAdapter("google/siglip2-base-patch16-224", normalize=False, max_seq_length=32)
model = MagicMock()
model.get_text_features.return_value = torch.zeros((2, 8))
tokenizer = MagicMock()
- tokenizer.pad_token_id = 1
- tokenizer.eos_token_id = 1
- tokenizer.return_value = {"input_ids": [[12, 13, 1], [42, 1]]}
+ tokenizer.side_effect = AssertionError("padding-free recount must not run")
processor = MagicMock()
processor.tokenizer = tokenizer
processor.return_value = {
@@ -480,7 +472,7 @@ class TestSiglipAdapter:
[42, 1, 1, 1],
]
),
- "attention_mask": attention_mask,
+ "attention_mask": torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0]]),
}
adapter._model = model
adapter._processor = processor
@@ -488,12 +480,8 @@ class TestSiglipAdapter:
_embeddings, counts = adapter._encode_texts(["first", "second"])
- assert counts == [3, 2]
- tokenizer.assert_called_once_with(
- ["first", "second"],
- truncation=True,
- max_length=64,
- )
+ assert counts == [32, 32]
+ tokenizer.assert_not_called()
def test_transformers_backend_reuses_positionally_aligned_prepared_images(self) -> None:
adapter = SiglipAdapter("google/siglip2-base-patch16-224", normalize=False)
@@ -587,6 +575,7 @@ class TestSiglipAdapter:
# Batching proof: exactly one stacked forward per tower for the whole call.
assert model.image_forward_calls == 1
assert model.text_forward_calls == 1
+ assert out.extra["input_token_counts"] == [0, 0, 64, 0, 64]
# Serial reference — replicate the pre-batch per-item algorithm exactly.
def ref_image(item: Item) -> np.ndarray:
diff --git a/packages/sie_server/tests/api/test_generate.py b/packages/sie_server/tests/api/test_generate.py
index df6380ba2..b3e1155ed 100644
--- a/packages/sie_server/tests/api/test_generate.py
+++ b/packages/sie_server/tests/api/test_generate.py
@@ -498,6 +498,50 @@ class TestGenerateEndpoint:
assert fake_adapter.last_call["top_k"] == 40
assert fake_adapter.last_call["min_new_tokens"] == 2
+ def test_profile_default_min_new_tokens_caps_to_explicit_max_before_adapter(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ ) -> None:
+ config = _make_config()
+ config.profiles["default"].adapter_options = AdapterOptions(
+ runtime={"default_sampling": {"min_new_tokens": 10}}
+ )
+ registry.get_config.return_value = config
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3-4B-Instruct",
+ json={"prompt": "Hello", "max_new_tokens": 1},
+ )
+
+ assert response.status_code == 200
+ assert fake_adapter.last_call is not None
+ assert fake_adapter.last_call["max_new_tokens"] == 1
+ assert fake_adapter.last_call["min_new_tokens"] == 1
+
+ def test_explicit_min_new_tokens_above_max_rejects_before_load(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ ) -> None:
+ registry.is_loaded.return_value = False
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3-4B-Instruct",
+ json={
+ "prompt": "Hello",
+ "max_new_tokens": 1,
+ "options": {"default_sampling": {"min_new_tokens": 10}},
+ },
+ )
+
+ assert response.status_code == 400
+ assert "min_new_tokens' (10) must not exceed max_new_tokens (1)" in response.json()["detail"]["message"]
+ registry.load_async.assert_not_awaited()
+ assert fake_adapter.last_call is None
+
def test_non_default_options_profile_rejects_before_load(self, client: TestClient, registry: MagicMock) -> None:
response = client.post(
"/v1/generate/Qwen__Qwen3-4B-Instruct",
diff --git a/packages/sie_server/tests/core/test_runtime_options.py b/packages/sie_server/tests/core/test_runtime_options.py
index 570a62c78..c217fbbc6 100644
--- a/packages/sie_server/tests/core/test_runtime_options.py
+++ b/packages/sie_server/tests/core/test_runtime_options.py
@@ -214,6 +214,47 @@ def test_generation_request_runtime_overrides_profile_defaults() -> None:
assert resolved["top_p"] == 0.8
+def test_generation_profile_default_min_new_tokens_caps_to_explicit_max() -> None:
+ config = _generation_config()
+ config.profiles["default"].adapter_options.runtime["default_sampling"]["min_new_tokens"] = 10
+
+ resolved = apply_generation_runtime_options(
+ config,
+ None,
+ {"prompt": "hi", "max_new_tokens": 1},
+ )
+
+ assert resolved["max_new_tokens"] == 1
+ assert resolved["min_tokens"] == 1
+
+
+def test_generation_request_sampling_min_new_tokens_above_max_fails() -> None:
+ with pytest.raises(
+ ValueError,
+ match=r"options\.default_sampling\.min_new_tokens.*must not exceed max_new_tokens",
+ ):
+ apply_generation_runtime_options(
+ _generation_config(),
+ {"default_sampling": {"min_new_tokens": 10}},
+ {"prompt": "hi", "max_new_tokens": 1},
+ )
+
+
+def test_generation_explicit_min_tokens_above_max_fails() -> None:
+ config = _generation_config()
+ del config.profiles["default"].adapter_options.runtime["default_sampling"]
+
+ with pytest.raises(
+ ValueError,
+ match=r"min_tokens \(10\) must not exceed max_new_tokens \(1\)",
+ ):
+ apply_generation_runtime_options(
+ config,
+ None,
+ {"prompt": "hi", "max_new_tokens": 1, "min_tokens": 10},
+ )
+
+
def test_generation_non_default_profile_requires_model_variant_identity() -> None:
with pytest.raises(ValueError, match="model:profile"):
apply_generation_runtime_options(
diff --git a/packages/sie_server/tests/core/test_video_frames.py b/packages/sie_server/tests/core/test_video_frames.py
new file mode 100644
index 000000000..684b8c5db
--- /dev/null
+++ b/packages/sie_server/tests/core/test_video_frames.py
@@ -0,0 +1,394 @@
+"""Video frame extraction seam: the basis on which video bills as images (§7).
+
+Every test video is GENERATED here with the same OpenCV that decodes it — no
+binary fixture is downloaded or committed. The default fixture uses the
+lossless FFV1 codec and fills frame N with grey level ``N * 8``, so a sampled
+frame's pixel value identifies its source index exactly and the sampling stride
+is directly assertable. Lossy containers (mp4/webm) get their own count-only
+tests, since they are the formats the removed placeholder silently dropped.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import pytest
+from sie_server.core import video_frames
+from sie_server.core.video_frames import (
+ MAX_SAMPLED_FRAMES,
+ VideoDecodeError,
+ extract_frames,
+)
+from sie_server.types.inputs import InvalidInputError, InvalidMediaError
+
+cv2 = pytest.importorskip("cv2", reason="video decoding requires the OpenCV wheel")
+
+_GREY_STEP = 8
+
+
+def _make_video(
+ tmp_path: Path,
+ *,
+ frames: int,
+ fps: float = 10.0,
+ codec: str = "FFV1",
+ suffix: str = ".avi",
+) -> bytes:
+ """Encode a tiny video whose frame N is uniformly filled with grey ``N * 8``.
+
+ The grey level wraps past 31 frames; ``_source_indices`` is therefore only
+ meaningful for the short fixtures, and the long ones assert counts.
+
+ Encoder availability varies by ``opencv-python-headless`` wheel and base
+ image, so a codec this wheel cannot write skips rather than fails — same
+ contract as the module-level ``importorskip("cv2")``. The billing
+ invariants that must never silently lapse (the budget-fill arithmetic and
+ the decode-work bounds) are asserted against fake captures instead and do
+ not depend on any encoder being present.
+ """
+ path = tmp_path / f"generated-{codec}{suffix}"
+ writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*codec), fps, (32, 24))
+ if not writer.isOpened():
+ writer.release()
+ pytest.skip(f"this OpenCV wheel cannot encode {codec}{suffix}")
+ for index in range(frames):
+ writer.write(np.full((24, 32, 3), (index * _GREY_STEP) % 256, dtype=np.uint8))
+ writer.release()
+ return path.read_bytes()
+
+
+def _video(data: bytes, fmt: str | None = "avi") -> dict[str, Any]:
+ return {"data": data, "format": fmt}
+
+
+def _source_indices(frames: list[Any]) -> list[int]:
+ """Recover each sampled frame's index in the source stream."""
+ return [int(np.asarray(frame)[0, 0, 0]) // _GREY_STEP for frame in frames]
+
+
+class TestExtractFrames:
+ def test_decodes_real_mp4_into_frames(self, tmp_path: Path) -> None:
+ # The placeholder this replaces returned [] for every real container.
+ data = _make_video(tmp_path, frames=8, codec="mp4v", suffix=".mp4")
+ frames = extract_frames(_video(data, "mp4"))
+ assert len(frames) == 8
+ assert frames[0].mode == "RGB"
+ assert frames[0].size == (32, 24)
+
+ def test_decodes_real_webm_into_frames(self, tmp_path: Path) -> None:
+ data = _make_video(tmp_path, frames=6, codec="VP80", suffix=".webm")
+ assert len(extract_frames(_video(data, "webm"))) == 6
+
+ def test_samples_uniformly_under_the_budget(self, tmp_path: Path) -> None:
+ # 20 source frames, budget 4 -> evenly spaced indices 0,5,10,15.
+ frames = extract_frames(_video(_make_video(tmp_path, frames=20)), max_frames=4)
+ assert _source_indices(frames) == [0, 5, 10, 15]
+
+ def test_never_exceeds_the_billing_budget(self, tmp_path: Path) -> None:
+ # The managed reservation ceiling is derived from MAX_SAMPLED_FRAMES, so
+ # a longer video must still settle at or below it.
+ frames = extract_frames(_video(_make_video(tmp_path, frames=MAX_SAMPLED_FRAMES * 3)))
+ assert len(frames) <= MAX_SAMPLED_FRAMES
+
+ def test_a_caller_budget_cannot_raise_the_billing_cap(self, tmp_path: Path) -> None:
+ frames = extract_frames(
+ _video(_make_video(tmp_path, frames=MAX_SAMPLED_FRAMES * 2)),
+ max_frames=MAX_SAMPLED_FRAMES * 2,
+ )
+ assert len(frames) <= MAX_SAMPLED_FRAMES
+
+ def test_short_video_yields_every_frame_once(self, tmp_path: Path) -> None:
+ frames = extract_frames(_video(_make_video(tmp_path, frames=3)))
+ assert _source_indices(frames) == [0, 1, 2]
+
+ def test_sampling_is_deterministic(self, tmp_path: Path) -> None:
+ # Same bytes -> same frames -> same bill, on every retry and replica.
+ data = _make_video(tmp_path, frames=17)
+ assert _source_indices(extract_frames(_video(data), max_frames=5)) == _source_indices(
+ extract_frames(_video(data), max_frames=5)
+ )
+
+ def test_unknown_format_hint_still_decodes(self, tmp_path: Path) -> None:
+ # The hint is advisory; the demuxer sniffs the container.
+ assert extract_frames(_video(_make_video(tmp_path, frames=4), "quicktimeish"))
+
+ def test_missing_format_hint_still_decodes(self, tmp_path: Path) -> None:
+ assert extract_frames({"data": _make_video(tmp_path, frames=4)})
+
+ def test_counts_frames_itself_when_metadata_is_unusable(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ # Containers that report no fps/frame count fall back to a grab-only
+ # counting pass; sampling must stay uniform over the real length.
+ monkeypatch.setattr(video_frames, "_validated_frame_total", lambda *_: None)
+ frames = extract_frames(_video(_make_video(tmp_path, frames=20)), max_frames=4)
+ assert _source_indices(frames) == [0, 5, 10, 15]
+
+
+class TestBudgetIsFilled:
+ """A stream at or above the budget must yield exactly the budget.
+
+ The uniform stride this replaces (``ceil(total / budget)``, retained where
+ ``index % stride == 0``) under-filled it for nearly every length: 33 source
+ frames at budget 32 yielded 17, 48 yielded 24, 100 yielded 25. That halves
+ both the visual context the model sees and the customer's bill, at a
+ boundary invisible to them — a 32-frame clip billed 32, a 33-frame clip 17.
+ """
+
+ @pytest.mark.parametrize("total", [33, 48, 63, 100])
+ def test_every_stream_length_fills_the_budget(self, tmp_path: Path, total: int) -> None:
+ frames = extract_frames(_video(_make_video(tmp_path, frames=total)))
+ assert len(frames) == MAX_SAMPLED_FRAMES
+
+ @pytest.mark.parametrize("total", [32, 33, 48, 63, 100, 1_000, 108_000])
+ def test_indices_are_distinct_ordered_and_in_range(self, total: int) -> None:
+ indices = video_frames._target_indices(total, MAX_SAMPLED_FRAMES)
+ assert len(indices) == MAX_SAMPLED_FRAMES
+ assert indices == sorted(set(indices)) # distinct and in stream order
+ assert indices[0] == 0
+ assert indices[-1] < total
+
+ @pytest.mark.parametrize("total", [1, 5, 31])
+ def test_a_stream_under_the_budget_yields_every_frame(self, total: int) -> None:
+ assert video_frames._target_indices(total, MAX_SAMPLED_FRAMES) == list(range(total))
+
+
+class _CountingCapture:
+ """Seekable capture that records exactly how much decode work was demanded.
+
+ Frame N is filled with grey ``N * 8`` like the generated fixtures, so
+ ``_source_indices`` recovers which frames a sampling strategy actually took.
+ """
+
+ def __init__(self, total: int, *, seekable: bool = True) -> None:
+ self.total = total
+ self.seekable = seekable
+ self.reads = 0
+ self.grabs = 0
+ self._index = 0
+
+ def set(self, _prop: int, value: float) -> bool:
+ if not self.seekable:
+ return False
+ self._index = int(value)
+ return True
+
+ def get(self, _prop: int) -> float:
+ return float(self._index)
+
+ def grab(self) -> bool:
+ if self._index >= self.total:
+ return False
+ self._index += 1
+ self.grabs += 1
+ return True
+
+ def read(self) -> tuple[bool, Any]:
+ if self._index >= self.total:
+ return False, None
+ frame = np.full((2, 2, 3), (self._index * _GREY_STEP) % 256, dtype=np.uint8)
+ self._index += 1
+ self.reads += 1
+ return True, frame
+
+
+class _LyingCapture(_CountingCapture):
+ """Backend whose ``set`` claims success but never moves the capture."""
+
+ def set(self, _prop: int, value: float) -> bool:
+ _ = value
+ return True
+
+
+class _KeyframeSnappingCapture(_CountingCapture):
+ """Backend that snaps a seek back to the preceding keyframe, and reports it.
+
+ OpenCV's FFmpeg backend documents exactly this for RAW mode (a request for
+ frame ``i`` seeks to keyframe ``k <= i``), and wheels differ in whether the
+ reported position is the request or the landing.
+ """
+
+ GOP = 8
+
+ def set(self, _prop: int, value: float) -> bool:
+ self._index = (int(value) // self.GOP) * self.GOP
+ return True
+
+
+class _OvershootingCapture(_CountingCapture):
+ """Backend that lands PAST the requested frame."""
+
+ def set(self, _prop: int, value: float) -> bool:
+ self._index = min(self.total, int(value) + 5)
+ return True
+
+
+class _FakeCv2:
+ CAP_PROP_POS_FRAMES = 1
+
+
+class TestDecodeWorkIsBoundedByTheBudget:
+ """Sampling cost must be the frame budget, not the stream length.
+
+ ``extract_frames`` is called from inside ``adapter.encode``, which on the
+ batched worker path runs on ``ModelWorker._inference_executor`` — a
+ single-worker pool that serializes the model's GPU work. Walking a long
+ stream there stalls every co-scheduled request in the container, including
+ other tenants', until they time out at the gateway.
+ """
+
+ def test_seeking_decodes_only_the_sampled_frames(self) -> None:
+ # 30 minutes at 30 fps: the walk this replaces issued ~54,000 grab/read
+ # calls on the inference thread for a single item.
+ capture = _CountingCapture(54_000)
+ frames = video_frames._sample(_FakeCv2, capture, total=54_000, budget=MAX_SAMPLED_FRAMES)
+ assert len(frames) == MAX_SAMPLED_FRAMES
+ assert capture.reads == MAX_SAMPLED_FRAMES
+ assert capture.grabs == 0 # not one frame of the stream was walked
+
+ def test_a_backend_that_cannot_seek_still_samples_correctly(self) -> None:
+ capture = _CountingCapture(40, seekable=False)
+ frames = video_frames._sample(_FakeCv2, capture, total=40, budget=4)
+ assert _source_indices(frames) == [0, 10, 20, 30]
+ assert capture.grabs == 27 # three gaps of nine skipped frames
+
+ def test_a_seek_that_lies_degrades_to_the_walk_instead_of_wrong_frames(self) -> None:
+ # Trusting a backend that reports success without moving would sample
+ # the wrong frames (a stuck position repeats frame 0 N times) — a
+ # correctness failure, not merely a slow one. The cursor is resynced
+ # from the reported position, so the walk still lands on target.
+ capture = _LyingCapture(40)
+ frames = video_frames._sample(_FakeCv2, capture, total=40, budget=4)
+ assert _source_indices(frames) == [0, 10, 20, 30]
+ assert capture.grabs == 27
+
+ def test_a_keyframe_snapped_seek_resyncs_the_cursor(self) -> None:
+ # A backend that lands on the preceding keyframe leaves the capture
+ # somewhere the caller did not ask for. Walking on from a stale logical
+ # index would overshoot and decode the WRONG frame (here: 17 instead of
+ # 10), so the cursor is seeded from where the capture actually landed
+ # and the short remainder is walked.
+ capture = _KeyframeSnappingCapture(40)
+ frames = video_frames._sample(_FakeCv2, capture, total=40, budget=4)
+ assert _source_indices(frames) == [0, 10, 20, 30]
+ # Only the sub-GOP remainders are walked: 8->10, 16->20, 24->30.
+ assert capture.grabs == 12
+
+ def test_an_overshooting_seek_stops_rather_than_sampling_wrong_frames(self) -> None:
+ # Landing past the target cannot be corrected by walking forward, and
+ # reading there would bill a frame the sampler never selected. Stop and
+ # bill only what was decoded.
+ capture = _OvershootingCapture(40)
+ frames = video_frames._sample(_FakeCv2, capture, total=40, budget=4)
+ assert _source_indices(frames) == [0]
+
+ def test_the_no_seek_walk_is_hard_capped(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # A broken-seek backend must not turn one item into an unbounded walk;
+ # past the cap the item is refused with a typed 400 instead.
+ monkeypatch.setattr(video_frames, "_MAX_SAMPLE_GRABS", 8)
+ capture = _CountingCapture(400, seekable=False)
+ with pytest.raises(VideoDecodeError, match="cannot seek"):
+ video_frames._sample(_FakeCv2, capture, total=400, budget=4)
+ assert capture.grabs <= 9
+
+ def test_an_over_reported_length_bills_only_the_frames_decoded(self) -> None:
+ # Containers can over-report CAP_PROP_FRAME_COUNT. Sampling then runs
+ # off the end; the frames actually decoded are the ones the model gets
+ # and therefore the only ones that may be billed.
+ capture = _CountingCapture(12)
+ frames = video_frames._sample(_FakeCv2, capture, total=40, budget=4)
+ assert len(frames) == len(_source_indices(frames)) <= 4
+ assert _source_indices(frames) == [0, 10]
+
+
+class TestFailsClosed:
+ """A video that cannot be decoded must fault, never silently bill zero."""
+
+ def test_undecodable_bytes_raise_typed_invalid_input(self) -> None:
+ with pytest.raises(VideoDecodeError):
+ extract_frames(_video(b"not-a-video-at-all"))
+
+ def test_decode_error_is_an_invalid_input_error(self) -> None:
+ # Both ingress paths map InvalidInputError to INVALID_INPUT / HTTP 400.
+ assert issubclass(VideoDecodeError, InvalidInputError)
+
+ def test_empty_payload_raises(self) -> None:
+ with pytest.raises(VideoDecodeError, match="no data"):
+ extract_frames(_video(b""))
+
+ def test_non_bytes_payload_raises_the_media_contract_error(self) -> None:
+ with pytest.raises(InvalidMediaError):
+ extract_frames({"data": "base64-string-that-was-never-decoded"})
+
+ def test_non_positive_budget_raises(self, tmp_path: Path) -> None:
+ with pytest.raises(VideoDecodeError, match="positive"):
+ extract_frames(_video(_make_video(tmp_path, frames=2)), max_frames=0)
+
+ def test_missing_decoder_raises_instead_of_returning_no_frames(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # A GPU image with a broken OpenCV wheel must reject the request, never
+ # return a billed success that processed zero frames. ``None`` in
+ # sys.modules is exactly what a failed import leaves behind.
+ monkeypatch.setitem(sys.modules, "cv2", None)
+ with pytest.raises(VideoDecodeError, match="no video decoder"):
+ extract_frames(_video(b"x" * 128))
+
+
+class TestAdmissionCaps:
+ def test_over_cap_bytes_are_rejected_before_decoding(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(video_frames, "MAX_VIDEO_BYTES", 8)
+ with pytest.raises(VideoDecodeError, match="admission cap"):
+ extract_frames(_video(b"x" * 9))
+
+ def test_over_cap_duration_is_rejected(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ # 30 frames at 10 fps = 3.0 s, over a 1 s cap.
+ monkeypatch.setattr(video_frames, "MAX_VIDEO_DURATION_S", 1.0)
+ with pytest.raises(VideoDecodeError, match="admission cap"):
+ extract_frames(_video(_make_video(tmp_path, frames=30, fps=10.0)))
+
+ def test_in_cap_duration_is_accepted(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(video_frames, "MAX_VIDEO_DURATION_S", 10.0)
+ assert extract_frames(_video(_make_video(tmp_path, frames=30, fps=10.0)))
+
+ def test_a_stream_exactly_at_the_scan_cap_is_accepted(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ # The cap is INCLUSIVE: a stream of exactly `_MAX_SCANNED_FRAMES` is
+ # within it. Reaching the cap is not the same as exceeding it, and
+ # "tightening" the guard to `total >= cap` would reject admissible
+ # input — you cannot know a stream is over the cap without grabbing
+ # the frame past it.
+ monkeypatch.setattr(video_frames, "_validated_frame_total", lambda *_: None)
+ monkeypatch.setattr(video_frames, "_MAX_SCANNED_FRAMES", 6)
+ frames = extract_frames(_video(_make_video(tmp_path, frames=6)), max_frames=3)
+ assert _source_indices(frames) == [0, 2, 4]
+
+ def test_scan_cap_bounds_metadata_less_containers(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Without fps metadata the duration cap degrades to a frame-scan cap;
+ # both bound the same abuse (unbounded decode work for one item).
+ monkeypatch.setattr(video_frames, "_validated_frame_total", lambda *_: None)
+ 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_FRAMES
diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.py
index c79169a20..c01bcf142 100644
--- a/packages/sie_server/tests/processors/test_streaming.py
+++ b/packages/sie_server/tests/processors/test_streaming.py
@@ -29,9 +29,10 @@ from sie_server.adapters._generation_base import (
)
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters.base import ModelCapabilities, ModelDims
+from sie_server.config.model import ModelConfig
from sie_server.observability import worker_telemetry as worker_metrics
from sie_server.processors import streaming as streaming_mod
-from sie_server.processors.streaming import StreamingProcessor
+from sie_server.processors.streaming import StreamingProcessor, _ValidationError
class _FakeGenAdapter(GenerationAdapter):
@@ -109,6 +110,30 @@ def _make_work_item(
return wi
+def _make_generation_config(*, min_new_tokens: int = 10) -> ModelConfig:
+ return ModelConfig.model_validate(
+ {
+ "sie_id": "test/model",
+ "hf_id": "test/model",
+ "inputs": {"text": True},
+ "tasks": {"generate": {"context_length": 4096, "max_output_tokens": 512}},
+ "max_sequence_length": 4096,
+ "profiles": {
+ "default": {
+ "max_batch_tokens": 4096,
+ "kv_budget_tokens": 2048,
+ "adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter",
+ "adapter_options": {
+ "runtime": {
+ "default_sampling": {"min_new_tokens": min_new_tokens},
+ }
+ },
+ }
+ },
+ }
+ )
+
+
def _make_msg(wi: dict[str, Any]) -> AsyncMock:
msg = AsyncMock()
msg.data = msgpack.packb(wi, use_bin_type=True)
@@ -2598,6 +2623,34 @@ def test_validate_rejects_content_parts_image_count_mismatch() -> None:
assert "image placeholder" in result.message
+def test_validate_generate_caps_profile_min_new_tokens_to_explicit_max() -> None:
+ result = StreamingProcessor._validate_generate_params(
+ _make_work_item(generate={"prompt": "Hello", "max_new_tokens": 1}),
+ _make_generation_config(min_new_tokens=10),
+ )
+
+ assert not isinstance(result, _ValidationError)
+ assert result.max_new_tokens == 1
+ assert result.min_tokens == 1
+
+
+def test_validate_generate_rejects_explicit_min_tokens_above_max() -> None:
+ result = StreamingProcessor._validate_generate_params(
+ _make_work_item(
+ generate={
+ "prompt": "Hello",
+ "max_new_tokens": 1,
+ "min_tokens": 10,
+ }
+ ),
+ _make_generation_config(min_new_tokens=10),
+ )
+
+ assert isinstance(result, _ValidationError)
+ assert result.code == "invalid_request"
+ assert result.message == "min_tokens (10) must not exceed max_new_tokens (1)"
+
+
def test_validate_threads_matching_gateway_content_parts() -> None:
# Gateway path with consistent counts: the ordered layout reaches the
# decoded message in order so the worker can interleave placeholders.
diff --git a/packages/sie_server/tests/test_metering_units.py b/packages/sie_server/tests/test_metering_units.py
index d19682919..2cfa1bcd5 100644
--- a/packages/sie_server/tests/test_metering_units.py
+++ b/packages/sie_server/tests/test_metering_units.py
@@ -19,6 +19,7 @@ bge-m3 / GLiNER / cross_encoder keep their exact values).
from __future__ import annotations
import asyncio
+import pathlib
import threading
import time
from typing import Any
@@ -40,10 +41,12 @@ from sie_server.adapters.qwen3_vl_reranker.adapter import Qwen3VLRerankerAdapter
from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter
from sie_server.adapters.siglip.adapter import SiglipAdapter
from sie_server.adapters.splade_flash.adapter import SPLADEFlashAdapter
-from sie_server.core.encode_pipeline import EncodePipeline
+from sie_server.core.encode_pipeline import EncodePipeline, _wholly_skipped_text_tower_zeros
from sie_server.core.inference_output import EncodeOutput, ExtractItemError, ExtractOutput, ScoreOutput
from sie_server.core.score_cost import MAX_SCORE_ITEMS, build_score_prepared_items
from sie_server.core.timing import RequestTiming
+from sie_server.core.video_frames import VideoDecodeError
+from sie_server.core.worker.handlers.encode import EncodeHandler
from sie_server.core.worker.handlers.score import ScoreHandler
from sie_server.core.worker.types import WorkerResult
from sie_server.ipc_types import (
@@ -56,8 +59,15 @@ from sie_server.ipc_types import (
ScoreBatchItem,
UnitCounts,
)
-from sie_server.queue_executor import QueueExecutor, _per_pair_image_counts, _with_audio_ms
+from sie_server.queue_executor import (
+ _MAX_ENCODE_ISOLATION_PASSES,
+ QueueExecutor,
+ _encode_units,
+ _per_pair_image_counts,
+ _with_audio_ms,
+)
from sie_server.types.inputs import Item
+from sie_server.types.responses import ErrorCode
class _FakeTokenizer:
@@ -837,6 +847,738 @@ class TestEncodeSeamImages:
assert outcome.outcomes[0].units is None
+# ---------------------------------------------------------------------------
+# Sampled video frames bill as images (§7, issue #2433)
+# ---------------------------------------------------------------------------
+#
+# A video item's wire payload is opaque compressed bytes, so the wire-derived
+# ``count_input_images`` hook cannot know its billable image count. The
+# video-capable adapter therefore stamps the frames it ACTUALLY sampled on
+# ``EncodeOutput.extra["input_image_counts"]``; the pipeline lifts them onto
+# ``RequestTiming`` and the encode seam prefers them over the hook. Nothing
+# processes a frame without settling it, and nothing settles a frame it did not
+# process.
+
+
+class _FakeVideoEncodeAdapter(BaseAdapter):
+ """Video-capable encoder (qwen3_vl_embedding shape): stamps the frames it
+ processed as the item's authoritative image count.
+ """
+
+ spec = AdapterSpec(inputs=("text", "image", "video"), outputs=("dense",), unload_fields=("_model",))
+
+ def __init__(self, *, frames_per_video: int = 0, counts: Any = None) -> None:
+ self._model = object()
+ self._device = "cpu"
+ self._frames_per_video = frames_per_video
+ self._counts = counts
+
+ def load(self, device: str) -> None: # pragma: no cover - not exercised
+ _ = device
+
+ def encode(self, items: list[Item], output_types: list[str], **_: Any) -> EncodeOutput:
+ _ = output_types
+ counts = self._counts
+ if counts is None:
+ counts = [
+ len(item.images or []) + (self._frames_per_video if item.video is not None else 0) for item in items
+ ]
+ return EncodeOutput(
+ dense=np.zeros((len(items), 4), dtype=np.float32),
+ batch_size=len(items),
+ extra={"input_image_counts": counts},
+ )
+
+
+def _vid() -> dict[str, Any]:
+ return {"data": b"fake-mp4-bytes", "format": "mp4"}
+
+
+class TestEncodePipelineVideoFrames:
+ async def _run(self, adapter: BaseAdapter, items: list[Item]) -> RequestTiming:
+ reg = _registry_for(adapter)
+ _formatted, timing = await EncodePipeline.run_encode(
+ registry=reg,
+ model="m",
+ items=items,
+ output_types=["dense"],
+ instruction=None,
+ config=MagicMock(),
+ is_query=False,
+ options={},
+ )
+ return timing
+
+ @pytest.mark.asyncio
+ async def test_pipeline_lifts_processed_frame_counts(self) -> None:
+ adapter = _FakeVideoEncodeAdapter(frames_per_video=6)
+ timing = await self._run(adapter, [Item(video=_vid()), Item(text="text only")])
+ assert timing.input_image_counts == [6, 0]
+
+ @pytest.mark.asyncio
+ async def test_misaligned_counts_are_dropped_not_mis_attributed(self) -> None:
+ adapter = _FakeVideoEncodeAdapter(counts=[3])
+ timing = await self._run(adapter, [Item(video=_vid()), Item(video=_vid())])
+ assert timing.input_image_counts is None
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("bad", [[-1], [True], ["4"], [1.5], "not-a-list"])
+ async def test_malformed_counts_are_dropped(self, bad: Any) -> None:
+ timing = await self._run(_FakeVideoEncodeAdapter(counts=bad), [Item(video=_vid())])
+ assert timing.input_image_counts is None
+
+ @pytest.mark.asyncio
+ async def test_adapters_that_stamp_nothing_leave_counts_unset(self) -> None:
+ # Every non-video adapter is unchanged: no ``extra`` stamp, so the
+ # result path stays on the wire-derived hook.
+ timing = await self._run(_FakeEncodeAdapter(), [Item(text="alpha")])
+ assert timing.input_image_counts is None
+
+
+class _FusingWorker:
+ """Fake ModelWorker that fans out through the REAL ``EncodeHandler``.
+
+ Reproduces the batched worker path exactly: the adapter is called once for
+ the whole GPU batch, ``slice_output`` splits that output per item and
+ ``assemble_output`` rebuilds this request's own output.
+
+ ``sibling_items`` are another request's items fused into the same batch, so
+ this request's slices start at a non-zero offset — the cross-request shape
+ the sidecar produces whenever two tenants' encodes share a sub-group.
+ """
+
+ def __init__(self, adapter: BaseAdapter, sibling_items: list[Item] | None = None) -> None:
+ self._adapter = adapter
+ self._sibling_items = sibling_items or []
+ self.fused_batch_size = 0
+
+ async def submit_preformed(self, **kwargs: Any) -> asyncio.Future[WorkerResult]:
+ items = kwargs["items"]
+ handler = EncodeHandler()
+ fused = [*self._sibling_items, *items]
+ self.fused_batch_size = len(fused)
+ output = handler.encode(
+ adapter=self._adapter,
+ items=fused,
+ output_types=kwargs["output_types"],
+ is_query=kwargs["is_query"],
+ options=kwargs["options"],
+ )
+ offset = len(self._sibling_items)
+ partials = {index: handler.slice_output(output, offset + index) for index in range(len(items))}
+ future: asyncio.Future[WorkerResult] = asyncio.Future()
+ future.set_result(WorkerResult(output=handler.assemble_output(partials, len(items)), timing=kwargs["timing"]))
+ return future
+
+ submit = submit_preformed
+
+
+def _batched_registry(adapter: BaseAdapter, worker: _FusingWorker) -> MagicMock:
+ """Registry whose model takes the BATCHED worker path.
+
+ ``config.inputs.image`` is declared and no image preprocessor is registered
+ — exactly ``models/Qwen__Qwen3-VL-Embedding-2B.yaml`` — so
+ ``_prepare_batch`` returns the passthrough ``PreparedBatch`` and
+ ``run_encode`` submits to the worker instead of calling the adapter direct.
+ """
+ reg = MagicMock()
+ reg.preprocessor_registry.has_preprocessor.return_value = False
+ reg.postprocessor_registry.transform_sync.return_value = 0.0
+ reg.get.return_value = adapter
+ reg.start_worker = AsyncMock(return_value=worker)
+ return reg
+
+
+class TestBatchedWorkerPathCarriesFrameCounts:
+ """The settlement basis must survive the batched worker path.
+
+ ``EncodeHandler.slice_output`` / ``assemble_output`` rebuild
+ ``EncodeOutput.extra`` from scratch, and used to copy only
+ ``input_token_counts``. Since ANY item carrying images routes the whole
+ sub-batch through the worker, a co-batched video encode arrived at the
+ meter with no frame count at all: a silent 32x under-bill when the item
+ also carried images, and a hard ``MeteringFault`` (which discards the
+ computed embeddings) when it did not.
+ """
+
+ @staticmethod
+ async def _run(
+ adapter: BaseAdapter,
+ items: list[Item],
+ sibling_items: list[Item] | None = None,
+ ) -> tuple[RequestTiming, _FusingWorker]:
+ worker = _FusingWorker(adapter, sibling_items)
+ config = MagicMock()
+ config.inputs.image = True
+ _formatted, timing = await EncodePipeline.run_encode(
+ registry=_batched_registry(adapter, worker),
+ model="m",
+ items=items,
+ output_types=["dense"],
+ instruction=None,
+ config=config,
+ is_query=False,
+ options={},
+ preformed_batch=True,
+ )
+ return timing, worker
+
+ @pytest.mark.asyncio
+ async def test_video_co_batched_with_another_requests_images(self) -> None:
+ # Tenant A encodes a video; tenant B concurrently encodes a plain image
+ # with the same options, so the sidecar fuses them into one sub-group —
+ # and B's images are what force the worker path onto A.
+ adapter = _FakeVideoEncodeAdapter(frames_per_video=32)
+ timing, worker = await self._run(
+ adapter,
+ [Item(video=_vid()), Item(images=[_img()])],
+ sibling_items=[Item(images=[_img(), _img()])],
+ )
+ assert worker.fused_batch_size == 3 # the batch really was fused
+ assert timing.input_image_counts == [32, 1] # each item keeps its own count
+
+ @pytest.mark.asyncio
+ async def test_a_lone_video_item_keeps_its_count_on_the_batched_path(self) -> None:
+ # One request, one item carrying an image AND a video: 1 + 32 = 33
+ # processed images. ``assemble_output`` takes its batch_size==1 fast
+ # path over an already-sliced partial, so the count was dropped here
+ # too — 33 images settling as the 1 the wire hook can see.
+ adapter = _FakeVideoEncodeAdapter(frames_per_video=32)
+ timing, _worker = await self._run(adapter, [Item(images=[_img()], video=_vid())])
+ assert timing.input_image_counts == [33]
+
+ def test_slice_and_assemble_preserve_both_unit_dimensions(self) -> None:
+ # The dimensions are independent: a video batch carries image counts
+ # with no token counts at all, so the all-or-nothing rule is per key.
+ handler = EncodeHandler()
+ output = EncodeOutput(
+ dense=np.zeros((2, 4), dtype=np.float32),
+ batch_size=2,
+ extra={"input_token_counts": [7, 9], "input_image_counts": [1, 33]},
+ )
+ partials = {index: handler.slice_output(output, index) for index in range(2)}
+ assembled = handler.assemble_output(partials, batch_size=2)
+ assert assembled.extra["input_token_counts"] == [7, 9]
+ assert assembled.extra["input_image_counts"] == [1, 33]
+
+ def test_each_request_assembles_only_its_own_slices(self) -> None:
+ # One fused GPU batch, two requests: item 0 is one tenant's image,
+ # items 1-2 are another's videos.
+ handler = EncodeHandler()
+ output = EncodeOutput(
+ dense=np.zeros((3, 4), dtype=np.float32),
+ batch_size=3,
+ extra={"input_image_counts": [1, 32, 7]},
+ )
+ first = handler.assemble_output({0: handler.slice_output(output, 0)}, batch_size=1)
+ second = handler.assemble_output(
+ {0: handler.slice_output(output, 1), 1: handler.slice_output(output, 2)},
+ batch_size=2,
+ )
+ assert first.extra["input_image_counts"] == [1]
+ assert second.extra["input_image_counts"] == [32, 7]
+
+ def test_a_partial_without_a_count_drops_that_dimension(self) -> None:
+ # All-or-nothing per key: one partial missing its single-element list
+ # means the request cannot be attributed exactly, so the dimension is
+ # dropped rather than assembled from a subset. Assembling the partial
+ # evidence instead would UNDER-bill (the missing item silently counts
+ # as nothing); dropping it leaves the meter on its reserve estimate.
+ handler = EncodeHandler()
+ good = EncodeOutput(
+ dense=np.zeros((1, 4), dtype=np.float32),
+ batch_size=1,
+ extra={"input_image_counts": [5], "input_token_counts": [7]},
+ )
+ # Same shape, but the image count never made it onto this partial.
+ bare = EncodeOutput(
+ dense=np.zeros((1, 4), dtype=np.float32),
+ batch_size=1,
+ extra={"input_token_counts": [9]},
+ )
+ assembled = handler.assemble_output({0: good, 1: bare}, batch_size=2)
+
+ assert "input_image_counts" not in assembled.extra
+ # The keys are independent: the intact dimension still assembles.
+ assert assembled.extra["input_token_counts"] == [7, 9]
+
+
+class TestVideoWithoutAnAuthoritativeCountFailsClosed:
+ """A video item never falls back to the wire-derived hook.
+
+ ``count_input_images`` sees opaque compressed bytes and scores them zero,
+ so using it for a video item would settle the sampled frames as free.
+ Leaving the count unset instead makes settlement refuse the item for want
+ of evidence — visible, not a silent revenue leak.
+ """
+
+ @staticmethod
+ def _run_encode_without_a_stamp() -> AsyncMock:
+ """``run_encode`` that records no authoritative image counts at all."""
+
+ async def fake_run_encode(**kwargs: Any) -> tuple[list[dict[str, Any]], RequestTiming]:
+ return [{"dense": [0.0]} for _ in kwargs["items"]], RequestTiming()
+
+ return AsyncMock(side_effect=fake_run_encode)
+
+ @pytest.mark.asyncio
+ async def test_video_item_settles_no_images_when_the_stamp_is_missing(self) -> None:
+ ex = QueueExecutor(_encode_registry(_FakeVisionEncodeAdapter()))
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode_without_a_stamp()):
+ outcome = await ex.process_encode_batch(
+ _encode_request([{"images": [_img()], "video": _vid()}, {"images": [_img(), _img()]}])
+ )
+
+ # The video item declines the hook's under-count of 1 …
+ assert outcome.outcomes[0].units is None
+ # … while its plain-image sibling keeps its exact wire-derived count.
+ assert outcome.outcomes[1].units is not None
+ assert outcome.outcomes[1].units.images == 2
+
+
+class TestMixedBatchDimensionsAgreeWithThePlan:
+ """A mixed text+video batch must report BOTH dimensions.
+
+ The gateway plans ``input_tokens`` whenever any item carries tokenizable
+ text and ``images`` whenever any item carries video, then settles only if
+ the terminal reports exactly the planned dimensions: a planned dimension
+ the terminal omits, or a priced one it reports unplanned, faults the whole
+ dispatch after the GPU is already spent.
+
+ Since #2538 a visual-only item reports its token zero rather than hiding
+ it, because that zero now carries its own witness — the item's positive
+ image count — and ``meter::zero_is_authoritative`` admits exactly that
+ shape. Credits are unchanged either way (a zero rates to nothing); what the
+ zero buys is a chunk in which EVERY item took the image tower, where the
+ dimension would otherwise be absent and settlement would fault it as
+ reserved-but-missing.
+ """
+
+ @staticmethod
+ def _run_encode(token_counts: list[int] | None, image_counts: list[int] | None) -> AsyncMock:
+ async def fake_run_encode(**kwargs: Any) -> tuple[list[dict[str, Any]], RequestTiming]:
+ timing = RequestTiming()
+ timing.input_token_counts = token_counts
+ timing.input_image_counts = image_counts
+ return [{"dense": [0.0]} for _ in kwargs["items"]], timing
+
+ return AsyncMock(side_effect=fake_run_encode)
+
+ @pytest.mark.asyncio
+ async def test_text_and_video_each_settle_their_own_dimension(self) -> None:
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter(frames_per_video=32)))
+ # The adapter scatters 0 text tokens to the video item (siglip shape).
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode([4, 0], [0, 32])):
+ outcome = await ex.process_encode_batch(_encode_request([{"text": "alpha beta"}, {"video": _vid()}]))
+
+ text_units = outcome.outcomes[0].units
+ video_units = outcome.outcomes[1].units
+ assert text_units is not None
+ assert text_units.input_tokens == 4
+ assert text_units.images is None
+ assert video_units is not None
+ assert video_units.images == 32
+ # The zero is REPORTED (#2538): its own image count witnesses it, and
+ # the gateway admits exactly that shape. It rates to nothing, so the
+ # request's debit is identical to what it was when the zero was hidden.
+ assert video_units.input_tokens == 0
+
+ def test_an_image_witnessed_zero_token_count_is_reported(self) -> None:
+ units = _encode_units(0, 32)
+ assert units is not None
+ assert units.input_tokens == 0
+ assert units.images == 32
+
+ def test_an_unwitnessed_zero_token_count_is_still_dropped(self) -> None:
+ # THE rail. Without a positive image count a zero explains nothing —
+ # it is a tokenizer that counted nothing on a text item — so it stays
+ # off the wire and the gateway keeps failing it closed. Byte for byte
+ # the rule `meter::zero_is_authoritative` applies on the other side.
+ units = _encode_units(0, None)
+ assert units is None
+ assert _encode_units(0, 0) is None
+ # And a positive count is unaffected in either direction.
+ positive = _encode_units(7, None)
+ assert positive is not None
+ assert positive.input_tokens == 7
+
+ def test_an_item_with_only_zeros_yields_no_units(self) -> None:
+ assert _encode_units(0, 0) is None
+
+
+class TestMalformedVideoIsolation:
+ """One caller's undecodable video must not fail its co-batched siblings.
+
+ ``process_encode_batch`` fuses items from DIFFERENT API requests into one
+ sub-group, and the direct-adapter path had no ``_isolate_invalid_input``
+ equivalent — so a single ``VideoDecodeError`` out of ``run_encode`` was
+ applied to every item in the group, 400-ing tenants whose input was fine.
+ """
+
+ @staticmethod
+ def _request(specs: list[tuple[str, dict[str, Any]]]) -> ProcessEncodeBatchRequest:
+ """Build one work batch from ``(request_id, item)`` pairs."""
+ totals: dict[str, int] = {}
+ for request_id, _item in specs:
+ totals[request_id] = totals.get(request_id, 0) + 1
+ seen: dict[str, int] = {}
+ items = []
+ for request_id, item in specs:
+ index = seen.get(request_id, 0)
+ seen[request_id] = index + 1
+ items.append(
+ EncodeBatchItem(
+ work_item_id=f"{request_id}.{index}",
+ request_id=request_id,
+ item_index=index,
+ total_items=totals[request_id],
+ timestamp=time.time(),
+ item=item,
+ )
+ )
+ return ProcessEncodeBatchRequest(model_id="test/model", items=items)
+
+ @staticmethod
+ def _run_encode_failing_on_video() -> AsyncMock:
+ """``run_encode`` that raises exactly where ``extract_frames`` does."""
+
+ async def fake_run_encode(**kwargs: Any) -> tuple[list[dict[str, Any]], RequestTiming]:
+ items = kwargs["items"]
+ if any(item.video is not None for item in items):
+ raise VideoDecodeError("video input could not be opened by the decoder")
+ timing = RequestTiming()
+ timing.input_token_counts = [4] * len(items)
+ return [{"dense": [0.0]} for _ in items], timing
+
+ return AsyncMock(side_effect=fake_run_encode)
+
+ @pytest.mark.asyncio
+ async def test_only_the_offending_request_fails(self) -> None:
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter()))
+ request = self._request(
+ [
+ ("req-a", {"text": "alpha"}),
+ ("req-bad", {"video": _vid()}),
+ ("req-c", {"text": "gamma"}),
+ ("req-d", {"text": "delta"}),
+ ]
+ )
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode_failing_on_video()):
+ outcome = await ex.process_encode_batch(request)
+
+ by_id = {o.work_item_id: o for o in outcome.outcomes}
+ assert by_id["req-bad.0"].disposition == "publish_error_and_ack"
+ assert by_id["req-bad.0"].error_code == ErrorCode.INVALID_INPUT.value
+ assert by_id["req-bad.0"].units is None
+ for good in ("req-a.0", "req-c.0", "req-d.0"):
+ assert by_id[good].disposition == "publish_and_ack", good
+ assert by_id[good].units is not None, good
+ assert by_id[good].units.input_tokens == 4, good
+
+ @pytest.mark.asyncio
+ async def test_the_offending_request_stays_atomic(self) -> None:
+ # Matches the worker-batched ``_isolate_invalid_input`` semantics: the
+ # split is by request identity, so a multi-item request fails whole
+ # rather than publishing a half-successful response.
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter()))
+ request = self._request(
+ [
+ ("req-bad", {"text": "caption"}),
+ ("req-ok", {"text": "alpha"}),
+ ("req-bad", {"video": _vid()}),
+ ]
+ )
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode_failing_on_video()):
+ outcome = await ex.process_encode_batch(request)
+
+ by_id = {o.work_item_id: o for o in outcome.outcomes}
+ assert by_id["req-bad.0"].disposition == "publish_error_and_ack"
+ assert by_id["req-bad.1"].disposition == "publish_error_and_ack"
+ assert by_id["req-ok.0"].disposition == "publish_and_ack"
+
+ @pytest.mark.asyncio
+ async def test_a_lone_malformed_request_still_reports_invalid_input(self) -> None:
+ # The terminal case of the recursion, unchanged from before the split.
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter()))
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode_failing_on_video()):
+ outcome = await ex.process_encode_batch(self._request([("req-solo", {"video": _vid()})]))
+
+ assert outcome.outcomes[0].error_code == ErrorCode.INVALID_INPUT.value
+
+ @pytest.mark.asyncio
+ async def test_isolating_one_bad_request_is_a_binary_search(self) -> None:
+ # The case isolation exists for: only the half holding the bad request
+ # fails, so the recursion is a true binary search — ~2*log2(R) passes,
+ # nowhere near the budget.
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter()))
+ specs: list[tuple[str, dict[str, Any]]] = [(f"req-{i}", {"text": f"doc {i}"}) for i in range(15)]
+ specs.insert(9, ("req-bad", {"video": _vid()}))
+ run_encode = self._run_encode_failing_on_video()
+ with patch.object(EncodePipeline, "run_encode", new=run_encode):
+ outcome = await ex.process_encode_batch(self._request(specs))
+
+ by_id = {o.work_item_id: o for o in outcome.outcomes}
+ assert by_id["req-bad.0"].error_code == ErrorCode.INVALID_INPUT.value
+ assert all(by_id[f"req-{i}.0"].disposition == "publish_and_ack" for i in range(15))
+ # 16 requests -> at most ~2*log2(16) + 1 passes, well under the budget.
+ assert run_encode.await_count <= 12, run_encode.await_count
+
+ @pytest.mark.asyncio
+ async def test_an_environmental_failure_cannot_fan_out_unbounded(self) -> None:
+ # The broken-OpenCV-wheel shape: EVERY video request fails, so both
+ # halves of every split fail and unbounded bisection would degenerate
+ # to ~2R re-encode passes on the single-threaded inference executor.
+ # The batch's isolation budget caps that; every request still gets the
+ # typed INVALID_INPUT it was always going to get.
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter()))
+ specs: list[tuple[str, dict[str, Any]]] = [(f"req-{i}", {"video": _vid()}) for i in range(32)]
+ run_encode = self._run_encode_failing_on_video()
+ with patch.object(EncodePipeline, "run_encode", new=run_encode):
+ outcome = await ex.process_encode_batch(self._request(specs))
+
+ assert len(outcome.outcomes) == 32
+ assert all(o.error_code == ErrorCode.INVALID_INPUT.value for o in outcome.outcomes)
+ assert all(o.units is None for o in outcome.outcomes)
+ # Unbounded bisection would be ~2*32 = 64 passes; the budget holds it
+ # to the cap plus the one initial pass per split branch.
+ assert run_encode.await_count <= _MAX_ENCODE_ISOLATION_PASSES + 2, run_encode.await_count
+
+
+class TestEncodeSeamVideoFrames:
+ @staticmethod
+ def _run_encode(image_counts: list[int] | None, token_counts: list[int] | None = None) -> Any:
+ async def fake_run_encode(**kwargs: Any) -> tuple[list[dict[str, Any]], RequestTiming]:
+ timing = RequestTiming()
+ timing.input_image_counts = image_counts
+ timing.input_token_counts = token_counts
+ return [{"dense": [0.0]} for _ in kwargs["items"]], timing
+
+ return AsyncMock(side_effect=fake_run_encode)
+
+ @pytest.mark.asyncio
+ async def test_video_only_item_settles_processed_frames_as_images(self) -> None:
+ # Previously this item faulted ("all failed to load") and settled
+ # nothing; now it settles the exact frames the model saw.
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter(frames_per_video=9)))
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode([9])):
+ outcome = await ex.process_encode_batch(_encode_request([{"video": _vid()}]))
+
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_and_ack"
+ assert o.units is not None
+ assert o.units.images == 9
+ assert o.units.input_tokens is None
+
+ @pytest.mark.asyncio
+ async def test_mixed_text_and_video_settles_both_dimensions(self) -> None:
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter(frames_per_video=5)))
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode([5], [12])):
+ outcome = await ex.process_encode_batch(_encode_request([{"text": "a caption", "video": _vid()}]))
+
+ o = outcome.outcomes[0]
+ assert o.units is not None
+ assert o.units.input_tokens == 12
+ assert o.units.images == 5
+
+ @pytest.mark.asyncio
+ async def test_processed_count_wins_over_the_wire_derived_hook(self) -> None:
+ # The wire item carries ONE image and one opaque video; the hook would
+ # bill 1. The adapter processed 1 image + 4 frames -> 5 billable images.
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter(frames_per_video=4)))
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode([5])):
+ outcome = await ex.process_encode_batch(_encode_request([{"images": [_img()], "video": _vid()}]))
+
+ assert outcome.outcomes[0].units is not None
+ assert outcome.outcomes[0].units.images == 5
+
+ @pytest.mark.asyncio
+ async def test_per_item_counts_stay_aligned_across_a_batch(self) -> None:
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter(frames_per_video=3)))
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode([0, 3])):
+ outcome = await ex.process_encode_batch(_encode_request([{"text": "alpha"}, {"video": _vid()}]))
+
+ assert outcome.outcomes[0].units is None # text-only, no token count either
+ assert outcome.outcomes[1].units is not None
+ assert outcome.outcomes[1].units.images == 3
+
+ @pytest.mark.asyncio
+ async def test_undecodable_video_settles_nothing_as_typed_invalid_input(self) -> None:
+ # No path settles frames it did not process: a decode failure is a
+ # typed 4xx with no units, not a billed success missing its video.
+ ex = QueueExecutor(_encode_registry(_FakeVideoEncodeAdapter()))
+ failing = AsyncMock(side_effect=VideoDecodeError("video input could not be opened by the decoder"))
+ with patch.object(EncodePipeline, "run_encode", new=failing):
+ outcome = await ex.process_encode_batch(_encode_request([{"video": _vid()}]))
+
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_error_and_ack"
+ assert o.error_code == ErrorCode.INVALID_INPUT.value
+ assert o.units is None
+
+ @pytest.mark.asyncio
+ async def test_absent_processed_counts_fall_back_to_the_wire_hook(self) -> None:
+ # Regression guard for every existing image adapter: with no ``extra``
+ # stamp the seam still bills submitted images off the shared hook.
+ ex = QueueExecutor(_encode_registry(_FakeVisionEncodeAdapter()))
+ with patch.object(EncodePipeline, "run_encode", new=self._run_encode(None)):
+ outcome = await ex.process_encode_batch(_encode_request([{"images": [_img(), _img()]}]))
+
+ assert outcome.outcomes[0].units is not None
+ assert outcome.outcomes[0].units.images == 2
+
+
+# ---------------------------------------------------------------------------
+# Measured modality routing — the authoritative-zero basis (#2538)
+# ---------------------------------------------------------------------------
+#
+# SigLIP/CLIP route ANY item carrying images to the image tower, even one that
+# also carries text, so an item's text-token count can be a genuine zero. Only
+# the adapter's own partition knows that; nothing downstream can re-derive it
+# from the wire item, because "has text" does not imply "was tokenized". The
+# adapters publish the partition on ``extra["text_tower_skipped"]`` and the
+# pipeline uses it as the LAST-resort count basis — after every real tokenizer
+# path has failed — so batches that count today keep counting exactly as before.
+
+
+class TestMeasuredModalityRouting:
+ def test_clip_publishes_its_partition(self) -> None:
+ adapter = TestVisionTextTokenStamp()._clip()
+ items = [Item(text="alpha beta"), Item(images=[{"data": b"x"}]), Item(text="one two three")]
+ out = adapter.encode(items, ["dense"])
+ assert out.extra["text_tower_skipped"] == [False, True, False]
+
+ def test_an_item_carrying_both_text_and_images_is_reported_as_skipped(self) -> None:
+ # The routing fact that finding 2 turns on: `has_images` wins, so this
+ # item never reaches the text tower and its text is never billed.
+ adapter = TestVisionTextTokenStamp()._clip()
+ out = adapter.encode([Item(text="a photo of a cat", images=[{"data": b"x"}])], ["dense"])
+ assert out.extra["text_tower_skipped"] == [True]
+ assert "input_token_counts" not in out.extra
+
+ def test_the_partition_is_per_item_sliceable(self) -> None:
+ # A fused GPU batch is split back into per-request outputs; a per-item
+ # extra that is not registered for slicing arrives misaligned, which
+ # would mis-attribute the zero to the wrong caller.
+ from sie_server.core.worker.handlers.encode import PER_ITEM_EXTRA_KEYS
+
+ assert "text_tower_skipped" in PER_ITEM_EXTRA_KEYS
+
+
+class TestWhollyImageTowerBatchCounts:
+ """The pipeline's last-resort basis: no tokenizer could count, but the
+ adapter measured that every item skipped the text tower.
+ """
+
+ @staticmethod
+ def _adapter(skipped: list[bool] | None, counts: list[int] | None) -> Any:
+ adapter = MagicMock()
+ adapter.count_input_tokens.return_value = counts
+ adapter._skipped = skipped
+ return adapter
+
+ @staticmethod
+ def _mixed(n: int = 2) -> list[Item]:
+ """Text+image items — the SigLIP shape where `has_images` wins, so the
+ item carries text the gateway reserved for and still skips the tower.
+ """
+ return [Item(text="a cat", images=[_img()]) for _ in range(n)]
+
+ def test_a_wholly_skipped_text_bearing_partition_is_an_authoritative_zero(self) -> None:
+ assert _wholly_skipped_text_tower_zeros([True, True], self._mixed(2)) == [0, 0]
+ assert _wholly_skipped_text_tower_zeros([True], self._mixed(1)) == [0]
+
+ def test_any_unskipped_item_keeps_the_dimension_absent(self) -> None:
+ # THE rail that keeps today's billing intact. A batch with even one
+ # text item had text a tokenizer should have counted; zeros here would
+ # convert "bill text the model read" into "bill nothing", which is a
+ # pricing decision and not a bug fix. `None` sends the meter back to
+ # its reserve estimate, exactly as before #2538.
+ assert _wholly_skipped_text_tower_zeros([True, False], self._mixed(2)) is None
+ assert _wholly_skipped_text_tower_zeros([False, False], self._mixed(2)) is None
+
+ def test_a_pure_image_batch_stays_off_the_token_dimension(self) -> None:
+ # `text_tower_skipped` is True for a pure-image item exactly as it is
+ # for a text+image one, so without the text condition this fallback
+ # would put `input_tokens = 0` on a request that never carried text and
+ # never reserved the dimension. The SigLIP/CLIP adapters already refuse
+ # to stamp `input_token_counts` for such a batch on purpose; #2538 must
+ # not reverse that from one layer up.
+ image_only = [Item(images=[_img()]), Item(images=[_img()])]
+ assert _wholly_skipped_text_tower_zeros([True, True], image_only) is None
+ # An empty string is not text either.
+ assert _wholly_skipped_text_tower_zeros([True], [Item(text="", images=[_img()])]) is None
+
+ def test_a_malformed_or_misaligned_partition_is_dropped(self) -> None:
+ # Same contract as every other metering basis (`_validated_counts`):
+ # a partition that cannot be attributed exactly is not a measurement.
+ # `1` is truthy and would pass a bare `all()`, so the bool check is
+ # load-bearing rather than decorative.
+ assert _wholly_skipped_text_tower_zeros([True, True], self._mixed(3)) is None
+ assert _wholly_skipped_text_tower_zeros("TT", self._mixed(2)) is None
+ assert _wholly_skipped_text_tower_zeros(None, self._mixed(2)) is None
+ assert _wholly_skipped_text_tower_zeros([1, 1], self._mixed(2)) is None
+ # An empty partition satisfies `all()` vacuously and must NOT mint a
+ # bare unwitnessed zero.
+ assert _wholly_skipped_text_tower_zeros([], []) is None
+
+ @pytest.mark.asyncio
+ async def test_all_skipped_settles_with_images_end_to_end(self) -> None:
+ ex = QueueExecutor(_encode_registry(_FakeVisionEncodeAdapter()))
+
+ async def fake_run_encode(**kwargs: Any) -> tuple[list[dict[str, Any]], RequestTiming]:
+ timing = RequestTiming()
+ timing.input_image_counts = [1, 1]
+ # What the pipeline's last-resort basis produces for this batch.
+ timing.input_token_counts = _wholly_skipped_text_tower_zeros([True, True], kwargs["items"])
+ return [{"dense": [0.0]} for _ in kwargs["items"]], timing
+
+ with patch.object(EncodePipeline, "run_encode", new=AsyncMock(side_effect=fake_run_encode)):
+ outcome = await ex.process_encode_batch(
+ _encode_request([{"text": "a cat", "images": [_img()]}, {"text": "a dog", "images": [_img()]}])
+ )
+ # Both dimensions reach the wire: the images that bill, and the token
+ # zero whose image witness lets settlement release that dimension
+ # instead of faulting the dispatch as reserved-but-missing.
+ for item in outcome.outcomes:
+ assert item.disposition == "publish_and_ack"
+ assert item.units is not None
+ assert item.units.images == 1
+ assert item.units.input_tokens == 0
+
+ @pytest.mark.asyncio
+ async def test_an_image_only_request_never_gains_a_token_dimension(self) -> None:
+ # The end-to-end half of the pure-image rail: an image-only request
+ # reserved no `input_tokens`, so its terminal must not carry one. This
+ # is the shape the last-resort basis would have captured if it keyed on
+ # `text_tower_skipped` alone.
+ ex = QueueExecutor(_encode_registry(_FakeVisionEncodeAdapter()))
+
+ async def fake_run_encode(**kwargs: Any) -> tuple[list[dict[str, Any]], RequestTiming]:
+ timing = RequestTiming()
+ timing.input_image_counts = [1, 1]
+ timing.input_token_counts = _wholly_skipped_text_tower_zeros([True, True], kwargs["items"])
+ return [{"dense": [0.0]} for _ in kwargs["items"]], timing
+
+ with patch.object(EncodePipeline, "run_encode", new=AsyncMock(side_effect=fake_run_encode)):
+ outcome = await ex.process_encode_batch(_encode_request([{"images": [_img()]}, {"images": [_img()]}]))
+ for item in outcome.outcomes:
+ assert item.disposition == "publish_and_ack"
+ assert item.units is not None
+ assert item.units.images == 1
+ assert item.units.input_tokens is None
+
+ def test_pipeline_only_uses_the_partition_when_nothing_else_counted(self) -> None:
+ # Ordering, which no unit test of the helper can observe: the branch
+ # sits AFTER the `count_input_tokens` fallback, so any batch a real
+ # tokenizer could count keeps those numbers.
+ source = pathlib.Path(EncodePipeline.__module__.replace(".", "/") + ".py")
+ text = (pathlib.Path(__file__).parents[3] / "packages/sie_server/src" / source).read_text()
+ fallback = text.index("adapter.count_input_tokens")
+ # The CALL site, not the helper's definition (which sits above both).
+ last_resort = text.index("timing.input_token_counts = _wholly_skipped_text_tower_zeros(")
+ assert fallback < last_resort, "the last-resort basis must not pre-empt a real tokenizer"
+
+
# ---------------------------------------------------------------------------
# QueueExecutor.process_extract_batch — extract seam stamps images
# ---------------------------------------------------------------------------
@@ -1113,15 +1855,13 @@ class TestVisionTextTokenStamp:
adapter._device = "cpu"
adapter._backend = "transformers" # type: ignore[assignment]
- # Stub the text forward: real counts come from the shared base counter
- # over the processor tokenizer; return matching zero vectors.
+ # Stub the text forward with SigLIP's fixed padded-work billing count.
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))
- return np.zeros((len(texts), 4), dtype=np.float32), counts
+ return np.zeros((len(texts), 4), dtype=np.float32), [adapter._max_seq_length] * len(texts)
adapter._encode_texts = fake_encode_texts # type: ignore[method-assign]
out = adapter.encode([Item(text="a b c")], ["dense"])
- assert out.extra["input_token_counts"] == [5]
+ assert out.extra["input_token_counts"] == [64]
# ---------------------------------------------------------------------------
diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.toml
index e6bb270da..096e45011 100644
--- a/packages/sie_server_sidecar/Cargo.toml
+++ b/packages/sie_server_sidecar/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-server-sidecar"
-version = "0.6.24"
+version = "0.6.25"
edition = "2021"
publish = false
description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."
diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.json
index 4dab675eb..bb339c5dd 100644
--- a/packages/sie_ts_sdk/package.json
+++ b/packages/sie_ts_sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-sdk",
- "version": "0.6.24",
+ "version": "0.6.25",
"description": "Official TypeScript SDK for SIE (Search Inference Engine)",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index 63cfa61ad..7aa52b0e9 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -65,6 +65,8 @@ import {
SERVER_VERSION_HEADER,
} from "./internal/constants.js";
import {
+ ESTIMATE_PATH,
+ buildEstimateEnvelope,
getErrorCode,
getRetryAfter,
handleError,
@@ -73,6 +75,8 @@ import {
parseExtractResults,
parseGenerateResult,
parseScoreResult,
+ settledChargeFields,
+ throwIfEstimateUnroutable,
throwIfInputTooLong,
throwIfModelLoadFailed,
} from "./internal/parsing.js";
@@ -93,6 +97,7 @@ import { packMessage, unpackMessage } from "./msgpack.js";
import { parseSseStream } from "./sse.js";
import type {
Batch,
+ BatchList,
CapacityInfo,
ChatCompletion,
ChatCompletionChunk,
@@ -101,6 +106,7 @@ import type {
Connection,
ConnectionCreated,
ConnectionRevoked,
+ CostEstimate,
CreatePoolOptions,
EncodeOptions,
EncodeResult,
@@ -108,6 +114,7 @@ import type {
ExtractOptions,
ExtractResult,
FileDeleted,
+ FileList,
GenerateChunk,
GenerateGrammar,
GenerateOptions,
@@ -173,6 +180,20 @@ export interface FilesNamespace {
create(options: { file: FileUploadInput; purpose?: string; filename?: string }): Promise<SIEFile>;
/** Fetch a file's metadata (`GET /v1/files/{id}`). */
retrieve(fileId: string): Promise<SIEFile>;
+ /** List the org's live files with OpenAI cursor/filter arguments. */
+ list(options?: {
+ after?: string;
+ limit?: number;
+ order?: "asc" | "desc";
+ purpose?: string;
+ }): Promise<SIEFile[]>;
+ /** Return one file cursor page, including pagination metadata. */
+ listPage(options?: {
+ after?: string;
+ limit?: number;
+ order?: "asc" | "desc";
+ purpose?: string;
+ }): Promise<FileList>;
/** Download a file's raw bytes (`GET /v1/files/{id}/content`). */
content(fileId: string): Promise<Uint8Array>;
/** Delete a file (`DELETE /v1/files/{id}`; additive OpenAI-parity surface). */
@@ -196,8 +217,10 @@ export interface BatchesNamespace {
}): Promise<Batch>;
/** Fetch a batch's status (`GET /v1/batches/{id}`). */
retrieve(batchId: string): Promise<Batch>;
- /** List the org's batches (`GET /v1/batches`; additive OpenAI-parity). */
- list(): Promise<Batch[]>;
+ /** List the org's batches; the historical array return is preserved. */
+ list(options?: { after?: string; limit?: number }): Promise<Batch[]>;
+ /** Return one batch cursor page, including pagination metadata. */
+ listPage(options?: { after?: string; limit?: number }): Promise<BatchList>;
/** Cancel a batch (`POST /v1/batches/{id}/cancel`; additive OpenAI-parity). */
cancel(batchId: string): Promise<Batch>;
}
@@ -214,8 +237,16 @@ function parseNonnegativeMeterHeader(headers: Headers, name: string): number | u
return Number.isSafeInteger(parsed) ? parsed : undefined;
}
-/** Parse optional request-scoped metadata from one successful terminal response. */
-function parseRequestMetadata(headers: Headers): RequestMetadata | undefined {
+/**
+ * Parse optional request-scoped metadata from one successful terminal response.
+ *
+ * `body` is the decoded response envelope, when the caller has one. The settled
+ * charge is read from its `usage` block FIRST and falls back to the
+ * `x-sie-credits-debited` header, which is the only source on a gateway that
+ * predates in-body surfacing (#2434). The two always agree when both are
+ * present; the body additionally names the rate book, which no header does.
+ */
+function parseRequestMetadata(headers: Headers, body?: unknown): RequestMetadata | undefined {
const metadata: RequestMetadata = {};
const requestId = headers.get("x-sie-request-id");
if (
@@ -248,18 +279,46 @@ function parseRequestMetadata(headers: Headers): RequestMetadata | undefined {
const value = parseNonnegativeMeterHeader(headers, header);
if (value !== undefined) usage[field] = value;
}
- if (Object.keys(usage).length > 0) metadata.usage = usage;
- const creditsDebited = parseNonnegativeMeterHeader(headers, "x-sie-credits-debited");
- if (creditsDebited !== undefined) metadata.creditsDebited = creditsDebited;
+ const settled = settledChargeFromBody(body);
+ if (settled !== undefined) {
+ usage.creditsCharged = settled.creditsCharged;
+ usage.rateBookVersion = settled.rateBookVersion;
+ metadata.creditsDebited = settled.creditsCharged;
+ metadata.rateBookVersion = settled.rateBookVersion;
+ } else {
+ const creditsDebited = parseNonnegativeMeterHeader(headers, "x-sie-credits-debited");
+ if (creditsDebited !== undefined) metadata.creditsDebited = creditsDebited;
+ }
+ if (Object.keys(usage).length > 0) metadata.usage = usage;
return Object.keys(metadata).length > 0 ? metadata : undefined;
}
+/**
+ * The settled charge from a response envelope's `usage` block (#2434).
+ *
+ * Shares `settledChargeFields`' validation so the metadata path and the result
+ * parsers can never disagree about what counts as a publishable charge.
+ * Anything malformed is treated as absent, so the header fallback still
+ * applies.
+ */
+function settledChargeFromBody(
+ body: unknown,
+): { creditsCharged: number; rateBookVersion: string } | undefined {
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return undefined;
+ const { creditsCharged, rateBookVersion } = settledChargeFields(
+ (body as Record<string, unknown>).usage,
+ );
+ if (creditsCharged === undefined || rateBookVersion === undefined) return undefined;
+ return { creditsCharged, rateBookVersion };
+}
+
function attachRequestMetadata<T extends { request?: RequestMetadata }>(
results: T[],
headers: Headers,
+ body?: unknown,
): void {
- const metadata = parseRequestMetadata(headers);
+ const metadata = parseRequestMetadata(headers, body);
if (metadata === undefined) return;
for (const result of results) {
result.request = { ...metadata };
@@ -578,13 +637,16 @@ export class SIEClient {
upload: (file, options) => this.fileUpload(file, options),
create: (options) => this.fileUpload(options.file, options),
retrieve: (fileId) => this.fileRetrieve(fileId),
+ list: (options) => this.fileList(options),
+ listPage: (options) => this.fileListPage(options),
content: (fileId) => this.fileContent(fileId),
delete: (fileId) => this.fileDelete(fileId),
};
this.batches = {
create: (options) => this.batchCreate(options),
retrieve: (batchId) => this.batchRetrieve(batchId),
- list: () => this.batchList(),
+ list: (options) => this.batchList(options),
+ listPage: (options) => this.batchListPage(options),
cancel: (batchId) => this.batchCancel(batchId),
};
}
@@ -676,7 +738,7 @@ export class SIEClient {
const data = unpackMessage<WireResponse>(new Uint8Array(await response.arrayBuffer()));
const results = parseEncodeResults(data.items);
- attachRequestMetadata(results, response.headers);
+ attachRequestMetadata(results, response.headers, data);
if (isSingleItem) {
const first = results[0];
@@ -688,6 +750,57 @@ export class SIEClient {
return results;
}
+ /**
+ * Price a request WITHOUT running it (`POST /v1/estimate`).
+ *
+ * The gateway plans the request through the same reservation planner the
+ * metered path runs, against the same active rate book, and returns the plan
+ * instead of holding it: no dispatch, no reservation, no credits consumed.
+ * The quote is the CONSERVATIVE ceiling the live path would hold —
+ * settlement bills the authoritative counts against that plan and releases
+ * the rest, so the real charge is at most `estimated_credits`.
+ *
+ * @param endpoint - The exact target path, e.g. `"/v1/encode/BAAI/bge-m3"`
+ * (native, model in the path) or `"/v1/chat/completions"`
+ * (OpenAI-compatible, model in `request.model`).
+ * @param request - The verbatim body you would send to `endpoint`. Passed
+ * through untouched — a body the SDK reshaped would be a quote for a
+ * request you never send.
+ * @param options.timeout - Per-call timeout override in milliseconds.
+ * @returns The planned units, applied rates, credits, and the active rate
+ * book's version + digest.
+ * @throws {EstimateUnroutableError} If the active book cannot price the
+ * request. Same verdict the real request would get; the message names the
+ * unpriced identity or the dimension the planner could not bound.
+ * @throws {RequestError} If the target body is invalid, with the same
+ * status/code the target route itself would return. In particular a
+ * `404 MODEL_NOT_FOUND` means this data plane does not serve the model at
+ * all — the estimate checks routability, not just priceability, so it never
+ * quotes a request that would 404.
+ *
+ * @example
+ * ```typescript
+ * const quote = await client.estimate("/v1/encode/BAAI/bge-m3", {
+ * items: [{ text: "Hello" }],
+ * });
+ * console.log(quote.estimated_credits, quote.rate_book_version);
+ * ```
+ */
+ async estimate(
+ endpoint: string,
+ request: Record<string, unknown>,
+ options: { timeout?: number } = {},
+ ): Promise<CostEstimate> {
+ const body = buildEstimateEnvelope(endpoint, request);
+ return this.jsonRequest<CostEstimate>(
+ ESTIMATE_PATH,
+ "POST",
+ body,
+ options.timeout ?? this.timeout,
+ throwIfEstimateUnroutable,
+ );
+ }
+
/**
* List available models.
*
@@ -921,7 +1034,7 @@ export class SIEClient {
throw new RequestError("Unexpected generate response shape");
}
const result = parseGenerateResult(data);
- attachRequestMetadata([result], response.headers);
+ attachRequestMetadata([result], response.headers, data);
return result;
}
@@ -1047,7 +1160,7 @@ export class SIEClient {
if (data === null || typeof data !== "object") {
throw new RequestError("Unexpected chat.completion response shape");
}
- attachRequestMetadata([data], response.headers);
+ attachRequestMetadata([data], response.headers, data);
return data;
}
@@ -1449,7 +1562,7 @@ export class SIEClient {
const data = unpackMessage<unknown>(new Uint8Array(await response.arrayBuffer()));
const result = parseScoreResult(data);
- attachRequestMetadata([result], response.headers);
+ attachRequestMetadata([result], response.headers, data);
return result;
}
@@ -1542,7 +1655,7 @@ export class SIEClient {
const data = unpackMessage<WireResponse>(new Uint8Array(await response.arrayBuffer()));
const results = parseExtractResults(data.items);
- attachRequestMetadata(results, response.headers);
+ attachRequestMetadata(results, response.headers, data);
if (isSingleItem) {
const first = results[0];
@@ -2305,12 +2418,20 @@ export class SIEClient {
// (`/v1/jobs`); connections ride the control plane (`/internal/orgs/{org}/…`).
// ---------------------------------------------------------------------------
- /** One JSON request over `fetch` (bearer auth reused; absolute or base-relative URL). */
+ /**
+ * One JSON request over `fetch` (bearer auth reused; absolute or
+ * base-relative URL).
+ *
+ * `onError` runs BEFORE the generic {@link handleError} dispatch, so a route
+ * with its own typed failure taxonomy (the #2435 cost estimate's unroutable
+ * verdict) can short-circuit without a second copy of this request path.
+ */
private async jsonRequest<T>(
target: string,
method: "GET" | "POST" | "DELETE",
body?: unknown,
timeoutMs: number = this.timeout,
+ onError?: (response: Response) => Promise<void>,
): Promise<T> {
const url = target.startsWith("http") ? target : `${this.baseUrl}${target}`;
const headers: Record<string, string> = {
@@ -2330,6 +2451,7 @@ export class SIEClient {
try {
const response = await fetch(url, init);
if (!response.ok) {
+ if (onError) await onError(response);
await handleError(response);
}
this.checkServerVersion(response);
@@ -2594,6 +2716,38 @@ export class SIEClient {
return this.jsonRequest<SIEFile>(`/v1/files/${encodeURIComponent(fileId)}`, "GET");
}
+ private async fileList(options?: {
+ after?: string;
+ limit?: number;
+ order?: "asc" | "desc";
+ purpose?: string;
+ }): Promise<SIEFile[]> {
+ return (await this.fileListPage(options)).data ?? [];
+ }
+
+ private async fileListPage(options?: {
+ after?: string;
+ limit?: number;
+ order?: "asc" | "desc";
+ purpose?: string;
+ }): Promise<FileList> {
+ const query = new URLSearchParams();
+ if (options?.after !== undefined) query.set("after", options.after);
+ if (options?.limit !== undefined) query.set("limit", String(options.limit));
+ if (options?.order !== undefined) query.set("order", options.order);
+ if (options?.purpose !== undefined) query.set("purpose", options.purpose);
+ const suffix = query.size > 0 ? `?${query.toString()}` : "";
+ const data = await this.jsonRequest<FileList | SIEFile[]>(`/v1/files${suffix}`, "GET");
+ if (!Array.isArray(data)) return data;
+ return {
+ object: "list",
+ data,
+ first_id: data[0]?.id ?? null,
+ last_id: data.at(-1)?.id ?? null,
+ has_more: false,
+ };
+ }
+
private async fileContent(fileId: string): Promise<Uint8Array> {
return this.rawGetBytes(`/v1/files/${encodeURIComponent(fileId)}/content`);
}
@@ -2628,9 +2782,30 @@ export class SIEClient {
return this.jsonRequest<Batch>(`/v1/batches/${encodeURIComponent(batchId)}`, "GET");
}
- private async batchList(): Promise<Batch[]> {
- const data = await this.jsonRequest<{ object?: string; data?: Batch[] }>("/v1/batches", "GET");
- return Array.isArray(data) ? data : (data.data ?? []);
+ private async batchList(options?: {
+ after?: string;
+ limit?: number;
+ }): Promise<Batch[]> {
+ return (await this.batchListPage(options)).data ?? [];
+ }
+
+ private async batchListPage(options?: {
+ after?: string;
+ limit?: number;
+ }): Promise<BatchList> {
+ const query = new URLSearchParams();
+ if (options?.after !== undefined) query.set("after", options.after);
+ if (options?.limit !== undefined) query.set("limit", String(options.limit));
+ const suffix = query.size > 0 ? `?${query.toString()}` : "";
+ const data = await this.jsonRequest<BatchList | Batch[]>(`/v1/batches${suffix}`, "GET");
+ if (!Array.isArray(data)) return data;
+ return {
+ object: "list",
+ data,
+ first_id: data[0]?.id ?? null,
+ last_id: data.at(-1)?.id ?? null,
+ has_more: false,
+ };
}
private async batchCancel(batchId: string): Promise<Batch> {
diff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.ts
index 1588e9da0..2886ef636 100644
--- a/packages/sie_ts_sdk/src/errors.ts
+++ b/packages/sie_ts_sdk/src/errors.ts
@@ -328,3 +328,26 @@ export class InputTooLongError extends RequestError {
this.model = options?.model;
}
}
+
+/**
+ * The gateway cannot PRICE the request, so it will not run it either.
+ *
+ * Thrown by {@link SIEClient.estimate} when the dry run answers `503`: the
+ * active rate book declares no rate for the request's
+ * (model, profile, operation, region) identity, or the planner cannot bound one
+ * of the dimensions that book DOES price (an unbounded generation input, say,
+ * or a sealed lane whose GPU class is unresolved).
+ *
+ * This is deliberately the same verdict the real request would get — the
+ * estimate runs the live planner — so treat it as "this request is not sellable
+ * right now", not as an estimator limitation. `message` is the planner's own
+ * reason, naming the unpriced identity or the dimension it could not bound.
+ *
+ * Subclass of {@link ServerError} so existing 5xx handlers keep working.
+ */
+export class EstimateUnroutableError extends ServerError {
+ constructor(message: string, code?: string) {
+ super(message, code, 503);
+ this.name = "EstimateUnroutableError";
+ }
+}
diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.ts
index ead1ea97d..f326c5a06 100644
--- a/packages/sie_ts_sdk/src/index.ts
+++ b/packages/sie_ts_sdk/src/index.ts
@@ -94,6 +94,7 @@ export type {
ConnectionRevoked,
// Files (client.files) — OpenAI-compatible file objects
File as SIEFile,
+ FileList,
FileDeleted,
// Batches (client.batches) — OpenAI-compatible batch objects
Batch,
@@ -133,6 +134,10 @@ export type {
ChatCompletionChunk,
ChatChunkChoice,
ChatDelta,
+ // Cost-estimate dry run (client.estimate)
+ AppliedRate,
+ RateIdentity,
+ CostEstimate,
} from "./types.js";
// Utility functions
@@ -162,6 +167,7 @@ export {
ResourceExhaustedError,
SIEStreamError,
InputTooLongError,
+ EstimateUnroutableError,
} from "./errors.js";
// Client-side scoring (MaxSim for ColBERT-style models)
diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.ts
index ac79a8dcf..e45de848e 100644
--- a/packages/sie_ts_sdk/src/internal/parsing.ts
+++ b/packages/sie_ts_sdk/src/internal/parsing.ts
@@ -3,6 +3,7 @@
*/
import {
+ EstimateUnroutableError,
InputTooLongError,
ModelLoadFailedError,
ProvisioningError,
@@ -176,6 +177,66 @@ export async function throwIfInputTooLong(response: Response, model?: string): P
throw new InputTooLongError(message, { model });
}
+/** The one exact path of the cost-estimate dry run (#2435). */
+export const ESTIMATE_PATH = "/v1/estimate";
+
+/**
+ * Error codes the gateway answers when it cannot PRICE a request.
+ *
+ * Both are the live billing path's own "this request is not sellable" verdict.
+ * A slab-capacity 503 (`BILLING_CAPACITY_UNAVAILABLE`) is a retryable gateway
+ * condition and deliberately stays a plain {@link ServerError}.
+ */
+const ESTIMATE_UNROUTABLE_ERROR_CODES = new Set(["QUEUE_UNAVAILABLE"]);
+
+/**
+ * The `POST /v1/estimate` envelope: the target path plus its verbatim body.
+ *
+ * The gateway prices whatever `request` would have been sent to `endpoint`, so
+ * the SDK does NOT reshape it. Anything normalized on the way in would be
+ * something the quote priced and the request never sent.
+ *
+ * @throws {TypeError} If the envelope arguments are malformed — a caller
+ * mistake about WHAT is being priced, caught here rather than as a 400.
+ */
+export function buildEstimateEnvelope(
+ endpoint: string,
+ request: Record<string, unknown>,
+): { endpoint: string; request: Record<string, unknown> } {
+ if (typeof endpoint !== "string" || !endpoint.startsWith("/")) {
+ throw new TypeError(`estimate endpoint must be the exact target path (got ${endpoint})`);
+ }
+ if (request === null || typeof request !== "object" || Array.isArray(request)) {
+ throw new TypeError("estimate request must be the target request body object");
+ }
+ return { endpoint, request: { ...request } };
+}
+
+/**
+ * Throw {@link EstimateUnroutableError} for an estimate the active rate book
+ * cannot price. No-op for any other status / error code.
+ *
+ * Short-circuits {@link handleError}'s generic 5xx dispatch so callers can
+ * catch "this request is not sellable" specifically, without string-matching a
+ * code. The message is the planner's own reason.
+ */
+export async function throwIfEstimateUnroutable(response: Response): Promise<void> {
+ if (response.status !== 503) return;
+ // The SHARED code reader, so this follows the same `X-SIE-Error-Code`
+ // header-over-body precedence (and the same normalization) as `handleError`
+ // and the Python twin's `get_error_code`. Reading `detail.code` directly
+ // would classify an edge-normalized code differently in one SDK than the
+ // other. `detail` is kept only for the fallback message.
+ const code = await getErrorCode(response.clone());
+ if (code === undefined || !ESTIMATE_UNROUTABLE_ERROR_CODES.has(code)) return;
+ const detail = await getErrorDetail(response.clone());
+ const message =
+ detail && typeof detail.message === "string"
+ ? detail.message
+ : "the active rate book cannot price this request";
+ throw new EstimateUnroutableError(message, code);
+}
+
/**
* Handle HTTP error response and throw appropriate error
*/
@@ -526,6 +587,26 @@ function describeType(value: unknown): string {
* coercion: keep only finite numbers and truncate toward zero; everything
* else (string, NaN, Infinity, null) becomes `0`.
*/
+/**
+ * The settled charge (#2434) carried by one wire `usage` block, as camelCase
+ * fields ready to spread into a parsed block.
+ *
+ * Both halves are required: a charge with no book version cannot be reconciled,
+ * and a version with no charge describes nothing. Anything malformed yields an
+ * empty object, so absence stays absence.
+ */
+export function settledChargeFields(usage: unknown): {
+ creditsCharged?: number;
+ rateBookVersion?: string;
+} {
+ if (typeof usage !== "object" || usage === null || Array.isArray(usage)) return {};
+ const credits = (usage as Record<string, unknown>).credits_charged;
+ const version = (usage as Record<string, unknown>).rate_book_version;
+ if (typeof credits !== "number" || !Number.isSafeInteger(credits) || credits < 0) return {};
+ if (typeof version !== "string" || version.length === 0) return {};
+ return { creditsCharged: credits, rateBookVersion: version };
+}
+
function coerceTokenCount(v: unknown): number {
return typeof v === "number" && Number.isFinite(v) ? Math.trunc(v) : 0;
}
@@ -552,6 +633,10 @@ export function parseGenerateResult(data: Record<string, unknown>): GenerateResu
promptTokens: coerceTokenCount(usage.prompt_tokens),
completionTokens: coerceTokenCount(usage.completion_tokens),
totalTokens: coerceTokenCount(usage.total_tokens),
+ // #2434: the gateway merges the settled charge into this same block, so
+ // rebuilding it field-by-field must carry the charge across. Absence
+ // stays absence — a request that committed no debit gets neither key.
+ ...settledChargeFields(usage),
},
attemptId: wire.attempt_id,
ttftMs: wire.ttft_ms,
diff --git a/packages/sie_ts_sdk/src/jobs.ts b/packages/sie_ts_sdk/src/jobs.ts
index 4d85f1e23..fc0841a70 100644
--- a/packages/sie_ts_sdk/src/jobs.ts
+++ b/packages/sie_ts_sdk/src/jobs.ts
@@ -87,7 +87,18 @@ export interface JobChunk {
state?: string;
ref?: string | null;
units?: number | null;
- credits?: number | null;
+ /**
+ * Exact credits committed for this chunk, or `null` until the chunk's
+ * settlement is acknowledged. A job settles per chunk, so these sum to the
+ * job's `settled_credits` exactly. (Wire-shape field, like the rest of this
+ * interface — snake_case as the API sends it.)
+ */
+ credits_charged?: number | null;
+ /**
+ * Immutable rate-book version that rated `credits_charged`. Present exactly
+ * when `credits_charged` is.
+ */
+ rate_book_version?: string | null;
error?: unknown;
}
@@ -383,7 +394,8 @@ export function jobChunks(jobDoc: JobStatus): JobChunk[] {
state: chunk.state,
ref: chunk.ref,
units: chunk.units,
- credits: chunk.credits,
+ credits_charged: chunk.credits_charged,
+ rate_book_version: chunk.rate_book_version,
error: chunk.error ?? null,
}));
}
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index a33b08b2d..3a4ce05df 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -105,7 +105,25 @@ export interface TimingInfo {
inferenceMs?: number;
}
-/** Authoritative units settled for one completed HTTP request. */
+/**
+ * Authoritative units settled for one completed HTTP request.
+ *
+ * `creditsCharged`/`rateBookVersion` are the SETTLED charge as this response
+ * BODY reported it — never an estimate, never a reservation, and never
+ * fabricated. They are published whenever the gateway could write them into
+ * this body, including on a billing-fault response, where dispatches that rated
+ * cleanly are burned before the fault is returned, so the charge is real even
+ * though the result was not delivered. An explicit `0` is a settlement that
+ * cost nothing.
+ *
+ * Their ABSENCE means the body did not carry a settled charge — NOT that
+ * nothing was charged. A body the gateway must leave byte-for-byte intact (an
+ * opaque content type, one it cannot safely rewrite or buffer) still settles
+ * and still charges, and reports the debit only in the `x-sie-credits-debited`
+ * header. Read `RequestMetadata.creditsDebited` for the authoritative answer:
+ * the SDK fills it from this block when present and from that header
+ * otherwise, so it is absent only when nothing was charged.
+ */
export interface RequestUsage {
inputTokens?: number;
pairs?: number;
@@ -113,6 +131,8 @@ export interface RequestUsage {
pages?: number;
outputTokens?: number;
audioMs?: number;
+ creditsCharged?: number;
+ rateBookVersion?: string;
}
/** Optional gateway metadata from the successful terminal response. */
@@ -121,7 +141,19 @@ export interface RequestMetadata {
/** Worker-origin immutable release/runtime identity digest. */
executionIdentitySha256?: string;
usage?: RequestUsage;
+ /**
+ * Exact committed debit — the authoritative charge for this request.
+ * Body-first (`usage.credits_charged`), falling back to the
+ * `x-sie-credits-debited` header, which the gateway sets on every
+ * non-streamed response whose settlement committed (including billing-fault
+ * responses and bodies it left untouched). The two always agree when both
+ * are present. Absence here — unlike absence inside `usage` — does mean
+ * nothing was charged. Streamed responses carry no headers at all: their
+ * charge rides the terminal usage chunk.
+ */
creditsDebited?: number;
+ /** Immutable rate-book version that rated `creditsDebited`, when reported. */
+ rateBookVersion?: string;
}
/**
@@ -633,6 +665,15 @@ export interface File {
expires_at?: number;
}
+/** The listing envelope from `GET /v1/files` (OpenAI cursor page). */
+export interface FileList {
+ object?: string;
+ data?: File[];
+ first_id?: string | null;
+ last_id?: string | null;
+ has_more?: boolean;
+}
+
/** The envelope from deleting a file (OpenAI `FileDeleted`). */
export interface FileDeleted {
id?: string;
@@ -680,8 +721,8 @@ export interface Batch {
export interface BatchList {
object?: string;
data?: Batch[];
- first_id?: string;
- last_id?: string;
+ first_id?: string | null;
+ last_id?: string | null;
has_more?: boolean;
}
@@ -720,11 +761,21 @@ export interface ScoreOptions {
/** Reason the generation terminated. */
export type FinishReason = "stop" | "length" | "cancelled" | "content_filter" | "error";
-/** Token usage for a single generation call. */
+/**
+ * Token usage for a single generation call.
+ *
+ * `creditsCharged`/`rateBookVersion` ride the same block on a settled response.
+ * An explicit `0` is a settlement that cost nothing; nothing here is ever an
+ * estimate or a fabricated zero. Absence means this block did not carry the
+ * charge, NOT that nothing was charged — read `RequestMetadata.creditsDebited`,
+ * which also covers responses whose body the gateway left untouched.
+ */
export interface GenerationUsage {
promptTokens: number;
completionTokens: number;
totalTokens: number;
+ creditsCharged?: number;
+ rateBookVersion?: string;
}
interface GrammarMetadata {
@@ -1016,11 +1067,30 @@ export interface ChatCompletionRequest {
prompt_cache_key?: string;
}
-/** Token usage block (snake_case, matches the wire shape). */
+/**
+ * Token usage block (snake_case, matches the wire shape).
+ *
+ * On a settled managed response this block also carries the exact committed
+ * debit and the immutable book that rated it (#2434) — including on the
+ * terminal chunk of a stream that opted into `stream_options.include_usage`,
+ * which is the only place a streamed request can report what it cost. An
+ * explicit `0` is a settlement that cost nothing; nothing here is ever an
+ * estimate or a fabricated zero.
+ *
+ * Absence means this block did not carry the charge, NOT that nothing was
+ * charged. On a buffered call read `RequestMetadata.creditsDebited`. On a
+ * stream there is no header to fall back to: without
+ * `stream_options.include_usage` there is no usage chunk at all, and a stream
+ * whose terminal settle did not commit in time reports its tokens without a
+ * charge rather than guessing one. `GET /me/usage` remains the balance
+ * authority.
+ */
export interface ChatUsage {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
+ credits_charged?: number;
+ rate_book_version?: string;
}
/** A single choice in a `ChatCompletion` (non-streaming). */
@@ -1164,6 +1234,64 @@ export interface ExtractOptions {
// Utility Types
// ---------------------------------------------------------------------------
+// ---------------------------------------------------------------------------
+// Cost-estimate dry run (`POST /v1/estimate`, #2435)
+// ---------------------------------------------------------------------------
+
+/**
+ * One priced dimension's exact rational rate from the active rate book.
+ *
+ * Credits are integers, so rates are exact rationals rather than floats:
+ * `rate_numerator / rate_denominator` credits per unit. If you re-derive a
+ * total client-side, multiply and round ONCE — never per unit.
+ *
+ * Wire-shaped (snake_case) like {@link JobPreflight}: this is the gateway's
+ * `ReservationPlan` projection, echoed verbatim.
+ */
+export interface AppliedRate {
+ unit: string;
+ rate_numerator: number;
+ rate_denominator: number;
+}
+
+/** The rate-book row set a request is priced under. */
+export interface RateIdentity {
+ model: string;
+ profile: string;
+ operation: string;
+ region: string;
+}
+
+/**
+ * A dispatch-free quote from `POST /v1/estimate`.
+ *
+ * The gateway prices the request through the SAME reservation planner the
+ * metered path runs, against the SAME active rate book, and returns the plan
+ * instead of holding it — no dispatch, no reservation, no credits consumed.
+ *
+ * `estimated_credits` is the CONSERVATIVE ceiling the live path would hold.
+ * Settlement bills the worker-authoritative counts against that plan and
+ * releases the remainder, so the real charge is at most this number.
+ *
+ * `minimum_billed_units` is present only for duration-priced (sealed custom
+ * lane, `gpu_second`) identities, where a dry run cannot know the request's
+ * duration: there the quote is a rate card — `applied_rates` plus this
+ * per-request floor — and `unit_ceilings` is the whole-window hold, not a
+ * prediction. `estimate_basis` says which of the two you are reading.
+ */
+export interface CostEstimate {
+ endpoint: string;
+ identity: RateIdentity;
+ estimated_credits: number;
+ unit_ceilings: Record<string, number>;
+ applied_rates: AppliedRate[];
+ rate_book_version: string;
+ rate_book_sha256: string;
+ rounding_rule: string;
+ estimate_basis: string;
+ minimum_billed_units?: Record<string, number> | null;
+}
+
/**
* Helper to convert typed arrays to regular number array.
* Useful for JSON serialization or working with libraries that expect number[].
diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.ts
index bd50f9edd..2ad9dec38 100644
--- a/packages/sie_ts_sdk/src/version.ts
+++ b/packages/sie_ts_sdk/src/version.ts
@@ -1 +1 @@
-export const SDK_VERSION = "0.6.24"; // x-release-please-version
+export const SDK_VERSION = "0.6.25"; // x-release-please-version
diff --git a/packages/sie_ts_sdk/tests/batches.test.ts b/packages/sie_ts_sdk/tests/batches.test.ts
index 5f3e4106b..27f937b14 100644
--- a/packages/sie_ts_sdk/tests/batches.test.ts
+++ b/packages/sie_ts_sdk/tests/batches.test.ts
@@ -80,4 +80,53 @@ describe("client.batches", () => {
expect(batches.map((b) => b.id)).toEqual(["batch-1", "batch-2"]);
expect(mockFetch.mock.calls[0][0]).toBe("http://gw:8080/v1/batches");
});
+
+ it("list encodes cursor arguments and preserves the array return", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({
+ object: "list",
+ data: [{ id: "batch-2" }],
+ first_id: "batch-2",
+ last_id: "batch-2",
+ has_more: false,
+ }),
+ );
+ const client = new SIEClient(GW);
+ const batches = await client.batches.list({
+ after: 'batch/"a b"&limit=1',
+ limit: 9,
+ });
+ expect(batches.map((batch) => batch.id)).toEqual(["batch-2"]);
+ expect(mockFetch.mock.calls[0][0]).toBe(
+ "http://gw:8080/v1/batches?after=batch%2F%22a+b%22%26limit%3D1&limit=9",
+ );
+ });
+
+ it("listPage exposes cursor metadata", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({
+ object: "list",
+ data: [{ id: "batch-1" }, { id: "batch-2" }],
+ first_id: "batch-1",
+ last_id: "batch-2",
+ has_more: true,
+ }),
+ );
+ const client = new SIEClient(GW);
+ const page = await client.batches.listPage();
+ expect(page.data?.map((batch) => batch.id)).toEqual(["batch-1", "batch-2"]);
+ expect(page.first_id).toBe("batch-1");
+ expect(page.last_id).toBe("batch-2");
+ expect(page.has_more).toBe(true);
+ });
+
+ it("listPage normalizes an empty legacy bare array", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse([]));
+ const client = new SIEClient(GW);
+ const page = await client.batches.listPage();
+ expect(page.data).toEqual([]);
+ expect(page.first_id).toBeNull();
+ expect(page.last_id).toBeNull();
+ expect(page.has_more).toBe(false);
+ });
});
diff --git a/packages/sie_ts_sdk/tests/estimate.test.ts b/packages/sie_ts_sdk/tests/estimate.test.ts
new file mode 100644
index 000000000..f33564fb6
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/estimate.test.ts
@@ -0,0 +1,316 @@
+/**
+ * Tests for the cost-estimate dry run (`POST /v1/estimate`, #2435).
+ *
+ * The SDK's job on this route is narrow and load-bearing:
+ * - send the target request VERBATIM inside `{endpoint, request}` — a body the
+ * SDK reshaped would be a quote for a request the caller never sends;
+ * - return the gateway's projection unchanged, so the customer reads the same
+ * ceiling the metered path would hold;
+ * - map "the book cannot price this" onto a typed {@link EstimateUnroutableError}
+ * rather than a generic 5xx, because that verdict is the request's, not the
+ * estimator's.
+ */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+import { EstimateUnroutableError, RequestError, SIEError, ServerError } from "../src/errors.js";
+import { buildEstimateEnvelope, throwIfEstimateUnroutable } from "../src/internal/parsing.js";
+import type { CostEstimate } from "../src/types.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+const QUOTE: CostEstimate = {
+ endpoint: "/v1/encode/BAAI/bge-m3",
+ identity: {
+ model: "BAAI/bge-m3",
+ profile: "default",
+ operation: "encode",
+ region: "us",
+ },
+ estimated_credits: 261,
+ unit_ceilings: { input_tokens: 261 },
+ applied_rates: [{ unit: "input_tokens", rate_numerator: 1, rate_denominator: 1 }],
+ rate_book_version: "2026-07-26-production-bootstrap-v2",
+ rate_book_sha256: "a".repeat(64),
+ rounding_rule: "ceil-once-per-terminal-event",
+ estimate_basis: "conservative pre-dispatch reservation ceiling",
+ minimum_billed_units: null,
+};
+
+const UNROUTABLE = {
+ detail: {
+ code: "QUEUE_UNAVAILABLE",
+ message:
+ 'missing rate for model="acme/unpriced", profile="default", operation="encode", region="us"',
+ },
+};
+
+function jsonResponse(status: number, body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+/**
+ * The error a rejecting call MUST produce.
+ *
+ * A bare `.catch(e => e as X)` binds the RESOLVED quote when the call
+ * unexpectedly succeeds, so the assertions that follow read as type confusion
+ * instead of "no error was thrown". This fails on the spot instead.
+ */
+async function rejection<T>(call: Promise<unknown>): Promise<T> {
+ let resolved: unknown;
+ let caught: unknown;
+ let threw = false;
+ try {
+ resolved = await call;
+ } catch (error) {
+ threw = true;
+ caught = error;
+ }
+ // Asserted OUTSIDE the try, so the failure cannot be caught and returned as
+ // if it were the error under test.
+ if (!threw) expect.fail(`expected a rejection, got ${JSON.stringify(resolved)}`);
+ return caught as T;
+}
+
+function sentBody(): { endpoint: string; request: Record<string, unknown> } {
+ const init = mockFetch.mock.calls[0][1] as RequestInit;
+ return JSON.parse(init.body as string);
+}
+
+describe("estimate envelope", () => {
+ it("carries the target body verbatim", () => {
+ const request = { items: [{ text: "Hello" }], params: { output_types: ["dense"] } };
+ expect(buildEstimateEnvelope("/v1/encode/BAAI/bge-m3", request)).toEqual({
+ endpoint: "/v1/encode/BAAI/bge-m3",
+ request,
+ });
+ });
+
+ it("detaches the caller object so a later mutation cannot change what was priced", () => {
+ const request: Record<string, unknown> = { items: [{ text: "Hello" }] };
+ const envelope = buildEstimateEnvelope("/v1/encode/m", request);
+ request.items = [];
+ expect(envelope.request.items).toEqual([{ text: "Hello" }]);
+ });
+
+ it.each([
+ ["v1/encode/m", { items: [] }],
+ ["", { items: [] }],
+ ["/v1/encode/m", ["not", "an", "object"]],
+ ["/v1/encode/m", null],
+ ])("rejects a malformed envelope client-side (%s)", (endpoint, request) => {
+ expect(() =>
+ buildEstimateEnvelope(endpoint as string, request as Record<string, unknown>),
+ ).toThrow(TypeError);
+ });
+});
+
+describe("EstimateUnroutableError class", () => {
+ it("is a ServerError and SIEError", () => {
+ const err = new EstimateUnroutableError("nope", "QUEUE_UNAVAILABLE");
+ expect(err).toBeInstanceOf(ServerError);
+ expect(err).toBeInstanceOf(SIEError);
+ expect(err).toBeInstanceOf(Error);
+ expect(err.name).toBe("EstimateUnroutableError");
+ expect(err.code).toBe("QUEUE_UNAVAILABLE");
+ expect(err.statusCode).toBe(503);
+ });
+});
+
+describe("throwIfEstimateUnroutable", () => {
+ it("throws on an unpriced identity and preserves the planner's reason", async () => {
+ await expect(throwIfEstimateUnroutable(jsonResponse(503, UNROUTABLE))).rejects.toThrow(
+ /acme\/unpriced/,
+ );
+ });
+
+ it("is a no-op for a retryable billing-capacity 503", async () => {
+ const capacity = {
+ detail: {
+ code: "BILLING_CAPACITY_UNAVAILABLE",
+ message: "audio billing preflight is at capacity",
+ },
+ };
+ await expect(throwIfEstimateUnroutable(jsonResponse(503, capacity))).resolves.toBeUndefined();
+ });
+
+ it("is a no-op for retryable provisioning capacity", async () => {
+ const capacity = {
+ detail: {
+ code: "PROVISIONING",
+ message: "a matching worker is scaling from zero",
+ },
+ };
+ await expect(throwIfEstimateUnroutable(jsonResponse(503, capacity))).resolves.toBeUndefined();
+ });
+
+ it("is a no-op for non-503 responses", async () => {
+ await expect(
+ throwIfEstimateUnroutable(jsonResponse(400, { detail: { code: "QUEUE_UNAVAILABLE" } })),
+ ).resolves.toBeUndefined();
+ });
+});
+
+describe("client.estimate", () => {
+ beforeEach(() => {
+ mockFetch.mockClear();
+ });
+
+ it("posts the envelope to /v1/estimate and returns the quote", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(200, QUOTE));
+ const client = new SIEClient("http://localhost:8080");
+
+ const quote = await client.estimate("/v1/encode/BAAI/bge-m3", {
+ items: [{ text: "Hello" }],
+ });
+
+ expect(quote).toEqual(QUOTE);
+ expect(quote.estimated_credits).toBe(261);
+ expect(quote.unit_ceilings).toEqual({ input_tokens: 261 });
+ expect(quote.applied_rates[0].rate_denominator).toBe(1);
+ expect(mockFetch.mock.calls[0][0]).toBe("http://localhost:8080/v1/estimate");
+ expect((mockFetch.mock.calls[0][1] as RequestInit).method).toBe("POST");
+ expect(sentBody()).toEqual({
+ endpoint: "/v1/encode/BAAI/bge-m3",
+ request: { items: [{ text: "Hello" }] },
+ });
+ });
+
+ it("passes an OpenAI-compatible body through untouched (model stays in the body)", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(200, QUOTE));
+ const client = new SIEClient("http://localhost:8080");
+ const body = {
+ model: "Qwen/Qwen3.6-27B",
+ messages: [{ role: "user", content: "hi" }],
+ max_tokens: 64,
+ n: 3,
+ };
+
+ await client.estimate("/v1/chat/completions", body);
+
+ expect(sentBody()).toEqual({ endpoint: "/v1/chat/completions", request: body });
+ });
+
+ it("throws EstimateUnroutableError for an unpriced identity", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(503, UNROUTABLE));
+ const client = new SIEClient("http://localhost:8080");
+
+ await expect(
+ client.estimate("/v1/encode/acme/unpriced", { items: [{ text: "Hello" }] }),
+ ).rejects.toThrowError(EstimateUnroutableError);
+
+ mockFetch.mockResolvedValueOnce(jsonResponse(503, UNROUTABLE));
+ const error = await rejection<EstimateUnroutableError>(
+ client.estimate("/v1/encode/acme/unpriced", { items: [{ text: "Hello" }] }),
+ );
+ expect(error.code).toBe("QUEUE_UNAVAILABLE");
+ expect(error.statusCode).toBe(503);
+ expect(error.message).toContain("acme/unpriced");
+ expect(error).toBeInstanceOf(ServerError);
+ });
+
+ it("leaves a retryable billing-capacity 503 as a plain ServerError", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse(503, {
+ detail: {
+ code: "BILLING_CAPACITY_UNAVAILABLE",
+ message: "audio billing preflight is at capacity",
+ },
+ }),
+ );
+ const client = new SIEClient("http://localhost:8080");
+
+ const error = await rejection<ServerError>(
+ client.estimate("/v1/extract/audio/asr", { items: [{ text: "x" }] }),
+ );
+ expect(error).toBeInstanceOf(ServerError);
+ expect(error).not.toBeInstanceOf(EstimateUnroutableError);
+ expect(error.code).toBe("BILLING_CAPACITY_UNAVAILABLE");
+ });
+
+ it("surfaces an unroutable model as a 404 RequestError, not a quote", async () => {
+ // The gateway checks routability, not just priceability: a model this data
+ // plane does not serve answers the live 404 even when the rate book prices
+ // it. A regression that turned that into a 200 quote would otherwise pass.
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse(404, {
+ detail: { code: "MODEL_NOT_FOUND", message: 'Model "acme/absent" not found.' },
+ }),
+ );
+ const client = new SIEClient("http://localhost:8080");
+
+ const error = await rejection<RequestError>(
+ client.estimate("/v1/encode/acme/absent", { items: [{ text: "Hello" }] }),
+ );
+ expect(error).toBeInstanceOf(RequestError);
+ expect(error).not.toBeInstanceOf(EstimateUnroutableError);
+ expect(error.statusCode).toBe(404);
+ expect(error.code).toBe("MODEL_NOT_FOUND");
+ });
+
+ it("surfaces a malformed target body as a RequestError", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse(400, {
+ detail: { code: "INVALID_REQUEST", message: "'items' must be an array" },
+ }),
+ );
+ const client = new SIEClient("http://localhost:8080");
+
+ const error = await rejection<RequestError>(
+ client.estimate("/v1/encode/BAAI/bge-m3", { items: "nope" }),
+ );
+ expect(error).toBeInstanceOf(RequestError);
+ expect(error.code).toBe("INVALID_REQUEST");
+ expect(error.statusCode).toBe(400);
+ });
+
+ it("returns a sealed rate card with its minimum-billed floor", async () => {
+ const sealed: CostEstimate = {
+ ...QUOTE,
+ endpoint: "/v1/generate/org-42/support-gen",
+ identity: {
+ model: "custom.l4",
+ profile: "default",
+ operation: "sealed",
+ region: "us",
+ },
+ unit_ceilings: { gpu_second: 130 },
+ applied_rates: [{ unit: "gpu_second", rate_numerator: 7, rate_denominator: 1 }],
+ estimated_credits: 910,
+ minimum_billed_units: { gpu_second: 1 },
+ estimate_basis: "sealed custom-lane rate card; duration is execution-dependent",
+ };
+ mockFetch.mockResolvedValueOnce(jsonResponse(200, sealed));
+ const client = new SIEClient("http://localhost:8080");
+
+ const quote = await client.estimate("/v1/generate/org-42/support-gen", {
+ prompt: "hi",
+ max_new_tokens: 32,
+ });
+
+ expect(quote.minimum_billed_units).toEqual({ gpu_second: 1 });
+ expect(quote.applied_rates[0].unit).toBe("gpu_second");
+ expect(quote.estimate_basis).toContain("duration");
+ });
+
+ it("rejects a malformed envelope before touching the network", async () => {
+ const client = new SIEClient("http://localhost:8080");
+ await expect(client.estimate("v1/encode/m", { items: [] })).rejects.toThrow(TypeError);
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it("sends the bearer token like every other authenticated route", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(200, QUOTE));
+ const client = new SIEClient("http://localhost:8080", { apiKey: "sk-sie-test" });
+
+ await client.estimate("/v1/encode/BAAI/bge-m3", { items: [{ text: "Hello" }] });
+
+ const headers = (mockFetch.mock.calls[0][1] as RequestInit).headers as Record<string, string>;
+ expect(headers.Authorization).toBe("Bearer sk-sie-test");
+ expect(headers["Content-Type"]).toBe("application/json");
+ });
+});
diff --git a/packages/sie_ts_sdk/tests/files.test.ts b/packages/sie_ts_sdk/tests/files.test.ts
index 13e285091..b622ffe7e 100644
--- a/packages/sie_ts_sdk/tests/files.test.ts
+++ b/packages/sie_ts_sdk/tests/files.test.ts
@@ -72,6 +72,59 @@ describe("client.files", () => {
expect(mockFetch.mock.calls[1][1].method).toBe("DELETE");
});
+ it("list encodes cursor and filter arguments and preserves the array return", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({
+ object: "list",
+ data: [FILE],
+ first_id: "file-abc",
+ last_id: "file-abc",
+ has_more: true,
+ }),
+ );
+ const client = new SIEClient(GW);
+ const files = await client.files.list({
+ after: 'file/"a b"&purpose=x',
+ limit: 7,
+ order: "asc",
+ purpose: "batch",
+ });
+ expect(files.map((file) => file.id)).toEqual(["file-abc"]);
+ expect(mockFetch.mock.calls[0][0]).toBe(
+ "http://gw:8080/v1/files?after=file%2F%22a+b%22%26purpose%3Dx&limit=7&order=asc&purpose=batch",
+ );
+ });
+
+ it("listPage exposes cursor metadata", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({
+ object: "list",
+ data: [FILE],
+ first_id: "file-abc",
+ last_id: "file-abc",
+ has_more: true,
+ }),
+ );
+ const client = new SIEClient(GW);
+ const page = await client.files.listPage();
+ expect(page.data?.map((file) => file.id)).toEqual(["file-abc"]);
+ expect(page.first_id).toBe("file-abc");
+ expect(page.last_id).toBe("file-abc");
+ expect(page.has_more).toBe(true);
+ });
+
+ it("listPage normalizes a legacy bare array", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse([FILE, { ...FILE, id: "file-def", filename: "next.jsonl" }]),
+ );
+ const client = new SIEClient(GW);
+ const page = await client.files.listPage();
+ expect(page.data?.map((file) => file.id)).toEqual(["file-abc", "file-def"]);
+ expect(page.first_id).toBe("file-abc");
+ expect(page.last_id).toBe("file-def");
+ expect(page.has_more).toBe(false);
+ });
+
it("content returns the raw file bytes", async () => {
const payload = new TextEncoder().encode('{"custom_id":"a","response":{"status_code":200}}\n');
mockFetch.mockResolvedValueOnce(new Response(payload, { status: 200 }));
diff --git a/packages/sie_ts_sdk/tests/settledCharge.test.ts b/packages/sie_ts_sdk/tests/settledCharge.test.ts
new file mode 100644
index 000000000..ecc1fe779
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/settledCharge.test.ts
@@ -0,0 +1,171 @@
+/**
+ * The settled charge surfaced in a response's `usage` block (#2434).
+ *
+ * The gateway publishes `usage.credits_charged` + `usage.rate_book_version` on
+ * every settled response and keeps the `x-sie-credits-debited` header
+ * unchanged for compatibility. The SDK reads the body first — it is the only
+ * source that also names the rate book — and falls back to the header for a
+ * gateway that predates in-body surfacing. All tests use a mocked `fetch`.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+import type { ChatCompletion } from "../src/types.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+const BOOK = "2026-07-22-production-bootstrap-v1";
+
+function completion(usage: Record<string, unknown>): ChatCompletion {
+ return {
+ id: "chatcmpl-settled",
+ object: "chat.completion",
+ created: 1_700_000_000,
+ model: "m",
+ system_fingerprint: null,
+ choices: [
+ {
+ index: 0,
+ message: { role: "assistant", content: "hi" },
+ finish_reason: "stop",
+ logprobs: null,
+ },
+ ],
+ usage: usage as ChatCompletion["usage"],
+ };
+}
+
+function jsonResponse(body: unknown, headers: Record<string, string> = {}): Response {
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json", ...headers },
+ });
+}
+
+async function chat(body: unknown, headers: Record<string, string> = {}) {
+ mockFetch.mockResolvedValueOnce(jsonResponse(body, headers));
+ const client = new SIEClient("http://localhost:8080");
+ return client.chatCompletions({ model: "m", messages: [{ role: "user", content: "hi" }] });
+}
+
+describe("settled charge", () => {
+ beforeEach(() => mockFetch.mockClear());
+ afterEach(() => vi.clearAllMocks());
+
+ it("reads the charge from the body, which also names the rate book", async () => {
+ const result = await chat(
+ completion({
+ prompt_tokens: 9,
+ completion_tokens: 3,
+ total_tokens: 12,
+ credits_charged: 7,
+ rate_book_version: BOOK,
+ }),
+ { "x-sie-credits-debited": "7" },
+ );
+
+ expect(result.usage.credits_charged).toBe(7);
+ expect(result.usage.rate_book_version).toBe(BOOK);
+ expect(result.request?.creditsDebited).toBe(7);
+ expect(result.request?.rateBookVersion).toBe(BOOK);
+ expect(result.request?.usage?.creditsCharged).toBe(7);
+ });
+
+ it("falls back to the header when the body carries no charge", async () => {
+ const result = await chat(
+ completion({ prompt_tokens: 9, completion_tokens: 3, total_tokens: 12 }),
+ { "x-sie-credits-debited": "7" },
+ );
+
+ expect(result.request?.creditsDebited).toBe(7);
+ expect(result.request?.rateBookVersion).toBeUndefined();
+ });
+
+ it("surfaces no charge at all when settlement did not commit", async () => {
+ const result = await chat(
+ completion({ prompt_tokens: 9, completion_tokens: 3, total_tokens: 12 }),
+ { "x-sie-request-id": "req-fault" },
+ );
+
+ expect(result.request?.creditsDebited).toBeUndefined();
+ expect(result.request?.rateBookVersion).toBeUndefined();
+ });
+
+ it("treats a settled zero as a charge", async () => {
+ const result = await chat(
+ completion({
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ total_tokens: 0,
+ credits_charged: 0,
+ rate_book_version: BOOK,
+ }),
+ );
+
+ expect(result.request?.creditsDebited).toBe(0);
+ expect(result.request?.usage?.creditsCharged).toBe(0);
+ });
+
+ it("carries the charge through the generate result's own usage block", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse(
+ {
+ model: "m",
+ text: "hi",
+ finish_reason: "stop",
+ usage: {
+ prompt_tokens: 9,
+ completion_tokens: 3,
+ total_tokens: 12,
+ credits_charged: 7,
+ rate_book_version: BOOK,
+ },
+ },
+ { "x-sie-credits-debited": "7" },
+ ),
+ );
+ const client = new SIEClient("http://localhost:8080");
+ const result = await client.generate("m", "hi", { maxNewTokens: 16 });
+
+ // The parser rebuilds `usage` field-by-field; the settled charge must
+ // survive that rebuild rather than being reachable only via `request`.
+ expect(result.usage.creditsCharged).toBe(7);
+ expect(result.usage.rateBookVersion).toBe(BOOK);
+ expect(result.usage.totalTokens).toBe(12);
+ });
+
+ it("leaves the generate usage block charge-free when nothing settled", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({
+ model: "m",
+ text: "hi",
+ finish_reason: "stop",
+ usage: { prompt_tokens: 9, completion_tokens: 3, total_tokens: 12 },
+ }),
+ );
+ const client = new SIEClient("http://localhost:8080");
+ const result = await client.generate("m", "hi", { maxNewTokens: 16 });
+
+ expect(result.usage.creditsCharged).toBeUndefined();
+ expect(result.usage.rateBookVersion).toBeUndefined();
+ });
+
+ it("ignores a half or malformed charge and falls back to the header", async () => {
+ for (const usage of [
+ { credits_charged: 7 },
+ { rate_book_version: BOOK },
+ { credits_charged: -1, rate_book_version: BOOK },
+ { credits_charged: "7", rate_book_version: BOOK },
+ { credits_charged: 1.5, rate_book_version: BOOK },
+ { credits_charged: 7, rate_book_version: "" },
+ ]) {
+ const result = await chat(
+ completion({ prompt_tokens: 1, completion_tokens: 1, total_tokens: 2, ...usage }),
+ { "x-sie-credits-debited": "3" },
+ );
+ expect(result.request?.creditsDebited).toBe(3);
+ expect(result.request?.rateBookVersion).toBeUndefined();
+ }
+ });
+});
diff --git a/uv.lock b/uv.lock
index 17b35af3e..667098ba2 100644
--- a/uv.lock
+++ b/uv.lock
@@ -5746,7 +5746,7 @@ dev = [
[[package]]
name = "sie-admin"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "packages/sie_admin" }
dependencies = [
{ name = "httpx" },
@@ -5779,12 +5779,12 @@ requires-dist = [
[[package]]
name = "sie-audio-prep"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "packages/sie_audio_prep" }
[[package]]
name = "sie-bench"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "packages/sie_bench" }
dependencies = [
{ name = "aiohttp" },
@@ -5877,7 +5877,7 @@ requires-dist = [
[[package]]
name = "sie-chroma"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "integrations/sie_chroma" }
dependencies = [
{ name = "chromadb" },
@@ -5957,7 +5957,7 @@ dev = [
[[package]]
name = "sie-crewai"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "integrations/sie_crewai" }
dependencies = [
{ name = "crewai" },
@@ -5982,7 +5982,7 @@ requires-dist = [
[[package]]
name = "sie-dspy"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "integrations/sie_dspy" }
dependencies = [
{ name = "dspy" },
@@ -6007,7 +6007,7 @@ requires-dist = [
[[package]]
name = "sie-haystack"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "integrations/sie_haystack" }
dependencies = [
{ name = "haystack-ai" },
@@ -6034,7 +6034,7 @@ requires-dist = [
[[package]]
name = "sie-lancedb"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "integrations/sie_lancedb" }
dependencies = [
{ name = "lancedb" },
@@ -6061,7 +6061,7 @@ requires-dist = [
[[package]]
name = "sie-langchain"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "integrations/sie_langchain" }
dependencies = [
{ name = "langchain-core" },
@@ -6088,7 +6088,7 @@ requires-dist = [
[[package]]
name = "sie-llamaindex"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "integrations/sie_llamaindex" }
dependencies = [
{ name = "llama-index-core" },
@@ -6154,7 +6154,7 @@ dev = [
[[package]]
name = "sie-qdrant"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "integrations/sie_qdrant" }
dependencies = [
{ name = "qdrant-client" },
@@ -6177,7 +6177,7 @@ requires-dist = [
[[package]]
name = "sie-sdk"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "packages/sie_sdk" }
dependencies = [
{ name = "aiohttp" },
@@ -6230,7 +6230,7 @@ requires-dist = [
[[package]]
name = "sie-server"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "packages/sie_server" }
dependencies = [
{ name = "blake3" },
@@ -6368,7 +6368,7 @@ requires-dist = [
[[package]]
name = "sie-weaviate"
-version = "0.6.24"
+version = "0.6.25"
source = { editable = "integrations/sie_weaviate" }
dependencies = [
{ name = "sie-sdk" },