mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-22 17:47:48 -06:00
refactor: move refresh_stale logic into freshness
This commit is contained in:
1 parent
7203b5be84
commit
5be72484d8
13 files changed
+693
-600
No files matched your search
@@ -1 +1 @@
|
||||
"""Freshness checks: every transcribed layer confronted with what its upstream serves today."""
|
||||
"""What has an upstream and whether ours is behind it."""
|
||||
@@ -0,0 +1,153 @@
|
||||
"""The command that pulls the upstream of each stale subject, by area."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from functools import lru_cache
|
||||
|
||||
from core.paths import DATA_DIRS_FILE, REPO_ROOT
|
||||
from model.registry import data_dir_registry_at
|
||||
|
||||
DATA_DIRS_REGISTRY = REPO_ROOT / DATA_DIRS_FILE
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _data_dir_keys() -> frozenset[str]:
|
||||
"""The entries refresh_data_dirs.py --key accepts."""
|
||||
return frozenset(data_dir_registry_at(DATA_DIRS_REGISTRY, required=True))
|
||||
|
||||
|
||||
def verify_command(platform: str) -> list[str]:
|
||||
"""The check a rescraped platform file is read with before it is kept."""
|
||||
return [sys.executable, "scripts/verify.py", "--platform", platform]
|
||||
|
||||
|
||||
def truth_refresh(platform: str) -> list[str]:
|
||||
return [sys.executable, "scripts/generate_truth.py", "--platform", platform]
|
||||
|
||||
|
||||
def native_refresh(platform: str) -> list[str]:
|
||||
return [
|
||||
sys.executable,
|
||||
"scripts/export_native.py",
|
||||
"--platform",
|
||||
platform,
|
||||
"--refresh-cache",
|
||||
]
|
||||
|
||||
|
||||
def export_refresh(platform: str) -> list[str]:
|
||||
"""Rewrite the published export from the refreshed original."""
|
||||
return [sys.executable, "scripts/export_native.py", "--platform", platform]
|
||||
|
||||
|
||||
def _platform_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
|
||||
entry = registry.get(subject) or {}
|
||||
scraper = entry.get("scraper")
|
||||
if not scraper:
|
||||
return None
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
f"scripts.scraper.{scraper}_scraper",
|
||||
"-o",
|
||||
f"platforms/{subject}.yml",
|
||||
*(str(a) for a in entry.get("rescrape_args") or ()),
|
||||
]
|
||||
|
||||
|
||||
def _target_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
|
||||
# "<platform> cores" rows list buildbot names without a profile. No
|
||||
# scraper fixes that, a human writes `cores:` or _overrides.yml.
|
||||
if subject.endswith(" cores"):
|
||||
return None
|
||||
entry = registry.get(subject) or {}
|
||||
module = entry.get("target_scraper")
|
||||
if not module:
|
||||
return None
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
f"scripts.scraper.targets.{module}_scraper",
|
||||
"-o",
|
||||
f"platforms/targets/{subject}.yml",
|
||||
]
|
||||
|
||||
|
||||
def _data_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
|
||||
if subject not in _data_dir_keys():
|
||||
# "_data_dirs.yml" and "buildbot system" name the registry and
|
||||
# what it does not track yet: a human adds the entry.
|
||||
return None
|
||||
return [
|
||||
sys.executable,
|
||||
"scripts/refresh_data_dirs.py",
|
||||
"--key",
|
||||
subject,
|
||||
"--force",
|
||||
]
|
||||
|
||||
|
||||
def _catalog_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
|
||||
if subject == "mame recipes":
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"scripts.scraper.romset_dat_importer",
|
||||
"--source",
|
||||
"mame",
|
||||
"--fetch",
|
||||
]
|
||||
if subject == "fbneo recipes":
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"scripts.scraper.romset_dat_importer",
|
||||
"--source",
|
||||
"fbneo",
|
||||
"--fetch",
|
||||
]
|
||||
if subject in ("no-intro games", "redump games"):
|
||||
# The game DATs download without a browser, unlike the BIOS ones.
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"scripts.scraper.game_dat_importer",
|
||||
"--source",
|
||||
subject.split()[0],
|
||||
"--fetch",
|
||||
"--refresh",
|
||||
"--floor",
|
||||
]
|
||||
# redump / no-intro / tosec need manual DAT download.
|
||||
return None
|
||||
|
||||
|
||||
_AREA_COMMANDS: dict[str, Callable[[str, dict[str, dict]], list[str] | None]] = {
|
||||
"platforms": _platform_command,
|
||||
"targets": _target_command,
|
||||
"data": _data_command,
|
||||
"catalogs": _catalog_command,
|
||||
}
|
||||
|
||||
|
||||
def command_for(
|
||||
area: str, subject: str, registry: dict[str, dict]
|
||||
) -> list[str] | None:
|
||||
"""Map a stale finding to its refresh command, or None if manual."""
|
||||
if area == "native":
|
||||
# export_native refuses a truth older than the profiles, so the
|
||||
# truth comes first and the original follows (Job.then).
|
||||
return truth_refresh(subject)
|
||||
|
||||
if area == "ci" and subject == "install.py pin":
|
||||
# The pin is the hash of the committed install.py, nothing to judge.
|
||||
return [sys.executable, "scripts/pin_installer.py"]
|
||||
|
||||
builder = _AREA_COMMANDS.get(area)
|
||||
if builder:
|
||||
return builder(subject, registry)
|
||||
|
||||
# coreinfo, ci, profiles: never auto-refresh.
|
||||
return None
|
||||
@@ -0,0 +1,54 @@
|
||||
"""The check_freshness.py --json report a refresh starts from, run or read from a file."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from core.paths import REPO_ROOT
|
||||
from freshness.stalejob import AUTO_AREAS, MANUAL_AREAS
|
||||
|
||||
CHECK_FRESHNESS = REPO_ROOT / "scripts" / "check_freshness.py"
|
||||
|
||||
|
||||
def run_check_freshness(areas: tuple[str, ...], extra: list[str]) -> list[dict]:
|
||||
"""Run check_freshness.py --json and return its findings."""
|
||||
cmd = [sys.executable, str(CHECK_FRESHNESS), "--json"]
|
||||
if areas and set(areas) != set(AUTO_AREAS + MANUAL_AREAS):
|
||||
cmd += ["--only", ",".join(areas)]
|
||||
cmd += extra
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd, cwd=REPO_ROOT, capture_output=True, text=True, check=False, timeout=1800
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise RuntimeError(
|
||||
f"check_freshness.py did not finish in {exc.timeout:.0f} s: run "
|
||||
f"`{' '.join(cmd[1:])} > report.json` alone, then pass --findings report.json"
|
||||
) from exc
|
||||
# Exit 1 is the STALE rows, and also a crash: only a JSON list on stdout
|
||||
# tells them apart, and the crash's own message is on stderr.
|
||||
try:
|
||||
findings = json.loads(proc.stdout) if proc.returncode in (0, 1) else None
|
||||
except json.JSONDecodeError:
|
||||
findings = None
|
||||
if not isinstance(findings, list):
|
||||
tail = (proc.stderr or proc.stdout).strip().splitlines()[-3:]
|
||||
raise RuntimeError(
|
||||
f"check_freshness.py failed (exit {proc.returncode}):\n"
|
||||
+ "\n".join(tail or ["(no output)"])
|
||||
)
|
||||
return findings
|
||||
|
||||
|
||||
def load_findings(path: Path, areas: tuple[str, ...]) -> list[dict]:
|
||||
"""A saved check_freshness.py --json report, kept to the asked areas."""
|
||||
try:
|
||||
findings = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
raise RuntimeError(f"cannot read findings from {path}: {exc}") from exc
|
||||
if not isinstance(findings, list):
|
||||
raise RuntimeError(f"{path} is not a check_freshness.py --json report")
|
||||
return [f for f in findings if f.get("area") in areas]
|
||||
@@ -0,0 +1,37 @@
|
||||
"""The refresh job a stale row becomes, its result, and the areas refreshed or listed."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
LOG_DIR = REPO_ROOT / "tmp" / "refresh_stale"
|
||||
|
||||
AUTO_AREAS = ("platforms", "native", "targets", "data", "catalogs")
|
||||
# A rom-folder pin is moved by hand in platforms/romfolders/_sources/,
|
||||
# then `python -m scripts.scraper.romfolders --setup NAME` reads it again.
|
||||
MANUAL_AREAS = ("romfolders", "coreinfo", "ci", "profiles")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Job:
|
||||
"""One refresh action derived from a stale finding."""
|
||||
|
||||
area: str
|
||||
subject: str
|
||||
command: list[str]
|
||||
log_path: Path
|
||||
# Commands run after `command`, in order, only while each one succeeds.
|
||||
then: tuple[tuple[str, ...], ...] = ()
|
||||
# Platforms whose rescrape job must end before this one starts.
|
||||
after: frozenset[str] = frozenset()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class JobResult:
|
||||
job: Job
|
||||
returncode: int
|
||||
duration: float
|
||||
tail: str # last non-empty line of stderr or stdout
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Stale findings split into refresh jobs, rows for a human, and rows left alone."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from core.paths import REPO_ROOT
|
||||
from freshness.stalecommands import (
|
||||
command_for,
|
||||
export_refresh,
|
||||
native_refresh,
|
||||
truth_refresh,
|
||||
verify_command,
|
||||
)
|
||||
from freshness.stalejob import LOG_DIR, Job
|
||||
from model.platforms import inheritance_chain
|
||||
from model.registry import load_platform_registry
|
||||
|
||||
PLATFORMS_REGISTRY = REPO_ROOT / "platforms" / "_registry.yml"
|
||||
|
||||
|
||||
def platform_registry() -> dict[str, dict]:
|
||||
"""Return the platforms map from _registry.yml, read once at startup."""
|
||||
return load_platform_registry(PLATFORMS_REGISTRY.parent, required=True)
|
||||
|
||||
|
||||
def platform_parents(registry: dict[str, dict]) -> dict[str, str]:
|
||||
"""Platform to the platform its YAML inherits from."""
|
||||
parents: dict[str, str] = {}
|
||||
for name in registry:
|
||||
chain = inheritance_chain(name, REPO_ROOT / "platforms")
|
||||
if len(chain) > 1:
|
||||
parents[name] = chain[1]
|
||||
return parents
|
||||
|
||||
|
||||
def _ancestors(platform: str, parents: dict[str, str]) -> set[str]:
|
||||
found: set[str] = set()
|
||||
while platform in parents and parents[platform] not in found:
|
||||
platform = parents[platform]
|
||||
found.add(platform)
|
||||
return found
|
||||
|
||||
|
||||
def _slug(subject: str) -> str:
|
||||
"""A safe filename stem for a finding's subject."""
|
||||
return re.sub(r"[^A-Za-z0-9_.-]+", "_", subject).strip("_") or "job"
|
||||
|
||||
|
||||
def plan_jobs(
|
||||
findings: list[dict],
|
||||
registry: dict[str, dict],
|
||||
parents: dict[str, str] | None = None,
|
||||
) -> tuple[list[Job], list[dict], list[dict]]:
|
||||
"""Split findings into (refreshable jobs, surfaced-only, ignored).
|
||||
|
||||
Surfaced-only entries carry stale state that only a human can resolve
|
||||
(new .info file, manual DAT download, PyPI bump). Ignored entries are
|
||||
anything not STALE (OK, SKIPPED, UNKNOWN, ERROR). ERROR is also surfaced
|
||||
so the final report mentions it. ``parents`` maps a platform to the one
|
||||
it inherits from: a child's jobs wait for its rescraped ancestors, and a
|
||||
child no row names gets its export rewritten after them.
|
||||
"""
|
||||
if parents is None:
|
||||
parents = platform_parents(registry)
|
||||
jobs: list[Job] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
surfaced: list[dict] = []
|
||||
ignored: list[dict] = []
|
||||
# A platform about to be rescraped refreshes its cached original itself,
|
||||
# after the scrape: a separate native job would race the scraper.
|
||||
rescraped = {
|
||||
str(f.get("subject") or "")
|
||||
for f in findings
|
||||
if f.get("status") == "STALE"
|
||||
and f.get("area") == "platforms"
|
||||
and command_for("platforms", str(f.get("subject") or ""), registry)
|
||||
}
|
||||
|
||||
for finding in findings:
|
||||
status = finding.get("status")
|
||||
area = str(finding.get("area") or "")
|
||||
subject = str(finding.get("subject") or "")
|
||||
|
||||
if status == "ERROR":
|
||||
surfaced.append(finding)
|
||||
continue
|
||||
if status != "STALE":
|
||||
ignored.append(finding)
|
||||
continue
|
||||
|
||||
if area == "native" and subject in rescraped:
|
||||
ignored.append(finding)
|
||||
continue
|
||||
|
||||
command = command_for(area, subject, registry)
|
||||
if command is None:
|
||||
surfaced.append(finding)
|
||||
continue
|
||||
|
||||
key = (area, " ".join(command))
|
||||
if key in seen:
|
||||
# Two findings funneling to the same command (e.g. mame recipes
|
||||
# listed twice) collapse to one job.
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
log = LOG_DIR / f"{area}__{_slug(subject)}.log"
|
||||
then: tuple[tuple[str, ...], ...] = ()
|
||||
if area == "platforms":
|
||||
# The truth reads the platform file: regenerated first, or the
|
||||
# native refresh refuses it as older than the profiles.
|
||||
then = (
|
||||
tuple(truth_refresh(subject)),
|
||||
tuple(native_refresh(subject)),
|
||||
tuple(export_refresh(subject)),
|
||||
tuple(verify_command(subject)),
|
||||
)
|
||||
elif area == "native":
|
||||
then = (tuple(native_refresh(subject)), tuple(export_refresh(subject)))
|
||||
after: frozenset[str] = frozenset()
|
||||
if area in ("platforms", "native"):
|
||||
after = frozenset(_ancestors(subject, parents) & rescraped)
|
||||
jobs.append(
|
||||
Job(area=area, subject=subject, command=command, log_path=log,
|
||||
then=then, after=after)
|
||||
)
|
||||
|
||||
# The export of a child is built from its parent's file: rewritten once
|
||||
# the parent is, or the next check reports it stale.
|
||||
covered = {j.subject for j in jobs if j.area in ("platforms", "native")}
|
||||
for child in sorted(parents):
|
||||
after = frozenset(_ancestors(child, parents) & rescraped)
|
||||
if not after or child in covered:
|
||||
continue
|
||||
jobs.append(Job(
|
||||
area="native",
|
||||
subject=child,
|
||||
command=truth_refresh(child),
|
||||
log_path=LOG_DIR / f"native__{_slug(child)}.log",
|
||||
then=(tuple(native_refresh(child)), tuple(export_refresh(child))),
|
||||
after=after,
|
||||
))
|
||||
|
||||
return jobs, surfaced, ignored
|
||||
@@ -0,0 +1,151 @@
|
||||
"""The plan and the outcome of a refresh, as a table for a human or as JSON."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from core.paths import REPO_ROOT
|
||||
from freshness.stalejob import Job, JobResult
|
||||
|
||||
VERIFY_MARK = "scripts/verify.py --platform"
|
||||
|
||||
|
||||
def verify_summary(path: Path) -> str:
|
||||
"""First line verify printed in a job log, empty when it did not run."""
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return ""
|
||||
lines = text.splitlines()
|
||||
for index, line in enumerate(lines):
|
||||
if line.startswith("$ ") and VERIFY_MARK in line:
|
||||
return next(
|
||||
(rest.strip() for rest in lines[index + 1:]
|
||||
if rest.strip() and not rest.startswith("$ ")),
|
||||
"",
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def _by_area(jobs: list[Job]) -> list[Job]:
|
||||
return sorted(jobs, key=lambda j: (j.area, j.subject))
|
||||
|
||||
|
||||
def plan_payload(jobs: list[Job], surfaced: list[dict], ignored: list[dict]) -> dict:
|
||||
"""What --dry-run --json prints: the planned jobs and the rows for a human."""
|
||||
return {
|
||||
"planned": [
|
||||
{
|
||||
"area": job.area,
|
||||
"subject": job.subject,
|
||||
"command": job.command,
|
||||
"after": sorted(job.after),
|
||||
"then": [list(command) for command in job.then],
|
||||
}
|
||||
for job in _by_area(jobs)
|
||||
],
|
||||
"surfaced": surfaced,
|
||||
"ignored_count": len(ignored),
|
||||
}
|
||||
|
||||
|
||||
def plan_text(jobs: list[Job], surfaced: list[dict], ignored: list[dict]) -> str:
|
||||
"""What --dry-run prints: each job with its waits and follow-ups."""
|
||||
lines = [f"\n[plan] {len(jobs)} refreshable, {len(surfaced)} manual, "
|
||||
f"{len(ignored)} already clean/skipped"]
|
||||
for job in _by_area(jobs):
|
||||
lines.append(f" {job.area:10} {job.subject:28} {' '.join(job.command)}")
|
||||
if job.after:
|
||||
lines.append(f" {'':10} {'':28} after {', '.join(sorted(job.after))}")
|
||||
lines.extend(f" {'':10} {'':28} then {' '.join(command)}" for command in job.then)
|
||||
if surfaced:
|
||||
lines.append("\n[manual review needed]")
|
||||
lines.extend(f" {f.get('status', ''):7} {f.get('area', ''):10} "
|
||||
f"{f.get('subject', ''):28} {str(f.get('detail') or '')[:100]}"
|
||||
for f in surfaced)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def results_payload(results: list[JobResult], surfaced: list[dict], ignored: list[dict]) -> dict:
|
||||
"""What --json prints after a run: each job's exit, duration, log and last line."""
|
||||
return {
|
||||
"refreshed": [
|
||||
{
|
||||
"area": r.job.area,
|
||||
"subject": r.job.subject,
|
||||
"returncode": r.returncode,
|
||||
"duration_sec": round(r.duration, 2),
|
||||
"log": str(r.job.log_path.relative_to(REPO_ROOT)),
|
||||
"tail": r.tail,
|
||||
}
|
||||
for r in results
|
||||
],
|
||||
"surfaced": surfaced,
|
||||
"ignored_count": len(ignored),
|
||||
}
|
||||
|
||||
|
||||
def render(
|
||||
results: list[JobResult],
|
||||
surfaced: list[dict],
|
||||
ignored: list[dict],
|
||||
) -> str:
|
||||
"""Human-readable table of what ran and what still needs a human."""
|
||||
lines: list[str] = []
|
||||
subject_w = max((len(r.job.subject) for r in results), default=10)
|
||||
subject_w = min(max(subject_w, 10), 44)
|
||||
|
||||
if results:
|
||||
lines.append("\n[refreshed]")
|
||||
lines.append(
|
||||
f" {'STATUS':8} {'AREA':10} {'SUBJECT':{subject_w}} "
|
||||
f"{'DUR':>7} LOG"
|
||||
)
|
||||
for r in sorted(results, key=lambda x: (x.job.area, x.job.subject)):
|
||||
status = "OK" if r.returncode == 0 else f"FAIL ({r.returncode})"
|
||||
rel_log = r.job.log_path.relative_to(REPO_ROOT)
|
||||
lines.append(
|
||||
f" {status:8} {r.job.area:10} {r.job.subject[:subject_w]:{subject_w}} "
|
||||
f"{r.duration:6.1f}s {rel_log}"
|
||||
)
|
||||
if r.returncode != 0 and r.tail:
|
||||
lines.append(f" -> {r.tail}")
|
||||
|
||||
rescraped = sorted(
|
||||
(r for r in results if r.job.area == "platforms" and r.returncode == 0),
|
||||
key=lambda r: r.job.subject,
|
||||
)
|
||||
if rescraped:
|
||||
lines.append(
|
||||
"\n[verify] a rescrape can add systems: read each report "
|
||||
"before keeping platforms/<name>.yml"
|
||||
)
|
||||
for r in rescraped:
|
||||
summary = verify_summary(r.job.log_path) or "(no verify output)"
|
||||
lines.append(f" {r.job.subject:12} {summary}")
|
||||
lines.append(
|
||||
f" {'':12} python scripts/verify.py --platform {r.job.subject}"
|
||||
)
|
||||
|
||||
if surfaced:
|
||||
lines.append("\n[manual review needed]")
|
||||
for f in surfaced:
|
||||
detail = str(f.get("detail") or "").strip()
|
||||
lines.append(
|
||||
f" {f.get('status', ''):7} {f.get('area', ''):10} "
|
||||
f"{f.get('subject', ''):28} {detail[:100]}"
|
||||
)
|
||||
|
||||
if ignored:
|
||||
counts: dict[str, int] = {}
|
||||
for f in ignored:
|
||||
counts[str(f.get("status") or "?")] = counts.get(str(f.get("status") or "?"), 0) + 1
|
||||
parts = ", ".join(f"{n} {status.lower()}" for status, n in sorted(counts.items()))
|
||||
lines.append(f"\n[ignored] {parts}")
|
||||
|
||||
ok = sum(1 for r in results if r.returncode == 0)
|
||||
fail = len(results) - ok
|
||||
lines.append(
|
||||
f"\nREFRESH: {ok} ok, {fail} failed, {len(surfaced)} to review manually"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Refresh jobs run in parallel, each after the rescrapes it waits for, logged to tmp/."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
||||
from pathlib import Path
|
||||
|
||||
from core.paths import REPO_ROOT
|
||||
from freshness.stalejob import Job, JobResult
|
||||
|
||||
JOB_TIMEOUT = 1800 # 30 minutes per refresher, scrapers rarely exceed 10
|
||||
|
||||
|
||||
def github_token_env() -> dict[str, str]:
|
||||
"""Hand `gh auth token` to the subprocess environment.
|
||||
|
||||
emudeck and retropie target scrapers hit the GitHub API. Without a token
|
||||
the unauthenticated rate limit (60/h) is burnt within a few platforms.
|
||||
"""
|
||||
from core.github import github_token
|
||||
|
||||
env = os.environ.copy()
|
||||
token = github_token()
|
||||
if token:
|
||||
env["GITHUB_TOKEN"] = token
|
||||
return env
|
||||
|
||||
|
||||
def run_jobs(jobs: list[Job], env: dict[str, str], workers: int) -> list[JobResult]:
|
||||
"""Run jobs in parallel, each once the rescrapes it waits for have ended.
|
||||
|
||||
A failed parent still releases its children: its file is unchanged, and
|
||||
the child reads it as it is.
|
||||
"""
|
||||
results: list[JobResult] = []
|
||||
ended: set[str] = set()
|
||||
waiting = list(jobs)
|
||||
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
|
||||
running: dict = {}
|
||||
while waiting or running:
|
||||
ready = [job for job in waiting if job.after <= ended]
|
||||
for job in ready:
|
||||
waiting.remove(job)
|
||||
running[pool.submit(run_job, job, env)] = job
|
||||
if not running:
|
||||
raise RuntimeError(
|
||||
"jobs wait on rescrapes that are not planned: "
|
||||
+ ", ".join(sorted(j.subject for j in waiting))
|
||||
)
|
||||
done, _ = wait(running, return_when=FIRST_COMPLETED)
|
||||
for future in done:
|
||||
job = running.pop(future)
|
||||
results.append(future.result())
|
||||
if job.area == "platforms":
|
||||
ended.add(job.subject)
|
||||
return results
|
||||
|
||||
|
||||
def run_job(job: Job, env: dict[str, str]) -> JobResult:
|
||||
"""Execute one refresh command and collect its output."""
|
||||
start = time.monotonic()
|
||||
job.log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
returncode = 0
|
||||
with job.log_path.open("w", encoding="utf-8") as log:
|
||||
for command in (job.command, *job.then):
|
||||
log.write(f"$ {' '.join(command)}\n")
|
||||
log.flush()
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
list(command),
|
||||
cwd=REPO_ROOT,
|
||||
stdout=log,
|
||||
stderr=subprocess.STDOUT,
|
||||
env=env,
|
||||
timeout=JOB_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
returncode = proc.returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
log.write(f"\nTIMEOUT after {JOB_TIMEOUT}s\n")
|
||||
returncode = 124
|
||||
if returncode != 0:
|
||||
break
|
||||
duration = time.monotonic() - start
|
||||
tail = _log_tail(job.log_path)
|
||||
return JobResult(job=job, returncode=returncode, duration=duration, tail=tail)
|
||||
|
||||
|
||||
def _log_tail(path: Path) -> str:
|
||||
"""Last non-empty line of a log, truncated for the summary table."""
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return ""
|
||||
for line in reversed(text.splitlines()):
|
||||
stripped = line.strip()
|
||||
if stripped and not stripped.startswith("$ "):
|
||||
return stripped[:120]
|
||||
return ""
|
||||
+17
-575
@@ -51,538 +51,17 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from model.platforms import inheritance_chain
|
||||
from model.registry import data_dir_registry_at, load_platform_registry
|
||||
from core.paths import DATA_DIRS_FILE, REPO_ROOT
|
||||
|
||||
LOG_DIR = REPO_ROOT / "tmp" / "refresh_stale"
|
||||
CHECK_FRESHNESS = REPO_ROOT / "scripts" / "check_freshness.py"
|
||||
PLATFORMS_REGISTRY = REPO_ROOT / "platforms" / "_registry.yml"
|
||||
DATA_DIRS_REGISTRY = REPO_ROOT / DATA_DIRS_FILE
|
||||
from freshness.stalefindings import load_findings, run_check_freshness
|
||||
from freshness.stalejob import AUTO_AREAS, LOG_DIR, MANUAL_AREAS
|
||||
from freshness.staleplan import plan_jobs, platform_registry
|
||||
from freshness.stalereport import plan_payload, plan_text, render, results_payload
|
||||
from freshness.stalerun import github_token_env, run_jobs
|
||||
|
||||
AUTO_AREAS = ("platforms", "native", "targets", "data", "catalogs")
|
||||
# A rom-folder pin is moved by hand in platforms/romfolders/_sources/,
|
||||
# then `python -m scripts.scraper.romfolders --setup NAME` reads it again.
|
||||
MANUAL_AREAS = ("romfolders", "coreinfo", "ci", "profiles")
|
||||
|
||||
JOB_TIMEOUT = 1800 # 30 minutes per refresher, scrapers rarely exceed 10
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Job:
|
||||
"""One refresh action derived from a stale finding."""
|
||||
|
||||
area: str
|
||||
subject: str
|
||||
command: list[str]
|
||||
log_path: Path
|
||||
# Commands run after `command`, in order, only while each one succeeds.
|
||||
then: tuple[tuple[str, ...], ...] = ()
|
||||
# Platforms whose rescrape job must end before this one starts.
|
||||
after: frozenset[str] = frozenset()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class JobResult:
|
||||
job: Job
|
||||
returncode: int
|
||||
duration: float
|
||||
tail: str # last non-empty line of stderr or stdout
|
||||
|
||||
|
||||
def _load_platform_registry() -> dict[str, dict]:
|
||||
"""Return the platforms map from _registry.yml, read once at startup."""
|
||||
return load_platform_registry(PLATFORMS_REGISTRY.parent, required=True)
|
||||
|
||||
|
||||
def _platform_parents(registry: dict[str, dict]) -> dict[str, str]:
|
||||
"""Platform to the platform its YAML inherits from."""
|
||||
parents: dict[str, str] = {}
|
||||
for name in registry:
|
||||
chain = inheritance_chain(name, REPO_ROOT / "platforms")
|
||||
if len(chain) > 1:
|
||||
parents[name] = chain[1]
|
||||
return parents
|
||||
|
||||
|
||||
def _ancestors(platform: str, parents: dict[str, str]) -> set[str]:
|
||||
found: set[str] = set()
|
||||
while platform in parents and parents[platform] not in found:
|
||||
platform = parents[platform]
|
||||
found.add(platform)
|
||||
return found
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _data_dir_keys() -> frozenset[str]:
|
||||
"""The entries refresh_data_dirs.py --key accepts."""
|
||||
return frozenset(data_dir_registry_at(DATA_DIRS_REGISTRY, required=True))
|
||||
|
||||
|
||||
def _run_check_freshness(areas: tuple[str, ...], extra: list[str]) -> list[dict]:
|
||||
"""Run check_freshness.py --json and return its findings."""
|
||||
cmd = [sys.executable, str(CHECK_FRESHNESS), "--json"]
|
||||
if areas and set(areas) != set(AUTO_AREAS + MANUAL_AREAS):
|
||||
cmd += ["--only", ",".join(areas)]
|
||||
cmd += extra
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd, cwd=REPO_ROOT, capture_output=True, text=True, check=False, timeout=1800
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise RuntimeError(
|
||||
f"check_freshness.py did not finish in {exc.timeout:.0f} s: run "
|
||||
f"`{' '.join(cmd[1:])} > report.json` alone, then pass --findings report.json"
|
||||
) from exc
|
||||
# Exit 1 is the STALE rows, and also a crash: only a JSON list on stdout
|
||||
# tells them apart, and the crash's own message is on stderr.
|
||||
try:
|
||||
findings = json.loads(proc.stdout) if proc.returncode in (0, 1) else None
|
||||
except json.JSONDecodeError:
|
||||
findings = None
|
||||
if not isinstance(findings, list):
|
||||
tail = (proc.stderr or proc.stdout).strip().splitlines()[-3:]
|
||||
raise RuntimeError(
|
||||
f"check_freshness.py failed (exit {proc.returncode}):\n"
|
||||
+ "\n".join(tail or ["(no output)"])
|
||||
)
|
||||
return findings
|
||||
|
||||
|
||||
def load_findings(path: Path, areas: tuple[str, ...]) -> list[dict]:
|
||||
"""A saved check_freshness.py --json report, kept to the asked areas."""
|
||||
try:
|
||||
findings = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
raise RuntimeError(f"cannot read findings from {path}: {exc}") from exc
|
||||
if not isinstance(findings, list):
|
||||
raise RuntimeError(f"{path} is not a check_freshness.py --json report")
|
||||
return [f for f in findings if f.get("area") in areas]
|
||||
|
||||
|
||||
def _slug(subject: str) -> str:
|
||||
"""A safe filename stem for a finding's subject."""
|
||||
return re.sub(r"[^A-Za-z0-9_.-]+", "_", subject).strip("_") or "job"
|
||||
|
||||
|
||||
def plan_jobs(
|
||||
findings: list[dict],
|
||||
registry: dict[str, dict],
|
||||
parents: dict[str, str] | None = None,
|
||||
) -> tuple[list[Job], list[dict], list[dict]]:
|
||||
"""Split findings into (refreshable jobs, surfaced-only, ignored).
|
||||
|
||||
Surfaced-only entries carry stale state that only a human can resolve
|
||||
(new .info file, manual DAT download, PyPI bump). Ignored entries are
|
||||
anything not STALE (OK, SKIPPED, UNKNOWN, ERROR). ERROR is also surfaced
|
||||
so the final report mentions it. ``parents`` maps a platform to the one
|
||||
it inherits from: a child's jobs wait for its rescraped ancestors, and a
|
||||
child no row names gets its export rewritten after them.
|
||||
"""
|
||||
if parents is None:
|
||||
parents = _platform_parents(registry)
|
||||
jobs: list[Job] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
surfaced: list[dict] = []
|
||||
ignored: list[dict] = []
|
||||
# A platform about to be rescraped refreshes its cached original itself,
|
||||
# after the scrape: a separate native job would race the scraper.
|
||||
rescraped = {
|
||||
str(f.get("subject") or "")
|
||||
for f in findings
|
||||
if f.get("status") == "STALE"
|
||||
and f.get("area") == "platforms"
|
||||
and _command_for("platforms", str(f.get("subject") or ""), registry)
|
||||
}
|
||||
|
||||
for finding in findings:
|
||||
status = finding.get("status")
|
||||
area = str(finding.get("area") or "")
|
||||
subject = str(finding.get("subject") or "")
|
||||
|
||||
if status == "ERROR":
|
||||
surfaced.append(finding)
|
||||
continue
|
||||
if status != "STALE":
|
||||
ignored.append(finding)
|
||||
continue
|
||||
|
||||
if area == "native" and subject in rescraped:
|
||||
ignored.append(finding)
|
||||
continue
|
||||
|
||||
command = _command_for(area, subject, registry)
|
||||
if command is None:
|
||||
surfaced.append(finding)
|
||||
continue
|
||||
|
||||
key = (area, " ".join(command))
|
||||
if key in seen:
|
||||
# Two findings funneling to the same command (e.g. mame recipes
|
||||
# listed twice) collapse to one job.
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
log = LOG_DIR / f"{area}__{_slug(subject)}.log"
|
||||
then: tuple[tuple[str, ...], ...] = ()
|
||||
if area == "platforms":
|
||||
# The truth reads the platform file: regenerated first, or the
|
||||
# native refresh refuses it as older than the profiles.
|
||||
then = (
|
||||
tuple(_truth_refresh(subject)),
|
||||
tuple(_native_refresh(subject)),
|
||||
tuple(_export_refresh(subject)),
|
||||
tuple(_verify(subject)),
|
||||
)
|
||||
elif area == "native":
|
||||
then = (tuple(_native_refresh(subject)), tuple(_export_refresh(subject)))
|
||||
after: frozenset[str] = frozenset()
|
||||
if area in ("platforms", "native"):
|
||||
after = frozenset(_ancestors(subject, parents) & rescraped)
|
||||
jobs.append(
|
||||
Job(area=area, subject=subject, command=command, log_path=log,
|
||||
then=then, after=after)
|
||||
)
|
||||
|
||||
# The export of a child is built from its parent's file: rewritten once
|
||||
# the parent is, or the next check reports it stale.
|
||||
covered = {j.subject for j in jobs if j.area in ("platforms", "native")}
|
||||
for child in sorted(parents):
|
||||
after = frozenset(_ancestors(child, parents) & rescraped)
|
||||
if not after or child in covered:
|
||||
continue
|
||||
jobs.append(Job(
|
||||
area="native",
|
||||
subject=child,
|
||||
command=_truth_refresh(child),
|
||||
log_path=LOG_DIR / f"native__{_slug(child)}.log",
|
||||
then=(tuple(_native_refresh(child)), tuple(_export_refresh(child))),
|
||||
after=after,
|
||||
))
|
||||
|
||||
return jobs, surfaced, ignored
|
||||
|
||||
|
||||
def _verify(platform: str) -> list[str]:
|
||||
"""The check a rescraped platform file is read with before it is kept."""
|
||||
return [sys.executable, "scripts/verify.py", "--platform", platform]
|
||||
|
||||
|
||||
VERIFY_MARK = "scripts/verify.py --platform"
|
||||
|
||||
|
||||
def verify_summary(path: Path) -> str:
|
||||
"""First line verify printed in a job log, empty when it did not run."""
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return ""
|
||||
lines = text.splitlines()
|
||||
for index, line in enumerate(lines):
|
||||
if line.startswith("$ ") and VERIFY_MARK in line:
|
||||
return next(
|
||||
(rest.strip() for rest in lines[index + 1:]
|
||||
if rest.strip() and not rest.startswith("$ ")),
|
||||
"",
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def run_jobs(jobs: list[Job], env: dict[str, str], workers: int) -> list[JobResult]:
|
||||
"""Run jobs in parallel, each once the rescrapes it waits for have ended.
|
||||
|
||||
A failed parent still releases its children: its file is unchanged, and
|
||||
the child reads it as it is.
|
||||
"""
|
||||
results: list[JobResult] = []
|
||||
ended: set[str] = set()
|
||||
waiting = list(jobs)
|
||||
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
|
||||
running: dict = {}
|
||||
while waiting or running:
|
||||
ready = [job for job in waiting if job.after <= ended]
|
||||
for job in ready:
|
||||
waiting.remove(job)
|
||||
running[pool.submit(run_job, job, env)] = job
|
||||
if not running:
|
||||
raise RuntimeError(
|
||||
"jobs wait on rescrapes that are not planned: "
|
||||
+ ", ".join(sorted(j.subject for j in waiting))
|
||||
)
|
||||
done, _ = wait(running, return_when=FIRST_COMPLETED)
|
||||
for future in done:
|
||||
job = running.pop(future)
|
||||
results.append(future.result())
|
||||
if job.area == "platforms":
|
||||
ended.add(job.subject)
|
||||
return results
|
||||
|
||||
|
||||
def _truth_refresh(platform: str) -> list[str]:
|
||||
return [sys.executable, "scripts/generate_truth.py", "--platform", platform]
|
||||
|
||||
|
||||
def _native_refresh(platform: str) -> list[str]:
|
||||
return [
|
||||
sys.executable,
|
||||
"scripts/export_native.py",
|
||||
"--platform",
|
||||
platform,
|
||||
"--refresh-cache",
|
||||
]
|
||||
|
||||
|
||||
def _export_refresh(platform: str) -> list[str]:
|
||||
"""Rewrite the published export from the refreshed original."""
|
||||
return [sys.executable, "scripts/export_native.py", "--platform", platform]
|
||||
|
||||
|
||||
def _platform_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
|
||||
entry = registry.get(subject) or {}
|
||||
scraper = entry.get("scraper")
|
||||
if not scraper:
|
||||
return None
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
f"scripts.scraper.{scraper}_scraper",
|
||||
"-o",
|
||||
f"platforms/{subject}.yml",
|
||||
*(str(a) for a in entry.get("rescrape_args") or ()),
|
||||
]
|
||||
|
||||
|
||||
def _target_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
|
||||
# "<platform> cores" rows list buildbot names without a profile. No
|
||||
# scraper fixes that, a human writes `cores:` or _overrides.yml.
|
||||
if subject.endswith(" cores"):
|
||||
return None
|
||||
entry = registry.get(subject) or {}
|
||||
module = entry.get("target_scraper")
|
||||
if not module:
|
||||
return None
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
f"scripts.scraper.targets.{module}_scraper",
|
||||
"-o",
|
||||
f"platforms/targets/{subject}.yml",
|
||||
]
|
||||
|
||||
|
||||
def _data_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
|
||||
if subject not in _data_dir_keys():
|
||||
# "_data_dirs.yml" and "buildbot system" name the registry and
|
||||
# what it does not track yet: a human adds the entry.
|
||||
return None
|
||||
return [
|
||||
sys.executable,
|
||||
"scripts/refresh_data_dirs.py",
|
||||
"--key",
|
||||
subject,
|
||||
"--force",
|
||||
]
|
||||
|
||||
|
||||
def _catalog_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
|
||||
if subject == "mame recipes":
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"scripts.scraper.romset_dat_importer",
|
||||
"--source",
|
||||
"mame",
|
||||
"--fetch",
|
||||
]
|
||||
if subject == "fbneo recipes":
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"scripts.scraper.romset_dat_importer",
|
||||
"--source",
|
||||
"fbneo",
|
||||
"--fetch",
|
||||
]
|
||||
if subject in ("no-intro games", "redump games"):
|
||||
# The game DATs download without a browser, unlike the BIOS ones.
|
||||
return [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"scripts.scraper.game_dat_importer",
|
||||
"--source",
|
||||
subject.split()[0],
|
||||
"--fetch",
|
||||
"--refresh",
|
||||
"--floor",
|
||||
]
|
||||
# redump / no-intro / tosec need manual DAT download.
|
||||
return None
|
||||
|
||||
|
||||
_AREA_COMMANDS: dict[str, Callable[[str, dict[str, dict]], list[str] | None]] = {
|
||||
"platforms": _platform_command,
|
||||
"targets": _target_command,
|
||||
"data": _data_command,
|
||||
"catalogs": _catalog_command,
|
||||
}
|
||||
|
||||
|
||||
def _command_for(
|
||||
area: str, subject: str, registry: dict[str, dict]
|
||||
) -> list[str] | None:
|
||||
"""Map a stale finding to its refresh command, or None if manual."""
|
||||
if area == "native":
|
||||
# export_native refuses a truth older than the profiles, so the
|
||||
# truth comes first and the original follows (Job.then).
|
||||
return _truth_refresh(subject)
|
||||
|
||||
if area == "ci" and subject == "install.py pin":
|
||||
# The pin is the hash of the committed install.py, nothing to judge.
|
||||
return [sys.executable, "scripts/pin_installer.py"]
|
||||
|
||||
builder = _AREA_COMMANDS.get(area)
|
||||
if builder:
|
||||
return builder(subject, registry)
|
||||
|
||||
# coreinfo, ci, profiles: never auto-refresh.
|
||||
return None
|
||||
|
||||
|
||||
def _github_token_env() -> dict[str, str]:
|
||||
"""Hand `gh auth token` to the subprocess environment.
|
||||
|
||||
emudeck and retropie target scrapers hit the GitHub API. Without a token
|
||||
the unauthenticated rate limit (60/h) is burnt within a few platforms.
|
||||
"""
|
||||
from core.github import github_token
|
||||
|
||||
env = os.environ.copy()
|
||||
token = github_token()
|
||||
if token:
|
||||
env["GITHUB_TOKEN"] = token
|
||||
return env
|
||||
|
||||
|
||||
def run_job(job: Job, env: dict[str, str]) -> JobResult:
|
||||
"""Execute one refresh command and collect its output."""
|
||||
start = time.monotonic()
|
||||
job.log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
returncode = 0
|
||||
with job.log_path.open("w", encoding="utf-8") as log:
|
||||
for command in (job.command, *job.then):
|
||||
log.write(f"$ {' '.join(command)}\n")
|
||||
log.flush()
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
list(command),
|
||||
cwd=REPO_ROOT,
|
||||
stdout=log,
|
||||
stderr=subprocess.STDOUT,
|
||||
env=env,
|
||||
timeout=JOB_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
returncode = proc.returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
log.write(f"\nTIMEOUT after {JOB_TIMEOUT}s\n")
|
||||
returncode = 124
|
||||
if returncode != 0:
|
||||
break
|
||||
duration = time.monotonic() - start
|
||||
tail = _log_tail(job.log_path)
|
||||
return JobResult(job=job, returncode=returncode, duration=duration, tail=tail)
|
||||
|
||||
|
||||
def _log_tail(path: Path) -> str:
|
||||
"""Last non-empty line of a log, truncated for the summary table."""
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return ""
|
||||
for line in reversed(text.splitlines()):
|
||||
stripped = line.strip()
|
||||
if stripped and not stripped.startswith("$ "):
|
||||
return stripped[:120]
|
||||
return ""
|
||||
|
||||
|
||||
def render(
|
||||
results: list[JobResult],
|
||||
surfaced: list[dict],
|
||||
ignored: list[dict],
|
||||
) -> str:
|
||||
"""Human-readable table of what ran and what still needs a human."""
|
||||
lines: list[str] = []
|
||||
subject_w = max((len(r.job.subject) for r in results), default=10)
|
||||
subject_w = min(max(subject_w, 10), 44)
|
||||
|
||||
if results:
|
||||
lines.append("\n[refreshed]")
|
||||
lines.append(
|
||||
f" {'STATUS':8} {'AREA':10} {'SUBJECT':{subject_w}} "
|
||||
f"{'DUR':>7} LOG"
|
||||
)
|
||||
for r in sorted(results, key=lambda x: (x.job.area, x.job.subject)):
|
||||
status = "OK" if r.returncode == 0 else f"FAIL ({r.returncode})"
|
||||
rel_log = r.job.log_path.relative_to(REPO_ROOT)
|
||||
lines.append(
|
||||
f" {status:8} {r.job.area:10} {r.job.subject[:subject_w]:{subject_w}} "
|
||||
f"{r.duration:6.1f}s {rel_log}"
|
||||
)
|
||||
if r.returncode != 0 and r.tail:
|
||||
lines.append(f" -> {r.tail}")
|
||||
|
||||
rescraped = sorted(
|
||||
(r for r in results if r.job.area == "platforms" and r.returncode == 0),
|
||||
key=lambda r: r.job.subject,
|
||||
)
|
||||
if rescraped:
|
||||
lines.append(
|
||||
"\n[verify] a rescrape can add systems: read each report "
|
||||
"before keeping platforms/<name>.yml"
|
||||
)
|
||||
for r in rescraped:
|
||||
summary = verify_summary(r.job.log_path) or "(no verify output)"
|
||||
lines.append(f" {r.job.subject:12} {summary}")
|
||||
lines.append(
|
||||
f" {'':12} python scripts/verify.py --platform {r.job.subject}"
|
||||
)
|
||||
|
||||
if surfaced:
|
||||
lines.append("\n[manual review needed]")
|
||||
for f in surfaced:
|
||||
detail = str(f.get("detail") or "").strip()
|
||||
lines.append(
|
||||
f" {f.get('status', ''):7} {f.get('area', ''):10} "
|
||||
f"{f.get('subject', ''):28} {detail[:100]}"
|
||||
)
|
||||
|
||||
if ignored:
|
||||
counts: dict[str, int] = {}
|
||||
for f in ignored:
|
||||
counts[str(f.get("status") or "?")] = counts.get(str(f.get("status") or "?"), 0) + 1
|
||||
parts = ", ".join(f"{n} {status.lower()}" for status, n in sorted(counts.items()))
|
||||
lines.append(f"\n[ignored] {parts}")
|
||||
|
||||
ok = sum(1 for r in results if r.returncode == 0)
|
||||
fail = len(results) - ok
|
||||
lines.append(
|
||||
f"\nREFRESH: {ok} ok, {fail} failed, {len(surfaced)} to review manually"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.split("\n\n")[0])
|
||||
parser.add_argument(
|
||||
"--only",
|
||||
@@ -617,6 +96,11 @@ def main() -> int:
|
||||
default=[],
|
||||
help="extra flag to pass through to check_freshness.py (repeatable)",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args()
|
||||
|
||||
all_areas = AUTO_AREAS + MANUAL_AREAS
|
||||
@@ -634,67 +118,25 @@ def main() -> int:
|
||||
if args.findings:
|
||||
findings = load_findings(Path(args.findings), areas)
|
||||
else:
|
||||
findings = _run_check_freshness(areas, args.freshness_arg)
|
||||
findings = run_check_freshness(areas, args.freshness_arg)
|
||||
except RuntimeError as exc:
|
||||
print(exc, file=sys.stderr)
|
||||
return 2
|
||||
|
||||
registry = _load_platform_registry()
|
||||
jobs, surfaced, ignored = plan_jobs(findings, registry)
|
||||
jobs, surfaced, ignored = plan_jobs(findings, platform_registry())
|
||||
|
||||
if args.dry_run and args.json:
|
||||
print(json.dumps({
|
||||
"planned": [
|
||||
{
|
||||
"area": job.area,
|
||||
"subject": job.subject,
|
||||
"command": job.command,
|
||||
"after": sorted(job.after),
|
||||
"then": [list(command) for command in job.then],
|
||||
}
|
||||
for job in sorted(jobs, key=lambda j: (j.area, j.subject))
|
||||
],
|
||||
"surfaced": surfaced,
|
||||
"ignored_count": len(ignored),
|
||||
}, indent=2))
|
||||
print(json.dumps(plan_payload(jobs, surfaced, ignored), indent=2))
|
||||
return 0
|
||||
if args.dry_run:
|
||||
print(f"\n[plan] {len(jobs)} refreshable, {len(surfaced)} manual, "
|
||||
f"{len(ignored)} already clean/skipped")
|
||||
for job in sorted(jobs, key=lambda j: (j.area, j.subject)):
|
||||
print(f" {job.area:10} {job.subject:28} {' '.join(job.command)}")
|
||||
if job.after:
|
||||
print(f" {'':10} {'':28} after {', '.join(sorted(job.after))}")
|
||||
for command in job.then:
|
||||
print(f" {'':10} {'':28} then {' '.join(command)}")
|
||||
if surfaced:
|
||||
print("\n[manual review needed]")
|
||||
for f in surfaced:
|
||||
print(f" {f.get('status', ''):7} {f.get('area', ''):10} "
|
||||
f"{f.get('subject', ''):28} {str(f.get('detail') or '')[:100]}")
|
||||
print(plan_text(jobs, surfaced, ignored))
|
||||
return 0
|
||||
|
||||
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
env = _github_token_env()
|
||||
results = run_jobs(jobs, env, args.jobs)
|
||||
results = run_jobs(jobs, github_token_env(), args.jobs)
|
||||
|
||||
if args.json:
|
||||
payload = {
|
||||
"refreshed": [
|
||||
{
|
||||
"area": r.job.area,
|
||||
"subject": r.job.subject,
|
||||
"returncode": r.returncode,
|
||||
"duration_sec": round(r.duration, 2),
|
||||
"log": str(r.job.log_path.relative_to(REPO_ROOT)),
|
||||
"tail": r.tail,
|
||||
}
|
||||
for r in results
|
||||
],
|
||||
"surfaced": surfaced,
|
||||
"ignored_count": len(ignored),
|
||||
}
|
||||
print(json.dumps(payload, indent=2))
|
||||
print(json.dumps(results_payload(results, surfaced, ignored), indent=2))
|
||||
else:
|
||||
print(render(results, surfaced, ignored))
|
||||
|
||||
|
||||
@@ -47,6 +47,10 @@ COMMANDS = {
|
||||
"commit_rules.py": ("devtools/commitrules.py",),
|
||||
"pr_checks.py": ("devtools/prchecks.py",),
|
||||
"check_buildbot_system.py": ("scraper/buildbot_system.py",),
|
||||
"refresh_stale.py": (
|
||||
"freshness/stalejob.py", "freshness/stalefindings.py", "freshness/stalecommands.py",
|
||||
"freshness/staleplan.py", "freshness/stalerun.py", "freshness/stalereport.py",
|
||||
),
|
||||
"generate_site.py": (
|
||||
"sitegen/config.py",
|
||||
"sitegen/emulatorsindex.py",
|
||||
|
||||
@@ -140,17 +140,17 @@ class NativeCacheTests(unittest.TestCase):
|
||||
def test_a_repeated_inherits_key_is_refused(self):
|
||||
"""refresh_stale read inherits: with yaml.safe_load, which kept the
|
||||
second of two keys the platform loader refuses."""
|
||||
import refresh_stale
|
||||
from core.cli import SourceUnreadable
|
||||
from freshness import staleplan
|
||||
|
||||
platforms = self.cache / "platforms"
|
||||
platforms.mkdir()
|
||||
(platforms / "child.yml").write_text(
|
||||
"inherits: a\ninherits: b\n", encoding="utf-8"
|
||||
)
|
||||
with mock.patch.object(refresh_stale, "REPO_ROOT", self.cache), \
|
||||
with mock.patch.object(staleplan, "REPO_ROOT", self.cache), \
|
||||
self.assertRaisesRegex(SourceUnreadable, "duplicate key 'inherits'"):
|
||||
refresh_stale._platform_parents({"child": {}})
|
||||
staleplan.platform_parents({"child": {}})
|
||||
|
||||
def test_every_registered_platform_with_an_exporter_gets_a_row(self):
|
||||
rows = check_native(REPO_ROOT / "platforms", self.cache, self.cache / "truth")
|
||||
|
||||
@@ -651,11 +651,11 @@ class SitePages(unittest.TestCase):
|
||||
|
||||
class Freshness(unittest.TestCase):
|
||||
def test_no_measurements_area(self) -> None:
|
||||
import refresh_stale
|
||||
from freshness.findings import AREAS
|
||||
from freshness.stalejob import AUTO_AREAS
|
||||
|
||||
self.assertNotIn("measurements", AREAS)
|
||||
self.assertNotIn("measurements", refresh_stale.AUTO_AREAS)
|
||||
self.assertNotIn("measurements", AUTO_AREAS)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+23
-18
@@ -19,7 +19,12 @@ from unittest import mock
|
||||
|
||||
import yaml
|
||||
|
||||
import refresh_stale as rs
|
||||
from freshness import stalefindings
|
||||
from freshness.stalefindings import load_findings
|
||||
from freshness.stalejob import AUTO_AREAS, MANUAL_AREAS, Job, JobResult
|
||||
from freshness.staleplan import plan_jobs
|
||||
from freshness.stalereport import render
|
||||
from freshness.stalerun import run_job, run_jobs
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
@@ -36,7 +41,7 @@ def finding(area: str, subject: str, status: str = "STALE") -> dict:
|
||||
|
||||
class Planning(unittest.TestCase):
|
||||
def _plan(self, *findings: dict, parents: dict | None = None):
|
||||
return rs.plan_jobs(list(findings), REGISTRY, parents or {})
|
||||
return plan_jobs(list(findings), REGISTRY, parents or {})
|
||||
|
||||
def test_a_stale_platform_is_rescraped_then_its_original_is_refreshed(self):
|
||||
jobs, surfaced, _ = self._plan(finding("platforms", "retrobat"))
|
||||
@@ -59,7 +64,7 @@ class Planning(unittest.TestCase):
|
||||
def test_a_scraper_reading_its_pin_is_moved_by_rescrape_args(self):
|
||||
registry = dict(REGISTRY, retrobat={"scraper": "retrobat",
|
||||
"rescrape_args": ["--revision", "master"]})
|
||||
jobs, _, _ = rs.plan_jobs([finding("platforms", "retrobat")], registry, {})
|
||||
jobs, _, _ = plan_jobs([finding("platforms", "retrobat")], registry, {})
|
||||
self.assertEqual(jobs[0].command[-2:], ["--revision", "master"])
|
||||
with (REPO_ROOT / "platforms" / "_registry.yml").open(encoding="utf-8") as fh:
|
||||
real = yaml.safe_load(fh)["platforms"]["retrobat"]
|
||||
@@ -71,7 +76,7 @@ class Planning(unittest.TestCase):
|
||||
registry = dict(REGISTRY, retroarch={"scraper": "libretro"},
|
||||
retropie={"scraper": "retropie"})
|
||||
parents = {"retropie": "retroarch", "lakka": "retroarch"}
|
||||
jobs, _, _ = rs.plan_jobs(
|
||||
jobs, _, _ = plan_jobs(
|
||||
[finding("platforms", "retroarch"), finding("platforms", "retropie"),
|
||||
finding("platforms", "retrobat")],
|
||||
registry, parents,
|
||||
@@ -190,9 +195,9 @@ class Running(unittest.TestCase):
|
||||
code = f"open({str(order)!r}, 'a').write({subject!r} + chr(10))"
|
||||
if subject == "parent":
|
||||
code = "import time; time.sleep(0.5); " + code
|
||||
return rs.Job(area, subject, [sys.executable, "-c", code],
|
||||
return Job(area, subject, [sys.executable, "-c", code],
|
||||
Path(directory) / f"{subject}.log", (), frozenset(after))
|
||||
rs.run_jobs([job("native", "child", ["parent"]),
|
||||
run_jobs([job("native", "child", ["parent"]),
|
||||
job("platforms", "parent")], {}, 4)
|
||||
self.assertEqual(order.read_text().split(), ["parent", "child"])
|
||||
|
||||
@@ -204,13 +209,13 @@ class Running(unittest.TestCase):
|
||||
"$ python scripts/verify.py --platform x\n"
|
||||
"X: 10/12 OK, 2 missing [md5]\n"
|
||||
)
|
||||
job = rs.Job("platforms", "x", ["true"], log)
|
||||
text = rs.render([rs.JobResult(job, 0, 1.0, "")], [], [])
|
||||
job = Job("platforms", "x", ["true"], log)
|
||||
text = render([JobResult(job, 0, 1.0, "")], [], [])
|
||||
self.assertIn("X: 10/12 OK, 2 missing [md5]", text)
|
||||
self.assertIn("python scripts/verify.py --platform x", text)
|
||||
|
||||
def _job(self, directory: str, command: list[str], then=()) -> rs.Job:
|
||||
return rs.Job("platforms", "x", command, Path(directory) / "x.log", then)
|
||||
def _job(self, directory: str, command: list[str], then=()) -> Job:
|
||||
return Job("platforms", "x", command, Path(directory) / "x.log", then)
|
||||
|
||||
def test_a_follow_up_runs_after_a_success(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
@@ -220,7 +225,7 @@ class Running(unittest.TestCase):
|
||||
[sys.executable, "-c", "pass"],
|
||||
((sys.executable, "-c", f"open({str(marker)!r}, 'w').close()"),),
|
||||
)
|
||||
result = rs.run_job(job, {})
|
||||
result = run_job(job, {})
|
||||
self.assertEqual(result.returncode, 0)
|
||||
self.assertTrue(marker.exists())
|
||||
|
||||
@@ -232,7 +237,7 @@ class Running(unittest.TestCase):
|
||||
[sys.executable, "-c", "raise SystemExit(3)"],
|
||||
((sys.executable, "-c", f"open({str(marker)!r}, 'w').close()"),),
|
||||
)
|
||||
result = rs.run_job(job, {})
|
||||
result = run_job(job, {})
|
||||
self.assertEqual(result.returncode, 3)
|
||||
self.assertFalse(marker.exists())
|
||||
|
||||
@@ -249,7 +254,7 @@ class SavedFindings(unittest.TestCase):
|
||||
' {"area": "platforms", "subject": "batocera", "status": "STALE"}]',
|
||||
encoding="utf-8",
|
||||
)
|
||||
findings = rs.load_findings(path, ("data", "catalogs"))
|
||||
findings = load_findings(path, ("data", "catalogs"))
|
||||
self.assertEqual([f["subject"] for f in findings], ["dolphin-sys"])
|
||||
|
||||
def test_dry_run_json_prints_the_plan_as_json(self):
|
||||
@@ -280,8 +285,8 @@ class SavedFindings(unittest.TestCase):
|
||||
romfolders was refused."""
|
||||
from freshness.findings import AREAS
|
||||
|
||||
self.assertEqual(set(AREAS), set(rs.AUTO_AREAS + rs.MANUAL_AREAS))
|
||||
jobs, surfaced, _ = rs.plan_jobs([finding("romfolders", "muos")], REGISTRY, {})
|
||||
self.assertEqual(set(AREAS), set(AUTO_AREAS + MANUAL_AREAS))
|
||||
jobs, surfaced, _ = plan_jobs([finding("romfolders", "muos")], REGISTRY, {})
|
||||
self.assertEqual((jobs, [f["subject"] for f in surfaced]), ([], ["muos"]))
|
||||
|
||||
def test_a_report_that_is_not_a_list_is_refused(self):
|
||||
@@ -289,7 +294,7 @@ class SavedFindings(unittest.TestCase):
|
||||
path = Path(directory) / "freshness.json"
|
||||
path.write_text('{"area": "data"}', encoding="utf-8")
|
||||
with self.assertRaises(RuntimeError):
|
||||
rs.load_findings(path, ("data",))
|
||||
load_findings(path, ("data",))
|
||||
|
||||
|
||||
class AFailedCheckIsNamed(unittest.TestCase):
|
||||
@@ -299,8 +304,8 @@ class AFailedCheckIsNamed(unittest.TestCase):
|
||||
|
||||
def _run(self, raises: Exception | None = None, **result):
|
||||
proc = subprocess.CompletedProcess([], **result) if result else None
|
||||
with mock.patch.object(rs.subprocess, "run", side_effect=raises, return_value=proc):
|
||||
return rs._run_check_freshness(("coreinfo",), [])
|
||||
with mock.patch.object(stalefindings.subprocess, "run", side_effect=raises, return_value=proc):
|
||||
return stalefindings.run_check_freshness(("coreinfo",), [])
|
||||
|
||||
def test_a_crash_shows_its_stderr(self):
|
||||
with self.assertRaises(RuntimeError) as raised:
|
||||
|
||||
@@ -52,7 +52,7 @@ scripts/ all tooling (Python and pyyaml, jsonschema for schema c
|
||||
devtools/ the commit message rules and the checks of a pull request
|
||||
schemas/ the data contracts behind validate_schemas.py: schemas and semantic invariants
|
||||
unattended/ the job registry, worktree, CI breaker and units behind autorun.py
|
||||
freshness/ each transcribed layer against its upstream, one module per area (check_freshness.py)
|
||||
freshness/ each transcribed layer against its upstream, one module per area (check_freshness.py), and the refresh of each stale row (refresh_stale.py)
|
||||
install/ JSON install manifests per platform
|
||||
targets/ JSON target manifests per platform (cores per architecture)
|
||||
install.py the installer, with install.sh and install.ps1 to start it,
|
||||
|
||||
Reference in new issue
Block a user