diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 8c39bc39..fdc7f3ed 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -51,6 +51,8 @@ use crate::prompt::{self, Effort, Message, Role}; #[cfg(test)] use serde_json::Map; +/// The tokenizer the request stages share. +type SharedCodec = Arc; static NEXT_RESPONSE_ID: AtomicU64 = AtomicU64::new(0); mod harmony_prompt; pub use harmony_prompt::{PromptDate, set_prompt_date}; diff --git a/control-plane/src/responses/intake/parts.rs b/control-plane/src/responses/intake/parts.rs index c4a59715..3e9a9b07 100644 --- a/control-plane/src/responses/intake/parts.rs +++ b/control-plane/src/responses/intake/parts.rs @@ -86,7 +86,7 @@ pub(super) async fn resolve_previous( /// The Qwen path renders through the chat template with the control-token marks and may carry pictures; the /// Harmony renderer of gpt-oss has no pictures. pub(super) fn render_prompt( - tokenizer: &Arc, + tokenizer: &SharedCodec, request: &CreateRequest, ) -> Result<(String, Vec), Box> { let rendered = crate::stage_trace::time("render", || match tokenizer.family() { @@ -112,7 +112,7 @@ pub(super) fn render_prompt( /// The one tokenization of a prompt, for generation and for counting: the template's own markers are special /// tokens, the control-token text inside the messages (marked by `render_request`) is ordinary text. pub(super) async fn tokenize_prompt( - tokenizer: Arc, + tokenizer: SharedCodec, prompt: String, ) -> Result<(Vec, String), Box> { let _tokenize = crate::stage_trace::span("tokenize"); diff --git a/control-plane/src/responses/stream.rs b/control-plane/src/responses/stream.rs index 050aa295..e9679bac 100644 --- a/control-plane/src/responses/stream.rs +++ b/control-plane/src/responses/stream.rs @@ -3,6 +3,9 @@ use super::*; +/// A token decoder borrowed for one stream. +type DecoderRef<'a> = &'a mut dyn crate::codec::TokenDecoder; + mod buffered; mod text; mod tool_run; diff --git a/control-plane/src/responses/stream/buffered.rs b/control-plane/src/responses/stream/buffered.rs index a2bc1979..5e51da15 100644 --- a/control-plane/src/responses/stream/buffered.rs +++ b/control-plane/src/responses/stream/buffered.rs @@ -1,13 +1,12 @@ //! Buffered streaming for structured output and reasoning (moved from responses.rs, STRA-338 S6). use super::*; -use crate::codec::TokenDecoder; use crate::wire::Done; /// What the stream is doing between the worker's events: the client connection, the numbering and the tokens so far. struct BufferedRun { request: CreateRequest, - tokenizer: Arc, + tokenizer: SharedCodec, source: mpsc::Receiver>, env: StreamEnv, sender: mpsc::Sender, @@ -23,7 +22,7 @@ struct BufferedRun { pub(in crate::responses) fn stream_live_buffered( request: CreateRequest, - tokenizer: Arc, + tokenizer: SharedCodec, source: mpsc::Receiver>, env: StreamEnv, ) -> Response { @@ -138,11 +137,7 @@ impl BufferedRun { } /// Keep one token; while thinking also decode it and stream the reasoning it completes. `Ok(false)`: client gone. - async fn push_token( - &mut self, - decoder: &mut dyn TokenDecoder, - token: u32, - ) -> Result { + async fn push_token(&mut self, decoder: DecoderRef<'_>, token: u32) -> Result { if self.thinking { let bytes = decoder.push(token)?; let delta = self.reasoning_stream.push(&bytes); diff --git a/control-plane/src/responses/stream/text.rs b/control-plane/src/responses/stream/text.rs index 7e562345..2067c680 100644 --- a/control-plane/src/responses/stream/text.rs +++ b/control-plane/src/responses/stream/text.rs @@ -1,13 +1,12 @@ //! Plain-text streaming of a Responses API generation (moved from responses.rs, STRA-338 S6). use super::*; -use crate::codec::TokenDecoder; use crate::wire::Done; /// What the stream is doing between the worker's events: the client connection, the numbering and the text so far. struct TextRun { request: CreateRequest, - tokenizer: Arc, + tokenizer: SharedCodec, source: mpsc::Receiver>, env: StreamEnv, sender: mpsc::Sender, @@ -22,7 +21,7 @@ struct TextRun { pub(in crate::responses) fn stream_live_text( request: CreateRequest, - tokenizer: Arc, + tokenizer: SharedCodec, source: mpsc::Receiver>, env: StreamEnv, ) -> Response { @@ -53,7 +52,7 @@ impl TextRun { /// The run for a new response, the receiver its events reach the client by and the initial events to send first. fn start( request: CreateRequest, - tokenizer: Arc, + tokenizer: SharedCodec, source: mpsc::Receiver>, env: StreamEnv, ) -> (Self, mpsc::Receiver, Vec) { @@ -122,11 +121,7 @@ impl TextRun { } /// Decode one token and stream the text it completes; `Ok(false)`: the client is gone. - async fn push_token( - &mut self, - decoder: &mut dyn TokenDecoder, - token: u32, - ) -> Result { + async fn push_token(&mut self, decoder: DecoderRef<'_>, token: u32) -> Result { let bytes = decoder.push(token)?; self.pending_bytes.extend_from_slice(&bytes); Ok(self.send_delta(false).await) diff --git a/control-plane/src/responses/stream/tool_run.rs b/control-plane/src/responses/stream/tool_run.rs index 4098d4a1..412a91f8 100644 --- a/control-plane/src/responses/stream/tool_run.rs +++ b/control-plane/src/responses/stream/tool_run.rs @@ -2,13 +2,12 @@ use super::tools::ToolStream; use super::*; -use crate::codec::TokenDecoder; use crate::wire::Done; /// What the stream is doing between the worker's events: the published items, the pending bytes and the debug copy. struct ToolsRun { request: CreateRequest, - tokenizer: Arc, + tokenizer: SharedCodec, source: mpsc::Receiver>, env: StreamEnv, stream: ToolStream, @@ -20,7 +19,7 @@ struct ToolsRun { pub(in crate::responses) fn stream_live_tools( request: CreateRequest, - tokenizer: Arc, + tokenizer: SharedCodec, source: mpsc::Receiver>, env: StreamEnv, ) -> Response { @@ -111,7 +110,7 @@ impl ToolsRun { /// Decode one token and publish the segments the text it completes makes whole. async fn push_token( &mut self, - decoder: &mut dyn TokenDecoder, + decoder: DecoderRef<'_>, parser: &mut Incremental<'_>, token: u32, ) -> Result<(), String> { diff --git a/control-plane/src/server_api/error_body.rs b/control-plane/src/server_api/error_body.rs index d60c9cc1..401905e9 100644 --- a/control-plane/src/server_api/error_body.rs +++ b/control-plane/src/server_api/error_body.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn error_body, fn reply, fn now_s, fn header_str, fn is_loaded, fn is_busy .... +//! Moved out of the parent module by STRA-338: fn error_body, fn reply, fn now_s, fn header_str, fn is_loaded, fn +//! is_busy .... #[allow(unused_imports)] use super::*; diff --git a/control-plane/src/server_api/model_busy.rs b/control-plane/src/server_api/model_busy.rs index 7ba194af..6e90e2a4 100644 --- a/control-plane/src/server_api/model_busy.rs +++ b/control-plane/src/server_api/model_busy.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn model_busy, fn v1_unload, fn v1_load, fn v1_reconfigure, fn api_requests, fn not_found .... +//! Moved out of the parent module by STRA-338: fn model_busy, fn v1_unload, fn v1_load, fn v1_reconfigure, fn +//! api_requests, fn not_found .... #[allow(unused_imports)] use super::*; @@ -44,12 +45,12 @@ pub async fn v1_load(State(state): State, headers: HeaderMap, body: By reply(StatusCode::OK, value) } -/// `POST /v1/reconfigure`: change the inference settings of the running engine without reloading the model (context length, -/// prefix cache, prefill chunk, CPU workers...). The body is a JSON object with any of: `context_tokens`, `prefill_capacity`, -/// `kv_resident` (only the value in force), `prefix_cache_mib`, `prefix_cache_tail`, `prefix_cache_block`, `prefix_retention_min`, -/// `cpu_workers` (1..=15), `spec_min_p`. The call waits for the request in flight, the engine reopens its serve stack (about 7 s on -/// the 5090; requests meanwhile wait in the queue) and the answer carries the effective settings; a refused change leaves the -/// previous settings in place. +/// `POST /v1/reconfigure`: change the inference settings of the running engine without reloading the model (context +/// length, prefix cache, prefill chunk, CPU workers...). The body is a JSON object with any of: `context_tokens`, +/// `prefill_capacity`, `kv_resident` (only the value in force), `prefix_cache_mib`, `prefix_cache_tail`, +/// `prefix_cache_block`, `prefix_retention_min`, `cpu_workers` (1..=15), `spec_min_p`. The call waits for the request +/// in flight, the engine reopens its serve stack (about 7 s on the 5090; requests meanwhile wait in the queue) and +/// the answer carries the effective settings; a refused change leaves the previous settings in place. pub async fn v1_reconfigure( State(state): State, headers: HeaderMap, @@ -58,25 +59,10 @@ pub async fn v1_reconfigure( if let Err(response) = own_page_check(&state, &headers, "the engine settings can be changed") { return *response; } - let parsed: Result = serde_json::from_slice(&body); - let Ok(settings) = parsed else { - return reply( - StatusCode::BAD_REQUEST, - error_body( - Some("invalid_request_error"), - "send a JSON object of settings", - ), - ); + let settings = match parse_settings(&body) { + Ok(settings) => settings, + Err(response) => return response, }; - if !settings.is_object() { - return reply( - StatusCode::BAD_REQUEST, - error_body( - Some("invalid_request_error"), - "send a JSON object of settings", - ), - ); - } let Some(control) = &state.engine.control else { return reply( StatusCode::NOT_IMPLEMENTED, @@ -84,19 +70,42 @@ pub async fn v1_reconfigure( ); }; let (answer, response) = tokio::sync::oneshot::channel(); - if control - .send(Control::Reconfigure { - settings: settings.to_string(), - reply: answer, - }) - .await - .is_err() - { - return reply( - StatusCode::SERVICE_UNAVAILABLE, - error_body(None, "the worker is gone"), - ); + let command = Control::Reconfigure { + settings: settings.to_string(), + reply: answer, + }; + if control.send(command).await.is_err() { + return worker_gone(); } + reconfigure_answer(response).await +} + +fn worker_gone() -> Response { + reply( + StatusCode::SERVICE_UNAVAILABLE, + error_body(None, "the worker is gone"), + ) +} + +/// The request body of a reconfigure: a JSON object of settings, or the 400 that says so. +fn parse_settings(body: &[u8]) -> Result { + let parsed: Result = serde_json::from_slice(body); + match parsed { + Ok(settings) if settings.is_object() => Ok(settings), + _ => Err(reply( + StatusCode::BAD_REQUEST, + error_body( + Some("invalid_request_error"), + "send a JSON object of settings", + ), + )), + } +} + +/// Wait for the engine's answer to a reconfigure (the engine reopens its serve stack) and shape the reply. +async fn reconfigure_answer( + response: tokio::sync::oneshot::Receiver>, +) -> Response { match tokio::time::timeout(std::time::Duration::from_secs(1900), response).await { Ok(Ok(Ok(effective))) => { let settings: Value = serde_json::from_str(&effective).unwrap_or(Value::Null); @@ -116,8 +125,9 @@ pub async fn v1_reconfigure( } } -/// `GET /api/requests`: the request monitor (`api_monitor` in the config; 404 while it is off, as in the Original). Without -/// `id` the retained requests, newest first, without prompts and answers; with `?id=` one whole record, or 404 once evicted. +/// `GET /api/requests`: the request monitor (`api_monitor` in the config; 404 while it is off, as in the Original). +/// Without `id` the retained requests, newest first, without prompts and answers; with `?id=` one whole record, or +/// 404 once evicted. pub async fn api_requests(State(state): State, RawQuery(query): RawQuery) -> Response { if !state.services.monitor.enabled() { return not_found().await; @@ -139,7 +149,8 @@ pub async fn api_requests(State(state): State, RawQuery(query): RawQue let worker = *state.engine.worker.read().await; reply( StatusCode::OK, - json!({"requests": state.services.monitor.summaries(), "retention": crate::request_monitor::RETENTION, "persistent": false, + json!({"requests": state.services.monitor.summaries(), + "retention": crate::request_monitor::RETENTION, "persistent": false, "loaded": is_loaded(&worker), "auto_load": state.engine.control.is_some()}), ) } @@ -192,8 +203,8 @@ pub async fn mcp_status(State(state): State) -> Response { reply(StatusCode::OK, body) } -/// `machine` of `GET /v1/status`: the engine's telemetry (GPU load and VRAM, RAM, CPU cores, throughput, cache hits, context) -/// when it reports any; the legacy `{at, gpu, ram}` shape with nulls otherwise. +/// `machine` of `GET /v1/status`: the engine's telemetry (GPU load and VRAM, RAM, CPU cores, throughput, cache hits, +/// context) when it reports any; the legacy `{at, gpu, ram}` shape with nulls otherwise. pub(super) fn machine_view(memory: &crate::memory_view::MemoryView) -> Value { let mut view = memory.telemetry_status(); if !view.is_object() { diff --git a/control-plane/src/server_api/slots.rs b/control-plane/src/server_api/slots.rs index 8463639a..2824c8ef 100644 --- a/control-plane/src/server_api/slots.rs +++ b/control-plane/src/server_api/slots.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn slots, fn v1_prefix_match, fn v1_status, fn status_value, fn settings_get, fn own_page_check .... +//! Moved out of the parent module by STRA-338: fn slots, fn v1_prefix_match, fn v1_status, fn status_value, fn +//! settings_get, fn own_page_check .... #[allow(unused_imports)] use super::*; @@ -16,25 +17,19 @@ pub async fn slots(State(state): State) -> Response { ) } -/// `POST /v1/prefix_match`: how many tokens of a prompt this runtime's prefix cache holds, for a pool router. -/// Body `{"block_hashes": ["<16 hex>", ...], "namespace": "<16 hex>"}`: the chain values of the prompt's full blocks in order -/// (see `docs/prefix-cache.md`); `namespace` is optional. The answer comes from the engine's last summary. +/// `POST /v1/prefix_match`: how many tokens of a prompt this runtime's prefix cache holds, for a pool router. Body +/// `{"block_hashes": ["<16 hex>", ...], "namespace": "<16 hex>"}`: the chain values of the prompt's full blocks in +/// order (see `docs/prefix-cache.md`); `namespace` is optional. The answer comes from the engine's last summary. pub async fn v1_prefix_match(State(state): State, body: Bytes) -> Response { let parsed: Result = serde_json::from_slice(&body); let Ok(request) = parsed else { - return reply( - StatusCode::BAD_REQUEST, - json!({"error": {"message": "the body must be a JSON object", "type": "invalid_request"}}), - ); + return invalid_request("the body must be a JSON object"); }; let hashes: Option> = request["block_hashes"] .as_array() .and_then(|list| list.iter().map(|h| h.as_str().map(str::to_owned)).collect()); let Some(hashes) = hashes else { - return reply( - StatusCode::BAD_REQUEST, - json!({"error": {"message": "block_hashes must be an array of hex strings", "type": "invalid_request"}}), - ); + return invalid_request("block_hashes must be an array of hex strings"); }; match state .model @@ -42,13 +37,21 @@ pub async fn v1_prefix_match(State(state): State, body: Bytes) -> Resp .prefix_match(request["namespace"].as_str(), &hashes) { Ok(answer) => reply(StatusCode::OK, answer), - Err(error) => reply( - StatusCode::BAD_REQUEST, - json!({"error": {"message": format!("{error:?}: at most {} lowercase-hex 16-digit chain values", crate::prefix_view::MAX_HASHES), "type": "invalid_request"}}), - ), + Err(error) => invalid_request(&format!( + "{error:?}: at most {} lowercase-hex 16-digit chain values", + crate::prefix_view::MAX_HASHES + )), } } +/// The 400 of the prefix-match route. +fn invalid_request(message: &str) -> Response { + reply( + StatusCode::BAD_REQUEST, + json!({"error": {"message": message, "type": "invalid_request"}}), + ) +} + /// `GET /v1/status`: what this server is and does, for a client that would rather ask than guess. pub async fn v1_status(State(state): State) -> Response { reply(StatusCode::OK, status_value(&state).await) @@ -56,19 +59,49 @@ pub async fn v1_status(State(state): State) -> Response { pub(super) async fn status_value(state: &AppState) -> Value { let worker = *state.engine.worker.read().await; - let lifecycle = state.lifecycle.snapshot(); - let busy = worker.metrics.active_since.is_some(); - let queued = lifecycle.generation_jobs.saturating_sub(usize::from(busy)); let context = context_of(&worker); - let last_at = worker - .last_activity - .map(|at| now_s().saturating_sub(at.elapsed().as_secs())); let started = state .services .started_at .duration_since(UNIX_EPOCH) .map_or(0, |d| d.as_secs()); - let timings = worker.metrics.last_done.map(|done| { + let mut body = json!({ + "service": "strata", "model": state.model.name, + "loaded": is_loaded(&worker), "auto_load": state.engine.control.is_some(), + "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", + "constrained_decoding": false, "stream_buffered": true}, + "engine": env!("CARGO_PKG_VERSION"), + "started": started, + "uptime_s": crate::app::uptime_s(state), + "cache_max_tokens": context, + "context": {"native": context, "max_positions": context}, + "concurrency": {"serving": 1, "requested": 1}, + "dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"], + "vision": {"enabled": state.model.vision.is_some(), "available": state.model.vision.is_some(), "error": null}, + "activity": activity_value(state, &worker), + "last_timings": last_timings(&worker), + "machine": machine_view(&state.model.memory), + "memory": state.model.memory.status(), + }); + add_prefix_cache(&mut body, state); + body +} + +/// Requests started, in flight and the time of the last one. +fn activity_value(state: &AppState, worker: &WorkerStatus) -> Value { + let lifecycle = state.lifecycle.snapshot(); + let busy = worker.metrics.active_since.is_some(); + let queued = lifecycle.generation_jobs.saturating_sub(usize::from(busy)); + let last_at = worker + .last_activity + .map(|at| now_s().saturating_sub(at.elapsed().as_secs())); + json!({"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued, + "last_request_at": last_at}) +} + +/// The timings of the last finished request, or null before the first one. +fn last_timings(worker: &WorkerStatus) -> Option { + worker.metrics.last_done.map(|done| { let mut value = leleka_serving_policy::timings::request_timings( &leleka_serving_policy::timings::Last { prompt_tokens: done.prompt_tokens, @@ -83,32 +116,15 @@ pub(super) async fn status_value(state: &AppState) -> Value { ); value["at"] = json!(now_s()); value - }); - let mut body = json!({ - "service": "strata", "model": state.model.name, - "loaded": is_loaded(&worker), "auto_load": state.engine.control.is_some(), - "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", - "constrained_decoding": false, "stream_buffered": true}, - "engine": env!("CARGO_PKG_VERSION"), - "started": started, - "uptime_s": crate::app::uptime_s(state), - "cache_max_tokens": context, - "context": {"native": context, "max_positions": context}, - "concurrency": {"serving": 1, "requested": 1}, - "dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"], - "vision": {"enabled": state.model.vision.is_some(), "available": state.model.vision.is_some(), "error": null}, - "activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued, - "last_request_at": last_at}, - "last_timings": timings, - "machine": machine_view(&state.model.memory), - "memory": state.model.memory.status(), - }); - // Present only when a prefix cache exists: the Python server's status has no such key (golden http_surface). + }) +} + +/// Present only when a prefix cache exists: the Python server's status has no such key (golden http_surface). +fn add_prefix_cache(body: &mut Value, state: &AppState) { let prefix = json!(state.model.prefix_cache.status()); if !prefix.is_null() { body["prefix_cache"] = prefix; } - body } /// `GET /settings`. diff --git a/control-plane/src/service_unit.rs b/control-plane/src/service_unit.rs index 24dd1b11..2557a3c6 100644 --- a/control-plane/src/service_unit.rs +++ b/control-plane/src/service_unit.rs @@ -7,6 +7,15 @@ pub fn render( working_dir: &Path, env_file: Option<&Path>, ) -> Result { + let executable = quoted_executable(executable)?; + let config = quote(&checked_path(config, false)?); + let working_dir = working_directory(working_dir)?; + let environment = environment_line(env_file)?; + Ok(unit_text(&working_dir, &environment, &executable, &config)) +} + +/// The executable path as a systemd `ExecStart` word. +fn quoted_executable(executable: &Path) -> Result { let executable = checked_path(executable, false)?; if executable.contains(['\'', '"', '\\']) { return Err( @@ -14,32 +23,42 @@ pub fn render( .into(), ); } - let executable = quote(&executable); - let config = quote(&checked_path(config, false)?); + Ok(quote(&executable)) +} + +fn working_directory(working_dir: &Path) -> Result { checked_path(working_dir, true)?; let canonical_dir = working_dir.canonicalize().map_err(|e| e.to_string())?; // These path directives are not shell-style token lists. Quotes and // backslashes are literal; a final '/.' prevents line continuation/trim. - let working_dir = format!( + Ok(format!( "{}/.", checked_path(&canonical_dir, true)?.trim_end_matches('/') ) - .replace('%', "%%"); - let environment = match env_file { - Some(path) => { - let value = checked_path(path, false)?; - // EnvironmentFile supports globs. Fail rather than load a different - // file, or silently treat a missing optional file as success. - if value.contains(['*', '?', '[', '\\']) || value.ends_with(char::is_whitespace) { - return Err("environment-file paths cannot contain glob characters/backslashes or end in whitespace".into()); - } - format!("EnvironmentFile={}\n", value.replace('%', "%%")) - } - None => String::new(), + .replace('%', "%%")) +} + +fn environment_line(env_file: Option<&Path>) -> Result { + let Some(path) = env_file else { + return Ok(String::new()); }; + let value = checked_path(path, false)?; + // EnvironmentFile supports globs. Fail rather than load a different + // file, or silently treat a missing optional file as success. + if value.contains(['*', '?', '[', '\\']) || value.ends_with(char::is_whitespace) { + return Err(concat!( + "environment-file paths cannot contain glob characters/backslashes ", + "or end in whitespace" + ) + .into()); + } + Ok(format!("EnvironmentFile={}\n", value.replace('%', "%%"))) +} + +fn unit_text(working_dir: &str, environment: &str, executable: &str, config: &str) -> String { // ':' disables ExecStart environment-variable substitution; %% escapes // specifiers. Do not wrap this in a shell or reset the worker restart budget. - Ok(format!( + format!( "# Generated by strata-next service-unit; install as a user unit.\n\ [Unit]\n\ Description=Strata Next native Responses runtime\n\ @@ -61,7 +80,7 @@ pub fn render( \n\ [Install]\n\ WantedBy=default.target\n" - )) + ) } fn checked_path(path: &Path, directory: bool) -> Result { diff --git a/control-plane/src/vision/config.rs b/control-plane/src/vision/config.rs index c3873e82..16003cfd 100644 --- a/control-plane/src/vision/config.rs +++ b/control-plane/src/vision/config.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl VisionConfig, impl std_fmt_Display, impl std_error_Error, impl Keep, impl PartialEq_for_Keep, impl Drop_for_TempFile. +//! Moved out of the parent module by STRA-338: impl VisionConfig, impl std_fmt_Display, impl std_error_Error, impl +//! Keep, impl PartialEq_for_Keep, impl Drop_for_TempFile. #[allow(unused_imports)] use super::*; diff --git a/control-plane/src/vision/encoder.rs b/control-plane/src/vision/encoder.rs index 34ce6f5a..bdcff649 100644 --- a/control-plane/src/vision/encoder.rs +++ b/control-plane/src/vision/encoder.rs @@ -20,6 +20,36 @@ fn reply_tokens(line: &str) -> Result { .ok_or_else(|| VisionError::Failed(format!("unexpected vision encoder reply: {line}"))) } +/// Wait for the `READY` line of a freshly started encoder; the process is killed when it does not come. +async fn await_ready( + child: &mut Child, + lines: &mut tokio::io::Lines>, +) -> Result<(), VisionError> { + let first = match timeout(START_TIMEOUT, lines.next_line()).await { + Ok(Ok(Some(line))) => line, + Ok(Ok(None)) => String::new(), + Ok(Err(e)) => { + return Err(VisionError::Failed(format!( + "the vision encoder did not start: {e}" + ))); + } + Err(_) => { + let _ = child.kill().await; + return Err(VisionError::Failed( + "the vision encoder did not start: no READY line in time".into(), + )); + } + }; + if !first.starts_with("READY") { + let _ = child.kill().await; + return Err(VisionError::Failed(format!( + "the vision encoder did not start: {}", + first.trim() + ))); + } + Ok(()) +} + impl Vision { /// Start the encoder and wait for its `READY` line (`Vision.__init__`). pub async fn start(config: VisionConfig) -> Result, VisionError> { @@ -55,6 +85,22 @@ impl Vision { } pub(super) async fn spawn(&self, inner: &mut Inner) -> Result<(), VisionError> { + let mut child = self.launch()?; + let stdin = child.stdin.take().expect("piped encoder stdin"); + let stdout = child.stdout.take().expect("piped encoder stdout"); + let mut lines = BufReader::new(stdout).lines(); + await_ready(&mut child, &mut lines).await?; + inner.proc = Some(Proc { + child, + stdin, + lines, + }); + self.stopped.store(false, Ordering::Release); + Ok(()) + } + + /// The encoder process with piped stdin and stdout. + fn launch(&self) -> Result { let mut command = Command::new(&self.config.exe); command .args(self.config.args()) @@ -65,44 +111,12 @@ impl Vision { for (name, value) in self.config.env() { command.env(name, value); } - let mut child = command.spawn().map_err(|e| { + command.spawn().map_err(|e| { VisionError::Failed(format!( "the vision encoder did not start: {}: {e}", self.config.exe.display() )) - })?; - let stdin = child.stdin.take().expect("piped encoder stdin"); - let stdout = child.stdout.take().expect("piped encoder stdout"); - let mut lines = BufReader::new(stdout).lines(); - let first = match timeout(START_TIMEOUT, lines.next_line()).await { - Ok(Ok(Some(line))) => line, - Ok(Ok(None)) => String::new(), - Ok(Err(e)) => { - return Err(VisionError::Failed(format!( - "the vision encoder did not start: {e}" - ))); - } - Err(_) => { - let _ = child.kill().await; - return Err(VisionError::Failed( - "the vision encoder did not start: no READY line in time".into(), - )); - } - }; - if !first.starts_with("READY") { - let _ = child.kill().await; - return Err(VisionError::Failed(format!( - "the vision encoder did not start: {}", - first.trim() - ))); - } - inner.proc = Some(Proc { - child, - stdin, - lines, - }); - self.stopped.store(false, Ordering::Release); - Ok(()) + }) } /// `Vision.alive`: started, not unloaded, and the process still runs. diff --git a/control-plane/src/wire.rs b/control-plane/src/wire.rs index b43efa35..f8162c4d 100644 --- a/control-plane/src/wire.rs +++ b/control-plane/src/wire.rs @@ -55,9 +55,9 @@ pub struct Generate { pub keep: crate::vision::Keep, /// Reasoning-budget wrap-up, executed by the worker; never sent to the engine. pub reasoning: Option, - /// The text `token_ids` was produced from (`encode(text, true)`), when the HTTP layer still has it. A text-level engine - /// is sent this text after a cheap check that the ids decode to it, instead of decoding the ids and tokenizing the result - /// again to prove they round-trip. + /// The text `token_ids` was produced from (`encode(text, true)`), when the HTTP layer still has it. A text-level + /// engine is sent this text after a cheap check that the ids decode to it, instead of decoding the ids and + /// tokenizing the result again to prove they round-trip. pub prompt_text: Option>, /// The request's log record (`request_log`); empty outside the HTTP generation routes. pub obs: crate::request_log::ObsHandle, diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs index 634dc562..191592c4 100644 --- a/control-plane/src/worker.rs +++ b/control-plane/src/worker.rs @@ -54,8 +54,9 @@ pub struct WorkerStatus { /// runtime gRPC facade does). A default output budget never exceeds it; an explicit request above /// it is refused by the worker, not truncated. pub output_cap: Option, - /// The engine speaks the text-level contract (a runtime backend): per-request token-level features it cannot carry - /// (`reasoning_budget_tokens`, `strata_tune`, `experimental_speed_projection`) are refused with a 400 by the HTTP layer. + /// The engine speaks the text-level contract (a runtime backend): per-request token-level features it cannot + /// carry (`reasoning_budget_tokens`, `strata_tune`, `experimental_speed_projection`) are refused with a 400 by + /// the HTTP layer. pub text_level_engine: bool, } diff --git a/control-plane/src/worker/finish.rs b/control-plane/src/worker/finish.rs index e98f9735..849dd011 100644 --- a/control-plane/src/worker/finish.rs +++ b/control-plane/src/worker/finish.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn finish, fn unix_ms, fn send_failure, fn parse_ready, fn update, fn stop .... +//! Moved out of the parent module by STRA-338: fn finish, fn unix_ms, fn send_failure, fn parse_ready, fn update, +//! fn stop .... #[allow(unused_imports)] use super::*; diff --git a/control-plane/src/worker/generation_result.rs b/control-plane/src/worker/generation_result.rs index 6d821284..4124db64 100644 --- a/control-plane/src/worker/generation_result.rs +++ b/control-plane/src/worker/generation_result.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl GenerationResult, impl Default_for_WorkerStatus, impl Default_for_WorkerConfig, fn reconfigure_unavailable, fn run, fn run_with_requests .... +//! Moved out of the parent module by STRA-338: impl GenerationResult, impl Default_for_WorkerStatus, +//! impl Default_for_WorkerConfig, fn reconfigure_unavailable, fn run, fn run_with_requests .... #[allow(unused_imports)] use super::*;