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(routing): enable shared threshold routing behind cluster opt-in (#555)
Krisztian Gajdar93d56609724e
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 039a11345..d57133579 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -2138,3 +2138,25 @@ around those identities. When tracing is enabled, configureTempo, otherwise the chart fails fast.Local / non-Helm note: the gateway, Python worker, and Rust worker-sidecar all require `SIE_TRACING_ENABLED=true` and an OTLP endpoint (`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, or `OTEL_EXPORTER_OTLP_ENDPOINT`) before exporting traces. Setting only one yields no traces rather than a partial trace. In-cluster, the Helm chart sets both for you.+++### Experimental threshold routing++`gateway.thresholdRouting.enabled` defaults to `false`. Enabling it creates a+separate authenticated control broker and admits generation/extraction model+configs with `routing.policy: threshold`. It requires sie-config with `config.configStore.enabled: true`, authenticated+NATS and worker sidecars. Apply a configuration mutation through sie-config so+its persisted epoch is nonzero; gateways wait for a complete export bootstrap+before acquiring coordination authority. The chart propagates the same opt-in to configuration+validation and queue workers. Only the gateway password is mounted into the+control broker, and its NetworkPolicy permits only gateway client traffic.++The shipped control broker has one replica and ephemeral memory streams.+Gateway replicas share counts and one elected sampler; a control-broker restart+rebuilds evidence while requests retain ordinary local/fallback behavior. If+config-store recovery rewinds the epoch, restart the isolated threshold broker+after all gateways have applied the recovered export. This discards the old+generation and rebuilds evidence; never reset the inference broker for this. This+flag does not enable managed Cloud or numerical hybrid routing. See+[the remote-backend guide](../../../packages/sie_server/REMOTE_BACKENDS.md#experimental-cluster-threshold-routing)+for the policy, limits and caller controls.diff --git a/deploy/helm/sie-cluster/templates/_threshold-control.tpl b/deploy/helm/sie-cluster/templates/_threshold-control.tplnew file mode 100644index 000000000..083cfdc6f--- /dev/null+++ b/deploy/helm/sie-cluster/templates/_threshold-control.tpl@@ -0,0 +1,36 @@+{{- define "sie-cluster.threshold.serviceName" -}}+{{- $fullname := include "sie-cluster.fullname" . | trunc 53 | trimSuffix "-" -}}+{{- printf "%s-threshold" $fullname -}}+{{- end }}++{{- define "sie-cluster.threshold.config" -}}+# Isolated control broker; only gateways have credentials.+port: 4222+http_port: 8222+jetstream { max_memory_store: 16MB, max_file_store: 0 }+max_payload: 64KB+authorization {+ users: [{+ user: sie-gateway+ password: $SIE_NATS_AUTH_GATEWAY_PASSWORD+ permissions: {+ publish: { allow: [+ "$JS.API.INFO",+ "$JS.API.STREAM.CREATE.KV_SIE_THRESHOLD_COUNTS",+ "$JS.API.STREAM.CREATE.KV_SIE_THRESHOLD_DECISIONS",+ "$JS.API.STREAM.CREATE.KV_SIE_THRESHOLD_LEASE",+ "$JS.API.STREAM.INFO.KV_SIE_THRESHOLD_COUNTS",+ "$JS.API.STREAM.INFO.KV_SIE_THRESHOLD_DECISIONS",+ "$JS.API.STREAM.INFO.KV_SIE_THRESHOLD_LEASE",+ "$JS.API.STREAM.MSG.GET.KV_SIE_THRESHOLD_COUNTS",+ "$JS.API.STREAM.MSG.GET.KV_SIE_THRESHOLD_DECISIONS",+ "$JS.API.STREAM.MSG.GET.KV_SIE_THRESHOLD_LEASE",+ "$KV.SIE_THRESHOLD_COUNTS.>",+ "$KV.SIE_THRESHOLD_DECISIONS.>",+ "$KV.SIE_THRESHOLD_LEASE.sampler"+ ] }+ subscribe: { allow: ["_INBOX.>"] }+ }+ }]+}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/config-deployment.yaml b/deploy/helm/sie-cluster/templates/config-deployment.yamlindex 6ff495349..d203dc967 100644--- a/deploy/helm/sie-cluster/templates/config-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/config-deployment.yaml@@ -74,6 +74,8 @@ spec:containerPort: 8080protocol: TCPenv:+ - name: SIE_THRESHOLD_ROUTING_ENABLED+ value: {{ dig "thresholdRouting" "enabled" false .Values.gateway | quote }}- name: POD_NAMEvalueFrom:fieldRef:diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex c8ccfc63e..ab2588604 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -36,6 +36,9 @@"SIE_CONFIG_SERVICE_TOKEN""SIE_NATS_PASSWORD""SIE_NATS_USER"+ "SIE_THRESHOLD_ROUTING_ENABLED"+ "SIE_THRESHOLD_NATS_URL"+ "SIE_THRESHOLD_NATS_REPLICAS""SIE_STREAM_MAX_AGE_S""SIE_STREAM_REPLICAS""SIE_STREAM_STORAGE") -}}@@ -278,6 +281,14 @@ spec:name: {{ . }}key: {{ include "sie-cluster.gateway.adminTokenSecretKey" $ }}{{- end }}+ - name: SIE_THRESHOLD_ROUTING_ENABLED+ value: {{ dig "thresholdRouting" "enabled" false .Values.gateway | quote }}+ {{- if dig "thresholdRouting" "enabled" false .Values.gateway }}+ - name: SIE_THRESHOLD_NATS_URL+ value: "nats://{{ include "sie-cluster.threshold.serviceName" . }}:4222"+ - name: SIE_THRESHOLD_NATS_REPLICAS+ value: "1"+ {{- end }}{{- if .Values.nats.enabled }}- name: SIE_NATS_URLvalue: {{ .Values.nats.url | default (printf "nats://%s-nats:4222" .Release.Name) | quote }}diff --git a/deploy/helm/sie-cluster/templates/threshold-control.yaml b/deploy/helm/sie-cluster/templates/threshold-control.yamlnew file mode 100644index 000000000..c9398529c--- /dev/null+++ b/deploy/helm/sie-cluster/templates/threshold-control.yaml@@ -0,0 +1,118 @@+{{- if dig "thresholdRouting" "enabled" false .Values.gateway }}+{{- if not (and .Values.nats.enabled .Values.nats.auth.enabled .Values.config.enabled .Values.config.configStore.enabled .Values.workers.common.workerSidecar.enabled) }}+{{- fail "gateway.thresholdRouting.enabled requires authenticated NATS, persistent sie-config storage, and queue worker sidecars" }}+{{- end }}+{{- $gatewaySecret := include "sie-cluster.nats.authSecretName" (dict "auth" .Values.nats.auth "release" .Release.Name "component" "gateway") }}+{{- range $component := list "config" "worker" }}+{{- if eq $gatewaySecret (include "sie-cluster.nats.authSecretName" (dict "auth" $.Values.nats.auth "release" $.Release.Name "component" $component)) }}+{{- fail "threshold control requires a gateway NATS Secret distinct from config and worker credentials" }}+{{- end }}+{{- end }}+{{- $name := include "sie-cluster.threshold.serviceName" . }}+apiVersion: v1+kind: ConfigMap+metadata:+ name: {{ $name }}+ namespace: {{ include "sie-cluster.namespace" . }}+data:+ nats.conf: |+ {{- include "sie-cluster.threshold.config" . | nindent 4 }}+---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: {{ $name }}+ namespace: {{ include "sie-cluster.namespace" . }}+spec:+ replicas: 1+ # Ephemeral state must have one broker authority during replacement.+ strategy:+ type: Recreate+ selector:+ matchLabels:+ app.kubernetes.io/instance: {{ .Release.Name }}+ app.kubernetes.io/component: threshold-control+ template:+ metadata:+ labels:+ app.kubernetes.io/instance: {{ .Release.Name }}+ app.kubernetes.io/component: threshold-control+ annotations:+ checksum/config: {{ include "sie-cluster.threshold.config" . | sha256sum | quote }}+ spec:+ automountServiceAccountToken: false+ {{- include "sie-cluster.imagePullSecrets" . | nindent 6 }}+ containers:+ - name: threshold-control+ image: {{ .Values.gateway.thresholdRouting.image | quote }}+ imagePullPolicy: IfNotPresent+ args: ["-c", "/etc/nats/nats.conf"]+ env:+ - name: SIE_NATS_AUTH_GATEWAY_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ include "sie-cluster.nats.authSecretName" (dict "auth" .Values.nats.auth "release" .Release.Name "component" "gateway") }}+ key: password+ ports:+ - name: client+ containerPort: 4222+ - name: monitor+ containerPort: 8222+ readinessProbe:+ httpGet:+ path: /healthz?js-enabled-only=true+ port: monitor+ livenessProbe:+ tcpSocket:+ port: client+ resources:+ requests:+ cpu: 50m+ memory: 64Mi+ limits:+ cpu: "1"+ memory: 128Mi+ volumeMounts:+ - name: config+ mountPath: /etc/nats+ readOnly: true+ volumes:+ - name: config+ configMap:+ name: {{ $name }}+---+apiVersion: v1+kind: Service+metadata:+ name: {{ $name }}+ namespace: {{ include "sie-cluster.namespace" . }}+spec:+ selector:+ app.kubernetes.io/instance: {{ .Release.Name }}+ app.kubernetes.io/component: threshold-control+ ports:+ - name: client+ port: 4222+ targetPort: client+---+apiVersion: networking.k8s.io/v1+kind: NetworkPolicy+metadata:+ name: {{ $name }}+ namespace: {{ include "sie-cluster.namespace" . }}+spec:+ podSelector:+ matchLabels:+ app.kubernetes.io/instance: {{ .Release.Name }}+ app.kubernetes.io/component: threshold-control+ policyTypes: [Ingress, Egress]+ ingress:+ - from:+ - podSelector:+ matchLabels:+ {{- include "sie-cluster.gateway.selectorLabels" . | nindent 14 }}+ ports:+ - port: 4222+ protocol: TCP+ egress: []+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex e0ca12599..1fd9f40ce 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -33,7 +33,7 @@ fast at render time.{{- fail (printf "workers.common.modelReadyTimeoutSec=%d must be lower than the adapter worker liveness budget (%d * %d = %ds); increase workers.common.probes.liveness.failureThreshold/periodSeconds or lower modelReadyTimeoutSec" $modelReadyTimeoutS $workerLivenessFailures $workerLivenessPeriodS $workerLivenessBudgetS) }}{{- end }}{{- $reservedOtelEnv := include "sie-cluster.otel.reservedEnvNames" $root | fromJsonArray -}}-{{- $reservedWorkerEnv := concat $reservedOtelEnv (list "SIE_BUNDLE" "SIE_GPU_TYPE" "SIE_MACHINE_PROFILE" "SIE_POOL" "SIE_REMOTE_SERVING" "SIE_SGLANG_KERNEL_CACHE_ROOT" "SIE_UPSTREAMS_FILE" "SIE_WORKER_ID") -}}+{{- $reservedWorkerEnv := concat $reservedOtelEnv (list "SIE_BUNDLE" "SIE_GPU_TYPE" "SIE_MACHINE_PROFILE" "SIE_POOL" "SIE_REMOTE_SERVING" "SIE_SGLANG_KERNEL_CACHE_ROOT" "SIE_UPSTREAMS_FILE" "SIE_WORKER_ID" "SIE_THRESHOLD_ROUTING_ENABLED") -}}{{- range $upstreamName, $_ := (default dict $root.Values.upstreams) -}}{{- $reservedWorkerEnv = append $reservedWorkerEnv (include "sie-cluster.upstream.keyEnvName" $upstreamName) -}}{{- end -}}@@ -450,6 +450,8 @@ spec:- name: SIE_REMOTE_SERVINGvalue: "0"{{- end }}+ - name: SIE_THRESHOLD_ROUTING_ENABLED+ value: {{ dig "thresholdRouting" "enabled" false $root.Values.gateway | quote }}{{- if $root.Values.workers.common.workerSidecar.enabled }}# worker-sidecar owns the NATS loop; the adapter process# exposes the IPC server over a shared Unix socket. The chart fails renderdiff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 3183d95fe..8031e977f 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -182,6 +182,13 @@ config:# config deltas. It does not own config persistence or writes;# POST /v1/configs/models is not registered on the gateway (axum returns 405).gateway:+ # -- Experimental shared-demand routing. Creates an isolated authenticated+ # control broker; disabled deployments continue to refuse threshold policies.+ thresholdRouting:+ enabled: false+ # -- Same pinned broker image used by gateway integration tests.+ image: nats:2.12-alpine@sha256:b270f5e2428354c0335612694d7dd2fb588148e567a5757fdff325ef9c9332e6+# -- Job/friendly model aliases → canonical model id, optionally bundle-# qualified. Maps a request like `model: "sql"` to a real model, and a# `bundle:/org/model` target pins a precision/profile bundle (e.g. route SQLdiff --git a/packages/sie_config/src/sie_config/model_registry.py b/packages/sie_config/src/sie_config/model_registry.pyindex 4ec1cc6d9..d565b126c 100644--- a/packages/sie_config/src/sie_config/model_registry.py+++ b/packages/sie_config/src/sie_config/model_registry.py@@ -4,6 +4,8 @@ import copyimport hashlibimport jsonimport logging+import math+import osimport reimport threadingfrom collections.abc import Iterable@@ -135,7 +137,7 @@ def validate_routing_config(config: dict[str, Any]) -> None:policy = routing.get("policy")if not isinstance(policy, str) or policy not in {"remote_only", "fallback", "threshold"}:raise ValueError("routing must set a recognized policy")- if policy == "threshold":+ if policy == "threshold" and os.environ.get("SIE_THRESHOLD_ROUTING_ENABLED") != "true":raise ValueError("routing policy 'threshold' is not available yet")threshold_fields = ("wake_above", "sleep_below", "window_s", "cooldown_s")@@ -151,23 +153,42 @@ def validate_routing_config(config: dict[str, Any]) -> None:else:if config.get("remote_backed"):raise ValueError("a 'remote_backed' model cannot use routing policy 'fallback'")- if any(routing.get(key) is not None for key in threshold_fields):- raise ValueError("routing policy 'fallback' takes no threshold field")- triggers = routing.get("triggers")- if triggers is not None:- allowed = {"provisioning", "model_loading", "saturated", "unhealthy"}- if not isinstance(triggers, list | tuple) or not triggers:- raise ValueError("routing.triggers must name at least one trigger; omit it for the default")- if any(not isinstance(trigger, str) or trigger not in allowed for trigger in triggers):- raise ValueError("routing.triggers contains an unsupported trigger")- if len(set(triggers)) != len(triggers):- raise ValueError("routing.triggers must not repeat a trigger")+ if policy == "threshold":+ if routing.get("triggers") is not None:+ raise ValueError("routing policy 'threshold' does not use triggers")+ for key in threshold_fields:+ value = routing.get(key)+ error = f"routing.{key} must be a finite positive number"+ if isinstance(value, bool) or not isinstance(value, int | float):+ raise ValueError(error)+ try:+ finite = math.isfinite(value)+ except OverflowError:+ finite = False+ if not finite or value <= 0:+ raise ValueError(error)+ if routing["sleep_below"] >= routing["wake_above"]:+ raise ValueError("routing.sleep_below must be lower than routing.wake_above")+ if routing["window_s"] > 86400 or routing["cooldown_s"] > 86400:+ raise ValueError("threshold windows must not exceed 86400 seconds")+ else:+ if any(routing.get(key) is not None for key in threshold_fields):+ raise ValueError("routing policy 'fallback' takes no threshold field")+ triggers = routing.get("triggers")+ if triggers is not None:+ allowed = {"provisioning", "model_loading", "saturated", "unhealthy"}+ if not isinstance(triggers, list | tuple) or not triggers:+ raise ValueError("routing.triggers must name at least one trigger; omit it for the default")+ if any(not isinstance(trigger, str) or trigger not in allowed for trigger in triggers):+ raise ValueError("routing.triggers contains an unsupported trigger")+ if len(set(triggers)) != len(triggers):+ raise ValueError("routing.triggers must not repeat a trigger")tasks = config.get("tasks") or {}if not isinstance(tasks, dict):raise ValueError("routing tasks must be a mapping")if any(tasks.get(task) is not None for task in ("encode", "score")):raise ValueError(- "routing policy 'fallback' cannot serve encode or score until remote equivalence is proven"+ f"routing policy '{policy}' cannot serve encode or score until remote equivalence is proven")profiles = config.get("profiles") or {}diff --git a/packages/sie_config/tests/test_remote_bundle_routing.py b/packages/sie_config/tests/test_remote_bundle_routing.pyindex a1e953c5c..0e945eff2 100644--- a/packages/sie_config/tests/test_remote_bundle_routing.py+++ b/packages/sie_config/tests/test_remote_bundle_routing.py@@ -9,7 +9,7 @@ from typing import Anyimport pytestimport yaml-from sie_config.model_registry import ModelRegistry+from sie_config.model_registry import ModelRegistry, validate_routing_configfrom sie_server.config.upstreams import Upstream, install_upstreamsfrom sie_server.core.registry import ModelRegistry as WorkerModelRegistryfrom sie_server.ipc_types import ReplaceModelConfigEntry, ReplaceModelConfigsRequest@@ -98,3 +98,53 @@ async def test_a_remote_lane_worker_reports_the_control_plane_hash(registry: Modassert response.unsupported_models == []assert response.bundle_config_hashassert response.bundle_config_hash == registry.compute_bundle_config_hash("remote")+++THRESHOLD = {+ "policy": "threshold",+ "fallback_profile": "remote",+ "wake_above": 2,+ "sleep_below": 1,+ "window_s": 1,+ "cooldown_s": 1,+}+++def test_threshold_config_is_flagged_and_routes_to_existing_bundles(+ registry: ModelRegistry, monkeypatch: pytest.MonkeyPatch+) -> None:+ config = {**copy.deepcopy(HYBRID), "tasks": {"generate": {}}, "routing": THRESHOLD}+ with pytest.raises(ValueError, match="not available yet"):+ validate_routing_config(config)+ monkeypatch.setenv("SIE_THRESHOLD_ROUTING_ENABLED", "true")+ validate_routing_config(config)+ registry.add_model_config(config)+ assert registry.resolve_bundle("acme/hybrid") == "default"+ assert registry.resolve_bundle("acme/hybrid:remote") == "remote"+ with pytest.raises(ValueError, match="remote equivalence"):+ validate_routing_config({**HYBRID, "routing": THRESHOLD})+++ "change",+ [+ {"wake_above": True},+ {"sleep_below": 2},+ {"window_s": float("inf")},+ {"cooldown_s": 0},+ {"window_s": 86401},+ {"cooldown_s": None},+ {"triggers": ["saturated"]},+ ],+)+def test_enabled_threshold_keeps_policy_bounds(change: dict[str, object], monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_THRESHOLD_ROUTING_ENABLED", "true")+ with pytest.raises(ValueError, match=r"routing|threshold"):+ validate_routing_config({**HYBRID, "tasks": {"generate": {}}, "routing": {**THRESHOLD, **change}})++[email protected]("field", ["wake_above", "sleep_below", "window_s", "cooldown_s"])+def test_threshold_rejects_unrepresentable_integer_bounds(field: str, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_THRESHOLD_ROUTING_ENABLED", "true")+ with pytest.raises(ValueError, match="finite positive number"):+ validate_routing_config({**HYBRID, "tasks": {"generate": {}}, "routing": {**THRESHOLD, field: 10**400}})diff --git a/packages/sie_gateway/docs/threshold-routing.md b/packages/sie_gateway/docs/threshold-routing.mdindex 2e39f6369..4bb12ca38 100644--- a/packages/sie_gateway/docs/threshold-routing.md+++ b/packages/sie_gateway/docs/threshold-routing.md@@ -1,9 +1,11 @@# Threshold demand coordinator-This is the shared-state prerequisite for the `threshold` policy in issue-[#415](https://github.com/superlinked/sie/issues/415). Request routing still-refuses `threshold`: the deployment flag, coordinator lifecycle, shared caller-validation and request-path integration are separate delivery steps.+This implements the shared-state contract for the experimental `threshold`+policy in issue [#415](https://github.com/superlinked/sie/issues/415). The cluster+integration is disabled by default. `gateway.thresholdRouting.enabled` creates+an isolated control broker and propagates the opt-in to gateway, configuration+service and queue workers. Numerical models and managed deployment routes stay+gated. See [the remote-backend guide](../../sie_server/REMOTE_BACKENDS.md#experimental-cluster-threshold-routing).`ThresholdCoordinator` accepts a JetStream context for an **isolated controlbroker endpoint**. Do not pass the inference queue connection. The coordinator@@ -84,3 +86,31 @@ restarts the evidence window; it does not move or consume inference work.One or three JetStream replicas are accepted, and the external endpoint mustsupply the corresponding topology. These bounds are implementation limits,not measured throughput or latency claims.+++## Request integration++`SIE_THRESHOLD_ROUTING_ENABLED=true` requires `SIE_THRESHOLD_NATS_URL`, gateway+NATS authentication and `SIE_THRESHOLD_NATS_REPLICAS` (1 or 3; the chart uses 1).+The URL must name a separate NATS endpoint without embedded credentials. The+runtime waits for a complete export bootstrap, then binds targets to the nonzero+authoritative config epoch and the exact registry snapshot, and samples every second. Standby ownership errors do not+prevent their demand flush or verified cached decisions. Snapshot or epoch+replacement refuses previous authority even when execution hashes are equal.+Requests also retain local/fallback routing while a registry writer holds the+snapshot fence; request threads never wait on that writer.++After shared caller validation, eligible bare-model generation/extraction+requests count once. A `Remote` decision returns a plan from the same pinned+snapshot and rewrites before any local demand, model-load work or inference+publish. The remote override requires execution-authority-capable transport and+current verified workers. Overrides cannot self-bridge. `WakeLocal` and missing+fresh authority preserve local routing and the provisioning/loading bridge.+Explicit caller selectors and remote-forbid controls keep their existing+behavior; a valid remote-forbid request still contributes bare-model demand.++The Helm opt-in requires persistent sie-config storage and a real configuration+mutation establishing a nonzero persisted epoch. If config-store recovery+rewinds that epoch, wait for all gateway replicas to apply the recovered export,+then restart only the isolated threshold broker to discard the superseded+generation. Requests retain local/fallback behavior until fresh evidence forms.diff --git a/packages/sie_gateway/src/handlers/audio.rs b/packages/sie_gateway/src/handlers/audio.rsindex 620054601..fe66dbc32 100644--- a/packages/sie_gateway/src/handlers/audio.rs+++ b/packages/sie_gateway/src/handlers/audio.rs@@ -1182,4 +1182,42 @@ mod tests {let body = to_bytes(srt.into_body(), 4096).await.unwrap();assert_eq!(body, "1\n00:00:00,000 --> 00:00:01,000\nhello world\n");}+ #[tokio::test]+ async fn audio_threshold_remote_creates_no_local_demand_or_warmup() {+ use crate::handlers::test_support::ThresholdBroker;+ use crate::state::threshold_coordinator::ThresholdSampler;+ let Some(broker) = ThresholdBroker::start().await else {+ return;+ };+ let config = format!("{HYBRID_EXTRACT_MODEL}\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 = TestGateway::with_threshold_routing(&[&config], true).await;+ gateway+ .add_verified_worker("remote-1", REMOTE_LANE, &[])+ .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(std::time::Duration::from_millis(1050)).await;+ binding.coordinator.sample(&mut sampler).await.unwrap();+ }+ let (content_type, body) =+ multipart_body(&[("model", "acme/extract")], "clip.wav", b"RIFFtest");+ let request = Request::builder()+ .method(Method::POST)+ .uri("/v1/audio/transcriptions")+ .header(header::CONTENT_TYPE, content_type)+ .body(Body::from(body))+ .unwrap();+ let response = proxy_openai_transcription(State(Arc::clone(&gateway.state)), request).await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()["x-sie-served-by"], "remote");+ assert!(!response.headers().contains_key("x-sie-fallback-reason"));+ assert!(gateway.state.demand_tracker.active_lanes().is_empty());+ let work = gateway.dispatcher.dispatched();+ assert_eq!(work.len(), 1);+ assert_eq!(work[0].model, "acme/extract:remote");+ assert_eq!(work[0].bundle, "remote");+ assert_eq!(gateway.dispatcher.execution_authority(), vec![true]);+ }}diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 539d4a697..3bd9886d8 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -2237,6 +2237,7 @@ fn fallback_plan_for_request(if !allowed|| !explicit_bundle.is_empty()|| attempt.active()+ || ext.get::<RemoteFallbackOverride>().is_some()|| ext.get::<ExplicitProfileSelector>().is_some()|| remote_forbidden(headers).unwrap_or(true)|| state.model_access_policy.is_some()@@ -2253,6 +2254,40 @@ fn fallback_plan_for_request(state.model_registry.remote_fallback_plan(model, trigger)}+/// Threshold decisions are counted only after caller validation and before+/// any local demand or work is published. Caller selectors retain authority.+#[allow(clippy::too_many_arguments)]+fn threshold_remote_plan_for_request(+ state: &AppState,+ headers: &HeaderMap,+ ext: &axum::http::Extensions,+ model: &str,+ allowed: bool,+ explicit_bundle: &str,+) -> Option<crate::state::model_registry::RemoteFallbackPlan> {+ if !allowed+ || !explicit_bundle.is_empty()+ || ext.get::<RemoteFallbackOverride>().is_some()+ || ext.get::<ExplicitProfileSelector>().is_some()+ || state.model_access_policy.is_some()+ || ["x-sie-machine-profile", "x-sie-pool", "x-sie-engine"]+ .iter()+ .any(|name| headers.contains_key(*name))+ || !state+ .work_publisher+ .as_ref()+ .is_some_and(|publisher| publisher.supports_execution_authority_v1())+ {+ return None;+ }+ 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) {+ return None;+ }+ Some(plan)+}+/// 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)]@@ -2401,19 +2436,11 @@ fn model_loading_refusal(endpoint: &str) -> Response {refusal}-/// 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.-#[allow(clippy::result_large_err, clippy::too_many_arguments)]-fn native_fallback_plan(- state: &AppState,- req: &Request,+fn native_bridge_eligible(endpoint: &str,- model: &str,parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,- trigger: FallbackTrigger,-) -> Option<crate::state::model_registry::RemoteFallbackPlan> {- let eligible = parsed.is_some_and(|(items, params)| match endpoint {+) -> bool {+ parsed.is_some_and(|(items, params)| match endpoint {"generate" => params.generate.is_some(),"extract" => {!items.is_empty()@@ -2425,7 +2452,22 @@ fn native_fallback_plan(})}_ => false,- });+ })+}++/// 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.+#[allow(clippy::result_large_err, clippy::too_many_arguments)]+fn native_fallback_plan(+ state: &AppState,+ req: &Request,+ endpoint: &str,+ model: &str,+ parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,+ trigger: FallbackTrigger,+) -> Option<crate::state::model_registry::RemoteFallbackPlan> {+ let eligible = native_bridge_eligible(endpoint, parsed);fallback_plan_for_request(state,req.headers(),@@ -2751,6 +2793,28 @@ async fn proxy_request_inner();}+ if let Some(plan) = threshold_remote_plan_for_request(+ &state,+ req.headers(),+ req.extensions(),+ &model_name,+ native_bridge_eligible(endpoint, prepared_native_parsed.as_ref()),+ "",+ ) {+ req.extensions_mut().insert(RemoteFallbackOverride(plan));+ if let Some(body) = prepared_native_body {+ *req.body_mut() = Body::from(body);+ }+ return Box::pin(proxy_request_inner(+ state,+ req,+ endpoint,+ provisioning_surface,+ inbound_publish_cx,+ ))+ .await;+ }+// Resolve the effective pool in one shot. `resolve_effective_pool`// folds the demand-tracking probe ("was there an exact// (bundle, machine_profile) match?") into the same registry load it uses to pick a@@ -3014,10 +3078,7 @@ async fn proxy_request_inner(let batch_target = if endpoint == "generate" {None} else if remote_forbidden(req.headers()).unwrap_or(false)- || req- .extensions()- .get::<FallbackAttempt>()- .is_some_and(FallbackAttempt::active)+ || req.extensions().get::<RemoteFallbackOverride>().is_some(){match execution_authority_target(&state,@@ -3072,10 +3133,7 @@ async fn proxy_request_inner(};let require_execution_authority_v1 = remote_forbidden(req.headers()).unwrap_or(false)- || req- .extensions()- .get::<FallbackAttempt>()- .is_some_and(FallbackAttempt::active);+ || req.extensions().get::<RemoteFallbackOverride>().is_some();let token_id = extract_bearer_token(req.headers()).map(|t| mask_token(&t)).unwrap_or_default();@@ -7894,6 +7952,32 @@ async fn resolve_generation_route(.map(|info| info.engine).unwrap_or_else(|| crate::types::bundle::DEFAULT_ENGINE.to_string()),};+ if let Some(plan) = threshold_remote_plan_for_request(+ state,+ hdr,+ ext,+ customer_model,+ bridge_allowed,+ explicit_bundle_override,+ ) {+ let mut remote_ext = ext.clone();+ remote_ext.insert(RemoteFallbackOverride(plan));+ return Box::pin(resolve_generation_route(+ state,+ hdr,+ &bundle,+ customer_model,+ dispatch_model,+ request_intent,+ explicit_bundle_override,+ &remote_ext,+ bridge_allowed,+ token_limit,+ metric_labels_slot,+ ))+ .await;+ }+let lookup = resolve_effective_pool_for_model(&state.registry,Some(&state.pool_manager),diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rsindex 93b646453..5ba0dbb51 100644--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs@@ -242,6 +242,7 @@ impl FallbackAttempt {#[cfg(test)]mod tests {use std::sync::Arc;+ use std::time::Duration;use axum::body::Body;use axum::extract::State;@@ -1716,4 +1717,225 @@ mod tests {.eq_ignore_ascii_case(UPSTREAM_HEADER.as_str()));assert_eq!(served_by["values"], json!(["local", "remote"]));}+ #[tokio::test]+ async fn threshold_shared_decision_routes_remote_without_local_demand_then_wakes_and_bridges() {+ 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 generate = format!("{HYBRID_GENERATE_MODEL}{policy}");+ let extract = format!("{HYBRID_EXTRACT_MODEL}{policy}");+ let gateway = TestGateway::with_threshold_routing(&[&generate, &extract], true).await;+ gateway+ .add_verified_worker("remote-1", REMOTE_LANE, &[])+ .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/chat").unwrap(),+ ThresholdDecision::Remote+ );+ for surface in ["native", "chat", "completions", "responses"] {+ let response = buffered_surface(&gateway, surface, json!({})).await;+ assert_eq!(response.status(), StatusCode::OK, "{surface}");+ assert_eq!(stamped(&response), (Some("remote"), Some("team-sie")));+ assert!(!response.headers().contains_key("x-sie-fallback-reason"));+ }+ for msgpack in [false, true] {+ let response = proxy_request(+ State(Arc::clone(&gateway.state)),+ extraction_request(msgpack, json!({})),+ "extract",+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ }+ assert!(gateway.state.demand_tracker.active_lanes().is_empty());+ assert!(gateway+ .dispatcher+ .dispatched()+ .iter()+ .all(|work| work.bundle == "remote"+ && work.model.ends_with(":remote")+ && work.endpoint != "load"));+ assert_eq!(gateway.dispatcher.execution_authority(), vec![true; 6]);++ for surface in ["native", "chat", "completions"] {+ let state = State(Arc::clone(&gateway.state));+ let response = match surface {+ "native" => proxy_request(state, json_request("/v1/generate/acme/chat", json!({"prompt":"hello", "max_new_tokens":4, "stream":true})), "generate").await,+ "chat" => proxy_chat(state, json_request("/v1/chat/completions", json!({"model":"acme/chat", "messages":[{"role":"user", "content":"hello"}], "stream":true}))).await,+ "completions" => proxy_completions(state, json_request("/v1/completions", json!({"model":"acme/chat", "prompt":"hello", "max_tokens":4, "stream":true}))).await,+ _ => unreachable!(),+ };+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(stamped(&response), (Some("remote"), Some("team-sie")));+ let body = axum::body::to_bytes(response.into_body(), 8192)+ .await+ .unwrap();+ assert!(String::from_utf8_lossy(&body).contains("[DONE]"));+ }+ assert!(gateway.state.demand_tracker.active_lanes().is_empty());+ assert_eq!(gateway.dispatcher.execution_authority(), vec![true; 9]);++ // Demand from two gateways reaches one decision, rather than dividing+ // the configured rate independently at each gateway.+ let replica = TestGateway::with_threshold_routing(&[&generate, &extract], true).await;+ replica+ .add_verified_worker("remote-2", REMOTE_LANE, &[])+ .await;+ let second = broker.bind(&replica).await;+ let mut standby = ThresholdSampler::default();+ let _ = second.coordinator.sample(&mut standby).await;+ tokio::time::sleep(Duration::from_millis(1050)).await;+ binding.coordinator.sample(&mut sampler).await.unwrap();+ for _ in 0..3 {+ second.coordinator.record_request("acme/chat").unwrap();+ }+ let _ = second.coordinator.sample(&mut standby).await;+ tokio::time::sleep(Duration::from_millis(1050)).await;+ binding.coordinator.sample(&mut sampler).await.unwrap();+ assert_eq!(+ binding.coordinator.decision("acme/chat").unwrap(),+ ThresholdDecision::WakeLocal+ );+ gateway+ .add_verified_worker("local-1", LOCAL_LANE, &[])+ .await;+ let before = gateway.dispatcher.dispatched().len();+ let response = buffered_surface(&gateway, "native", json!({})).await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()["x-sie-fallback-reason"], "model_loading");+ assert_eq!(+ &gateway.dispatcher.dispatched()[before..],+ &[+ dispatched("load", LOCAL_LANE, "acme/chat"),+ dispatched("generate", REMOTE_LANE, "acme/chat:remote"),+ ]+ );+ gateway+ .add_verified_worker("local-1", LOCAL_LANE, &["acme/chat"])+ .await;+ let response = buffered_surface(&gateway, "chat", json!({})).await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(stamped(&response), (Some("local"), None));+ assert_eq!(+ gateway.dispatcher.dispatched().last().unwrap().model,+ "acme/chat"+ );+ }+ #[tokio::test]+ async fn threshold_authority_preserves_selectors_validation_and_configuration_fences() {+ use crate::handlers::test_support::ThresholdBroker;+ use crate::state::threshold_coordinator::ThresholdSampler;+ use sha2::{Digest, Sha256};+ 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 config = format!("{HYBRID_GENERATE_MODEL}{policy}");+ let gateway = TestGateway::with_threshold_routing(&[&config], true).await;+ // A legacy worker may not become the authority of a threshold rewrite.+ gateway.add_worker("remote-1", REMOTE_LANE, &[]).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();+ }+ let response = proxy_request(+ State(Arc::clone(&gateway.state)),+ json_request(+ "/v1/generate/acme/chat",+ json!({"prompt":"", "max_new_tokens":0}),+ ),+ "generate",+ )+ .await;+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ let response = buffered_surface(&gateway, "native", json!({"profile":"default"})).await;+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ binding.coordinator.sample(&mut sampler).await.unwrap();+ let key = Sha256::digest(b"acme/chat")+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect::<String>();+ let counts = broker+ .context+ .get_key_value("SIE_THRESHOLD_COUNTS")+ .await+ .unwrap();+ let message = counts+ .stream+ .get_last_raw_message_by_subject(&format!("$KV.SIE_THRESHOLD_COUNTS.{key}"))+ .await+ .unwrap();+ let counter: serde_json::Value = serde_json::from_slice(&message.payload).unwrap();+ assert_eq!(counter["total"], 0);+ assert!(gateway.dispatcher.dispatched().is_empty());++ for lane in gateway.state.demand_tracker.active_lanes() {+ gateway.state.demand_tracker.clear(&lane);+ }+ let before = gateway.dispatcher.dispatched().len();+ let response = buffered_surface(&gateway, "native", json!({})).await;+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(gateway.dispatcher.dispatched().len(), before);+ assert!(gateway+ .state+ .demand_tracker+ .active_lanes()+ .iter()+ .all(|lane| lane.bundle() != "default"));+ gateway+ .add_verified_worker("remote-1", REMOTE_LANE, &[])+ .await;+ let mut request = json_request(+ "/v1/generate/acme/chat",+ json!({"prompt":"hello", "max_new_tokens":4}),+ );+ request+ .headers_mut()+ .insert("x-sie-remote", HeaderValue::from_static("forbid"));+ let response = proxy_request(State(Arc::clone(&gateway.state)), request, "generate").await;+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert!(gateway.dispatcher.dispatched().is_empty());++ // Forbid constrains execution, while valid bare-model demand still+ // contributes to the shared decision to wake local capacity.+ binding.coordinator.sample(&mut sampler).await.unwrap();+ let message = counts+ .stream+ .get_last_raw_message_by_subject(&format!("$KV.SIE_THRESHOLD_COUNTS.{key}"))+ .await+ .unwrap();+ let counter: serde_json::Value = serde_json::from_slice(&message.payload).unwrap();+ assert_eq!(counter["total"], 2);++ // Replace the registry while retaining the same epoch, and even the+ // same execution hashes: the old decision must still lose authority.+ gateway.state.model_registry.reload();+ assert!(gateway+ .state+ .model_registry+ .threshold_remote_route("acme/chat", 1)+ .is_none());+ assert!(gateway+ .state+ .model_registry+ .threshold_remote_route("acme/chat", 2)+ .is_none());+ gateway.state.model_registry.clear_threshold_binding();+ let response = buffered_surface(&gateway, "chat", json!({})).await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()["x-sie-fallback-reason"], "provisioning");+ }}diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rsindex de9aa1408..6c24d3662 100644--- a/packages/sie_gateway/src/handlers/test_support.rs+++ b/packages/sie_gateway/src/handlers/test_support.rs@@ -140,6 +140,7 @@ pub(crate) struct RecordingDispatcher {stream_mid_error: AtomicBool,stream_terminal_failure: Mutex<Option<&'static str>>,dispatched: Mutex<Vec<Dispatched>>,+ execution_authority: Mutex<Vec<bool>>,}impl RecordingDispatcher {@@ -147,6 +148,10 @@ impl RecordingDispatcher {self.dispatched.lock().unwrap().clone()}+ pub(crate) fn execution_authority(&self) -> Vec<bool> {+ self.execution_authority.lock().unwrap().clone()+ }+pub(crate) fn saturate_local_queue(&self) {self.local_backpressure.store(true, Ordering::SeqCst);}@@ -277,7 +282,7 @@ impl WorkDispatcher for RecordingDispatcher {_engine: &str,_bundle_config_hash: &str,items: Vec<rmpv::Value>,- _params: &WorkParams,+ params: &WorkParams,) -> Result<(String,@@ -286,6 +291,10 @@ impl WorkDispatcher for RecordingDispatcher {),DispatchError,> {+ self.execution_authority+ .lock()+ .unwrap()+ .push(params.require_execution_authority_v1);self.record(Dispatched::new(endpoint, &target));if self.work_refused.load(Ordering::SeqCst) {return Err(DispatchError::Other("private upstream failure".into()));@@ -329,7 +338,7 @@ impl WorkDispatcher for RecordingDispatcher {display_model: &str,_engine: &str,bundle_config_hash: &str,- _params: &WorkParams,+ params: &WorkParams,_admission_pool: &str,) -> Result<(@@ -343,6 +352,10 @@ impl WorkDispatcher for RecordingDispatcher {if self.generate_refused.load(Ordering::SeqCst) {return Err("private upstream failure".into());}+ self.execution_authority+ .lock()+ .unwrap()+ .push(params.require_execution_authority_v1);self.record(Dispatched::new("generate", &target));let (rx, _tap) = terminal_chunk_collector(display_model, bundle_config_hash);Ok((@@ -359,7 +372,7 @@ impl WorkDispatcher for RecordingDispatcher {display_model: &str,_engine: &str,bundle_config_hash: &str,- _params: &WorkParams,+ params: &WorkParams,_admission_pool: &str,) -> Result<(@@ -370,6 +383,10 @@ impl WorkDispatcher for RecordingDispatcher {),String,> {+ self.execution_authority+ .lock()+ .unwrap()+ .push(params.require_execution_authority_v1);self.record(Dispatched::new("generate", &target));if self.generate_refused.load(Ordering::SeqCst) {return Err("private upstream failure".into());@@ -444,6 +461,10 @@ pub(crate) struct TestGateway {impl TestGateway {pub(crate) async fn new(models: &[&str]) -> Self {+ Self::with_threshold_routing(models, false).await+ }++ pub(crate) async fn with_threshold_routing(models: &[&str], threshold: bool) -> Self {let bundles_dir = tempfile::TempDir::new().unwrap();let models_dir = tempfile::TempDir::new().unwrap();std::fs::write(bundles_dir.path().join("default.yaml"), DEFAULT_BUNDLE).unwrap();@@ -468,10 +489,11 @@ impl TestGateway {profiles,lanes.clone(),)),- model_registry: Arc::new(ModelRegistry::new(+ model_registry: Arc::new(ModelRegistry::with_threshold_routing(bundles_dir.path(),models_dir.path(),true,+ threshold,)),pool_manager,work_publisher: Some(dispatcher.clone()),@@ -601,3 +623,97 @@ fn test_config(public_base_url: None,}}++/// Independent authenticated control broker for request-path regressions.+/// The inference dispatcher remains the recording fixture above.+pub(crate) struct ThresholdBroker {+ pub context: async_nats::jetstream::Context,+ _process: tokio::process::Child,+ _config: tempfile::NamedTempFile,+ _store_dir: tempfile::TempDir,+}++impl ThresholdBroker {+ pub(crate) async fn start() -> Option<Self> {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ drop(listener);+ let fixture = include_str!("../../../../tools/ci/fixtures/sie-threshold-nats.conf")+ .replace("port: 4222", &format!("listen: 127.0.0.1:{port}"))+ .replace("http_port: 8222", "http_port: -1");+ let store_dir = tempfile::tempdir().unwrap();+ let config = tempfile::NamedTempFile::new().unwrap();+ std::fs::write(config.path(), fixture).unwrap();+ let process = tokio::process::Command::new("nats-server")+ .args(["-c", config.path().to_str().unwrap()])+ .arg("-sd")+ .arg(store_dir.path())+ .env(+ "SIE_NATS_AUTH_GATEWAY_PASSWORD",+ "GatewayThresholdTestPassword0123456789",+ )+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .kill_on_drop(true)+ .spawn();+ let mut process = match process {+ Ok(process) => process,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ assert!(+ std::env::var("NATS_URL").is_err(),+ "NATS integration requires nats-server"+ );+ return None;+ }+ Err(error) => panic!("control fixture start failed: {error}"),+ };+ let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(10);+ while tokio::time::Instant::now() < ready_deadline {+ if let Some(status) = process.try_wait().expect("control fixture status") {+ panic!("control fixture exited before readiness: {status}");+ }+ if let Ok(Ok(client)) = tokio::time::timeout(+ Duration::from_millis(250),+ async_nats::ConnectOptions::new()+ .user_and_password(+ "sie-gateway".into(),+ "GatewayThresholdTestPassword0123456789".into(),+ )+ .connect(format!("nats://127.0.0.1:{port}")),+ )+ .await+ {+ return Some(Self {+ context: async_nats::jetstream::new(client),+ _process: process,+ _config: config,+ _store_dir: store_dir,+ });+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ panic!("control broker did not become ready");+ }++ pub(crate) async fn bind(+ &self,+ gateway: &TestGateway,+ ) -> Arc<crate::state::threshold_runtime::ThresholdBinding> {+ use crate::state::threshold_coordinator::ThresholdCoordinator;+ use crate::state::threshold_runtime::ThresholdBinding;+ gateway.state.config_epoch.set_max(1);+ let (generation, targets) = gateway.state.model_registry.threshold_targets(1).unwrap();+ let binding = Arc::new(ThresholdBinding {+ generation,+ epoch: 1,+ coordinator: ThresholdCoordinator::connect(&self.context, 1, targets)+ .await+ .unwrap(),+ });+ gateway+ .state+ .model_registry+ .install_threshold_binding(Arc::clone(&binding));+ binding+ }+}diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rsindex 35dcb33d8..5345fb333 100644--- a/packages/sie_gateway/src/main.rs+++ b/packages/sie_gateway/src/main.rs@@ -259,12 +259,13 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {// Set up discoverylet discovery = StaticDiscovery::new(config.worker_urls.clone());+ let threshold_settings = state::threshold_runtime::ThresholdSettings::from_env(&config)?;// Set up model registry (before NATS — NatsManager depends on it)- let model_registry = Arc::new(ModelRegistry::new(- &config.bundles_dir,- &config.models_dir,- true,- ));+ let model_registry = Arc::new(if threshold_settings.is_some() {+ ModelRegistry::with_threshold_routing(&config.bundles_dir, &config.models_dir, true, true)+ } else {+ ModelRegistry::new(&config.bundles_dir, &config.models_dir, true)+ });// Monotonic epoch counter shared between bootstrap, NATS delta handler,// epoch poller, and the /v1/configs/models/{id}/status endpoint. Starts@@ -742,6 +743,10 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {server::LaneBacklogMode::JetStreamRequired,);+ let _threshold_task = threshold_settings.map(|settings| {+ state::threshold_runtime::spawn_threshold_runtime(Arc::clone(&state), settings)+ });+let app = server::create_router(Arc::clone(&state), Arc::clone(&config));info!(diff --git a/packages/sie_gateway/src/state/mod.rs b/packages/sie_gateway/src/state/mod.rsindex 945500759..99397a601 100644--- a/packages/sie_gateway/src/state/mod.rs+++ b/packages/sie_gateway/src/state/mod.rs@@ -10,7 +10,7 @@ pub mod k8s_pool_watcher;pub mod model_registry;pub mod pinned_models;pub mod pool_manager;-#[allow(dead_code)] // Prerequisite; flag/routing wiring is the next layer.pub mod threshold_coordinator;+pub mod threshold_runtime;pub mod warm_floor;pub mod worker_registry;diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 7105014b0..e263d9a58 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -4,10 +4,13 @@ use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex, OnceLock};-use arc_swap::ArcSwap;+use arc_swap::{ArcSwap, ArcSwapOption};use sha2::{Digest, Sha256};use tracing::{debug, error, info, warn};+use crate::state::threshold_coordinator::{ThresholdDecision, ThresholdError, ThresholdTarget};+use crate::state::threshold_runtime::ThresholdBinding;+use crate::types::bundle::{engine_adapter_prefixes, BundleInfo, DEFAULT_ENGINE, KNOWN_ENGINES};use crate::types::model::{remote_adapter_upstream_kind, CanonicalProfile, FallbackTrigger, ModelConfig, ModelEntry,@@ -237,6 +240,8 @@ pub struct ModelRegistry {/// installed is protected by the retention guard, so a config service/// that later restarts empty cannot take it down.authoritative_surface: AtomicBool,+ threshold_enabled: bool,+ threshold_binding: ArcSwapOption<ThresholdBinding>,}impl ModelRegistry {@@ -244,6 +249,15 @@ impl ModelRegistry {bundles_dir: impl AsRef<Path>,models_dir: impl AsRef<Path>,auto_load: bool,+ ) -> Self {+ Self::with_threshold_routing(bundles_dir, models_dir, auto_load, false)+ }++ pub fn with_threshold_routing(+ bundles_dir: impl AsRef<Path>,+ models_dir: impl AsRef<Path>,+ auto_load: bool,+ threshold_enabled: bool,) -> Self {let registry = Self {bundles_dir: bundles_dir.as_ref().to_path_buf(),@@ -251,6 +265,8 @@ impl ModelRegistry {snapshot: ArcSwap::from_pointee(RegistrySnapshot::default()),write_lock: Mutex::new(()),authoritative_surface: AtomicBool::new(false),+ threshold_enabled,+ threshold_binding: ArcSwapOption::empty(),};if auto_load {registry.reload();@@ -366,7 +382,7 @@ impl ModelRegistry {if path.extension().and_then(|e| e.to_str()) != Some("yaml") {continue;}- match Self::load_model_file(&path) {+ match Self::load_model_file(&path, self.threshold_enabled) {Ok(model_entries) => {for model_entry in model_entries {debug!(@@ -504,11 +520,14 @@ impl ModelRegistry {})}- fn load_model_file(path: &Path) -> Result<Vec<ModelEntry>, Box<dyn std::error::Error>> {+ fn load_model_file(+ path: &Path,+ threshold_enabled: bool,+ ) -> Result<Vec<ModelEntry>, Box<dyn std::error::Error>> {let content = std::fs::read_to_string(path)?;let config: ModelConfig = serde_yaml::from_str(&content)?;- Self::expand_model_config_into_profile_variants(&config).map_err(|message| {+ Self::expand_model_config_with_threshold(&config, threshold_enabled).map_err(|message| {Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData,message,@@ -538,10 +557,18 @@ impl ModelRegistry {Ok(())}+ #[cfg(test)]fn expand_model_config_into_profile_variants(config: &ModelConfig,) -> Result<Vec<ModelEntry>, String> {- let base_entry = Self::model_entry_from_config(config)?;+ Self::expand_model_config_with_threshold(config, false)+ }++ fn expand_model_config_with_threshold(+ config: &ModelConfig,+ threshold_enabled: bool,+ ) -> Result<Vec<ModelEntry>, String> {+ let base_entry = Self::model_entry_with_threshold(config, threshold_enabled)?;let mut entries = if base_entry.profile_names.contains("default") {vec![base_entry.clone()]} else {@@ -694,7 +721,15 @@ impl ModelRegistry {.retain(|name, _| Some(name.as_str()) == native_encode_output);}+ #[cfg(test)]fn model_entry_from_config(config: &ModelConfig) -> Result<ModelEntry, String> {+ Self::model_entry_with_threshold(config, false)+ }++ fn model_entry_with_threshold(+ config: &ModelConfig,+ threshold_enabled: bool,+ ) -> Result<ModelEntry, String> {let info_extras = crate::types::model::ModelInfoExtras::from_model_config(config);let model_name = config.name.clone();let pool = Self::normalize_model_pool(config.pool.as_deref())?;@@ -722,18 +757,30 @@ impl ModelRegistry {info_extras,};Self::validate_profile_grammar_fallbacks(&entry)?;- Self::validate_remote_routing(&entry)?;+ Self::validate_remote_routing(&entry, threshold_enabled)?;Ok(entry)}- fn validate_remote_routing(entry: &ModelEntry) -> Result<(), String> {+ fn validate_remote_routing(entry: &ModelEntry, threshold_enabled: bool) -> Result<(), String> {let Some(routing) = &entry.info_extras.routing else {return Ok(());};routing.validate()?;- if matches!(routing.policy, RoutingPolicy::Threshold) {+ 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@@ -1716,6 +1763,25 @@ impl ModelRegistry {{return None;}+ Self::remote_plan_from_snapshot(&snap, local)+ }++ fn remote_plan_from_snapshot(+ 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"+ )+ })+ {+ return None;+ }+ let routing = local.info_extras.routing.as_ref()?;let remote_name = format!("{}:{}",local.canonical_base_model,@@ -1746,6 +1812,85 @@ impl ModelRegistry {})}+ pub(crate) fn threshold_targets(+ &self,+ epoch: u64,+ ) -> Result<(ModelRegistryGeneration, Vec<ThresholdTarget>), ThresholdError> {+ let generation = self.capture_generation();+ let snap = &generation.snapshot;+ let mut targets = Vec::new();+ for local in snap.models.values() {+ let Some(routing) = local.info_extras.routing.as_ref() else {+ continue;+ };+ if routing.policy != RoutingPolicy::Threshold || local.canonical_profile != "default" {+ continue;+ }+ let plan = Self::remote_plan_from_snapshot(snap, local)+ .ok_or(ThresholdError::Configuration)?;+ let local_bundle = local.bundles.first().ok_or(ThresholdError::Configuration)?;+ let local_hash = snap+ .bundle_pool_config_hashes+ .get(&(+ local_bundle.clone(),+ Self::entry_pool_name(local).to_string(),+ ))+ .ok_or(ThresholdError::Configuration)?;+ if local_hash.is_empty() {+ return Err(ThresholdError::Configuration);+ }+ let mut fingerprint = Sha256::new();+ fingerprint.update(local_hash.as_bytes());+ fingerprint.update(plan.config_hash.as_bytes());+ let fingerprint = fingerprint+ .finalize()+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect::<String>();+ targets.push(ThresholdTarget::new(+ &local.name,+ epoch,+ &fingerprint,+ routing,+ )?);+ }+ Ok((generation, targets))+ }++ pub(crate) fn install_threshold_binding(&self, binding: Arc<ThresholdBinding>) {+ self.with_current_generation(&binding.generation, || {+ self.threshold_binding.store(Some(binding.clone()))+ });+ }++ pub(crate) fn clear_threshold_binding(&self) {+ self.threshold_binding.store(None);+ }++ pub(crate) fn threshold_remote_route(+ &self,+ model: &str,+ epoch: u64,+ ) -> Option<RemoteFallbackPlan> {+ let binding = self.threshold_binding.load_full()?;+ if binding.epoch != epoch || model.contains(':') {+ return None;+ }+ // A snapshot writer must never block a request thread. Contention is+ // unavailable authority and retains the ordinary local/fallback path.+ let _fence = self.write_lock.try_lock().ok()?;+ if !Arc::ptr_eq(&self.snapshot.load_full(), &binding.generation.snapshot) {+ return None;+ }+ let snap = &binding.generation.snapshot;+ let canonical = Self::canonical_model_name(snap, model)?;+ binding.coordinator.record_request(&canonical).ok()?;+ if binding.coordinator.decision(&canonical).ok()? != ThresholdDecision::Remote {+ return None;+ }+ Self::remote_plan_from_snapshot(snap, snap.models.get(&canonical)?)+ }+pub fn get_model_pool_name(&self, model: &str) -> Option<String> {let snap = self.snapshot.load();let canonical = Self::canonical_model_name(&snap, model)?;@@ -2357,7 +2502,7 @@ impl ModelRegistry {};let applied = configs.len();let (new_models, new_model_names_lower) =- Self::build_authoritative_models(configs, &new_bundles)?;+ Self::build_authoritative_models(configs, &new_bundles, self.threshold_enabled)?;let mut bundle_config_hashes =Self::rebuild_bundle_config_hashes(&new_bundles, &new_models);@@ -2438,6 +2583,7 @@ impl ModelRegistry {fn build_authoritative_models(configs: Vec<ModelConfig>,bundles: &HashMap<String, BundleInfo>,+ threshold_enabled: bool,) -> Result<AuthoritativeModels, String> {let mut new_models: HashMap<String, ModelEntry> = HashMap::new();let mut new_model_names_lower: HashMap<String, String> = HashMap::new();@@ -2489,7 +2635,7 @@ impl ModelRegistry {));}- for mut entry in Self::expand_model_config_into_profile_variants(&config)? {+ for mut entry in Self::expand_model_config_with_threshold(&config, threshold_enabled)? {Self::assign_bundles(&mut entry, bundles);new_model_names_lower.insert(entry.name.to_lowercase(), entry.name.clone());new_models.insert(entry.name.clone(), entry);@@ -2710,7 +2856,7 @@ impl ModelRegistry {let mut affected_model_names = vec![sie_id.clone()];if let Some(base_entry) = snap.models.get(sie_id).cloned() {Self::validate_profile_grammar_fallbacks(&base_entry)?;- Self::validate_remote_routing(&base_entry)?;+ Self::validate_remote_routing(&base_entry, self.threshold_enabled)?;let old_variants: Vec<String> = snap.models.keys()@@ -2841,7 +2987,11 @@ impl ModelRegistry {#[cfg(test)]mod tests {use super::*;+ use crate::handlers::test_support::{TestGateway, ThresholdBroker, HYBRID_GENERATE_MODEL};+ use crate::state::threshold_coordinator::ThresholdSampler;use std::fs;+ use std::sync::mpsc;+ use std::time::Duration;use tempfile::TempDir;fn create_test_dirs() -> (TempDir, PathBuf, PathBuf) {@@ -2887,6 +3037,77 @@ mod tests {(dir, registry, config)}+ #[test]+ fn threshold_flag_admits_generation_but_keeps_numerical_and_zero_epoch_gates() {+ let (_dir, mut registry, mut config) = remote_routing_fixture();+ registry.threshold_enabled = true;+ config.routing = Some(+ serde_json::from_value(serde_json::json!({+ "policy":"threshold", "fallback_profile":"remote", "wake_above":2,+ "sleep_below":1, "window_s":1, "cooldown_s":1+ }))+ .unwrap(),+ );+ config.tasks = Some(serde_yaml::from_str("generate: {}\n").unwrap());+ registry+ .replace_model_configs_authoritative(vec![config.clone()])+ .unwrap();+ 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+ .replace_model_configs_authoritative(vec![config])+ .unwrap_err()+ .contains("fleet equivalence"));+ assert_eq!(registry.threshold_targets(1).unwrap().1.len(), 1);+ }++ #[tokio::test]+ async fn threshold_request_refuses_contended_snapshot_without_blocking() {+ let Some(broker) = ThresholdBroker::start().await else {+ return;+ };+ let model = format!(+ "{HYBRID_GENERATE_MODEL}\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 = TestGateway::with_threshold_routing(&[&model], true).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!(gateway+ .state+ .model_registry+ .threshold_remote_route("acme/chat", 1)+ .is_some());++ let registry = Arc::clone(&gateway.state.model_registry);+ let (held_tx, held_rx) = mpsc::channel();+ let (release_tx, release_rx) = mpsc::channel();+ let writer = std::thread::spawn(move || {+ let _write = registry.write_lock.lock().unwrap();+ held_tx.send(()).unwrap();+ // Bound a regression's blocking wait so this test cannot hang.+ release_rx.recv_timeout(Duration::from_secs(2)).unwrap();+ });+ held_rx.recv_timeout(Duration::from_secs(2)).unwrap();+ let route = gateway+ .state+ .model_registry+ .threshold_remote_route("acme/chat", 1);+ release_tx.send(()).unwrap();+ writer.join().unwrap();+ assert!(route.is_none());+ assert!(gateway+ .state+ .model_registry+ .threshold_remote_route("acme/chat", 1)+ .is_some());+ }+#[test]fn remote_routing_policy_survives_snapshots_and_is_scoped_to_bare_model() {let (_dir, registry, mut config) = remote_routing_fixture();diff --git a/packages/sie_gateway/src/state/threshold_runtime.rs b/packages/sie_gateway/src/state/threshold_runtime.rsnew file mode 100644index 000000000..b5ac920ee--- /dev/null+++ b/packages/sie_gateway/src/state/threshold_runtime.rs@@ -0,0 +1,266 @@+use std::sync::Arc;+use std::time::Duration;++use async_nats::jetstream;+use reqwest::Url;++use crate::config::{Config, NatsCredentials};+use crate::server::AppState;+use crate::state::model_registry::ModelRegistryGeneration;+use crate::state::threshold_coordinator::{+ ThresholdCoordinator, ThresholdSampler, THRESHOLD_SAMPLE_INTERVAL,+};++pub struct ThresholdSettings {+ url: String,+ credentials: NatsCredentials,+ replicas: usize,+}++impl ThresholdSettings {+ pub fn from_env(config: &Config) -> Result<Option<Self>, String> {+ let flag =+ std::env::var("SIE_THRESHOLD_ROUTING_ENABLED").unwrap_or_else(|_| "false".into());+ Self::parse(+ &flag,+ &std::env::var("SIE_THRESHOLD_NATS_URL").unwrap_or_default(),+ &std::env::var("SIE_THRESHOLD_NATS_REPLICAS").unwrap_or_else(|_| "1".into()),+ config,+ )+ }++ fn parse(+ flag: &str,+ url: &str,+ replicas: &str,+ config: &Config,+ ) -> Result<Option<Self>, String> {+ match flag {+ "false" => return Ok(None),+ "true" => {}+ _ => return Err("SIE_THRESHOLD_ROUTING_ENABLED must be true or false".into()),+ }+ let parsed = Url::parse(url)+ .map_err(|_| "threshold control endpoint must be an absolute NATS URL")?;+ if !matches!(parsed.scheme(), "nats" | "tls")+ || parsed.host_str().is_none()+ || !parsed.username().is_empty()+ || parsed.password().is_some()+ || parsed.query().is_some()+ || parsed.fragment().is_some()+ || !matches!(parsed.path(), "" | "/")+ {+ return Err(+ "threshold control endpoint must be a NATS URL without credentials or extra fields"+ .into(),+ );+ }+ let endpoint = url+ .parse::<async_nats::ServerAddr>()+ .map_err(|_| "invalid threshold control endpoint")?;+ for server in config.nats_url.split(',') {+ let queue = server+ .parse::<async_nats::ServerAddr>()+ .map_err(|_| "invalid inference NATS endpoint")?;+ if queue.host() == endpoint.host() && queue.port() == endpoint.port() {+ return Err("threshold state requires a separate broker endpoint".into());+ }+ }+ let credentials = config+ .nats_credentials()?+ .ok_or("threshold control endpoint requires gateway authentication")?;+ let replicas = replicas+ .parse::<usize>()+ .map_err(|_| "threshold replicas must be 1 or 3")?;+ if !matches!(replicas, 1 | 3) {+ return Err("threshold replicas must be 1 or 3".into());+ }+ Ok(Some(Self {+ url: url.to_string(),+ credentials,+ replicas,+ }))+ }+}++pub(crate) struct ThresholdBinding {+ pub generation: ModelRegistryGeneration,+ pub epoch: u64,+ pub coordinator: ThresholdCoordinator,+}++/// Own the isolated connection and sampler. Registry pointer fencing prevents+/// any decision from a superseded snapshot from suppressing local warm-up.+pub fn spawn_threshold_runtime(+ state: Arc<AppState>,+ settings: ThresholdSettings,+) -> tokio::task::JoinHandle<()> {+ tokio::spawn(async move {+ let mut context = None;+ let mut binding: Option<Arc<ThresholdBinding>> = None;+ let mut sampler = ThresholdSampler::default();+ let mut ticks = tokio::time::interval(THRESHOLD_SAMPLE_INTERVAL);+ ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ loop {+ ticks.tick().await;+ let epoch = state.config_epoch.get();+ if epoch == 0 || !state.config_epoch.is_bootstrapped() {+ state.model_registry.clear_threshold_binding();+ binding = None;+ continue;+ }+ if context.is_none() {+ let connect = async_nats::ConnectOptions::new()+ .user_and_password(+ settings.credentials.user.clone(),+ settings.credentials.password.clone(),+ )+ .connection_timeout(Duration::from_secs(2))+ .connect(&settings.url);+ context = match tokio::time::timeout(Duration::from_secs(2), connect).await {+ Ok(Ok(client)) => Some(jetstream::new(client)),+ _ => continue,+ };+ }+ if binding.as_ref().is_none_or(|old| {+ old.epoch != epoch+ || state+ .model_registry+ .with_current_generation(&old.generation, || ())+ .is_none()+ }) {+ state.model_registry.clear_threshold_binding();+ binding = None;+ sampler = ThresholdSampler::default();+ let Ok((generation, targets)) = state.model_registry.threshold_targets(epoch)+ else {+ continue;+ };+ if targets.is_empty() {+ continue;+ }+ let Ok(coordinator) = ThresholdCoordinator::connect(+ context.as_ref().expect("connected context"),+ settings.replicas,+ targets,+ )+ .await+ else {+ continue;+ };+ if state.config_epoch.get() != epoch || !state.config_epoch.is_bootstrapped() {+ continue;+ }+ let current = Arc::new(ThresholdBinding {+ generation,+ epoch,+ coordinator,+ });+ state+ .model_registry+ .install_threshold_binding(Arc::clone(¤t));+ binding = Some(current);+ }+ if let Some(current) = &binding {+ // Standby sampling normally returns unavailable; its requests+ // still read decisions bound to the elected sampler's lease.+ let _ = current.coordinator.sample(&mut sampler).await;+ }+ }+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn nonzero_delta_epoch_cannot_acquire_authority_before_complete_bootstrap() {+ use crate::handlers::test_support::{TestGateway, ThresholdBroker, HYBRID_GENERATE_MODEL};+ let Some(broker) = ThresholdBroker::start().await else {+ return;+ };+ let model = format!(+ "{HYBRID_GENERATE_MODEL}\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 = TestGateway::with_threshold_routing(&[&model], true).await;+ gateway.state.config_epoch.set_max(7);+ let runtime = spawn_threshold_runtime(+ Arc::clone(&gateway.state),+ ThresholdSettings {+ url: format!(+ "nats://127.0.0.1:{}",+ broker.context.client().server_info().port+ ),+ credentials: NatsCredentials {+ user: "sie-gateway".into(),+ password: "GatewayThresholdTestPassword0123456789".into(),+ },+ replicas: 1,+ },+ );+ tokio::time::sleep(Duration::from_millis(1100)).await;+ assert!(!gateway.state.config_epoch.is_bootstrapped());+ assert!(broker+ .context+ .get_key_value("SIE_THRESHOLD_COUNTS")+ .await+ .is_err());+ assert!(gateway+ .state+ .model_registry+ .threshold_remote_route("acme/chat", 7)+ .is_none());+ gateway.state.config_epoch.mark_bootstrapped();+ tokio::time::timeout(Duration::from_secs(4), async {+ loop {+ if broker+ .context+ .get_key_value("SIE_THRESHOLD_LEASE")+ .await+ .is_ok()+ {+ break;+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await+ .expect("complete bootstrap allows coordination");+ runtime.abort();+ let _ = runtime.await;+ }++ #[test]+ fn flag_requires_an_isolated_authenticated_control_endpoint() {+ let mut config = Config::load();+ config.nats_url = "nats://queue.example:4222".into();+ config.nats_user = "sie-gateway".into();+ config.nats_password = "gateway-test-password".into();+ assert!(ThresholdSettings::parse("false", "", "", &config)+ .unwrap()+ .is_none());+ assert!(+ ThresholdSettings::parse("true", "nats://control.example:4222", "1", &config)+ .unwrap()+ .is_some()+ );+ for url in [+ "nats://queue.example:4222",+ "nats://user:[email protected]:4222",+ "nats://control.example:4222?token=secret",+ "https://control.example:4222",+ "nats://control.example:4222/path",+ ] {+ assert!(ThresholdSettings::parse("true", url, "1", &config).is_err());+ }+ assert!(ThresholdSettings::parse("yes", "", "1", &config).is_err());+ assert!(+ ThresholdSettings::parse("true", "nats://control.example:4222", "2", &config).is_err()+ );+ config.nats_password.clear();+ assert!(+ ThresholdSettings::parse("true", "nats://control.example:4222", "1", &config).is_err()+ );+ }+}diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex 21c4c8f10..c293e2fbe 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -489,14 +489,16 @@ impl RoutingConfig {#[allow(dead_code)] // Consumed by subsequent cluster fallback dispatch.pub fn permits(&self, trigger: FallbackTrigger) -> bool {- self.policy == RoutingPolicy::Fallback- && self.triggers.as_ref().map_or(- matches!(- trigger,- FallbackTrigger::Provisioning | FallbackTrigger::ModelLoading- ),- |triggers| triggers.contains(&trigger),- )+ matches!(+ self.policy,+ RoutingPolicy::Fallback | RoutingPolicy::Threshold+ ) && self.triggers.as_ref().map_or(+ matches!(+ trigger,+ FallbackTrigger::Provisioning | FallbackTrigger::ModelLoading+ ),+ |triggers| triggers.contains(&trigger),+ )}pub fn validate(&self) -> Result<(), String> {@@ -513,6 +515,13 @@ impl RoutingConfig {{return Err("routing threshold bounds must be finite and positive".into());}+ if [self.window_s, self.cooldown_s]+ .iter()+ .flatten()+ .any(|value| *value > 86400.0)+ {+ return Err("threshold windows must not exceed 86400 seconds".into());+ }match self.policy {RoutingPolicy::RemoteOnly => {if self.fallback_profile.is_some()@@ -1126,6 +1135,8 @@ pool: customer-a"sleep_below":2, "window_s":1, "cooldown_s":1}),json!({"policy":"threshold", "fallback_profile":"remote", "wake_above":2,"sleep_below":1, "window_s":0, "cooldown_s":1}),+ json!({"policy":"threshold", "fallback_profile":"remote", "wake_above":2,+ "sleep_below":1, "window_s":86401, "cooldown_s":1}),json!({"policy":"threshold", "fallback_profile":"remote", "wake_above":2,"sleep_below":1, "window_s":1, "cooldown_s":1, "triggers":["provisioning"]}),] {@@ -1141,7 +1152,7 @@ pool: customer-a"fallback_profile":"remote", "wake_above":2, "sleep_below":1,"window_s":1, "cooldown_s":1})).unwrap();- assert!(!threshold.permits(FallbackTrigger::Provisioning));+ assert!(threshold.permits(FallbackTrigger::Provisioning));}#[test]diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.mdindex ec3b3a60d..02918e00a 100644--- a/packages/sie_server/REMOTE_BACKENDS.md+++ b/packages/sie_server/REMOTE_BACKENDS.md@@ -48,11 +48,12 @@ declared output (see [Single-node generation fallback](#single-node-generation-fA request that names a profile bypasses the bare-model policy, including anexplicit `default`. Single-node OpenAI hybrid `encode` and `score` require theoperator-owned equivalence admission described below. SIE hybrid encode and-score require the fresh identity admission described below; `threshold` remains-a separate delivery. Cluster remote profiles use the queue. Cluster-generation and extraction fallback are described below. Cluster saturation and-unhealthy-worker spill require explicit triggers. Numeric fleet bridges and-coordinated threshold routing remain separate deliveries.+score require the fresh identity admission described below. Cluster remote+profiles use the queue. Cluster generation and extraction fallback are described+below. Cluster saturation and unhealthy-worker spill require explicit triggers.+Numeric fleet bridges remain separately gated. Experimental cluster threshold+routing is opt-in as described below; single-node threshold routing remains+refused.## Single-node embedding example@@ -439,7 +440,7 @@ 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 and coordinated threshold routing remain inactive.+Numerical fleet equivalence remains inactive. Threshold routing requires its separate deployment opt-in.### Observing cluster fallback@@ -451,3 +452,51 @@ set `alertRules.remoteFallbackPersistenceSeconds` to the desired thresholdthe same gateway replica. Successful local serving clears that replica'sobserved duration. See [the telemetry contract](../../telemetry/README.md#remote-fallback-observations)for bounded-label and replica semantics.+++## Experimental cluster threshold routing++Set `gateway.thresholdRouting.enabled: true` in the `sie-cluster` chart only+when opting into shared demand routing for generation or extraction. It is off+by default. The chart requires authenticated inference NATS, sie-config and+queue worker sidecars, and starts a separate ephemeral control broker that+accepts only gateway credentials. Workers retain their existing queue+connection and upstream secrets. The control broker has a gateway-only ingress+NetworkPolicy; the inference broker and its persisted work are unchanged.++A local model with an existing remote profile can use:++```yaml+routing:+ policy: threshold+ fallback_profile: remote+ wake_above: 2+ sleep_below: 0.5+ window_s: 10+ cooldown_s: 60+```++Rates count validated bare-model requests per second across all gateway+replicas. Once low demand is established, requests use the remote profile and+create no local demand or load-only work. Sustained high demand resumes local+routing: a cold local lane receives demand and load-only work while the remote+profile bridges provisioning and model loading. Once local capacity is ready,+requests stay local. Sustained low demand returns requests to remote; existing+worker 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+threshold demand. A remote-selected request still requires the current exact+worker execution contract; it cannot select a legacy worker or retry into+another backend after output has started. An unavailable remote lane returns+the ordinary remote provisioning/refusal response, without waking the local+lane or recursively bridging to itself.++A newly started, disconnected or configuration-skewed coordinator retains the+ordinary local warm-up/fallback behavior until it has fresh sustained evidence.+Windows have at least one-second resolution and a maximum of 86400 seconds.+The isolated broker is memory-backed and single-replica in the chart: a restart+rebuilds evidence conservatively. This is an experimental routing control,+without a measured throughput, cold-start or cost acceptance claim.+See the [coordinator contract](../sie_gateway/docs/threshold-routing.md).diff --git a/packages/sie_server/src/sie_server/config/routing.py b/packages/sie_server/src/sie_server/config/routing.pyindex d8d138fc1..489bc8a54 100644--- a/packages/sie_server/src/sie_server/config/routing.py+++ b/packages/sie_server/src/sie_server/config/routing.py@@ -7,6 +7,7 @@ config: the models directory, a config added at runtime, and a config snapshot.from __future__ import annotations+import osfrom pathlib import Pathfrom sie_server.adapters._generation_base import GenerationAdapter@@ -19,6 +20,7 @@ from sie_server.core.loader import expand_profile_variants, resolve_adapter_clas_HYBRID_POLICIES = frozenset({"fallback", "threshold"})_EQUIVALENCE_TASKS = ("encode", "score")+_MAX_THRESHOLD_WINDOW_S = 86400def hybrid_equivalence_refusal(config: ModelConfig) -> str | None:@@ -79,8 +81,15 @@ def validate_model_routing(if routing is None:returnif routing.policy == "threshold":- msg = f"Model '{config.sie_id}': routing policy 'threshold' is not available yet"- raise ValueError(msg)+ if os.environ.get("SIE_THRESHOLD_ROUTING_ENABLED") != "true":+ msg = f"Model '{config.sie_id}': routing policy 'threshold' is not available yet"+ raise ValueError(msg)+ if not os.environ.get("SIE_IPC_SOCKET_PATH"):+ raise ValueError("threshold routing requires a queue worker behind a threshold-enabled gateway")+ if config.tasks.encode is not None or config.tasks.score is not None:+ raise ValueError("threshold routing cannot serve encode or score until fleet equivalence is proven")+ if (routing.window_s or 0) > _MAX_THRESHOLD_WINDOW_S or (routing.cooldown_s or 0) > _MAX_THRESHOLD_WINDOW_S:+ raise ValueError("threshold windows must not exceed 86400 seconds")refusal = hybrid_equivalence_refusal(config)if refusal is not None and routing.fallback_profile is not None:# Dispatch expands live fields. A reused mutable Python config mustdiff --git a/packages/sie_server/tests/config/test_routing_config.py b/packages/sie_server/tests/config/test_routing_config.pyindex 9c64207de..b1abd811c 100644--- a/packages/sie_server/tests/config/test_routing_config.py+++ b/packages/sie_server/tests/config/test_routing_config.py@@ -433,3 +433,22 @@ async def test_authoritative_replacement_refuses_unsupported_remote_outputs_withassert registry.has_model("acme/kept")assert not registry.has_model("acme/hybrid")assert not registry.has_model("acme/hybrid:remote")+++def test_threshold_requires_flag_and_queue_worker_and_keeps_numerical_gate(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ config = ModelConfig.model_validate(hybrid(routing=THRESHOLD))+ monkeypatch.setenv("SIE_THRESHOLD_ROUTING_ENABLED", "true")+ monkeypatch.delenv("SIE_IPC_SOCKET_PATH", raising=False)+ with pytest.raises(ValueError, match="queue worker"):+ validate_model_routing(config)+ monkeypatch.setenv("SIE_IPC_SOCKET_PATH", str(tmp_path / "ipc.sock"))+ validate_model_routing(config)+ with pytest.raises(ValueError, match="fleet equivalence"):+ validate_model_routing(ModelConfig.model_validate(hybrid(tasks=ENCODE, routing=THRESHOLD)))+ with pytest.raises(ValueError, match="86400"):+ validate_model_routing(ModelConfig.model_validate(hybrid(routing={**THRESHOLD, "window_s": 86401})))+ monkeypatch.setenv("SIE_THRESHOLD_ROUTING_ENABLED", "false")+ with pytest.raises(ValueError, match="not available yet"):+ validate_model_routing(config)diff --git a/tools/ci/tests/test_helm_render.py b/tools/ci/tests/test_helm_render.pyindex 64f9192fe..ea40d4db0 100644--- a/tools/ci/tests/test_helm_render.py+++ b/tools/ci/tests/test_helm_render.py@@ -1555,7 +1555,9 @@ def bound_rules(docs: list[dict], service_account: str) -> list[dict]:def test_no_role_of_the_gateway_reaches_secrets_and_the_remote_lane_has_none(tmp_path: Path) -> None:docs = rendered_documents(tmp_path, remote_pool_values())(gateway,) = [- doc for doc in docs if doc["kind"] == "Deployment" and doc["metadata"]["name"] == GATEWAY.split("/")[0]+ doc+ for doc in docs+ if doc["kind"] == "Deployment" and doc["metadata"]["name"] == GATEWAY.split("/", maxsplit=1)[0]]gateway_account = gateway["spec"]["template"]["spec"]["serviceAccountName"]@@ -1575,7 +1577,9 @@ def test_the_remote_lane_runs_as_its_own_account_without_identity_or_hugging_faclanes = lane_pod_specs(docs)(gateway,) = [- doc for doc in docs if doc["kind"] == "Deployment" and doc["metadata"]["name"] == GATEWAY.split("/")[0]+ doc+ for doc in docs+ if doc["kind"] == "Deployment" and doc["metadata"]["name"] == GATEWAY.split("/", maxsplit=1)[0]]assert lanes[REMOTE_WORKER[1]]["serviceAccountName"] == REMOTE_SERVICE_ACCOUNTassert lanes[REMOTE_WORKER[1]]["automountServiceAccountToken"] is False@@ -2585,3 +2589,110 @@ def test_remote_fallback_persistence_alert_refuses_invalid_thresholds(tmp_path:)assert result.returncode != 0assert "alertRules.remoteFallbackPersistenceSeconds" in result.stderr+++THRESHOLD_VALUES = {+ "gateway": {"thresholdRouting": {"enabled": True}},+ "config": {"configStore": {"enabled": True}},+}+++def test_threshold_control_is_isolated_and_gateway_only(tmp_path: Path) -> None:+ result = render_template(tmp_path, THRESHOLD_VALUES, "templates/threshold-control.yaml")+ assert result.returncode == 0, result.stderr+ docs = {doc["kind"]: doc for doc in yaml.safe_load_all(result.stdout) if doc}+ assert set(docs) == {"ConfigMap", "Deployment", "Service", "NetworkPolicy"}+ config = docs["ConfigMap"]["data"]["nats.conf"]+ fixture = (ROOT / "tools/ci/fixtures/sie-threshold-nats.conf").read_text()++ def strip_comments(text: str) -> str:+ return "\n".join(line for line in text.splitlines() if not line.startswith("#")).strip()++ assert strip_comments(config) == strip_comments(fixture)+ deployment = docs["Deployment"]["spec"]+ assert deployment["replicas"] == 1+ assert deployment["strategy"]["type"] == "Recreate"+ pod = deployment["template"]["spec"]+ assert pod["automountServiceAccountToken"] is False+ (container,) = pod["containers"]+ assert container["env"] == [+ {+ "name": "SIE_NATS_AUTH_GATEWAY_PASSWORD",+ "valueFrom": {"secretKeyRef": {"name": "sie-nats-auth-gateway", "key": "password"}},+ }+ ]+ policy = docs["NetworkPolicy"]["spec"]+ assert policy["policyTypes"] == ["Ingress", "Egress"]+ assert policy["egress"] == []+ assert policy["ingress"][0]["from"][0]["podSelector"]["matchLabels"]["app.kubernetes.io/component"] == "gateway"+ assert docs["Service"]["spec"]["ports"] == [{"name": "client", "port": 4222, "targetPort": "client"}]+++ "override",+ [+ {"nats": {"auth": {"enabled": False}}},+ {"config": {"enabled": False}},+ {"config": {"configStore": {"enabled": False}}},+ {"workers": {"common": {"workerSidecar": {"enabled": False}}}},+ ],+)+def test_threshold_rejects_incomplete_queue_authority(tmp_path: Path, override: dict) -> None:+ values = {**THRESHOLD_VALUES, **override}+ result = render_template(tmp_path, values, "templates/threshold-control.yaml")+ assert result.returncode != 0+++def test_threshold_flag_is_owned_by_chart_and_propagates(tmp_path: Path) -> None:+ for template, container_name in [+ ("templates/gateway-deployment.yaml", "gateway"),+ ("templates/config-deployment.yaml", "config"),+ ]:+ result = render_template(tmp_path, THRESHOLD_VALUES, template)+ assert result.returncode == 0, result.stderr+ deployment = next(doc for doc in yaml.safe_load_all(result.stdout) if doc and doc["kind"] == "Deployment")+ container = next(c for c in deployment["spec"]["template"]["spec"]["containers"] if c["name"] == container_name)+ env = {item["name"]: item for item in container["env"]}+ assert env["SIE_THRESHOLD_ROUTING_ENABLED"]["value"] == "true"+ if container_name == "gateway":+ assert env["SIE_THRESHOLD_NATS_URL"]["value"] == "nats://sie-sie-cluster-threshold:4222"+ values = {"gateway": {"extraEnv": [{"name": "SIE_THRESHOLD_ROUTING_ENABLED", "value": "true"}]}}+ result = render_template(tmp_path, values, "templates/gateway-deployment.yaml")+ assert result.returncode != 0+++def test_threshold_flag_reaches_workers_and_refuses_shared_gateway_secret(tmp_path: Path) -> None:+ docs = worker_statefulsets(tmp_path, {**THRESHOLD_VALUES, **L4_POOL})+ assert docs+ for doc in docs:+ containers = doc["spec"]["template"]["spec"]["containers"]+ for container in containers:+ env = {item["name"]: item for item in container.get("env", [])}+ if container["name"] != "worker-sidecar":+ assert env["SIE_THRESHOLD_ROUTING_ENABLED"]["value"] == "true"+ assert "SIE_THRESHOLD_NATS_URL" not in env+ assert "SIE_NATS_AUTH_GATEWAY_PASSWORD" not in env+ values = {**THRESHOLD_VALUES, "nats": {"auth": {"existingSecrets": {"gateway": "shared", "worker": "shared"}}}}+ result = render_template(tmp_path, values, "templates/threshold-control.yaml")+ assert result.returncode != 0+ assert "distinct from config and worker" in result.stderr++[email protected]("fullname", ["a" * 90, "a" * 52 + "-" + "b" * 10])+def test_threshold_long_name_keeps_control_resources_and_gateway_url_aligned(tmp_path: Path, fullname: str) -> None:+ values = {**THRESHOLD_VALUES, "fullnameOverride": fullname}+ result = render_template(tmp_path, values, "templates/threshold-control.yaml")+ assert result.returncode == 0, result.stderr+ docs = [doc for doc in yaml.safe_load_all(result.stdout) if doc]+ names = {doc["metadata"]["name"] for doc in docs}+ assert len(names) == 1+ (name,) = names+ assert len(name) <= 63+ assert name == fullname[:53].rstrip("-") + "-threshold"+ deployment = next(doc for doc in docs if doc["kind"] == "Deployment")+ assert deployment["spec"]["template"]["spec"]["volumes"][0]["configMap"]["name"] == name+ gateway_result = render_template(tmp_path, values, "templates/gateway-deployment.yaml")+ assert gateway_result.returncode == 0, gateway_result.stderr+ gateway = next(doc for doc in yaml.safe_load_all(gateway_result.stdout) if doc and doc["kind"] == "Deployment")+ env = {item["name"]: item for item in gateway["spec"]["template"]["spec"]["containers"][0]["env"]}+ assert env["SIE_THRESHOLD_NATS_URL"]["value"] == f"nats://{name}:4222"