diff --git a/crates/gateway-domain/src/responses/effort.rs b/crates/gateway-domain/src/responses/effort.rs index b15c0048..edfd1a80 100644 --- a/crates/gateway-domain/src/responses/effort.rs +++ b/crates/gateway-domain/src/responses/effort.rs @@ -56,7 +56,7 @@ fn effort_level(effort: Option<&Value>) -> Result`. gpt-oss always reasons. +/// Whether the output starts inside a reasoning block that ends with ``. gpt-oss always reasons. pub fn reasoning_enabled(request: &CreateRequest, family: Family) -> bool { family == Family::GptOss || reasoning_effort(request).is_ok_and(|effort| effort != Effort::None) } diff --git a/crates/gateway-domain/src/responses/tool_calls.rs b/crates/gateway-domain/src/responses/tool_calls.rs index 9790898d..28c83a4d 100644 --- a/crates/gateway-domain/src/responses/tool_calls.rs +++ b/crates/gateway-domain/src/responses/tool_calls.rs @@ -102,8 +102,8 @@ pub fn decode_generation_noted( const THINK_END: &[u8] = b""; /// The text has a `` at byte `boundary`: the reasoning before it, the answer after it. -fn decode_closed( - tokenizer: &dyn TextCodec, +fn decode_closed( + tokenizer: &T, ids: &[u32], bytes: &[u8], boundary: usize, @@ -139,8 +139,8 @@ struct Unclosed<'a> { } /// The text has no ``. -fn decode_unclosed( - tokenizer: &dyn TextCodec, +fn decode_unclosed( + tokenizer: &T, ids: &[u32], bytes: &[u8], unclosed: Unclosed<'_>, @@ -171,7 +171,11 @@ fn decode_unclosed( } /// The tokens whose text lies before byte `at`. -fn tokens_before(tokenizer: &dyn TextCodec, ids: &[u32], at: usize) -> Result { +fn tokens_before( + tokenizer: &T, + ids: &[u32], + at: usize, +) -> Result { let mut consumed = 0; let mut tokens = 0; let mut decoder = tokenizer.decoder(); diff --git a/crates/gateway-domain/src/responses/trace.rs b/crates/gateway-domain/src/responses/trace.rs index 400bc6e2..b90b564f 100644 --- a/crates/gateway-domain/src/responses/trace.rs +++ b/crates/gateway-domain/src/responses/trace.rs @@ -1,4 +1,5 @@ -///! The Responses object and its event stream, built from a request, the output items and the usage. +//! The Responses object and its event stream, built from a request, the output items and the usage. + use crate::responses::output::{OutputItem, Usage}; use crate::responses::request::CreateRequest; use crate::responses::trace_items::ItemWriter; diff --git a/crates/gateway-domain/src/responses/trace_items.rs b/crates/gateway-domain/src/responses/trace_items.rs index 78b07873..eae203b2 100644 --- a/crates/gateway-domain/src/responses/trace_items.rs +++ b/crates/gateway-domain/src/responses/trace_items.rs @@ -9,6 +9,13 @@ use leleka_gateway_text::response_tools::{self, Catalog}; use serde_json::{Value, json}; use std::collections::HashSet; +const PART_ADDED: &str = "response.content_part.added"; +const PART_DONE: &str = "response.content_part.done"; +const REASONING_DELTA: &str = "response.reasoning_text.delta"; +const REASONING_DONE: &str = "response.reasoning_text.done"; +const TEXT_DELTA: &str = "response.output_text.delta"; +const TEXT_DONE: &str = "response.output_text.done"; + /// What the output items accumulate while their events are written. pub(super) struct ItemWriter<'a> { id: &'a str, @@ -21,6 +28,42 @@ pub(super) struct ItemWriter<'a> { has_text: bool, } +/// Where an item sits in the response: its id and its output index. +struct Slot { + item_id: String, + index: usize, +} + +impl Slot { + fn new(prefix: &str, response_id: &str, index: usize) -> Self { + Self { + item_id: format!("{prefix}_{}_{}", &response_id[5..], index), + index, + } + } +} + +/// The fields after the ids of a content part event. +type Tail = Vec<(&'static str, Value)>; + +fn one(key: &'static str, value: Value) -> Tail { + vec![(key, value)] +} + +fn with_logprobs(key: &'static str, value: Value) -> Tail { + vec![(key, value), ("logprobs", json!([]))] +} + +fn reasoning_item(slot: &Slot, status: &str, content: Value) -> Value { + json!({"id": slot.item_id, "type": "reasoning", "status": status, "summary": [], "content": content}) +} + +fn message_item(slot: &Slot, status: &str, content: Value) -> Value { + json!({ + "id": slot.item_id, "type": "message", "status": status, "role": "assistant", "content": content + }) +} + impl<'a> ItemWriter<'a> { pub(super) fn new( tools: &[Value], @@ -68,6 +111,15 @@ impl<'a> ItemWriter<'a> { Ok(()) } + /// The status of a message once its text is complete. + fn end_status(&self) -> &'static str { + if self.incomplete { + "incomplete" + } else { + "completed" + } + } + fn item_added(&mut self, index: usize, item: Value) { let id = self.id; let fields = json!({"response_id": id, "output_index": index, "item": item}); @@ -82,15 +134,11 @@ impl<'a> ItemWriter<'a> { } /// An event of a content part: the ids, `content_index` 0 and then the given fields in order. - fn part_event( - &mut self, - kind: &'static str, - item_id: &str, - index: usize, - tail: Vec<(&str, Value)>, - ) { - let id = self.id; - let mut fields = json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0}); + fn part_event(&mut self, slot: &Slot, kind: &'static str, tail: Tail) { + let (id, item_id, index) = (self.id, &slot.item_id, slot.index); + let mut fields = json!({ + "response_id": id, "item_id": item_id, "output_index": index, "content_index": 0 + }); let object = fields.as_object_mut().expect("event fields are an object"); for (key, value) in tail { object.insert(key.to_owned(), value); @@ -102,78 +150,39 @@ impl<'a> ItemWriter<'a> { if !complete && !self.incomplete { return Err("unfinished reasoning needs an incomplete response".into()); } - let item_id = format!("rs_{}_{}", &self.id[5..], index); - let pending = json!({"id":item_id,"type":"reasoning","status":"in_progress","summary":[],"content":[]}); + let slot = Slot::new("rs", self.id, index); + let pending = reasoning_item(&slot, "in_progress", json!([])); self.item_added(index, pending); let empty = json!({"type":"reasoning_text","text":""}); - self.part_event( - "response.content_part.added", - &item_id, - index, - vec![("part", empty)], - ); + self.part_event(&slot, PART_ADDED, one("part", empty)); let whole = deltas.concat(); for delta in deltas { - let tail = vec![("delta", json!(delta))]; - self.part_event("response.reasoning_text.delta", &item_id, index, tail); + self.part_event(&slot, REASONING_DELTA, one("delta", json!(delta))); } - self.part_event( - "response.reasoning_text.done", - &item_id, - index, - vec![("text", json!(whole))], - ); + self.part_event(&slot, REASONING_DONE, one("text", json!(whole))); let part = json!({"type":"reasoning_text","text":whole}); - self.part_event( - "response.content_part.done", - &item_id, - index, - vec![("part", part.clone())], - ); + self.part_event(&slot, PART_DONE, one("part", part.clone())); let status = if complete { "completed" } else { "incomplete" }; - let done = - json!({"id":item_id,"type":"reasoning","status":status,"summary":[],"content":[part]}); + let done = reasoning_item(&slot, status, json!([part])); self.item_done(index, done); Ok(()) } fn text(&mut self, index: usize, deltas: &[String]) { self.has_text = true; - let item_id = format!("msg_{}_{}", &self.id[5..], index); - let pending = json!({ - "id": item_id, "type": "message", "status": "in_progress", "role": "assistant", "content": [] - }); + let slot = Slot::new("msg", self.id, index); + let pending = message_item(&slot, "in_progress", json!([])); self.item_added(index, pending); - self.part_event( - "response.content_part.added", - &item_id, - index, - vec![("part", text_part(""))], - ); + self.part_event(&slot, PART_ADDED, one("part", text_part(""))); let mut whole = String::new(); for delta in deltas { whole.push_str(delta); - let tail = vec![("delta", json!(delta)), ("logprobs", json!([]))]; - self.part_event("response.output_text.delta", &item_id, index, tail); + self.part_event(&slot, TEXT_DELTA, with_logprobs("delta", json!(delta))); } self.all_text.push_str(&whole); - let tail = vec![("text", json!(whole)), ("logprobs", json!([]))]; - self.part_event("response.output_text.done", &item_id, index, tail); - self.part_event( - "response.content_part.done", - &item_id, - index, - vec![("part", text_part(&whole))], - ); - let status = if self.incomplete { - "incomplete" - } else { - "completed" - }; - let done = json!({ - "id": item_id, "type": "message", "status": status, "role": "assistant", - "content": [text_part(&whole)] - }); + self.part_event(&slot, TEXT_DONE, with_logprobs("text", json!(whole))); + self.part_event(&slot, PART_DONE, one("part", text_part(&whole))); + let done = message_item(&slot, self.end_status(), json!([text_part(&whole)])); self.item_done(index, done); } @@ -227,14 +236,10 @@ impl<'a> ItemWriter<'a> { ) -> Result<(), String> { self.check_call(name, call_id)?; let custom = self.catalog.is_custom(name); - let prefix = if custom { "ctc" } else { "fc" }; - let item_id = format!("{prefix}_{}_{}", &self.id[5..], index); + let slot = Slot::new(if custom { "ctc" } else { "fc" }, self.id, index); let arguments = argument_deltas.concat(); self.check_arguments(name, &arguments)?; - let mut done = json!({ - "id": item_id, "type": "function_call", "status": "completed", "call_id": call_id, "name": name, - "arguments": arguments - }); + let mut done = function_call_item(&slot, call_id, name, arguments); self.catalog.restore(&mut done)?; let field = if custom { "input" } else { "arguments" }; let mut pending = done.clone(); @@ -246,20 +251,13 @@ impl<'a> ItemWriter<'a> { } else { argument_deltas.to_vec() }; - self.call_input_events(index, &item_id, custom, deltas, &done[field]); + self.call_input_events(&slot, custom, deltas, &done[field]); self.item_done(index, done); Ok(()) } - fn call_input_events( - &mut self, - index: usize, - item_id: &str, - custom: bool, - deltas: Vec, - input: &Value, - ) { - let id = self.id; + fn call_input_events(&mut self, slot: &Slot, custom: bool, deltas: Vec, input: &Value) { + let (id, item_id, index) = (self.id, &slot.item_id, slot.index); let (delta_event, done_event) = response_tools::input_events(custom); let field = if custom { "input" } else { "arguments" }; for delta in deltas { @@ -271,3 +269,10 @@ impl<'a> ItemWriter<'a> { self.emitter.push(done_event, fields); } } + +fn function_call_item(slot: &Slot, call_id: &str, name: &str, arguments: String) -> Value { + json!({ + "id": slot.item_id, "type": "function_call", "status": "completed", "call_id": call_id, "name": name, + "arguments": arguments + }) +} diff --git a/crates/runtime-client/src/backend.rs b/crates/runtime-client/src/backend.rs index 7c1efe07..045450ae 100644 --- a/crates/runtime-client/src/backend.rs +++ b/crates/runtime-client/src/backend.rs @@ -55,6 +55,7 @@ struct ActiveRequest { } mod log_status; +mod probe; #[allow(unused_imports)] pub use log_status::*; mod impl_api_backend_for; diff --git a/crates/runtime-client/src/backend/consumer_gone.rs b/crates/runtime-client/src/backend/consumer_gone.rs index 8569a7fe..a6086394 100644 --- a/crates/runtime-client/src/backend/consumer_gone.rs +++ b/crates/runtime-client/src/backend/consumer_gone.rs @@ -10,6 +10,44 @@ pub(super) async fn consumer_gone(sink: &api::GenerationSink) { } } +/// The next frame of the runtime, or none when the stream failed or ended, or the consumer went away while the +/// runtime is silent (a long prefill). +async fn next_frame( + generation: &mut RuntimeGeneration, + sink: &api::GenerationSink, +) -> Option { + tokio::select! { + frame = generation.message() => match frame { + Ok(Some(frame)) => Some(frame), + Ok(None) | Err(_) => None, + }, + () = consumer_gone(sink) => None, + } +} + +/// The next event for the consumer; none when the stream ends or breaks first, or the consumer is gone. +async fn next_event( + generation: &mut RuntimeGeneration, + sink: &api::GenerationSink, +) -> Option { + loop { + // A consumer that dropped the stream is a cancellation the runtime must hear about. + if sink.is_closed() { + return None; // dropping `generation` afterwards sends the Cancel + } + let frame = next_frame(generation, sink).await?; + let payload = frame.payload?; + if matches!(payload, proto::generation_frame::Payload::Accepted(_)) { + continue; + } + return convert::event_from_proto(payload).ok(); + } +} + +fn clear_active(active: &Mutex>) { + *active.lock().expect("active lock") = None; +} + /// Forward frames to the consumer. A transport failure or a malformed frame ends the stream /// *without* a terminal event, which the consumer reports as a lost engine; dropping `generation` /// afterwards asks the runtime to cancel the request. @@ -18,37 +56,15 @@ pub(super) async fn pump( sink: api::GenerationSink, active: Arc>>, ) { - let clear = |active: &Arc>>| { - *active.lock().expect("active lock") = None; - }; - loop { - // A consumer that dropped the stream is a cancellation the runtime must hear about. - if sink.is_closed() { - break; // dropping `generation` below sends the Cancel - } - let frame = tokio::select! { - frame = generation.message() => match frame { - Ok(Some(frame)) => frame, - Ok(None) | Err(_) => break, - }, - // The consumer can go away while the runtime is silent (a long prefill). - () = consumer_gone(&sink) => break, - }; - let Some(payload) = frame.payload else { break }; - if matches!(payload, proto::generation_frame::Payload::Accepted(_)) { - continue; - } - let Ok(event) = convert::event_from_proto(payload) else { - break; - }; + while let Some(event) = next_event(&mut generation, &sink).await { let terminal = matches!(event, api::GenerationEvent::Terminal(_)); // Release the active slot before the terminal is visible, so the next generation can start. if terminal { - clear(&active); + clear_active(&active); } if sink.emit(event).is_err() || terminal { return; } } - clear(&active); + clear_active(&active); } diff --git a/crates/runtime-client/src/backend/impl_api_backend_for.rs b/crates/runtime-client/src/backend/impl_api_backend_for.rs index 117162a6..e33f9a5b 100644 --- a/crates/runtime-client/src/backend/impl_api_backend_for.rs +++ b/crates/runtime-client/src/backend/impl_api_backend_for.rs @@ -15,72 +15,10 @@ impl api::Backend for GrpcBackend { /// What the runtime advertises right now: re-read on every call (a health probe), empty when /// it is unreachable, has no model loaded, or has restarted since the attach. fn capabilities(&self) -> api::BackendCapabilities { - // `capabilities` takes `&self` by contract; the probe needs a connection of its own. - let (address, token) = (self.address, self.token.clone()); - let attached = self.attached.clone(); - let existing = self.client.clone(); - let probe = self.runtime.block_on(async move { - let mut client = match existing { - Some(client) => client, - None => match RuntimeClient::connect(address, token).await { - Ok(client) => client, - Err(status) => { - log_status("probe_failed", &status); - return None; - } - }, - }; - match client.snapshot().await { - Ok(snapshot) => Some(snapshot), - Err(status) => { - log_status("probe_failed", &status); - None - } - } - }); - // the probe is one snapshot read per health tick: keep its prefix-cache summary for `prefix_cache_summary` - if let Ok(mut cell) = self.memory_report.lock() { - // memory pressure matters before and without a loaded model: no epoch/ready condition, only a non-empty report - *cell = probe - .as_ref() - .filter(|snapshot| !snapshot.memory_json.is_empty()) - .map(|snapshot| snapshot.memory_json.clone()); - } - if let Ok(mut cell) = self.telemetry_report.lock() { - *cell = probe - .as_ref() - .filter(|snapshot| !snapshot.telemetry_json.is_empty()) - .map(|snapshot| snapshot.telemetry_json.clone()); - } - if let Ok(mut cell) = self.prefix_summary.lock() { - *cell = probe - .as_ref() - .filter(|snapshot| { - snapshot.model_ready - && !snapshot.prefix_cache_json.is_empty() - && attached.as_ref().is_some_and(|a| a.epoch == snapshot.epoch) - }) - .map(|snapshot| snapshot.prefix_cache_json.clone()); - } - match (probe, attached) { - (Some(snapshot), Some(attached)) - if snapshot.model_ready - && snapshot.epoch == attached.epoch - && snapshot - .loaded - .as_ref() - .is_some_and(|l| l.handle == attached.handle) => - { - snapshot - .capabilities - .as_ref() - .map(convert::capabilities_from_proto) - .unwrap_or_default() - } - _ => api::BackendCapabilities::default(), - } + let probe = self.probe_snapshot(); + self.keep_reports(probe.as_ref()); + probe::advertised(probe, self.attached.clone()) } - /// The runtime's prefix-cache summary as of the last `capabilities` probe (one health tick old at most); `None` when the /// runtime is unreachable, restarted since the attach, or has no such cache. fn prefix_cache_summary(&self) -> Option { @@ -139,40 +77,8 @@ impl api::Backend for GrpcBackend { model: &api::LoadedModel, request: api::GenerationRequest, ) -> Result { - let attached = self.attached.clone().ok_or_else(|| { - error( - api::ErrorCode::BackendUnavailable, - "not attached to a loaded model", - true, - ) - })?; - if attached.handle != model.handle { - return Err(error( - api::ErrorCode::BackendUnavailable, - "stale model handle", - true, - )); - } - // Fresh identity check: the runtime may have restarted since the last call. - let snapshot = match self.snapshot() { - Ok(snapshot) => snapshot, - Err(error) => { - self.attached = None; - return Err(error); - } - }; - let still = snapshot - .loaded - .as_ref() - .is_some_and(|l| l.handle == attached.handle); - if snapshot.epoch != attached.epoch || !snapshot.model_ready || !still { - self.attached = None; - return Err(error( - api::ErrorCode::BackendUnavailable, - "the runtime restarted or unloaded the model", - true, - )); - } + let attached = self.attached_to(model)?; + self.check_still_attached(&attached)?; let mut wire = proto::GenerateRequest { request_id: request.request_id.clone(), expected_epoch: attached.epoch.clone(), @@ -180,14 +86,7 @@ impl api::Backend for GrpcBackend { ..Default::default() }; convert::apply_generation_request(&mut wire, &request); - let client = self.client.as_mut().expect("snapshot connected the client"); - let generation = self - .runtime - .block_on(client.generate(wire)) - .map_err(|status| { - log_status("generate_failed", &status); - from_status(&status) - })?; + let generation = self.dispatch(wire)?; *self.active.lock().expect("active lock") = Some(ActiveRequest { id: request.request_id, epoch: attached.epoch, @@ -197,7 +96,6 @@ impl api::Backend for GrpcBackend { self.runtime.spawn(pump(generation, sink, active)); Ok(stream) } - fn cancel(&mut self, request_id: &str) -> Result<(), api::BackendError> { let active = self.active.lock().expect("active lock").clone(); let Some(active) = active.filter(|a| a.id == request_id) else { @@ -231,33 +129,12 @@ impl api::Backend for GrpcBackend { true, )); }; - let Some(client) = self.client.as_mut() else { - return Err(error( - api::ErrorCode::BackendUnavailable, - "not connected", - true, - )); - }; - let reply = self - .runtime - .block_on(client.reconfigure(proto::ReconfigureRequest { - operation_id: String::new(), - expected_epoch: attached.epoch, - settings_json: settings_json.to_owned(), - })) - .map_err(|status| from_status(&status))?; + let reply = self.send_reconfigure(attached.epoch, settings_json)?; if reply.ok { return Ok(reply.effective_json); } - let code = match reply.error_code.as_str() { - "invalid" => api::ErrorCode::InvalidRequest, - "unsupported" => api::ErrorCode::UnsupportedModel, - "exhausted" => api::ErrorCode::ResourceExhausted, - "unavailable" => api::ErrorCode::BackendUnavailable, - _ => api::ErrorCode::Internal, - }; Err(api::BackendError { - code, + code: probe::reconfigure_error_code(&reply.error_code), message: reply.error, retryable: reply.retryable, }) diff --git a/crates/runtime-client/src/backend/probe.rs b/crates/runtime-client/src/backend/probe.rs new file mode 100644 index 00000000..482882c5 --- /dev/null +++ b/crates/runtime-client/src/backend/probe.rs @@ -0,0 +1,190 @@ +//! The stages of `Backend::capabilities`, `start_generation` and `reconfigure` that need the connection or the +//! attached identity. + +#[allow(unused_imports)] +use super::*; + +impl GrpcBackend { + /// One snapshot read over the connection we have, or one of its own: `None` when the runtime is unreachable. + pub(super) fn probe_snapshot(&self) -> Option { + // `capabilities` takes `&self` by contract; the probe needs a connection of its own. + let (address, token) = (self.address, self.token.clone()); + let existing = self.client.clone(); + self.runtime + .block_on(probe_runtime(existing, address, token)) + } + + /// The probe is one snapshot read per health tick: keep the reports it carries for `memory_report`, + /// `telemetry_report` and `prefix_cache_summary`. + pub(super) fn keep_reports(&self, probe: Option<&proto::Snapshot>) { + let report = |read: fn(&proto::Snapshot) -> &String| { + probe.map(read).filter(|text| !text.is_empty()).cloned() + }; + // memory pressure matters before and without a loaded model: no epoch/ready condition, only a non-empty report + keep(&self.memory_report, report(|s| &s.memory_json)); + keep(&self.telemetry_report, report(|s| &s.telemetry_json)); + let attached = self.attached.as_ref(); + let current = + probe.filter(|s| s.model_ready && attached.is_some_and(|a| a.epoch == s.epoch)); + let prefix = current + .map(|s| &s.prefix_cache_json) + .filter(|text| !text.is_empty()) + .cloned(); + keep(&self.prefix_summary, prefix); + } + + /// The attached identity for a generation on `model`: attached, and to this handle. + pub(super) fn attached_to( + &self, + model: &api::LoadedModel, + ) -> Result { + let attached = self.attached.clone().ok_or_else(|| { + error( + api::ErrorCode::BackendUnavailable, + "not attached to a loaded model", + true, + ) + })?; + if attached.handle != model.handle { + return Err(error( + api::ErrorCode::BackendUnavailable, + "stale model handle", + true, + )); + } + Ok(attached) + } + + /// Fresh identity check: the runtime may have restarted since the last call. + pub(super) fn check_still_attached( + &mut self, + attached: &Attached, + ) -> Result<(), api::BackendError> { + let snapshot = match self.snapshot() { + Ok(snapshot) => snapshot, + Err(error) => { + self.attached = None; + return Err(error); + } + }; + let still = snapshot + .loaded + .as_ref() + .is_some_and(|l| l.handle == attached.handle); + if snapshot.epoch != attached.epoch || !snapshot.model_ready || !still { + self.attached = None; + return Err(error( + api::ErrorCode::BackendUnavailable, + "the runtime restarted or unloaded the model", + true, + )); + } + Ok(()) + } + + /// Sends the generation to the runtime; nothing is retried. + pub(super) fn dispatch( + &mut self, + wire: proto::GenerateRequest, + ) -> Result { + let client = self.client.as_mut().expect("snapshot connected the client"); + self.runtime + .block_on(client.generate(wire)) + .map_err(|status| { + log_status("generate_failed", &status); + from_status(&status) + }) + } + + /// Sends the reconfiguration for the attached epoch. + pub(super) fn send_reconfigure( + &mut self, + epoch: String, + settings_json: &str, + ) -> Result { + let Some(client) = self.client.as_mut() else { + return Err(error( + api::ErrorCode::BackendUnavailable, + "not connected", + true, + )); + }; + self.runtime + .block_on(client.reconfigure(proto::ReconfigureRequest { + operation_id: String::new(), + expected_epoch: epoch, + settings_json: settings_json.to_owned(), + })) + .map_err(|status| from_status(&status)) + } +} + +fn keep(cell: &Mutex>, value: Option) { + if let Ok(mut cell) = cell.lock() { + *cell = value; + } +} + +/// A snapshot read over `existing`, or over a connection made for it. +async fn probe_runtime( + existing: Option, + address: SocketAddr, + token: String, +) -> Option { + let mut client = match existing { + Some(client) => client, + None => connect_for_probe(address, token).await?, + }; + match client.snapshot().await { + Ok(snapshot) => Some(snapshot), + Err(status) => { + log_status("probe_failed", &status); + None + } + } +} + +async fn connect_for_probe(address: SocketAddr, token: String) -> Option { + match RuntimeClient::connect(address, token).await { + Ok(client) => Some(client), + Err(status) => { + log_status("probe_failed", &status); + None + } + } +} + +/// What the runtime advertises when it is ready, at the epoch and with the model this backend is attached to. +pub(super) fn advertised( + probe: Option, + attached: Option, +) -> api::BackendCapabilities { + match (probe, attached) { + (Some(snapshot), Some(attached)) + if snapshot.model_ready + && snapshot.epoch == attached.epoch + && snapshot + .loaded + .as_ref() + .is_some_and(|l| l.handle == attached.handle) => + { + snapshot + .capabilities + .as_ref() + .map(convert::capabilities_from_proto) + .unwrap_or_default() + } + _ => api::BackendCapabilities::default(), + } +} + +/// The error code a refused reconfiguration carries on the wire. +pub(super) fn reconfigure_error_code(code: &str) -> api::ErrorCode { + match code { + "invalid" => api::ErrorCode::InvalidRequest, + "unsupported" => api::ErrorCode::UnsupportedModel, + "exhausted" => api::ErrorCode::ResourceExhausted, + "unavailable" => api::ErrorCode::BackendUnavailable, + _ => api::ErrorCode::Internal, + } +} diff --git a/crates/runtime-client/src/client.rs b/crates/runtime-client/src/client.rs index 80f8d2ab..ec09d378 100644 --- a/crates/runtime-client/src/client.rs +++ b/crates/runtime-client/src/client.rs @@ -183,14 +183,7 @@ fn validate_operation( } pub fn validate_snapshot(value: &proto::Snapshot) -> Result<(), Status> { - if value.protocol_version != PROTOCOL_VERSION - || value.backend_api_version != 2 - || uuid::Uuid::parse_str(&value.epoch).is_err() - || value.sequence == 0 - || !value.full_snapshot - || (value.model_ready && value.loaded.is_none()) - || value.encoded_len() > FRAME_LIMIT - { + if snapshot_is_malformed(value) { return Err(Status::data_loss("invalid_runtime_snapshot")); } if !value.model_ready @@ -202,32 +195,48 @@ pub fn validate_snapshot(value: &proto::Snapshot) -> Result<(), Status> { return Err(Status::data_loss("unloaded_capability_advertisement")); } if let Some(loaded) = &value.loaded { - let descriptor = convert::descriptor_from_proto( - loaded - .descriptor - .as_ref() - .ok_or_else(|| Status::data_loss("missing_loaded_descriptor"))?, - )?; - let config = convert::config_from_proto(&proto::LoadConfig { - version: loaded.load_config_version, - mode: loaded.effective_mode.clone(), - gpu_memory_limit_bytes: None, - allow_experimental: true, - })?; - let result = leleka_backend_api::LoadedModel { - handle: loaded.handle.clone(), - descriptor: descriptor.clone(), - load_config_version: config.load_config_version, - effective_mode: config.inference_mode.clone(), - mode_identity_digest: loaded.mode_identity_digest.clone(), - }; - result - .validate_for_load(&descriptor, &config) - .map_err(|_| Status::data_loss("invalid_loaded_identity"))?; + validate_loaded_identity(loaded)?; } Ok(()) } +/// The versions, the epoch, the sequence and the size of a snapshot, and that a ready model is reported. +fn snapshot_is_malformed(value: &proto::Snapshot) -> bool { + value.protocol_version != PROTOCOL_VERSION + || value.backend_api_version != 2 + || uuid::Uuid::parse_str(&value.epoch).is_err() + || value.sequence == 0 + || !value.full_snapshot + || (value.model_ready && value.loaded.is_none()) + || value.encoded_len() > FRAME_LIMIT +} + +// The loaded model a snapshot reports must be one the contract accepts for its own descriptor and mode. +fn validate_loaded_identity(loaded: &proto::LoadedModel) -> Result<(), Status> { + let descriptor = convert::descriptor_from_proto( + loaded + .descriptor + .as_ref() + .ok_or_else(|| Status::data_loss("missing_loaded_descriptor"))?, + )?; + let config = convert::config_from_proto(&proto::LoadConfig { + version: loaded.load_config_version, + mode: loaded.effective_mode.clone(), + gpu_memory_limit_bytes: None, + allow_experimental: true, + })?; + let result = leleka_backend_api::LoadedModel { + handle: loaded.handle.clone(), + descriptor: descriptor.clone(), + load_config_version: config.load_config_version, + effective_mode: config.inference_mode.clone(), + mode_identity_digest: loaded.mode_identity_digest.clone(), + }; + result + .validate_for_load(&descriptor, &config) + .map_err(|_| Status::data_loss("invalid_loaded_identity")) +} + /// Validates request/epoch/sequence, initial acceptance and terminal completeness. /// Drop cancels observation's request; it never retries it or unloads the model. pub struct RuntimeGeneration { @@ -247,64 +256,74 @@ impl RuntimeGeneration { if self.failed { return Err(Status::data_loss("generation_stream_failed")); } - let value = match self.stream.message().await { - Ok(Some(value)) => value, - Ok(None) => { - self.failed = true; - return Err(Status::data_loss("generation_missing_terminal")); - } - Err(status) => { - self.failed = true; - return Err(status); - } - }; + let value = self.next_frame().await?; + self.check_frame(&value)?; + if let Some(proto::generation_frame::Payload::Terminal(terminal)) = &value.payload { + self.finish_after_terminal(terminal).await?; + } + self.sequence = value.sequence; + Ok(Some(value)) + } + + /// Any failure ends the generation: every later read says so. + fn fail(&mut self, status: Status) -> Status { + self.failed = true; + status + } + + async fn next_frame(&mut self) -> Result { + match self.stream.message().await { + Ok(Some(value)) => Ok(value), + Ok(None) => Err(self.fail(Status::data_loss("generation_missing_terminal"))), + Err(status) => Err(self.fail(status)), + } + } + + fn check_frame(&mut self, value: &proto::GenerationFrame) -> Result<(), Status> { let first = self.sequence == 0; if value.request_id != self.id || value.epoch != self.epoch || value.sequence != self.sequence + 1 || value.encoded_len() > FRAME_LIMIT || value.payload.is_none() - || (first - && !matches!( - value.payload, - Some(proto::generation_frame::Payload::Accepted( - proto::Accepted { accepted: true } - )) - )) + || (first && !is_acceptance(&value.payload)) || (!first && matches!( value.payload, Some(proto::generation_frame::Payload::Accepted(_)) )) { - self.failed = true; - return Err(Status::data_loss("invalid_generation_frame")); + return Err(self.fail(Status::data_loss("invalid_generation_frame"))); } - if let Some(proto::generation_frame::Payload::Terminal(terminal)) = &value.payload { - if !matches!(terminal.state, 1..=3) || (terminal.state == 1 && terminal.usage.is_none()) - { - self.failed = true; - return Err(Status::data_loss("invalid_generation_terminal")); - } - // Do not publish the terminal until the HTTP2 stream finishes - // successfully. Duplicate frames and errors after terminal fail. - match self.stream.message().await { - Ok(None) => {} - Ok(Some(_)) => { - self.failed = true; - return Err(Status::data_loss("generation_after_terminal")); - } - Err(status) => { - self.failed = true; - return Err(status); - } - } - self.terminal = true; + Ok(()) + } + + async fn finish_after_terminal(&mut self, terminal: &proto::Terminal) -> Result<(), Status> { + if !matches!(terminal.state, 1..=3) || (terminal.state == 1 && terminal.usage.is_none()) { + return Err(self.fail(Status::data_loss("invalid_generation_terminal"))); } - self.sequence = value.sequence; - Ok(Some(value)) + // Do not publish the terminal until the HTTP2 stream finishes + // successfully. Duplicate frames and errors after terminal fail. + match self.stream.message().await { + Ok(None) => {} + Ok(Some(_)) => return Err(self.fail(Status::data_loss("generation_after_terminal"))), + Err(status) => return Err(self.fail(status)), + } + self.terminal = true; + Ok(()) } } + +/// The payload is the `Accepted` frame with `accepted` set. +fn is_acceptance(payload: &Option) -> bool { + matches!( + payload, + Some(proto::generation_frame::Payload::Accepted( + proto::Accepted { accepted: true } + )) + ) +} + impl Drop for RuntimeGeneration { fn drop(&mut self) { if !self.terminal { diff --git a/crates/runtime-client/src/client/tests.rs b/crates/runtime-client/src/client/tests.rs index 1a7340de..bcd58baa 100644 --- a/crates/runtime-client/src/client/tests.rs +++ b/crates/runtime-client/src/client/tests.rs @@ -10,47 +10,56 @@ use std::{ }, }; use tonic::Response; -#[test] -fn runtime_client_retained_handle_is_not_ready() { +/// The snapshot of a runtime at `epoch` that reports `loaded` (and is not ready). +fn snapshot_of(epoch: String, loaded: Option) -> proto::Snapshot { + proto::Snapshot { + protocol_version: 1, + backend_api_version: 2, + epoch, + sequence: 1, + full_snapshot: true, + transport_ready: true, + model_ready: false, + loaded, + capabilities: Some(proto::Capabilities::default()), + active_request_id: String::new(), + prefix_cache_json: String::new(), + memory_json: String::new(), + telemetry_json: String::new(), + } +} + +fn retained_loaded() -> leleka_backend_api::LoadedModel { let model = leleka_backend_api::ModelDescriptor { family: "fixture".into(), architecture: "fixture".into(), weight_format: "fixture".into(), artifact_digest: format!("sha256:{}", "a".repeat(64)), }; - let loaded = leleka_backend_api::LoadedModel { + leleka_backend_api::LoadedModel { handle: "retained-fixture".into(), descriptor: model, load_config_version: 1, effective_mode: leleka_backend_api::InferenceMode::Native, mode_identity_digest: format!("sha256:{}", "b".repeat(64)), - }; - let mut snapshot = proto::Snapshot { - protocol_version: 1, - backend_api_version: 2, - epoch: uuid::Uuid::new_v4().to_string(), - sequence: 1, - full_snapshot: true, - transport_ready: true, - model_ready: false, - loaded: Some(convert::loaded_to_proto(&loaded)), - capabilities: Some(proto::Capabilities::default()), - active_request_id: String::new(), - prefix_cache_json: String::new(), - memory_json: String::new(), - telemetry_json: String::new(), - }; + } +} + +fn fixture_model_tuple() -> proto::SupportedModelTuple { + proto::SupportedModelTuple { + family: "fixture".into(), + architecture: "fixture".into(), + weight_format: "fixture".into(), + } +} + +#[test] +fn runtime_client_retained_handle_is_not_ready() { + let loaded = convert::loaded_to_proto(&retained_loaded()); + let mut snapshot = snapshot_of(uuid::Uuid::new_v4().to_string(), Some(loaded)); assert!(validate_snapshot(&snapshot).is_ok()); - snapshot - .capabilities - .as_mut() - .unwrap() - .models - .push(proto::SupportedModelTuple { - family: "fixture".into(), - architecture: "fixture".into(), - weight_format: "fixture".into(), - }); + let capabilities = snapshot.capabilities.as_mut().unwrap(); + capabilities.models.push(fixture_model_tuple()); assert!(validate_snapshot(&snapshot).is_err()); snapshot.capabilities = Some(proto::Capabilities::default()); snapshot.loaded = None; @@ -65,22 +74,57 @@ struct FaultServer { } impl FaultServer { fn snapshot(&self) -> proto::Snapshot { - proto::Snapshot { - protocol_version: 1, - backend_api_version: 2, - epoch: self.epoch.clone(), - sequence: 1, - full_snapshot: true, - transport_ready: true, - model_ready: false, - loaded: None, - capabilities: Some(proto::Capabilities::default()), - active_request_id: String::new(), - prefix_cache_json: String::new(), - memory_json: String::new(), - telemetry_json: String::new(), - } + snapshot_of(self.epoch.clone(), None) } + + /// The accepted frame, a terminal and then what the fault adds (0: nothing; 1: no terminal; 2: data after it; + /// 3: a stream error after it; 4: a terminal out of sequence). + fn fault_frames(&self, id: &str) -> Vec> { + let frame = |sequence, payload| fault_frame(id, &self.epoch, sequence, payload); + let accepted = + proto::generation_frame::Payload::Accepted(proto::Accepted { accepted: true }); + let mut frames = vec![Ok(frame(1, accepted))]; + if self.fault != 1 { + frames.push(Ok(frame( + if self.fault == 4 { 5 } else { 2 }, + stop_terminal(), + ))); + } + if self.fault == 2 { + let text = proto::TextDelta { + text: "must-not-publish".into(), + }; + frames.push(Ok(frame(3, proto::generation_frame::Payload::Text(text)))); + } + if self.fault == 3 { + frames.push(Err(Status::internal("fixture_trailer_error"))); + } + frames + } +} + +fn fault_frame( + id: &str, + epoch: &str, + sequence: u64, + payload: proto::generation_frame::Payload, +) -> proto::GenerationFrame { + proto::GenerationFrame { + request_id: id.to_owned(), + epoch: epoch.to_owned(), + sequence, + payload: Some(payload), + } +} + +fn stop_terminal() -> proto::generation_frame::Payload { + proto::generation_frame::Payload::Terminal(proto::Terminal { + state: 1, + reason: "stop".into(), + usage: Some(proto::Usage::default()), + error_code: String::new(), + retryable: false, + }) } #[tonic::async_trait] impl proto::runtime_server::Runtime for FaultServer { @@ -145,40 +189,7 @@ impl proto::runtime_server::Runtime for FaultServer { request: Request, ) -> Result, Status> { let id = request.into_inner().request_id; - let frame = |sequence, payload| proto::GenerationFrame { - request_id: id.clone(), - epoch: self.epoch.clone(), - sequence, - payload: Some(payload), - }; - let mut frames = vec![Ok(frame( - 1, - proto::generation_frame::Payload::Accepted(proto::Accepted { accepted: true }), - ))]; - let terminal = frame( - if self.fault == 4 { 5 } else { 2 }, - proto::generation_frame::Payload::Terminal(proto::Terminal { - state: 1, - reason: "stop".into(), - usage: Some(proto::Usage::default()), - error_code: String::new(), - retryable: false, - }), - ); - if self.fault != 1 { - frames.push(Ok(terminal)); - } - if self.fault == 2 { - frames.push(Ok(frame( - 3, - proto::generation_frame::Payload::Text(proto::TextDelta { - text: "must-not-publish".into(), - }), - ))); - } - if self.fault == 3 { - frames.push(Err(Status::internal("fixture_trailer_error"))); - } + let frames = self.fault_frames(&id); let stream = Box::pin(tokio_stream::iter(frames)) as Self::GenerateStream; let mut response = Response::new(stream); response @@ -190,69 +201,94 @@ impl proto::runtime_server::Runtime for FaultServer { #[tokio::test(flavor = "current_thread")] async fn runtime_client_requires_terminal_eof_and_rejects_trailing_data_or_status() { for fault in 0..=4 { - let epoch = uuid::Uuid::new_v4().to_string(); - let cancels = Arc::new(AtomicUsize::new(0)); - let service = FaultServer { - epoch: epoch.clone(), - fault, - cancels: cancels.clone(), - }; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let (stop, stopped) = tokio::sync::oneshot::channel(); - let task = tokio::spawn(async move { - tonic::transport::Server::builder() - .add_service(proto::runtime_server::RuntimeServer::new(service)) - .serve_with_incoming_shutdown( - tokio_stream::wrappers::TcpListenerStream::new(listener), - async { - let _ = stopped.await; - }, - ) - .await - .unwrap(); - }); - let mut client = - RuntimeClient::connect(address, "synthetic-runtime-test-token-00000000".into()) - .await - .unwrap(); - let mut stream = client - .generate(proto::GenerateRequest { - request_id: uuid::Uuid::new_v4().to_string(), - expected_epoch: epoch, - handle: "fixture".into(), - prompt: String::new(), - max_output_tokens: 1, - temperature_milli: 0, - ..Default::default() - }) - .await - .unwrap(); - assert!(matches!( - stream.message().await.unwrap().unwrap().payload, - Some(proto::generation_frame::Payload::Accepted(_)) - )); - if fault == 0 { - assert!(matches!( - stream.message().await.unwrap().unwrap().payload, - Some(proto::generation_frame::Payload::Terminal(_)) - )); - assert!(stream.message().await.unwrap().is_none()); - } else { - assert!(stream.message().await.is_err()); - } - drop(stream); - if fault != 0 { - for _ in 0..50 { - if cancels.load(Ordering::SeqCst) > 0 { - break; - } - tokio::time::sleep(Duration::from_millis(2)).await; - } - assert_eq!(cancels.load(Ordering::SeqCst), 1); - } - drop(client); - stop.send(()).unwrap(); - task.await.unwrap(); + run_fault_case(fault).await; } } + +/// Serves `service` on a loopback port until the returned sender fires. +async fn serve_fault( + service: FaultServer, +) -> ( + std::net::SocketAddr, + tokio::sync::oneshot::Sender<()>, + tokio::task::JoinHandle<()>, +) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (stop, stopped) = tokio::sync::oneshot::channel(); + let task = tokio::spawn(async move { + tonic::transport::Server::builder() + .add_service(proto::runtime_server::RuntimeServer::new(service)) + .serve_with_incoming_shutdown( + tokio_stream::wrappers::TcpListenerStream::new(listener), + async { + let _ = stopped.await; + }, + ) + .await + .unwrap(); + }); + (address, stop, task) +} + +fn fault_request(epoch: String) -> proto::GenerateRequest { + proto::GenerateRequest { + request_id: uuid::Uuid::new_v4().to_string(), + expected_epoch: epoch, + handle: "fixture".into(), + prompt: String::new(), + max_output_tokens: 1, + temperature_milli: 0, + ..Default::default() + } +} + +/// Reads the stream of one fault: whole when there is none, an error at the fault otherwise. +async fn expect_stream(stream: &mut RuntimeGeneration, fault: u8) { + assert!(matches!( + stream.message().await.unwrap().unwrap().payload, + Some(proto::generation_frame::Payload::Accepted(_)) + )); + if fault == 0 { + assert!(matches!( + stream.message().await.unwrap().unwrap().payload, + Some(proto::generation_frame::Payload::Terminal(_)) + )); + assert!(stream.message().await.unwrap().is_none()); + } else { + assert!(stream.message().await.is_err()); + } +} + +/// A faulty stream dropped before its end makes the client ask the runtime to cancel, exactly once. +async fn expect_one_cancel(cancels: &AtomicUsize) { + for _ in 0..50 { + if cancels.load(Ordering::SeqCst) > 0 { + break; + } + tokio::time::sleep(Duration::from_millis(2)).await; + } + assert_eq!(cancels.load(Ordering::SeqCst), 1); +} + +async fn run_fault_case(fault: u8) { + let epoch = uuid::Uuid::new_v4().to_string(); + let cancels = Arc::new(AtomicUsize::new(0)); + let service = FaultServer { + epoch: epoch.clone(), + fault, + cancels: cancels.clone(), + }; + let (address, stop, task) = serve_fault(service).await; + let token = "synthetic-runtime-test-token-00000000".into(); + let mut client = RuntimeClient::connect(address, token).await.unwrap(); + let mut stream = client.generate(fault_request(epoch)).await.unwrap(); + expect_stream(&mut stream, fault).await; + drop(stream); + if fault != 0 { + expect_one_cancel(&cancels).await; + } + drop(client); + stop.send(()).unwrap(); + task.await.unwrap(); +} diff --git a/crates/runtime-client/src/convert.rs b/crates/runtime-client/src/convert.rs index f41027e6..4088e482 100644 --- a/crates/runtime-client/src/convert.rs +++ b/crates/runtime-client/src/convert.rs @@ -71,24 +71,27 @@ pub fn mode_to_proto(mode: &api::InferenceMode) -> proto::InferenceMode { profile_id: profile_id.clone(), }), api::InferenceMode::ExperimentalKarExperts(e) => { - Selection::KarExperts(proto::KarExpertsMode { - bundle_directory: e.bundle_directory.clone(), - archive_file: e.archive_file.clone(), - binding_file: e.binding_file.clone(), - provenance_file: e.provenance_file.clone(), - levels: u32::from(e.levels), - cache_mib: e.cache_mib, - prefill_mode: match e.prefill_mode { - api::KarPrefillMode::DecodeOnly => 1, - api::KarPrefillMode::AllRoutedBatched => 2, - }, - }) + Selection::KarExperts(kar_experts_to_proto(e)) } }; proto::InferenceMode { selection: Some(selection), } } +fn kar_experts_to_proto(e: &api::KarExpertLoad) -> proto::KarExpertsMode { + proto::KarExpertsMode { + bundle_directory: e.bundle_directory.clone(), + archive_file: e.archive_file.clone(), + binding_file: e.binding_file.clone(), + provenance_file: e.provenance_file.clone(), + levels: u32::from(e.levels), + cache_mib: e.cache_mib, + prefill_mode: match e.prefill_mode { + api::KarPrefillMode::DecodeOnly => 1, + api::KarPrefillMode::AllRoutedBatched => 2, + }, + } +} pub fn config_to_proto(config: &api::RuntimeConfig) -> proto::LoadConfig { proto::LoadConfig { version: u32::from(config.load_config_version), @@ -98,43 +101,7 @@ pub fn config_to_proto(config: &api::RuntimeConfig) -> proto::LoadConfig { } } pub fn config_from_proto(config: &proto::LoadConfig) -> Result { - use proto::inference_mode::Selection; - let mode = match config.mode.as_ref().and_then(|m| m.selection.as_ref()) { - Some(Selection::Native(_)) => api::InferenceMode::Native, - Some(Selection::KarPle(p)) => api::InferenceMode::ExperimentalKarPle { - profile_id: p.profile_id.clone(), - }, - Some(Selection::Mtp(p)) => api::InferenceMode::ExperimentalMtp { - profile_id: p.profile_id.clone(), - }, - Some(Selection::KarExperts(e)) => { - api::InferenceMode::ExperimentalKarExperts(api::KarExpertLoad { - bundle_directory: e.bundle_directory.clone(), - archive_file: e.archive_file.clone(), - binding_file: e.binding_file.clone(), - provenance_file: e.provenance_file.clone(), - levels: u8::try_from(e.levels) - .map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_expert_levels"))?, - cache_mib: e.cache_mib, - prefill_mode: match e.prefill_mode { - 1 => api::KarPrefillMode::DecodeOnly, - 2 => api::KarPrefillMode::AllRoutedBatched, - _ => { - return Err(refusal( - tonic::Code::InvalidArgument, - "invalid_expert_prefill", - )); - } - }, - }) - } - None => { - return Err(refusal( - tonic::Code::InvalidArgument, - "missing_inference_mode", - )); - } - }; + let mode = mode_from_proto(config.mode.as_ref().and_then(|m| m.selection.as_ref()))?; let value = api::RuntimeConfig { load_config_version: u16::try_from(config.version) .map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_load_version"))?, @@ -147,6 +114,50 @@ pub fn config_from_proto(config: &proto::LoadConfig) -> Result, +) -> Result { + use proto::inference_mode::Selection; + Ok(match selection { + Some(Selection::Native(_)) => api::InferenceMode::Native, + Some(Selection::KarPle(p)) => api::InferenceMode::ExperimentalKarPle { + profile_id: p.profile_id.clone(), + }, + Some(Selection::Mtp(p)) => api::InferenceMode::ExperimentalMtp { + profile_id: p.profile_id.clone(), + }, + Some(Selection::KarExperts(e)) => { + api::InferenceMode::ExperimentalKarExperts(kar_experts_from_proto(e)?) + } + None => { + return Err(refusal( + tonic::Code::InvalidArgument, + "missing_inference_mode", + )); + } + }) +} +fn kar_experts_from_proto(e: &proto::KarExpertsMode) -> Result { + Ok(api::KarExpertLoad { + bundle_directory: e.bundle_directory.clone(), + archive_file: e.archive_file.clone(), + binding_file: e.binding_file.clone(), + provenance_file: e.provenance_file.clone(), + levels: u8::try_from(e.levels) + .map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_expert_levels"))?, + cache_mib: e.cache_mib, + prefill_mode: match e.prefill_mode { + 1 => api::KarPrefillMode::DecodeOnly, + 2 => api::KarPrefillMode::AllRoutedBatched, + _ => { + return Err(refusal( + tonic::Code::InvalidArgument, + "invalid_expert_prefill", + )); + } + }, + }) +} pub fn loaded_to_proto(value: &api::LoadedModel) -> proto::LoadedModel { proto::LoadedModel { handle: value.handle.clone(), @@ -223,38 +234,52 @@ pub fn event_from_proto( arguments_delta: tool.arguments_delta, }, Payload::Usage(usage) => api::GenerationEvent::Usage(usage_from_proto(&usage)), - Payload::Terminal(terminal) => api::GenerationEvent::Terminal(match terminal.state { - 1 => api::GenerationTerminal::Completed { - reason: match terminal.reason.as_str() { - "stop" => api::FinishReason::Stop, - "length" => api::FinishReason::Length, - "tool_calls" => api::FinishReason::ToolCalls, - _ => return Err(Status::data_loss("unknown_finish_reason")), - }, - usage: usage_from_proto( - terminal - .usage - .as_ref() - .ok_or_else(|| Status::data_loss("missing_terminal_usage"))?, - ), - }, - 2 => api::GenerationTerminal::Failed { - code: match terminal.error_code.as_str() { - "invalid_request" => api::ErrorCode::InvalidRequest, - "unsupported_model" => api::ErrorCode::UnsupportedModel, - "resource_exhausted" => api::ErrorCode::ResourceExhausted, - "backend_unavailable" => api::ErrorCode::BackendUnavailable, - _ => api::ErrorCode::Internal, - }, - message: terminal.reason, - retryable: terminal.retryable, - }, - 3 => api::GenerationTerminal::Cancelled, - _ => return Err(Status::data_loss("invalid_generation_terminal")), - }), + Payload::Terminal(terminal) => { + api::GenerationEvent::Terminal(terminal_from_proto(terminal)?) + } }) } +fn terminal_from_proto(terminal: proto::Terminal) -> Result { + Ok(match terminal.state { + 1 => completed_from_proto(&terminal)?, + 2 => api::GenerationTerminal::Failed { + code: error_code_from_wire(terminal.error_code.as_str()), + message: terminal.reason, + retryable: terminal.retryable, + }, + 3 => api::GenerationTerminal::Cancelled, + _ => return Err(Status::data_loss("invalid_generation_terminal")), + }) +} + +fn completed_from_proto(terminal: &proto::Terminal) -> Result { + Ok(api::GenerationTerminal::Completed { + reason: match terminal.reason.as_str() { + "stop" => api::FinishReason::Stop, + "length" => api::FinishReason::Length, + "tool_calls" => api::FinishReason::ToolCalls, + _ => return Err(Status::data_loss("unknown_finish_reason")), + }, + usage: usage_from_proto( + terminal + .usage + .as_ref() + .ok_or_else(|| Status::data_loss("missing_terminal_usage"))?, + ), + }) +} + +fn error_code_from_wire(code: &str) -> api::ErrorCode { + match code { + "invalid_request" => api::ErrorCode::InvalidRequest, + "unsupported_model" => api::ErrorCode::UnsupportedModel, + "resource_exhausted" => api::ErrorCode::ResourceExhausted, + "backend_unavailable" => api::ErrorCode::BackendUnavailable, + _ => api::ErrorCode::Internal, + } +} + /// The prompt and sampling controls of a backend request as wire fields. pub fn apply_generation_request( wire: &mut proto::GenerateRequest, diff --git a/crates/runtime-client/tests/grpc_backend/fixtures.rs b/crates/runtime-client/tests/grpc_backend/fixtures.rs index 096585a5..af6060bd 100644 --- a/crates/runtime-client/tests/grpc_backend/fixtures.rs +++ b/crates/runtime-client/tests/grpc_backend/fixtures.rs @@ -58,20 +58,7 @@ impl Fake { transport_ready: true, model_ready: state.loaded.is_some(), loaded: state.loaded.as_ref().map(convert::loaded_to_proto), - capabilities: Some(proto::Capabilities { - models: if state.loaded.is_some() { - vec![proto::SupportedModelTuple { - family: descriptor().family, - architecture: descriptor().architecture, - weight_format: descriptor().weight_format, - }] - } else { - Vec::new() - }, - max_concurrent_generations: 1, - cancellation: true, - tool_call_streaming: false, - }), + capabilities: Some(capabilities_of(state.loaded.is_some())), active_request_id: String::new(), prefix_cache_json: String::new(), memory_json: String::new(), @@ -94,3 +81,23 @@ impl Fake { self.state.lock().unwrap().scripts.push(frames); } } + +/// What the fake advertises: the fixture model when one is loaded. +fn capabilities_of(loaded: bool) -> proto::Capabilities { + let models = if loaded { + let model = descriptor(); + vec![proto::SupportedModelTuple { + family: model.family, + architecture: model.architecture, + weight_format: model.weight_format, + }] + } else { + Vec::new() + }; + proto::Capabilities { + models, + max_concurrent_generations: 1, + cancellation: true, + tool_call_streaming: false, + } +} diff --git a/crates/runtime-client/tests/grpc_backend/generation.rs b/crates/runtime-client/tests/grpc_backend/generation.rs index e1ec5116..3c32c32d 100644 --- a/crates/runtime-client/tests/grpc_backend/generation.rs +++ b/crates/runtime-client/tests/grpc_backend/generation.rs @@ -18,32 +18,41 @@ async fn a_generation_sends_the_identity_and_every_sampling_field_and_maps_frame let sent = request(&request_id); let (_backend, stream) = blocking(backend, move |b| b.start_generation(&attached, sent)).await; let mut stream = stream.unwrap(); - let (events, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream)).await.unwrap(); + let (events, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream)) + .await + .unwrap(); assert!(terminated); - assert_eq!( - events, - vec![ - GenerationEvent::TextDelta { text: "hel".into() }, - GenerationEvent::TextDelta { text: "lo".into() }, - GenerationEvent::Usage(Usage { - input_tokens: 10, - output_tokens: 2, - reused_input_tokens: 2 - }), - GenerationEvent::Terminal(GenerationTerminal::Completed { - reason: FinishReason::Stop, - usage: Usage { - input_tokens: 10, - output_tokens: 3, - reused_input_tokens: 2 - } - }), - ] - ); - let seen = server.fake.state.lock().unwrap().requests[0].clone(); + assert_eq!(events, mapped_events()); + assert_sent_request(&server, &request_id); + server.finish().await; +} + +/// The events the scripted frames map to. +fn mapped_events() -> Vec { + let counts = |output_tokens| Usage { + input_tokens: 10, + output_tokens, + reused_input_tokens: 2, + }; + let completed = GenerationTerminal::Completed { + reason: FinishReason::Stop, + usage: counts(3), + }; + vec![ + GenerationEvent::TextDelta { text: "hel".into() }, + GenerationEvent::TextDelta { text: "lo".into() }, + GenerationEvent::Usage(counts(2)), + GenerationEvent::Terminal(completed), + ] +} + +/// What the server saw: the identity and every sampling field of the request. +fn assert_sent_request(server: &Server, request_id: &str) { + let state = server.fake.state.lock().unwrap(); + let seen = state.requests[0].clone(); assert_eq!(seen.request_id, request_id); assert_eq!(seen.handle, "h-1"); - assert_eq!(seen.expected_epoch, server.fake.state.lock().unwrap().epoch); + assert_eq!(seen.expected_epoch, state.epoch); assert_eq!(seen.prompt, "<|im_start|>user\nhi<|im_end|>\n"); assert_eq!((seen.max_output_tokens, seen.temperature_milli), (64, 700)); assert_eq!(seen.top_p_micro, Some(900_000)); @@ -54,35 +63,51 @@ async fn a_generation_sends_the_identity_and_every_sampling_field_and_maps_frame assert_eq!(seen.presence_penalty_micro, Some(250_000)); assert_eq!(seen.penalty_last_n, Some(64)); assert_eq!(seen.seed, Some(42)); - server.finish().await; } - #[tokio::test(flavor = "multi_thread")] async fn failed_and_cancelled_terminals_keep_their_meaning() { let server = Server::start(Some(loaded("h-1"))).await; - server - .fake - .push(vec![Ok(text("x")), Ok(terminal(2, "engine exploded", false))]); + server.fake.push(vec![ + Ok(text("x")), + Ok(terminal(2, "engine exploded", false)), + ]); server.fake.push(vec![Ok(terminal(3, "cancelled", false))]); - let (mut backend, attached) = blocking(server.backend(), |b| b.load(descriptor(), config())).await; + let (mut backend, attached) = + blocking(server.backend(), |b| b.load(descriptor(), config())).await; let attached = attached.unwrap(); for expected in ["failed", "cancelled"] { - let (b, stream) = { - let attached = attached.clone(); - blocking(backend, move |b| b.start_generation(&attached, request(&id()))).await - }; + let (b, events, terminated) = generate_to_the_end(backend, &attached).await; backend = b; - let mut stream = stream.unwrap(); - let (events, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream)).await.unwrap(); assert!(terminated, "{expected}"); - match (expected, events.last().unwrap()) { - ("failed", GenerationEvent::Terminal(GenerationTerminal::Failed { code, message, .. })) => { - assert_eq!(*code, ErrorCode::ResourceExhausted); - assert_eq!(message, "engine exploded"); - } - ("cancelled", GenerationEvent::Terminal(GenerationTerminal::Cancelled)) => {} - other => panic!("{other:?}"), - } + assert_terminal_meaning(expected, events.last().unwrap()); } server.finish().await; } + +/// One generation on `backend`, read until its stream ends: the events and whether a terminal came. +async fn generate_to_the_end( + backend: GrpcBackend, + attached: &LoadedModel, +) -> (GrpcBackend, Vec, bool) { + let attached = attached.clone(); + let (backend, stream) = blocking(backend, move |b| { + b.start_generation(&attached, request(&id())) + }) + .await; + let mut stream = stream.unwrap(); + let (events, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream)) + .await + .unwrap(); + (backend, events, terminated) +} + +fn assert_terminal_meaning(expected: &str, last: &GenerationEvent) { + match (expected, last) { + ("failed", GenerationEvent::Terminal(GenerationTerminal::Failed { code, message, .. })) => { + assert_eq!(*code, ErrorCode::ResourceExhausted); + assert_eq!(message, "engine exploded"); + } + ("cancelled", GenerationEvent::Terminal(GenerationTerminal::Cancelled)) => {} + other => panic!("{other:?}"), + } +} diff --git a/crates/runtime-client/tests/grpc_backend/scripted_service.rs b/crates/runtime-client/tests/grpc_backend/scripted_service.rs index 78ccdf5f..44b64d9f 100644 --- a/crates/runtime-client/tests/grpc_backend/scripted_service.rs +++ b/crates/runtime-client/tests/grpc_backend/scripted_service.rs @@ -5,23 +5,41 @@ use super::*; #[tonic::async_trait] impl proto::runtime_server::Runtime for Fake { - async fn handshake(&self, _: Request) -> Result, Status> { + async fn handshake( + &self, + _: Request, + ) -> Result, Status> { Ok(Response::new(self.snapshot())) } - async fn snapshot(&self, _: Request) -> Result, Status> { + async fn snapshot( + &self, + _: Request, + ) -> Result, Status> { Ok(Response::new(self.snapshot())) } type WatchStream = Pin> + Send>>; - async fn watch(&self, _: Request) -> Result, Status> { + async fn watch( + &self, + _: Request, + ) -> Result, Status> { Err(Status::unimplemented("fixture")) } - async fn load(&self, _: Request) -> Result, Status> { + async fn load( + &self, + _: Request, + ) -> Result, Status> { panic!("an attach-only backend must never send Load"); } - async fn unload(&self, _: Request) -> Result, Status> { + async fn unload( + &self, + _: Request, + ) -> Result, Status> { panic!("an attach-only backend must never send Unload"); } - async fn operation(&self, _: Request) -> Result, Status> { + async fn operation( + &self, + _: Request, + ) -> Result, Status> { Err(Status::unimplemented("fixture")) } async fn reconfigure( @@ -35,7 +53,11 @@ impl proto::runtime_server::Runtime for Fake { epoch: request.expected_epoch, ok: !refuse, effective_json: request.settings_json, - error_code: if refuse { "invalid".into() } else { String::new() }, + error_code: if refuse { + "invalid".into() + } else { + String::new() + }, error: if refuse { "context_tokens must be 1..=262144".into() } else { @@ -44,7 +66,10 @@ impl proto::runtime_server::Runtime for Fake { retryable: false, })) } - async fn cancel(&self, request: Request) -> Result, Status> { + async fn cancel( + &self, + request: Request, + ) -> Result, Status> { self.cancels.fetch_add(1, Ordering::SeqCst); let request = request.into_inner(); let ack = proto::CancelAck { @@ -55,7 +80,8 @@ impl proto::runtime_server::Runtime for Fake { self.state.lock().unwrap().cancel_requests.push(request); Ok(Response::new(ack)) } - type GenerateStream = Pin> + Send>>; + type GenerateStream = + Pin> + Send>>; async fn generate( &self, request: Request, @@ -71,35 +97,10 @@ impl proto::runtime_server::Runtime for Fake { }; (state.epoch.clone(), frames) }; - let id = request.request_id; - let mut out: Vec> = Vec::new(); - let sequence = 1; - let frame = |sequence, payload| proto::GenerationFrame { - request_id: id.clone(), - epoch: epoch.clone(), - sequence, - payload: Some(payload), - }; - out.push(Ok(frame( - sequence, - Payload::Accepted(proto::Accepted { accepted: true }), - ))); - for (sequence, item) in (2..).zip(frames) { - out.push(item.map(|payload| frame(sequence, payload))); - } + let out = scripted_frames(request.request_id, epoch, frames); // A trailing `Aborted("hang")` means: stay open and silent after the scripted frames. let hang = matches!(out.last(), Some(Err(s)) if s.code() == tonic::Code::Aborted && s.message() == "hang"); - if hang { - out.pop(); - } - let stream: Self::GenerateStream = if hang { - Box::pin(tokio_stream::StreamExt::chain( - tokio_stream::iter(out), - futures_util::stream::pending(), - )) - } else { - Box::pin(tokio_stream::iter(out)) - }; + let stream = scripted_stream(out, hang); let mut response = Response::new(stream); response .metadata_mut() @@ -107,3 +108,39 @@ impl proto::runtime_server::Runtime for Fake { Ok(response) } } + +/// The accepted frame, then the scripted payloads in sequence; an error item stays an error. +fn scripted_frames( + id: String, + epoch: String, + frames: Frames, +) -> Vec> { + let frame = |sequence, payload| proto::GenerationFrame { + request_id: id.clone(), + epoch: epoch.clone(), + sequence, + payload: Some(payload), + }; + let accepted = Payload::Accepted(proto::Accepted { accepted: true }); + let mut out: Vec> = vec![Ok(frame(1, accepted))]; + for (sequence, item) in (2..).zip(frames) { + out.push(item.map(|payload| frame(sequence, payload))); + } + out +} + +/// The frames as a stream; with `hang` the trailing marker is dropped and the stream stays open after the rest. +fn scripted_stream( + mut out: Vec>, + hang: bool, +) -> Pin> + Send>> { + if hang { + out.pop(); + Box::pin(tokio_stream::StreamExt::chain( + tokio_stream::iter(out), + futures_util::stream::pending(), + )) + } else { + Box::pin(tokio_stream::iter(out)) + } +}