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: 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
33 changes: 33 additions & 0 deletions crates/skippy-inference-api/src/http_exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,29 @@ pub struct HttpExchangeAdmission {
pub observer: Option<Arc<dyn WireBytesObserver>>,
pub denial: Option<InferenceError>,
pub observation_id: Option<String>,
/// 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<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 +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,
Expand Down Expand Up @@ -99,10 +120,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 +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());
Expand Down
83 changes: 77 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,58 @@ 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_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!(
uuid::Uuid::parse_str(&dispatched[0]).is_ok(),
"{path} stream={stream}: {}",
dispatched[0]
),
}
}
}
}
}
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
5 changes: 3 additions & 2 deletions crates/skippy-serving/src/frontend/backend/exchange_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
Expand Down Expand Up @@ -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()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading