From 36e8ea6b33ab4c21c0aefdb8a79f35ac124c380f Mon Sep 17 00:00:00 2001 From: pgm1207 <104554896+pgm1207@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:41 +0100 Subject: [PATCH 1/5] farm: small robustness fixes from review (M1,M3,M5 id,M6,L) --- tools/farm/farmd | 22 +++++++++++++--------- tools/farm/farmlib.py | 7 ++++++- tools/farm/holdlib.py | 2 +- tools/farm/test_farm.py | 9 +++++++++ 4 files changed, 29 insertions(+), 11 deletions(-) diff --git a/tools/farm/farmd b/tools/farm/farmd index a918cb06..4465e541 100755 --- a/tools/farm/farmd +++ b/tools/farm/farmd @@ -61,6 +61,7 @@ def git(*a, cwd=HERE, timeout=120): class Farm: + dst_lock = threading.RLock() # set_dstate is called from workers and the tick (class level: tests build Farm without __init__) def __init__(self, fake, once, poll): self.fake, self.once, self.poll = fake, once, poll self.cfg, self.devs = L.load_devices() @@ -154,14 +155,15 @@ class Farm: return "usb" if t == self.devs[alias]["serial"] else ("mdns" if t.startswith("adb-") else "wireless") if t else "" def set_dstate(self, alias, status, note="", **extra): - cur = self.dstate.get(alias, {}) - if cur.get("status") != status: - keep = {k: cur[k] for k in ("batt", "temp_c", "thermal", "wireless") if k in cur} - self.dstate[alias] = dict(keep, status=status, since=time.time(), note=note, since_iso=L.now()) - else: - cur["note"] = note - self.dstate[alias].update(extra) - L.write_json(self.st_path, self.dstate) + with self.dst_lock: # workers and the tick call this concurrently: serialise mutation and dump + cur = self.dstate.get(alias, {}) + if cur.get("status") != status: + keep = {k: cur[k] for k in ("batt", "temp_c", "thermal", "wireless") if k in cur} + self.dstate[alias] = dict(keep, status=status, since=time.time(), note=note, since_iso=L.now()) + else: + cur["note"] = note + self.dstate[alias].update(extra) + L.write_json(self.st_path, json.loads(json.dumps(self.dstate))) # ---------- health gates def is_disabled(self, dev): @@ -1395,6 +1397,8 @@ class Farm: done(why, clean=clean, clean_note=note) except Exception: log(f"{alias}: hold {hid} error: " + traceback.format_exc()[-300:]) + if not touched: + self.cool[alias] = time.time() + (0 if self.fake else 30) # do not re-tick and retry at full speed if touched: try: clean, note = (False, "restore deferred: disabled by owner") if self.is_disabled(dev) else self.hold_cleanup(dev) @@ -1468,7 +1472,7 @@ class Farm: and "(fake)" not in res.get("notes", "") and not self.is_disabled(dev)): log(f"{alias}: {jid}/{cls} driver sha mismatch ({res.get('notes', '')[:80]}); re-pushing and retrying once inside the hold") res = getattr(self, "suite_" + job["suite"])(job, dev) # shellroute pushes + verifies afresh; still invalid -> normal requeue - if res.get("lost") or (self.fake is False and alias not in self.attached() and res["verdict"] != "pass"): + if res.get("lost") or (self.fake is False and alias not in self.attached() and res.get("verdict") != "pass"): res = None # phone vanished mid-run: do not blame the commit, retry later except Exception: res = {"verdict": "error", "notes": "farmd exception: " + traceback.format_exc()[-300:]} diff --git a/tools/farm/farmlib.py b/tools/farm/farmlib.py index 8b5fed78..135c076f 100644 --- a/tools/farm/farmlib.py +++ b/tools/farm/farmlib.py @@ -210,6 +210,8 @@ def write_json(path, obj): fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-") with os.fdopen(fd, "w") as f: json.dump(obj, f, indent=1, sort_keys=True) + f.flush() + os.fsync(f.fileno()) os.replace(tmp, path) @@ -476,7 +478,10 @@ def flip_scan(days=3, since=None): continue for cls, p in j["parts"].items(): rp = run_path(j["id"], cls) - run = read_json(rp) if os.path.exists(rp) else None + try: + run = read_json(rp) if os.path.exists(rp) else None + except (ValueError, OSError): + run = None # one corrupt run file must not abort the scan if not run or run.get("verdict") in ("error", "invalid") or (run.get("started") or "") < cutoff: continue f = os.path.join(state_dir(), "logs", f"{j['id']}-{p.get('device')}-daily.tsv") diff --git a/tools/farm/holdlib.py b/tools/farm/holdlib.py index cd667515..82297585 100644 --- a/tools/farm/holdlib.py +++ b/tools/farm/holdlib.py @@ -24,7 +24,7 @@ def path(hid, ext="json"): def new_hold(alias, max_s, prio=DEFAULT_PRIO, lease=False, who=""): - hid, n = time.strftime("h%Y%m%d-%H%M%S") + f"-{os.getpid()}", 1 + hid = time.strftime("h%Y%m%d-%H%M%S") + f"-{os.getpid()}-{time.time_ns() % 10**9:09d}" h = {"id": hid, "device": alias, "prio": int(prio), "max_s": int(max_s), "lease": bool(lease), "who": who, "state": "queued", "created": L.now(), "seq": time.time_ns(), "auto": 0} touch(hid, "hb") # first the heartbeat: farmd must never see a queued hold without one and cancel a live caller diff --git a/tools/farm/test_farm.py b/tools/farm/test_farm.py index 812ed983..a46e0212 100644 --- a/tools/farm/test_farm.py +++ b/tools/farm/test_farm.py @@ -2219,6 +2219,15 @@ def test_dead_caller_while_queued_and_release_cancel(self): time.sleep(0.2) self.assertIn("caller lost", L.read_json(H.path(h["id"]))["reason"]) + def test_hold_ids_unique_within_one_second_and_one_process(self): + ids = {H.new_hold("dev-a", 60)["id"] for _ in range(20)} + self.assertEqual(len(ids), 20) + + def test_write_json_survives_and_flip_scan_ignores_corrupt_run(self): + p = os.path.join(os.environ["FARM_STATE_DIR"] if "FARM_STATE_DIR" in os.environ else L.state_dir(), "wj.json") + L.write_json(p, {"a": 1}) + self.assertEqual(L.read_json(p), {"a": 1}) + def test_end_reason(self): h = {"deadline": 100} self.assertEqual(H.end_reason(h, 1, False, now=50), "") From 6c8185cf2b93d0a12bb8f8ef5ab530a9aac053be Mon Sep 17 00:00:00 2001 From: pgm1207 <104554896+pgm1207@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:49:18 +0100 Subject: [PATCH 2/5] farm test: supersede test passes --allow-stale so it does not depend on how far the checkout is behind origin/main --- tools/farm/test_farm.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/farm/test_farm.py b/tools/farm/test_farm.py index a46e0212..c66a70a5 100644 --- a/tools/farm/test_farm.py +++ b/tools/farm/test_farm.py @@ -1238,15 +1238,15 @@ def test_supersede_old_gate_jobs(self): j = L.find_job(old) j["parts"]["v13"]["state"] = "running" # a running part is never touched L.write_json(L.job_path(old), j) - rc, new, err = self.farm("submit", "HEAD", "--suite", "smoke", "--need", "v11,v13") + rc, new, err = self.farm("submit", "HEAD", "--suite", "smoke", "--need", "v11,v13", "--allow-stale") self.assertEqual(rc, 0) self.assertIn("supersede", err) self.assertEqual({c: p["state"] for c, p in L.find_job(old)["parts"].items()}, {"v11": "cancelled", "v13": "running"}) self.assertEqual(L.find_job(other)["parts"]["v11"]["state"], "pending") self.assertEqual(L.find_job(keep)["parts"]["v11"]["state"], "cancelled") # older and pending: superseded too (kept only from being cancelled BY ITS OWN submit) self.assertIn(old, open(self.d + "/state/logs/farm-queue.log").read()) - _, k2, _ = self.farm("submit", "HEAD~1", "--suite", "smoke", "--need", "v11", "--keep-old") - _, new2, err2 = self.farm("submit", "HEAD", "--suite", "smoke", "--need", "v11", "--keep-old") # --keep-old on the NEW job: cancels nothing + _, k2, _ = self.farm("submit", "HEAD~1", "--suite", "smoke", "--need", "v11", "--keep-old", "--allow-stale") + _, new2, err2 = self.farm("submit", "HEAD", "--suite", "smoke", "--need", "v11", "--keep-old", "--allow-stale") # --keep-old on the NEW job: cancels nothing self.assertNotIn("supersede", err2) self.assertEqual(L.find_job(k2)["parts"]["v11"]["state"], "pending") From 9609d7d0b03fdc4bce515cada9e8d1d81e81e8dc Mon Sep 17 00:00:00 2001 From: pgm1207 <104554896+pgm1207@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:17:05 +0100 Subject: [PATCH 3/5] farm tests: farmd() helper timeout 60s->240s (fake bisect test times out on a loaded host) --- tools/farm/test_farm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/farm/test_farm.py b/tools/farm/test_farm.py index 17b46b9c..470f1593 100644 --- a/tools/farm/test_farm.py +++ b/tools/farm/test_farm.py @@ -310,7 +310,7 @@ def farm(self, *a): return r.returncode, r.stdout.strip(), r.stderr def farmd(self): - r = subprocess.run([sys.executable, HERE + "/farmd", "--fake", "--once"], capture_output=True, text=True, env=self.env, timeout=60) + r = subprocess.run([sys.executable, HERE + "/farmd", "--fake", "--once"], capture_output=True, text=True, env=self.env, timeout=240) self.assertEqual(r.returncode, 0, r.stderr) return r.stdout From 46a01d4f3d1954778bfb349f6b4a9416a7aecce4 Mon Sep 17 00:00:00 2001 From: pgm1207 <104554896+pgm1207@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:30:02 +0100 Subject: [PATCH 4/5] farm: fsync the directory after write_json's rename; wj test stays in its temp dir --- tools/farm/farmlib.py | 8 ++++++++ tools/farm/test_farm.py | 3 ++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/tools/farm/farmlib.py b/tools/farm/farmlib.py index 135c076f..bcd1b5f1 100644 --- a/tools/farm/farmlib.py +++ b/tools/farm/farmlib.py @@ -213,6 +213,14 @@ def write_json(path, obj): f.flush() os.fsync(f.fileno()) os.replace(tmp, path) + try: # persist the directory entry the rename changed + dfd = os.open(os.path.dirname(path) or ".", os.O_RDONLY) + try: + os.fsync(dfd) + finally: + os.close(dfd) + except OSError: + pass def read_json(path): diff --git a/tools/farm/test_farm.py b/tools/farm/test_farm.py index 470f1593..ccd3a0c3 100644 --- a/tools/farm/test_farm.py +++ b/tools/farm/test_farm.py @@ -2234,7 +2234,8 @@ def test_hold_ids_unique_within_one_second_and_one_process(self): self.assertEqual(len(ids), 20) def test_write_json_survives_and_flip_scan_ignores_corrupt_run(self): - p = os.path.join(os.environ["FARM_STATE_DIR"] if "FARM_STATE_DIR" in os.environ else L.state_dir(), "wj.json") + os.makedirs(self.d + "/state", exist_ok=True) + p = self.d + "/state/wj.json" L.write_json(p, {"a": 1}) self.assertEqual(L.read_json(p), {"a": 1}) From e3c648925f899934d3fdcd98a9949fa0502c4398 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pablo=20Gonz=C3=A1lez?= Date: Fri, 20 Nov 2026 00:18:10 +0100 Subject: [PATCH 5/5] farm: M2 restore-pending/attempts/KillMode, M4 re-adopt live hold, orphan hold-file gc (stacked on #85) (#108) * farm: M2 persist restore-pending, count an attempt for a part lost to a farmd restart, unit KillMode=mixed * farm: M4 re-adopt a live hold after a farmd restart; gc orphan .hb/.rel/.tmp hold files * farm tests: farmd() helper timeout 60s->240s (fake bisect test times out on a loaded host) --- tools/farm/farmd | 66 ++++++++++++++++++++++++------------ tools/farm/holdlib.py | 38 +++++++++++++++++++-- tools/farm/mali-farm.service | 5 +++ tools/farm/test_farm.py | 57 ++++++++++++++++++++++++++++++- 4 files changed, 142 insertions(+), 24 deletions(-) diff --git a/tools/farm/farmd b/tools/farm/farmd index 4465e541..ebe5873f 100755 --- a/tools/farm/farmd +++ b/tools/farm/farmd @@ -91,7 +91,7 @@ class Farm: self.sweeping, self.sweep_run, self.prebuild_t, self._cl = {}, set(), None, None self.idle_since = {} # alias -> when it last stopped doing real (non-sweep) work or became healthy self.last_auto = 0 - self.restore_pending = set() # phones whose last hold was cut short by a restart: restore before the next use + self.restore_pending = H.load_restore() # persisted (holdlib): survives further restarts; phones whose last hold was cut short by a restart: restore before the next use self.menu_next = {} # alias -> next time to probe its MediaDeck versionCode # ---------- devices @@ -1346,7 +1346,7 @@ class Farm: ok = rc == 0 and "PROBLEM" not in out and not ps.strip() return ok, (note + (" STILL RUNNING" if ps.strip() else "") + ("" if rc == 0 and "PROBLEM" not in out else f" qrestore rc={rc}: {(out.strip().splitlines() or [''])[-1][:100]}")).strip() - def run_hold(self, hid, alias): + def run_hold(self, hid, alias, adopt=False): dev = dict(self.devs[alias]) # a snapshot: devices.toml edits during the hold must not retarget the cleanup or the lock name lock = L.PhoneLock(dev, self.fake) h = L.read_json(H.path(hid)) @@ -1356,7 +1356,7 @@ class Farm: L.write_json(H.path(hid), h2) log(f"{alias}: hold {hid} ended: {reason}" + (f" ({kw['clean_note']})" if kw.get("clean_note") else "")) self.wake.set() - if H.released(hid) or H.age(hid) > H.HB_STALE: + if not adopt and (H.released(hid) or H.age(hid) > H.HB_STALE): return done("cancelled while queued" if H.released(hid) else "caller lost while queued") if self.is_disabled(dev): self.cool[alias] = time.time() + (0 if self.fake else 30) @@ -1366,22 +1366,28 @@ class Farm: return touched = False try: - gs, gwhy, _ = self.gate_check(dev) - if gs != "ok": - log(f"{alias}: gated ({gs}: {gwhy}); hold {hid} stays queued") - self.cool[alias] = time.time() + (0 if self.fake else 60) - return - h = L.read_json(H.path(hid)) - if H.released(hid) or H.age(hid) > H.HB_STALE or self.is_disabled(dev): # cancelled while the gate was being read - return done("cancelled while queued" if H.released(hid) else "caller lost or phone disabled while queued") - if alias in self.restore_pending: # a hold was cut short by a farmd restart: the phone may still be in its state - self.hold_cleanup(dev) - self.restore_pending.discard(alias) - touched = True - now = time.time() - h.update(state="active", started=L.now(), deadline=now + h["max_s"], lock=dev["lock"], serial=self.tid.get(alias) or dev["serial"]) - L.write_json(H.path(hid), h) - log(f"{alias}: hold {hid} active (max {h['max_s']}s, waited {int(now - h['seq'] / 1e9)}s)") + if adopt: # M4: farmd restarted under a live hold; its caller's command still runs on the phone + touched = True + h = L.read_json(H.path(hid)) + log(f"{alias}: hold {hid} re-adopted after a farmd restart (deadline in {int(h.get('deadline', 0) - time.time())}s)") + else: + gs, gwhy, _ = self.gate_check(dev) + if gs != "ok": + log(f"{alias}: gated ({gs}: {gwhy}); hold {hid} stays queued") + self.cool[alias] = time.time() + (0 if self.fake else 60) + return + h = L.read_json(H.path(hid)) + if H.released(hid) or H.age(hid) > H.HB_STALE or self.is_disabled(dev): # cancelled while the gate was being read + return done("cancelled while queued" if H.released(hid) else "caller lost or phone disabled while queued") + if alias in self.restore_pending: # a hold was cut short by a farmd restart: the phone may still be in its state + self.hold_cleanup(dev) + self.restore_pending.discard(alias) + H.clear_restore(alias) + touched = True + now = time.time() + h.update(state="active", started=L.now(), deadline=now + h["max_s"], lock=dev["lock"], serial=self.tid.get(alias) or dev["serial"]) + L.write_json(H.path(hid), h) + log(f"{alias}: hold {hid} active (max {h['max_s']}s, waited {int(now - h['seq'] / 1e9)}s)") while True: why = H.end_reason(h, H.age(hid), H.released(hid), disabled=self.is_disabled(dev)) if why: @@ -1459,6 +1465,7 @@ class Farm: if alias in self.restore_pending and not menu: # an earlier hold was cut short by a farmd restart self.hold_cleanup(dev) self.restore_pending.discard(alias) + H.clear_restore(alias) touched = not menu # menubench restores the phone itself self.upd(jid, lambda x: x["parts"][cls].update(state="running", device=alias)) sha, why = self.build(job) @@ -1886,15 +1893,32 @@ class Farm: self.threads = {a: t for a, t in self.threads.items() if t.is_alive()} for h in H.list_holds(): # farmd restarted mid-hold: its lock died with it if h["state"] == "active" and not any(t.name == "hold/" + h["device"] for t in self.threads.values()): + al = h["device"] + if (al in self.devs and al not in self.threads and not H.released(h["id"]) and H.age(h["id"]) <= H.HB_STALE + and time.time() < h.get("deadline", 0) and not self.is_disabled(self.devs[al])): + t = threading.Thread(target=self.run_hold, args=(h["id"], al, True), name=f"hold/{al}", daemon=False) # M4: re-adopt the live hold + self.threads[al] = t + t.start() + continue h.update(state="done", ended=L.now(), reason="farmd restarted", clean=False, clean_note="restore runs before the next job or hold") L.write_json(H.path(h["id"]), h) self.restore_pending.add(h["device"]) + H.mark_restore(h["device"]) H.gc() for j in B.order_jobs(jobs): # explicit jobs first, auto bench after them (sweep is last: real_pending) for cls, p in j["parts"].items(): if p["state"] == "running" and not any(t.name.startswith(j["id"] + "/" + cls) for t in self.threads.values()): - self.upd(j["id"], lambda x, c=cls: x["parts"][c].update(state="pending")) # farmd restarted mid-run - p["state"] = "pending" + def lost(x, c=cls): # farmd restarted mid-run: the part counts an attempt, or a job that kills farmd loops forever + q = x["parts"][c] + q["attempts"] = q.get("attempts", 0) + 1 + q["state"] = "pending" if q["attempts"] < RETRIES else "done" + if q["state"] == "done": + q["verdict"] = "error" + self.upd(j["id"], lost) + p["state"] = "pending" if p.get("attempts", 0) + 1 < RETRIES else "done" # same rule as lost(): the loop below must not run an exhausted part + if j["suite"] != "menu" and p.get("device"): # the phone may still be in the dead run's state + self.restore_pending.add(p["device"]) + H.mark_restore(p["device"]) if p["state"] != "pending": continue if j["suite"] == "menu" and self.menu_stale(j): diff --git a/tools/farm/holdlib.py b/tools/farm/holdlib.py index 82297585..588c541c 100644 --- a/tools/farm/holdlib.py +++ b/tools/farm/holdlib.py @@ -88,8 +88,9 @@ def end_reason(h, hb_age, rel, now=None, disabled=False): return "" -def gc(keep_s=86400): - """drop finished hold files older than a day""" +def gc(keep_s=86400, orphan_s=600): + """drop finished hold files older than a day, and orphans: .hb/.rel with no .json (a crashed new_hold or a gc cut short) and + leftover .tmp-* files of an interrupted write_json, once older than orphan_s (new_hold writes the .hb first: leave it a grace period)""" now = time.time() for h in list_holds(): if h["state"] == "done" and now - os.path.getmtime(path(h["id"])) > keep_s: @@ -98,3 +99,36 @@ def gc(keep_s=86400): os.unlink(path(h["id"], e)) except OSError: pass + d = holds_dir() + for n in os.listdir(d): + p = os.path.join(d, n) + orphan = n.startswith(".tmp-") or (n.rsplit(".", 1)[-1] in ("hb", "rel") and not os.path.exists(p.rsplit(".", 1)[0] + ".json")) + try: + if orphan and now - os.path.getmtime(p) > orphan_s: + os.unlink(p) + except OSError: + pass + + +# ---- restore-pending marks: a phone whose hold/job was cut short by a farmd restart must be restored before its next use; the mark is a +# file so it survives further restarts (an in-memory set was lost by the very restart it was meant to cover) +def restore_dir(): + d = os.path.join(L.state_dir(), "restore-pending") + os.makedirs(d, exist_ok=True) + return d + + +def mark_restore(alias): + with open(os.path.join(restore_dir(), alias), "a"): + pass + + +def clear_restore(alias): + try: + os.unlink(os.path.join(restore_dir(), alias)) + except OSError: + pass + + +def load_restore(): + return set(os.listdir(restore_dir())) diff --git a/tools/farm/mali-farm.service b/tools/farm/mali-farm.service index 116fd628..831b3e0c 100644 --- a/tools/farm/mali-farm.service +++ b/tools/farm/mali-farm.service @@ -7,6 +7,11 @@ Type=simple EnvironmentFile=%h/.config/mali-farm/service.env ExecStart=/bin/sh -c 'exec "$MALI_FARM_DIR/farmd"' Restart=always +# M2/M4: the default KillMode=control-group SIGKILLs every child (adb, qdeqp, shell-route) the moment farmd restarts, mid-job/mid-hold. +# mixed: SIGTERM only to farmd (it exits, its hold callers keep their own processes), SIGKILL to leftovers after the timeout. +# farmd then re-adopts live holds and restores phones marked in /restore-pending. +KillMode=mixed +TimeoutStopSec=30 RestartSec=10 Environment=PYTHONUNBUFFERED=1 diff --git a/tools/farm/test_farm.py b/tools/farm/test_farm.py index ccd3a0c3..4fc59a0d 100644 --- a/tools/farm/test_farm.py +++ b/tools/farm/test_farm.py @@ -2127,7 +2127,7 @@ def test_harness_replaces_valrun_without_the_this_run_fix(self): class HoldTests(unittest.TestCase): """farm hold: server-side FIFO queue of agent holds, fair with jobs, lease + heartbeat, same flock underneath""" - setUp, attach, farm = T.setUp, T.attach, T.farm + setUp, attach, farm, farmd = T.setUp, T.attach, T.farm, T.farmd def daemon(self): self.env.update(MALI_FARM_HB_STALE="3", MALI_FARM_HB_EVERY="0.3") @@ -2239,6 +2239,61 @@ def test_write_json_survives_and_flip_scan_ignores_corrupt_run(self): L.write_json(p, {"a": 1}) self.assertEqual(L.read_json(p), {"a": 1}) + + def test_restart_marks_persist_and_lost_running_part_counts_an_attempt(self): + self.attach("dev-a") + H.mark_restore("dev-a") + self.assertEqual(H.load_restore(), {"dev-a"}) # a file, not memory: a second restart still sees it + H.clear_restore("dev-a") + self.assertEqual(H.load_restore(), set()) + _, jid, _ = self.farm("submit", "HEAD", "--suite", "smoke", "--need", "v11") + j = L.find_job(jid) + j["parts"]["v11"].update(state="running", device="dev-a", attempts=2) + L.write_json(L.job_path(jid), j) + self.farmd() # fresh daemon: nothing owns the "running" part + p = L.find_job(jid)["parts"]["v11"] + self.assertEqual((p["state"], p.get("verdict")), ("done", "error"), p) # the retry budget is spent, not an endless loop + self.assertEqual(H.load_restore(), {"dev-a"}) # and the phone is marked for restore before its next use + + def test_live_hold_is_readopted_after_a_farmd_restart_and_stale_one_is_closed(self): + self.attach("dev-a") + live = H.new_hold("dev-a", 60) + live.update(state="active", started=L.now(), deadline=time.time() + 60, lock="cmf", serial="SERIAL-A") + L.write_json(H.path(live["id"]), live) # what a dead farmd left behind, caller still heartbeating + dead = H.new_hold("dev-b", 60) # one active hold per phone: the stale one is on the other phone + dead.update(state="active", started=L.now(), deadline=time.time() + 60, lock="poco", serial="SERIAL-B") + L.write_json(H.path(dead["id"]), dead) + os.utime(H.path(dead["id"], "hb"), (0, 0)) + self.daemon() + t0 = time.time() + while time.time() - t0 < 20 and L.read_json(H.path(dead["id"]))["state"] != "done": + H.touch(live["id"], "hb") + time.sleep(0.2) + self.assertEqual(L.read_json(H.path(dead["id"]))["reason"], "farmd restarted") + for _ in range(10): # the live one must stay active, not be closed + H.touch(live["id"], "hb") + time.sleep(0.2) + self.assertEqual(L.read_json(H.path(live["id"]))["state"], "active") + H.touch(live["id"], "rel") + t0 = time.time() + while time.time() - t0 < 20 and L.read_json(H.path(live["id"]))["state"] != "done": + time.sleep(0.2) + h = L.read_json(H.path(live["id"])) + self.assertEqual((h["reason"], h.get("clean")), ("released", True), h) # adopted: it ended through the normal release + cleanup + + def test_gc_removes_orphan_hb_rel_and_tmp_but_not_fresh_or_owned_ones(self): + h = H.new_hold("dev-a", 60) + for e in ("hb", "rel"): + H.touch("orph", e) + os.utime(H.path("orph", e), (0, 0)) + tmp = os.path.join(H.holds_dir(), ".tmp-abc") + open(tmp, "w").close() + os.utime(tmp, (0, 0)) + H.touch("fresh", "hb") # a new_hold between its .hb and .json writes + H.gc() + left = set(os.listdir(H.holds_dir())) + self.assertEqual(left, {h["id"] + ".json", h["id"] + ".hb", "fresh.hb"}) + def test_end_reason(self): h = {"deadline": 100} self.assertEqual(H.end_reason(h, 1, False, now=50), "")