From d716dbaf70211f5a8888c146348b1e5fdfd66290 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 01:07:39 +0200 Subject: [PATCH] Persist opt-in native Responses history across restarts (#16) * feat: persist opt-in native Responses history across restarts * fix: retain private snapshot mode under restrictive umask * docs: clarify optional persistence on resource routes --- .github/workflows/linux.yml | 2 + control-plane/src/config.rs | 16 ++ control-plane/src/history_store.rs | 224 ++++++++++++++++++++++++ control-plane/src/lib.rs | 1 + control-plane/src/main.rs | 6 + control-plane/src/preflight.rs | 1 + control-plane/src/responses.rs | 271 +++++++++++++++++++++++++++-- docs/api-contract.md | 58 +++++- scripts/smoke-response-history.py | 102 +++++++++-- 9 files changed, 650 insertions(+), 31 deletions(-) create mode 100644 control-plane/src/history_store.rs diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 69ed62df..590eaeb3 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -260,6 +260,8 @@ jobs: run: python3 scripts/smoke-tool-policy.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Stored Responses retrieval and deletion without GPU run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Durable Responses restart and disk failure gate + run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --durable - name: Native drain and resume without GPU run: python3 scripts/smoke-native-drain.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Native signal shutdown grace without GPU diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs index b86bbe8b..5eb6b81a 100644 --- a/control-plane/src/config.rs +++ b/control-plane/src/config.rs @@ -12,6 +12,7 @@ use serde::Deserialize; use crate::worker::WorkerConfig; pub struct Config { + pub response_history_dir: Option, pub assets: Vec, pub native_model: Option, pub gpu_requirement: Option, @@ -29,6 +30,7 @@ pub struct Config { #[derive(Default, Deserialize)] #[serde(deny_unknown_fields)] struct FileConfig { + response_history_dir: Option, #[serde(default)] assets: Vec, native_model: Option, @@ -202,7 +204,21 @@ impl Config { .or(file.api_key_file) .map(|path| crate::auth::ApiKey::from_file(&path).map(std::sync::Arc::new)) .transpose()?; + let response_history_dir = env::var_os("STRATA_RESPONSE_HISTORY_DIR") + .map(PathBuf::from) + .or(file.response_history_dir); + if response_history_dir.as_ref().is_some_and(|p| { + !p.is_absolute() + || p.file_name().is_none() + || p.components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + }) { + return Err( + "response_history_dir must be an absolute non-root path without '..'".into(), + ); + } Ok(Self { + response_history_dir, assets: file.assets, native_model: file.native_model, gpu_requirement: file.gpu_requirement, diff --git a/control-plane/src/history_store.rs b/control-plane/src/history_store.rs new file mode 100644 index 00000000..07c86935 --- /dev/null +++ b/control-plane/src/history_store.rs @@ -0,0 +1,224 @@ +//! Explicitly opted-in, single-operator plaintext history. No payload logging. +use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicBool, Ordering}, +}; + +pub(crate) struct Store { + directory: PathBuf, + directory_handle: File, + _lock: File, + failed: AtomicBool, +} + +const SNAPSHOT: &str = "history-v1.json"; +const STAGE: &str = "history-v1.pending"; +pub(crate) const MAX_SNAPSHOT_BYTES: u64 = 129 * 1024 * 1024; + +impl Store { + #[cfg(unix)] + pub(crate) fn open(directory: &Path) -> Result { + use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; + if !directory.is_absolute() || directory.file_name().is_none() { + return Err("response_history_dir must be an absolute non-root path"); + } + match fs::DirBuilder::new().mode(0o700).create(directory) { + Ok(()) => (), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => (), + Err(_) => { + return Err("cannot create private response history directory; parent must exist"); + } + } + let metadata = + fs::symlink_metadata(directory).map_err(|_| "cannot inspect history directory")?; + if !metadata.is_dir() + || metadata.file_type().is_symlink() + || metadata.uid() != unsafe { libc::geteuid() } + || metadata.mode() & 0o777 != 0o700 + { + return Err( + "history directory must be owned by this user with mode 0700, not a symlink", + ); + } + let directory = directory + .canonicalize() + .map_err(|_| "cannot resolve history directory")?; + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(directory.join("history.lock")) + .map_err(|_| "cannot open history lock")?; + private_file(&lock)?; + lock.try_lock() + .map_err(|_| "response history is already in use or cannot be locked")?; + let store = Self { + directory_handle: File::open(&directory) + .map_err(|_| "cannot open history directory")?, + directory, + _lock: lock, + failed: AtomicBool::new(false), + }; + // The only disposable file is our unpublished stage, after taking the lock. + let stage = store.directory.join(STAGE); + match fs::symlink_metadata(&stage) { + Ok(_) => { + drop(open_private(&stage)?); + fs::remove_file(stage).map_err(|_| "cannot clean interrupted history stage")?; + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => (), + Err(_) => return Err("cannot inspect history stage"), + } + // Persist creation of the private directory before acknowledging any data. + File::open( + store + .directory + .parent() + .ok_or("history directory has no parent")?, + ) + .and_then(|f| f.sync_all()) + .map_err(|_| "cannot flush history parent directory")?; + Ok(store) + } + + #[cfg(not(unix))] + pub(crate) fn open(_: &Path) -> Result { + Err("durable response history currently requires Unix private-file semantics") + } + + pub(crate) fn read(&self) -> Result>, &'static str> { + let path = self.directory.join(SNAPSHOT); + match fs::symlink_metadata(&path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(_) => return Err("cannot inspect history snapshot"), + Ok(_) => (), + } + let file = open_private(&path)?; + if file + .metadata() + .map_err(|_| "cannot inspect history snapshot")? + .len() + > MAX_SNAPSHOT_BYTES + { + return Err("history snapshot exceeds size limit"); + } + let mut bytes = Vec::new(); + file.take(MAX_SNAPSHOT_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|_| "cannot read history snapshot")?; + if bytes.len() as u64 > MAX_SNAPSHOT_BYTES { + return Err("history snapshot exceeds size limit"); + } + Ok(Some(bytes)) + } + + pub(crate) fn write(&self, bytes: &[u8]) -> Result<(), &'static str> { + if self.failed.load(Ordering::Acquire) { + return Err("history storage failed; restart after repairing storage"); + } + if bytes.len() as u64 > MAX_SNAPSHOT_BYTES { + return Err("history snapshot exceeds size limit"); + } + let result = self.publish(bytes); + if result.is_err() { + // A directory fsync failure after rename has an uncertain durability + // outcome. Never permit subsequent commits to overwrite that outcome. + self.failed.store(true, Ordering::Release); + } + result + } + + fn publish(&self, bytes: &[u8]) -> Result<(), &'static str> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let current = fs::symlink_metadata(&self.directory) + .map_err(|_| "history directory disappeared")?; + let original = self + .directory_handle + .metadata() + .map_err(|_| "cannot inspect history directory")?; + if current.dev() != original.dev() + || current.ino() != original.ino() + || !current.is_dir() + || current.mode() & 0o777 != 0o700 + || current.uid() != unsafe { libc::geteuid() } + { + return Err("history directory identity or private permissions changed"); + } + } + let path = self.directory.join(SNAPSHOT); + if fs::symlink_metadata(&path).is_ok() { + drop(open_private(&path)?); + } + let stage = self.directory.join(STAGE); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + } + let mut file = options + .open(&stage) + .map_err(|_| "cannot stage response history snapshot")?; + let result = (|| { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(fs::Permissions::from_mode(0o600)) + .map_err(|_| "cannot set private history snapshot permissions")?; + private_file(&file)?; + } + file.write_all(bytes) + .and_then(|_| file.sync_all()) + .map_err(|_| "cannot flush response history snapshot")?; + fs::rename(&stage, &path).map_err(|_| "cannot publish response history snapshot")?; + self.directory_handle + .sync_all() + .map_err(|_| "history commit durability uncertain; restart and inspect storage")?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_file(stage); + } + result + } +} + +#[cfg(unix)] +fn private_file(file: &File) -> Result<(), &'static str> { + use std::os::unix::fs::MetadataExt; + let meta = file.metadata().map_err(|_| "cannot inspect history file")?; + if !meta.is_file() + || meta.uid() != unsafe { libc::geteuid() } + || meta.mode() & 0o777 != 0o600 + || meta.nlink() != 1 + { + return Err( + "history files must be private owned regular files with mode 0600 and one link", + ); + } + Ok(()) +} + +fn open_private(path: &Path) -> Result { + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let file = options + .open(path) + .map_err(|_| "cannot open private history file")?; + #[cfg(unix)] + private_file(&file)?; + Ok(file) +} diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index a9b01ed1..70e41e3b 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -12,6 +12,7 @@ pub mod engine_probe; pub mod ggml_bridge; pub mod gguf; pub mod gguf_f32_stream; +mod history_store; pub mod iq3_s; mod iq3s_grid; pub mod kar; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index f2292a4a..9c01725d 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -781,6 +781,11 @@ fn print_tensor_index(path: &Path, hash: bool) -> Result<(), Box) -> Result<(), Box> { let mut config = Config::load_with_path(config_path)?; + let history_dir = config.response_history_dir.clone(); + let response_history = tokio::task::spawn_blocking(move || { + strata_control::responses::ResponseHistory::open(history_dir.as_deref()) + }) + .await??; config.check_host().await?; let _embedded = match config.worker.as_mut() { Some(worker) => { @@ -796,6 +801,7 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box) -> Result { "generation_timeout_s": config.worker.as_ref().and_then(|worker| worker.generation_timeout.map(|duration| duration.as_secs())), "model": config.model, "authentication_enabled": config.api_key.is_some(), + "response_history": if config.response_history_dir.is_some() { "durable_unchecked" } else { "memory" }, "engine": engine, "tokenizer_validated": config.tokenizer_dir.is_some() && !tokenizer_pending, "native_model_configured":config.native_model.is_some(), diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 5405aa93..3a528599 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -38,13 +38,16 @@ static NEXT_RESPONSE_ID: AtomicU64 = AtomicU64::new(0); const MAX_STORED_RESPONSES: usize = 64; const MAX_HISTORY_BYTES: usize = 128 * 1024 * 1024; -#[derive(Default)] +#[derive(Clone, Default)] pub struct ResponseHistory { - entries: HashMap, + entries: HashMap>, order: VecDeque, bytes: usize, + store: Option>, } +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] struct StoredResponse { model: String, transcript: Vec, @@ -54,6 +57,101 @@ struct StoredResponse { } impl ResponseHistory { + /// Call before worker acquisition/start. Payloads are never included in errors. + pub fn open(directory: Option<&std::path::Path>) -> Result { + let Some(directory) = directory else { + return Ok(Self::default()); + }; + let store = Arc::new(crate::history_store::Store::open(directory)?); + let mut history = Self::default(); + if let Some(bytes) = store.read()? { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Snapshot { + schema: u32, + sha256: String, + entries: Vec, + } + let snapshot: Snapshot = + serde_json::from_slice(&bytes).map_err(|_| "invalid history snapshot")?; + if snapshot.schema != 1 || snapshot.entries.len() > MAX_STORED_RESPONSES { + return Err("unsupported history snapshot schema or entry count"); + } + use sha2::Digest; + let encoded = + serde_json::to_vec(&snapshot.entries).map_err(|_| "invalid history snapshot")?; + if hex::encode(sha2::Sha256::digest(&encoded)) != snapshot.sha256 { + return Err("history snapshot checksum mismatch"); + } + drop(encoded); + for entry in snapshot.entries { + let id = entry.response["id"] + .as_str() + .ok_or("invalid stored response ID")?; + if !id.starts_with("resp_") + || id.len() > 180 + || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') + || entry.model.is_empty() + || entry.model.len() > 180 + || entry.input_len > entry.transcript.len() + || entry.response["object"] != "response" + || !matches!( + entry.response["status"].as_str(), + Some("completed" | "incomplete") + ) + { + return Err("invalid stored response metadata"); + } + let input = Value::Array(entry.transcript[..entry.input_len].to_vec()); + if !input.as_array().unwrap().iter().all(Value::is_object) { + return Err("invalid stored response input"); + } + // Rebuild and compare, never trust persisted size or transcript bounds. + let count = history.entries.len(); + history.insert(id, &entry.model, &input, &entry.response)?; + let rebuilt = &history.entries[id]; + if history.entries.len() != count + 1 + || rebuilt.bytes != entry.bytes + || rebuilt.transcript != entry.transcript + { + return Err("inconsistent or oversized history snapshot"); + } + } + } + history.store = Some(store); + Ok(history) + } + + fn persist(&self) -> Result<(), &'static str> { + if let Some(store) = &self.store { + #[derive(Serialize)] + struct Snapshot<'a> { + schema: u32, + sha256: String, + entries: Vec<&'a StoredResponse>, + } + use sha2::Digest; + let entries: Vec<_> = self + .order + .iter() + .map(|id| self.entries[id].as_ref()) + .collect(); + let encoded = + serde_json::to_vec(&entries).map_err(|_| "cannot encode history snapshot")?; + let sha256 = hex::encode(sha2::Sha256::digest(&encoded)); + drop(encoded); + let snapshot = Snapshot { + schema: 1, + sha256, + entries, + }; + let bytes = + serde_json::to_vec(&snapshot).map_err(|_| "cannot encode history snapshot")?; + store.write(&bytes)?; + } + Ok(()) + } + fn get(&self, id: &str, model: &str) -> Option<&[Value]> { let response = self.entries.get(id)?; (response.model == model).then_some(response.transcript.as_slice()) @@ -66,7 +164,14 @@ impl ResponseHistory { input: &Value, response: &Value, ) -> Result<(), &'static str> { - self.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES) + if self.store.is_none() { + return self.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES); + } + let mut candidate = self.clone(); + candidate.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES)?; + candidate.persist()?; + *self = candidate; + Ok(()) } fn insert_with_limit( @@ -114,17 +219,27 @@ impl ResponseHistory { self.order.push_back(id.to_owned()); self.entries.insert( id.to_owned(), - StoredResponse { + Arc::new(StoredResponse { model: model.to_owned(), transcript, input_len, response: response.clone(), bytes, - }, + }), ); Ok(()) } + fn delete_committed(&mut self, id: &str) -> Result { + let mut candidate = self.clone(); + if !candidate.remove(id) { + return Ok(false); + } + candidate.persist()?; + *self = candidate; + Ok(true) + } + fn remove(&mut self, id: &str) -> bool { let Some(removed) = self.entries.remove(id) else { return false; @@ -135,6 +250,28 @@ impl ResponseHistory { } } +async fn store_response( + history: &Arc>, + id: &str, + model: &str, + input: &Value, + response: &Value, +) -> Result<(), &'static str> { + let mut guard = history.clone().write_owned().await; + if guard.store.is_none() { + return guard.insert(id, model, input, response); + } + let (id, model, input, response) = ( + id.to_owned(), + model.to_owned(), + input.clone(), + response.clone(), + ); + tokio::task::spawn_blocking(move || guard.insert(&id, &model, &input, &response)) + .await + .map_err(|_| "history storage task failed")? +} + fn resource_not_found() -> Response { api_error( StatusCode::NOT_FOUND, @@ -318,8 +455,21 @@ pub async fn delete( if let Some(error) = resource_query_error(query) { return error; } - if !state.response_history.write().await.remove(&id) { - return resource_not_found(); + let mut guard = state.response_history.clone().write_owned().await; + let target = id.clone(); + let result = tokio::task::spawn_blocking(move || guard.delete_committed(&target)).await; + match result { + Ok(Ok(true)) => (), + Ok(Ok(false)) => return resource_not_found(), + _ => { + return api_error( + StatusCode::INSUFFICIENT_STORAGE, + "server_error", + "response_storage_failed", + None, + "cannot commit response deletion; inspect storage and restart", + ); + } } Json(json!({"id":id,"object":"response.deleted","deleted":true})).into_response() } @@ -895,12 +1045,14 @@ pub async fn create( ) { Ok(trace) => { if request.store != Some(false) - && let Err(message) = state.response_history.write().await.insert( + && let Err(message) = store_response( + &state.response_history, &id, &request.model, &request.input, &trace.response, ) + .await { return api_error( StatusCode::INSUFFICIENT_STORAGE, @@ -1572,12 +1724,14 @@ fn stream_live_text( Ok(trace) => { if request.store != Some(false) && let Some(history) = &history - && let Err(error) = history.write().await.insert( + && let Err(error) = store_response( + history, &id, &request.model, &request.input, &trace.response, ) + .await { failure = Some(error.to_owned()); } @@ -1750,12 +1904,14 @@ fn stream_live_buffered( Ok(trace) => { if request.store != Some(false) && let Some(history) = &history - && let Err(error) = history.write().await.insert( + && let Err(error) = store_response( + history, &id, &request.model, &request.input, &trace.response, ) + .await { failure = Some(error.to_owned()); } @@ -2070,12 +2226,14 @@ fn stream_live_tools( Ok(trace) => { if request.store != Some(false) && let Some(history) = &history - && let Err(error) = history.write().await.insert( + && let Err(error) = store_response( + history, &id, &request.model, &request.input, &trace.response, ) + .await { failure = Some(error.to_owned()); } @@ -3231,6 +3389,97 @@ mod tests { } } + #[cfg(unix)] + #[test] + fn durable_history_roundtrip_delete_eviction_and_faults() { + use std::os::unix::fs::PermissionsExt; + let root = std::env::temp_dir().join(format!( + "strata-durable-{}-{}", + std::process::id(), + NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) + )); + let mut history = ResponseHistory::open(Some(&root)).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + let input = json!([{"role":"user","content":"exact"}, + {"type":"custom_tool_call","call_id":"call_x","namespace":"files","name":"run","input":"a\nb"}, + {"type":"custom_tool_call_output","call_id":"call_x","output":"done"}]); + for i in 0..65 { + let id = format!("resp_{i}"); + history.insert(&id, "model", &input, &json!({"id":id,"model":"model", + "object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":"A"}]})).unwrap(); + } + let before = history.entries["resp_64"].response.clone(); + assert!(history.delete_committed("resp_1").unwrap()); + drop(history); + let mut history = ResponseHistory::open(Some(&root)).unwrap(); + assert_eq!(history.entries.len(), 63); + assert!(history.get("resp_0", "model").is_none()); + assert!(history.get("resp_1", "model").is_none()); + assert!(history.get("resp_64", "other-model").is_none()); + assert_eq!(history.entries["resp_64"].response, before); + assert_eq!( + &history.entries["resp_64"].transcript[..3], + input.as_array().unwrap() + ); + let committed = std::fs::read(root.join("history-v1.json")).unwrap(); + // A non-file destination fails closed without mutating memory or committed bytes. + std::fs::create_dir(root.join("history-v1.pending")).unwrap(); + assert!(history.delete_committed("resp_64").is_err()); + assert!(history.get("resp_64", "model").is_some()); + assert_eq!( + std::fs::read(root.join("history-v1.json")).unwrap(), + committed + ); + std::fs::remove_dir(root.join("history-v1.pending")).unwrap(); + assert!(history.delete_committed("resp_64").is_err()); // failed store stays fenced + drop(history); + let snapshot = root.join("history-v1.json"); + for corruption in [b"{".to_vec(), b"{\"schema\":2,\"entries\":[]}".to_vec()] { + std::fs::write(&snapshot, &corruption).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + assert_eq!(std::fs::read(&snapshot).unwrap(), corruption); + } + std::fs::write(&snapshot, &committed).unwrap(); + let mut forged: Value = serde_json::from_slice(&committed).unwrap(); + forged["entries"][0]["input_len"] = json!(999999); + std::fs::write(&snapshot, serde_json::to_vec(&forged).unwrap()).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + std::fs::write(&snapshot, &committed).unwrap(); + std::fs::set_permissions(&snapshot, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + std::fs::set_permissions(&snapshot, std::fs::Permissions::from_mode(0o600)).unwrap(); + let history = ResponseHistory::open(Some(&root)).unwrap(); + assert_eq!(history.entries["resp_64"].response, before); + drop(history); + let link = root.with_extension("symlink"); + std::os::unix::fs::symlink(&root, &link).unwrap(); + assert!(ResponseHistory::open(Some(&link)).is_err()); + std::fs::remove_file(link).unwrap(); + let file = std::fs::OpenOptions::new() + .write(true) + .open(&snapshot) + .unwrap(); + file.set_len(crate::history_store::MAX_SNAPSHOT_BYTES + 1) + .unwrap(); + drop(file); + assert!(ResponseHistory::open(Some(&root)).is_err()); + std::fs::remove_file(&snapshot).unwrap(); + std::os::unix::fs::symlink("missing", &snapshot).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + std::fs::remove_file(&snapshot).unwrap(); + std::fs::write(&snapshot, &committed).unwrap(); + std::fs::set_permissions(&snapshot, std::fs::Permissions::from_mode(0o600)).unwrap(); + // Interrupted unpublished data is never replayed. + let stage = root.join("history-v1.pending"); + std::fs::write(&stage, "incomplete").unwrap(); + std::fs::set_permissions(&stage, std::fs::Permissions::from_mode(0o600)).unwrap(); + let history = ResponseHistory::open(Some(&root)).unwrap(); + assert!(!stage.exists()); + assert_eq!(history.entries["resp_64"].response, before); + drop(history); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn history_counts_response_and_transcript_and_reclaims_deleted_entries() { let mut history = ResponseHistory::default(); diff --git a/docs/api-contract.md b/docs/api-contract.md index 20a5e34f..bad61fb9 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -45,7 +45,47 @@ The offline trace builder accepts text fragments, function-call argument fragmen `control-plane/src/wire.rs` encodes the upstream `GEN` request line and parses the current `T`, `PP`, `DONE`, and `ERR` output lines. The supervisor accepts an internal token-ID generation command, checks its context budget, and sends it to a resident worker. It can return a buffered result or stream bounded token events. Dropping the SSE receiver cancels generation. Native Qwen prompt assembly matches pinned text-only and one representative tool golden case byte-for-byte. The live Qwen parser holds split call markers and rejects incomplete calls; it validates full argument objects before publishing function-call events. -Current request parsing supports `model`, string or array `input`, `stream`, `instructions`, `max_output_tokens`, `previous_response_id`, `parallel_tool_calls`, `reasoning`, `text`, named function `tools`, `tool_choice`, `temperature`, `top_p`, `truncation`, `metadata`, and `store`. Unknown fields are rejected. Terminal responses are stored by default; `store: false` disables this. `previous_response_id` replays a stored response with the new input, including function calls and matching results. The store is process-local and bounded to 64 responses or 128 MiB, whichever is reached first; old IDs become unavailable after eviction or restart. Multimodal input remains unsupported. The body limit is 16 MiB. +Current request parsing supports `model`, string or array `input`, `stream`, `instructions`, `max_output_tokens`, `previous_response_id`, `parallel_tool_calls`, `reasoning`, `text`, named function `tools`, `tool_choice`, `temperature`, `top_p`, `truncation`, `metadata`, and `store`. Unknown fields are rejected. Terminal responses are stored by default; `store: false` disables this. `previous_response_id` replays a stored response with the new input, including function calls and matching results. By default the store is process-local and bounded to 64 responses or 128 MiB, whichever is reached first; old IDs become unavailable after eviction or restart. Multimodal input remains unsupported. The body limit is 16 MiB. + +### Opt-in durable history (Unix preview) + +Set `response_history_dir` in the serve config or `STRATA_RESPONSE_HISTORY_DIR` +(environment wins) to an absolute dedicated directory whose parent already exists. +The service creates it with mode `0700`; an existing directory must be owned by +its user with exactly that mode. Snapshot and lock files must be owned regular +`0600` files with one link. Symlinks are refused. An OS lock permits only one +service to use the directory. `check-config` reports `durable_unchecked` without +opening, creating or locking it. `provision` also leaves history untouched. + +This explicitly persists **plaintext input, tool results, and terminal responses**; +use a private external volume, outside Git. It has the same single-operator API +key scope as memory history, with no encryption or tenant separation. Changing +API keys does not erase the store. `store: false` writes nothing. Omitting the +option retains memory-only behavior. Windows durable storage is not supported. + +Completed/incomplete responses, expanded continuation transcripts and input-item +IDs survive service restarts. DELETE and oldest-entry eviction are committed too. +The existing limits remain 64 responses and 128 MiB of serialized response plus +transcript data. A versioned snapshot is bounded to 129 MiB including metadata; +this is not a total resident-memory bound. Each mutation writes a full snapshot +on a blocking pool, flushes it, atomically renames it and flushes the directory +before acknowledging success. Budget space for the current and staged snapshots. +This feature is not a throughput optimization. + +Startup validates the store before asset preparation, worker or listener startup. +Invalid schema, SHA-256 checksum mismatch, corruption, insecure files, excess size or an occupied lock fail +startup without resetting history. An interrupted unpublished stage is discarded +under the lock; the committed snapshot is restored. Disk failures produce the +existing `response_storage_failed` JSON error or terminal SSE `response.failed`, +never a false successful commit. Earlier text deltas may already be visible. +A failed store fences further mutations until restart; existing in-memory GETs +remain available. Failure before rename preserves the previous snapshot. Failure +after rename while flushing the directory has an **uncertain outcome**: the +request was not acknowledged, but its record can be present after restart. +A disconnected client can likewise miss an already committed result. DELETE is +logical deletion, not secure erasure of filesystem blocks or backups. +No in-progress stream, worker state, KV state or automatic retry is restored. + Before switching the testing runtime, exercise all engine stop conditions and tool calls with the real tokenizer and model on Linux GPU, and compare sanitized real Codex replays against the upstream Python server. Native reasoning now has its own output items, streaming events and continuation path. Do not mark Gate A complete based on synthetic fixtures. @@ -65,12 +105,12 @@ and usage. `DELETE` on the same path returns entry's response and continuation transcript. These route shapes follow the official OpenAI [retrieve](https://developers.openai.com/api/reference/resources/responses/methods/retrieve) and [delete](https://developers.openai.com/api/reference/resources/responses/methods/delete) -references; the implementation supports a restricted process-local subset. +references; the implementation supports the bounded history subset described here. - Both routes share the optional bearer authentication policy. They remain available while draining or when the worker is unavailable; they do not invoke the model. There is still one operator credential, without tenant isolation. -- Unknown, deleted, evicted, restarted and `store:false` IDs return +- Unknown, deleted, evicted, memory-only restarted and `store:false` IDs return `404 response_not_found`. Repeated deletion also returns 404. Failed generations are not stored; these routes do not poll or cancel in-progress jobs. - Nonempty query strings return `400 unsupported_query`. Retrieval streaming, @@ -79,13 +119,14 @@ references; the implementation supports a restricted process-local subset. transcript data**. Both objects count toward the budget; this is not a process RSS cap. Oversized records fail storage before publishing a successful terminal response. Eviction removes both objects together; retrieval does not refresh - retention order. Nothing is written to disk. + retention order. Disk storage is disabled unless explicitly configured above. - Deletion prevents subsequent continuation using that ID. It does not erase copies already included in descendant responses or an in-flight request that obtained the transcript before deletion, and does not cancel generation. These routes require the newer preview; the preserved user trial is unchanged. -CPU verification: `python3 scripts/smoke-response-history.py /path/to/strata-next`. +CPU verification: `python3 scripts/smoke-response-history.py /path/to/strata-next`; +add `--durable` for actual process restart, corruption and disk-failure coverage. ### Input item listing @@ -105,10 +146,11 @@ client item IDs in this view so duplicate IDs cannot make pagination ambiguous. Tool `call_id`, name, namespace, arguments and custom input are unchanged. The transcript used to render subsequent model prompts is never modified. -The route shares the existing process-local retention, deletion and authentication +The route shares the configured history retention, deletion and authentication policy. It works during drain/worker outage without generating tokens. Missing, -`store:false`, deleted and evicted responses return 404; restart clears history. -This endpoint does not add durable history, payload logging or tenant isolation. +`store:false`, deleted and evicted responses return 404. Restart clears default +memory history; the opt-in durable store described above also preserves these +input pages. No payload logging or tenant isolation is added. CPU HTTP coverage includes both response modes, exact tool-payload replay, pagination, stable cursors, failure cases and no extra worker generation. diff --git a/scripts/smoke-response-history.py b/scripts/smoke-response-history.py index d88e40d8..bdfc14ee 100644 --- a/scripts/smoke-response-history.py +++ b/scripts/smoke-response-history.py @@ -15,6 +15,7 @@ import time def main(): binary = Path(sys.argv[1]).resolve() + durable = "--durable" in sys.argv[2:] spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) fixture = importlib.util.module_from_spec(spec) spec.loader.exec_module(fixture) @@ -45,6 +46,10 @@ done 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0'} + history_dir = root / 'private-history' + if durable: + env['STRATA_RESPONSE_HISTORY_DIR'] = str(history_dir) + def request(method, path, payload=None, auth=True): connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8) headers = {'Content-Type': 'application/json'} @@ -56,7 +61,7 @@ done data = response.read().decode() if response.getheader('Content-Type', '').startswith('text/event-stream'): events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')] - assert events[-1]['type'] in ('response.completed', 'response.incomplete'), events[-1] + assert events[-1]['type'] in ('response.completed', 'response.incomplete', 'response.failed'), events[-1] data = events[-1]['response'] else: data = json.loads(data) @@ -76,17 +81,40 @@ done return result with tempfile.TemporaryFile() as logs: - process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs) + def start(): + proc = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs) + try: + deadline = time.monotonic() + 10 + while True: + try: + if request('GET', '/ready')[0] == 200: + return proc + except OSError: + pass + assert proc.poll() is None and time.monotonic() < deadline + time.sleep(.02) + except BaseException: + proc.kill() + proc.wait(timeout=5) + raise + + def restart(): + nonlocal process + process.terminate() + assert process.wait(timeout=10) == 0 + process = start() + + if durable: + checked = subprocess.run([binary, 'check-config'], env=env, capture_output=True, timeout=5) + assert checked.returncode == 0 and json.loads(checked.stdout)['response_history'] == 'durable_unchecked' + assert not history_dir.exists() + process = start() try: - deadline = time.monotonic() + 10 - while True: - try: - if request('GET', '/ready')[0] == 200: - break - except OSError: - pass - assert process.poll() is None and time.monotonic() < deadline - time.sleep(.02) + if durable: + assert history_dir.stat().st_mode & 0o777 == 0o700 + duplicate = subprocess.run([binary, 'serve'], env=env, stdout=logs, stderr=logs, timeout=5) + assert duplicate.returncode != 0 + assert request('GET', '/ready')[0] == 200 tool = '\n\n\nprint(1)\n\n\n' function = '\n\n1\n\n' cases = [('A', {}, 'stop'), ('Think.\n\nA', {'reasoning': {'effort': 'low'}}, 'stop'), @@ -102,6 +130,8 @@ done for store in (False, True): result = generate(text, {**options, 'stream': stream, 'store': store}, finish) path = '/v1/responses/' + result['id'] + if durable: + restart() assert request('GET', path, auth=False)[0] == 401 assert request('DELETE', path, auth=False)[0] == 401 assert request('GET', path + '/input_items', auth=False)[0] == 401 @@ -121,9 +151,13 @@ done assert request('DELETE', path + '?unknown=1')[0] == 400 assert request('GET', path) == (200, result) assert request('DELETE', path) == (200, {'id': result['id'], 'object': 'response.deleted', 'deleted': True}) + if durable: + restart() assert request('GET', path)[0] == request('DELETE', path)[0] == 404 assert request('GET', path + '/input_items')[0] == 404 parent = generate('A') + if durable: + restart() child = generate('A', {'previous_response_id': parent['id']}) child_path = '/v1/responses/' + child['id'] + '/input_items' code, child_page = request('GET', child_path + '?order=asc') @@ -176,6 +210,8 @@ done {'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object', 'properties': {'x': {'type': 'integer'}}}}, {'type': 'custom', 'name': 'run'}]}] response = generate('A', {'input': history_input, 'tools': tools, 'stream': stream}) + if durable: + restart() path = '/v1/responses/' + response['id'] + '/input_items?order=asc' code, page = request('GET', path) assert code == 200 and len(page['data']) == 5, page @@ -183,6 +219,32 @@ done assert {k: v for k, v in projected.items() if k != 'id'} == original # Returned items remain usable for stateless continuation. assert generate('A', {'input': page['data'], 'tools': tools, 'stream': stream})['status'] == 'completed' + if durable: + snapshot = history_dir / 'history-v1.json' + assert snapshot.stat().st_mode & 0o777 == 0o600 + for stream in (False, True): + committed = snapshot.read_bytes() + stage = history_dir / 'history-v1.pending' + stage.mkdir() + code, error = request('POST', '/v1/responses', { + 'model': 'fixture', 'input': 'storage-fault', + 'reasoning': {'effort': 'none'}, 'stream': stream}) + if stream: + assert code == 200 and error['status'] == 'failed', error + assert request('GET', '/v1/responses/' + error['id'])[0] == 404 + else: + assert code == 507 and error['error']['code'] == 'response_storage_failed', error + assert snapshot.read_bytes() == committed + assert request('GET', '/v1/responses/' + child['id']) == (200, child) + assert request('DELETE', '/v1/responses/' + child['id'])[0] == 507 + stage.rmdir() + restart() + assert request('GET', '/v1/responses/' + child['id']) == (200, child) + # A hard control-plane kill restores the latest acknowledged commit. + process.kill() + process.wait(timeout=5) + process = start() + assert request('GET', '/v1/responses/' + child['id']) == (200, child) assert request('POST', '/admin/drain', {})[0] == 200 worker_pid = int((root / 'worker.pid').read_text()) os.kill(worker_pid, signal.SIGKILL) @@ -197,6 +259,22 @@ done assert request('GET', '/v1/responses/missing')[0] == 404 process.terminate() assert process.wait(timeout=10) == 0 + if durable: + # Corruption fails before any new worker spawn, retaining the file. + snapshot = history_dir / 'history-v1.json' + worker_identity = (root / 'worker.pid').read_bytes() + original = snapshot.read_bytes() + snapshot.write_bytes(b'{broken-private-fixture') + failed = subprocess.run([binary, 'serve'], env=env, capture_output=True, timeout=5) + assert failed.returncode != 0 + assert b'broken-private-fixture' not in failed.stderr + assert (root / 'worker.pid').read_bytes() == worker_identity + assert snapshot.read_bytes() == b'{broken-private-fixture' + snapshot.write_bytes(original) + process = start() + assert request('GET', '/v1/responses/' + child['id'])[0] == 404 + process.terminate() + assert process.wait(timeout=10) == 0 finally: if process.poll() is None: process.terminate() @@ -205,7 +283,7 @@ done except subprocess.TimeoutExpired: process.kill() process.wait() - print('Response resources: 28 original variants plus input-items pagination, exact tool replay, auth/deletion/outage and no extra generation passed') + print(('Durable restart/fault mode: ' if durable else '') + 'Response resources: 28 original variants plus input-items pagination, exact tool replay, auth/deletion/outage and no extra generation passed') if __name__ == '__main__':