Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

fix(scene): refuse conflicting byte snapshots for one scene input path

Soohong Kimb7760776c5ba
diff --git a/sprite_gen/scene/model.py b/sprite_gen/scene/model.py
index 72fa64e..029344e 100644
--- a/sprite_gen/scene/model.py
+++ b/sprite_gen/scene/model.py
@@ -1,5 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
-"""Scene layout and time belong here; source frames belong to asset metadata."""
+"""Scene layout and time belong here; source frames belong to asset metadata.
+
+The scene also owns the scene-wide input fingerprint map: one digest per
+resolved path for the spec, every asset file and every stride report, each
+hashed from the bytes that were actually parsed or decoded. Inputs that are
+read more than once must come back as the same bytes, or the scene is refused.
+"""
from __future__ import annotations
from dataclasses import dataclass
@@ -36,6 +42,23 @@ def read_json(path: Path) -> tuple[object, str]:
return json.loads(data.decode("utf-8")), hashlib.sha256(data).hexdigest()
+def merge_fingerprints(fingerprints: dict, more: dict) -> dict:
+ """Add ``more`` to a scene-wide fingerprint map that keeps one digest per path.
+
+ One path may legitimately be read more than once while a scene loads: two
+ asset names can share a file, two states share an atlas, two layers share a
+ stride report. A path that comes back with a different digest was replaced
+ between those reads, so the scene would hold two versions of one input while
+ attesting to only one of them. That is refused with the map left untouched;
+ neither digest is preferred and nothing is read again.
+ """
+ changed = sorted(path for path, digest in more.items() if fingerprints.get(path, digest) != digest)
+ if changed:
+ raise ValueError(f"scene inputs changed during load; read twice as different bytes: {', '.join(changed)}")
+ fingerprints.update(more)
+ return fingerprints
+
+
@dataclass
class Layer:
id: str
@@ -145,7 +168,7 @@ def load_scene(path: Path) -> Scene:
raise ValueError(f"asset {name} requires a source path")
asset = load_asset(path.parent / reference["source"], state=reference.get("state"))
assets[name] = asset
- fingerprints.update(asset.fingerprints())
+ merge_fingerprints(fingerprints, asset.fingerprints())
entries = data.get("layers")
if not isinstance(entries, list) or not entries:
raise ValueError("scene layers must be a nonempty list")
@@ -187,7 +210,7 @@ def load_scene(path: Path) -> Scene:
# the raster scale actually used for this layer times the playback rate.
raster_scale = raster_size[0] / seq.size[0]
velocity = (speed*raster_scale*rate*(-1 if stride["direction"] == "left" else 1), 0)
- fingerprints[str(rp)] = report_digest
+ merge_fingerprints(fingerprints, {str(rp): report_digest})
velocity = tuple(a+b for a, b in zip(plane_v, velocity))
period = finite(entry.get("period", seq.size[0]), "repeat period", positive=True)
if period > seq.size[0] or int(period) != period or round(period*scale) < 1:
diff --git a/tests/scene/test_model.py b/tests/scene/test_model.py
index 5056e45..9c7a371 100644
--- a/tests/scene/test_model.py
+++ b/tests/scene/test_model.py
@@ -10,7 +10,8 @@ from PIL import Image, ImageDraw
from sprite_gen.qa.motion import analyze_motion
from sprite_gen.scene import model
-from sprite_gen.scene.model import bound_stride, load_scene
+from sprite_gen.scene.model import bound_stride, load_scene, merge_fingerprints
+from sprite_gen.spec import assets
from sprite_gen.spec.assets import load_asset
@@ -182,6 +183,90 @@ def test_scene_and_report_identity_are_the_parsed_bytes(tmp_path, monkeypatch):
assert loaded.layers[0].velocity == (pytest.approx(20), 0)
+def test_merge_fingerprints_keeps_one_digest_per_path_and_refuses_a_second_without_touching_the_map():
+ known = {"/scene.json": "a", "/actor.png": "b"}
+ assert merge_fingerprints(known, {"/actor.png": "b", "/atlas.png": "c"}) is known
+ assert known == {"/scene.json": "a", "/actor.png": "b", "/atlas.png": "c"}
+ with pytest.raises(ValueError, match=r"changed during load.*/actor\.png, /scene\.json"):
+ merge_fingerprints(known, {"/report.json": "d", "/scene.json": "A", "/actor.png": "B"})
+ assert known == {"/scene.json": "a", "/actor.png": "b", "/atlas.png": "c"}
+
+
+def test_shared_asset_file_replaced_between_two_loads_is_refused(tmp_path, monkeypatch):
+ actor = tmp_path / "actor.png"
+ Image.new("RGBA", (4, 4), "red").save(actor)
+ spec = scene(tmp_path, assets={"first": "actor.png", "second": "actor.png"},
+ layers=[{"id": "first", "asset": "first", "at": [12, 40]}, {"id": "second", "asset": "second", "at": [36, 40]}])
+ original = assets._read_bytes
+ reads = []
+
+ def read_then_replace_once(path):
+ data = original(path)
+ if Path(path).name == "actor.png":
+ reads.append(data)
+ if len(reads) == 1:
+ Image.new("RGBA", (4, 4), "blue").save(actor)
+ return data
+
+ monkeypatch.setattr(assets, "_read_bytes", read_then_replace_once)
+ # Each asset's own snapshot is right; the scene must not attest to one file with two byte histories.
+ with pytest.raises(ValueError, match=r"changed during load.*actor\.png"):
+ load_scene(spec)
+ assert len(reads) == 2 and reads[0] != reads[1]
+ monkeypatch.undo()
+ loaded = load_scene(spec)
+ assert loaded.source_fingerprints[str(actor.resolve())] == sha(actor)
+ assert loaded.assets["first"].fingerprints() == loaded.assets["second"].fingerprints() == {str(actor.resolve()): sha(actor)}
+
+
+def test_stride_report_replaced_between_two_layers_reads_is_refused(tmp_path, monkeypatch):
+ atlas(tmp_path)
+ report = motion_report(tmp_path, state="walk")
+ spec = scene(tmp_path, layers=[
+ {"id": "left", "asset": "walk", "at": [12, 40], "stride": {"report": report.name, "direction": "left"}},
+ {"id": "right", "asset": "walk", "at": [36, 40], "stride": {"report": report.name, "direction": "right"}},
+ ])
+ original = model.read_json
+ digests = []
+
+ def read_then_double_the_stride_once(path):
+ document, digest = original(path)
+ if Path(path) == report.resolve():
+ digests.append(digest)
+ if len(digests) == 1:
+ report.write_text(json.dumps({**document, "stride_px_per_second": 2 * document["stride_px_per_second"]}))
+ return document, digest
+
+ monkeypatch.setattr(model, "read_json", read_then_double_the_stride_once)
+ with pytest.raises(ValueError, match=r"changed during load.*walk\.motion\.json"):
+ load_scene(spec)
+ assert len(digests) == 2 and digests[0] != digests[1]
+ # Both versions pass the per-report gate for this sequence; only the scene-wide map tells them apart.
+ assert bound_stride(json.loads(report.read_text()), load_asset(tmp_path / "atlas.json", state="walk")) == pytest.approx(40)
+ monkeypatch.undo()
+ loaded = load_scene(spec)
+ assert [layer.velocity for layer in loaded.layers] == [(pytest.approx(-40), 0), (pytest.approx(40), 0)]
+ assert loaded.source_fingerprints[str(report.resolve())] == sha(report)
+
+
+def test_unchanged_repeated_references_share_one_digest_per_path(tmp_path):
+ atlas(tmp_path)
+ Image.new("RGBA", (4, 4), "red").save(tmp_path / "actor.png")
+ report = motion_report(tmp_path, state="walk")
+ loaded = load_scene(scene(tmp_path, assets={"walk": {"source": "atlas.json", "state": "walk"}, "idle": {"source": "atlas.json", "state": "idle"},
+ "first": "actor.png", "second": "actor.png"},
+ layers=[{"id": "left", "asset": "walk", "at": [12, 40], "stride": {"report": report.name, "direction": "left"}},
+ {"id": "right", "asset": "walk", "at": [36, 40], "stride": {"report": report.name, "direction": "right"}},
+ {"id": "still", "asset": "idle", "at": [24, 40]},
+ {"id": "first", "asset": "first", "at": [8, 40]},
+ {"id": "second", "asset": "second", "at": [40, 40]}]))
+ assert loaded.source_fingerprints == {str((tmp_path / name).resolve()): sha(tmp_path / name)
+ for name in ("scene.json", "atlas.json", "atlas.png", "actor.png", report.name)}
+ by_id = {layer.id: layer for layer in loaded.layers}
+ assert by_id["left"].velocity == (pytest.approx(-20), 0) and by_id["right"].velocity == (pytest.approx(20), 0)
+ assert by_id["still"].velocity == by_id["first"].velocity == by_id["second"].velocity == (0, 0)
+
+
@pytest.mark.parametrize("overrides, message", [
({"kind": "scene"}, "kind sprite-gen-scene"),
({"extra": 1}, "unknown scene fields"),
diff --git a/tests/scene/test_render.py b/tests/scene/test_render.py
index 8da98cc..6c30245 100644
--- a/tests/scene/test_render.py
+++ b/tests/scene/test_render.py
@@ -232,6 +232,34 @@ def test_input_replaced_after_decoding_is_detected_and_nothing_is_published(tmp_
assert frame.getpixel((2, 2)) == BLUE
+def test_shared_source_replaced_between_asset_loads_fails_before_any_output_exists(tmp_path, monkeypatch):
+ actor = square(tmp_path / "actor.png")
+ spec = write_scene(tmp_path, [{"id": "left", "asset": "first", "at": [4, 8]}, {"id": "right", "asset": "second", "at": [12, 8]}],
+ assets={"first": "actor.png", "second": "actor.png"}, height=8, fps=1, duration=1)
+ original = assets._read_bytes
+ reads = []
+
+ def replace_after_first_read(path):
+ data = original(path)
+ if Path(path).name == "actor.png":
+ reads.append(data)
+ if len(reads) == 1:
+ square(actor, BLUE)
+ return data
+
+ monkeypatch.setattr(assets, "_read_bytes", replace_after_first_read)
+ out = tmp_path / "out"
+ with pytest.raises(ValueError, match="changed during load"):
+ render_scene(spec, out, formats="png")
+ assert len(reads) == 2 and reads[0] != reads[1]
+ assert not out.exists() and sorted(p.name for p in tmp_path.iterdir()) == ["actor.png", "scene.json"]
+ monkeypatch.undo()
+ report = render_scene(spec, out, formats="png")
+ assert report["source_fingerprints"][str(actor.resolve())] == hashlib.sha256(actor.read_bytes()).hexdigest()
+ with Image.open(out / "check-00000.png") as frame:
+ assert frame.getpixel((4, 6)) == BLUE and frame.getpixel((12, 6)) == BLUE
+
+
@pytest.mark.parametrize("problem", ["inputs-inside", "nonempty", "live-lock", "file"])
def test_output_directory_rules_are_enforced_without_touching_the_destination(tmp_path, problem):
spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}])