From 5d2564f4ff6d1476430ea592ade5bc77004787c2 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 01:00:33 +0100 Subject: [PATCH] STRA-338 S6: control-plane/src/responses.rs children named by responsibility (intake, create, route, history, resources, errors, tool_recovery, reasoning, render) responses.rs is 97 lines (311 at the start of this step, after the domain move); the mechanical child names impl_* and *_fn are gone. Function texts are moved without change; the fields and constants that sibling modules read became pub(super). Public paths (responses::create, create_route, retrieve, delete, input_items, count_input_tokens, ResponseHistory, HistoryResponseStore, TracedJson, PromptDate, set_prompt_date, set_tool_call_recovery and the domain types) are unchanged. Functions that still miss the limits are listed in docs/architecture/tech-debt.md. Linux test ids of strata-control, strata-desktop-core, leleka-gateway-text and leleka-gateway-domain: 0 changed, 0 missing against the tip before S21 wider (2 new: the golden test and its ignored regenerator). --- control-plane/src/responses.rs | 174 +++++----------- .../src/responses/{create_fn.rs => create.rs} | 2 +- control-plane/src/responses/errors.rs | 78 ++++++++ ...et_tool_call_recovery_fn.rs => history.rs} | 145 ++++++++++++-- .../src/responses/impl_createrequest_2.rs | 70 ------- .../{vision_error_fn.rs => intake.rs} | 112 ++++++++--- control-plane/src/responses/queue_error_fn.rs | 31 --- .../{impl_reasoningstream.rs => reasoning.rs} | 8 +- .../{render_request_fn.rs => render.rs} | 0 .../src/responses/resource_query_error_fn.rs | 189 ------------------ control-plane/src/responses/resources.rs | 79 ++++++++ control-plane/src/responses/route.rs | 12 ++ ...se_output_items_fn.rs => tool_recovery.rs} | 22 +- .../src/responses/validate_live_subset_fn.rs | 18 -- docs/architecture/tech-debt.md | 15 ++ 15 files changed, 476 insertions(+), 479 deletions(-) rename control-plane/src/responses/{create_fn.rs => create.rs} (99%) create mode 100644 control-plane/src/responses/errors.rs rename control-plane/src/responses/{set_tool_call_recovery_fn.rs => history.rs} (57%) delete mode 100644 control-plane/src/responses/impl_createrequest_2.rs rename control-plane/src/responses/{vision_error_fn.rs => intake.rs} (70%) delete mode 100644 control-plane/src/responses/queue_error_fn.rs rename control-plane/src/responses/{impl_reasoningstream.rs => reasoning.rs} (92%) rename control-plane/src/responses/{render_request_fn.rs => render.rs} (100%) delete mode 100644 control-plane/src/responses/resource_query_error_fn.rs create mode 100644 control-plane/src/responses/resources.rs create mode 100644 control-plane/src/responses/route.rs rename control-plane/src/responses/{parse_output_items_fn.rs => tool_recovery.rs} (72%) delete mode 100644 control-plane/src/responses/validate_live_subset_fn.rs diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index bc778a7a..cf52445f 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -1,3 +1,16 @@ +//! `/v1/responses`: the HTTP handlers of the Responses API. The pure protocol is `leleka-gateway-domain`; the children +//! here are split by responsibility: +//! +//! * `route`, `create`: the create handler and its route layers; +//! * `intake`: the body, its decode and validation, and the prompt prepared for the engine; +//! * `render`, `reasoning`, `tool_recovery`: the prompt, the reasoning split and the tool-call reading, as wrappers over +//! the domain functions with the process-wide switches and the log lines; +//! * `stream`: the server-sent-event loops (plain text, buffered, tool calls); +//! * `history`, `history_adapter`, `resources`: the stored responses, the `ResponseStore` adapter and the retrieve, +//! input-items and delete routes; +//! * `errors`: the error answers; +//! * `harmony_prompt`: the gpt-oss system message and its date. + use axum::{ Json, extract::{Path, Query, RawQuery, State, rejection::JsonRejection}, @@ -40,64 +53,53 @@ use crate::prompt::{self, Message, Role}; use serde_json::Map; static NEXT_RESPONSE_ID: AtomicU64 = AtomicU64::new(0); -/// EXPERIMENTAL `tool_call_recovery` (config key or `STRATA_TOOL_CALL_RECOVERY`): off unless `main` turns it on at start. -static TOOL_CALL_RECOVERY: std::sync::atomic::AtomicBool = - std::sync::atomic::AtomicBool::new(false); - mod harmony_prompt; pub use harmony_prompt::{PromptDate, set_prompt_date}; -const MAX_STORED_RESPONSES: usize = 64; -const MAX_HISTORY_BYTES: usize = 128 * 1024 * 1024; - -#[derive(Clone, Default)] -pub struct ResponseHistory { - entries: HashMap>, - order: VecDeque, - bytes: usize, - store: Option>, -} - -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct StoredResponse { - model: String, - transcript: Vec, - input_len: usize, - response: Value, - bytes: usize, -} - -/// `Json` with the body read and parse timed as the stage `http_body_json`; same rejections. -pub struct TracedJson(pub Json); - -/// A request's prompt as the engine reads it: token ids (every image already expanded to its rows) and, with -/// pictures, the embeddings file `GENI` takes. -struct Prepared { - token_ids: Vec, - /// What `token_ids` is the encoding of (absent once pictures were expanded into the ids). Control-token text inside the - /// messages is still marked (`LiteralMarks`); a consumer that tokenizes it again must use `Tokenizer::encode_marked`. - prompt_text: Option>, - embeddings: Option, - keep: crate::vision::Keep, -} - -const IMAGE_PAD: &str = "<|image_pad|>"; -const VISION_START: &str = "<|vision_start|>"; - -/// The engines refuse a request unless `prompt + max_new + 8 <= context`. -const CONTEXT_MARGIN_TOKENS: usize = 8; - -#[derive(Default)] -struct ReasoningStream { - pending: Vec, - ended: bool, -} - +mod create; +pub use create::create; +mod errors; +#[allow(unused_imports)] +use errors::{ + api_error, debug_failed_output, log_generation_failure, queue_error, resource_not_found, + vision_error, +}; +mod history; +pub use history::ResponseHistory; +#[allow(unused_imports)] +use history::{MAX_HISTORY_BYTES, MAX_STORED_RESPONSES, StoredResponse, append_input}; mod history_adapter; pub use history_adapter::HistoryResponseStore; +mod intake; +#[allow(unused_imports)] +use intake::{ + CONTEXT_MARGIN_TOKENS, IMAGE_PAD, Prepared, VISION_START, expand_images, parse_request, + prepare_input_tokens, +}; +pub use intake::{TracedJson, count_input_tokens}; +mod reasoning; +#[cfg(test)] +use reasoning::render_request_prompt; +#[allow(unused_imports)] +use reasoning::{ReasoningStream, reasoning_plan}; +mod render; +use render::render_request; +mod resources; +#[allow(unused_imports)] +use resources::resource_query_error; +pub use resources::{delete, input_items, retrieve}; +mod route; +pub use route::create_route; mod stream; pub(crate) use stream::StreamEnv; use stream::*; +mod tool_recovery; +pub use tool_recovery::set_tool_call_recovery; +#[cfg(test)] +use tool_recovery::{decode_generation, parse_output_items}; +#[allow(unused_imports)] +use tool_recovery::{ + decode_generation_with, decoded_items, log_tool_notes, parse_output_items_after, tool_options, +}; // The pure part of the protocol lives in `leleka-gateway-domain`; the old paths stay. pub use leleka_gateway_domain::responses::{ @@ -114,73 +116,3 @@ use leleka_gateway_domain::responses::{ mod golden; #[cfg(test)] mod tests; - -mod set_tool_call_recovery_fn; -#[allow(unused_imports)] -use set_tool_call_recovery_fn::resource_not_found; -#[allow(unused_imports)] -pub use set_tool_call_recovery_fn::set_tool_call_recovery; -#[allow(unused_imports)] -use set_tool_call_recovery_fn::tool_options; -mod resource_query_error_fn; -#[allow(unused_imports)] -use resource_query_error_fn::append_input; -#[allow(unused_imports)] -pub use resource_query_error_fn::delete; -#[allow(unused_imports)] -pub use resource_query_error_fn::input_items; -#[allow(unused_imports)] -use resource_query_error_fn::resource_query_error; -#[allow(unused_imports)] -pub use resource_query_error_fn::retrieve; -mod impl_createrequest_2; -#[allow(unused_imports)] -use impl_createrequest_2::parse_request; -mod vision_error_fn; -#[allow(unused_imports)] -pub use vision_error_fn::count_input_tokens; -#[allow(unused_imports)] -use vision_error_fn::debug_failed_output; -#[allow(unused_imports)] -use vision_error_fn::expand_images; -#[allow(unused_imports)] -use vision_error_fn::log_generation_failure; -#[allow(unused_imports)] -use vision_error_fn::prepare_input_tokens; -#[allow(unused_imports)] -use vision_error_fn::vision_error; -mod queue_error_fn; -#[allow(unused_imports)] -pub use queue_error_fn::create_route; -#[allow(unused_imports)] -use queue_error_fn::queue_error; -mod create_fn; -#[allow(unused_imports)] -pub use create_fn::create; -mod parse_output_items_fn; -#[cfg(test)] -#[allow(unused_imports)] -use parse_output_items_fn::decode_generation; -#[allow(unused_imports)] -use parse_output_items_fn::decode_generation_with; -#[allow(unused_imports)] -use parse_output_items_fn::decoded_items; -#[allow(unused_imports)] -use parse_output_items_fn::log_tool_notes; -#[cfg(test)] -#[allow(unused_imports)] -use parse_output_items_fn::parse_output_items; -#[allow(unused_imports)] -use parse_output_items_fn::parse_output_items_after; -mod impl_reasoningstream; -#[allow(unused_imports)] -use impl_reasoningstream::reasoning_plan; -#[cfg(test)] -#[allow(unused_imports)] -use impl_reasoningstream::render_request_prompt; -mod render_request_fn; -#[allow(unused_imports)] -use render_request_fn::render_request; -mod validate_live_subset_fn; -#[allow(unused_imports)] -use validate_live_subset_fn::api_error; diff --git a/control-plane/src/responses/create_fn.rs b/control-plane/src/responses/create.rs similarity index 99% rename from control-plane/src/responses/create_fn.rs rename to control-plane/src/responses/create.rs index ccd57c2e..fc6c0c50 100644 --- a/control-plane/src/responses/create_fn.rs +++ b/control-plane/src/responses/create.rs @@ -1,4 +1,4 @@ -//! Moved out of the parent module by STRA-338: fn create. +//! `POST /v1/responses` handler: admission, intake, history lookup, prompt, the engine command and the answer. #[allow(unused_imports)] use super::*; diff --git a/control-plane/src/responses/errors.rs b/control-plane/src/responses/errors.rs new file mode 100644 index 00000000..508d3336 --- /dev/null +++ b/control-plane/src/responses/errors.rs @@ -0,0 +1,78 @@ +//! The error answers of the Responses handlers: the JSON error body, and the queue, vision and lookup failures. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn api_error( + status: StatusCode, + kind: &'static str, + code: &'static str, + param: Option<&'static str>, + message: &str, +) -> Response { + ( + status, + Json(json!({"error": {"message": message, "type": kind, "param": param, "code": code}})), + ) + .into_response() +} + +pub(super) fn queue_error(error: crate::queue::Error) -> Response { + match error { + crate::queue::Error::Expired => api_error( + StatusCode::GATEWAY_TIMEOUT, + "server_error", + "queue_timeout", + None, + "request exceeded the configured queue deadline before worker claim; generation was not started", + ), + crate::queue::Error::Closed => api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "worker_not_ready", + None, + "the Strata worker command queue closed before request claim", + ), + } +} + +pub(super) fn vision_error(error: crate::vision::VisionError) -> Box { + Box::new(match error { + crate::vision::VisionError::Invalid(message) => api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_image", + Some("input"), + &message, + ), + crate::vision::VisionError::Failed(message) => api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "vision_encoder_failed", + None, + &message, + ), + }) +} + +pub(super) fn resource_not_found() -> Response { + api_error( + StatusCode::NOT_FOUND, + "invalid_request_error", + "response_not_found", + Some("response_id"), + "the stored response is unavailable", + ) +} + +/// Every failed generation leaves one line in the log (the message is the one the client gets: no prompt or output text). +/// With `STRATA_DEBUG_FAILED_OUTPUT=1` the generated text of a failed streaming tool turn is logged too: operator debugging +/// only, because it is model output. +pub(super) fn log_generation_failure(message: &str) { + crate::elog!("generation failed: {message}"); +} + +pub(super) fn debug_failed_output() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("STRATA_DEBUG_FAILED_OUTPUT").is_some_and(|v| v == "1")) +} diff --git a/control-plane/src/responses/set_tool_call_recovery_fn.rs b/control-plane/src/responses/history.rs similarity index 57% rename from control-plane/src/responses/set_tool_call_recovery_fn.rs rename to control-plane/src/responses/history.rs index 7102ca94..4f6ebd6b 100644 --- a/control-plane/src/responses/set_tool_call_recovery_fn.rs +++ b/control-plane/src/responses/history.rs @@ -1,19 +1,28 @@ -//! Moved out of the parent module by STRA-338: fn set_tool_call_recovery, fn tool_options, impl ResponseHistory, fn resource_not_found. +//! The in-memory response history (64 entries, a byte limit) and its checksummed disk snapshot, and the paging of a +//! stored response's input items. #[allow(unused_imports)] use super::*; -/// Turn the experimental recovery of drifted tool-call forms on or off for the rest of the process. -pub fn set_tool_call_recovery(on: bool) { - TOOL_CALL_RECOVERY.store(on, Ordering::Relaxed); +pub(super) const MAX_STORED_RESPONSES: usize = 64; +pub(super) const MAX_HISTORY_BYTES: usize = 128 * 1024 * 1024; + +#[derive(Clone, Default)] +pub struct ResponseHistory { + pub(super) entries: HashMap>, + pub(super) order: VecDeque, + pub(super) bytes: usize, + pub(super) store: Option>, } -/// How tool calls are read: `natural_stop` as the generation ended, recovery as configured. -pub(super) fn tool_options(natural_stop: bool) -> tool_output::Options { - tool_output::Options { - natural_stop, - recovery: TOOL_CALL_RECOVERY.load(Ordering::Relaxed), - } +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct StoredResponse { + pub(super) model: String, + pub(super) transcript: Vec, + pub(super) input_len: usize, + pub(super) response: Value, + pub(super) bytes: usize, } impl ResponseHistory { @@ -210,12 +219,112 @@ impl ResponseHistory { } } -pub(super) fn resource_not_found() -> Response { - api_error( - StatusCode::NOT_FOUND, - "invalid_request_error", - "response_not_found", - Some("response_id"), - "the stored response is unavailable", - ) +impl StoredResponse { + pub(super) fn input_page( + &self, + id: &str, + options: &InputItemsQuery, + ) -> Result { + let descending = options.order.as_deref().unwrap_or("desc") == "desc"; + let prefix = format!("input_{id}_"); + let start = match options.after.as_deref() { + None => 0, + Some(cursor) => { + let index = cursor + .strip_prefix(&prefix) + .and_then(|s| s.parse::().ok()) + .filter(|i| *i < self.input_len && format!("{prefix}{i}") == cursor) + .ok_or("after does not identify an input item of this response")?; + if descending { + self.input_len - index + } else { + index + 1 + } + } + }; + let limit = options.limit.unwrap_or(20); + let count = self.input_len.saturating_sub(start).min(limit); + let mut data = Vec::with_capacity(count); + for position in start..start + count { + let index = if descending { + self.input_len - 1 - position + } else { + position + }; + // Project rather than mutate the transcript used for prompt replay. + // IDs identify occurrences in this response, so repeated client IDs + // cannot make a pagination cursor ambiguous. call_id stays intact. + let mut item = self.transcript[index].clone(); + item.as_object_mut() + .ok_or("stored input item is not an object")? + .insert("id".into(), json!(format!("{prefix}{index}"))); + if item.get("role").is_some() + && (item.get("type").is_none() || item["type"] == "message") + { + item["type"] = json!("message"); + if let Some(text) = item["content"].as_str() { + item["content"] = if item["role"] == "assistant" { + json!([{"type":"output_text","text":text,"annotations":[]}]) + } else { + json!([{"type":"input_text","text":text}]) + }; + } + let assistant = item["role"] == "assistant"; + if let Some(parts) = item["content"].as_array_mut() { + for part in parts { + if part["type"] == "input_text" || part["type"] == "output_text" { + part["type"] = json!(if assistant { + "output_text" + } else { + "input_text" + }); + if assistant && part.get("annotations").is_none() { + part["annotations"] = json!([]); + } + } + } + } + if item.get("status").is_none() { + item["status"] = json!("completed"); + } + } + data.push(item); + } + Ok( + json!({"object":"list", "first_id":data.first().map(|item| &item["id"]), + "last_id":data.last().map(|item| &item["id"]), + "has_more":self.input_len.saturating_sub(start) > count,"data":data}), + ) + } +} + +impl InputItemsQuery { + pub(super) fn parse(query: Option<&str>) -> Result { + let uri = format!("/?{}", query.unwrap_or("")) + .parse::() + .map_err(|_| "invalid input-items query")?; + let Query(options) = Query::::try_from_uri(&uri) + .map_err(|_| "only single after, limit and order query parameters are supported")?; + if options.limit.is_some_and(|n| !(1..=100).contains(&n)) + || options + .order + .as_deref() + .is_some_and(|s| s != "asc" && s != "desc") + || options + .after + .as_ref() + .is_some_and(|s| s.is_empty() || s.len() > 256) + { + return Err("limit must be 1..100, order asc|desc and after a nonempty item ID"); + } + Ok(options) + } +} + +pub(super) fn append_input(transcript: &mut Vec, input: &Value) { + if let Some(items) = input.as_array() { + transcript.extend(items.iter().cloned()); + } else if let Some(text) = input.as_str() { + transcript.push(json!({"role":"user","content":text})); + } } diff --git a/control-plane/src/responses/impl_createrequest_2.rs b/control-plane/src/responses/impl_createrequest_2.rs deleted file mode 100644 index 4a362e5b..00000000 --- a/control-plane/src/responses/impl_createrequest_2.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! Request intake: the body read as traced JSON, and the decode, validation and model check of a create request. - -#[allow(unused_imports)] -use super::*; - -impl axum::extract::FromRequest for TracedJson { - type Rejection = JsonRejection; - - async fn from_request( - request: axum::extract::Request, - state: &S, - ) -> Result { - let _span = crate::stage_trace::span("http_body_json"); - Json::::from_request(request, state).await.map(Self) - } -} - -pub(super) fn parse_request( - state: &AppState, - body: Result, JsonRejection>, -) -> Result> { - let Json(body) = match body { - Ok(body) => body, - Err(error) => { - return Err(Box::new(api_error( - error.status(), - "invalid_request_error", - "invalid_json", - None, - &error.to_string(), - ))); - } - }; - let decode = crate::stage_trace::span("request_decode"); - let request: CreateRequest = match serde_json::from_value(body) { - Ok(request) => request, - Err(error) => { - return Err(Box::new(api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_request", - None, - &error.to_string(), - ))); - } - }; - drop(decode); - let validated = crate::stage_trace::time("request_validate", || request.validate()); - if let Err((param, message)) = validated { - return Err(Box::new(api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_request", - Some(param), - message, - ))); - } - if state.model.name.as_ref().is_some_and(|model| { - model != &request.model && !state.model.aliases.contains(&request.model) - }) { - return Err(Box::new(api_error( - StatusCode::NOT_FOUND, - "invalid_request_error", - "model_not_found", - Some("model"), - "the requested model is not served by this runtime", - ))); - } - Ok(request) -} diff --git a/control-plane/src/responses/vision_error_fn.rs b/control-plane/src/responses/intake.rs similarity index 70% rename from control-plane/src/responses/vision_error_fn.rs rename to control-plane/src/responses/intake.rs index a76a5ab5..5a3d5f5d 100644 --- a/control-plane/src/responses/vision_error_fn.rs +++ b/control-plane/src/responses/intake.rs @@ -1,25 +1,93 @@ -//! Moved out of the parent module by STRA-338: fn vision_error, fn expand_images, fn prepare_input_tokens, fn count_input_tokens, fn log_generation_failure, fn debug_failed_output. +//! Request intake: the body read as traced JSON, the decode, validation and model check of a create request, and the +//! prompt prepared for the engine (token ids, with every picture expanded to its rows). #[allow(unused_imports)] use super::*; -pub(super) fn vision_error(error: crate::vision::VisionError) -> Box { - Box::new(match error { - crate::vision::VisionError::Invalid(message) => api_error( +/// `Json` with the body read and parse timed as the stage `http_body_json`; same rejections. +pub struct TracedJson(pub Json); + +/// A request's prompt as the engine reads it: token ids (every image already expanded to its rows) and, with +/// pictures, the embeddings file `GENI` takes. +pub(super) struct Prepared { + pub(super) token_ids: Vec, + /// What `token_ids` is the encoding of (absent once pictures were expanded into the ids). Control-token text inside the + /// messages is still marked (`LiteralMarks`); a consumer that tokenizes it again must use `Tokenizer::encode_marked`. + pub(super) prompt_text: Option>, + pub(super) embeddings: Option, + pub(super) keep: crate::vision::Keep, +} + +pub(super) const IMAGE_PAD: &str = "<|image_pad|>"; +pub(super) const VISION_START: &str = "<|vision_start|>"; + +/// The engines refuse a request unless `prompt + max_new + 8 <= context`. +pub(super) const CONTEXT_MARGIN_TOKENS: usize = 8; + +impl axum::extract::FromRequest for TracedJson { + type Rejection = JsonRejection; + + async fn from_request( + request: axum::extract::Request, + state: &S, + ) -> Result { + let _span = crate::stage_trace::span("http_body_json"); + Json::::from_request(request, state).await.map(Self) + } +} + +pub(super) fn parse_request( + state: &AppState, + body: Result, JsonRejection>, +) -> Result> { + let Json(body) = match body { + Ok(body) => body, + Err(error) => { + return Err(Box::new(api_error( + error.status(), + "invalid_request_error", + "invalid_json", + None, + &error.to_string(), + ))); + } + }; + let decode = crate::stage_trace::span("request_decode"); + let request: CreateRequest = match serde_json::from_value(body) { + Ok(request) => request, + Err(error) => { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_request", + None, + &error.to_string(), + ))); + } + }; + drop(decode); + let validated = crate::stage_trace::time("request_validate", || request.validate()); + if let Err((param, message)) = validated { + return Err(Box::new(api_error( StatusCode::BAD_REQUEST, "invalid_request_error", - "invalid_image", - Some("input"), - &message, - ), - crate::vision::VisionError::Failed(message) => api_error( - StatusCode::SERVICE_UNAVAILABLE, - "server_error", - "vision_encoder_failed", - None, - &message, - ), - }) + "invalid_request", + Some(param), + message, + ))); + } + if state.model.name.as_ref().is_some_and(|model| { + model != &request.model && !state.model.aliases.contains(&request.model) + }) { + return Err(Box::new(api_error( + StatusCode::NOT_FOUND, + "invalid_request_error", + "model_not_found", + Some("model"), + "the requested model is not served by this runtime", + ))); + } + Ok(request) } /// `Service.prepare`'s image branch: encode the pictures (in turn with the engine), then turn each @@ -223,15 +291,3 @@ pub async fn count_input_tokens( Err(error) => *error, } } - -/// Every failed generation leaves one line in the log (the message is the one the client gets: no prompt or output text). -/// With `STRATA_DEBUG_FAILED_OUTPUT=1` the generated text of a failed streaming tool turn is logged too: operator debugging -/// only, because it is model output. -pub(super) fn log_generation_failure(message: &str) { - crate::elog!("generation failed: {message}"); -} - -pub(super) fn debug_failed_output() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("STRATA_DEBUG_FAILED_OUTPUT").is_some_and(|v| v == "1")) -} diff --git a/control-plane/src/responses/queue_error_fn.rs b/control-plane/src/responses/queue_error_fn.rs deleted file mode 100644 index e20def2c..00000000 --- a/control-plane/src/responses/queue_error_fn.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Moved out of the parent module by STRA-338: fn queue_error, fn create_route. - -#[allow(unused_imports)] -use super::*; - -pub(super) fn queue_error(error: crate::queue::Error) -> Response { - match error { - crate::queue::Error::Expired => api_error( - StatusCode::GATEWAY_TIMEOUT, - "server_error", - "queue_timeout", - None, - "request exceeded the configured queue deadline before worker claim; generation was not started", - ), - crate::queue::Error::Closed => api_error( - StatusCode::SERVICE_UNAVAILABLE, - "server_error", - "worker_not_ready", - None, - "the Strata worker command queue closed before request claim", - ), - } -} - -/// The `/v1/responses` route: [`create`] with the body read and parse timed. -pub async fn create_route( - state: State, - body: Result, -) -> Response { - create(state, body.map(|traced| traced.0)).await -} diff --git a/control-plane/src/responses/impl_reasoningstream.rs b/control-plane/src/responses/reasoning.rs similarity index 92% rename from control-plane/src/responses/impl_reasoningstream.rs rename to control-plane/src/responses/reasoning.rs index 34cab104..56484544 100644 --- a/control-plane/src/responses/impl_reasoningstream.rs +++ b/control-plane/src/responses/reasoning.rs @@ -1,8 +1,14 @@ -//! The reasoning stream splitter and the reasoning-budget plan of a request. +//! The reasoning stream splitter (`` across chunks) and the reasoning-budget plan of a request. #[allow(unused_imports)] use super::*; +#[derive(Default)] +pub(super) struct ReasoningStream { + pending: Vec, + pub(super) ended: bool, +} + impl ReasoningStream { pub(super) fn push(&mut self, bytes: &[u8]) -> String { if self.ended { diff --git a/control-plane/src/responses/render_request_fn.rs b/control-plane/src/responses/render.rs similarity index 100% rename from control-plane/src/responses/render_request_fn.rs rename to control-plane/src/responses/render.rs diff --git a/control-plane/src/responses/resource_query_error_fn.rs b/control-plane/src/responses/resource_query_error_fn.rs deleted file mode 100644 index 5e19e347..00000000 --- a/control-plane/src/responses/resource_query_error_fn.rs +++ /dev/null @@ -1,189 +0,0 @@ -//! Moved out of the parent module by STRA-338: fn resource_query_error, fn retrieve, impl InputItemsQuery, impl StoredResponse, fn input_items, fn delete .... - -#[allow(unused_imports)] -use super::*; - -pub(super) fn resource_query_error(query: Option) -> Option { - query.filter(|value| !value.is_empty()).map(|_| { - api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "unsupported_query", - None, - "stored response query options and stream resumption are not supported", - ) - }) -} - -pub async fn retrieve( - State(state): State, - Path(id): Path, - RawQuery(query): RawQuery, -) -> Response { - if let Some(error) = resource_query_error(query) { - return error; - } - match state.services.responses.response(&id).await { - Some(response) => Json(response).into_response(), - None => resource_not_found(), - } -} - -impl InputItemsQuery { - pub(super) fn parse(query: Option<&str>) -> Result { - let uri = format!("/?{}", query.unwrap_or("")) - .parse::() - .map_err(|_| "invalid input-items query")?; - let Query(options) = Query::::try_from_uri(&uri) - .map_err(|_| "only single after, limit and order query parameters are supported")?; - if options.limit.is_some_and(|n| !(1..=100).contains(&n)) - || options - .order - .as_deref() - .is_some_and(|s| s != "asc" && s != "desc") - || options - .after - .as_ref() - .is_some_and(|s| s.is_empty() || s.len() > 256) - { - return Err("limit must be 1..100, order asc|desc and after a nonempty item ID"); - } - Ok(options) - } -} - -impl StoredResponse { - pub(super) fn input_page( - &self, - id: &str, - options: &InputItemsQuery, - ) -> Result { - let descending = options.order.as_deref().unwrap_or("desc") == "desc"; - let prefix = format!("input_{id}_"); - let start = match options.after.as_deref() { - None => 0, - Some(cursor) => { - let index = cursor - .strip_prefix(&prefix) - .and_then(|s| s.parse::().ok()) - .filter(|i| *i < self.input_len && format!("{prefix}{i}") == cursor) - .ok_or("after does not identify an input item of this response")?; - if descending { - self.input_len - index - } else { - index + 1 - } - } - }; - let limit = options.limit.unwrap_or(20); - let count = self.input_len.saturating_sub(start).min(limit); - let mut data = Vec::with_capacity(count); - for position in start..start + count { - let index = if descending { - self.input_len - 1 - position - } else { - position - }; - // Project rather than mutate the transcript used for prompt replay. - // IDs identify occurrences in this response, so repeated client IDs - // cannot make a pagination cursor ambiguous. call_id stays intact. - let mut item = self.transcript[index].clone(); - item.as_object_mut() - .ok_or("stored input item is not an object")? - .insert("id".into(), json!(format!("{prefix}{index}"))); - if item.get("role").is_some() - && (item.get("type").is_none() || item["type"] == "message") - { - item["type"] = json!("message"); - if let Some(text) = item["content"].as_str() { - item["content"] = if item["role"] == "assistant" { - json!([{"type":"output_text","text":text,"annotations":[]}]) - } else { - json!([{"type":"input_text","text":text}]) - }; - } - let assistant = item["role"] == "assistant"; - if let Some(parts) = item["content"].as_array_mut() { - for part in parts { - if part["type"] == "input_text" || part["type"] == "output_text" { - part["type"] = json!(if assistant { - "output_text" - } else { - "input_text" - }); - if assistant && part.get("annotations").is_none() { - part["annotations"] = json!([]); - } - } - } - } - if item.get("status").is_none() { - item["status"] = json!("completed"); - } - } - data.push(item); - } - Ok( - json!({"object":"list", "first_id":data.first().map(|item| &item["id"]), - "last_id":data.last().map(|item| &item["id"]), - "has_more":self.input_len.saturating_sub(start) > count,"data":data}), - ) - } -} - -pub async fn input_items( - State(state): State, - Path(id): Path, - RawQuery(query): RawQuery, -) -> Response { - let invalid = |message| { - api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_input_items_query", - None, - message, - ) - }; - let options = match InputItemsQuery::parse(query.as_deref()) { - Ok(options) => options, - Err(message) => return invalid(message), - }; - match state.services.responses.input_page(&id, &options).await { - None => resource_not_found(), - Some(Ok(page)) => Json(page).into_response(), - Some(Err(message)) => invalid(message), - } -} - -pub async fn delete( - State(state): State, - Path(id): Path, - RawQuery(query): RawQuery, -) -> Response { - if let Some(error) = resource_query_error(query) { - return error; - } - match state.services.responses.delete(&id).await { - Ok(true) => (), - Ok(false) => return resource_not_found(), - Err(_) => { - return api_error( - StatusCode::INSUFFICIENT_STORAGE, - "server_error", - "response_storage_failed", - None, - "cannot commit response deletion; inspect storage and restart", - ); - } - } - Json(json!({"id":id,"object":"response.deleted","deleted":true})).into_response() -} - -pub(super) fn append_input(transcript: &mut Vec, input: &Value) { - if let Some(items) = input.as_array() { - transcript.extend(items.iter().cloned()); - } else if let Some(text) = input.as_str() { - transcript.push(json!({"role":"user","content":text})); - } -} diff --git a/control-plane/src/responses/resources.rs b/control-plane/src/responses/resources.rs new file mode 100644 index 00000000..ce5ba615 --- /dev/null +++ b/control-plane/src/responses/resources.rs @@ -0,0 +1,79 @@ +//! The stored-response routes: retrieve, list input items and delete. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn resource_query_error(query: Option) -> Option { + query.filter(|value| !value.is_empty()).map(|_| { + api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "unsupported_query", + None, + "stored response query options and stream resumption are not supported", + ) + }) +} + +pub async fn retrieve( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + if let Some(error) = resource_query_error(query) { + return error; + } + match state.services.responses.response(&id).await { + Some(response) => Json(response).into_response(), + None => resource_not_found(), + } +} + +pub async fn input_items( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + let invalid = |message| { + api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_input_items_query", + None, + message, + ) + }; + let options = match InputItemsQuery::parse(query.as_deref()) { + Ok(options) => options, + Err(message) => return invalid(message), + }; + match state.services.responses.input_page(&id, &options).await { + None => resource_not_found(), + Some(Ok(page)) => Json(page).into_response(), + Some(Err(message)) => invalid(message), + } +} + +pub async fn delete( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + if let Some(error) = resource_query_error(query) { + return error; + } + match state.services.responses.delete(&id).await { + Ok(true) => (), + Ok(false) => return resource_not_found(), + Err(_) => { + return api_error( + StatusCode::INSUFFICIENT_STORAGE, + "server_error", + "response_storage_failed", + None, + "cannot commit response deletion; inspect storage and restart", + ); + } + } + Json(json!({"id":id,"object":"response.deleted","deleted":true})).into_response() +} diff --git a/control-plane/src/responses/route.rs b/control-plane/src/responses/route.rs new file mode 100644 index 00000000..31936075 --- /dev/null +++ b/control-plane/src/responses/route.rs @@ -0,0 +1,12 @@ +//! `POST /v1/responses` as the route sees it: the handler `create` behind the admission and API key layers. + +#[allow(unused_imports)] +use super::*; + +/// The `/v1/responses` route: [`create`] with the body read and parse timed. +pub async fn create_route( + state: State, + body: Result, +) -> Response { + create(state, body.map(|traced| traced.0)).await +} diff --git a/control-plane/src/responses/parse_output_items_fn.rs b/control-plane/src/responses/tool_recovery.rs similarity index 72% rename from control-plane/src/responses/parse_output_items_fn.rs rename to control-plane/src/responses/tool_recovery.rs index 00907202..1751c915 100644 --- a/control-plane/src/responses/parse_output_items_fn.rs +++ b/control-plane/src/responses/tool_recovery.rs @@ -1,9 +1,27 @@ -//! Reading the model's output: the wrappers that give the domain parsers the process-wide tool-call recovery flag and -//! write the log lines for calls accepted beyond the template form. +//! Reading tool calls out of the model's text: the process-wide switch of the experimental recovery, and the wrappers +//! that give the domain parsers that switch and write the log lines for calls accepted beyond the template form. #[allow(unused_imports)] use super::*; +/// EXPERIMENTAL `tool_call_recovery` (config key or `STRATA_TOOL_CALL_RECOVERY`): off unless `main` turns it on at +/// start. +static TOOL_CALL_RECOVERY: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +/// Turn the experimental recovery of drifted tool-call forms on or off for the rest of the process. +pub fn set_tool_call_recovery(on: bool) { + TOOL_CALL_RECOVERY.store(on, Ordering::Relaxed); +} + +/// How tool calls are read: `natural_stop` as the generation ended, recovery as configured. +pub(super) fn tool_options(natural_stop: bool) -> tool_output::Options { + tool_output::Options { + natural_stop, + recovery: TOOL_CALL_RECOVERY.load(Ordering::Relaxed), + } +} + #[cfg(test)] pub(super) fn parse_output_items( request: &CreateRequest, diff --git a/control-plane/src/responses/validate_live_subset_fn.rs b/control-plane/src/responses/validate_live_subset_fn.rs deleted file mode 100644 index a41387eb..00000000 --- a/control-plane/src/responses/validate_live_subset_fn.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! The JSON error body every Responses handler answers with. - -#[allow(unused_imports)] -use super::*; - -pub(super) fn api_error( - status: StatusCode, - kind: &'static str, - code: &'static str, - param: Option<&'static str>, - message: &str, -) -> Response { - ( - status, - Json(json!({"error": {"message": message, "type": kind, "param": param, "code": code}})), - ) - .into_response() -} diff --git a/docs/architecture/tech-debt.md b/docs/architecture/tech-debt.md index cffab4da..d003df83 100644 --- a/docs/architecture/tech-debt.md +++ b/docs/architecture/tech-debt.md @@ -286,3 +286,18 @@ What changed in the move, apart from `pub(super)` becoming `pub`: schema is validated three times per request). It moved with the function, so `process-global:leleka-gateway-domain` is 3 and `process-global:strata-control` fell from 14 to 11 (`--allow-increase` was used for the new key only; the sum is unchanged). Removing it needs the memo owned by the gateway state and passed to `validate`, which changes every caller. + +## strata-control `responses/` (STRA-338 S6, rest) + +`responses.rs` is 97 lines (module list and re-exports); its children are named for what they do: `route`, `create`, +`intake`, `render`, `reasoning`, `tool_recovery`, `stream/`, `history`, `history_adapter`, `resources`, `errors`, +`harmony_prompt`. The text of every function is unchanged (moved only); the fields and constants that siblings read +became `pub(super)`. Functions that still miss the limits (30 lines, complexity 10, nesting 4): + +| File | Function | Lines | Complexity | Removes it | +|---|---|---|---|---| +| `responses/create.rs` | `create` | 391 | 29 | admission, history lookup, prompt preparation, command build, buffered answer and stream start as separate functions | +| `responses/intake.rs` | `prepare_input_tokens` | 99 | 7 | text prompt, picture expansion and context check as three functions | +| `responses/intake.rs` | `expand_images`, `parse_request`, `count_input_tokens` | 62, 53, 34 | 2..5 | one step per function | +| `responses/history.rs` | `StoredResponse::input_page` | 76 | 18 | cursor parsing, order and limit as helpers (nesting 6) | +| `responses/history.rs` | `ResponseHistory::open`, `insert_with_limit` | 63, 55 | 19, 9 | snapshot decode and entry check as functions |