Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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: 5 additions & 2 deletions crates/skippy-inference-api/src/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ impl InferenceBackend for HookedInferenceBackend {
mut request: GenerationRequest,
context: InferenceRequestContext,
) -> InferenceResult<GenerationResponse> {
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
Expand Down Expand Up @@ -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 },
Expand All @@ -539,7 +542,7 @@ impl InferenceBackend for HookedInferenceBackend {
mut request: GenerationRequest,
context: InferenceRequestContext,
) -> InferenceResult<GenerationEventStream> {
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`
Expand Down
38 changes: 38 additions & 0 deletions crates/skippy-inference-api/src/http_exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,32 @@ use crate::{
pub struct HttpExchangeAdmission {
pub observer: Option<Arc<dyn WireBytesObserver>>,
pub denial: Option<InferenceError>,
/// Observation metadata, independent of the dispatch exchange ID.
pub observation_id: Option<String>,
/// Opaque host-assigned ID for dispatch and request-log correlation.
/// Published as `X-Exchange-Id` when header-safe; the host can customize
/// that header in [`HttpExchangePolicy::write_response_headers`].
pub exchange_id: Option<String>,
/// 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; }

#[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 {
current_host_exchange_id().unwrap_or_else(|| uuid::Uuid::new_v4().to_string())
}

pub(crate) fn current_host_exchange_id() -> Option<String> {
HTTP_EXCHANGE_ID.try_with(Clone::clone).ok()
}

/// Exact host-owned observation correlated with this typed backend dispatch.
pub fn current_http_exchange_observation_id() -> Option<String> {
Expand All @@ -45,6 +65,9 @@ pub trait HttpExchangePolicy: Send + Sync + 'static {
async fn is_enabled(&self) -> bool {
true
}
/// 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(
&self,
method: &str,
Expand Down Expand Up @@ -99,10 +122,18 @@ 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 scoped_exchange_id {
Some(id) => HTTP_EXCHANGE_ID.scope(id, call).await,
Comment thread
i386 marked this conversation as resolved.
Resolved
None => call.await,
}
};
match admission.observation_id {
Some(id) => HTTP_EXCHANGE_OBSERVATION.scope(id, call).await,
None => call.await,
Expand Down Expand Up @@ -130,6 +161,13 @@ pub(crate) async fn http_exchange_middleware(
response.headers_mut().append(name, value);
}
}
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));
}
match admission.observer {
Some(observer) => {
observer.response_status(response.status().as_u16());
Expand Down
152 changes: 146 additions & 6 deletions crates/skippy-inference-api/src/http_exchange_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
};

Expand All @@ -27,10 +27,18 @@ struct Recorder {
terminals: Mutex<Vec<WireBytesCommitment>>,
deny: bool,
response_headers: Vec<(String, String)>,
/// The exchange id this host names at admission.
exchange_id: Option<String>,
/// [`crate::http_exchange::dispatch_exchange_id`] as each dispatch saw it.
dispatched: Mutex<Vec<String>>,
}

#[async_trait]
impl HttpExchangePolicy for Arc<Recorder> {
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,
Expand All @@ -42,6 +50,7 @@ impl HttpExchangePolicy for Arc<Recorder> {
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(|| {
Expand Down Expand Up @@ -73,12 +82,18 @@ struct Backend {
}

impl Backend {
fn count_call(&self, model: &str) -> InferenceResult<()> {
fn count_call(&self, model: &str) -> InferenceResult<String> {
self.calls.fetch_add(1, Ordering::SeqCst);
let exchange_id = crate::http_exchange::dispatch_exchange_id();
self.recorder
.dispatched
.lock()
.unwrap()
.push(exchange_id.clone());
match model {
"error" => Err(InferenceError::backend("failed backend")),
"timeout" => Err(InferenceError::timeout("backend deadline")),
_ => Ok(()),
_ => Ok(exchange_id),
}
}
}
Expand All @@ -95,18 +110,19 @@ impl InferenceBackend for Backend {
&self,
request: GenerationRequest,
) -> InferenceResult<GenerationResponse> {
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<GenerationEventStream> {
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()));
}
Expand Down Expand Up @@ -293,3 +309,127 @@ 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 host_id = response.extensions().get::<HostExchangeId>();
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_some() || 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!(
uuid::Uuid::parse_str(&dispatched[0]).is_ok(),
"{path} stream={stream}: {}",
dispatched[0]
),
}
}
}
}
}

#[derive(Default)]
struct HookIds {
routes: Mutex<Vec<String>>,
terminals: Mutex<Vec<String>>,
}

#[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"]);
}
}
12 changes: 10 additions & 2 deletions crates/skippy-inference-api/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Comment thread
i386 marked this conversation as resolved.
Resolved
if trusted_agent_session {
context = context.with_trusted_agent_session();
}
Expand Down Expand Up @@ -899,7 +902,12 @@ async fn frontend_lifecycle_middleware(
.extensions()
.get::<ExchangeIdExtension>()
.map(|extension| extension.0.clone());
if let Some(exchange_id) = &exchange_id
let host_exchange_id = response
.extensions()
.get::<crate::http_exchange::HostExchangeId>()
.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
Expand All @@ -913,7 +921,7 @@ async fn frontend_lifecycle_middleware(
.extensions()
.get::<TerminalUsage>()
.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(),
Expand Down
2 changes: 2 additions & 0 deletions crates/skippy-serving/src/frontend/backend.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
mod completion_exchange;
mod exchange_hooks;
#[cfg(test)]
mod http_exchange_tests;
mod inference;
mod phase_spans;
mod prepared_exchange;
Expand Down
19 changes: 7 additions & 12 deletions crates/skippy-serving/src/frontend/backend/exchange_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,16 @@ impl StageOpenAiBackend {
F: FnOnce(GenerationRequest) -> Fut,
Fut: std::future::Future<Output = InferenceResult<GenerationResponse>>,
{
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<F, Fut>(
pub(super) async fn chat_completion_with_prepared_hooks<F, Fut>(
&self,
mut request: GenerationRequest,
observation_id: Option<String>,
dispatch: F,
) -> InferenceResult<GenerationResponse>
where
Expand All @@ -36,7 +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(|| 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()));
Expand Down Expand Up @@ -166,7 +161,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()));
Expand Down
Loading
Loading