fix(battlenet): a download that stops moving ends with Retry, and a killed update comes back as an update (#2602)

* fix(battlenet): a Battle.net download that stops moving ends as retryable, and a killed update comes back as an update

A job reply without a state or byte counts no longer counts as a started
download, and an Agent job that reports no change for ten minutes is
stopped with its Agent and fails with a Retry instead of waiting forever.
Updates remember their game folder in the saved queue, so one restored
after the app was closed runs agent-update on that folder instead of a
fresh install.

* fix(battlenet): a stalled job stops only the Agent it started

A game or Battle.net client running in the prefix keeps running when a
stalled Agent job is ended, and the progress test keeps the job alive
across polls with a controlled clock.

* fix(battlenet): only real progress holds off the stall timeout

The download rate and time estimate can change while no bytes move, so
the stall timer now resets only on byte counts, progress, state, phase,
pause or error.

* test(battlenet): bound the stalled-rate fake child's polls
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-14 10:58:42 -05:00
1 parent 84b7295f11
commit d8b3c66b95
38 files changed
+218 -6

No files matched your search

@@ -88,6 +88,8 @@ COUNTRY = re.compile(r"[A-Z]{3}")
REGION = re.compile(r"[A-Z]{2}")
REPORT = "BNET"
ETA_LIMIT = 30 * 86400
STALL = 600
MOVING = ("download_current", "download_total", "progress", "playable_progress", "state", "phase", "paused", "error")
DONE_STATE = 1004
REPORTED = ("progress", "playable_progress", "download_rate", "download_remaining", "estimated_time_in_sec", "state",
"playable", "paused", "download_complete", "installed", "error")
@@ -118,6 +120,12 @@ function field(text, name) {
return m ? m[1] : "";
}
function job(text) {
if (/"error"\s*:\s*[1-9]/.test(text)) return false;
var bare = text.replace(/"extended_status"\s*:\s*\{[^}]*\}/, "");
return /"state"\s*:\s*\d+/.test(bare) || /"download_current"\s*:/.test(bare);
}
function install() {
// Blizzard's China repository moved to cn.patch.battlenet.com.cn; cn.patch.battle.net only redirects away from it.
var patch = zone == "cn" ? "cn.patch.battlenet.com.cn" : zone + ".patch.battle.net";
@@ -140,7 +148,7 @@ function watch(path) {
if (/"error"\s*:\s*[1-9]/.test(s)) break;
var state = /"state"\s*:\s*(\d+)/.exec(s.replace(/"extended_status"\s*:\s*\{[^}]*\}/, "")), complete = /"download_complete"\s*:\s*true/.test(s);
state = state ? +state[1] : 0;
if (state == 1000 || state == 1003 || !complete) started = true;
if (state == 1000 || state == 1003 || job(s) && !complete) started = true;
if (started && (state == 1004 || complete && /"playable"\s*:\s*true/.test(s))) break;
if (!started && state == 1004 && i >= 20) break;
if (!started && i >= 180) {
@@ -1376,7 +1384,7 @@ def summary(status):
return out
def agent_job(root, action, uid, product="", folder="", locale="enUS", country="USA", region="US", poll=None, wait=None):
def agent_job(root, action, uid, product="", folder="", locale="enUS", country="USA", region="US", poll=None, wait=None, stall=None):
pfx = os.path.join(prefix(root), "pfx")
if not installed(root) or agent_exe(root) is None:
emit("ERROR", "client")
@@ -1432,6 +1440,7 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
os.replace(output, output + ".1")
except OSError:
pass
before = {pid for pid, _ in wine_processes(pfx)}
with open(output, "ab") as log:
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env)
@@ -1439,6 +1448,9 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
emit("ERROR", "stopped gamescope: %s" % error)
return 1
seen = None
mark = None
moved = time.monotonic()
stalled = False
while True:
done = child.poll() is not None
status = read_status(base + ".json")
@@ -1447,12 +1459,27 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
if brief != seen:
emit("PROGRESS", json.dumps(brief, sort_keys=True))
seen = brief
signature = tuple(brief.get(key) for key in MOVING)
if signature != mark:
mark = signature
moved = time.monotonic()
if done:
break
if action != "uninstall" and time.monotonic() - moved > (STALL if stall is None else stall):
say("the %s of %s made no progress for %d s; stopping it" % (action, uid, STALL if stall is None else stall))
stalled = True
child.kill()
child.wait()
break
time.sleep(POLL if poll is None else poll)
leftovers = wine_processes(pfx)
if leftovers and idle(leftovers):
stop(leftovers)
elif stalled:
stop([(pid, argv) for pid, argv in leftovers if pid not in before and program(argv) == AGENT])
if stalled:
emit("ERROR", "stalled")
return 6
answer = read_status(base + ".game")
game = answer or {}
status = read_status(base + ".json") or {}
+132
View File
@@ -1441,6 +1441,138 @@ class AgentJobTest(Harness):
self.assertEqual(BNET["agent_job"](self.root, "update", "gryphon", poll=0), 1)
self.assertEqual(self.lines[-1][0], "ERROR")
def test_a_job_that_stops_moving_is_ended_as_stalled_and_its_agent_stopped(self):
self.install()
self.files = {".json": json.dumps({"state": 1003, "paused": True, "download_current": [10, 0, 0], "download_total": [99, 0, 0]})}
killed = []
stopped = []
class Hung:
returncode = None
def __init__(self, cmd, **kwargs):
base = cmd[-1][2:].replace("\\", "/")
with open(base + ".json", "wb") as f:
f.write(self_files[".json"].encode("utf-16"))
def poll(self):
return None
def kill(self):
killed.append(True)
def wait(self):
return -9
self_files = self.files
with mock.patch.object(BNET["subprocess"], "Popen", Hung), \
mock.patch.dict(BNET, {"wine_processes": lambda pfx: [(5, ["agent.exe"])], "stop": lambda p: stopped.append(p)}):
code = BNET["agent_job"](self.root, "install", "s1", "s1", str(self.tmp / "S1"), "enUS", "USA", "US", poll=0, stall=0.05)
self.assertEqual(code, 6)
self.assertEqual(killed, [True])
self.assertEqual(stopped, [[(5, ["agent.exe"])]])
self.assertEqual(self.lines[-1], ("ERROR", "stalled"))
def test_a_stalled_job_leaves_a_game_or_client_in_the_prefix_running(self):
self.install()
self.files = {".json": json.dumps({"state": 1003, "download_current": [10, 0, 0], "download_total": [99, 0, 0]})}
stopped = []
calls = []
class Hung:
returncode = None
def __init__(self, cmd, **kwargs):
calls.append(True)
def poll(self):
return None
def kill(self):
pass
def wait(self):
return -9
def processes(pfx):
if not calls:
return [(3, ["agent.exe"])]
return [(3, ["agent.exe"]), (5, ["Agent.exe"]), (6, ["wineserver"]), (7, ["Wow.exe"])]
with mock.patch.object(BNET["subprocess"], "Popen", Hung), \
mock.patch.dict(BNET, {"wine_processes": processes, "stop": lambda p: stopped.append(p)}):
code = BNET["agent_job"](self.root, "install", "s1", "s1", str(self.tmp / "S1"), "enUS", "USA", "US", poll=0, stall=0.05)
self.assertEqual(code, 6)
self.assertEqual(stopped, [[(5, ["Agent.exe"])]])
def test_only_a_changing_rate_or_estimate_does_not_hold_off_the_stall(self):
self.install()
clock = [0.0]
class Spinning:
returncode = None
def __init__(self, cmd, **kwargs):
self.base = cmd[-1][2:].replace("\\", "/")
self.polls = 0
def poll(self):
self.polls += 1
if self.polls > 10:
raise AssertionError("the stall timeout never ended the job")
clock[0] += 10
with open(self.base + ".json", "wb") as f:
f.write(json.dumps({"state": 1003, "download_current": [4, 0, 0], "download_total": [9, 0, 0],
"download_rate": self.polls, "estimated_time_in_sec": self.polls}).encode("utf-16"))
return None
def kill(self):
pass
def wait(self):
return -9
fake = mock.Mock(monotonic=lambda: clock[0], sleep=lambda s: None)
with mock.patch.object(BNET["subprocess"], "Popen", Spinning), mock.patch.dict(BNET, {"time": fake, "stop": lambda p: None}):
code = BNET["agent_job"](self.root, "update", "gryphon", poll=0, stall=25)
self.assertEqual(code, 6)
self.assertEqual(self.lines[-1], ("ERROR", "stalled"))
def test_a_moving_job_is_not_ended_as_stalled(self):
self.install()
done = json.dumps({"installed": True, "playable": True, "install_dir": "Z:/g", "local_version": "2"})
clock = [0.0]
class Moving:
returncode = 0
def __init__(self, cmd, **kwargs):
self.base = cmd[-1][2:].replace("\\", "/")
self.polls = 0
def poll(self):
self.polls += 1
clock[0] += 10
with open(self.base + ".json", "wb") as f:
f.write(json.dumps({"state": 1003, "download_current": [self.polls, 0, 0], "download_total": [9, 0, 0]}).encode("utf-16"))
if self.polls < 6:
return None
with open(self.base + ".game", "wb") as f:
f.write(done.encode("utf-16"))
return 0
fake = mock.Mock(monotonic=lambda: clock[0], sleep=lambda s: None)
with mock.patch.object(BNET["subprocess"], "Popen", Moving), mock.patch.dict(BNET, {"time": fake}):
code = BNET["agent_job"](self.root, "update", "gryphon", poll=0, stall=15)
self.assertEqual(code, 0)
self.assertNotIn(("ERROR", "stalled"), self.lines)
def test_only_a_real_job_reply_counts_as_started(self):
script = BNET["AGENT_SCRIPT"]
self.assertIn("if (state == 1000 || state == 1003 || job(s) && !complete) started = true;", script)
self.assertIn('return /"state"\\s*:\\s*\\d+/.test(bare) || /"download_current"\\s*:/.test(bare);', script)
self.assertIn('if (/"error"\\s*:\\s*[1-9]/.test(text)) return false;', script)
def test_the_driver_only_stops_once_the_agent_has_really_run(self):
script = BNET["AGENT_SCRIPT"]
self.assertIn("if (started && (state == 1004 || complete && /\"playable\"\\s*:\\s*true/.test(s))) break;", script)