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: keep out-of-range timeouts from panicking the gateway and sidecar (#411)

Krisztian Gajdar658d1d464618
diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rs
index b4de99240..ea6799809 100644
--- a/packages/sie_gateway/src/config.rs
+++ b/packages/sie_gateway/src/config.rs
@@ -1,5 +1,6 @@
use std::collections::{HashMap, HashSet};
use std::env;
+use std::time::Duration;
use serde::Deserialize;
@@ -444,6 +445,22 @@ fn env_finite_float(key: &str, fallback: f64) -> f64 {
value
}
+/// The longest timeout the gateway arms: Tokio's own horizon for a deadline
+/// it cannot represent. Any `Instant` can be advanced by it without overflow.
+pub const MAX_TIMEOUT: Duration = Duration::from_secs(30 * 365 * 24 * 60 * 60);
+
+/// Converts seconds into a timeout: values that are not positive become zero,
+/// and larger values than [`MAX_TIMEOUT`] saturate to it.
+pub fn timeout_from_secs(seconds: f64) -> Duration {
+ if seconds > 0.0 {
+ Duration::try_from_secs_f64(seconds)
+ .unwrap_or(Duration::MAX)
+ .min(MAX_TIMEOUT)
+ } else {
+ Duration::ZERO
+ }
+}
+
/// Read `SIE_STREAM_STORAGE`. An unset, empty, or unrecognized value keeps
/// the historical `Memory` behaviour so a typo can never silently change the
/// durability posture of a running cluster in the *other* direction either.
@@ -1337,6 +1354,21 @@ mod tests {
});
}
+ #[test]
+ fn test_timeout_from_secs_saturates_instead_of_panicking() {
+ assert_eq!(timeout_from_secs(45.5), Duration::from_millis(45_500));
+ for seconds in [0.0, -1.0, f64::NAN, f64::NEG_INFINITY] {
+ assert_eq!(timeout_from_secs(seconds), Duration::ZERO, "{seconds}");
+ }
+ for seconds in [f64::INFINITY, 1e300, 1e19, 2.0 * MAX_TIMEOUT.as_secs_f64()] {
+ assert_eq!(timeout_from_secs(seconds), MAX_TIMEOUT, "{seconds}");
+ }
+ let now = std::time::Instant::now();
+ assert!(now + MAX_TIMEOUT > now);
+ let now = tokio::time::Instant::now();
+ assert!(now + MAX_TIMEOUT > now);
+ }
+
#[test]
fn test_config_service_url_from_env() {
with_env(
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index f1448aa5f..4b34b3c4b 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -12,6 +12,7 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{debug, error, info, warn, Instrument};
+use crate::config::timeout_from_secs;
use crate::endpoint::InferenceEndpoint;
use crate::http_error::{
code as err_code, embeddings_error, json_detail, json_detail_merge, json_openai_error,
@@ -2992,7 +2993,7 @@ async fn queue_mode_proxy(
// Wait for results (use configured request_timeout instead of hardcoded 300s).
// Preserve fractional env values instead of truncating them through `as u64`.
- let timeout = Duration::from_secs_f64(state.config.request_timeout.max(0.001));
+ let timeout = timeout_from_secs(state.config.request_timeout.max(0.001));
let timeout_secs = timeout.as_secs_f64();
let wait_start = Instant::now();
let wait_deadline = tokio::time::Instant::now() + timeout;
@@ -8908,9 +8909,9 @@ pub(crate) fn generation_timeout_config(
enforce_first_chunk_invariant(first_chunk, overall, model, profile_name);
GenerationTimeoutConfig {
- first_chunk: Duration::from_secs_f64(first_chunk),
- inter_chunk: Duration::from_secs_f64(inter_chunk),
- overall: Duration::from_secs_f64(overall),
+ first_chunk: timeout_from_secs(first_chunk),
+ inter_chunk: timeout_from_secs(inter_chunk),
+ overall: timeout_from_secs(overall),
}
}
@@ -11039,16 +11040,23 @@ fn validate_generate_options_map(
"overall_timeout_s",
] {
if let Some(value) = options.get(key) {
- let valid = value
+ let field = format!("options.{key}");
+ let Some(seconds) = value
.as_f64()
- .is_some_and(|value| value.is_finite() && value > 0.0);
- if !valid {
- let field = format!("options.{key}");
+ .filter(|seconds| seconds.is_finite() && *seconds > 0.0)
+ else {
return Err(sampler_bad_request(
format!("'{field}' must be a positive number"),
&field,
oai_code::INVALID_REQUEST,
));
+ };
+ if Duration::try_from_secs_f64(seconds).is_err() {
+ return Err(sampler_bad_request(
+ format!("'{field}' must be less than 2^64 seconds"),
+ &field,
+ oai_code::INVALID_REQUEST,
+ ));
}
}
}
@@ -18258,6 +18266,107 @@ mod tests {
assert_eq!(ov, 30.0);
}
+ const GENERATION_TIMEOUT_KEYS: [&str; 3] = [
+ "first_chunk_timeout_s",
+ "inter_chunk_timeout_s",
+ "overall_timeout_s",
+ ];
+
+ #[tokio::test]
+ async fn test_generation_timeout_options_beyond_duration_range_are_rejected() {
+ let state = admission_test_state(Arc::new(PoolManager::new(vec!["l4".to_string()])));
+ for key in GENERATION_TIMEOUT_KEYS {
+ for seconds in [1e300, 18_446_744_073_709_551_616.0] {
+ let body = serde_json::json!({
+ "prompt": "hi",
+ "max_new_tokens": 8,
+ "options": {key: seconds},
+ });
+ let response = match work_params_from_json(&body, "generate") {
+ Err(QueueParseError::PreBuilt(response)) => response,
+ Err(_) => panic!("options.{key}={seconds:e} must fail as a prebuilt 400"),
+ Ok(params) => {
+ let config = generation_timeout_config(&state, "m", &params, 8);
+ panic!("options.{key}={seconds:e} was accepted as {config:?}");
+ }
+ };
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)
+ .await
+ .unwrap();
+ let error: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(error["error"]["code"], "invalid_request");
+ assert_eq!(error["error"]["param"], format!("options.{key}"));
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn test_generation_timeout_options_beyond_instant_range_arm_deadlines() {
+ let state = admission_test_state(Arc::new(PoolManager::new(vec!["l4".to_string()])));
+ for seconds in [1e19, 18_446_744_073_709_549_568.0] {
+ let options: serde_json::Map<String, serde_json::Value> = GENERATION_TIMEOUT_KEYS
+ .iter()
+ .map(|key| (key.to_string(), serde_json::json!(seconds)))
+ .collect();
+ let body = serde_json::json!({"prompt": "hi", "max_new_tokens": 8, "options": options});
+ let Ok(params) = work_params_from_json(&body, "generate") else {
+ panic!("timeouts of {seconds:e} s fit a duration and must be accepted");
+ };
+ let config = generation_timeout_config(&state, "m", &params, 8);
+ let start = tokio::time::Instant::now();
+ for timeout in [config.first_chunk, config.inter_chunk, config.overall] {
+ assert!(start + timeout > start);
+ assert_eq!(timeout, crate::config::MAX_TIMEOUT);
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn test_generation_timeout_profile_values_beyond_duration_range_saturate() {
+ use crate::types::model::{ModelConfig, ProfileConfig};
+
+ let mut state = admission_test_state(Arc::new(PoolManager::new(vec!["l4".to_string()])));
+ state.model_registry = Arc::new(empty_registry());
+ let runtime: serde_json::Map<String, serde_json::Value> = GENERATION_TIMEOUT_KEYS
+ .iter()
+ .map(|key| (key.to_string(), serde_json::json!(1e300)))
+ .collect();
+ let profile = ProfileConfig {
+ kv_budget_tokens: None,
+ max_output_tokens: None,
+ grammar_profile: None,
+ chat_template_kwargs: None,
+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),
+ max_batch_tokens: None,
+ compute_precision: None,
+ adapter_options: Some(serde_json::json!({"runtime": runtime})),
+ extends: None,
+ };
+ state
+ .model_registry
+ .add_model_config(ModelConfig {
+ name: "org/slow".to_string(),
+ hf_revision: None,
+ adapter_module: None,
+ default_bundle: None,
+ pool: None,
+ profiles: std::collections::HashMap::from([("default".to_string(), profile)]),
+ inputs: None,
+ max_sequence_length: None,
+ tasks: None,
+ })
+ .unwrap();
+
+ let config =
+ generation_timeout_config(&state, "org/slow", &publisher::WorkParams::default(), 8);
+ let start = tokio::time::Instant::now();
+ for timeout in [config.first_chunk, config.inter_chunk, config.overall] {
+ assert!(start + timeout > start);
+ assert_eq!(timeout, crate::config::MAX_TIMEOUT);
+ }
+ }
+
// H7 contract (ADR-0003): generation streaming does NOT clamp
// `timeout_config.overall` with `state.config.request_timeout`. The
// legacy ceiling continues to bound encode/score/extract, but the
diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rs
index a8461f6e8..aac83af31 100644
--- a/packages/sie_gateway/src/main.rs
+++ b/packages/sie_gateway/src/main.rs
@@ -520,7 +520,7 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {
jetstream,
nats_manager.router_id().to_string(),
payload_store,
- Duration::from_secs_f64(config.request_timeout),
+ config::timeout_from_secs(config.request_timeout),
config.max_stream_pending,
queue::publisher::WorkStreamConfig {
max_age: Duration::from_secs(config.stream_max_age_s),
diff --git a/packages/sie_server/src/sie_server/core/runtime_options.py b/packages/sie_server/src/sie_server/core/runtime_options.py
index fbe1bef5e..c1d656555 100644
--- a/packages/sie_server/src/sie_server/core/runtime_options.py
+++ b/packages/sie_server/src/sie_server/core/runtime_options.py
@@ -123,6 +123,8 @@ _GENERATION_RUNTIME_KEYS = frozenset(
"overall_timeout_s",
}
)
+# The gateway rejects a request timeout that does not fit in its duration type.
+_MAX_REQUEST_TIMEOUT_S = 2.0**64
_GENERATION_SAMPLING_KEYS = {
"temperature": "temperature",
"top_p": "top_p",
@@ -175,9 +177,13 @@ def apply_generation_runtime_options(
if "stop_tokens" in request_options and not isinstance(request_options["stop_tokens"], list):
raise ValueError("'options.stop_tokens' must be an array of non-empty strings")
for key in ("first_chunk_timeout_s", "inter_chunk_timeout_s", "overall_timeout_s"):
- value = request_options.get(key)
- if key in request_options and (isinstance(value, bool) or not isinstance(value, int | float) or value <= 0):
+ if key not in request_options:
+ continue
+ value = request_options[key]
+ if isinstance(value, bool) or not isinstance(value, int | float) or value <= 0:
raise ValueError(f"'options.{key}' must be a positive number")
+ if _is_finite_number(value) and float(value) >= _MAX_REQUEST_TIMEOUT_S:
+ raise ValueError(f"'options.{key}' must be less than 2^64 seconds")
runtime = merge_runtime_options(config, request_options)
profile_sampling = config.resolve_profile("default").runtime.get("default_sampling")
diff --git a/packages/sie_server/tests/core/test_runtime_options.py b/packages/sie_server/tests/core/test_runtime_options.py
index bbce0ccfe..e3de524ad 100644
--- a/packages/sie_server/tests/core/test_runtime_options.py
+++ b/packages/sie_server/tests/core/test_runtime_options.py
@@ -344,6 +344,18 @@ def test_generation_non_finite_timeout_fails_closed(value: float) -> None:
apply_generation_runtime_options(_generation_config(), {"overall_timeout_s": value}, {"prompt": "hi"})
[email protected]("key", ["first_chunk_timeout_s", "inter_chunk_timeout_s", "overall_timeout_s"])
[email protected]("value", [1e300, 2.0**64, 1 << 64])
+def test_generation_request_timeout_beyond_duration_range_fails_closed(key: str, value: float) -> None:
+ with pytest.raises(ValueError, match=r"less than 2\^64 seconds"):
+ apply_generation_runtime_options(_generation_config(), {key: value}, {"prompt": "hi"})
+
+
+def test_generation_request_timeout_below_duration_range_is_accepted() -> None:
+ largest_below = float.fromhex("0x1.fffffffffffffp+63")
+ apply_generation_runtime_options(_generation_config(), {"overall_timeout_s": largest_below}, {"prompt": "hi"})
+
+
def test_generation_timeouts_resolve_from_profile_and_request() -> None:
config = _generation_config()
diff --git a/packages/sie_server_sidecar/src/latency.rs b/packages/sie_server_sidecar/src/latency.rs
index 438493dde..8d8ca9dc6 100644
--- a/packages/sie_server_sidecar/src/latency.rs
+++ b/packages/sie_server_sidecar/src/latency.rs
@@ -169,7 +169,7 @@ impl FetchExpiryController {
};
let headroom_ms = self.target_p50_ms - observed;
let adjustment_s = headroom_ms * self.gain / 1000.0;
- let adjustment = Duration::from_secs_f64(adjustment_s.abs());
+ let adjustment = Duration::try_from_secs_f64(adjustment_s.abs()).unwrap_or(Duration::MAX);
let new = if adjustment_s >= 0.0 {
current.saturating_add(adjustment)
} else {
@@ -279,6 +279,31 @@ mod tests {
);
}
+ #[test]
+ fn adjust_stays_within_bounds_for_extreme_targets() {
+ let mut t = LatencyTracker::new(200, 10);
+ for _ in 0..20 {
+ t.record(10.0);
+ }
+ let defaults = FetchExpiryController::from_env_or_default();
+ for (target_p50_ms, expected) in [
+ (f64::INFINITY, defaults.max),
+ (1e300, defaults.max),
+ (-1e300, defaults.min),
+ (f64::NAN, defaults.min),
+ ] {
+ let c = FetchExpiryController {
+ target_p50_ms,
+ ..defaults.clone()
+ };
+ assert_eq!(
+ c.adjust(Duration::from_millis(5), &t),
+ expected,
+ "{target_p50_ms}"
+ );
+ }
+ }
+
#[test]
fn adjust_clamps_to_min_on_aggressive_shrink() {
let c = FetchExpiryController::from_env_or_default();
diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rs
index b054c7abd..52522309b 100644
--- a/packages/sie_server_sidecar/src/nats_consumer.rs
+++ b/packages/sie_server_sidecar/src/nats_consumer.rs
@@ -43,10 +43,18 @@ fn max_deliver() -> i64 {
.unwrap_or(DEFAULT_MAX_DELIVER)
}
+/// Longest redelivery envelope, so that it can always be added to an `Instant`.
+const MAX_REDELIVERY_ENVELOPE: Duration = Duration::from_secs(30 * 365 * 24 * 60 * 60);
+
/// How long JetStream keeps redelivering an unacknowledged work message
/// before it dead-letters it: `max_deliver` rounds of the ACK wait.
pub(crate) fn redelivery_envelope() -> Duration {
- Duration::from_secs(ACK_WAIT_SECS.saturating_mul(max_deliver() as u64))
+ redelivery_envelope_for(max_deliver())
+}
+
+fn redelivery_envelope_for(max_deliver: i64) -> Duration {
+ Duration::from_secs(ACK_WAIT_SECS.saturating_mul(max_deliver as u64))
+ .min(MAX_REDELIVERY_ENVELOPE)
}
/// The larger of the durable work lifetime and configured retry envelope is the
@@ -869,6 +877,18 @@ mod tests {
);
}
+ #[test]
+ fn redelivery_envelope_can_always_be_added_to_an_instant() {
+ assert_eq!(
+ redelivery_envelope_for(DEFAULT_MAX_DELIVER),
+ Duration::from_secs(600)
+ );
+ let envelope = redelivery_envelope_for(i64::MAX);
+ let now = tokio::time::Instant::now();
+ assert!(now + envelope > now);
+ assert_eq!(envelope, MAX_REDELIVERY_ENVELOPE);
+ }
+
#[test]
fn env_free_accessors_match_defaults() {
// Env-free calls must return the hardcoded defaults. We do not
diff --git a/packages/sie_server_sidecar/src/scheduler/batch_former.rs b/packages/sie_server_sidecar/src/scheduler/batch_former.rs
index 23ea96627..7192145bc 100644
--- a/packages/sie_server_sidecar/src/scheduler/batch_former.rs
+++ b/packages/sie_server_sidecar/src/scheduler/batch_former.rs
@@ -524,7 +524,7 @@ fn wait_timeout<I: HasCost, T>(inner: &Inner<I, T>) -> Option<Duration> {
let effective_ms = batch_remaining_ms.min(coalesce_remaining_ms);
// ms → Duration, clamping tiny negatives to zero.
- Some(Duration::from_secs_f64(effective_ms.max(0.0) / 1000.0))
+ Some(Duration::try_from_secs_f64(effective_ms.max(0.0) / 1000.0).unwrap_or(Duration::MAX))
}
fn extract_batch<I: HasCost, T>(
@@ -1030,6 +1030,29 @@ mod tests {
assert!(t <= Duration::from_millis(20));
}
+ #[test]
+ fn wait_timeout_saturates_for_windows_beyond_duration_range() {
+ let cfg = BatchConfig {
+ max_batch_wait_ms: 1e300,
+ coalesce_ms: 1e300,
+ coalesce_ratio: 1.0,
+ ..BatchConfig::default()
+ };
+ let now = Instant::now();
+ let inner: Inner<StubItem, u32> = Inner {
+ pending: vec![PendingRequest {
+ item: StubItem::new(1),
+ metadata: 1,
+ arrival_time: now,
+ }],
+ total_cost: 1,
+ first_request_time: Some(now),
+ last_submit_time: Some(now),
+ config: cfg,
+ };
+ assert_eq!(wait_timeout(&inner), Some(Duration::MAX));
+ }
+
#[test]
fn wait_timeout_none_when_no_pending() {
let cfg = BatchConfig::default();