refactor: autorun code in the unattended package

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 21:32:47 +01:00
1 parent 963a81b09a
commit b20c0127f9
16 files changed
+1286 -1213

No files matched your search

+5 -1045
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -79,7 +79,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
import yaml
import autorun
from unattended import worktree
from core import hostguard
from probes.profileedit import ProfileEditError
from core.paths import REPO_ROOT
@@ -235,7 +235,7 @@ def main(argv: Sequence[str] | None = None) -> int:
def _run_pass(campaign: Campaign, args: argparse.Namespace, only: set[str], paths: Paths) -> int:
campaign.dirty_at_start = set(autorun.changed_files(paths.root)) if args.commit else set()
campaign.dirty_at_start = set(worktree.changed_files(paths.root)) if args.commit else set()
def stop(signum: int, frame: object) -> None:
# SIGTERM ends the pass like Ctrl-C: state saved, pass line written.
+4 -3
View File
@@ -15,7 +15,8 @@ from pathlib import Path
import yaml
import autorun
from unattended import jobs
from unattended import worktree
import core_probe
from core import hostguard
from core.hashing import file_digest
@@ -959,10 +960,10 @@ class Campaign:
return []
made = []
for subject, paths in plan:
problems = autorun.check_subject(subject)
problems = jobs.check_subject(subject)
if problems:
raise ValueError(f"{subject!r}: {', '.join(problems)}")
made.append(autorun.commit_paths(self.paths.root, paths, autorun.CommitRule(subject, tuple(paths))))
made.append(worktree.commit_paths(self.paths.root, paths, jobs.CommitRule(subject, tuple(paths))))
if self.current:
self.current.touched.clear()
return made
+2 -2
View File
@@ -7,7 +7,7 @@ import sys
from collections.abc import Sequence
from pathlib import Path
import autorun
from unattended import worktree
from probes.host import Host
@@ -38,5 +38,5 @@ def gate(root: Path, emulators: Sequence[str], host: Host | None = None) -> int:
def changed_profiles(root: Path) -> list[str]:
return [Path(p).stem for p in autorun.changed_files(root)
return [Path(p).stem for p in worktree.changed_files(root)
if p.startswith("emulators/") and p.endswith(".yml")]
+2 -2
View File
@@ -16,7 +16,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import IO, TYPE_CHECKING, TypedDict
import autorun
from unattended import worktree
import core_probe
from core import childenv, hostguard
from core.paths import REPO_ROOT
@@ -154,7 +154,7 @@ class Paths:
@classmethod
def default(cls) -> Paths:
main = autorun.main_checkout()
main = worktree.main_checkout()
return cls(root=REPO_ROOT, home=main / ".cache" / "campaign",
content=main / ".cache" / "test-content", db=REPO_ROOT / "database.json")
+2 -2
View File
@@ -17,7 +17,7 @@ from collections.abc import Iterable, Iterator, Sequence
from dataclasses import dataclass
from pathlib import Path
import autorun
from unattended import worktree
from core_probe import PROBE_LOCK_ENV, PROBE_LOCK_HELD_ENV, VERDICTS, probe_lock_path
from core.hashing import file_digest
from core.paths import REPO_ROOT
@@ -44,7 +44,7 @@ from resolve.layout import runs_standalone
from resolve.validation import filter_files_by_mode
MAIN = autorun.main_checkout()
MAIN = worktree.main_checkout()
PACK_CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "pack_content.yml"
CONTENT_DIR = MAIN / ".cache" / "test-content"
CORE_CACHE = MAIN / ".cache" / "pack-probe" / "cores"
+3
View File
@@ -0,0 +1,3 @@
"""The unattended jobs of automation/jobs.yml: their registry, the worktree they
commit in, the CI breaker, one run, and the systemd units.
"""
+106
View File
@@ -0,0 +1,106 @@
"""The circuit breaker: the CI runs of pushed automation commits, read through
gh, decide whether a job may commit and push.
"""
from __future__ import annotations
import json
import subprocess
from collections.abc import Callable, Sequence
from unattended.jobs import token_env
from unattended.worktree import TARGET
REPO_SLUG = "Abdess/retrobios"
CI_RED = frozenset({"failure", "timed_out", "startup_failure"})
CI_GREEN = frozenset({"success", "skipped", "neutral"})
# Circuit breaker
def gh_json(args: list[str]) -> object:
"""Parsed output of a gh command, or None when gh cannot answer."""
try:
proc = subprocess.run(
["gh", *args], capture_output=True, text=True, timeout=120, check=False,
env=token_env(),
)
except (OSError, subprocess.TimeoutExpired):
return None
if proc.returncode != 0:
return None
try:
return json.loads(proc.stdout)
except ValueError:
return None
RUN_FIELDS = "workflowName,status,conclusion,headSha,createdAt"
def ci_verdict(runs: Sequence[dict]) -> str:
"""failure as soon as one run is red, success once all ended green."""
if any(r.get("conclusion") in CI_RED for r in runs):
return "failure"
if not runs or any(r.get("status") != "completed" for r in runs):
return "pending"
if all(r.get("conclusion") in CI_GREEN for r in runs):
return "success"
return "pending"
def refresh_breaker(state: dict, gh: Callable[[list[str]], object], now: str) -> None:
"""Read CI for the last automation push, open or close the breaker."""
push = state.setdefault("push", {})
breaker = state.setdefault("breaker", {"open": False})
sha = push.get("sha")
if sha and push.get("ci") not in ("success", "failure"):
runs = gh(["run", "list", "-R", REPO_SLUG, "--commit", sha, "--json", RUN_FIELDS])
if isinstance(runs, list):
verdict = ci_verdict(runs)
push["ci"] = verdict
if verdict == "failure":
red = [r for r in runs if r.get("conclusion") in CI_RED]
state["breaker"] = breaker = {
"open": True,
"sha": sha,
"opened_at": now,
"failed_run_at": max(str(r.get("createdAt") or "") for r in runs),
"reason": ", ".join(sorted({str(r.get("workflowName")) for r in red})),
}
state.setdefault("alerts", {})["ci"] = {
"since": now, "detail": f"red CI on {sha[:12]}: {breaker['reason']}",
}
if not breaker.get("open"):
return
runs = gh([
"run", "list", "-R", REPO_SLUG, "--branch", TARGET, "--limit", "40",
"--json", RUN_FIELDS,
])
if not isinstance(runs, list):
return
after = [
r for r in runs
if str(r.get("createdAt") or "") > breaker.get("failed_run_at", "")
and r.get("headSha") != breaker.get("sha")
]
if not after:
return
newest = max(after, key=lambda r: str(r.get("createdAt") or ""))["headSha"]
if ci_verdict([r for r in after if r.get("headSha") == newest]) == "success":
state["breaker"] = {"open": False, "closed_at": now, "closed_by": newest}
state.get("alerts", {}).pop("ci", None)
def may_push(state: dict) -> str:
"""Empty when a push may go out, else the reason it may not."""
if state.get("breaker", {}).get("open"):
return "circuit breaker open"
push = state.get("push") or {}
if push.get("sha") and push.get("ci") != "success":
return f"CI of {push['sha'][:12]} has not ended green"
return ""
+240
View File
@@ -0,0 +1,240 @@
"""The job registry: automation/jobs.yml read into jobs, the results a job ends
with, and the environment each step gets.
"""
from __future__ import annotations
import os
import re
import subprocess
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
from core.childenv import is_secret, safe_env
from core.hostguard import LOCK_HELD_ENV
from core.paths import REPO_ROOT
JOBS_FILE = REPO_ROOT / "automation" / "jobs.yml"
OK = "ok"
FAILED = "failed"
DEFERRED = "deferred"
REFUSED = "refused"
BLOCKED = "blocked"
JOB_KEYS = frozenset({
"schedule", "steps", "gate", "twice", "commits", "worktree", "lock",
"network", "min_free_gb", "max_load_wait", "timeout", "scratch", "report",
})
class AutorunError(RuntimeError):
"""A condition that ends a job with a named result."""
def __init__(self, result: str, detail: str) -> None:
super().__init__(detail)
self.result = result
self.detail = detail
@dataclass(frozen=True)
class Step:
argv: tuple[str, ...]
ok_codes: tuple[int, ...] = (0,)
stdout: str = ""
# Variables passed through beside the allowlist (romfetch's settings).
env: tuple[str, ...] = ()
# GITHUB_TOKEN for a first-party script that calls the GitHub API.
github_token: bool = False
@dataclass(frozen=True)
class Twice:
"""An artifact the gate wrote, computed again into {out} and compared."""
artifact: str
argv: tuple[str, ...]
glob: str = ""
@dataclass(frozen=True)
class CommitRule:
subject: str
paths: tuple[str, ...]
body: str = ""
@dataclass(frozen=True)
class Job:
name: str
steps: tuple[Step, ...] = ()
gate: tuple[Step, ...] = ()
twice: tuple[Twice, ...] = ()
commits: tuple[CommitRule, ...] = ()
schedule: str = ""
worktree: bool = True
lock: bool = True
network: bool = False
min_free_gb: float = 30.0
max_load_wait: int = 3600
timeout: int = 21600
scratch: tuple[str, ...] = ()
report: str = ""
# Job registry
def check_subject(subject: str, body: str = "") -> list[str]:
"""What the repository's commit rules refuse in this message, checked
when the job list loads instead of two hours into the job."""
from devtools.commitrules import problems
return problems(f"{subject}\n\n{body}" if body else subject)
# The first-party scripts that call the GitHub API and may receive
# GITHUB_TOKEN: run as `python <script>` or `python -m <module>`, and tracked
# by git in this repository. Nothing else ever gets it, third-party code least.
TOKEN_SCRIPTS = ("scripts/check_freshness.py", "scripts/refresh_stale.py")
TOKEN_MODULE_PREFIX = "scripts.scraper."
NO_TOKEN_JOBS = frozenset({"campaign"})
def tracked(path: str, repo: Path = REPO_ROOT) -> bool:
proc = subprocess.run(["git", "-C", str(repo), "ls-files", "--error-unmatch", "--", path],
capture_output=True, check=False)
return proc.returncode == 0
def token_script(argv: Sequence[str], repo: Path = REPO_ROOT) -> str:
"""The tracked first-party script a step runs, or '' when it runs anything else."""
if len(argv) < 2 or argv[0] != "python":
return ""
if argv[1] in TOKEN_SCRIPTS:
path = argv[1]
elif argv[1] == "-m" and len(argv) > 2 and argv[2].startswith(TOKEN_MODULE_PREFIX) \
and re.fullmatch(r"[a-z0-9_.]+", argv[2]):
path = argv[2].replace(".", "/") + ".py"
else:
return ""
return path if tracked(path, repo) else ""
def _step(raw: object, where: str, job: str = "") -> Step:
if isinstance(raw, list):
return Step(argv=tuple(str(a) for a in raw))
if isinstance(raw, dict) and isinstance(raw.get("run"), list):
unknown = set(raw) - {"run", "ok_codes", "stdout", "env", "github_token"}
if unknown:
raise ValueError(f"{where}: unknown step key {sorted(unknown)}")
names = tuple(str(n) for n in raw.get("env") or ())
secret = [n for n in names if is_secret(n)]
if secret:
raise ValueError(f"{where}: a step never receives {', '.join(secret)}")
argv = tuple(str(a) for a in raw["run"])
token = raw.get("github_token", False)
if token is not False:
if token is not True:
raise ValueError(f"{where}: github_token is true or absent")
if job in NO_TOKEN_JOBS:
raise ValueError(f"{where}: job {job} never receives GITHUB_TOKEN")
if not token_script(argv):
raise ValueError(f"{where}: github_token only goes to {', '.join(TOKEN_SCRIPTS)} "
f"or python -m {TOKEN_MODULE_PREFIX}*, tracked in this repository")
return Step(
argv=argv,
ok_codes=tuple(int(c) for c in raw.get("ok_codes", (0,))),
stdout=str(raw.get("stdout") or ""),
env=names,
github_token=token is True,
)
raise ValueError(f"{where}: a step is a command list or a mapping with 'run'")
def parse_jobs(data: dict) -> dict[str, Job]:
"""Jobs from the registry mapping, refused whole on any unknown key."""
defaults = data.get("defaults") or {}
jobs: dict[str, Job] = {}
for name, raw in (data.get("jobs") or {}).items():
raw = {**defaults, **(raw or {})}
unknown = set(raw) - JOB_KEYS
if unknown:
raise ValueError(f"job {name}: unknown key {sorted(unknown)}")
twice = []
for i, item in enumerate(raw.get("twice") or ()):
argv = tuple(str(a) for a in item["run"])
if "{out}" not in argv:
raise ValueError(f"job {name}: twice[{i}] names no {{out}}")
twice.append(Twice(str(item["artifact"]), argv, str(item.get("glob") or "")))
commits = []
for item in raw.get("commits") or ():
rule = CommitRule(
subject=str(item["subject"]),
paths=tuple(str(p) for p in item["paths"]),
body=str(item.get("body") or "").strip(),
)
problems = check_subject(rule.subject, rule.body)
if problems:
raise ValueError(f"job {name}: {rule.subject!r}: {', '.join(problems)}")
commits.append(rule)
if commits and raw.get("worktree") is False:
raise ValueError(f"job {name}: a job that commits runs in the worktree")
jobs[name] = Job(
name=name,
steps=tuple(_step(s, f"job {name}", name) for s in raw.get("steps") or ()),
gate=tuple(_step(s, f"job {name} gate", name) for s in raw.get("gate") or ()),
twice=tuple(twice),
commits=tuple(commits),
schedule=str(raw.get("schedule") or ""),
worktree=bool(raw.get("worktree", True)),
lock=bool(raw.get("lock", True)),
network=bool(raw.get("network", False)),
min_free_gb=float(raw.get("min_free_gb", 30)),
max_load_wait=int(raw.get("max_load_wait", 3600)),
timeout=int(raw.get("timeout", 21600)),
scratch=tuple(str(p) for p in raw.get("scratch") or ()),
report=str(raw.get("report") or ""),
)
return jobs
def load_jobs(path: Path = JOBS_FILE) -> dict[str, Job]:
import yaml
with path.open(encoding="utf-8") as handle:
return parse_jobs(yaml.safe_load(handle) or {})
# Running a job
def token_env() -> dict[str, str]:
"""The environment of the phases that need GitHub: the push and gh."""
from core.github import github_token
env = dict(os.environ)
token = github_token()
if token:
env["GITHUB_TOKEN"] = token
return env
def job_env(job: Job, step: Step | None = None) -> dict[str, str]:
"""A step's environment: the allowlist, the runner's own markers and the
variables the step names. GITHUB_TOKEN only for a step that declares
github_token, which the registry allows on first-party scripts alone."""
add = {"RETROBIOS_AUTO": "1"}
if job.lock:
# A step that takes the host lock itself (campaign.py) runs under ours.
add[LOCK_HELD_ENV] = "1"
env = safe_env(step.env if step else (), add)
if step is not None and step.github_token and job.name not in NO_TOKEN_JOBS:
token = token_env().get("GITHUB_TOKEN")
if token:
env["GITHUB_TOKEN"] = token
return env
+543
View File
@@ -0,0 +1,543 @@
"""One job run: the host checks, the steps retried after a misread, the artifacts
computed twice, the commits, the state and the logs.
"""
from __future__ import annotations
import contextlib
import datetime as dt
import json
import os
import shlex
import shutil
import subprocess
import sys
import time
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from core.hostguard import LockBusy, free_gb, global_lock, lock_busy
from core.statefile import now_iso, save_state
from unattended.breaker import may_push, refresh_breaker
from unattended.jobs import AutorunError, BLOCKED, DEFERRED, FAILED, Job, OK, REFUSED, Step, job_env
from unattended.worktree import (
changed_files,
commit_paths,
ensure_worktree,
plan_commit,
push_batch,
seed_worktree,
sync_worktree,
unpushed,
)
AUTORUN_DIR = Path(".cache") / "autorun"
ALERT_FREE_GB = 100
LOG_DAYS = 30
SEGFAULT_CODES = (139, -11)
HOST_MISREAD_MARKERS = ("SystemError", "unknown opcode")
VOLATILE_KEYS = frozenset({"generated_at", "generated", "imported_at"})
@dataclass
class Outcome:
returncode: int
text: str = ""
retried: bool = False
@dataclass
class Host:
"""What a run reads from the machine, replaced by fakes in the tests."""
loadavg: Callable[[], tuple[float, float, float]] = os.getloadavg
sleep: Callable[[float], None] = time.sleep
clock: Callable[[], float] = time.monotonic
cpu_count: int = os.cpu_count() or 1
poll: float = 60.0
@property
def max_load(self) -> float:
return self.cpu_count / 4
@dataclass
class Context:
repo: Path
jobs: dict[str, Job]
lock_path: Path
host: Host = field(default_factory=Host)
gh: Callable[[list[str]], object] | None = None
dry_run: bool = False
push: bool = False
@property
def home(self) -> Path:
return self.repo / AUTORUN_DIR
@property
def worktree(self) -> Path:
return self.home / "worktree"
@property
def state_path(self) -> Path:
return self.home / "state.json"
# Host guards
def wait_for_load(host: Host, max_wait: float) -> bool:
"""True once the 1-minute load is at most a quarter of the CPUs."""
deadline = host.clock() + max_wait
while True:
if host.loadavg()[0] <= host.max_load:
return True
left = deadline - host.clock()
if left <= 0:
return False
host.sleep(min(host.poll, left))
def host_misread(returncode: int, text: str) -> bool:
"""A failure this host's CPU produces under load, worth one idle retry."""
if returncode in SEGFAULT_CODES:
return True
return returncode != 0 and any(marker in text for marker in HOST_MISREAD_MARKERS)
# Running commands
def resolve_argv(argv: Sequence[str], out: str = "") -> list[str]:
"""`python` is the interpreter running autorun, {out} the scratch output."""
resolved = [sys.executable if a == "python" else a for a in argv]
return [a.replace("{out}", out) for a in resolved] if out else resolved
def execute(
argv: Sequence[str],
cwd: Path,
log: Path,
env: dict[str, str],
timeout: float,
stdout: Path | None = None,
) -> Outcome:
"""Run one command, its output appended to the job log."""
log.parent.mkdir(parents=True, exist_ok=True)
with log.open("a", encoding="utf-8") as handle:
handle.write(f"$ {shlex.join(argv)}\n")
start = handle.tell()
try:
with log.open("a", encoding="utf-8") as handle:
if stdout is not None:
stdout.parent.mkdir(parents=True, exist_ok=True)
with stdout.open("w", encoding="utf-8") as out:
proc = subprocess.run(
list(argv), cwd=cwd, stdout=out, stderr=handle,
env=env, timeout=max(1, timeout), check=False,
)
else:
proc = subprocess.run(
list(argv), cwd=cwd, stdout=handle, stderr=subprocess.STDOUT,
env=env, timeout=max(1, timeout), check=False,
)
returncode = proc.returncode
except subprocess.TimeoutExpired:
returncode = 124
with log.open("a", encoding="utf-8") as handle:
handle.write(f"\nTIMEOUT after {int(timeout)}s\n")
except OSError as exc:
returncode = 127
with log.open("a", encoding="utf-8") as handle:
handle.write(f"\ncannot run: {exc}\n")
with log.open("rb") as handle:
handle.seek(start)
text = handle.read().decode("utf-8", errors="replace")
return Outcome(returncode, text)
def run_with_retry(
run: Callable[[], Outcome],
ok_codes: Sequence[int],
wait_idle: Callable[[], object],
) -> Outcome:
"""Run once, and once more on an idle host when the failure is a misread."""
first = run()
if first.returncode in ok_codes or not host_misread(first.returncode, first.text):
return first
wait_idle()
second = run()
second.retried = True
return second
# Double computation
def strip_volatile(value: object) -> object:
if isinstance(value, dict):
return {k: strip_volatile(v) for k, v in value.items() if k not in VOLATILE_KEYS}
if isinstance(value, list):
return [strip_volatile(v) for v in value]
return value
def comparable(path: Path) -> object:
if path.suffix == ".json":
with contextlib.suppress(ValueError):
return strip_volatile(json.loads(path.read_text(encoding="utf-8")))
return path.read_bytes()
def _files(root: Path, glob: str) -> dict[str, Path]:
if not root.is_dir():
return {}
found = root.glob(glob) if glob else root.rglob("*")
return {p.relative_to(root).as_posix(): p for p in found if p.is_file()}
def differences(a: Path, b: Path, glob: str = "") -> list[str]:
"""Files that differ between two outputs, timestamps aside."""
if a.is_dir() or b.is_dir():
files_a, files_b = _files(a, glob), _files(b, glob)
return sorted(
name for name in set(files_a) | set(files_b)
if name not in files_a or name not in files_b
or comparable(files_a[name]) != comparable(files_b[name])
)
if not a.is_file() or not b.is_file():
return [a.name]
return [] if comparable(a) == comparable(b) else [a.name]
def twice(
argv: Sequence[str],
out_a: Path,
out_b: Path,
run: Callable[[list[str]], Outcome],
glob: str = "",
) -> list[str]:
"""Compute one output twice and name what the two runs disagree on."""
for out in (out_a, out_b):
outcome = run(resolve_argv(argv, str(out)))
if outcome.returncode != 0:
raise AutorunError(FAILED, f"{shlex.join(argv)} exited {outcome.returncode}")
return differences(out_a, out_b, glob)
# State and logs
def load_state(path: Path) -> dict:
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return {}
except ValueError as exc:
raise AutorunError(FAILED, f"{path} is unreadable: {exc}") from exc
def prune_logs(logs: Path, days: int = LOG_DAYS, now: float | None = None) -> int:
limit = (now if now is not None else time.time()) - days * 86400
removed = 0
for path in logs.glob("*/*.log") if logs.is_dir() else ():
if path.stat().st_mtime < limit:
path.unlink()
removed += 1
return removed
def set_alert(state: dict, name: str, active: bool, detail: str, now: str) -> None:
alerts = state.setdefault("alerts", {})
if active:
alerts.setdefault(name, {"since": now})["detail"] = detail
else:
alerts.pop(name, None)
def _remove_scratch(root: Path, rel: str) -> None:
target = (root / rel).resolve()
if root.resolve() not in target.parents:
raise AutorunError(FAILED, f"scratch path {rel} leaves {root}")
if target.is_dir():
shutil.rmtree(target)
elif target.exists():
target.unlink()
def read_report(root: Path, rel: str) -> object:
"""The JSON report a job's step wrote, kept in the job's state."""
if not rel:
return None
try:
return json.loads((root / rel).read_text(encoding="utf-8"))
except FileNotFoundError:
return None
except ValueError as exc:
return {"unreadable": str(exc)}
class Runner:
"""One job run: guards, steps, gate, double computation, commits, push."""
def __init__(self, ctx: Context, job: Job, state: dict) -> None:
self.ctx = ctx
self.job = job
self.state = state
self.cwd = ctx.worktree if job.worktree else ctx.repo
self.log = ctx.home / "logs" / job.name / f"{dt.date.today().isoformat()}.log"
self.deadline = ctx.host.clock() + job.timeout
self.commits: list[str] = []
self.retried: list[str] = []
self.report: object = None
def note(self, text: str) -> None:
self.log.parent.mkdir(parents=True, exist_ok=True)
with self.log.open("a", encoding="utf-8") as handle:
handle.write(f"# {now_iso()} {text}\n")
def wait_idle(self) -> None:
self.note("host misread suspected, retrying once on an idle host")
wait_for_load(self.ctx.host, self.job.max_load_wait)
def run_step(self, step: Step, argv: list[str] | None = None) -> Outcome:
argv = argv if argv is not None else resolve_argv(step.argv)
stdout = self.cwd / step.stdout if step.stdout else None
def once() -> Outcome:
left = self.deadline - self.ctx.host.clock()
if left <= 0:
return Outcome(124, "job timeout reached")
return execute(argv, self.cwd, self.log, job_env(self.job, step), left, stdout)
outcome = run_with_retry(once, step.ok_codes, self.wait_idle)
if outcome.retried:
self.retried.append(shlex.join(argv))
return outcome
def run_all(self, steps: Sequence[Step], what: str) -> None:
for step in steps:
outcome = self.run_step(step)
if outcome.returncode not in step.ok_codes:
raise AutorunError(
FAILED, f"{what}: {shlex.join(step.argv)} exited {outcome.returncode}"
)
def regate(self) -> bool:
"""The gate on the rebased batch. What it regenerates is computed
twice and committed under the same rules before the push."""
try:
self.run_all(self.job.gate, "gate")
self.check_twice()
self.commit()
except AutorunError as exc:
self.note(f"gate on the rebased batch: {exc.detail}")
return False
return True
def check_twice(self) -> None:
"""Each shipped artifact the gate wrote, computed again and compared."""
scratch = self.cwd / "tmp" / "autorun" / "twice"
for index, item in enumerate(self.job.twice):
artifact = self.cwd / item.artifact
for attempt in (1, 2):
slot = scratch / f"{index}-{attempt}"
if slot.exists():
_remove_scratch(self.cwd, slot.relative_to(self.cwd).as_posix())
if item.glob or artifact.is_dir():
slot.parent.mkdir(parents=True, exist_ok=True)
out = slot
else:
slot.mkdir(parents=True)
out = slot / artifact.name
rel = out.relative_to(self.cwd).as_posix()
outcome = self.run_step(Step(item.argv), resolve_argv(item.argv, rel))
if outcome.returncode != 0:
raise AutorunError(FAILED, f"recomputing {item.artifact} exited "
f"{outcome.returncode}")
diff = differences(artifact, out, item.glob)
if not diff:
break
self.note(f"{item.artifact}: second computation differs on "
f"{', '.join(diff[:10])}")
if attempt == 1:
wait_for_load(self.ctx.host, self.job.max_load_wait)
continue
set_alert(self.state, "host-integrity", True,
f"{item.artifact} computed twice differs", now_iso())
raise AutorunError(FAILED, f"{item.artifact}: two computations disagree "
f"on {', '.join(diff[:5])}")
set_alert(self.state, "host-integrity", False, "", now_iso())
def commit(self) -> None:
changed = changed_files(self.cwd)
for rule in self.job.commits:
files = plan_commit(changed, rule.paths)
if not files:
continue
sha = commit_paths(self.cwd, files, rule)
self.commits.append(sha)
self.note(f"committed {sha[:12]} {rule.subject} ({len(files)} files)")
leftovers = changed_files(self.cwd)
if leftovers:
raise AutorunError(
FAILED, f"{len(leftovers)} paths changed outside every commit rule: "
+ ", ".join(leftovers[:5])
)
def execute(self) -> tuple[str, str]:
ctx, job = self.ctx, self.job
free = free_gb(ctx.repo)
set_alert(self.state, "disk", free < ALERT_FREE_GB,
f"{free:.0f} GB free, under {ALERT_FREE_GB} GB", now_iso())
if free < job.min_free_gb:
return REFUSED, f"{free:.0f} GB free, {job.name} needs {job.min_free_gb:.0f} GB"
if not wait_for_load(ctx.host, job.max_load_wait):
return DEFERRED, f"load stayed above {ctx.host.max_load:.1f}"
if job.commits and ctx.gh is not None:
refresh_breaker(self.state, ctx.gh, now_iso())
if job.commits and self.state.get("breaker", {}).get("open"):
return BLOCKED, "circuit breaker open: a pushed automation commit failed CI"
base = ""
if job.worktree:
ensure_worktree(ctx.repo, ctx.worktree)
seeded = seed_worktree(ctx.repo, ctx.worktree)
if seeded:
self.note(f"hard-linked {', '.join(seeded[:5])}")
base = sync_worktree(ctx.worktree)
try:
self.run_all(job.steps, "step")
self.run_all(job.gate, "gate")
self.check_twice()
if job.commits:
self.commit()
if ctx.push and job.commits:
reason = may_push(self.state)
if reason:
return OK, f"{len(self.commits)} commits, push held: {reason}"
pushed = push_batch(ctx.worktree, base, self.regate)
if pushed:
self.state["push"] = {"sha": pushed, "at": now_iso(), "ci": "pending"}
return OK, f"pushed {pushed[:12]}"
finally:
self.report = read_report(self.cwd, job.report)
for rel in job.scratch:
_remove_scratch(self.cwd, rel)
return OK, f"{len(self.commits)} commits"
def describe(job: Job, ctx: Context) -> list[str]:
"""What a run would do, for --dry-run."""
lines = [f"job {job.name} in {ctx.worktree if job.worktree else ctx.repo}"]
lines += [f" step {shlex.join(s.argv)}" for s in job.steps]
lines += [f" gate {shlex.join(s.argv)}" for s in job.gate]
lines += [f" twice {t.artifact}: {shlex.join(t.argv)}" for t in job.twice]
changed = changed_files(ctx.worktree) if (ctx.worktree / ".git").exists() else []
for rule in job.commits:
files = plan_commit(changed, rule.paths)
lines.append(f" commit {rule.subject!r} paths {', '.join(rule.paths)}")
lines += [f" would commit {f}" for f in files]
lines += [f" scratch {s}" for s in job.scratch]
return lines
def run_job(ctx: Context, name: str) -> tuple[str, str]:
"""Run one job and record it, returning (result, detail)."""
job = ctx.jobs.get(name)
if job is None:
raise SystemExit(f"unknown job {name!r}: {', '.join(sorted(ctx.jobs))}")
if ctx.dry_run:
print("\n".join(describe(job, ctx)))
return OK, "dry run"
state = load_state(ctx.state_path)
runner = Runner(ctx, job, state)
started, clock = now_iso(), ctx.host.clock()
lock = global_lock(ctx.lock_path) if job.lock else contextlib.nullcontext()
try:
with lock:
runner.note(f"start {name}")
try:
result, detail = runner.execute()
except AutorunError as exc:
result, detail = exc.result, exc.detail
except OSError as exc:
result, detail = FAILED, f"{type(exc).__name__}: {exc}"
except LockBusy as exc:
result, detail = DEFERRED, str(exc)
runner.note(f"end {name}: {result} {detail}")
previous = state.setdefault("jobs", {}).get(name, {})
record = {
"last_start": started,
"last_end": now_iso(),
"duration_sec": round(ctx.host.clock() - clock, 1),
"result": result,
"detail": detail,
"commits": runner.commits,
"retried": runner.retried,
"report": runner.report,
"log": str(runner.log),
"last_success": started if result == OK else previous.get("last_success"),
"consecutive_failures": 0 if result in (OK, DEFERRED)
else previous.get("consecutive_failures", 0) + 1,
}
state["jobs"][name] = record
# A job's report can raise an alert of its own: campaign.py refusing to
# run third-party code outside its sandbox.
alert = runner.report.get("alert") if isinstance(runner.report, dict) else None
if result != DEFERRED:
set_alert(state, f"job:{name}", bool(alert), str(alert or ""), now_iso())
prune_logs(ctx.home / "logs")
save_state(ctx.state_path, state)
return result, detail
# Status
def status(ctx: Context) -> dict:
state = load_state(ctx.state_path)
return {
"jobs": {
name: {"schedule": job.schedule, **state.get("jobs", {}).get(name, {})}
for name, job in sorted(ctx.jobs.items())
},
"breaker": state.get("breaker", {"open": False}),
"push": state.get("push", {}),
"alerts": state.get("alerts", {}),
"lock": {"path": str(ctx.lock_path), "busy": lock_busy(ctx.lock_path)},
"free_gb": round(free_gb(ctx.repo), 1),
"worktree": {
"path": str(ctx.worktree),
"exists": (ctx.worktree / ".git").exists(),
"unpushed": unpushed(ctx.worktree),
},
}
def render_status(report: dict) -> str:
lines = []
for name, job in report["jobs"].items():
lines.append(
f"{name:12} {job.get('result', 'never run'):9} {job.get('last_end', ''):25} "
f"{job.get('detail', '')}"
)
counts = (job.get("report") or {}).get("counts") if isinstance(
job.get("report"), dict) else None
if counts:
lines.append(f"{'':12} " + ", ".join(f"{n} {v}" for v, n in sorted(counts.items())))
wt = report["worktree"]
lines.append(f"worktree {wt['path']} ({'present' if wt['exists'] else 'absent'}, "
f"{wt['unpushed']} unpushed commits)")
lines.append(f"lock {report['lock']['path']} ({'busy' if report['lock']['busy'] else 'free'})")
lines.append(f"disk {report['free_gb']} GB free")
breaker = report["breaker"]
lines.append("breaker " + (f"OPEN since {breaker.get('opened_at')}: {breaker.get('reason')}"
if breaker.get("open") else "closed"))
for name, alert in sorted(report["alerts"].items()):
lines.append(f"ALERT {name}: {alert.get('detail', '')} (since {alert.get('since')})")
return "\n".join(lines)
+71
View File
@@ -0,0 +1,71 @@
"""The systemd user units that run the jobs on their schedule."""
from __future__ import annotations
import subprocess
from collections.abc import Callable
from pathlib import Path
from unattended.jobs import AutorunError, FAILED, Job
# Timers
def render_units(
jobs: dict[str, Job], repo: Path, python: str, push: bool = False
) -> dict[str, str]:
"""systemd user units: one service template and a timer per scheduled job."""
flags = " --push" if push else ""
units = {
"retrobios@.service": (
"[Unit]\n"
"Description=retrobios automation job %i\n"
"\n"
"[Service]\n"
"Type=oneshot\n"
f"WorkingDirectory={repo}\n"
"Environment=RETROBIOS_AUTO=1\n"
f"ExecStart={python} {repo / 'scripts' / 'autorun.py'} run %i{flags}\n"
"TimeoutStartSec=6h\n"
"Nice=10\n"
"IOSchedulingClass=idle\n"
"SuccessExitStatus=75\n"
)
}
for name, job in sorted(jobs.items()):
if not job.schedule:
continue
units[f"retrobios-{name}.timer"] = (
"[Unit]\n"
f"Description=retrobios automation: {name}\n"
"\n"
"[Timer]\n"
f"OnCalendar={job.schedule}\n"
"Persistent=true\n"
f"Unit=retrobios@{name}.service\n"
"\n"
"[Install]\n"
"WantedBy=timers.target\n"
)
return units
def install_timers(
unit_dir: Path,
units: dict[str, str],
enable: bool,
systemctl: Callable[[list[str]], int] | None = None,
) -> list[str]:
"""Write the units, and enable the timers only when asked."""
unit_dir.mkdir(parents=True, exist_ok=True)
for name, text in units.items():
(unit_dir / name).write_text(text, encoding="utf-8")
timers = sorted(n for n in units if n.endswith(".timer"))
if enable:
call = systemctl or (lambda args: subprocess.run(
["systemctl", "--user", *args], check=False).returncode)
for args in (["daemon-reload"], ["enable", "--now", *timers]):
if call(args) != 0:
raise AutorunError(FAILED, f"systemctl --user {' '.join(args)} failed")
return timers
+164
View File
@@ -0,0 +1,164 @@
"""Git for the jobs that commit: the automation worktree, the paths each commit
may carry, and the push.
"""
from __future__ import annotations
import fnmatch
import os
import shutil
import subprocess
from collections.abc import Callable, Sequence
from pathlib import Path
from core.paths import REPO_ROOT
from unattended.jobs import AutorunError, BLOCKED, CommitRule, FAILED, token_env
BRANCH = "autorun"
REMOTE = "origin"
TARGET = "main"
# Git
def git(cwd: Path, *args: str, check: bool = True,
env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
proc = subprocess.run(
["git", "-C", str(cwd), *args], capture_output=True, text=True, check=False, env=env,
)
if check and proc.returncode != 0:
raise AutorunError(
FAILED, f"git {' '.join(args)}: {(proc.stderr or proc.stdout).strip()}"
)
return proc
def changed_files(worktree: Path) -> list[str]:
"""Every path git status reports, untracked included, ignored excluded."""
out = git(worktree, "status", "--porcelain=v1", "-z", "--untracked-files=all").stdout
entries = out.split("\0")
paths: list[str] = []
i = 0
while i < len(entries):
entry = entries[i]
i += 1
if len(entry) < 4:
continue
paths.append(entry[3:])
if entry[0] in "RC":
i += 1 # the rename source follows
return sorted(set(paths))
def path_matches(pattern: str, path: str) -> bool:
"""A glob whose `*` stays inside one path segment."""
parts, segments = pattern.split("/"), path.split("/")
return len(parts) == len(segments) and all(
fnmatch.fnmatchcase(s, p) for p, s in zip(parts, segments)
)
def plan_commit(changed: Sequence[str], patterns: Sequence[str]) -> list[str]:
return sorted(p for p in changed if any(path_matches(g, p) for g in patterns))
def commit_paths(worktree: Path, files: Sequence[str], rule: CommitRule) -> str:
"""Commit exactly these files, and return the new commit."""
if not files:
raise ValueError("no file to commit")
git(worktree, "add", "--", *files)
message = ["-m", rule.subject] + (["-m", rule.body] if rule.body else [])
git(worktree, "commit", "--quiet", *message, "--", *files)
return git(worktree, "rev-parse", "HEAD").stdout.strip()
def _hardlink_tree(src: Path, dst: Path) -> None:
if src.is_dir():
shutil.copytree(src, dst, copy_function=os.link, symlinks=True)
else:
dst.parent.mkdir(parents=True, exist_ok=True)
os.link(src, dst)
def seed_worktree(repo: Path, worktree: Path) -> list[str]:
"""Hard-link what git does not carry: a tool deleting a file drops a link."""
from model.largefiles import load_registered_paths
seeded = []
for rel in [".cache/large", "data", *load_registered_paths(repo / ".gitignore")]:
src, dst = repo / rel, worktree / rel
if src.exists() and not dst.exists():
_hardlink_tree(src, dst)
seeded.append(rel)
return seeded
def ensure_worktree(repo: Path, worktree: Path) -> None:
"""Create the automation worktree on branch `autorun`, once."""
if (worktree / ".git").exists():
return
git(repo, "fetch", "--quiet", REMOTE, TARGET)
has_branch = git(
repo, "rev-parse", "--verify", "--quiet", f"refs/heads/{BRANCH}", check=False
).returncode == 0
worktree.parent.mkdir(parents=True, exist_ok=True)
if has_branch:
git(repo, "worktree", "add", str(worktree), BRANCH)
else:
git(repo, "worktree", "add", "-b", BRANCH, str(worktree), f"{REMOTE}/{TARGET}")
def sync_worktree(worktree: Path) -> str:
"""Bring the worktree onto origin/main, and return the base it now sits on."""
leftovers = changed_files(worktree)
if leftovers:
raise AutorunError(
BLOCKED, f"worktree holds {len(leftovers)} uncommitted paths: "
+ ", ".join(leftovers[:5])
)
git(worktree, "fetch", "--quiet", REMOTE, TARGET)
upstream = f"{REMOTE}/{TARGET}"
ahead = int(git(worktree, "rev-list", "--count", f"{upstream}..HEAD").stdout)
if ahead == 0:
git(worktree, "merge", "--ff-only", "--quiet", upstream)
elif (git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode != 0
and git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0):
git(worktree, "rebase", "--abort", check=False)
raise AutorunError(BLOCKED, f"{ahead} automation commits conflict with {upstream}")
return git(worktree, "rev-parse", upstream).stdout.strip()
def unpushed(worktree: Path) -> int:
if not (worktree / ".git").exists():
return 0
proc = git(worktree, "rev-list", "--count", f"{REMOTE}/{TARGET}..HEAD", check=False)
return int(proc.stdout.strip() or 0) if proc.returncode == 0 else 0
def push_batch(worktree: Path, gate_base: str, regate: Callable[[], bool]) -> str:
"""Rebase the night's commits on origin/main, gate again if it moved, push."""
git(worktree, "fetch", "--quiet", REMOTE, TARGET)
upstream = f"{REMOTE}/{TARGET}"
if int(git(worktree, "rev-list", "--count", f"{upstream}..HEAD").stdout) == 0:
return ""
if (git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode != 0
and git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0):
git(worktree, "rebase", "--abort", check=False)
raise AutorunError(BLOCKED, f"rebase onto {upstream} conflicts, batch kept")
if git(worktree, "rev-parse", upstream).stdout.strip() != gate_base and not regate():
raise AutorunError(FAILED, f"gate failed on the batch rebased onto {upstream}")
git(worktree, "push", "--quiet", REMOTE, f"HEAD:{TARGET}", env=token_env())
return git(worktree, "rev-parse", "HEAD").stdout.strip()
# Command line
def main_checkout() -> Path:
"""The main checkout, also when this script runs from a linked worktree."""
proc = git(REPO_ROOT, "rev-parse", "--path-format=absolute", "--git-common-dir",
check=False)
common = Path(proc.stdout.strip()) if proc.returncode == 0 else REPO_ROOT / ".git"
return common.parent
+120 -116
View File
@@ -23,7 +23,11 @@ import unittest.mock
from pathlib import Path
from types import MappingProxyType
import autorun as ar
from unattended import breaker
from unattended import jobs as unattended_jobs
from unattended import runner
from unattended import timers as unattended_timers
from unattended import worktree as unattended_worktree
from core import childenv
from core import hostguard
from core import statefile
@@ -71,7 +75,7 @@ def run_git(cwd: Path, *args: str) -> str:
).stdout
class FakeHost(ar.Host):
class FakeHost(runner.Host):
def __init__(self, loads: list[float] | None = None, cpus: int = 4) -> None:
self.loads = list(loads or [0.0])
self.now = 0.0
@@ -95,44 +99,44 @@ class Scratch(unittest.TestCase):
self.tmp = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp" / "tests"))
self.addCleanup(shutil.rmtree, self.tmp, True)
def context(self, jobs: dict, **kwargs) -> ar.Context:
def context(self, jobs: dict, **kwargs) -> runner.Context:
repo = self.tmp / "repo"
repo.mkdir(exist_ok=True)
parsed = ar.parse_jobs({"jobs": jobs})
parsed = unattended_jobs.parse_jobs({"jobs": jobs})
kwargs.setdefault("host", FakeHost())
return ar.Context(repo=repo, jobs=parsed, lock_path=self.tmp / "auto.lock", **kwargs)
return runner.Context(repo=repo, jobs=parsed, lock_path=self.tmp / "auto.lock", **kwargs)
def state(self, ctx: ar.Context) -> dict:
def state(self, ctx: runner.Context) -> dict:
return json.loads(ctx.state_path.read_text(encoding="utf-8"))
class Registry(Scratch):
def test_the_committed_registry_loads(self):
jobs = ar.load_jobs()
jobs = unattended_jobs.load_jobs()
self.assertIn("nightly", jobs)
self.assertTrue(jobs["nightly"].commits)
self.assertFalse(jobs["disk-check"].lock)
def test_an_unknown_key_is_refused(self):
with self.assertRaises(ValueError):
ar.parse_jobs({"jobs": {"x": {"steps": [], "schedul": "daily"}}})
unattended_jobs.parse_jobs({"jobs": {"x": {"steps": [], "schedul": "daily"}}})
def test_a_subject_the_hook_refuses_is_refused_at_load(self):
for subject in ("chore: fix the broken manifests",
"update things",
"chore: " + "a" * 60):
with self.subTest(subject=subject), self.assertRaises(ValueError):
ar.parse_jobs({"jobs": {"x": {"commits": [
unattended_jobs.parse_jobs({"jobs": {"x": {"commits": [
{"subject": subject, "paths": ["a"]}]}}})
def test_a_job_outside_the_worktree_cannot_commit(self):
with self.assertRaises(ValueError):
ar.parse_jobs({"jobs": {"x": {"worktree": False, "commits": [
unattended_jobs.parse_jobs({"jobs": {"x": {"worktree": False, "commits": [
{"subject": "chore: add a", "paths": ["a"]}]}}})
def test_a_twice_entry_names_its_output(self):
with self.assertRaises(ValueError):
ar.parse_jobs({"jobs": {"x": {"twice": [
unattended_jobs.parse_jobs({"jobs": {"x": {"twice": [
{"artifact": "a.json", "run": [PY, "gen.py"]}]}}})
@@ -149,43 +153,43 @@ class Lock(Scratch):
ctx = self.context({"x": {"worktree": False, "min_free_gb": 0,
"steps": [[PY, "-c", "open('ran', 'w')"]]}})
with hostguard.global_lock(ctx.lock_path):
result, detail = ar.run_job(ctx, "x")
self.assertEqual(result, ar.DEFERRED)
result, detail = runner.run_job(ctx, "x")
self.assertEqual(result, unattended_jobs.DEFERRED)
self.assertIn("held", detail)
self.assertFalse((ctx.repo / "ran").exists())
self.assertEqual(self.state(ctx)["jobs"]["x"]["result"], ar.DEFERRED)
self.assertEqual(self.state(ctx)["jobs"]["x"]["result"], unattended_jobs.DEFERRED)
def test_a_job_that_takes_no_lock_runs_beside_a_holder(self):
ctx = self.context({"x": {"worktree": False, "lock": False, "min_free_gb": 0,
"steps": [[PY, "-c", "open('ran', 'w')"]]}})
with hostguard.global_lock(ctx.lock_path):
self.assertEqual(ar.run_job(ctx, "x")[0], ar.OK)
self.assertEqual(runner.run_job(ctx, "x")[0], unattended_jobs.OK)
self.assertTrue((ctx.repo / "ran").exists())
class Guards(Scratch):
def test_the_load_guard_waits_then_lets_go(self):
host = FakeHost(loads=[3.0, 3.0, 0.5], cpus=4)
self.assertTrue(ar.wait_for_load(host, max_wait=600))
self.assertTrue(runner.wait_for_load(host, max_wait=600))
self.assertEqual(host.slept, [10.0, 10.0])
def test_the_load_guard_gives_up_at_its_deadline(self):
host = FakeHost(loads=[8.0], cpus=4)
self.assertFalse(ar.wait_for_load(host, max_wait=25))
self.assertFalse(runner.wait_for_load(host, max_wait=25))
self.assertEqual(sum(host.slept), 25)
def test_a_busy_host_defers_the_job(self):
ctx = self.context({"x": {"worktree": False, "min_free_gb": 0, "max_load_wait": 0,
"steps": [[PY, "-c", "open('ran', 'w')"]]}},
host=FakeHost(loads=[64.0]))
self.assertEqual(ar.run_job(ctx, "x")[0], ar.DEFERRED)
self.assertEqual(runner.run_job(ctx, "x")[0], unattended_jobs.DEFERRED)
self.assertFalse((ctx.repo / "ran").exists())
def test_a_full_disk_refuses_the_job(self):
ctx = self.context({"x": {"worktree": False, "min_free_gb": 10 ** 9,
"steps": [[PY, "-c", "open('ran', 'w')"]]}})
result, detail = ar.run_job(ctx, "x")
self.assertEqual(result, ar.REFUSED)
result, detail = runner.run_job(ctx, "x")
self.assertEqual(result, unattended_jobs.REFUSED)
self.assertIn("GB free", detail)
self.assertFalse((ctx.repo / "ran").exists())
@@ -193,10 +197,10 @@ class Guards(Scratch):
ctx = self.context({
"bad": {"worktree": False, "min_free_gb": 0, "steps": [[PY, "-c", "raise SystemExit(3)"]]},
})
ar.run_job(ctx, "bad")
ar.run_job(ctx, "bad")
runner.run_job(ctx, "bad")
runner.run_job(ctx, "bad")
record = self.state(ctx)["jobs"]["bad"]
self.assertEqual(record["result"], ar.FAILED)
self.assertEqual(record["result"], unattended_jobs.FAILED)
self.assertEqual(record["consecutive_failures"], 2)
self.assertIsNone(record["last_success"])
@@ -220,7 +224,7 @@ class StepEnvironment(Scratch):
def test_a_step_naming_a_secret_is_refused_at_load(self):
for name in ("GITHUB_TOKEN", "ROMSTATION_PASS", "MY_SECRET"):
with self.subTest(name=name), self.assertRaises(ValueError):
ar.parse_jobs({"jobs": {"x": {"steps": [{"run": [PY, "-V"], "env": [name]}]}}})
unattended_jobs.parse_jobs({"jobs": {"x": {"steps": [{"run": [PY, "-V"], "env": [name]}]}}})
def test_a_network_job_step_sees_no_token(self):
dump = "import json, os; print(json.dumps(dict(os.environ)))"
@@ -230,8 +234,8 @@ class StepEnvironment(Scratch):
with unittest.mock.patch.dict(os.environ, {"GITHUB_TOKEN": "t1", "GH_TOKEN": "t2",
"ROMSTATION_PASS": "p",
"ROMFETCH_CONTENT_DIR": "/c", "EDITOR": "vi"}):
self.assertEqual(ar.run_job(ctx, "x")[0], ar.OK)
given = ar.token_env()
self.assertEqual(runner.run_job(ctx, "x")[0], unattended_jobs.OK)
given = unattended_jobs.token_env()
seen = json.loads((ctx.repo / "env.json").read_text())
self.assertFalse({"GITHUB_TOKEN", "GH_TOKEN", "ROMSTATION_PASS", "EDITOR"} & set(seen))
self.assertEqual((seen["ROMFETCH_CONTENT_DIR"], seen["RETROBIOS_AUTO"]), ("/c", "1"))
@@ -245,7 +249,7 @@ class GithubTokenPerStep(Scratch):
per step, and never to third-party code or the campaign."""
def job(self, run: list[str], name: str = "x") -> dict:
return ar.parse_jobs({"jobs": {name: {"steps": [{"run": run, "github_token": True}]}}})
return unattended_jobs.parse_jobs({"jobs": {name: {"steps": [{"run": run, "github_token": True}]}}})
def test_allowed_on_the_scrapers_and_freshness_scripts(self):
for run in ([PY, "-m", "scripts.scraper.mame_hash_scraper"],
@@ -254,8 +258,8 @@ class GithubTokenPerStep(Scratch):
with self.subTest(run=run):
step = self.job(run)["x"].steps[0]
self.assertTrue(step.github_token)
with unittest.mock.patch.object(ar, "token_env", return_value={"GITHUB_TOKEN": "t1"}):
self.assertEqual(ar.job_env(self.job(run)["x"], step)["GITHUB_TOKEN"], "t1")
with unittest.mock.patch.object(unattended_jobs, "token_env", return_value={"GITHUB_TOKEN": "t1"}):
self.assertEqual(unattended_jobs.job_env(self.job(run)["x"], step)["GITHUB_TOKEN"], "t1")
def test_refused_on_any_other_step(self):
for run in ([PY, "-c", "print(1)"], [PY, "scripts/campaign.py", "run"],
@@ -270,14 +274,14 @@ class GithubTokenPerStep(Scratch):
self.job([PY, "-m", "scripts.scraper.mame_hash_scraper"], name="campaign")
def test_an_undeclared_step_gets_no_token(self):
job = ar.parse_jobs({"jobs": {"x": {"network": True, "steps": [
job = unattended_jobs.parse_jobs({"jobs": {"x": {"network": True, "steps": [
[PY, "-m", "scripts.scraper.mame_hash_scraper"]]}}})["x"]
with unittest.mock.patch.object(ar, "token_env", return_value={"GITHUB_TOKEN": "t1"}), \
with unittest.mock.patch.object(unattended_jobs, "token_env", return_value={"GITHUB_TOKEN": "t1"}), \
unittest.mock.patch.dict(os.environ, {"GITHUB_TOKEN": "t1"}):
self.assertNotIn("GITHUB_TOKEN", ar.job_env(job, job.steps[0]))
self.assertNotIn("GITHUB_TOKEN", unattended_jobs.job_env(job, job.steps[0]))
def test_the_committed_registry(self):
jobs = ar.load_jobs()
jobs = unattended_jobs.load_jobs()
self.assertTrue(all(step.github_token for step in jobs["nightly"].steps))
@@ -287,7 +291,7 @@ class ReportAlert(Scratch):
for message, expected in (("no sandbox", True), ("", False)):
ctx = self.context({"x": {"worktree": False, "min_free_gb": 0, "report": "r.json",
"steps": [[PY, "-c", write, message]]}})
ar.run_job(ctx, "x")
runner.run_job(ctx, "x")
alerts = self.state(ctx).get("alerts", {})
self.assertEqual("job:x" in alerts, expected)
if expected:
@@ -295,35 +299,35 @@ class ReportAlert(Scratch):
class Retry(Scratch):
def _runs(self, *outcomes: ar.Outcome):
def _runs(self, *outcomes: runner.Outcome):
queue = list(outcomes)
calls = []
def run() -> ar.Outcome:
def run() -> runner.Outcome:
calls.append(1)
return queue.pop(0)
return run, calls
def test_a_segfault_is_retried_once_on_an_idle_host(self):
run, calls = self._runs(ar.Outcome(139), ar.Outcome(0))
run, calls = self._runs(runner.Outcome(139), runner.Outcome(0))
waited = []
outcome = ar.run_with_retry(run, (0,), lambda: waited.append(1))
outcome = runner.run_with_retry(run, (0,), lambda: waited.append(1))
self.assertEqual((outcome.returncode, outcome.retried, len(calls), waited),
(0, True, 2, [1]))
def test_a_second_segfault_is_a_failure(self):
run, calls = self._runs(ar.Outcome(-11), ar.Outcome(-11), ar.Outcome(0))
outcome = ar.run_with_retry(run, (0,), lambda: None)
run, calls = self._runs(runner.Outcome(-11), runner.Outcome(-11), runner.Outcome(0))
outcome = runner.run_with_retry(run, (0,), lambda: None)
self.assertEqual((outcome.returncode, len(calls)), (-11, 2))
def test_a_host_misread_message_is_retried(self):
run, calls = self._runs(ar.Outcome(1, "SystemError: unknown opcode"), ar.Outcome(0))
self.assertEqual(ar.run_with_retry(run, (0,), lambda: None).returncode, 0)
run, calls = self._runs(runner.Outcome(1, "SystemError: unknown opcode"), runner.Outcome(0))
self.assertEqual(runner.run_with_retry(run, (0,), lambda: None).returncode, 0)
self.assertEqual(len(calls), 2)
def test_an_ordinary_failure_is_not_retried(self):
run, calls = self._runs(ar.Outcome(1, "KeyError: 'x'"), ar.Outcome(0))
self.assertEqual(ar.run_with_retry(run, (0,), lambda: None).returncode, 1)
run, calls = self._runs(runner.Outcome(1, "KeyError: 'x'"), runner.Outcome(0))
self.assertEqual(runner.run_with_retry(run, (0,), lambda: None).returncode, 1)
self.assertEqual(len(calls), 1)
def test_a_real_segfault_runs_again_and_the_job_passes(self):
@@ -334,7 +338,7 @@ class Retry(Scratch):
" os.kill(os.getpid(), signal.SIGSEGV)\n")
ctx = self.context({"x": {"worktree": False, "min_free_gb": 0,
"steps": [[PY, "-c", crash]]}})
self.assertEqual(ar.run_job(ctx, "x")[0], ar.OK)
self.assertEqual(runner.run_job(ctx, "x")[0], unattended_jobs.OK)
self.assertEqual(len(self.state(ctx)["jobs"]["x"]["retried"]), 1)
@@ -345,20 +349,20 @@ class DoubleComputation(Scratch):
def _run(self, cwd: Path):
def run(argv):
return ar.Outcome(subprocess.run(argv, cwd=cwd, check=False).returncode)
return runner.Outcome(subprocess.run(argv, cwd=cwd, check=False).returncode)
return run
def test_timestamps_aside_two_equal_runs_agree(self):
script = self.tmp / "gen.py"
script.write_text(self.GEN % "1", encoding="utf-8")
diff = ar.twice([PY, str(script), "{out}"], self.tmp / "a.json",
diff = runner.twice([PY, str(script), "{out}"], self.tmp / "a.json",
self.tmp / "b.json", self._run(self.tmp))
self.assertEqual(diff, [])
def test_two_runs_that_disagree_are_named(self):
script = self.tmp / "gen.py"
script.write_text(self.GEN % "random.random()", encoding="utf-8")
diff = ar.twice([PY, str(script), "{out}"], self.tmp / "a.json",
diff = runner.twice([PY, str(script), "{out}"], self.tmp / "a.json",
self.tmp / "b.json", self._run(self.tmp))
self.assertEqual(diff, ["a.json"])
@@ -369,9 +373,9 @@ class DoubleComputation(Scratch):
(a / "x.json").write_text('{"generated": "1", "n": 1}')
(b / "x.json").write_text('{"generated": "2", "n": 1}')
(a / "targets" / "t.json").write_text("{}")
self.assertEqual(ar.differences(a, b, "*.json"), [])
self.assertEqual(runner.differences(a, b, "*.json"), [])
(b / "y.json").write_text("{}")
self.assertEqual(ar.differences(a, b, "*.json"), ["y.json"])
self.assertEqual(runner.differences(a, b, "*.json"), ["y.json"])
def test_a_job_whose_artifact_disagrees_fails_with_an_alert(self):
script = self.tmp / "repo" / "gen.py"
@@ -382,8 +386,8 @@ class DoubleComputation(Scratch):
"gate": [[PY, "gen.py", "db.json"]],
"twice": [{"artifact": "db.json", "run": [PY, "gen.py", "{out}"]}],
}})
result, detail = ar.run_job(ctx, "x")
self.assertEqual(result, ar.FAILED)
result, detail = runner.run_job(ctx, "x")
self.assertEqual(result, unattended_jobs.FAILED)
self.assertIn("two computations disagree", detail)
self.assertIn("host-integrity", self.state(ctx)["alerts"])
@@ -397,7 +401,7 @@ class DoubleComputation(Scratch):
"twice": [{"artifact": "db.json", "run": [PY, "gen.py", "{out}"]}],
}})
statefile.save_state(ctx.state_path, {"alerts": {"host-integrity": {"since": "x"}}})
self.assertEqual(ar.run_job(ctx, "x")[0], ar.OK)
self.assertEqual(runner.run_job(ctx, "x")[0], unattended_jobs.OK)
self.assertNotIn("host-integrity", self.state(ctx).get("alerts", {}))
@@ -423,18 +427,18 @@ class CircuitBreaker(Scratch):
gh, _ = self._gh({"a" * 40: [ci_run("a" * 40, "success", "2026-10-27T02:10:00Z"),
ci_run("a" * 40, "failure", "2026-10-27T02:10:00Z",
"Validate")]}, [])
ar.refresh_breaker(state, gh, "now")
breaker.refresh_breaker(state, gh, "now")
self.assertTrue(state["breaker"]["open"])
self.assertEqual(state["breaker"]["reason"], "Validate")
self.assertIn("ci", state["alerts"])
self.assertEqual(ar.may_push(state), "circuit breaker open")
self.assertEqual(breaker.may_push(state), "circuit breaker open")
def test_runs_still_going_keep_the_push_pending(self):
state = {"push": {"sha": "a" * 40, "ci": "pending"}}
gh, _ = self._gh({"a" * 40: [ci_run("a" * 40, None, "2026-10-27T02:10:00Z")]}, [])
ar.refresh_breaker(state, gh, "now")
breaker.refresh_breaker(state, gh, "now")
self.assertFalse(state["breaker"]["open"])
self.assertIn("has not ended green", ar.may_push(state))
self.assertIn("has not ended green", breaker.may_push(state))
def test_a_later_green_run_on_main_closes_it(self):
state = {"push": {"sha": "a" * 40, "ci": "failure"},
@@ -443,12 +447,12 @@ class CircuitBreaker(Scratch):
"alerts": {"ci": {"since": "x"}}}
pending = [ci_run("b" * 40, None, "2026-10-27T09:00:00Z")]
gh, _ = self._gh({}, pending + [ci_run("a" * 40, "failure", "2026-10-27T02:10:00Z")])
ar.refresh_breaker(state, gh, "now")
breaker.refresh_breaker(state, gh, "now")
self.assertTrue(state["breaker"]["open"])
green = [ci_run("c" * 40, "success", "2026-10-27T10:00:00Z"),
ci_run("c" * 40, "skipped", "2026-10-27T10:00:01Z", "Validate")]
gh, _ = self._gh({}, green + pending)
ar.refresh_breaker(state, gh, "later")
breaker.refresh_breaker(state, gh, "later")
self.assertFalse(state["breaker"]["open"])
self.assertNotIn("ci", state["alerts"])
@@ -457,8 +461,8 @@ class CircuitBreaker(Scratch):
ctx = self.context({"x": {"min_free_gb": 0, "commits": [
{"subject": "chore: add a", "paths": ["a"]}]}}, gh=gh)
statefile.save_state(ctx.state_path, {"push": {"sha": "a" * 40, "ci": "pending"}})
result, _ = ar.run_job(ctx, "x")
self.assertEqual(result, ar.BLOCKED)
result, _ = runner.run_job(ctx, "x")
self.assertEqual(result, unattended_jobs.BLOCKED)
self.assertFalse(ctx.worktree.exists())
@@ -492,28 +496,28 @@ class Origin(Scratch):
def worktree(self) -> Path:
wt = self.repo / ".cache" / "autorun" / "worktree"
ar.ensure_worktree(self.repo, wt)
unattended_worktree.ensure_worktree(self.repo, wt)
return wt
class Commits(Origin):
def test_globs_stay_inside_one_segment(self):
self.assertTrue(ar.path_matches("install/*.json", "install/a.json"))
self.assertFalse(ar.path_matches("install/*.json", "install/targets/a.json"))
self.assertFalse(ar.path_matches("install/*.json", "x/install/a.json"))
self.assertTrue(unattended_worktree.path_matches("install/*.json", "install/a.json"))
self.assertFalse(unattended_worktree.path_matches("install/*.json", "install/targets/a.json"))
self.assertFalse(unattended_worktree.path_matches("install/*.json", "x/install/a.json"))
def test_the_dry_run_names_only_matching_files_and_stages_nothing(self):
wt = self.worktree()
(wt / "database.json").write_text('{"n": 1}\n', encoding="utf-8")
(wt / "install" / "b.json").write_text("{}\n", encoding="utf-8")
(wt / "notes.txt").write_text("x", encoding="utf-8")
ctx = ar.Context(repo=self.repo, lock_path=self.tmp / "l", dry_run=True,
jobs=ar.parse_jobs({"jobs": {"n": {"commits": [{
ctx = runner.Context(repo=self.repo, lock_path=self.tmp / "l", dry_run=True,
jobs=unattended_jobs.parse_jobs({"jobs": {"n": {"commits": [{
"subject": "chore: regenerate collection records",
"paths": ["database.json", "install/*.json"]}]}}}))
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(ar.run_job(ctx, "n"), (ar.OK, "dry run"))
lines = ar.describe(ctx.jobs["n"], ctx)
self.assertEqual(runner.run_job(ctx, "n"), (unattended_jobs.OK, "dry run"))
lines = runner.describe(ctx.jobs["n"], ctx)
would = sorted(line.split("would commit ")[1] for line in lines if "would commit" in line)
self.assertEqual(would, ["database.json", "install/b.json"])
self.assertEqual(run_git(wt, "diff", "--cached", "--name-only"), "")
@@ -524,9 +528,9 @@ class Commits(Origin):
(wt / "database.json").write_text('{"n": 1}\n', encoding="utf-8")
(wt / "other.txt").write_text("x", encoding="utf-8")
run_git(wt, "add", "other.txt")
rule = ar.CommitRule("chore: regenerate collection records", ("database.json",))
files = ar.plan_commit(ar.changed_files(wt), rule.paths)
ar.commit_paths(wt, files, rule)
rule = unattended_jobs.CommitRule("chore: regenerate collection records", ("database.json",))
files = unattended_worktree.plan_commit(unattended_worktree.changed_files(wt), rule.paths)
unattended_worktree.commit_paths(wt, files, rule)
shown = run_git(wt, "show", "--name-only", "--format=%s", "HEAD").split()
self.assertEqual(shown[-1], "database.json")
self.assertNotIn("other.txt", shown)
@@ -536,21 +540,21 @@ class Commits(Origin):
class Worktree(Origin):
def test_it_is_created_on_its_own_branch_and_reused(self):
wt = self.worktree()
self.assertEqual(run_git(wt, "branch", "--show-current").strip(), ar.BRANCH)
self.assertEqual(run_git(wt, "branch", "--show-current").strip(), unattended_worktree.BRANCH)
self.assertEqual(run_git(self.repo, "branch", "--show-current").strip(), "main")
ar.ensure_worktree(self.repo, wt)
unattended_worktree.ensure_worktree(self.repo, wt)
self.assertEqual(len(run_git(self.repo, "worktree", "list").splitlines()), 2)
def test_it_follows_origin_and_stops_on_leftovers(self):
wt = self.worktree()
self.other_commit("x.txt")
base = ar.sync_worktree(wt)
base = unattended_worktree.sync_worktree(wt)
self.assertTrue((wt / "x.txt").exists())
self.assertEqual(base, run_git(wt, "rev-parse", "HEAD").strip())
(wt / "database.json").write_text("changed", encoding="utf-8")
with self.assertRaises(ar.AutorunError) as caught:
ar.sync_worktree(wt)
self.assertEqual(caught.exception.result, ar.BLOCKED)
with self.assertRaises(unattended_jobs.AutorunError) as caught:
unattended_worktree.sync_worktree(wt)
self.assertEqual(caught.exception.result, unattended_jobs.BLOCKED)
self.assertEqual((wt / "database.json").read_text(), "changed")
def test_the_hard_links_share_bytes_with_the_main_checkout(self):
@@ -560,34 +564,34 @@ class Worktree(Origin):
(self.repo / ".cache" / "large").mkdir(parents=True)
(self.repo / ".cache" / "large" / "a.zip").write_bytes(b"z")
wt = self.worktree()
seeded = ar.seed_worktree(self.repo, wt)
seeded = unattended_worktree.seed_worktree(self.repo, wt)
self.assertEqual(sorted(seeded), [".cache/large", "bios/big.bin"])
self.assertTrue(os.path.samefile(wt / "bios" / "big.bin", self.repo / "bios" / "big.bin"))
self.assertEqual(ar.seed_worktree(self.repo, wt), [])
self.assertEqual(unattended_worktree.seed_worktree(self.repo, wt), [])
class Push(Origin):
def _commit(self, wt: Path) -> None:
(wt / "database.json").write_text('{"n": 2}\n', encoding="utf-8")
ar.commit_paths(wt, ["database.json"],
ar.CommitRule("chore: regenerate collection records", ("database.json",)))
unattended_worktree.commit_paths(wt, ["database.json"],
unattended_jobs.CommitRule("chore: regenerate collection records", ("database.json",)))
def test_a_batch_on_an_unmoved_origin_pushes_without_a_second_gate(self):
wt = self.worktree()
base = ar.sync_worktree(wt)
base = unattended_worktree.sync_worktree(wt)
self._commit(wt)
gates = []
pushed = ar.push_batch(wt, base, lambda: gates.append(1) or True)
pushed = unattended_worktree.push_batch(wt, base, lambda: gates.append(1) or True)
self.assertEqual(gates, [])
self.assertEqual(run_git(self.origin, "rev-parse", "main").strip(), pushed)
def test_a_moved_origin_rebases_and_gates_again(self):
wt = self.worktree()
base = ar.sync_worktree(wt)
base = unattended_worktree.sync_worktree(wt)
self._commit(wt)
self.other_commit("y.txt")
gates = []
pushed = ar.push_batch(wt, base, lambda: gates.append(1) or True)
pushed = unattended_worktree.push_batch(wt, base, lambda: gates.append(1) or True)
self.assertEqual(gates, [1])
log = run_git(self.origin, "log", "--format=%s", "main").splitlines()
self.assertEqual(log[:2], ["chore: regenerate collection records", "chore: add y.txt"])
@@ -595,17 +599,17 @@ class Push(Origin):
def test_a_failed_second_gate_pushes_nothing(self):
wt = self.worktree()
base = ar.sync_worktree(wt)
base = unattended_worktree.sync_worktree(wt)
self._commit(wt)
self.other_commit("y.txt")
before = run_git(self.origin, "rev-parse", "main")
with self.assertRaises(ar.AutorunError):
ar.push_batch(wt, base, lambda: False)
with self.assertRaises(unattended_jobs.AutorunError):
unattended_worktree.push_batch(wt, base, lambda: False)
self.assertEqual(run_git(self.origin, "rev-parse", "main"), before)
def test_a_conflicting_batch_is_kept_and_nothing_pushed(self):
wt = self.worktree()
base = ar.sync_worktree(wt)
base = unattended_worktree.sync_worktree(wt)
self._commit(wt)
other = self.tmp / "other"
run_git(self.tmp, "clone", "--quiet", str(self.origin), str(other))
@@ -613,47 +617,47 @@ class Push(Origin):
run_git(other, "commit", "--quiet", "-am", "chore: other database")
run_git(other, "push", "--quiet", "origin", "main")
mine = run_git(wt, "rev-parse", "HEAD")
with self.assertRaises(ar.AutorunError) as caught:
ar.push_batch(wt, base, lambda: True)
self.assertEqual(caught.exception.result, ar.BLOCKED)
with self.assertRaises(unattended_jobs.AutorunError) as caught:
unattended_worktree.push_batch(wt, base, lambda: True)
self.assertEqual(caught.exception.result, unattended_jobs.BLOCKED)
self.assertEqual(run_git(wt, "rev-parse", "HEAD"), mine)
self.assertEqual(ar.changed_files(wt), [])
self.assertEqual(unattended_worktree.changed_files(wt), [])
class RunnerPush(Origin):
def _ctx(self, value: int, push: bool) -> ar.Context:
def _ctx(self, value: int, push: bool) -> runner.Context:
write = f"open('database.json', 'w').write('{{\"n\": {value:d}}}')"
jobs = {"n": {"min_free_gb": 0, "steps": [[PY, "-c", write]], "commits": [
{"subject": "chore: regenerate collection records", "paths": ["database.json"]}]}}
return ar.Context(repo=self.repo, jobs=ar.parse_jobs({"jobs": jobs}),
return runner.Context(repo=self.repo, jobs=unattended_jobs.parse_jobs({"jobs": jobs}),
lock_path=self.tmp / "auto.lock", host=FakeHost(),
gh=lambda _args: [], push=push)
def test_without_push_the_commit_stays_local(self):
before = run_git(self.origin, "rev-parse", "main")
result, detail = ar.run_job(self._ctx(5, push=False), "n")
self.assertEqual((result, detail), (ar.OK, "1 commits"))
result, detail = runner.run_job(self._ctx(5, push=False), "n")
self.assertEqual((result, detail), (unattended_jobs.OK, "1 commits"))
self.assertEqual(run_git(self.origin, "rev-parse", "main"), before)
self.assertEqual(ar.unpushed(self.repo / ".cache" / "autorun" / "worktree"), 1)
self.assertEqual(unattended_worktree.unpushed(self.repo / ".cache" / "autorun" / "worktree"), 1)
def test_a_push_waits_for_the_previous_push_to_end_green(self):
ctx = self._ctx(5, push=True)
result, detail = ar.run_job(ctx, "n")
self.assertEqual(result, ar.OK)
result, detail = runner.run_job(ctx, "n")
self.assertEqual(result, unattended_jobs.OK)
self.assertIn("pushed", detail)
pushed = run_git(self.origin, "rev-parse", "main").strip()
self.assertEqual(self.state(ctx)["push"]["sha"], pushed)
result, detail = ar.run_job(self._ctx(6, push=True), "n")
self.assertEqual(result, ar.OK)
result, detail = runner.run_job(self._ctx(6, push=True), "n")
self.assertEqual(result, unattended_jobs.OK)
self.assertIn("push held", detail)
self.assertEqual(run_git(self.origin, "rev-parse", "main").strip(), pushed)
class Units(Scratch):
def test_one_service_template_and_a_timer_per_scheduled_job(self):
jobs = ar.parse_jobs({"jobs": {
jobs = unattended_jobs.parse_jobs({"jobs": {
"nightly": {"schedule": "*-*-* 02:00"}, "manual": {}}})
units = ar.render_units(jobs, Path("/srv/retrobios"), "/usr/bin/python3")
units = unattended_timers.render_units(jobs, Path("/srv/retrobios"), "/usr/bin/python3")
self.assertEqual(sorted(units), ["retrobios-nightly.timer", "retrobios@.service"])
service = units["retrobios@.service"]
self.assertIn("ExecStart=/usr/bin/python3 /srv/retrobios/scripts/autorun.py run %i\n",
@@ -664,16 +668,16 @@ class Units(Scratch):
self.assertIn("OnCalendar=*-*-* 02:00\n", timer)
self.assertIn("Persistent=true\n", timer)
self.assertIn("Unit=retrobios@nightly.service\n", timer)
pushed = ar.render_units(jobs, Path("/r"), "py", push=True)["retrobios@.service"]
pushed = unattended_timers.render_units(jobs, Path("/r"), "py", push=True)["retrobios@.service"]
self.assertIn("run %i --push\n", pushed)
def test_units_are_written_and_enabled_only_when_asked(self):
units = ar.render_units(ar.load_jobs(), Path("/r"), "py")
units = unattended_timers.render_units(unattended_jobs.load_jobs(), Path("/r"), "py")
calls = []
timers = ar.install_timers(self.tmp, units, False, lambda a: calls.append(a) or 0)
timers = unattended_timers.install_timers(self.tmp, units, False, lambda a: calls.append(a) or 0)
self.assertEqual(calls, [])
self.assertEqual(sorted(p.name for p in self.tmp.iterdir()), sorted(units))
ar.install_timers(self.tmp, units, True, lambda a: calls.append(a) or 0)
unattended_timers.install_timers(self.tmp, units, True, lambda a: calls.append(a) or 0)
self.assertEqual(calls, [["daemon-reload"], ["enable", "--now", *timers]])
@@ -938,18 +942,18 @@ class BiosIntegrity(Scratch):
self.flip(rel)
Path(self.db_path).write_text(json.dumps(self.db), encoding="utf-8")
script = str(REPO_ROOT / "scripts" / "bios_integrity.py")
ctx = ar.Context(
ctx = runner.Context(
repo=self.repo, lock_path=self.tmp / "auto.lock", host=FakeHost(),
jobs=ar.parse_jobs({"jobs": {"bios-integrity": {
jobs=unattended_jobs.parse_jobs({"jobs": {"bios-integrity": {
"worktree": False, "min_free_gb": 0,
"steps": [{"run": [PY, script, "--apply", "--json", "--db", self.db_path],
"stdout": "tmp/autorun/bios-integrity.json"}],
"report": "tmp/autorun/bios-integrity.json"}}}))
self.assertEqual(ar.run_job(ctx, "bios-integrity")[0], ar.OK)
self.assertEqual(runner.run_job(ctx, "bios-integrity")[0], unattended_jobs.OK)
report = self.state(ctx)["jobs"]["bios-integrity"]["report"]
self.assertEqual(report["counts"], {"restored": 1})
self.assertEqual(report["findings"][0]["path"], rel)
self.assertIn("1 restored", ar.render_status(ar.status(ctx)))
self.assertIn("1 restored", runner.render_status(runner.status(ctx)))
@property
def db_path(self) -> str:
@@ -965,9 +969,9 @@ class SubjectsFollowTheRepositoryRules(unittest.TestCase):
for subject in ("chore: fix the broken manifests", "update things", "chore: " + "a" * 60):
with self.subTest(subject=subject):
self.assertEqual(ar.check_subject(subject), commitrules.problems(subject))
self.assertTrue(ar.check_subject(subject))
self.assertEqual(ar.check_subject("chore: tidy the cache"), [])
self.assertEqual(unattended_jobs.check_subject(subject), commitrules.problems(subject))
self.assertTrue(unattended_jobs.check_subject(subject))
self.assertEqual(unattended_jobs.check_subject("chore: tidy the cache"), [])
def test_review_numbers_are_refused(self):
"""47 pushed subjects pointed at a numbered private review, which no
+3 -3
View File
@@ -28,7 +28,7 @@ from types import MappingProxyType
import yaml
import autorun
from unattended import jobs
import campaign
import core_probe
from core import hostguard
@@ -1009,7 +1009,7 @@ class Findings(Workspace):
("chore: add campaign measurements", ["measurements/fake.jsonl", "measurements/findings.jsonl"]),
("chore: apply tested fields to fake", ["emulators/fake.yml"])])
for subject, _ in plan:
self.assertEqual(autorun.check_subject(subject), [], subject)
self.assertEqual(jobs.check_subject(subject), [], subject)
# A file someone had changed before the pass is left to them.
self.assertEqual(self.c.plan_commits({"emulators/fake.yml"})[1:], [])
out = io.StringIO()
@@ -1051,7 +1051,7 @@ class Registry(unittest.TestCase):
def test_no_job_runs_a_standing_campaign(self) -> None:
"""A daily pass over every profile contradicted the rule that probes
run on demand, for a question that names its profiles."""
for name, job in autorun.load_jobs().items():
for name, job in jobs.load_jobs().items():
for step in [*job.steps, *job.gate]:
with self.subTest(job=name):
self.assertNotIn("scripts/campaign.py", step.argv)
+4 -3
View File
@@ -1927,7 +1927,8 @@ class TheInstallerSamplesTravelWithTheManifests(unittest.TestCase):
place for the samples the gate's pipeline rewrites."""
def test_the_pages_and_the_nightly_carry_them(self):
import autorun
from unattended import jobs
from unattended import worktree
guide = (WIKI / "testing-guide.md").read_text(encoding="utf-8")
for name in ("wiki/installer.md", "derivable.json", "generate_installer_doc.py"):
@@ -1935,11 +1936,11 @@ class TheInstallerSamplesTravelWithTheManifests(unittest.TestCase):
tools = (WIKI / "tools.md").read_text(encoding="utf-8")
manifests = tools.index("--all --manifest --output-dir install/")
self.assertIn("generate_installer_doc.py", tools[manifests:manifests + 300])
nightly = autorun.load_jobs()["nightly"]
nightly = jobs.load_jobs()["nightly"]
patterns = [p for rule in nightly.commits for p in rule.paths]
for path in ("wiki/installer.md", "derivable.json", "install/retroarch.json"):
with self.subTest(path=path):
self.assertTrue(any(autorun.path_matches(p, path) for p in patterns))
self.assertTrue(any(worktree.path_matches(p, path) for p in patterns))
class TheRemovalProofsAreTheExportersOwn(unittest.TestCase):
+15 -35
View File
@@ -3,10 +3,8 @@
A module imports only from its own layer or below. core is the standard
library's only client, model loads data, resolve turns declarations into
files, the domain packages build on them, and the top-level scripts are the
commands. Library code still waiting at the top level is listed in
NOT_YET_PACKAGED, and the edges a domain package still has to it in
PENDING_TOP_LEVEL_IMPORTS: both lists must be exact, so a later move that
empties an entry also removes it.
commands. No module imports a command: library code lives in a package, and
the only top-level files other modules may import are the SELF_CONTAINED ones.
"""
from __future__ import annotations
@@ -21,7 +19,7 @@ SCRIPTS = Path(__file__).resolve().parent.parent / "scripts"
PACKAGE_LAYERS = {"core": 0, "model": 1, "resolve": 2, "packs": 3, "scraper": 3, "exporter": 3,
"probes": 3, "profiling": 3, "sitegen": 3, "romrecipes": 3, "acquire": 3,
"release": 3, "installer_build": 3, "devtools": 3}
"release": 3, "installer_build": 3, "devtools": 3, "unattended": 3}
LIBRARY_LAYER = 3
COMMAND_LAYER = 4
@@ -31,7 +29,8 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = {
# A search starts from what verify finds missing.
"acquire": frozenset({"packs"}),
"packs": frozenset(),
"probes": frozenset(),
# A campaign commits its findings the way the unattended jobs commit.
"probes": frozenset({"unattended"}),
"profiling": frozenset(),
"romrecipes": frozenset(),
# The site prints the recipe counts and the dump-catalog coverage report
@@ -43,29 +42,15 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = {
# The launcher archives are written by the pack member writer.
"installer_build": frozenset({"packs"}),
"devtools": frozenset(),
# A job's commit subjects are checked against the repository's commit rules.
"unattended": frozenset({"devtools"}),
}
# Top-level modules other modules of scripts/ import: library code that a
# later wave moves into a package.
NOT_YET_PACKAGED = frozenset({
"autorun",
})
# Top-level files that stay whole at their path although packages import them:
# the file is the unit. core_probe.py runs alone in its sandbox, where nothing
# beside the standard library exists, and its records name and hash this file.
SELF_CONTAINED = frozenset({"core_probe"})
# Imports from a package module to a top-level module, left for the wave that
# packages the top-level side.
PENDING_TOP_LEVEL_IMPORTS = frozenset({
# autorun, the job runner, keeps its git helpers, which raise its own error.
("probes.campaign", "autorun"),
("probes.gate", "autorun"),
("probes.host", "autorun"),
("probes.packprobe", "autorun"),
})
def module_name(path: Path) -> str:
parts = list(path.relative_to(SCRIPTS).with_suffix("").parts)
@@ -135,7 +120,7 @@ def layer_of(name: str) -> int:
top = name.split(".")[0]
if "." in name or top in PACKAGE_LAYERS:
return PACKAGE_LAYERS[top]
return LIBRARY_LAYER if name in NOT_YET_PACKAGED | SELF_CONTAINED else COMMAND_LAYER
return LIBRARY_LAYER if name in SELF_CONTAINED else COMMAND_LAYER
def is_package_module(name: str) -> bool:
@@ -217,11 +202,9 @@ class ImportLayers(unittest.TestCase):
self.assertIsNone(find_cycle(nodes, self.graph.internal))
def test_package_modules_import_no_top_level_module(self):
found = {(src, dst) for src, dst in self.graph.edges()
if is_package_module(src) and not is_package_module(dst) and dst not in SELF_CONTAINED}
self.assertEqual(sorted(found - PENDING_TOP_LEVEL_IMPORTS), [])
self.assertEqual(sorted(PENDING_TOP_LEVEL_IMPORTS - found), [],
"a pending import no longer exists: remove it from the list")
found = sorted(f"{src} imports {dst}" for src, dst in self.graph.edges()
if is_package_module(src) and not is_package_module(dst) and dst not in SELF_CONTAINED)
self.assertEqual(found, [])
def test_core_imports_the_standard_library_only(self):
stdlib = set(sys.stdlib_module_names)
@@ -250,13 +233,10 @@ class ImportLayers(unittest.TestCase):
found.append(f"{name} imports from {node.module}")
self.assertEqual(found, [])
def test_not_yet_packaged_is_the_exact_set_of_top_level_libraries(self):
imported = {dst for _src, dst in self.graph.edges()
if not is_package_module(dst) and dst not in SELF_CONTAINED}
self.assertEqual(sorted(imported - NOT_YET_PACKAGED), [],
"a top-level module became a library: package it or list it")
self.assertEqual(sorted(NOT_YET_PACKAGED - imported), [],
"listed modules no longer imported by scripts/ (moved, or now a command only)")
def test_no_module_imports_a_command(self):
found = sorted(f"{src} imports {dst}" for src, dst in self.graph.edges()
if not is_package_module(dst) and dst not in SELF_CONTAINED)
self.assertEqual(found, [], "a top-level module became a library: move its code into a package")
if __name__ == "__main__":