Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Release tools: a failed git status, worktree list, ps or lsof refuses instead of reading as clean or idle (Fixes #2625) (#2633)

Eyal Golan7f2652ec0f56
diff --git a/tools/machine_lock.py b/tools/machine_lock.py
index 886a4bbbc..9bc32cc4d 100644
--- a/tools/machine_lock.py
+++ b/tools/machine_lock.py
@@ -15,7 +15,7 @@ before either child appears in process listings. Ordinary --shared requests and
overlap them; --exclusive excludes every participating shared holder. --timeout limits the Unity-process wait, not lock
acquisition. The lock file is
~/.cache/statecraft/machine.lock (fcntl.flock; STATECRAFT_MACHINE_LOCK overrides it), shared by every worktree of this
-user. Exit code: the command's, or 3 when --wait-unity times out.
+user. Exit code: the command's, 3 when --wait-unity times out, or 4 when Unity-process discovery fails.
Unity processes are recognised by their executable (`ps -o comm=`), never by argument text, so queued wrappers that
name Unity in their command line do not count (review C1). macOS flock does not queue fairly, so every request first
@@ -48,6 +48,22 @@ UNITY_EXE = "/Unity.app/Contents/MacOS/Unity"
HOLDER_ENV = "STATECRAFT_LOCK_HOLDER"
+class DiscoveryFailed(RuntimeError):
+ """Unity's state could not be determined, so the guarded command must not start."""
+
+
+def checked_output(command: list[str]) -> str:
+ try:
+ result = subprocess.run(command, capture_output=True, text=True)
+ except OSError as e:
+ raise DiscoveryFailed(f"`{' '.join(command)}` could not start: {e}") from e
+ if result.returncode != 0:
+ detail = result.stderr.strip()
+ suffix = f": {detail}" if detail else ""
+ raise DiscoveryFailed(f"`{' '.join(command)}` exited {result.returncode}{suffix}")
+ return result.stdout
+
+
def parse(argv: list[str]) -> argparse.Namespace:
ap = argparse.ArgumentParser()
mode = ap.add_mutually_exclusive_group(required=True)
@@ -84,14 +100,14 @@ def batch_unity_pids(comm_text: str, args_text: str, exclude: set[int] | frozens
def unity_batch_pids() -> list[int]:
def ps(field: str) -> str:
- return subprocess.run(["ps", "-axo", f"pid=,{field}="], capture_output=True, text=True).stdout
+ return checked_output(["ps", "-axo", f"pid=,{field}="])
return batch_unity_pids(ps("comm"), ps("args"), exclude={os.getpid()})
def worktrees() -> list[Path]:
"""Every worktree of this repository, so an editor open in any of them is seen."""
- r = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, text=True)
- return [Path(line[len("worktree "):]) for line in r.stdout.splitlines() if line.startswith("worktree ")]
+ text = checked_output(["git", "worktree", "list", "--porcelain"])
+ return [Path(line[len("worktree "):]) for line in text.splitlines() if line.startswith("worktree ")]
def lockfile_holders(roots: list[Path], lsof=None) -> list[int]:
@@ -99,10 +115,25 @@ def lockfile_holders(roots: list[Path], lsof=None) -> list[int]:
files = [str(p / "unity" / "Temp" / "UnityLockfile") for p in roots if (p / "unity" / "Temp" / "UnityLockfile").exists()]
if not files:
return []
- run = lsof or (lambda fs: subprocess.run(["lsof", "-t", *fs], capture_output=True, text=True).stdout)
+ run = lsof or lsof_holders_output
return sorted({int(p) for p in run(files).split() if p.isdigit()})
+def lsof_holders_output(files: list[str]) -> str:
+ """`lsof -t` exits 1 when nothing holds the files, and says "No such file" for one that vanished since the check:
+ both mean no holder. Any other failure is a discovery failure. (macOS ships lsof 4.91, which has no -Q.)"""
+ try:
+ result = subprocess.run(["lsof", "-t", *files], capture_output=True, text=True)
+ except OSError as e:
+ raise DiscoveryFailed(f"`lsof` could not start: {e}") from e
+ if result.returncode == 0:
+ return result.stdout
+ errors = [l for l in result.stderr.splitlines() if l.strip() and "No such file or directory" not in l]
+ if result.returncode == 1 and not errors:
+ return result.stdout
+ raise DiscoveryFailed(f"`lsof` exited {result.returncode}: {result.stderr.strip()}")
+
+
def unity_pids() -> list[int]:
return sorted(set(unity_batch_pids()) | set(lockfile_holders(worktrees())))
@@ -175,9 +206,15 @@ def main(argv: list[str] | None = None) -> int:
if a.shared and a.wait_unity:
unity_lock = reservations.enter_context(open(UNITY_LOCK, "a+"))
fcntl.flock(unity_lock, fcntl.LOCK_EX)
- if a.wait_unity and not wait_for_unity(a.timeout):
- print("machine_lock: timed out waiting for Unity")
- return 3
+ if a.wait_unity:
+ try:
+ idle = wait_for_unity(a.timeout)
+ except DiscoveryFailed as e:
+ print(f"machine_lock: refused because Unity-process discovery failed: {e}", file=sys.stderr)
+ return 4
+ if not idle:
+ print("machine_lock: timed out waiting for Unity")
+ return 3
child = None
signals = (signal.SIGTERM, signal.SIGHUP, signal.SIGINT)
previous = {}
diff --git a/tools/release_build.py b/tools/release_build.py
index f844fe710..863c35603 100644
--- a/tools/release_build.py
+++ b/tools/release_build.py
@@ -137,6 +137,10 @@ class Result:
stdout: str = ""
+class SafetyCheckFailed(RuntimeError):
+ """A release-safety command failed, so its output cannot be treated as an all-clear."""
+
+
def run(cmd: list, **kw) -> Result:
"""The one place a process is started (tests replace it). Output is captured only when asked for."""
capture = kw.pop("capture", False)
@@ -214,8 +218,19 @@ def git(*args: str) -> Result:
return run(["git", *args], cwd=REPO, capture=True)
+def checked_git_output(*args: str) -> str:
+ try:
+ result = git(*args)
+ except OSError as e:
+ raise SafetyCheckFailed(f"`git {' '.join(args)}` could not start: {e}") from e
+ if result.returncode != 0:
+ raise SafetyCheckFailed(f"`git {' '.join(args)}` exited {result.returncode}")
+ return result.stdout
+
+
def dirty_lines() -> list[str]:
- return [l for l in git("status", "--porcelain", "--untracked-files=normal").stdout.splitlines() if l.strip()]
+ text = checked_git_output("status", "--porcelain", "--untracked-files=normal")
+ return [line for line in text.splitlines() if line.strip()]
def missing_modules(names: list[str], editor_root: Path) -> list[Platform]:
@@ -233,7 +248,7 @@ def modules_message(missing: list[Platform], version: str) -> str:
def checkouts() -> list[Path]:
"""This checkout, the main one and every worktree of the repository."""
- listed = git("worktree", "list", "--porcelain").stdout.splitlines()
+ listed = checked_git_output("worktree", "list", "--porcelain").splitlines()
return [REPO, *(Path(l[len("worktree "):]) for l in listed if l.startswith("worktree "))]
@@ -519,7 +534,11 @@ def main(argv: list[str] | None = None) -> int:
if missing:
print(modules_message(missing, version), file=sys.stderr)
return 2
- dirty = dirty_lines()
+ try:
+ dirty = dirty_lines()
+ except SafetyCheckFailed as e:
+ print(f"REFUSED: cannot prove the working tree is clean: {e}. Nothing was built.", file=sys.stderr)
+ return 1
if nightly is not None and (problem := stamp_problem(dirty, nightly)):
print(f"REFUSED: {problem}", file=sys.stderr)
return 1
@@ -573,7 +592,13 @@ def main(argv: list[str] | None = None) -> int:
return 1
tag = f"v{vers['bundle_version']}-dev.{commit[:8]}"
out = (a.out or default_out(commit, vers["bundle_version"] or "0", started.strftime("%Y%m%dT%H%M%SZ"))).absolute()
- if (root := inside_a_checkout(out)) is not None:
+ try:
+ root = inside_a_checkout(out)
+ except SafetyCheckFailed as e:
+ print(f"REFUSED: cannot enumerate every checkout before accepting --out: {e}. Nothing was built.",
+ file=sys.stderr)
+ return 1
+ if root is not None:
print(f"REFUSED: {out} is inside the checkout {root}; choose a folder outside every checkout of the repository "
"(the default is ~/statecraft-release/).", file=sys.stderr)
return 1
@@ -668,7 +693,12 @@ def main(argv: list[str] | None = None) -> int:
"unity_build_seconds": unity_seconds(log_text), "wall_seconds_with_lock_wait": wall,
"unity_log": str(log.relative_to(out)), "golden": golden})
- dirty_after = [l.strip() for l in dirty_lines()]
+ try:
+ dirty_after = [line.strip() for line in dirty_lines()]
+ except SafetyCheckFailed as e:
+ print(f"FAILED: cannot prove the working tree remained clean after the builds: {e}; "
+ "no build record was written.", file=sys.stderr)
+ return 1
record = {"schema": 1, "tool": "tools/release_build.py", "commit": commit,
"describe": describe, "branch": branch, "release": release,
# checked before the builds: a dirty tree is refused (a nightly may carry only its own bundleVersion stamp)
diff --git a/tools/tests/test_machine_lock.py b/tools/tests/test_machine_lock.py
index c1188d31d..17e265415 100644
--- a/tools/tests/test_machine_lock.py
+++ b/tools/tests/test_machine_lock.py
@@ -2,6 +2,7 @@ import os
import subprocess
import sys
import time
+from contextlib import nullcontext
from pathlib import Path
import pytest
@@ -12,6 +13,10 @@ fcntl = pytest.importorskip("fcntl", reason="fcntl is POSIX-only (machine_lock u
import machine_lock as ml # noqa: E402
+def completed(command, code=0, stdout="", stderr=""):
+ return subprocess.CompletedProcess(command, code, stdout, stderr)
+
+
def test_the_command_follows_the_double_dash_and_a_mode_is_required():
a = ml.parse(["--exclusive", "--wait-unity", "--", "uv", "run", "tools/web_check.py", "--query", "vprofile"])
assert a.exclusive and a.wait_unity and a.command == ["uv", "run", "tools/web_check.py", "--query", "vprofile"]
@@ -68,6 +73,65 @@ def test_an_editor_holding_a_worktree_lockfile_counts_as_unity(tmp_path):
assert ml.lockfile_holders([tmp_path / "b"], lsof=lambda files: "1\n") == []
[email protected]("failed_field", ["comm", "args"])
+def test_failed_ps_refuses_unity_discovery(monkeypatch, failed_field):
+ def run(command, **kwargs):
+ field = command[-1]
+ return completed(command, 1, stderr="ps failed") if failed_field in field else completed(command)
+
+ monkeypatch.setattr(ml.subprocess, "run", run)
+ with pytest.raises(ml.DiscoveryFailed, match="ps"):
+ ml.unity_batch_pids()
+
+
+def test_failed_git_worktree_list_refuses_unity_discovery(monkeypatch):
+ monkeypatch.setattr(
+ ml.subprocess, "run",
+ lambda command, **kwargs: completed(command, 1, stderr="git failed"))
+ with pytest.raises(ml.DiscoveryFailed, match="git worktree list"):
+ ml.worktrees()
+
+
+def test_failed_lsof_refuses_unity_discovery(monkeypatch, tmp_path):
+ lockfile = tmp_path / "wt/unity/Temp/UnityLockfile"
+ lockfile.parent.mkdir(parents=True)
+ lockfile.write_text("")
+
+ def run(command, **kwargs):
+ assert command[:2] == ["lsof", "-t"]
+ return completed(command, 1, stderr="lsof failed")
+
+ monkeypatch.setattr(ml.subprocess, "run", run)
+ with pytest.raises(ml.DiscoveryFailed, match="lsof"):
+ ml.lockfile_holders([tmp_path / "wt"])
+
+
+def test_lsof_no_holder_is_a_successful_empty_result(monkeypatch, tmp_path):
+ lockfile = tmp_path / "wt/unity/Temp/UnityLockfile"
+ lockfile.parent.mkdir(parents=True)
+ lockfile.write_text("")
+
+ def run(command, **kwargs):
+ assert command[:2] == ["lsof", "-t"]
+ return completed(command)
+
+ monkeypatch.setattr(ml.subprocess, "run", run)
+ assert ml.lockfile_holders([tmp_path / "wt"]) == []
+
+
+def test_discovery_failure_never_launches_the_guarded_command(monkeypatch, capsys):
+ monkeypatch.setattr(ml, "hold", lambda **kwargs: nullcontext())
+ monkeypatch.setattr(
+ ml.subprocess, "run",
+ lambda command, **kwargs: completed(command, 1, stderr="ps failed"))
+ monkeypatch.setattr(
+ ml.subprocess, "Popen",
+ lambda *args, **kwargs: pytest.fail("guarded command was launched"))
+
+ assert ml.main(["--exclusive", "--wait-unity", "--", "unused"]) == 4
+ assert "discovery failed" in capsys.readouterr().err
+
+
UNITY_EXE = "/Applications/Unity/Hub/Editor/6000.3.25f1/Unity.app/Contents/MacOS/Unity"
@@ -250,3 +314,32 @@ def test_python_hold_uses_the_same_shared_lock_and_releases_on_exit(tmp_path, mo
with open(path, "a+") as released:
fcntl.flock(released, fcntl.LOCK_EX | fcntl.LOCK_NB)
fcntl.flock(released, fcntl.LOCK_UN)
+
+
[email protected]("returncode, stdout, stderr, expected", [
+ (0, "123\n456\n", "", "123\n456\n"), # holders found
+ (1, "", "", ""), # nobody holds the lockfiles
+ (1, "", "lsof: status error on /x/UnityLockfile: No such file or directory\n", ""), # vanished since the check
+])
+def test_lsof_exit_1_without_a_real_error_means_no_holder(monkeypatch, returncode, stdout, stderr, expected):
+ monkeypatch.setattr(ml.subprocess, "run",
+ lambda cmd, **kw: subprocess.CompletedProcess(cmd, returncode, stdout, stderr))
+ assert ml.lsof_holders_output(["/x/UnityLockfile"]) == expected
+
+
[email protected]("returncode, stderr", [(1, "lsof: illegal option character: Q\n"), (2, "boom\n")])
+def test_lsof_with_a_real_error_is_a_discovery_failure(monkeypatch, returncode, stderr):
+ monkeypatch.setattr(ml.subprocess, "run",
+ lambda cmd, **kw: subprocess.CompletedProcess(cmd, returncode, "", stderr))
+ with pytest.raises(ml.DiscoveryFailed):
+ ml.lsof_holders_output(["/x/UnityLockfile"])
+
+
+def test_lsof_is_called_without_flags_this_macs_lsof_lacks(monkeypatch):
+ calls = []
+ def fake(cmd, **kw):
+ calls.append(cmd)
+ return subprocess.CompletedProcess(cmd, 1, "", "")
+ monkeypatch.setattr(ml.subprocess, "run", fake)
+ ml.lsof_holders_output(["/x/UnityLockfile"])
+ assert calls == [["lsof", "-t", "/x/UnityLockfile"]]
diff --git a/tools/tests/test_release_build.py b/tools/tests/test_release_build.py
index 9394c79e3..9aa8948ad 100644
--- a/tools/tests/test_release_build.py
+++ b/tools/tests/test_release_build.py
@@ -66,19 +66,27 @@ class Fake:
steam_library = True
def __init__(self, dirty="", golden_ok=True, build_ok=True, branch="main", tags=("v0.1.0",), worktrees=None,
- build_raises=None, dirty_after="", on_origin_main=True):
+ build_raises=None, dirty_after="", on_origin_main=True, fail_status=False,
+ fail_status_after=False, fail_worktree_list=False):
self.calls: list[list[str]] = []
self.dirty, self.golden_ok, self.build_ok = dirty, golden_ok, build_ok
self.branch, self.tags, self.worktrees = branch, tags, worktrees
self.build_raises, self.dirty_after, self.built = build_raises, dirty_after, False
self.on_origin_main = on_origin_main
+ self.fail_status = fail_status
+ self.fail_status_after = fail_status_after
+ self.fail_worktree_list = fail_worktree_list
def __call__(self, cmd, **kw):
cmd = [str(c) for c in cmd]
self.calls.append(cmd)
out, code = "", 0
if cmd[:2] == ["git", "status"]:
- out = self.dirty_after if self.built else self.dirty
+ status_failed = self.fail_status_after if self.built else self.fail_status
+ if status_failed:
+ code = 1
+ else:
+ out = self.dirty_after if self.built else self.dirty
elif cmd[:2] == ["git", "rev-parse"]:
out = self.branch + "\n" if "--abbrev-ref" in cmd else SHA + "\n"
elif cmd[:2] == ["git", "merge-base"]:
@@ -86,7 +94,10 @@ class Fake:
elif cmd[:3] == ["git", "tag", "--points-at"]:
out = "".join(t + "\n" for t in self.tags)
elif cmd[:3] == ["git", "worktree", "list"]:
- out = "".join(f"worktree {w}\nHEAD {SHA}\nbranch refs/heads/x\n\n" for w in self.worktrees or [])
+ if self.fail_worktree_list:
+ code = 1
+ else:
+ out = "".join(f"worktree {w}\nHEAD {SHA}\nbranch refs/heads/x\n\n" for w in self.worktrees or [])
elif cmd[:2] == ["git", "describe"]:
out = "v0.1.0-5-g1b7a36cb\n"
elif cmd[:2] == ["git", "check-ignore"]:
@@ -223,6 +234,14 @@ def test_every_checkout_of_the_repository_is_refused(repo, editor, monkeypatch,
assert unity_calls(fake) == []
+def test_a_failed_worktree_list_is_refused_before_build(repo, editor, monkeypatch, tmp_path, capsys):
+ fake = Fake(fail_worktree_list=True)
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "out")],
+ repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+ assert "cannot enumerate every checkout" in capsys.readouterr().err
+
+
def test_a_non_empty_output_folder_is_refused(repo, editor, monkeypatch, tmp_path):
out = tmp_path / "out"
(out / "players/linux").mkdir(parents=True)
@@ -330,6 +349,16 @@ def test_the_record_says_whether_the_tree_stayed_clean(repo, editor, monkeypatch
assert describe < next(i for i, c in enumerate(fake.calls) if "-executeMethod" in c), "describe is taken before"
+def test_a_failed_postbuild_git_status_writes_no_clean_record(repo, editor, monkeypatch, tmp_path, capsys):
+ out = tmp_path / "out"
+ fake = Fake(fail_status_after=True)
+ assert run_main(["--platform", "mac", "--out", str(out)], repo, editor, fake, monkeypatch) == 1
+ assert len(unity_calls(fake)) == 1
+ assert not (out / "build-record.json").exists()
+ assert not (out / "build-record.md").exists()
+ assert "cannot prove the working tree remained clean" in capsys.readouterr().err
+
+
# --- what the script reads ------------------------------------------------------------------------------------------------
def test_unity_version_and_goldens_come_from_the_repository(repo, monkeypatch):
@@ -350,6 +379,30 @@ def test_a_dirty_tree_is_refused_before_any_build(repo, editor, monkeypatch, cap
assert not (tmp_path / "out").exists()
+def test_a_failed_initial_git_status_is_refused_before_build(repo, editor, monkeypatch, tmp_path, capsys):
+ fake = Fake(fail_status=True)
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "out")],
+ repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+ assert "cannot prove the working tree is clean" in capsys.readouterr().err
+
+
+class GitWontStart(Fake):
+ def __call__(self, cmd, **kw):
+ if [str(c) for c in cmd][:2] == ["git", "status"]:
+ raise FileNotFoundError(2, "No such file or directory", "git")
+ return super().__call__(cmd, **kw)
+
+
+def test_a_git_that_cannot_start_is_refused_with_a_message(repo, editor, monkeypatch, tmp_path, capsys):
+ fake = GitWontStart()
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "out")],
+ repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+ assert "cannot prove the working tree is clean: `git status --porcelain --untracked-files=normal` could not start" \
+ in capsys.readouterr().err
+
+
def test_untracked_files_count_as_dirty(repo, editor, monkeypatch, tmp_path):
fake = Fake(dirty="?? notes.txt\n")
assert run_main(["--platform", "mac", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch) == 1