From 6191e6382eff6b34ddee55393b01176b900f835b Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 22:23:47 -0700 Subject: [PATCH] Tests gate: check a dynamic version through __version__; add darkroom_state.py A pyproject.toml whose [project] lists version in `dynamic` (graphik reads it from preponderous/graphik/_version.py) declares no version, so the `version` assertion failed for every candidate. With a dynamic version, `version` now needs PACKAGE, and each import- check holds the installed package's __version__ to EXPECTED_VERSION (a missing __version__ fails there instead of passing). Static versions are checked as before. scenarios/darkroom_state.py covers darkroom's per-project state (.darkroom/state.json and takes): the baseline shoots two projects with the command backend and a stand-in capture program, and each version's view is what its own `shoot` does to them, run in place and restored byte for byte afterwards. darkroom promises that upgrading does not by itself make a shot stale, so a shot the candidate reshoots or rewrites shows as `rewritten` and fails read-1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeumA4DYW41mYg7nCwNn --- CLAUDE.md | 1 + README.md | 20 ++- gates/tests_gate.py | 35 ++++- scenarios/darkroom_state.py | 262 +++++++++++++++++++++++++++++++ tests/test_tests_gate_version.py | 27 +++- 5 files changed, 337 insertions(+), 8 deletions(-) create mode 100644 scenarios/darkroom_state.py diff --git a/CLAUDE.md b/CLAUDE.md index ffa1ce6..9fd4940 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -70,6 +70,7 @@ scenarios/ Per-library save scenarios: `write DIR`, `read DIR` (o trace_client_install_id.py trace-client-python install-ID file (install_id_from_file) gardener_state.py gardener's per-device state dir (run history, lists, cursor, hub store) usd_recorder_recordings.py usd-recorder's .usda/.usdc recordings and usd-replay/1 replays + darkroom_state.py darkroom's .darkroom/state.json and takes (nothing reshot on upgrade) menu_bot.py a seeded bot standing in for a menu-driven game's front-end (used by the game scenarios) tak_game_saves.py Tidewater / Overwinter / Night Ferry saves, played through the game (checkout mode) fishe_saves.py FishE saves, flat (2.x) and slotted layouts, played through the game (checkout mode) diff --git a/README.md b/README.md index 0f90654..1263be6 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ Each gate adds its own keys beside these, set as far as the run got: | `python_versions` | `3.12` | comma-separated interpreters | | `install_extras` | `dev` | extras installed with the package | | `test_command` | `python -m pytest -q` | run in the checkout; a leading `python` or `python3` is the gate's virtualenv | -| `expected_version` | `""` | the `[project] version` pyproject.toml must declare | +| `expected_version` | `""` | the `[project] version` pyproject.toml must declare. When pyproject.toml's version is dynamic (`dynamic = ["version"]`, read from the package at build time; `v7`), `package` must be set and its installed `__version__` must equal this on every interpreter | Assertions: `checkout`, `version` (only when `expected_version` is set), then for each interpreter `install-`, `import-` (only when `package` is set), `tests-`. @@ -192,6 +192,17 @@ readers report: `inspect_stage`, `has_clips`, every attribute and computed visib at every tick for a stage, and `validate_replay`, `replay_info` and `read_replay` for a replay. +[`scenarios/darkroom_state.py`](scenarios/darkroom_state.py) covers darkroom's per-project +state: `.darkroom/state.json` and the takes under `.darkroom/takes/`, beside a shot list. The +baseline shoots two projects with the `command` backend and a standard-library stand-in for a +capture program (stills, a clip with GIF, poster and contact sheet, a still under two tags, a +prep and the still that depends on it, and a shot recorded by `shoot --adopt`). darkroom +promises that upgrading does not by itself make a shot stale, so each version's view of a +project is what its own `shoot` does to it: every shot `kept` (state entry, take and outputs +byte-identical) or `rewritten`, plus whether the recorded hashes equal that version's own and +the outputs it expects. darkroom's capture hash includes the project's absolute path, so that +shoot runs in place and the project is restored byte for byte from a copy afterwards. + ### Game scenarios (checkout mode) Four scenarios cover games that are run from a checkout. Each one **plays** the baseline: the @@ -255,6 +266,12 @@ gh workflow run save-compat.yml --repo Stephenson-Software/python-release-gates -f scenario=scenarios/usd_recorder_recordings.py -f distribution=usd-recorder ``` +``` +gh workflow run save-compat.yml --repo Stephenson-Software/python-release-gates --ref v7 \ + -f repository=Preponderous-Software/darkroom -f sha= -f baseline_ref=v0.7.1 \ + -f scenario=scenarios/darkroom_state.py -f distribution=darkroom +``` + Reference a tag, never a branch, so that a change here cannot alter a check already in progress. @@ -272,6 +289,7 @@ it fails as `harness`. Each tag holds everything in the tags before it. | `v4` | `tak_game_saves.py`, `fishe_saves.py`, `cave_saves.py`, `ophidian_saves.py`, `menu_bot.py`; an unknown `pin_sources` fails as `harness` with a `result.json` (before, the gate exited with none) | | `v5` | `SAVE_MIGRATIONS`, declared by `fishe_saves.py` | | `v6` | `complete` in `result.json` and the summary's `DID NOT FINISH`; a package without `__version__` passes `import-` (in `v5` and earlier it fails); stderr after a scenario's JSON line no longer fails the read (in `v5` and earlier it does); a view must be a JSON object (in `v5` and earlier any JSON on the last line is taken as the view); a URL pin must name the repository whole, so `owner/tak-client` no longer pins `owner/tak` (in `v5` and earlier the consumer is tested, not skipped); a baseline write or fixture that leaves only directories fails `baseline-write` or `fixture` (in `v5` and earlier it passes with `0 file(s)`); an indented `version` key, or a comment after the `[project]` header, is read by the `version` check (in `v5` and earlier it reads as none, so `version` fails); the gate jobs run on `ubuntu-24.04`, where Python 3.8 and 3.9 can be set up (in `v5` and earlier they run on `ubuntu-latest`, which no longer has them) | +| `v7` | `darkroom_state.py`; a dynamic version (`dynamic = ["version"]` in pyproject.toml) is checked through the installed package's `__version__`, which every `import-` must report as `expected_version` (in `v6` and earlier `version` fails, since pyproject.toml declares none) | ## License diff --git a/gates/tests_gate.py b/gates/tests_gate.py index 19d4836..cbfd70b 100644 --- a/gates/tests_gate.py +++ b/gates/tests_gate.py @@ -4,10 +4,13 @@ Assertions, in order — the run stops at the first failure: checkout the candidate commit is checked out (infrastructure if not) - version the version the build file declares equals EXPECTED_VERSION (when given) + version the version the build file declares equals EXPECTED_VERSION (when given); + when pyproject.toml's version is dynamic (v7), PACKAGE must be set, and + the import- checks hold its `__version__` to EXPECTED_VERSION instead install- `pip install ` succeeds on interpreter import- the package imports from the installed copy and, when it defines - `__version__`, reports EXPECTED_VERSION + `__version__`, reports EXPECTED_VERSION (with a dynamic version it must + define it) tests- TEST_COMMAND exits 0 (pytest's summary line is quoted) Environment (set by the workflow from its inputs): REPOSITORY, SHA, PACKAGE, PYTHON_VERSIONS, @@ -38,6 +41,17 @@ def declared_version(src: Path) -> str: return v.group(1) if v else "" +def version_is_dynamic(src: Path) -> bool: + """pyproject.toml's `[project]` lists `version` in `dynamic` (the build reads it from the + package, e.g. setuptools' `version = {attr = "pkg._version.__version__"}`).""" + text = (src / "pyproject.toml").read_text() if (src / "pyproject.toml").exists() else "" + m = re.search(r"^\[project\][ \t]*(?:#[^\n]*)?$(.*?)(?=^\[|\Z)", text, re.M | re.S) + if not m: + return False + d = re.search(r"^[ \t]*dynamic\s*=\s*\[([^\]]*)\]", m.group(1), re.M) + return bool(d) and re.search(r"""["']version["']""", d.group(1)) is not None + + PROBE_TAG = "prg-import-probe " @@ -78,8 +92,16 @@ def main() -> int: head = run(["git", "-C", str(src), "rev-parse", "HEAD"])[1].strip() result.check("checkout", head == sha, f"checked out {head}") declared = declared_version(src) + dynamic = not declared and version_is_dynamic(src) result.doc["version"] = declared - if expected: + result.doc["versionDynamic"] = dynamic + if expected and dynamic: + # Nothing to read in pyproject.toml: the version is the package's own __version__, + # which every import- check below must then report exactly. + result.check("version", bool(package), + f"pyproject.toml's version is dynamic; each import- check holds {package}.__version__ to {expected}" + if package else f"pyproject.toml's version is dynamic and no package was given to read it from; expected {expected}") + elif expected: result.check("version", declared == expected, f"pyproject.toml declares {declared or '(none)'}; expected {expected}") for py in pythons: interp = make_venv(work / f"venv-{py}", f"python{py}") @@ -89,11 +111,12 @@ def main() -> int: if package: code, out = run([str(interp), "-c", import_probe(package)], cwd=work) where, ver = parse_probe(out) - ok = code == 0 and "site-packages" in where and (not expected or not ver or ver == expected) + ok = (code == 0 and "site-packages" in where + and (not expected or ver == expected or (not ver and not dynamic))) detail = (f"{package} {ver or '(no __version__)'} from {where}" if code == 0 else f"import failed: {tail(out)}") - if code == 0 and expected and ver and ver != expected: - detail += f"; expected {expected}" + if code == 0 and expected and ver != expected and (ver or dynamic): + detail += f"; expected {expected}" + (" (pyproject.toml's version is dynamic)" if dynamic else "") result.check(f"import-{py}", ok, detail) # The suite runs against the INSTALLED copy where the project allows it; a # `pythonpath = ["src"]` pytest setting points it back at the checkout, which is diff --git a/scenarios/darkroom_state.py b/scenarios/darkroom_state.py new file mode 100644 index 0000000..a312f5f --- /dev/null +++ b/scenarios/darkroom_state.py @@ -0,0 +1,262 @@ +"""Save-compatibility scenario for darkroom (https://github.com/Preponderous-Software/darkroom). + +darkroom keeps state next to each shot list (`media.json`): `.darkroom/state.json` (one entry +per shot: the capture and encode hashes it was made with, its outputs, the darkroom version) +and `.darkroom/takes//` (each take's frames and `meta.json`, which a re-encode reads +back). Its README promises that upgrading does not by itself make a shot stale, and 0.7.0's +changelog that "nothing is reshot on upgrade". So a project an older release shot must, under +a newer one, still load, still name the same outputs, and come out of a `shoot` with nothing +reshot or rewritten. + +Every project here is shot with the `command` backend and a stand-in capture program +(`fake_capture.py`, standard library only, written beside the shot list and named through +`{manifest_dir}`), so no browser, display or ffmpeg is needed. The baseline's `write DIR` +lays down two projects: + + projects/game/ a still (jpg, vars in the capture), a clip (GIF, poster and contact + sheet), a still shot twice under the tags `before` and `after`, and a prep + (`kind: prep`) whose output file a dependent still reads (`depends`) + projects/docs/ a still whose outputs were committed and recorded by `shoot --adopt` + (no take), and a still shot normally + +`read DIR` leaves DIR as it found it. For each project it loads the shot list with the reading +version (`darkroom.manifest.load`) and runs that version's `shoot` over it, with lock and run +registries in a temporary directory. darkroom's capture hash includes the project's absolute +path, so the shoot has to run in place: the project is copied aside first and put back from +that copy afterwards, byte for byte. A shot is `kept` when its state entry, its take and every +output it lists are byte-identical after that shoot, and `rewritten` otherwise; a project whose +shot list does not load is reported as `error`. `projects` says, per project, whether it +loaded, how many shots that shoot failed, which state keys it added and which files it added +or removed. Each entry in `saves` (one per shot, prep and tagged take) also carries what the +reader makes of the state file: the entry's recorded outputs and hashes, whether they equal +the reading version's own capture/encode hashes, and the outputs that version expects +(`expected_outputs`). Nothing in the view depends on the machine or the time. + +`append DIR` (the candidate) shoots a third project, projects/appended/, beside the others. + +Modes: `write DIR`, `read DIR` (prints one JSON line), `append DIR`. +""" + +import hashlib +import json +import os +import shutil +import sys +import tempfile +from pathlib import Path + +FAKE_CAPTURE = r'''"""Writes N solid PNG frames (standard library only): fake_capture.py OUT_DIR W H [N] [R,G,B].""" +import struct +import sys +import zlib +from pathlib import Path + + +def png(width, height, rgb): + row = b"\x00" + bytes(rgb) * width + raw = zlib.compress(row * height, 9) + + def chunk(tag, data): + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", raw) + chunk(b"IEND", b"")) + + +out, width, height = Path(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]) +frames = int(sys.argv[4]) if len(sys.argv) > 4 else 1 +rgb = [int(x) for x in (sys.argv[5] if len(sys.argv) > 5 else "40,120,200").split(",")] +for i in range(frames): + shade = [min(255, c + 12 * i) for c in rgb] + (out / ("frame-%03d.png" % i)).write_bytes(png(width, height, shade)) +''' + +PREP = ("import pathlib, sys; d = pathlib.Path(sys.argv[1], 'data'); d.mkdir(exist_ok=True); " + "(d / 'stats.json').write_text('{\"value\": %s}' % sys.argv[2])") + + +def fake(*args): + return ["{python}", "{manifest_dir}/fake_capture.py", "{out_dir}", "{width}", "{height}", *args] + + +GAME = { + "out": "docs/media", + "vars": {"color": "40,120,200", "value": "40"}, + "shots": [ + {"name": "title", "kind": "still", "backend": "command", "device": {"width": 64, "height": 36}, + "argv": fake("1", "{color}"), "caption": "The title screen.", "alt": "A blue title screen"}, + {"name": "walk", "kind": "clip", "backend": "command", "device": {"width": 48, "height": 32}, + "argv": fake("6"), "gif": {"fps": 6}, "poster": 0.5, "sheet": True, "caption": "Walking."}, + {"name": "versus", "kind": "still", "backend": "command", "device": {"width": 32, "height": 32}, + "argv": fake("1", "{color}"), "format": "png"}, + {"name": "rig", "kind": "prep", "argv": ["{python}", "-c", PREP, "{manifest_dir}", "{value}"], + "outputs": ["data/stats.json"]}, + {"name": "chart", "kind": "still", "backend": "command", "depends": ["rig"], + "device": {"width": 40, "height": 30}, "argv": fake("1", "10,200,10"), "format": "png"}, + ], +} + +DOCS = { + "out": "media", + "vars": {}, + "shots": [ + {"name": "committed", "kind": "still", "backend": "command", "device": {"width": 32, "height": 24}, + "argv": fake("1", "200,40,40"), "format": "png"}, + {"name": "menu", "kind": "still", "backend": "command", "device": {"width": 32, "height": 24}, + "argv": fake("1", "90,90,90"), "format": "png"}, + ], +} + +APPENDED = { + "out": "media", + "vars": {}, + "shots": [ + {"name": "fresh", "kind": "still", "backend": "command", "device": {"width": 24, "height": 24}, + "argv": fake("1", "1,2,3"), "format": "png"}, + ], +} + + +def quiet(*_): + pass + + +def isolate(tmp): + """Lock and run registries out of the real ones (other darkroom runs may be live).""" + os.environ["DARKROOM_LOCK_DIR"] = str(Path(tmp) / "locks") + os.environ["DARKROOM_RUN_DIR"] = str(Path(tmp) / "runs") + + +def lay_down(project, data): + project.mkdir(parents=True, exist_ok=True) + (project / "fake_capture.py").write_text(FAKE_CAPTURE) + data = json.loads(json.dumps(data)) + data["vars"]["python"] = sys.executable + (project / "media.json").write_text(json.dumps(data, indent=2, sort_keys=True) + "\n") + return project / "media.json" + + +def shoot_or_die(path, **kw): + from darkroom.manifest import load + from darkroom.shoot import shoot + failed = shoot(load(path), log=quiet, **kw) + if failed: + raise SystemExit(f"{path}: {failed} shot(s) failed") + + +def write(root): + root = Path(root) + with tempfile.TemporaryDirectory() as tmp: + isolate(tmp) + game = lay_down(root / "projects" / "game", GAME) + shoot_or_die(game) + shoot_or_die(game, only=["versus"], tag="before") + shoot_or_die(game, only=["versus"], tag="after") + + docs = lay_down(root / "projects" / "docs", DOCS) + shoot_or_die(docs, only=["menu"]) + # `committed`: outputs made elsewhere (shot in a scratch copy) and committed, then + # recorded with `shoot --adopt`, so this project has no take for it. + scratch = Path(tmp) / "scratch" + shutil.copytree(docs.parent, scratch) + shoot_or_die(scratch / "media.json", only=["committed"]) + (docs.parent / "media").mkdir(exist_ok=True) + shutil.copyfile(scratch / "media" / "committed.png", docs.parent / "media" / "committed.png") + from darkroom.manifest import load + from darkroom.shoot import adopt + if adopt(load(docs), only=["committed"], log=quiet) != 1: + raise SystemExit("adopt did not record the committed shot") + + +def sha(path): + return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None + + +def tree(path): + """{relative file: sha256} under path (empty when it does not exist).""" + if not path.is_dir(): + return {} + return {str(f.relative_to(path)): sha(f) for f in sorted(path.rglob("*")) if f.is_file()} + + +def state_of(project): + try: + data = json.loads((project / ".darkroom" / "state.json").read_text()) + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + + +def describe(project): + """The reading version's view of one project (see the module docstring).""" + from darkroom.manifest import load + from darkroom.shoot import expected_outputs, shoot + name = project.name + entries = [] + try: + m = load(project / "media.json") + except Exception as e: # noqa: BLE001 — a shot list the reader cannot load is the finding + return [{"project": name, "result": "error", "error": type(e).__name__}], {"loaded": False} + state = state_of(project) + with tempfile.TemporaryDirectory() as tmp: + isolate(tmp) + # darkroom's capture hash includes the project's absolute path (`manifest_dir`), so a + # copy elsewhere would reshoot by design. The shoot runs in place, and the project is + # then put back exactly as it was from a copy taken first. + before = Path(tmp) / "before" + shutil.copytree(project, before) + try: + failed = shoot(load(project / "media.json"), log=quiet) + after = state_of(project) + shots = {s.name: s for s in m.shots} + for key in sorted(state): + entry = state[key] if isinstance(state[key], dict) else {} + shot_name, _, tag = key.partition(".") + shot = shots.get(shot_name) + outputs = [str(o) for o in entry.get("outputs") or []] + take = Path(".darkroom") / "takes" / key + kept = (after.get(key) == entry and tree(before / take) == tree(project / take) + and all(sha(before / o) is not None and sha(before / o) == sha(project / o) for o in outputs)) + view = {"project": name, "key": key, "result": "kept" if kept else "rewritten", + "kind": entry.get("kind", "shot"), "outputs": outputs, + "recorded": {k: entry.get(k) for k in + ("capture_hash", "encode_hash", "hash", "tag", "adopted", "darkroom") if k in entry}, + "take_files": sorted(tree(before / take))} + if shot is None: + view["shot"] = "missing from the shot list" + else: + t = tag or None + view["capture_hash_matches"] = m.capture_hash(shot, None if shot.prep else t) == entry.get("capture_hash") + if not shot.prep: + view["encode_hash_matches"] = m.encode_hash(shot, t) == entry.get("encode_hash") + view["expected_outputs"] = [str(p.relative_to(m.dir)) for p in expected_outputs(m, shot, t)] + entries.append(view) + changed = sorted(set(tree(before)) ^ set(tree(project))) + summary = {"loaded": True, "failed": failed, "new_keys": sorted(set(after) - set(state)), + "files_added_or_removed": changed} + finally: + shutil.rmtree(project) + shutil.copytree(before, project) + return entries, summary + + +def read(root): + projects = sorted(p for p in (Path(root) / "projects").iterdir() if (p / "media.json").is_file()) + saves, summaries = [], {} + for p in projects: + entries, summaries[p.name] = describe(p) + saves += entries + print(json.dumps({"saves": saves, "projects": summaries}, sort_keys=True)) + + +def append(root): + project = Path(root) / "projects" / "appended" + if project.exists(): + raise SystemExit("append target already exists") + with tempfile.TemporaryDirectory() as tmp: + isolate(tmp) + shoot_or_die(lay_down(project, APPENDED)) + + +if __name__ == "__main__": + mode, target = sys.argv[1], sys.argv[2] + {"write": write, "read": read, "append": append}[mode](target) diff --git a/tests/test_tests_gate_version.py b/tests/test_tests_gate_version.py index 71f6cd5..8c4f35e 100644 --- a/tests/test_tests_gate_version.py +++ b/tests/test_tests_gate_version.py @@ -7,7 +7,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "gates")) -from tests_gate import declared_version # noqa: E402 +from tests_gate import declared_version, version_is_dynamic # noqa: E402 def src_with(pyproject=None): @@ -71,5 +71,30 @@ def test_commented_out_version_is_not_read(self): self.assertEqual(declared_version(src), "") +class VersionIsDynamic(unittest.TestCase): + def test_dynamic_version_from_an_attribute(self): + src = src_with('[project]\nname = "graphik"\ndynamic = ["version"]\n\n' + '[tool.setuptools.dynamic]\nversion = { attr = "preponderous.graphik._version.__version__" }\n') + self.assertTrue(version_is_dynamic(src)) + + def test_other_dynamic_fields_alone_are_not_a_dynamic_version(self): + src = src_with('[project]\nname = "x"\nversion = "1.0.0"\ndynamic = ["readme", "dependencies"]\n') + self.assertFalse(version_is_dynamic(src)) + + def test_single_quotes_and_several_fields(self): + src = src_with("[project]\nname = 'x'\ndynamic = ['readme', 'version']\n") + self.assertTrue(version_is_dynamic(src)) + + def test_static_version_is_not_dynamic(self): + self.assertFalse(version_is_dynamic(src_with('[project]\nname = "tak"\nversion = "0.3.1"\n'))) + + def test_dynamic_outside_the_project_table_is_not_read(self): + src = src_with('[project]\nname = "x"\n\n[tool.other]\ndynamic = ["version"]\n') + self.assertFalse(version_is_dynamic(src)) + + def test_no_pyproject_is_not_dynamic(self): + self.assertFalse(version_is_dynamic(src_with())) + + if __name__ == "__main__": unittest.main()