Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(gateway): bridge encode and score under a numerical admission (#587)
Krisztian Gajdarf6e0820715f3
diff --git a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json b/deploy/helm/sie-cluster/files/dashboards/queue-routing.jsonindex 84592530a..ae55fc962 100644--- a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json+++ b/deploy/helm/sie-cluster/files/dashboards/queue-routing.json@@ -1816,6 +1816,45 @@],"title": "Remote Serving Duration Since Local Success","type": "timeseries"+ },+ {+ "description": "Gateway decisions on bridging numerical encode and score work: admitted, or refused because no remote worker advertises a current admission, a live local worker reports no complete process inventory, or a live local process is outside the admission.",+ "fieldConfig": {+ "defaults": {+ "unit": "reqps"+ }+ },+ "gridPos": {+ "x": 0,+ "y": 133,+ "w": 24,+ "h": 8+ },+ "id": 121,+ "options": {+ "legend": {+ "calcs": [+ "mean",+ "max"+ ],+ "displayMode": "table",+ "placement": "bottom",+ "showLegend": true+ },+ "tooltip": {+ "mode": "multi",+ "sort": "desc"+ }+ },+ "targets": [+ {+ "expr": "sum by (model, operation, outcome, reason) (rate(sie_gateway_remote_numerical_admissions_total{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"}[$__rate_interval]))",+ "legendFormat": "{{model}} {{operation}} {{outcome}} {{reason}}",+ "refId": "A"+ }+ ],+ "title": "Remote Numerical Admission Decisions",+ "type": "timeseries"}],"refresh": "10s",diff --git a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl b/deploy/helm/sie-cluster/templates/_otel-collector-config.tplindex 33e706cf3..59c5902f8 100644--- a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl+++ b/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl@@ -89,7 +89,7 @@ processors:error_mode: propagatemetrics:metric:- - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]remote[.]fallbacks|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]remote[.]serving[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]queue[.]worker_pool[.]events|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]routing[.]unsupported_model_exclusions|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pool[.]pinned_model[.]loaded|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]capacity[.]snapshot[.]timestamp|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'+ - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]remote[.]fallbacks|sie[.]gateway[.]remote[.]numerical_admissions|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]remote[.]serving[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]queue[.]worker_pool[.]events|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]routing[.]unsupported_model_exclusions|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pool[.]pinned_model[.]loaded|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]capacity[.]snapshot[.]timestamp|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'- 'resource.attributes["service.name"] != "sie-gateway"'filter/prometheus_application_contract:error_mode: propagate@@ -120,7 +120,7 @@ processors:- context: metricstatements:- set(description, "")- - 'set(unit, "{request}") where IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]remote[.]fallbacks|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[.]worker[.]upstream[.]refusals|sie[.]gateway[.]pending_demand|sie[.]gateway[.]rejected[.]requests)$")'+ - 'set(unit, "{request}") where IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]remote[.]fallbacks|sie[.]gateway[.]remote[.]numerical_admissions|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[.]worker[.]upstream[.]refusals|sie[.]gateway[.]pending_demand|sie[.]gateway[.]rejected[.]requests)$")'- 'set(unit, "s") where IsMatch(name, "^(sie[.]gateway[.]request[.]duration|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]remote[.]serving[.]duration|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]dispatcher[.]invocation[.]duration|sie[.]dispatcher[.]sealed[.]stage[.]duration|sie[.]dispatcher[.]sealed[.]sandbox[.]seconds|sie[.]dispatcher[.]sealed[.]cold_start[.]seconds|sie[.]config[.]request[.]duration|sie[.]worker[.]queue[.]duration|sie[.]worker[.]scheduler[.]request_batch[.]dispatch_wait|sie[.]worker[.]scheduler[.]request_batch[.]total|sie[.]worker[.]scheduler[.]adaptive[.]wait|sie[.]worker[.]scheduler[.]adaptive[.]p50|sie[.]worker[.]ipc[.]request[.]duration|sie[.]worker[.]payload[.]fetch[.]duration|sie[.]worker[.]ipc[.]acquire[.]duration|sie[.]worker[.]shutdown[.]drain[.]duration|sie[.]worker[.]request[.]duration|sie[.]worker[.]inference[.]duration|sie[.]worker[.]model[.]load[.]duration|sie[.]worker[.]generation[.]worker_wait|sie[.]worker[.]generation[.]ttft|sie[.]worker[.]generation[.]tpot|sie[.]worker[.]generation[.]grammar[.]compile[.]duration|sie[.]worker[.]runtime[.]forward[.]duration|sie[.]worker[.]runtime[.]forward[.]permit[.]wait|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]capacity[.]snapshot[.]timestamp|sie[.]gateway[.]settlement[.]confirm[.]duration|sie[.]worker[.]work_item[.]age)$")'- 'set(unit, "{epoch}") where IsMatch(name, "^(sie[.]gateway[.]config[.]applied_epoch|sie[.]config[.]epoch|sie[.]worker[.]config[.]epoch)$")'- 'set(unit, "{operation}") where IsMatch(name, "^(sie[.]gateway[.]config[.]operations|sie[.]config[.]publish|sie[.]config[.]store[.]writes|sie[.]worker[.]nats[.]operations)$")'@@ -170,6 +170,7 @@ processors:- 'keep_keys(attributes, ["operation", "dispatch.path", "outcome", "fallback.reason", "lane"]) where IsMatch(metric.name, "^(sie[.]gateway[.]dispatches|sie[.]gateway[.]dispatch[.]duration)$")'- 'keep_keys(attributes, ["operation", "model", "fallback.reason", "outcome"]) where metric.name == "sie.gateway.remote.fallbacks"'- 'keep_keys(attributes, ["model"]) where metric.name == "sie.gateway.remote.serving.duration"'+ - 'keep_keys(attributes, ["operation", "model", "outcome", "reason"]) where metric.name == "sie.gateway.remote.numerical_admissions"'- 'keep_keys(attributes, []) where IsMatch(metric.name, "^(sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]config[.]epoch|sie[.]gateway[.]capacity[.]snapshot[.]timestamp)$")'- 'keep_keys(attributes, ["transport"]) where IsMatch(metric.name, "^(sie[.]gateway[.]messaging[.]client[.]ready|sie[.]config[.]messaging[.]ready)$")'- 'keep_keys(attributes, ["event", "outcome"]) where metric.name == "sie.gateway.queue.events"'@@ -289,7 +290,7 @@ processors:error_mode: propagatemetrics:metric:- - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]remote[.]fallbacks|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]remote[.]serving[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]routing[.]unsupported_model_exclusions|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'+ - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]remote[.]fallbacks|sie[.]gateway[.]remote[.]numerical_admissions|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]remote[.]serving[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]routing[.]unsupported_model_exclusions|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'- 'resource.attributes["service.name"] != "sie-gateway"'filter/remote_application_contract:error_mode: propagatediff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 31a2e3304..625c75650 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -421,7 +421,7 @@ The `ConfigNotification` JSON payload carries the following fields, verified agaThe hot path is always **msgpack** (`rmp_serde` on the gateway, `msgpack-python` / `msgpack-numpy` on workers). Specifically:-- `WorkItem` (gateway → worker on JetStream): msgpack. `model_id` is the route the work runs on. When routing dispatched the request to another route of the requested model (a profile variant), `display_model` carries the model id the caller asked for, so logs and accounting downstream can report it; it is omitted otherwise. `WorkDispatcher::publish_work` takes the same `display_model`. A remote attempt that stands in for a local refusal the gateway holds carries `fallback_reason`, the trigger of that refusal (`provisioning`, `model_loading`, `saturated` or `unhealthy`), on every fallback bridge and on a threshold bridge while local capacity wakes. The remote worker answers such an item it cannot serve now with a retryable error instead of redelivering it, so the gateway restores the local refusal at once. Other work, including a low-demand threshold route, omits the field.+- `WorkItem` (gateway → worker on JetStream): msgpack. `model_id` is the route the work runs on. When routing dispatched the request to another route of the requested model (a profile variant), `display_model` carries the model id the caller asked for, so logs and accounting downstream can report it; it is omitted otherwise. `WorkDispatcher::publish_work` takes the same `display_model`. A remote attempt that stands in for a local refusal the gateway holds carries `fallback_reason`, the trigger of that refusal (`provisioning`, `model_loading`, `saturated` or `unhealthy`), on every fallback bridge and on a threshold bridge while local capacity wakes. The remote worker answers such an item it cannot serve now with a retryable error instead of redelivering it, so the gateway restores the local refusal at once. Other work, including a low-demand threshold route, omits the field. An admitted numerical remote attempt also carries `numerical_admission_sha256` (see [Numerical bridges](#numerical-bridges)), and the remote worker answers it at once in the same way, even on a threshold route.- `WorkResult` (worker → gateway on the inbox subject): msgpack. Numpy arrays use `msgpack-numpy`'s extension-free encoding (maps with a `nd: true` sentinel + `type`, `shape`, `data`). When the gateway advertises `WorkItem.accepts_result_chunks: true`, a result that does not fit one NATS message may instead arrive as named-msgpack `result_chunk_v1` envelopes. This boolean negotiates v1 only; a future envelope version requires a new capability rather than reinterpreting the existing field. The gateway reassembles v1 transfers within the pending request lifetime, with a SHA-256 digest and fixed item/chunk/request/process memory limits, then decodes the reconstructed bytes as the same `WorkResult`. The gateway transcodes to native JSON arrays only when the client's `Accept` header asks for JSON.JSON (`serde_json`) is used where payloads are low-frequency or human-oriented:@@ -953,8 +953,66 @@ Sidecars probe on dedicated IPC connections independently of readiness pingsand health publication, with afive-second timeout and a ten-second observation lifetime. Shutdown tombstonesomit diagnostics. A snapshot describes the process and model configuration at-its observation time; it is not an atomic fleet proof and does not grant routing-or execution authority. Numerical fallback requires operator-owned numerical-evidence as a separate prerequisite. Consumers must also verify freshness,-membership, local identity, request contract and evidence at execution before-enabling numerical fallback.+its observation time; it is not an atomic fleet proof, and on its own it grants+no routing or execution authority.++### Numerical bridges++A bare `encode` or `score` request for a local model with numerical outputs+(`dense`, `sparse`, `multivector` or `score`) bridges to the model's remote+profile only under a numerical admission. This covers fallback bridges, the+threshold route and `/v1/embeddings`, which wraps `encode`. Generation and+extraction surfaces never bridge such a model. For these models alone, the+gateway reads and parses the request body after route resolution and before+any bridge, threshold or load decision. An invalid body gets its `400` before+threshold demand is counted or load-only work is published. The parse lets the+gateway refuse a body-level `options.profile` selector, check the request+against the admission and replay the body remotely. The bridge decision is made+when the gateway is about to commit to the remote attempt:++- The request sets no runtime option other than `is_query`, and every output it+ asks for (`dense` when an encode names none, `score` for score) is listed in+ the admission. Otherwise the remote process would refuse it, so it stays local+ with the reason `unmeasured_request`. A request with another runtime option is+ not a bridge candidate at all: a fallback trigger leaves it on its ordinary+ local path instead of committing to the local refusal.+- An eligible remote worker is fresh and eligible for dispatch, reports+ `supports_execution_authority_v1`, `supports_numerical_admission_v1` and+ `supports_numerical_admission_subject_v1` (which builds that predate the+ admission subject never send), has+ the remote profile's exact configuration hash, bundle and pool, and has a+ unique worker name. Every child in its inventory must report the same+ admission for the bare model, together with the admission's own model+ contract, expiring at least five seconds after the decision.+- Every local process that could serve the model must be covered. That means+ each child of every worker on the model's local bundles and in the model's+ pool (`default` when it names none, because a worker loads only the models of+ its own pool), starting and degraded workers included, unless the worker lists+ the model as unsupported. Each such child must report an identity the+ admission lists and the admission's model contract. A worker without a+ complete inventory, a worker past the heartbeat timeout that has not been+ evicted, or a child without an identity or without the model, closes the+ bridge. The registry also closes it until it has heard worker health for one+ heartbeat timeout after the health subscription starts or resumes, or after+ a silence longer than that timeout, because a worker that has not reported+ yet looks absent. With no local worker the remote admission decides.+- The bridge pins one remote worker that both conditions admit. Selection checks+ again that the worker still reports `supports_numerical_admission_subject_v1` and the+ admitted digest. Its work items carry that digest as+ `numerical_admission_sha256` on the worker's `numerical-admission-v1` subject,+ which only a sidecar with the admission fence consumes, and the publisher+ refuses the digest on any other subject. The remote process derives its+ admission again before calling the upstream, and the sidecar answers a refused+ admitted item at once. A bridged caller then receives its local refusal with+ `X-SIE-Fallback-Error`. A threshold route holds no local refusal, so it+ answers `503 INFERENCE_ERROR` with the worker's `Retry-After` hint (1 to 60+ seconds, else 5).++Anything else keeps the request on its local route. A numerical plan that was+not admitted cannot select a worker, and a numerical bridge whose pinned worker+has no admitted digest is refused before publication. Each request's decision+is counted once, with the decision that applied, on+`sie.gateway.remote.numerical_admissions` with `admitted` or one of the refusal+reasons `no_admission`, `local_unobserved`, `uncovered_identity` and+`unmeasured_request`. Configuration load no longer refuses `threshold` routing+for numerical models; the admission gates each request instead.diff --git a/packages/sie_gateway/src/discovery/nats_health.rs b/packages/sie_gateway/src/discovery/nats_health.rsindex 9933ef1d9..e88ed4b22 100644--- a/packages/sie_gateway/src/discovery/nats_health.rs+++ b/packages/sie_gateway/src/discovery/nats_health.rs@@ -33,6 +33,7 @@ impl NatsHealthManager {client: &async_nats::Client,) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {let sub = subscribe_health(client).await?;+ self.registry.health_subscription_started();info!(subject = HEALTH_SUBJECT, "subscribed to NATS health");let registry = Arc::clone(&self.registry);@@ -130,6 +131,7 @@ async fn run_subscription_supervised(Some(sub) => sub,None => match subscribe_health(&client).await {Ok(sub) => {+ registry.health_subscription_started();info!(subject = HEALTH_SUBJECT, "resubscribed to NATS health");sub}@@ -297,6 +299,8 @@ mod tests {fn status(ready: bool) -> WorkerStatusMessage {WorkerStatusMessage {supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,name: "worker-1".into(),ready,gpu_count: 1,diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex 0c16834a7..9824fc424 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -853,6 +853,8 @@ mod tests {) -> crate::types::worker::WorkerStatusMessage {crate::types::worker::WorkerStatusMessage {supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,name: name.into(),gpu_count: 1,total_gpu_slots: None,diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 07a0d251e..b7ca2419d 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -683,6 +683,8 @@ mod route_tests {fn worker_msg(name: &str, loaded_models: Vec<String>) -> WorkerStatusMessage {WorkerStatusMessage {supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,name: name.into(),gpu_count: 1,total_gpu_slots: None,diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 46bf20923..5d3da2497 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -404,6 +404,9 @@ const LORA_LOADING_RETRY_AFTER: &str = RetryAfter::DEFAULT.lora_loading;/// worker's ``retry_after_s`` when it gave one.const QUEUE_FULL_ERROR_CODE: &str = "QUEUE_FULL";const QUEUE_FULL_RETRY_AFTER: &str = RetryAfter::DEFAULT.queue_full;+/// The code a remote worker answers when its numerical admission check+/// refuses an admitted item before calling the upstream.+const INFERENCE_ERROR_ERROR_CODE: &str = "INFERENCE_ERROR";const INVALID_INPUT_ERROR_CODE: &str = "INVALID_INPUT";/// Worker-side input exceeds the model's context window (for example a label/// set that does not fit). Caller-fixable, so it maps to 400 like@@ -1868,6 +1871,64 @@ fn native_request_has_profile_selector(body: &[u8], msgpack: bool) -> bool {#[derive(Clone)]struct RemoteFallbackOverride(crate::state::model_registry::RemoteFallbackPlan);+/// A request's latest numerical admission decision. A threshold route and a+/// later fallback trigger can both decide for one request, which counts once,+/// with the decision that applied.+#[derive(Clone, Default)]+struct NumericalDecision(Arc<std::sync::Mutex<Option<NumericalDecisionRecord>>>);++struct NumericalDecisionRecord {+ model: String,+ operation: String,+ refusal: Option<crate::state::worker_registry::NumericalRefusal>,+}++impl NumericalDecision {+ fn install(req: &mut Request) -> Self {+ if let Some(existing) = req.extensions().get::<Self>() {+ return existing.clone();+ }+ let decision = Self::default();+ req.extensions_mut().insert(decision.clone());+ decision+ }++ fn note(+ ext: &axum::http::Extensions,+ model: &str,+ operation: &str,+ refusal: Option<crate::state::worker_registry::NumericalRefusal>,+ ) {+ let Some(decision) = ext.get::<Self>() else {+ crate::observability::metrics::record_numerical_admission(model, operation, refusal);+ return;+ };+ *decision+ .0+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(NumericalDecisionRecord {+ model: model.to_string(),+ operation: operation.to_string(),+ refusal,+ });+ }++ fn record(&self) {+ let latest = self+ .0+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .take();+ if let Some(latest) = latest {+ crate::observability::metrics::record_numerical_admission(+ &latest.model,+ &latest.operation,+ latest.refusal,+ );+ }+ }+}+/// The trigger a bridged remote attempt carries to its worker. A remote route/// with no held local refusal, such as a low-demand threshold route, has none.fn bridged_fallback_reason(ext: &axum::http::Extensions) -> Option<FallbackTrigger> {@@ -2229,8 +2290,9 @@ async fn resolve_routing(})}-/// Shared OSS admission for a bridge. Deployment-governed routes retain-/// their own authority until they explicitly admit a remote physical route.+/// Shared OSS admission for a bridge that never carries numerical outputs.+/// Deployment-governed routes retain their own authority until they+/// explicitly admit a remote physical route.#[allow(clippy::too_many_arguments)]fn fallback_plan_for_request(state: &AppState,@@ -2240,6 +2302,30 @@ fn fallback_plan_for_request(allowed: bool,explicit_bundle: &str,trigger: FallbackTrigger,+) -> Option<crate::state::model_registry::RemoteFallbackPlan> {+ fallback_plan_candidate(+ state,+ headers,+ ext,+ model,+ allowed,+ explicit_bundle,+ trigger,+ )+ .filter(|plan| plan.numerical.is_none())+}++/// The configured bridge for a request, numerical or not. A numerical plan+/// must pass [`admit_numerical`] before the gateway commits to it.+#[allow(clippy::too_many_arguments)]+fn fallback_plan_candidate(+ state: &AppState,+ headers: &HeaderMap,+ ext: &axum::http::Extensions,+ model: &str,+ allowed: bool,+ explicit_bundle: &str,+ trigger: FallbackTrigger,) -> Option<crate::state::model_registry::RemoteFallbackPlan> {let attempt = ext.get::<FallbackAttempt>()?;if !allowed@@ -2270,6 +2356,8 @@ fn threshold_remote_plan_for_request(headers: &HeaderMap,ext: &axum::http::Extensions,model: &str,+ operation: &str,+ parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,allowed: bool,explicit_bundle: &str,) -> Option<crate::state::model_registry::RemoteFallbackPlan> {@@ -2290,12 +2378,125 @@ fn threshold_remote_plan_for_request(}let epoch = state.config_epoch.get();let plan = state.model_registry.threshold_remote_route(model, epoch)?;- if state.config_epoch.get() != epoch || remote_forbidden(headers).unwrap_or(true) {+ if state.config_epoch.get() != epoch+ || remote_forbidden(headers).unwrap_or(true)+ || (plan.numerical.is_some() && !matches!(operation, "encode" | "score"))+ {return None;}+ admit_numerical(state, plan, operation, parsed, ext)+}++/// Commit to a numerical plan only when a current admission covers every+/// local process that could serve the model and the request stays within what+/// the admission measured; note the decision. Other plans pass unchanged.+fn admit_numerical(+ state: &AppState,+ mut plan: crate::state::model_registry::RemoteFallbackPlan,+ operation: &str,+ parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,+ ext: &axum::http::Extensions,+) -> Option<crate::state::model_registry::RemoteFallbackPlan> {+ let Some(route) = plan.numerical.as_ref() else {+ return Some(plan);+ };+ let decision = match numerical_request_outputs(operation, parsed) {+ None => Err(crate::state::worker_registry::NumericalRefusal::UnmeasuredRequest),+ Some(outputs) => {+ let now_unix_ms = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |elapsed| {+ u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)+ });+ state.registry.numerical_admission(+ &crate::state::worker_registry::NumericalLanes {+ model: &route.model,+ local_bundles: &route.local_bundles,+ local_pool: &route.local_pool,+ remote_model: &plan.model,+ remote_bundle: &plan.bundle,+ remote_pool: &plan.pool,+ remote_hash: &plan.config_hash,+ outputs: &outputs,+ },+ now_unix_ms,+ )+ }+ };+ NumericalDecision::note(+ ext,+ &route.model,+ operation,+ decision.as_ref().err().copied(),+ );+ let admitted = Arc::new(decision.ok()?);+ if let Some(route) = plan.numerical.as_mut() {+ route.admitted = Some(admitted);+ }Some(plan)}+/// The outputs a numerical request asks for, when it sets no runtime option+/// that a numerical admission could not have measured. The remote process+/// refuses any option except `is_query` that differs from the measured+/// defaults, so a request with another option stays local.+fn numerical_request_outputs(+ operation: &str,+ parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,+) -> Option<Vec<String>> {+ let (_, params) = parsed?;+ let measured = match params.options.as_ref() {+ None | Some(Value::Null) => true,+ Some(Value::Object(options)) => options.keys().all(|key| key == "is_query"),+ Some(_) => false,+ };+ if !measured {+ return None;+ }+ match operation {+ "encode" => Some(+ params+ .output_types+ .clone()+ .unwrap_or_else(|| vec!["dense".to_string()]),+ ),+ "score" => Some(vec!["score".to_string()]),+ _ => None,+ }+}++/// The admitted remote workers a bridged numerical plan pins, for its bare+/// model. A numerical plan the gateway has not admitted pins none.+fn bridged_numerical_pin(+ ext: &axum::http::Extensions,+) -> Option<(String, Arc<crate::state::worker_registry::AdmittedWorkers>)> {+ let RemoteFallbackOverride(plan) = ext.get::<RemoteFallbackOverride>()?;+ let route = plan.numerical.as_ref()?;+ Some((+ route.model.clone(),+ route.admitted.clone().unwrap_or_default(),+ ))+}++/// The admission digest a bridged numerical item names: the one its pinned+/// worker advertised when the gateway admitted the bridge.+fn bridged_numerical_admission(+ ext: &axum::http::Extensions,+ target: Option<&publisher::PublishTarget>,+) -> Option<String> {+ let RemoteFallbackOverride(plan) = ext.get::<RemoteFallbackOverride>()?;+ let admitted = plan.numerical.as_ref()?.admitted.as_ref()?;+ let publisher::PublishTarget::VerifiedWorker {+ worker_id,+ numerical_admission: true,+ ..+ } = target?+ else {+ return None;+ };+ admitted.get(worker_id).cloned()+}+/// Refusal classification is scoped to the local route and admitted workers./// It carries no dispatch authority and never accepts inference work.#[allow(clippy::too_many_arguments)]@@ -2447,7 +2648,11 @@ fn model_loading_refusal(endpoint: &str) -> Response {fn native_bridge_eligible(endpoint: &str,parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,+ body_held: bool,) -> bool {+ if matches!(endpoint, "encode" | "score") {+ return body_held;+ }parsed.is_some_and(|(items, params)| match endpoint {"generate" => params.generate.is_some(),"extract" => {@@ -2463,9 +2668,9 @@ fn native_bridge_eligible(})}-/// Begin one non-numerical bridge only at a typed pre-dispatch refusal.-/// Fleet numerical admission remains separately gated; no failure-/// after a work item was published reaches this helper.+/// Begin one bridge only at a typed pre-dispatch refusal. A numerical plan+/// serves only encode and score, and only once admitted; no failure after a+/// work item was published reaches this helper.#[allow(clippy::result_large_err, clippy::too_many_arguments)]fn native_fallback_plan(state: &AppState,@@ -2473,10 +2678,11 @@ fn native_fallback_plan(endpoint: &str,model: &str,parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,+ body_held: bool,trigger: FallbackTrigger,) -> Option<crate::state::model_registry::RemoteFallbackPlan> {- let eligible = native_bridge_eligible(endpoint, parsed);- fallback_plan_for_request(+ let eligible = native_bridge_eligible(endpoint, parsed, body_held);+ fallback_plan_candidate(state,req.headers(),req.extensions(),@@ -2485,6 +2691,9 @@ fn native_fallback_plan("",trigger,)+ .filter(|plan| {+ plan.numerical.is_none() || numerical_request_outputs(endpoint, parsed).is_some()+ })}#[allow(clippy::result_large_err, clippy::too_many_arguments)]@@ -2494,10 +2703,13 @@ fn begin_native_fallback(endpoint: &str,model: &str,parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,+ body_held: bool,refusal: Response,trigger: FallbackTrigger,) -> Result<(), Response> {- let Some(plan) = native_fallback_plan(state, req, endpoint, model, parsed, trigger) else {+ let Some(plan) = native_fallback_plan(state, req, endpoint, model, parsed, body_held, trigger)+ .and_then(|plan| admit_numerical(state, plan, endpoint, parsed, req.extensions()))+ else {return Err(refusal);};let attempt = req@@ -2524,6 +2736,7 @@ pub(crate) async fn proxy_request(}let disclosure = ServingDisclosure::install(&mut req);let fallback = FallbackAttempt::install(&mut req);+ let numerical_decision = NumericalDecision::install(&mut req);let defer_fallback = req.extensions().get::<DeferredFallbackFinish>().is_some();let provisioning_surface = provisioning_surface_for_endpoint(endpoint);@@ -2579,6 +2792,7 @@ pub(crate) async fn proxy_request(inbound_publish_cx,).await;+ numerical_decision.record();disclosure.stamp(response.status(), response.headers_mut());if defer_fallback {response@@ -2680,8 +2894,56 @@ async fn proxy_request_inner(req.extensions_mut().insert(ExplicitProfileSelector);}ServingDisclosure::record(&state, req.extensions(), &dispatch_model);+ // A numerical bridge needs the body to detect a caller's profile selector,+ // to check the request against the admission and to replay it remotely.+ // The request is validated before either side counts it. Other encode and+ // score requests keep streaming their body straight to the queue path.+ if prepared_native_body.is_none()+ && matches!(endpoint, "encode" | "score")+ && state.model_registry.has_numerical_bridge(&model_name)+ {+ let body_limit = native_request_body_limit(endpoint);+ 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, body_limit).await {+ Ok(body) => body,+ Err(error) => {+ let (status, code, message) = request_body_error(&error, body_limit);+ return endpoint_error_response(+ endpoint,+ status,+ code,+ oai_type::INVALID_REQUEST,+ oai_code::INVALID_REQUEST,+ None,+ message,+ );+ }+ };+ req = Request::from_parts(parts, Body::empty());+ let parsed = match parse_queue_request(&body_bytes, is_msgpack, endpoint) {+ Ok(parsed) => parsed,+ Err(error) => return queue_parse_error_response(endpoint, error),+ };+ if let Some(response) = queue_items_error(endpoint, &parsed.0) {+ return response;+ }+ if native_request_has_profile_selector(&body_bytes, is_msgpack) {+ req.extensions_mut().insert(ExplicitProfileSelector);+ }+ prepared_native_body = Some(body_bytes);+ prepared_native_parsed = Some(parsed);+ }+ let body_held = prepared_native_body.is_some();- if let Some((items, params)) = prepared_native_parsed.as_ref() {+ if let Some((items, params)) = prepared_native_parsed+ .as_ref()+ .filter(|_| matches!(endpoint, "generate" | "extract"))+ {let response = if endpoint == "generate" {validate_native_generate_pre_admission(&state,@@ -2806,7 +3068,9 @@ async fn proxy_request_inner(req.headers(),req.extensions(),&model_name,- native_bridge_eligible(endpoint, prepared_native_parsed.as_ref()),+ endpoint,+ prepared_native_parsed.as_ref(),+ native_bridge_eligible(endpoint, prepared_native_parsed.as_ref(), body_held),"",) {req.extensions_mut().insert(RemoteFallbackOverride(plan));@@ -2877,6 +3141,7 @@ async fn proxy_request_inner(endpoint,&model_name,prepared_native_parsed.as_ref(),+ body_held,refusal,trigger,) {@@ -2940,6 +3205,7 @@ async fn proxy_request_inner(endpoint,&model_name,prepared_native_parsed.as_ref(),+ body_held,FallbackTrigger::Saturated,).is_some()@@ -2949,6 +3215,7 @@ async fn proxy_request_inner(endpoint,&model_name,prepared_native_parsed.as_ref(),+ body_held,FallbackTrigger::Unhealthy,).is_some()@@ -2970,6 +3237,7 @@ async fn proxy_request_inner(endpoint,&model_name,prepared_native_parsed.as_ref(),+ body_held,trigger,).is_some()@@ -2982,6 +3250,7 @@ async fn proxy_request_inner(endpoint,&model_name,prepared_native_parsed.as_ref(),+ body_held,refusal,trigger,) {@@ -3010,6 +3279,7 @@ async fn proxy_request_inner(endpoint,&model_name,prepared_native_parsed.as_ref(),+ body_held,FallbackTrigger::ModelLoading,).is_some()@@ -3039,6 +3309,7 @@ async fn proxy_request_inner(&bundle,&bundle_config_hash,&admission_pool,+ None,).await{@@ -3061,6 +3332,7 @@ async fn proxy_request_inner(endpoint,&model_name,prepared_native_parsed.as_ref(),+ body_held,refusal,FallbackTrigger::ModelLoading,) {@@ -3089,6 +3361,7 @@ async fn proxy_request_inner(let batch_target = if endpoint == "generate" {None} else if require_execution_authority_v1 {+ let numerical_pin = bridged_numerical_pin(req.extensions());match execution_authority_target(&state,&dispatch_model,@@ -3097,6 +3370,15 @@ async fn proxy_request_inner(&bundle,&bundle_config_hash,&admission_pool,+ numerical_pin+ .as_ref()+ .map(+ |(model, admitted)| crate::state::worker_registry::NumericalPin {+ model,+ admitted,+ },+ )+ .as_ref(),).await{@@ -3109,7 +3391,11 @@ async fn proxy_request_inner(oai_type::SERVER_ERROR,oai_code::TRANSPORT_FAILURE,None,- "No current worker can verify local execution",+ if numerical_pin.is_some() {+ "No admitted remote worker can run this numerical bridge"+ } else {+ "No current worker can verify local execution"+ },);response.headers_mut()@@ -3274,6 +3560,24 @@ fn managed_request_parent(req: &Request) -> opentelemetry::Context {})}+/// The request-wide item checks of the queue path.+fn queue_items_error(endpoint: &str, items: &[rmpv::Value]) -> Option<Response> {+ let message = if items.is_empty() && endpoint != "score" && endpoint != "generate" {+ "No items found in request body".to_string()+ } else {+ publisher::validate_queue_request_item_count(items.len()).err()?+ };+ Some(endpoint_error_response(+ endpoint,+ StatusCode::BAD_REQUEST,+ err_code::INVALID_REQUEST,+ oai_type::INVALID_REQUEST,+ oai_code::INVALID_REQUEST,+ None,+ message,+ ))+}+/// Route request through the queue-only JetStream path.////// `pool` is always pre-resolved by the caller via@@ -3695,29 +3999,33 @@ async fn queue_mode_proxy(params.require_execution_authority_v1 = require_execution_authority_v1;params.fallback_reason = bridged_fallback_reason(request_extensions);-- if items.is_empty() && endpoint != "score" && endpoint != "generate" {- return endpoint_error_response(- endpoint,- StatusCode::BAD_REQUEST,- err_code::INVALID_REQUEST,- oai_type::INVALID_REQUEST,- oai_code::INVALID_REQUEST,- None,- "No items found in request body",- );+ if request_extensions+ .get::<RemoteFallbackOverride>()+ .is_some_and(|RemoteFallbackOverride(plan)| plan.numerical.is_some())+ {+ let Some(admission) = matches!(endpoint, "encode" | "score")+ .then(|| bridged_numerical_admission(request_extensions, batch_target.as_ref()))+ .flatten()+ else {+ let mut response = endpoint_error_response(+ endpoint,+ StatusCode::SERVICE_UNAVAILABLE,+ err_code::QUEUE_UNAVAILABLE,+ oai_type::SERVER_ERROR,+ oai_code::TRANSPORT_FAILURE,+ None,+ "No current worker can verify the numerical admission",+ );+ response+ .headers_mut()+ .insert("retry-after", HeaderValue::from_static("5"));+ return response;+ };+ params.numerical_admission_sha256 = Some(admission);}- if let Err(message) = publisher::validate_queue_request_item_count(items.len()) {- return endpoint_error_response(- endpoint,- StatusCode::BAD_REQUEST,- err_code::INVALID_REQUEST,- oai_type::INVALID_REQUEST,- oai_code::INVALID_REQUEST,- None,- message,- );+ if let Some(response) = queue_items_error(endpoint, &items) {+ return response;}// Generate has its own publish + result-collection path@@ -4066,6 +4374,28 @@ async fn queue_mode_proxy({return build_model_load_failed_response();}+ // An admitted remote attempt refused by its worker's admission check,+ // which happens when the admission changed after this gateway checked+ // it. Like an upstream that cannot serve now, it is retryable, and on+ // a fallback route the held local refusal replaces it.+ if params.numerical_admission_sha256.is_some()+ && errors+ .iter()+ .all(|r| r.error_code.as_deref() == Some(INFERENCE_ERROR_ERROR_CODE))+ {+ let retry_after = longest_worker_retry_after(&errors).map_or_else(+ || QUEUE_FULL_RETRY_AFTER.to_string(),+ |seconds| seconds.to_string(),+ );+ return service_unavailable_with_code(+ INFERENCE_ERROR_ERROR_CODE,+ errors+ .first()+ .and_then(|r| r.error.as_deref())+ .unwrap_or("The remote profile cannot serve this request now"),+ &retry_after,+ );+ }// Translate retryable worker error codes into the SDK-expected 503// contract. Without this every per-item failure surfaced as 500// ``all_items_failed`` and the SDK retry path never engaged. We@@ -4409,6 +4739,7 @@ pub(crate) async fn execution_authority_target(bundle: &str,hash: &str,admission_pool: &str,+ numerical: Option<&crate::state::worker_registry::NumericalPin<'_>>,) -> Result<publisher::PublishTarget, Box<Response>> {if !publisher::PublishTarget::verified_model_is_unambiguous(model)|| !state@@ -4441,6 +4772,7 @@ pub(crate) async fn execution_authority_target(bundle,hash,admitted.as_ref(),+ numerical,) {return Ok(publisher::PublishTarget::VerifiedWorker {pool: pool.to_string(),@@ -4448,6 +4780,7 @@ pub(crate) async fn execution_authority_target(bundle: bundle.to_string(),model: model.to_string(),worker_id,+ numerical_admission: numerical.is_some(),});}let mut response = endpoint_error_response(@@ -4720,6 +5053,7 @@ pub(crate) async fn run_streaming_generate(bundle,bundle_config_hash,admission_pool,+ None,).await.map_err(|_| StreamingDriverErr::PublishFailed {@@ -7986,6 +8320,8 @@ async fn resolve_generation_route(hdr,ext,customer_model,+ "generate",+ None,bridge_allowed,explicit_bundle_override,) {@@ -8230,6 +8566,7 @@ async fn resolve_generation_route(&bundle,&bundle_config_hash,&admission_pool,+ None,).await{@@ -10619,6 +10956,12 @@ fn build_retryable_error_response();MODEL_LOADING_RETRY_AFTER.to_string()});+ service_unavailable_with_code(code, message, &retry_after)+}++/// A `503` with the worker contract's error envelope, `Retry-After`,+/// `X-SIE-Error-Code` and version headers.+fn service_unavailable_with_code(code: &str, message: &str, retry_after: &str) -> Response {let mut resp = (StatusCode::SERVICE_UNAVAILABLE,Json(json!({@@ -10631,7 +10974,7 @@ fn build_retryable_error_response(.into_response();resp.headers_mut().insert(HeaderName::from_static("retry-after"),- HeaderValue::from_str(&retry_after).unwrap_or_else(|_| HeaderValue::from_static("5")),+ HeaderValue::from_str(retry_after).unwrap_or_else(|_| HeaderValue::from_static("5")),);resp.headers_mut().insert(HeaderName::from_static("x-sie-error-code"),@@ -12284,6 +12627,7 @@ fn work_params_from_json(routing_key: None,prompt_cache_key: None,fallback_reason: None,+ numerical_admission_sha256: None,});}@@ -12339,6 +12683,7 @@ fn work_params_from_json(routing_key: None,prompt_cache_key: None,fallback_reason: None,+ numerical_admission_sha256: None,})}@@ -13186,6 +13531,7 @@ fn work_params_from_rmpv(routing_key: None,prompt_cache_key: None,fallback_reason: None,+ numerical_admission_sha256: None,});}@@ -13247,6 +13593,7 @@ fn work_params_from_rmpv(routing_key: None,prompt_cache_key: None,fallback_reason: None,+ numerical_admission_sha256: None,})}@@ -18997,6 +19344,8 @@ mod tests {"http://assigned-cold:8080",crate::types::WorkerStatusMessage {supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,name: "assigned-cold".to_string(),ready: true,gpu_count: 1,@@ -21027,6 +21376,74 @@ mod tests {assert_eq!(unanimous_retryable_error_code(&errors), None);}+ #[test]+ fn a_request_keeps_only_its_last_numerical_decision() {+ use crate::state::worker_registry::NumericalRefusal;+ let decision = NumericalDecision::default();+ let mut ext = axum::http::Extensions::new();+ ext.insert(decision.clone());+ NumericalDecision::note(+ &ext,+ "acme/hybrid",+ "encode",+ Some(NumericalRefusal::NoAdmission),+ );+ NumericalDecision::note(&ext, "acme/hybrid", "encode", None);+ let latest = decision.0.lock().unwrap().take().unwrap();+ assert_eq!(+ (+ latest.model.as_str(),+ latest.operation.as_str(),+ latest.refusal+ ),+ ("acme/hybrid", "encode", None)+ );+ assert!(decision.0.lock().unwrap().is_none());+ }++ #[test]+ fn a_numerical_request_is_measured_only_without_other_runtime_options() {+ let parsed = |params: serde_json::Value| {+ parse_queue_request(+ serde_json::to_vec(&json!({"items":[{"text":"x"}], "params": params}))+ .unwrap()+ .as_slice(),+ false,+ "encode",+ )+ .unwrap()+ };+ let outputs = |operation: &str, params: serde_json::Value| {+ numerical_request_outputs(operation, Some(&parsed(params)))+ };+ assert_eq!(+ outputs("encode", json!({})),+ Some(vec!["dense".to_string()])+ );+ assert_eq!(+ outputs(+ "encode",+ json!({"output_types":["dense", "sparse"], "is_query": true})+ ),+ Some(vec!["dense".to_string(), "sparse".to_string()])+ );+ assert_eq!(+ outputs("encode", json!({"options":{"is_query": true}})),+ Some(vec!["dense".to_string()])+ );+ assert_eq!(outputs("score", json!({})), Some(vec!["score".to_string()]));+ for params in [+ json!({"output_dtype": "int8"}),+ json!({"output_dtype": "float32"}),+ json!({"options": {"normalize": true}}),+ json!({"options": {"max_seq_length": 16}}),+ ] {+ assert_eq!(outputs("encode", params.clone()), None, "{params}");+ }+ assert_eq!(numerical_request_outputs("encode", None), None);+ assert_eq!(outputs("extract", json!({})), None);+ }+#[test]fn test_unanimous_terminal_client_errors_map_to_400_and_413() {for (code, status) in [@@ -23150,6 +23567,8 @@ mod tests {fn worker_msg(bundle: &str, gpu: &str, pool: &str) -> WorkerStatusMessage {WorkerStatusMessage {supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,name: "worker-1".into(),ready: true,gpu_count: 1,diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rsindex 318380bf7..a99c71c53 100644--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs@@ -3248,4 +3248,434 @@ mod tests {assert_eq!(response.status(), StatusCode::OK);assert_eq!(response.headers()["x-sie-fallback-reason"], "provisioning");}++ const ADMITTED_IDENTITY: &str =+ "v2:sha256:1111111111111111111111111111111111111111111111111111111111111111";+ const UNADMITTED_IDENTITY: &str =+ "v2:sha256:2222222222222222222222222222222222222222222222222222222222222222";+ const MODEL_CONTRACT: &str = "3333333333333333333333333333333333333333333333333333333333333333";++ fn unix_ms_from_now(offset_ms: i64) -> u64 {+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_millis() as i64;+ (now + offset_ms) as u64+ }++ fn inventory(profile: serde_json::Value) -> serde_json::Value {+ json!({+ "observed_at_unix_ms": 1,+ "children": [{+ "child_index": 0,+ "status": "observed",+ "snapshot": {+ "runtime_instance_id": "9".repeat(64),+ "complete": true,+ "profiles": [profile],+ },+ }],+ })+ }++ fn remote_admission(expires_in_ms: i64) -> serde_json::Value {+ inventory(json!({+ "model_id": "acme/hybrid-encode",+ "model_contract_sha256": MODEL_CONTRACT,+ "local_identity": null,+ "admission": {+ "sha256": "a".repeat(64),+ "kind": "sie",+ "local_identities": [ADMITTED_IDENTITY],+ "model_contract_sha256": MODEL_CONTRACT,+ "outputs": ["dense"],+ "expires_at_unix_ms": unix_ms_from_now(expires_in_ms),+ },+ }))+ }++ fn local_identity(identity: &str) -> serde_json::Value {+ inventory(json!({+ "model_id": "acme/hybrid-encode",+ "model_contract_sha256": MODEL_CONTRACT,+ "local_identity": identity,+ }))+ }++ async fn numerical_gateway(policy: &str, threshold: bool) -> TestGateway {+ let encode = format!("{HYBRID_ENCODE_MODEL}{policy}");+ let gateway = TestGateway::with_threshold_routing(&[&encode], threshold).await;+ gateway+ .add_numerical_worker("remote-1", REMOTE_LANE, &[], true, remote_admission(60_000))+ .await;+ gateway+ }++ const NUMERICAL_FALLBACK: &str = "\nrouting:\n policy: fallback\n fallback_profile: remote\n";++ async fn encode(gateway: &TestGateway, body: serde_json::Value) -> Response {+ proxy_request(+ State(Arc::clone(&gateway.state)),+ json_request("/v1/encode/acme/hybrid-encode", body),+ "encode",+ )+ .await+ }++ fn assert_numerical_work_stayed_local(gateway: &TestGateway, response: &Response, case: &str) {+ assert!(+ !response.headers().contains_key("x-sie-fallback-reason"),+ "{case}"+ );+ assert_ne!(stamped(response).0, Some("remote"), "{case}");+ assert!(+ gateway+ .dispatcher+ .dispatched()+ .iter()+ .all(|work| work.bundle != REMOTE_LANE.2),+ "{case}"+ );+ assert!(+ gateway+ .dispatcher+ .numerical_admissions()+ .iter()+ .all(Option::is_none),+ "{case}"+ );+ }++ #[tokio::test]+ async fn an_admitted_numerical_bridge_names_the_admission_its_worker_advertised() {+ for local in ["cold", "loading"] {+ let gateway = numerical_gateway(NUMERICAL_FALLBACK, false).await;+ if local == "loading" {+ gateway+ .add_numerical_worker(+ "local-1",+ LOCAL_LANE,+ &[],+ true,+ local_identity(ADMITTED_IDENTITY),+ )+ .await;+ }+ let response = encode(&gateway, json!({"items":[{"text":"hello"}]})).await;+ assert_eq!(response.status(), StatusCode::OK, "{local}");+ assert_eq!(+ stamped(&response),+ (Some("remote"), Some("team-sie")),+ "{local}"+ );+ let remote: Vec<_> = gateway+ .dispatcher+ .dispatched()+ .into_iter()+ .filter(|work| work.endpoint != "load")+ .zip(gateway.dispatcher.numerical_admissions())+ .zip(gateway.dispatcher.fallback_reasons())+ .filter(|((work, _), _)| work.bundle == REMOTE_LANE.2)+ .collect();+ assert_eq!(remote.len(), 1, "{local}");+ let ((work, admission), reason) = &remote[0];+ assert_eq!(work.model, "acme/hybrid-encode:remote");+ assert_eq!(+ admission.as_deref(),+ Some("a".repeat(64).as_str()),+ "{local}"+ );+ assert!(reason.is_some(), "{local}");+ }+ }++ #[tokio::test]+ async fn the_embeddings_route_bridges_numerical_work_under_the_same_admission() {+ let gateway = numerical_gateway(NUMERICAL_FALLBACK, false).await;+ let response = proxy_openai_embeddings(+ State(Arc::clone(&gateway.state)),+ json_request(+ "/v1/embeddings",+ json!({"model":"acme/hybrid-encode", "input":"hello"}),+ ),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ gateway.dispatcher.numerical_admissions(),+ vec![Some("a".repeat(64))]+ );+ }++ #[tokio::test]+ async fn numerical_work_stays_local_unless_a_current_admission_covers_every_local_process() {+ for case in [+ "uncovered local identity",+ "local worker without inventory",+ "admission about to expire",+ "remote worker without the fence",+ "profile selected in the body",+ "health heard for less than a heartbeat timeout",+ "quantized output",+ "a runtime option the admission did not measure",+ "an output the admission did not measure",+ ] {+ let mut gateway = numerical_gateway(NUMERICAL_FALLBACK, false).await;+ gateway.set_request_timeout(1.0);+ let mut body = json!({"items":[{"text":"hello"}]});+ match case {+ "uncovered local identity" => {+ gateway+ .add_numerical_worker(+ "local-1",+ LOCAL_LANE,+ &[],+ true,+ local_identity(UNADMITTED_IDENTITY),+ )+ .await;+ }+ "local worker without inventory" => {+ gateway+ .add_verified_worker("local-1", LOCAL_LANE, &[])+ .await;+ }+ "admission about to expire" => {+ gateway+ .add_numerical_worker(+ "remote-1",+ REMOTE_LANE,+ &[],+ true,+ remote_admission(4_000),+ )+ .await;+ }+ "remote worker without the fence" => {+ gateway+ .add_numerical_worker(+ "remote-1",+ REMOTE_LANE,+ &[],+ false,+ remote_admission(60_000),+ )+ .await;+ }+ "profile selected in the body" => {+ body = json!({"items":[{"text":"hello"}], "params":{"options":{"profile":"default"}}});+ }+ "health heard for less than a heartbeat timeout" => {+ gateway.state.registry.health_subscription_started();+ }+ "quantized output" => {+ body = json!({"items":[{"text":"hello"}], "params":{"output_dtype":"int8"}});+ }+ "a runtime option the admission did not measure" => {+ body = json!({"items":[{"text":"hello"}], "params":{"options":{"normalize":false}}});+ }+ "an output the admission did not measure" => {+ body =+ json!({"items":[{"text":"hello"}], "params":{"output_types":["sparse"]}});+ }+ _ => unreachable!(),+ }+ let response = encode(&gateway, body).await;+ assert!(!response.status().is_success(), "{case}");+ assert_numerical_work_stayed_local(&gateway, &response, case);+ }+ }++ #[tokio::test]+ async fn threshold_routes_numerical_work_remote_only_under_a_covering_admission() {+ use crate::handlers::test_support::ThresholdBroker;+ use crate::state::threshold_coordinator::{ThresholdDecision, ThresholdSampler};+ let policy = "\nrouting:\n policy: threshold\n fallback_profile: remote\n wake_above: 1\n sleep_below: 0.5\n window_s: 1\n cooldown_s: 1\n";+ for covered in [true, false] {+ let Some(broker) = ThresholdBroker::start().await else {+ return;+ };+ let mut gateway = numerical_gateway(policy, true).await;+ gateway.set_request_timeout(1.0);+ gateway+ .add_numerical_worker(+ "local-1",+ LOCAL_LANE,+ &["acme/hybrid-encode"],+ true,+ local_identity(if covered {+ ADMITTED_IDENTITY+ } else {+ UNADMITTED_IDENTITY+ }),+ )+ .await;+ let binding = broker.bind(&gateway).await;+ let mut sampler = ThresholdSampler::default();+ binding.coordinator.sample(&mut sampler).await.unwrap();+ for _ in 0..2 {+ tokio::time::sleep(Duration::from_millis(1050)).await;+ binding.coordinator.sample(&mut sampler).await.unwrap();+ }+ assert_eq!(+ binding.coordinator.decision("acme/hybrid-encode").unwrap(),+ ThresholdDecision::Remote+ );+ let response = encode(&gateway, json!({"items":[{"text":"hello"}]})).await;+ assert_eq!(response.status(), StatusCode::OK, "covered={covered}");+ if covered {+ assert_eq!(stamped(&response), (Some("remote"), Some("team-sie")));+ assert_eq!(+ gateway.dispatcher.numerical_admissions(),+ vec![Some("a".repeat(64))]+ );+ assert_eq!(gateway.dispatcher.fallback_reasons(), vec![None]);+ } else {+ assert_numerical_work_stayed_local(+ &gateway,+ &response,+ "uncovered threshold route",+ );+ }+ }+ }++ #[tokio::test]+ async fn a_refused_admitted_threshold_attempt_is_answered_at_once() {+ use crate::handlers::test_support::ThresholdBroker;+ use crate::state::threshold_coordinator::{ThresholdDecision, ThresholdSampler};+ let Some(broker) = ThresholdBroker::start().await else {+ return;+ };+ let policy = "\nrouting:\n policy: threshold\n fallback_profile: remote\n wake_above: 1\n sleep_below: 0.5\n window_s: 1\n cooldown_s: 1\n";+ let mut gateway = numerical_gateway(policy, true).await;+ gateway.set_request_timeout(30.0);+ let binding = broker.bind(&gateway).await;+ let mut sampler = ThresholdSampler::default();+ binding.coordinator.sample(&mut sampler).await.unwrap();+ for _ in 0..2 {+ tokio::time::sleep(Duration::from_millis(1050)).await;+ binding.coordinator.sample(&mut sampler).await.unwrap();+ }+ assert_eq!(+ binding.coordinator.decision("acme/hybrid-encode").unwrap(),+ ThresholdDecision::Remote+ );+ gateway+ .dispatcher+ .answer_only_bridged_remote_work("INFERENCE_ERROR", 1);+ let started = std::time::Instant::now();+ let response = encode(&gateway, json!({"items":[{"text":"hello"}]})).await;+ assert!(started.elapsed() < Duration::from_secs(5));+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(response.headers()["retry-after"], "1");+ assert_eq!(response.headers()["x-sie-error-code"], "INFERENCE_ERROR");+ assert_eq!(+ gateway.dispatcher.numerical_admissions(),+ vec![Some("a".repeat(64))]+ );+ }++ #[tokio::test]+ async fn a_worker_of_another_pool_does_not_close_the_bridge() {+ let gateway = numerical_gateway(NUMERICAL_FALLBACK, false).await;+ gateway+ .add_numerical_worker(+ "batch-1",+ ("batch", LOCAL_LANE.1, LOCAL_LANE.2),+ &[],+ true,+ inventory(json!({+ "model_id": "acme/batch-only",+ "model_contract_sha256": MODEL_CONTRACT,+ "local_identity": UNADMITTED_IDENTITY,+ })),+ )+ .await;+ let response = encode(&gateway, json!({"items":[{"text":"hello"}]})).await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ gateway.dispatcher.numerical_admissions(),+ vec![Some("a".repeat(64))]+ );+ }++ #[tokio::test]+ async fn a_request_that_can_never_bridge_keeps_its_ordinary_local_path() {+ let gateway = numerical_gateway(NUMERICAL_FALLBACK, false).await;+ gateway+ .add_numerical_worker(+ "local-1",+ LOCAL_LANE,+ &[],+ true,+ local_identity(ADMITTED_IDENTITY),+ )+ .await;+ let response = encode(+ &gateway,+ json!({"items":[{"text":"hello"}], "params":{"output_dtype":"int8"}}),+ )+ .await;+ assert!(+ !response.headers().contains_key("x-sie-fallback-reason"),+ "a request outside the admission is not a bridge candidate"+ );+ assert!(gateway+ .dispatcher+ .dispatched()+ .iter()+ .all(|work| work.endpoint != "load" && work.bundle != REMOTE_LANE.2));+ assert!(gateway+ .dispatcher+ .dispatched()+ .iter()+ .any(|work| work.bundle == LOCAL_LANE.2));+ assert!(gateway+ .dispatcher+ .numerical_admissions()+ .iter()+ .all(Option::is_none));+ }++ #[tokio::test]+ async fn an_admitted_numerical_bridge_accepts_a_query_flag() {+ let gateway = numerical_gateway(NUMERICAL_FALLBACK, false).await;+ let response = encode(+ &gateway,+ json!({"items":[{"text":"hello"}], "params":{"is_query":true, "options":{"is_query":true}}}),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ gateway.dispatcher.numerical_admissions(),+ vec![Some("a".repeat(64))]+ );+ }++ #[tokio::test]+ async fn an_invalid_numerical_request_is_refused_before_either_side_counts_it() {+ for policy in [+ NUMERICAL_FALLBACK,+ "\nrouting:\n policy: threshold\n fallback_profile: remote\n wake_above: 1\n sleep_below: 0.5\n window_s: 1\n cooldown_s: 1\n",+ ] {+ let gateway = numerical_gateway(policy, policy != NUMERICAL_FALLBACK).await;+ gateway+ .add_verified_worker("local-1", LOCAL_LANE, &[])+ .await;+ for body in [+ json!({"items":"not-an-array"}),+ json!({"items":[]}),+ ] {+ let response = encode(&gateway, body.clone()).await;+ assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{body}");+ assert!(+ !response.headers().contains_key("x-sie-fallback-reason"),+ "{body}"+ );+ }+ assert!(gateway.dispatcher.dispatched().is_empty());+ assert!(gateway.dispatcher.numerical_admissions().is_empty());+ }+ }}diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex a7164c9c9..f8faceb59 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -173,6 +173,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {&bundle,&bundle_config_hash,&admission_pool,+ None,).await{diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rsindex c8a06f450..781c11162 100644--- a/packages/sie_gateway/src/handlers/test_support.rs+++ b/packages/sie_gateway/src/handlers/test_support.rs@@ -173,6 +173,7 @@ pub(crate) struct RecordingDispatcher {dispatched: Mutex<Vec<Dispatched>>,execution_authority: Mutex<Vec<bool>>,fallback_reasons: Mutex<Vec<Option<FallbackTrigger>>>,+ numerical_admissions: Mutex<Vec<Option<String>>>,}impl RecordingDispatcher {@@ -225,10 +226,16 @@ impl RecordingDispatcher {self.fallback_reasons.lock().unwrap().clone()}+ /// The numerical admission each published work request named, in order.+ pub(crate) fn numerical_admissions(&self) -> Vec<Option<String>> {+ self.numerical_admissions.lock().unwrap().clone()+ }+/// Answer remote-lane work the way a remote worker whose backend asks for- /// redelivery does: a remote attempt that carries a fallback reason gets a- /// retryable `code` result with the upstream's hint at once, while other- /// work is redelivered, so its result never arrives.+ /// redelivery does: a remote attempt that carries a fallback reason or a+ /// numerical admission gets a retryable `code` result with the upstream's+ /// hint at once, while other work is redelivered, so its result never+ /// arrives.pub(crate) fn answer_only_bridged_remote_work(&self, code: &'static str, retry_after_s: u32) {*self.bridged_refusal.lock().unwrap() = Some((code, retry_after_s));}@@ -273,7 +280,7 @@ impl RecordingDispatcher {fn record_authority(&self, target: &PublishTarget, params: &WorkParams) {assert!(- !params.require_execution_authority_v1+ !(params.require_execution_authority_v1 || params.numerical_admission_sha256.is_some())|| matches!(target, PublishTarget::VerifiedWorker { .. }),"verified execution requires a verified worker target");@@ -428,6 +435,10 @@ impl WorkDispatcher for RecordingDispatcher {.lock().unwrap().push(params.fallback_reason);+ self.numerical_admissions+ .lock()+ .unwrap()+ .push(params.numerical_admission_sha256.clone());if self.work_refused.load(Ordering::SeqCst) {return Err(DispatchError::Other("private upstream failure".into()));}@@ -437,7 +448,7 @@ impl WorkDispatcher for RecordingDispatcher {bridged_refusal.filter(|_| target.bundle() == REMOTE_LANE.2){let (tx, rx) = oneshot::channel();- if params.fallback_reason.is_some() {+ if params.fallback_reason.is_some() || params.numerical_admission_sha256.is_some() {let refused = (0..items.len().max(1) as u32).map(|index| refused_result(&request_id, index, (code, Some(retry_after_s)))).collect();@@ -767,6 +778,42 @@ impl TestGateway {.await;}+ /// Register a verified worker whose heartbeat also reports `inventory`,+ /// with `numerical` support for re-verifying a numerical admission.+ pub(crate) async fn add_numerical_worker(+ &self,+ name: &str,+ lane: (&str, &str, &str),+ loaded: &[&str],+ numerical: bool,+ inventory: serde_json::Value,+ ) {+ let (pool, machine_profile, bundle) = lane;+ let status = WorkerStatusMessage {+ supports_execution_authority_v1: true,+ supports_numerical_admission_v1: numerical,+ supports_numerical_admission_subject_v1: numerical,+ name: name.to_string(),+ ready: true,+ gpu_count: 1,+ machine_profile: machine_profile.to_string(),+ pool_name: pool.to_string(),+ bundle: bundle.to_string(),+ bundle_config_hash: self+ .state+ .model_registry+ .compute_bundle_config_hash_for_pool(bundle, pool),+ loaded_models: loaded.iter().map(|model| model.to_string()).collect(),+ numerical_process_inventory: Some(serde_json::from_value(inventory).unwrap()),+ ..Default::default()+ };+ self.state+ .registry+ .update_worker(&format!("http://{name}:8080"), status)+ .await;+ self.state.registry.settle_health_view_for_tests();+ }+async fn add_worker_with_authority(&self,name: &str,diff --git a/packages/sie_gateway/src/observability/metrics.rs b/packages/sie_gateway/src/observability/metrics.rsindex 75ca4a0fe..ba5e69051 100644--- a/packages/sie_gateway/src/observability/metrics.rs+++ b/packages/sie_gateway/src/observability/metrics.rs@@ -28,6 +28,9 @@ pub const REMOTE_SERVING_DURATION_METRIC_NAME: &str = "sie.gateway.remote.servinpub const REMOTE_FALLBACK_MODEL_LIMIT: usize = 256;const REMOTE_SERVING_MAX_IDLE: Duration = Duration::from_secs(300);pub const REMOTE_FALLBACK_COUNTER_LIMIT: usize = (REMOTE_FALLBACK_MODEL_LIMIT + 1) * 7 * 4 * 2;+pub const REMOTE_NUMERICAL_ADMISSIONS_METRIC_NAME: &str = "sie.gateway.remote.numerical_admissions";+pub const REMOTE_NUMERICAL_ADMISSION_COUNTER_LIMIT: usize =+ (REMOTE_FALLBACK_MODEL_LIMIT + 1) * 7 * 2 * 5;pub const PENDING_DEMAND_METRIC_NAME: &str = "sie.gateway.pending_demand";pub const LANE_QUEUE_DEPTH_METRIC_NAME: &str = "sie.gateway.lane.queue.depth";pub const LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME: &str =@@ -851,6 +854,8 @@ struct GatewayTelemetry {remote_fallbacks: Counter<u64>,remote_serving_duration: Gauge<f64>,remote_serving_state: Mutex<RemoteServingState>,+ remote_numerical_admissions: Counter<u64>,+ numerical_admission_models: Mutex<HashSet<String>>,pending_demand: Gauge<f64>,lane_queue_depth: Gauge<f64>,lane_queue_snapshot_timestamp: Gauge<f64>,@@ -954,6 +959,12 @@ impl GatewayTelemetry {.with_unit("s").build(),remote_serving_state: Mutex::new(RemoteServingState::default()),+ remote_numerical_admissions: meter+ .u64_counter(REMOTE_NUMERICAL_ADMISSIONS_METRIC_NAME)+ .with_description("Numerical bridge admission decisions.")+ .with_unit("{request}")+ .build(),+ numerical_admission_models: Mutex::new(HashSet::new()),pending_demand: meter.f64_gauge(PENDING_DEMAND_METRIC_NAME).with_description("Whether a physical worker lane has refreshable unmet demand.")@@ -1663,6 +1674,57 @@ fn record_remote_fallback_to(}}+/// One numerical bridge admission decision: admitted, or refused for `refusal`.+pub(crate) fn record_numerical_admission(+ model: &str,+ operation: &str,+ refusal: Option<crate::state::worker_registry::NumericalRefusal>,+) {+ record_numerical_admission_to(telemetry(), model, operation, refusal);+}++fn record_numerical_admission_to(+ telemetry: Option<&GatewayTelemetry>,+ model: &str,+ operation: &str,+ refusal: Option<crate::state::worker_registry::NumericalRefusal>,+) {+ let Some(telemetry) = telemetry else {+ return;+ };+ let model = {+ let mut models = telemetry+ .numerical_admission_models+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let model = sanitize_model_label(model);+ if model != "other"+ && (models.contains(&model) || models.len() < REMOTE_FALLBACK_MODEL_LIMIT)+ {+ models.insert(model.clone());+ model+ } else {+ "other".to_string()+ }+ };+ telemetry.remote_numerical_admissions.add(+ 1,+ &[+ KeyValue::new("model", model),+ KeyValue::new("operation", bounded_operation(operation)),+ KeyValue::new(+ "outcome",+ if refusal.is_some() {+ "refused"+ } else {+ "admitted"+ },+ ),+ KeyValue::new("reason", refusal.map_or("none", |refusal| refusal.as_str())),+ ],+ );+}+pub(crate) fn record_local_serving_success(model: &str) {record_local_serving_success_to(telemetry(), model);}@@ -2546,6 +2608,77 @@ mod tests {provider.shutdown().unwrap();}+ #[test]+ fn numerical_admission_counter_exports_its_declared_domain_without_sdk_overflow() {+ use crate::state::worker_registry::NumericalRefusal;+ let (telemetry, exporter, provider) = metric_points();+ let decisions = [+ None,+ Some(NumericalRefusal::NoAdmission),+ Some(NumericalRefusal::LocalUnobserved),+ Some(NumericalRefusal::UncoveredIdentity),+ Some(NumericalRefusal::UnmeasuredRequest),+ ];+ for model in 0..=REMOTE_FALLBACK_MODEL_LIMIT {+ for operation in [+ "encode",+ "score",+ "extract",+ "embeddings",+ "moderations",+ "generate",+ "other",+ ] {+ for refusal in decisions {+ record_numerical_admission_to(+ Some(&telemetry),+ &format!("acme/model-{model}"),+ operation,+ refusal,+ );+ }+ }+ }+ record_numerical_admission_to(Some(&telemetry), "private invalid\nlabel", "encode", None);+ provider.force_flush().unwrap();+ let resources = exporter.get_finished_metrics().unwrap();+ let counter = resources+ .iter()+ .flat_map(|resource| resource.scope_metrics())+ .flat_map(|scope| scope.metrics())+ .find(|metric| metric.name() == REMOTE_NUMERICAL_ADMISSIONS_METRIC_NAME)+ .unwrap();+ assert_eq!(counter.unit(), "{request}");+ let AggregatedMetrics::U64(MetricData::Sum(counter)) = counter.data() else {+ panic!("expected numerical admission counter");+ };+ assert_eq!(+ counter.data_points().count(),+ (REMOTE_FALLBACK_MODEL_LIMIT + 1) * 7 * decisions.len()+ );+ for point in counter.data_points() {+ let attributes: HashMap<_, _> = point+ .attributes()+ .map(|attribute| {+ (+ attribute.key.as_str(),+ attribute.value.as_str().into_owned(),+ )+ })+ .collect();+ assert!(!attributes.contains_key("otel.metric.overflow"));+ let mut keys: Vec<_> = attributes.keys().copied().collect();+ keys.sort_unstable();+ assert_eq!(keys, ["model", "operation", "outcome", "reason"]);+ assert_eq!(+ attributes["outcome"] == "admitted",+ attributes["reason"] == "none",+ "{attributes:?}"+ );+ }+ provider.shutdown().unwrap();+ }+#[test]fn every_admission_outcome_is_declared_in_the_telemetry_contract() {let contract: serde_yaml::Value = serde_yaml::from_str(include_str!(concat!(diff --git a/packages/sie_gateway/src/observability/tracing.rs b/packages/sie_gateway/src/observability/tracing.rsindex 87224e28f..17bbd5c95 100644--- a/packages/sie_gateway/src/observability/tracing.rs+++ b/packages/sie_gateway/src/observability/tracing.rs@@ -61,6 +61,7 @@ use crate::observability::metrics::{LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME, PENDING_DEMAND_METRIC_NAME,POOL_WARM_FLOOR_METRIC_NAME, REJECTED_REQUESTS_METRIC_NAME, REMOTE_FALLBACKS_METRIC_NAME,REMOTE_FALLBACK_COUNTER_LIMIT, REMOTE_FALLBACK_MODEL_LIMIT,+ REMOTE_NUMERICAL_ADMISSIONS_METRIC_NAME, REMOTE_NUMERICAL_ADMISSION_COUNTER_LIMIT,REMOTE_SERVING_DURATION_METRIC_NAME,};use crate::state::demand_tracker::MAX_CONFIGURED_PHYSICAL_LANES;@@ -520,6 +521,7 @@ pub(crate) fn keda_metric_cardinality_view(instrument: &Instrument) -> Option<St| POOL_WARM_FLOOR_METRIC_NAME => MAX_CONFIGURED_PHYSICAL_LANES,REJECTED_REQUESTS_METRIC_NAME => KEDA_REJECTED_REQUESTS_CARDINALITY_LIMIT,REMOTE_FALLBACKS_METRIC_NAME => REMOTE_FALLBACK_COUNTER_LIMIT,+ REMOTE_NUMERICAL_ADMISSIONS_METRIC_NAME => REMOTE_NUMERICAL_ADMISSION_COUNTER_LIMIT,REMOTE_SERVING_DURATION_METRIC_NAME => REMOTE_FALLBACK_MODEL_LIMIT,_ => return None,};diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex 55dff6680..504facae1 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -205,6 +205,10 @@ pub struct WorkParams {/// gateway holds that refusal for the caller.#[serde(skip_serializing_if = "Option::is_none")]pub fallback_reason: Option<FallbackTrigger>,+ /// The numerical admission a remote encode or score attempt runs under.+ /// The pinned worker re-verifies it before the upstream sees the item.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub numerical_admission_sha256: Option<String>,}/// Discriminated input for a generate work item.@@ -572,6 +576,10 @@ struct WorkItemRef<'a> {/// Older workers ignore the unknown map field.#[serde(skip_serializing_if = "Option::is_none")]pub fallback_reason: Option<FallbackTrigger>,+ /// Present only on an admitted numerical remote attempt, which is pinned+ /// to a worker that advertised support for re-verifying it.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub numerical_admission_sha256: Option<&'a str>,/// Rolling-upgrade negotiation for `result_chunk_v1` specifically. Older/// workers ignore this unknown map field; workers must keep publishing the/// legacy one-shot ``WorkResult`` unless it is true. A future chunk version@@ -1934,6 +1942,9 @@ pub enum PublishTarget {bundle: String,model: String,worker_id: String,+ /// Admitted numerical work, on a subject that only a worker with the+ /// numerical admission fence consumes.+ numerical_admission: bool,},/// Pool fan-out — any worker subscribed to/// `sie.work.{pool}.{machine_profile}.{bundle}.*` can pick it up.@@ -1962,9 +1973,15 @@ impl PublishTarget {bundle,model,worker_id,+ numerical_admission,} => format!(- "{}.execution-authority-v1",- work_subject_worker(pool, machine_profile, bundle, model, worker_id)+ "{}.{}",+ work_subject_worker(pool, machine_profile, bundle, model, worker_id),+ if *numerical_admission {+ "numerical-admission-v1"+ } else {+ "execution-authority-v1"+ }),PublishTarget::Pool {pool,@@ -1988,7 +2005,15 @@ impl PublishTarget {fn validate_execution_contract(&self, params: &WorkParams, hash: &str) -> Result<(), String> {let verified = matches!(self, Self::VerifiedWorker { .. });+ let admitted = matches!(+ self,+ Self::VerifiedWorker {+ numerical_admission: true,+ ..+ }+ );if (params.require_execution_authority_v1 && !verified)+ || params.numerical_admission_sha256.is_some() != admitted|| (verified && (hash.is_empty() || !Self::verified_model_is_unambiguous(self.model()))){return Err(@@ -3053,6 +3078,7 @@ impl WorkPublisher {timestamp,deadline: Some(timestamp + self.result_timeout.as_secs_f64()),fallback_reason: None,+ numerical_admission_sha256: None,accepts_result_chunks: false,traceparent: None,tracestate: None,@@ -3574,6 +3600,7 @@ impl WorkPublisher {timestamp: shared.timestamp,deadline: shared.deadline,fallback_reason: shared.params.fallback_reason,+ numerical_admission_sha256: shared.params.numerical_admission_sha256.as_deref(),accepts_result_chunks: true,traceparent: shared.traceparent,tracestate: shared.tracestate,@@ -4205,6 +4232,7 @@ impl WorkPublisher {timestamp: shared.timestamp,deadline: shared.deadline,fallback_reason: shared.params.fallback_reason,+ numerical_admission_sha256: shared.params.numerical_admission_sha256.as_deref(),accepts_result_chunks: true,traceparent: shared.traceparent,tracestate: shared.tracestate,@@ -4502,6 +4530,7 @@ impl WorkPublisher {timestamp: shared.timestamp,deadline: shared.deadline,fallback_reason: shared.params.fallback_reason,+ numerical_admission_sha256: shared.params.numerical_admission_sha256.as_deref(),accepts_result_chunks: true,traceparent: shared.traceparent,tracestate: shared.tracestate,@@ -5507,6 +5536,7 @@ mod tests {bundle: "default".into(),model: "Org/model:local".into(),worker_id: "worker-1".into(),+ numerical_admission: false,};assert_eq!(verified.subject(),@@ -5544,6 +5574,57 @@ mod tests {.is_none());}+ #[test]+ fn admitted_work_travels_only_on_the_admission_subject() {+ let target = |numerical_admission| PublishTarget::VerifiedWorker {+ pool: "tenant".into(),+ machine_profile: "l4".into(),+ bundle: "remote".into(),+ model: "Org/model:remote".into(),+ worker_id: "worker-1".into(),+ numerical_admission,+ };+ let admitted = target(true);+ assert_eq!(+ admitted.subject(),+ "sie.work.tenant.l4.remote.Org__model:remote.worker-1.numerical-admission-v1"+ );+ assert!(admitted.pool_fallback_subject().is_none());+ let with_digest = WorkParams {+ require_execution_authority_v1: true,+ numerical_admission_sha256: Some("a".repeat(64)),+ ..Default::default()+ };+ let without_digest = WorkParams {+ require_execution_authority_v1: true,+ ..Default::default()+ };+ assert!(admitted+ .validate_execution_contract(&with_digest, "hash")+ .is_ok());+ assert!(admitted+ .validate_execution_contract(&without_digest, "hash")+ .is_err());+ assert!(target(false)+ .validate_execution_contract(&with_digest, "hash")+ .is_err());+ let pooled = PublishTarget::Pool {+ pool: "tenant".into(),+ machine_profile: "l4".into(),+ bundle: "remote".into(),+ model: "Org/model:remote".into(),+ };+ assert!(pooled+ .validate_execution_contract(+ &WorkParams {+ numerical_admission_sha256: Some("a".repeat(64)),+ ..Default::default()+ },+ "hash"+ )+ .is_err());+ }+/// Two lanes on one pool, differing only in machine profile. The pool-wide/// check cannot tell them apart — the whole point of B5's first half.fn hot_lane() -> LaneKey {@@ -6399,6 +6480,8 @@ mod tests {pub deadline: Option<f64>,#[serde(default, skip_serializing_if = "Option::is_none")]pub fallback_reason: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub numerical_admission_sha256: Option<String>,#[serde(default)]pub accepts_result_chunks: bool,#[serde(default, skip_serializing_if = "Option::is_none")]@@ -7746,6 +7829,7 @@ mod tests {timestamp: 1700000000.0,deadline: None,fallback_reason: None,+ numerical_admission_sha256: None,accepts_result_chunks: true,traceparent: None,tracestate: None,@@ -7882,6 +7966,7 @@ mod tests {timestamp: 1_700_000_000.5,deadline: Some(1_700_000_120.5),fallback_reason: Some("saturated".to_string()),+ numerical_admission_sha256: Some("a".repeat(64)),accepts_result_chunks: true,traceparent: None,tracestate: None,@@ -7926,6 +8011,7 @@ mod tests {timestamp: owned.timestamp,deadline: owned.deadline,fallback_reason: Some(FallbackTrigger::Saturated),+ numerical_admission_sha256: owned.numerical_admission_sha256.as_deref(),accepts_result_chunks: true,traceparent: owned.traceparent.as_deref(),tracestate: owned.tracestate.as_deref(),@@ -8109,6 +8195,7 @@ mod tests {timestamp: 0.0,deadline: None,fallback_reason: None,+ numerical_admission_sha256: None,accepts_result_chunks: true,traceparent: None,tracestate: None,@@ -8797,6 +8884,7 @@ mod tests {timestamp: 1.0,deadline: None,fallback_reason: None,+ numerical_admission_sha256: None,accepts_result_chunks: true,traceparent: None,tracestate: None,@@ -8950,6 +9038,7 @@ mod tests {timestamp: 1.0,deadline: None,fallback_reason: None,+ numerical_admission_sha256: None,accepts_result_chunks: true,traceparent: Some(tp.to_string()),tracestate: Some(ts.to_string()),@@ -8998,6 +9087,7 @@ mod tests {timestamp: 1.0,deadline: None,fallback_reason: None,+ numerical_admission_sha256: None,accepts_result_chunks: true,traceparent: None,tracestate: None,@@ -9825,6 +9915,7 @@ mod tests {routing_key: None,prompt_cache_key: None,fallback_reason: None,+ numerical_admission_sha256: None,};let items = vec![rmpv::Value::Map(vec![(rmpv::Value::String("text".into()),@@ -10107,6 +10198,7 @@ mod tests {routing_key: None,prompt_cache_key: None,fallback_reason: None,+ numerical_admission_sha256: None,};let items = vec![rmpv::Value::Map(vec![(rmpv::Value::String("image".into()),diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 0996885a4..010f4cfe6 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -210,7 +210,6 @@ impl ModelRegistryGeneration {}/// The remote profile and worker contract chosen from one registry snapshot.-/// Numerical hybrid models remain closed until fleet equivalence is admitted.#[derive(Clone, Debug)]pub(crate) struct RemoteFallbackPlan {pub model: String,@@ -220,6 +219,22 @@ pub(crate) struct RemoteFallbackPlan {pub config_hash: String,pub revision: Option<String>,pub served_by: ServedBy,+ /// Set for a model with numerical outputs, whose remote attempt also needs+ /// a current numerical admission that covers the local fleet.+ pub numerical: Option<NumericalRoute>,+}++/// The local side of a numerical bridge, and the remote workers whose+/// admission covers it once the gateway has checked.+#[derive(Clone, Debug)]+pub(crate) struct NumericalRoute {+ /// The bare model, as worker inventories name it.+ pub model: String,+ pub local_bundles: Vec<String>,+ /// The model's own pool, `default` when it names none. Workers load only+ /// the models of their own pool.+ pub local_pool: String,+ pub admitted: Option<Arc<crate::state::worker_registry::AdmittedWorkers>>,}pub struct ModelRegistry {@@ -769,18 +784,6 @@ impl ModelRegistry {if matches!(routing.policy, RoutingPolicy::Threshold) && !threshold_enabled {return Err("routing policy threshold is not available yet".into());}- if routing.policy == RoutingPolicy::Threshold- && entry.info_extras.outputs.iter().any(|output| {- matches!(- output.as_str(),- "dense" | "sparse" | "multivector" | "score"- )- })- {- return Err(- "threshold routing requires fleet equivalence for numerical outputs".into(),- );- }let profile_kind = |name: &str| {entry.profile_configs@@ -1749,9 +1752,23 @@ impl ModelRegistry {})}+ /// Whether a bare local model with numerical outputs declares a bridge,+ /// so its encode and score requests may need a numerical admission.+ pub(crate) fn has_numerical_bridge(&self, model: &str) -> bool {+ if model.contains(':') {+ return false;+ }+ let snap = self.snapshot.load();+ Self::canonical_model_name(&snap, model)+ .and_then(|canonical| snap.models.get(&canonical))+ .and_then(|local| Self::remote_plan_from_snapshot(&snap, local))+ .is_some_and(|plan| plan.numerical.is_some())+ }+/// Resolve only a bare local model's configured and enabled bridge./// The route, disclosure and exact worker hash share one snapshot; caller- /// profile selectors and numerical models cannot acquire this authority.+ /// profile selectors cannot acquire this authority, and a numerical plan+ /// still needs the gateway's admission check.pub(crate) fn remote_fallback_plan(&self,model: &str,@@ -1767,12 +1784,6 @@ impl ModelRegistry {if !routing.permits(trigger)|| local.canonical_profile != "default"|| !matches!(local.served_by(), ServedBy::Local)- || local.info_extras.outputs.iter().any(|output| {- matches!(- output.as_str(),- "dense" | "sparse" | "multivector" | "score"- )- }){return None;}@@ -1783,15 +1794,7 @@ impl ModelRegistry {snap: &RegistrySnapshot,local: &ModelEntry,) -> Option<RemoteFallbackPlan> {- if local.canonical_profile != "default"- || !matches!(local.served_by(), ServedBy::Local)- || local.info_extras.outputs.iter().any(|output| {- matches!(- output.as_str(),- "dense" | "sparse" | "multivector" | "score"- )- })- {+ if local.canonical_profile != "default" || !matches!(local.served_by(), ServedBy::Local) {return None;}let routing = local.info_extras.routing.as_ref()?;@@ -1814,6 +1817,22 @@ impl ModelRegistry {if config_hash.is_empty() {return None;}+ let numerical = local+ .info_extras+ .outputs+ .iter()+ .any(|output| {+ matches!(+ output.as_str(),+ "dense" | "sparse" | "multivector" | "score"+ )+ })+ .then(|| NumericalRoute {+ model: local.canonical_base_model.clone(),+ local_bundles: local.bundles.clone(),+ local_pool: Self::normalize_pool_name(Self::entry_pool_name(local)),+ admitted: None,+ });Some(RemoteFallbackPlan {model: remote_name,engine: snap.bundles.get(&bundle)?.engine.clone(),@@ -1822,6 +1841,7 @@ impl ModelRegistry {config_hash,revision: Self::immutable_model_revision(remote),served_by,+ numerical,})}@@ -3051,7 +3071,7 @@ mod tests {}#[test]- fn threshold_flag_admits_generation_but_keeps_numerical_and_zero_epoch_gates() {+ fn threshold_flag_admits_generation_and_numerical_models_but_keeps_the_zero_epoch_gate() {let (_dir, mut registry, mut config) = remote_routing_fixture();registry.threshold_enabled = true;config.routing = Some(@@ -3068,11 +3088,11 @@ mod tests {assert_eq!(registry.threshold_targets(1).unwrap().1.len(), 1);assert!(registry.threshold_targets(0).is_err());config.tasks = Some(serde_yaml::from_str("encode:\n dense:\n dim: 2\n").unwrap());- assert!(registry+ registry.replace_model_configs_authoritative(vec![config])- .unwrap_err()- .contains("fleet equivalence"));+ .unwrap();assert_eq!(registry.threshold_targets(1).unwrap().1.len(), 1);+ assert!(registry.has_numerical_bridge("acme/hybrid"));}#[tokio::test]@@ -3319,7 +3339,7 @@ mod tests {}#[test]- fn fallback_plan_never_treats_numerical_dimensions_as_fleet_equivalence() {+ fn a_numerical_plan_names_its_local_route_and_is_not_yet_admitted() {let (_dir, registry, mut config) = remote_routing_fixture();config.routing = Some(serde_json::from_value(serde_json::json!({@@ -3327,10 +3347,35 @@ mod tests {})).unwrap(),);- registry.add_model_config(config).unwrap();- assert!(registry+ config.tasks = Some(serde_yaml::from_str("encode:\n dense:\n dim: 2\n").unwrap());+ registry.add_model_config(config.clone()).unwrap();+ let plan = registry.remote_fallback_plan("acme/hybrid", FallbackTrigger::Provisioning)- .is_none());+ .unwrap();+ let route = plan+ .numerical+ .expect("a numerical model's plan needs admission");+ assert_eq!(route.model, "acme/hybrid");+ assert_eq!(route.local_bundles, ["default"]);+ assert_eq!(+ route.local_pool, DEFAULT_MODEL_POOL,+ "a model without a pool is served from the default pool"+ );+ assert!(route.admitted.is_none());+ assert!(registry.has_numerical_bridge("acme/hybrid"));+ assert!(!registry.has_numerical_bridge("acme/hybrid:remote"));++ for (pool, expected) in [("default", DEFAULT_MODEL_POOL), (" Tenant ", "tenant")] {+ let mut pooled = config.clone();+ pooled.pool = Some(pool.to_string());+ registry+ .replace_model_configs_authoritative(vec![pooled])+ .unwrap();+ let plan = registry+ .remote_fallback_plan("acme/hybrid", FallbackTrigger::Provisioning)+ .unwrap();+ assert_eq!(plan.numerical.unwrap().local_pool, expected, "{pool}");+ }}#[test]diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rsindex 9375dbd6d..b8ef12b01 100644--- a/packages/sie_gateway/src/state/worker_registry.rs+++ b/packages/sie_gateway/src/state/worker_registry.rs@@ -1,6 +1,6 @@use std::collections::{HashMap, HashSet};use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::Arc;+use std::sync::{Arc, Mutex, PoisonError};use std::time::{Duration, Instant};use arc_swap::ArcSwap;@@ -9,11 +9,105 @@ use tokio::sync::RwLock;use crate::routing::hrw::{RingEntry, RingSnapshot};use crate::state::pool_manager::normalize_pool_name;use crate::types::model::FallbackTrigger;-use crate::types::worker::MAX_UNSUPPORTED_MODELS;+use crate::types::worker::{+ NumericalAdmissionObservation, NumericalSnapshotStatus, MAX_UNSUPPORTED_MODELS,+};use crate::types::{ClusterStatus, ModelInfo, WorkerHealth, WorkerInfo, WorkerState, WorkerStatusMessage,};+/// An admission must outlive this margin when a bridge relies on it, so the+/// remote process does not refuse the item for expiry while it is in flight.+pub(crate) const NUMERICAL_ADMISSION_EXPIRY_MARGIN_MS: u64 = 5_000;++/// The two sides of a numerical bridge for one model.+pub(crate) struct NumericalLanes<'a> {+ /// The bare model, as worker inventories name it.+ pub model: &'a str,+ pub local_bundles: &'a [String],+ /// The model's own pool, `default` when it names none. Workers load only+ /// the models of their own pool.+ pub local_pool: &'a str,+ /// The remote profile's routable id and its exact lane contract.+ pub remote_model: &'a str,+ pub remote_bundle: &'a str,+ pub remote_pool: &'a str,+ pub remote_hash: &'a str,+ /// The outputs the request asks for, all of which the admission must list.+ pub outputs: &'a [String],+}++/// A numerical bridge pinned to the admitted remote workers of one model.+pub(crate) struct NumericalPin<'a> {+ /// The bare model, as worker inventories name it.+ pub model: &'a str,+ pub admitted: &'a AdmittedWorkers,+}++/// Why a numerical bridge stays closed.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum NumericalRefusal {+ /// No eligible remote worker advertises a current admission.+ NoAdmission,+ /// A live local worker has no complete process inventory.+ LocalUnobserved,+ /// A live local process reports an identity or model contract the+ /// admission does not cover.+ UncoveredIdentity,+ /// The request asks for runtime options or outputs that the admission+ /// did not measure.+ UnmeasuredRequest,+}++impl NumericalRefusal {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::NoAdmission => "no_admission",+ Self::LocalUnobserved => "local_unobserved",+ Self::UncoveredIdentity => "uncovered_identity",+ Self::UnmeasuredRequest => "unmeasured_request",+ }+ }+}++/// Admitted remote worker names, each with the admission digest it advertises.+pub(crate) type AdmittedWorkers = HashMap<String, String>;++/// The admission every observed child of a remote worker reports for `model`,+/// with the earliest expiry, when it outlives the margin.+fn remote_admission<'a>(+ worker: &'a WorkerState,+ model: &str,+ now_unix_ms: u64,+) -> Option<&'a NumericalAdmissionObservation> {+ let inventory = worker.numerical_process_inventory.as_deref()?;+ let mut agreed: Option<&NumericalAdmissionObservation> = None;+ let mut expires_at_unix_ms = u64::MAX;+ for child in &inventory.children {+ if child.status != NumericalSnapshotStatus::Observed {+ return None;+ }+ let profile = child+ .snapshot+ .as_ref()?+ .profiles+ .iter()+ .find(|profile| profile.model_id == model)?;+ let admission = profile.admission.as_ref()?;+ if profile.model_contract_sha256.as_deref()+ != Some(admission.model_contract_sha256.as_str())+ || agreed.is_some_and(|agreed| agreed.sha256 != admission.sha256)+ {+ return None;+ }+ agreed = Some(admission);+ expires_at_unix_ms = expires_at_unix_ms.min(admission.expires_at_unix_ms);+ }+ agreed.filter(|_| {+ expires_at_unix_ms >= now_unix_ms.saturating_add(NUMERICAL_ADMISSION_EXPIRY_MARGIN_MS)+ })+}+/// Rate-limit gate for the duplicate-worker-name warning, in whole/// seconds since process start. `ring_snapshot_for` runs on the/// per-request hot path, so an unconditional `warn!` on a persistent@@ -96,12 +190,16 @@ struct RegistrySnapshot {all_healthy: Vec<WorkerState>,/// Healthy workers indexed by lowercase bundle name.by_bundle: HashMap<String, Vec<WorkerState>>,+ /// Every registered worker, whatever its health. Numerical admission must+ /// see starting and degraded workers that may serve a model next.+ all: Vec<WorkerState>,}impl RegistrySnapshot {fn build(workers: &HashMap<String, WorkerState>) -> Self {let mut all_healthy = Vec::new();let mut by_bundle: HashMap<String, Vec<WorkerState>> = HashMap::new();+ let all = workers.values().cloned().collect();for w in workers.values() {if !w.healthy() {@@ -117,6 +215,7 @@ impl RegistrySnapshot {Self {all_healthy,by_bundle,+ all,}}}@@ -140,6 +239,17 @@ pub struct WorkerRegistry {request_count: AtomicU64,last_qps_calculation: RwLock<Instant>,current_qps: RwLock<f64>,+ health_view: Mutex<HealthView>,+}++/// How long this gateway has heard worker health without a gap. A worker+/// that has not reported yet is indistinguishable from an absent one, so a+/// numerical admission waits one heartbeat timeout after the health stream+/// starts, resumes, or delivers a status after a longer silence.+#[derive(Default)]+struct HealthView {+ continuous_since: Option<Instant>,+ last_status: Option<Instant>,}impl WorkerRegistry {@@ -174,7 +284,58 @@ impl WorkerRegistry {request_count: AtomicU64::new(0),last_qps_calculation: RwLock::new(Instant::now()),current_qps: RwLock::new(0.0),+ health_view: Mutex::new(HealthView::default()),+ }+ }++ /// Record that the health subscription started or resumed. Statuses+ /// published while it was down were never seen.+ pub fn health_subscription_started(&self) {+ let now = Instant::now();+ let mut view = self+ .health_view+ .lock()+ .unwrap_or_else(PoisonError::into_inner);+ view.continuous_since = Some(now);+ view.last_status = Some(now);+ }++ fn note_health_status(&self) {+ let now = Instant::now();+ let mut view = self+ .health_view+ .lock()+ .unwrap_or_else(PoisonError::into_inner);+ if view+ .last_status+ .is_none_or(|last| now.duration_since(last) > self.heartbeat_timeout)+ {+ view.continuous_since = Some(now);}+ view.last_status = Some(now);+ }++ /// Whether every live worker has had a heartbeat timeout to report since+ /// this gateway's view of worker health last became continuous.+ fn health_view_is_settled(&self) -> bool {+ self.health_view+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .continuous_since+ .is_some_and(|since| since.elapsed() >= self.heartbeat_timeout)+ }++ #[cfg(test)]+ pub(crate) fn settle_health_view_for_tests(&self) {+ let mut view = self+ .health_view+ .lock()+ .unwrap_or_else(PoisonError::into_inner);+ let settled = Instant::now()+ .checked_sub(self.heartbeat_timeout)+ .unwrap_or_else(Instant::now);+ view.continuous_since = Some(settled);+ view.last_status = Some(Instant::now());}/// Rebuild the pre-computed snapshot from the current worker state.@@ -193,6 +354,7 @@ impl WorkerRegistry {}pub async fn update_worker(&self, url: &str, msg: WorkerStatusMessage) -> bool {+ self.note_health_status();let (became_healthy, became_degraded, worker_copy) = {let mut workers = self.workers.write().await;let exists = workers.contains_key(url);@@ -208,6 +370,8 @@ impl WorkerRegistry {bundle: "default".to_string(),bundle_config_hash: String::new(),supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,numerical_process_inventory: None,models: Vec::new(),queue_depth: 0,@@ -239,6 +403,10 @@ impl WorkerRegistry {};w.bundle_config_hash = msg.bundle_config_hash.clone();w.supports_execution_authority_v1 = msg.supports_execution_authority_v1;+ w.supports_numerical_admission_v1 =+ msg.supports_execution_authority_v1 && msg.supports_numerical_admission_v1;+ w.supports_numerical_admission_subject_v1 =+ w.supports_numerical_admission_v1 && msg.supports_numerical_admission_subject_v1;// Replace on every heartbeat: legacy or invalid observations clear// the previous process inventory rather than retaining stale IDs.w.numerical_process_inventory = msg@@ -847,7 +1015,8 @@ impl WorkerRegistry {/// Select only a fresh, positively capable worker for verified direct dispatch./// The versioned subject keeps the execution fence even after a worker rollback.- pub fn execution_authority_worker(+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn execution_authority_worker(&self,model: &str,pool: &str,@@ -855,6 +1024,7 @@ impl WorkerRegistry {bundle: &str,expected_hash: &str,admitted_worker_names: Option<&HashSet<String>>,+ numerical: Option<&NumericalPin<'_>>,) -> Option<String> {if expected_hash.is_empty() {return None;@@ -877,6 +1047,7 @@ impl WorkerRegistry {&& w.machine_profile.eq_ignore_ascii_case(machine_profile)&& w.supports_model(model)&& worker_allowed_by_admission(w, admitted_worker_names)+ && numerical.is_none_or(|pin| self.still_admitted(w, pin))// Avoid subject normalization collisions and ambiguous worker identities.&& !w.name.is_empty()&& w.name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')@@ -902,6 +1073,138 @@ impl WorkerRegistry {crate::routing::pick_worker(&ring, &key).map(str::to_owned)}+ /// Remote workers that may run a numerical bridge for `lanes.model`.+ ///+ /// A remote worker qualifies when it is fresh, eligible, positively+ /// supports execution authority and numerical admission, carries the+ /// exact remote hash, and every one of its children reports the same+ /// current admission, which must list every requested output. Its+ /// admission must then cover every local process that could serve the+ /// model: each child of each worker on the model's local bundles and pool,+ /// starting workers included, must report an admitted identity and the+ /// admission's model contract. A local worker past the heartbeat timeout that has not+ /// been evicted cannot be vouched for, and neither can any worker until+ /// this gateway has heard worker health for one heartbeat timeout. With+ /// no local worker the remote admission decides alone.+ pub(crate) fn numerical_admission(+ &self,+ lanes: &NumericalLanes<'_>,+ now_unix_ms: u64,+ ) -> Result<AdmittedWorkers, NumericalRefusal> {+ let snap = self.snapshot.load();+ let mut name_counts = HashMap::<&str, usize>::with_capacity(snap.all.len());+ for worker in &snap.all {+ *name_counts.entry(worker.name.as_str()).or_default() += 1;+ }+ let advertised: Vec<(&WorkerState, &NumericalAdmissionObservation)> = snap+ .all+ .iter()+ .filter(|w| {+ w.eligible_for_dispatch()+ && w.supports_execution_authority_v1+ && w.supports_numerical_admission_subject_v1+ && w.last_heartbeat.elapsed() <= self.heartbeat_timeout+ && !lanes.remote_hash.is_empty()+ && w.bundle_config_hash == lanes.remote_hash+ && w.bundle.eq_ignore_ascii_case(lanes.remote_bundle)+ && w.pool_name.eq_ignore_ascii_case(lanes.remote_pool)+ && w.supports_model(lanes.remote_model)+ && !w.name.is_empty()+ && w.name+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')+ && name_counts.get(w.name.as_str()) == Some(&1)+ })+ .filter_map(|w| Some((w, remote_admission(w, lanes.model, now_unix_ms)?)))+ .collect();+ if advertised.is_empty() {+ return Err(NumericalRefusal::NoAdmission);+ }+ let remote: Vec<(&WorkerState, &NumericalAdmissionObservation)> = advertised+ .into_iter()+ .filter(|(_, admission)| {+ !lanes.outputs.is_empty()+ && lanes+ .outputs+ .iter()+ .all(|output| admission.outputs.iter().any(|admitted| admitted == output))+ })+ .collect();+ if remote.is_empty() {+ return Err(NumericalRefusal::UnmeasuredRequest);+ }+ if !self.health_view_is_settled() {+ return Err(NumericalRefusal::LocalUnobserved);+ }+ let mut local = Vec::new();+ for worker in snap.all.iter().filter(|w| {+ lanes+ .local_bundles+ .iter()+ .any(|bundle| w.bundle.eq_ignore_ascii_case(bundle))+ && w.pool_name.eq_ignore_ascii_case(lanes.local_pool)+ && w.supports_model(lanes.model)+ }) {+ if worker.last_heartbeat.elapsed() > self.heartbeat_timeout {+ return Err(NumericalRefusal::LocalUnobserved);+ }+ let Some(inventory) = worker.numerical_process_inventory.as_deref() else {+ return Err(NumericalRefusal::LocalUnobserved);+ };+ for child in &inventory.children {+ let Some(snapshot) = child+ .snapshot+ .as_ref()+ .filter(|_| child.status == NumericalSnapshotStatus::Observed)+ else {+ return Err(NumericalRefusal::LocalUnobserved);+ };+ let profile = snapshot+ .profiles+ .iter()+ .find(|profile| profile.model_id == lanes.model);+ local.push((+ profile.and_then(|profile| profile.local_identity.as_deref()),+ profile.and_then(|profile| profile.model_contract_sha256.as_deref()),+ ));+ }+ }+ let admitted: AdmittedWorkers = remote+ .into_iter()+ .filter(|(_, admission)| {+ local.iter().all(|(identity, contract)| {+ identity.is_some_and(|identity| {+ admission+ .local_identities+ .iter()+ .any(|admitted| admitted == identity)+ }) && *contract == Some(admission.model_contract_sha256.as_str())+ })+ })+ .map(|(worker, admission)| (worker.name.clone(), admission.sha256.clone()))+ .collect();+ if admitted.is_empty() {+ Err(NumericalRefusal::UncoveredIdentity)+ } else {+ Ok(admitted)+ }+ }++ /// Whether `worker` still runs a numerical bridge under the admission+ /// this gateway pinned for it.+ fn still_admitted(&self, worker: &WorkerState, pin: &NumericalPin<'_>) -> bool {+ let now_unix_ms = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |elapsed| {+ u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)+ });+ worker.supports_numerical_admission_subject_v1+ && pin.admitted.get(&worker.name).is_some_and(|pinned| {+ remote_admission(worker, pin.model, now_unix_ms)+ .is_some_and(|admission| &admission.sha256 == pinned)+ })+ }+pub async fn get_models(&self) -> HashMap<String, Vec<String>> {let snap = self.snapshot.load();let mut models: HashMap<String, Vec<String>> = HashMap::new();@@ -1056,6 +1359,8 @@ mod tests {fn make_msg(ready: bool) -> WorkerStatusMessage {WorkerStatusMessage {supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,name: "worker-1".into(),ready,gpu_count: 1,@@ -1147,6 +1452,477 @@ mod tests {assert!(status.workers[0].numerical_process_inventory.is_none());}+ const MODEL: &str = "acme/hybrid";+ const COVERED: &str =+ "v2:sha256:1111111111111111111111111111111111111111111111111111111111111111";+ const OTHER: &str =+ "v2:sha256:2222222222222222222222222222222222222222222222222222222222222222";+ const CONTRACT: &str = "3333333333333333333333333333333333333333333333333333333333333333";+ const NOW_MS: u64 = 1_800_000_000_000;++ fn admission(sha256: char, expires_at_unix_ms: u64) -> serde_json::Value {+ serde_json::json!({+ "sha256": sha256.to_string().repeat(64),+ "kind": "openai",+ "local_identities": [COVERED],+ "model_contract_sha256": CONTRACT,+ "outputs": ["dense"],+ "expires_at_unix_ms": expires_at_unix_ms,+ })+ }++ fn child(index: usize, seed: usize, profile: serde_json::Value) -> serde_json::Value {+ serde_json::json!({+ "child_index": index,+ "status": "observed",+ "snapshot": {+ "runtime_instance_id": format!("{:064x}", seed * 16 + index + 1),+ "complete": true,+ "profiles": [profile],+ },+ })+ }++ fn local_profile(identity: Option<&str>, contract: &str) -> serde_json::Value {+ serde_json::json!({"model_id": MODEL, "model_contract_sha256": contract, "local_identity": identity})+ }++ fn remote_profile(admission: serde_json::Value) -> serde_json::Value {+ serde_json::json!({+ "model_id": MODEL,+ "model_contract_sha256": CONTRACT,+ "local_identity": null,+ "admission": admission,+ })+ }++ fn numerical_worker(+ name: &str,+ bundle: &str,+ children: Vec<serde_json::Value>,+ ) -> WorkerStatusMessage {+ let mut message = make_msg(true);+ message.name = name.into();+ message.bundle = bundle.into();+ message.pool_name = "default".into();+ message.bundle_config_hash = format!("{bundle}-hash");+ message.supports_execution_authority_v1 = true;+ message.supports_numerical_admission_v1 = true;+ message.supports_numerical_admission_subject_v1 = true;+ message.numerical_process_inventory = serde_json::from_value(serde_json::json!({+ "observed_at_unix_ms": 1,+ "children": children,+ }))+ .unwrap();+ message+ }++ fn remote_worker(+ name: &str,+ seed: usize,+ admissions: &[serde_json::Value],+ ) -> WorkerStatusMessage {+ numerical_worker(+ name,+ "remote",+ admissions+ .iter()+ .enumerate()+ .map(|(index, admission)| child(index, seed, remote_profile(admission.clone())))+ .collect(),+ )+ }++ fn local_worker(+ name: &str,+ seed: usize,+ profiles: &[serde_json::Value],+ ) -> WorkerStatusMessage {+ numerical_worker(+ name,+ "default",+ profiles+ .iter()+ .enumerate()+ .map(|(index, profile)| child(index, seed, profile.clone()))+ .collect(),+ )+ }++ fn decide(+ reg: &WorkerRegistry,+ local_pool: &str,+ outputs: &[&str],+ ) -> Result<AdmittedWorkers, NumericalRefusal> {+ let local_bundles = ["default".to_string()];+ let outputs: Vec<String> = outputs.iter().map(|output| output.to_string()).collect();+ reg.numerical_admission(+ &NumericalLanes {+ model: MODEL,+ local_bundles: &local_bundles,+ local_pool,+ remote_model: "acme/hybrid:remote",+ remote_bundle: "remote",+ remote_pool: "default",+ remote_hash: "remote-hash",+ outputs: &outputs,+ },+ NOW_MS,+ )+ }++ fn numerical_decision(reg: &WorkerRegistry) -> Result<AdmittedWorkers, NumericalRefusal> {+ reg.settle_health_view_for_tests();+ decide(reg, "default", &["dense"])+ }++ #[tokio::test]+ async fn numerical_admission_needs_a_current_admission_that_covers_every_live_local_process() {+ let current = admission('a', NOW_MS + 60_000);+ let reg = registry();+ reg.update_worker(+ "http://r1",+ remote_worker("remote-1", 1, &[current.clone(), current.clone()]),+ )+ .await;+ assert_eq!(+ numerical_decision(®).unwrap(),+ HashMap::from([("remote-1".to_string(), "a".repeat(64))]),+ "with no live local process the remote admission decides"+ );+ let covered = local_profile(Some(COVERED), CONTRACT);+ reg.update_worker(+ "http://l1",+ local_worker("local-1", 2, &[covered.clone(), covered.clone()]),+ )+ .await;+ assert!(numerical_decision(®).is_ok());++ let cases: [(&str, Option<WorkerStatusMessage>, NumericalRefusal); 5] = [+ (+ "uncovered identity",+ Some(local_worker(+ "local-1",+ 2,+ &[covered.clone(), local_profile(Some(OTHER), CONTRACT)],+ )),+ NumericalRefusal::UncoveredIdentity,+ ),+ (+ "other model contract",+ Some(local_worker(+ "local-1",+ 2,+ &[local_profile(Some(COVERED), &"4".repeat(64))],+ )),+ NumericalRefusal::UncoveredIdentity,+ ),+ (+ "no identity",+ Some(local_worker("local-1", 2, &[local_profile(None, CONTRACT)])),+ NumericalRefusal::UncoveredIdentity,+ ),+ (+ "model missing from the process",+ Some(local_worker(+ "local-1",+ 2,+ &[+ serde_json::json!({"model_id": "acme/other", "model_contract_sha256": CONTRACT, "local_identity": COVERED}),+ ],+ )),+ NumericalRefusal::UncoveredIdentity,+ ),+ ("no inventory", None, NumericalRefusal::LocalUnobserved),+ ];+ for (case, message, refusal) in cases {+ let message = message.unwrap_or_else(|| {+ let mut legacy = local_worker("local-1", 2, std::slice::from_ref(&covered));+ legacy.numerical_process_inventory = None;+ legacy+ });+ reg.update_worker("http://l1", message).await;+ assert_eq!(numerical_decision(®), Err(refusal), "{case}");+ }++ let mut incomplete = local_worker("local-1", 2, std::slice::from_ref(&covered));+ let child = &mut incomplete+ .numerical_process_inventory+ .as_mut()+ .unwrap()+ .children[0];+ child.status = NumericalSnapshotStatus::Incomplete;+ child.snapshot.as_mut().unwrap().complete = false;+ reg.update_worker("http://l1", incomplete).await;+ assert_eq!(+ numerical_decision(®),+ Err(NumericalRefusal::LocalUnobserved)+ );+ reg.update_worker("http://l1", local_worker("local-1", 2, &[covered]))+ .await;+ assert!(numerical_decision(®).is_ok());+ }++ #[tokio::test]+ async fn numerical_admission_covers_starting_and_stale_workers_of_the_models_pool() {+ let reg = registry();+ reg.update_worker(+ "http://r1",+ remote_worker("remote-1", 1, &[admission('a', NOW_MS + 60_000)]),+ )+ .await;+ let uncovered = local_profile(Some(OTHER), CONTRACT);+ let mut starting = local_worker("local-1", 2, std::slice::from_ref(&uncovered));+ starting.ready = false;+ reg.update_worker("http://l1", starting).await;+ assert_eq!(+ numerical_decision(®),+ Err(NumericalRefusal::UncoveredIdentity)+ );++ let mut elsewhere = local_worker("local-1", 2, std::slice::from_ref(&uncovered));+ elsewhere.pool_name = "other-pool".into();+ reg.update_worker("http://l1", elsewhere).await;+ assert!(+ numerical_decision(®).is_ok(),+ "a worker loads only the models of its own pool"+ );++ reg.update_worker(+ "http://l1",+ local_worker("local-1", 2, &[local_profile(Some(COVERED), CONTRACT)]),+ )+ .await;+ assert!(numerical_decision(®).is_ok());+ {+ let mut workers = reg.workers.write().await;+ workers.get_mut("http://l1").unwrap().last_heartbeat =+ Instant::now() - Duration::from_secs(60);+ reg.rebuild_snapshot(&workers);+ }+ assert_eq!(+ numerical_decision(®),+ Err(NumericalRefusal::LocalUnobserved),+ "a stale worker that has not been evicted may still serve"+ );+ }++ #[tokio::test]+ async fn a_worker_of_another_pool_on_the_same_bundle_leaves_the_bridge_open() {+ let reg = registry();+ reg.update_worker(+ "http://r1",+ remote_worker("remote-1", 1, &[admission('a', NOW_MS + 60_000)]),+ )+ .await;+ reg.update_worker(+ "http://l1",+ local_worker("local-1", 2, &[local_profile(Some(COVERED), CONTRACT)]),+ )+ .await;+ assert!(numerical_decision(®).is_ok());++ let mut batch = local_worker(+ "batch-1",+ 3,+ &[+ serde_json::json!({"model_id": "acme/batch-only", "model_contract_sha256": CONTRACT, "local_identity": OTHER}),+ ],+ );+ batch.pool_name = "batch".into();+ reg.update_worker("http://b1", batch).await;+ assert!(+ numerical_decision(®).is_ok(),+ "a batch-pool worker never serves a model of the default pool"+ );+ }++ #[tokio::test]+ async fn numerical_admission_waits_one_heartbeat_timeout_after_health_resumes() {+ let reg = registry();+ reg.update_worker(+ "http://r1",+ remote_worker("remote-1", 1, &[admission('a', NOW_MS + 60_000)]),+ )+ .await;+ assert_eq!(+ decide(®, "default", &["dense"]),+ Err(NumericalRefusal::LocalUnobserved),+ "the first status starts the view"+ );+ reg.settle_health_view_for_tests();+ assert!(decide(®, "default", &["dense"]).is_ok());++ reg.health_subscription_started();+ assert_eq!(+ decide(®, "default", &["dense"]),+ Err(NumericalRefusal::LocalUnobserved),+ "a resumed subscription missed statuses"+ );+ reg.settle_health_view_for_tests();+ reg.health_view+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .last_status = Instant::now().checked_sub(reg.heartbeat_timeout * 2);+ reg.update_worker(+ "http://r1",+ remote_worker("remote-1", 1, &[admission('a', NOW_MS + 60_000)]),+ )+ .await;+ assert_eq!(+ decide(®, "default", &["dense"]),+ Err(NumericalRefusal::LocalUnobserved),+ "a status after a long silence follows an outage"+ );+ }++ #[tokio::test]+ async fn numerical_admission_must_list_every_requested_output() {+ let reg = registry();+ reg.update_worker(+ "http://r1",+ remote_worker("remote-1", 1, &[admission('a', NOW_MS + 60_000)]),+ )+ .await;+ reg.settle_health_view_for_tests();+ assert!(decide(®, "default", &["dense"]).is_ok());+ for outputs in [&["sparse"][..], &["dense", "multivector"], &[]] {+ assert_eq!(+ decide(®, "default", outputs),+ Err(NumericalRefusal::UnmeasuredRequest),+ "{outputs:?}"+ );+ }+ }++ #[tokio::test]+ async fn numerical_selection_requires_the_pinned_admission() {+ let reg = registry();+ reg.update_worker(+ "http://r1",+ remote_worker("remote-1", 1, &[admission('a', NOW_MS + 60_000)]),+ )+ .await;+ let admitted = numerical_decision(®).unwrap();+ let pick = |reg: &WorkerRegistry| {+ reg.execution_authority_worker(+ "acme/hybrid:remote",+ "default",+ "l4-spot",+ "remote",+ "remote-hash",+ None,+ Some(&NumericalPin {+ model: MODEL,+ admitted: &admitted,+ }),+ )+ };+ let message = remote_worker("remote-1", 1, &[admission('a', u64::MAX)]);+ reg.update_worker("http://r1", message.clone()).await;+ assert_eq!(pick(®).as_deref(), Some("remote-1"));++ let mut downgraded = message.clone();+ downgraded.supports_numerical_admission_v1 = false;+ reg.update_worker("http://r1", downgraded).await;+ assert!(pick(®).is_none(), "the capability was withdrawn");++ let replaced = remote_worker("remote-1", 1, &[admission('b', u64::MAX)]);+ reg.update_worker("http://r1", replaced).await;+ assert!(+ pick(®).is_none(),+ "the admission changed after the decision"+ );+ }++ #[tokio::test]+ async fn numerical_admission_needs_a_capable_current_and_unanimous_remote_worker() {+ let current = admission('a', NOW_MS + 60_000);+ let cases: [(&str, WorkerStatusMessage); 8] = [+ (+ "expires within the margin",+ remote_worker("remote-1", 1, &[admission('a', NOW_MS + 4_000)]),+ ),+ (+ "children disagree",+ remote_worker(+ "remote-1",+ 1,+ &[current.clone(), admission('b', NOW_MS + 60_000)],+ ),+ ),+ ("no numerical admission support", {+ let mut message = remote_worker("remote-1", 1, std::slice::from_ref(¤t));+ message.supports_numerical_admission_v1 = false;+ message+ }),+ ("a build that predates the admission subject", {+ let mut message = remote_worker("remote-1", 1, std::slice::from_ref(¤t));+ message.supports_numerical_admission_subject_v1 = false;+ message+ }),+ ("no execution authority", {+ let mut message = remote_worker("remote-1", 1, std::slice::from_ref(¤t));+ message.supports_execution_authority_v1 = false;+ message+ }),+ ("another configuration hash", {+ let mut message = remote_worker("remote-1", 1, std::slice::from_ref(¤t));+ message.bundle_config_hash = "stale".into();+ message+ }),+ ("saturated", {+ let mut message = remote_worker("remote-1", 1, std::slice::from_ref(¤t));+ message.saturated = true;+ message+ }),+ (+ "the child reports another model contract",+ numerical_worker(+ "remote-1",+ "remote",+ vec![child(+ 0,+ 1,+ serde_json::json!({+ "model_id": MODEL,+ "model_contract_sha256": "4".repeat(64),+ "local_identity": null,+ "admission": current.clone(),+ }),+ )],+ ),+ ),+ ];+ for (case, message) in cases {+ let reg = registry();+ reg.update_worker("http://r1", message).await;+ assert_eq!(+ numerical_decision(®),+ Err(NumericalRefusal::NoAdmission),+ "{case}"+ );+ }++ let reg = registry();+ reg.update_worker("http://r1", remote_worker("remote-1", 1, &[current]))+ .await;+ let mut narrower = admission('b', NOW_MS + 60_000);+ narrower["local_identities"] = serde_json::json!([OTHER]);+ reg.update_worker("http://r2", remote_worker("remote-2", 3, &[narrower]))+ .await;+ reg.update_worker(+ "http://l1",+ local_worker("local-1", 2, &[local_profile(Some(COVERED), CONTRACT)]),+ )+ .await;+ assert_eq!(+ numerical_decision(®).unwrap(),+ HashMap::from([("remote-1".to_string(), "a".repeat(64))]),+ "only a remote worker whose own admission covers the local fleet is admitted"+ );+ }+#[tokio::test]async fn unavailable_lane_trigger_is_scoped_and_usable_workers_win() {let reg = registry();@@ -1562,6 +2338,8 @@ mod tests {let reg = registry();let msg = WorkerStatusMessage {supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,name: "w-compact".into(),ready: true,gpu_count: 1,@@ -1600,6 +2378,8 @@ mod tests {let reg = registry();let msg = WorkerStatusMessage {supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,name: "w-none".into(),ready: true,gpu_count: 1,@@ -1705,6 +2485,7 @@ mod tests {"default",hash,names,+ None,)};reg.update_worker("w1", good.clone()).await;@@ -1755,6 +2536,7 @@ mod tests {"default","abc123",None,+ None,).unwrap()})@@ -1784,6 +2566,7 @@ mod tests {"l4-spot","default","abc123",+ None,None).is_none());@@ -2273,6 +3056,8 @@ mod tests {) -> WorkerStatusMessage {WorkerStatusMessage {supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,name: "w".into(),ready,gpu_count: 1,diff --git a/packages/sie_gateway/src/types/worker.rs b/packages/sie_gateway/src/types/worker.rsindex 56c2f2aab..ceb9cd397 100644--- a/packages/sie_gateway/src/types/worker.rs+++ b/packages/sie_gateway/src/types/worker.rs@@ -34,6 +34,10 @@ pub struct WorkerState {pub bundle_config_hash: String,/// Positive support for the versioned queue and backend execution fence.pub supports_execution_authority_v1: bool,+ /// Every backend child re-verifies a numerical admission before execution.+ pub supports_numerical_admission_v1: bool,+ /// The worker also consumes admitted numerical work on its own subject.+ pub supports_numerical_admission_subject_v1: bool,/// Diagnostic observations only; never sufficient for numerical admission.pub numerical_process_inventory: Option<Arc<NumericalProcessInventory>>,pub models: Vec<String>,@@ -220,6 +224,10 @@ pub struct WorkerStatusMessage {#[serde(default)]pub supports_execution_authority_v1: bool,#[serde(default)]+ pub supports_numerical_admission_v1: bool,+ #[serde(default)]+ pub supports_numerical_admission_subject_v1: bool,+ #[serde(default)]pub loaded_models: Vec<String>,#[serde(default)]pub models: Vec<ModelStatus>,@@ -751,6 +759,8 @@ mod tests {bundle: "default".into(),bundle_config_hash: String::new(),supports_execution_authority_v1: false,+ supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,numerical_process_inventory: None,models: vec![],queue_depth: 0,diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.mdindex 7e54a0343..b5bc1c8b6 100644--- a/packages/sie_server/REMOTE_BACKENDS.md+++ b/packages/sie_server/REMOTE_BACKENDS.md@@ -51,7 +51,8 @@ operator-owned equivalence admission described below. SIE hybrid encode andscore require the fresh identity admission described below. Cluster remoteprofiles use the queue. Cluster generation and extraction fallback are describedbelow. Cluster saturation and unhealthy-worker spill require explicit triggers.-Numeric fleet bridges remain separately gated. Experimental `threshold` routing+Cluster `encode` and `score` bridges need a numerical admission (see+[Cluster numerical bridges](#cluster-numerical-bridges)). Experimental `threshold` routingis cluster-only and opt-in, as described below. A single node refuses a`threshold` routing block at configuration load; use `fallback` there.@@ -505,10 +506,64 @@ caller then receives its local refusal withafter a change: a batch that has already passed it completes its upstream calls,and an SIE upstream's identity comes from a cache trusted for up to 30 seconds.-These observations and the evidence file grant no gateway routing authority.-An `observed` child can still lack a local identity. Numerical gateway routing-remains inactive until operator-owned evidence, complete live membership and-execution fencing are connected.+An observation alone grants no routing authority, and an `observed` child can+still lack a local identity. The gateway combines these observations into the+admission decision described next.++## Cluster numerical bridges++In a cluster, a bare `encode` or `score` request for a model with a `fallback`+or `threshold` policy runs on the remote profile only under a current numerical+admission. `/v1/embeddings` follows the same rule, because it wraps `encode`.+The gateway validates such a request before it counts threshold demand,+publishes load-only work or makes a decision, so an invalid request gets its+`400` and nothing else. It decides when it is about to commit to the remote+attempt:++- The request must set no runtime option other than `is_query`, and every+ output it asks for must be listed in the admission. Any other option, such as+ `output_dtype`, keeps the request local, because the remote process would+ refuse it.+- A remote-lane worker qualifies when it is fresh, eligible and positively+ supports both execution authority and the numerical admission method,+ consumes the admission subject, carries the remote profile's exact+ configuration hash, and every adapter child reports+ the same admission for the model with the model contract it reports itself.+ That admission must expire at least five seconds later.+- Its admission must cover every local process that could serve the model.+ Each child of every worker on the model's local bundles and in the model's+ pool (`default` when it names none), starting and degraded workers included,+ must report an admitted identity and the admission's model contract.+ A worker without a complete inventory, a worker past the heartbeat timeout+ that has not been evicted, or a child without an identity or without the+ model keeps the request local. So does every request until the gateway has+ heard worker health for one heartbeat timeout after its health subscription+ starts or resumes, or after a longer silence. With no local worker the remote+ admission decides alone.+- The request is pinned to one admitted remote worker that still reports the+ capability and the same admission digest. Its items carry that digest on a+ subject that only a worker with the numerical admission check consumes, and+ the worker checks the admission again before calling the upstream.++A request that names a profile, including one in its body options, stays on its+selected route. Generation and extraction requests of a model with numerical+outputs never bridge in a cluster. If the remote worker refuses an admitted+attempt, for example because the admission changed after the gateway checked+it, a fallback route answers with its local refusal, and a threshold route+answers `503 INFERENCE_ERROR` with the worker's `Retry-After`. Each request's+decision is counted once on `sie.gateway.remote.numerical_admissions`.++Upgrade workers and gateways before applying a hybrid `encode` or `score`+configuration. A remote lane rolled back below the numerical admission subject+stops numerical bridging: its older sidecar never consumes admitted work, so+queued attempts time out instead of running unchecked, and a fenced sidecar+that later consumes them drops those past their deadline. Configuring a numerical+bridge also changes local behavior while no admission holds: a trigger that+would bridge a request commits to its local refusal, so a cold model answers+`MODEL_LOADING` instead of waiting for its load, and an opted-in `saturated` or+`unhealthy` trigger refuses instead of queueing. A request that could never+bridge, because it sets a runtime option other than `is_query`, keeps its+ordinary local path.## Single-node generation fallback@@ -602,7 +657,8 @@ local refusal and retry interval; streaming failures after the first outputremain in the stream. Explicit selectors and `X-SIE-Remote: forbid` retaintheir existing authority.-Numerical fleet equivalence remains inactive. Threshold routing requires its separate deployment opt-in.+Numerical models bridge only as described in+[Cluster numerical bridges](#cluster-numerical-bridges). Threshold routing requires its separate deployment opt-in.### Observing cluster fallback@@ -655,8 +711,11 @@ requests stay local. Sustained low demand returns requests to remote; existingworker idle eviction and autoscaling govern when the local lane sleeps.Explicit profiles, bundle/pool/machine/engine selectors and `X-SIE-Remote:-forbid` retain caller authority. Managed deployment routes and numerical-encode/score models remain outside this flag. Invalid requests do not add+forbid` retain caller authority. Managed deployment routes remain outside this+flag. A numerical `encode` or `score` model takes the remote route only under a+current numerical admission (see+[Cluster numerical bridges](#cluster-numerical-bridges)); otherwise its request+stays local. Invalid requests do not addthreshold demand. A remote-selected request still requires the current exactworker execution contract; it cannot select a legacy worker or retry intoanother backend after output has started. An unavailable remote lane returnsdiff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.pyindex 7f890a8ef..fee65cb58 100644--- a/packages/sie_server/src/sie_server/ipc_server.py+++ b/packages/sie_server/src/sie_server/ipc_server.py@@ -27,7 +27,6 @@ from sie_server.core.gpu_health import gpu_is_healthy_asyncfrom sie_server.core.grammar_routing import resolve_grammar_serving_modelfrom sie_server.core.profile_identity import local_profile_identity, runtime_instance_id, serving_code_digestfrom sie_server.core.readiness import is_ready-from sie_server.core.score_cost import SCORE_MEDIA_COSTfrom sie_server.ipc_types import (IPC_VERSION,METHOD_APPLY_MODEL_CONFIG,@@ -238,26 +237,6 @@ def _named_admission(item: Any) -> str | None:return next((token for token in tokens if token is not None), None)-def _score_side_cost(item: Mapping[str, Any]) -> int:- text = item["text"] if "text" in item else item.get("content")- images = item.get("images")- media = (len(images) if isinstance(images, list) else 0) + sum(- item.get(key) is not None for key in ("audio", "video", "document")- )- return (len(text) if isinstance(text, str) else 0) + media * SCORE_MEDIA_COST---def _run_batch_item_cost(item: RunBatchItem) -> int:- """The sidecar scheduler's batching cost of an encode or score item."""- payload = item.encode if item.encode is not None else item.score- if payload is not None and payload.prepared_tokens is not None:- return max(1, sum(len(ids) for ids in payload.prepared_tokens.input_ids))- if item.score is None:- return 1- query = _score_side_cost(item.score.query_item)- return max(1, sum(query + _score_side_cost(document) for document in item.score.score_items))--class IpcServer:"""UDS msgpack RPC server fronting the QueueExecutor.@@ -828,10 +807,7 @@ class IpcServer:served: dict[str, ItemOutcome] = {}batched: list[BatchedF16MultivectorOutput] = []if kept:- subset = msgspec.structs.replace(req, items=kept)- if isinstance(subset, RunBatchRequest):- subset = msgspec.structs.replace(subset, total_cost=sum(map(_run_batch_item_cost, subset.items)))- result = await run(subset)+ result = await run(msgspec.structs.replace(req, items=kept))served = {outcome.work_item_id: outcome for outcome in result.outcomes}batched = result.batched_f16_multivectorsoutcomes: list[ItemOutcome] = []diff --git a/packages/sie_server/tests/config/test_hybrid_admission.py b/packages/sie_server/tests/config/test_hybrid_admission.pyindex 7f01bf32c..731fb2edf 100644--- a/packages/sie_server/tests/config/test_hybrid_admission.py+++ b/packages/sie_server/tests/config/test_hybrid_admission.py@@ -48,7 +48,6 @@ from sie_server.ipc_types import (ProcessScoreBatchRequest,ReplaceModelConfigEntry,ReplaceModelConfigsRequest,- RunBatchItem,RunBatchRequest,WorkerCapabilitiesRequest,WorkerCapabilitiesResponse,@@ -1071,7 +1070,7 @@ async def test_a_failing_admission_check_refuses_every_item_and_logs_only_its_classert "secret-input" not in caplog.text-async def test_the_fence_keeps_shared_outputs_recosts_its_subset_and_names_an_unanswered_item(+async def test_the_fence_keeps_shared_outputs_and_names_an_unanswered_item(admission: tuple, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:config, _, path, data = admission@@ -1100,10 +1099,7 @@ async def test_the_fence_keeps_shared_outputs_recosts_its_subset_and_names_an_unconfig.sie_id + ":remote",bundle_hash,{"numerical_admission_sha256": "0" * 64},- {- "numerical_admission_sha256": current.sha256,- "prepared_tokens": {"input_ids": [[1, 2, 3], [4, 5]], "tokenizer_id": "t"},- },+ {"numerical_admission_sha256": current.sha256},{"numerical_admission_sha256": current.sha256},),require_authority=True,@@ -1111,7 +1107,6 @@ async def test_the_fence_keeps_shared_outputs_recosts_its_subset_and_names_an_un)assert [item.work_item_id for item in seen[0].items] == ["req.1", "req.2"]- assert seen[0].total_cost == 6assert outcome.batched_f16_multivectors == [shared]assert [value.work_item_id for value in outcome.outcomes] == ["req.0", "req.1", "req.2"]assert outcome.outcomes[1].disposition == "publish_and_ack"@@ -1119,21 +1114,3 @@ async def test_the_fence_keeps_shared_outputs_recosts_its_subset_and_names_an_unassert outcome.outcomes[0].error == "bridged item names a different numerical admission"_assert_refused_before_the_upstream(outcome.outcomes[2])assert outcome.outcomes[2].error == "the backend returned no outcome for this admitted item"---def test_a_subset_is_costed_as_the_sidecar_scheduler_costs_its_items() -> None:- def item(op: str, **payload: Any) -> RunBatchItem:- base = {"work_item_id": "w", "request_id": "r", "item_index": 0, "total_items": 1, "timestamp": 1.0}- return msgspec.convert({"op": op, op: {**base, **payload}}, type=RunBatchItem)-- tokens = {"input_ids": [[1, 2, 3], [4, 5]], "tokenizer_id": "t"}- query = {"text": "query"}- documents = [{"text": "doc"}, {"content": "abcd"}, {"text": None, "content": "zz"}, {"images": [b"a", b"b"]}]- assert ipc_server._run_batch_item_cost(item("encode", item={"text": "x" * 40})) == 1- assert ipc_server._run_batch_item_cost(item("encode", item={"text": "x"}, prepared_tokens=tokens)) == 5- empty = {"input_ids": [[]], "tokenizer_id": "t"}- assert ipc_server._run_batch_item_cost(item("encode", item={"text": "x"}, prepared_tokens=empty)) == 1- assert ipc_server._run_batch_item_cost(item("score", query_item=query, score_items=documents)) == 2075- scored = item("score", query_item=query, score_items=documents, prepared_tokens=tokens)- assert ipc_server._run_batch_item_cost(scored) == 5- assert ipc_server._run_batch_item_cost(item("score", query_item={"text": ""}, score_items=[{"text": ""}])) == 1diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex cc904c63e..4deb7db0c 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -423,20 +423,29 @@ matches that subject, including its authority consumer. A rollback thereforecannot hand such a sidecar admitted work that is already queued, and until afenced sidecar has created the stream, admitted work cannot be published atall. The contract comes from the subject, never from the payload field, which-an older sidecar would ignore.+an older sidecar would ignore. Every worker therefore runs a fourth stream,+durable consumer and pull loop, including lanes that never receive admitted+work.Admitted work also runs under execution authority. Before readiness oroffloaded input retrieval, the sidecar answers an item with `INFERENCE_ERROR`-and ACKs it when the item and its subject disagree: the field on any other-subject, an item without the field on the admission subject, an operation other-than `encode` or `score`, or a payload model other than the subject's. It does-the same for an `encode` or `score` item that carries `fallback_reason` without-the field, because every numerical remote attempt that stands in for a local-refusal is admitted work. Such an item can never become valid, and a NAK could-hand an item on a pool subject to a worker without the fence. An item that-arrives before every backend child supports the method is NAKed on the-worker's own admission stream, like other authority work. The local-ingest-lane rejects the field, and `fallback_reason` on `encode` or `score`.+and ACKs it, whether or not the answer could be published, when the item and+its subject disagree: the field on any other subject, an item without the field+on the admission subject, an operation other than `encode` or `score`, a+payload model other than the subject's, or an admitted item without a+configuration hash. It does the same for an `encode` or `score` item that+carries `fallback_reason` without the field, because every numerical remote+attempt that stands in for a local refusal is admitted work. Such an item can+never become valid, and a NAK could hand an item on a pool subject to a worker+without the fence. An admitted item whose configuration hash this worker does+not hold is also answered with `INFERENCE_ERROR` at once, at receipt, at the+model group's check and at the scheduler's barrier, because its bridged caller+waits with a local refusal. Only an admitted item that arrives before every+backend child supports the method is NAKed on the worker's own admission+stream, like other authority work. An admitted item past its gateway deadline+is ACK-dropped before the backend call even when `SIE_WORK_DEADLINE_ENFORCE` is+off, because its caller has stopped waiting. The local-ingest lane rejects the+field, and `fallback_reason` on `encode` or `score`.Admitted items keep their own scheduler partition and run only through`RunBatchWithNumericalAdmissionV1`, which an older backend rejects. A sidecar@@ -462,12 +471,19 @@ upstream calls. An SIE upstream's identity comes from a cache that is trustedfor up to 30 seconds.The backend capability `supports_numerical_admission_v1` defaults to false. The-heartbeat reports `supports_numerical_admission_v1` only when it reports-`supports_execution_authority_v1`, every backend child supports the method and-the admission pull consumer runs. After a rollback below this version, admitted-work still queued for that worker never runs and its callers time out. The-gateway stops selecting the worker once its heartbeat no longer reports the-capability. No gateway produces these items yet.+heartbeat reports `supports_numerical_admission_v1` when it reports+`supports_execution_authority_v1` and every backend child supports the method.+It reports `supports_numerical_admission_subject_v1` only when, in addition,+the admission pull consumer runs. Builds that predate the admission subject+never send that field, so the gateway selects on it alone. A sidecar rolled+back below this version does not run admitted work still queued for that+worker, and its callers time out. A fenced sidecar that later consumes such an+item drops it once its deadline has passed. The gateway stops selecting the+worker once its heartbeat no longer reports the capability. The gateway+produces these items only for an `encode` or `score` bridge or threshold route+whose numerical admission it has checked, and only toward a worker that+reports `supports_numerical_admission_subject_v1`. The gateway architecture+guide's "Numerical bridges" section describes that decision.Non-streaming backend responses use one physical frame while the serializedresponse is at most 32 MiB. For a larger response, the sidecar explicitly setsdiff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 3b0c8420f..f3e4a0e84 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -673,11 +673,15 @@ pub struct Dispatcher {}impl Dispatcher {- fn execution_authority_is_available(&self, wi: &WorkItem, needs_scheduler: bool) -> bool {+ fn execution_hash_is_current(&self, wi: &WorkItem) -> bool {!wi.bundle_config_hash.is_empty()&& self.config_apply_state.is_some()&& unknown_bundle_config_hash(std::iter::once(wi), self.config_apply_state.as_deref()).is_none()+ }++ fn execution_authority_is_available(&self, wi: &WorkItem, needs_scheduler: bool) -> bool {+ self.execution_hash_is_current(wi)&& self.worker_pool.execution_authority_v1()@@ -1036,7 +1040,9 @@ impl Dispatcher {return false;};let telemetry = &self.runtime_state.telemetry;- if !self.work_deadline.enforce {+ // A bridged caller never waits past the gateway's deadline, so+ // admitted work is dropped then whatever the enforcement setting.+ if !self.work_deadline.enforce && wi.numerical_admission_sha256.is_none() {if stage == "before_ipc" {telemetry.work_item_deadline_exceeded(&wi.operation, "executed");if let Some(suppressed) = EXPIRED_EXECUTE_WARNINGS.allow() {@@ -1298,7 +1304,11 @@ impl Dispatcher {// consumes, and its payload field must agree with that// subject. Refuse before readiness or payload fetch.let admission_violation = numerical_admission_violation(&msg.subject, &wi);+ let stale_admission = admission_violation.is_none()+ && wi.numerical_admission_sha256.is_some()+ && !self.execution_hash_is_current(&wi);if admission_violation.is_none()+ && !stale_admission&& requires_execution_authority_v1(&msg.subject)&& (!execution_authority_model_matches(&msg.subject, &wi.model_id)|| !self@@ -1336,21 +1346,17 @@ impl Dispatcher {}let mut delivery = Delivery::Nats(msg, admission_permit, None);if let Some(violation) = admission_violation {- // Such an item can never become valid, and a NAK- // could hand it to a consumer without the fence.warn!(work_item_id = %wi.work_item_id,model = %wi.model_id,violation,"work breaks the numerical admission contract — answering and ACKing",);- self.refuse_fallback_attempt(- &wi,- &delivery,- INFERENCE_ERROR_CODE,- NUMERICAL_ADMISSION_RETRY_AFTER_S,- )- .await;+ self.refuse_violation(&wi, &delivery).await;+ continue;+ }+ if stale_admission {+ self.refuse_stale_admission(&wi, &delivery).await;continue;}self.observe_deadline_clock(&wi, &delivery);@@ -2274,9 +2280,10 @@ impl Dispatcher {items: Vec<(WorkItem, Delivery)>,ready_deadline: Option<tokio::time::Instant>,) -> Result<(), DispatchError> {- let mut items = self+ let items = self.retain_uncancelled(items, "before_model_readiness").await;+ let mut items = self.answer_stale_admissions(items).await;if items.is_empty() {return Ok(());}@@ -2315,6 +2322,7 @@ impl Dispatcher {}let readiness_resp = loop {items = self.retain_uncancelled(items, "model_readiness").await;+ items = self.answer_stale_admissions(items).await;if items.is_empty() {return Ok(());}@@ -2604,13 +2612,7 @@ impl Dispatcher {kept.push((wi, delivery));continue;}- self.refuse_fallback_attempt(- &wi,- &delivery,- INFERENCE_ERROR_CODE,- NUMERICAL_ADMISSION_RETRY_AFTER_S,- )- .await;+ self.refuse_violation(&wi, &delivery).await;}kept}@@ -3360,6 +3362,63 @@ impl Dispatcher {}}+ /// Answer an item that breaks the numerical admission contract and ACK it+ /// whatever the publish result: it can never become valid, and a NAK+ /// could hand it to a consumer without the fence.+ async fn refuse_violation(&self, wi: &WorkItem, delivery: &Delivery) {+ let mut outcome =+ synthetic_error_outcome(wi, INFERENCE_ERROR_CODE, FALLBACK_REFUSAL_MESSAGE);+ outcome.retry_after_s = Some(NUMERICAL_ADMISSION_RETRY_AFTER_S);+ if let Err(e) = self+ .deliver_result(wi, delivery, &outcome, None, None)+ .await+ {+ warn!(+ work_item_id = %wi.work_item_id,+ error = %e,+ "failed to publish a numerical admission refusal — ACKing anyway"+ );+ }+ if let Err(e) = ack(delivery, &self.runtime_state.telemetry).await {+ warn!(error = %e, "ack after a numerical admission refusal failed");+ }+ }++ /// Answer an admitted item whose configuration hash this worker no longer+ /// holds. Redelivery to the pinned worker rarely converges, and its+ /// bridged caller is waiting with a local refusal.+ async fn refuse_stale_admission(&self, wi: &WorkItem, delivery: &Delivery) {+ info!(+ work_item_id = %wi.work_item_id,+ model = %wi.model_id,+ "admitted work names a configuration this worker does not hold — answering"+ );+ self.refuse_fallback_attempt(+ wi,+ delivery,+ INFERENCE_ERROR_CODE,+ NUMERICAL_ADMISSION_RETRY_AFTER_S,+ )+ .await;+ }++ /// Answer the admitted items whose configuration hash is no longer+ /// current, and return the others.+ async fn answer_stale_admissions(+ &self,+ items: Vec<(WorkItem, Delivery)>,+ ) -> Vec<(WorkItem, Delivery)> {+ let mut kept = Vec::with_capacity(items.len());+ for (wi, delivery) in items {+ if wi.numerical_admission_sha256.is_some() && !self.execution_hash_is_current(&wi) {+ self.refuse_stale_admission(&wi, &delivery).await;+ } else {+ kept.push((wi, delivery));+ }+ }+ kept+ }+/// Answer a work item the gateway sent to a remote profile in place of a/// refusing local route. The gateway is holding that local refusal for/// its caller, so a redelivery would only make the caller wait: the item@@ -4924,6 +4983,9 @@ fn numerical_admission_violation(subject: &str, wi: &WorkItem) -> Option<&'stati(true, false) => Some("admitted_work_off_the_admission_subject"),(false, true) => Some("unadmitted_work_on_the_admission_subject"),(true, true) if !numerical => Some("admitted_work_is_not_encode_or_score"),+ (true, true) if wi.bundle_config_hash.is_empty() => {+ Some("admitted_work_names_no_configuration")+ }(true, true) if !execution_authority_model_matches(subject, &wi.model_id) => {Some("admitted_work_names_another_model")}@@ -5508,6 +5570,7 @@ async fn process_scheduler_contract_batch(.into_iter().map(|meta| (meta.wi, meta.delivery)).collect();+ let msgs_only = dispatcher.answer_stale_admissions(msgs_only).await;nak_all_at_barrier(&msgs_only,base_nak_delay_ms(),@@ -6788,12 +6851,15 @@ mod tests {async fn the_scheduler_less_path_answers_admitted_items_without_the_backend() {for op in ["encode", "score"] {let backend = naking_backend(None, None, Some(2_500));- let dispatcher = dispatcher_with_backend(backend.clone());+ let mut dispatcher = dispatcher_with_backend(backend.clone());+ Arc::get_mut(&mut dispatcher).unwrap().config_apply_state =+ Some(Arc::new(ConfigApplyState::new("fresh".into())));let events = settle_one(&dispatcher,WorkItem {numerical_admission_sha256: Some("a".repeat(64)),+ bundle_config_hash: "fresh".into(),..wi("admitted", 0, "acme/model:remote", op)},)@@ -7212,12 +7278,124 @@ mod tests {let mut work = wi("req", 0, model, op);work.numerical_admission_sha256 = token.then(|| "a".repeat(64));work.fallback_reason = fallback.then(|| "provisioning".to_string());+ work.bundle_config_hash = "fresh".into();assert_eq!(numerical_admission_violation(subject, &work),violation,"{subject} {model} {op} {token} {fallback}");}+ let mut unpinned = wi("req", 0, "model", "encode");+ unpinned.numerical_admission_sha256 = Some("a".repeat(64));+ assert_eq!(+ numerical_admission_violation(admission, &unpinned),+ Some("admitted_work_names_no_configuration")+ );+ }++ #[tokio::test]+ async fn an_admitted_item_with_a_configuration_this_worker_no_longer_holds_is_answered() {+ let backend = naking_backend(None, None, Some(2_500));+ let mut dispatcher = dispatcher_with_backend(backend.clone());+ Arc::get_mut(&mut dispatcher).unwrap().config_apply_state =+ Some(Arc::new(ConfigApplyState::new("fresh".into())));+ let admitted = |hash: &str| WorkItem {+ numerical_admission_sha256: Some("a".repeat(64)),+ bundle_config_hash: hash.into(),+ ..wi("admitted", 0, "acme/model:remote", "encode")+ };++ let stale = settle_one(&dispatcher, admitted("stale")).await;+ let [crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }] = stale.as_slice()+ else {+ panic!("a stale admitted item must settle with a result: {stale:?}");+ };+ assert_eq!(result.error_code.as_deref(), Some(INFERENCE_ERROR_CODE));+ assert_eq!(result.retry_after_s, Some(1));+ assert_eq!(backend.encoded.load(Ordering::SeqCst), 0);++ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ let ordinary = WorkItem {+ bundle_config_hash: "stale".into(),+ ..wi("plain", 0, "acme/model:remote", "encode")+ };+ let kept = dispatcher+ .answer_stale_admissions(vec![+ (+ admitted("fresh"),+ Delivery::Local(LocalDelivery::new(0, 0, tx.clone())),+ ),+ (ordinary, Delivery::Local(LocalDelivery::new(1, 0, tx))),+ ])+ .await;+ assert_eq!(+ kept.len(),+ 2,+ "a current admission and ordinary work are kept"+ );+ assert!(rx.try_recv().is_err());+ }++ #[tokio::test(start_paused = true)]+ async fn an_admission_that_goes_stale_while_its_model_loads_is_answered() {+ let backend = LoadingModelBackend::new("cold");+ let mut dispatcher = dispatcher_with_backend(backend.clone());+ let state = Arc::new(ConfigApplyState::new("fresh".into()));+ Arc::get_mut(&mut dispatcher).unwrap().config_apply_state = Some(Arc::clone(&state));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ let admitted = WorkItem {+ numerical_admission_sha256: Some("a".repeat(64)),+ bundle_config_hash: "fresh".into(),+ ..wi("admitted", 0, "cold", "encode")+ };++ dispatcher+ .dispatch_decoded(+ vec![(admitted, Delivery::Local(LocalDelivery::new(0, 0, tx)))],+ 1,+ Instant::now(),+ )+ .await;+ // The second probe comes from the parked group's readiness loop.+ while backend.probes.load(Ordering::SeqCst) < 2 {+ tokio::task::yield_now().await;+ }+ state.set_bundle_hash("next".into());+ dispatcher+ .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)+ .await;++ let Ok(crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }) = rx.try_recv()+ else {+ panic!("an admission that went stale must settle with a result");+ };+ assert_eq!(result.error_code.as_deref(), Some(INFERENCE_ERROR_CODE));+ assert!(backend.encoded_models().is_empty());+ }++ #[tokio::test]+ async fn admitted_work_past_its_deadline_is_dropped_whatever_the_enforcement_flag() {+ let dispatcher = dispatcher_with_backend(naking_backend(None, None, None));+ assert!(!dispatcher.work_deadline.enforce);+ let now = unix_now_s();+ let expired = |token: Option<String>| WorkItem {+ numerical_admission_sha256: token,+ timestamp: now - 180.0,+ deadline: Some(now - 60.0),+ ..wi("late", 0, "acme/model:remote", "encode")+ };+ let delivery = admission_test_delivery().await;+ assert!(+ dispatcher+ .settle_if_expired(&expired(Some("a".repeat(64))), &delivery, "before_ipc")+ .await+ );+ assert!(+ !dispatcher+ .settle_if_expired(&expired(None), &delivery, "before_ipc")+ .await,+ "ordinary work still runs without enforcement"+ );}#[tokio::test]diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rsindex 2cde987e9..ac8e06d66 100644--- a/packages/sie_server_sidecar/src/health_publisher.rs+++ b/packages/sie_server_sidecar/src/health_publisher.rs@@ -248,6 +248,7 @@ struct WorkerStatusPayload<'a> {terminated: bool,supports_execution_authority_v1: bool,supports_numerical_admission_v1: bool,+ supports_numerical_admission_subject_v1: bool,gpu_count: i32,total_gpu_slots: i32,ready_gpu_slots: i32,@@ -341,13 +342,15 @@ fn encode_payload(&& !hash.is_empty()&& config.execution_authority_v1.load(Ordering::Acquire)&& config.authority_consumer_ready.load(Ordering::Acquire);+ let supports_numerical_admission_v1 =+ supports_execution_authority_v1 && config.numerical_admission_v1.load(Ordering::Acquire);let payload = WorkerStatusPayload {name: &config.worker_id,ready,terminated,supports_execution_authority_v1,- supports_numerical_admission_v1: supports_execution_authority_v1- && config.numerical_admission_v1.load(Ordering::Acquire)+ supports_numerical_admission_v1,+ supports_numerical_admission_subject_v1: supports_numerical_admission_v1&& config.admission_consumer_ready.load(Ordering::Acquire),gpu_count: config.gpu_count,total_gpu_slots,@@ -761,6 +764,11 @@ mod tests {serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();assert_eq!(payload["supports_numerical_admission_v1"],+ authority && backend,+ "{authority} {backend} {consumer}"+ );+ assert_eq!(+ payload["supports_numerical_admission_subject_v1"],authority && backend && consumer,"{authority} {backend} {consumer}");@@ -781,6 +789,7 @@ mod tests {terminated: false,supports_execution_authority_v1: false,supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,gpu_count: c.gpu_count,total_gpu_slots: 1,ready_gpu_slots: 1,@@ -830,6 +839,7 @@ mod tests {terminated: false,supports_execution_authority_v1: false,supports_numerical_admission_v1: false,+ supports_numerical_admission_subject_v1: false,gpu_count: c.gpu_count,total_gpu_slots: 1,ready_gpu_slots: 1,diff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rsindex 7c126d0e4..36de696b7 100644--- a/packages/sie_server_sidecar/tests/integration_smoke.rs+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs@@ -3610,9 +3610,9 @@ async fn admitted_work_is_invisible_to_a_sidecar_without_the_admission_fence() {drop(nats);}-/// Work that breaks the numerical admission contract never runs and is never-/// handed to another consumer: the worker answers it once with-/// `INFERENCE_ERROR` and ACKs it.+/// Work that breaks the numerical admission contract, or admitted work that+/// names a configuration this worker does not hold, never runs and is never+/// redelivered: the worker answers it once with `INFERENCE_ERROR` and ACKs it.#[tokio::test(flavor = "multi_thread", worker_threads = 4)]async fn work_breaking_the_numerical_admission_contract_is_answered_and_acked() {if skip_unless_tools_available() {@@ -3647,31 +3647,57 @@ async fn work_breaking_the_numerical_admission_contract_is_answered_and_acked()let direct = worker_work_subject(pool, pool, bundle, model, "smoke-worker");let token = Some("a".repeat(64));let bridged = Some("provisioning".to_string());- for (request_id, subject, admission, fallback_reason) in [- ("admitted-on-the-pool", pooled.clone(), token.clone(), None),+ let admitted_subject = format!("{direct}.numerical-admission-v1");+ let unknown = "f".repeat(64);+ for (request_id, subject, admission, fallback_reason, hash) in [+ (+ "admitted-on-the-pool",+ pooled.clone(),+ token.clone(),+ None,+ "",+ ),("admitted-on-the-worker",direct.clone(),token.clone(),None,+ "",),("admitted-on-the-authority-subject",format!("{direct}.execution-authority-v1"),token.clone(),None,+ "",),("unadmitted-on-the-admission-subject",- format!("{direct}.numerical-admission-v1"),+ admitted_subject.clone(),None,None,+ "",+ ),+ (+ "admitted-without-a-configuration",+ admitted_subject.clone(),+ token.clone(),+ None,+ "",+ ),+ (+ "admitted-with-a-configuration-this-worker-lacks",+ admitted_subject,+ token.clone(),+ None,+ unknown.as_str(),),- ("bridge-without-an-admission", pooled, None, bridged),+ ("bridge-without-an-admission", pooled, None, bridged, ""),] {let mut work = encode_work_item(request_id, model, pool, "", &reply_subject, None);work.numerical_admission_sha256 = admission;work.fallback_reason = fallback_reason;+ work.bundle_config_hash = hash.to_string();let payload = rmp_serde::to_vec_named(&work).expect("encode WorkItem");let (stream_name, sequence) = publish_jetstream_with_retry(&js, &subject, payload).await;diff --git a/packages/wire-fixtures/worker_status.json b/packages/wire-fixtures/worker_status.jsonindex c87746123..8250a7762 100644--- a/packages/wire-fixtures/worker_status.json+++ b/packages/wire-fixtures/worker_status.json@@ -6,6 +6,7 @@"terminated","supports_execution_authority_v1","supports_numerical_admission_v1",+ "supports_numerical_admission_subject_v1","gpu_count","total_gpu_slots","ready_gpu_slots",@@ -29,6 +30,7 @@"terminated": false,"supports_execution_authority_v1": true,"supports_numerical_admission_v1": true,+ "supports_numerical_admission_subject_v1": true,"gpu_count": 1,"total_gpu_slots": 1,"ready_gpu_slots": 1,diff --git a/telemetry/README.md b/telemetry/README.mdindex e4a2645cd..c40f5cd6a 100644--- a/telemetry/README.md+++ b/telemetry/README.md@@ -730,6 +730,21 @@ series. Disabled telemetry constructs no point attributes. The collectorpreserves only the declared attributes, exports through the existing OTLP andPrometheus paths, and the queue-routing dashboard displays both instruments.+`sie.gateway.remote.numerical_admissions` counts each decision on a numerical+`encode` or `score` bridge or threshold route, made when the gateway is about+to commit to the remote attempt. Its labels are operation, canonical catalog+model, `admitted` or `refused`, and the reason: `none`, `no_admission` (no+eligible remote worker advertises a current admission), `local_unobserved` (a+live local worker reports no complete process inventory) or+`uncovered_identity` (a live local process reports an identity or model+contract outside the admission) or `unmeasured_request` (the request sets a+runtime option other than `is_query`, or asks for an output, that the admission+did not measure). A local worker past the heartbeat timeout, and every worker+until the gateway has heard worker health for one heartbeat timeout, counts as+`local_unobserved`. A request counts once, with the decision that applied. It+keeps its own 256-model bound with the same `other` overflow, and the+queue-routing dashboard displays it.+`SIERemoteFallbackPersistent` requires recent committed activity from the sameproducer instance and collector generation before comparing its duration with`alertRules.remoteFallbackPersistenceSeconds` (600 by default, integer 1–86400).diff --git a/telemetry/contract.yaml b/telemetry/contract.yamlindex 96a0814e3..497dd05f2 100644--- a/telemetry/contract.yaml+++ b/telemetry/contract.yaml@@ -414,11 +414,17 @@ cardinality_budgets:operation: operationreason: remote_fallback_reasonoutcome: remote_fallback_outcome+ admission_outcome: remote_numerical_admission_outcome+ admission_reason: remote_numerical_admission_reasoninstrument_limits:fallback_responses:metrics: [sie.gateway.remote.fallbacks]formula: models * operation * reason * outcomelimit: 14392+ numerical_admissions:+ metrics: [sie.gateway.remote.numerical_admissions]+ formula: models * operation * admission_outcome * admission_reason+ limit: 17990remote_duration:metrics: [sie.gateway.remote.serving.duration]formula: exact_models@@ -434,6 +440,7 @@ cardinality_budgets:applies_to:- sie.gateway.remote.fallbacks- sie.gateway.remote.serving.duration+ - sie.gateway.remote.numerical_admissionsgateway_lane_admission_domain:source: SIE_GATEWAY_CONFIGURED_PHYSICAL_LANES@@ -826,6 +833,8 @@ enums:settlement_confirm_outcome: [success, error, skipped]remote_fallback_reason: [provisioning, model_loading, saturated, unhealthy]remote_fallback_outcome: [committed, refused]+ remote_numerical_admission_outcome: [admitted, refused]+ remote_numerical_admission_reason: [none, no_admission, local_unobserved, uncovered_identity, unmeasured_request]gateway_dispatch_path: [i6pn, modal, other]dispatcher_path: [modal_remote, modal_stream, modal_spawn, generation_ws, other]dispatch_outcome: [success, error, timeout, cancelled, not_found, other]@@ -1107,6 +1116,11 @@ attribute_sets:outcome: remote_fallback_outcomegateway_remote_serving:model: model+ gateway_remote_numerical_admission:+ operation: operation+ model: model+ outcome: remote_numerical_admission_outcome+ reason: remote_numerical_admission_reasongateway_config_operation:operation: gateway_config_operationoutcome: gateway_config_outcome@@ -1602,6 +1616,14 @@ metrics:attributes: gateway_remote_servingprometheus_name: sie_gateway_remote_serving_duration_secondsexport: [prometheus, otlp]+ - name: sie.gateway.remote.numerical_admissions+ owner: gateway+ facade_event: gateway.remote_numerical_admission_decided+ type: counter+ unit: "{request}"+ attributes: gateway_remote_numerical_admission+ prometheus_name: sie_gateway_remote_numerical_admissions_total+ export: [prometheus, otlp]- name: sie.gateway.config.applied_epochowner: gatewayfacade_event: gateway.config_state_changed