File size: 12,918 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
"""Determinism and integrity tests for published reference frame sequences.

The sequence becomes a benchmark input, so the same recording must always yield
the same bytes and the same ordered digest, and a tampered or reordered export
must not load.
"""

from __future__ import annotations

import json
import subprocess
from pathlib import Path

import pytest

from bench_builder import reference_frames


def _synthetic_recording(path: Path, *, seconds: int = 6) -> Path:
    """Render a short deterministic clip with the bundled FFmpeg build."""

    import imageio_ffmpeg

    path.parent.mkdir(parents=True, exist_ok=True)
    completed = subprocess.run(
        (
            imageio_ffmpeg.get_ffmpeg_exe(),
            "-nostdin",
            "-v",
            "error",
            "-f",
            "lavfi",
            "-i",
            f"testsrc=size=320x180:rate=10:duration={seconds}",
            "-pix_fmt",
            "yuv420p",
            "-y",
            str(path),
        ),
        capture_output=True,
        timeout=180,
        check=False,
    )
    if completed.returncode != 0 or not path.is_file():
        pytest.skip("the bundled FFmpeg build could not render a synthetic recording")
    return path


def _menu_then_play_recording(path: Path) -> Path:
    """Render a clip that holds a static screen longer than it shows movement.

    This is the shape that made the old rules fail: the menu occupies most of the
    session, so both "the last frame" and "the most typical frame" land on it.
    """

    import imageio_ffmpeg

    path.parent.mkdir(parents=True, exist_ok=True)
    completed = subprocess.run(
        (
            imageio_ffmpeg.get_ffmpeg_exe(),
            "-nostdin",
            "-v",
            "error",
            "-f",
            "lavfi",
            "-i",
            "color=c=navy:size=320x180:rate=10:duration=8",
            "-f",
            "lavfi",
            "-i",
            "testsrc=size=320x180:rate=10:duration=4",
            "-f",
            "lavfi",
            "-i",
            "color=c=maroon:size=320x180:rate=10:duration=4",
            "-filter_complex",
            "[0:v][1:v][2:v]concat=n=3:v=1[out]",
            "-map",
            "[out]",
            "-pix_fmt",
            "yuv420p",
            "-y",
            str(path),
        ),
        capture_output=True,
        timeout=180,
        check=False,
    )
    if completed.returncode != 0 or not path.is_file():
        pytest.skip("the bundled FFmpeg build could not render a synthetic recording")
    return path


def _trajectory(path: Path) -> Path:
    path.write_text(
        "\n".join(
            json.dumps(item)
            for item in (
                {"event": "key_press", "key": "ArrowRight", "time_ns": 1_000_000_000, "seq": 1},
                {
                    "event": "mouse_move",
                    "normalized_x": 0.2,
                    "normalized_y": 0.3,
                    "time_ns": 9_000_000_000,
                    "seq": 2,
                },
                {
                    "event": "mouse_move",
                    "normalized_x": 0.8,
                    "normalized_y": 0.7,
                    "time_ns": 9_200_000_000,
                    "seq": 3,
                },
                {
                    "event": "mouse_press",
                    "normalized_x": 0.8,
                    "normalized_y": 0.7,
                    "time_ns": 9_300_000_000,
                    "seq": 4,
                },
            )
        )
        + "\n",
        encoding="utf-8",
    )
    return path


def test_still_selection_prefers_movement_over_the_longest_held_screen() -> None:
    # Eleven identical menu frames, then four that move: a plain medoid would take
    # the menu because it is the most common picture in the session.
    pixels = 160 * 90 * 3
    menu = bytes(pixels)
    play = [
        bytes((index * 37 + offset) % 256 for offset in range(pixels)) for index in range(4)
    ]
    thumbnails = [menu] * 11 + play

    chosen = reference_frames.select_design_still_index(thumbnails)
    motion = reference_frames.frame_motion(thumbnails)

    assert chosen >= 11
    assert motion[chosen] > 0.0
    assert motion[5] == pytest.approx(0.0)


def test_still_selection_is_deterministic_and_handles_a_motionless_session() -> None:
    identical = [bytes(160 * 90 * 3)] * 4

    assert reference_frames.select_design_still_index(identical) == 0
    assert reference_frames.select_design_still_index([bytes(3)]) == 0
    with pytest.raises(reference_frames.ReferenceFrameError, match="empty sequence"):
        reference_frames.select_design_still_index([])


def test_exported_still_comes_from_play_and_not_the_end_of_the_session(
    tmp_path: Path,
) -> None:
    video = _menu_then_play_recording(tmp_path / "recording" / "session.webm")

    exported = reference_frames.export_reference_frame_sequence(
        session_id="session-1",
        video_path=video,
        trajectory_path=None,
        metadata_path=None,
        output_dir=tmp_path / "frames",
        interval_seconds=0.5,
        max_frames=64,
    )

    still = exported.design_still
    assert still is not None
    # The moving segment runs from 8s to 12s; the session ends on a held screen.
    assert 8.0 <= still.timestamp_seconds <= 12.0
    assert still.index < exported.frame_count - 1
    assert still.width == reference_frames.DEFAULT_STILL_WIDTH
    assert still.height == reference_frames.DEFAULT_STILL_HEIGHT
    assert (exported.output_dir / reference_frames.DESIGN_STILL_NAME).is_file()


def test_exported_still_omits_the_input_overlay_drawn_on_the_sequence(
    tmp_path: Path,
) -> None:
    video = _menu_then_play_recording(tmp_path / "recording" / "session.webm")
    trajectory = _trajectory(tmp_path / "input.jsonl")
    shared = {
        "session_id": "session-1",
        "video_path": video,
        "trajectory_path": trajectory,
        "metadata_path": None,
        "interval_seconds": 0.5,
        "max_frames": 64,
    }

    overlaid = reference_frames.export_reference_frame_sequence(
        **shared, output_dir=tmp_path / "with-overlay", overlay_inputs=True
    )
    plain = reference_frames.export_reference_frame_sequence(
        **shared, output_dir=tmp_path / "without-overlay", overlay_inputs=False
    )

    assert overlaid.overlay_inputs is True
    assert plain.overlay_inputs is False
    # The overlay changes the published frames, so this is a live comparison.
    assert [frame.sha256 for frame in overlaid.frames] != [
        frame.sha256 for frame in plain.frames
    ]
    # The still is the same picture either way, which is what "no overlay" means.
    assert overlaid.design_still is not None
    assert plain.design_still is not None
    assert overlaid.design_still.sha256 == plain.design_still.sha256


def test_frame_manifest_refuses_a_tampered_still(tmp_path: Path) -> None:
    video = _synthetic_recording(tmp_path / "recording" / "session.webm")
    output = tmp_path / "frames"
    reference_frames.export_reference_frame_sequence(
        session_id="session-1",
        video_path=video,
        trajectory_path=None,
        metadata_path=None,
        output_dir=output,
        interval_seconds=1.0,
        max_frames=8,
    )

    assert reference_frames.load_frame_manifest(output) is not None

    (output / reference_frames.DESIGN_STILL_NAME).write_bytes(b"not-a-png")

    assert reference_frames.load_frame_manifest(output) is None


def test_frame_plan_covers_the_whole_trimmed_recording() -> None:
    effective, timestamps = reference_frames.plan_frame_timestamps(
        11.0, interval_seconds=0.5, max_frames=64
    )

    assert len(timestamps) == 20
    assert effective == pytest.approx(0.5)
    assert timestamps[0] == pytest.approx(0.75)
    assert timestamps[-1] == pytest.approx(10.25)
    assert list(timestamps) == sorted(timestamps)


def test_frame_plan_stretches_the_interval_to_respect_the_budget() -> None:
    effective, timestamps = reference_frames.plan_frame_timestamps(
        601.0, interval_seconds=0.5, max_frames=64
    )

    assert len(timestamps) == 64
    assert effective == pytest.approx(600.0 / 64)
    # The budget must not truncate the session: the last sample still lands near
    # the end rather than 32 seconds in.
    assert timestamps[-1] > 595.0


def test_frame_plan_rejects_a_recording_that_is_too_short() -> None:
    with pytest.raises(reference_frames.ReferenceFrameError, match="too short"):
        reference_frames.plan_frame_timestamps(0.4)


def test_sequence_digest_binds_frame_order() -> None:
    frames = tuple(
        reference_frames.ReferenceFrame(
            index=index,
            name=f"frame-{index:04d}.png",
            timestamp_seconds=float(index),
            sha256=digest * 64,
            size_bytes=10,
            held_keys=(),
        )
        for index, digest in enumerate("ab")
    )
    reordered = (
        frames[1].__class__(**{**frames[1].__dict__, "index": 0}),
        frames[0].__class__(**{**frames[0].__dict__, "index": 1}),
    )

    assert reference_frames.sequence_sha256("s1", frames) == reference_frames.sequence_sha256(
        "s1", frames
    )
    assert reference_frames.sequence_sha256("s1", frames) != reference_frames.sequence_sha256(
        "s1", reordered
    )
    assert reference_frames.sequence_sha256("s1", frames) != reference_frames.sequence_sha256(
        "s2", frames
    )


def test_sequence_digest_binds_the_graded_design_still() -> None:
    frames = (
        reference_frames.ReferenceFrame(
            index=0,
            name="frame-0000.png",
            timestamp_seconds=0.0,
            sha256="a" * 64,
            size_bytes=10,
            held_keys=(),
        ),
    )
    still = reference_frames.DesignStill(
        index=0,
        name=reference_frames.DESIGN_STILL_NAME,
        timestamp_seconds=0.0,
        sha256="b" * 64,
        size_bytes=20,
        width=1280,
        height=720,
        motion=1.0,
        held_keys=(),
    )
    swapped = reference_frames.DesignStill(**{**still.__dict__, "sha256": "c" * 64})

    bound = reference_frames.sequence_sha256("s1", frames, still)

    assert bound != reference_frames.sequence_sha256("s1", frames)
    assert bound != reference_frames.sequence_sha256("s1", frames, swapped)


def test_input_events_load_in_video_time_order(tmp_path: Path) -> None:
    trajectory = tmp_path / "inputs.jsonl"
    trajectory.write_text(
        "\n".join(
            json.dumps(item)
            for item in (
                {"event": "key_press", "key": "ArrowRight", "time_ns": 2_000_000_000, "seq": 2},
                {"event": "key_press", "key": " ", "time_ns": 1_000_000_000, "seq": 1},
                {"event": "noise_without_time"},
            )
        )
        + "\n",
        encoding="utf-8",
    )

    events = reference_frames.load_input_events(trajectory)

    assert [event["key"] for event in events] == [" ", "ArrowRight"]
    assert events[0]["video_time_seconds"] == pytest.approx(1.0)
    assert reference_frames._held_keys(events, 2.5) == ("Space", "Right")
    assert reference_frames._held_keys(events, 1.5) == ("Space",)


def test_frame_sequence_export_is_deterministic_and_verifiable(tmp_path: Path) -> None:
    video = _synthetic_recording(tmp_path / "recording" / "session.webm")
    first = tmp_path / "frames-a"
    second = tmp_path / "frames-b"

    exported = reference_frames.export_reference_frame_sequence(
        session_id="session-1",
        video_path=video,
        trajectory_path=None,
        metadata_path=None,
        output_dir=first,
        interval_seconds=1.0,
        max_frames=8,
    )
    repeated = reference_frames.export_reference_frame_sequence(
        session_id="session-1",
        video_path=video,
        trajectory_path=None,
        metadata_path=None,
        output_dir=second,
        interval_seconds=1.0,
        max_frames=8,
    )

    assert exported.frame_count == 5
    assert exported.sequence_sha256 == repeated.sequence_sha256
    assert [frame.name for frame in exported.frames] == [
        f"frame-{index:04d}.png" for index in range(exported.frame_count)
    ]
    assert reference_frames.load_frame_manifest(first).sequence_sha256 == (
        exported.sequence_sha256
    )


def test_frame_manifest_refuses_a_tampered_frame(tmp_path: Path) -> None:
    video = _synthetic_recording(tmp_path / "recording" / "session.webm")
    output = tmp_path / "frames"
    exported = reference_frames.export_reference_frame_sequence(
        session_id="session-1",
        video_path=video,
        trajectory_path=None,
        metadata_path=None,
        output_dir=output,
        interval_seconds=1.0,
        max_frames=8,
    )

    (output / exported.frames[0].name).write_bytes(b"not-a-png")

    assert reference_frames.load_frame_manifest(output) is None