From c6e8a3450924e693620694fd1778fb4ba1856366 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?=
Date: Thu, 8 Oct 2026 06:56:03 +0500
Subject: [PATCH] Make the update check survive damaged launcher state and an
unavailable database
A crash during a launcher write can leave .state/*.json zero-filled, which made
every launcher start (and so the update check) fail with "Something went wrong".
Zero-filled state files are now discarded before each launcher verb, the check
degrades to a warning when the database cannot be inspected, and database start
failures carry the launcher's own output.
Co-Authored-By: Claude Sonnet 5.5
---
...008-update-check-survives-damaged-state.md | 7 +++
crates/coa-core/src/backup.rs | 3 +-
crates/coa-core/src/driver.rs | 43 +++++++++++++++++++
crates/coa-core/src/update.rs | 15 ++++++-
src/i18n/locales/de.ts | 1 +
src/i18n/locales/en.ts | 1 +
src/i18n/locales/es.ts | 1 +
src/i18n/locales/fr.ts | 1 +
src/i18n/locales/ru.ts | 1 +
src/i18n/locales/zh.ts | 1 +
src/lib/api.ts | 2 +
src/lib/serverUpdateStatus.ts | 2 +-
src/screens/SettingsHome.tsx | 6 ++-
13 files changed, 80 insertions(+), 4 deletions(-)
create mode 100644 changelog.d/20261008-update-check-survives-damaged-state.md
diff --git a/changelog.d/20261008-update-check-survives-damaged-state.md b/changelog.d/20261008-update-check-survives-damaged-state.md
new file mode 100644
index 0000000..b01e708
--- /dev/null
+++ b/changelog.d/20261008-update-check-survives-damaged-state.md
@@ -0,0 +1,7 @@
+---
+area: manager
+type: fixed
+audience: admins
+title: Checking for updates no longer fails with "Something went wrong" after an interrupted start
+---
+A crash or power loss could leave a damaged status file that made every database start fail. The Manager now removes such files itself, still compares the files when the database is unavailable, and shows the real reason.
diff --git a/crates/coa-core/src/backup.rs b/crates/coa-core/src/backup.rs
index 8e21adb..c3094ea 100644
--- a/crates/coa-core/src/backup.rs
+++ b/crates/coa-core/src/backup.rs
@@ -163,7 +163,8 @@ pub fn with_database(root: &Path, f: impl FnOnce(&Db) -> Result) -> Result
if !mysql_was_up {
let out = driver::run(root, Verb::StartMysql)?;
if !out.ok {
- return Err(Error::Invalid(out.human.map(|h| h.title.to_string()).unwrap_or_else(|| "The database could not be started.".into())));
+ // Keep the launcher's own last lines: the title alone ("Something went wrong") hides the cause.
+ return Err(Error::Invalid(format!("The database could not be started. {}", driver::startup_failure(root, &out))));
}
}
let result = f(&db);
diff --git a/crates/coa-core/src/driver.rs b/crates/coa-core/src/driver.rs
index b3c8a1e..930ed7b 100644
--- a/crates/coa-core/src/driver.rs
+++ b/crates/coa-core/src/driver.rs
@@ -136,6 +136,7 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result Result = redacted.lines().rev().take(12).collect();
+ tracing::warn!(?verb, exit_code, output = %tail.into_iter().rev().collect::>().join("\n"), "driver: launcher verb failed");
+ }
if ok && verb == Verb::StartAll { crate::multiworld::start(&root)?; }
Ok(DriverOutcome { ok, exit_code, code, human: code.map(ErrorCode::human), output })
}
+/// The launcher keeps one JSON record per service in `.state`. A crash or power loss while it writes one can leave
+/// a file of the right length that holds only zero bytes (NTFS keeps the length but not the data), and the launcher
+/// then dies on every start with an unreadable record. Such a file carries no information, so remove it: the
+/// launcher treats a missing record as "not running". Only empty or all-zero `*.json` files are touched.
+pub(crate) fn discard_damaged_launcher_state(root: &Path) -> Vec {
+ let mut removed = Vec::new();
+ let Ok(entries) = std::fs::read_dir(root.join(".state")) else { return removed; };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.extension().is_none_or(|e| !e.eq_ignore_ascii_case("json")) || !path.is_file() { continue; }
+ let Ok(bytes) = std::fs::read(&path) else { continue; };
+ if bytes.iter().all(|b| *b == 0) && std::fs::remove_file(&path).is_ok() {
+ tracing::warn!(file = %path.display(), bytes = bytes.len(), "driver: removed a launcher state file damaged by an interrupted write");
+ removed.push(path);
+ }
+ }
+ removed
+}
+
const LAUNCH_SCRIPT: &str = "import runpy,sys;from pathlib import Path;script=sys.argv[1];sys.path.insert(0,str(Path(script).resolve().parent));sys.argv=sys.argv[1:];runpy.run_path(script,run_name='__main__')";
pub(crate) fn patch_launcher_imports(text: &str) -> Result {
@@ -251,6 +276,24 @@ mod tests {
assert_eq!(Verb::StartWorld.timeout(folder.path()), Duration::from_secs(420));
}
+ #[test]
+ fn zero_filled_launcher_state_is_discarded_and_valid_state_is_kept() {
+ let folder = tempfile::tempdir().unwrap();
+ let state = folder.path().join(".state");
+ std::fs::create_dir_all(&state).unwrap();
+ std::fs::write(state.join("mysql.json"), vec![0u8; 116]).unwrap();
+ std::fs::write(state.join("configuration.json"), Vec::::new()).unwrap();
+ std::fs::write(state.join("world.json"), "{\"pid\": 4}\n").unwrap();
+ std::fs::write(state.join("stop-relay"), Vec::::new()).unwrap();
+ std::fs::write(state.join("auth.json"), "{\"pid\": 0}").unwrap();
+ let mut removed: Vec<_> = discard_damaged_launcher_state(folder.path()).iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect();
+ removed.sort();
+ assert_eq!(removed, ["configuration.json", "mysql.json"]);
+ assert!(state.join("world.json").exists() && state.join("auth.json").exists() && state.join("stop-relay").exists());
+ assert!(discard_damaged_launcher_state(folder.path()).is_empty());
+ assert!(discard_damaged_launcher_state(&folder.path().join("missing")).is_empty());
+ }
+
#[test]
fn translates_known_launcher_messages() {
assert_eq!(translate("RuntimeError: Port 8085 is already used. Stop the other server"), ErrorCode::PortInUse);
diff --git a/crates/coa-core/src/update.rs b/crates/coa-core/src/update.rs
index a048010..7ff06ea 100644
--- a/crates/coa-core/src/update.rs
+++ b/crates/coa-core/src/update.rs
@@ -259,6 +259,10 @@ pub struct Preview {
pub migrations: usize,
pub pending_migrations: usize,
pub download_bytes: u64,
+ /// Why the database could not be inspected. The check still answers about the files; applying the update starts
+ /// the database itself and reports its own failure.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub database_check_error: Option,
}
/// Describe the update; a managed launcher may need a one-time authenticated payload check.
@@ -277,7 +281,15 @@ pub fn preview(root: &Path, meta: &InstallMeta, source: &Source, trusted_key: &s
item.reason = Some("already up to date with Manager integration".into());
}
}
- let pending_migrations = (RepackEnv { root, meta_dir: &meta_dir }).pending_migrations(&m)?;
+ // Counting pending SQL needs the database. If it cannot be started the files can still be compared, so report
+ // that instead of failing the whole check.
+ let (pending_migrations, database_check_error) = match (RepackEnv { root, meta_dir: &meta_dir }).pending_migrations(&m) {
+ Ok(count) => (count, None),
+ Err(error) => {
+ tracing::warn!(%error, "update check: the database could not be inspected");
+ (m.migrations.len(), Some(error.to_string()))
+ }
+ };
Ok(Preview {
from_version: meta.core.version.clone(),
to_version: m.version.clone(),
@@ -286,6 +298,7 @@ pub fn preview(root: &Path, meta: &InstallMeta, source: &Source, trusted_key: &s
migrations: m.migrations.len(),
pending_migrations,
download_bytes: m.archive.as_ref().map(|a| a.parts.iter().map(|p| p.size).sum()).unwrap_or(0),
+ database_check_error,
})
}
diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts
index c13b43a..7fc74bd 100644
--- a/src/i18n/locales/de.ts
+++ b/src/i18n/locales/de.ts
@@ -827,6 +827,7 @@ const de: Partial> = {
"set.searchAll": "Alle Einstellungen nach Name oder Beschreibung durchsuchen…",
"set.search": "Einstellungen durchsuchen…",
"upd.current": "Du bist auf dem neuesten Stand (Version {v}).",
+ "upd.dbUnchecked": "Die Datenbank konnte nicht geprüft werden, daher sind offene Datenbankänderungen unbekannt: {why}",
"client.job.checking": "Client wird geprüft…",
"client.job.updating": "Client wird aktualisiert",
"fr.lan.address": "Netzwerkadresse",
diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts
index 03db274..af81ef5 100644
--- a/src/i18n/locales/en.ts
+++ b/src/i18n/locales/en.ts
@@ -848,6 +848,7 @@ const en = {
"set.searchAll": "Search all settings by name or description…",
"set.search": "Search settings…",
"upd.current": "You are up to date (version {v}).",
+ "upd.dbUnchecked": "The database could not be checked, so pending database changes are unknown: {why}",
"client.job.checking": "Checking the client…",
"client.job.updating": "Updating the client",
"fr.lan.address": "Network address",
diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts
index 3bd4e70..4336f40 100644
--- a/src/i18n/locales/es.ts
+++ b/src/i18n/locales/es.ts
@@ -827,6 +827,7 @@ const es: Partial> = {
"set.searchAll": "Buscar en todos los ajustes por nombre o descripción…",
"set.search": "Buscar ajustes…",
"upd.current": "Estás al día (versión {v}).",
+ "upd.dbUnchecked": "No se pudo comprobar la base de datos, así que se desconocen los cambios pendientes: {why}",
"client.job.checking": "Comprobando el cliente…",
"client.job.updating": "Actualizando el cliente",
"fr.lan.address": "Dirección de red",
diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts
index beb10a4..83b52a2 100644
--- a/src/i18n/locales/fr.ts
+++ b/src/i18n/locales/fr.ts
@@ -827,6 +827,7 @@ const fr: Partial> = {
"set.searchAll": "Rechercher dans tous les réglages par nom ou description…",
"set.search": "Rechercher un réglage…",
"upd.current": "Vous êtes à jour (version {v}).",
+ "upd.dbUnchecked": "La base de données n'a pas pu être vérifiée ; les modifications en attente sont donc inconnues : {why}",
"client.job.checking": "Vérification du client…",
"client.job.updating": "Mise à jour du client",
"fr.lan.address": "Adresse réseau",
diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts
index 7d24c29..a6ae392 100644
--- a/src/i18n/locales/ru.ts
+++ b/src/i18n/locales/ru.ts
@@ -846,6 +846,7 @@ const ru: Partial> = {
"set.searchAll": "Поиск по всем настройкам: название или описание…",
"set.search": "Поиск по настройкам…",
"upd.current": "У вас последняя версия ({v}).",
+ "upd.dbUnchecked": "Не удалось проверить базу данных, поэтому неизвестно, нужны ли ей изменения: {why}",
"client.job.checking": "Проверка клиента…",
"client.job.updating": "Обновление клиента",
"fr.lan.address": "Сетевой адрес",
diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts
index fe83254..9b21111 100644
--- a/src/i18n/locales/zh.ts
+++ b/src/i18n/locales/zh.ts
@@ -827,6 +827,7 @@ const zh = {
"set.searchAll": "按名称或描述搜索全部设置…",
"set.search": "搜索设置…",
"upd.current": "当前已是最新版本 ({v})。",
+ "upd.dbUnchecked": "无法检查数据库,因此不清楚是否有待应用的数据库更改:{why}",
"client.job.checking": "正在检查游戏客户端…",
"client.job.updating": "正在更新游戏客户端",
"err.docker_unavailable.title": "Docker 不可用",
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 19f0539..5d2ddb4 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -285,6 +285,8 @@ export interface UpdatePreview {
migrations: number;
pending_migrations?: number;
download_bytes: number;
+ /** Set when the database could not be inspected; the file comparison is still valid. */
+ database_check_error?: string;
}
export interface UpdateTxn {
diff --git a/src/lib/serverUpdateStatus.ts b/src/lib/serverUpdateStatus.ts
index be84a75..dd5a76d 100644
--- a/src/lib/serverUpdateStatus.ts
+++ b/src/lib/serverUpdateStatus.ts
@@ -3,5 +3,5 @@ import type { UpdatePreview } from "./api";
export function isUpdateCurrent(preview: UpdatePreview): boolean {
return preview.from_version === preview.to_version
&& preview.items.every((item) => item.action === "skip")
- && (preview.pending_migrations ?? (preview.migrations === 0 ? 0 : undefined)) === 0;
+ && (preview.database_check_error !== undefined || (preview.pending_migrations ?? (preview.migrations === 0 ? 0 : undefined)) === 0);
}
diff --git a/src/screens/SettingsHome.tsx b/src/screens/SettingsHome.tsx
index 1f5574f..60ab99a 100644
--- a/src/screens/SettingsHome.tsx
+++ b/src/screens/SettingsHome.tsx
@@ -202,6 +202,10 @@ export function SettingsHome({ serverId }: { serverId: string }) {
)}
+ {preview?.database_check_error && (
+ {t("upd.dbUnchecked", { why: preview.database_check_error })}
+ )}
+
{preview && isUpdateCurrent(preview) && (
{t("upd.current", { v: preview.to_version })}
@@ -214,7 +218,7 @@ export function SettingsHome({ serverId }: { serverId: string }) {
{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}
- {(preview.pending_migrations ?? preview.migrations) > 0
+ {!preview.database_check_error && (preview.pending_migrations ?? preview.migrations) > 0
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations })
: t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}