From 53fb9be7ee9ea8b2f3572b32f3223a53a015bbc3 Mon Sep 17 00:00:00 2001 From: "minke.yu" Date: Sun, 11 Oct 2026 21:42:21 +0800 Subject: [PATCH] G9i: TTFT p95/p99 statistics (observability only, no admission gate) --- sgl-model-gateway/src/main.rs | 5 + sgl-model-gateway/src/routers/http/g9i.rs | 142 ++++++++++++++++-- .../src/routers/http/pd_router.rs | 91 +++++++---- 3 files changed, 193 insertions(+), 45 deletions(-) diff --git a/sgl-model-gateway/src/main.rs b/sgl-model-gateway/src/main.rs index 360a111e8c..0fd9dc7ce7 100644 --- a/sgl-model-gateway/src/main.rs +++ b/sgl-model-gateway/src/main.rs @@ -264,6 +264,10 @@ struct CliArgs { #[arg(long, default_value_t = false, help_heading = "G9i Pool Admission")] g9i_regular_pool_least_wait: bool, + /// Sliding window for TTFT p95/p99 statistics publication (seconds; observability only, never gates) + #[arg(long, default_value_t = 300, help_heading = "G9i Pool Admission")] + g9i_ttft_window_s: u64, + // ==================== Service Discovery (Kubernetes) ==================== /// Enable Kubernetes service discovery #[arg( @@ -1138,6 +1142,7 @@ impl CliArgs { d_no_snapshot: self.g9i_d_no_snapshot.clone(), cache_hit_query_timeout_ms: self.g9i_cache_hit_query_timeout_ms, regular_pool_least_wait: self.g9i_regular_pool_least_wait, + ttft_window_s: self.g9i_ttft_window_s, }; config.validate().map_err(|reason| ConfigError::ValidationFailed { reason })?; Ok(Some(config)) diff --git a/sgl-model-gateway/src/routers/http/g9i.rs b/sgl-model-gateway/src/routers/http/g9i.rs index c8df5342e4..3d95c2de0e 100644 --- a/sgl-model-gateway/src/routers/http/g9i.rs +++ b/sgl-model-gateway/src/routers/http/g9i.rs @@ -21,13 +21,21 @@ //! 4. Fast-P queue gate: least-wait fast-P estimate > `fast_p_queue_reject_secs` //! -> 429 (`fast_p_queue`) with `x-estimated-wait-s`. //! +//! TTFT statistics (user directive 2026-10-11: measure p95/p99 against the +//! 10s/30s reference budgets, **observability only — no hard gate**): every +//! streaming request's time-to-first-token is recorded into a sliding window +//! and published as per-path histogram + pooled p95/p99 gauges. Nothing is +//! rejected on these percentiles; they exist to watch the SLO and feed +//! capacity decisions. Non-streaming requests carry no observable +//! first-token moment and are not sampled. +//! //! Fail-open discipline: missing/stale snapshots never hard-fail a request //! (the engine's own max-running-requests is the hard backstop); every //! fail-open path emits a warn log + metric. All numeric thresholds are //! tentative (measured values to be tuned in bench) and config-driven. use std::{ - collections::HashMap, + collections::{HashMap, VecDeque}, sync::{ atomic::{AtomicBool, Ordering}, Arc, RwLock, @@ -46,6 +54,7 @@ const METRIC_DECISIONS: &str = "smg_g9i_decisions_total"; const METRIC_REJECTS: &str = "smg_g9i_rejects_total"; const METRIC_QUERY_LATENCY: &str = "smg_g9i_cache_hit_query_duration_seconds"; const METRIC_NO_DATA: &str = "smg_g9i_no_fresh_snapshot_total"; +const METRIC_TTFT: &str = "smg_g9i_ttft_seconds"; /// G9i admission / fast-P routing configuration. /// @@ -96,6 +105,10 @@ pub struct G9iConfig { /// prefill policy). Default false: regular pool keeps existing policy. #[serde(default)] pub regular_pool_least_wait: bool, + /// Sliding window for TTFT percentile publication (seconds). Statistics + /// only — never gates admission. + #[serde(default = "default_ttft_window_s")] + pub ttft_window_s: u64, } fn default_max_new_tokens() -> u64 { @@ -122,6 +135,9 @@ fn default_d_no_snapshot() -> String { fn default_cache_hit_query_timeout_ms() -> u64 { 2000 } +fn default_ttft_window_s() -> u64 { + 300 +} impl Default for G9iConfig { fn default() -> Self { @@ -137,6 +153,7 @@ impl Default for G9iConfig { d_no_snapshot: default_d_no_snapshot(), cache_hit_query_timeout_ms: default_cache_hit_query_timeout_ms(), regular_pool_least_wait: false, + ttft_window_s: default_ttft_window_s(), } } } @@ -206,6 +223,56 @@ pub struct G9iState { /// Whether any /v1/loads fetch ever succeeded (startup grace for D-gate). had_any_success: AtomicBool, monitor_started: AtomicBool, + /// TTFT sliding window: per-path samples with insert timestamps. + /// Statistics only — never used for admission. + ttft: RwLock, +} + +/// Sliding-window TTFT samples (observability; no shedding state). +#[derive(Debug, Default)] +struct TtftWindow { + /// path label -> (inserted at, ttft seconds) + samples: HashMap<&'static str, VecDeque<(Instant, f64)>>, +} + +impl TtftWindow { + fn evict_stale(&mut self, window: Duration) { + for deque in self.samples.values_mut() { + while deque + .front() + .is_some_and(|(t, _)| t.elapsed() > window) + { + deque.pop_front(); + } + } + } + + fn record(&mut self, path: &'static str, value: f64, window: Duration) { + self.samples + .entry(path) + .or_default() + .push_back((Instant::now(), value)); + self.evict_stale(window); + } + + /// Pooled samples across all paths (the SLO is user-facing, path-agnostic). + fn pooled(&self) -> Vec { + let mut all: Vec = self + .samples + .values() + .flat_map(|d| d.iter().map(|(_, v)| *v)) + .collect(); + all.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + all + } + + fn percentile(sorted: &[f64], q: f64) -> Option { + if sorted.is_empty() { + return None; + } + let idx = ((sorted.len() - 1) as f64 * q).round() as usize; + sorted.get(idx).copied() + } } impl G9iState { @@ -215,6 +282,7 @@ impl G9iState { snapshots: RwLock::new(HashMap::new()), had_any_success: AtomicBool::new(false), monitor_started: AtomicBool::new(false), + ttft: RwLock::new(TtftWindow::default()), } } @@ -282,6 +350,8 @@ impl G9iState { snap.insert(url, load); } } + + self.publish_ttft_percentiles(); } fn snapshot(&self, url: &str) -> Option { @@ -393,23 +463,59 @@ impl G9iState { Ok(()) } + /// Record one streaming request's time-to-first-token (seconds, measured + /// from dispatch entry). Called from the response stream on its first + /// chunk; histogram per path, sample into the gate window. + pub fn record_ttft(&self, path: &'static str, seconds: f64) { + metrics::histogram!(METRIC_TTFT, "path" => path).record(seconds); + if seconds < 0.0 { + return; + } + let window = Duration::from_secs(self.config.ttft_window_s.max(10)); + if let Ok(mut w) = self.ttft.write() { + w.record(path, seconds, window); + } + } + + /// Publish observed TTFT percentiles as gauges (called from the snapshot + /// poller — cheap, piggybacks an existing periodic task). Statistics + /// only: never rejects. Reference budgets (p95 10s / p99 30s) are an + /// alerting concern for the consumer of these metrics, not enforced here. + pub fn publish_ttft_percentiles(&self) { + let window = Duration::from_secs(self.config.ttft_window_s.max(10)); + let mut w = match self.ttft.write() { + Ok(w) => w, + Err(_) => return, + }; + w.evict_stale(window); + let sorted = w.pooled(); + metrics::gauge!("smg_g9i_ttft_window_samples").set(sorted.len() as f64); + if let Some(v) = TtftWindow::percentile(&sorted, 0.95) { + metrics::gauge!("smg_g9i_ttft_p95_seconds").set(v); + } + if let Some(v) = TtftWindow::percentile(&sorted, 0.99) { + metrics::gauge!("smg_g9i_ttft_p99_seconds").set(v); + } + } + /// Gate 2 + 3 + 4: classify small-prefill requests onto the fast-P pool /// with least-wait selection and queue-wait rejection. /// /// `body` is the OpenAI chat request JSON. Non-chat routes must not call /// this. All probe failures fall back to the default routing path - /// (fail-open, metric emitted). + /// (fail-open, metric emitted). The returned label feeds the TTFT + /// histogram's `path` dimension ("fast_p" / "regular"). pub async fn classify_prefill( &self, registry: &WorkerRegistry, client: &Client, body: &Value, - ) -> PrefillPlan { + ) -> (PrefillPlan, &'static str) { let prefill_workers = registry.get_prefill_workers(); let fast_pool = self.fast_pool(&prefill_workers); if fast_pool.is_empty() { metrics::counter!(METRIC_DECISIONS, "path" => "fast_pool_empty").increment(1); - return PrefillPlan::Default; + return (self.regular_plan(&prefill_workers), "regular"); } // Probe for prefix-hit classification. Candidates in order: fast-P @@ -421,7 +527,7 @@ impl G9iState { if fast_sorted.is_empty() { metrics::counter!(METRIC_DECISIONS, "path" => "fast_pool_no_fresh_snapshot") .increment(1); - return self.regular_plan(&prefill_workers); + return (self.regular_plan(&prefill_workers), "regular"); } let regular: Vec<&Arc> = prefill_workers .iter() @@ -448,7 +554,7 @@ impl G9iState { // node, no point trying more. metrics::counter!(METRIC_DECISIONS, "path" => "query_unclassifiable") .increment(1); - return self.regular_plan(&prefill_workers); + return (self.regular_plan(&prefill_workers), "regular"); } Err(e) => { debug!("G9i probe failed on {}: {}", cand.url(), e); @@ -464,13 +570,13 @@ impl G9iState { last_err ); metrics::counter!(METRIC_DECISIONS, "path" => "query_error").increment(1); - return self.regular_plan(&prefill_workers); + return (self.regular_plan(&prefill_workers), "regular"); } }; if new_tokens >= self.config.max_new_tokens { metrics::counter!(METRIC_DECISIONS, "path" => "regular_large_prefill").increment(1); - return self.regular_plan(&prefill_workers); + return (self.regular_plan(&prefill_workers), "regular"); } // Small prefill -> fast-P pool, least-wait pick. @@ -479,15 +585,18 @@ impl G9iState { // Lost our snapshots between probe and pick; fail-open to regular. metrics::counter!(METRIC_DECISIONS, "path" => "fast_pool_no_fresh_snapshot") .increment(1); - return self.regular_plan(&prefill_workers); + return (self.regular_plan(&prefill_workers), "regular"); } let est_wait = if picked.is_some() { est_wait } else { 0.0 }; if est_wait > self.config.fast_p_queue_reject_secs { metrics::counter!(METRIC_REJECTS, "reason" => "fast_p_queue").increment(1); - return PrefillPlan::Reject(RejectInfo { - reason: "fast_p_queue", - estimated_wait_secs: Some(est_wait), - }); + return ( + PrefillPlan::Reject(RejectInfo { + reason: "fast_p_queue", + estimated_wait_secs: Some(est_wait), + }), + "fast_p", + ); } match picked { Some(w) => { @@ -499,9 +608,12 @@ impl G9iState { w.url(), est_wait, ); - PrefillPlan::Override(normalize_url(&w.url().to_string())) + ( + PrefillPlan::Override(normalize_url(&w.url().to_string())), + "fast_p", + ) } - None => self.regular_plan(&prefill_workers), + None => (self.regular_plan(&prefill_workers), "regular"), } } diff --git a/sgl-model-gateway/src/routers/http/pd_router.rs b/sgl-model-gateway/src/routers/http/pd_router.rs index 6889b10db2..9fb8b43f32 100644 --- a/sgl-model-gateway/src/routers/http/pd_router.rs +++ b/sgl-model-gateway/src/routers/http/pd_router.rs @@ -403,40 +403,44 @@ impl PDRouter { let shared_request = Arc::new(original_request.clone()); // G9i admission (router-side, zero engine changes). Computed once per - // request, outside the retry loop: our own 429s must never be retried. - let g9i_prefill_override: Option = if let Some(g9i) = &self.g9i { - if let Err(info) = g9i.check_decode_pool(&self.worker_registry).await { - metrics::counter!("smg_g9i_rejects_total", "reason" => info.reason) - .increment(1); - return super::g9i::reject_response(&info); - } - if context.route == "/v1/chat/completions" { - match serde_json::to_value(original_request) { - Ok(body) => { - match g9i - .classify_prefill(&self.worker_registry, &self.client, &body) - .await - .into_override() - { - Ok(override_url) => override_url, - Err(info) => { - metrics::counter!( - "smg_g9i_rejects_total", - "reason" => info.reason - ) - .increment(1); - return super::g9i::reject_response(&info); + // request, outside the retry loop: our own 429s must never be + // retried. `ttft_path` labels the TTFT histogram dimension for this + // request's eventual first-token sample. + let (g9i_prefill_override, g9i_ttft_path): (Option, &'static str) = + if let Some(g9i) = &self.g9i { + if let Err(info) = g9i.check_decode_pool(&self.worker_registry).await { + metrics::counter!("smg_g9i_rejects_total", "reason" => info.reason) + .increment(1); + return super::g9i::reject_response(&info); + } + if context.route == "/v1/chat/completions" { + match serde_json::to_value(original_request) { + Ok(body) => { + match g9i + .classify_prefill(&self.worker_registry, &self.client, &body) + .await + { + (plan, path) => match plan.into_override() { + Ok(override_url) => (override_url, path), + Err(info) => { + metrics::counter!( + "smg_g9i_rejects_total", + "reason" => info.reason + ) + .increment(1); + return super::g9i::reject_response(&info); + } + }, } } + Err(_) => (None, "regular"), } - Err(_) => None, + } else { + (None, "non_chat") } } else { - None - } - } else { - None - }; + (None, "untracked") + }; let response = RetryExecutor::execute_response_with_retry( &self.retry_config, @@ -527,6 +531,7 @@ impl PDRouter { Arc::clone(&prefill), Arc::clone(&decode), start_time, + g9i_ttft_path, ) .await; @@ -656,6 +661,7 @@ impl PDRouter { Some(response_headers), prefill, decode, + None, ) } else { // Handle non-streaming error response @@ -737,7 +743,8 @@ impl PDRouter { context: PDRequestContext<'_>, prefill: Arc, decode: Arc, - _start_time: Instant, + start_time: Instant, + g9i_path: &'static str, ) -> Response { // For non-streaming: use guard for automatic load management // For streaming: load will be managed in create_streaming_response @@ -957,6 +964,7 @@ impl PDRouter { Some(response_headers), prefill, decode, + Some((start_time, g9i_path)), ) } else { // Non-streaming response @@ -1197,11 +1205,23 @@ impl PDRouter { headers: Option, prefill: Arc, decode: Arc, + // TTFT sampling hook: Some((dispatch-entry instant, path label)) for + // real upstream streams; None for synthetic error envelopes (their + // "first chunk" is not a token — sampling them would poison the + // window with near-zero error samples) and for tests. + ttft: Option<(Instant, &'static str)>, ) -> Response { use crate::core::AttachedBody; let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + // G9i TTFT sample: record on the first upstream chunk — that moment is + // the request's time-to-first-token as seen by the gateway (dispatch + // entry -> first token). Non-streaming requests have no observable + // first-token moment and are not sampled. + let g9i_ttft = self.g9i.clone().zip(ttft); + let mut ttft_recorded = false; + // Uses select! to race stream.next() against tx.closed() so that // when the client disconnects the upstream HTTP connection is dropped // promptly, allowing the engine to abort the request. @@ -1232,6 +1252,16 @@ impl PDRouter { Some(Ok(chunk)) => { let is_done = memmem::find(&chunk, b"data: [DONE]").is_some(); + if !ttft_recorded { + ttft_recorded = true; + if let Some((g9i, (start_time, g9i_path))) = &g9i_ttft { + g9i.record_ttft( + g9i_path, + start_time.elapsed().as_secs_f64(), + ); + } + } + let result = if return_logprob && prefill_logprobs.is_some() { Self::merge_streaming_logprobs(prefill_logprobs.clone(), &chunk) .unwrap_or(chunk) @@ -2130,6 +2160,7 @@ mod tests { None, prefill_ref.clone(), decode_ref.clone(), + None, ); // Guards are now attached to response body, so load should be 1