From 5bafd000c81af8fbb4282b95df31931228d878af Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 24 Nov 2026 18:42:56 +0100 Subject: [PATCH] Respond to code review: sampling defaults, abort race, hardening + README Bug fixes (from review/README.md): - Apply config sampling defaults field-by-field, so an absent temperature no longer means greedy; expose top_k/min_p/repetition_penalty on ChatRequest; top_k=0 is "disabled" (-> 64), not greedy. - Fix cross-request abort race: Engine::request_stop() sets the cancel flag only; the owning generate loop does STOP+drain itself, instead of a spawned abort() that could hit a later request holding the lock. - Initialize tracing-subscriber (RUST_LOG, default info); events were dropped. - TempFilesGuard removes materialized images on every exit path (error/panic/drop); build_prompt runs in spawn_blocking off the async worker; ureq image fetch gets a 15s timeout, a 32MB cap and a basic SSRF guard (literal loopback/private hosts). - Non-blocking shutdown (STOP+QUIT without taking the request lock first) and a bounded drain_to_done that marks the engine dead on timeout. Operational hardening: - Graceful shutdown on SIGTERM as well as SIGINT. - Warn when binding a non-loopback address (no auth, allowed_hosts not enforced). - Configurable startup/silence timeouts (optional config keys, default 600s). Docs: - Add README.md (English): what strata-ctl is, why Rust for stable server use, architecture, usage, honest status, and credits to Strata / Niko1221. 76 tests green + 2 real-file ignored; clippy clean; cargo fmt applied. Deferred (heavy): automatic engine restart after a crash. --- Cargo.lock | 79 +++++++++++++++++++++ Cargo.toml | 1 + README.md | 137 +++++++++++++++++++++++++++++++++++++ src/api/service.rs | 83 +++++++++++++++++----- src/api/types.rs | 8 +++ src/config.rs | 32 +++++++++ src/engine/protocol.rs | 18 ++++- src/engine/supervisor.rs | 54 +++++++++++++-- src/inkling/formatter.rs | 23 +++++-- src/inkling/images.rs | 114 ++++++++++++++++++++++++++---- src/main.rs | 71 +++++++++++++++++-- tests/engine_supervisor.rs | 34 +++++++++ tests/inkling_formatter.rs | 48 +++++++++++++ 13 files changed, 651 insertions(+), 51 deletions(-) create mode 100644 README.md diff --git a/Cargo.lock b/Cargo.lock index 2eb9f26..2b6fe25 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -882,6 +882,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "lebe" version = "0.5.3" @@ -944,6 +950,15 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + [[package]] name = "matchit" version = "0.8.4" @@ -1112,6 +1127,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -1634,6 +1658,15 @@ dependencies = [ "serde", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" @@ -1730,6 +1763,7 @@ dependencies = [ "tokio-stream", "tower", "tracing", + "tracing-subscriber", "ureq", ] @@ -1799,6 +1833,15 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + [[package]] name = "tiff" version = "0.11.3" @@ -1944,6 +1987,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", ] [[package]] @@ -2037,6 +2110,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "version_check" version = "0.9.5" diff --git a/Cargo.toml b/Cargo.toml index e2e5c26..8581eea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ minijinja = { version = "3.1.0", features = ["serde"] } image = "0.25.10" base64 = "0.23.1" ureq = "3.5.2" +tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } [dev-dependencies] http-body-util = "0.1.5" diff --git a/README.md b/README.md new file mode 100644 index 0000000..99e1264 --- /dev/null +++ b/README.md @@ -0,0 +1,137 @@ +# strata-ctl + +A Rust control layer for the [Strata](https://github.com/Niko1221/Strata) inference +engine: an OpenAI-compatible HTTP API that drives the engine over its native line +protocol. + +`strata-ctl` is a from-scratch **Rust rewrite of Strata's control framework** (the +Python "serve" layer that sits between HTTP clients and the C++ inference engine). +It is not a fork of the engine itself: the engine stays the upstream C++ binary +(`strata-inkling`); this project replaces the layer that supervises it and exposes +it to the network. + +## Why Rust? + +We believe Rust is a much better fit than Python for a process meant to run +**stably, unattended, on a server** for long periods: + +- **Memory safety without a garbage collector** — no GC pauses, no reference-count + cycles leaking over weeks of uptime, no interpreter runtime to babysit. +- **Predictable latency and throughput** — compiled, no GIL, async I/O on `tokio` + with explicit control over blocking work. +- **Fearless concurrency** — the compiler enforces the ownership rules that keep a + shared, long-lived engine supervisor honest under concurrent requests. +- **A single self-contained binary** — trivial to deploy, supervise (systemd) and + reproduce; no virtualenv, no dependency drift at runtime. + +The original Python layer remains the **behavioral specification**: this rewrite +aims to match what it does on the wire, while being a more dependable thing to +leave running on a server. + +## Relationship to Strata + +- **Strata** — "Run powerful AI on your own computer. Chat, code and work with + images, locally." Free, open source (MIT), by **Niko1221** and the Strata + contributors: . +- This project targets Strata's **Inkling** engine (`strata-inkling`, the + `inkling2_loop` architecture) and its in-process Vision. The API layer is built + behind a model-agnostic `Formatter` seam, so other dialects can be added later. +- All credit for the engine, the model format and the original control-layer + behavior goes to the Strata project and its author. `strata-ctl` is an + independent reimplementation of the control layer only. + +## Features + +OpenAI-compatible endpoints: + +- `POST /v1/chat/completions` — streaming (SSE) and non-streaming. +- `GET /v1/models`, `GET /health`. + +Behavior implemented and validated against the real Inkling engine: + +- **Chain-of-thought separation** — thinking is streamed live as + `reasoning_content`, distinct from the answer `content`. +- **Images** — OpenAI / Responses / Anthropic image parts (base64 data URLs, + http(s) URLs, local paths) are materialized and handed to the engine's + in-process Vision; unsupported formats are normalized to PNG. +- **Tool calling** — structured OpenAI `tool_calls` in the llama.cpp `--jinja` + style: the server renders tool declarations and parses the model's calls; + **execution is client-side** (the server never runs tools). +- **Stop sequences** — incremental matching with hold-back, so a stop string split + across streaming deltas is still caught. +- **Abort on client disconnect** — generation is stopped when the SSE client goes + away, freeing the engine for the next request. +- **Sampling** — per-request knobs override config defaults field-by-field + (`temperature`, `top_p`, `top_k`, `min_p`, penalties, `seed`); `top_k = 0` is + treated as "disabled", not greedy. + +Operational hardening: + +- Graceful shutdown on **SIGINT and SIGTERM**; the engine is signalled without + blocking on an in-flight request. +- Configurable startup and silence-watchdog timeouts. +- A warning when binding a non-loopback address (the API has no authentication). +- Blocking image I/O runs off the async event loop; temp files are cleaned on every + exit path; image fetches have a timeout, a size cap and a basic SSRF guard. + +## Architecture + +``` +shared JSON config ──► InklingFormatter ──► Engine supervisor ──► axum HTTP API + (tolerant) tokenizer + chat line protocol /v1/... + template + dialect (GEN/T/DONE/STOP) +``` + +- `config` — tolerant loader for the shared `strata-inkling.json`: it reads what it + understands and ignores every other key, so one file can drive several tools. +- `inkling` — the model dialect: HF `tokenizers` (o200k BPE) wrapper, MiniJinja chat + template, the channel-token state machine, and the image bridge. +- `engine` — a pure protocol parser plus a supervisor that owns the child process, + serializes requests on its single control stream, and handles STOP/drain/QUIT. +- `api` — request/response types, the `Formatter`/`Decoder` seam, the completion + service (stream + non-stream) and the axum router. + +## Building and running + +Requires a Rust toolchain and a built Strata engine binary (`strata-inkling`). + +```sh +cargo build --release + +# Print the launch plan resolved from the config (default): +./target/release/strata-ctl --config /path/to/strata-inkling.json + +# Start the engine and serve the API: +./target/release/strata-ctl --serve --config /path/to/strata-inkling.json +# overrides: --host 127.0.0.1 --port 8095 +``` + +The default config path is `~/.config/strata-inkling/strata-inkling.json`. Logging +uses `tracing`; set `RUST_LOG` to control verbosity (default `info`). + +### Configuration + +The config is the same JSON the other Strata tools use. Keys acted on here include +`exe`, `args`, `cwd`, `tokenizer`, `model_name`, `host`, `port`, `reasoning_effort`, +`sampling`, and the optional `startup_timeout_secs` / `silence_timeout_secs`. +Everything else (`arch`, `mcp_servers`, `cors_origins`, `allowed_hosts`, …) is +preserved untouched and reported as ignored — unknown keys never break startup. + +## Status + +Working and tested (76 tests, plus 2 real-file tests run on demand). Text, images +and the full client-side tool loop have been validated live against the real +Inkling engine. + +Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function +returns a clear 400), multi-slot batching, logprobs / structured output, automatic +engine restart after a crash, an API key / `allowed_hosts` enforcement, a full +SSRF guard against DNS rebinding, and the Anthropic / Responses native endpoints. + +## License and credits + +MIT, like Strata itself. + +- **Strata** engine and original control layer: Niko1221 and the Strata + contributors — . +- **strata-ctl** (this Rust control layer): Federico (`iz0eyj`). \ No newline at end of file diff --git a/src/api/service.rs b/src/api/service.rs index 9fb8a6b..af33fc1 100644 --- a/src/api/service.rs +++ b/src/api/service.rs @@ -16,7 +16,7 @@ use tokio_stream::wrappers::UnboundedReceiverStream; use crate::engine::{Engine, EngineLine, Outcome}; -use super::formatter::{self, Formatter, Piece}; +use super::formatter::{self, Formatter, Piece, Prompt}; use super::stop::StopFilter; use super::types::{ completion_id, now_unix, tool_call_id, ApiErrorEnvelope, ChatChunk, ChatMessage, ChatRequest, @@ -41,18 +41,15 @@ impl ChatService { /// One-shot completion. pub async fn complete(&self, req: &ChatRequest) -> Result { - let prompt = self.fmt.build_prompt(req)?; + let mut prompt = self.build_prompt_blocking(req).await?; + // temp files are removed on any exit path (engine error/panic included) + let _temp = TempFilesGuard(std::mem::take(&mut prompt.temp_files)); let outcome = self .engine .generate(prompt.max_new, &prompt.sampling, &prompt.ids, |_| {}) .await .map_err(formatter_error)?; - // drop per-request temp files (materialized images) now generation is done - for p in &prompt.temp_files { - let _ = std::fs::remove_file(p); - } - let mut dec = self.fmt.decoder(); let reason = outcome.done.as_ref().map(|d| d.finish.as_str()); let decoded = @@ -115,7 +112,7 @@ impl ChatService { &self, req: &ChatRequest, ) -> Result + Send + 'static, ApiErrorEnvelope> { - let prompt = self.fmt.build_prompt(req)?; + let prompt = self.build_prompt_blocking(req).await?; let id = completion_id(); let created = now_unix(); @@ -135,6 +132,8 @@ impl ChatService { ); let p_stops = req.stop.clone().map(|s| s.into_vec()).unwrap_or_default(); tokio::spawn(async move { + // temp files removed on any exit path (error/panic/drop included) + let _temp = TempFilesGuard(p_temp); // Open the stream the way OpenAI clients expect: role first. send( &tx, @@ -205,11 +204,6 @@ impl ChatService { ); } - // drop per-request temp files (materialized images) - for p in &p_temp { - let _ = std::fs::remove_file(p); - } - let finish = if st.had_tools { FinishReason::ToolCalls } else if st.stop_hit { @@ -230,6 +224,23 @@ impl ChatService { Ok(UnboundedReceiverStream::new(rx)) } + + /// Run `build_prompt` off the async worker: image materialization does + /// blocking network/disk I/O (ureq fetch, image decode, fs write) that would + /// otherwise stall the Tokio event loop and every other HTTP request. + async fn build_prompt_blocking(&self, req: &ChatRequest) -> Result { + let fmt = self.fmt.clone(); + let req = req.clone(); + tokio::task::spawn_blocking(move || fmt.build_prompt(&req)) + .await + .map_err(|e| { + ApiErrorEnvelope::new( + format!("prompt build task failed: {e}"), + "engine_error", + None, + ) + })? + } } /// Mutable per-request emit state for the streaming path (kept in one struct so @@ -241,6 +252,18 @@ struct EmitState { stop_hit: bool, } +/// Removes per-request temp files (materialized images) on ANY exit path: +/// normal return, engine error, panic, or a dropped stream future. +struct TempFilesGuard(Vec); + +impl Drop for TempFilesGuard { + fn drop(&mut self) { + for p in &self.0 { + let _ = std::fs::remove_file(p); + } + } +} + fn send_piece( tx: &UnboundedSender, id: &str, @@ -248,7 +271,7 @@ fn send_piece( model: &str, piece: &Piece, st: &mut EmitState, - abort_engine: &Arc, + engine: &Arc, ) { let delta = match piece { Piece::Content(s) => { @@ -256,11 +279,10 @@ fn send_piece( let emit = st.stops.feed(s); if st.stops.hit && !st.stop_hit { st.stop_hit = true; - // stop reached: abort the engine so we don't keep generating - let e = abort_engine.clone(); - tokio::spawn(async move { - let _ = e.abort().await; - }); + // stop reached: signal the owning generate loop to STOP+drain. + // No spawn/abort(): that could race a later request on the lock + // and abort the wrong one. + engine.request_stop(); } if emit.is_empty() { return; @@ -344,3 +366,26 @@ fn usage_of(outcome: &Outcome, prompt_len: u32, completion: u32) -> Usage { fn formatter_error(err: crate::engine::EngineError) -> ApiErrorEnvelope { formatter::engine_error(err).1 } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn temp_files_guard_removes_on_drop() { + let p = std::env::temp_dir().join(format!( + "strata-ctl-guard-{}-{}.tmp", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::write(&p, b"x").unwrap(); + assert!(p.exists()); + { + let _g = TempFilesGuard(vec![p.clone()]); + } + assert!(!p.exists(), "guard must remove the file on drop"); + } +} diff --git a/src/api/types.rs b/src/api/types.rs index ed1fb72..e47cc32 100644 --- a/src/api/types.rs +++ b/src/api/types.rs @@ -119,6 +119,14 @@ pub struct ChatRequest { pub presence_penalty: Option, #[serde(default)] pub seed: Option, + /// Engine sampling extensions many OpenAI-compatible clients send + /// (OpenWebUI, llama.cpp, ...). `top_k = 0` means "disabled". + #[serde(default)] + pub top_k: Option, + #[serde(default)] + pub min_p: Option, + #[serde(default)] + pub repetition_penalty: Option, #[serde(default)] pub stop: Option, /// Tool definitions. Parsed but not yet acted on: kept so the request diff --git a/src/config.rs b/src/config.rs index 581c3cf..fe31629 100644 --- a/src/config.rs +++ b/src/config.rs @@ -14,6 +14,7 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; +use std::time::Duration; use serde::Deserialize; @@ -79,6 +80,13 @@ pub struct Config { #[serde(default)] pub sampling: SamplingDefaults, + /// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds. + /// Optional: both default to 600s when absent. + #[serde(default)] + pub startup_timeout_secs: Option, + #[serde(default)] + pub silence_timeout_secs: Option, + /// Keys we understand but don't act on yet are NOT listed above, so they /// arrive here untouched — the "ignore what isn't ours" guarantee. #[serde(flatten)] @@ -165,6 +173,16 @@ impl Config { cli.or(self.port).unwrap_or(8095) } + /// Timeout waiting for the engine's `READY` line (default 600s). + pub fn startup_timeout(&self) -> Duration { + Duration::from_secs(self.startup_timeout_secs.unwrap_or(600)) + } + + /// Silence watchdog: max gap between engine output lines (default 600s). + pub fn silence_timeout(&self) -> Duration { + Duration::from_secs(self.silence_timeout_secs.unwrap_or(600)) + } + /// The top-level keys present in the file that we are not acting on — /// reported by `--check` so the shared-file contract stays visible. pub fn ignored_keys(&self) -> Vec<&str> { @@ -281,4 +299,18 @@ mod tests { let keys = s.keys(); assert_eq!(keys, " temperature=1.0"); } + + #[test] + fn timeouts_default_and_override() { + let cfg = Config::parse(REAL, "test").unwrap(); + assert_eq!(cfg.startup_timeout(), Duration::from_secs(600)); + assert_eq!(cfg.silence_timeout(), Duration::from_secs(600)); + let cfg2 = Config::parse( + r#"{"exe":"/x/e","startup_timeout_secs":30,"silence_timeout_secs":120}"#, + "test", + ) + .unwrap(); + assert_eq!(cfg2.startup_timeout(), Duration::from_secs(30)); + assert_eq!(cfg2.silence_timeout(), Duration::from_secs(120)); + } } diff --git a/src/engine/protocol.rs b/src/engine/protocol.rs index 828614f..e8d39ca 100644 --- a/src/engine/protocol.rs +++ b/src/engine/protocol.rs @@ -184,8 +184,11 @@ impl Sampling { key("top_p", fmt_float(tp)); } if let Some(tk) = self.top_k { - // the engine's sampled path keeps at most 64 candidates - key("top_k", (tk.clamp(1, 64)).to_string()); + // `top_k = 0` means "disabled" in OpenAI-compatible clients: map it + // to the engine's widest sampled path (64) instead of clamping to 1, + // which would silently make sampling greedy. + let k = if tk == 0 { 64 } else { tk.clamp(1, 64) }; + key("top_k", k.to_string()); } if let Some(mp) = self.min_p.filter(|mp| *mp > 0.0 && *mp <= 1.0) { key("min_p", fmt_float(mp)); @@ -346,6 +349,17 @@ mod tests { assert_eq!(s.keys(), " temperature=1.0 top_p=0.9 top_k=64 seed=42"); } + #[test] + fn top_k_zero_means_disabled_not_greedy() { + // 0 is "disabled" for OpenAI-compatible clients: it must NOT become 1 + // (greedy); we map it to the engine's widest sampled path. + let s = Sampling { + top_k: Some(0), + ..Default::default() + }; + assert_eq!(s.keys(), " top_k=64"); + } + #[test] fn penalties_drag_the_window() { let s = Sampling { diff --git a/src/engine/supervisor.rs b/src/engine/supervisor.rs index 5dfad71..110928a 100644 --- a/src/engine/supervisor.rs +++ b/src/engine/supervisor.rs @@ -167,6 +167,14 @@ impl Engine { }) } + /// Override the silence watchdog (max gap between engine output lines). + /// Builder-style so callers can tune it from config without a new `start` + /// parameter. + pub fn with_silence(mut self, silence: Duration) -> Self { + self.silence = silence; + self + } + pub fn ready(&self) -> Ready { self.ready } @@ -211,7 +219,10 @@ impl Engine { // here, inside the request that owns the wires. if self.ctl.flag.load(std::sync::atomic::Ordering::Relaxed) { self.send("STOP\n").await?; - drain_to_done(&mut g.stdout).await?; + if let Err(e) = drain_to_done(&mut g.stdout, self.silence).await { + g.dead = true; + return Err(e); + } return Err(EngineError::Refused("aborted".into())); } let raw = match tokio::time::timeout(self.silence, read_line(&mut g.stdout)).await { @@ -220,7 +231,9 @@ impl Engine { // and report, like Python's silence watchdog. The DONE we // trigger is drained here, so the wires stay usable. let _ = self.send("STOP\n").await; - let _ = drain_to_done(&mut g.stdout).await; + if drain_to_done(&mut g.stdout, self.silence).await.is_err() { + g.dead = true; + } return Err(EngineError::Silent(self.silence)); } Ok(Err(e)) => { @@ -283,13 +296,31 @@ impl Engine { self.pipes.try_lock().is_ok() } - /// `QUIT` and reap the child. + /// Signals the request that owns the wires to stop, WITHOUT taking the lock + /// or sending STOP from outside: the owning `generate` loop sees the flag and + /// does STOP+drain itself. For the synchronous token callback (stop-sequence + /// hit), where spawning `abort()` could race a later request that already + /// took the lock and abort the wrong one. + pub fn request_stop(&self) { + self.ctl + .flag + .store(true, std::sync::atomic::Ordering::Relaxed); + } + + /// `QUIT` and reap the child. Signals first without waiting on the request + /// lock: STOP finishes the in-flight request (DONE) and QUIT makes the engine + /// exit, so the owning `generate` releases the wires. Taking `pipes.lock()` + /// first would block Ctrl-C for up to the silence timeout mid-generation. pub async fn shutdown(&self) -> Result<(), EngineError> { - let mut g = self.pipes.lock().await; + let _ = self.send("STOP\n").await; + let _ = self.send("QUIT\n").await; + let mut g = match tokio::time::timeout(Duration::from_secs(5), self.pipes.lock()).await { + Ok(g) => g, + Err(_) => return Ok(()), // engine already signalled; do not hang + }; if g.dead { return Ok(()); } - let _ = self.send("QUIT\n").await; let _ = tokio::time::timeout(Duration::from_secs(5), g.child.wait()).await; let _ = g.child.start_kill(); g.dead = true; @@ -297,9 +328,18 @@ impl Engine { } } -async fn drain_to_done(stdout: &mut BufReader) -> Result<(), EngineError> { +async fn drain_to_done( + stdout: &mut BufReader, + timeout: Duration, +) -> Result<(), EngineError> { loop { - match EngineLine::parse(&read_line(stdout).await?).into_kind() { + // Bounded: an engine that never answers STOP must not hold the wires + // forever (the caller marks itself dead on timeout). + let raw = match tokio::time::timeout(timeout, read_line(stdout)).await { + Err(_) => return Err(EngineError::Silent(timeout)), + Ok(r) => r?, + }; + match EngineLine::parse(&raw).into_kind() { LineKind::Done | LineKind::Err => return Ok(()), _ => continue, } diff --git a/src/inkling/formatter.rs b/src/inkling/formatter.rs index 209bfd3..2041a9c 100644 --- a/src/inkling/formatter.rs +++ b/src/inkling/formatter.rs @@ -22,6 +22,9 @@ pub struct InklingFormatter { model: String, effort: Option, max_new_default: u32, + /// Config-level sampling defaults, applied field-by-field when the request + /// omits a knob (otherwise the engine would fall back to greedy). + default_sampling: Sampling, } impl InklingFormatter { @@ -30,6 +33,7 @@ impl InklingFormatter { template: ChatTemplate, model: String, effort: Option, + default_sampling: Sampling, ) -> Self { Self { tok, @@ -37,6 +41,7 @@ impl InklingFormatter { model, effort, max_new_default: 2048, + default_sampling, } } @@ -100,14 +105,20 @@ impl Formatter for InklingFormatter { .map(|p| super::images::encode_path(&p.to_string_lossy())) .collect(); + // Per-request knobs win; anything the client omits falls back to the + // config defaults (so an absent temperature does not mean greedy). + let d = &self.default_sampling; let sampling = Sampling { - temperature: req.temperature, - top_p: req.top_p, - frequency_penalty: req.frequency_penalty, - presence_penalty: req.presence_penalty, - seed: req.seed, + temperature: req.temperature.or(d.temperature), + top_p: req.top_p.or(d.top_p), + top_k: req.top_k.or(d.top_k), + min_p: req.min_p.or(d.min_p), + repetition_penalty: req.repetition_penalty.or(d.repetition_penalty), + frequency_penalty: req.frequency_penalty.or(d.frequency_penalty), + presence_penalty: req.presence_penalty.or(d.presence_penalty), + penalty_last_n: d.penalty_last_n, + seed: req.seed.or(d.seed), images, - ..Default::default() }; Ok(Prompt { ids, diff --git a/src/inkling/images.rs b/src/inkling/images.rs index 7c1c14c..9f06bb8 100644 --- a/src/inkling/images.rs +++ b/src/inkling/images.rs @@ -6,12 +6,20 @@ //! Unsupported formats (WebP/TIFF/AVIF, which agents like omp send) are //! normalized to PNG; JPEG/PNG/BMP/GIF pass through untouched. +use std::io::Read; use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; use base64::Engine; use serde_json::Value as Json; +/// Cap on a fetched image body: a hostile/slow URL must not exhaust memory. +const MAX_IMAGE_BYTES: u64 = 32 * 1024 * 1024; +/// Global timeout for an image fetch (connect + read), so a slow URL cannot +/// stall the request indefinitely. +const FETCH_TIMEOUT: Duration = Duration::from_secs(15); + #[derive(Debug, thiserror::Error)] pub enum ImageError { #[error("unsupported image source: {0}")] @@ -101,11 +109,23 @@ pub fn materialize(sources: &[String]) -> Result, ImageError> { ); let mut out = Vec::new(); for (idx, src) in sources.iter().enumerate() { - let raw = load_bytes(src)?; - let (data, ext) = normalize(raw)?; - let p = base.join(format!("{nonce}-{idx}{ext}")); - std::fs::write(&p, &data).map_err(|e| ImageError::Io(e.to_string()))?; - out.push(p); + let written = (|| -> Result { + let raw = load_bytes(src)?; + let (data, ext) = normalize(raw)?; + let p = base.join(format!("{nonce}-{idx}{ext}")); + std::fs::write(&p, &data).map_err(|e| ImageError::Io(e.to_string()))?; + Ok(p) + })(); + match written { + Ok(p) => out.push(p), + Err(e) => { + // a later image failed: do not leak the ones already written + for p in &out { + let _ = std::fs::remove_file(p); + } + return Err(e); + } + } } Ok(out) } @@ -126,18 +146,64 @@ fn load_bytes(src: &str) -> Result, ImageError> { .map_err(|e| ImageError::Decode(e.to_string())); } if src.starts_with("http://") || src.starts_with("https://") { - let mut resp = ureq::get(src) - .call() - .map_err(|e| ImageError::Fetch(e.to_string()))?; - return resp - .body_mut() - .read_to_vec() - .map_err(|e| ImageError::Fetch(e.to_string())); + return fetch_http(src); } let path = src.strip_prefix("file://").unwrap_or(src); std::fs::read(path).map_err(|e| ImageError::Io(format!("{path}: {e}"))) } +/// Fetch an http(s) image with a timeout and a size cap. Blocks literal +/// loopback/private hosts (basic SSRF guard); a hostname that *resolves* to an +/// internal address (DNS rebinding) is not covered here. +fn fetch_http(src: &str) -> Result, ImageError> { + if is_blocked_host(src) { + return Err(ImageError::Fetch( + "refusing to fetch an internal/loopback address".into(), + )); + } + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(FETCH_TIMEOUT)) + .build() + .new_agent(); + let mut resp = agent + .get(src) + .call() + .map_err(|e| ImageError::Fetch(e.to_string()))?; + let mut buf = Vec::new(); + resp.body_mut() + .as_reader() + .take(MAX_IMAGE_BYTES) + .read_to_end(&mut buf) + .map_err(|e| ImageError::Fetch(e.to_string()))?; + Ok(buf) +} + +/// True for localhost / `.local` / `.internal` names and literal loopback, +/// private, link-local or unspecified IPs. +fn is_blocked_host(url: &str) -> bool { + let rest = url.split_once("://").map(|(_, r)| r).unwrap_or(url); + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + let host = authority + .rsplit_once('@') + .map(|(_, h)| h) + .unwrap_or(authority); + let host = match host.strip_prefix('[') { + Some(v6) => v6.split(']').next().unwrap_or(v6), // [::1]:port + None => host.split(':').next().unwrap_or(host), // host:port + }; + let host = host.to_ascii_lowercase(); + if host == "localhost" || host.ends_with(".local") || host.ends_with(".internal") { + return true; + } + match host.parse::() { + Ok(std::net::IpAddr::V4(v4)) => { + v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_unspecified() + } + Ok(std::net::IpAddr::V6(v6)) => v6.is_loopback() || v6.is_unspecified(), + Err(_) => false, + } +} + /// Keep JPEG/PNG/BMP/GIF as-is; convert anything else to PNG via the image crate. fn normalize(data: Vec) -> Result<(Vec, &'static str), ImageError> { if let Some(ext) = sniff(&data) { @@ -164,3 +230,27 @@ fn sniff(data: &[u8]) -> Option<&'static str> { None } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ssrf_guard_blocks_internal_hosts() { + for url in [ + "http://localhost/x.png", + "http://127.0.0.1/x.png", + "http://10.0.0.5/x.png", + "http://192.168.1.1/x.png", + "http://169.254.1.1/x.png", + "http://[::1]/x.png", + "http://user@127.0.0.1/x.png", + "http://foo.local/x.png", + ] { + assert!(is_blocked_host(url), "{url} should be blocked"); + } + for url in ["https://example.com/x.png", "https://8.8.8.8/x.png"] { + assert!(!is_blocked_host(url), "{url} should be allowed"); + } + } +} diff --git a/src/main.rs b/src/main.rs index e354c03..57fb100 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,7 +7,6 @@ use std::path::Path; use std::process::ExitCode; use std::sync::Arc; -use std::time::Duration; use strata_ctl::api::{router, ChatService}; use strata_ctl::config::{Config, ConfigError}; @@ -74,6 +73,14 @@ fn parse_args>(mut it: I) -> Result { #[tokio::main] async fn main() -> ExitCode { + // Without a subscriber every tracing event (engine INFO, stream errors) + // would be silently dropped. RUST_LOG overrides the default `info` level. + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .init(); let args = match parse_args(std::env::args().skip(1)) { Ok(a) => a, Err(e) => { @@ -140,17 +147,18 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> E template, cfg.model_name().to_string(), cfg.reasoning_effort.clone(), + cfg.sampling.to_sampling(), )); let engine = match Engine::start( &cfg.exe, &cfg.engine_argv(), cfg.cwd.as_deref(), - Duration::from_secs(600), + cfg.startup_timeout(), ) .await { - Ok(e) => Arc::new(e), + Ok(e) => Arc::new(e.with_silence(cfg.silence_timeout())), Err(e) => { eprintln!("error: the engine failed to start: {e}"); return ExitCode::FAILURE; @@ -164,7 +172,16 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> E let svc = ChatService::new(engine.clone(), fmt); let app = router(svc); - let addr = format!("{}:{}", cfg.bind_host(cli_host), cfg.bind_port(cli_port)); + let host = cfg.bind_host(cli_host); + let port = cfg.bind_port(cli_port); + if !is_loopback_host(&host) { + tracing::warn!( + host = %host, + "binding a non-loopback address: the API has NO authentication and \ + `allowed_hosts` is not enforced — anyone on the network can use it" + ); + } + let addr = format!("{host}:{port}"); let listener = match tokio::net::TcpListener::bind(&addr).await { Ok(l) => l, Err(e) => { @@ -177,7 +194,7 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> E let shutdown_engine = engine.clone(); let result = axum::serve(listener, app) .with_graceful_shutdown(async move { - let _ = tokio::signal::ctrl_c().await; + wait_for_shutdown_signal().await; println!("\nshutting down"); let _ = shutdown_engine.shutdown().await; }) @@ -228,3 +245,47 @@ fn report_config_error(path: &std::path::Path, err: ConfigError) -> ExitCode { } ExitCode::FAILURE } + +/// Resolve on Ctrl-C (SIGINT) or SIGTERM (systemd's default stop signal). +async fn wait_for_shutdown_signal() { + let ctrl_c = tokio::signal::ctrl_c(); + let mut sigterm = match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + { + Ok(s) => s, + Err(e) => { + tracing::warn!(error = %e, "cannot install SIGTERM handler; SIGINT only"); + let _ = ctrl_c.await; + return; + } + }; + tokio::select! { + _ = ctrl_c => {}, + _ = sigterm.recv() => {}, + } +} + +/// True for `localhost` and literal loopback IPs (127.0.0.1, ::1). Wildcard +/// binds (0.0.0.0, ::) and LAN addresses are NOT loopback. +fn is_loopback_host(host: &str) -> bool { + if host.eq_ignore_ascii_case("localhost") { + return true; + } + host.parse::() + .map(|ip| ip.is_loopback()) + .unwrap_or(false) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn loopback_detection() { + for h in ["127.0.0.1", "::1", "localhost", "LOCALHOST"] { + assert!(is_loopback_host(h), "{h} should be loopback"); + } + for h in ["0.0.0.0", "::", "192.168.1.10", "10.0.0.5"] { + assert!(!is_loopback_host(h), "{h} should NOT be loopback"); + } + } +} diff --git a/tests/engine_supervisor.rs b/tests/engine_supervisor.rs index 7d2640f..80f2102 100644 --- a/tests/engine_supervisor.rs +++ b/tests/engine_supervisor.rs @@ -119,3 +119,37 @@ async fn abort_reaches_a_running_request_and_frees_the_wires() { assert!(!engine.abort().await.unwrap()); engine.shutdown().await.unwrap(); } + +#[tokio::test] +async fn request_stop_signals_the_owner_without_taking_the_lock() { + let exe_mock = mock(); + let engine = std::sync::Arc::new( + Engine::start( + &exe_mock.0, + &[exe_mock.1[0].clone()], + None, + Duration::from_secs(10), + ) + .await + .unwrap(), + ); + let holder = { + let engine = engine.clone(); + tokio::spawn(async move { + engine + .generate(1000, &Sampling::default(), &[888888], |_| {}) + .await + }) + }; + tokio::time::sleep(Duration::from_millis(200)).await; + // sync, takes no lock and sends no STOP from outside: the owning generate + // loop sees the flag and does STOP+drain itself (no race on a later request) + engine.request_stop(); + let held = holder.await.unwrap(); + assert!( + matches!(&held, Err(EngineError::Refused(m)) if m == "aborted"), + "the held request should end aborted: {held:?}" + ); + assert!(engine.is_idle()); + engine.shutdown().await.unwrap(); +} diff --git a/tests/inkling_formatter.rs b/tests/inkling_formatter.rs index 581c529..a2d136f 100644 --- a/tests/inkling_formatter.rs +++ b/tests/inkling_formatter.rs @@ -13,6 +13,7 @@ use tokenizers::{AddedToken, Tokenizer}; use strata_ctl::api::formatter::{Formatter, Piece}; use strata_ctl::api::types::ChatRequest; +use strata_ctl::engine::Sampling; use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer}; static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -66,6 +67,7 @@ fn formatter() -> (InklingFormatter, Arc, std::path::PathBuf) template, "test-model".into(), Some("low".into()), + Sampling::default(), ); (fmt, tok, path) } @@ -220,3 +222,49 @@ fn tool_choice_none_and_auto_accepted() { } let _ = std::fs::remove_file(&path); } + +#[test] +fn config_sampling_defaults_are_applied_and_overridable() { + let (tok, path) = fixture_tokenizer(); + let template = ChatTemplate::new(TEMPLATE).unwrap(); + let defaults = Sampling { + temperature: Some(0.7), + top_p: Some(0.9), + min_p: Some(0.05), + repetition_penalty: Some(1.1), + ..Default::default() + }; + let fmt = InklingFormatter::new( + tok.clone(), + template, + "test-model".into(), + Some("low".into()), + defaults, + ); + + // request omits every knob -> config defaults apply (not greedy) + let req: ChatRequest = serde_json::from_value( + json!({"model": "test-model", "messages": [{"role": "user", "content": "hello"}]}), + ) + .unwrap(); + let s = fmt.build_prompt(&req).unwrap().sampling; + assert_eq!(s.temperature, Some(0.7)); + assert_eq!(s.top_p, Some(0.9)); + assert_eq!(s.min_p, Some(0.05)); + assert_eq!(s.repetition_penalty, Some(1.1)); + + // a per-request knob wins; the others still fall back to the defaults + let req2: ChatRequest = serde_json::from_value(json!({ + "model": "test-model", + "messages": [{"role": "user", "content": "hello"}], + "temperature": 0.2, + "top_k": 0 + })) + .unwrap(); + let s2 = fmt.build_prompt(&req2).unwrap().sampling; + assert_eq!(s2.temperature, Some(0.2)); + assert_eq!(s2.top_p, Some(0.9)); + assert_eq!(s2.top_k, Some(0)); // carried through; keys() maps 0 -> 64 + assert!(s2.keys().contains("top_k=64")); + let _ = std::fs::remove_file(&path); +}