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

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