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.
This commit is contained in:
1 parent
597ac432e1
commit
5bafd000c8
13 files changed
+651
-51
No files matched your search
+64
-19
@@ -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<ChatResponse, ApiErrorEnvelope> {
|
||||
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<impl Stream<Item = Event> + 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<Prompt, ApiErrorEnvelope> {
|
||||
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<std::path::PathBuf>);
|
||||
|
||||
impl Drop for TempFilesGuard {
|
||||
fn drop(&mut self) {
|
||||
for p in &self.0 {
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn send_piece(
|
||||
tx: &UnboundedSender<Event>,
|
||||
id: &str,
|
||||
@@ -248,7 +271,7 @@ fn send_piece(
|
||||
model: &str,
|
||||
piece: &Piece,
|
||||
st: &mut EmitState,
|
||||
abort_engine: &Arc<Engine>,
|
||||
engine: &Arc<Engine>,
|
||||
) {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -119,6 +119,14 @@ pub struct ChatRequest {
|
||||
pub presence_penalty: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub seed: Option<u64>,
|
||||
/// Engine sampling extensions many OpenAI-compatible clients send
|
||||
/// (OpenWebUI, llama.cpp, ...). `top_k = 0` means "disabled".
|
||||
#[serde(default)]
|
||||
pub top_k: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub min_p: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub repetition_penalty: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub stop: Option<Stop>,
|
||||
/// Tool definitions. Parsed but not yet acted on: kept so the request
|
||||
|
||||
Reference in new issue
Block a user