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

@@ -96,8 +96,12 @@ The dashboard's start and stop buttons, and the app binary itself, run the servi
starting; `restart` is stop then start. A start that fails leaves nothing running. A stop while
starting cancels the start (the LLM's model download or load stops and its server is cleared) and
ends in `stopped` without an error; if the start finished anyway, what came up is stopped again.
The screens' `service_start` and `service_restart` return at once and the start runs in the
background (the first start downloads the model); the dashboard shows how it goes. Starting reads the
The screens' `service_start` and `service_restart` return as soon as the state is `starting`
(restart stops first) and the start runs in the background (the first start downloads the model);
the dashboard shows how it goes, a stop right after the answer cancels the start and a second start
is refused. A stop that cannot confirm everything ended (the LLM's server still answers) ends in
`failed` with the reason, not `stopped`; a start (Strata's `--restart`) can follow. The same goes
for a cancelled start that could not clear the server. Starting reads the
settings and the stored token again, so saved changes take effect on the next start. Each start
gets a new dashboard fed by that run's events; `stop` ends the feeding (and waits for it) before
the dashboard is forgotten, so an event queued before the stop, or sent by an earlier run, never
@@ -182,8 +186,12 @@ start it first, so nothing answers before the brain can, and stop it last.
replaces a server left with other choices; the same choices are reused. `--parallel` is 1 (faster
on a 16 GB card, M0) and 2 when a chat channel answers every message, so its answers do not wait
behind voice answers. Pictures are off until something in v2 sends one. Stopping the services
runs `strata launch --stop`; so does a failed or cancelled start, so nothing half-started keeps
graphics memory. Not installed: the start fails and says to run the install.
runs `strata launch --stop` (ended after 2 minutes, with everything it started) and then checks
that the port no longer lists a model; so does a failed or cancelled start, so nothing
half-started keeps graphics memory. Stopped means nothing answers any more (a stop command that
fails while nothing answers counts as stopped); a server still answering makes the LLM `failed`
with the reason, and the stop or the start reports it. Not installed: the start fails and says to
run the install.
- **A server the app does not start**: with `llm.url` (an OpenAI-compatible `/v1` address, in the
settings file only) the app starts nothing; that server must list a model within 30 seconds.
- **Settings**: `llm.context` (default 32768 tokens per request, 4096-262144) and `llm.port`
@@ -256,7 +264,10 @@ service starter, a stop while starting (cancelled, or finished and stopped again
(launch arguments from the settings and inside the data folder, the second request slot for a chat
channel answering everything, the download percentage, the brain's settings file, a given server
used without Strata, Strata missing, a fake Strata that reports progress, returns, serves and is
stopped, is cancelled during its download and cleared, or fails with its last line; the brain's
stopped, is cancelled during its download and cleared, or fails with its last line, a stop that
fails or hangs while the server still answers (failed, not off) and one that fails while nothing
answers (off); a background start that is starting at once, so a stop right after it cancels it
and a second start is refused, also through the admin commands; a failed stop reported as failed; the brain's
config loaded without writing to the home folder, `tests/test_config_db_path.py`); the dashboard from made-up events (captions replaced and cleared, latency stages
and medians, an answer matched to its asker's final, missed requests without text); the admin
commands (first run: folder then token, the token never returned whole, the wizard resumed at its

View File

@@ -195,17 +195,14 @@ impl AdminApi {
}
// Starting can take long (the LLM's first start downloads the model), so it runs in the
// background and the dashboard shows how it goes; stop also cancels a start.
"service_start" | "service_restart" => {
"service_start" => self.controller()?.start_in_background().map(|_| json!({"ok": true})),
"service_restart" => {
let c = self.controller()?;
let restart = command == "service_restart";
let ok = if restart { c.state() == State::Running } else { matches!(c.state(), State::Stopped | State::Failed) };
if !ok {
return Err(format!("cannot {} while {:?}", if restart { "restart" } else { "start" }, c.state()).to_lowercase());
if c.state() != State::Running {
return Err(format!("cannot restart while {:?}", c.state()).to_lowercase());
}
tokio::spawn(async move {
let _ = if restart { c.restart().await } else { c.start().await };
});
Ok(json!({"ok": true}))
c.stop().await?;
c.start_in_background().map(|_| json!({"ok": true}))
}
"service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})),
"dashboard" => Ok(self.controller()?.snapshot().await),
@@ -308,4 +305,20 @@ mod tests {
assert_eq!(d["state"], json!("stopped"));
assert!(a.call("service_stop", json!({})).await.is_err());
}
#[tokio::test]
async fn a_start_is_starting_when_it_answers_so_a_stop_right_after_it_is_not_refused() {
let (a, base) = api("api4");
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
a.call("service_start", json!({})).await.unwrap();
assert!(a.call("service_start", json!({})).await.unwrap_err().contains("starting"));
a.call("service_stop", json!({})).await.unwrap();
let mut state = Value::Null;
for _ in 0..200 {
state = a.call("dashboard", json!({})).await.unwrap()["state"].clone();
if state == json!("stopped") { break; }
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert_eq!(state, json!("stopped"), "the start was cancelled, not started late");
}
}

View File

@@ -26,7 +26,8 @@ pub enum State {
/// The running services as the controller sees them.
#[async_trait]
pub trait Running: Send + Sync + 'static {
async fn stop(&self);
/// Stop everything; an error means something may still run (the LLM's server still answers).
async fn stop(&self) -> Result<(), String>;
/// Worker, voice channel members and missed requests, for the snapshot.
fn status(&self, now: Instant) -> Value;
}
@@ -76,15 +77,33 @@ impl Controller {
/// Start from stopped or failed; a failed start leaves nothing running.
pub async fn start(&self) -> Result<(), String> {
{
let mut i = self.inner.lock().unwrap();
if !matches!(i.state, State::Stopped | State::Failed) {
return Err(format!("cannot start while {:?}", i.state).to_lowercase());
}
i.state = State::Starting;
i.error = None;
i.stop_asked = false;
self.begin_start()?;
self.run_start().await
}
/// The same in the background: the state is `starting` when this returns, so a stop right after
/// it cancels the start and a second start is refused.
pub fn start_in_background(self: &Arc<Self>) -> Result<(), String> {
self.begin_start()?;
let me = self.clone();
tokio::spawn(async move {
let _ = me.run_start().await;
});
Ok(())
}
fn begin_start(&self) -> Result<(), String> {
let mut i = self.inner.lock().unwrap();
if !matches!(i.state, State::Stopped | State::Failed) {
return Err(format!("cannot start while {:?}", i.state).to_lowercase());
}
i.state = State::Starting;
i.error = None;
i.stop_asked = false;
Ok(())
}
async fn run_start(&self) -> Result<(), String> {
crate::info_log!("app", "starting the services");
let started = self.host.start().await;
// The stop flag is read under the same lock that makes the state Running, so a stop asked
@@ -120,12 +139,23 @@ impl Controller {
};
}
};
// Stopped while starting: whatever came up goes down again.
if let Ok((running, _)) = started {
running.stop().await;
// Stopped while starting: whatever came up goes down again. If that fails, or the cancelled
// start could not clear the LLM's server, the state says so.
let left = match started {
Ok((running, _)) => running.stop().await.err(),
Err(e) if self.host.llm()["state"] == "failed" => Some(e),
Err(_) => None,
};
let mut i = self.inner.lock().unwrap();
if let Some(e) = left {
let e = crate::logs::redact(&e, &self.host.secrets());
crate::error_log!("app", "start cancelled, but: {e}");
i.state = State::Failed;
i.error = Some(e);
} else {
i.state = State::Stopped;
crate::info_log!("app", "start cancelled");
}
self.inner.lock().unwrap().state = State::Stopped;
crate::info_log!("app", "start cancelled");
Err("cancelled".into())
}
@@ -145,9 +175,10 @@ impl Controller {
i.state = State::Stopping;
i.running.take()
};
if let Some(r) = running {
r.stop().await;
}
let stopped = match running {
Some(r) => r.stop().await,
None => Ok(()),
};
// Stop feeding before forgetting: nothing still queued may reach the screen afterwards.
let feeder = self.inner.lock().unwrap().feeder.take();
if let Some(f) = feeder {
@@ -156,10 +187,24 @@ impl Controller {
}
let mut i = self.inner.lock().unwrap();
i.dashboard = Arc::default();
i.state = State::Stopped;
drop(i);
crate::info_log!("app", "services stopped");
Ok(())
match stopped {
Ok(()) => {
i.state = State::Stopped;
drop(i);
crate::info_log!("app", "services stopped");
Ok(())
}
// Something may still run: shown as failed with the reason; a start (Strata's
// `--restart`) or another stop attempt can follow.
Err(e) => {
let e = crate::logs::redact(&e, &self.host.secrets());
i.state = State::Failed;
i.error = Some(e.clone());
drop(i);
crate::error_log!("app", "the services did not stop cleanly: {e}");
Err(e)
}
}
}
pub async fn restart(&self) -> Result<(), String> {
@@ -248,8 +293,8 @@ impl Host for ServicesHost {
#[async_trait]
impl Running for crate::services::Services {
async fn stop(&self) {
crate::services::Services::stop(self).await;
async fn stop(&self) -> Result<(), String> {
crate::services::Services::stop(self).await
}
fn status(&self, now: Instant) -> Value {
@@ -274,13 +319,15 @@ mod tests {
struct Counts {
starts: AtomicU32,
stops: AtomicU32,
stop_fails: std::sync::atomic::AtomicBool,
}
struct FakeRunning(Arc<Counts>);
#[async_trait]
impl Running for FakeRunning {
async fn stop(&self) {
async fn stop(&self) -> Result<(), String> {
self.0.stops.fetch_add(1, Ordering::SeqCst);
if self.0.stop_fails.load(Ordering::SeqCst) { Err("Strata를 끄지 못했습니다: still answering".into()) } else { Ok(()) }
}
fn status(&self, _: Instant) -> Value {
json!({"worker": {"connected": true}, "voiceMembers": [{"id": "11", "name": "민수"}], "missed": []})
@@ -377,6 +424,36 @@ mod tests {
}
}
#[tokio::test]
async fn a_background_start_is_starting_at_once_so_an_immediate_stop_or_second_start_is_handled() {
let counts = Arc::new(Counts::default());
let c = Controller::new(SlowHost { counts: counts.clone(), honours_cancel: true, cancelled: Arc::default() });
c.start_in_background().unwrap();
assert_eq!(c.state(), State::Starting, "starting before anything else runs");
assert!(c.start_in_background().unwrap_err().contains("starting"), "no second start");
c.stop().await.unwrap();
for _ in 0..100 {
if c.state() == State::Stopped { break; }
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(c.state(), State::Stopped);
assert_eq!(counts.starts.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn a_stop_that_fails_is_reported_and_a_new_start_is_allowed() {
let (c, counts, _) = controller(0);
c.start().await.unwrap();
counts.stop_fails.store(true, Ordering::SeqCst);
let e = c.stop().await.unwrap_err();
assert!(e.contains("Strata"), "{e}");
let s = c.snapshot().await;
assert_eq!((s["state"].clone(), s["error"].clone()), (json!("failed"), json!(e)));
counts.stop_fails.store(false, Ordering::SeqCst);
c.start().await.unwrap();
assert_eq!(c.state(), State::Running);
}
#[tokio::test]
async fn start_and_stop_follow_the_state_rules() {
let (c, counts, _) = controller(0);

View File

@@ -25,11 +25,12 @@ pub struct Services {
}
impl Services {
pub async fn stop(&self) {
/// Stop everything; an error means the LLM's server may still run.
pub async fn stop(&self) -> Result<(), String> {
self.core.close().await;
self.worker.close();
self.worker_process.stop().await;
self.llm.stop().await;
self.llm.stop().await
}
}
@@ -48,10 +49,7 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
let (base_url, model) = llm.start(&settings).await?;
let brain_config = match crate::strata::write_brain_config(data_dir, &base_url, &model) {
Ok(f) => f,
Err(e) => {
llm.stop().await;
return Err(format!("could not write the brain settings: {e}").into());
}
Err(e) => return Err(after_llm_stop(&llm, format!("could not write the brain settings: {e}")).await.into()),
};
let w = &settings.voice_worker;
@@ -64,10 +62,7 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
wopts.env.insert("JARVIS_CONFIG_PATH".into(), brain_config.to_string_lossy().into_owned());
let worker_process = match WorkerProcess::new(wopts) {
Ok(p) => p,
Err(e) => {
llm.stop().await;
return Err(e.into());
}
Err(e) => return Err(after_llm_stop(&llm, e.to_string()).await.into()),
};
let mut process_events = worker_process.subscribe();
worker_process.start();
@@ -101,9 +96,16 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
if let Err(e) = core.start().await {
worker.close();
worker_process.stop().await;
llm.stop().await;
return Err(Box::new(e));
return Err(after_llm_stop(&llm, e.to_string()).await.into());
}
crate::info_log!("app", "services started");
Ok(Services { core, events, worker, worker_process, missed, llm })
}
/// Stop the LLM after a failed start; the error also says if its server may still run.
async fn after_llm_stop(llm: &Llm, error: String) -> String {
match llm.stop().await {
Ok(()) => error,
Err(stop) => format!("{error} ({stop})"),
}
}

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);
}
}