From ee377b36f7382005b8a97348ddf122bff68a360f Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Thu, 26 Nov 2026 10:13:01 -0600 Subject: [PATCH 1/3] Use host-assigned exchange IDs for HTTP inference dispatch Ported-from: https://github.com/Mesh-LLM/mesh-llm/pull/3066 Source-commit: f604daa5e46d31928b8575a78a9356390131e04a --- crates/skippy-inference-api/src/hooks.rs | 7 ++- .../skippy-inference-api/src/http_exchange.rs | 21 +++++++++ .../src/http_exchange_tests.rs | 45 +++++++++++++++++++ .../src/frontend/backend/exchange_hooks.rs | 5 ++- .../src/frontend/backend/prepared_exchange.rs | 2 +- 5 files changed, 75 insertions(+), 5 deletions(-) diff --git a/crates/skippy-inference-api/src/hooks.rs b/crates/skippy-inference-api/src/hooks.rs index 100500de..3dac24b7 100644 --- a/crates/skippy-inference-api/src/hooks.rs +++ b/crates/skippy-inference-api/src/hooks.rs @@ -441,7 +441,7 @@ impl InferenceBackend for HookedInferenceBackend { mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { - let exchange_id = uuid::Uuid::new_v4().to_string(); + let exchange_id = crate::http_exchange::dispatch_exchange_id(); // Armed immediately after minting the exchange id — before // `before_chat_completion` and `on_effective_chat_completion` run — // so a future dropped during either of those pre-backend awaits @@ -519,6 +519,9 @@ impl InferenceBackend for HookedInferenceBackend { ); } } + if let Ok(response) = &mut result { + response.exchange_id = Some(exchange_id.clone()); + } let error_message; let terminal = match &result { Ok(response) => ChatCompletionOutcome::Success { response }, @@ -539,7 +542,7 @@ impl InferenceBackend for HookedInferenceBackend { mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { - let exchange_id = uuid::Uuid::new_v4().to_string(); + let exchange_id = crate::http_exchange::dispatch_exchange_id(); context.publish_exchange_id(exchange_id.clone()); // Same admission-time arming as `chat_completion_with_context` above // — see its comment. A future dropped while `before_chat_completion` diff --git a/crates/skippy-inference-api/src/http_exchange.rs b/crates/skippy-inference-api/src/http_exchange.rs index e80511ab..d26dba73 100644 --- a/crates/skippy-inference-api/src/http_exchange.rs +++ b/crates/skippy-inference-api/src/http_exchange.rs @@ -24,11 +24,26 @@ pub struct HttpExchangeAdmission { pub observer: Option>, pub denial: Option, pub observation_id: Option, + /// The exchange id the host named for this HTTP exchange. A typed dispatch + /// inside it takes this id ([`dispatch_exchange_id`]), so the + /// `X-Exchange-Id` response header, the request log and the host's own + /// exchange events all name the exchange the same way. + pub exchange_id: Option, /// Bounded host-validated metadata supplied before response headers commit. pub response_headers: Vec<(String, String)>, } tokio::task_local! { static HTTP_EXCHANGE_OBSERVATION: String; } +tokio::task_local! { static HTTP_EXCHANGE_ID: String; } + +/// The id for a typed dispatch's exchange: the one the host named at HTTP +/// admission ([`HttpExchangeAdmission::exchange_id`]) when there is one, a +/// fresh UUID otherwise. +pub fn dispatch_exchange_id() -> String { + HTTP_EXCHANGE_ID + .try_with(Clone::clone) + .unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()) +} /// Exact host-owned observation correlated with this typed backend dispatch. pub fn current_http_exchange_observation_id() -> Option { @@ -103,6 +118,12 @@ pub(crate) async fn http_exchange_middleware( Some(error) => error.into_response(), None => { let call = next.run(Request::from_parts(parts, Body::from(body))); + let call = async move { + match admission.exchange_id { + Some(id) => HTTP_EXCHANGE_ID.scope(id, call).await, + None => call.await, + } + }; match admission.observation_id { Some(id) => HTTP_EXCHANGE_OBSERVATION.scope(id, call).await, None => call.await, diff --git a/crates/skippy-inference-api/src/http_exchange_tests.rs b/crates/skippy-inference-api/src/http_exchange_tests.rs index 12847967..6f9c0807 100644 --- a/crates/skippy-inference-api/src/http_exchange_tests.rs +++ b/crates/skippy-inference-api/src/http_exchange_tests.rs @@ -27,6 +27,10 @@ struct Recorder { terminals: Mutex>, deny: bool, response_headers: Vec<(String, String)>, + /// The exchange id this host names at admission. + exchange_id: Option, + /// [`crate::http_exchange::dispatch_exchange_id`] as each dispatch saw it. + dispatched: Mutex>, } #[async_trait] @@ -42,6 +46,7 @@ impl HttpExchangePolicy for Arc { self.original.lock().unwrap().push(body.to_vec()); HttpExchangeAdmission { observation_id: None, + exchange_id: self.exchange_id.clone(), observer: Some(self.clone()), response_headers: self.response_headers.clone(), denial: self.deny.then(|| { @@ -75,6 +80,11 @@ struct Backend { impl Backend { fn count_call(&self, model: &str) -> InferenceResult<()> { self.calls.fetch_add(1, Ordering::SeqCst); + self.recorder + .dispatched + .lock() + .unwrap() + .push(crate::http_exchange::dispatch_exchange_id()); match model { "error" => Err(InferenceError::backend("failed backend")), "timeout" => Err(InferenceError::timeout("backend deadline")), @@ -293,3 +303,38 @@ async fn dropped_pending_stream_has_one_incomplete_terminal() { Some(WireBytesIncomplete::Cancelled) ); } + +/// A dispatch inside an exchange the host named takes that id on every +/// endpoint; without one, each dispatch gets a fresh id. +#[tokio::test] +async fn dispatch_takes_the_exchange_id_the_host_named() { + for path in ["/v1/chat/completions", "/v1/completions", "/v1/responses"] { + for stream in [false, true] { + for named in [Some("host-named-exchange"), None] { + let backend = Arc::new(Backend { + recorder: Arc::new(Recorder { + exchange_id: named.map(str::to_owned), + ..Recorder::default() + }), + calls: AtomicUsize::new(0), + }); + let response = crate::router(backend.clone()) + .oneshot(request(path, &request_body(path, stream, "tiny"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let _ = to_bytes(response.into_body(), 1024 * 1024).await.unwrap(); + let dispatched = backend.recorder.dispatched.lock().unwrap().clone(); + assert_eq!(dispatched.len(), 1, "{path} stream={stream}"); + match named { + Some(id) => assert_eq!(dispatched[0], id, "{path} stream={stream}"), + None => assert!( + uuid::Uuid::parse_str(&dispatched[0]).is_ok(), + "{path} stream={stream}: {}", + dispatched[0] + ), + } + } + } + } +} diff --git a/crates/skippy-serving/src/frontend/backend/exchange_hooks.rs b/crates/skippy-serving/src/frontend/backend/exchange_hooks.rs index 08fac396..dc9fa2d9 100644 --- a/crates/skippy-serving/src/frontend/backend/exchange_hooks.rs +++ b/crates/skippy-serving/src/frontend/backend/exchange_hooks.rs @@ -36,7 +36,8 @@ impl StageOpenAiBackend { let hooks = self.hook_policy.clone().filter(|hooks| { chat_skippy_hooks_enabled(&request) || hooks.requires_exchange_lifecycle() }); - let exchange_id = observation_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); + let exchange_id = observation_id + .unwrap_or_else(skippy_inference_api::http_exchange::dispatch_exchange_id); let mut guard = hooks .as_ref() .map(|hooks| TerminalGuard::new(hooks.clone(), request.clone(), exchange_id.clone())); @@ -166,7 +167,7 @@ impl StageOpenAiBackend { let hooks = self.hook_policy.clone().filter(|hooks| { chat_skippy_hooks_enabled(&request) || hooks.requires_exchange_lifecycle() }); - let exchange_id = uuid::Uuid::new_v4().to_string(); + let exchange_id = skippy_inference_api::http_exchange::dispatch_exchange_id(); let mut guard = hooks .as_ref() .map(|hooks| TerminalGuard::new(hooks.clone(), request.clone(), exchange_id.clone())); diff --git a/crates/skippy-serving/src/frontend/backend/prepared_exchange.rs b/crates/skippy-serving/src/frontend/backend/prepared_exchange.rs index f84ad6c0..0eedb25b 100644 --- a/crates/skippy-serving/src/frontend/backend/prepared_exchange.rs +++ b/crates/skippy-serving/src/frontend/backend/prepared_exchange.rs @@ -69,7 +69,7 @@ impl StageOpenAiBackend { else { return Ok(None); }; - let id = uuid::Uuid::new_v4().to_string(); + let id = skippy_inference_api::http_exchange::dispatch_exchange_id(); let mut guard = super::completion_exchange::CompletionTerminalGuard::new(hooks.clone(), id.clone()); if let Err(error) = hooks.admit_effective_completion(request, &id).await { From df9dd40708a9c1d964c7a022af7e6887cacc1c11 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 28 Nov 2026 12:10:04 +1100 Subject: [PATCH 2/3] Let HTTP hosts publish headers for their exchange IDs Signed-off-by: James Dumay --- .../skippy-inference-api/src/http_exchange.rs | 28 +++++++++---- .../src/http_exchange_tests.rs | 40 +++++++++++++++---- crates/skippy-inference-api/src/router.rs | 12 +++++- 3 files changed, 63 insertions(+), 17 deletions(-) diff --git a/crates/skippy-inference-api/src/http_exchange.rs b/crates/skippy-inference-api/src/http_exchange.rs index d26dba73..f6339486 100644 --- a/crates/skippy-inference-api/src/http_exchange.rs +++ b/crates/skippy-inference-api/src/http_exchange.rs @@ -24,10 +24,8 @@ pub struct HttpExchangeAdmission { pub observer: Option>, pub denial: Option, pub observation_id: Option, - /// The exchange id the host named for this HTTP exchange. A typed dispatch - /// inside it takes this id ([`dispatch_exchange_id`]), so the - /// `X-Exchange-Id` response header, the request log and the host's own - /// exchange events all name the exchange the same way. + /// Opaque host-assigned ID for dispatch and request-log correlation. + /// The host decides how to expose it in [`HttpExchangePolicy::write_response_headers`]. pub exchange_id: Option, /// Bounded host-validated metadata supplied before response headers commit. pub response_headers: Vec<(String, String)>, @@ -36,13 +34,18 @@ pub struct HttpExchangeAdmission { tokio::task_local! { static HTTP_EXCHANGE_OBSERVATION: String; } tokio::task_local! { static HTTP_EXCHANGE_ID: String; } +#[derive(Clone)] +pub(crate) struct HostExchangeId(pub(crate) String); + /// The id for a typed dispatch's exchange: the one the host named at HTTP /// admission ([`HttpExchangeAdmission::exchange_id`]) when there is one, a /// fresh UUID otherwise. pub fn dispatch_exchange_id() -> String { - HTTP_EXCHANGE_ID - .try_with(Clone::clone) - .unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()) + current_host_exchange_id().unwrap_or_else(|| uuid::Uuid::new_v4().to_string()) +} + +pub(crate) fn current_host_exchange_id() -> Option { + HTTP_EXCHANGE_ID.try_with(Clone::clone).ok() } /// Exact host-owned observation correlated with this typed backend dispatch. @@ -60,6 +63,9 @@ pub trait HttpExchangePolicy: Send + Sync + 'static { async fn is_enabled(&self) -> bool { true } + /// Add trusted host headers for the opaque ID named at admission. + fn write_response_headers(&self, _exchange_id: &str, _headers: &mut HeaderMap) {} + async fn received( &self, method: &str, @@ -114,12 +120,14 @@ pub(crate) async fn http_exchange_middleware( request_id, ) .await; + let host_exchange_id = admission.exchange_id; let mut response = match admission.denial { Some(error) => error.into_response(), None => { let call = next.run(Request::from_parts(parts, Body::from(body))); + let scoped_exchange_id = host_exchange_id.clone(); let call = async move { - match admission.exchange_id { + match scoped_exchange_id { Some(id) => HTTP_EXCHANGE_ID.scope(id, call).await, None => call.await, } @@ -151,6 +159,10 @@ pub(crate) async fn http_exchange_middleware( response.headers_mut().append(name, value); } } + if let Some(id) = host_exchange_id { + policy.write_response_headers(&id, response.headers_mut()); + response.extensions_mut().insert(HostExchangeId(id)); + } match admission.observer { Some(observer) => { observer.response_status(response.status().as_u16()); diff --git a/crates/skippy-inference-api/src/http_exchange_tests.rs b/crates/skippy-inference-api/src/http_exchange_tests.rs index 6f9c0807..d11aa16a 100644 --- a/crates/skippy-inference-api/src/http_exchange_tests.rs +++ b/crates/skippy-inference-api/src/http_exchange_tests.rs @@ -16,7 +16,7 @@ use tower::ServiceExt; use crate::{ CompletionChunk, CompletionRequest, CompletionResponse, CompletionStream, InferenceBackend, InferenceError, InferenceRequestContext, InferenceResult, ModelObject, RequestId, Usage, - http_exchange::{HttpExchangeAdmission, HttpExchangePolicy}, + http_exchange::{HostExchangeId, HttpExchangeAdmission, HttpExchangePolicy}, wire_bytes::{WireBytesCommitment, WireBytesIncomplete, WireBytesObserver, commit_wire_bytes}, }; @@ -35,6 +35,10 @@ struct Recorder { #[async_trait] impl HttpExchangePolicy for Arc { + fn write_response_headers(&self, exchange_id: &str, headers: &mut HeaderMap) { + headers.insert("x-host-test-id", exchange_id.parse().unwrap()); + } + async fn received( &self, _method: &str, @@ -78,17 +82,18 @@ struct Backend { } impl Backend { - fn count_call(&self, model: &str) -> InferenceResult<()> { + fn count_call(&self, model: &str) -> InferenceResult { self.calls.fetch_add(1, Ordering::SeqCst); + let exchange_id = crate::http_exchange::dispatch_exchange_id(); self.recorder .dispatched .lock() .unwrap() - .push(crate::http_exchange::dispatch_exchange_id()); + .push(exchange_id.clone()); match model { "error" => Err(InferenceError::backend("failed backend")), "timeout" => Err(InferenceError::timeout("backend deadline")), - _ => Ok(()), + _ => Ok(exchange_id), } } } @@ -105,18 +110,19 @@ impl InferenceBackend for Backend { &self, request: GenerationRequest, ) -> InferenceResult { - self.count_call(&request.model)?; + let exchange_id = self.count_call(&request.model)?; let mut response = GenerationResponse::new(request.model, "hello", Usage::new(2, 1)); response.id = "fixed".into(); response.created = 1; + response.exchange_id = Some(exchange_id); Ok(response) } async fn chat_completion_stream( &self, request: GenerationRequest, - _context: InferenceRequestContext, + context: InferenceRequestContext, ) -> InferenceResult { - self.count_call(&request.model)?; + context.publish_exchange_id(self.count_call(&request.model)?); if request.model == "pending" { return Ok(Box::pin(futures_util::stream::pending())); } @@ -323,9 +329,29 @@ async fn dispatch_takes_the_exchange_id_the_host_named() { .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); + let host_id = response.extensions().get::(); + assert_eq!(host_id.map(|id| id.0.as_str()), named); + let host_header = response + .headers() + .get("x-host-test-id") + .map(|value| value.to_str().unwrap()); + assert_eq!(host_header, named); + let header = response + .headers() + .get("x-exchange-id") + .map(|value| value.to_str().unwrap().to_owned()); + let backend_reports_id = path != "/v1/completions"; + assert_eq!( + header.is_some(), + named.is_none() && backend_reports_id, + "{path} stream={stream}" + ); let _ = to_bytes(response.into_body(), 1024 * 1024).await.unwrap(); let dispatched = backend.recorder.dispatched.lock().unwrap().clone(); assert_eq!(dispatched.len(), 1, "{path} stream={stream}"); + if let Some(header) = header { + assert_eq!(header, dispatched[0], "{path} stream={stream}"); + } match named { Some(id) => assert_eq!(dispatched[0], id, "{path} stream={stream}"), None => assert!( diff --git a/crates/skippy-inference-api/src/router.rs b/crates/skippy-inference-api/src/router.rs index 04a21ff3..1d1db0bf 100644 --- a/crates/skippy-inference-api/src/router.rs +++ b/crates/skippy-inference-api/src/router.rs @@ -793,6 +793,9 @@ pub(crate) fn request_context( observe_stream_usage: bool, ) -> InferenceRequestContext { let mut context = InferenceRequestContext::with_request_id(request_id); + if let Some(id) = crate::http_exchange::current_host_exchange_id() { + context.publish_exchange_id(id); + } if trusted_agent_session { context = context.with_trusted_agent_session(); } @@ -899,7 +902,12 @@ async fn frontend_lifecycle_middleware( .extensions() .get::() .map(|extension| extension.0.clone()); - if let Some(exchange_id) = &exchange_id + let host_exchange_id = response + .extensions() + .get::() + .map(|id| id.0.clone()); + if host_exchange_id.is_none() + && let Some(exchange_id) = &exchange_id && let Ok(value) = HeaderValue::from_str(exchange_id) { response @@ -913,7 +921,7 @@ async fn frontend_lifecycle_middleware( .extensions() .get::() .map(|usage| usage.0); - lifecycle.finish_with_usage(response.status(), usage, exchange_id); + lifecycle.finish_with_usage(response.status(), usage, host_exchange_id.or(exchange_id)); } tracing::info!( request_id = %request_id.as_ref(), From cfd67d96fabad2631bd520241c4055cf05970995 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 07:47:00 +1100 Subject: [PATCH 3/3] Fix host exchange ID publication and prepared dispatch identity --- .../skippy-inference-api/src/http_exchange.rs | 9 +- .../src/http_exchange_tests.rs | 71 ++++++- crates/skippy-serving/src/frontend/backend.rs | 2 + .../src/frontend/backend/exchange_hooks.rs | 18 +- .../frontend/backend/http_exchange_tests.rs | 177 ++++++++++++++++++ .../src/frontend/backend/inference.rs | 3 +- .../backend/prepared_exchange_tests.rs | 7 +- 7 files changed, 267 insertions(+), 20 deletions(-) create mode 100644 crates/skippy-serving/src/frontend/backend/http_exchange_tests.rs diff --git a/crates/skippy-inference-api/src/http_exchange.rs b/crates/skippy-inference-api/src/http_exchange.rs index f6339486..7740c383 100644 --- a/crates/skippy-inference-api/src/http_exchange.rs +++ b/crates/skippy-inference-api/src/http_exchange.rs @@ -23,9 +23,11 @@ use crate::{ pub struct HttpExchangeAdmission { pub observer: Option>, pub denial: Option, + /// Observation metadata, independent of the dispatch exchange ID. pub observation_id: Option, /// Opaque host-assigned ID for dispatch and request-log correlation. - /// The host decides how to expose it in [`HttpExchangePolicy::write_response_headers`]. + /// Published as `X-Exchange-Id` when header-safe; the host can customize + /// that header in [`HttpExchangePolicy::write_response_headers`]. pub exchange_id: Option, /// Bounded host-validated metadata supplied before response headers commit. pub response_headers: Vec<(String, String)>, @@ -63,7 +65,7 @@ pub trait HttpExchangePolicy: Send + Sync + 'static { async fn is_enabled(&self) -> bool { true } - /// Add trusted host headers for the opaque ID named at admission. + /// Customize trusted host headers after the default `X-Exchange-Id` is set. fn write_response_headers(&self, _exchange_id: &str, _headers: &mut HeaderMap) {} async fn received( @@ -160,6 +162,9 @@ pub(crate) async fn http_exchange_middleware( } } if let Some(id) = host_exchange_id { + if let Ok(value) = axum::http::HeaderValue::from_str(&id) { + response.headers_mut().insert("x-exchange-id", value); + } policy.write_response_headers(&id, response.headers_mut()); response.extensions_mut().insert(HostExchangeId(id)); } diff --git a/crates/skippy-inference-api/src/http_exchange_tests.rs b/crates/skippy-inference-api/src/http_exchange_tests.rs index d11aa16a..c60e7c27 100644 --- a/crates/skippy-inference-api/src/http_exchange_tests.rs +++ b/crates/skippy-inference-api/src/http_exchange_tests.rs @@ -343,7 +343,7 @@ async fn dispatch_takes_the_exchange_id_the_host_named() { let backend_reports_id = path != "/v1/completions"; assert_eq!( header.is_some(), - named.is_none() && backend_reports_id, + named.is_some() || backend_reports_id, "{path} stream={stream}" ); let _ = to_bytes(response.into_body(), 1024 * 1024).await.unwrap(); @@ -364,3 +364,72 @@ async fn dispatch_takes_the_exchange_id_the_host_named() { } } } + +#[derive(Default)] +struct HookIds { + routes: Mutex>, + terminals: Mutex>, +} + +#[async_trait] +impl crate::InferenceHookPolicy for HookIds { + fn requires_exchange_lifecycle(&self) -> bool { + true + } + + async fn on_effective_chat_completion( + &self, + _request: &GenerationRequest, + route: &crate::ChatExchangeRoute, + ) { + self.routes.lock().unwrap().push(route.exchange_id.clone()); + } + + async fn on_chat_completion_terminal( + &self, + _request: &GenerationRequest, + exchange_id: &str, + outcome: &crate::ChatCompletionOutcome<'_>, + ) { + match outcome { + crate::ChatCompletionOutcome::Success { response } => { + assert_eq!(response.exchange_id.as_deref(), Some(exchange_id)); + } + crate::ChatCompletionOutcome::StreamCompleted => {} + _ => panic!("unexpected terminal outcome"), + } + self.terminals.lock().unwrap().push(exchange_id.into()); + } +} + +#[tokio::test] +async fn hooked_backend_uses_host_id_for_route_response_and_terminal() { + for stream in [false, true] { + let backend = Arc::new(Backend { + recorder: Arc::new(Recorder { + exchange_id: Some("host-exchange".into()), + ..Default::default() + }), + calls: AtomicUsize::new(0), + }); + let hooks = Arc::new(HookIds::default()); + let hooked = crate::HookedInferenceBackend::new(backend, hooks.clone()); + let path = "/v1/chat/completions"; + let response = crate::router(Arc::new(hooked)) + .oneshot(request(path, &request_body(path, stream, "tiny"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["x-exchange-id"], "host-exchange"); + let _ = to_bytes(response.into_body(), 1024 * 1024).await.unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(2), async { + while hooks.terminals.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .expect("stream terminal delivered"); + assert_eq!(*hooks.routes.lock().unwrap(), ["host-exchange"]); + assert_eq!(*hooks.terminals.lock().unwrap(), ["host-exchange"]); + } +} diff --git a/crates/skippy-serving/src/frontend/backend.rs b/crates/skippy-serving/src/frontend/backend.rs index 04fe4c54..1e7b0a97 100644 --- a/crates/skippy-serving/src/frontend/backend.rs +++ b/crates/skippy-serving/src/frontend/backend.rs @@ -1,5 +1,7 @@ mod completion_exchange; mod exchange_hooks; +#[cfg(test)] +mod http_exchange_tests; mod inference; mod phase_spans; mod prepared_exchange; diff --git a/crates/skippy-serving/src/frontend/backend/exchange_hooks.rs b/crates/skippy-serving/src/frontend/backend/exchange_hooks.rs index dc9fa2d9..65a78f03 100644 --- a/crates/skippy-serving/src/frontend/backend/exchange_hooks.rs +++ b/crates/skippy-serving/src/frontend/backend/exchange_hooks.rs @@ -12,21 +12,16 @@ impl StageOpenAiBackend { F: FnOnce(GenerationRequest) -> Fut, Fut: std::future::Future>, { - self.chat_completion_with_prepared_hooks_for_exchange( - request, - None, - move |request, admission| async move { - admission.admit(&request).await?; - dispatch(request).await - }, - ) + self.chat_completion_with_prepared_hooks(request, move |request, admission| async move { + admission.admit(&request).await?; + dispatch(request).await + }) .await } - pub(super) async fn chat_completion_with_prepared_hooks_for_exchange( + pub(super) async fn chat_completion_with_prepared_hooks( &self, mut request: GenerationRequest, - observation_id: Option, dispatch: F, ) -> InferenceResult where @@ -36,8 +31,7 @@ impl StageOpenAiBackend { let hooks = self.hook_policy.clone().filter(|hooks| { chat_skippy_hooks_enabled(&request) || hooks.requires_exchange_lifecycle() }); - let exchange_id = observation_id - .unwrap_or_else(skippy_inference_api::http_exchange::dispatch_exchange_id); + let exchange_id = skippy_inference_api::http_exchange::dispatch_exchange_id(); let mut guard = hooks .as_ref() .map(|hooks| TerminalGuard::new(hooks.clone(), request.clone(), exchange_id.clone())); diff --git a/crates/skippy-serving/src/frontend/backend/http_exchange_tests.rs b/crates/skippy-serving/src/frontend/backend/http_exchange_tests.rs new file mode 100644 index 00000000..49f2ed50 --- /dev/null +++ b/crates/skippy-serving/src/frontend/backend/http_exchange_tests.rs @@ -0,0 +1,177 @@ +//! Exercise the production router and prepared hook pipeline without model generation. +use super::*; +use axum::{ + body::{Body, to_bytes}, + http::{HeaderMap, Request, StatusCode}, +}; +use skippy_inference_api::{ + InferenceFrontendConfig, InferenceHookPolicy, RequestId, Usage, + generation::GenerationEvent, + http_exchange::{ + HttpExchangeAdmission, HttpExchangePolicy, current_http_exchange_observation_id, + }, +}; +use tower::ServiceExt; + +const HOST_ID: &str = "host-exchange"; +const OBSERVATION_ID: &str = "separate-observation"; + +struct HostAdmission; + +#[async_trait] +impl HttpExchangePolicy for HostAdmission { + async fn received( + &self, + _method: &str, + _path: &str, + _headers: &HeaderMap, + _body: &[u8], + _request_id: RequestId, + ) -> HttpExchangeAdmission { + HttpExchangeAdmission { + exchange_id: Some(HOST_ID.into()), + observation_id: Some(OBSERVATION_ID.into()), + ..Default::default() + } + } +} + +#[derive(Default)] +struct HookIds { + admissions: Mutex>, + routes: Mutex>, + terminals: Mutex>, +} + +#[async_trait] +impl InferenceHookPolicy for HookIds { + fn requires_exchange_lifecycle(&self) -> bool { + true + } + async fn admit_effective_chat_completion( + &self, + _request: &GenerationRequest, + route: &ChatExchangeRoute, + ) -> InferenceResult<()> { + assert_eq!( + current_http_exchange_observation_id().as_deref(), + Some(OBSERVATION_ID) + ); + self.admissions + .lock() + .unwrap() + .push(route.exchange_id.clone()); + Ok(()) + } + async fn on_effective_chat_completion( + &self, + _request: &GenerationRequest, + route: &ChatExchangeRoute, + ) { + self.routes.lock().unwrap().push(route.exchange_id.clone()); + } + async fn on_chat_completion_terminal( + &self, + _request: &GenerationRequest, + id: &str, + outcome: &ChatCompletionOutcome<'_>, + ) { + match outcome { + ChatCompletionOutcome::Success { response } => { + assert_eq!(response.exchange_id.as_deref(), Some(HOST_ID)); + } + ChatCompletionOutcome::StreamCompleted => {} + _ => panic!("unexpected terminal outcome"), + } + self.terminals.lock().unwrap().push(id.into()); + } +} + +// Only generation is substituted: the serving hooks and HTTP routing are real. +struct PreparedBackend(StageOpenAiBackend); + +#[async_trait] +impl InferenceBackend for PreparedBackend { + async fn models(&self) -> InferenceResult> { + Ok(Vec::new()) + } + async fn chat_completion( + &self, + request: GenerationRequest, + ) -> InferenceResult { + self.0 + .chat_completion_with_prepared_hooks(request, |request, admission| async move { + admission.admit(&request).await?; + Ok(GenerationResponse::new( + request.model, + "hello", + Usage::new(2, 1), + )) + }) + .await + } + async fn chat_completion_stream( + &self, + request: GenerationRequest, + context: InferenceRequestContext, + ) -> InferenceResult { + self.0 + .chat_completion_stream_with_prepared_hooks( + request, + &context, + |request, admission| async move { + admission.admit(&request).await?; + let events = stream::iter([Ok(GenerationEvent::done(request.model))]); + Ok(Box::pin(events) as GenerationEventStream) + }, + ) + .await + } +} + +#[tokio::test] +async fn host_id_reaches_prepared_hooks_and_headers_independently_of_lifecycle_hooks() { + for tracked in [false, true] { + for stream in [false, true] { + let hooks = Arc::new(HookIds::default()); + let policy = tracked.then(|| hooks.clone() as Arc); + let backend = PreparedBackend(super::tests::hooks_test_backend(policy)); + let config = InferenceFrontendConfig::default() + .with_http_exchange_policy(Arc::new(HostAdmission)); + let request = Request::builder() + .method("POST") + .uri("/v1/chat/completions") + .header("content-type", "application/json") + .body(Body::from( + json!({ + "model": "tiny", + "messages": [{"role": "user", "content": "hi"}], + "skippy_hooks": false, + "stream": stream, + }) + .to_string(), + )) + .unwrap(); + let response = skippy_inference_api::router_with_config(Arc::new(backend), config) + .oneshot(request) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["x-exchange-id"], HOST_ID); + let _ = to_bytes(response.into_body(), 1024 * 1024).await.unwrap(); + if tracked { + tokio::time::timeout(Duration::from_secs(2), async { + while hooks.terminals.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .expect("stream terminal delivered"); + } + let expected = if tracked { vec![HOST_ID] } else { vec![] }; + assert_eq!(*hooks.admissions.lock().unwrap(), expected); + assert_eq!(*hooks.routes.lock().unwrap(), expected); + assert_eq!(*hooks.terminals.lock().unwrap(), expected); + } + } +} diff --git a/crates/skippy-serving/src/frontend/backend/inference.rs b/crates/skippy-serving/src/frontend/backend/inference.rs index 7fbf61ce..edc949f4 100644 --- a/crates/skippy-serving/src/frontend/backend/inference.rs +++ b/crates/skippy-serving/src/frontend/backend/inference.rs @@ -47,9 +47,8 @@ impl InferenceBackend for StageOpenAiBackend { ); let request_timer = PhaseTimer::start(); let _request = self.enter_openai_summary_task(&request_timer); - self.chat_completion_with_prepared_hooks_for_exchange( + self.chat_completion_with_prepared_hooks( request, - None, move |mut request, admission| async move { self.ensure_model(&request.model)?; let (request_defaults, defaults_diagnostics) = diff --git a/crates/skippy-serving/src/frontend/backend/prepared_exchange_tests.rs b/crates/skippy-serving/src/frontend/backend/prepared_exchange_tests.rs index 147be311..1bfe62e5 100644 --- a/crates/skippy-serving/src/frontend/backend/prepared_exchange_tests.rs +++ b/crates/skippy-serving/src/frontend/backend/prepared_exchange_tests.rs @@ -46,9 +46,8 @@ async fn prepared_admission_denies_after_preparation_before_generation() { let generated = Arc::new(std::sync::atomic::AtomicBool::new(false)); let marker = generated.clone(); let result = backend - .chat_completion_with_prepared_hooks_for_exchange( + .chat_completion_with_prepared_hooks( GenerationRequest::default(), - Some("exchange".into()), move |mut request, admission| async move { // This models defaults/template preparation inside the dispatch closure. request.model = "prepared-denied".into(); @@ -60,6 +59,8 @@ async fn prepared_admission_denies_after_preparation_before_generation() { .await; assert!(result.is_err()); assert!(!generated.load(std::sync::atomic::Ordering::SeqCst)); - assert_eq!(*policy.seen.lock().unwrap(), ["exchange"]); + let seen = policy.seen.lock().unwrap(); + assert_eq!(seen.len(), 1); + assert!(uuid::Uuid::parse_str(&seen[0]).is_ok()); assert_eq!(*policy.terminals.lock().unwrap(), ["prepared-denied"]); }