eprintln! panics when stderr is unwritable (consumer gone: EPIPE, disk full: ENOSPC). worker.rs logged before it marked the worker Failed, so with a dead log consumer the supervisor task died, readiness stayed true and later requests hit a dead worker (charter M1 / Gate A). All diagnostics now go through the non-panicking elog! macro. tests/log_failure_sse.rs starts the real strata-next binary with a scripted engine, drops the stderr consumer after startup and provokes a protocol failure inside a streamed Responses request: the stream must end with response.failed and readiness must drop (the control case with a live sink passes before and after; the dead-sink case failed before). A source scan keeps eprintln! out of the crate. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
180 lines
5.9 KiB
Rust
180 lines
5.9 KiB
Rust
//! Server-wide sampling defaults: the run config's `sampling` block and the Chat settings every
|
|
//! client shares (`POST /settings`), kept next to the config between starts. Port of the
|
|
//! settings half of `serve/server.py` `Service` (`set_shared`, `with_shared`, the default merge in
|
|
//! `run`). The pure rules live in `leleka-serving-policy`.
|
|
|
|
use std::{
|
|
fs,
|
|
path::{Path, PathBuf},
|
|
sync::RwLock,
|
|
};
|
|
|
|
use leleka_serving_policy::shared::{
|
|
ConfigSampling, MergedDefaults, SharedDefaults, clean_shared_defaults, merged_defaults,
|
|
};
|
|
use serde_json::Value;
|
|
|
|
#[derive(Default)]
|
|
pub struct Settings {
|
|
config: ConfigSampling,
|
|
shared: RwLock<SharedDefaults>,
|
|
shared_path: Option<PathBuf>,
|
|
/// The config's `reasoning_budget_tokens` (raw, validated at startup).
|
|
reasoning_budget_default: Option<Value>,
|
|
}
|
|
|
|
impl Settings {
|
|
pub fn new(config: ConfigSampling) -> Self {
|
|
Self {
|
|
config,
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
pub fn with_reasoning_budget(mut self, default: Option<Value>) -> Self {
|
|
self.reasoning_budget_default = default;
|
|
self
|
|
}
|
|
|
|
/// Persist shared settings in `path` and load what a previous run left there. A missing,
|
|
/// unreadable or invalid file means "clients use their own settings" (as in the Original).
|
|
pub fn with_shared_file(mut self, path: PathBuf) -> Self {
|
|
let loaded = fs::read_to_string(&path)
|
|
.ok()
|
|
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
|
|
.and_then(|value| clean_shared_defaults(&value).ok())
|
|
.unwrap_or_default();
|
|
*self.shared.write().expect("settings lock") = loaded;
|
|
self.shared_path = Some(path);
|
|
self
|
|
}
|
|
|
|
pub fn shared(&self) -> SharedDefaults {
|
|
self.shared.read().expect("settings lock").clone()
|
|
}
|
|
|
|
pub fn config(&self) -> &ConfigSampling {
|
|
&self.config
|
|
}
|
|
|
|
pub fn reasoning_budget_default(&self) -> Option<&Value> {
|
|
self.reasoning_budget_default.as_ref()
|
|
}
|
|
|
|
/// `{**config sampling, **shared}`.
|
|
pub fn merged(&self) -> MergedDefaults {
|
|
merged_defaults(&self.config, &self.shared())
|
|
}
|
|
|
|
/// `POST /settings`: validate, replace and persist. `Err` is the 400 message.
|
|
pub fn set_shared(&self, defaults: &Value) -> Result<SharedDefaults, String> {
|
|
let cleaned = clean_shared_defaults(defaults)?;
|
|
*self.shared.write().expect("settings lock") = cleaned.clone();
|
|
if let Some(path) = &self.shared_path
|
|
&& let Err(error) = persist(path, &cleaned)
|
|
{
|
|
crate::elog!("could not save the shared settings: {error}");
|
|
}
|
|
Ok(cleaned)
|
|
}
|
|
}
|
|
|
|
fn persist(path: &Path, shared: &SharedDefaults) -> std::io::Result<()> {
|
|
if shared.is_empty() {
|
|
match fs::remove_file(path) {
|
|
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
|
|
_ => Ok(()),
|
|
}
|
|
} else {
|
|
// Written next to the destination and renamed, so a crash never leaves half a file.
|
|
let temporary = path.with_extension("tmp");
|
|
fs::write(&temporary, serde_json::to_string_pretty(&shared.to_json())?)?;
|
|
fs::rename(&temporary, path)
|
|
}
|
|
}
|
|
|
|
/// The shared-settings file the Original keeps next to its config: `<config minus extension>.shared-settings.json`.
|
|
pub fn default_shared_path(config: &Path) -> PathBuf {
|
|
let mut name = config.with_extension("").into_os_string();
|
|
name.push(".shared-settings.json");
|
|
PathBuf::from(name)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
|
|
fn temp(name: &str) -> PathBuf {
|
|
let dir =
|
|
std::env::temp_dir().join(format!("strata-settings-{}-{name}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&dir);
|
|
fs::create_dir_all(&dir).unwrap();
|
|
dir
|
|
}
|
|
|
|
#[test]
|
|
fn shared_settings_persist_across_starts_and_empty_removes_the_file() {
|
|
let dir = temp("persist");
|
|
let path = dir.join("strata.shared-settings.json");
|
|
let first = Settings::default().with_shared_file(path.clone());
|
|
assert!(first.shared().is_empty());
|
|
first
|
|
.set_shared(&json!({"temperature": 0.5, "max_tokens": 128}))
|
|
.unwrap();
|
|
assert!(path.exists());
|
|
let second = Settings::default().with_shared_file(path.clone());
|
|
assert_eq!(second.shared().temperature, Some(0.5));
|
|
assert_eq!(second.shared().max_tokens, Some(128));
|
|
second.set_shared(&json!({})).unwrap();
|
|
assert!(!path.exists());
|
|
assert!(
|
|
Settings::default()
|
|
.with_shared_file(path)
|
|
.shared()
|
|
.is_empty()
|
|
);
|
|
let _ = fs::remove_dir_all(dir);
|
|
}
|
|
|
|
#[test]
|
|
fn a_corrupt_file_means_no_shared_settings() {
|
|
let dir = temp("corrupt");
|
|
let path = dir.join("s.json");
|
|
fs::write(&path, "{not json").unwrap();
|
|
assert!(
|
|
Settings::default()
|
|
.with_shared_file(path.clone())
|
|
.shared()
|
|
.is_empty()
|
|
);
|
|
fs::write(&path, r#"{"temperature": 9}"#).unwrap();
|
|
assert!(
|
|
Settings::default()
|
|
.with_shared_file(path)
|
|
.shared()
|
|
.is_empty()
|
|
);
|
|
let _ = fs::remove_dir_all(dir);
|
|
}
|
|
|
|
#[test]
|
|
fn a_rejected_update_keeps_the_previous_settings() {
|
|
let settings = Settings::default();
|
|
settings.set_shared(&json!({"top_k": 10})).unwrap();
|
|
assert_eq!(
|
|
settings.set_shared(&json!({"top_k": 100})).unwrap_err(),
|
|
"top_k: an integer 1..64"
|
|
);
|
|
assert_eq!(settings.shared().top_k, Some(10));
|
|
}
|
|
|
|
#[test]
|
|
fn default_path_sits_next_to_the_config() {
|
|
assert_eq!(
|
|
default_shared_path(Path::new("/etc/strata/run.json")),
|
|
PathBuf::from("/etc/strata/run.shared-settings.json")
|
|
);
|
|
}
|
|
}
|