Skip to content

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

25.3 KB
Raw Blame
# SPDX-License-Identifier: Apache-2.0
"""Video -> sprite pipeline contracts on synthetic frames: canvas profiles, edge-contact
keying, global-period cycle detection (incl. the 1.5-cycle trap), seam gate, GIF/WebP
verification, and the batch runner's stagger/429 handling."""

from __future__ import annotations

import json
import math
import shutil
from pathlib import Path

import pytest
from PIL import Image

from sprite_gen._deps import np
from sprite_gen.video import batch as batch_mod
from sprite_gen.video import canvas as canvas_mod
from sprite_gen.video import frames as frames_mod
from sprite_gen.video import loop as loop_mod

GREEN = (0, 255, 0)
HAS_IMG2WEBP = shutil.which("img2webp") is not None and __import__("sprite_gen.video.loop", fromlist=["x"]).img2webp_supports_exact()  # presence is not support: libwebp < 1.3 has no -exact


def _still(tmp_path: Path, size=(120, 160), key=GREEN, name="still.png") -> Path:
    im = Image.new("RGB", size, key)
    for y in range(40, 150):
        for x in range(40, 80):
            im.putpixel((x, y), (200, 40, 40))
    p = tmp_path / name
    im.save(p)
    return p


# --- canvas -------------------------------------------------------------------


def test_profile_table_routes_states_and_shape_overrides() -> None:
    assert canvas_mod.profile_for("jump").shape == "tall"
    assert canvas_mod.profile_for("attack").shape == "wide"
    assert canvas_mod.profile_for("walk").shape == "square"
    assert canvas_mod.profile_for(None).shape == "square"
    assert canvas_mod.profile_for("jump", shape="wide").shape == "wide"
    with pytest.raises(SystemExit, match="unknown --shape"):
        canvas_mod.profile_for("jump", shape="round")


@pytest.mark.parametrize("facing", ["right"])
def test_attack_canvas_reserves_overhead_room_and_reports_placement(tmp_path: Path, facing) -> None:
    still = _still(tmp_path)
    out = tmp_path / "attack.png"
    report = tmp_path / "attack.json"
    rep = canvas_mod.run_canvas(still, out, state="attack", shape=None,
                                facing=facing, headroom=None, lead=None, report_path=report)
    image = Image.open(out)
    x, y = rep["offset"]
    assert rep["headroom"] > 0 and y >= round(image.height * rep["headroom"]) - 1
    assert abs(image.width / image.height - 16 / 9) < 0.01
    assert image.crop((x, y, x + 120, y + 160)).tobytes() == Image.open(still).tobytes()
    assert image.crop((0, 0, image.width, y)).getextrema() == ((0, 0), (255, 255), (0, 0))
    assert json.loads(report.read_text()) == rep
    assert rep["why"] == canvas_mod.STATE_CANVAS["attack"].why
    # Explicit zeros still give the pre-headroom, pre-trail wide layout.
    zero, zero_rep = canvas_mod.pad_canvas(Image.open(still), canvas_mod.profile_for("attack"), headroom=0, trail=0)
    assert zero.size == (284, 160) and zero_rep["offset"] == [0, 0]


@pytest.mark.parametrize("state,size,offset", [
    ("walk", (160, 160), (20, 0)),
    ("jump", (182, 242), (31, 82)),
])
def test_nonattack_canvas_defaults_preserve_pixels(tmp_path: Path, state, size, offset) -> None:
    still = Image.open(_still(tmp_path))
    actual, rep = canvas_mod.pad_canvas(still, canvas_mod.profile_for(state))
    expected = Image.new("RGB", size, GREEN)
    expected.paste(still, offset)
    assert actual.size == expected.size and actual.tobytes() == expected.tobytes()
    assert rep["offset"] == list(offset)


def test_square_canvas_never_shrinks_and_refuses_non_flat_corners(tmp_path: Path) -> None:
    still = Image.open(_still(tmp_path))
    out, rep = canvas_mod.pad_canvas(still, canvas_mod.profile_for("walk"))
    assert out.size == (160, 160) and rep["offset"] == [20, 0]
    bad = Image.new("RGB", (60, 60), GREEN)
    bad.putpixel((0, 0), (255, 255, 255))
    with pytest.raises(SystemExit, match="not one flat colour"):
        canvas_mod.pad_canvas(bad, canvas_mod.profile_for("walk"))


# --- frames ----------------------------------------------------------------------


def _raw_frames(tmp_path: Path, n: int, *, touch_top: bool = False) -> list[Path]:
    d = tmp_path / "raw"
    d.mkdir()
    files = []
    for k in range(n):
        im = Image.new("RGB", (80, 100), GREEN)
        top = 0 if touch_top else 20
        for y in range(top, 90):
            for x in range(25 + (k % 3), 55 + (k % 3)):
                im.putpixel((x, y), (180, 60, 30))
        p = d / f"frame-{k:04d}.png"
        im.save(p)
        files.append(p)
    return files


def test_key_frames_keys_green_and_reports_alpha(tmp_path: Path) -> None:
    files = _raw_frames(tmp_path, 4)
    rep = frames_mod.key_frames(files, tmp_path / "keyed", key="green")
    assert rep["frames"] == 4 and rep["edge_contacts"] == []
    assert rep["alpha_zero_pct_min"] > 50
    keyed = Image.open(tmp_path / "keyed" / "frame-0000.png").convert("RGBA")
    assert keyed.getpixel((0, 0))[3] == 0 and keyed.getpixel((40, 50))[3] > 0


# --- loop ----------------------------------------------------------------------------


def _gait_frames(tmp_path: Path, *, period: int, n: int, size=(64, 64), stamp: bool = False) -> list[Path]:
    """A 'walker': a body block plus one leg that swings with `period`; the swing is
    mirror-symmetric every half period (the classic 1.5-cycle trap) but a side marker
    breaks the symmetry slightly, exactly like a near/far leg in a side view."""
    d = tmp_path / "keyed"
    d.mkdir()
    files = []
    for t in range(n):
        im = Image.new("RGBA", size, (0, 0, 0, 0))
        for y in range(10, 40):
            for x in range(26, 38):
                im.putpixel((x, y), (200, 60, 60, 255))
        phase = 2 * math.pi * t / period
        leg_x = 32 + round(10 * math.sin(phase))
        for y in range(40, 58):
            for x in range(leg_x - 3, leg_x + 3):
                if 0 <= x < size[0]:
                    im.putpixel((x, y), (60, 60, 200, 255))
        # near-leg marker only on the first half of the period
        if math.sin(phase) >= 0:
            im.putpixel((leg_x, 50), (255, 255, 0, 255))
        if stamp:  # recolour one BODY pixel per frame so no two frames are identical (a detached
            # marker would be erased as a speck; GIF writers merge byte-identical frames)
            im.putpixel((26 + t % 12, 10 + (t // 12) % 30), (90, 200, 90, 255))
        p = d / f"frame-{t:04d}.png"
        im.save(p)
        files.append(p)
    return files


def test_detect_cycle_finds_the_full_period_not_the_half_or_1_5x(tmp_path: Path) -> None:
    files = _gait_frames(tmp_path, period=12, n=100)
    D = loop_mod.distance_matrix(files)
    cycle = loop_mod.detect_cycle(D, min_len=4, max_len=40)
    assert cycle["period_global"] == 12
    assert cycle["length"] in (11, 12, 13)
    # The cut closes exactly: the frame that would come next IS the frame it jumps back to.
    assert cycle["next_frame_distance"] == pytest.approx(0.0, abs=1e-6)
    # `ratio` scores the step that actually plays at the wrap, so it is a step of this
    # cycle and not a number that shrinks toward zero. The fixture's leg is a rounded
    # sine, which makes its own steps lumpy (1.50 1.20 0.32 0.32 1.20 1.50 ... x the mean),
    # so the closest any cut can put the wrap to an average step here is ~1.2.
    assert 0.9 < cycle["ratio"] < 1.6


def test_detect_cycle_refuses_empty_window() -> None:
    D = np.zeros((10, 10), dtype=np.float32)
    with pytest.raises(SystemExit, match="window"):
        loop_mod.detect_cycle(D, min_len=9, max_len=8)


@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")
def test_run_loop_emits_strip_gif_webp_and_verifies(tmp_path: Path) -> None:
    files = _gait_frames(tmp_path, period=12, n=96)
    rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="walker", report_path=None, repair="off")
    # 12 frames at 24 fps is half a second — below the walk gait floor (0.6 s), so the
    # half-period guard doubles it to the two-step 24 and records that it did
    assert rep["cycle"]["period_global"] == 24
    assert rep["cycle"]["half_period_guard"]["applied"] is True and rep["cycle"]["half_period_guard"]["from"] == 12
    assert rep["resampled_seam_ratio"] <= 2.0
    strip = Image.open(rep["strip"]["path"])
    assert strip.size == (rep["strip"]["w"] * rep["strip"]["frames"], rep["strip"]["h"])
    assert rep["strip"]["body_h"] <= rep["strip"]["h"]
    assert rep["gif"]["n_frames"] == 8 and rep["gif"]["loop"] == 0 and rep["gif"]["corners_transparent"]
    assert rep["webp"]["n_frames"] == 8 and rep["webp"]["stale_rgb_under_alpha0"] == 0
    assert json.loads((tmp_path / "out" / "walker.strip.json").read_text())["frames"] == rep["strip"]["frames"]
    assert len(list((tmp_path / "out" / "cycle").glob("frame-*.png"))) == rep["cycle"]["length"]


def test_run_loop_seam_gate_fails_loud_on_noise(tmp_path: Path, monkeypatch) -> None:
    d = tmp_path / "keyed"
    d.mkdir()
    rng = np.random.default_rng(7)
    for t in range(40):
        arr = np.zeros((48, 48, 4), dtype=np.uint8)
        mask = rng.random((48, 48)) > 0.6
        arr[..., 0][mask] = 200
        arr[..., 3][mask] = 255
        Image.fromarray(arr, "RGBA").save(d / f"frame-{t:04d}.png")
    with pytest.raises(SystemExit, match="seam ratio|no periodic cycle"):
        loop_mod.run_loop(d, tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=6, seam_max=2.0, name="noise", report_path=None, repair="off")
    assert not (tmp_path / "out" / "noise.gif").exists()


def _one_shot_frames(tmp_path: Path, n: int = 144, hop: tuple[int, int] = (60, 76), size=(64, 64), jitter: int = 2) -> list[Path]:
    """A body that stands (with a little rest jitter, like a real keyed clip) except for ONE
    hop between the given frames — what a video model does when it ignores 'over and over'
    (2026-09-09 quadruped run)."""
    d = tmp_path / "keyed"
    d.mkdir()
    files = []
    rng = np.random.default_rng(3)
    for t in range(n):
        im = Image.new("RGBA", size, (0, 0, 0, 0))
        lift = 0
        if hop[0] <= t < hop[1]:
            lift = round(14 * math.sin(math.pi * (t - hop[0]) / (hop[1] - hop[0])))
        dx = int(rng.integers(-jitter, jitter + 1))
        dy = int(rng.integers(-jitter, jitter + 1))
        for y in range(20 - lift + dy, 58 - lift + dy):
            for x in range(24 + dx, 40 + dx):
                im.putpixel((x, y), (200, 60, 60, 255))
        p = d / f"frame-{t:04d}.png"
        im.save(p)
        files.append(p)
    return files


def test_one_shot_detector_cuts_rest_excursion_rest(tmp_path: Path) -> None:
    files = _one_shot_frames(tmp_path)
    D = loop_mod.distance_matrix(files)
    periodic = loop_mod.detect_cycle(D, min_len=16, max_len=65)
    assert periodic["periodicity"] < loop_mod.PERIODICITY_MIN  # one hop is not a period
    cycle = loop_mod.detect_one_shot(D, min_len=9, max_len=65)
    assert cycle["kind"] == "one-shot"
    assert cycle["start"] <= 60 and cycle["start"] + cycle["length"] >= 75  # covers the hop, rest on both sides
    assert cycle["ratio"] < 2.0  # rest -> rest seam within the gate


def test_one_shot_detector_fails_loud_when_nothing_moves(tmp_path: Path) -> None:
    files = _one_shot_frames(tmp_path, n=60, hop=(0, 0), jitter=0)
    D = loop_mod.distance_matrix(files)
    with pytest.raises(SystemExit, match="never leaves its rest pose"):
        loop_mod.detect_one_shot(D, min_len=4, max_len=60)


@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")
def test_run_loop_auto_fails_over_to_one_shot_only_for_action_states(tmp_path: Path) -> None:
    _one_shot_frames(tmp_path)
    # walk must not repeat once: the gate stays a hard failure
    with pytest.raises(SystemExit, match="no periodic cycle"):
        loop_mod.run_loop(tmp_path / "keyed", tmp_path / "walk", fps=24.0, state="walk", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="w", report_path=None, repair="off")
    # jump may happen once: recorded failover, periodic attempt kept in the report
    rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "jump", fps=24.0, state="jump", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="j", report_path=None)
    assert rep["cycle"]["kind"] == "one-shot" and rep["cycle_mode"] == "auto"
    assert rep["periodic_attempt"]["periodicity"] < loop_mod.PERIODICITY_MIN
    assert rep["gif"]["loop"] == 0 and rep["webp"]["stale_rgb_under_alpha0"] == 0
    # forcing periodic keeps the old behaviour
    with pytest.raises(SystemExit, match="no periodic cycle"):
        loop_mod.run_loop(tmp_path / "keyed", tmp_path / "jump2", fps=24.0, state="jump", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="j2", report_path=None, cycle_mode="periodic")


def test_strip_cap_is_on_pixels_not_cells() -> None:
    # 100 wide frames (body 700 px across): 64 cells would be 44,800 px — Chrome cannot show it
    frames = []
    for t in range(100):
        im = Image.new("RGBA", (720, 300), (0, 0, 0, 0))
        im.paste((200, 60, 60, 255), (10, 40 + (t % 7), 710, 300))
        frames.append(im)
    strip, meta = loop_mod.build_strip(frames, cycle_seconds=100 / 24)
    assert strip.width <= loop_mod.STRIP_MAX_WIDTH
    assert meta["frames"] == meta["cell_cap"] < 64 and meta["subsampled"] is True
    assert strip.width == meta["w"] * meta["frames"]


@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")
def test_gif_frame_count_follows_cycle_length_at_a_fixed_playback_rate(tmp_path: Path) -> None:
    """A 2.5 s jump used to get the same 12 frames as a 1.1 s walk and play at ~5 fps
    (2026-09-09, lead: '점프만 혼자 왜 프레임이 느리냐')."""
    (tmp_path / "long").mkdir()
    _gait_frames(tmp_path / "long", period=60, n=150, stamp=True)  # 60 frames @ 24 fps = 2.5 s
    rep = loop_mod.run_loop(tmp_path / "long" / "keyed", tmp_path / "long-out", fps=24.0, state="jump", min_len=None, max_len=None, n_out=None, seam_max=2.0, name="j", report_path=None, gif_fps=12.0)
    assert rep["n_out"] == 30 and 80 <= rep["delay_ms"] <= 90
    (tmp_path / "short").mkdir()
    _gait_frames(tmp_path / "short", period=26, n=100, stamp=True)  # 1.08 s
    rep2 = loop_mod.run_loop(tmp_path / "short" / "keyed", tmp_path / "short-out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=2.0, name="w", report_path=None, gif_fps=12.0, repair="off")
    assert 12 <= rep2["n_out"] <= 14 and abs(rep2["delay_ms"] - rep["delay_ms"]) <= 15  # ~1.1 s at 12 fps; the period may resolve to 24-26
    explicit = loop_mod.run_loop(tmp_path / "short" / "keyed", tmp_path / "short-out2", fps=24.0, state="walk", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="w8", report_path=None, repair="off")
    assert explicit["n_out"] == 8
    assert rep["n_out"] <= rep["cycle"]["length"] and rep2["n_out"] <= rep2["cycle"]["length"]


@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")
def test_default_gif_rate_keeps_every_cycle_frame(tmp_path: Path) -> None:
    """24 fps source, 24 fps GIF: a 61-frame jump cycle stays 61 frames at ~42 ms."""
    (tmp_path / "j").mkdir()
    _gait_frames(tmp_path / "j", period=61, n=150, stamp=True)
    rep = loop_mod.run_loop(tmp_path / "j" / "keyed", tmp_path / "j-out", fps=24.0, state="jump", min_len=None, max_len=None, n_out=None, seam_max=2.0, name="j", report_path=None)
    assert rep["n_out"] == rep["cycle"]["length"] and 40 <= rep["delay_ms"] <= 43 and rep["gif_fps"] == 24.0


@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")
def test_fixed_cycle_cuts_exactly_and_skips_detection(tmp_path: Path) -> None:
    """A clip with too few repeats for the periodicity gate can still be cut where the
    caller says (2026-09-09: the reel's jump clip held 2.3 hops)."""
    _one_shot_frames(tmp_path)  # 144 frames, one hop at 60..76 — no period at all
    rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "fx", fps=24.0, state="jump", min_len=None, max_len=None, n_out=None, seam_max=5.0, name="f", report_path=None, cycle_mode="fixed", start=50, length=40)
    assert rep["cycle"]["kind"] == "fixed" and rep["cycle"]["start"] == 50 and rep["cycle"]["length"] == 40
    assert rep["periodic_attempt"] is None and len(list((tmp_path / "fx" / "cycle").glob("frame-*.png"))) == 40
    with pytest.raises(SystemExit, match="does not fit"):
        loop_mod.run_loop(tmp_path / "keyed", tmp_path / "fx2", fps=24.0, state="jump", min_len=None, max_len=None, n_out=None, seam_max=5.0, name="f2", report_path=None, cycle_mode="fixed", start=120, length=40)
    with pytest.raises(SystemExit, match="needs --start"):
        loop_mod.run_loop(tmp_path / "keyed", tmp_path / "fx3", fps=24.0, state="jump", min_len=None, max_len=None, n_out=None, seam_max=5.0, name="f3", report_path=None, cycle_mode="fixed")


@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")
def test_strip_height_caps_the_output_size(tmp_path: Path) -> None:
    files = _gait_frames(tmp_path, period=12, n=60, size=(160, 400))
    rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "h", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=2.0, name="h", report_path=None, strip_height=100, repair="off")
    assert rep["strip"]["h"] <= 100
    assert Image.open(rep["gif"]["file"] if Path(rep["gif"]["file"]).is_absolute() else tmp_path / "h" / rep["gif"]["file"]).height <= 100


def test_body_h_is_the_standing_height_not_the_cycle_median() -> None:
    """A jump cycle: 10 standing frames (60 px tall), 20 crouched (40 px) and 30 airborne
    (60 px, lifted). The median height is not the standing height; body_h must be 60 and
    --body-height must scale the standing frames, not the median."""
    frames = []
    def body(top, height):
        im = Image.new("RGBA", (80, 120), (0, 0, 0, 0))
        for y in range(top, top + height):
            for x in range(30, 50):
                im.putpixel((x, y), (200, 60, 60, 255))
        return im
    frames += [body(60, 60) for _ in range(10)]        # standing on the floor (bottom = 119)
    frames += [body(80, 40) for _ in range(20)]        # crouched on the floor
    frames += [body(20, 60) for _ in range(30)]        # airborne (bottom = 79)
    strip, meta = loop_mod.build_strip(frames, cycle_seconds=60 / 24)
    assert meta["body_h"] == 60
    strip2, meta2 = loop_mod.build_strip(frames, cycle_seconds=60 / 24, body_height=30)
    assert meta2["body_h"] == 30 and meta2["body_height_target"] == 30 and meta2["h"] == 54  # union crop 108 px (8 px top margin) → 0.5
    strip3, meta3 = loop_mod.build_strip(frames, cycle_seconds=60 / 24, body_height=30, max_height=40)
    assert meta3["h"] <= 40, "--strip-height stays the cap"


def test_body_height_measures_the_clips_first_frame_not_a_raised_weapon(tmp_path: Path) -> None:
    """Every clip starts from its still, so the first frame is the one pose all of a
    character's states share. An attack's tallest grounded frame is its windup with the
    weapon overhead; scaled to the target, it made the attacking character smaller than
    the walking one."""
    files = _gait_frames(tmp_path, period=12, n=72)
    for path in files[1:]:  # from the second frame on, something is held up above the head
        im = Image.open(path)
        for y in range(2, 10):
            im.putpixel((36, y), (120, 120, 120, 255))
        im.save(path)
    rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None,
                            n_out=8, seam_max=9.0, name="w", report_path=None, body_height=48, repair="off")
    meta = json.loads((tmp_path / "out" / "w.strip.json").read_text())
    assert meta["body_ref"] == "first-frame"
    assert (meta["body_src_h"], meta["scale"], meta["body_h"]) == (48, 1.0, 48)  # the raised frames are 56 tall
    assert rep["strip"]["body_h"] == 48
    # without a target nothing changes: the tallest grounded frame, never scaled up
    loop_mod.run_loop(tmp_path / "keyed", tmp_path / "plain", fps=24.0, state="walk", min_len=None, max_len=None,
                      n_out=8, seam_max=9.0, name="w", report_path=None, repair="off")
    plain = json.loads((tmp_path / "plain" / "w.strip.json").read_text())
    assert plain["body_ref"] == "tallest-grounded" and plain["body_src_h"] == 56


def test_body_height_is_a_target_across_states_not_a_downward_clamp() -> None:
    """`--body-height` exists so the same number across states gives one character size.
    That only holds if a state whose source body is SHORTER than the request scales UP:
    a 40 px walk and an 80 px jump both asked for 60 must both come out 60. Clamping the
    scale to 1.0 first left the short one at 40 and the tall one at 60 — two sizes from
    the one option meant to produce one."""
    def body(height: int) -> Image.Image:
        im = Image.new("RGBA", (80, 120), (0, 0, 0, 0))
        for y in range(120 - height, 120):        # standing on the floor
            for x in range(30, 50):
                im.putpixel((x, y), (200, 60, 60, 255))
        return im

    short = [body(40) for _ in range(4)]
    tall = [body(80) for _ in range(4)]
    _, short_meta = loop_mod.build_strip(short, cycle_seconds=4 / 24, body_height=60)
    _, tall_meta = loop_mod.build_strip(tall, cycle_seconds=4 / 24, body_height=60)
    assert short_meta["body_h"] == tall_meta["body_h"] == 60
    # the sidecar says which one was filmed small: the short body was upscaled, the tall one was not
    assert (short_meta["body_src_h"], short_meta["scale"]) == (40, 1.5)
    assert (tall_meta["body_src_h"], tall_meta["scale"]) == (80, 0.75)

    # No body_height still never scales up: that is what --strip-height is for.
    _, plain = loop_mod.build_strip(short, cycle_seconds=4 / 24)
    assert plain["body_h"] == 40

    # The cell cap still beats the target, and the miss stays visible in the meta.
    _, capped = loop_mod.build_strip(short, cycle_seconds=4 / 24, body_height=60, max_height=40)
    assert capped["h"] <= 40
    assert capped["body_height_target"] == 60 and capped["body_h"] < 60


# --- batch -------------------------------------------------------------------------------


def test_motion_templates_do_not_assume_a_body_plan() -> None:
    # the templates were first written for a biped; a quadruped or a legless blob must not
    # be prompted into a contradiction (2026-09-09 generalization run)
    for state, text in [*batch_mod.MOTION_TEXT.items(), *batch_mod.VIEW_MOTION_TEXT.items()]:
        for word in (
            "bipedal",
            "knees",
            "arms pumping",
            "arms swinging",
            "limbs alternating",
            "Feet never",
            "alternating strides",
            "crouch,",  # biped verb; jump uses "compress" instead
        ):
            assert word not in text, (state, word)


def test_run_set_runs_each_clip_once_and_tables_failures(tmp_path: Path, monkeypatch) -> None:
    """A 429 is sent again inside `sprite-gen video` (gen.retry); the set does not run the clip a second
    time on top of that, which would make every one of its POSTs a second retry loop."""
    monkeypatch.setattr(batch_mod.facing_mod.vision, "grok_inspect", lambda *a, **kw: ("right", {}))
    base = _still(tmp_path)
    calls: list[tuple[str, float]] = []
    import time as _time

    def fake_video(image, prompt, out, report, *, duration, resolution, log):
        calls.append((out.parent.name, _time.monotonic()))
        item = out.parent.name
        if item == "side-jump":
            log.write_text("video: generation request refused (HTTP 429): resource-exhausted")
            return 1
        out.write_bytes(b"\x00\x00\x00\x18ftypisom")
        report.write_text("{}")
        log.write_text("ok")
        return 0

    monkeypatch.setattr(batch_mod.time, "sleep", lambda s: None)  # no real stagger waits
    monkeypatch.setattr(frames_mod, "run_frames", lambda clip, out_dir, **kw: {"fps": 24.0, "frames": 10, "alpha_zero_pct_min": 60.0, "alpha_zero_pct_max": 70.0, "keyed_dir": str(out_dir / "keyed")})
    monkeypatch.setattr(batch_mod.frames_mod, "run_frames", frames_mod.run_frames)
    monkeypatch.setattr(batch_mod.loop_mod, "run_loop", lambda frames_dir, out_dir, **kw: {"cycle": {"length": 12, "period_global": 12, "ratio": 0.3, "review_recommended": kw["state"] == "run"}, "resampled_seam_ratio": 0.5, "held_fill": {"cells": 10, "poses": 10, "held_runs": [], "made": [], "before": {"cells": 10, "poses": 10, "held_runs": []}}, "n_out": 12, "gif": {"file": "x.gif"}, "webp": {"file": "x.webp"}, "strip": {"path": "x.png"}})

    payload = batch_mod.run_set(bases={"side": base}, states=["walk", "run", "jump"], root=tmp_path / "set", character=None, duration=6, resolution="720p", key="green", concurrency=3, force=False, gap=0.0, video_runner=fake_video)

    by = {r["item"]: r for r in payload["items"]}
    assert by["side-walk"]["ok"] and by["side-walk"]["clip"]["attempts"] == [0]
    assert by["side-run"]["ok"] and by["side-run"]["clip"]["attempts"] == [0]
    assert not by["side-jump"]["ok"] and "clip generation failed" in by["side-jump"]["error"]
    assert by["side-jump"]["clip"]["attempts"] == [1] and [c[0] for c in calls].count("side-jump") == 1  # never run again by the set
    assert by["side-run"]["loop"]["review_recommended"] is True
    assert by["side-walk"]["loop"]["review_recommended"] is False
    assert payload["failed"] == ["side-jump"]
    table = (tmp_path / "set" / "table.md").read_text()
    assert "| side | jump | - | - | - | - | - | FAIL" in table and "| side | walk | periodic | 12 | 12 | 0.50 | 12 | OK |" in table
    assert "| side | run | periodic | 12 | 12 | 0.50 | 12 | OK (review gait) |" in table
    assert (tmp_path / "set" / "set.report.json").is_file()
    assert (tmp_path / "set" / "side-walk" / "canvas.png").is_file()  # canvas ran for real