fix(app): settle the start state before answering and report failed stops

service_start now moves the controller to starting before it returns
(Controller::start_in_background), so a stop right after it cancels the
start and a second start is refused instead of the start running late.
service_restart stops, then starts the same way.

Stopping Strata now confirms the server is gone: `launch --stop` is ended
after 2 minutes with everything it started, then the port must stop
listing a model. A server still answering makes the LLM failed with the
reason, and Services::stop / Running::stop return it, so the controller
shows failed instead of stopped (also for a cancelled start that could
not clear the server). A stop command that fails while nothing answers
counts as stopped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-12 17:51:11 +09:00
parent 5c510bb602
commit 41026a1eff
5 changed files with 295 additions and 74 deletions

View File

@@ -126,6 +126,9 @@ pub struct Llm {
status: Mutex<LlmStatus>,
active: Mutex<Option<Arc<Ctx>>>,
cancel: Arc<AtomicBool>,
/// The port the managed server was started on (to confirm it is gone after a stop).
port: Mutex<u16>,
stop_timeout: Duration,
}
/// How long the model may take to answer after `strata launch` returned (it loads in about 15 s
@@ -144,7 +147,14 @@ impl Llm {
pub fn with_exe(layout: Layout, exe: std::path::PathBuf) -> Self {
Self { layout, exe, status: Mutex::new(LlmStatus { state: LlmState::Off, managed: false, percent: None, note: None }),
active: Mutex::new(None), cancel: Arc::new(AtomicBool::new(false)) }
active: Mutex::new(None), cancel: Arc::new(AtomicBool::new(false)), port: Mutex::new(0),
stop_timeout: Duration::from_secs(120) }
}
/// How long `strata launch --stop` may take before it is ended and the stop reported as failed.
pub fn with_stop_timeout(mut self, t: Duration) -> Self {
self.stop_timeout = t;
self
}
pub fn status(&self) -> LlmStatus {
@@ -198,6 +208,7 @@ impl Llm {
}
let ctx = Arc::new(Ctx::standalone(self.layout.clone(), "llm", self.cancel.clone()));
*self.active.lock().unwrap() = Some(ctx.clone());
*self.port.lock().unwrap() = settings.llm.port;
let args = launch_args(&self.layout, settings);
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
let home = self.layout.strata_home();
@@ -208,11 +219,15 @@ impl Llm {
Err(e) => Err(e),
};
*self.active.lock().unwrap() = None;
if ready.is_err() {
// Nothing half-started stays on the graphics card.
self.stop_server().await;
match ready {
Ok(model) => Ok((base, model)),
// Nothing half-started stays on the graphics card; if it may have, say so.
Err(e) => match self.stop_server().await {
Ok(()) => Err(e),
Err(stop) if e == "cancelled" => Err(stop),
Err(stop) => Err(format!("{e} ({stop})")),
},
}
Ok((base, ready?))
}
/// Stop a start in progress (the download resumes on the next start).
@@ -220,30 +235,79 @@ impl Llm {
self.cancel.store(true, Ordering::SeqCst);
}
/// Stop the server this app started (nothing for `llm.url`).
pub async fn stop(&self) {
/// Stop the server this app started (nothing for `llm.url`). Off only once the server no longer
/// answers; otherwise `failed` with the reason, which is also returned.
pub async fn stop(&self) -> Result<(), String> {
let managed = self.status.lock().unwrap().managed;
if managed {
self.stop_server().await;
let result = if managed { self.stop_server().await } else { Ok(()) };
match &result {
Ok(()) => self.set(LlmState::Off, None),
Err(e) => {
crate::error_log!("llm", "{e}");
self.set(LlmState::Failed, Some(e.clone()));
}
}
self.set(LlmState::Off, None);
result
}
async fn stop_server(&self) {
/// `strata launch --stop`, then confirm the port no longer lists a model. A stop command that
/// fails while nothing answers (nothing was serving) counts as stopped.
async fn stop_server(&self) -> Result<(), String> {
if !self.exe.exists() {
return;
return Ok(());
}
let ctx = Ctx::standalone(self.layout.clone(), "llm", Arc::new(AtomicBool::new(false)));
// The timeout ends the command and everything it started, like an install cancel.
let cancel = Arc::new(AtomicBool::new(false));
let ctx = Ctx::standalone(self.layout.clone(), "llm", cancel.clone());
let home = self.layout.strata_home();
let stop = ctx.run_in(&self.exe, &["launch", "--stop"], Some(&home));
match tokio::time::timeout(Duration::from_secs(120), stop).await {
Ok(Ok(())) => { crate::info_log!("llm", "stopped"); }
Ok(Err(e)) => { crate::warn_log!("llm", "stop failed: {e}"); }
Err(_) => { crate::warn_log!("llm", "stop timed out"); }
let timer = {
let (cancel, t) = (cancel.clone(), self.stop_timeout);
tokio::spawn(async move {
tokio::time::sleep(t).await;
cancel.store(true, Ordering::SeqCst);
})
};
let ran = ctx.run_in(&self.exe, &["launch", "--stop"], Some(&home)).await;
timer.abort();
let ran = ran.map_err(|e| if e == "cancelled" { format!("{}초 안에 끝나지 않았습니다", self.stop_timeout.as_secs()) } else { e });
let port = *self.port.lock().unwrap();
let base = format!("http://127.0.0.1:{port}/v1");
let gone = port == 0 || wait_gone(&base, if ran.is_ok() { Duration::from_secs(15) } else { Duration::from_secs(2) }).await;
match (ran, gone) {
(Ok(()), true) => {
crate::info_log!("llm", "stopped");
Ok(())
}
(Err(e), true) => {
crate::warn_log!("llm", "stop command failed but nothing answers: {e}");
Ok(())
}
(Ok(()), false) => Err(format!("Strata를 껐지만 {base}가 아직 응답합니다")),
(Err(e), false) => Err(format!("Strata를 끄지 못했습니다: {e}")),
}
}
}
/// Whether `base` stops listing a model within `timeout` (a refused connection counts).
async fn wait_gone(base: &str, timeout: Duration) -> bool {
let Ok(client) = reqwest::Client::builder().timeout(Duration::from_secs(2)).build() else { return false };
let until = Instant::now() + timeout;
loop {
let listed = match client.get(format!("{base}/models")).send().await {
Ok(r) => r.text().await.ok().and_then(|t| serde_json::from_str::<Value>(&t).ok())
.is_some_and(|v| v["data"][0]["id"].is_string()),
Err(_) => false,
};
if !listed {
return true;
}
if Instant::now() >= until {
return false;
}
tokio::time::sleep(Duration::from_millis(300)).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -292,8 +356,13 @@ mod tests {
assert!(Path::new(v["db_path"].as_str().unwrap()).starts_with(&l.data));
}
/// A tiny `/v1/models` server answering with `id`, after `delay`.
/// A tiny `/v1/models` server answering with `id`, after `delay`; it lists nothing once the file
/// `gone` exists (a fake Strata's `--stop` makes it).
async fn models_server(id: &'static str, delay: Duration) -> u16 {
models_server_until(id, delay, None).await
}
async fn models_server_until(id: &'static str, delay: Duration, gone: Option<std::path::PathBuf>) -> u16 {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
@@ -302,7 +371,8 @@ mod tests {
while let Ok((mut s, _)) = listener.accept().await {
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf).await;
let body = if opened.elapsed() >= delay { format!(r#"{{"data":[{{"id":"{id}"}}]}}"#) } else { "{}".into() };
let stopped = gone.as_ref().is_some_and(|g| g.exists());
let body = if opened.elapsed() >= delay && !stopped { format!(r#"{{"data":[{{"id":"{id}"}}]}}"#) } else { "{}".into() };
let _ = s.write_all(format!("HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()).as_bytes()).await;
}
@@ -331,14 +401,20 @@ mod tests {
assert_eq!(llm.status().note.as_deref(), Some(e.as_str()));
}
/// A fake `strata`: `launch --stop` records itself; `launch ...` prints progress and returns.
/// A fake `strata`: `launch --stop` records itself and runs `stop_body` (by default it stops the
/// server: the file `gone` appears); `launch ...` runs `launch_body`.
#[cfg(unix)]
fn fake_strata(l: &Layout, launch_body: &str) -> std::path::PathBuf {
fake_strata_stop(l, launch_body, &format!("touch '{}'", l.data.join("gone").display()))
}
#[cfg(unix)]
fn fake_strata_stop(l: &Layout, launch_body: &str, stop_body: &str) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let exe = l.data.join("fake-strata");
std::fs::create_dir_all(l.strata_home()).unwrap();
let log = l.data.join("calls");
std::fs::write(&exe, format!("#!/bin/sh\necho \"$@\" >> '{}'\nif [ \"$2\" = --stop ]; then exit 0; fi\n{launch_body}\n",
std::fs::write(&exe, format!("#!/bin/sh\necho \"$@\" >> '{}'\nif [ \"$2\" = --stop ]; then {stop_body}; exit $?; fi\n{launch_body}\n",
log.display())).unwrap();
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
exe
@@ -347,8 +423,8 @@ mod tests {
#[cfg(unix)]
#[tokio::test]
async fn strata_starts_reports_its_download_waits_for_the_model_and_stops() {
let port = models_server("qwen-test", Duration::from_millis(300)).await;
let l = layout("llm5");
let port = models_server_until("qwen-test", Duration::from_millis(300), Some(l.data.join("gone"))).await;
let exe = fake_strata(&l, "echo 'Downloading: 12.5%'; sleep 1; echo 'Downloading: 100%'; echo 'Strata is serving.'");
let llm = Arc::new(Llm::with_exe(l.clone(), exe));
let s = parse_settings(&json!({"llm": {"port": port}})).unwrap();
@@ -369,7 +445,7 @@ mod tests {
let (base, model) = run.await.unwrap().unwrap();
assert_eq!((base, model.as_str()), (format!("http://127.0.0.1:{port}/v1"), "qwen-test"));
assert_eq!(llm.status().state, LlmState::Ready);
llm.stop().await;
llm.stop().await.unwrap();
let calls = std::fs::read_to_string(l.data.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().starts_with("launch --family"), "{calls}");
assert_eq!(calls.lines().last(), Some("launch --stop"));
@@ -404,4 +480,46 @@ mod tests {
assert!(e.contains("Not enough disk space"), "{e}");
assert_eq!(llm.status().state, LlmState::Failed);
}
#[cfg(unix)]
#[tokio::test]
async fn a_server_still_answering_after_a_failed_stop_is_reported_not_marked_off() {
let l = layout("llm8");
let port = models_server("qwen-test", Duration::ZERO).await;
let exe = fake_strata_stop(&l, "echo 'Strata is serving.'", "echo 'could not stop the engine' >&2; exit 3");
let llm = Llm::with_exe(l, exe);
llm.start(&parse_settings(&json!({"llm": {"port": port}})).unwrap()).await.unwrap();
let e = llm.stop().await.unwrap_err();
assert!(e.contains("could not stop the engine"), "{e}");
assert_eq!(llm.status().state, LlmState::Failed);
assert_eq!(llm.status().note.as_deref(), Some(e.as_str()));
}
#[cfg(unix)]
#[tokio::test]
async fn a_stop_that_hangs_is_given_up_on_and_reported() {
let l = layout("llm9");
let port = models_server("qwen-test", Duration::ZERO).await;
let exe = fake_strata_stop(&l, "echo 'Strata is serving.'", "sleep 30");
let llm = Llm::with_exe(l, exe).with_stop_timeout(Duration::from_millis(500));
llm.start(&parse_settings(&json!({"llm": {"port": port}})).unwrap()).await.unwrap();
let t = Instant::now();
let e = llm.stop().await.unwrap_err();
assert!(t.elapsed() < Duration::from_secs(10), "{:?}", t.elapsed());
assert!(e.contains("Strata"), "{e}");
assert_eq!(llm.status().state, LlmState::Failed);
}
#[cfg(unix)]
#[tokio::test]
async fn a_stop_command_that_fails_while_nothing_answers_counts_as_stopped() {
let l = layout("llm10");
let port = models_server_until("qwen-test", Duration::ZERO, Some(l.data.join("gone"))).await;
let stop = format!("touch '{}'; exit 1", l.data.join("gone").display());
let exe = fake_strata_stop(&l, "echo 'Strata is serving.'", &stop);
let llm = Llm::with_exe(l, exe);
llm.start(&parse_settings(&json!({"llm": {"port": port}})).unwrap()).await.unwrap();
llm.stop().await.unwrap();
assert_eq!(llm.status().state, LlmState::Off);
}
}