From 64b6c6d30ab08d2ecc067ccfd30df3504683da7d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 14 Nov 2026 19:40:20 +0100 Subject: [PATCH] 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 --- control-plane/src/app/metrics_document.rs | 2 +- control-plane/src/backend_worker.rs | 24 ++- control-plane/src/backend_worker/conclude.rs | 5 +- ...request_id.rs => engine_request_checks.rs} | 5 +- .../{serve_one.rs => serve_generation.rs} | 4 +- ...{run_backend_worker.rs => worker_entry.rs} | 5 +- control-plane/src/chat.rs | 8 +- ...letion.rs => chat_completions_endpoint.rs} | 5 +- control-plane/src/chat/stream_response.rs | 4 +- control-plane/src/config.rs | 7 +- control-plane/src/config/control_vector.rs | 5 +- control-plane/src/config/methods.rs | 3 +- control-plane/src/config/methods/load.rs | 3 +- .../src/config/methods/load_checks.rs | 16 +- .../src/config/methods/load_engine.rs | 19 +-- .../src/config/methods/load_sections.rs | 20 +-- .../{provision.rs => startup_preparation.rs} | 5 +- control-plane/src/config/process_env.rs | 20 --- control-plane/src/config/tests.rs | 4 +- control-plane/src/cuda_memory.rs | 7 +- control-plane/src/env_settings.rs | 143 ++++++++++++++++++ control-plane/src/hardware_view.rs | 4 +- control-plane/src/harmony_family/tests.rs | 3 +- control-plane/src/kar/tests.rs | 3 +- control-plane/src/kar_overlay.rs | 19 +-- control-plane/src/kar_overlay/compare.rs | 5 +- control-plane/src/kar_overlay/prepare.rs | 5 +- ...ified.rs => verified_source_resolution.rs} | 5 +- .../src/kar_overlay/write_provenance.rs | 4 +- control-plane/src/kar_quality.rs | 4 +- control-plane/src/kar_quality/analyze.rs | 5 +- .../{parse_digest.rs => sample_records.rs} | 5 +- control-plane/src/kar_quality/tests.rs | 3 +- control-plane/src/kar_stream_encode/tests.rs | 3 +- control-plane/src/kar_writer.rs | 16 +- ...ite_archive.rs => archive_entry_points.rs} | 4 +- control-plane/src/kar_writer/archive_file.rs | 1 - .../src/kar_writer/archive_write_steps.rs | 2 - .../{write_record.rs => directory_record.rs} | 4 +- ...ite_nested_section.rs => nested_layout.rs} | 5 +- .../{write_section.rs => section_payload.rs} | 5 +- control-plane/src/kar_writer/tests.rs | 4 +- control-plane/src/key_init/windows.rs | 2 +- control-plane/src/lib.rs | 1 + control-plane/src/mcp.rs | 16 +- control-plane/src/mcp/http_transport.rs | 5 +- control-plane/src/mcp/hub.rs | 21 ++- ...ings_default.rs => mcp_settings_errors.rs} | 4 +- control-plane/src/mcp/parse_config.rs | 5 +- control-plane/src/mcp/server.rs | 16 +- .../{dispatch.rs => stdio_message_routing.rs} | 5 +- control-plane/src/mcp/stdio_transport.rs | 7 +- control-plane/src/mcp/tests.rs | 3 +- .../{result_text.rs => tool_result_text.rs} | 4 +- control-plane/src/mcp/transport.rs | 4 +- control-plane/src/messages.rs | 4 +- .../messages/{adapt.rs => messages_stream.rs} | 5 +- control-plane/src/messages/tests.rs | 4 +- control-plane/src/model.rs | 4 +- .../model/{fetch_one.rs => file_download.rs} | 18 ++- control-plane/src/model/manifest_fetch.rs | 15 +- control-plane/src/model/tests.rs | 5 +- control-plane/src/mtp_fetch.rs | 12 +- .../{mtime_ns.rs => command_line.rs} | 8 +- control-plane/src/mtp_fetch/fetcher.rs | 12 +- .../{repo_url.rs => url_range_digest.rs} | 5 +- control-plane/src/native_pack.rs | 8 +- .../src/native_pack/convert_tensor.rs | 5 +- control-plane/src/native_pack/dense_files.rs | 4 +- .../src/native_pack/expert_layout.rs | 5 +- ...conversions_inexact.rs => pack_outputs.rs} | 4 +- .../{safe_name.rs => pack_rules.rs} | 4 +- control-plane/src/native_pack/same_bytes.rs | 4 +- control-plane/src/native_pack/tests.rs | 3 +- control-plane/src/preflight.rs | 8 +- control-plane/src/prepare_preview.rs | 20 +-- ...ify_derived.rs => derived_verification.rs} | 4 +- .../src/prepare_preview/prepare_sharded.rs | 4 +- .../{prepare.rs => prepare_single_file.rs} | 4 +- ...yload_bytes.rs => preview_entry_points.rs} | 4 +- .../src/prepare_preview/spool_raw_f32.rs | 4 +- ..._policy.rs => streamed_sharded_prepare.rs} | 4 +- ...e_preview_tensor.rs => tensor_encoding.rs} | 4 +- control-plane/src/prepare_preview/tests.rs | 3 +- control-plane/src/prometheus.rs | 4 +- .../src/prometheus/{counter.rs => render.rs} | 4 +- control-plane/src/prometheus/tests.rs | 3 +- control-plane/src/request_log.rs | 13 +- .../{engine_counters.rs => metrics_text.rs} | 4 +- .../{obs_handle.rs => observation.rs} | 4 +- .../{endpoint_index.rs => request_context.rs} | 5 +- control-plane/src/request_log/tests.rs | 4 +- control-plane/src/request_monitor.rs | 4 +- .../{now_unix.rs => captured_text.rs} | 4 +- control-plane/src/request_monitor/tests.rs | 3 +- control-plane/src/responses.rs | 21 +-- control-plane/src/responses/intake.rs | 4 +- control-plane/src/responses/reasoning.rs | 7 +- control-plane/src/responses/stream.rs | 3 +- control-plane/src/responses/tests.rs | 3 +- control-plane/src/runtime_config.rs | 2 +- control-plane/src/server_api.rs | 15 +- .../{error_body.rs => engine_lifecycle.rs} | 4 +- ...{model_busy.rs => model_control_routes.rs} | 4 +- .../server_api/{slots.rs => status_routes.rs} | 4 +- control-plane/src/service_install.rs | 4 +- .../{parse.rs => command_line.rs} | 9 +- control-plane/src/service_install/control.rs | 9 +- control-plane/src/service_install/tests.rs | 3 +- control-plane/src/service_install/unix.rs | 2 +- .../src/service_install/unix/tests.rs | 5 +- control-plane/src/service_switch.rs | 4 +- control-plane/src/service_switch/reconcile.rs | 9 +- control-plane/src/service_switch/run.rs | 9 +- ...provision_budget.rs => switch_profiles.rs} | 10 +- control-plane/src/service_switch/tests.rs | 3 +- control-plane/src/vision.rs | 9 +- control-plane/src/vision/config.rs | 4 +- control-plane/src/vision/encoder.rs | 4 +- .../src/vision/{cleanup.rs => image_fetch.rs} | 4 +- control-plane/src/wait_ready/tests.rs | 4 +- control-plane/src/worker.rs | 21 +-- .../{combine_done.rs => engine_request.rs} | 4 +- .../worker/{finish.rs => generation_end.rs} | 4 +- .../{generation_result.rs => worker_entry.rs} | 5 +- .../tests/reasoning_budget_oracle.rs | 2 +- 126 files changed, 534 insertions(+), 417 deletions(-) rename control-plane/src/backend_worker/{request_id.rs => engine_request_checks.rs} (95%) rename control-plane/src/backend_worker/{serve_one.rs => serve_generation.rs} (95%) rename control-plane/src/backend_worker/{run_backend_worker.rs => worker_entry.rs} (85%) rename control-plane/src/chat/{completion.rs => chat_completions_endpoint.rs} (97%) rename control-plane/src/config/methods/{provision.rs => startup_preparation.rs} (92%) delete mode 100644 control-plane/src/config/process_env.rs create mode 100644 control-plane/src/env_settings.rs rename control-plane/src/kar_overlay/{resolve_verified.rs => verified_source_resolution.rs} (97%) rename control-plane/src/kar_quality/{parse_digest.rs => sample_records.rs} (94%) rename control-plane/src/kar_writer/{write_archive.rs => archive_entry_points.rs} (82%) rename control-plane/src/kar_writer/{write_record.rs => directory_record.rs} (93%) rename control-plane/src/kar_writer/{write_nested_section.rs => nested_layout.rs} (97%) rename control-plane/src/kar_writer/{write_section.rs => section_payload.rs} (97%) rename control-plane/src/mcp/{settings_default.rs => mcp_settings_errors.rs} (89%) rename control-plane/src/mcp/{dispatch.rs => stdio_message_routing.rs} (89%) rename control-plane/src/mcp/{result_text.rs => tool_result_text.rs} (93%) rename control-plane/src/messages/{adapt.rs => messages_stream.rs} (93%) rename control-plane/src/model/{fetch_one.rs => file_download.rs} (94%) rename control-plane/src/mtp_fetch/{mtime_ns.rs => command_line.rs} (89%) rename control-plane/src/mtp_fetch/{repo_url.rs => url_range_digest.rs} (85%) rename control-plane/src/native_pack/{conversions_inexact.rs => pack_outputs.rs} (98%) rename control-plane/src/native_pack/{safe_name.rs => pack_rules.rs} (95%) rename control-plane/src/prepare_preview/{verify_derived.rs => derived_verification.rs} (97%) rename control-plane/src/prepare_preview/{prepare.rs => prepare_single_file.rs} (98%) rename control-plane/src/prepare_preview/{minimum_part_payload_bytes.rs => preview_entry_points.rs} (92%) rename control-plane/src/prepare_preview/{prepare_sharded_streamed_with_policy.rs => streamed_sharded_prepare.rs} (96%) rename control-plane/src/prepare_preview/{encode_preview_tensor.rs => tensor_encoding.rs} (96%) rename control-plane/src/prometheus/{counter.rs => render.rs} (96%) rename control-plane/src/request_log/{engine_counters.rs => metrics_text.rs} (94%) rename control-plane/src/request_log/{obs_handle.rs => observation.rs} (97%) rename control-plane/src/request_log/{endpoint_index.rs => request_context.rs} (96%) rename control-plane/src/request_monitor/{now_unix.rs => captured_text.rs} (86%) rename control-plane/src/server_api/{error_body.rs => engine_lifecycle.rs} (97%) rename control-plane/src/server_api/{model_busy.rs => model_control_routes.rs} (97%) rename control-plane/src/server_api/{slots.rs => status_routes.rs} (98%) rename control-plane/src/service_install/{parse.rs => command_line.rs} (94%) rename control-plane/src/service_switch/{provision_budget.rs => switch_profiles.rs} (95%) rename control-plane/src/vision/{cleanup.rs => image_fetch.rs} (88%) rename control-plane/src/worker/{combine_done.rs => engine_request.rs} (92%) rename control-plane/src/worker/{finish.rs => generation_end.rs} (94%) rename control-plane/src/worker/{generation_result.rs => worker_entry.rs} (96%) diff --git a/control-plane/src/app/metrics_document.rs b/control-plane/src/app/metrics_document.rs index b00511bc..6842b977 100644 --- a/control-plane/src/app/metrics_document.rs +++ b/control-plane/src/app/metrics_document.rs @@ -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 { diff --git a/control-plane/src/backend_worker.rs b/control-plane/src/backend_worker.rs index c78137fb..3423a07d 100644 --- a/control-plane/src/backend_worker.rs +++ b/control-plane/src/backend_worker.rs @@ -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::*; diff --git a/control-plane/src/backend_worker/conclude.rs b/control-plane/src/backend_worker/conclude.rs index 5663f606..5400f7b5 100644 --- a/control-plane/src/backend_worker/conclude.rs +++ b/control-plane/src/backend_worker/conclude.rs @@ -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, diff --git a/control-plane/src/backend_worker/request_id.rs b/control-plane/src/backend_worker/engine_request_checks.rs similarity index 95% rename from control-plane/src/backend_worker/request_id.rs rename to control-plane/src/backend_worker/engine_request_checks.rs index 32afc379..42e42122 100644 --- a/control-plane/src/backend_worker/request_id.rs +++ b/control-plane/src/backend_worker/engine_request_checks.rs @@ -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}; diff --git a/control-plane/src/backend_worker/serve_one.rs b/control-plane/src/backend_worker/serve_generation.rs similarity index 95% rename from control-plane/src/backend_worker/serve_one.rs rename to control-plane/src/backend_worker/serve_generation.rs index 6c447efb..3c31dbbc 100644 --- a/control-plane/src/backend_worker/serve_one.rs +++ b/control-plane/src/backend_worker/serve_generation.rs @@ -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, diff --git a/control-plane/src/backend_worker/run_backend_worker.rs b/control-plane/src/backend_worker/worker_entry.rs similarity index 85% rename from control-plane/src/backend_worker/run_backend_worker.rs rename to control-plane/src/backend_worker/worker_entry.rs index 508cd315..0ba509b7 100644 --- a/control-plane/src/backend_worker/run_backend_worker.rs +++ b/control-plane/src/backend_worker/worker_entry.rs @@ -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, diff --git a/control-plane/src/chat.rs b/control-plane/src/chat.rs index 85a4009a..3c73255a 100644 --- a/control-plane/src/chat.rs +++ b/control-plane/src/chat.rs @@ -21,9 +21,7 @@ use leleka_gateway_domain::chat_completions::{Request, call, finish, identity, u struct Events(mpsc::Receiver); -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::*; diff --git a/control-plane/src/chat/completion.rs b/control-plane/src/chat/chat_completions_endpoint.rs similarity index 97% rename from control-plane/src/chat/completion.rs rename to control-plane/src/chat/chat_completions_endpoint.rs index be8585af..9a6a6c98 100644 --- a/control-plane/src/chat/completion.rs +++ b/control-plane/src/chat/chat_completions_endpoint.rs @@ -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, diff --git a/control-plane/src/chat/stream_response.rs b/control-plane/src/chat/stream_response.rs index 47d71b38..faeaea67 100644 --- a/control-plane/src/chat/stream_response.rs +++ b/control-plane/src/chat/stream_response.rs @@ -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}; diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs index 780b5052..33b5f743 100644 --- a/control-plane/src/config.rs +++ b/control-plane/src/config.rs @@ -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::*; diff --git a/control-plane/src/config/control_vector.rs b/control-plane/src/config/control_vector.rs index 51a9ca32..49bfa833 100644 --- a/control-plane/src/config/control_vector.rs +++ b/control-plane/src/config/control_vector.rs @@ -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}; diff --git a/control-plane/src/config/methods.rs b/control-plane/src/config/methods.rs index 2dba85f9..ffcdfc59 100644 --- a/control-plane/src/config/methods.rs +++ b/control-plane/src/config/methods.rs @@ -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; diff --git a/control-plane/src/config/methods/load.rs b/control-plane/src/config/methods/load.rs index e0a58846..837548fe 100644 --- a/control-plane/src/config/methods/load.rs +++ b/control-plane/src/config/methods/load.rs @@ -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; diff --git a/control-plane/src/config/methods/load_checks.rs b/control-plane/src/config/methods/load_checks.rs index 1380150d..24a9e2d2 100644 --- a/control-plane/src/config/methods/load_checks.rs +++ b/control-plane/src/config/methods/load_checks.rs @@ -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, 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::(&fs::read_to_string(path)?)?, @@ -39,7 +39,7 @@ fn tokenizer_setting( file: &FileConfig, worker: Option<&WorkerConfig>, ) -> Result, 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, 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) -> Result, 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) -> Result, crate::BoxError fn api_key_setting( from_file: Option, ) -> Result>, 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) -> Result, 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) -> Result { - 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!( diff --git a/control-plane/src/config/methods/load_engine.rs b/control-plane/src/config/methods/load_engine.rs index c9c41792..cff422a2 100644 --- a/control-plane/src/config/methods/load_engine.rs +++ b/control-plane/src/config/methods/load_engine.rs @@ -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, } -fn parsed_env(name: &str) -> Result, crate::BoxError> -where - T::Err: std::error::Error + 'static, -{ - Ok(optional_env(name)? - .map(|value| value.parse::()) - .transpose()?) -} - fn args_and_startup_timeout(file: &FileConfig) -> Result<(Vec, 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::>(&value)) .transpose()?; - let timeout_override = parsed_env::("STRATA_STARTUP_TIMEOUT_S")?; + let timeout_override = crate::env_settings::number::("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, u64), cra } fn restarts_limit(file: &FileConfig) -> Result { - let max_restarts = parsed_env::("STRATA_MAX_WORKER_RESTARTS")? + let max_restarts = crate::env_settings::number::("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 { } fn generation_timeout(file: &FileConfig) -> Result, crate::BoxError> { - let generation_timeout_s = parsed_env::("STRATA_GENERATION_TIMEOUT_S")?.or_else(|| { + let generation_timeout_s = crate::env_settings::number::("STRATA_GENERATION_TIMEOUT_S")?.or_else(|| { file.engine .as_ref() .and_then(|engine| engine.generation_timeout_s) diff --git a/control-plane/src/config/methods/load_sections.rs b/control-plane/src/config/methods/load_sections.rs index 5e13601f..faf677a5 100644 --- a/control-plane/src/config/methods/load_sections.rs +++ b/control-plane/src/config/methods/load_sections.rs @@ -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 Result { - 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 { - let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")? - .map(|value| value.parse::()) - .transpose()? + let max_in_flight_requests = crate::env_settings::number::("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 { } fn prompt_date_setting(file: &FileConfig) -> Result { - 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 Result, crate::BoxError> { - let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")? - .map(|value| value.parse::()) - .transpose()? + let queue_timeout_s = crate::env_settings::number::("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, crate::BoxError> { } fn shutdown_grace(file: &FileConfig) -> Result { - let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")? - .map(|value| value.parse::()) - .transpose()? + let shutdown_grace_s = crate::env_settings::number::("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 { - 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)) diff --git a/control-plane/src/config/methods/provision.rs b/control-plane/src/config/methods/startup_preparation.rs similarity index 92% rename from control-plane/src/config/methods/provision.rs rename to control-plane/src/config/methods/startup_preparation.rs index 397a5b5c..82fe64b9 100644 --- a/control-plane/src/config/methods/provision.rs +++ b/control-plane/src/config/methods/startup_preparation.rs @@ -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; diff --git a/control-plane/src/config/process_env.rs b/control-plane/src/config/process_env.rs deleted file mode 100644 index 636d60d9..00000000 --- a/control-plane/src/config/process_env.rs +++ /dev/null @@ -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, 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 { - env::var_os(name) -} diff --git a/control-plane/src/config/tests.rs b/control-plane/src/config/tests.rs index 94f53d55..10f013fd 100644 --- a/control-plane/src/config/tests.rs +++ b/control-plane/src/config/tests.rs @@ -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; diff --git a/control-plane/src/cuda_memory.rs b/control-plane/src/cuda_memory.rs index d09d4976..887ebbbe 100644 --- a/control-plane/src/cuda_memory.rs +++ b/control-plane/src/cuda_memory.rs @@ -20,12 +20,7 @@ impl Policy { } pub async fn select(self) -> Result { 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()) diff --git a/control-plane/src/env_settings.rs b/control-plane/src/env_settings.rs new file mode 100644 index 00000000..1d5ff133 --- /dev/null +++ b/control-plane/src/env_settings.rs @@ -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, 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 { + 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(name: &str) -> Result, crate::BoxError> +where + T::Err: std::error::Error + 'static, +{ + Ok(text(name)?.map(|value| value.parse::()).transpose()?) +} + +/// A variable named by the configuration (the runtime credential), `None` when unset or not Unicode. +pub fn variable(name: &str) -> Option { + std::env::var(name).ok() +} + +/// The status document of the supervisor that started this process (`LELEKA_STATUS_FILE`). +pub fn supervisor_status_file() -> Option { + 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 { + 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, 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, 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 { + 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> { + 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 { + 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 { + std::env::vars_os() + .map(|(name, _)| name) + .filter(|name| name.to_string_lossy().starts_with("STRATA_")) + .collect() +} diff --git a/control-plane/src/hardware_view.rs b/control-plane/src/hardware_view.rs index 0fd7d4f5..98e50fff 100644 --- a/control-plane/src/hardware_view.rs +++ b/control-plane/src/hardware_view.rs @@ -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, + 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) diff --git a/control-plane/src/harmony_family/tests.rs b/control-plane/src/harmony_family/tests.rs index de414e8a..09948dfe 100644 --- a/control-plane/src/harmony_family/tests.rs +++ b/control-plane/src/harmony_family/tests.rs @@ -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; diff --git a/control-plane/src/kar/tests.rs b/control-plane/src/kar/tests.rs index 72a35d82..6867ab46 100644 --- a/control-plane/src/kar/tests.rs +++ b/control-plane/src/kar/tests.rs @@ -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; diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs index 3ce7499b..416ef179 100644 --- a/control-plane/src/kar_overlay.rs +++ b/control-plane/src/kar_overlay.rs @@ -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::*; diff --git a/control-plane/src/kar_overlay/compare.rs b/control-plane/src/kar_overlay/compare.rs index df034bbd..9c8df21c 100644 --- a/control-plane/src/kar_overlay/compare.rs +++ b/control-plane/src/kar_overlay/compare.rs @@ -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, diff --git a/control-plane/src/kar_overlay/prepare.rs b/control-plane/src/kar_overlay/prepare.rs index b5dbc03b..d448c510 100644 --- a/control-plane/src/kar_overlay/prepare.rs +++ b/control-plane/src/kar_overlay/prepare.rs @@ -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, diff --git a/control-plane/src/kar_overlay/resolve_verified.rs b/control-plane/src/kar_overlay/verified_source_resolution.rs similarity index 97% rename from control-plane/src/kar_overlay/resolve_verified.rs rename to control-plane/src/kar_overlay/verified_source_resolution.rs index 971b4c57..dd3aaa17 100644 --- a/control-plane/src/kar_overlay/resolve_verified.rs +++ b/control-plane/src/kar_overlay/verified_source_resolution.rs @@ -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, diff --git a/control-plane/src/kar_overlay/write_provenance.rs b/control-plane/src/kar_overlay/write_provenance.rs index 10f0fbd7..2fe4f192 100644 --- a/control-plane/src/kar_overlay/write_provenance.rs +++ b/control-plane/src/kar_overlay/write_provenance.rs @@ -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}; diff --git a/control-plane/src/kar_quality.rs b/control-plane/src/kar_quality.rs index 59e546f8..295182b8 100644 --- a/control-plane/src/kar_quality.rs +++ b/control-plane/src/kar_quality.rs @@ -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::*; diff --git a/control-plane/src/kar_quality/analyze.rs b/control-plane/src/kar_quality/analyze.rs index 57555285..316a1530 100644 --- a/control-plane/src/kar_quality/analyze.rs +++ b/control-plane/src/kar_quality/analyze.rs @@ -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, diff --git a/control-plane/src/kar_quality/parse_digest.rs b/control-plane/src/kar_quality/sample_records.rs similarity index 94% rename from control-plane/src/kar_quality/parse_digest.rs rename to control-plane/src/kar_quality/sample_records.rs index 0a74097b..028b81e5 100644 --- a/control-plane/src/kar_quality/parse_digest.rs +++ b/control-plane/src/kar_quality/sample_records.rs @@ -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, diff --git a/control-plane/src/kar_quality/tests.rs b/control-plane/src/kar_quality/tests.rs index 0d110d93..7c1d45be 100644 --- a/control-plane/src/kar_quality/tests.rs +++ b/control-plane/src/kar_quality/tests.rs @@ -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::*; diff --git a/control-plane/src/kar_stream_encode/tests.rs b/control-plane/src/kar_stream_encode/tests.rs index cc458944..25fb28f1 100644 --- a/control-plane/src/kar_stream_encode/tests.rs +++ b/control-plane/src/kar_stream_encode/tests.rs @@ -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}; diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index 093525ee..b5728382 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -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::*; diff --git a/control-plane/src/kar_writer/write_archive.rs b/control-plane/src/kar_writer/archive_entry_points.rs similarity index 82% rename from control-plane/src/kar_writer/write_archive.rs rename to control-plane/src/kar_writer/archive_entry_points.rs index 39186151..cde25647 100644 --- a/control-plane/src/kar_writer/write_archive.rs +++ b/control-plane/src/kar_writer/archive_entry_points.rs @@ -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}; diff --git a/control-plane/src/kar_writer/archive_file.rs b/control-plane/src/kar_writer/archive_file.rs index 1a3c6a83..ac5dbda8 100644 --- a/control-plane/src/kar_writer/archive_file.rs +++ b/control-plane/src/kar_writer/archive_file.rs @@ -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, diff --git a/control-plane/src/kar_writer/archive_write_steps.rs b/control-plane/src/kar_writer/archive_write_steps.rs index b9ca5945..0d5dbe86 100644 --- a/control-plane/src/kar_writer/archive_write_steps.rs +++ b/control-plane/src/kar_writer/archive_write_steps.rs @@ -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}; diff --git a/control-plane/src/kar_writer/write_record.rs b/control-plane/src/kar_writer/directory_record.rs similarity index 93% rename from control-plane/src/kar_writer/write_record.rs rename to control-plane/src/kar_writer/directory_record.rs index 759ef341..83bb7227 100644 --- a/control-plane/src/kar_writer/write_record.rs +++ b/control-plane/src/kar_writer/directory_record.rs @@ -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}; diff --git a/control-plane/src/kar_writer/write_nested_section.rs b/control-plane/src/kar_writer/nested_layout.rs similarity index 97% rename from control-plane/src/kar_writer/write_nested_section.rs rename to control-plane/src/kar_writer/nested_layout.rs index 7a64eb3d..67eb04e0 100644 --- a/control-plane/src/kar_writer/write_nested_section.rs +++ b/control-plane/src/kar_writer/nested_layout.rs @@ -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, diff --git a/control-plane/src/kar_writer/write_section.rs b/control-plane/src/kar_writer/section_payload.rs similarity index 97% rename from control-plane/src/kar_writer/write_section.rs rename to control-plane/src/kar_writer/section_payload.rs index f7c14af2..a157e3e9 100644 --- a/control-plane/src/kar_writer/write_section.rs +++ b/control-plane/src/kar_writer/section_payload.rs @@ -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}; diff --git a/control-plane/src/kar_writer/tests.rs b/control-plane/src/kar_writer/tests.rs index 9c2986b0..3e435f7d 100644 --- a/control-plane/src/kar_writer/tests.rs +++ b/control-plane/src/kar_writer/tests.rs @@ -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; diff --git a/control-plane/src/key_init/windows.rs b/control-plane/src/key_init/windows.rs index 30ccc729..9f1c36c5 100644 --- a/control-plane/src/key_init/windows.rs +++ b/control-plane/src/key_init/windows.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Path, USAGE}; use std::{ fs::{File, OpenOptions}, io::{Read, Write}, diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index 87663631..353747bc 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -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; diff --git a/control-plane/src/mcp.rs b/control-plane/src/mcp.rs index d36a6486..09bb43f8 100644 --- a/control-plane/src/mcp.rs +++ b/control-plane/src/mcp.rs @@ -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, + clock: AnyClock, } /// One tool call's outcome (`McpHub.call`). @@ -137,20 +139,22 @@ pub struct CallOutput { pub struct Hub { pub servers: Vec>, 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::*; diff --git a/control-plane/src/mcp/http_transport.rs b/control-plane/src/mcp/http_transport.rs index c49d8756..df381ecc 100644 --- a/control-plane/src/mcp/http_transport.rs +++ b/control-plane/src/mcp/http_transport.rs @@ -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, diff --git a/control-plane/src/mcp/hub.rs b/control-plane/src/mcp/hub.rs index f11b9719..a3355f6f 100644 --- a/control-plane/src/mcp/hub.rs +++ b/control-plane/src/mcp/hub.rs @@ -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>, 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>, 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, ) -> Result { - 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, }) diff --git a/control-plane/src/mcp/settings_default.rs b/control-plane/src/mcp/mcp_settings_errors.rs similarity index 89% rename from control-plane/src/mcp/settings_default.rs rename to control-plane/src/mcp/mcp_settings_errors.rs index e39ef972..ad7e3c70 100644 --- a/control-plane/src/mcp/settings_default.rs +++ b/control-plane/src/mcp/mcp_settings_errors.rs @@ -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}; diff --git a/control-plane/src/mcp/parse_config.rs b/control-plane/src/mcp/parse_config.rs index fed91ded..4d5f1500 100644 --- a/control-plane/src/mcp/parse_config.rs +++ b/control-plane/src/mcp/parse_config.rs @@ -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}; diff --git a/control-plane/src/mcp/server.rs b/control-plane/src/mcp/server.rs index 513c4872..ecc685ed 100644 --- a/control-plane/src/mcp/server.rs +++ b/control-plane/src/mcp/server.rs @@ -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, settings: Settings) -> Self { + pub(super) fn new(name: String, config: Map, 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 ({})", diff --git a/control-plane/src/mcp/dispatch.rs b/control-plane/src/mcp/stdio_message_routing.rs similarity index 89% rename from control-plane/src/mcp/dispatch.rs rename to control-plane/src/mcp/stdio_message_routing.rs index 8fa09633..ef54b9e5 100644 --- a/control-plane/src/mcp/dispatch.rs +++ b/control-plane/src/mcp/stdio_message_routing.rs @@ -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}; diff --git a/control-plane/src/mcp/stdio_transport.rs b/control-plane/src/mcp/stdio_transport.rs index 9e62ecd2..6a0c3af5 100644 --- a/control-plane/src/mcp/stdio_transport.rs +++ b/control-plane/src/mcp/stdio_transport.rs @@ -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"); diff --git a/control-plane/src/mcp/tests.rs b/control-plane/src/mcp/tests.rs index c362bbbb..13f655c6 100644 --- a/control-plane/src/mcp/tests.rs +++ b/control-plane/src/mcp/tests.rs @@ -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::*; diff --git a/control-plane/src/mcp/result_text.rs b/control-plane/src/mcp/tool_result_text.rs similarity index 93% rename from control-plane/src/mcp/result_text.rs rename to control-plane/src/mcp/tool_result_text.rs index bec606bb..ca205c22 100644 --- a/control-plane/src/mcp/result_text.rs +++ b/control-plane/src/mcp/tool_result_text.rs @@ -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}; diff --git a/control-plane/src/mcp/transport.rs b/control-plane/src/mcp/transport.rs index 860aad38..8be55d29 100644 --- a/control-plane/src/mcp/transport.rs +++ b/control-plane/src/mcp/transport.rs @@ -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}; diff --git a/control-plane/src/messages.rs b/control-plane/src/messages.rs index eca2af78..87892f40 100644 --- a/control-plane/src/messages.rs +++ b/control-plane/src/messages.rs @@ -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::*; diff --git a/control-plane/src/messages/adapt.rs b/control-plane/src/messages/messages_stream.rs similarity index 93% rename from control-plane/src/messages/adapt.rs rename to control-plane/src/messages/messages_stream.rs index f8588932..4c8aab22 100644 --- a/control-plane/src/messages/adapt.rs +++ b/control-plane/src/messages/messages_stream.rs @@ -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, diff --git a/control-plane/src/messages/tests.rs b/control-plane/src/messages/tests.rs index e71454ac..782ce3c2 100644 --- a/control-plane/src/messages/tests.rs +++ b/control-plane/src/messages/tests.rs @@ -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::*; diff --git a/control-plane/src/model.rs b/control-plane/src/model.rs index d7445553..99cfc86c 100644 --- a/control-plane/src/model.rs +++ b/control-plane/src/model.rs @@ -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::*; diff --git a/control-plane/src/model/fetch_one.rs b/control-plane/src/model/file_download.rs similarity index 94% rename from control-plane/src/model/fetch_one.rs rename to control-plane/src/model/file_download.rs index 3d7861cb..04ae7848 100644 --- a/control-plane/src/model/fetch_one.rs +++ b/control-plane/src/model/file_download.rs @@ -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(); } } diff --git a/control-plane/src/model/manifest_fetch.rs b/control-plane/src/model/manifest_fetch.rs index 4c0575f9..034325c2 100644 --- a/control-plane/src/model/manifest_fetch.rs +++ b/control-plane/src/model/manifest_fetch.rs @@ -108,24 +108,11 @@ pub(crate) fn http_client() -> Result { .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> { - 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?; } diff --git a/control-plane/src/model/tests.rs b/control-plane/src/model/tests.rs index 275e0678..038798e5 100644 --- a/control-plane/src/model/tests.rs +++ b/control-plane/src/model/tests.rs @@ -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; diff --git a/control-plane/src/mtp_fetch.rs b/control-plane/src/mtp_fetch.rs index 38bbf76b..90d22ef8 100644 --- a/control-plane/src/mtp_fetch.rs +++ b/control-plane/src/mtp_fetch.rs @@ -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; diff --git a/control-plane/src/mtp_fetch/mtime_ns.rs b/control-plane/src/mtp_fetch/command_line.rs similarity index 89% rename from control-plane/src/mtp_fetch/mtime_ns.rs rename to control-plane/src/mtp_fetch/command_line.rs index b1ad016b..24f7de90 100644 --- a/control-plane/src/mtp_fetch/mtime_ns.rs +++ b/control-plane/src/mtp_fetch/command_line.rs @@ -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 { diff --git a/control-plane/src/mtp_fetch/fetcher.rs b/control-plane/src/mtp_fetch/fetcher.rs index 5a2c9daa..8136ca35 100644 --- a/control-plane/src/mtp_fetch/fetcher.rs +++ b/control-plane/src/mtp_fetch/fetcher.rs @@ -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 { - 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)) } diff --git a/control-plane/src/mtp_fetch/repo_url.rs b/control-plane/src/mtp_fetch/url_range_digest.rs similarity index 85% rename from control-plane/src/mtp_fetch/repo_url.rs rename to control-plane/src/mtp_fetch/url_range_digest.rs index eef1a21e..842ad89d 100644 --- a/control-plane/src/mtp_fetch/repo_url.rs +++ b/control-plane/src/mtp_fetch/url_range_digest.rs @@ -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}; diff --git a/control-plane/src/native_pack.rs b/control-plane/src/native_pack.rs index c3eaa165..67f673e0 100644 --- a/control-plane/src/native_pack.rs +++ b/control-plane/src/native_pack.rs @@ -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::*; diff --git a/control-plane/src/native_pack/convert_tensor.rs b/control-plane/src/native_pack/convert_tensor.rs index eefd3e5f..5db1e421 100644 --- a/control-plane/src/native_pack/convert_tensor.rs +++ b/control-plane/src/native_pack/convert_tensor.rs @@ -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, diff --git a/control-plane/src/native_pack/dense_files.rs b/control-plane/src/native_pack/dense_files.rs index 1a891498..e8252e06 100644 --- a/control-plane/src/native_pack/dense_files.rs +++ b/control-plane/src/native_pack/dense_files.rs @@ -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, diff --git a/control-plane/src/native_pack/expert_layout.rs b/control-plane/src/native_pack/expert_layout.rs index 92bfc686..8db9e09f 100644 --- a/control-plane/src/native_pack/expert_layout.rs +++ b/control-plane/src/native_pack/expert_layout.rs @@ -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}; diff --git a/control-plane/src/native_pack/conversions_inexact.rs b/control-plane/src/native_pack/pack_outputs.rs similarity index 98% rename from control-plane/src/native_pack/conversions_inexact.rs rename to control-plane/src/native_pack/pack_outputs.rs index 1701db4d..66d8818a 100644 --- a/control-plane/src/native_pack/conversions_inexact.rs +++ b/control-plane/src/native_pack/pack_outputs.rs @@ -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, diff --git a/control-plane/src/native_pack/safe_name.rs b/control-plane/src/native_pack/pack_rules.rs similarity index 95% rename from control-plane/src/native_pack/safe_name.rs rename to control-plane/src/native_pack/pack_rules.rs index efdb4486..c6243691 100644 --- a/control-plane/src/native_pack/safe_name.rs +++ b/control-plane/src/native_pack/pack_rules.rs @@ -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}; diff --git a/control-plane/src/native_pack/same_bytes.rs b/control-plane/src/native_pack/same_bytes.rs index 11396ea8..73e4829a 100644 --- a/control-plane/src/native_pack/same_bytes.rs +++ b/control-plane/src/native_pack/same_bytes.rs @@ -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}; diff --git a/control-plane/src/native_pack/tests.rs b/control-plane/src/native_pack/tests.rs index 437a18c3..de033a29 100644 --- a/control-plane/src/native_pack/tests.rs +++ b/control-plane/src/native_pack/tests.rs @@ -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::*; diff --git a/control-plane/src/preflight.rs b/control-plane/src/preflight.rs index 12e042c6..f5095619 100644 --- a/control-plane/src/preflight.rs +++ b/control-plane/src/preflight.rs @@ -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))) }) } diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 1a22e17c..462c2f58 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -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; diff --git a/control-plane/src/prepare_preview/verify_derived.rs b/control-plane/src/prepare_preview/derived_verification.rs similarity index 97% rename from control-plane/src/prepare_preview/verify_derived.rs rename to control-plane/src/prepare_preview/derived_verification.rs index 66dd8add..3c4e4eb8 100644 --- a/control-plane/src/prepare_preview/verify_derived.rs +++ b/control-plane/src/prepare_preview/derived_verification.rs @@ -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, diff --git a/control-plane/src/prepare_preview/prepare_sharded.rs b/control-plane/src/prepare_preview/prepare_sharded.rs index b4db427d..527688db 100644 --- a/control-plane/src/prepare_preview/prepare_sharded.rs +++ b/control-plane/src/prepare_preview/prepare_sharded.rs @@ -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, diff --git a/control-plane/src/prepare_preview/prepare.rs b/control-plane/src/prepare_preview/prepare_single_file.rs similarity index 98% rename from control-plane/src/prepare_preview/prepare.rs rename to control-plane/src/prepare_preview/prepare_single_file.rs index 0325cb0f..e7cfb41a 100644 --- a/control-plane/src/prepare_preview/prepare.rs +++ b/control-plane/src/prepare_preview/prepare_single_file.rs @@ -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, diff --git a/control-plane/src/prepare_preview/minimum_part_payload_bytes.rs b/control-plane/src/prepare_preview/preview_entry_points.rs similarity index 92% rename from control-plane/src/prepare_preview/minimum_part_payload_bytes.rs rename to control-plane/src/prepare_preview/preview_entry_points.rs index 1f5e04db..f2e6415e 100644 --- a/control-plane/src/prepare_preview/minimum_part_payload_bytes.rs +++ b/control-plane/src/prepare_preview/preview_entry_points.rs @@ -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}; diff --git a/control-plane/src/prepare_preview/spool_raw_f32.rs b/control-plane/src/prepare_preview/spool_raw_f32.rs index 012621f8..2fa73964 100644 --- a/control-plane/src/prepare_preview/spool_raw_f32.rs +++ b/control-plane/src/prepare_preview/spool_raw_f32.rs @@ -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}; diff --git a/control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs b/control-plane/src/prepare_preview/streamed_sharded_prepare.rs similarity index 96% rename from control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs rename to control-plane/src/prepare_preview/streamed_sharded_prepare.rs index 16d9e3e4..cf047915 100644 --- a/control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs +++ b/control-plane/src/prepare_preview/streamed_sharded_prepare.rs @@ -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, diff --git a/control-plane/src/prepare_preview/encode_preview_tensor.rs b/control-plane/src/prepare_preview/tensor_encoding.rs similarity index 96% rename from control-plane/src/prepare_preview/encode_preview_tensor.rs rename to control-plane/src/prepare_preview/tensor_encoding.rs index 3ed07617..4ae8015e 100644 --- a/control-plane/src/prepare_preview/encode_preview_tensor.rs +++ b/control-plane/src/prepare_preview/tensor_encoding.rs @@ -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, diff --git a/control-plane/src/prepare_preview/tests.rs b/control-plane/src/prepare_preview/tests.rs index 1b91e9e1..51da62aa 100644 --- a/control-plane/src/prepare_preview/tests.rs +++ b/control-plane/src/prepare_preview/tests.rs @@ -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; diff --git a/control-plane/src/prometheus.rs b/control-plane/src/prometheus.rs index 407fa081..8224a4f3 100644 --- a/control-plane/src/prometheus.rs +++ b/control-plane/src/prometheus.rs @@ -45,6 +45,6 @@ mod tests; mod series; use series::SERIES; -mod counter; +mod render; #[allow(unused_imports)] -pub use counter::*; +pub use render::*; diff --git a/control-plane/src/prometheus/counter.rs b/control-plane/src/prometheus/render.rs similarity index 96% rename from control-plane/src/prometheus/counter.rs rename to control-plane/src/prometheus/render.rs index cbd357db..4e5db4d5 100644 --- a/control-plane/src/prometheus/counter.rs +++ b/control-plane/src/prometheus/render.rs @@ -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}; diff --git a/control-plane/src/prometheus/tests.rs b/control-plane/src/prometheus/tests.rs index c0877765..f956d947 100644 --- a/control-plane/src/prometheus/tests.rs +++ b/control-plane/src/prometheus/tests.rs @@ -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; diff --git a/control-plane/src/request_log.rs b/control-plane/src/request_log.rs index 942ecc34..11472c39 100644 --- a/control-plane/src/request_log.rs +++ b/control-plane/src/request_log.rs @@ -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 = 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::*; diff --git a/control-plane/src/request_log/engine_counters.rs b/control-plane/src/request_log/metrics_text.rs similarity index 94% rename from control-plane/src/request_log/engine_counters.rs rename to control-plane/src/request_log/metrics_text.rs index 71e0fa6a..c926ce2e 100644 --- a/control-plane/src/request_log/engine_counters.rs +++ b/control-plane/src/request_log/metrics_text.rs @@ -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}; diff --git a/control-plane/src/request_log/obs_handle.rs b/control-plane/src/request_log/observation.rs similarity index 97% rename from control-plane/src/request_log/obs_handle.rs rename to control-plane/src/request_log/observation.rs index 2318823c..267b3812 100644 --- a/control-plane/src/request_log/obs_handle.rs +++ b/control-plane/src/request_log/observation.rs @@ -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, diff --git a/control-plane/src/request_log/endpoint_index.rs b/control-plane/src/request_log/request_context.rs similarity index 96% rename from control-plane/src/request_log/endpoint_index.rs rename to control-plane/src/request_log/request_context.rs index b9f34213..c1545b36 100644 --- a/control-plane/src/request_log/endpoint_index.rs +++ b/control-plane/src/request_log/request_context.rs @@ -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, }; diff --git a/control-plane/src/request_log/tests.rs b/control-plane/src/request_log/tests.rs index c8161aa9..1f3d8e80 100644 --- a/control-plane/src/request_log/tests.rs +++ b/control-plane/src/request_log/tests.rs @@ -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}; diff --git a/control-plane/src/request_monitor.rs b/control-plane/src/request_monitor.rs index dc717ca0..0e1e2c16 100644 --- a/control-plane/src/request_monitor.rs +++ b/control-plane/src/request_monitor.rs @@ -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::*; diff --git a/control-plane/src/request_monitor/now_unix.rs b/control-plane/src/request_monitor/captured_text.rs similarity index 86% rename from control-plane/src/request_monitor/now_unix.rs rename to control-plane/src/request_monitor/captured_text.rs index fb9b395a..584d218a 100644 --- a/control-plane/src/request_monitor/now_unix.rs +++ b/control-plane/src/request_monitor/captured_text.rs @@ -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}; diff --git a/control-plane/src/request_monitor/tests.rs b/control-plane/src/request_monitor/tests.rs index eb2f79a2..7eb2fdfa 100644 --- a/control-plane/src/request_monitor/tests.rs +++ b/control-plane/src/request_monitor/tests.rs @@ -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::*; diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 107d3667..538d9a6e 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -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}; diff --git a/control-plane/src/responses/intake.rs b/control-plane/src/responses/intake.rs index 9532afd3..e988beed 100644 --- a/control-plane/src/responses/intake.rs +++ b/control-plane/src/responses/intake.rs @@ -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, + tokenizer: SharedCodec, encode_images: bool, ) -> Result> { resolve_previous(state, request).await?; diff --git a/control-plane/src/responses/reasoning.rs b/control-plane/src/responses/reasoning.rs index d50ba688..ed52ae09 100644 --- a/control-plane/src/responses/reasoning.rs +++ b/control-plane/src/responses/reasoning.rs @@ -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, + codec: &SharedCodec, ) -> Option { // The wrap-up and the byte accounting are the Qwen path's; the Harmony family has no reasoning budget. let tokenizer = codec.qwen()?; diff --git a/control-plane/src/responses/stream.rs b/control-plane/src/responses/stream.rs index 09981145..fc1a5171 100644 --- a/control-plane/src/responses/stream.rs +++ b/control-plane/src/responses/stream.rs @@ -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, diff --git a/control-plane/src/responses/tests.rs b/control-plane/src/responses/tests.rs index 5ed59876..79d121ad 100644 --- a/control-plane/src/responses/tests.rs +++ b/control-plane/src/responses/tests.rs @@ -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; diff --git a/control-plane/src/runtime_config.rs b/control-plane/src/runtime_config.rs index d68a0520..a2807940 100644 --- a/control-plane/src/runtime_config.rs +++ b/control-plane/src/runtime_config.rs @@ -94,7 +94,7 @@ fn seconds(name: &str, value: Option, default: f64) -> Result Result { - self.resolve_with(|name| std::env::var(name).ok()) + self.resolve_with(crate::env_settings::variable) } fn resolve_with(self, env: impl Fn(&str) -> Option) -> Result { diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index bc230f62..bb686af0 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -35,12 +35,9 @@ use crate::{ pub const DEFAULT_CHAT_TEMPLATE: &str = include_str!("../../engine/strata/serve/chat_template.jinja"); -mod error_body; -#[allow(unused_imports)] -pub use error_body::*; -mod slots; -#[allow(unused_imports)] -pub use slots::*; -mod model_busy; -#[allow(unused_imports)] -pub use model_busy::*; +mod engine_lifecycle; +pub use engine_lifecycle::*; +mod status_routes; +pub use status_routes::*; +mod model_control_routes; +pub use model_control_routes::*; diff --git a/control-plane/src/server_api/error_body.rs b/control-plane/src/server_api/engine_lifecycle.rs similarity index 97% rename from control-plane/src/server_api/error_body.rs rename to control-plane/src/server_api/engine_lifecycle.rs index c9b20625..e0457c9d 100644 --- a/control-plane/src/server_api/error_body.rs +++ b/control-plane/src/server_api/engine_lifecycle.rs @@ -1,5 +1,5 @@ -//! Functions: `error_body`, `reply`, `now_s`, `header_str` and 15 more. -//! Split out of `server_api` to keep its files under the line limit. +//! The engine load and unload of the operational API (`ensure_loaded`, `load`, `unload`, the idle unload loop), the +//! `/props` and `/api/health` routes, and the helpers the routes share: error bodies, replies, query parsing. use super::{ AppState, Control, DEFAULT_CHAT_TEMPLATE, Duration, HeaderMap, IntoResponse, Json, LoadError, Outcome, Request, diff --git a/control-plane/src/server_api/model_busy.rs b/control-plane/src/server_api/model_control_routes.rs similarity index 97% rename from control-plane/src/server_api/model_busy.rs rename to control-plane/src/server_api/model_control_routes.rs index 9f0d12a9..6d4cdcee 100644 --- a/control-plane/src/server_api/model_busy.rs +++ b/control-plane/src/server_api/model_control_routes.rs @@ -1,5 +1,5 @@ -//! Functions: `model_busy`, `v1_unload`, `v1_load`, `v1_reconfigure` and 8 more. -//! Split out of `server_api` to keep its files under the line limit. +//! The model control routes (`/v1/load`, `/v1/unload`, `/v1/reconfigure`), the request monitor route, the `/mcp` +//! status, the not-found answer, the CORS layer and the `machine` view of `/v1/status`. use super::{ AppState, Arc, Bytes, Control, Cors, HeaderMap, HeaderName, HeaderValue, IntoResponse, Method, Next, Outcome, diff --git a/control-plane/src/server_api/slots.rs b/control-plane/src/server_api/status_routes.rs similarity index 98% rename from control-plane/src/server_api/slots.rs rename to control-plane/src/server_api/status_routes.rs index fbf229cd..7ede1bb8 100644 --- a/control-plane/src/server_api/slots.rs +++ b/control-plane/src/server_api/status_routes.rs @@ -1,5 +1,5 @@ -//! Functions: `slots`, `v1_prefix_match`, `invalid_request`, `v1_status` and 12 more. -//! Split out of `server_api` to keep its files under the line limit. +//! The status and settings routes: `/slots`, `/v1/prefix_match`, `/v1/status`, `/settings` (read, and write from the +//! app's own page only), and the `/load` and `/unload` posts. use super::{ AppState, Bytes, HeaderMap, Outcome, Response, State, StatusCode, UNIX_EPOCH, Value, WorkerState, WorkerStatus, diff --git a/control-plane/src/service_install.rs b/control-plane/src/service_install.rs index 2a2442ab..035b4596 100644 --- a/control-plane/src/service_install.rs +++ b/control-plane/src/service_install.rs @@ -27,9 +27,9 @@ mod unix; #[cfg(test)] mod tests; -mod parse; +mod command_line; #[allow(unused_imports)] -pub use parse::*; +pub use command_line::*; mod control; #[allow(unused_imports)] pub use control::*; diff --git a/control-plane/src/service_install/parse.rs b/control-plane/src/service_install/command_line.rs similarity index 94% rename from control-plane/src/service_install/parse.rs rename to control-plane/src/service_install/command_line.rs index a76fcbac..c6efbf03 100644 --- a/control-plane/src/service_install/parse.rs +++ b/control-plane/src/service_install/command_line.rs @@ -1,5 +1,5 @@ -//! Methods of `SplitFlags`: `take`. Functions: `parse`, `options_from`, `validate_name`, `install_options` and 5 more. -//! Defines `SplitFlags`. +//! Command-line parsing of `service-install` and `service-control`: flags and values, the `--ready-*` readiness flags, +//! the checks on the accepted actions, unit-name validation and the user unit directory. use super::{CONTROL_USAGE, INSTALL_READY_USAGE, Options, PathBuf, USAGE}; @@ -208,10 +208,7 @@ pub(super) fn control_options( #[cfg(unix)] pub(super) fn unit_directory() -> Result { - let config = match std::env::var_os("XDG_CONFIG_HOME") { - Some(value) if !value.is_empty() => PathBuf::from(value), - _ => PathBuf::from(std::env::var_os("HOME").ok_or("HOME is missing")?).join(".config"), - }; + let config = crate::env_settings::config_home()?; if !config.is_absolute() { return Err("user config directory must be absolute".into()); } diff --git a/control-plane/src/service_install/control.rs b/control-plane/src/service_install/control.rs index 32b145a7..d78c88d0 100644 --- a/control-plane/src/service_install/control.rs +++ b/control-plane/src/service_install/control.rs @@ -1,8 +1,9 @@ -//! Methods of `Managed`: `open`, `recheck`, `drain_or_resume`, `stop_unit` and 2 more. -//! Functions: `control`, `controlled`, `admit`, `active_pid` and 5 more. Defines `Managed`. +//! The `service-control` command (status, start, stop, drain, resume, enable and disable of an installed unit, with its +//! readiness check) and the `service-install` run that writes the unit and asks the manager to act on it. -#[allow(unused_imports)] -use super::*; +use super::{Options, Path, PathBuf, control_options, install_options, ready_control_args}; +#[cfg(unix)] +use super::{unit_directory, unix}; #[cfg(unix)] use crate::wait_ready::Waiter; #[cfg(unix)] diff --git a/control-plane/src/service_install/tests.rs b/control-plane/src/service_install/tests.rs index fb03558b..a27e67e8 100644 --- a/control-plane/src/service_install/tests.rs +++ b/control-plane/src/service_install/tests.rs @@ -1,4 +1,5 @@ -//! Unit tests of this module (split out of its file; the test ids are unchanged). +//! Unit tests of the service installer's command lines: the explicit `--start-ready` install, control-only scoped +//! actions, scoped unit names, refused arguments, and the strict readiness options and managed process id. use super::*; diff --git a/control-plane/src/service_install/unix.rs b/control-plane/src/service_install/unix.rs index 250e4a03..4be760ad 100644 --- a/control-plane/src/service_install/unix.rs +++ b/control-plane/src/service_install/unix.rs @@ -1,6 +1,6 @@ //! Unix side of the unit installer: private publication of the unit file and the `systemctl --user` calls. -use super::*; +use super::{Path, validate_name}; use std::{ fs::{self, OpenOptions}, io::{Read, Write}, diff --git a/control-plane/src/service_install/unix/tests.rs b/control-plane/src/service_install/unix/tests.rs index 9dc1b43a..f95f01be 100644 --- a/control-plane/src/service_install/unix/tests.rs +++ b/control-plane/src/service_install/unix/tests.rs @@ -1,7 +1,10 @@ //! Tests of the unit publication and the `systemctl` wrapper (moved out of service_install.rs, STRA-338 S7). use super::*; -use std::os::unix::fs::{PermissionsExt, symlink}; +use std::{ + os::unix::fs::{PermissionsExt, symlink}, + path::PathBuf, +}; /// A directory name under the temp dir that no other test or process uses. fn unique_test_root(prefix: &str) -> PathBuf { std::env::temp_dir().join(format!( diff --git a/control-plane/src/service_switch.rs b/control-plane/src/service_switch.rs index 75a6ee0a..62f3a932 100644 --- a/control-plane/src/service_switch.rs +++ b/control-plane/src/service_switch.rs @@ -214,9 +214,9 @@ mod storage { #[cfg(test)] mod tests; -mod provision_budget; +mod switch_profiles; #[allow(unused_imports)] -pub use provision_budget::*; +pub use switch_profiles::*; mod run; #[allow(unused_imports)] pub use run::*; diff --git a/control-plane/src/service_switch/reconcile.rs b/control-plane/src/service_switch/reconcile.rs index 581e6369..abb5a5b5 100644 --- a/control-plane/src/service_switch/reconcile.rs +++ b/control-plane/src/service_switch/reconcile.rs @@ -1,8 +1,9 @@ -//! Methods of `Interrupted`: `verified_target`, `check_recorded`, `moved_since`, `record` and 1 more. -//! Functions: `reconcile`, `reconcile_journal`, `load_interrupted`, `recorded_catalog` and 2 more. +//! The `service-switch reconcile` command: reads the journal of an interrupted transaction, checks it against the +//! catalog and the recorded digests, observes which service runs and records the outcome. -#[allow(unused_imports)] -use super::*; +use super::{BTreeMap, Catalog, Digest, Path, PathBuf, Profile, Sha256, Value, discover, json, reconcile_arguments}; +#[cfg(unix)] +use super::{storage, validate_auto}; #[cfg(unix)] use storage::{Journal, read}; diff --git a/control-plane/src/service_switch/run.rs b/control-plane/src/service_switch/run.rs index 6b0313bb..f56b4be2 100644 --- a/control-plane/src/service_switch/run.rs +++ b/control-plane/src/service_switch/run.rs @@ -1,8 +1,9 @@ -//! Functions: `run`, `reconcile_arguments`. -//! Split out of `service_switch` to keep its files under the line limit. +//! Entry point of `service-switch`: sends `reconcile` to the reconcile command and every other call to the switch +//! transaction; holds the argument parsing of `reconcile`. -#[allow(unused_imports)] -use super::*; +use super::{BTreeMap, Value, arguments, reconcile}; +#[cfg(unix)] +use super::transaction; pub async fn run(args: &[String]) -> Result { if args.first().is_some_and(|arg| arg == "reconcile") { diff --git a/control-plane/src/service_switch/provision_budget.rs b/control-plane/src/service_switch/switch_profiles.rs similarity index 95% rename from control-plane/src/service_switch/provision_budget.rs rename to control-plane/src/service_switch/switch_profiles.rs index 1e14718a..7e3d37f7 100644 --- a/control-plane/src/service_switch/provision_budget.rs +++ b/control-plane/src/service_switch/switch_profiles.rs @@ -1,5 +1,5 @@ -//! Methods of `Profile`: `readiness`, `control`. -//! Functions: `provision_budget`, `ready_budget`, `check_profile_ids`, `arguments` and 8 more. +//! The profiles of a `service-switch`: the provision and readiness time budgets, the readiness and control calls of a +//! profile, the parsing of the switch arguments, the discovery of the running service and the provisioning of a target. use super::{BTreeMap, Catalog, Duration, PathBuf, Profile, USAGE, Value, storage}; #[cfg(unix)] @@ -190,10 +190,8 @@ fn provision_command(profile: &Profile) -> Result Box> + 'a> { + ) -> impl Iterator> + 'a { self.calls.push((prompt.to_vec(), max_new)); let stream = self .streams