Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(cluster): keep a worker lane up while its model is loading (#659)

Yeonwoo Sungf73cce5b53f4
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.md
index 1dbedddc6..77b95ac36 100644
--- a/deploy/helm/sie-cluster/README.md
+++ b/deploy/helm/sie-cluster/README.md
@@ -433,6 +433,7 @@ label that KEDA cannot match.
|--------|--------|---------|
| `sie_gateway_pending_demand` | Gateway | Trigger scale from 0 |
| `sie_gateway_lane_queue_depth` | Gateway JetStream backlog reconciler | Scale up on exact durable-consumer `num_pending + num_ack_pending`, including work held by a dead/loading worker |
+| `sie_gateway_model_loads_in_progress` | Gateway worker heartbeats | Hold the lane at 1 while a fresh worker is loading a model, and emit 0 when the lane has no live workers. See #293 |
| `sie_gateway_lane_queue_snapshot_timestamp_seconds` | Gateway JetStream backlog reconciler | Prove that the exact lane queue value, including zero, came from a fresh successful broker read |
| `sie_gateway_active_lease_gpus` | Gateway pool manager | Hold distinct assigned-worker capacity for active pool leases in the exact pool/profile/bundle lane |
| `sie_gateway_pool_warm_floor` | Gateway pool manager | Enforce a configured per-lane minimum without bypassing KEDA |
diff --git a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json b/deploy/helm/sie-cluster/files/dashboards/queue-routing.json
index ae55fc962..6448f2385 100644
--- a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json
+++ b/deploy/helm/sie-cluster/files/dashboards/queue-routing.json
@@ -1192,6 +1192,11 @@
"legendFormat": "warm floor {{pool}} / {{machine_profile}} / {{bundle}}",
"refId": "D"
},
+ {
+ "expr": "max by (pool, machine_profile, bundle) (sie_gateway_model_loads_in_progress{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"})",
+ "legendFormat": "loads in progress {{pool}} / {{machine_profile}} / {{bundle}}",
+ "refId": "G"
+ },
{
"expr": "max by (producer_instance) (sie_gateway_capacity_snapshot_timestamp_seconds{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"})",
"legendFormat": "capacity snapshot {{producer_instance}}",
diff --git a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl b/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl
index 59c5902f8..eb9d88b7f 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: propagate
metrics:
metric:
- - '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)$")'
+ - '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[.]model_loads_in_progress|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
@@ -124,7 +124,7 @@ processors:
- '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)$")'
- - 'set(unit, "1") where IsMatch(name, "^(sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]config[.]messaging[.]ready|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]config[.]degraded|sie[.]worker[.]saturated|sie[.]gateway[.]pool[.]pinned_model[.]loaded)$")'
+ - 'set(unit, "1") where IsMatch(name, "^(sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]config[.]messaging[.]ready|sie[.]worker[.]batch[.]fill_ratio|sie[.]worker[.]config[.]degraded|sie[.]worker[.]saturated|sie[.]gateway[.]pool[.]pinned_model[.]loaded|sie[.]gateway[.]model_loads_in_progress)$")'
- 'set(unit, "{publish}") where name == "sie.gateway.queue.publishes"'
- 'set(unit, "{item}") where IsMatch(name, "^(sie[.]gateway[.]queue[.]publish[.]items|sie[.]worker[.]queue[.]depth|sie[.]worker[.]batch[.]size|sie[.]worker[.]queue[.]pending_at_dispatch|sie[.]worker[.]pending[.]items|sie[.]worker[.]runtime[.]batch[.]size|sie[.]worker[.]runtime[.]subgroup[.]size|sie[.]worker[.]requests|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]worker[.]work_item[.]deadline_exceeded)$")'
- 'set(unit, "{wait}") where name == "sie.gateway.queue.result_waits"'
@@ -231,7 +231,7 @@ processors:
- 'keep_keys(attributes, ["output.path", "backend", "lane", "model", "profile"]) where metric.name == "sie.worker.runtime.forward.permit.wait"'
- 'keep_keys(attributes, ["state", "backend", "lane", "model", "profile"]) where metric.name == "sie.worker.runtime.forward.concurrent"'
- 'keep_keys(attributes, ["pool", "model"]) where metric.name == "sie.gateway.pool.pinned_model.loaded"'
- - 'keep_keys(attributes, ["pool", "machine_profile", "bundle"]) where IsMatch(metric.name, "^(sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor)$")'
+ - 'keep_keys(attributes, ["pool", "machine_profile", "bundle"]) where IsMatch(metric.name, "^(sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]model_loads_in_progress)$")'
- 'keep_keys(attributes, ["pool", "machine_profile", "bundle", "reason", "scaling_action"]) where metric.name == "sie.gateway.rejected.requests"'
- 'keep_keys(attributes, ["pool", "machine_profile", "bundle", "outcome"]) where metric.name == "sie.gateway.queue.lane_admission.decisions"'
# Prometheus producer labels are explicit collector output, not copied
@@ -290,7 +290,7 @@ processors:
error_mode: propagate
metrics:
metric:
- - '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)$")'
+ - '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[.]model_loads_in_progress|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: propagate
diff --git a/deploy/helm/sie-cluster/templates/hooks/keda-ready-test.yaml b/deploy/helm/sie-cluster/templates/hooks/keda-ready-test.yaml
index d279e4276..69f456857 100644
--- a/deploy/helm/sie-cluster/templates/hooks/keda-ready-test.yaml
+++ b/deploy/helm/sie-cluster/templates/hooks/keda-ready-test.yaml
@@ -6,7 +6,7 @@
{{- range $bundleCfg := $pool.bundles -}}
{{- if dig "enabled" true $bundleCfg -}}
{{- $expectedScaledObjects = add1 $expectedScaledObjects -}}
-{{- $expectedExternalMetrics = add $expectedExternalMetrics 5 -}}
+{{- $expectedExternalMetrics = add $expectedExternalMetrics 6 -}}
{{- end -}}
{{- end -}}
{{- end -}}
@@ -18,7 +18,7 @@
{{- $probeConcurrency := 16 -}}
{{- $probeRequestTimeout := 5 -}}
{{- $probeBatches := div (add $expectedScaledObjects (sub $probeConcurrency 1)) $probeConcurrency -}}
-{{- $probeRoundBudget := mul $probeBatches (mul 5 $probeRequestTimeout) -}}
+{{- $probeRoundBudget := mul $probeBatches (mul 6 $probeRequestTimeout) -}}
{{- $probeBudget := mul $probeRoundBudget $failureThreshold -}}
{{- $timeout := add (add $validationWindow $probeBudget) 180 -}}
{{- $activeDeadline := add $timeout 60 -}}
@@ -59,7 +59,7 @@ rules:
# populate trigger health even while the HPA is disabled at zero. The
# aggregated API authorizes an exact-metric response as a namespaced list on
# its wildcard resource; strict path/catalog validation below narrows use to
- # the five chart-owned metric names.
+ # the six chart-owned worker metric names, plus the gateway trigger.
- apiGroups: ["external.metrics.k8s.io"]
resources: ["*"]
verbs: ["list"]
@@ -232,9 +232,9 @@ spec:
([.items[].spec.triggers[]] | length == $expected_metrics) and
all(.items[];
(.metadata.name | dns_label) and
- (.spec.triggers | type == "array" and length >= 1 and length <= 5) and
+ (.spec.triggers | type == "array" and length >= 1 and length <= 6) and
all(.spec.triggers | to_entries[];
- .key >= 0 and .key <= 4 and .value.type == "prometheus"
+ .key >= 0 and .key <= 5 and .value.type == "prometheus"
)
)
' "$SCALEDOBJECTS_FILE" >/dev/null; then
@@ -312,7 +312,7 @@ spec:
exit 1
fi
done < "$EXTERNAL_METRICS_FILE"
- if [ "$object_metric_index" -lt 1 ] || [ "$object_metric_index" -gt 5 ]; then
+ if [ "$object_metric_index" -lt 1 ] || [ "$object_metric_index" -gt 6 ]; then
exit 1
fi
) &
diff --git a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml
index 393ba9e61..dc4c97b7c 100644
--- a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml
+++ b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml
@@ -256,6 +256,15 @@ data:
ignoreNullValues: "false"
threshold: "1"
activationThreshold: "0"
+ - type: prometheus
+ metadata:
+ serverAddress: {{ $promAddr }}
+ # Appended last so existing HPA metric indexes stay stable. See #293.
+ metricName: sie_gateway_model_loads_in_progress_{{ $poolName }}_{{ $bundleName }}
+ query: (max(sie_gateway_model_loads_in_progress{ {{- $gatewayTarget -}}, pool="{{ $queuePool }}", machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"} and on(producer_instance,collector_generation) {{ $freshGatewayInstances }}) and on() {{ $controlReady }})
+ ignoreNullValues: "false"
+ threshold: "1"
+ activationThreshold: "0"
{{- $_ := set $manifestState "laneIndex" (add1 $laneIndex) }}
{{- end }}
{{- end }}
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index 10a3ffe0b..21d7649b3 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -600,10 +600,10 @@ Prometheus client, host an application `/metrics` route, or choose a backend.
The collector owns Prometheus exposition for OSS/KEDA and OTLP routing for
remote telemetry. The checked-in source of truth is `telemetry/contract.yaml`.
-The gateway contract contains request count/duration/admission, five lane-value
-families (pending demand, durable lane queue depth, active lease GPUs, pool warm
-floor, and scale-worthy rejected requests), a local capacity-reconciliation
-timestamp, and a same-label queue-snapshot timestamp.
+The gateway contract contains request count/duration/admission, six lane-value
+families (pending demand, durable lane queue depth, in-progress model loads,
+active lease GPUs, pool warm floor, and scale-worthy rejected requests), a local
+capacity-reconciliation timestamp, and a same-label queue-snapshot timestamp.
KEDA state refreshes independently of HTTP at least every five seconds.
The physical catalog is frozen for the bounded process lifetime; physical lane
labels are `pool`, `machine_profile`, and `bundle`. For every catalog lane, the gateway reads the
@@ -623,7 +623,11 @@ to a stable offset within the five-second cadence, preventing rollout-aligned
replicas from scanning in one burst. Helm caps metrics-enabled gateway replicas
at ten, and the live broker benchmark covers the resulting maximum 10,240
lookups per interval. Worker identity and heartbeat queue depth never enter
-this KEDA series.
+the queue-depth series. `sie.gateway.model_loads_in_progress` is 1 when any
+fresh worker in the catalog lane is loading a model, and an explicit 0
+otherwise, including a lane with no live workers. Queue depth is not an input
+(#293). A stale worker cannot pin the lane. The KEDA query uses the same
+capacity-snapshot freshness guard as the other non-queue gauges.
Prometheus target labels bind every query to one Helm release; the queue gauge
is sent to Better Stack under its canonical dotted name and naturally exports
diff --git a/packages/sie_gateway/src/discovery/nats_health.rs b/packages/sie_gateway/src/discovery/nats_health.rs
index e88ed4b22..8e40a05ab 100644
--- a/packages/sie_gateway/src/discovery/nats_health.rs
+++ b/packages/sie_gateway/src/discovery/nats_health.rs
@@ -311,6 +311,7 @@ mod tests {
bundle: "sglang".into(),
bundle_config_hash: "hash".into(),
loaded_models: vec![],
+ loading_models: Vec::new(),
models: vec![],
gpus: vec![],
queue_depth: None,
diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rs
index 9824fc424..fa177e2aa 100644
--- a/packages/sie_gateway/src/handlers/config_api.rs
+++ b/packages/sie_gateway/src/handlers/config_api.rs
@@ -864,6 +864,7 @@ mod tests {
bundle_config_hash: hash.into(),
ready: true,
loaded_models: Vec::new(),
+ loading_models: Vec::new(),
queue_depth: Some(0),
pending_cost: None,
inflight_batches: None,
diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rs
index 90af9049f..b2333d044 100644
--- a/packages/sie_gateway/src/handlers/models.rs
+++ b/packages/sie_gateway/src/handlers/models.rs
@@ -761,6 +761,7 @@ mod route_tests {
bundle_config_hash: String::new(),
ready: true,
loaded_models,
+ loading_models: Vec::new(),
queue_depth: Some(0),
pending_cost: None,
inflight_batches: None,
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index e94c3916b..158219da8 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -19731,6 +19731,7 @@ mod tests {
bundle: "default".to_string(),
bundle_config_hash: "h1".to_string(),
loaded_models: Vec::new(),
+ loading_models: Vec::new(),
models: Vec::new(),
gpus: Vec::new(),
queue_depth: None,
@@ -23969,6 +23970,7 @@ mod tests {
bundle: bundle.into(),
bundle_config_hash: "abc".into(),
loaded_models: vec![],
+ loading_models: Vec::new(),
models: vec![ModelStatus { queue_depth: 0 }],
gpus: vec![GpuStatus {
memory_used_bytes: 0,
diff --git a/packages/sie_gateway/src/observability/metrics.rs b/packages/sie_gateway/src/observability/metrics.rs
index ba5e69051..eb17035f5 100644
--- a/packages/sie_gateway/src/observability/metrics.rs
+++ b/packages/sie_gateway/src/observability/metrics.rs
@@ -37,6 +37,7 @@ pub const LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME: &str =
"sie.gateway.lane.queue.snapshot.timestamp";
pub const ACTIVE_LEASE_GPUS_METRIC_NAME: &str = "sie.gateway.active_lease.gpus";
pub const POOL_WARM_FLOOR_METRIC_NAME: &str = "sie.gateway.pool.warm_floor";
+pub const MODEL_LOADS_IN_PROGRESS_METRIC_NAME: &str = "sie.gateway.model_loads_in_progress";
pub const POOL_PINNED_MODEL_LOADED_METRIC_NAME: &str = "sie.gateway.pool.pinned_model.loaded";
pub const REJECTED_REQUESTS_METRIC_NAME: &str = "sie.gateway.rejected.requests";
pub const CAPACITY_SNAPSHOT_TIMESTAMP_METRIC_NAME: &str = "sie.gateway.capacity.snapshot.timestamp";
@@ -760,15 +761,17 @@ pub(crate) struct LaneSnapshot {
/// Gateway-owned KEDA state captured by one business reconciliation.
///
-/// The three registry families are complete snapshots. `lane_queue_depth` is
-/// intentionally a set of successful per-lane broker updates: omitted lanes
-/// retain their last value but do not receive a new lane freshness timestamp.
+/// The registry families and `model_loads_in_progress` are complete snapshots.
+/// `lane_queue_depth` is intentionally a set of successful per-lane broker
+/// updates: omitted lanes retain their last value but do not receive a new
+/// lane freshness timestamp.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct KedaCapacitySnapshot {
pub pending_demand: Vec<LaneSnapshot>,
pub lane_queue_depth: Vec<LaneSnapshot>,
pub active_lease_gpus: Vec<LaneSnapshot>,
pub pool_warm_floor: Vec<LaneSnapshot>,
+ pub model_loads_in_progress: Vec<LaneSnapshot>,
}
/// One current pinned-model readiness value for a logical pool.
@@ -861,6 +864,7 @@ struct GatewayTelemetry {
lane_queue_snapshot_timestamp: Gauge<f64>,
active_lease_gpus: Gauge<f64>,
pool_warm_floor: Gauge<f64>,
+ model_loads_in_progress: Gauge<f64>,
#[allow(dead_code)] // Retains the observable callback registration.
pool_pinned_model_loaded: ObservableGauge<u64>,
rejected_requests: Counter<u64>,
@@ -903,6 +907,7 @@ struct GatewayTelemetry {
previous_pending_lanes: Mutex<HashSet<LaneKey>>,
previous_lease_lanes: Mutex<HashSet<LaneKey>>,
previous_warm_floor_lanes: Mutex<HashSet<LaneKey>>,
+ previous_model_load_lanes: Mutex<HashSet<LaneKey>>,
pinned_model_state: Arc<Mutex<PinnedModelObservableState>>,
}
@@ -987,6 +992,13 @@ impl GatewayTelemetry {
.with_description("Configured minimum warm workers for one physical lane.")
.with_unit("{worker}")
.build(),
+ model_loads_in_progress: meter
+ .f64_gauge(MODEL_LOADS_IN_PROGRESS_METRIC_NAME)
+ .with_description(
+ "Whether a fresh worker in the physical lane is loading a model. Queue depth is not an input.",
+ )
+ .with_unit("1")
+ .build(),
pool_pinned_model_loaded: meter
.u64_observable_gauge(POOL_PINNED_MODEL_LOADED_METRIC_NAME)
.with_description(
@@ -1232,6 +1244,7 @@ impl GatewayTelemetry {
previous_pending_lanes: Mutex::new(HashSet::new()),
previous_lease_lanes: Mutex::new(HashSet::new()),
previous_warm_floor_lanes: Mutex::new(HashSet::new()),
+ previous_model_load_lanes: Mutex::new(HashSet::new()),
pinned_model_state,
}
}
@@ -1526,6 +1539,14 @@ impl GatewayTelemetry {
);
}
+ fn set_model_loads_in_progress_snapshot(&self, values: &[LaneSnapshot]) {
+ set_lane_snapshot(
+ &self.model_loads_in_progress,
+ &self.previous_model_load_lanes,
+ values,
+ );
+ }
+
fn set_pool_pinned_model_loaded_snapshot(&self, values: &[PinnedModelSnapshot]) {
let current_values: HashMap<PinnedModelKey, bool> = values
.iter()
@@ -1588,6 +1609,7 @@ trait KedaSnapshotSink {
fn record_lane_queue_timestamp(&self, values: &[LaneSnapshot], unix_time_s: f64);
fn record_active_lease_gpus(&self, values: &[LaneSnapshot]);
fn record_pool_warm_floor(&self, values: &[LaneSnapshot]);
+ fn record_model_loads_in_progress(&self, values: &[LaneSnapshot]);
fn record_timestamp(&self, unix_time_s: f64);
}
@@ -1612,6 +1634,10 @@ impl KedaSnapshotSink for GatewayTelemetry {
self.set_pool_warm_floor_snapshot(values);
}
+ fn record_model_loads_in_progress(&self, values: &[LaneSnapshot]) {
+ self.set_model_loads_in_progress_snapshot(values);
+ }
+
fn record_timestamp(&self, unix_time_s: f64) {
self.set_capacity_snapshot_timestamp(unix_time_s);
}
@@ -2332,6 +2358,7 @@ fn record_keda_capacity_snapshot_to(
target.record_lane_queue_timestamp(&snapshot.lane_queue_depth, unix_time_s);
target.record_active_lease_gpus(&snapshot.active_lease_gpus);
target.record_pool_warm_floor(&snapshot.pool_warm_floor);
+ target.record_model_loads_in_progress(&snapshot.model_loads_in_progress);
target.record_timestamp(unix_time_s);
true
}
@@ -2340,7 +2367,7 @@ fn record_keda_capacity_snapshot_to(
/// `snapshot_started_unix_time_s` before async state collection; this facade
/// records it after all state values so a slow build ages out rather than
/// refreshing stale capacity. Synchronous OTel gauge collection is not claimed
-/// to be export-atomic across the five instruments.
+/// to be export-atomic across the instruments.
pub(crate) fn record_keda_capacity_snapshot(
snapshot: &KedaCapacitySnapshot,
snapshot_started_unix_time_s: f64,
@@ -2405,6 +2432,7 @@ pub(crate) fn benchmark_keda_capacity_emit_export(
| LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME
| ACTIVE_LEASE_GPUS_METRIC_NAME
| POOL_WARM_FLOOR_METRIC_NAME
+ | MODEL_LOADS_IN_PROGRESS_METRIC_NAME
)
})
.map(|metric| match metric.data() {
@@ -3824,6 +3852,7 @@ mod tests {
lane_queue_depth: vec![lane(3.0)],
active_lease_gpus: vec![lane(1.0)],
pool_warm_floor: vec![lane(2.0)],
+ model_loads_in_progress: vec![lane(1.0)],
};
assert!(record_keda_capacity_snapshot_to(
Some(&telemetry),
@@ -3860,6 +3889,7 @@ mod tests {
LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME.to_string(),
ACTIVE_LEASE_GPUS_METRIC_NAME.to_string(),
POOL_WARM_FLOOR_METRIC_NAME.to_string(),
+ MODEL_LOADS_IN_PROGRESS_METRIC_NAME.to_string(),
REJECTED_REQUESTS_METRIC_NAME.to_string(),
CAPACITY_SNAPSHOT_TIMESTAMP_METRIC_NAME.to_string(),
])
@@ -3878,6 +3908,7 @@ mod tests {
(LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME, "s"),
(ACTIVE_LEASE_GPUS_METRIC_NAME, "{gpu}"),
(POOL_WARM_FLOOR_METRIC_NAME, "{worker}"),
+ (MODEL_LOADS_IN_PROGRESS_METRIC_NAME, "1"),
(REJECTED_REQUESTS_METRIC_NAME, "{request}"),
(CAPACITY_SNAPSHOT_TIMESTAMP_METRIC_NAME, "s"),
] {
@@ -3941,6 +3972,7 @@ mod tests {
PENDING_DEMAND_METRIC_NAME,
ACTIVE_LEASE_GPUS_METRIC_NAME,
POOL_WARM_FLOOR_METRIC_NAME,
+ MODEL_LOADS_IN_PROGRESS_METRIC_NAME,
] {
let metric = by_name[name];
let AggregatedMetrics::F64(MetricData::Gauge(gauge)) = metric.data() else {
@@ -4145,7 +4177,8 @@ mod tests {
pending_demand: lanes.clone(),
lane_queue_depth: lanes.clone(),
active_lease_gpus: lanes.clone(),
- pool_warm_floor: lanes,
+ pool_warm_floor: lanes.clone(),
+ model_loads_in_progress: lanes,
};
assert!(record_keda_capacity_snapshot_to(
@@ -4162,6 +4195,7 @@ mod tests {
LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME,
ACTIVE_LEASE_GPUS_METRIC_NAME,
POOL_WARM_FLOOR_METRIC_NAME,
+ MODEL_LOADS_IN_PROGRESS_METRIC_NAME,
] {
let metric = resource_metrics
.iter()
@@ -4312,13 +4346,17 @@ mod tests {
self.push("pool_warm_floor");
}
+ fn record_model_loads_in_progress(&self, _values: &[LaneSnapshot]) {
+ self.push("model_loads_in_progress");
+ }
+
fn record_timestamp(&self, _unix_time_s: f64) {
self.push("timestamp");
}
}
#[test]
- fn capacity_timestamp_is_recorded_after_all_four_state_families() {
+ fn capacity_timestamp_is_recorded_after_the_state_families() {
let sink = RecordingKedaSink::default();
assert!(record_keda_capacity_snapshot_to(
Some(&sink),
@@ -4336,6 +4374,7 @@ mod tests {
"lane_queue_timestamp",
"active_lease_gpus",
"pool_warm_floor",
+ "model_loads_in_progress",
"timestamp",
]
);
@@ -4445,7 +4484,8 @@ mod tests {
pending_demand: lanes.clone(),
lane_queue_depth: lanes.clone(),
active_lease_gpus: lanes.clone(),
- pool_warm_floor: lanes,
+ pool_warm_floor: lanes.clone(),
+ model_loads_in_progress: lanes,
};
let (telemetry, _exporter, provider) = metric_points();
@@ -4488,7 +4528,7 @@ mod tests {
println!(
"gateway_keda_capacity_emit lanes={} gauge_points_per_emit={} samples={SAMPLES} disabled_public_ns_per_emit={disabled_samples:?} disabled_median_ns_per_emit={disabled_median_ns:.2} enabled_instrumented_ms_per_emit={enabled_samples:?} enabled_median_ms_per_emit={enabled_median_ms:.3} snapshot_build=excluded exporter_flush=excluded allocation_measurement=not_instrumented",
crate::state::demand_tracker::MAX_CONFIGURED_PHYSICAL_LANES,
- crate::state::demand_tracker::MAX_CONFIGURED_PHYSICAL_LANES * 4,
+ crate::state::demand_tracker::MAX_CONFIGURED_PHYSICAL_LANES * 5,
);
let disabled_budget = telemetry_performance_budget("gateway_keda_disabled_ns_per_snapshot");
assert!(
diff --git a/packages/sie_gateway/src/observability/tracing.rs b/packages/sie_gateway/src/observability/tracing.rs
index 17bbd5c95..c85c34167 100644
--- a/packages/sie_gateway/src/observability/tracing.rs
+++ b/packages/sie_gateway/src/observability/tracing.rs
@@ -58,9 +58,9 @@ use tracing_subscriber::{EnvFilter, Layer};
use crate::observability::metrics::{
RequestCompletionObservation, ACTIVE_LEASE_GPUS_METRIC_NAME,
KEDA_SCALE_UP_REJECTION_REASON_CARDINALITY, LANE_QUEUE_DEPTH_METRIC_NAME,
- 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,
+ LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME, MODEL_LOADS_IN_PROGRESS_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,
};
@@ -518,7 +518,8 @@ pub(crate) fn keda_metric_cardinality_view(instrument: &Instrument) -> Option<St
| LANE_QUEUE_DEPTH_METRIC_NAME
| LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME
| ACTIVE_LEASE_GPUS_METRIC_NAME
- | POOL_WARM_FLOOR_METRIC_NAME => MAX_CONFIGURED_PHYSICAL_LANES,
+ | POOL_WARM_FLOOR_METRIC_NAME
+ | MODEL_LOADS_IN_PROGRESS_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,
diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rs
index f20679ac1..c5cebd3f5 100644
--- a/packages/sie_gateway/src/server.rs
+++ b/packages/sie_gateway/src/server.rs
@@ -19,7 +19,7 @@ use crate::state::demand_tracker::{DemandTracker, PhysicalLane, PhysicalLaneCata
use crate::state::model_registry::ModelRegistry;
use crate::state::pool_manager::{CapacityPoolSnapshot, PoolManager, DEFAULT_POOL_NAME};
use crate::state::worker_registry::WorkerRegistry;
-use crate::types::PoolState;
+use crate::types::{PoolState, WorkerState};
use tracing::warn;
/// A model served from a dedicated sandbox rather than a catalog bundle (#1841).
@@ -360,7 +360,45 @@ pub(crate) async fn keda_capacity_snapshot(
}
let pools = state.pool_manager.capacity_pools().await;
let pending_lanes = state.demand_tracker.active_lanes();
- build_keda_capacity_snapshot(catalog, &lane_backlogs, &pools, pending_lanes)
+ let workers = state.registry.workers().await;
+ let loading_workers =
+ worker_loading_reports(workers.values(), state.registry.heartbeat_timeout());
+ build_keda_capacity_snapshot(
+ catalog,
+ &lane_backlogs,
+ &pools,
+ pending_lanes,
+ &loading_workers,
+ )
+}
+
+/// One worker's contribution to `sie.gateway.model_loads_in_progress`.
+///
+/// `heartbeat_fresh` is the normal heartbeat timeout. A stale worker stays in
+/// the registry until a later eviction, but it must not keep a lane at 1.
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct WorkerLoadingReport {
+ pool: String,
+ machine_profile: String,
+ bundle: String,
+ loading: bool,
+ heartbeat_fresh: bool,
+}
+
+fn worker_loading_reports<'a>(
+ workers: impl IntoIterator<Item = &'a WorkerState>,
+ heartbeat_timeout: Duration,
+) -> Vec<WorkerLoadingReport> {
+ workers
+ .into_iter()
+ .map(|worker| WorkerLoadingReport {
+ pool: worker.pool_name.clone(),
+ machine_profile: worker.machine_profile.clone(),
+ bundle: worker.bundle.clone(),
+ loading: worker.model_load_in_progress,
+ heartbeat_fresh: worker.last_heartbeat.elapsed() <= heartbeat_timeout,
+ })
+ .collect()
}
fn build_keda_capacity_snapshot(
@@ -368,6 +406,7 @@ fn build_keda_capacity_snapshot(
lane_backlogs: &LaneBacklogSnapshot,
pools: &[CapacityPoolSnapshot],
pending_lanes: Vec<PhysicalLane>,
+ loading_workers: &[WorkerLoadingReport],
) -> Result<telemetry::KedaCapacitySnapshot, String> {
if lane_backlogs
.values()
@@ -421,6 +460,36 @@ fn build_keda_capacity_snapshot(
lane_queue_depth,
active_lease_gpus: active_lease_values(pools, catalog, &catalog_lanes),
pool_warm_floor,
+ model_loads_in_progress: model_loads_in_progress(catalog, &catalog_lanes, loading_workers),
+ })
+}
+
+/// 1 when any fresh worker in the catalog lane is loading a model, else 0.
+///
+/// Queue depth is not an input (#293). Every configured lane is present,
+/// including an explicit 0 when the lane has no live workers.
+fn model_loads_in_progress(
+ catalog: &PhysicalLaneCatalog,
+ catalog_lanes: &[PhysicalLane],
+ loading_workers: &[WorkerLoadingReport],
+) -> Vec<telemetry::LaneSnapshot> {
+ let mut loading_lanes = HashSet::new();
+ for worker in loading_workers {
+ if !worker.heartbeat_fresh || !worker.loading {
+ continue;
+ }
+ let Some(lane) = catalog.resolve(&worker.pool, &worker.machine_profile, &worker.bundle)
+ else {
+ continue;
+ };
+ loading_lanes.insert(lane);
+ }
+ complete_lane_snapshot(catalog_lanes, |lane| {
+ if loading_lanes.contains(lane) {
+ 1.0
+ } else {
+ 0.0
+ }
})
}
@@ -736,6 +805,7 @@ mod capacity_snapshot_tests {
&LaneBacklogSnapshot::default(),
&[],
Vec::new(),
+ &[],
)
.unwrap();
let expected = vec![
@@ -756,10 +826,159 @@ mod capacity_snapshot_tests {
assert_eq!(snapshot.pending_demand, expected);
assert_eq!(snapshot.active_lease_gpus, expected);
assert_eq!(snapshot.pool_warm_floor, expected);
+ assert_eq!(snapshot.model_loads_in_progress, expected);
assert!(snapshot.lane_queue_depth.is_empty());
let (_, exported_points) = telemetry::benchmark_keda_capacity_emit_export(&snapshot);
- assert_eq!(exported_points, catalog.len() * 3);
+ assert_eq!(exported_points, catalog.len() * 4);
+ }
+
+ fn loading_worker(
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ models: &[&str],
+ fresh: bool,
+ ) -> WorkerLoadingReport {
+ WorkerLoadingReport {
+ pool: pool.to_string(),
+ machine_profile: machine_profile.to_string(),
+ bundle: bundle.to_string(),
+ loading: models.iter().any(|model| !model.trim().is_empty()),
+ heartbeat_fresh: fresh,
+ }
+ }
+
+ #[test]
+ fn loading_models_hold_the_lane_at_one_when_queue_depth_is_zero() {
+ let catalog = lane_catalog(&[("default", "l4", "default"), ("shared", "h100", "sglang")]);
+ let idle = catalog.resolve("default", "l4", "default").unwrap();
+ let backlogs = LaneBacklogSnapshot::from([(idle, 0)]);
+ let snapshot = build_keda_capacity_snapshot(
+ &catalog,
+ &backlogs,
+ &[],
+ Vec::new(),
+ &[
+ loading_worker("DEFAULT", "L4", "DEFAULT", &["org/loading"], true),
+ loading_worker("shared", "h100", "sglang", &[], true),
+ loading_worker("shared", "h100", "sglang", &[" "], true),
+ ],
+ )
+ .unwrap();
+
+ assert_eq!(snapshot.lane_queue_depth[0].value, 0.0);
+ assert_eq!(
+ snapshot.model_loads_in_progress,
+ vec![
+ telemetry::LaneSnapshot {
+ pool: "default".to_string(),
+ machine_profile: "l4".to_string(),
+ bundle: "default".to_string(),
+ value: 1.0,
+ },
+ telemetry::LaneSnapshot {
+ pool: "shared".to_string(),
+ machine_profile: "h100".to_string(),
+ bundle: "sglang".to_string(),
+ value: 0.0,
+ },
+ ]
+ );
+ }
+
+ #[test]
+ fn stale_or_absent_workers_emit_explicit_zero_for_model_loads() {
+ let catalog = lane_catalog(&[("default", "l4", "default")]);
+ let expected = vec![telemetry::LaneSnapshot {
+ pool: "default".to_string(),
+ machine_profile: "l4".to_string(),
+ bundle: "default".to_string(),
+ value: 0.0,
+ }];
+ let stale = build_keda_capacity_snapshot(
+ &catalog,
+ &LaneBacklogSnapshot::default(),
+ &[],
+ Vec::new(),
+ &[loading_worker(
+ "default",
+ "l4",
+ "default",
+ &["org/loading"],
+ false,
+ )],
+ )
+ .unwrap();
+ let none = build_keda_capacity_snapshot(
+ &catalog,
+ &LaneBacklogSnapshot::default(),
+ &[],
+ Vec::new(),
+ &[],
+ )
+ .unwrap();
+ let foreign = build_keda_capacity_snapshot(
+ &catalog,
+ &LaneBacklogSnapshot::default(),
+ &[],
+ Vec::new(),
+ &[loading_worker(
+ "attacker",
+ "l4",
+ "default",
+ &["org/loading"],
+ true,
+ )],
+ )
+ .unwrap();
+
+ assert_eq!(stale.model_loads_in_progress, expected);
+ assert_eq!(none.model_loads_in_progress, expected);
+ assert_eq!(foreign.model_loads_in_progress, expected);
+ }
+
+ #[test]
+ fn heartbeat_timeout_marks_a_loading_worker_stale() {
+ let timeout = Duration::from_secs(30);
+ let mut fresh = crate::types::WorkerState {
+ url: "http://fresh".into(),
+ name: "fresh".into(),
+ health: crate::types::WorkerHealth::Healthy,
+ gpu_count: 1,
+ ready_gpu_slots: 1,
+ machine_profile: "l4".into(),
+ 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![],
+ model_load_in_progress: true,
+ queue_depth: 0,
+ pending_cost: 0,
+ inflight_batches: 0,
+ memory_used_bytes: 0,
+ memory_total_bytes: 0,
+ last_heartbeat: Instant::now(),
+ pool_name: "default".into(),
+ saturated: false,
+ unsupported_models: std::sync::Arc::from([]),
+ unsupported_overflow: false,
+ };
+ let mut stale = fresh.clone();
+ stale.url = "http://stale".into();
+ stale.queue_depth = 40;
+ stale.last_heartbeat = Instant::now()
+ .checked_sub(timeout + Duration::from_secs(1))
+ .unwrap();
+ let reports = worker_loading_reports([&fresh, &stale], timeout);
+ assert!(reports[0].heartbeat_fresh && reports[0].loading);
+ assert!(!reports[1].heartbeat_fresh);
+ fresh.model_load_in_progress = false;
+ let cleared = worker_loading_reports([&fresh], timeout);
+ assert!(!cleared[0].loading);
}
#[test]
@@ -776,7 +995,8 @@ mod capacity_snapshot_tests {
),
]);
- let snapshot = build_keda_capacity_snapshot(&catalog, &backlogs, &[], Vec::new()).unwrap();
+ let snapshot =
+ build_keda_capacity_snapshot(&catalog, &backlogs, &[], Vec::new(), &[]).unwrap();
assert_eq!(
snapshot.lane_queue_depth,
vec![
@@ -804,6 +1024,7 @@ mod capacity_snapshot_tests {
&LaneBacklogSnapshot::default(),
&[],
Vec::new(),
+ &[],
)
.unwrap();
assert!(snapshot.lane_queue_depth.is_empty());
@@ -818,6 +1039,7 @@ mod capacity_snapshot_tests {
&LaneBacklogSnapshot::default(),
&[],
vec![lane],
+ &[],
)
.unwrap();
@@ -832,7 +1054,7 @@ mod capacity_snapshot_tests {
PhysicalLane::try_new("attacker", "l4", "default").unwrap(),
99,
)]);
- assert!(build_keda_capacity_snapshot(&catalog, &foreign, &[], Vec::new()).is_err());
+ assert!(build_keda_capacity_snapshot(&catalog, &foreign, &[], Vec::new(), &[]).is_err());
}
#[test]
@@ -843,7 +1065,8 @@ mod capacity_snapshot_tests {
let partial = LaneBacklogSnapshot::from([(healthy, 4)]);
let snapshot =
- build_keda_capacity_snapshot(&catalog, &partial, &[], vec![corrupt.clone()]).unwrap();
+ build_keda_capacity_snapshot(&catalog, &partial, &[], vec![corrupt.clone()], &[])
+ .unwrap();
assert_eq!(
snapshot.lane_queue_depth,
@@ -929,6 +1152,7 @@ mod capacity_snapshot_tests {
black_box(&backlog_view),
black_box(&pool_view),
black_box(lanes.clone()),
+ black_box(&[]),
)
.unwrap();
@@ -941,6 +1165,7 @@ mod capacity_snapshot_tests {
black_box(&backlog_view),
black_box(&pool_view),
black_box(lanes.clone()),
+ black_box(&[]),
)
.unwrap();
}
@@ -950,14 +1175,15 @@ mod capacity_snapshot_tests {
assert_eq!(snapshot.lane_queue_depth.len(), LANES);
assert_eq!(snapshot.active_lease_gpus.len(), LANES);
assert_eq!(snapshot.pool_warm_floor.len(), LANES);
+ assert_eq!(snapshot.model_loads_in_progress.len(), LANES);
let mut emit_export_samples = [0.0; SAMPLES];
for sample in &mut emit_export_samples {
let (_, warmup_points) = telemetry::benchmark_keda_capacity_emit_export(&snapshot);
- assert_eq!(warmup_points, LANES * 5);
+ assert_eq!(warmup_points, LANES * 6);
let (elapsed, exported_points) =
telemetry::benchmark_keda_capacity_emit_export(&snapshot);
- assert_eq!(exported_points, LANES * 5);
+ assert_eq!(exported_points, LANES * 6);
*sample = elapsed.as_secs_f64() * 1_000.0;
}
let build_median_ms = telemetry::telemetry_benchmark_median(build_samples);
@@ -966,7 +1192,7 @@ mod capacity_snapshot_tests {
"gateway_keda_capacity_build_emit_export lanes={LANES} broker_lane_values={} logical_pools={} samples={SAMPLES} build_iterations_per_sample={BUILD_ITERATIONS} compact_clone_and_build_ms_per_snapshot={build_samples:?} compact_clone_and_build_median_ms_per_snapshot={build_median_ms:.3} emit_and_force_flush_ms={emit_export_samples:?} emit_and_force_flush_median_ms={emit_export_median_ms:.3} exported_points={} lock_wait=excluded allocation_measurement=not_instrumented",
backlogs.len(),
pools.len(),
- LANES * 5,
+ LANES * 6,
);
}
}
diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rs
index b8ef12b01..04eb73d18 100644
--- a/packages/sie_gateway/src/state/worker_registry.rs
+++ b/packages/sie_gateway/src/state/worker_registry.rs
@@ -349,6 +349,10 @@ impl WorkerRegistry {
self.workers.read().await.clone()
}
+ pub fn heartbeat_timeout(&self) -> Duration {
+ self.heartbeat_timeout
+ }
+
pub async fn healthy_workers(&self) -> Vec<WorkerState> {
self.snapshot.load().all_healthy.clone()
}
@@ -374,6 +378,7 @@ impl WorkerRegistry {
supports_numerical_admission_subject_v1: false,
numerical_process_inventory: None,
models: Vec::new(),
+ model_load_in_progress: false,
queue_depth: 0,
pending_cost: 0,
inflight_batches: 0,
@@ -407,6 +412,8 @@ impl WorkerRegistry {
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;
+ // Keep a flag, not the reported ids. The list is unbounded.
+ let model_load_in_progress = msg.model_load_in_progress();
// Replace on every heartbeat: legacy or invalid observations clear
// the previous process inventory rather than retaining stale IDs.
w.numerical_process_inventory = msg
@@ -433,6 +440,7 @@ impl WorkerRegistry {
w.machine_profile = msg.machine_profile.clone();
w.pool_name = msg.pool_name.clone();
w.models = msg.loaded_models.clone();
+ w.model_load_in_progress = model_load_in_progress;
// Aggregate queue depth from models (fallback to compact top-level field)
w.queue_depth = if !msg.models.is_empty() {
@@ -1371,6 +1379,7 @@ mod tests {
bundle: "default".into(),
bundle_config_hash: "abc123".into(),
loaded_models: vec!["BAAI/bge-m3".into()],
+ loading_models: Vec::new(),
models: vec![ModelStatus { queue_depth: 2 }],
gpus: vec![GpuStatus {
memory_used_bytes: 1000,
@@ -1392,6 +1401,20 @@ mod tests {
WorkerRegistry::new(Duration::from_secs(30), None)
}
+ #[tokio::test]
+ async fn loading_models_collapse_to_a_per_worker_flag() {
+ let reg = registry();
+ let mut loading = make_msg(true);
+ loading.loading_models = vec!["org/loading".into(), " ".into(), "org/other".into()];
+ reg.update_worker("http://w1", loading).await;
+ assert!(reg.workers().await["http://w1"].model_load_in_progress);
+
+ let mut cleared = make_msg(true);
+ cleared.loading_models.clear();
+ reg.update_worker("http://w1", cleared).await;
+ assert!(!reg.workers().await["http://w1"].model_load_in_progress);
+ }
+
#[tokio::test]
async fn numerical_inventory_includes_saturated_workers_and_replaces_processes() {
let reg = registry();
@@ -2350,6 +2373,7 @@ mod tests {
bundle: "default".into(),
bundle_config_hash: String::new(),
loaded_models: vec![],
+ loading_models: Vec::new(),
models: vec![], // empty — should use compact fallback
gpus: vec![], // empty — should use compact fallback
queue_depth: Some(7),
@@ -2390,6 +2414,7 @@ mod tests {
bundle: "default".into(),
bundle_config_hash: String::new(),
loaded_models: vec![],
+ loading_models: Vec::new(),
models: vec![],
gpus: vec![],
queue_depth: None,
@@ -3068,6 +3093,7 @@ mod tests {
bundle: "default".into(),
bundle_config_hash: String::new(),
loaded_models: models.iter().map(|s| (*s).into()).collect(),
+ loading_models: Vec::new(),
models: vec![],
gpus: vec![],
queue_depth: None,
diff --git a/packages/sie_gateway/src/types/worker.rs b/packages/sie_gateway/src/types/worker.rs
index ceb9cd397..5cf9c34d5 100644
--- a/packages/sie_gateway/src/types/worker.rs
+++ b/packages/sie_gateway/src/types/worker.rs
@@ -41,6 +41,9 @@ pub struct WorkerState {
/// Diagnostic observations only; never sufficient for numerical admission.
pub numerical_process_inventory: Option<Arc<NumericalProcessInventory>>,
pub models: Vec<String>,
+ /// True when the latest heartbeat listed a model still loading. The wire
+ /// field stays a list; the registry keeps only this flag.
+ pub model_load_in_progress: bool,
pub queue_depth: i32,
pub pending_cost: i64,
pub inflight_batches: i32,
@@ -229,6 +232,10 @@ pub struct WorkerStatusMessage {
pub supports_numerical_admission_subject_v1: bool,
#[serde(default)]
pub loaded_models: Vec<String>,
+ /// In-progress model loads. Absent on workers that predate the field,
+ /// which deserializes to empty and is not a load in progress.
+ #[serde(default)]
+ pub loading_models: Vec<String>,
#[serde(default)]
pub models: Vec<ModelStatus>,
#[serde(default)]
@@ -271,6 +278,16 @@ pub struct WorkerStatusMessage {
pub numerical_process_inventory: Option<NumericalProcessInventory>,
}
+impl WorkerStatusMessage {
+ /// Whether the heartbeat names a model that is still loading.
+ #[must_use]
+ pub fn model_load_in_progress(&self) -> bool {
+ self.loading_models
+ .iter()
+ .any(|model| !model.trim().is_empty())
+ }
+}
+
/// Wire budget shared with the sidecar publisher. Never truncate a fleet.
pub const MAX_NUMERICAL_INVENTORY_BYTES: usize = 64 * 1024;
pub const MAX_NUMERICAL_CHILDREN: usize = 256;
@@ -763,6 +780,7 @@ mod tests {
supports_numerical_admission_subject_v1: false,
numerical_process_inventory: None,
models: vec![],
+ model_load_in_progress: false,
queue_depth: 0,
pending_cost: 0,
inflight_batches: 0,
@@ -833,6 +851,10 @@ mod tests {
serde_json::json!(msg.loaded_models),
example["loaded_models"]
);
+ assert_eq!(
+ serde_json::json!(msg.loading_models),
+ example["loading_models"]
+ );
assert_eq!(
msg.queue_depth,
example["queue_depth"].as_i64().map(|v| v as i32)
@@ -934,6 +956,8 @@ mod tests {
assert_eq!(msg.total_gpu_slots, None);
assert_eq!(msg.ready_gpu_slots, None);
assert!(msg.loaded_models.is_empty());
+ assert!(msg.loading_models.is_empty());
+ assert!(!msg.model_load_in_progress());
assert!(msg.models.is_empty());
assert!(msg.gpus.is_empty());
assert_eq!(msg.pending_cost, None);
@@ -941,6 +965,19 @@ mod tests {
assert!(!msg.terminated);
}
+ #[test]
+ fn loading_models_default_false_and_ignore_blank_names() {
+ let omitted: WorkerStatusMessage = serde_json::from_str("{}").unwrap();
+ assert!(omitted.loading_models.is_empty());
+ assert!(!omitted.model_load_in_progress());
+ let blank: WorkerStatusMessage =
+ serde_json::from_str(r#"{"loading_models":[""," "]}"#).unwrap();
+ assert!(!blank.model_load_in_progress());
+ let loading: WorkerStatusMessage =
+ serde_json::from_str(r#"{"loading_models":["org/loading"]}"#).unwrap();
+ assert!(loading.model_load_in_progress());
+ }
+
#[test]
fn test_worker_status_message_full() {
let json = r#"{
diff --git a/packages/sie_server/src/sie_server/_ipc_test_harness.py b/packages/sie_server/src/sie_server/_ipc_test_harness.py
index 4cb46533b..019c5946b 100644
--- a/packages/sie_server/src/sie_server/_ipc_test_harness.py
+++ b/packages/sie_server/src/sie_server/_ipc_test_harness.py
@@ -145,6 +145,9 @@ class _StubExecutor:
def loaded_model_names(self) -> list[str]:
return []
+ def loading_model_names(self) -> list[str]:
+ return []
+
async def set_pinned_models(self, req: SetPinnedModelsRequest) -> SetPinnedModelsResponse:
self._pinned_models = frozenset(model.strip() for model in req.models if model.strip())
return SetPinnedModelsResponse(applied=True, pinned_count=len(self._pinned_models))
diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.py
index 249c7eb8c..adb0825a9 100644
--- a/packages/sie_server/src/sie_server/core/registry.py
+++ b/packages/sie_server/src/sie_server/core/registry.py
@@ -671,6 +671,11 @@ class ModelRegistry:
"""Return list of currently loaded model names."""
return list(self._loaded.keys())
+ @property
+ def loading_model_names(self) -> list[str]:
+ """Return model ids whose load is still in ``_loading``."""
+ return list(self._loading)
+
@property
def loaded_model_memory_bytes(self) -> dict[str, int]:
"""Snapshot resident model memory for post-snapshot metric replay."""
diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.py
index ac80ff28f..b1743f782 100644
--- a/packages/sie_server/src/sie_server/ipc_server.py
+++ b/packages/sie_server/src/sie_server/ipc_server.py
@@ -688,12 +688,18 @@ class IpcServer:
loaded_models = self._executor.loaded_model_names()
except Exception: # noqa: BLE001
logger.debug("Could not compute loaded_models for ping", exc_info=True)
+ loading_models: list[str] = []
+ try:
+ loading_models = self._executor.loading_model_names()
+ except Exception: # noqa: BLE001
+ logger.debug("Could not compute loading_models for ping", exc_info=True)
return PingResponse(
timestamp_ms=req.timestamp_ms,
worker_id=self._worker_id,
ready=ready,
bundle_config_hash=bundle_config_hash,
loaded_models=loaded_models,
+ loading_models=loading_models,
)
async def _handle_ensure_ready(self, req: EnsureModelReadyRequest) -> EnsureModelReadyResponse:
diff --git a/packages/sie_server/src/sie_server/ipc_types.py b/packages/sie_server/src/sie_server/ipc_types.py
index a395551c2..0b9d93a93 100644
--- a/packages/sie_server/src/sie_server/ipc_types.py
+++ b/packages/sie_server/src/sie_server/ipc_types.py
@@ -90,6 +90,10 @@ class PingResponse(msgspec.Struct):
ready: bool = False
bundle_config_hash: str = ""
loaded_models: list[str] = msgspec.field(default_factory=list)
+ # In-progress registry loads. Defaulted so an older peer that omits the
+ # field still decodes; Ready, Failed, and Cancelled clear it because the
+ # registry drops the id from ``_loading`` in ``finally``.
+ loading_models: list[str] = msgspec.field(default_factory=list)
# -----------------------------------------------------------------------------
diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.py
index f6901931c..10745f203 100644
--- a/packages/sie_server/src/sie_server/queue_executor.py
+++ b/packages/sie_server/src/sie_server/queue_executor.py
@@ -632,6 +632,10 @@ class QueueExecutor:
"""Return sorted currently loaded model ids for sidecar health heartbeats."""
return sorted(self._registry.loaded_model_names)
+ def loading_model_names(self) -> list[str]:
+ """Return sorted model ids currently in ``_loading`` for health heartbeats."""
+ return sorted(self._registry.loading_model_names)
+
def invalidate_model_descriptor(self, model_id: str) -> None:
"""Drop the cached descriptor for ``model_id``.
diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.py
index 78f7ee8a9..cb65e7003 100644
--- a/packages/sie_server/tests/test_ipc_server.py
+++ b/packages/sie_server/tests/test_ipc_server.py
@@ -613,6 +613,7 @@ def _make_executor() -> tuple[QueueExecutor, MagicMock]:
reg.model_names = ["test/model"]
reg.device = "cpu"
reg.loaded_model_names = ["test/model"]
+ reg.loading_model_names = []
reg.is_loaded.return_value = True
reg.is_loading.return_value = False
reg._config_version = 0
@@ -972,6 +973,7 @@ class TestFraming:
assert resp["body"]["ready"] is False
assert resp["body"]["bundle_config_hash"] == ""
assert resp["body"]["loaded_models"] == ["test/model"]
+ assert resp["body"]["loading_models"] == []
assert srv.is_heartbeat_fresh()
finally:
await client.close()
@@ -1046,6 +1048,24 @@ class TestFraming:
finally:
await client.close()
+ @pytest.mark.asyncio
+ async def test_ping_reports_models_in_loading_and_omits_them_after_clear(self) -> None:
+ registry = ModelRegistry(enable_hot_reload=False)
+ registry._loading.add("org/loading-model")
+ executor = QueueExecutor(registry)
+ sock = _short_sock_path()
+ async with IpcServer(sock, executor, worker_id="w"):
+ client = await _Client.connect(sock)
+ try:
+ loading = await client.rpc("Ping", {"timestamp_ms": 1.0}, request_id="load")
+ assert loading["ok"] is True
+ assert loading["body"]["loading_models"] == ["org/loading-model"]
+ registry._loading.discard("org/loading-model")
+ cleared = await client.rpc("Ping", {"timestamp_ms": 2.0}, request_id="clear")
+ assert cleared["body"]["loading_models"] == []
+ finally:
+ await client.close()
+
@pytest.mark.asyncio
async def test_multiple_requests_on_one_connection(self, server_and_path) -> None:
_srv, sock = server_and_path
diff --git a/packages/sie_server_sidecar/src/config_subscriber.rs b/packages/sie_server_sidecar/src/config_subscriber.rs
index e564bf3a4..f4619c429 100644
--- a/packages/sie_server_sidecar/src/config_subscriber.rs
+++ b/packages/sie_server_sidecar/src/config_subscriber.rs
@@ -49,6 +49,7 @@ pub struct ConfigApplyState {
/// cannot serve. Committed together with the hash.
unsupported_models: SharedUnsupportedModels,
loaded_models: SharedLoadedModels,
+ loading_models: SharedLoadedModels,
/// Config mutation is exclusive while inference takes a shared guard.
/// This binds each execution to one stable backend registry revision.
execution_barrier: AsyncRwLock<()>,
@@ -61,6 +62,7 @@ impl ConfigApplyState {
bundle_config_hash: Arc::new(RwLock::new(initial_bundle_config_hash)),
unsupported_models: Arc::new(RwLock::new(Vec::new())),
loaded_models: Arc::new(RwLock::new(Vec::new())),
+ loading_models: Arc::new(RwLock::new(Vec::new())),
execution_barrier: AsyncRwLock::new(()),
}
}
@@ -77,6 +79,10 @@ impl ConfigApplyState {
Arc::clone(&self.loaded_models)
}
+ pub fn loading_models(&self) -> SharedLoadedModels {
+ Arc::clone(&self.loading_models)
+ }
+
pub fn unsupported_models(&self) -> SharedUnsupportedModels {
Arc::clone(&self.unsupported_models)
}
@@ -219,6 +225,30 @@ impl ConfigApplyState {
guard.sort();
}
+ /// Replace the in-progress load set. Returns whether the published list
+ /// changed so the health heartbeat can go out before the next interval.
+ pub fn set_loading_models<I>(&self, models: I) -> bool
+ where
+ I: IntoIterator<Item = String>,
+ {
+ let mut deduped: Vec<String> = models
+ .into_iter()
+ .map(|model| model.trim().to_string())
+ .filter(|model| !model.is_empty())
+ .collect();
+ deduped.sort();
+ deduped.dedup();
+ let mut guard = self
+ .loading_models
+ .write()
+ .expect("loading models lock poisoned");
+ if *guard == deduped {
+ return false;
+ }
+ *guard = deduped;
+ true
+ }
+
fn mark_applied(
&self,
epoch: u64,
@@ -1241,6 +1271,24 @@ mod tests {
assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "");
}
+ #[test]
+ fn set_loading_models_reports_change_and_normalizes() {
+ let state = ConfigApplyState::new("initial".into());
+ assert!(state.set_loading_models(vec![
+ "model/b".into(),
+ " model/a ".into(),
+ "".into(),
+ "model/b".into(),
+ ]));
+ assert_eq!(
+ state.loading_models().read().unwrap().as_slice(),
+ ["model/a".to_string(), "model/b".to_string()]
+ );
+ assert!(!state.set_loading_models(vec!["model/b".into(), "model/a".into()]));
+ assert!(state.set_loading_models(Vec::new()));
+ assert!(state.loading_models().read().unwrap().is_empty());
+ }
+
#[test]
fn set_loaded_models_are_trimmed_deduped_and_sorted() {
let state = ConfigApplyState::new("initial".into());
diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rs
index ac8e06d66..7d3926fee 100644
--- a/packages/sie_server_sidecar/src/health_publisher.rs
+++ b/packages/sie_server_sidecar/src/health_publisher.rs
@@ -38,6 +38,13 @@
//! signal. Backends that need explicit residency, such as Candle, must only
//! publish models here after their readiness handshake has made them serveable.
//!
+//! `loading_models` is the engine's in-progress load set. It rides this same
+//! heartbeat, and the publisher sends the payload immediately when that set
+//! changes. A failed IPC ping keeps the previous set until the last successful
+//! ping is older than the gateway heartbeat timeout; the sidecar then clears
+//! it. Heartbeats continue either way, so a wedged engine must not hold the
+//! lane until liveness restarts the container.
+//!
//! [`WorkerStatusMessage`]: https://github.com/superlinked/sie/blob/main/packages/sie_gateway/src/types/worker.rs
//! [`resolve_queue_route`]: https://github.com/superlinked/sie/blob/main/packages/sie_gateway/src/state/worker_registry.rs
@@ -49,6 +56,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use async_nats::Client;
use serde::Serialize;
+use tokio::sync::Notify;
use tokio::task::JoinHandle;
use tokio::time::interval;
use tracing::{debug, info, warn};
@@ -205,6 +213,11 @@ pub struct HealthPublisherConfig {
/// Models the colocated backend reports as loaded. Updated by the IPC
/// heartbeat, not by config apply.
pub loaded_models: SharedLoadedModels,
+ /// Models the backend still has in `_loading`. Same update path as
+ /// `loaded_models`, plus an immediate republish when the set changes.
+ pub loading_models: SharedLoadedModels,
+ /// Wakes [`spawn`] to publish the current payload before `interval` elapses.
+ pub publish_now: Arc<Notify>,
/// Independently polled process diagnostics; never grants routing authority.
pub numerical_process_inventory: SharedNumericalInventory,
/// Positive only when every backend child supports the method fence.
@@ -257,6 +270,7 @@ struct WorkerStatusPayload<'a> {
bundle: &'a str,
bundle_config_hash: &'a str,
loaded_models: &'a [String],
+ loading_models: &'a [String],
queue_depth: i32,
pending_cost: i64,
inflight_batches: i32,
@@ -287,6 +301,17 @@ fn encode_payload(
Some(guard) => guard.as_slice(),
None => &[],
};
+ let loading_models_guard = match config.loading_models.read() {
+ Ok(guard) => Some(guard),
+ Err(_) => {
+ warn!("loading_models lock poisoned; publishing an empty in-progress load set");
+ None
+ }
+ };
+ let loading_models = match &loading_models_guard {
+ Some(guard) => guard.as_slice(),
+ None => &[],
+ };
// Read under the hash guard taken above: the config subscriber writes the
// hash and this list under the same order, so the pair is consistent.
let unsupported_models = config
@@ -360,6 +385,7 @@ fn encode_payload(
bundle: &config.bundle,
bundle_config_hash: hash.as_str(),
loaded_models,
+ loading_models,
queue_depth,
pending_cost,
inflight_batches,
@@ -426,10 +452,73 @@ pub async fn publish_tombstone(
Ok(())
}
+async fn publish_heartbeat(
+ nats: &Client,
+ config: &HealthPublisherConfig,
+ readiness: &Readiness,
+ subject: &str,
+ consecutive_failures: &mut u64,
+) {
+ let snap = readiness.snapshot();
+ let ready = snap.is_ready();
+ let bytes = match encode_payload(config, ready, false) {
+ Ok(b) => b,
+ Err(e) => {
+ warn!(
+ error = %e,
+ "nats-health: serde_json encode failed (unexpected for static shape)"
+ );
+ return;
+ }
+ };
+ match nats.publish(subject.to_string(), bytes.into()).await {
+ Ok(_) => {
+ if *consecutive_failures > 0 {
+ info!(
+ consecutive_failures,
+ subject = %subject,
+ "nats-health: publish recovered"
+ );
+ }
+ *consecutive_failures = 0;
+ debug!(subject = %subject, ready, "nats-health: heartbeat published");
+ }
+ Err(e) => {
+ *consecutive_failures = consecutive_failures.saturating_add(1);
+ // Same warn cadence as `spawn_heartbeat`:
+ // first failure, then 5 / 30 / every 120
+ // so a sustained NATS outage doesn't
+ // drown the log file.
+ if *consecutive_failures == 1
+ || *consecutive_failures == 5
+ || *consecutive_failures == 30
+ || consecutive_failures.is_multiple_of(120)
+ {
+ warn!(
+ consecutive_failures,
+ subject = %subject,
+ error = %e,
+ "nats-health: publish failed"
+ );
+ } else {
+ debug!(
+ consecutive_failures,
+ subject = %subject,
+ error = %e,
+ "nats-health: publish still failing"
+ );
+ }
+ }
+ }
+}
+
/// Spawn the heartbeat-publisher loop. The returned [`JoinHandle`]
/// is owned by `run()` so shutdown can `.abort()` it after the
/// pull loop exits — same lifecycle as `crate::spawn_heartbeat`.
///
+/// `config.publish_now` republishes the same payload as soon as the
+/// in-progress load set changes. That is not a second broker subject.
+///
/// Failure modes (non-fatal):
///
/// * NATS publish errors — logged, counter bumped via WARN every
@@ -461,6 +550,7 @@ pub fn spawn(
let mut consecutive_failures: u64 = 0;
loop {
let wait = shutdown.wait();
+ let publish_now = config.publish_now.notified();
tokio::select! {
biased;
_ = wait => {
@@ -475,57 +565,10 @@ pub fn spawn(
return;
}
_ = tick.tick() => {
- let snap = readiness.snapshot();
- let ready = snap.is_ready();
- let bytes = match encode_payload(&config, ready, false) {
- Ok(b) => b,
- Err(e) => {
- warn!(
- error = %e,
- "nats-health: serde_json encode failed (unexpected for static shape)"
- );
- continue;
- }
- };
- match nats.publish(subject.clone(), bytes.into()).await {
- Ok(_) => {
- if consecutive_failures > 0 {
- info!(
- consecutive_failures,
- subject = %subject,
- "nats-health: publish recovered"
- );
- }
- consecutive_failures = 0;
- debug!(subject = %subject, ready, "nats-health: heartbeat published");
- }
- Err(e) => {
- consecutive_failures = consecutive_failures.saturating_add(1);
- // Same warn cadence as `spawn_heartbeat`:
- // first failure, then 5 / 30 / every 120
- // so a sustained NATS outage doesn't
- // drown the log file.
- if consecutive_failures == 1
- || consecutive_failures == 5
- || consecutive_failures == 30
- || consecutive_failures.is_multiple_of(120)
- {
- warn!(
- consecutive_failures,
- subject = %subject,
- error = %e,
- "nats-health: publish failed"
- );
- } else {
- debug!(
- consecutive_failures,
- subject = %subject,
- error = %e,
- "nats-health: publish still failing"
- );
- }
- }
- }
+ publish_heartbeat(&nats, &config, &readiness, &subject, &mut consecutive_failures).await;
+ }
+ _ = publish_now => {
+ publish_heartbeat(&nats, &config, &readiness, &subject, &mut consecutive_failures).await;
}
}
}
@@ -552,6 +595,8 @@ mod tests {
bundle_config_hash: Arc::new(RwLock::new("hash-abc".into())),
unsupported_models: Arc::new(RwLock::new(Vec::new())),
loaded_models: Arc::new(RwLock::new(Vec::new())),
+ loading_models: Arc::new(RwLock::new(Vec::new())),
+ publish_now: Arc::new(Notify::new()),
numerical_process_inventory: Arc::new(RwLock::new(None)),
execution_authority_v1: Arc::new(AtomicBool::new(false)),
numerical_admission_v1: Arc::new(AtomicBool::new(false)),
@@ -802,6 +847,7 @@ mod tests {
inflight_batches: 0,
saturated: false,
loaded_models: &[],
+ loading_models: &[],
unsupported_models: &[],
numerical_process_inventory: None,
};
@@ -852,6 +898,7 @@ mod tests {
inflight_batches: 0,
saturated: false,
loaded_models: &[],
+ loading_models: &[],
unsupported_models: &[],
numerical_process_inventory: None,
};
@@ -873,6 +920,20 @@ mod tests {
json["loaded_models"],
serde_json::json!(["model/a", "model/b"])
);
+ assert_eq!(json["loading_models"], serde_json::json!([]));
+ }
+
+ #[test]
+ fn payload_reads_updated_loading_models() {
+ let c = cfg();
+ {
+ let mut models = c.loading_models.write().unwrap();
+ *models = vec!["org/loading".into()];
+ }
+ let json: serde_json::Value =
+ serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();
+ assert_eq!(json["loading_models"], serde_json::json!(["org/loading"]));
+ assert_eq!(json["loaded_models"], serde_json::json!([]));
}
#[test]
diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rs
index 5c1c939f5..7078e265d 100644
--- a/packages/sie_server_sidecar/src/lib.rs
+++ b/packages/sie_server_sidecar/src/lib.rs
@@ -47,7 +47,7 @@ use std::time::{Duration, Instant};
use anyhow::Context;
use futures_util::StreamExt;
-use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};
+use tokio::sync::{Mutex, Notify, OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinHandle;
use tokio::time::{interval, sleep, timeout};
use tracing::{debug, info, warn};
@@ -456,6 +456,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
let config_apply_state = Arc::new(ConfigApplyState::new(config.bundle_config_hash.clone()));
let loaded_models = config_apply_state.loaded_models();
+ let health_publish_now = Arc::new(Notify::new());
let batch_cancel_state = BatchCancelState::default();
let request_cancel_state = RequestCancelState::new(work_cancel_tombstone_ttl());
@@ -536,6 +537,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
Arc::clone(&readiness),
Arc::clone(&config_apply_state),
Arc::clone(&loaded_models),
+ Arc::clone(&health_publish_now),
shutdown.clone(),
);
@@ -570,6 +572,8 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
bundle_config_hash: config_apply_state.bundle_config_hash(),
unsupported_models: config_apply_state.unsupported_models(),
loaded_models: Arc::clone(&loaded_models),
+ loading_models: config_apply_state.loading_models(),
+ publish_now: Arc::clone(&health_publish_now),
numerical_process_inventory,
execution_authority_v1: worker_pool.execution_authority_v1(),
numerical_admission_v1: worker_pool.numerical_admission_v1(),
@@ -849,6 +853,7 @@ pub async fn run_local(config: WorkerConfig) -> anyhow::Result<()> {
));
let config_apply_state = Arc::new(ConfigApplyState::new(config.bundle_config_hash.clone()));
let loaded_models = config_apply_state.loaded_models();
+ let health_publish_now = Arc::new(Notify::new());
let latency_tracker = Arc::new(Mutex::new(LatencyTracker::new(200, 10)));
let dispatcher = Arc::new(Dispatcher::new(
@@ -879,6 +884,7 @@ pub async fn run_local(config: WorkerConfig) -> anyhow::Result<()> {
Arc::clone(&readiness),
Arc::clone(&config_apply_state),
Arc::clone(&loaded_models),
+ health_publish_now,
shutdown.clone(),
);
@@ -1508,11 +1514,164 @@ fn request_id_from_cancel_subject(subject: &str) -> Option<String> {
}
}
+/// Gateway `WorkerRegistry` heartbeat timeout (`packages/sie_gateway/src/main.rs`).
+/// Health publication continues while IPC pings fail, so a child's loading list
+/// older than this is cleared instead of holding the lane until liveness restarts it.
+const GATEWAY_HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Published in-progress loads after one IPC ping round.
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum LoadingSetUpdate {
+ Replace(Vec<String>),
+ Keep,
+}
+
+/// Last loading list from one adapter child, and when that child last reported it.
+#[derive(Clone, Debug)]
+struct ChildLoadingMemory {
+ models: Vec<String>,
+ reported_at: Instant,
+}
+
+/// Last successful loading report from one adapter child, aged at decision time.
+/// An age equal to the heartbeat timeout is still fresh; only an older report expires.
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct ChildLoadingSnapshot {
+ models: Vec<String>,
+ age: Duration,
+}
+
+/// One child's ping in this round.
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum ChildPingRound {
+ /// The child responded. An empty list clears only this child.
+ Reported(Vec<String>),
+ /// The ping failed. `None` means this child has never reported.
+ Failed(Option<ChildLoadingSnapshot>),
+}
+
+fn loading_report_expired(age: Duration, heartbeat_timeout: Duration) -> bool {
+ age > heartbeat_timeout
+}
+
+/// Models this child still contributes. A report replaces only that child's
+/// list, including when the list is empty. A failed ping contributes the stored
+/// list until that child's own report expires.
+fn retained_loading_models(
+ round: &ChildPingRound,
+ heartbeat_timeout: Duration,
+) -> Option<&[String]> {
+ match round {
+ ChildPingRound::Reported(models) => Some(models.as_slice()),
+ ChildPingRound::Failed(Some(snapshot))
+ if !loading_report_expired(snapshot.age, heartbeat_timeout) =>
+ {
+ Some(snapshot.models.as_slice())
+ }
+ ChildPingRound::Failed(_) => None,
+ }
+}
+
+/// Merge per-child loading reports.
+///
+/// Another child's success does not clear a child whose ping failed. A round
+/// where every ping fails keeps each unexpired list (`Keep` when nothing
+/// expired). A stored report older than `heartbeat_timeout` is dropped on its
+/// own clock, including when some other child answered.
+fn loading_set_after_ping_round(
+ children: &[ChildPingRound],
+ heartbeat_timeout: Duration,
+) -> LoadingSetUpdate {
+ let every_ping_failed = children
+ .iter()
+ .all(|child| matches!(child, ChildPingRound::Failed(_)));
+ let any_expired = children.iter().any(|child| {
+ matches!(
+ child,
+ ChildPingRound::Failed(Some(snapshot))
+ if loading_report_expired(snapshot.age, heartbeat_timeout)
+ )
+ });
+ if every_ping_failed && !any_expired {
+ return LoadingSetUpdate::Keep;
+ }
+ let mut merged = Vec::new();
+ for child in children {
+ if let Some(models) = retained_loading_models(child, heartbeat_timeout) {
+ merged.extend(models.iter().cloned());
+ }
+ }
+ LoadingSetUpdate::Replace(merged)
+}
+
+fn store_child_loading_report(
+ memory: &mut Option<ChildLoadingMemory>,
+ round: &ChildPingRound,
+ now: Instant,
+ heartbeat_timeout: Duration,
+) {
+ match round {
+ ChildPingRound::Reported(models) => {
+ *memory = Some(ChildLoadingMemory {
+ models: models.clone(),
+ reported_at: now,
+ });
+ }
+ ChildPingRound::Failed(_) => {
+ if retained_loading_models(round, heartbeat_timeout).is_none() {
+ *memory = None;
+ }
+ }
+ }
+}
+
+/// Record this round's per-child reports and return the set to publish.
+/// A missing ping result is a failure for that child and keeps its stored list
+/// until that list's own age exceeds `heartbeat_timeout`.
+fn apply_loading_ping_round<E>(
+ child_count: usize,
+ ping_results: &[(usize, Result<crate::ipc_types::PingResponse, E>)],
+ memory: &mut Vec<Option<ChildLoadingMemory>>,
+ now: Instant,
+ heartbeat_timeout: Duration,
+) -> LoadingSetUpdate {
+ if memory.len() < child_count {
+ memory.resize_with(child_count, || None);
+ }
+ let mut reported: Vec<Option<Vec<String>>> = vec![None; child_count];
+ for (index, result) in ping_results {
+ if let Some(slot) = reported.get_mut(*index) {
+ *slot = result
+ .as_ref()
+ .ok()
+ .map(|response| response.loading_models.clone());
+ }
+ }
+ let mut rounds = Vec::with_capacity(child_count);
+ for (index, reported_models) in reported.into_iter().enumerate() {
+ rounds.push(match reported_models {
+ Some(models) => ChildPingRound::Reported(models),
+ None => {
+ ChildPingRound::Failed(memory[index].as_ref().map(|stored| ChildLoadingSnapshot {
+ models: stored.models.clone(),
+ age: now.saturating_duration_since(stored.reported_at),
+ }))
+ }
+ });
+ }
+ let update = loading_set_after_ping_round(&rounds, heartbeat_timeout);
+ for (index, round) in rounds.iter().enumerate() {
+ store_child_loading_report(&mut memory[index], round, now, heartbeat_timeout);
+ }
+ update
+}
+
/// Ping every adapter IPC server on a ticker. A failure is logged but
/// non-fatal — the consumer loop will surface real problems via
/// EnsureModelReady / Process* errors.
///
/// Each successful ready ping refreshes the [`Readiness`] heartbeat timestamp.
+#[allow(clippy::too_many_arguments)] // each arg is a distinct dependency
fn spawn_heartbeat(
worker_pool: Arc<AdapterWorkerPool>,
runtime_state: Arc<RuntimeState>,
@@ -1520,6 +1679,7 @@ fn spawn_heartbeat(
readiness: Arc<Readiness>,
config_apply_state: Arc<ConfigApplyState>,
loaded_models: crate::health_publisher::SharedLoadedModels,
+ health_publish_now: Arc<Notify>,
shutdown: Arc<Shutdown>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
@@ -1529,6 +1689,7 @@ fn spawn_heartbeat(
// (0 -> 1 "heartbeat broke", N -> 0 "heartbeat recovered")
// without spamming once per tick while the backend is down.
let mut consecutive_failures: u64 = 0;
+ let mut last_loading_by_child: Vec<Option<ChildLoadingMemory>> = Vec::new();
loop {
let wait = shutdown.wait();
tokio::select! {
@@ -1542,11 +1703,33 @@ fn spawn_heartbeat(
let ping_results = worker_pool.ping_all(ts).await;
let ready_children = worker_pool.ready_child_count();
crate::health_publisher::record_runtime_telemetry(&runtime_state);
- let successful_ready: Vec<_> = ping_results
+ let successful: Vec<_> = ping_results
.iter()
.filter_map(|(_index, result)| result.as_ref().ok())
+ .collect();
+ let successful_ready: Vec<_> = successful
+ .iter()
+ .copied()
.filter(|resp| resp.ready)
.collect();
+ // A child's list is replaced only when that child responds,
+ // including with an empty list. A failed ping keeps that
+ // child's list until its own report is older than the
+ // gateway heartbeat timeout. Another child's success must
+ // not clear it. Heartbeats continue, so the gateway would
+ // not age the lane out on its own.
+ let update = apply_loading_ping_round(
+ worker_pool.child_count(),
+ &ping_results,
+ &mut last_loading_by_child,
+ Instant::now(),
+ GATEWAY_HEARTBEAT_TIMEOUT,
+ );
+ if let LoadingSetUpdate::Replace(models) = update {
+ if config_apply_state.set_loading_models(models) {
+ health_publish_now.notify_one();
+ }
+ }
if let Some(resp) = (ready_children > 0).then(|| successful_ready.first()).flatten() {
config_apply_state.adopt_backend_hash_if_unset(&resp.bundle_config_hash);
let mut merged_loaded_models = Vec::new();
@@ -1948,6 +2131,92 @@ async fn run_pull_loop(
mod tests {
use super::*;
+ fn failed_at(models: Vec<String>, age: Duration) -> ChildPingRound {
+ ChildPingRound::Failed(Some(ChildLoadingSnapshot { models, age }))
+ }
+
+ #[test]
+ fn failed_ping_round_keeps_loading_models_until_heartbeat_timeout() {
+ let timeout = GATEWAY_HEARTBEAT_TIMEOUT;
+ let loading = vec!["org/loading".to_string()];
+ let other = vec!["org/other".to_string()];
+ assert_eq!(
+ loading_set_after_ping_round(
+ &[
+ ChildPingRound::Reported(loading.clone()),
+ ChildPingRound::Reported(other.clone()),
+ ],
+ timeout,
+ ),
+ LoadingSetUpdate::Replace(vec!["org/loading".into(), "org/other".into()])
+ );
+ assert_eq!(
+ loading_set_after_ping_round(&[ChildPingRound::Reported(Vec::new())], timeout),
+ LoadingSetUpdate::Replace(vec![])
+ );
+ assert_eq!(
+ loading_set_after_ping_round(&[failed_at(loading.clone(), timeout)], timeout),
+ LoadingSetUpdate::Keep
+ );
+ assert_eq!(
+ loading_set_after_ping_round(
+ &[failed_at(loading.clone(), Duration::from_secs(1))],
+ timeout,
+ ),
+ LoadingSetUpdate::Keep
+ );
+ assert_eq!(
+ loading_set_after_ping_round(&[ChildPingRound::Failed(None)], timeout),
+ LoadingSetUpdate::Keep
+ );
+ assert_eq!(
+ loading_set_after_ping_round(
+ &[failed_at(
+ loading.clone(),
+ timeout + Duration::from_nanos(1)
+ )],
+ timeout,
+ ),
+ LoadingSetUpdate::Replace(vec![])
+ );
+ assert_eq!(
+ loading_set_after_ping_round(
+ &[
+ failed_at(loading, Duration::from_secs(1)),
+ failed_at(other, timeout + Duration::from_nanos(1)),
+ ],
+ timeout,
+ ),
+ LoadingSetUpdate::Replace(vec!["org/loading".into()])
+ );
+ }
+
+ #[test]
+ fn sibling_ping_does_not_clear_a_child_whose_ping_failed() {
+ let timeout = GATEWAY_HEARTBEAT_TIMEOUT;
+ let loading = vec!["org/loading".to_string()];
+ assert_eq!(
+ loading_set_after_ping_round(
+ &[
+ failed_at(loading.clone(), Duration::from_secs(1)),
+ ChildPingRound::Reported(Vec::new()),
+ ],
+ timeout,
+ ),
+ LoadingSetUpdate::Replace(loading.clone())
+ );
+ assert_eq!(
+ loading_set_after_ping_round(
+ &[
+ failed_at(loading, timeout + Duration::from_nanos(1)),
+ ChildPingRound::Reported(Vec::new()),
+ ],
+ timeout,
+ ),
+ LoadingSetUpdate::Replace(Vec::new())
+ );
+ }
+
#[test]
fn pull_loop_inflight_defaults_are_positive() {
// Env-free default should be at least 1 and match the dispatcher
diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rs
index 0cd55dc81..95ceb925f 100644
--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs
+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs
@@ -187,6 +187,10 @@ pub struct PingResponse {
pub bundle_config_hash: String,
#[serde(default)]
pub loaded_models: Vec<String>,
+ /// Models whose load is still in progress. Omitted by an older engine;
+ /// an empty list is the steady state after Ready, Failed, or Cancelled.
+ #[serde(default)]
+ pub loading_models: Vec<String>,
}
// -----------------------------------------------------------------------------
@@ -1620,6 +1624,23 @@ mod tests {
assert!(!back.ready);
assert_eq!(back.bundle_config_hash, "");
assert!(back.loaded_models.is_empty());
+ assert!(back.loading_models.is_empty());
+ }
+
+ #[test]
+ fn ping_response_roundtrips_loading_models() {
+ let response = PingResponse {
+ timestamp_ms: 1.0,
+ worker_id: "w-1".into(),
+ ready: true,
+ bundle_config_hash: String::new(),
+ loaded_models: vec!["org/ready".into()],
+ loading_models: vec!["org/loading".into()],
+ };
+ let bytes = rmp_serde::to_vec_named(&response).unwrap();
+ let back: PingResponse = rmp_serde::from_slice(&bytes).unwrap();
+ assert_eq!(back.loading_models, ["org/loading".to_string()]);
+ assert_eq!(back.loaded_models, ["org/ready".to_string()]);
}
#[test]
diff --git a/packages/wire-fixtures/worker_status.json b/packages/wire-fixtures/worker_status.json
index 8250a7762..b2531dd30 100644
--- a/packages/wire-fixtures/worker_status.json
+++ b/packages/wire-fixtures/worker_status.json
@@ -15,6 +15,7 @@
"bundle",
"bundle_config_hash",
"loaded_models",
+ "loading_models",
"queue_depth",
"pending_cost",
"inflight_batches",
@@ -39,6 +40,7 @@
"bundle": "default",
"bundle_config_hash": "5f1e0b1a3c6d8e2f4a7b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f",
"loaded_models": ["BAAI/bge-m3"],
+ "loading_models": ["org/loading-model"],
"queue_depth": 2,
"pending_cost": 4096,
"inflight_batches": 1,
diff --git a/telemetry/README.md b/telemetry/README.md
index 33756edc3..59087a245 100644
--- a/telemetry/README.md
+++ b/telemetry/README.md
@@ -37,7 +37,11 @@ Topology determines whether a durable-queue observation exists. The OSS
Kubernetes gateway has an exact JetStream consumer authority and emits queue
depth plus lane freshness. Managed Modal dispatch has no JetStream queue, so it
omits those two families without warning; it still emits the same canonical
-pending-demand, active-lease, warm-floor, and rejection state over OTLP. An
+pending-demand, active-lease, warm-floor, model-load, and rejection state over
+OTLP. `sie.gateway.model_loads_in_progress` is 1 while any fresh worker in the
+lane is loading a model and an explicit 0 otherwise, including a lane with no
+live workers. It uses the same capacity-snapshot freshness guard as the other
+non-queue gauges. See #293 for why queue depth does not cover that window. An
absent managed queue series therefore means “not applicable,” never a measured
zero and never a broken duplicate metric path.
@@ -575,15 +579,16 @@ All Prometheus triggers set `ignoreNullValues: "false"`, so KEDA advances its
failure threshold and uses the ScaledObject's bounded fallback instead of
interpreting the failure as zero demand.
-The four current-state families use synchronous last-value gauges. Broker,
-pool, and demand reads are independently reconciled, and the OTel reader may
-collect instruments while a reconciliation is recording, so this contract is
+The current-state families, including `sie.gateway.model_loads_in_progress`,
+use synchronous last-value gauges. Broker, pool, and demand reads are
+independently reconciled, and the OTel reader may collect instruments while a
+reconciliation is recording, so this contract is
explicitly eventually consistent rather than cross-family export-atomic. Using
reconciliation *start* time makes a slow build age out instead of falsely
refreshing old state. Broker success is lane-scoped: one consumer failure
updates neither that lane's queue value nor its freshness timestamp, while
-successful lanes and the independent global demand/lease/floor state keep
-refreshing. The retained queue value becomes unusable when its timestamp ages
+successful lanes and the independent global demand, lease, floor, and
+model-load state keep refreshing. The retained queue value becomes unusable when its timestamp ages
out; it is never rewritten to a false zero. The five-second loop skips missed
ticks rather than queueing catch-up work. Each process hashes its process-start
UUID to a stable offset within that interval, so rollout-coincident replicas
diff --git a/telemetry/contract.yaml b/telemetry/contract.yaml
index 497dd05f2..167b1fe9f 100644
--- a/telemetry/contract.yaml
+++ b/telemetry/contract.yaml
@@ -395,6 +395,7 @@ cardinality_budgets:
- sie.gateway.lane.queue.snapshot.timestamp
- sie.gateway.active_lease.gpus
- sie.gateway.pool.warm_floor
+ - sie.gateway.model_loads_in_progress
- sie.gateway.rejected.requests
# Per-lane queue admission reuses the same deployment-owned lane tuple and
# the same fail-closed rules as the KEDA control domain, but is not itself a
@@ -2717,6 +2718,22 @@ metrics:
export: [prometheus, otlp]
topology_availability: [realtime_jetstream, managed_modal]
keda: pool_warm_floor
+ - name: sie.gateway.model_loads_in_progress
+ owner: gateway
+ facade_event: gateway.capacity_state_changed
+ type: gauge
+ unit: "1"
+ # 1 while any fresh worker in the lane is loading a model, else 0.
+ # Generation MODEL_LOADING deliveries stay acknowledged (#293), so lane
+ # queue depth can be 0 while this gauge holds the replica. A stale worker
+ # is excluded after the normal heartbeat timeout. Configured lanes with no
+ # live workers emit an explicit 0. The KEDA query uses the same capacity
+ # snapshot freshness guard as the other non-queue gauges.
+ attributes: keda_lane
+ prometheus_name: sie_gateway_model_loads_in_progress
+ export: [prometheus, otlp]
+ topology_availability: [realtime_jetstream, managed_modal]
+ keda: model_loads_in_progress
- name: sie.gateway.rejected.requests
owner: gateway
facade_event: gateway.request_rejected
@@ -3024,5 +3041,6 @@ keda:
lane_queue_depth: '(max(sie_gateway_lane_queue_depth{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway", pool="{{ pool }}", machine_profile="{{ machine_profile }}", bundle="{{ bundle }}"} and on(producer_instance,collector_generation) (abs(time() - sie_gateway_lane_queue_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway", pool="{{ pool }}", machine_profile="{{ machine_profile }}", bundle="{{ bundle }}"}) < 20)) and on() ((max(up{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus"}) == 1) and on() (count(sie_gateway_lane_queue_depth{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway", pool="{{ pool }}", machine_profile="{{ machine_profile }}", bundle="{{ bundle }}"} and on(producer_instance,collector_generation) (abs(time() - sie_gateway_lane_queue_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway", pool="{{ pool }}", machine_profile="{{ machine_profile }}", bundle="{{ bundle }}"}) < 20)) > 0)))'
active_lease_gpus: '(max(sie_gateway_active_lease_gpus{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway", pool="{{ pool }}", machine_profile="{{ machine_profile }}", bundle="{{ bundle }}"} and on(producer_instance,collector_generation) (abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20)) and on() ((max(up{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus"}) == 1) and on() (max(abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20))))'
pool_warm_floor: '(max(sie_gateway_pool_warm_floor{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway", pool="{{ pool }}", machine_profile="{{ machine_profile }}", bundle="{{ bundle }}"} and on(producer_instance,collector_generation) (abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20)) and on() ((max(up{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus"}) == 1) and on() (max(abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20))))'
+ model_loads_in_progress: '(max(sie_gateway_model_loads_in_progress{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway", pool="{{ pool }}", machine_profile="{{ machine_profile }}", bundle="{{ bundle }}"} and on(producer_instance,collector_generation) (abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20)) and on() ((max(up{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus"}) == 1) and on() (max(abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20))))'
scale_worthy_rejection_rate: '((sum(rate(sie_gateway_rejected_requests_total{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway", pool="{{ pool }}", machine_profile="{{ machine_profile }}", bundle="{{ bundle }}", scaling_action="scale_up"}[2m]) and on(producer_instance,collector_generation) (abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20)) or on() (0 * max(sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"} and on(producer_instance,collector_generation) (abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20)))) and on() ((max(up{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus"}) == 1) and on() (max(abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20))))'
gateway_request_rate: '((sum(rate(sie_gateway_requests_total{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}[1m]) and on(producer_instance,collector_generation) (abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20)) or on() (0 * max(sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"} and on(producer_instance,collector_generation) (abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20)))) and on() ((max(up{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus"}) == 1) and on() (max(abs(time() - sie_gateway_capacity_snapshot_timestamp_seconds{namespace="{{ namespace }}", service="{{ collector_service }}", endpoint="prometheus", producer_service="sie-gateway"}) < 20))))'
diff --git a/tools/ci/tests/test_helm_render.py b/tools/ci/tests/test_helm_render.py
index 28be4de15..8a22ce73b 100644
--- a/tools/ci/tests/test_helm_render.py
+++ b/tools/ci/tests/test_helm_render.py
@@ -146,6 +146,49 @@ def hook_events(tmp_path: Path, values: dict, template: str) -> dict[tuple[str,
}
+def test_worker_scaledobject_appends_the_sixth_trigger(tmp_path: Path) -> None:
+ values = {**L4_POOL, **AUTOSCALING_VALUES}
+ rendered = render_template(tmp_path, values, KEDA_APPLY_TEMPLATE)
+ assert rendered.returncode == 0, rendered.stderr
+ scaled_objects = [
+ manifest
+ for doc in yaml.safe_load_all(rendered.stdout)
+ if doc and doc.get("kind") == "ConfigMap"
+ for manifest in yaml.safe_load_all(doc.get("data", {}).get("scaledobjects.yaml", ""))
+ if manifest and manifest.get("kind") == "ScaledObject"
+ ]
+ (worker,) = [
+ scaled_object
+ for scaled_object in scaled_objects
+ if scaled_object["spec"]["scaleTargetRef"]["kind"] == "StatefulSet"
+ ]
+ triggers = worker["spec"]["triggers"]
+ assert [trigger["type"] for trigger in triggers] == ["prometheus"] * 6
+ # Indexes 0-4 match the pre-#293 HPA names. The loading trigger is last.
+ assert [trigger["metadata"]["metricName"] for trigger in triggers] == [
+ "sie_gateway_pending_demand_l4_default",
+ "sie_gateway_queue_depth_l4_default",
+ "sie_gateway_active_lease_gpus_l4_default",
+ "sie_gateway_pool_warm_floor_l4_default",
+ "sie_gateway_rejected_rate_l4_default",
+ "sie_gateway_model_loads_in_progress_l4_default",
+ ]
+
+ hook = render_template(tmp_path, values, "templates/hooks/keda-ready-test.yaml")
+ assert hook.returncode == 0, hook.stderr
+ (job,) = [doc for doc in yaml.safe_load_all(hook.stdout) if doc and doc.get("kind") == "Job"]
+ script = job["spec"]["template"]["spec"]["containers"][0]["args"][0]
+ assert "EXPECTED_METRIC_COUNT=7" in script
+ # 1-based probe count: 6 is trigger index 5 and is allowed; 7 is rejected.
+ assert re.search(r'\[ "\$object_metric_index" -lt 1 \] \|\| \[ "\$object_metric_index" -gt 6 \]', script)
+ assert re.search(r"\.key >= 0 and \.key <= 5\b", script)
+ scaled_objects_count = 2
+ probe_batches = (scaled_objects_count + 16 - 1) // 16
+ timeout = (30 * 3) + (probe_batches * 6 * 5 * 3) + 180
+ assert f"TIMEOUT={timeout}" in script
+ assert job["spec"]["activeDeadlineSeconds"] == timeout + 60
+
+
def test_scaledobject_apply_hook_also_runs_on_rollback(tmp_path: Path) -> None:
hooks = hook_events(tmp_path, AUTOSCALING_VALUES, KEDA_APPLY_TEMPLATE)