fix(recognize): verify manifest state instead of trusting steamcmd's exit code

Confirmed live against a real install: steamcmd's app_update can exit 0
without actually finishing -- it left installdir pointing at a stale,
unrelated folder name (from an earlier corrupted manifest state) and
InstalledDepots empty despite a "clean" exit. Relaunching the Steam
client then read that same stale field and wiped the correctly-downloaded
folder as orphaned while starting a fresh download into the wrong one --
real data loss, not a hypothetical.

- manifest_reflects_real_install() checks StateFlags/installdir/
  InstalledDepots directly instead of trusting the return code.
- ensure_installdir_correct() patches a stale installdir BEFORE running
  steamcmd, not just in the crash-fallback path after.
- run_steamcmd_validate() no longer captures stdout/stderr: steamcmd
  prompts for a password (and Steam Guard) on stdin, and prompt text
  written to a captured/buffered stdout never reached the terminal --
  the process looked hung with no visible request for input. Output
  now inherits the parent terminal, matching depotdownloader's own
  interactive login. The confirmed install-script segfault is detected
  via the SIGSEGV exit signal instead of grepping captured text.
- finish_manifest_manually() now also corrects installdir (previously
  only fixed by ensure_installdir_correct, not the crash-fallback path)
  and no longer lets a "0" buildid sentinel short-circuit past a real
  TargetBuildID via a bare `or` chain.
- cli.py gains --skip-steamcmd: go straight from depotdownloader's
  download to a direct manifest write, bypassing steamcmd's app_update
  entirely. It has now shown two separate failure modes (the segfault,
  and a silent no-op run) -- this is the same direct-write approach
  already confirmed to work standalone.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-07-25 15:51:20 +02:00
parent 72390acc2c
commit f9e91bba17
3 changed files with 259 additions and 31 deletions

View File

@ -55,13 +55,25 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument(
"--max-downloads", type=int, default=depotdl.DEFAULT_MAX_DOWNLOADS
)
parser.add_argument(
"--skip-steamcmd",
action="store_true",
help=(
"Finish the manifest directly from depotdownloader's own cached data "
"instead of running steamcmd's app_update. Steamcmd's install-script "
"step has shown two separate failure modes (a confirmed segfault, "
"and a silent no-op run); this is the same direct-write approach "
"already confirmed to work."
),
)
args = parser.parse_args(argv)
if args.appid is None and args.name is None:
parser.error("provide a game name to search for, or --appid directly")
_require_tool("depotdownloader", "See ~/depotdownloader.")
_require_tool("steamcmd", "Run: yay -S steamcmd")
if not args.skip_steamcmd:
_require_tool("steamcmd", "Run: yay -S steamcmd")
appid = _resolve_appid(args)
metadata = appinfo.get_metadata(appid)
@ -89,32 +101,43 @@ def main(argv: list[str] | None = None) -> int:
max_downloads=args.max_downloads,
)
print("Reconciling with steamcmd (validate)...")
library = next(lib for lib in libraries if lib.common == target.parent)
result = recognize.run_steamcmd_validate(metadata.appid, target, args.username)
recognize.ensure_installdir_correct(library, metadata.appid, target)
if result.completed:
print("steamcmd finished cleanly -- Steam should show Play.")
return 0
if not args.skip_steamcmd:
print("Reconciling with steamcmd (validate)...")
result = recognize.run_steamcmd_validate(metadata.appid, target, args.username)
if result.crashed_on_install_script:
print(
"steamcmd hit the known install-script crash; finishing the manifest manually..."
)
manifest_path = recognize.finish_manifest_manually(
library=library,
appid=metadata.appid,
install_dir=target,
now_unix=int(time.time()),
)
print(f"Wrote {manifest_path} -- launch Steam and confirm Play works.")
return 0
# Never trust steamcmd's exit code alone -- verify the manifest actually
# reflects a real install before believing it. A "clean" exit has
# produced a manifest steamcmd itself hadn't finished updating before.
if (
not result.crashed_on_install_script
and recognize.manifest_reflects_real_install(
library, metadata.appid, target
)
):
print("steamcmd finished cleanly -- Steam should show Play.")
return 0
print(
"steamcmd failed for an unrecognized reason -- output above, not auto-resolved."
if result.crashed_on_install_script:
print(
"steamcmd hit the known install-script crash; finishing the manifest manually..."
)
else:
print(
f"steamcmd exited {result.returncode} but the manifest doesn't reflect a "
"real install; finishing it manually..."
)
manifest_path = recognize.finish_manifest_manually(
library=library,
appid=metadata.appid,
install_dir=target,
now_unix=int(time.time()),
)
print(result.output[-4000:])
return 1
print(f"Wrote {manifest_path} -- launch Steam and confirm Play works.")
return 0
if __name__ == "__main__":

View File

@ -22,6 +22,7 @@ hand-edited fields on its own.
from __future__ import annotations
import re
import signal
import subprocess
from dataclasses import dataclass
from pathlib import Path
@ -29,8 +30,6 @@ from pathlib import Path
from steam_installer import vdf
from steam_installer.library import SteamLibrary
CRASH_SIGNATURE = "Standalone evaluator returned error code"
MANIFEST_CACHE_RE = re.compile(r"^(\d+)_(\d+)\.manifest$")
@ -42,14 +41,28 @@ class RecognizeError(Exception):
class ValidateResult:
completed: bool
crashed_on_install_script: bool
output: str
returncode: int
def run_steamcmd_validate(
appid: int, install_dir: Path, username: str
) -> ValidateResult:
"""Run steamcmd's app_update ... validate. `force_install_dir` must precede `+login`
(steamcmd itself warns about this ordering)."""
(steamcmd itself warns about this ordering).
Deliberately does NOT capture stdout/stderr: steamcmd prompts for a
password (and possibly a Steam Guard code) on stdin, and prompt text
written to a captured/buffered stdout never reaches the terminal --
the process looks hung with no visible request for input. Output is
left to inherit the parent's terminal instead, exactly like
depotdownloader's own interactive login.
The confirmed steamcmd install-script bug (see module docstring) kills
the process with SIGSEGV -- Python reports that as returncode -11 on
POSIX. Checking the signal directly is more reliable than grepping
captured text for a message string, and doesn't require capturing
output at all.
"""
cmd = [
"steamcmd",
"+force_install_dir",
@ -61,13 +74,64 @@ def run_steamcmd_validate(
"validate",
"+quit",
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)
output = result.stdout + result.stderr
crashed = CRASH_SIGNATURE in output
result = subprocess.run(cmd, timeout=3600)
crashed = result.returncode == -signal.SIGSEGV
return ValidateResult(
completed=result.returncode == 0,
crashed_on_install_script=crashed,
output=output,
returncode=result.returncode,
)
def ensure_installdir_correct(
library: SteamLibrary, appid: int, install_dir: Path
) -> None:
"""Patch a stale `installdir` field BEFORE running steamcmd, not just after.
Confirmed necessary: a prior, unrelated Steam GUI glitch left this app's
manifest pointing at a different folder name. steamcmd's own validate run
didn't correct it despite a clean exit, and relaunching the Steam client
read that same stale field and wiped the correctly-downloaded folder as
"orphaned" while starting a fresh download into the wrong one. Fixing it
proactively, before steamcmd ever runs, closes that window entirely.
Does nothing if no manifest exists yet -- steamcmd creates one itself in
that case, with the right installdir since we pass force_install_dir.
"""
manifest_path = library.steamapps / f"appmanifest_{appid}.acf"
if not manifest_path.is_file():
return
data = vdf.parse(manifest_path.read_text())
app_state = data.get("AppState", {})
if not isinstance(app_state, dict):
return
if app_state.get("installdir") == install_dir.name:
return
app_state["installdir"] = install_dir.name
manifest_path.write_text(vdf.dumps("AppState", app_state))
def manifest_reflects_real_install(
library: SteamLibrary, appid: int, install_dir: Path
) -> bool:
"""Don't trust steamcmd's exit code alone -- verify the manifest actually matches
reality. Confirmed necessary the hard way: steamcmd exited 0 while leaving
`installdir` pointed at a stale, unrelated folder name from an earlier corrupted
manifest state, `InstalledDepots` empty, and `StateFlags` still "update needed" --
a "clean" exit that hadn't actually recognized anything. Relaunching the Steam
client then treated the real, correctly-downloaded folder as orphaned and wiped
it while starting a fresh (slow, wrong-folder) download.
"""
manifest_path = library.steamapps / f"appmanifest_{appid}.acf"
if not manifest_path.is_file():
return False
data = vdf.parse(manifest_path.read_text())
app_state = data.get("AppState", {})
if not isinstance(app_state, dict):
return False
return (
app_state.get("StateFlags") == "4"
and app_state.get("installdir") == install_dir.name
and bool(app_state.get("InstalledDepots"))
)
@ -115,7 +179,12 @@ def finish_manifest_manually(
)
size_on_disk = sum(f.stat().st_size for f in install_dir.rglob("*") if f.is_file())
buildid = app_state.get("buildid") or app_state.get("TargetBuildID") or "0"
# "0" means "no real build installed yet" (steamcmd/Steam use it as a
# sentinel) -- a bare `or` treats that non-empty string as truthy and
# never falls through to TargetBuildID, leaving a stale/wrong buildid.
existing_buildid = app_state.get("buildid")
buildid = existing_buildid if existing_buildid and existing_buildid != "0" else None
buildid = buildid or app_state.get("TargetBuildID") or "0"
installed_depots = {
depot_id: {"manifest": manifest_id, "size": "0"}
@ -123,6 +192,7 @@ def finish_manifest_manually(
}
app_state["StateFlags"] = "4"
app_state["installdir"] = install_dir.name
app_state["LastUpdated"] = str(now_unix)
app_state["SizeOnDisk"] = str(size_on_disk)
app_state["StagingSize"] = "0"

View File

@ -7,7 +7,9 @@ from steam_installer.library import SteamLibrary
from steam_installer.recognize import (
RecognizeError,
discover_cached_depot_manifests,
ensure_installdir_correct,
finish_manifest_manually,
manifest_reflects_real_install,
)
@ -79,3 +81,136 @@ def test_finish_manifest_manually_sets_state_flags_and_depots(tmp_path):
assert app_state["SharedDepots"] == {"228989": "228980"}
assert "StagedDepots" not in app_state
assert manifest_path.with_suffix(".acf.bak").is_file()
def test_finish_manifest_manually_falls_back_to_target_buildid_when_zero(tmp_path):
"""buildid "0" is a sentinel for "no real build installed yet", not a real
value -- a naive `or` chain treats it as truthy and never falls through."""
library = SteamLibrary(tmp_path / "Steam")
library.steamapps.mkdir(parents=True)
data = {
"appid": "1771300",
"StateFlags": "1026",
"buildid": "0",
"TargetBuildID": "23914554",
}
(library.steamapps / "appmanifest_1771300.acf").write_text(
vdf.dumps("AppState", data)
)
install_dir = library.common / "Game"
cache_dir = install_dir / ".DepotDownloader"
cache_dir.mkdir(parents=True)
(cache_dir / "1771302_257127247679847518.manifest").write_bytes(b"x")
manifest_path = finish_manifest_manually(
library, 1771300, install_dir, now_unix=1000
)
app_state = vdf.parse(manifest_path.read_text())["AppState"]
assert app_state["buildid"] == "23914554"
def test_finish_manifest_manually_corrects_installdir(tmp_path):
"""The exact bug that caused real data loss: a stale installdir field
pointing at a different folder than where content was actually downloaded."""
library = SteamLibrary(tmp_path / "Steam")
_write_partial_manifest(library.steamapps, 1771300)
data = vdf.parse((library.steamapps / "appmanifest_1771300.acf").read_text())
data["AppState"]["installdir"] = "Some Stale Wrong Name"
(library.steamapps / "appmanifest_1771300.acf").write_text(
vdf.dumps("AppState", data["AppState"])
)
install_dir = library.common / "KingdomComeDeliverance2"
cache_dir = install_dir / ".DepotDownloader"
cache_dir.mkdir(parents=True)
(cache_dir / "1771302_257127247679847518.manifest").write_bytes(b"x")
manifest_path = finish_manifest_manually(
library, 1771300, install_dir, now_unix=1000
)
app_state = vdf.parse(manifest_path.read_text())["AppState"]
assert app_state["installdir"] == "KingdomComeDeliverance2"
def test_ensure_installdir_correct_patches_stale_field(tmp_path):
library = SteamLibrary(tmp_path / "Steam")
_write_partial_manifest(library.steamapps, 1771300)
data = vdf.parse((library.steamapps / "appmanifest_1771300.acf").read_text())
data["AppState"]["installdir"] = "Kingdom Come: Deliverance II"
(library.steamapps / "appmanifest_1771300.acf").write_text(
vdf.dumps("AppState", data["AppState"])
)
install_dir = library.common / "KingdomComeDeliverance2"
ensure_installdir_correct(library, 1771300, install_dir)
app_state = vdf.parse((library.steamapps / "appmanifest_1771300.acf").read_text())[
"AppState"
]
assert app_state["installdir"] == "KingdomComeDeliverance2"
def test_ensure_installdir_correct_noop_when_already_correct(tmp_path):
library = SteamLibrary(tmp_path / "Steam")
_write_partial_manifest(library.steamapps, 1771300)
manifest_path = library.steamapps / "appmanifest_1771300.acf"
data = vdf.parse(manifest_path.read_text())
data["AppState"]["installdir"] = "KingdomComeDeliverance2"
manifest_path.write_text(vdf.dumps("AppState", data["AppState"]))
before = manifest_path.read_text()
ensure_installdir_correct(
library, 1771300, library.common / "KingdomComeDeliverance2"
)
assert manifest_path.read_text() == before
def test_ensure_installdir_correct_noop_when_no_manifest(tmp_path):
library = SteamLibrary(tmp_path / "Steam")
library.steamapps.mkdir(parents=True)
# Should not raise, and should not create a manifest out of nothing.
ensure_installdir_correct(library, 1771300, library.common / "Game")
assert not (library.steamapps / "appmanifest_1771300.acf").exists()
def test_manifest_reflects_real_install_true_when_consistent(tmp_path):
library = SteamLibrary(tmp_path / "Steam")
library.steamapps.mkdir(parents=True)
data = {
"StateFlags": "4",
"installdir": "KingdomComeDeliverance2",
"InstalledDepots": {"1771302": {"manifest": "257127247679847518"}},
}
(library.steamapps / "appmanifest_1771300.acf").write_text(
vdf.dumps("AppState", data)
)
assert manifest_reflects_real_install(
library, 1771300, library.common / "KingdomComeDeliverance2"
)
def test_manifest_reflects_real_install_false_when_installdir_mismatches(tmp_path):
library = SteamLibrary(tmp_path / "Steam")
library.steamapps.mkdir(parents=True)
data = {
"StateFlags": "4",
"installdir": "Kingdom Come: Deliverance II",
"InstalledDepots": {"1771302": {"manifest": "257127247679847518"}},
}
(library.steamapps / "appmanifest_1771300.acf").write_text(
vdf.dumps("AppState", data)
)
assert not manifest_reflects_real_install(
library, 1771300, library.common / "KingdomComeDeliverance2"
)
def test_manifest_reflects_real_install_false_when_no_manifest(tmp_path):
library = SteamLibrary(tmp_path / "Steam")
library.steamapps.mkdir(parents=True)
assert not manifest_reflects_real_install(library, 1771300, library.common / "Game")