Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions bindings/python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,9 @@ struct Router {
mesh_advertise_host: Option<String>,
mesh_port: u16,
mesh_peer_urls: Vec<String>,
/// New parameters MUST be appended here (not inserted mid-list) to avoid
/// breaking external Python callers that pass `_Router(...)` positionally.
drain_settle_secs: u64,
}

impl Router {
Expand Down Expand Up @@ -698,6 +701,7 @@ impl Router {
endpoint: self.health_check_endpoint.clone(),
disable_health_check: self.disable_health_check,
remove_unhealthy_workers: self.remove_unhealthy_workers,
drain_settle_secs: self.drain_settle_secs,
})
.tokenizer_cache(config::TokenizerCacheConfig {
enable_l0: self.tokenizer_cache_enable_l0,
Expand Down Expand Up @@ -855,6 +859,7 @@ impl Router {
mesh_port = 39527u16,
mesh_peer_urls = vec![],
mesh_advertise_host = None,
drain_settle_secs = 5,
))]
#[expect(clippy::too_many_arguments)]
#[expect(
Expand Down Expand Up @@ -964,6 +969,7 @@ impl Router {
mesh_port: u16,
mesh_peer_urls: Vec<String>,
mesh_advertise_host: Option<String>,
drain_settle_secs: u64,
) -> PyResult<Self> {
let mut all_urls = worker_urls.clone();

Expand Down Expand Up @@ -1083,6 +1089,7 @@ impl Router {
mesh_advertise_host,
mesh_port,
mesh_peer_urls,
drain_settle_secs,
})
}

Expand Down
128 changes: 128 additions & 0 deletions crates/protocols/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ pub enum WorkerStatus {

/// Sustained liveness failure. Will be removed if `--remove-unhealthy-workers`.
Failed = 3,

/// Marked for removal (e.g. K8s pod has `deletionTimestamp`). Excluded
/// from selection so no new traffic is routed, but kept in the registry
/// so in-flight requests can complete before the worker is removed.
Draining = 4,
}

impl WorkerStatus {
Expand All @@ -127,6 +132,7 @@ impl WorkerStatus {
1 => Some(Self::Ready),
2 => Some(Self::NotReady),
3 => Some(Self::Failed),
4 => Some(Self::Draining),
_ => None,
}
}
Expand Down Expand Up @@ -155,6 +161,7 @@ impl std::fmt::Display for WorkerStatus {
WorkerStatus::Ready => write!(f, "ready"),
WorkerStatus::NotReady => write!(f, "not_ready"),
WorkerStatus::Failed => write!(f, "failed"),
WorkerStatus::Draining => write!(f, "draining"),
}
}
}
Expand Down Expand Up @@ -376,6 +383,10 @@ fn default_max_connection_attempts() -> u32 {
20
}

fn default_drain_settle_secs() -> u64 {
5
}

// ── Health check config ─────────────────────────────────────────────

/// Health check configuration shared across protocol and runtime layers.
Expand All @@ -400,6 +411,13 @@ pub struct HealthCheckConfig {
/// Disable periodic health checks for this worker (default: false).
#[serde(default)]
pub disable_health_check: bool,

/// Seconds to keep a worker in `Draining` after `RemoveWorker` is
/// submitted before the registry entry is actually removed. Lets
/// in-flight requests complete naturally (default: 5). Set to `0`
/// to skip draining and remove immediately.
#[serde(default = "default_drain_settle_secs")]
pub drain_settle_secs: u64,
}

impl Default for HealthCheckConfig {
Expand All @@ -410,6 +428,7 @@ impl Default for HealthCheckConfig {
success_threshold: default_health_success_threshold(),
failure_threshold: default_health_failure_threshold(),
disable_health_check: false,
drain_settle_secs: default_drain_settle_secs(),
}
}
}
Expand Down Expand Up @@ -806,6 +825,8 @@ pub struct HealthCheckUpdate {
pub success_threshold: Option<u32>,
pub failure_threshold: Option<u32>,
pub disable_health_check: Option<bool>,
/// Per-worker override for `HealthCheckConfig::drain_settle_secs`.
pub drain_settle_secs: Option<u64>,
}

impl HealthCheckUpdate {
Expand All @@ -816,6 +837,7 @@ impl HealthCheckUpdate {
&& self.success_threshold.is_none()
&& self.failure_threshold.is_none()
&& self.disable_health_check.is_none()
&& self.drain_settle_secs.is_none()
}
}

Expand All @@ -833,6 +855,7 @@ impl HealthCheckUpdate {
disable_health_check: self
.disable_health_check
.unwrap_or(existing.disable_health_check),
drain_settle_secs: self.drain_settle_secs.unwrap_or(existing.drain_settle_secs),
}
}
}
Expand Down Expand Up @@ -1087,3 +1110,108 @@ impl IntoResponse for WorkerLoadsResult {
Json(json!({"workers": loads})).into_response()
}
}

#[cfg(test)]
mod worker_status_tests {
use super::WorkerStatus;

#[test]
fn test_try_from_u8_draining() {
assert_eq!(WorkerStatus::try_from_u8(4), Some(WorkerStatus::Draining));
}

#[test]
fn test_try_from_u8_unknown_returns_none() {
assert_eq!(WorkerStatus::try_from_u8(5), None);
assert_eq!(WorkerStatus::try_from_u8(255), None);
}

#[test]
fn test_from_u8_draining() {
assert_eq!(WorkerStatus::from_u8(4), WorkerStatus::Draining);
}

#[test]
fn test_display_draining_is_snake_case() {
assert_eq!(WorkerStatus::Draining.to_string(), "draining");
}

#[test]
fn test_serde_round_trip_draining() {
let s = serde_json::to_string(&WorkerStatus::Draining).unwrap();
assert_eq!(s, "\"draining\"");
let back: WorkerStatus = serde_json::from_str(&s).unwrap();
assert_eq!(back, WorkerStatus::Draining);
}

#[test]
fn test_draining_is_not_routable() {
assert!(!WorkerStatus::Draining.is_routable());
}

#[test]
fn test_only_ready_is_routable() {
for s in [
WorkerStatus::Pending,
WorkerStatus::Ready,
WorkerStatus::NotReady,
WorkerStatus::Failed,
WorkerStatus::Draining,
] {
assert_eq!(s.is_routable(), s == WorkerStatus::Ready, "{s:?}");
}
}
}

#[cfg(test)]
mod health_check_drain_settle_tests {
use super::{HealthCheckConfig, HealthCheckUpdate};

#[test]
fn test_default_drain_settle_secs_is_5() {
assert_eq!(HealthCheckConfig::default().drain_settle_secs, 5);
}

#[test]
fn test_health_check_update_overrides_drain_settle_secs() {
let base = HealthCheckConfig::default();
let update = HealthCheckUpdate {
drain_settle_secs: Some(30),
..Default::default()
};
let merged = update.apply_to(&base);
assert_eq!(merged.drain_settle_secs, 30);
}

#[test]
fn test_health_check_update_keeps_default_when_unset() {
let base = HealthCheckConfig {
drain_settle_secs: 12,
..Default::default()
};
let update = HealthCheckUpdate::default();
assert_eq!(update.apply_to(&base).drain_settle_secs, 12);
}

#[test]
fn test_health_check_update_is_empty_includes_drain_settle_secs() {
let mut update = HealthCheckUpdate::default();
assert!(update.is_empty());
update.drain_settle_secs = Some(3);
assert!(!update.is_empty());
}

#[test]
fn test_health_check_config_deserialize_omitted_uses_default() {
// Existing serialized configs without drain_settle_secs must
// still deserialize with the default value, not fail.
let json = r#"{
"timeout_secs": 30,
"check_interval_secs": 60,
"success_threshold": 2,
"failure_threshold": 3
}"#;
let cfg: HealthCheckConfig = serde_json::from_str(json).unwrap();
assert_eq!(cfg.drain_settle_secs, 5);
}
}
1 change: 1 addition & 0 deletions model_gateway/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ rsa = { version = "0.9", features = ["sha2"] }
jsonwebtoken = "9.3"
validator = "0.20.0"
tracing-test = "0.2"
tokio = { workspace = true, features = ["test-util"] }
kv-index.workspace = true
wasmtime-wasi = { workspace = true }
lru = { workspace = true }
Expand Down
12 changes: 12 additions & 0 deletions model_gateway/src/config/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,16 @@ pub struct HealthCheckConfig {
pub disable_health_check: bool,
#[serde(default)]
pub remove_unhealthy_workers: bool,
/// Seconds to keep a Ready worker in `Draining` after `RemoveWorker`
/// is submitted before the registry entry is removed. Lets in-flight
/// requests complete naturally. Set to `0` to skip draining and
/// remove immediately. Default: 5.
#[serde(default = "default_drain_settle_secs")]
pub drain_settle_secs: u64,
}

fn default_drain_settle_secs() -> u64 {
5
}

impl Default for HealthCheckConfig {
Expand All @@ -551,6 +561,7 @@ impl Default for HealthCheckConfig {
endpoint: "/health".to_string(),
disable_health_check: false,
remove_unhealthy_workers: false,
drain_settle_secs: default_drain_settle_secs(),
}
}
}
Expand All @@ -564,6 +575,7 @@ impl HealthCheckConfig {
success_threshold: self.success_threshold,
failure_threshold: self.failure_threshold,
disable_health_check: self.disable_health_check,
drain_settle_secs: self.drain_settle_secs,
}
}
}
Expand Down
9 changes: 9 additions & 0 deletions model_gateway/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,14 @@ struct CliArgs {
#[arg(long, default_value_t = false, help_heading = "Health Checks")]
remove_unhealthy_workers: bool,

/// Seconds to keep a Ready worker in `Draining` before removing it from
/// the registry. Applies to all RemoveWorker submissions (K8s deletion,
/// `--remove-unhealthy-workers`, manual API). Per-worker overrides are
/// supported via `WorkerSpec::health.drain_settle_secs`. Set to `0` to
/// remove immediately without draining.
#[arg(long, default_value_t = 5, help_heading = "Health Checks")]
drain_settle_secs: u64,

// ==================== Tokenizer ====================
/// Model path for loading tokenizer (HuggingFace ID or local path)
#[arg(long, alias = "model", help_heading = "Tokenizer")]
Expand Down Expand Up @@ -1224,6 +1232,7 @@ impl CliArgs {
endpoint: self.health_check_endpoint.clone(),
disable_health_check: self.disable_health_check,
remove_unhealthy_workers: self.remove_unhealthy_workers,
drain_settle_secs: self.drain_settle_secs,
})
.tokenizer_cache(TokenizerCacheConfig {
enable_l0: self.tokenizer_cache_enable_l0,
Expand Down
37 changes: 37 additions & 0 deletions model_gateway/src/policies/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,4 +223,41 @@ mod tests {
let indices = get_healthy_worker_indices(&workers);
assert_eq!(indices, vec![0, 2]);
}

/// Only `Ready` workers may be selected. Pending, NotReady, Failed, and
/// Draining are all excluded. Draining specifically guards against
/// routing new traffic to a worker that is being torn down.
#[test]
fn test_get_healthy_worker_indices_excludes_each_non_ready_status() {
let cases = [
(WorkerStatus::Pending, false),
(WorkerStatus::Ready, true),
(WorkerStatus::NotReady, false),
(WorkerStatus::Failed, false),
(WorkerStatus::Draining, false),
];

for (status, expected_included) in cases {
let worker: Arc<dyn Worker> = Arc::new(
BasicWorkerBuilder::new("http://w:8000")
.worker_type(WorkerType::Regular)
.api_key("k")
.health_config(no_health_check())
.build(),
);
worker.set_status(status);
let workers = vec![worker];
let indices = get_healthy_worker_indices(&workers);
assert_eq!(
indices == vec![0],
expected_included,
"status {status:?} should be {}",
if expected_included {
"included"
} else {
"excluded"
}
);
}
}
}
2 changes: 2 additions & 0 deletions model_gateway/src/worker/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,7 @@ mod tests {
failure_threshold: 3,
success_threshold: 2,
disable_health_check: false,
drain_settle_secs: 5,
};

let cb_config = CircuitBreakerConfig {
Expand Down Expand Up @@ -462,6 +463,7 @@ mod tests {
failure_threshold: 5,
success_threshold: 3,
disable_health_check: false,
drain_settle_secs: 5,
};

let worker = BasicWorkerBuilder::new("http://localhost:8080")
Expand Down
Loading
Loading