fix(app): the game placement reads the card again and stage retries start over with each new wish

- the game stage reads the card again: other programs as at the last normal placement made with
  no game running, and a reserve of at least what grew since (the game and programs opened after
  that reading); with a game already running at the start (game detection now looks once before
  the LLM starts) it counts what the card holds now and leaves only the room for other programs,
  so it no longer pauses for counting the game twice
- the retry count starts over whenever another stage is wanted, also when the game ends with the
  normal stage already running, so the next game tries again
- the wait before the next try counts from when the failed switch and its way back are over
- the worker client keeps, sends and readies a connection under one lock (llm, then state), so an
  LLM state set while a worker connects is not lost
- a game watch dropped by a start that fails part way stops its thread

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-14 10:45:00 +09:00
parent aa6d950af6
commit 4a81b88d41
6 changed files with 243 additions and 33 deletions

View File

@@ -119,7 +119,9 @@ async fn start_browser(data_dir: &Path, settings: &crate::settings::Settings) ->
/// before the brain can. A failure stops what already started.
pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services, Box<dyn std::error::Error + Send + Sync>> {
let settings = load_settings(&data_dir.join("config").join("settings.json"))?;
let game_settings = settings.game.clone();
// Game detection first: a game already running is not taken for other programs' memory.
let game = Arc::new(crate::game::GameWatch::start(settings.game.clone()));
llm.game_at_start(game.on());
let perf_settings = settings.clone();
// The stored token (the setup wizard keeps it encrypted, admin.spec.md), else the environment.
let secrets = crate::secrets::Secrets::new(&data_dir.join("config").join("secrets.dat"));
@@ -201,7 +203,6 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
return Err(after_stop(&llm, &browser, e.to_string()).await.into());
}
crate::info_log!("app", "services started");
let game = Arc::new(crate::game::GameWatch::start(game_settings));
let on = { let g = game.clone(); Arc::new(move || g.on()) };
let perf = std::sync::Mutex::new(Some(tokio::spawn(perf_loop(perf_settings, llm.clone(), Arc::new(worker.clone()), on, RETRY_AFTER))));
Ok(Services { core, events, worker, worker_process, missed, llm, browser, game, perf })
@@ -264,10 +265,16 @@ async fn perf_loop(settings: crate::settings::Settings, llm: Arc<Llm>, brain: Ar
// The stage that runs (a game stage that had to pause counts as the game stage, so it is not
// tried again while the game runs).
let mut actual = Stage::Normal;
let mut last_want = Stage::Normal;
loop {
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
let now = std::time::Instant::now();
let want = perf.target(game(), now);
// Another stage wanted (also back to the one that runs): earlier failures no longer count.
if want != last_want {
retry.succeeded();
last_want = want;
}
if want == actual || !retry.allowed(want, now) {
continue;
}
@@ -283,9 +290,8 @@ async fn perf_loop(settings: crate::settings::Settings, llm: Arc<Llm>, brain: Ar
ended
}
Err(e) => {
retry.failed(want, now);
crate::error_log!("perf", "the LLM did not start in the {want:?} stage: {e}; going back to {actual:?}");
match llm.switch(&settings, actual, brain.stt_on_card()).await {
let back = match llm.switch(&settings, actual, brain.stt_on_card()).await {
Ok(ended) => ended,
Err(e) => {
crate::error_log!("perf", "the LLM did not come back in the {actual:?} stage either: {e}");
@@ -293,7 +299,10 @@ async fn perf_loop(settings: crate::settings::Settings, llm: Arc<Llm>, brain: Ar
actual = Stage::Paused;
Stage::Paused
}
}
};
// The wait counts from when that is over, not from when the switch began.
retry.failed(want, std::time::Instant::now());
back
}
};
brain.llm_state(if ended == Stage::Paused { "paused" } else { "ready" });
@@ -394,6 +403,80 @@ mod perf_tests {
task.abort();
}
/// A Strata that cannot start at the game's context (taking `fail_secs` to fail).
#[cfg(unix)]
fn strata_failing_in_games(l: &crate::install::Layout, fail_secs: f64) -> std::path::PathBuf {
let log = l.strata_home().join("x.engine.log");
crate::strata::tests::fake_strata(l, &format!(
"case \"$*\" in *'--context 16384'*) sleep {fail_secs}; echo 'out of memory' >&2; exit 4;; esac; rm -f '{}'; echo 'strata-q36: (1.10 GiB staging) on 16 CPU threads' >> '{}'; echo 'Strata is serving.'",
l.data.join("gone").display(), log.display()))
}
#[cfg(unix)]
#[tokio::test]
async fn a_new_game_tries_the_game_stage_again_after_three_failures_with_the_last_one() {
let l = layout("perf-loop-new-game");
let port = server_after_launch(&l, "list").await;
let llm = Arc::new(Llm::with_exe(l.clone(), strata_failing_in_games(&l, 0.0)).with_gpu(card(&l, "GPU-test", 0)));
let s = crate::settings::parse_settings(&serde_json::json!({"llm": {"port": port}, "game": {"revertSeconds": 0}})).unwrap();
llm.start(&s).await.unwrap();
let brain = Arc::new(FakeBrain::default());
let game = Arc::new(AtomicBool::new(true));
let g = game.clone();
let task = tokio::spawn(perf_loop(s, llm.clone(), brain.clone(), Arc::new(move || g.load(Ordering::SeqCst)), Duration::from_millis(200)));
let switchings = |b: &FakeBrain| b.0.lock().unwrap().iter().filter(|m| m.starts_with("switching")).count();
tokio::time::sleep(Duration::from_secs(6)).await;
assert_eq!(switchings(&brain), 3, "three tries");
// The game ends (the normal stage runs already) and a new one starts: tried again.
game.store(false, Ordering::SeqCst);
tokio::time::sleep(Duration::from_secs(1)).await;
game.store(true, Ordering::SeqCst);
tokio::time::sleep(Duration::from_secs(2)).await;
assert!(switchings(&brain) > 3, "{:?}", brain.0.lock().unwrap());
task.abort();
}
#[cfg(unix)]
#[tokio::test]
async fn the_wait_before_the_next_try_counts_from_when_the_failed_switch_is_over() {
// The failing start takes 1.5 s, longer than the 1 s wait: the next try still waits 1 s
// after the normal stage came back.
let l = layout("perf-loop-wait");
let port = server_after_launch(&l, "list").await;
let llm = Arc::new(Llm::with_exe(l.clone(), strata_failing_in_games(&l, 1.5)).with_gpu(card(&l, "GPU-test", 0)));
let s = crate::settings::parse_settings(&serde_json::json!({"llm": {"port": port}})).unwrap();
llm.start(&s).await.unwrap();
let brain = Arc::new(TimedBrain::default());
let task = tokio::spawn(perf_loop(s, llm.clone(), brain.clone(), Arc::new(|| true), Duration::from_secs(1)));
tokio::time::sleep(Duration::from_secs(7)).await;
task.abort();
let got = brain.0.lock().unwrap().clone();
let at = |what: &str, n: usize| got.iter().filter(|(m, _)| m.starts_with(what)).nth(n).map(|(_, t)| *t).expect(what);
let gap = at("switching", 1).duration_since(at("ready", 0));
assert!(gap >= Duration::from_secs(1), "the next try came {gap:?} after the normal stage was back");
}
#[derive(Default)]
struct TimedBrain(Mutex<Vec<(String, std::time::Instant)>>);
#[async_trait::async_trait]
impl LlmBrain for TimedBrain {
fn llm_switching(&self, _notice: Option<&str>) -> u64 {
self.0.lock().unwrap().push(("switching".into(), std::time::Instant::now()));
1
}
fn llm_state(&self, state: &str) -> bool {
self.0.lock().unwrap().push((state.into(), std::time::Instant::now()));
true
}
async fn wait_llm_idle(&self, _id: u64, _t: Duration) -> bool {
true
}
fn stt_on_card(&self) -> bool {
false
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_game_stage_that_fails_to_start_goes_back_and_is_tried_three_times() {