From 9ef058ce1ed8042736ab6cdbe2516d8bb40f71bb Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:27:12 -0700 Subject: [PATCH 1/6] Fuzz the documents offloader reads back Port the oracle-first approach from markcopy's fuzzing strategy. tests/fuzz_oracle.py holds the checks every parser target applies: only documented exceptions, a time and memory ceiling per input, and no NaN or infinity in the result. tests/test_fuzz_parsers.py adds targets for iXML, RIFF chunk walking, the ASC MHL reader and timeline file: URLs, plus a differential verify target: manifests are written by the test, hashes are taken by the test, and a pass must be backed by a hash taken now. Fixes found by the new targets: - A damaged encoding declaration in a previous ASC MHL manifest raised LookupError (or ValueError for a multi-byte encoding) out of the reader, failing the next ASC MHL report instead of starting a new generation. verify now reports such a manifest as a ParseError. - An iXML frame rate of inf was accepted and reached the sound report. Per-test max_examples now scale with the loaded profile, so --fuzz goes deeper on the PDF, report and flat-mode properties instead of staying at 20 to 40 examples. .hypothesis/ is ignored. --- .github/workflows/ci.yml | 10 +- .gitignore | 1 + AGENTS.md | 2 +- CHANGELOG.md | 15 ++ CONTRIBUTING.md | 2 +- README.md | 15 +- src/offloader/ascmhl.py | 17 +- src/offloader/ixml.py | 5 +- src/offloader/verify.py | 8 +- tests/fuzz_oracle.py | 95 +++++++++ tests/test_fuzz.py | 15 +- tests/test_fuzz_edges.py | 3 +- tests/test_fuzz_parsers.py | 414 +++++++++++++++++++++++++++++++++++++ 13 files changed, 579 insertions(+), 23 deletions(-) create mode 100644 tests/fuzz_oracle.py create mode 100644 tests/test_fuzz_parsers.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 783dfae..1830c59 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -104,10 +104,12 @@ jobs: python -m pip install --upgrade pip python -m pip install -e ".[dev]" - name: Run the property tests at soak depth - # All three property modules: test_fuzz.py fuzzes what a filename can - # contain, test_fuzz_edges.py what a card can contain, and - # test_edge_cases.py the layers between the bytes and the paperwork. - run: pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_edge_cases.py --fuzz -q + # All four property modules: test_fuzz.py fuzzes what a filename can + # contain, test_fuzz_edges.py what a card can contain, + # test_fuzz_parsers.py the documents read back (iXML, ASC MHL, the + # manifest verify vouches for, timeline URLs), and test_edge_cases.py + # the layers between the bytes and the paperwork. + run: pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_edge_cases.py --fuzz -q build: name: build the distribution diff --git a/.gitignore b/.gitignore index 416e834..7a0c047 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ dist/ .venv-build/ venv/ .pytest_cache/ +.hypothesis/ .coverage htmlcov/ *.log diff --git a/AGENTS.md b/AGENTS.md index 53ba7f7..d9cb8a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -135,7 +135,7 @@ python -m pytest -q Run the deeper property checks when relevant to safety or parser changes: ```powershell -python -m pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_edge_cases.py --fuzz -q +python -m pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_edge_cases.py --fuzz -q ``` Build Python distributions when packaging changes: diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b0653c..2494760 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,21 @@ project uses [semantic versioning][semver]. ## [Unreleased] +### Fixed + +Found by `tests/test_fuzz_parsers.py`, which fuzzes the documents offloader +reads back. Each fix has the reproduction that found it. + +- **One damaged byte in a previous ASC MHL manifest cost the next one.** An + XML declaration reading `encoding="TF-8"` raised `LookupError`, and a + multi-byte encoding a `ValueError`, where the reader expected only a parse + error. The ASC MHL report then failed (recorded, not silent) instead of + starting a new generation. `verify` now reports such a manifest as one that + will not parse. +- **An iXML frame rate of `inf` reached the sound report.** `float()` accepts + `inf`, and a huge ratio overflows to it. Non-finite rates are now ignored, + like a zero or negative one. + ### Changed - **Full verification is the default.** The read-back is the only mode that diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e476f4..1225307 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,7 +38,7 @@ pip install -e ".[dev]" ```sh pytest # run the full suite -pytest --fuzz # property tests at 3000 examples each, about 3 min +pytest --fuzz # property tests at 3000 examples each, about 5 min ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` diff --git a/README.md b/README.md index e2553a5..8b2d59b 100644 --- a/README.md +++ b/README.md @@ -622,12 +622,12 @@ what makes the report layer testable without moving bytes. ```sh pip install -e ".[dev]" pytest # run the full suite -pytest --fuzz # same suite, 3000 examples per property (~3 min) +pytest --fuzz # same suite, 3000 examples per property (~5 min) ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` -918 tests at 84% line coverage. They cover formatting against the reference's +937 tests at 87% line coverage. They cover formatting against the reference's exact strings, checksum vectors and streaming equivalence, copy/verify behaviour including simulated destination corruption, pause/resume/cancel concurrency, retry discrimination, BRAW container parsing, ffprobe parsing, @@ -646,7 +646,7 @@ real camera file when one is present. ### Property-based testing -Three modules use [Hypothesis][hyp] to assert invariants over generated input +Four modules use [Hypothesis][hyp] to assert invariants over generated input rather than over a handful of fixtures, each aimed at a different layer: - **`tests/test_fuzz.py`: what a filename can contain.** Names come off camera @@ -657,6 +657,15 @@ rather than over a handful of fixtures, each aimed at a different layer: atom headers lie, a tree that maps two sources onto one destination, a directory junction pointing at its own parent, a retry policy someone hand-edited into a preset. +- **`tests/test_fuzz_parsers.py`: what someone else wrote.** The iXML a + recorder put in a WAV, the ASC MHL a previous offload left behind, the + manifest `verify` is asked to vouch for, the `file:` URLs in a timeline. + Manifests are written by the test, not by `reports/`, and `verify` is + checked against hashes taken by the test: a report that passed must be + backed by a hash taken now, and a flipped byte, a deleted file, a dropped + digest or a hash marked failed must never pass. Every target also runs under + the shared oracle in `tests/fuzz_oracle.py`: only documented exceptions, a + time and memory ceiling per input, and no NaN or infinity in the result. - **`tests/test_edge_cases.py`: the layers between the bytes and the paperwork.** What ffprobe hands back, what a number formats to, what a digest compares equal to, what a name renders to. diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py index e421cde..9221631 100644 --- a/src/offloader/ascmhl.py +++ b/src/offloader/ascmhl.py @@ -224,6 +224,21 @@ def next_sequence(root: Path) -> int: return int(last.group(1)) + 1 +def parse_manifest(manifest: Path) -> ET.Element: + """The root element of a manifest file, or `ET.ParseError`. + + `ET.parse` has two more ways to say "this is not a manifest" than + `ParseError`, both from the XML declaration: an unknown encoding name is + a `LookupError` and a multi-byte one such as Shift-JIS is a `ValueError`. + One damaged byte in `encoding="UTF-8"` is enough to reach the first. They + are folded in here so every caller has one exception to catch. + """ + try: + return ET.parse(manifest).getroot() + except (LookupError, ValueError) as exc: + raise ET.ParseError(f"{manifest}: {exc}") from exc + + def read_manifest_hashes(manifest: Path) -> dict[str, dict[str, str]]: """{relative path: {algorithm tag: digest}} from an existing manifest. @@ -232,7 +247,7 @@ def read_manifest_hashes(manifest: Path) -> dict[str, dict[str, str]]: """ result: dict[str, dict[str, str]] = {} try: - root = ET.parse(manifest).getroot() + root = parse_manifest(manifest) except (ET.ParseError, OSError): return result diff --git a/src/offloader/ixml.py b/src/offloader/ixml.py index 57172e0..f73a2cf 100644 --- a/src/offloader/ixml.py +++ b/src/offloader/ixml.py @@ -23,6 +23,7 @@ from __future__ import annotations +import math import struct from pathlib import Path from typing import BinaryIO @@ -158,7 +159,9 @@ def _ratio(value: str | None) -> float | None: rate = float(text) except (TypeError, ValueError): return None - return rate if rate > 0 else None + # `float` accepts "inf" and "nan", and a huge ratio overflows to inf: none + # is a frame rate, and inf reaches `round()` in `timecode_of` as an error. + return rate if math.isfinite(rate) and rate > 0 else None def _int(value: str | None) -> int | None: diff --git a/src/offloader/verify.py b/src/offloader/verify.py index df8f091..808fa61 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -28,7 +28,7 @@ from xml.etree import ElementTree as ET from . import longpath -from .ascmhl import ASCMHL_DIRNAME +from .ascmhl import ASCMHL_DIRNAME, parse_manifest from .ascmhl import NAMESPACE as ASCMHL_NAMESPACE from .ascmhl import directory_hashes as ascmhl_directory_hashes from .hashers import ALGORITHMS, get_algorithm, hash_file @@ -257,7 +257,7 @@ def _entries(manifest: Path) -> Iterator[tuple[Path, str | None, str | None, int (``, namespaced, and living in an `ascmhl/` folder so its paths are relative to the folder above). """ - root = ET.parse(manifest).getroot() + root = parse_manifest(manifest) if root.tag == f"{{{ASCMHL_NAMESPACE}}}hashlist": yield from _ascmhl_entries(manifest, root) return @@ -461,7 +461,7 @@ def _ascmhl_root(manifest: Path) -> ET.Element | None: Classic MHL 1.1 has no concept of a directory hash, so there is nothing to re-check and nothing to read. """ - root = ET.parse(manifest).getroot() + root = parse_manifest(manifest) return root if root.tag == f"{{{ASCMHL_NAMESPACE}}}hashlist" else None @@ -667,7 +667,7 @@ def _recorded_at(manifest: Path) -> _dt.datetime | None: later. """ try: - root = ET.parse(manifest).getroot() + root = parse_manifest(manifest) except (OSError, ET.ParseError): return None prefix = (f"{{{ASCMHL_NAMESPACE}}}" diff --git a/tests/fuzz_oracle.py b/tests/fuzz_oracle.py new file mode 100644 index 0000000..9429e40 --- /dev/null +++ b/tests/fuzz_oracle.py @@ -0,0 +1,95 @@ +"""The checks every parser fuzz target applies, whatever it parses. + +A fuzz target is only as good as its oracle. "It did not crash" catches a +fraction of what a hostile card can do; the rest is a parser that runs for a +minute, allocates a gigabyte, or returns an answer that is quietly wrong: a +frame rate of infinity that a report prints, or a verdict that says a file +matched when nobody hashed it. These helpers turn those into failures. + +Ported from the shared oracle in markcopy's fuzzing strategy, cut down to what +a Python parser can get wrong. +""" + +from __future__ import annotations + +import dataclasses +import enum +import math +import time +import tracemalloc +from collections.abc import Callable, Mapping +from pathlib import PurePath +from typing import Any, TypeVar + +from hypothesis import settings + +T = TypeVar("T") + +#: Per-input ceilings. Every input a target is fed is a few kilobytes, so a +#: parser that needs seconds or megabytes on one is doing something +#: proportional to a number it read from the input rather than to its length. +SECONDS = 3.0 +MEGABYTES = 64 + + +def scaled(examples: int) -> int: + """An example budget that grows with the active profile. + + A test that pins `max_examples` overrides the profile, so a bare + `@settings(max_examples=40)` stays at 40 under `--fuzz` and the soak never + goes deeper on it. This keeps `examples` as the quick-run budget and + multiplies it by however much larger the loaded profile is than the + default 100. + """ + return max(examples, examples * settings().max_examples // 100) + + +def bounded(fn: Callable[..., T], *args: Any, + allowed: tuple[type[BaseException], ...] = (), + seconds: float = SECONDS, megabytes: int = MEGABYTES, + **kwargs: Any) -> T | None: + """Call a parser and fail if it escapes its contract. + + Returns the result, or None when it raised one of `allowed`, the + exceptions its callers are documented to catch. Anything else propagates + and fails the test. Time and peak allocation are checked either way. + """ + tracing = tracemalloc.is_tracing() + if not tracing: + tracemalloc.start() + tracemalloc.reset_peak() + started = time.perf_counter() + try: + return fn(*args, **kwargs) + except allowed: + return None + finally: + elapsed = time.perf_counter() - started + _, peak = tracemalloc.get_traced_memory() + if not tracing: + tracemalloc.stop() + assert elapsed < seconds, f"{fn.__name__} took {elapsed:.1f}s on one input" + assert peak < megabytes * 2**20, ( + f"{fn.__name__} peaked at {peak / 2**20:.0f} MB on one input") + + +def assert_finite(value: Any, where: str = "result") -> None: + """No float anywhere in `value` is NaN or infinite. + + A parser that reads a number has to decide what an absurd one means. Left + undecided, `inf` reaches a report as text, or `round()` as an + OverflowError, far from the field that held it. + """ + if isinstance(value, float): + assert math.isfinite(value), f"{where} is {value!r}" + elif isinstance(value, (str, bytes, int, PurePath, enum.Enum)) or value is None: + return + elif dataclasses.is_dataclass(value) and not isinstance(value, type): + for field in dataclasses.fields(value): + assert_finite(getattr(value, field.name), f"{where}.{field.name}") + elif isinstance(value, Mapping): + for key, item in value.items(): + assert_finite(item, f"{where}[{key!r}]") + elif isinstance(value, (list, tuple, set, frozenset)): + for index, item in enumerate(value): + assert_finite(item, f"{where}[{index}]") diff --git a/tests/test_fuzz.py b/tests/test_fuzz.py index 9f9fffa..1a23c5a 100644 --- a/tests/test_fuzz.py +++ b/tests/test_fuzz.py @@ -23,6 +23,7 @@ from hypothesis import given, settings from hypothesis import strategies as st +from fuzz_oracle import scaled from offloader import naming, util from offloader.hashers import ALGORITHMS, hash_file, new_hasher from offloader.models import ( @@ -238,7 +239,7 @@ def test_hash_file_matches_in_memory(payload: bytes, key: str, tmp_path_factory) # --------------------------------------------------------------------- PDF -@settings(max_examples=40, deadline=None) +@settings(max_examples=scaled(40), deadline=None) @given(names=st.lists(hostile_text, min_size=1, max_size=6), size=byte_sizes) def test_pdf_survives_hostile_filenames(names: list[str], size: int, tmp_path_factory): """No input may push text off the page or crash the writer.""" @@ -255,7 +256,7 @@ def test_pdf_survives_hostile_filenames(names: list[str], size: int, tmp_path_fa assert span["bbox"][3] <= layout.PAGE_HEIGHT + 1.0 -@settings(max_examples=25, deadline=None) +@settings(max_examples=scaled(25), deadline=None) @given(depth=st.integers(min_value=1, max_value=6), segment=st.integers(min_value=1, max_value=400)) def test_pdf_long_paths_stay_on_the_page(depth: int, segment: int, @@ -274,7 +275,7 @@ def test_pdf_long_paths_stay_on_the_page(depth: int, segment: int, assert span["bbox"][2] <= layout.PAGE_WIDTH + 1.0 -@settings(max_examples=20, deadline=None) +@settings(max_examples=scaled(20), deadline=None) @given(file_count=st.integers(min_value=0, max_value=30), destinations=st.integers(min_value=1, max_value=4)) def test_pdf_page_count_grows_with_content(file_count: int, destinations: int, @@ -290,7 +291,7 @@ def test_pdf_page_count_grows_with_content(file_count: int, destinations: int, assert f"Page {number}" in page.get_text() -@settings(max_examples=20, deadline=None) +@settings(max_examples=scaled(20), deadline=None) @given(width=st.integers(min_value=0, max_value=8000), height=st.integers(min_value=0, max_value=8000), fps=st.floats(min_value=0.01, max_value=1000, allow_nan=False, @@ -311,7 +312,7 @@ def test_pdf_handles_extreme_media_metadata(width: int, height: int, fps: float, # --------------------------------------------------------------------- CSV / MHL / HTML -@settings(max_examples=40, deadline=None) +@settings(max_examples=scaled(40), deadline=None) @given(names=st.lists(hostile_text, min_size=1, max_size=5)) def test_csv_keeps_its_column_count(names: list[str], tmp_path_factory): """A filename containing commas, quotes or newlines must not shift columns.""" @@ -326,7 +327,7 @@ def test_csv_keeps_its_column_count(names: list[str], tmp_path_factory): assert len(row) == len(header) -@settings(max_examples=40, deadline=None) +@settings(max_examples=scaled(40), deadline=None) @given(names=st.lists(hostile_text, min_size=1, max_size=5)) def test_mhl_is_always_well_formed_xml(names: list[str], tmp_path_factory): out = tmp_path_factory.mktemp("mhl") / "JobReport.mhl" @@ -367,7 +368,7 @@ def handle_starttag(self, tag, attrs): injecting_text = st.one_of(hostile_text, st.sampled_from(INJECTION_PAYLOADS)) -@settings(max_examples=40, deadline=None) +@settings(max_examples=scaled(40), deadline=None) @given(names=st.lists(injecting_text, min_size=1, max_size=5)) def test_html_input_can_never_become_markup(names: list[str], tmp_path_factory): """The real anti-injection property: whatever the filenames contain, the diff --git a/tests/test_fuzz_edges.py b/tests/test_fuzz_edges.py index cc7ae44..d4567c0 100644 --- a/tests/test_fuzz_edges.py +++ b/tests/test_fuzz_edges.py @@ -41,6 +41,7 @@ from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st +from fuzz_oracle import scaled from offloader import ascmhl, braw, engine, naming, retry from offloader.engine import OffloadOptions from offloader.hashers import hash_file @@ -298,7 +299,7 @@ def test_destination_paths_are_injective_when_structure_is_preserved(tmp_path): assert landed == [1000, 2000] -@settings(max_examples=30, deadline=None, +@settings(max_examples=scaled(30), deadline=None, suppress_health_check=[HealthCheck.function_scoped_fixture, HealthCheck.too_slow]) @given(folders=st.lists(st.text(alphabet="ABCDEFG", min_size=1, max_size=3), diff --git a/tests/test_fuzz_parsers.py b/tests/test_fuzz_parsers.py new file mode 100644 index 0000000..3eb7e9b --- /dev/null +++ b/tests/test_fuzz_parsers.py @@ -0,0 +1,414 @@ +"""Fuzz targets for the parsers that read what someone else wrote. + +`test_fuzz.py` fuzzes filenames and `test_fuzz_edges.py` fuzzes the card. This +module fuzzes the documents offloader reads back: the iXML a recorder put in a +WAV, the ASC MHL a previous offload left behind, the manifest `verify` is +asked to vouch for, and the `file:` URLs in an editor's timeline. + +Each target pairs a generator with an oracle from `fuzz_oracle`. For the +manifest readers the oracle is differential: the manifest is written here, +independently of `reports/`, and the reader must report exactly what was +written. For `verify` it is the one property the product exists for: a +report that passed means every file it vouches for hashes, now, to the digest +the manifest recorded, checked against a hash taken here and not by +`hashers`. + +Run longer sweeps with: pytest --fuzz tests/test_fuzz_parsers.py +""" + +from __future__ import annotations + +import hashlib +import struct +import tempfile +import unicodedata +from pathlib import Path +from urllib.parse import quote +from xml.etree import ElementTree as ET +from xml.sax.saxutils import escape + +import pytest +import xxhash +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +from bwf import ixml_document +from fuzz_oracle import assert_finite, bounded, scaled +from offloader import ascmhl, ixml, timeline, verify +from offloader.models import SoundInfo + +QUICK = settings(max_examples=scaled(100), deadline=None, + suppress_health_check=[HealthCheck.too_slow]) +#: Targets that touch the filesystem per example. +SLOW = settings(max_examples=scaled(40), deadline=None, + suppress_health_check=[HealthCheck.too_slow]) + +#: Numbers a recorder should never write and a hand-edited file easily can. +ABSURD_NUMBERS = ["inf", "-inf", "nan", "INF/1", "1e308/1e-308", "0/0", "25/0", + "-25/1", "1e-320", "30000/1001", "25", ""] + +#: Independent reference hashes: not `offloader.hashers`, so a bug there +#: cannot make the oracle agree with it. +REFERENCE = { + "md5": lambda data: hashlib.md5(data).hexdigest(), + "sha256": lambda data: hashlib.sha256(data).hexdigest(), + "xxh64": lambda data: xxhash.xxh64(data).hexdigest(), + "xxh3": lambda data: xxhash.xxh3_64(data).hexdigest(), +} +#: The verify module's algorithm key for each tag above. +TAG_KEY = {"md5": "md5", "sha256": "sha256", "xxh64": "xxh64", "xxh3": "xxh3-64"} +KEY_TAG = {key: tag for tag, key in TAG_KEY.items()} + +xml_text = st.text( + st.characters(blacklist_categories=("Cs", "Cc")), max_size=40).map(escape) + + +# ---------------------------------------------------------------------- iXML + + +def _check_sound(info: SoundInfo | None) -> None: + assert info is None or isinstance(info, SoundInfo) + assert_finite(info, "SoundInfo") + # `timecode_of` is where a rate becomes arithmetic, so it is part of the + # parser's contract: whatever was accepted must be usable. + stamp = bounded(ixml.timecode_of, info, 48000) + assert stamp is None or isinstance(stamp, str) + + +@QUICK +@given(text=st.text(max_size=2048)) +def test_parse_ixml_on_any_text(text): + _check_sound(bounded(ixml.parse_ixml, text)) + + +@QUICK +@given(project=xml_text, scene=xml_text, take=xml_text, note=xml_text, + rate=st.sampled_from(ABSURD_NUMBERS) | xml_text, + flag=st.sampled_from(["DF", "NDF", "df", ""]) | xml_text, + sample_rate=st.sampled_from(["48000", "0", "-1", "1e9", "nan"]) | xml_text, + samples=st.integers(min_value=0, max_value=2**64 - 1), + names=st.lists(xml_text, max_size=6)) +def test_parse_ixml_on_recorder_shaped_documents(project, scene, take, note, rate, + flag, sample_rate, samples, names): + document = ixml_document(project=project, scene=scene, take=take, note=note, + rate=rate, flag=flag, sample_rate=sample_rate, + samples_since_midnight=samples, track_names=names) + _check_sound(bounded(ixml.parse_ixml, document)) + + +def test_an_infinite_timecode_rate_is_refused(): + """A rate of `inf` used to be accepted, then raise OverflowError in + `timecode_of`'s `round()`. `probe` swallowed that, but only after it had + stored the SoundInfo, so the infinite rate still reached the sound report.""" + for rate in ("inf", "INF/1", "1e308/1e-308"): + info = ixml.parse_ixml(ixml_document(rate=rate)) + assert info is not None and info.timecode_rate is None, rate + assert ixml.timecode_of(info, 48000) is None + + +def _riff_chunk(identifier: bytes, payload: bytes, declared: int | None) -> bytes: + size = len(payload) if declared is None else declared + return identifier + struct.pack(" str: + """The key two names collide on, on a case-insensitive or normalising + filesystem (NTFS, APFS).""" + return unicodedata.normalize("NFC", name).casefold() + + +asc_entries = st.lists(st.tuples( + relative_names, + st.lists(st.tuples(st.sampled_from(sorted(REFERENCE)), st.sampled_from(ACTIONS), + st.text("0123456789abcdefABCDEF", min_size=1, max_size=32)), + max_size=3), +), max_size=6, unique_by=lambda entry: entry[0]) + + +def asc_manifest(entries) -> bytes: + """An ASC MHL hashlist, written by hand rather than by `ascmhl`.""" + hashes = [] + for name, digests in entries: + inner = [f'{escape(name)}'] + for tag, action, digest in digests: + attribute = f' action="{action}"' if action else "" + inner.append(f"<{tag}{attribute}>{digest}") + hashes.append(f"{''.join(inner)}") + return (f'' + f'{"".join(hashes)}' + f"").encode() + + +def expected_hashes(entries) -> dict[str, dict[str, str]]: + """What the spec says a reader may use: never a hash marked failed.""" + result: dict[str, dict[str, str]] = {} + for name, digests in entries: + usable = {tag: digest for tag, action, digest in digests + if action != ascmhl.ACTION_FAILED} + if usable: + result.setdefault(name.strip(), {}).update(usable) + return result + + +@SLOW +@given(entries=asc_entries) +def test_read_manifest_hashes_reports_exactly_what_was_written(entries): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "0001_card.mhl" + path.write_bytes(asc_manifest(entries)) + assert bounded(ascmhl.read_manifest_hashes, path) == expected_hashes(entries) + + +#: XML declarations `ET.parse` refuses with something other than ParseError. +BAD_ENCODINGS = ["TF-8", "bogus", "shift_jis", "utf-32"] + + +def _with_encoding(document: bytes, encoding: str) -> bytes: + return document.replace(b'encoding="UTF-8"', f'encoding="{encoding}"'.encode(), 1) + + +@pytest.mark.parametrize("encoding", BAD_ENCODINGS) +def test_a_manifest_with_a_bad_encoding_reads_as_empty(tmp_path, encoding): + """One damaged byte in the declaration used to raise LookupError out of + the reader, failing the next ASC MHL generation instead of starting it.""" + path = tmp_path / "0001_card.mhl" + path.write_bytes(_with_encoding( + asc_manifest([("a.mov", [("md5", None, "00")])]), encoding)) + assert ascmhl.read_manifest_hashes(path) == {} + + +@pytest.mark.parametrize("encoding", BAD_ENCODINGS) +def test_verify_reports_a_bad_encoding_as_a_parse_error(tmp_path, encoding): + manifest = _write_case(tmp_path, {"a.mov": b"x"}, "md5", False, "none", 0) + manifest.write_bytes(_with_encoding(manifest.read_bytes(), encoding)) + with pytest.raises(ET.ParseError): + verify.verify_manifest(manifest, bypass_cache=False) + + +def _mutate(data: bytes, edits) -> bytes: + buffer = bytearray(data) + for position, kind, value in edits: + if not buffer: + break + at = position % len(buffer) + if kind == 0: + del buffer[at] + elif kind == 1: + buffer.insert(at, value) + else: + buffer[at] = value + return bytes(buffer) + + +edits = st.lists(st.tuples(st.integers(min_value=0), st.integers(0, 2), + st.integers(0, 255)), min_size=1, max_size=8) + + +@SLOW +@given(entries=asc_entries, edits=edits) +def test_read_manifest_hashes_on_damaged_xml(entries, edits): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "0001_card.mhl" + path.write_bytes(_mutate(asc_manifest(entries), edits)) + result = bounded(ascmhl.read_manifest_hashes, path) + assert isinstance(result, dict) + for name, digests in result.items(): + assert isinstance(name, str) and name + assert digests and all(isinstance(d, str) for d in digests.values()) + + +# -------------------------------------------------------------------- verify + +#: What can happen to a tree or its manifest between offload and verify, and +#: whether a correct verifier may still pass it. +MUTATIONS = { + "none": True, + "uppercase-digest": True, # hex compares case-insensitively + "flip-byte": False, + "truncate": False, + "delete": False, + "drop-digest": False, # nothing recorded, nothing verified + "wrong-duplicate": False, # a second entry for the file disagrees + "mark-failed": False, # ASC MHL: a failed hash is not a reference +} + +def _plausible_tree(tree: dict[str, bytes]) -> bool: + folded = [_folded(name) for name in tree] + if len(set(folded)) != len(folded): + return False + # A name may not be both a file and a folder in the same tree. + return not any(other.startswith(name + "/") for name in folded for other in folded) + + +trees = st.dictionaries(relative_names, st.binary(min_size=1, max_size=256), + min_size=1, max_size=5).filter(_plausible_tree) + + +def _assert_sound(report: verify.VerifyReport, tag: str) -> None: + """The property `verify` exists for: a pass is backed by a hash taken now.""" + if not report.passed: + return + for verdict in report.verdicts: + if verdict.superseded_by is not None: + continue + assert verdict.path.is_file(), f"passed but {verdict.path} is not there" + actual = REFERENCE[tag](verdict.path.read_bytes()) + assert verdict.expected is not None + assert verdict.expected.lower() == actual, f"passed but {verdict.path} differs" + + +def _write_case(base: Path, tree: dict[str, bytes], tag: str, asc: bool, + mutation: str, victim: int) -> Path: + """The tree and a manifest of it, then one mutation.""" + root = base / "card" + for name, data in tree.items(): + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_bytes(data) + + names = sorted(tree) + target = names[victim % len(names)] + entries = [] + for name in names: + digest = REFERENCE[tag](tree[name]) + if name == target and mutation == "uppercase-digest": + digest = digest.upper() + recorded = [] if name == target and mutation == "drop-digest" else [digest] + entries.append((name, len(tree[name]), recorded)) + if mutation == "wrong-duplicate": + entries.append((target, len(tree[target]), ["0" * len(REFERENCE[tag](b""))])) + + if asc: + action = ascmhl.ACTION_FAILED if mutation == "mark-failed" else "original" + body = "".join( + f'{escape(name)}' + + "".join(f'<{tag} action="{action if name == target else "original"}">' + f"{d}" for d in digests) + + "" for name, size, digests in entries) + manifest = root / ascmhl.ASCMHL_DIRNAME / "0001_card_2026-01-01_000000Z.mhl" + manifest.parent.mkdir(parents=True) + manifest.write_text(f'{body}' + "", encoding="utf-8") + else: + body = "".join( + f"{escape(name)}{size}" + + "".join(f"<{tag}>{d}" for d in digests) + + "" for name, size, digests in entries) + manifest = root / "card.mhl" + manifest.write_text(f'' + f'{body}', + encoding="utf-8") + + path = root / target + if mutation == "flip-byte": + data = bytearray(tree[target]) + data[victim % len(data)] ^= 0xFF + path.write_bytes(bytes(data)) + elif mutation == "truncate": + path.write_bytes(tree[target][:-1]) + elif mutation == "delete": + path.unlink() + return manifest + + +@SLOW +@given(tree=trees, tag=st.sampled_from(sorted(REFERENCE)), asc=st.booleans(), + mutation=st.sampled_from(sorted(MUTATIONS)), victim=st.integers(min_value=0)) +def test_verify_passes_exactly_when_it_should(tree, tag, asc, mutation, victim): + if mutation == "mark-failed" and not asc: + mutation = "none" # classic MHL has no action attribute + with tempfile.TemporaryDirectory() as folder: + manifest = _write_case(Path(folder), tree, tag, asc, mutation, victim) + report = verify.verify_manifest(manifest, bypass_cache=False) + _assert_sound(report, tag) + assert report.passed is MUTATIONS[mutation], ( + f"{mutation}: passed={report.passed} {report.counts()}") + + +@SLOW +@given(tree=trees, tag=st.sampled_from(sorted(REFERENCE)), asc=st.booleans(), + edits=edits) +def test_verify_on_a_damaged_manifest_never_vouches_for_wrong_bytes(tree, tag, asc, + edits): + with tempfile.TemporaryDirectory() as folder: + manifest = _write_case(Path(folder), tree, tag, asc, "none", 0) + manifest.write_bytes(_mutate(manifest.read_bytes(), edits)) + # The CLI reports a manifest that will not parse as an error, which + # is the right answer; anything else must still be a sound verdict. + report = bounded(verify.verify_manifest, manifest, bypass_cache=False, + allowed=(ET.ParseError,), seconds=10) + if report is not None: + _assert_sound(report, tag) + + +# ------------------------------------------------------------------ timeline + + +@QUICK +@given(url=st.text(max_size=200)) +def test_url_to_path_on_any_text(url): + result = bounded(timeline._url_to_path, url) + assert result is None or isinstance(result, Path) + scheme = bounded(timeline._url_scheme, url) + assert isinstance(scheme, str) and scheme == scheme.lower() + + +segments = st.lists(st.text(st.characters(whitelist_categories=("L", "N"), + whitelist_characters=" -_.%#&+"), + min_size=1, max_size=10).filter(lambda s: s.strip(" .")), + min_size=1, max_size=4) + + +@QUICK +@given(drive=st.sampled_from("CDEZ"), parts=segments, + form=st.sampled_from(["file:///", "file://localhost/", "FILE:///"])) +def test_windows_file_urls_round_trip(drive, parts, form): + url = form + quote(f"{drive}:/" + "/".join(parts)) + assert timeline._url_to_path(url) == Path(f"{drive}:/" + "/".join(parts)) + + +@QUICK +@given(parts=segments, form=st.sampled_from(["file://", "file://localhost"])) +def test_posix_file_urls_keep_their_root(parts, form): + """The leading slash of `/Volumes/...` is the path's root, not noise.""" + url = form + quote("/Volumes/" + "/".join(parts)) + result = timeline._url_to_path(url) + assert result is not None and result.anchor + assert result == Path("/Volumes/" + "/".join(parts)) From 6b1cf34f630abee1a6a4c89bb1121683a7aa356d Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:30:20 -0700 Subject: [PATCH 2/6] Map every input surface to its fuzz targets tests/fuzz_surfaces.json classifies every module under src/offloader and src/offloader/reports as a surface that reads or renders outside input, with the Hypothesis tests that fuzz it, or as not a surface, with a reason. A surface with nothing fuzzed, or only part of it, records the gap instead of implying coverage: companions, config, history, installation, longpath, thumbs and volumes have no target yet, and the OTIO documents, ffprobe JSON, control files and copy/verify/cancel sequences are listed as gaps on the modules that own them. tests/test_fuzz_surfaces.py reads files only and fails on an unclassified module, a listed path that is gone, a surface with neither a target nor a gap, a target that is not a @given test, a @given test no surface claims, or a fuzz file missing from the CI soak job's pytest line. Ported from markcopy's fuzz coverage manifest. --- AGENTS.md | 4 + CONTRIBUTING.md | 18 ++++ README.md | 2 +- tests/fuzz_surfaces.json | 165 ++++++++++++++++++++++++++++++++++++ tests/test_fuzz_surfaces.py | 106 +++++++++++++++++++++++ 5 files changed, 294 insertions(+), 1 deletion(-) create mode 100644 tests/fuzz_surfaces.json create mode 100644 tests/test_fuzz_surfaces.py diff --git a/AGENTS.md b/AGENTS.md index d9cb8a7..ce8eb03 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -138,6 +138,10 @@ Run the deeper property checks when relevant to safety or parser changes: python -m pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_edge_cases.py --fuzz -q ``` +A module that starts reading outside input needs an entry in +`tests/fuzz_surfaces.json` in the same change: a fuzz target, or a stated gap. +See CONTRIBUTING's "Fuzz targets". + Build Python distributions when packaging changes: ```powershell diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1225307..7d24a03 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -60,6 +60,24 @@ python tools/screenshots.py # rewrites docs/images/ It runs the real app against a throwaway config directory and invented volumes, so it neither reads your presets nor puts your drive labels in the README. +## Fuzz targets + +[`tests/fuzz_surfaces.json`](tests/fuzz_surfaces.json) lists every module +that reads or renders input offloader did not write, with the property tests +that fuzz it, or a `gap` saying what is not fuzzed yet. A module that starts +parsing card data, a manifest, a timeline or a state file comes with an entry +in the same change: a new target, or an honest gap. `tests/test_fuzz_surfaces.py` +fails on an unclassified module, a target that is not a `@given` test, a fuzz +test no surface claims, or a fuzz file the CI soak job does not run. + +A target checks the answer, not just that nothing raised. Wrap the call in +`fuzz_oracle.bounded` (documented exceptions only, a time and memory ceiling) +and add the property only a correct parser satisfies: a round trip, a +reference implementation, or for anything that feeds a verdict, that a pass +is backed by a hash taken now. Use `fuzz_oracle.scaled(n)` for a per-test +example budget, so `--fuzz` still deepens it. A bug a target finds keeps a +deterministic regression test beside the fix. + ## Testing without a card Almost nobody has a 27 GB BRAW clip, a sound cart and a failing card reader to diff --git a/README.md b/README.md index 8b2d59b..fc82b06 100644 --- a/README.md +++ b/README.md @@ -627,7 +627,7 @@ ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` -937 tests at 87% line coverage. They cover formatting against the reference's +945 tests at 87% line coverage. They cover formatting against the reference's exact strings, checksum vectors and streaming equivalence, copy/verify behaviour including simulated destination corruption, pause/resume/cancel concurrency, retry discrimination, BRAW container parsing, ffprobe parsing, diff --git a/tests/fuzz_surfaces.json b/tests/fuzz_surfaces.json new file mode 100644 index 0000000..28ddaa1 --- /dev/null +++ b/tests/fuzz_surfaces.json @@ -0,0 +1,165 @@ +{ + "_comment": [ + "Every module that reads or renders input offloader did not write, and the", + "property tests that fuzz it. Enforced by tests/test_fuzz_surfaces.py: a", + "module in a policed folder must appear in exactly one table, every target", + "must be a Hypothesis test, and every Hypothesis test must be claimed here.", + "A surface with no target, or with part of it unfuzzed, says so in `gap`.", + "A gap is a known limit, not a protection: do not delete one without a", + "target that closes it." + ], + "policed": ["src/offloader", "src/offloader/reports"], + "exempt": { + "src/offloader/gui": "Qt widgets. They read untrusted input only through engine, presets, volumes and history, which are listed here." + }, + "surfaces": { + "src/offloader/ascmhl.py": { + "targets": [ + "tests/test_fuzz_parsers.py::test_read_manifest_hashes_reports_exactly_what_was_written", + "tests/test_fuzz_parsers.py::test_read_manifest_hashes_on_damaged_xml" + ], + "gap": "The writer's hostile-name round trip in test_fuzz_edges.py is parametrized over fixed names, not generated." + }, + "src/offloader/braw.py": { + "targets": [ + "tests/test_fuzz_edges.py::test_braw_read_info_survives_arbitrary_bytes", + "tests/test_fuzz_edges.py::test_braw_read_info_survives_random_atom_trees", + "tests/test_fuzz_edges.py::test_braw_read_info_survives_truncated_video_traks", + "tests/test_fuzz_edges.py::test_find_moov_never_reads_past_the_end_of_the_file" + ] + }, + "src/offloader/companions.py": { + "targets": [], + "gap": "Matching card filenames to their proxies is example-tested only." + }, + "src/offloader/config.py": { + "targets": [], + "gap": "read_json on a corrupt or hostile state file is example-tested only." + }, + "src/offloader/engine.py": { + "targets": [ + "tests/test_fuzz_edges.py::test_flat_mode_never_silently_drops_a_file", + "tests/test_fuzz_edges.py::test_exclude_patterns_never_raise" + ], + "gap": "Control-file contents (JobControl) and source scanning are example-tested only; no generated sequence of copy, verify, cancel and cleanup with injected faults." + }, + "src/offloader/hashers.py": { + "targets": [ + "tests/test_fuzz.py::test_chunked_hashing_matches_whole_buffer", + "tests/test_fuzz.py::test_hash_file_matches_in_memory" + ] + }, + "src/offloader/history.py": { + "targets": [], + "gap": "Corrupt history is a fixed list of bodies in test_fuzz_edges.py, not generated." + }, + "src/offloader/installation.py": { + "targets": [], + "gap": "The install inventory JSON is example-tested only." + }, + "src/offloader/ixml.py": { + "targets": [ + "tests/test_fuzz_parsers.py::test_parse_ixml_on_any_text", + "tests/test_fuzz_parsers.py::test_parse_ixml_on_recorder_shaped_documents", + "tests/test_fuzz_parsers.py::test_read_sound_info_on_hostile_riff" + ] + }, + "src/offloader/longpath.py": { + "targets": [], + "gap": "Prefixing hostile card paths past MAX_PATH is example-tested only." + }, + "src/offloader/naming.py": { + "targets": [ + "tests/test_fuzz.py::test_sanitize_output_is_always_a_legal_filename", + "tests/test_fuzz.py::test_build_never_collides_with_taken_names", + "tests/test_fuzz.py::test_sequential_builds_are_all_distinct", + "tests/test_fuzz.py::test_index_token_pads_to_three_digits" + ] + }, + "src/offloader/presets.py": { + "targets": [ + "tests/test_fuzz.py::test_preset_round_trips_through_json", + "tests/test_fuzz.py::test_preset_from_dict_tolerates_garbage" + ], + "gap": "The preset file loader around from_dict is example-tested only." + }, + "src/offloader/probe.py": { + "targets": [ + "tests/test_edge_cases.py::test_parse_rate_never_raises_on_a_rational", + "tests/test_edge_cases.py::test_parse_rate_never_raises_on_junk" + ], + "gap": "Whole ffprobe JSON documents (_build) are example-tested only." + }, + "src/offloader/retry.py": { + "targets": [ + "tests/test_fuzz_edges.py::test_retry_never_asks_to_sleep_for_a_negative_time" + ] + }, + "src/offloader/thumbs.py": { + "targets": [], + "gap": "ffmpeg is called with an argument list, but the paths it is handed are not fuzzed." + }, + "src/offloader/timeline.py": { + "targets": [ + "tests/test_fuzz_parsers.py::test_url_to_path_on_any_text", + "tests/test_fuzz_parsers.py::test_windows_file_urls_round_trip", + "tests/test_fuzz_parsers.py::test_posix_file_urls_keep_their_root" + ], + "gap": "Timeline documents themselves (read_references over OTIO and FCP XML) are not fuzzed." + }, + "src/offloader/util.py": { + "targets": [ + "tests/test_fuzz.py::test_format_size_always_parses_back", + "tests/test_fuzz.py::test_format_size_is_monotonic", + "tests/test_edge_cases.py::test_format_size_promotes_negative_values_too", + "tests/test_fuzz.py::test_format_duration_shape", + "tests/test_fuzz.py::test_format_elapsed_shape", + "tests/test_fuzz.py::test_timecode_fields_stay_in_range", + "tests/test_fuzz.py::test_datetime_formats_never_crash" + ] + }, + "src/offloader/verify.py": { + "targets": [ + "tests/test_fuzz_parsers.py::test_verify_passes_exactly_when_it_should", + "tests/test_fuzz_parsers.py::test_verify_on_a_damaged_manifest_never_vouches_for_wrong_bytes" + ] + }, + "src/offloader/volumes.py": { + "targets": [], + "gap": "Volume labels and mount tables reported by the OS are example-tested only." + }, + "src/offloader/reports/csv_report.py": { + "targets": ["tests/test_fuzz.py::test_csv_keeps_its_column_count"] + }, + "src/offloader/reports/html.py": { + "targets": ["tests/test_fuzz.py::test_html_input_can_never_become_markup"] + }, + "src/offloader/reports/mhl.py": { + "targets": ["tests/test_fuzz.py::test_mhl_is_always_well_formed_xml"] + }, + "src/offloader/reports/pdf.py": { + "targets": [ + "tests/test_fuzz.py::test_pdf_survives_hostile_filenames", + "tests/test_fuzz.py::test_pdf_long_paths_stay_on_the_page", + "tests/test_fuzz.py::test_pdf_page_count_grows_with_content", + "tests/test_fuzz.py::test_pdf_handles_extreme_media_metadata" + ] + } + }, + "not_surfaces": { + "src/offloader/__init__.py": "Package metadata.", + "src/offloader/__main__.py": "Entry point.", + "src/offloader/_version.py": "Version literal.", + "src/offloader/cli.py": "Arguments come from the operator, not the card; documents are read through the surface modules.", + "src/offloader/installation_lock.py": "Takes a byte-range lock on a file it owns; reads no content.", + "src/offloader/integrity.py": "Evicts files from the cache; reads no structure.", + "src/offloader/models.py": "Dataclasses; parses nothing.", + "src/offloader/sysinfo.py": "Host facts from the OS, not from a card or a document.", + "src/offloader/windows_launch.py": "Launches an installed executable; takes no outside input.", + "src/offloader/reports/__init__.py": "Writer registry.", + "src/offloader/reports/fonts.py": "Bundled font lookup.", + "src/offloader/reports/icons.py": "Bundled drawings.", + "src/offloader/reports/layout.py": "PDF geometry; exercised by the PDF targets.", + "src/offloader/reports/paperwork.py": "Calls the writers and records their failures; renders nothing itself." + } +} diff --git a/tests/test_fuzz_surfaces.py b/tests/test_fuzz_surfaces.py new file mode 100644 index 0000000..59e0b9e --- /dev/null +++ b/tests/test_fuzz_surfaces.py @@ -0,0 +1,106 @@ +"""Keep `fuzz_surfaces.json` honest. + +The manifest maps every module that reads or renders outside input to the +property tests that fuzz it, or records the gap. These checks make it +impossible to add a module, rename a target or add a fuzz file without the +manifest and the CI soak job hearing about it. They read files only; nothing +here runs a fuzzer. Ported from markcopy's `fuzzCoverage` test. +""" + +from __future__ import annotations + +import ast +import json +import re +from functools import cache +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent +MANIFEST = json.loads((REPO / "tests" / "fuzz_surfaces.json").read_text(encoding="utf-8")) +SURFACES: dict[str, dict] = MANIFEST["surfaces"] +NOT_SURFACES: dict[str, str] = MANIFEST["not_surfaces"] +HOW = "Add it to tests/fuzz_surfaces.json, under surfaces (with targets or a gap) " \ + "or not_surfaces (with a reason)." + + +@cache +def given_tests(test_file: str) -> frozenset[str]: + """Top-level test functions in `test_file` decorated with `@given`.""" + tree = ast.parse((REPO / test_file).read_text(encoding="utf-8")) + return frozenset( + node.name for node in tree.body + if isinstance(node, ast.FunctionDef) + and any(_is_given(decorator) for decorator in node.decorator_list)) + + +def _is_given(decorator: ast.expr) -> bool: + target = decorator.func if isinstance(decorator, ast.Call) else decorator + return (isinstance(target, ast.Name) and target.id == "given") or ( + isinstance(target, ast.Attribute) and target.attr == "given") + + +def fuzz_files() -> list[str]: + return sorted(path.relative_to(REPO).as_posix() + for path in (REPO / "tests").glob("test_*.py") if given_tests( + path.relative_to(REPO).as_posix())) + + +def test_every_module_in_a_policed_folder_is_classified(): + unlisted = [] + for folder in MANIFEST["policed"]: + for module in sorted((REPO / folder).glob("*.py")): + name = module.relative_to(REPO).as_posix() + if name not in SURFACES and name not in NOT_SURFACES: + unlisted.append(name) + assert not unlisted, f"unclassified: {unlisted}. {HOW}" + + +def test_no_module_is_both_a_surface_and_not_one(): + assert not set(SURFACES) & set(NOT_SURFACES) + + +def test_every_listed_path_exists(): + listed = [*SURFACES, *NOT_SURFACES, *MANIFEST["policed"], *MANIFEST["exempt"]] + missing = [name for name in listed if not (REPO / name).exists()] + assert not missing, f"listed but gone: {missing}" + + +def test_every_surface_has_a_target_or_a_stated_gap(): + bare = [name for name, entry in SURFACES.items() + if not entry.get("targets") and not entry.get("gap", "").strip()] + assert not bare, f"no target and no gap: {bare}" + + +def test_every_exclusion_gives_a_reason(): + unexplained = [name for name, reason in {**NOT_SURFACES, **MANIFEST["exempt"]}.items() + if not reason.strip()] + assert not unexplained + + +def test_every_target_is_a_hypothesis_test(): + wrong = [] + for name, entry in SURFACES.items(): + for target in entry.get("targets", []): + test_file, _, function = target.partition("::") + if not (REPO / test_file).is_file() or function not in given_tests(test_file): + wrong.append(f"{name}: {target}") + assert not wrong, f"not a @given test: {wrong}" + + +def test_every_hypothesis_test_is_claimed_by_a_surface(): + claimed = {target for entry in SURFACES.values() for target in entry.get("targets", [])} + orphans = [f"{test_file}::{function}" for test_file in fuzz_files() + for function in sorted(given_tests(test_file)) + if f"{test_file}::{function}" not in claimed] + assert not orphans, f"fuzz tests no surface claims: {orphans}. List each under " \ + "the module it fuzzes in tests/fuzz_surfaces.json." + + +def test_every_fuzz_file_runs_in_the_soak_job(): + """The soak job names its files, so a new one is otherwise left at the + quick-run budget forever.""" + workflow = (REPO / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + soak = [line for line in workflow.splitlines() if re.search(r"pytest .*--fuzz", line)] + assert len(soak) == 1, "expected exactly one `pytest ... --fuzz` line in ci.yml" + missing = [test_file for test_file in fuzz_files() if test_file not in soak[0]] + assert not missing, f"not in the soak job's pytest line: {missing}" From ed10f4c87cfa92791f43a2d8dfb50d231f3e61f0 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:36:29 -0700 Subject: [PATCH 3/6] Fuzz the state, history and control files tests/test_fuzz_state.py covers the files kept between runs, each against an independent reading of what the bytes mean: read_json returns the value or the default, History keeps every record with a fingerprint, a control file moves the job only on a whole control word, a cancel stays final, and claim never overwrites a file that is not a control word. Fixes found by the new targets: - Deeply nested JSON raised RecursionError out of read_json, so a damaged history.json stopped History from being built. - A file_count of 1e400 raised OverflowError in HistoryEntry.from_dict, dropping the record and the duplicate-card warning its fingerprint gives. config.py and history.py move from gaps to fuzzed surfaces, and the control-file targets are listed under engine.py. --- .github/workflows/ci.yml | 8 +- AGENTS.md | 2 +- CHANGELOG.md | 11 ++- README.md | 10 +- src/offloader/config.py | 5 +- src/offloader/history.py | 2 +- tests/fuzz_surfaces.json | 34 +++++-- tests/test_fuzz_state.py | 203 +++++++++++++++++++++++++++++++++++++++ 8 files changed, 254 insertions(+), 21 deletions(-) create mode 100644 tests/test_fuzz_state.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1830c59..c0a23c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -104,12 +104,14 @@ jobs: python -m pip install --upgrade pip python -m pip install -e ".[dev]" - name: Run the property tests at soak depth - # All four property modules: test_fuzz.py fuzzes what a filename can + # All five property modules: test_fuzz.py fuzzes what a filename can # contain, test_fuzz_edges.py what a card can contain, # test_fuzz_parsers.py the documents read back (iXML, ASC MHL, the - # manifest verify vouches for, timeline URLs), and test_edge_cases.py + # manifest verify vouches for, timeline URLs), test_fuzz_state.py the + # files kept between runs (state, history, the control file), and + # test_edge_cases.py # the layers between the bytes and the paperwork. - run: pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_edge_cases.py --fuzz -q + run: pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_fuzz_state.py tests/test_edge_cases.py --fuzz -q build: name: build the distribution diff --git a/AGENTS.md b/AGENTS.md index ce8eb03..c0f4a29 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -135,7 +135,7 @@ python -m pytest -q Run the deeper property checks when relevant to safety or parser changes: ```powershell -python -m pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_edge_cases.py --fuzz -q +python -m pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_fuzz_state.py tests/test_edge_cases.py --fuzz -q ``` A module that starts reading outside input needs an entry in diff --git a/CHANGELOG.md b/CHANGELOG.md index 2494760..5eb1e71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,9 @@ project uses [semantic versioning][semver]. ### Fixed -Found by `tests/test_fuzz_parsers.py`, which fuzzes the documents offloader -reads back. Each fix has the reproduction that found it. +Found by `tests/test_fuzz_parsers.py` and `tests/test_fuzz_state.py`, which +fuzz the documents offloader reads back and the files it keeps between +runs. Each fix has the reproduction that found it. - **One damaged byte in a previous ASC MHL manifest cost the next one.** An XML declaration reading `encoding="TF-8"` raised `LookupError`, and a @@ -19,6 +20,12 @@ reads back. Each fix has the reproduction that found it. error. The ASC MHL report then failed (recorded, not silent) instead of starting a new generation. `verify` now reports such a manifest as one that will not parse. +- **A deeply nested state file stopped the history loading.** `[[[[...` + raised `RecursionError`, which `read_json` did not treat as damage, so the + promise that a corrupt state file never stops an offload did not hold. +- **One overflowing count dropped a history record.** A `file_count` of + `1e400` made `int()` raise `OverflowError`, losing the record and the + duplicate-card warning its fingerprint provides. The count is now zero. - **An iXML frame rate of `inf` reached the sound report.** `float()` accepts `inf`, and a huge ratio overflows to it. Non-finite rates are now ignored, like a zero or negative one. diff --git a/README.md b/README.md index fc82b06..c64b255 100644 --- a/README.md +++ b/README.md @@ -627,7 +627,7 @@ ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` -945 tests at 87% line coverage. They cover formatting against the reference's +954 tests at 87% line coverage. They cover formatting against the reference's exact strings, checksum vectors and streaming equivalence, copy/verify behaviour including simulated destination corruption, pause/resume/cancel concurrency, retry discrimination, BRAW container parsing, ffprobe parsing, @@ -646,7 +646,7 @@ real camera file when one is present. ### Property-based testing -Four modules use [Hypothesis][hyp] to assert invariants over generated input +Five modules use [Hypothesis][hyp] to assert invariants over generated input rather than over a handful of fixtures, each aimed at a different layer: - **`tests/test_fuzz.py`: what a filename can contain.** Names come off camera @@ -666,6 +666,12 @@ rather than over a handful of fixtures, each aimed at a different layer: digest or a hash marked failed must never pass. Every target also runs under the shared oracle in `tests/fuzz_oracle.py`: only documented exceptions, a time and memory ceiling per input, and no NaN or infinity in the result. +- **`tests/test_fuzz_state.py`: what is kept between runs.** The state file, + the history and the CLI's control file. Damaged content may be ignored but + never guessed at: a garbled control file never pauses or cancels a job, a + cancel stays final, claiming the control path never overwrites a file that + is not a control word, and a damaged history field costs that field, not + the record and its duplicate-card warning. - **`tests/test_edge_cases.py`: the layers between the bytes and the paperwork.** What ffprobe hands back, what a number formats to, what a digest compares equal to, what a name renders to. diff --git a/src/offloader/config.py b/src/offloader/config.py index 90b9c7a..629b4ed 100644 --- a/src/offloader/config.py +++ b/src/offloader/config.py @@ -49,11 +49,12 @@ def read_json(path: Path, default: Any) -> Any: Config corruption must never stop someone offloading a card, so a bad file is treated as an empty one. That includes a file that is not valid UTF-8: `read_text` raises UnicodeDecodeError, which is a ValueError rather than an - OSError, and json.JSONDecodeError is a ValueError too. + OSError, and json.JSONDecodeError is a ValueError too. Deep nesting is a + RecursionError, which is neither, and one line of `[[[[` is enough. """ try: return json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): + except (OSError, ValueError, RecursionError): return default diff --git a/src/offloader/history.py b/src/offloader/history.py index 342d56c..c60f865 100644 --- a/src/offloader/history.py +++ b/src/offloader/history.py @@ -104,7 +104,7 @@ def text(key: str) -> str: def count(key: str) -> int: try: return int(data.get(key, 0)) - except (TypeError, ValueError): + except (TypeError, ValueError, OverflowError): # int(inf) return 0 # A JSON string here would otherwise be exploded character by diff --git a/tests/fuzz_surfaces.json b/tests/fuzz_surfaces.json index 28ddaa1..38169b0 100644 --- a/tests/fuzz_surfaces.json +++ b/tests/fuzz_surfaces.json @@ -8,7 +8,10 @@ "A gap is a known limit, not a protection: do not delete one without a", "target that closes it." ], - "policed": ["src/offloader", "src/offloader/reports"], + "policed": [ + "src/offloader", + "src/offloader/reports" + ], "exempt": { "src/offloader/gui": "Qt widgets. They read untrusted input only through engine, presets, volumes and history, which are listed here." }, @@ -33,15 +36,19 @@ "gap": "Matching card filenames to their proxies is example-tested only." }, "src/offloader/config.py": { - "targets": [], - "gap": "read_json on a corrupt or hostile state file is example-tested only." + "targets": [ + "tests/test_fuzz_state.py::test_read_json_returns_the_value_or_the_default" + ] }, "src/offloader/engine.py": { "targets": [ "tests/test_fuzz_edges.py::test_flat_mode_never_silently_drops_a_file", - "tests/test_fuzz_edges.py::test_exclude_patterns_never_raise" + "tests/test_fuzz_edges.py::test_exclude_patterns_never_raise", + "tests/test_fuzz_state.py::test_control_read_means_a_word_or_no_opinion", + "tests/test_fuzz_state.py::test_a_damaged_control_file_never_changes_the_job", + "tests/test_fuzz_state.py::test_claim_never_overwrites_what_is_not_a_control_file" ], - "gap": "Control-file contents (JobControl) and source scanning are example-tested only; no generated sequence of copy, verify, cancel and cleanup with injected faults." + "gap": "Source scanning is example-tested only; no generated sequence of copy, verify, cancel and cleanup with injected faults." }, "src/offloader/hashers.py": { "targets": [ @@ -50,8 +57,9 @@ ] }, "src/offloader/history.py": { - "targets": [], - "gap": "Corrupt history is a fixed list of bodies in test_fuzz_edges.py, not generated." + "targets": [ + "tests/test_fuzz_state.py::test_history_keeps_every_record_it_can_identify" + ] }, "src/offloader/installation.py": { "targets": [], @@ -129,13 +137,19 @@ "gap": "Volume labels and mount tables reported by the OS are example-tested only." }, "src/offloader/reports/csv_report.py": { - "targets": ["tests/test_fuzz.py::test_csv_keeps_its_column_count"] + "targets": [ + "tests/test_fuzz.py::test_csv_keeps_its_column_count" + ] }, "src/offloader/reports/html.py": { - "targets": ["tests/test_fuzz.py::test_html_input_can_never_become_markup"] + "targets": [ + "tests/test_fuzz.py::test_html_input_can_never_become_markup" + ] }, "src/offloader/reports/mhl.py": { - "targets": ["tests/test_fuzz.py::test_mhl_is_always_well_formed_xml"] + "targets": [ + "tests/test_fuzz.py::test_mhl_is_always_well_formed_xml" + ] }, "src/offloader/reports/pdf.py": { "targets": [ diff --git a/tests/test_fuzz_state.py b/tests/test_fuzz_state.py new file mode 100644 index 0000000..4756e28 --- /dev/null +++ b/tests/test_fuzz_state.py @@ -0,0 +1,203 @@ +"""Fuzz targets for the files offloader keeps between runs. + +The state file, the history and the CLI's control file are all hand-editable, +all written by something other than this process at some point, and all read +at moments when failing would stop an offload: at startup, before a job, and +once per chunk during one. The contract for each is the same. Damaged +content may be ignored; it may not raise, may not be guessed at, and may not +cost the user something that was intact. + +Run longer sweeps with: pytest --fuzz tests/test_fuzz_state.py +""" + +from __future__ import annotations + +import json +import tempfile +from pathlib import Path + +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +from fuzz_oracle import bounded, scaled +from offloader import config, engine, history + +FILES = settings(max_examples=scaled(100), deadline=None, + suppress_health_check=[HealthCheck.too_slow]) + +#: Any JSON value, including the NaN and Infinity Python's json writes. +json_values = st.recursive( + st.none() | st.booleans() | st.integers() | st.floats() | st.text(max_size=20), + lambda inner: st.lists(inner, max_size=4) + | st.dictionaries(st.text(max_size=12), inner, max_size=4), + max_leaves=20) + + +def _scratch(data: bytes, name: str = "state.json") -> tuple[tempfile.TemporaryDirectory, Path]: + folder = tempfile.TemporaryDirectory() + path = Path(folder.name) / name + path.write_bytes(data) + return folder, path + + +# ------------------------------------------------------------------ read_json + + +SENTINEL = object() + + +@FILES +@given(data=st.binary(max_size=512) + | json_values.map(lambda v: json.dumps(v).encode()) + | st.builds(lambda depth, bracket: bracket * depth, + st.integers(1, 200_000), st.sampled_from([b"[", b'{"a":']))) +def test_read_json_returns_the_value_or_the_default(data): + folder, path = _scratch(data) + with folder: + result = bounded(config.read_json, path, SENTINEL) + try: + expected = json.loads(data.decode("utf-8")) + except (ValueError, RecursionError): + expected = SENTINEL + if expected is SENTINEL: + assert result is SENTINEL + else: + assert json.dumps(result) == json.dumps(expected) + + +@pytest.mark.parametrize("opening", ["[", '{"a":']) +def test_deeply_nested_state_falls_back_to_the_default(tmp_path, opening): + """Deep nesting raised RecursionError, which is neither OSError nor + ValueError, out of `read_json`, so a damaged history.json stopped the + History from being built at all.""" + path = tmp_path / "history.json" + path.write_text(opening * 100_000, encoding="utf-8") + assert config.read_json(path, []) == [] + assert history.History(path).entries == [] + + +# -------------------------------------------------------------------- history + + +records = st.lists( + st.dictionaries( + st.sampled_from(["fingerprint", "job_name", "source", "destinations", + "file_count", "total_bytes", "status", "finished"]), + json_values, max_size=8) + | json_values, + max_size=6) + + +@FILES +@given(records=records) +def test_history_keeps_every_record_it_can_identify(records): + """A damaged field costs that field, never the record: the record's + fingerprint is the duplicate-card warning for that card.""" + folder, path = _scratch(json.dumps(records).encode()) + with folder: + loaded = bounded(history.History, path) + assert loaded is not None + for entry in loaded.entries: + assert isinstance(entry.file_count, int) + assert isinstance(entry.total_bytes, int) + assert all(isinstance(d, str) for d in entry.destinations) + assert isinstance(entry.describe(), str) + assert entry.finished_at is None or entry.finished_at.year > 0 + identified = [r["fingerprint"] for r in records + if isinstance(r, dict) and isinstance(r.get("fingerprint"), str)] + kept = [e.fingerprint for e in loaded.entries] + assert all(fingerprint in kept for fingerprint in identified), (identified, kept) + + +@pytest.mark.parametrize("count", ["1e400", "-1e400"]) +def test_an_overflowing_count_costs_the_count_not_the_record(tmp_path, count): + """`int(inf)` raises OverflowError, which `count()` did not catch, so the + whole record was dropped along with its fingerprint.""" + path = tmp_path / "history.json" + path.write_text(f'[{{"fingerprint": "card-a", "file_count": {count}}}]', + encoding="utf-8") + entries = history.History(path).entries + assert [e.fingerprint for e in entries] == ["card-a"] + assert entries[0].file_count == 0 + + +# --------------------------------------------------------------- control file + + +def _word(data: bytes) -> str | None: + """What the control file means, decided independently of `read`.""" + try: + word = data.decode("utf-8").replace("\r\n", "\n").strip().lower() + except UnicodeDecodeError: + return None + return word if word in engine.FileControl.STATES else None + + +control_bytes = ( + st.binary(max_size=80) + | st.builds(lambda pad, word, tail: (pad + word + tail).encode(), + st.sampled_from(["", " ", "\n", "", "\t"]), + st.sampled_from(["run", "pause", "cancel", "CANCEL", "Pause", + "cancel pending", "cancel\x00", "can cel"]), + st.sampled_from(["", "\n", "\r\n", " ", "\x00", "!"]))) + + +@FILES +@given(data=control_bytes) +def test_control_read_means_a_word_or_no_opinion(data): + folder, path = _scratch(data, "offload.control") + with folder: + control = engine.FileControl(path, poll=0.05) + assert bounded(control.read) == _word(data) + + +@FILES +@given(writes=st.lists(control_bytes, min_size=1, max_size=8)) +def test_a_damaged_control_file_never_changes_the_job(writes): + """Only a whole control word moves the job. A cancel is final: a `pause` + written after it may show as the file's state, but the next checkpoint + still ends the job rather than holding it.""" + folder, path = _scratch(b"run\n", "offload.control") + with folder: + ticks = iter(range(1, 1000)) + control = engine.FileControl(path, poll=0.05, clock=lambda: next(ticks)) + state, cancelled = engine.FileControl.RUN, False + for data in writes: + path.write_bytes(data) + control.sync() + word = _word(data) + if word is not None: + state = word + cancelled = cancelled or word == engine.FileControl.CANCEL + assert control.state == state + assert control.cancelled is cancelled + if cancelled: + with pytest.raises(engine.JobCancelled): + control.checkpoint() + else: + assert control.paused is (state == engine.FileControl.PAUSE) + + +@FILES +@given(existing=control_bytes | st.binary(min_size=65, max_size=200)) +def test_claim_never_overwrites_what_is_not_a_control_file(existing): + """The control path comes from a command line and a typo can name a clip. + Claiming may replace an empty file or a control word, and nothing else.""" + folder, path = _scratch(existing, "offload.control") + with folder: + control = engine.FileControl(path, poll=0.05) + try: + text = existing.decode("utf-8").strip().lower() + except UnicodeDecodeError: + text = None + replaceable = (len(existing) <= engine.FileControl.MAX_BYTES + and text is not None + and (not text or text in engine.FileControl.STATES)) + if replaceable: + control.claim() + assert path.read_bytes() == b"run\n" + else: + with pytest.raises(engine.UnsafeControlFile): + control.claim() + assert path.read_bytes() == existing From 95d1ce333865d3ddd84e529966ff679bf5a68875 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:41:23 -0700 Subject: [PATCH 4/6] Replay a committed seed corpus on every test run Byte-level fuzz targets move to tests/fuzz_targets.py as bytes -> None functions (braw, riff, ixml, ascmhl, state-json, history, control), so the Hypothesis tests and a replay share one statement of each property. tests/fuzz_corpus// holds 32 small seeds generated from the unit-test builders by tests/make_fuzz_seeds.py, including the input behind every bug the fuzzers have found. tests/test_fuzz_corpus.py replays each seed through its target in the ordinary suite, and checks that every corpus folder is a target and every target has seeds. Every fix found so far is also an @example on the target that found it. With the fixes reverted, all regression seeds and examples fail. The corpus is marked binary in .gitattributes, so line-ending normalisation cannot rewrite a seed such as "pause\r\n". --- .gitattributes | 3 + CONTRIBUTING.md | 15 +- README.md | 6 +- tests/fuzz_corpus/ascmhl/failed-hash.mhl | 1 + tests/fuzz_corpus/ascmhl/one-hash.mhl | 1 + .../ascmhl/regress-encoding-shift-jis.mhl | 1 + .../ascmhl/regress-encoding-tf8.mhl | 1 + tests/fuzz_corpus/braw/moov-only.braw | Bin 0 -> 8 bytes tests/fuzz_corpus/braw/no-video.braw | Bin 0 -> 56 bytes .../braw/regress-64bit-size-lie.braw | Bin 0 -> 28 bytes tests/fuzz_corpus/braw/video-trak.braw | Bin 0 -> 124 bytes tests/fuzz_corpus/control/cancel-pending | 1 + tests/fuzz_corpus/control/cancel-upper | 1 + tests/fuzz_corpus/control/cancel-with-bom | 1 + tests/fuzz_corpus/control/clip-bytes | Bin 0 -> 512 bytes tests/fuzz_corpus/control/not-utf8 | 1 + tests/fuzz_corpus/control/pause-crlf | 1 + tests/fuzz_corpus/control/run | 1 + tests/fuzz_corpus/history/bare-object.json | 1 + .../history/destinations-string.json | 1 + tests/fuzz_corpus/history/one-record.json | 1 + .../history/regress-deep-nesting.json | 1 + .../history/regress-overflowing-count.json | 1 + tests/fuzz_corpus/ixml/doctype-entity.xml | 1 + tests/fuzz_corpus/ixml/recorder.xml | 32 ++++ .../ixml/regress-infinite-rate.xml | 32 ++++ .../ixml/regress-overflowing-ratio.xml | 32 ++++ tests/fuzz_corpus/riff/bext-only.wav | Bin 0 -> 750 bytes tests/fuzz_corpus/riff/bwf-ixml-bext.wav | Bin 0 -> 1720 bytes tests/fuzz_corpus/riff/bwf-ixml-first.wav | Bin 0 -> 1110 bytes tests/fuzz_corpus/riff/lying-chunk-size.wav | Bin 0 -> 29 bytes .../riff/regress-infinite-rate.wav | Bin 0 -> 1108 bytes tests/fuzz_corpus/state-json/history.json | 1 + tests/fuzz_corpus/state-json/not-utf8.json | 1 + .../state-json/regress-deep-nesting.json | 1 + tests/fuzz_targets.py | 152 ++++++++++++++++++ tests/make_fuzz_seeds.py | 117 ++++++++++++++ tests/test_fuzz_corpus.py | 36 +++++ tests/test_fuzz_edges.py | 11 +- tests/test_fuzz_parsers.py | 41 ++--- tests/test_fuzz_state.py | 72 ++------- 41 files changed, 470 insertions(+), 98 deletions(-) create mode 100644 tests/fuzz_corpus/ascmhl/failed-hash.mhl create mode 100644 tests/fuzz_corpus/ascmhl/one-hash.mhl create mode 100644 tests/fuzz_corpus/ascmhl/regress-encoding-shift-jis.mhl create mode 100644 tests/fuzz_corpus/ascmhl/regress-encoding-tf8.mhl create mode 100644 tests/fuzz_corpus/braw/moov-only.braw create mode 100644 tests/fuzz_corpus/braw/no-video.braw create mode 100644 tests/fuzz_corpus/braw/regress-64bit-size-lie.braw create mode 100644 tests/fuzz_corpus/braw/video-trak.braw create mode 100644 tests/fuzz_corpus/control/cancel-pending create mode 100644 tests/fuzz_corpus/control/cancel-upper create mode 100644 tests/fuzz_corpus/control/cancel-with-bom create mode 100644 tests/fuzz_corpus/control/clip-bytes create mode 100644 tests/fuzz_corpus/control/not-utf8 create mode 100644 tests/fuzz_corpus/control/pause-crlf create mode 100644 tests/fuzz_corpus/control/run create mode 100644 tests/fuzz_corpus/history/bare-object.json create mode 100644 tests/fuzz_corpus/history/destinations-string.json create mode 100644 tests/fuzz_corpus/history/one-record.json create mode 100644 tests/fuzz_corpus/history/regress-deep-nesting.json create mode 100644 tests/fuzz_corpus/history/regress-overflowing-count.json create mode 100644 tests/fuzz_corpus/ixml/doctype-entity.xml create mode 100644 tests/fuzz_corpus/ixml/recorder.xml create mode 100644 tests/fuzz_corpus/ixml/regress-infinite-rate.xml create mode 100644 tests/fuzz_corpus/ixml/regress-overflowing-ratio.xml create mode 100644 tests/fuzz_corpus/riff/bext-only.wav create mode 100644 tests/fuzz_corpus/riff/bwf-ixml-bext.wav create mode 100644 tests/fuzz_corpus/riff/bwf-ixml-first.wav create mode 100644 tests/fuzz_corpus/riff/lying-chunk-size.wav create mode 100644 tests/fuzz_corpus/riff/regress-infinite-rate.wav create mode 100644 tests/fuzz_corpus/state-json/history.json create mode 100644 tests/fuzz_corpus/state-json/not-utf8.json create mode 100644 tests/fuzz_corpus/state-json/regress-deep-nesting.json create mode 100644 tests/fuzz_targets.py create mode 100644 tests/make_fuzz_seeds.py create mode 100644 tests/test_fuzz_corpus.py diff --git a/.gitattributes b/.gitattributes index ebfb896..80bc4a9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -24,5 +24,8 @@ *.mp4 binary *.mhl text +# Fuzz seeds are exact bytes: a CRLF or a stray encoding is the test case. +tests/fuzz_corpus/** binary + # Keep generated/vendored material out of language stats and diffs. docs/** linguist-documentation diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7d24a03..9b4f873 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,8 +75,19 @@ A target checks the answer, not just that nothing raised. Wrap the call in and add the property only a correct parser satisfies: a round trip, a reference implementation, or for anything that feeds a verdict, that a pass is backed by a hash taken now. Use `fuzz_oracle.scaled(n)` for a per-test -example budget, so `--fuzz` still deepens it. A bug a target finds keeps a -deterministic regression test beside the fix. +example budget, so `--fuzz` still deepens it. + +Byte-level targets live in [`tests/fuzz_targets.py`](tests/fuzz_targets.py) +as `bytes -> None` functions, so the Hypothesis tests and the seed replay +state each property once. Their seeds are in `tests/fuzz_corpus//`, +generated from the unit-test builders by `python tests/make_fuzz_seeds.py` +(small, reproducible, never copied off a real card), and +`tests/test_fuzz_corpus.py` replays every one on each test run. + +A bug a target finds becomes three things in the same change: the fix, a +deterministic regression test, and the failing input, both as an `@example` +on the target that found it and as a `regress-` seed in +`make_fuzz_seeds.py`. Check that the test and the seed fail without the fix. ## Testing without a card diff --git a/README.md b/README.md index c64b255..91d3a39 100644 --- a/README.md +++ b/README.md @@ -627,7 +627,7 @@ ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` -954 tests at 87% line coverage. They cover formatting against the reference's +988 tests at 87% line coverage. They cover formatting against the reference's exact strings, checksum vectors and streaming equivalence, copy/verify behaviour including simulated destination corruption, pause/resume/cancel concurrency, retry discrimination, BRAW container parsing, ffprobe parsing, @@ -672,6 +672,10 @@ rather than over a handful of fixtures, each aimed at a different layer: cancel stays final, claiming the control path never overwrites a file that is not a control word, and a damaged history field costs that field, not the record and its duplicate-card warning. + +The byte-level properties also replay a committed seed corpus +(`tests/fuzz_corpus/`) on every run, including the input behind every bug the +fuzzers have found, so those stay fixed without `--fuzz`. - **`tests/test_edge_cases.py`: the layers between the bytes and the paperwork.** What ffprobe hands back, what a number formats to, what a digest compares equal to, what a name renders to. diff --git a/tests/fuzz_corpus/ascmhl/failed-hash.mhl b/tests/fuzz_corpus/ascmhl/failed-hash.mhl new file mode 100644 index 0000000..5fe9daa --- /dev/null +++ b/tests/fuzz_corpus/ascmhl/failed-hash.mhl @@ -0,0 +1 @@ +2026-01-01T00:00:00ZA001/clip.braw0123456789abcdef \ No newline at end of file diff --git a/tests/fuzz_corpus/ascmhl/one-hash.mhl b/tests/fuzz_corpus/ascmhl/one-hash.mhl new file mode 100644 index 0000000..ad14d95 --- /dev/null +++ b/tests/fuzz_corpus/ascmhl/one-hash.mhl @@ -0,0 +1 @@ +2026-01-01T00:00:00ZA001/clip.braw0123456789abcdef \ No newline at end of file diff --git a/tests/fuzz_corpus/ascmhl/regress-encoding-shift-jis.mhl b/tests/fuzz_corpus/ascmhl/regress-encoding-shift-jis.mhl new file mode 100644 index 0000000..a72fb1a --- /dev/null +++ b/tests/fuzz_corpus/ascmhl/regress-encoding-shift-jis.mhl @@ -0,0 +1 @@ +2026-01-01T00:00:00ZA001/clip.braw0123456789abcdef \ No newline at end of file diff --git a/tests/fuzz_corpus/ascmhl/regress-encoding-tf8.mhl b/tests/fuzz_corpus/ascmhl/regress-encoding-tf8.mhl new file mode 100644 index 0000000..de65718 --- /dev/null +++ b/tests/fuzz_corpus/ascmhl/regress-encoding-tf8.mhl @@ -0,0 +1 @@ +2026-01-01T00:00:00ZA001/clip.braw0123456789abcdef \ No newline at end of file diff --git a/tests/fuzz_corpus/braw/moov-only.braw b/tests/fuzz_corpus/braw/moov-only.braw new file mode 100644 index 0000000000000000000000000000000000000000..b077fbdf29e03286ff8616f4e7d9928f1e981653 GIT binary patch literal 8 PcmZQzVBpBj&o2W21cd?0 literal 0 HcmV?d00001 diff --git a/tests/fuzz_corpus/braw/no-video.braw b/tests/fuzz_corpus/braw/no-video.braw new file mode 100644 index 0000000000000000000000000000000000000000..e95eae21e26918008ffe0e9520072d30c26ddc83 GIT binary patch literal 56 ycmZQzVBkqBsVqn;N-Sq!V9?3U&o2YgDkVjU*+5z*HzhL>NQ-2oNQ-2oMC+6cQE@6%&_`l#-T_m6KOcR8m$^Ra4i{)Y8_`)zddH zG%_|ZH8Z!cw6eCbwX=6{baHlab#wRd^z!!c_45x13RUz zF>}`JIdkXDU$Ah|;w4L$Enl&6)#^2C*R9{Mant54TeofBv2)k%J$v`]>&a; \ No newline at end of file diff --git a/tests/fuzz_corpus/ixml/recorder.xml b/tests/fuzz_corpus/ixml/recorder.xml new file mode 100644 index 0000000..8bf9b94 --- /dev/null +++ b/tests/fuzz_corpus/ixml/recorder.xml @@ -0,0 +1,32 @@ + + + 1.5 + ChairsDoc + 12A + 3 + SR082226 + TRUE + wind on the boom + ABC123 + + 25/1 + 25/1 + NDF + 48000 + 0 + 1728000000 + + + 2 + + 1 + 1 + Boom + + + 2 + 2 + Lav 1 + + + diff --git a/tests/fuzz_corpus/ixml/regress-infinite-rate.xml b/tests/fuzz_corpus/ixml/regress-infinite-rate.xml new file mode 100644 index 0000000..c1fa904 --- /dev/null +++ b/tests/fuzz_corpus/ixml/regress-infinite-rate.xml @@ -0,0 +1,32 @@ + + + 1.5 + ChairsDoc + 12A + 3 + SR082226 + TRUE + wind on the boom + ABC123 + + inf + inf + NDF + 48000 + 0 + 1728000000 + + + 2 + + 1 + 1 + Boom + + + 2 + 2 + Lav 1 + + + diff --git a/tests/fuzz_corpus/ixml/regress-overflowing-ratio.xml b/tests/fuzz_corpus/ixml/regress-overflowing-ratio.xml new file mode 100644 index 0000000..083a768 --- /dev/null +++ b/tests/fuzz_corpus/ixml/regress-overflowing-ratio.xml @@ -0,0 +1,32 @@ + + + 1.5 + ChairsDoc + 12A + 3 + SR082226 + TRUE + wind on the boom + ABC123 + + 1e308/1e-308 + 1e308/1e-308 + NDF + 48000 + 0 + 1728000000 + + + 2 + + 1 + 1 + Boom + + + 2 + 2 + Lav 1 + + + diff --git a/tests/fuzz_corpus/riff/bext-only.wav b/tests/fuzz_corpus/riff/bext-only.wav new file mode 100644 index 0000000000000000000000000000000000000000..66b3e3a1987998d219b8a489be523bfde65355ba GIT binary patch literal 750 zcmWIYbaQ*g#J~{l80MOmTcRMqz`(%Bz{Jq78^}myVPIpBU`R@>D2W298R;N6zcepJ z!6mgUGdZ!~iieFf!9Mu+TL!GBmI<03im0|7jpY7)dl~xG7IbEJ;kDgQoy{ C-xW;& literal 0 HcmV?d00001 diff --git a/tests/fuzz_corpus/riff/bwf-ixml-bext.wav b/tests/fuzz_corpus/riff/bwf-ixml-bext.wav new file mode 100644 index 0000000000000000000000000000000000000000..d4f812689f70bd02be9ea7b0f404c2d384bb3bad GIT binary patch literal 1720 zcmd^9K~LK-6gF()z-h-Fquxsrcd%+QMycaakHo2B7tk(QX~T#_8;N#>BR^^Po%YMN z=eQY^X#*}hY*C~ZL=JAIm(H@dnwQmVzvb_EEvJ}`t4TTgwBH))sNHQH&~4H?iJ*dRI}Q;L z|#`2&BJO;+y*jf#kl0u#{qF|Xh0ntaoQnn{j|V< zQTJk~+pJ7Rrkd015?;+}<}5A>=d7xx#I0eIk3`J#p$KWv zV?KsnKLL|f0}iSXL7W6i^DMUz-gSNAu0fWiMZ#Gc@;nQmv8AnJ4|q`=98wuZu$!i| zhAgdiqk?1rE^Ea%UC;AYF7M-as!9Vrw>gz7AsNpT5lV5`*Lh!1s5YG*qdieDPO1ME z8&kEfN0osO%5ccdWQooKc9h3L>D8buz|x`A6oc71ZWr#<_on9%mMR_?p}jR|o5L=(XLvx#`LbYM@lp@%M- M+1S|;xA`E^4@MafO8@`> literal 0 HcmV?d00001 diff --git a/tests/fuzz_corpus/riff/bwf-ixml-first.wav b/tests/fuzz_corpus/riff/bwf-ixml-first.wav new file mode 100644 index 0000000000000000000000000000000000000000..137c549f52fdf5789ab237a55987bb7a51ac3798 GIT binary patch literal 1110 zcmcJOO;g)25Qf#l^uVb{j-K3$KU&%xgcwC$6M-#fECsl!DM^cG8hZvZw8#E0PW&@g zR$K_37B2P0t7qR`z51$TmZ@z*&iE;OU9N(+gpgO{HTiXm!D5@dA-kkLFY>!BLg?Yo z<@exbadlm{&A}kviw41>xoGEg^X*_THQBr2;E?Um(OHHSY$ph)#K4|HrDdsDythxo z4dNt|syqf^n7EwPSJ!EKLBk%ov=*R%#R;dO4;?i81lW5Tc7G2hz;qQ2lO*}*I1U{b zvJyF@%v4jLVLx&iRT^MF>Si9aO|ZIL1Yg>ANy84id?s_SQ<*Y85^;ia{RS?pCxBfs z!noktKxI8j_QRNl8_27SEI^bg*ox!CUbe}e=(3z2F_mVxn!dC{Ue>wMyqKWNuH%Pc z6h&*7kNHDaZBTA~PFpRN09(jZ$)mBcW67}E&Gek?g$?tP#h(&qs`K@1XVhb7Jmh|7 zsj0X)vANV{z0n?sa;gkV&}^6Y!?h_#yck=FF;@z5D^&{T3{PbfbR{U03QsQwy#Ei% zKUgnTyZ|=xH^qg1UT@{G%fFaF*Do}I%72^4XEy<^sWbG{MZY(G?`YURNHU+TW}oq4 H|L^Y}g_;8s literal 0 HcmV?d00001 diff --git a/tests/fuzz_corpus/riff/lying-chunk-size.wav b/tests/fuzz_corpus/riff/lying-chunk-size.wav new file mode 100644 index 0000000000000000000000000000000000000000..af5694233e05586a40594ad96dacefa02e40f448 GIT binary patch literal 29 jcmWIYbaT^SU|48&^J$iC4j@_>ugcwC$6BSv`*a~n{Qxb}28hZvZw8#E04*a#Q zq__||EnMo0cb|Q=`&zOpndfSUkQ06k=c{$}iV*UQJSRVIFj(%8m*h2B%-8eJnEvml zIW5%f3qt6@kJY#6dU<)(bnX5i*&7a`WqZ~wn)d7dU}o|+qrm~&rQ?$vSFqhEq7nmp z3{@>l&62(MG~OakGOfx_APf^1^XBp@>&|H0BUi2kXkbaoX&gca4L<_*md5@az!X?r z4M%C3esCO9$Azqff{dAJ1~l$7SJ9;b_PuErQP)Q6i)Hks>sB=O*wu5Xz|LgG_*f(< z&iV~pwVncY#R%hq*9IyZP}82%c#8y)kp+k{16y&N>s8z6fh<@2km)SPZ|PTh6lC5@ z&5J2|^bOyQhQr~;<9&YDwKgcXp;p^kY5}&8nU;qWV<(c~YB%XI*%KS8k|iHgXUh9} zv@`0lGahljuhdjr99bo6v)SeVL^;!jrD)dIL%K2LNDyNyG2vQ+vQlSo$`U;ME#Q}+ zOlmwk1$fKulz*^Zta$-!9R3p*hPlDYeV2bRfv%ru0+s(Zq2|{Sev>!!&_%yDVee?% HUq|u_gBSz* literal 0 HcmV?d00001 diff --git a/tests/fuzz_corpus/state-json/history.json b/tests/fuzz_corpus/state-json/history.json new file mode 100644 index 0000000..b759cb9 --- /dev/null +++ b/tests/fuzz_corpus/state-json/history.json @@ -0,0 +1 @@ +[{"fingerprint": "abc", "job_name": "A001", "source": "E:/", "destinations": ["F:/A001"], "file_count": 12, "total_bytes": 3000000, "status": "Verified", "finished": "2026-08-22T10:00:00"}] \ No newline at end of file diff --git a/tests/fuzz_corpus/state-json/not-utf8.json b/tests/fuzz_corpus/state-json/not-utf8.json new file mode 100644 index 0000000..f3db0cf --- /dev/null +++ b/tests/fuzz_corpus/state-json/not-utf8.json @@ -0,0 +1 @@ +["ÿþ"] \ No newline at end of file diff --git a/tests/fuzz_corpus/state-json/regress-deep-nesting.json b/tests/fuzz_corpus/state-json/regress-deep-nesting.json new file mode 100644 index 0000000..0ce346b --- /dev/null +++ b/tests/fuzz_corpus/state-json/regress-deep-nesting.json @@ -0,0 +1 @@ +[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ \ No newline at end of file diff --git a/tests/fuzz_targets.py b/tests/fuzz_targets.py new file mode 100644 index 0000000..2ede219 --- /dev/null +++ b/tests/fuzz_targets.py @@ -0,0 +1,152 @@ +"""Byte-level fuzz targets: one function per input surface, `bytes -> None`. + +Each target writes the bytes where the surface reads them, calls it under the +shared oracle and asserts what a correct reader must return. A violation is +an AssertionError, or whatever exception escaped the documented set. + +The same functions serve three callers, so a property is stated once: + +- the Hypothesis tests, which generate the bytes; +- `test_fuzz_corpus.py`, which replays every committed seed in + `tests/fuzz_corpus//` on every test run; +- a coverage-guided fuzzer, should one be added, which only needs a + `bytes -> None` callable and the corpus folder. +""" + +from __future__ import annotations + +import json +import tempfile +from collections.abc import Callable +from pathlib import Path + +from fuzz_oracle import assert_finite, bounded +from offloader import ascmhl, braw, config, engine, history, ixml +from offloader.models import SoundInfo + +#: What `braw.read_info` may raise: its caller catches OSError, nothing else. +BRAW_MAY_RAISE = (OSError,) + + +def _written(data: bytes, name: str): + """A temporary folder holding `data` at `name`; use as a context manager.""" + folder = tempfile.TemporaryDirectory() + (Path(folder.name) / name).write_bytes(data) + return folder, Path(folder.name) / name + + +def check_sound(info: SoundInfo | None) -> None: + assert info is None or isinstance(info, SoundInfo) + assert_finite(info, "SoundInfo") + # `timecode_of` is where a rate becomes arithmetic, so it is part of the + # parser's contract: whatever was accepted must be usable. + stamp = bounded(ixml.timecode_of, info, 48000) + assert stamp is None or isinstance(stamp, str) + + +def braw_file(data: bytes) -> None: + folder, path = _written(data, "clip.braw") + with folder: + assert_finite(bounded(braw.read_info, path, allowed=BRAW_MAY_RAISE), "BrawInfo") + + +def riff(data: bytes) -> None: + folder, path = _written(data, "take.wav") + with folder: + check_sound(bounded(ixml.read_sound_info, path)) + + +def ixml_text(data: bytes) -> None: + check_sound(bounded(ixml.parse_ixml, data.decode("utf-8", "replace"))) + + +def ascmhl_manifest(data: bytes) -> None: + folder, path = _written(data, "0001_card.mhl") + with folder: + result = bounded(ascmhl.read_manifest_hashes, path) + assert isinstance(result, dict) + for name, digests in result.items(): + assert isinstance(name, str) and name + assert digests and all(isinstance(d, str) for d in digests.values()) + + +_DEFAULT = object() + + +def state_json(data: bytes) -> None: + """`read_json` returns exactly what the file holds, or the default.""" + folder, path = _written(data, "state.json") + with folder: + result = bounded(config.read_json, path, _DEFAULT) + try: + expected = json.loads(data.decode("utf-8")) + except (ValueError, RecursionError): + assert result is _DEFAULT + else: + assert json.dumps(result) == json.dumps(expected) + + +def history_file(data: bytes) -> None: + """A damaged field costs that field, never the record: the record's + fingerprint is the duplicate-card warning for that card.""" + folder, path = _written(data, "history.json") + with folder: + loaded = bounded(history.History, path) + assert loaded is not None + for entry in loaded.entries: + assert isinstance(entry.file_count, int) + assert isinstance(entry.total_bytes, int) + assert all(isinstance(d, str) for d in entry.destinations) + assert isinstance(entry.describe(), str) + try: + records = json.loads(data.decode("utf-8")) + except (ValueError, RecursionError): + records = [] + identified = [r["fingerprint"] for r in records if isinstance(r, dict) + and isinstance(r.get("fingerprint"), str)] if isinstance(records, list) else [] + kept = [entry.fingerprint for entry in loaded.entries] + assert all(fingerprint in kept for fingerprint in identified), (identified, kept) + + +def control_word(data: bytes) -> str | None: + """What a control file means, decided independently of `FileControl.read`.""" + try: + word = data.decode("utf-8").replace("\r\n", "\n").strip().lower() + except UnicodeDecodeError: + return None + return word if word in engine.FileControl.STATES else None + + +def control_file(data: bytes) -> None: + """`read` means a whole word or no opinion; `claim` replaces an empty file + or a control word and leaves anything else byte for byte.""" + folder, path = _written(data, "offload.control") + with folder: + control = engine.FileControl(path, poll=0.05) + assert bounded(control.read) == control_word(data) + + try: + text = data.decode("utf-8").strip().lower() + except UnicodeDecodeError: + text = None + replaceable = (len(data) <= engine.FileControl.MAX_BYTES and text is not None + and (not text or text in engine.FileControl.STATES)) + try: + control.claim() + except engine.UnsafeControlFile: + assert not replaceable, f"refused a replaceable control file {data!r}" + assert path.read_bytes() == data, "a refused claim changed the file" + else: + assert replaceable, f"claim overwrote {data!r}" + assert path.read_bytes() == b"run\n" + + +TARGETS: dict[str, Callable[[bytes], None]] = { + "braw": braw_file, + "riff": riff, + "ixml": ixml_text, + "ascmhl": ascmhl_manifest, + "state-json": state_json, + "history": history_file, + "control": control_file, +} diff --git a/tests/make_fuzz_seeds.py b/tests/make_fuzz_seeds.py new file mode 100644 index 0000000..75c042e --- /dev/null +++ b/tests/make_fuzz_seeds.py @@ -0,0 +1,117 @@ +"""Write the seed corpus in `tests/fuzz_corpus//`. + + python tests/make_fuzz_seeds.py + +Seeds are generated from the same builders the unit tests use, never +collected from real cards: they are reproducible, small, licence-free and of +known origin. Each is a file named for what it is, replayed through +`fuzz_targets.TARGETS[]` on every test run by `test_fuzz_corpus.py`. + +A bug a target finds adds its input here (as `regress-`), beside the +fix and the deterministic regression test. Rerunning this script rewrites +the generated seeds and leaves any other file in the folder alone. +""" + +from __future__ import annotations + +import json +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) + +from bwf import bext_chunk, ixml_document, write_wav # noqa: E402 +from test_fuzz_edges import GOOD_MDHD, atom, braw_file, video_trak # noqa: E402 + +CORPUS = HERE / "fuzz_corpus" +#: Small seeds mutate faster; anything larger belongs in a unit-test fixture. +MAX_SEED_BYTES = 8192 + + +def _wav(**options) -> bytes: + with tempfile.TemporaryDirectory() as folder: + return write_wav(Path(folder) / "take.wav", frames=16, **options).read_bytes() + + +def _asc(body: str, encoding: str = "UTF-8") -> bytes: + return (f'' + '' + "2026-01-01T00:00:00Z" + f"{body}").encode() + + +ONE_HASH = ('A001/clip.braw' + '0123456789abcdef') + +SEEDS: dict[str, dict[str, bytes]] = { + "braw": { + "video-trak.braw": braw_file(video_trak(GOOD_MDHD, struct.pack(">II", 1, 1) * 2)), + "no-video.braw": braw_file(atom(b"trak", atom(b"mdia", atom(b"hdlr", bytes(12))))), + "moov-only.braw": atom(b"moov", b""), + "regress-64bit-size-lie.braw": atom(b"ftyp", b"braw") + + struct.pack(">I", 1) + b"moov" + struct.pack(">Q", 2 ** 40), + }, + "riff": { + "bwf-ixml-bext.wav": _wav(ixml=ixml_document(), bext=bext_chunk()), + "bwf-ixml-first.wav": _wav(ixml=ixml_document(), ixml_first=True), + "bext-only.wav": _wav(bext=bext_chunk()), + "lying-chunk-size.wav": b"RIFF" + struct.pack("", + "regress-infinite-rate.wav": _wav(ixml=ixml_document(rate="inf")), + }, + "ixml": { + "recorder.xml": ixml_document().encode(), + "doctype-entity.xml": b']>&a;', + "regress-infinite-rate.xml": ixml_document(rate="inf").encode(), + "regress-overflowing-ratio.xml": ixml_document(rate="1e308/1e-308").encode(), + }, + "ascmhl": { + "one-hash.mhl": _asc(ONE_HASH), + "failed-hash.mhl": _asc(ONE_HASH.replace("original", "failed")), + "regress-encoding-tf8.mhl": _asc(ONE_HASH, "TF-8"), + "regress-encoding-shift-jis.mhl": _asc(ONE_HASH, "shift_jis"), + }, + "state-json": { + "history.json": json.dumps([{ + "fingerprint": "abc", "job_name": "A001", "source": "E:/", + "destinations": ["F:/A001"], "file_count": 12, "total_bytes": 3_000_000, + "status": "Verified", "finished": "2026-08-22T10:00:00"}]).encode(), + "not-utf8.json": b'["\xff\xfe"]', + "regress-deep-nesting.json": b"[" * 3000, + }, + "history": { + "one-record.json": json.dumps([{ + "fingerprint": "abc", "job_name": "A001", "destinations": ["F:/A001"], + "file_count": 12, "status": "Verified"}]).encode(), + "bare-object.json": b'{"fingerprint": "abc"}', + "destinations-string.json": b'[{"fingerprint": "abc", "destinations": "F:/A001"}]', + "regress-deep-nesting.json": b"[" * 3000, + "regress-overflowing-count.json": b'[{"fingerprint": "card-a", "file_count": 1e400}]', + }, + "control": { + "run": b"run\n", + "pause-crlf": b"pause\r\n", + "cancel-upper": b"CANCEL", + "cancel-with-bom": b"\xef\xbb\xbfcancel", + "cancel-pending": b"cancel pending upload", + "not-utf8": b"\xffcancel", + "clip-bytes": bytes(range(256)) * 2, + }, +} + + +def main() -> None: + for target, seeds in SEEDS.items(): + folder = CORPUS / target + folder.mkdir(parents=True, exist_ok=True) + for name, data in seeds.items(): + assert len(data) <= MAX_SEED_BYTES, f"{target}/{name} is {len(data)} bytes" + (folder / name).write_bytes(data) + print(f"wrote {sum(map(len, SEEDS.values()))} seeds under {CORPUS}") + + +if __name__ == "__main__": + main() diff --git a/tests/test_fuzz_corpus.py b/tests/test_fuzz_corpus.py new file mode 100644 index 0000000..d769f66 --- /dev/null +++ b/tests/test_fuzz_corpus.py @@ -0,0 +1,36 @@ +"""Replay every committed seed through its fuzz target, on every test run. + +The Hypothesis targets only reach their deep budgets under `--fuzz`, which +runs in its own CI job. This is the quick tier: each seed in +`tests/fuzz_corpus//` goes through `fuzz_targets.TARGETS[]` +once, so a regression input, a target that no longer loads, or a seed that +has started failing breaks the ordinary suite. Ported from markcopy's +seed-replay test. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from fuzz_targets import TARGETS +from make_fuzz_seeds import CORPUS, MAX_SEED_BYTES + +SEEDS = sorted(path for path in CORPUS.glob("*/*") if path.is_file()) + + +@pytest.mark.parametrize("seed", SEEDS, ids=lambda p: f"{p.parent.name}/{p.name}") +def test_seed_passes_its_target(seed: Path): + assert seed.stat().st_size <= MAX_SEED_BYTES, "seeds stay small" + TARGETS[seed.parent.name](seed.read_bytes()) + + +def test_every_corpus_folder_is_a_target(): + folders = {path.name for path in CORPUS.iterdir() if path.is_dir()} + assert folders <= set(TARGETS), f"no target for {sorted(folders - set(TARGETS))}" + + +def test_every_target_has_seeds(): + seeded = {seed.parent.name for seed in SEEDS} + assert seeded == set(TARGETS), f"unseeded: {sorted(set(TARGETS) - seeded)}" diff --git a/tests/test_fuzz_edges.py b/tests/test_fuzz_edges.py index d4567c0..e5e57ae 100644 --- a/tests/test_fuzz_edges.py +++ b/tests/test_fuzz_edges.py @@ -41,6 +41,7 @@ from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st +import fuzz_targets from fuzz_oracle import scaled from offloader import ascmhl, braw, engine, naming, retry from offloader.engine import OffloadOptions @@ -139,15 +140,9 @@ def write_braw(directory: Path, payload: bytes, name: str = "clip.braw") -> Path @settings(deadline=None, suppress_health_check=[HealthCheck.too_slow]) @given(payload=st.binary(max_size=4096)) -def test_braw_read_info_survives_arbitrary_bytes(payload: bytes, tmp_path_factory): +def test_braw_read_info_survives_arbitrary_bytes(payload: bytes): """The cheapest fuzz there is: a .braw that is not BRAW at all.""" - target = write_braw(tmp_path_factory.mktemp("braw"), payload) - try: - braw.read_info(target) - except PARSER_MAY_RAISE: - pass - except Exception as exc: # noqa: BLE001 - pytest.fail(f"read_info raised {type(exc).__name__}: {exc}") + fuzz_targets.braw_file(payload) @settings(deadline=None, suppress_health_check=[HealthCheck.too_slow]) diff --git a/tests/test_fuzz_parsers.py b/tests/test_fuzz_parsers.py index 3eb7e9b..30471e5 100644 --- a/tests/test_fuzz_parsers.py +++ b/tests/test_fuzz_parsers.py @@ -29,13 +29,14 @@ import pytest import xxhash -from hypothesis import HealthCheck, given, settings +from hypothesis import HealthCheck, example, given, settings from hypothesis import strategies as st +import fuzz_targets from bwf import ixml_document -from fuzz_oracle import assert_finite, bounded, scaled +from fuzz_oracle import bounded, scaled +from fuzz_targets import check_sound from offloader import ascmhl, ixml, timeline, verify -from offloader.models import SoundInfo QUICK = settings(max_examples=scaled(100), deadline=None, suppress_health_check=[HealthCheck.too_slow]) @@ -66,19 +67,11 @@ # ---------------------------------------------------------------------- iXML -def _check_sound(info: SoundInfo | None) -> None: - assert info is None or isinstance(info, SoundInfo) - assert_finite(info, "SoundInfo") - # `timecode_of` is where a rate becomes arithmetic, so it is part of the - # parser's contract: whatever was accepted must be usable. - stamp = bounded(ixml.timecode_of, info, 48000) - assert stamp is None or isinstance(stamp, str) - - @QUICK @given(text=st.text(max_size=2048)) +@example(text=ixml_document(rate="inf")) def test_parse_ixml_on_any_text(text): - _check_sound(bounded(ixml.parse_ixml, text)) + check_sound(bounded(ixml.parse_ixml, text)) @QUICK @@ -93,7 +86,7 @@ def test_parse_ixml_on_recorder_shaped_documents(project, scene, take, note, rat document = ixml_document(project=project, scene=scene, take=take, note=note, rate=rate, flag=flag, sample_rate=sample_rate, samples_since_midnight=samples, track_names=names) - _check_sound(bounded(ixml.parse_ixml, document)) + check_sound(bounded(ixml.parse_ixml, document)) def test_an_infinite_timecode_rate_is_refused(): @@ -126,10 +119,7 @@ def _riff_chunk(identifier: bytes, payload: bytes, declared: int | None) -> byte def test_read_sound_info_on_hostile_riff(chunks, form, declared): body = form + b"".join(_riff_chunk(*chunk) for chunk in chunks) size = len(body) if declared is None else declared - with tempfile.TemporaryDirectory() as folder: - path = Path(folder) / "take.wav" - path.write_bytes(b"RIFF" + struct.pack(" bytes: return bytes(buffer) +#: Deletes the U of `encoding="UTF-8"` in either manifest form, which is +#: the edit that found the LookupError escaping `ET.parse`. +UTF8_TO_TF8 = (len(' tuple[tempfile.TemporaryD # ------------------------------------------------------------------ read_json -SENTINEL = object() - - @FILES @given(data=st.binary(max_size=512) | json_values.map(lambda v: json.dumps(v).encode()) | st.builds(lambda depth, bracket: bracket * depth, st.integers(1, 200_000), st.sampled_from([b"[", b'{"a":']))) +@example(data=b"[" * 3000) def test_read_json_returns_the_value_or_the_default(data): - folder, path = _scratch(data) - with folder: - result = bounded(config.read_json, path, SENTINEL) - try: - expected = json.loads(data.decode("utf-8")) - except (ValueError, RecursionError): - expected = SENTINEL - if expected is SENTINEL: - assert result is SENTINEL - else: - assert json.dumps(result) == json.dumps(expected) + fuzz_targets.state_json(data) @pytest.mark.parametrize("opening", ["[", '{"a":']) @@ -91,23 +80,11 @@ def test_deeply_nested_state_falls_back_to_the_default(tmp_path, opening): @FILES @given(records=records) +@example(records=[{"fingerprint": "card-a", "file_count": float("inf")}]) def test_history_keeps_every_record_it_can_identify(records): """A damaged field costs that field, never the record: the record's fingerprint is the duplicate-card warning for that card.""" - folder, path = _scratch(json.dumps(records).encode()) - with folder: - loaded = bounded(history.History, path) - assert loaded is not None - for entry in loaded.entries: - assert isinstance(entry.file_count, int) - assert isinstance(entry.total_bytes, int) - assert all(isinstance(d, str) for d in entry.destinations) - assert isinstance(entry.describe(), str) - assert entry.finished_at is None or entry.finished_at.year > 0 - identified = [r["fingerprint"] for r in records - if isinstance(r, dict) and isinstance(r.get("fingerprint"), str)] - kept = [e.fingerprint for e in loaded.entries] - assert all(fingerprint in kept for fingerprint in identified), (identified, kept) + fuzz_targets.history_file(json.dumps(records).encode()) @pytest.mark.parametrize("count", ["1e400", "-1e400"]) @@ -125,15 +102,6 @@ def test_an_overflowing_count_costs_the_count_not_the_record(tmp_path, count): # --------------------------------------------------------------- control file -def _word(data: bytes) -> str | None: - """What the control file means, decided independently of `read`.""" - try: - word = data.decode("utf-8").replace("\r\n", "\n").strip().lower() - except UnicodeDecodeError: - return None - return word if word in engine.FileControl.STATES else None - - control_bytes = ( st.binary(max_size=80) | st.builds(lambda pad, word, tail: (pad + word + tail).encode(), @@ -146,14 +114,12 @@ def _word(data: bytes) -> str | None: @FILES @given(data=control_bytes) def test_control_read_means_a_word_or_no_opinion(data): - folder, path = _scratch(data, "offload.control") - with folder: - control = engine.FileControl(path, poll=0.05) - assert bounded(control.read) == _word(data) + fuzz_targets.control_file(data) @FILES @given(writes=st.lists(control_bytes, min_size=1, max_size=8)) +@example(writes=[b"cancel", b"pause"]) def test_a_damaged_control_file_never_changes_the_job(writes): """Only a whole control word moves the job. A cancel is final: a `pause` written after it may show as the file's state, but the next checkpoint @@ -166,7 +132,7 @@ def test_a_damaged_control_file_never_changes_the_job(writes): for data in writes: path.write_bytes(data) control.sync() - word = _word(data) + word = fuzz_targets.control_word(data) if word is not None: state = word cancelled = cancelled or word == engine.FileControl.CANCEL @@ -184,20 +150,4 @@ def test_a_damaged_control_file_never_changes_the_job(writes): def test_claim_never_overwrites_what_is_not_a_control_file(existing): """The control path comes from a command line and a typo can name a clip. Claiming may replace an empty file or a control word, and nothing else.""" - folder, path = _scratch(existing, "offload.control") - with folder: - control = engine.FileControl(path, poll=0.05) - try: - text = existing.decode("utf-8").strip().lower() - except UnicodeDecodeError: - text = None - replaceable = (len(existing) <= engine.FileControl.MAX_BYTES - and text is not None - and (not text or text in engine.FileControl.STATES)) - if replaceable: - control.claim() - assert path.read_bytes() == b"run\n" - else: - with pytest.raises(engine.UnsafeControlFile): - control.claim() - assert path.read_bytes() == existing + fuzz_targets.control_file(existing) From 737bd58e8276658fac89a608d3e57c1a91de6bf2 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:54:32 -0700 Subject: [PATCH 5/6] Fuzz whole offloads under injected faults tests/test_fuzz_engine.py runs engine.run end to end on a random card, against destinations that may already hold a good copy, a stale one, a truncated one or a same-size impostor, in each verification mode, with skip and replace on or off. A fault plan fails source reads, destination writes, fsync or promotion, transiently or for good, once or from then on; corrupts a staged copy before its full reread; or cancels the job at an arbitrary progress event. The oracle checks the bytes on disk, not the job's account of them: run raises nothing and finishes within a watchdog, the source is unchanged, no partial survives and nothing else appears, every final-named file is the old one or exactly the source, a different existing file survives unless replace_existing, Verified and Copied destinations hold the source, and a "Verified" job had every destination verified, was not cancelled, saw no fault that kept failing and omitted no file. 1200 offloads at --fuzz depth found no violation. Planting a skipped checksum comparison or a no-op _discard in the engine fails the target at the quick budget. Hypothesis events report which faults fired and which verdicts resulted, so a harness that stops reaching the engine shows up in --hypothesis-show-statistics. --- .github/workflows/ci.yml | 7 +- AGENTS.md | 2 +- CONTRIBUTING.md | 2 +- README.md | 16 +- tests/fuzz_surfaces.json | 5 +- tests/test_fuzz_engine.py | 332 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 354 insertions(+), 10 deletions(-) create mode 100644 tests/test_fuzz_engine.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c0a23c4..08ccf3d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -104,14 +104,15 @@ jobs: python -m pip install --upgrade pip python -m pip install -e ".[dev]" - name: Run the property tests at soak depth - # All five property modules: test_fuzz.py fuzzes what a filename can + # All six property modules: test_fuzz.py fuzzes what a filename can # contain, test_fuzz_edges.py what a card can contain, # test_fuzz_parsers.py the documents read back (iXML, ASC MHL, the # manifest verify vouches for, timeline URLs), test_fuzz_state.py the - # files kept between runs (state, history, the control file), and + # files kept between runs (state, history, the control file), + # test_fuzz_engine.py whole offloads under injected faults, and # test_edge_cases.py # the layers between the bytes and the paperwork. - run: pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_fuzz_state.py tests/test_edge_cases.py --fuzz -q + run: pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_fuzz_state.py tests/test_fuzz_engine.py tests/test_edge_cases.py --fuzz -q build: name: build the distribution diff --git a/AGENTS.md b/AGENTS.md index c0f4a29..1e4e89b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -135,7 +135,7 @@ python -m pytest -q Run the deeper property checks when relevant to safety or parser changes: ```powershell -python -m pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_fuzz_state.py tests/test_edge_cases.py --fuzz -q +python -m pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_fuzz_state.py tests/test_fuzz_engine.py tests/test_edge_cases.py --fuzz -q ``` A module that starts reading outside input needs an entry in diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9b4f873..256b119 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,7 +38,7 @@ pip install -e ".[dev]" ```sh pytest # run the full suite -pytest --fuzz # property tests at 3000 examples each, about 5 min +pytest --fuzz # property tests at 3000 examples each, about 7 min ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` diff --git a/README.md b/README.md index 91d3a39..794f572 100644 --- a/README.md +++ b/README.md @@ -622,12 +622,12 @@ what makes the report layer testable without moving bytes. ```sh pip install -e ".[dev]" pytest # run the full suite -pytest --fuzz # same suite, 3000 examples per property (~5 min) +pytest --fuzz # same suite, 3000 examples per property (~7 min) ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` -988 tests at 87% line coverage. They cover formatting against the reference's +989 tests at 87% line coverage. They cover formatting against the reference's exact strings, checksum vectors and streaming equivalence, copy/verify behaviour including simulated destination corruption, pause/resume/cancel concurrency, retry discrimination, BRAW container parsing, ffprobe parsing, @@ -646,7 +646,7 @@ real camera file when one is present. ### Property-based testing -Five modules use [Hypothesis][hyp] to assert invariants over generated input +Six modules use [Hypothesis][hyp] to assert invariants over generated input rather than over a handful of fixtures, each aimed at a different layer: - **`tests/test_fuzz.py`: what a filename can contain.** Names come off camera @@ -676,6 +676,16 @@ rather than over a handful of fixtures, each aimed at a different layer: The byte-level properties also replay a committed seed corpus (`tests/fuzz_corpus/`) on every run, including the input behind every bug the fuzzers have found, so those stay fixed without `--fuzz`. +- **`tests/test_fuzz_engine.py`: whole offloads under faults.** A random card + against destinations that may already hold a good copy, a stale one or a + same-size impostor, while source reads, writes, fsync or promotion fail + (transiently or for good), a staged copy is corrupted before its reread, or + the job is cancelled mid-flight. Checked against the bytes on disk: no + partial survives, every final file is the old one or exactly the source, a + different existing file survives unless replacing was asked for, nothing + marked Verified differs from the source, and a "Verified" job saw no fault + that kept failing. Planting a skipped checksum comparison or a no-op cleanup + in the engine fails it within the quick budget. - **`tests/test_edge_cases.py`: the layers between the bytes and the paperwork.** What ffprobe hands back, what a number formats to, what a digest compares equal to, what a name renders to. diff --git a/tests/fuzz_surfaces.json b/tests/fuzz_surfaces.json index 38169b0..511c68f 100644 --- a/tests/fuzz_surfaces.json +++ b/tests/fuzz_surfaces.json @@ -46,9 +46,10 @@ "tests/test_fuzz_edges.py::test_exclude_patterns_never_raise", "tests/test_fuzz_state.py::test_control_read_means_a_word_or_no_opinion", "tests/test_fuzz_state.py::test_a_damaged_control_file_never_changes_the_job", - "tests/test_fuzz_state.py::test_claim_never_overwrites_what_is_not_a_control_file" + "tests/test_fuzz_state.py::test_claim_never_overwrites_what_is_not_a_control_file", + "tests/test_fuzz_engine.py::test_an_offload_under_faults_keeps_the_safety_contract" ], - "gap": "Source scanning is example-tested only; no generated sequence of copy, verify, cancel and cleanup with injected faults." + "gap": "Source scanning is example-tested only. Faults are injected at the engine's I/O seams (open, read, write, fsync, replace, cache eviction), not below them; pause, paranoid rereads and concurrent instances are not in the fault plan." }, "src/offloader/hashers.py": { "targets": [ diff --git a/tests/test_fuzz_engine.py b/tests/test_fuzz_engine.py new file mode 100644 index 0000000..220beca --- /dev/null +++ b/tests/test_fuzz_engine.py @@ -0,0 +1,332 @@ +"""Fuzz whole offloads: random cards, existing copies and injected faults. + +Every other fuzz target feeds one parser. This one runs `engine.run` end to +end, on a random card, against destinations that may already hold a good +copy, a stale one or a same-size impostor, while a fault plan fails source +reads, destination writes, fsync or promotion, corrupts a staged copy before +it is reread, or cancels the job at an arbitrary progress event. + +The oracle is the safety contract in AGENTS.md and docs/data-safety.md, +checked against the bytes on disk rather than against what the job says: + +- `run` raises nothing once its pre-flight checks pass, and finishes; +- the source is never changed; +- no `.offloader-partial` survives, and nothing else new appears; +- every final-named file holds either what was there before or exactly the + source's bytes: never a truncation, never a corrupt staged copy; +- a pre-existing different file survives unless `replace_existing`; +- a destination marked Verified or Copied holds the source's bytes, and one + marked Skipped at least has its size; +- a "Verified" job had every destination verified, was not cancelled, and + saw no fault that kept failing; +- no source file is silently missing from the job. + +Run longer sweeps with: pytest --fuzz tests/test_fuzz_engine.py +""" + +from __future__ import annotations + +import errno +import os +import random +import tempfile +import threading +from dataclasses import dataclass, field +from pathlib import Path + +import pytest +from hypothesis import HealthCheck, event, given, settings +from hypothesis import strategies as st + +from fuzz_oracle import scaled +from offloader import engine, longpath, retry +from offloader.models import FileStatus, VerificationMode + +CHUNK = 4096 +#: Long enough for a slow CI runner, short enough that a deadlock is a finding. +FINISH_WITHIN = 60.0 + +ENGINE = settings(max_examples=scaled(40), deadline=None, + suppress_health_check=[HealthCheck.too_slow, + HealthCheck.data_too_large]) + + +def _error(code: int, winerror: int, message: str) -> OSError: + """An OSError retry.py classifies the same way on every platform: when + `winerror` is set it alone decides.""" + exc = OSError(code, message) + exc.winerror = winerror + return exc + + +def transient() -> OSError: + return _error(errno.EIO, 1117, "simulated I/O device error") + + +def permanent() -> OSError: + return _error(errno.ENOSPC, 112, "simulated disk full") + + +@dataclass +class Fault: + kind: str # read | write | fsync | replace | corrupt | cancel + nth: int # fires on the nth operation of its kind + sticky: bool # and on every one after it + lasting: bool # a permanent error rather than a transient one + + def due(self, count: int) -> bool: + return count == self.nth or (self.sticky and count > self.nth) + + +@dataclass +class Plan: + faults: list[Fault] + counts: dict[str, int] = field(default_factory=dict) + fired: list[Fault] = field(default_factory=list) + lock: threading.Lock = field(default_factory=threading.Lock) + + def tick(self, kind: str) -> Fault | None: + """Count one operation of `kind`; the fault due on it, if any.""" + with self.lock: + count = self.counts[kind] = self.counts.get(kind, 0) + 1 + for fault in self.faults: + if fault.kind == kind and fault.due(count): + self.fired.append(fault) + return fault + return None + + def raise_if_due(self, kind: str) -> None: + fault = self.tick(kind) + if fault is not None: + raise permanent() if fault.lasting else transient() + + @property + def kept_failing(self) -> bool: + """A sticky fault fired: retries see it too, so something must fail.""" + return any(fault.sticky and fault.kind != "cancel" for fault in self.fired) + + +class _Faulty: + """A file handle whose reads or writes consult the plan first.""" + + def __init__(self, handle, plan: Plan, kind: str, fds: set[int]) -> None: + self._handle, self._plan, self._kind = handle, plan, kind + if kind == "write": + fds.add(handle.fileno()) + + def read(self, *args): + self._plan.raise_if_due("read") + return self._handle.read(*args) + + def write(self, data): + self._plan.raise_if_due("write") + return self._handle.write(data) + + def __getattr__(self, name): + return getattr(self._handle, name) + + def __enter__(self): + return self + + def __exit__(self, *exc): + self._handle.close() + return False + + +def _install(mp: pytest.MonkeyPatch, plan: Plan, card: Path, dests: list[Path]) -> None: + card = card.resolve() + dests = [d.resolve() for d in dests] + fds: set[int] = set() + open_binary, replace = longpath.open_binary, longpath.replace + evict, fsync = engine.integrity.evict_from_cache, os.fsync + + def under(path, roots) -> bool: + resolved = Path(os.path.abspath(str(path).removeprefix("\\\\?\\"))) + return any(resolved.is_relative_to(root) for root in roots) + + def faulty_open(path, mode="rb", *args, **kwargs): + handle = open_binary(path, mode, *args, **kwargs) + if "r" in mode and under(path, [card]): + return _Faulty(handle, plan, "read", fds) + if "w" in mode and under(path, dests): + return _Faulty(handle, plan, "write", fds) + return handle + + def faulty_fsync(fd): + if fd in fds: + plan.raise_if_due("fsync") + return fsync(fd) + + def faulty_replace(source, target): + if under(target, dests): + plan.raise_if_due("replace") + return replace(source, target) + + def corrupting_evict(path): + # The last moment before the verify reread: flipping a byte here is a + # write that landed wrong, which only a full reread can catch. + if str(path).endswith(engine.PARTIAL_SUFFIX) and plan.tick("corrupt"): + data = bytearray(Path(path).read_bytes()) + if data: + data[len(data) // 2] ^= 0xFF + Path(path).write_bytes(bytes(data)) + return evict(path) + + mp.setattr(engine, "CHUNK_SIZE", CHUNK) + mp.setattr(longpath, "open_binary", faulty_open) + mp.setattr(longpath, "replace", faulty_replace) + mp.setattr(os, "fsync", faulty_fsync) + mp.setattr(engine.integrity, "evict_from_cache", corrupting_evict) + + +# ----------------------------------------------------------------- strategies + +names = st.sampled_from(["A001_C001.mov", "A001_C002.mov", "CLIP/B002.braw", + "CLIP/B003.braw", "SOUND/T01.wav", "x"]) +#: (seed, size): bytes are drawn from a seeded generator, not by Hypothesis, +#: so a 16 KB clip does not cost 16 KB of shrinkable choices. +contents = st.tuples(st.integers(0, 2**32), st.integers(0, 4 * CHUNK + 7)) +cards = st.dictionaries(names, contents, min_size=1, max_size=4).filter( + lambda card: not ("x" in card and any(n.startswith("x/") for n in card))) + +#: What a destination already holds at a card file's path. +PRIOR = ["nothing", "same", "different", "same-size", "truncated"] + +faults = st.lists(st.builds( + Fault, + kind=st.sampled_from(["read", "write", "fsync", "replace", "corrupt", "cancel"]), + nth=st.integers(1, 8), sticky=st.booleans(), lasting=st.booleans()), + min_size=1, max_size=3) + + +def _bytes(seed: int, size: int) -> bytes: + return random.Random(seed).randbytes(size) + + +def _snapshot(root: Path) -> dict[str, bytes]: + return {p.relative_to(root).as_posix(): p.read_bytes() + for p in root.rglob("*") if p.is_file()} + + +# ---------------------------------------------------------------------- target + + +@ENGINE +@given(card=cards, destinations=st.integers(1, 2), prior=st.data(), + mode=st.sampled_from(list(VerificationMode)), skip_existing=st.booleans(), + replace_existing=st.booleans(), plan=faults) +def test_an_offload_under_faults_keeps_the_safety_contract( + card, destinations, prior, mode, skip_existing, replace_existing, plan): + if mode is not VerificationMode.FULL: + # Only a full reread can see a corrupt write; under the other modes it + # is a documented limit, not a property. + plan = [f for f in plan if f.kind != "corrupt"] + plan = Plan(plan) + + with tempfile.TemporaryDirectory() as folder, pytest.MonkeyPatch.context() as mp: + base = Path(folder) + source = {name: _bytes(*spec) for name, spec in card.items()} + for name, data in source.items(): + (base / "card" / name).parent.mkdir(parents=True, exist_ok=True) + (base / "card" / name).write_bytes(data) + + roots = [base / f"dest{i}" for i in range(destinations)] + before: list[dict[str, bytes]] = [] + for root in roots: + root.mkdir() + for name, data in source.items(): + kind = prior.draw(st.sampled_from(PRIOR), label=f"{root.name}/{name}") + old = {"same": data, "different": data[::-1] + b"old", + "same-size": bytes(len(data)), "truncated": data[: len(data) // 2], + }.get(kind) + if old is not None: + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_bytes(old) + before.append(_snapshot(root)) + + control = engine.JobControl() + events = 0 + + def progress(event) -> None: + nonlocal events + events += 1 + if plan.tick("cancel"): + control.cancel() + + options = engine.OffloadOptions( + destinations=roots, verification=mode, thumbnail_count=0, + extra_probe=False, skip_existing=skip_existing, + replace_existing=replace_existing, + retry=retry.RetryPolicy(attempts=3, delay=0)) + _install(mp, plan, base / "card", roots) + + outcome: dict = {} + + def offload() -> None: + try: + outcome["job"] = engine.run(base / "card", options, progress=progress, + control=control) + except BaseException as exc: # noqa: BLE001 - reported below + outcome["error"] = exc + + worker = threading.Thread(target=offload, daemon=True) + worker.start() + worker.join(FINISH_WITHIN) + mp.undo() + + assert not worker.is_alive(), f"run did not finish; faults fired: {plan.fired}" + if "error" in outcome: + raise AssertionError(f"run raised; faults fired: {plan.fired}") \ + from outcome["error"] + job = outcome["job"] + # Visible with --hypothesis-show-statistics: proof the plan reaches + # the engine, rather than every fault landing after the job ended. + for kind in sorted({fault.kind for fault in plan.fired}) or ["no fault"]: + event(f"fired: {kind}") + event(f"verdict: {job.final_status}") + _assert_contract(job, base, source, roots, before, plan, mode, + skip_existing, replace_existing) + + +def _assert_contract(job, base, source, roots, before, plan, mode, + skip_existing, replace_existing) -> None: + context = f"faults fired: {plan.fired}; verdict {job.final_status!r}" + + assert _snapshot(base / "card") == source, f"the source changed; {context}" + + for root, prior in zip(roots, before, strict=True): + after = _snapshot(root) + partials = [name for name in after if name.endswith(engine.PARTIAL_SUFFIX)] + assert not partials, f"left behind {partials}; {context}" + strays = set(after) - set(source) - set(prior) + assert not strays, f"unexpected files {strays}; {context}" + for name, data in after.items(): + assert data in (prior.get(name), source.get(name)), ( + f"{root.name}/{name} is neither the old file nor the source; {context}") + old = prior.get(name) + if old is not None and old != source[name] and not replace_existing: + assert data == old, f"{root.name}/{name} was replaced; {context}" + + listed = {Path(entry.source).resolve() for entry in job.files} + listed |= {Path(p).resolve() for p in job.not_attempted} + missing = [n for n in source if (base / "card" / n).resolve() not in listed] + assert not missing, f"silently omitted {missing}; {context}" + + statuses = [] + for entry in job.files: + name = Path(entry.source).resolve().relative_to((base / "card").resolve()).as_posix() + for destination in entry.destinations: + statuses.append(destination.status) + target = Path(destination.path) + if destination.status in (FileStatus.VERIFIED, FileStatus.COPIED): + assert target.read_bytes() == source[name], ( + f"{target} marked {destination.status.value} but differs; {context}") + elif destination.status is FileStatus.SKIPPED: + assert skip_existing and target.stat().st_size == len(source[name]) + + if job.final_status == "Verified": + assert mode is not VerificationMode.NONE + assert statuses and all(s is FileStatus.VERIFIED for s in statuses), context + assert len(job.files) == len(source), context + assert not job.cancelled, context + assert not plan.kept_failing, f"a fault kept failing and the job says Verified; {context}" From 78296fd1a894b73c623c20e6da1e77909afabb43 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:02:33 -0700 Subject: [PATCH 6/6] Run the property-test soak nightly on Linux and Windows The soak took about 7 minutes on every pull request and ran on Linux only. .github/workflows/fuzz.yml now runs the whole suite under --fuzz nightly and on demand (with an example count input), on ubuntu-latest and windows-latest, with a 60-minute timeout. Hypothesis's example database is carried between runs through actions/cache, so a failure found one night is replayed first the next. Permissions are split: the soak job holds a read-only token, and a separate report job with issues: write opens or comments on a "Fuzz failure: " issue carrying the run link and the falsifying examples with their @reproduce_failure lines. A placeholder log and a !success() upload mean a setup failure or a timeout still reaches an issue. The fuzz profile now prints those blobs and reads its depth from OFFLOADER_FUZZ_EXAMPLES. Pull requests keep every property at 100 examples and the seed corpus replay; the soak job is removed from ci.yml. test_fuzz_surfaces now checks that fuzz.yml is scheduled and runs every fuzz module. The release plan's candidate qualification adds a dispatched soak run and no open "Fuzz failure:" issue. --- .github/workflows/ci.yml | 23 ------ .github/workflows/fuzz.yml | 146 ++++++++++++++++++++++++++++++++++++ AGENTS.md | 7 +- CHANGELOG.md | 7 ++ CONTRIBUTING.md | 11 ++- docs/release-plan.md | 4 +- tests/conftest.py | 7 +- tests/test_fuzz_surfaces.py | 12 ++- 8 files changed, 184 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/fuzz.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 08ccf3d..e8a1f52 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,29 +91,6 @@ jobs: - run: offloader info - run: pytest -q - fuzz: - name: property tests (soak) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: "3.13" - cache: pip - - run: | - python -m pip install --upgrade pip - python -m pip install -e ".[dev]" - - name: Run the property tests at soak depth - # All six property modules: test_fuzz.py fuzzes what a filename can - # contain, test_fuzz_edges.py what a card can contain, - # test_fuzz_parsers.py the documents read back (iXML, ASC MHL, the - # manifest verify vouches for, timeline URLs), test_fuzz_state.py the - # files kept between runs (state, history, the control file), - # test_fuzz_engine.py whole offloads under injected faults, and - # test_edge_cases.py - # the layers between the bytes and the paperwork. - run: pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_fuzz_state.py tests/test_fuzz_engine.py tests/test_edge_cases.py --fuzz -q - build: name: build the distribution runs-on: ubuntu-latest diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 0000000..55e0225 --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,146 @@ +name: Fuzz + +# The soak: every property test at a deep example budget. Too slow for every +# pull request, where the ordinary suite already runs each property at 100 +# examples and replays the committed seed corpus. Here it runs nightly and on +# demand, on Linux and on Windows, whose paths, junctions and file locking are +# where a card offload is most likely to differ. +# +# Permissions are split as in markcopy's fuzz workflow: the job that runs +# untrusted-input tests holds a read-only token, and only the reporting job +# can write issues. + +on: + schedule: + - cron: "17 3 * * *" + workflow_dispatch: + inputs: + examples: + description: Examples per property (the --fuzz default is 3000) + required: false + default: "3000" + +permissions: + contents: read + +concurrency: + group: fuzz-${{ github.ref }} + cancel-in-progress: false + +env: + QT_QPA_PLATFORM: offscreen + PYTHONUTF8: "1" + +jobs: + soak: + name: soak / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + # Replaced by the test output below. If setup fails first, this is the + # log the artifact carries, so that platform still gets an issue. + - run: echo "The soak did not reach the tests." > soak.log + shell: bash + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + cache: pip + - run: | + python -m pip install --upgrade pip + python -m pip install -e ".[dev]" + + # Hypothesis replays every failing example it has saved before + # generating new ones, so a failure found one night is retried first + # the next. A per-run key with a prefix restore carries the newest + # database forward. + - uses: actions/cache@v4 + with: + path: .hypothesis + key: hypothesis-${{ matrix.os }}-${{ github.run_id }} + restore-keys: hypothesis-${{ matrix.os }}- + + - name: Run every property test at soak depth + shell: bash + env: + OFFLOADER_FUZZ_EXAMPLES: ${{ inputs.examples || '3000' }} + # The whole suite, so a new fuzz module needs no change here. + run: | + set -o pipefail + pytest --fuzz -q 2>&1 | tee soak.log + + - name: Keep the log and the example database + # Not `failure()`: a job that hits timeout-minutes ends cancelled. + if: ${{ !success() }} + uses: actions/upload-artifact@v4 + with: + name: soak-${{ matrix.os }} + path: | + soak.log + .hypothesis/ + retention-days: 30 + + report: + name: file the failure + needs: soak + # Any soak outcome but success, timeouts included. A run cancelled by + # hand files one too; close it if it says nothing. + if: ${{ always() && needs.soak.result != 'success' }} + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + actions: read + steps: + - uses: actions/download-artifact@v4 + with: + pattern: soak-* + - name: Open or update an issue per failing platform + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + shopt -s nullglob + folders=(soak-*/) + if [ ${#folders[@]} -eq 0 ]; then + # Failed before the log existed: setup, install, or a timeout. + folders=("soak-unknown/") + fi + for folder in "${folders[@]}"; do + platform="${folder#soak-}"; platform="${platform%/}" + title="Fuzz failure: ${platform}" + { + echo "The nightly soak failed on \`${platform}\`: ${RUN_URL}" + echo + if [ -f "${folder}soak.log" ]; then + echo "Each falsifying example is printed with a \`@reproduce_failure\`" + echo "line that replays it locally. The log and the example database" + echo "are attached to the run as \`soak-${platform}\`." + echo + echo '```' + found=$(sed -n -E '/^(FAILED|E |Falsifying|@reproduce_failure)/p' "${folder}soak.log" | head -n 80) + if [ -n "${found}" ]; then + echo "${found}" + else + # No test failed: setup broke, or the job ran out of time. + tail -n 40 "${folder}soak.log" + fi + echo '```' + else + echo "No log was produced: the job failed before the tests ran or" + echo "timed out. Treat the harness as broken until the run says why." + fi + } > body.md + existing=$(gh issue list --state open --search "in:title \"${title}\"" \ + --json number,title --jq ".[] | select(.title == \"${title}\") | .number" | head -n 1) + if [ -n "${existing}" ]; then + gh issue comment "${existing}" --body-file body.md + else + gh issue create --title "${title}" --body-file body.md + fi + done diff --git a/AGENTS.md b/AGENTS.md index 1e4e89b..c5db3cc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -165,8 +165,11 @@ reference outputs for formats and checksums over tests that mirror the writer. See CONTRIBUTING for existing synthetic BRAW/BWF fixtures and failure helpers. CI configuration is in [ci.yml](.github/workflows/ci.yml): cross-platform -tests, a Python minimum-version job, ffmpeg coverage, property-test soak, and -wheel/sdist validation. A configured job is not evidence of a passing run. +tests, a Python minimum-version job, ffmpeg coverage, and wheel/sdist +validation. The property-test soak runs nightly and on demand in +[fuzz.yml](.github/workflows/fuzz.yml) on Linux and Windows, and a failure +opens or updates a `Fuzz failure: ` issue. A configured job is not +evidence of a passing run. Report what was actually executed and any skips or environment limitations. ## Implementation, documentation, and releases diff --git a/CHANGELOG.md b/CHANGELOG.md index 5eb1e71..12dfa49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,13 @@ runs. Each fix has the reproduction that found it. ### Changed +- **The property-test soak runs nightly, on Linux and Windows.** It took + about 7 minutes on every pull request and ran on Linux only. `fuzz.yml` + now runs it on a schedule and on demand, keeps Hypothesis's database of + failing examples between runs, and opens or updates a `Fuzz failure: ` + issue with the reproduction when it fails. Pull requests still run every + property at the quick budget and replay the seed corpus. + - **Full verification is the default.** The read-back is the only mode that proves what is on the destination device, and the default should be the one whose "Verified" means the most. Applies to the engine's options, new diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 256b119..d2df6c8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,7 +68,16 @@ that fuzz it, or a `gap` saying what is not fuzzed yet. A module that starts parsing card data, a manifest, a timeline or a state file comes with an entry in the same change: a new target, or an honest gap. `tests/test_fuzz_surfaces.py` fails on an unclassified module, a target that is not a `@given` test, a fuzz -test no surface claims, or a fuzz file the CI soak job does not run. +test no surface claims, or a soak workflow that no longer runs on a schedule. + +The soak (`pytest --fuzz`, about 3000 examples per property) is too slow for +every pull request, so [`fuzz.yml`](.github/workflows/fuzz.yml) runs it +nightly on Linux and Windows, and on demand with a chosen example count +(`OFFLOADER_FUZZ_EXAMPLES` locally). Pull requests still run every property +at 100 examples and replay the seed corpus. A nightly failure opens or +updates a `Fuzz failure: ` issue with the falsifying examples and their +`@reproduce_failure` lines; paste one above the failing test to replay it, +then fix it as below. A target checks the answer, not just that nothing raised. Wrap the call in `fuzz_oracle.bounded` (documented exceptions only, a time and memory ceiling) diff --git a/docs/release-plan.md b/docs/release-plan.md index ad02213..50c5fd8 100644 --- a/docs/release-plan.md +++ b/docs/release-plan.md @@ -52,7 +52,7 @@ tests or builds were run for this documentation task. | --- | --- | --- | | Product | Engine, CLI, Qt desktop app, reports, BRAW/BWF support, optional timeline import | Exercise the frozen application against representative workflows | | Version | One source in `src/offloader/_version.py` used by package metadata and the Windows bundle | Confirm the frozen release identity across all published assets | -| CI | Windows/macOS/Linux tests on Python 3.13, Linux Python 3.10, ffmpeg job, property-test soak, wheel/sdist build and metadata checks | Install built artifacts in fresh environments; build and smoke-test Windows desktop artifacts | +| CI | Windows/macOS/Linux tests on Python 3.13, Linux Python 3.10, ffmpeg job, nightly property-test soak on Linux and Windows, wheel/sdist build and metadata checks | Install built artifacts in fresh environments; build and smoke-test Windows desktop artifacts | | Distribution | Frozen bundle, NSIS installer path, source and bundle inventories, and checksums | Hardware-key signing, clean-machine installation, release workflow, and publication documentation | | Dependencies | Minimum versions and optional extras | Recorded build environment and pinned release dependency sets | | Media tools | ffmpeg/ffprobe discovered externally; copying works without them | Explicit installer dependency policy and useful missing-tool messaging | @@ -127,7 +127,7 @@ not elapsed time; set a public date after the first clean-machine pilot. | 1. Release foundation | Single version source; frozen scope; dependency pins; build instructions; chosen artifact names and repository | A clean checkout produces matching package/app/report versions; release identity is unambiguous | | 2. Windows package | PyInstaller spec and entry points; icon/version metadata; NSIS installer; third-party notices; media-tool status | GUI and CLI work on a clean Windows account without Python; reports render and manifests re-verify | | 3. Trust and installation | Signing integration; signature verification; safe active-job handling; install/upgrade/uninstall checks | Both executable and installer signatures validate; install lifecycle preserves user data and never interrupts a job | -| 4. Candidate qualification | All existing CI jobs green for the exact source commit; artifact smoke tests; integrity acceptance matrix below | Every gate has recorded evidence; no unexplained skips, false success, data loss, or blocking install defects | +| 4. Candidate qualification | All existing CI jobs green for the exact source commit, including a dispatched soak run; no open `Fuzz failure:` issue; artifact smoke tests; integrity acceptance matrix below | Every gate has recorded evidence; no unexplained skips, false success, data loss, or blocking install defects | | 5. Private pilot | Same candidate tested by 3 to 5 willing users on disposable copies of real media | At least 3 complete offload/re-verify workflows across 2 independent Windows machines; all blocking findings resolved and retested | | 6. Public beta | GitHub prerelease; verified asset downloads; quick start; known limits; support instructions; brief demo | A new user can install, run, locate the reports, and report a problem using the published instructions | | 7. Stabilize | Triage pilot/public reports; publish fixes with fresh versions; retain prior assets | At least one week of observation plus repeat acceptance evidence and no open integrity, installation, or recovery blockers before a normal release | diff --git a/tests/conftest.py b/tests/conftest.py index 3ef08f0..337dd93 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -153,8 +153,13 @@ def pytest_configure(config): "ci", max_examples=100, deadline=None, suppress_health_check=[HealthCheck.too_slow], ) + # The nightly job can ask for a different depth without a code change; + # `fuzz_oracle.scaled` budgets follow whatever this is. `print_blob` + # puts a `@reproduce_failure` line in the log, so a failure seen only in + # CI can be replayed locally from the issue it opens. settings.register_profile( - "fuzz", max_examples=3000, deadline=None, + "fuzz", max_examples=int(os.environ.get("OFFLOADER_FUZZ_EXAMPLES", "3000")), + deadline=None, print_blob=True, suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large], ) settings.load_profile("fuzz" if config.getoption("--fuzz") else "ci") diff --git a/tests/test_fuzz_surfaces.py b/tests/test_fuzz_surfaces.py index 59e0b9e..99e5672 100644 --- a/tests/test_fuzz_surfaces.py +++ b/tests/test_fuzz_surfaces.py @@ -97,10 +97,14 @@ def test_every_hypothesis_test_is_claimed_by_a_surface(): def test_every_fuzz_file_runs_in_the_soak_job(): - """The soak job names its files, so a new one is otherwise left at the - quick-run budget forever.""" - workflow = (REPO / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + """The nightly soak is the only place the deep budgets run. It runs the + whole suite; should it ever name files instead, a new fuzz module would + be left at the quick budget forever, so every one must then be named.""" + workflow = (REPO / ".github" / "workflows" / "fuzz.yml").read_text(encoding="utf-8") + assert "schedule:" in workflow, "the soak must run on a schedule" soak = [line for line in workflow.splitlines() if re.search(r"pytest .*--fuzz", line)] - assert len(soak) == 1, "expected exactly one `pytest ... --fuzz` line in ci.yml" + assert len(soak) == 1, "expected exactly one `pytest ... --fuzz` line in fuzz.yml" + if "tests/" not in soak[0]: + return missing = [test_file for test_file in fuzz_files() if test_file not in soak[0]] assert not missing, f"not in the soak job's pytest line: {missing}"