Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
21 changes: 21 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,26 @@ pub struct HttpExchangeAdmission {
pub observer: Option<Arc<dyn WireBytesObserver>>,
pub denial: Option<InferenceError>,
pub observation_id: Option<String>,
/// 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<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; }

/// 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<String> {
Expand Down Expand Up @@ -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,
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
45 changes: 45 additions & 0 deletions crates/skippy-inference-api/src/http_exchange_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ 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]
Expand All @@ -42,6 +46,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 @@ -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")),
Expand Down Expand Up @@ -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]
),
}
}
}
}
}
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