strata-control: env_settings reader, explicit imports, no blanket unused-import allows, MCP and hardware series on a clock, doc headers and renamed modules

env-read 14 -> 0 outside src/env_settings.rs (config/process_env.rs removed; typed text/number/path/mode accessors), glob-super-import 9 -> 0, allow-unused-imports 48 -> 0, 38 modules renamed by responsibility (worker_entry, serve_generation, file_download, pack_outputs, request_context, status_routes, ...). The hot-path code (admission, streaming, gRPC client) is untouched here.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-14 19:40:20 +01:00
co-authored by Claude Sonnet 5.5
parent 13742421bb
commit 64b6c6d30a
126 changed files with 534 additions and 417 deletions
+1 -1
View File
@@ -189,7 +189,7 @@ pub(crate) fn uptime_s(state: &AppState) -> u64 {
/// The supervisor's own account (`LELEKA_STATUS_FILE`, set by `leleka run`): restarts and uptime of the service.
/// `null` when this process was not started by a supervisor, or the file cannot be read.
pub(super) fn supervisor_block() -> serde_json::Value {
let Some(path) = std::env::var_os("LELEKA_STATUS_FILE") else {
let Some(path) = crate::env_settings::supervisor_status_file() else {
return serde_json::Value::Null;
};
let Ok(text) = std::fs::read_to_string(path) else {
+9 -15
View File
@@ -115,20 +115,14 @@ struct Conclusion<'a> {
}
mod attach;
#[allow(unused_imports)]
pub use attach::*;
use attach::*;
mod generation_run;
#[allow(unused_imports)]
pub use generation_run::*;
mod request_id;
#[allow(unused_imports)]
pub use request_id::*;
mod run_backend_worker;
#[allow(unused_imports)]
pub use run_backend_worker::*;
mod serve_one;
#[allow(unused_imports)]
pub use serve_one::*;
use generation_run::*;
mod engine_request_checks;
use engine_request_checks::*;
mod worker_entry;
pub use worker_entry::*;
mod serve_generation;
use serve_generation::*;
mod conclude;
#[allow(unused_imports)]
pub use conclude::*;
use conclude::*;
+3 -2
View File
@@ -1,5 +1,6 @@
//! Methods of `Ending`: `done`, `fail`, `finish_with`, `deliver_tail` and 4 more. Functions: `timings`, `conclude`.
//! Defines `Ending`.
//! Ends one generation: turns the engine's terminal event (completed, cancelled, failed or vanished) into the `Done`
//! record or the failure the HTTP layer sees, flushing any held-back text and settling the usage and timings.
//! It is separate because the end-of-stream cases (client cancel, stop marker, engine failure) are one decision table.
use super::{
Cancel, Conclusion, Done, Event, Finish, GenerationCommand, Instant, RwLock, Served, WorkerStatus, api, deliver,
@@ -1,5 +1,6 @@
//! Functions: `request_id`, `on_engine`, `prompt_text`, `text_tokens` and 5 more.
//! Split out of `backend_worker` to keep its files under the line limit.
//! The edge between the HTTP layer's token ids and the text-level engine contract: request UUIDs, running blocking
//! engine calls off the async threads, the prompt and delta re-tokenization checks, and the refusal of requests the
//! text contract cannot carry. Every check fails closed so the engine never sees different tokens than were counted.
use super::{Arc, BackendWorkerConfig, Engine, Generate, Tokenizer, api};
@@ -1,5 +1,5 @@
//! Functions: `serve_one`, `call_start`, `count_failed_start`, `answer_refused_start` and 5 more.
//! Split out of `backend_worker` to keep its files under the line limit.
//! Serves one queued generation: asks the engine to start it, answers a refused or lost start, hands the event stream
//! to the pump, and closes the request record. It decides whether the engine stays attached after a refusal.
use super::{
Context, Engine, GenerationCommand, Run, RwLock, Served, Started, WorkerStatus, api, fail_command, on_engine,
@@ -1,5 +1,6 @@
//! Functions: `run_backend_worker`, `refresh_prefix_view`, `trigger_cancel`, `fail_command`.
//! Split out of `backend_worker` to keep its files under the line limit.
//! The worker entry point: wraps the backend in the shared engine handle and runs the attach loop. Also holds the
//! small engine-facing actions the loop and the serve path share: refreshing the prefix-cache and memory views the
//! status endpoint reads, cancelling a running request, and failing a queued one.
use super::{
Arc, AttachLoop, BackendWorkerConfig, Engine, GenerationCommand, Mutex, RwLock, WorkerInbox, WorkerStatus, api,
+3 -5
View File
@@ -21,9 +21,7 @@ use leleka_gateway_domain::chat_completions::{Request, call, finish, identity, u
struct Events(mpsc::Receiver<Event>);
mod completion;
#[allow(unused_imports)]
pub use completion::*;
mod chat_completions_endpoint;
pub use chat_completions_endpoint::*;
mod stream_response;
#[allow(unused_imports)]
pub use stream_response::*;
use stream_response::*;
@@ -1,5 +1,6 @@
//! Methods of `Adapter`: `base`, `push`, `done_marker`, `created` and 5 more. Implements `Stream for Events`.
//! Functions: `append_message_text`, `collect_output`, `completion`, `error` and 8 more. Defines `Adapter`.
//! The Chat Completions endpoint: parses the request, runs it through the native Responses handler, and converts the
//! native answer back, either as one `chat.completion` object or as a stream of `chat.completion.chunk` events
//! produced by the `Adapter`. Also builds the OpenAI-shaped error bodies.
use super::{
AppState, Body, Context, Event, Events, Infallible, IntoResponse, Json, JsonRejection, MAX_EVENT, NativeEvents,
+2 -2
View File
@@ -1,5 +1,5 @@
//! Functions: `stream_response`.
//! Split out of `chat` to keep its files under the line limit.
//! The streaming reply of Chat Completions: runs the adapter on its own task and hands its chunks to the client as
//! server-sent events, ending with an error chunk and `[DONE]` if the adapter fails.
use super::{Body, Event, Events, IntoResponse, Response, Sse, adapt, json, mpsc, send};
+3 -4
View File
@@ -1,5 +1,4 @@
use std::{
env,
ffi::OsString,
fs,
net::SocketAddr,
@@ -9,6 +8,9 @@ use std::{
use serde::Deserialize;
#[cfg(test)]
use std::env;
use crate::worker::WorkerConfig;
pub struct Config {
@@ -168,6 +170,3 @@ pub use control_vector::*;
mod methods;
#[allow(unused_imports)]
pub use methods::*;
mod process_env;
#[allow(unused_imports)]
pub use process_env::*;
+3 -2
View File
@@ -1,5 +1,6 @@
//! Methods of `ControlVector`: `engine_args`, `checked_mode`, `arguments`.
//! Functions: `check_entry`, `read_vector`, `check_direction`, `check_directions`.
//! Preflight of the experimental control-vector setting: every listed GGUF file is read and checked (absolute path,
//! finite scale, f32 direction tensors of one width) before the engine arguments that load it are built. A bad file
//! stops the start instead of failing inside the engine.
use super::{ControlVector, ControlVectorFile, fs};
+1 -2
View File
@@ -2,7 +2,6 @@
use super::{
Config, Duration, FileConfig, FileEngine, FileExtraWorker, OsString, Path, PathBuf, SocketAddr, WorkerConfig, fs,
optional_env, optional_env_os,
};
mod load;
@@ -11,4 +10,4 @@ mod load_engine;
mod config_assembly;
mod load_sections;
mod load_with_path;
mod provision;
mod startup_preparation;
+1 -2
View File
@@ -1,5 +1,4 @@
//! Methods of `Config`: `load`.
//! Split out of `methods` to keep its files under the line limit.
//! `Config::load`: the entry point without an explicit file path; the file is then chosen by `STRATA_CONFIG`.
use super::Config;
@@ -2,7 +2,7 @@
//! the single function used to run them. Each fails with the same message as before.
use super::config_assembly::{EngineSide, Identity, Surface};
use super::{Config, FileConfig, Path, PathBuf, WorkerConfig, fs, optional_env, optional_env_os};
use super::{Config, FileConfig, Path, PathBuf, WorkerConfig, fs};
/// The file named by the CLI path or the environment, parsed, with its asset bundles and native model validated.
pub(super) fn read_checked_file(
@@ -20,7 +20,7 @@ pub(super) fn read_checked_file(
fn read_file(path: Option<&Path>) -> Result<(Option<PathBuf>, FileConfig), crate::BoxError> {
let config_path = path
.map(|p| p.as_os_str().to_owned())
.or_else(|| optional_env_os("STRATA_CONFIG"))
.or_else(|| crate::env_settings::os_string("STRATA_CONFIG"))
.map(PathBuf::from);
let file = match &config_path {
Some(path) => serde_json::from_str::<FileConfig>(&fs::read_to_string(path)?)?,
@@ -39,7 +39,7 @@ fn tokenizer_setting(
file: &FileConfig,
worker: Option<&WorkerConfig>,
) -> Result<Option<PathBuf>, crate::BoxError> {
let mut tokenizer_dir = optional_env_os("STRATA_TOKENIZER_DIR")
let mut tokenizer_dir = crate::env_settings::os_string("STRATA_TOKENIZER_DIR")
.map(PathBuf::from)
.or_else(|| {
file.engine
@@ -96,7 +96,7 @@ fn gptoss_setting(
worker: Option<&WorkerConfig>,
tokenizer_dir: Option<&PathBuf>,
) -> Result<Option<PathBuf>, crate::BoxError> {
let gptoss_gguf = optional_env_os("STRATA_GPTOSS_GGUF")
let gptoss_gguf = crate::env_settings::os_string("STRATA_GPTOSS_GGUF")
.map(PathBuf::from)
.or_else(|| {
file.engine
@@ -160,7 +160,7 @@ fn is_name_byte(b: u8) -> bool {
/// `STRATA_MODEL_ID` or the file's `model`: 1..180 ASCII letters, digits, dots, hyphens or underscores.
fn model_id(from_file: Option<String>) -> Result<Option<String>, crate::BoxError> {
let model = optional_env("STRATA_MODEL_ID")?.or(from_file);
let model = crate::env_settings::text("STRATA_MODEL_ID")?.or(from_file);
if model
.as_ref()
.is_some_and(|id| id.is_empty() || id.len() > 180 || !id.bytes().all(is_name_byte))
@@ -176,7 +176,7 @@ fn model_id(from_file: Option<String>) -> Result<Option<String>, crate::BoxError
fn api_key_setting(
from_file: Option<PathBuf>,
) -> Result<Option<std::sync::Arc<crate::auth::ApiKey>>, crate::BoxError> {
let key = optional_env_os("STRATA_API_KEY_FILE")
let key = crate::env_settings::os_string("STRATA_API_KEY_FILE")
.map(PathBuf::from)
.or(from_file)
.map(|path| crate::auth::ApiKey::from_file(&path).map(std::sync::Arc::new))
@@ -186,7 +186,7 @@ fn api_key_setting(
/// `STRATA_RESPONSE_HISTORY_DIR` or the file's: absolute, not the root, no `..`.
fn history_dir_setting(from_file: Option<PathBuf>) -> Result<Option<PathBuf>, crate::BoxError> {
let dir = optional_env_os("STRATA_RESPONSE_HISTORY_DIR")
let dir = crate::env_settings::os_string("STRATA_RESPONSE_HISTORY_DIR")
.map(PathBuf::from)
.or(from_file);
if dir.as_ref().is_some_and(|p| {
@@ -268,7 +268,7 @@ pub(super) fn check_vision(
/// `STRATA_TOOL_CALL_RECOVERY` (1, true, 0, false) or the file's `tool_call_recovery`.
pub(super) fn tool_call_recovery(from_file: Option<bool>) -> Result<bool, crate::BoxError> {
match optional_env("STRATA_TOOL_CALL_RECOVERY")?.as_deref() {
match crate::env_settings::text("STRATA_TOOL_CALL_RECOVERY")?.as_deref() {
Some("1" | "true") => Ok(true),
Some("0" | "false") => Ok(false),
Some(other) => Err(format!(
@@ -1,7 +1,7 @@
//! The engine section of the config as `Config::read_engine` reads it: the knobs of the main worker, the worker
//! itself, and the pool of extra workers. Same messages, same order as when it was one function.
use super::{Duration, FileConfig, FileEngine, FileExtraWorker, OsString, WorkerConfig, optional_env};
use super::{Duration, FileConfig, FileEngine, FileExtraWorker, OsString, WorkerConfig};
/// The numbers and arguments of the main worker, each already checked against its range.
pub(super) struct Knobs {
@@ -13,20 +13,11 @@ pub(super) struct Knobs {
pub(super) idle_unload_s: Option<f64>,
}
fn parsed_env<T: std::str::FromStr>(name: &str) -> Result<Option<T>, crate::BoxError>
where
T::Err: std::error::Error + 'static,
{
Ok(optional_env(name)?
.map(|value| value.parse::<T>())
.transpose()?)
}
fn args_and_startup_timeout(file: &FileConfig) -> Result<(Vec<String>, u64), crate::BoxError> {
let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")?
let args_override = crate::env_settings::text("STRATA_ENGINE_ARGS_JSON")?
.map(|value| serde_json::from_str::<Vec<String>>(&value))
.transpose()?;
let timeout_override = parsed_env::<u64>("STRATA_STARTUP_TIMEOUT_S")?;
let timeout_override = crate::env_settings::number::<u64>("STRATA_STARTUP_TIMEOUT_S")?;
let configured_args = file.engine.as_ref().map(|engine| engine.args.clone());
let args = args_override.or(configured_args).unwrap_or_default();
let startup_timeout_s = timeout_override
@@ -43,7 +34,7 @@ fn args_and_startup_timeout(file: &FileConfig) -> Result<(Vec<String>, u64), cra
}
fn restarts_limit(file: &FileConfig) -> Result<u32, crate::BoxError> {
let max_restarts = parsed_env::<u32>("STRATA_MAX_WORKER_RESTARTS")?
let max_restarts = crate::env_settings::number::<u32>("STRATA_MAX_WORKER_RESTARTS")?
.or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts))
.unwrap_or(3);
if max_restarts > 3 {
@@ -53,7 +44,7 @@ fn restarts_limit(file: &FileConfig) -> Result<u32, crate::BoxError> {
}
fn generation_timeout(file: &FileConfig) -> Result<Option<u64>, crate::BoxError> {
let generation_timeout_s = parsed_env::<u64>("STRATA_GENERATION_TIMEOUT_S")?.or_else(|| {
let generation_timeout_s = crate::env_settings::number::<u64>("STRATA_GENERATION_TIMEOUT_S")?.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.generation_timeout_s)
@@ -3,7 +3,7 @@
//! same order as when it was one function.
use super::load_engine as engine;
use super::{Config, FileConfig, OsString, Path, SocketAddr, WorkerConfig, optional_env, optional_env_os};
use super::{Config, FileConfig, OsString, Path, SocketAddr, WorkerConfig};
pub(super) struct Limits {
pub(super) bind: SocketAddr,
@@ -24,16 +24,14 @@ type Servers = std::collections::BTreeMap<String, serde_json::Map<String, serde_
pub(super) type Mcp = (Servers, crate::mcp::Settings);
fn bind_address(file: &FileConfig) -> Result<SocketAddr, crate::BoxError> {
Ok(optional_env("STRATA_BIND")?
Ok(crate::env_settings::text("STRATA_BIND")?
.or(file.bind.clone())
.unwrap_or_else(|| "127.0.0.1:8081".to_owned())
.parse()?)
}
fn in_flight_limit(file: &FileConfig) -> Result<usize, crate::BoxError> {
let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")?
.map(|value| value.parse::<usize>())
.transpose()?
let max_in_flight_requests = crate::env_settings::number::<usize>("STRATA_MAX_IN_FLIGHT_REQUESTS")?
.or(file.max_in_flight_requests)
.unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS);
crate::lifecycle::validate_capacity(max_in_flight_requests)?;
@@ -41,7 +39,7 @@ fn in_flight_limit(file: &FileConfig) -> Result<usize, crate::BoxError> {
}
fn prompt_date_setting(file: &FileConfig) -> Result<crate::responses::PromptDate, crate::BoxError> {
Ok(optional_env("STRATA_PROMPT_DATE")?
Ok(crate::env_settings::text("STRATA_PROMPT_DATE")?
.or(file.prompt_date.clone())
.map(|text| crate::responses::PromptDate::parse(&text))
.transpose()?
@@ -49,9 +47,7 @@ fn prompt_date_setting(file: &FileConfig) -> Result<crate::responses::PromptDate
}
fn queue_timeout(file: &FileConfig) -> Result<Option<u64>, crate::BoxError> {
let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
let queue_timeout_s = crate::env_settings::number::<u64>("STRATA_QUEUE_TIMEOUT_S")?
.or(file.queue_timeout_s);
if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("queue_timeout_s must be between 1 and 86400 when configured".into());
@@ -60,9 +56,7 @@ fn queue_timeout(file: &FileConfig) -> Result<Option<u64>, crate::BoxError> {
}
fn shutdown_grace(file: &FileConfig) -> Result<u64, crate::BoxError> {
let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")?
.map(|value| value.parse::<u64>())
.transpose()?
let shutdown_grace_s = crate::env_settings::number::<u64>("STRATA_SHUTDOWN_GRACE_S")?
.or(file.shutdown_grace_s)
.unwrap_or(0);
if shutdown_grace_s > 20 {
@@ -102,7 +96,7 @@ impl Config {
}
pub(super) fn read_engine(file: &FileConfig) -> Result<EngineSection, crate::BoxError> {
let executable = optional_env_os("STRATA_ENGINE_EXE").or_else(|| {
let executable = crate::env_settings::os_string("STRATA_ENGINE_EXE").or_else(|| {
file.engine
.as_ref()
.map(|engine| OsString::from(&engine.executable))
@@ -1,5 +1,6 @@
//! Methods of `Config`: `provision`, `prepare_for_switch`, `prepare_assets`, `probe_engine` and 3 more.
//! Split out of `methods` to keep its files under the line limit.
//! What `Config` does before the listener or the worker starts: probe the host, probe the engine executable, acquire
//! and verify the model assets, and append the MTP and native-model arguments to the engine command line. Also the
//! lighter preparation of a switch target while the previous runtime still holds the GPU.
use super::Config;
-20
View File
@@ -1,20 +0,0 @@
//! The only place the run configuration reads the process environment (`STRATA_*`): one reader, so the keys the
//! operator can set are all asked here and a test can see where they enter. Separate from `config` for that reason.
use std::ffi::OsString;
use super::env;
/// The value of the variable; `Ok(None)` when it is unset, an error when it is set but not valid Unicode.
pub(super) fn optional_env(name: &str) -> Result<Option<String>, env::VarError> {
match env::var(name) {
Ok(value) => Ok(Some(value)),
Err(env::VarError::NotPresent) => Ok(None),
Err(error) => Err(error),
}
}
/// The value of the variable as an OS string (a path); `None` when it is unset.
pub(super) fn optional_env_os(name: &str) -> Option<OsString> {
env::var_os(name)
}
+3 -1
View File
@@ -1,4 +1,6 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of configuration loading: serving settings are read and checked at start, tool-call recovery and the
//! request monitor switch on only as documented, the `runtime` block refuses every way of starting an engine itself,
//! a control vector becomes engine arguments after a preflight, and the `vision` section needs an engine.
use super::*;
use serde_json::json;
+1 -6
View File
@@ -20,12 +20,7 @@ impl Policy {
}
pub async fn select(self) -> Result<Selection, String> {
self.validate()?;
let visible = std::env::var("CUDA_VISIBLE_DEVICES")
.map(Some)
.or_else(|e| match e {
std::env::VarError::NotPresent => Ok(None),
_ => Err("CUDA_VISIBLE_DEVICES must be UTF-8".to_owned()),
})?;
let visible = crate::env_settings::cuda_visible_devices()?;
let allowed = visibility(visible.as_deref())?;
let devices = inventory().await?;
choose(self, devices, allowed.as_deref())
+143
View File
@@ -0,0 +1,143 @@
//! The only place `strata-control` reads the process environment, and what each variable is parsed into.
//!
//! One reader means the operator's surface is one list and a test can see where the environment enters. The readers
//! are live (each call asks the process, nothing is snapshotted at start), which keeps the order of the checks and
//! the messages of the run configuration exactly as they were when every module asked for itself. Each function
//! returns the parsed type (a number, a path, a flag, a mode), not the raw string, and says what an unset, empty or
//! non-Unicode value means.
//!
//! The variables, and the function that reads each:
//!
//! * the `STRATA_*` of the run configuration (config path, bind address, limits, model id, key file, tokenizer,
//! engine arguments, ...): [`text`], [`os_string`], [`number`]; they override the file's value and the config
//! loader checks the range;
//! * the name the configuration gives (`runtime.token_env`): [`variable`], the runtime credential;
//! * `LELEKA_STATUS_FILE`: [`supervisor_status_file`], the supervisor's status document;
//! * `LELEKA_PROFILE`: [`serving_profile`], the profile name shown in the request log;
//! * `CUDA_VISIBLE_DEVICES`: [`cuda_visible_devices`]; `HF_TOKEN`: [`hub_token`] (the model downloader's credential);
//! * `STRATA_MTP_REVISION`: [`mtp_revision`], the checkpoint revision of the MTP pack;
//! * `STRATA_DEBUG`, `STRATA_DEBUG_FAILED_OUTPUT`: [`mcp_stderr_debug`], [`debug_failed_output`], debugging switches;
//! * `STRATA_STAGE_TRACE`: [`stage_trace`], the per-stage timing of the host side of a request;
//! * `PATH`: [`search_path`], the executable lookup of the preflight;
//! * `XDG_CONFIG_HOME`, `HOME`: [`config_home`], where the user systemd unit goes;
//! * every `STRATA_*`: [`strata_variable_names`], scrubbed from the environment of a provisioning child.
use std::{
env::VarError,
ffi::OsString,
path::PathBuf,
};
/// The value of the variable; `Ok(None)` when it is unset, an error when it is set but not valid Unicode.
pub fn text(name: &str) -> Result<Option<String>, VarError> {
match std::env::var(name) {
Ok(value) => Ok(Some(value)),
Err(VarError::NotPresent) => Ok(None),
Err(error) => Err(error),
}
}
/// The value of the variable as an OS string (a path); `None` when it is unset.
pub fn os_string(name: &str) -> Option<OsString> {
std::env::var_os(name)
}
/// The variable parsed as `T` (a number); `Ok(None)` when unset, an error for a value that is not valid Unicode or
/// does not parse.
pub fn number<T: std::str::FromStr>(name: &str) -> Result<Option<T>, crate::BoxError>
where
T::Err: std::error::Error + 'static,
{
Ok(text(name)?.map(|value| value.parse::<T>()).transpose()?)
}
/// A variable named by the configuration (the runtime credential), `None` when unset or not Unicode.
pub fn variable(name: &str) -> Option<String> {
std::env::var(name).ok()
}
/// The status document of the supervisor that started this process (`LELEKA_STATUS_FILE`).
pub fn supervisor_status_file() -> Option<PathBuf> {
std::env::var_os("LELEKA_STATUS_FILE").map(PathBuf::from)
}
/// The serving profile named by `LELEKA_PROFILE`, when it is set and not empty.
pub fn serving_profile() -> Option<String> {
std::env::var("LELEKA_PROFILE").ok().filter(|profile| !profile.is_empty())
}
/// `CUDA_VISIBLE_DEVICES`: `Ok(None)` when unset, an error message when it is not UTF-8.
pub fn cuda_visible_devices() -> Result<Option<String>, String> {
text("CUDA_VISIBLE_DEVICES").map_err(|_| "CUDA_VISIBLE_DEVICES must be UTF-8".to_owned())
}
/// The `HF_TOKEN` variable: unset or empty is no token; whitespace or non-UTF-8 is an error.
pub fn hub_token() -> Result<Option<String>, crate::BoxError> {
match std::env::var("HF_TOKEN") {
Ok(token) if token.is_empty() => Ok(None),
Ok(token) if token.chars().any(char::is_whitespace) => {
Err("HF_TOKEN must not contain whitespace".into())
}
Ok(token) => Ok(Some(token)),
Err(VarError::NotPresent) => Ok(None),
Err(VarError::NotUnicode(_)) => Err("HF_TOKEN must contain valid UTF-8".into()),
}
}
/// The checkpoint revision of the MTP pack (`STRATA_MTP_REVISION`), `None` when unset or empty.
pub fn mtp_revision() -> Option<String> {
std::env::var("STRATA_MTP_REVISION").ok().filter(|revision| !revision.is_empty())
}
/// Is `STRATA_DEBUG` set (to anything)? Then the stderr of an MCP server child is copied into the log.
pub fn mcp_stderr_debug() -> bool {
std::env::var_os("STRATA_DEBUG").is_some()
}
/// Is `STRATA_DEBUG_FAILED_OUTPUT` exactly `1`? Then the text of a failed streaming tool turn is logged (model output).
pub fn debug_failed_output() -> bool {
std::env::var_os("STRATA_DEBUG_FAILED_OUTPUT").is_some_and(|value| value == "1")
}
/// What `STRATA_STAGE_TRACE` asks of the stage timer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StageTrace {
/// Unset or any other value: no clock reads.
Off,
/// `1`: spans add their duration to the per-stage table.
Spans,
/// `log`: spans also write one line each to stderr.
SpansAndLog,
}
/// The mode `STRATA_STAGE_TRACE` selects.
pub fn stage_trace() -> StageTrace {
match std::env::var("STRATA_STAGE_TRACE").as_deref() {
Ok("1") => StageTrace::Spans,
Ok("log") => StageTrace::SpansAndLog,
_ => StageTrace::Off,
}
}
/// The directories of `PATH`, `None` when `PATH` is unset (a missing `PATH` is deliberately not guessed).
pub fn search_path() -> Option<Vec<PathBuf>> {
std::env::var_os("PATH").map(|paths| std::env::split_paths(&paths).collect())
}
/// The base of the user configuration directory: `XDG_CONFIG_HOME` when it is set and not empty, else `HOME/.config`.
/// `Err` when neither is available.
#[cfg(unix)]
pub fn config_home() -> Result<PathBuf, String> {
match std::env::var_os("XDG_CONFIG_HOME") {
Some(value) if !value.is_empty() => Ok(PathBuf::from(value)),
_ => Ok(PathBuf::from(std::env::var_os("HOME").ok_or("HOME is missing")?).join(".config")),
}
}
/// The names of the variables that start with `STRATA_` (a child that must not inherit the operator's overrides).
pub fn strata_variable_names() -> Vec<OsString> {
std::env::vars_os()
.map(|(name, _)| name)
.filter(|name| name.to_string_lossy().starts_with("STRATA_"))
.collect()
}
+3 -1
View File
@@ -11,6 +11,7 @@ use std::{
time::{Duration, Instant},
};
use leleka_obs::time::{AnyClock, Clock};
use serde_json::{Map, Value, json};
/// Samples kept per series. The worker copies the telemetry document on its health tick (2 s by default), so 60
@@ -130,6 +131,7 @@ pub fn hardware_static(document: &Value) -> Value {
#[derive(Default)]
pub struct Series {
inner: Mutex<Inner>,
clock: AnyClock,
}
#[derive(Default)]
@@ -145,7 +147,7 @@ impl Series {
let Ok(mut inner) = self.inner.lock() else {
return;
};
let at = Instant::now();
let at = self.clock.now();
if inner
.last
.is_some_and(|last| at.duration_since(last) < MIN_GAP)
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the gpt-oss codec: reasoning and answers become think markup, tool calls become tool-call blocks in
//! order, bad arguments are errors, multibyte text survives token boundaries, and special and terminal ids are fixed.
use super::*;
use leleka_tokenizer::gguf_bpe::SpecialIds;
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the KAR-2 metadata inspector: the CRC-32 reference, source identity from verified shards in filename
//! order, raw and nested archive inspection with payload corruption detected, and bounded range decoding.
use super::*;
use crate::model::ModelFile;
+6 -13
View File
@@ -181,23 +181,16 @@ pub struct Summary {
}
mod sidecar_and_tensor_locations;
#[allow(unused_imports)]
pub use sidecar_and_tensor_locations::*;
use sidecar_and_tensor_locations::*;
mod base_provenance;
#[allow(unused_imports)]
pub use base_provenance::*;
mod resolve_verified;
#[allow(unused_imports)]
pub use resolve_verified::*;
use base_provenance::*;
mod verified_source_resolution;
pub use verified_source_resolution::*;
mod encode_overlay;
#[allow(unused_imports)]
pub use encode_overlay::*;
use encode_overlay::*;
mod prepare;
#[allow(unused_imports)]
pub use prepare::*;
mod compare;
#[allow(unused_imports)]
pub use compare::*;
mod write_provenance;
#[allow(unused_imports)]
pub use write_provenance::*;
use write_provenance::*;
+3 -2
View File
@@ -1,5 +1,6 @@
//! Methods of `Comparer`: `compare_all`, `compare_record`, `stream_errors`, `decode_chunk`.
//! Methods of `SourcePair`: `identity_differs`, `offsets_differ`. Implements `Default for ErrorSums`.
//! Compares an overlay archive with its base: checks the two provenance sidecars agree, then decodes every selected
//! tensor from both archives and measures the error of each against the verified source bytes. It reads the base
//! archive as previously verified, so only the selected tensors and the small overlay are read in a run.
use super::{
BaseProvenance, CandidateSource, ComparedRecord, Comparison, Digest, File, HashMap, HashSet, Location, Manifest,
+3 -2
View File
@@ -1,5 +1,6 @@
//! Functions: `prepare`, `plan_sources`, `read_candidates`, `read_base` and 7 more. Defines `SourcePlan`.
//! Split out of `kar_overlay` to keep its files under the line limit.
//! Prepares an overlay archive: reads the candidate list and the base provenance, plans where each candidate's source
//! tensor lives in the GGUF shards, encodes the candidates into a staging archive and commits it with its provenance
//! sidecar. It refuses to overwrite an existing destination.
use super::{
BaseProvenance, BaseShard, Candidates, Component, Digest, Encoder, HashMap, HashSet, Location, Manifest,
@@ -1,5 +1,6 @@
//! Functions: `resolve_verified`, `check_archives`, `check_base_directory`, `policy_differs` and 14 more.
//! Defines `ExpectedSource`, `ExpectedSources`.
//! Resolves which archive serves each tensor name once a base archive and an overlay archive are both fully
//! verified: every replacement is bound to the same virtual-F32 source record of the base, and the result is the
//! per-tensor selection a loader reads. It checks the partition policy and the record directories of both archives.
use super::{
BaseProvenance, BaseTensor, HashMap, HashSet, OverlayProvenance, OverlayRecord, PartitionPart, PartitionedTensor,
@@ -1,5 +1,5 @@
//! Functions: `write_provenance`.
//! Split out of `kar_overlay` to keep its files under the line limit.
//! Writes a provenance JSON sidecar exactly once and durably: the file must not exist, is synced to disk, and is
//! removed again if the write fails, so a half-written sidecar never describes an archive.
use super::{OpenOptions, Path, Write, fs};
+2 -2
View File
@@ -99,6 +99,6 @@ mod previous;
mod sample;
#[allow(unused_imports)]
pub use analyze::*;
mod parse_digest;
mod sample_records;
#[allow(unused_imports)]
pub use parse_digest::*;
pub use sample_records::*;
+3 -2
View File
@@ -1,5 +1,6 @@
//! Functions: `analyze`, `recorded_archive_sha256`, `analyze_previously_verified`.
//! Split out of `kar_quality` to keep its files under the line limit.
//! The two ways to produce a quality report for a KAR archive: a full verification of the derived source and the
//! archive before sampling, or a reuse of an earlier full verification of the same immutable files, which checks the
//! provenance and reads only the sampled payloads.
use super::{
File, Manifest, Path, Report, SourceShards, VerifiedRangeDecoder, derived_mixed, kar_shard_plan, prepare_preview,
@@ -1,5 +1,6 @@
//! Functions: `parse_digest`, `sample_all`, `sample_records`, `sample_starts` and 2 more. Defines `SourceShards`.
//! Split out of `kar_quality` to keep its files under the line limit.
//! The sampling step of the KAR quality report: picks the sampled windows of every tensor, decodes them from the
//! archive and compares them with the source, and writes the report file. Also parses the SHA-256 digests the
//! provenance records.
use super::{
File, Path, RecordError, Report, SAMPLE_ELEMENTS, SampleWindow, VerifiedRangeDecoder, Write, derived_mixed, gguf,
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the KAR quality sampling: the sampled windows of a tensor are bounded in number, aligned to the
//! block size, 4096 elements wide, distinct and inside the tensor.
use super::*;
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the bounded-memory section encoder: a streamed section matches the section of the existing writer and
//! forms a verified archive, and an IQ3 section keeps its source and virtual F32 identity across chunks.
use super::*;
use crate::{iq3_s, kar, kar_writer};
+8 -8
View File
@@ -102,18 +102,18 @@ mod tests;
mod archive_file;
mod archive_plan;
mod write_archive;
mod archive_entry_points;
#[allow(unused_imports)]
pub use write_archive::*;
pub use archive_entry_points::*;
mod archive_write_steps;
#[allow(unused_imports)]
pub use archive_write_steps::*;
mod write_nested_section;
mod nested_layout;
#[allow(unused_imports)]
pub use write_nested_section::*;
mod write_section;
pub use nested_layout::*;
mod section_payload;
#[allow(unused_imports)]
pub use write_section::*;
mod write_record;
pub use section_payload::*;
mod directory_record;
#[allow(unused_imports)]
pub use write_record::*;
pub use directory_record::*;
@@ -1,5 +1,5 @@
//! Functions: `write_archive`, `write_archive_consuming_files`.
//! Split out of `kar_writer` to keep its files under the line limit.
//! The two public ways to write a KAR archive: from tensors held in memory or file-backed, and from file-backed
//! tensors whose staging files are consumed while their sections are copied, which bounds peak disk use.
use super::{Path, SourceIdentity, Tensor, TensorData, kar, write_archive_inner};
@@ -1,6 +1,5 @@
//! Write stage of the KAR writer: sections, directory and header of a planned archive.
#[allow(unused_imports)]
use super::archive_plan::Plan;
use super::{
Digest, File, Placed, Seek, SeekFrom, Sha256, SourceIdentity, TensorData, Write, fs, kar, put_u32, put_u64,
@@ -1,9 +1,7 @@
//! `write_archive_inner`: check the request, write the archive to a `.part` file, verify it and publish it with a hard
//! link that never replaces an existing destination. Separate from `kar_writer` so that order reads on its own.
#[allow(unused_imports)]
use super::archive_file::write_archive_file;
#[allow(unused_imports)]
use super::archive_plan::plan;
use super::{OpenOptions, Path, SourceIdentity, Tensor, fs, kar};
@@ -1,5 +1,5 @@
//! Functions: `write_record`, `write_identity`, `nested_params`, `write_nested_fields` and 3 more.
//! Defines `NestedParams`.
//! Encodes the fixed-size directory record of one tensor (name, shape, storage kind, NESTED parameters, payload CRC,
//! section placement, source digest) at its byte offsets, with the little-endian integer writers it uses.
use super::{Placed, Tensor, TensorData};
@@ -1,5 +1,6 @@
//! Functions: `write_nested_section`, `spool_layout`, `create_new_file`, `spool_entry` and 14 more.
//! Defines `NestedGeometry`, `NestedSlices`.
//! Writes one NESTED tensor section to its own staging file, so a later archive assembly needs bounded memory. Also
//! holds the NESTED shape rules that all writers share: validation of scales, books and planes, and the layout of
//! the section (padded sizes, plane strides, alignment).
use super::{
Digest, File, NestedLayout, OpenOptions, Path, Placed, Read, SectionSummary, Seek, SeekFrom, Sha256, Tensor,
@@ -1,5 +1,6 @@
//! Methods of `Out`: `bytes`, `pad_to`. Methods of `FileSpan`: `of`.
//! Functions: `write_section`, `open_span`, `stream_span`, `write_raw_file` and 9 more.
//! Writes the payload section of one tensor into the archive, from memory or by streaming a byte range of a source
//! file, while tracking its CRC and length. Also checks file-backed regions (padding bytes and NESTED headers) and
//! provides the padded byte writers used by the section writers.
use super::{Digest, File, Path, Placed, Read, RegionRule, Seek, SeekFrom, Sha256, TensorData, Write, kar};
+3 -1
View File
@@ -1,4 +1,6 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the KAR writer: a NESTED section streams out canonically and corruption is rejected, a RAW tensor
//! streams across a buffer boundary, the consuming writer removes its staged input only after a verified copy, and the
//! archive bytes match the pinned reference writer.
use super::*;
use std::path::PathBuf;
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{Path, USAGE};
use std::{
fs::{File, OpenOptions},
io::{Read, Write},
+1
View File
@@ -37,6 +37,7 @@ pub mod derived_iq3;
pub mod derived_mixed;
pub mod doctor;
pub mod embedded_engine;
pub mod env_settings;
#[cfg(test)]
mod embedded_spec;
pub mod engine_probe;
+10 -6
View File
@@ -28,6 +28,7 @@ use std::{
time::{Duration, Instant},
};
use leleka_obs::time::{AnyClock, Clock};
use serde_json::{Map, Value, json};
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
@@ -118,6 +119,7 @@ pub struct Server {
kind: &'static str,
settings: Settings,
state: AsyncMutex<State>,
clock: AnyClock,
}
/// One tool call's outcome (`McpHub.call`).
@@ -137,20 +139,22 @@ pub struct CallOutput {
pub struct Hub {
pub servers: Vec<Arc<Server>>,
settings: Settings,
/// The clock of the tool-call timings and of the server start stamps; tests move it by hand.
clock: AnyClock,
}
#[cfg(test)]
mod tests;
mod settings_default;
mod mcp_settings_errors;
#[allow(unused_imports)]
pub use settings_default::*;
pub use mcp_settings_errors::*;
mod stdio_transport;
#[allow(unused_imports)]
pub use stdio_transport::*;
mod dispatch;
mod stdio_message_routing;
#[allow(unused_imports)]
pub use dispatch::*;
pub use stdio_message_routing::*;
mod http_transport;
#[allow(unused_imports)]
pub use http_transport::*;
@@ -160,9 +164,9 @@ pub use transport::*;
mod server;
#[allow(unused_imports)]
pub use server::*;
mod result_text;
mod tool_result_text;
#[allow(unused_imports)]
pub use result_text::*;
pub use tool_result_text::*;
mod hub;
#[allow(unused_imports)]
pub use hub::*;
+3 -2
View File
@@ -1,5 +1,6 @@
//! Methods of `Http`: `new`, `alive`, `builder`, `post` and 8 more.
//! Functions: `timeout_error`, `response_in_event`, `read_events`.
//! The Streamable HTTP transport to an MCP server reached by `url`: each JSON-RPC request is a POST with the
//! configured headers and the session id the server assigned, and the answer is read from a JSON body or from an
//! event stream. It also tracks a broken connection and sends the cancel notification of an abandoned call.
use super::{
AtomicU64, Cancel, Duration, Http, Map, McpError, Mutex, Ordering, Value, cancelled, failed, fmt_g, json,
+14 -7
View File
@@ -1,19 +1,26 @@
//! Methods of `Hub`: `new`, `start`, `routes`, `template_tools` and 5 more. Functions: `falsy`, `tool_outcome`.
//! Split out of `mcp` to keep its files under the line limit.
//! The hub that owns the configured MCP servers: starts them together, maps the tool names the model sees to their
//! server and own tool name, lists the tools in the chat-template form, runs a tool call with the result cap and the
//! `error:` convention, reports the `GET /mcp` status, and closes the servers.
use super::{
Arc, BTreeMap, CallOutput, Cancel, Duration, Hub, Instant, Map, McpError, Server, Settings, Status, Value, clean,
group_thousands, json, result_text,
AnyClock, Arc, BTreeMap, CallOutput, Cancel, Clock, Duration, Hub, Map, McpError, Server, Settings, Status, Value,
clean, group_thousands, json, result_text,
};
impl Hub {
pub fn new(servers: BTreeMap<String, Map<String, Value>>, settings: Settings) -> Self {
Self::with_clock(servers, settings, AnyClock::default())
}
/// A hub whose timings come from `clock` (the unit tests pass a manual one).
pub fn with_clock(servers: BTreeMap<String, Map<String, Value>>, settings: Settings, clock: AnyClock) -> Self {
Self {
servers: servers
.into_iter()
.map(|(name, config)| Arc::new(Server::new(name, config, settings.clone())))
.map(|(name, config)| Arc::new(Server::new(name, config, settings.clone(), clock.clone())))
.collect(),
settings,
clock,
}
}
@@ -90,7 +97,7 @@ impl Hub {
arguments: Value,
cancel: Option<Cancel>,
) -> Result<CallOutput, McpError> {
let started = Instant::now();
let started = self.clock.now();
let route = self.routes().await.into_iter().find(|(n, _, _)| n == name);
let (server, tool) = match &route {
Some((_, server, tool)) => (Some(server.clone()), tool.clone()),
@@ -106,7 +113,7 @@ impl Hub {
text,
chars: full,
truncated,
ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
ms: u64::try_from(self.clock.since(started).as_millis()).unwrap_or(u64::MAX),
server: server.as_ref().map(|s| s.name.clone()),
tool,
})
@@ -1,5 +1,5 @@
//! Implements `Default for Settings`, `Display for McpError`. Functions: `failed`, `response_result`.
//! Split out of `mcp` to keep its files under the line limit.
//! The default MCP settings (timeouts, result cap, round limit), the message text of each `McpError`, and the
//! reading of a JSON-RPC response as its `result` or the error it carried.
use super::{McpError, Settings, Value, json};
+3 -2
View File
@@ -1,5 +1,6 @@
//! Functions: `parse_config`, `misshapen`, `url_problem`, `command_problem` and 6 more.
//! Split out of `mcp` to keep its files under the line limit.
//! Reading and checking the operator's MCP configuration at start: each server entry (a `command` or a `url`, with
//! the types of its fields) and the settings block (timeouts, result cap, round limit). A bad entry stops the start
//! with a message naming the entry, as the Original does.
use super::{BTreeMap, Map, Settings, Value, falsy, json};
+9 -7
View File
@@ -1,13 +1,14 @@
//! Methods of `Server`: `new`, `start`, `start_locked`, `record_failure` and 5 more.
//! Functions: `handshake`, `initialize`, `server_info`, `page_tools` and 1 more.
//! One MCP server of the hub: chooses the stdio or the HTTP transport from its entry, starts it with the
//! `initialize` handshake and the paged tool listing, retries a failed start at most every 10 s, runs calls on the
//! ready transport, and records the failure that explains a server left out.
use super::{
Arc, AsyncMutex, Cancel, Duration, Http, Instant, Map, McpError, PROTOCOL, Server, Settings, StartResult, State,
Status, StdioTransport, Transport, Value, failed, json,
AnyClock, Arc, AsyncMutex, Cancel, Clock, Duration, Http, Map, McpError, PROTOCOL, Server, Settings, StartResult,
State, Status, StdioTransport, Transport, Value, failed, json,
};
impl Server {
pub(super) fn new(name: String, config: Map<String, Value>, settings: Settings) -> Self {
pub(super) fn new(name: String, config: Map<String, Value>, settings: Settings, clock: AnyClock) -> Self {
let kind = if config
.get("url")
.is_some_and(|u| u.as_str().is_some_and(|s| !s.is_empty()))
@@ -29,6 +30,7 @@ impl Server {
transport: None,
last_start: None,
}),
clock,
}
}
@@ -43,7 +45,7 @@ impl Server {
}
state.status = Status::Starting;
state.error = None;
state.last_start = Some(Instant::now());
state.last_start = Some(self.clock.now());
match self.connect().await {
Ok((transport, tools, info)) => {
self.log_started(&tools);
@@ -124,7 +126,7 @@ impl Server {
if state.status == Status::Failed
&& state
.last_start
.is_some_and(|at| at.elapsed() < Duration::from_secs(10))
.is_some_and(|at| self.clock.since(at) < Duration::from_secs(10))
{
return Err(failed(format!(
"the server is not running ({})",
@@ -1,5 +1,6 @@
//! Functions: `dispatch`, `answer_request`, `cancelled`, `fmt_g`.
//! Split out of `mcp` to keep its files under the line limit.
//! Routing of the messages an MCP server sends on stdout: an answer goes to the call waiting for it, a request from
//! the server gets a fixed reply. Also the helpers the stdio and HTTP transports share: waiting for a cancel
//! signal and formatting a timeout in seconds as the Original does.
use super::{Arc, AsyncMutex, AsyncWriteExt, Cancel, ChildStdin, HashMap, Mutex, Slot, Value, json};
+4 -3
View File
@@ -1,5 +1,6 @@
//! Methods of `StdioTransport`: `spawn`, `tail`, `alive`, `send` and 5 more.
//! Methods of `StdoutReader`: `transport`, `run`, `finish`.
//! The stdio transport to an MCP server Leleka starts itself: spawns the program with its arguments, environment and
//! working directory, writes newline-delimited JSON-RPC requests to its stdin, and reads the answers from its stdout
//! on a reader task. The last lines of its stderr are kept to explain a failure.
use super::{
Arc, AsyncBufReadExt, AsyncMutex, AsyncWriteExt, AtomicU64, BufReader, Cancel, Child, ChildStdin, Command,
@@ -218,7 +219,7 @@ fn spawn_stderr_log(
if line.is_empty() {
continue;
}
if std::env::var_os("STRATA_DEBUG").is_some() {
if crate::env_settings::mcp_stderr_debug() {
crate::elog!("[mcp {label}] {line}");
}
let mut log = log.lock().expect("mcp log");
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the MCP hub: tool results read as text with other blocks named, JSON-RPC errors read like the
//! Original's, server entries and the settings block are checked at start, and tool names are cleaned and made unique.
use super::*;
@@ -1,5 +1,5 @@
//! Functions: `result_text`, `field_text`, `block_text`, `resource_text` and 3 more.
//! Split out of `mcp` to keep its files under the line limit.
//! Turns an MCP tool result into the text the model reads: text blocks as they are, other block kinds (images,
//! resources) named. Also two small text helpers of the hub: cleaning a tool name and grouping digits of a count.
use super::{Map, Value};
+2 -2
View File
@@ -1,5 +1,5 @@
//! Methods of `Transport`: `alive`, `request`, `notify`, `close`. Methods of `Status`: `as_str`.
//! Split out of `mcp` to keep its files under the line limit.
//! The transport seen by a server: one request, notify, alive and close interface that forwards to the stdio or the
//! HTTP implementation. Also the status names of a server as `GET /mcp` prints them.
use super::{Cancel, Duration, McpError, Status, Transport, Value};
+2 -2
View File
@@ -35,6 +35,6 @@ pub use count_tokens::*;
mod error_type;
#[allow(unused_imports)]
pub use error_type::*;
mod adapt;
mod messages_stream;
#[allow(unused_imports)]
pub use adapt::*;
pub use messages_stream::*;
@@ -1,5 +1,6 @@
//! Methods of `Blocks`: `event`, `message_start`, `open_text`, `text_delta` and 4 more.
//! Functions: `adapt`, `stream_response`. Defines `Step`, `Blocks`.
//! The streaming reply of the Anthropic Messages endpoint: converts the native Responses event stream into Messages
//! events (`message_start`, content blocks for text and tool use, `message_delta`, `message_stop`, or an error
//! event) and serves it as server-sent events. `Blocks` tracks which content block is open.
use super::{
Body, Event, Events, IntoResponse, NativeEvents, Response, Sse, StatusCode, Value, close_text, error_value, json,
+3 -1
View File
@@ -1,4 +1,6 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the Messages adapter: replayed `tool_use` arguments keep the order the client wrote, and a
//! `tool_result` keeps errors, empty content and the bytes of a success, while malformed error flags and results
//! are rejected.
use super::*;
+2 -2
View File
@@ -46,6 +46,6 @@ mod tests;
mod manifest_fetch;
#[allow(unused_imports)]
pub use manifest_fetch::*;
mod fetch_one;
mod file_download;
#[allow(unused_imports)]
pub use fetch_one::*;
pub use file_download::*;
@@ -1,8 +1,14 @@
//! Functions: `fetch_one`, `publish_complete_partial`, `open_body`, `verified_in_place` and 16 more.
//! Split out of `model` to keep its files under the line limit.
//! Downloads one manifest file safely: keeps a `.part` file and resumes it from its size, checks the server's answer
//! and the free disk space, hashes while writing, and publishes the file only after its size and SHA-256 match the
//! manifest. Also holds the verification of finished files that the rest of `model` reuses.
#[allow(unused_imports)]
use super::*;
use super::{
AsyncReadExt, AsyncWriteExt, CONTENT_RANGE, Client, Digest, Duration, File, Manifest, ModelFile, OpenOptions, Path,
PathBuf, Result, Sha256, StatusCode, fs, io, model_request,
};
#[cfg(unix)]
use super::CString;
use crate::{adapters::SystemClock, ports::Clock};
pub(super) async fn fetch_one(
client: &Client,
@@ -136,7 +142,7 @@ async fn write_body(
) -> Result<(u64, Sha256)> {
let mut writer = open_partial(partial, offset).await?;
let mut received = offset;
let mut progress_at = tokio::time::Instant::now();
let mut progress_at = SystemClock.now();
crate::elog!("fetching {}: {received}/{} bytes", file.name, file.size);
while let Some(chunk) = response.chunk().await? {
received = received
@@ -164,7 +170,7 @@ fn log_progress(file: &ModelFile, received: u64, progress_at: &mut tokio::time::
file.size,
received as f64 * 100.0 / file.size as f64
);
*progress_at = tokio::time::Instant::now();
*progress_at = SystemClock.now();
}
}
+1 -14
View File
@@ -108,24 +108,11 @@ pub(crate) fn http_client() -> Result<Client> {
.build()?)
}
/// The `HF_TOKEN` environment variable: unset or empty is no token; whitespace or non-UTF-8 is an error.
fn hub_token_from_env() -> Result<Option<String>> {
match std::env::var("HF_TOKEN") {
Ok(token) if token.is_empty() => Ok(None),
Ok(token) if token.chars().any(char::is_whitespace) => {
Err("HF_TOKEN must not contain whitespace".into())
}
Ok(token) => Ok(Some(token)),
Err(std::env::VarError::NotPresent) => Ok(None),
Err(std::env::VarError::NotUnicode(_)) => Err("HF_TOKEN must contain valid UTF-8".into()),
}
}
pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> {
fs::create_dir_all(output).await?;
preflight_space(manifest, output).await?;
let client = http_client()?;
let hub_token = hub_token_from_env()?;
let hub_token = crate::env_settings::hub_token()?;
for file in &manifest.files {
fetch_one_with_retry(&client, file, output, hub_token.as_deref()).await?;
}
+4 -1
View File
@@ -1,4 +1,7 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of manifest-pinned model acquisition, against a local HTTP server: not enough disk space stops before
//! any request, an interrupted download resumes and verifies, a checksum mismatch never publishes, transient server
//! failures and short responses resume the same partial file, and a manifest with path traversal or URL credentials is
//! refused. The Hugging Face token goes only to the exact HTTPS host.
use super::*;
use serde_json::json;
+4 -8
View File
@@ -204,15 +204,11 @@ pub struct Fetcher {
backoff: fn(u32) -> Duration,
}
mod repo_url;
#[allow(unused_imports)]
pub use repo_url::*;
mod url_range_digest;
pub use url_range_digest::*;
mod fetcher;
#[allow(unused_imports)]
pub use fetcher::*;
mod mtime_ns;
#[allow(unused_imports)]
pub use mtime_ns::*;
mod command_line;
pub use command_line::*;
mod fetch_steps;
use fetch_steps::{drop_foreign_file, write_manifest};
mod inventory_steps;
@@ -1,8 +1,8 @@
//! Functions: `mtime_ns`, `mtime_ns`, `cli`, `build_fetcher` and 2 more.
//! Split out of `mtp_fetch` to keep its files under the line limit.
//! The command line of `tools mtp-fetch`: parses `inventory`, `fetch` and `verify` with their `--out`, `--only`,
//! `--repo` and `--sha256-file` flags, builds the fetcher for them and returns the exit code. Also the file
//! modification time in nanoseconds, which the fetcher uses to recognise an unchanged file.
#[allow(unused_imports)]
use super::*;
use super::{BAD, Fetcher, Path, PathBuf, Result, fs};
#[cfg(unix)]
pub(super) fn mtime_ns(metadata: &fs::Metadata) -> i128 {
+6 -6
View File
@@ -1,15 +1,15 @@
//! The MTP pack fetcher: the pinned or overridden revision, the HTTP client and the fetch of one pack.
#[allow(unused_imports)]
use super::*;
use super::{
BTreeMap, CONTENT_RANGE, Duration, Fetcher, HEADERS_ATTEMPTS, Inventory, Map, PINNED_REVISION, Path, RANGE, Result,
Row, SHA256, StatusCode, USER_AGENT, Value, check_all_found, check_range, drop_foreign_file, fs, inventory_markdown,
json_indent1, mtime_ns, repo_url, sha256_of, write_manifest,
};
impl Fetcher {
/// The production configuration: the pinned revision, or `STRATA_MTP_REVISION`.
pub fn from_env() -> Result<Self> {
let revision = std::env::var("STRATA_MTP_REVISION")
.ok()
.filter(|r| !r.is_empty())
.unwrap_or_else(|| PINNED_REVISION.to_owned());
let revision = crate::env_settings::mtp_revision().unwrap_or_else(|| PINNED_REVISION.to_owned());
Self::new(repo_url(&revision), repo_url(PINNED_REVISION))
}
@@ -1,5 +1,6 @@
//! Functions: `repo_url`, `json_indent1`, `check_range`, `sha256_of`.
//! Split out of `mtp_fetch` to keep its files under the line limit.
//! Small helpers of the MTP fetch: the Hugging Face URL of the pinned checkpoint revision, the check that a range
//! request was honoured (206 with the Content-Range asked for), the SHA-256 of a file, and JSON written with the
//! one-space indent of the Python tool.
use super::{Digest, File, Path, Read, Result, Serialize, Sha256};
+4 -4
View File
@@ -69,9 +69,9 @@ pub struct Options {
#[cfg(test)]
mod tests;
mod safe_name;
mod pack_rules;
#[allow(unused_imports)]
pub use safe_name::*;
pub use pack_rules::*;
mod expert_layout;
#[allow(unused_imports)]
pub use expert_layout::*;
@@ -84,9 +84,9 @@ pub use dense_files::*;
mod pack_publication;
#[allow(unused_imports)]
pub use pack_publication::*;
mod conversions_inexact;
mod pack_outputs;
#[allow(unused_imports)]
pub use conversions_inexact::*;
pub use pack_outputs::*;
mod same_bytes;
#[allow(unused_imports)]
pub use same_bytes::*;
@@ -1,5 +1,6 @@
//! Methods of `Conv`: `new`, `src_lower`, `need_compat`, `finish` and 7 more.
//! Functions: `convert_tensor`, `write_counted`, `exact_bf16_value`, `rounded_bf16_value` and 2 more.
//! Conversion of one dense tensor into the form the engine reads (exact or rounded BF16, F16, F32) while it streams
//! into `dense.bin`, with the digest of the source bytes and the error of each rounding.
//! Separate from `dense_files`, which walks the tensors, because it holds the per-kind conversion rules.
use super::{
Converted, Digest, Error64, File, Result, Sha256, Shard, Write, bf16_round_nearest_even, gguf, kar_codec,
+2 -2
View File
@@ -1,5 +1,5 @@
//! Methods of `Dense`: `add_shard`, `add_tensor`, `pad_and_advance`, `convert` and 1 more.
//! Functions: `dense_files`, `matrix_dims`, `serves_natively`, `copy_verbatim` and 4 more. Defines `Dense`.
//! The standalone pack's `dense.bin`, `index.txt` and `conversions.json`: walks every non-expert tensor of the shards,
//! converts or copies those the engine reads from the pack and leaves quantized ones to be served from the GGUF.
use super::{
Converted, File, Options, Path, PathBuf, Record, Result, Shard, SourceTensor, Write, align, convert_tensor, expert,
@@ -1,5 +1,6 @@
//! Methods of `Table`: `push_layer`. Methods of `Error64`: `new`, `note`.
//! Functions: `expert_layout`, `index_tensors`, `expert_layer`, `blob_bytes` and 9 more.
//! The expert table of the native pack (`native_experts.txt`): per layer, where the gate, up and down tensors of every
//! expert sit in the shards, with the shape and geometry checks. It also holds what the conversion files share: the
//! GGML type names, BF16 rounding, the running conversion error and the F32 stream of a tensor.
use super::{BTreeMap, Error64, File, Layout, Result, Shard, expert, gguf, gguf_f32_stream};
@@ -1,5 +1,5 @@
//! Methods of `Rebuild`: `add_row`, `reuse_float`, `move_to_extra`, `assign_pool_offsets` and 1 more.
//! Functions: `conversions_inexact`, `primary_shard`, `tokenizer_assets_preflight`, `copy_directory` and 13 more.
//! The pack files that are not dense tensors: `experts.bin` with its source sidecar, the index rebuilt from a `--base`
//! pack, the tokenizer asset copy and the check whether any recorded conversion rounded a weight.
use super::{
BTreeMap, Digest, File, FileRun, Layout, Path, PathBuf, Read, Result, Seek, SeekFrom, Sha256, Shard, Write, align,
@@ -1,5 +1,5 @@
//! Functions: `safe_name`, `align`, `form`, `expert` and 6 more.
//! Split out of `native_pack` to keep its files under the line limit.
//! The naming rules of the native pack: which file names are safe, which tensors the engine reads as BF16 or F32 and
//! which are experts, the 64-byte alignment, and the loading and checking of the shard set (one complete split family).
use super::{HashSet, Path, Result, Shard, gguf, model};
+2 -2
View File
@@ -1,5 +1,5 @@
//! Functions: `same_bytes`. Defines `FileRun`.
//! Split out of `native_pack` to keep its files under the line limit.
//! Byte-for-byte comparison of two runs of file data, read in 1 MiB chunks, used to check that a float tensor is
//! identical in the new pack and in its base pack.
use super::{File, Read, Result, Seek, SeekFrom};
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the native pack: the refusal of NVFP4 experts, the expert tables reproduced from the Python golden,
//! the native PLE key encodings and the F16 and BF16 rounding against numpy and gguf-py.
use super::*;
+5 -3
View File
@@ -1,5 +1,5 @@
//! Read-only deployment validation; never spawn a worker or acquire a listener.
use std::{env, ffi::OsStr, path::Path};
use std::{ffi::OsStr, path::Path};
use crate::{config::Config, embedded_engine, tokenizer::Tokenizer};
@@ -119,8 +119,10 @@ fn executable_available(executable: &OsStr) -> bool {
return executable_file(path);
}
// A missing PATH is deliberately not guessed. An explicit path is portable.
env::var_os("PATH").is_some_and(|paths| {
env::split_paths(&paths).any(|directory| executable_file(&directory.join(path)))
crate::env_settings::search_path().is_some_and(|directories| {
directories
.iter()
.any(|directory| executable_file(&directory.join(path)))
})
}
+10 -10
View File
@@ -79,27 +79,27 @@ struct StagingDir(PathBuf);
#[cfg(test)]
mod tests;
mod minimum_part_payload_bytes;
mod preview_entry_points;
#[allow(unused_imports)]
pub use minimum_part_payload_bytes::*;
pub use preview_entry_points::*;
mod prepare_sharded;
#[allow(unused_imports)]
pub use prepare_sharded::*;
mod prepare_sharded_streamed_with_policy;
mod streamed_sharded_prepare;
#[allow(unused_imports)]
pub use prepare_sharded_streamed_with_policy::*;
pub use streamed_sharded_prepare::*;
mod spool_raw_f32;
#[allow(unused_imports)]
pub use spool_raw_f32::*;
mod prepare;
mod prepare_single_file;
#[allow(unused_imports)]
pub use prepare::*;
mod encode_preview_tensor;
pub use prepare_single_file::*;
mod tensor_encoding;
#[allow(unused_imports)]
pub use encode_preview_tensor::*;
mod verify_derived;
pub use tensor_encoding::*;
mod derived_verification;
#[allow(unused_imports)]
pub use verify_derived::*;
pub use derived_verification::*;
mod staging_and_raw_tensor_reads;
use staging_and_raw_tensor_reads::*;
mod sharded_encode;
@@ -1,5 +1,5 @@
//! Functions: `load_derived_identity`, `require_derived_header`, `require_derived_source`, `verify_derived` and 10 m...
//! Split out of `prepare_preview` to keep its files under the line limit.
//! Read-back of a derived preview archive against its source (header, source identity, tensor sections), and the
//! helpers the preparation shares with it: decoding of source tensors, the provenance file, and file hashing.
use super::{
DerivedIdentity, Digest, File, Path, PathBuf, PreviewKind, Read, Sha256, derived_iq3, derived_mixed, fs, iq3_s,
@@ -1,5 +1,5 @@
//! Functions: `prepare_sharded`, `require_sharded_source_limit`, `require_sharded_tensor_count`, `sharded_builder` a...
//! Split out of `prepare_preview` to keep its files under the line limit.
//! Preparation of a preview from a manifest-pinned set of GGUF shards: source limits, tensor-by-tensor encoding,
//! archive and provenance. It also holds the entry points of the experimental streamed (bounded-memory) variant.
use super::{
MAX_SOURCE_BYTES, MAX_TENSORS, Manifest, PartLimits, Path, PreviewSummary, ShardedEncoding, derived_mixed,
@@ -1,5 +1,5 @@
//! Methods of `PreviewPlan`: `load`, `require_supported`, `encode_tensors`, `count_tensor` and 7 more.
//! Functions: `prepare`, `require_source_limits`, `derive_identity`, `preview_source_name` and 3 more.
//! Preparation of a preview from one GGUF file: checks the source against the preview limits, derives its identity,
//! encodes each tensor, then writes the KAR archive and the provenance file next to it.
use super::{
DerivedIdentity, Digest, File, MAX_SOURCE_BYTES, MAX_TENSOR_ELEMENTS, MAX_TENSORS, Path, PathBuf, PreparedTensor,
@@ -1,5 +1,5 @@
//! Methods of `DerivedIdentity`: `gguf_digest`, `derived_digest`, `derived_bytes`, `tensor` and 1 more.
//! Implements `Drop for StagingDir`.
//! The preview entry points `prepare_f32`, `prepare_iq3` and `prepare_mixed`, the accessors of the derived identity
//! of a source, the removal of the staging directory on drop, and the smallest payload a KAR part has for an F32 size.
use super::{DerivedIdentity, DerivedTensorRef, Path, PreviewKind, PreviewSummary, StagingDir, fs, prepare};
@@ -1,5 +1,5 @@
//! Functions: `spool_raw_f32`, `write_raw_f32`, `finish_writer`.
//! Split out of `prepare_preview` to keep its files under the line limit.
//! Writes a source tensor as a raw F32 file while hashing both the source bytes and the decoded values, so a part too
//! large for memory can be encoded from disk in chunks.
use super::{BufWriter, Digest, File, Path, Read, Seek, Sha256, Write, fs, gguf_f32_stream};
@@ -1,5 +1,5 @@
//! Functions: `prepare_sharded_streamed_with_policy`, `require_free_destination`, `plan_stream_parts`, `require_stre...
//! Split out of `prepare_preview` to keep its files under the line limit.
//! The streamed sharded preparation under a part-size policy: plans the parts, checks the size budget, encodes part by
//! part and writes the archive with its provenance. Separate from `prepare_sharded` because no whole tensor is held.
use super::{
Manifest, PartLimits, Path, PreviewSummary, StreamedEncoding, StreamedRun, StreamedTensor, apply_stream_policy,
@@ -1,5 +1,5 @@
//! Methods of `Quantized`: `fit`, `plane_refs`, `book_refs`, `relative_l2` and 1 more.
//! Functions: `relative_l2_error`, `prepared_tensor`, `encode_preview_tensor`, `verify_iq3` and 5 more.
//! Encoding of one preview tensor into a nested KAR section (calibrated planes, relative L2 error against the source
//! weights) and the public `verify_*` entry points that read an archive back against its source.
use super::{
Manifest, PartLimits, Path, PreparedTensor, PreviewKind, StreamPolicy, derived_mixed, kar, kar_codec,
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the preview preparation: conversion of small GGUF files, the supported source kinds, overlays, PLE
//! partitioning, and sharded and streamed archives with their verification and tampering checks.
mod convert;
mod fixtures;
+2 -2
View File
@@ -45,6 +45,6 @@ mod tests;
mod series;
use series::SERIES;
mod counter;
mod render;
#[allow(unused_imports)]
pub use counter::*;
pub use render::*;
@@ -1,5 +1,5 @@
//! Functions: `counter`, `gauge`, `labelled_counter`, `labelled` and 9 more.
//! Split out of `prometheus` to keep its files under the line limit.
//! The rendering of the `/metrics` document as Prometheus text: the series constructors, the scaled value of a series,
//! the HELP, TYPE and sample lines, the one-hot phase and throttle gauges, and the choice of format by request.
use super::{Kind, PHASES, SERIES, Series, THROTTLE_REASONS, Value, Write};
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the Prometheus exposition: the text format of counters, gauges and labels, the engine figures with
//! their fixed labels, unmeasured figures left out, and the choice of format by query or `Accept` header.
use super::*;
use serde_json::json;
+6 -7
View File
@@ -14,7 +14,6 @@
//! The same moment feeds the Prometheus histograms and counters of [`render_prometheus`], whose labels are enums of
//! fixed size (endpoint x outcome, error class): there is no label whose value comes from a client.
use std::{
fmt::Write as _,
sync::{
Arc, LazyLock, Mutex,
atomic::{AtomicU64, Ordering},
@@ -185,12 +184,12 @@ static REGISTRY: LazyLock<Registry> = LazyLock::new(|| Registry {
#[cfg(test)]
mod tests;
mod endpoint_index;
mod request_context;
#[allow(unused_imports)]
pub use endpoint_index::*;
mod obs_handle;
pub use request_context::*;
mod observation;
#[allow(unused_imports)]
pub use obs_handle::*;
mod engine_counters;
pub use observation::*;
mod metrics_text;
#[allow(unused_imports)]
pub use engine_counters::*;
pub use metrics_text::*;
@@ -1,5 +1,5 @@
//! Functions: `note_engine_attached`, `render_prometheus`, `render_requests`, `render_errors` and 4 more.
//! Split out of `request_log` to keep its files under the line limit.
//! The request metrics in the Prometheus text format (requests by endpoint and outcome, errors by class, engine lost,
//! attached and restart counters, time and token histograms) and the note that a worker attached to a loaded engine.
use std::fmt::Write as _;
use super::{ENDPOINTS, ERROR_CLASSES, OUTCOMES, Ordering, REGISTRY};
@@ -1,5 +1,5 @@
//! Methods of `ObsHandle`: `current`, `now`, `id`, `set_stream` and 6 more.
//! Methods of `Record`: `from_state`, `fields`, `push_identity`, `push_measures` and 2 more.
//! The handle through which handlers and the worker mark a request, the `observe` middleware that creates the record,
//! the building of the log line (outcome, token counts, rates) and the update of the request metrics at the end.
use super::{
Arc, CURRENT, Done, ENDPOINTS, ERROR_CLASSES, HeaderValue, Instant, Live, Next, OUTCOMES, ObsHandle, Observe,
@@ -1,7 +1,6 @@
//! Methods of `ReqCtx`: `new`, `with`, `id`, `set_stream` and 7 more.
//! Implements `Drop for ReqCtx`, `Debug for ObsHandle` and 1 more.
//! The life of one request's record (`ReqCtx`: engine start, first token, outcome, written once when it is dropped) and
//! the classifiers that keep free text out of the line: endpoint index, session tag by digest, error class.
use std::fmt::Write as _;
use super::{
Arc, Digest, Done, DoneInfo, Finish, HeaderMap, Live, Mutex, ObsHandle, Record, ReqCtx, SESSION_HEADERS, Sha256,
};
+3 -1
View File
@@ -1,4 +1,6 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the per-request log record: stamps from the injected clock, the figures of a completed request, the
//! one-line size bound, no prompt text or credential in the line, outcome classes, a single publication, the hashed
//! session header, the `observe` middleware and the Prometheus labels.
use super::*;
use leleka_obs::{Format, Level, Settings};
+2 -2
View File
@@ -92,9 +92,9 @@ struct Tap {
#[cfg(test)]
mod tests;
mod now_unix;
mod captured_text;
#[allow(unused_imports)]
pub use now_unix::*;
pub use captured_text::*;
mod record;
#[allow(unused_imports)]
pub use record::*;
@@ -1,5 +1,5 @@
//! Functions: `now_unix`, `seconds`, `append_clipped`, `clipped`.
//! Split out of `request_monitor` to keep its files under the line limit.
//! The wall clock and elapsed seconds stamped on the monitor's records, and the clipping of captured text to `CAP`
//! bytes at a character boundary.
use super::{CAP, Instant, SystemTime, UNIX_EPOCH};
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of this module (split out of its file; the test ids are unchanged).
//! Unit tests of the request monitor: the captured request, the streams and whole responses of the three dialects,
//! usage and failure events, bounded text, eviction by retention, and the disabled monitor.
use super::*;
+8 -13
View File
@@ -58,34 +58,30 @@ pub use harmony_prompt::{PromptDate, set_prompt_date};
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};
use history::append_input;
#[cfg(test)]
use history::{MAX_STORED_RESPONSES, StoredResponse};
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,
CONTEXT_MARGIN_TOKENS, Prepared, parse_request,
prepare_input_tokens,
};
pub use intake::{TracedJson, count_input_tokens};
mod reasoning;
#[allow(unused_imports)]
use reasoning::reasoning_plan;
#[cfg(test)]
use reasoning::render_request_prompt;
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;
@@ -94,18 +90,17 @@ pub(crate) use stream::StreamEnv;
use stream::*;
mod tool_recovery;
pub use tool_recovery::set_tool_call_recovery;
#[allow(unused_imports)]
use tool_recovery::{at_end_plan, finish_generation, log_tool_notes, tool_call_recovery};
#[cfg(test)]
use leleka_gateway_domain::responses::reasoning_effort;
// The pure part of the protocol lives in `leleka-gateway-domain`; the old paths stay.
pub use leleka_gateway_domain::responses::{
CreateRequest, OutputItem, ResponseIdentity, ResponseTrace, TextFormat, TextOptions, Usage,
};
#[allow(unused_imports)]
use leleka_gateway_domain::responses::{
flat_tools, is_structured, reasoning_effort, reasoning_enabled, reject_remote_refs,
render_request_with, text_part, tool_schema_accepted, validate_live_subset,
validate_text_format,
flat_tools, is_structured, reasoning_enabled,
render_request_with, text_part, validate_live_subset,
};
use leleka_gateway_domain::sampler_limit::{drop_unsupported_samplers, unsupported_sampler};
+2 -2
View File
@@ -3,7 +3,7 @@
use super::{
AppState, Arc, CreateRequest, Family, IntoResponse, Json, JsonRejection, Response, SharedCodec, State, StatusCode,
TextCodec, Tokenizer, Value, api_error, append_input, harmony_prompt, json, render_request, validate_live_subset,
Tokenizer, Value, api_error, append_input, harmony_prompt, json, render_request, validate_live_subset,
vision_error,
};
@@ -112,7 +112,7 @@ pub(super) async fn expand_images(
pub(super) async fn prepare_input_tokens(
state: &AppState,
request: &mut CreateRequest,
tokenizer: Arc<dyn TextCodec>,
tokenizer: SharedCodec,
encode_images: bool,
) -> Result<Prepared, Box<Response>> {
resolve_previous(state, request).await?;
+4 -3
View File
@@ -1,14 +1,15 @@
//! The reasoning-budget plan of a request.
#[allow(unused_imports)]
use super::*;
use super::{AppState, Arc, CreateRequest, SharedCodec, reasoning_enabled};
#[cfg(test)]
use super::{render_request, tests};
/// The reasoning-budget wrap-up for this request, if thinking is on and a budget is set (the
/// request's `reasoning_budget_tokens`, else the config's).
pub(super) fn reasoning_plan(
request: &CreateRequest,
state: &AppState,
codec: &Arc<dyn TextCodec>,
codec: &SharedCodec,
) -> Option<crate::wire::ReasoningPlan> {
// The wrap-up and the byte accounting are the Qwen path's; the Harmony family has no reasoning budget.
let tokenizer = codec.qwen()?;
+2 -1
View File
@@ -1,5 +1,6 @@
//! Server-sent-event streaming of a Responses API generation: plain text, buffered and tool calls.
//! Moved out of responses.rs (STRA-338 S6); everything here is private to the `responses` module tree.
//! Holds what the three loops share: the event stream type, response id and usage, the prelude and trace tail events,
//! the storing of the finished response, and the classification of engine events. Private to the `responses` tree.
use super::{
Catalog, Context, CreateRequest, Event, Finish, Infallible, IntoResponse, NEXT_RESPONSE_ID, Ordering, OutputItem,
+2 -1
View File
@@ -1,4 +1,5 @@
//! Unit tests of the Responses API handlers (moved out of responses.rs, STRA-338 S6).
//! Unit tests of the Responses API handlers: control tokens, custom tools, stored history, input items, live streaming,
//! reasoning, sampling, stateless replay, stream termination, structured output, tool policy and replay, validation.
mod control_tokens;
mod custom_tools;

Some files were not shown because too many files have changed in this diff Show More