From 77fcea542ffd732834132493be912d2042b6cc24 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:50:33 -0700 Subject: [PATCH 1/7] Supersede an unhashed entry only with the same source file or job A later manifest for the same root used to answer an earlier one's unhashed entry by path alone, so card A002's clip cleared card A001's failed clip at the same relative path and the tree read VERIFIED. A file entry now also needs the same recorded source size and modification date (compared as instants), and a folder marker needs the same job name, ignoring case and the taken-name suffix. ASC MHL records no job name, so its folder markers are never superseded. --- CHANGELOG.md | 8 ++ README.md | 4 +- docs/data-safety.md | 36 ++++++-- src/offloader/naming.py | 19 ++++ src/offloader/verify.py | 154 +++++++++++++++++++++++++++----- tests/test_naming.py | 12 +++ tests/test_verdict_integrity.py | 144 +++++++++++++++++++++++++++-- 7 files changed, 338 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21ed0d7..48fe543 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,14 @@ project uses [semantic versioning][semver]. ### Fixed +- **A different card's manifest could clear a failed card's entry.** When + card A001 failed a clip and card A002 was offloaded into the same root, + A002's clip at the same relative path superseded A001's unhashed entry and + `verify` passed with A001's clip never copied. An unhashed entry is now + superseded only when both entries record the same source size and + modification date. A folder marker, which records neither, is superseded + only by a manifest naming the same job; ASC MHL records no job name, so + its markers are never superseded. - **A timeline offload could call a partial cut complete.** With nothing to copy it printed "every reference is already here" and exited 0 while references were missing or ambiguous, and with gaps to copy it reported diff --git a/README.md b/README.md index aeabcdf..1b2cab9 100644 --- a/README.md +++ b/README.md @@ -252,8 +252,8 @@ destination, including any that failed (recorded with no checksum when none could be taken), so a destination missing a clip fails here; every manifest under the folder is checked, earlier runs' included. An entry a failed run could not hash is reported as superseded, and stops failing, once a newer manifest for -the same destination lists that file with a hash that still matches; a hashed -entry is never superseded. See +the same destination lists that file with a hash that still matches and the +same source size and modification date; a hashed entry is never superseded. See [`docs/data-safety.md`](docs/data-safety.md#a-manifest-lists-what-did-not-arrive). `--allow-cache` skips the page-cache eviction: faster, and may verify memory rather than the device. diff --git a/docs/data-safety.md b/docs/data-safety.md index d294748..7061771 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -211,23 +211,43 @@ Every file the job scanned is now listed for each destination: An unhashed entry has nothing to pass against, so on its own it keeps failing. After a failed run has been resumed, its manifest still lists the files it could not read. When `verify` checks a folder, such an entry is **superseded** if a -newer manifest for the same destination root lists the same path with a hash -and that file matches it now. The entry is printed as `superseded by -`, not dropped, and the older manifest passes only if nothing else in -it failed. +newer manifest for the same destination root lists the same path with a hash, +that file matches it now, and both entries record the same size and the same +last-modification date. The entry is printed as `superseded by `, not +dropped, and the older manifest passes only if nothing else in it failed. Supersession runs one way only: - Only an entry with no hash can be superseded. A hashed entry is never answered by a later manifest, so a copy corrupted since an earlier run still fails on that run's manifest, whatever a later run recorded. +- The size and date must agree because a path alone does not say which card a + file came from. Both are the *source* file's, so a rerun of the same card + records the same pair. Card A002 offloaded into the same root after card + A001 failed has its own `Clips/C0001.MXF`; without the check its manifest + answered A001's unhashed entry, and the tree read VERIFIED with A001's clip + never copied. Dates are compared as instants, so the same moment written + with a different UTC offset (MHL 1.1 writes local time, ASC MHL writes UTC) + matches, and a date with an offset never matches one without. An entry that + records no size or no date, on either side, is not superseded. A file a + cancelled job never reached is recorded that way, so the cancelled job's + manifest keeps failing `verify` on the folder even after a rerun copied the + file; check the rerun's manifest on its own, by file. - A folder marker (a source folder that could not be listed, or a skipped link, recorded as one unhashed entry at the folder's path) is superseded by a newer manifest for the same destination root when that manifest lists at - least one hashed file under the folder and every entry it lists under the - folder matched. Any unhashed, missing, mismatched or unreadable entry under - the folder keeps the marker failing: a rerun lists the files inside a folder, - never the folder itself, so exact-path matching could never clear it. + least one hashed file under the folder, every entry it lists under the + folder matched, and both manifests name the same job. Any unhashed, missing, + mismatched or unreadable entry under the folder keeps the marker failing: a + rerun lists the files inside a folder, never the folder itself, so + exact-path matching could never clear it. A marker records no size or date, + so the job name (MHL 1.1 `creatorinfo/name`) is what ties the rerun to the + card. Names are compared ignoring case and the `-2`, `-3` suffix the queue + adds to a name already taken. ASC MHL records no job name, so a marker in an + ASC MHL history is never superseded. **Limit:** two different cards given + the same job name (a naming template without `{card}`, or `--name` reused) + still clear each other's folder markers; file entries are protected by + their size and date. - Only a hashed entry that matched can supersede. A later run that could not read the file lists it unhashed, and that entry fails on its own. - "Newer" is the manifest's own recorded time (MHL 1.1 `finishdate`, ASC MHL diff --git a/src/offloader/naming.py b/src/offloader/naming.py index 7d96bc9..60770b5 100644 --- a/src/offloader/naming.py +++ b/src/offloader/naming.py @@ -109,3 +109,22 @@ def build(template: str, source: Path, *, volume_label: str | None = None, if candidate.casefold() not in used: return candidate raise AssertionError("unreachable: more candidates than taken names") + + +#: The `-2`, `-3` suffix `build` appends to a name that is already taken. +_TAKEN_SUFFIX = re.compile(r"^(?P.+)-(?P[0-9]+)$") + + +def base_name(name: str) -> str: + """`name` without the suffix `build` appends when the name is taken. + + Two queue entries for the same card come out as `A001` and `A001-2`, and + they are still the same job as far as the card is concerned. Only a + number from 2 up is removed, since `build` never appends `-1` or `-0`. + A name that genuinely ends in `-2` loses it too; nothing in the name can + tell the two apart. + """ + match = _TAKEN_SUFFIX.match(name) + if match and int(match.group("number")) >= 2: + return match.group("base") + return name diff --git a/src/offloader/verify.py b/src/offloader/verify.py index dcb8142..5323ea0 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -25,6 +25,7 @@ from dataclasses import dataclass, field from enum import Enum from pathlib import Path +from typing import NamedTuple from xml.etree import ElementTree as ET from . import longpath @@ -34,6 +35,7 @@ from .engine import DEFAULT_EXCLUDES, is_excluded from .hashers import ALGORITHMS, get_algorithm, hash_file from .integrity import evict_from_cache +from .naming import base_name #: Where this tool files its own paperwork, as a pattern, for manifests that #: do not record the directory itself. A current ASC MHL history carries the @@ -57,6 +59,10 @@ class FileVerdict: actual: str | None = None expected_size: int | None = None actual_size: int | None = None + #: The source file's last-modification date as the manifest recorded it, + #: `None` when it recorded none or the value does not parse. With the + #: size, it is what says two manifests' entries came from the same file. + expected_modified: _dt.datetime | None = None detail: str = "" #: A later manifest for the same root hashed this file and it matched, #: which answers an entry this manifest could not check. Only ever set on @@ -154,6 +160,9 @@ class VerifyReport: #: When the manifest says it was written (MHL 1.1 `finishdate`, ASC MHL #: `creationdate`), or `None` when it does not say or cannot be read. recorded_at: _dt.datetime | None = None + #: The job name the manifest records (MHL 1.1 `creatorinfo/name`), or + #: `None`. ASC MHL has nowhere this tool records one. + job_name: str | None = None @property def checked(self) -> int: @@ -251,8 +260,31 @@ def find_manifests(root: Path) -> list[Path]: return sorted(standalone + newest, key=lambda p: p.stat().st_mtime) -def _entries(manifest: Path) -> Iterator[tuple[Path, str | None, str | None, int | None]]: - """(path, algorithm key, expected digest, expected size) per manifest entry. +class _Entry(NamedTuple): + """One manifest entry, as recorded.""" + + path: Path + algorithm: str | None + digest: str | None + size: int | None + #: The source file's last-modification date, `None` when not recorded. + modified: _dt.datetime | None + + +def _moment(text: str | None) -> _dt.datetime | None: + """An ISO 8601 date as a manifest writes it, or `None`. A value that will + not parse is absent, never guessed at.""" + text = (text or "").strip() + if not text: + return None + try: + return _dt.datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError: + return None + + +def _entries(manifest: Path) -> Iterator[_Entry]: + """Every entry in a manifest, in document order. Handles both classic MHL 1.1 (``) and ASC MHL v2 (``, namespaced, and living in an `ascmhl/` folder so its paths @@ -280,7 +312,8 @@ def _entries(manifest: Path) -> Iterator[tuple[Path, str | None, str | None, int if value: algorithm_key, digest = key, value.strip() break - yield (base / relative), algorithm_key, digest, size + yield _Entry(base / relative, algorithm_key, digest, size, + _moment(node.findtext("lastmodificationdate"))) def verify_manifest( @@ -307,16 +340,18 @@ def verify_manifest( manifest = Path(manifest) entries = list(_entries(manifest)) report = VerifyReport(manifest=manifest, - algorithm=next((e[1] for e in entries if e[1]), "unknown")) + algorithm=next((e.algorithm for e in entries if e.algorithm), + "unknown")) # ASC MHL keeps its manifests in `ascmhl/` at the root of the managed data, # so the folder above is what the recorded paths are relative to. managed_root = manifest.parent.parent parsed = _ascmhl_root(manifest) - listed = {p.resolve() for p, _, _, _ in entries} + listed = {e.path.resolve() for e in entries} report.root = (managed_root if parsed is not None else _described_root(manifest, listed)) report.recorded_at = _recorded_at(manifest) + report.job_name = _recorded_job_name(manifest) ascmhl_root = parsed if check_directories else None recorded: dict[str, tuple[str, str]] = {} if ascmhl_root is not None: @@ -357,21 +392,28 @@ def _evict(path: Path) -> None: "so this verification may have read from memory rather than " "the device") - for index, (path, algorithm_key, expected, expected_size) in enumerate(entries): + for index, entry in enumerate(entries): + path, algorithm_key, expected = entry.path, entry.algorithm, entry.digest + expected_size, expected_modified = entry.size, entry.modified if progress: progress(index, len(entries), path) if algorithm_key is None or not expected: # Including a hash the manifest itself disowned would contradict the # writer, which left it out of the directory hashes for the same - # reason. Deliberately not noted either way. - report.verdicts.append(FileVerdict(path, EntryResult.NO_CHECKSUM)) + # reason. Deliberately not noted either way. The recorded size and + # date are kept: `supersede` needs them to tell a rerun of the same + # card from a different card's file at the same path. + report.verdicts.append(FileVerdict( + path, EntryResult.NO_CHECKSUM, expected_size=expected_size, + expected_modified=expected_modified)) continue if not longpath.exists(path): note(path, None) report.verdicts.append( FileVerdict(path, EntryResult.MISSING, expected=expected, - expected_size=expected_size)) + expected_size=expected_size, + expected_modified=expected_modified)) continue try: @@ -383,6 +425,8 @@ def _evict(path: Path) -> None: note(path, None) report.verdicts.append( FileVerdict(path, EntryResult.UNREADABLE, expected=expected, + expected_size=expected_size, + expected_modified=expected_modified, detail=str(exc))) continue @@ -398,6 +442,7 @@ def _evict(path: Path) -> None: EntryResult.OK if matched else EntryResult.MISMATCH, expected=expected, actual=actual, expected_size=expected_size, actual_size=actual_size, + expected_modified=expected_modified, )) # Listing only (see the docstring): unlisted files are reported, never @@ -592,7 +637,7 @@ def _directory_verdicts(base: Path, recorded: dict[str, tuple[str, str]], return verdicts -def _ascmhl_entries(manifest: Path, root: ET.Element): +def _ascmhl_entries(manifest: Path, root: ET.Element) -> Iterator[_Entry]: """ASC MHL paths are relative to the root of the managed data, which is the parent of the `ascmhl` folder the manifest sits in.""" base = manifest.parent.parent @@ -619,7 +664,8 @@ def _ascmhl_entries(manifest: Path, root: ET.Element): algorithm_key = _TAG_TO_ALGORITHM[name] digest = child.text.strip() break - yield (base / path_element.text.strip()), algorithm_key, digest, size + yield _Entry(base / path_element.text.strip(), algorithm_key, digest, + size, _moment(path_element.get("lastmodificationdate"))) def _described_root(manifest: Path, listed: set[Path]) -> Path: @@ -676,13 +722,27 @@ def _recorded_at(manifest: Path) -> _dt.datetime | None: text = (info.findtext(f"{prefix}{name}") or "").strip() if not text: continue - try: - return _dt.datetime.fromisoformat(text.replace("Z", "+00:00")) - except ValueError: - return None + return _moment(text) return None +def _recorded_job_name(manifest: Path) -> str | None: + """The job name a classic manifest records in `creatorinfo/name`. + + ASC MHL's creator info has no field this tool fills with a job name (it + records the date, host and tool), so an ASC MHL manifest has none and + nothing that depends on job identity can match it. + """ + try: + root = ET.parse(manifest).getroot() + except (OSError, ET.ParseError): + return None + if root.tag == f"{{{ASCMHL_NAMESPACE}}}hashlist": + return None + name = (root.findtext("creatorinfo/name") or "").strip() + return name or None + + _NUMBERED = re.compile(r"^(?P.*)-(?P[0-9]+)$") @@ -753,6 +813,43 @@ def _entry_key(path: Path) -> str: return os.path.normcase(os.path.normpath(str(path))) +def _same_instant(a: _dt.datetime | None, b: _dt.datetime | None) -> bool: + """Both recorded, and the same moment. + + Two aware values are compared as instants, so the same moment written + with a different UTC offset (MHL 1.1 writes local time, ASC MHL writes + UTC) still matches. An aware value never matches a naive one: there is no + knowing which instant the naive one meant. + """ + if a is None or b is None: + return False + if (a.utcoffset() is None) != (b.utcoffset() is None): + return False + return a == b + + +def _same_source(older: FileVerdict, newer: FileVerdict) -> bool: + """Whether two entries for one path describe the same source file. + + Both sizes and modification dates come from the *source* file, so a + genuine rerun of the same card records the same pair, and a different + card's clip at the same relative path almost never does. Either value + missing on either side is not a match: the older entry keeps failing. + """ + return (older.expected_size is not None + and older.expected_size == newer.expected_size + and _same_instant(older.expected_modified, newer.expected_modified)) + + +def _same_job(a: VerifyReport, b: VerifyReport) -> bool: + """Both manifests name the same job, ignoring case and the `-2` suffix + the naming adds when a name is already taken. A manifest with no job name + (every ASC MHL one) matches nothing.""" + if not a.job_name or not b.job_name: + return False + return base_name(a.job_name).casefold() == base_name(b.job_name).casefold() + + def _folder_answered(folder_key: str, newer: VerifyReport) -> bool: """Whether `newer` lists files under a folder marker and all of them matched. @@ -775,17 +872,26 @@ def supersede(reports: list[VerifyReport]) -> None: One direction only. An entry is superseded when it has no hash in its own manifest, and a newer manifest for the same destination root lists the - same path with a hash that matched just now. A hashed entry is never - superseded, so a copy corrupted since an earlier run cannot hide behind a - later manifest; and an unhashed entry never answers anything. Directory - hash failures are untouched, so a manifest that has them still fails. + same path with a hash that matched just now, and both entries record the + same size and the same last-modification date. Those two come from the + source file, so they are what ties the entries to one card: without them + card A002's clip would answer card A001's failed clip at the same relative + path, and the tree would pass with A001's clip never copied. An entry + missing either value is not superseded. + + A hashed entry is never superseded, so a copy corrupted since an earlier + run cannot hide behind a later manifest; and an unhashed entry never + answers anything. Directory hash failures are untouched, so a manifest + that has them still fails. A source folder that could not be listed (or was a skipped link) is recorded as one unhashed entry at the folder's path, and a rerun lists the files inside it, never the folder. So such a marker is also superseded by a newer manifest for the same root that lists at least one hashed file under that folder, when every entry it lists under the folder matched and none of - them is unhashed. + them is unhashed. A marker records no size or date, so here the two + manifests must also name the same job (`_same_job`); an ASC MHL manifest + records no job name, so its markers are never superseded this way. """ for older in reports: pending = [v for v in older.verdicts @@ -797,13 +903,17 @@ def supersede(reports: list[VerifyReport]) -> None: continue if not _is_newer(newer, older): continue - matched = {_entry_key(v.path) for v in newer.verdicts + matched = {_entry_key(v.path): v for v in newer.verdicts if v.result is EntryResult.OK and v.expected} + same_job = _same_job(older, newer) for verdict in pending: if verdict.superseded_by is not None: continue key = _entry_key(verdict.path) - if key in matched or _folder_answered(key, newer): + answer = matched.get(key) + if answer is not None and _same_source(verdict, answer): + verdict.superseded_by = newer.manifest + elif same_job and _folder_answered(key, newer): verdict.superseded_by = newer.manifest diff --git a/tests/test_naming.py b/tests/test_naming.py index 80f9652..ef0c152 100644 --- a/tests/test_naming.py +++ b/tests/test_naming.py @@ -46,6 +46,18 @@ def test_collision_without_index_gets_a_suffix(): assert naming.build("{card}", card, when=WHEN, taken=["A001", "A001-2"]) == "A001-3" +def test_base_name_removes_exactly_the_suffix_build_appends(): + taken: list[str] = [] + for _ in range(3): + name = naming.build("{card}", Path("A001"), when=WHEN, taken=taken) + assert naming.base_name(name) == "A001" + taken.append(name) + assert naming.base_name("A001-1") == "A001-1" + assert naming.base_name("A001-0") == "A001-0" + assert naming.base_name("Roll_003") == "Roll_003" + assert naming.base_name("-2") == "-2" + + def test_collision_check_is_case_insensitive(): # Windows and exFAT both fold case; two jobs must not share a report folder. assert naming.build("{card}", Path("A001"), when=WHEN, taken=["a001"]) == "A001-2" diff --git a/tests/test_verdict_integrity.py b/tests/test_verdict_integrity.py index 18703f3..a6eb928 100644 --- a/tests/test_verdict_integrity.py +++ b/tests/test_verdict_integrity.py @@ -270,27 +270,38 @@ def test_a_manifest_for_a_different_destination_root_does_not_supersede( assert f"superseded by {rerun}" in out -def _classic_manifest(path: Path, finished: str, entries: dict[str, str | None]) -> Path: - """A hand-written MHL 1.1 file, so the timestamps are exactly as given.""" +SAME = "2026-10-11T12:00:00+00:00" +EARLIER = "2026-10-11T11:00:00+00:00" +#: The source clip's modification date, as the writer records it per entry. +SHOT = "2026-10-10T09:30:00+00:00" + + +def _classic_manifest(path: Path, finished: str, entries: dict[str, str | None], + *, size: int | None = 3000, modified: str | None = SHOT, + name: str | None = None) -> Path: + """A hand-written MHL 1.1 file, so the timestamps are exactly as given. + + Every entry records `size` and `modified` as the source file's, which is + what the real writer does; `None` leaves the element out.""" tag = get_algorithm("xxh3-64").mhl_tag path.parent.mkdir(parents=True, exist_ok=True) rows = "".join( f"{relative}" + + (f"{size}" if size is not None else "") + + (f"{modified}" + if modified is not None else "") + (f"<{tag}>{digest}" if digest else "") + "" for relative, digest in entries.items()) + job = f"{name}" if name is not None else "" path.write_text( '' - f"{finished}" + f"{job}{finished}" f"{finished}{rows}", encoding="utf-8") return path -SAME = "2026-10-11T12:00:00+00:00" -EARLIER = "2026-10-11T11:00:00+00:00" - - @pytest.mark.parametrize( "first_name, first_at, first_hashed, second_name, second_at, second_hashed, " "passes", @@ -836,3 +847,122 @@ def test_a_folder_marker_is_not_superseded_while_something_under_it_is_unresolve report = _report_for(verify.verify_tree(dest), first) assert not report.passed assert not report.superseded + + +# --------------- P1: a later job answers only its own card's unhashed entries + + +def test_a_different_cards_clip_at_the_same_path_does_not_supersede( + tmp_path, monkeypatch, capsys): + """Card A001's clip failed to read, so its manifest lists it unhashed. Card + A002, offloaded into the same root under the same job name, has its own + clip at the same relative path, of the same size. Its manifest used to + answer A001's entry, and the tree read VERIFIED with A001's clip never + copied.""" + first_card = _card(tmp_path, {"Clips/C0001.MXF": os.urandom(4000), + "Clips/C0002.MXF": os.urandom(3000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _fail_reads_of(patch, "C0001.MXF") + assert _offload("--source", str(first_card), "--dest", str(dest), + "--report", "mhl") == 1 + second_card = _card(tmp_path, {"Clips/C0001.MXF": os.urandom(4000)}, + name="A002") + clip = second_card / "Clips" / "C0001.MXF" + shot = (first_card / "Clips" / "C0001.MXF").stat().st_mtime + os.utime(clip, (shot + 3600, shot + 3600)) + assert _offload("--source", str(second_card), "--dest", str(dest), + "--report", "mhl", "--name", "A001") == 0 + capsys.readouterr() + + first = dest / "A001_Reports" / "JobReport.mhl" + report = _report_for(verify.verify_tree(dest), first) + assert [(v.path.name, v.result) for v in report.failures] == [ + ("C0001.MXF", verify.EntryResult.NO_CHECKSUM)] + assert not report.superseded + assert cli.main(["verify", str(dest), "--quiet"]) == 1 + assert "do not erase" in capsys.readouterr().out + + +# The older entry has no hash; the newer one hashed the file and it matched. +# Only the recorded size and source modification date differ between cases. +OFFSET = "2026-10-10T11:30:00+02:00" # SHOT, written with another offset +NAIVE = "2026-10-10T09:30:00" # SHOT's wall clock, no offset + + +@pytest.mark.parametrize( + "older_size, older_modified, newer_size, newer_modified, passes", + [ + (3000, SHOT, 3000, SHOT, True), + (3000, SHOT, 3000, OFFSET, True), + (3000, SHOT, 3001, SHOT, False), + (3000, SHOT, 3000, "2026-10-10T09:30:02+00:00", False), + (3000, SHOT, 3000, NAIVE, False), + (None, SHOT, 3000, SHOT, False), + (3000, None, 3000, SHOT, False), + (3000, SHOT, None, SHOT, False), + (3000, SHOT, 3000, None, False), + (3000, "not a date", 3000, "not a date", False), + ]) +def test_an_unhashed_entry_is_superseded_only_by_the_same_source_file( + tmp_path, older_size, older_modified, newer_size, newer_modified, passes): + dest = tmp_path / "dst" + clip = dest / "Clips" / "C0001.MXF" + clip.parent.mkdir(parents=True) + clip.write_bytes(os.urandom(3000)) + relative = "../Clips/C0001.MXF" + older = _classic_manifest(dest / "A001_Reports" / "JobReport.mhl", EARLIER, + {relative: None}, size=older_size, + modified=older_modified, name="A001") + _classic_manifest(dest / "A002_Reports" / "JobReport.mhl", SAME, + {relative: hash_file(clip, "xxh3-64")}, size=newer_size, + modified=newer_modified, name="A002") + + report = _report_for(verify.verify_tree(dest), older) + assert report.passed is passes + assert bool(report.superseded) is passes + + +@pytest.mark.parametrize( + "older_name, newer_name, passes", + [ + ("A001", "A001", True), + ("A001", "a001", True), + ("A001", "A001-2", True), # the suffix a taken name gets + ("A001-3", "A001", True), + ("A001", "A002", False), + ("A001", "A001-1", False), # never appended, so a different name + (None, "A001", False), + ("A001", None, False), + ("", "", False), + ]) +def test_a_folder_marker_is_superseded_only_by_the_same_job( + tmp_path, older_name, newer_name, passes): + """A folder marker records no size or date, so nothing in the entry ties + it to one card. Any later job listing matched files under the folder used + to clear it.""" + dest = tmp_path / "dst" + clip = dest / "Alias" / "C002.mov" + clip.parent.mkdir(parents=True) + clip.write_bytes(os.urandom(3000)) + older = _classic_manifest(dest / "A001_Reports" / "JobReport.mhl", EARLIER, + {"../Alias": None}, size=None, modified=None, + name=older_name) + _classic_manifest(dest / "B001_Reports" / "JobReport.mhl", SAME, + {"../Alias/C002.mov": hash_file(clip, "xxh3-64")}, + name=newer_name) + + report = _report_for(verify.verify_tree(dest), older) + assert report.passed is passes + assert [v.path.name for v in report.superseded] == (["Alias"] if passes else []) + + +def test_the_job_name_comes_from_a_classic_manifest_and_never_from_ascmhl( + tmp_path): + card = _card(tmp_path, {"C001.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + job = engine.run(card, _options(dest, algorithm="xxh64")) + classic = write_mhl(job, dest / "A001_Reports" / "JobReport.mhl") + history = ascmhl.write_manifest(job, dest) + assert verify.verify_manifest(classic).job_name == "A001" + assert verify.verify_manifest(history).job_name is None From 44f5a35f323f171cd7d4fc6026b1f24c0906047f Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:55:02 -0700 Subject: [PATCH 2/7] Verify an ASC MHL history as one view across its generations Only the newest generation was checked, and a generation lists only what its own run handled. A clip an earlier card's run recorded as failed passed once a second card wrote its own generation into the same root, and files a --skip-existing rerun skipped were never re-hashed. Each path is now judged by the latest generation that lists it, each file is hashed once, directory hashes stay the newest generation's, and an earlier generation that cannot be read is an error rather than skipped. --- CHANGELOG.md | 7 ++ docs/ascmhl.md | 11 ++- docs/data-safety.md | 47 ++++++++-- src/offloader/verify.py | 146 +++++++++++++++++++++++++------- tests/test_ascmhl.py | 18 ++-- tests/test_verdict_integrity.py | 143 +++++++++++++++++++++++++++++++ 6 files changed, 328 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48fe543..658b7f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,13 @@ project uses [semantic versioning][semver]. modification date. A folder marker, which records neither, is superseded only by a manifest naming the same job; ASC MHL records no job name, so its markers are never superseded. +- **An ASC MHL history hid what its earlier generations recorded.** `verify` + checked only the newest generation, so a clip an earlier card's run had + recorded as failed passed once a second card wrote a generation of its own, + and files a `--skip-existing` rerun skipped were never re-hashed. A history + is now verified as one view: each path is judged by the latest generation + that lists it, each file is hashed once, and an earlier generation that + cannot be read is an error. - **A timeline offload could call a partial cut complete.** With nothing to copy it printed "every reference is already here" and exited 0 while references were missing or ambiguous, and with gaps to copy it reported diff --git a/docs/ascmhl.md b/docs/ascmhl.md index 677b570..14a40a7 100644 --- a/docs/ascmhl.md +++ b/docs/ascmhl.md @@ -113,9 +113,14 @@ file checksum in its own right — `--hash c4`. offloader verify D:\video\A001 ``` -Only the newest generation of a history is checked. Every generation covers the -same files, so verifying all of them would hash the media once per generation -for no additional evidence. +A history is checked as one view. A generation lists only what its own run +handled (a second card into the same root, a `--skip-existing` rerun), so the +newest one alone can omit a failure or a file an earlier one recorded. Every +path any generation lists is judged by the latest generation that lists it: a +`failed` or unhashed latest record fails, a hashed one is checked, and each +file is hashed once however many generations list it. Directory hashes are the +newest generation's, over the files it lists. The rules and limits are in +[data-safety.md](data-safety.md#an-asc-mhl-history-is-verified-as-one). Digests, file and directory alike, are compared per algorithm rather than as plain strings. Hex formats compare case-insensitively, because a manifest is an diff --git a/docs/data-safety.md b/docs/data-safety.md index 7061771..1b19136 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -259,11 +259,46 @@ Supersession runs one way only: manifest: the folder above `_Reports*`, or the folder above `ascmhl/`. A manifest for a subfolder (another job whose destination was `dst/Clips`) does not answer one for `dst`, even about the same file. -- Directory hash failures are not touched, so the ASC MHL false alarm after a - `--skip-existing` rerun (below) still fails. +- Directory hash failures are not touched: a manifest that has them still + fails. Verifying a single `.mhl` file checks that file alone, so its unhashed entries -fail as before. +fail as before. An ASC MHL generation is the exception, since it is never the +whole record on its own: see "An ASC MHL history is verified as one" below. + +### An ASC MHL history is verified as one + +A generation lists only what its own run handled. Card A002 offloaded into the +root card A001 used writes a generation that lists A002's files alone, and a +`--skip-existing` rerun writes one that lists only what it copied. `verify` +used to check only the newest generation, so a clip A001's run had recorded +as failed or unhashed was never looked at and the tree read VERIFIED, and a +copy the rerun skipped was never re-hashed, however corrupt. + +`verify` now reads every generation of a history as one view. Each path that +any generation lists is judged by the latest generation that lists it: + +- A path whose latest record is labelled `failed`, or has no hash, fails as + `no hash`, unless a later generation lists it with a hash that matches. +- A path whose latest record has a hash is checked against it, missing, + mismatched and unreadable all failing, even when the newest generation does + not list it. The verdict names the generation the record came from. +- Each file is hashed once per history, however many generations list it. +- An earlier generation that cannot be read stops `verify` with an error + (exit `2`) rather than being skipped, since it may hold the only record of + a failure. + +This also happens when the newest generation is passed as a file: it stands +for the history up to itself. Directory and root hashes are still the newest +generation's own, recomputed over the files it lists, because that is all +they ever covered; a file recorded only in an earlier generation is checked +by its file hash and does not move a directory hash. + +Still not covered: the directory hashes an *earlier* generation recorded are +not rechecked, so a rename of a file only an earlier generation lists is +caught as a missing file, not as a structure change. A path is matched by its +text, so a generation that renamed a file is not linked to the old name. +Generations are ordered by their sequence number, not by date. ### A manifest is never overwritten @@ -346,9 +381,9 @@ known. safety one, and should not be used on a tree whose integrity is in question. Skipped files are left out of the rerun's manifest and the job reads `Incomplete` (CLI exit `4`). An earlier classic manifest that covered them is - kept and still checked; an ASC MHL history checks only its newest - generation, which omits them, so its directory hashes fail `verify` after such - a rerun (a false alarm, in the safe direction). + kept and still checked, and so is an earlier ASC MHL generation that covered + them: a history is verified as one view (see above), so the skipped files + are re-hashed against the generation that last recorded them. - **Concurrent instances.** One app instance serialises its queue. Two instances pointed at the same destination are not coordinated. - **Duplicate detection is a heuristic.** The fingerprint is the source's diff --git a/src/offloader/verify.py b/src/offloader/verify.py index 5323ea0..925cb61 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -32,6 +32,7 @@ from .ascmhl import ASCMHL_DIRNAME from .ascmhl import NAMESPACE as ASCMHL_NAMESPACE from .ascmhl import directory_hashes as ascmhl_directory_hashes +from .ascmhl import existing_manifests as ascmhl_existing_manifests from .engine import DEFAULT_EXCLUDES, is_excluded from .hashers import ALGORITHMS, get_algorithm, hash_file from .integrity import evict_from_cache @@ -68,24 +69,30 @@ class FileVerdict: #: which answers an entry this manifest could not check. Only ever set on #: a `NO_CHECKSUM` verdict; see `supersede`. superseded_by: Path | None = None + #: The earlier ASC MHL generation this entry's latest record is in, when + #: the generation being verified does not list the file. `None` for an + #: entry of the manifest itself. + recorded_in: Path | None = None @property def ok(self) -> bool: return self.result is EntryResult.OK def describe(self) -> str: + where = (f" (recorded in {self.recorded_in.name})" + if self.recorded_in is not None else "") if self.superseded_by is not None: - return (f"superseded {self.path} (no hash here; superseded by " + return (f"superseded {self.path}{where} (no hash here; superseded by " f"{self.superseded_by})") if self.result is EntryResult.OK: - return f"ok {self.path}" + return f"ok {self.path}{where}" if self.result is EntryResult.MISSING: - return f"MISSING {self.path}" + return f"MISSING {self.path}{where}" if self.result is EntryResult.UNREADABLE: - return f"UNREADABLE {self.path} ({self.detail})" + return f"UNREADABLE {self.path} ({self.detail}){where}" if self.result is EntryResult.NO_CHECKSUM: - return f"no hash {self.path}" - return (f"MISMATCH {self.path}\n" + return f"no hash {self.path}{where}" + return (f"MISMATCH {self.path}{where}\n" f" expected {self.expected}\n" f" actual {self.actual}") @@ -241,9 +248,11 @@ def summary(self) -> str: def find_manifests(root: Path) -> list[Path]: """Every manifest worth checking under `root`, newest last. - An ASC MHL history holds one manifest per generation, all covering the same - files. Only the newest is returned, so verifying a three-generation history - hashes the media once rather than three times. + An ASC MHL history holds one manifest per generation. Only the newest is + returned, and `verify_manifest` reads the earlier generations through it + as one merged view, so a three-generation history hashes each file once + rather than three times and still checks what only an older generation + records. """ root = Path(root) histories: dict[Path, list[Path]] = {} @@ -269,6 +278,9 @@ class _Entry(NamedTuple): size: int | None #: The source file's last-modification date, `None` when not recorded. modified: _dt.datetime | None + #: The earlier ASC MHL generation the entry came from, `None` when it is + #: the manifest's own. See `_earlier_generation_entries`. + recorded_in: Path | None = None def _moment(text: str | None) -> _dt.datetime | None: @@ -336,9 +348,20 @@ def verify_manifest( and not a failure, because a shared root legitimately holds other jobs. A rename still fails, as a missing listed file, with the new name shown alongside it as unlisted. + + An ASC MHL generation is read together with the generations before it in + its history, so passing the newest one verifies the whole history: each + path is judged by the latest generation that lists it, and each file is + hashed once. Directory hashes stay the verified generation's own. """ manifest = Path(manifest) entries = list(_entries(manifest)) + parsed = _ascmhl_root(manifest) + if parsed is not None: + # One view of the whole history, see `_earlier_generation_entries`. + # Appended after the manifest's own entries, so the algorithm below + # is still this generation's whenever it hashed anything. + entries += _earlier_generation_entries(manifest, entries) report = VerifyReport(manifest=manifest, algorithm=next((e.algorithm for e in entries if e.algorithm), "unknown")) @@ -346,7 +369,6 @@ def verify_manifest( # ASC MHL keeps its manifests in `ascmhl/` at the root of the managed data, # so the folder above is what the recorded paths are relative to. managed_root = manifest.parent.parent - parsed = _ascmhl_root(manifest) listed = {e.path.resolve() for e in entries} report.root = (managed_root if parsed is not None else _described_root(manifest, listed)) @@ -367,13 +389,18 @@ def verify_manifest( #: re-reported as a fresh failure for every directory above it. unsound: set[str] = set() - def note(path: Path, digest: str | None) -> str | None: + def note(entry: _Entry, digest: str | None) -> str | None: """Record what a file hashes to now, a `digest` of `None` meaning it - cannot stand as evidence at all. Returns the key it was filed under.""" - if ascmhl_root is None: + cannot stand as evidence at all. Returns the key it was filed under. + + Only the verified generation's own entries are noted. Its directory + hashes cover its own files and nothing an earlier generation listed, + so folding those in would fail every directory above them in a tree + that is exactly as recorded.""" + if ascmhl_root is None or entry.recorded_in is not None: return None try: - relative = path.relative_to(managed_root).as_posix() + relative = entry.path.relative_to(managed_root).as_posix() except ValueError: return None if digest is None: @@ -394,7 +421,9 @@ def _evict(path: Path) -> None: for index, entry in enumerate(entries): path, algorithm_key, expected = entry.path, entry.algorithm, entry.digest - expected_size, expected_modified = entry.size, entry.modified + as_recorded = dict(expected_size=entry.size, + expected_modified=entry.modified, + recorded_in=entry.recorded_in) if progress: progress(index, len(entries), path) @@ -404,16 +433,14 @@ def _evict(path: Path) -> None: # reason. Deliberately not noted either way. The recorded size and # date are kept: `supersede` needs them to tell a rerun of the same # card from a different card's file at the same path. - report.verdicts.append(FileVerdict( - path, EntryResult.NO_CHECKSUM, expected_size=expected_size, - expected_modified=expected_modified)) + report.verdicts.append(FileVerdict(path, EntryResult.NO_CHECKSUM, + **as_recorded)) continue if not longpath.exists(path): - note(path, None) + note(entry, None) report.verdicts.append( FileVerdict(path, EntryResult.MISSING, expected=expected, - expected_size=expected_size, - expected_modified=expected_modified)) + **as_recorded)) continue try: @@ -422,27 +449,24 @@ def _evict(path: Path) -> None: _evict(path) actual = hash_file(path, algorithm_key) except OSError as exc: - note(path, None) + note(entry, None) report.verdicts.append( FileVerdict(path, EntryResult.UNREADABLE, expected=expected, - expected_size=expected_size, - expected_modified=expected_modified, - detail=str(exc))) + detail=str(exc), **as_recorded)) continue # Case-folded for hex, exact for C4. An MHL is an interchange format, # and plenty of tools write their hex uppercase: comparing those with # `==` calls every byte-identical file a mismatch. matched = get_algorithm(algorithm_key).digests_match(actual, expected) - relative = note(path, actual) + relative = note(entry, actual) if not matched and relative is not None: unsound.add(relative) report.verdicts.append(FileVerdict( path, EntryResult.OK if matched else EntryResult.MISMATCH, - expected=expected, actual=actual, - expected_size=expected_size, actual_size=actual_size, - expected_modified=expected_modified, + expected=expected, actual=actual, actual_size=actual_size, + **as_recorded, )) # Listing only (see the docstring): unlisted files are reported, never @@ -668,6 +692,70 @@ def _ascmhl_entries(manifest: Path, root: ET.Element) -> Iterator[_Entry]: size, _moment(path_element.get("lastmodificationdate"))) +_GENERATION_NUMBER = re.compile(r"^([0-9]+)_") + + +def _earlier_generations(manifest: Path) -> list[Path]: + """The generations of `manifest`'s history up to it, oldest first, not + including `manifest` itself. + + A generation numbered the same as `manifest` is included: a history with + two of one number is damaged, and leaving either out would hide what it + records. A manifest without a number (not one this tool or the spec names) + is taken as the newest, which is how `find_manifests` chose it. + """ + if manifest.parent.name != ASCMHL_DIRNAME: + return [] + match = _GENERATION_NUMBER.match(manifest.name) + own = int(match.group(1)) if match else None + itself = os.path.normcase(str(manifest.resolve())) + earlier: list[Path] = [] + for candidate in ascmhl_existing_manifests(manifest.parent.parent): + if os.path.normcase(str(candidate.resolve())) == itself: + continue + number = int(_GENERATION_NUMBER.match(candidate.name).group(1)) + if own is None or number <= own: + earlier.append(candidate) + return earlier + + +def _earlier_generation_entries(manifest: Path, own: list[_Entry]) -> list[_Entry]: + """What earlier generations of an ASC MHL history record and `manifest` + does not, the latest record of each path. + + A generation lists only what its own run handled. Card A002 offloaded into + the root card A001 used writes a generation listing A002's files alone, + and a `--skip-existing` rerun one listing only what it copied. Checking + the newest generation by itself therefore passed a tree where A001's clip + had failed, and never rechecked the files the rerun skipped. So a history + is verified as one view: every path any generation lists, judged by the + latest generation that lists it. A path whose latest record is failed or + unhashed fails, exactly as an unhashed entry of the newest one does; one + whose latest record has a hash is checked against it. + + An earlier generation that cannot be read is an error, never skipped: it + may be the only record of a failure. + """ + seen = {_entry_key(entry.path) for entry in own} + found: list[_Entry] = [] + for generation in reversed(_earlier_generations(manifest)): + try: + root = ET.parse(generation).getroot() + except ET.ParseError as exc: + raise ValueError(f"earlier generation {generation.name} of this " + f"history cannot be read: {exc}") from exc + if root.tag != f"{{{ASCMHL_NAMESPACE}}}hashlist": + raise ValueError(f"earlier generation {generation.name} of this " + "history is not an ASC MHL manifest") + for entry in _ascmhl_entries(generation, root): + key = _entry_key(entry.path) + if key in seen: + continue + seen.add(key) + found.append(entry._replace(recorded_in=generation)) + return found + + def _described_root(manifest: Path, listed: set[Path]) -> Path: """The managed root a classic manifest belongs to. diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py index 9c4d158..639301d 100644 --- a/tests/test_ascmhl.py +++ b/tests/test_ascmhl.py @@ -316,9 +316,10 @@ def test_verify_catches_a_flipped_bit_in_an_ascmhl_tree(history): assert report.failures[0].result is verify.EntryResult.MISMATCH -def test_verify_uses_only_the_newest_generation(tmp_path: Path): - """Every generation covers the same files; hashing all of them would triple - the work for no extra evidence.""" +def test_a_history_is_found_once_by_its_newest_generation(tmp_path: Path): + """The newest generation stands for the history: `verify_manifest` reads + the earlier ones through it, so the media is hashed once, not once per + generation.""" payloads = {"a.mov": b"aaaa"} for _ in range(3): job, destination = _offload(tmp_path, payloads) @@ -513,7 +514,11 @@ def _offload_card(tmp_path: Path, card_name: str, destination: Path, def test_a_second_card_in_the_same_root_leaves_both_verified(tmp_path: Path): """REGRESSION. Only the newest generation is found, and the verifier used to hash card A001 and its reports as unexpected files and fold them into - the root hash, failing a healthy pair of copies.""" + the root hash, failing a healthy pair of copies. + + Card A001's clip is recorded only in the first generation. It is checked + against that record, as part of the history, and kept out of the second + generation's directory hashes, which never covered it.""" destination = tmp_path / "shoot" _offload_card(tmp_path, "A001", destination) _offload_card(tmp_path, "A002", destination) @@ -523,8 +528,9 @@ def test_a_second_card_in_the_same_root_leaves_both_verified(tmp_path: Path): report = verify.verify_manifest(manifests[0]) assert report.passed, report.summary() assert all(v.ok for v in report.directories) - # The other card is mentioned, not hashed and not a failure. - assert any("A001_C001.mov" in p.name for p in report.unlisted) + assert sorted(v.path.name for v in report.verdicts) == [ + "A001_C001.mov", "A002_C001.mov"] + assert not any("A001_C001.mov" in p.name for p in report.unlisted) assert cli.main(["verify", str(destination), "--quiet"]) == 0 diff --git a/tests/test_verdict_integrity.py b/tests/test_verdict_integrity.py index a6eb928..030c7ba 100644 --- a/tests/test_verdict_integrity.py +++ b/tests/test_verdict_integrity.py @@ -966,3 +966,146 @@ def test_the_job_name_comes_from_a_classic_manifest_and_never_from_ascmhl( history = ascmhl.write_manifest(job, dest) assert verify.verify_manifest(classic).job_name == "A001" assert verify.verify_manifest(history).job_name is None + + +# ------------------- P1: an ASC MHL history is verified as one merged view + + +def _only_history(dest: Path) -> Path: + (manifest,) = verify.find_manifests(dest) + return manifest + + +def _generation(dest: Path, number: int) -> str: + return next(p.name for p in (dest / "ascmhl").glob(f"{number:04d}_*.mhl")) + + +def test_a_failure_recorded_in_an_earlier_generation_still_fails( + tmp_path, monkeypatch, capsys): + """Card A001's clip failed and the first generation lists it unhashed. + Card A002 into the same root writes a second generation listing only its + own files. Only that one was checked, and the tree read VERIFIED.""" + first_card = _card(tmp_path, {"Clips/C0001.MXF": os.urandom(4000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _fail_reads_of(patch, "C0001.MXF") + assert _offload("--source", str(first_card), "--dest", str(dest), + "--report", "ascmhl") == 1 + second_card = _card(tmp_path, {"Clips/B0001.MXF": os.urandom(4000)}, + name="A002") + assert _offload("--source", str(second_card), "--dest", str(dest), + "--report", "ascmhl") == 0 + capsys.readouterr() + + manifest = _only_history(dest) + assert manifest.name == _generation(dest, 2) + report = verify.verify_manifest(manifest) + assert [(v.path.name, v.result, v.recorded_in.name) for v in report.failures] == [ + ("C0001.MXF", verify.EntryResult.NO_CHECKSUM, _generation(dest, 1))] + # The second generation's directory hashes never covered A001's clip. + assert report.directories and all(d.ok for d in report.directories) + + assert cli.main(["verify", str(dest), "--quiet"]) == 1 + out = capsys.readouterr().out + assert f"no hash {dest / 'Clips' / 'C0001.MXF'}" in out + assert f"(recorded in {_generation(dest, 1)})" in out + + +def test_a_hash_an_earlier_generation_marked_failed_still_fails(tmp_path): + card = _card(tmp_path, {"C001.mov": os.urandom(2000), + "C002.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + job = engine.run(card, _options(dest, algorithm="xxh64")) + first = ascmhl.write_manifest(job, dest) + namespace = f"{{{ascmhl.NAMESPACE}}}" + tree = ET.parse(first) + for node in tree.getroot().iter(f"{namespace}hash"): + if node.find(f"{namespace}path").text == "C002.mov": + node.find(f"{namespace}xxh64").set("action", "failed") + tree.write(first, encoding="utf-8", xml_declaration=True) + other = _card(tmp_path, {"B001.mov": os.urandom(2000)}, name="A002") + ascmhl.write_manifest(engine.run(other, _options(dest, algorithm="xxh64")), dest) + + report = verify.verify_manifest(_only_history(dest)) + assert [(v.path.name, v.result) for v in report.failures] == [ + ("C002.mov", verify.EntryResult.NO_CHECKSUM)] + + +def test_files_recorded_only_in_an_earlier_generation_are_rechecked( + tmp_path, capsys): + """A `--skip-existing` rerun's generation lists only what it copied, so + a corrupt or deleted copy it skipped was never looked at again.""" + card = _card(tmp_path, {"C001.mov": os.urandom(5000), + "C002.mov": os.urandom(5000)}) + dest = tmp_path / "dst" + assert _offload("--source", str(card), "--dest", str(dest), + "--report", "ascmhl") == 0 + (card / "C003.mov").write_bytes(os.urandom(4000)) + assert _offload("--source", str(card), "--dest", str(dest), + "--report", "ascmhl", "--skip-existing") == 4 + _flip_one_byte(dest / "C001.mov") # same size, wrong bytes + (dest / "C002.mov").unlink() + capsys.readouterr() + + report = verify.verify_manifest(_only_history(dest)) + earliest = _generation(dest, 1) + assert sorted((v.path.name, v.result, v.recorded_in and v.recorded_in.name) + for v in report.verdicts) == [ + ("C001.mov", verify.EntryResult.MISMATCH, earliest), + ("C002.mov", verify.EntryResult.MISSING, earliest), + ("C003.mov", verify.EntryResult.OK, None)] + assert report.directories and all(d.ok for d in report.directories) + assert not report.unlisted + assert cli.main(["verify", str(dest), "--quiet"]) == 1 + + +def test_a_history_hashes_each_file_once(tmp_path, monkeypatch): + card = _card(tmp_path, {"C001.mov": os.urandom(3000), + "C002.mov": os.urandom(3000)}) + other = _card(tmp_path, {"B001.mov": os.urandom(3000)}, name="A002") + dest = tmp_path / "dst" + for source in (card, card, other): + ascmhl.write_manifest(engine.run(source, _options(dest, algorithm="xxh64")), + dest) + assert len(list((dest / "ascmhl").glob("*.mhl"))) == 3 + + hashed: list[str] = [] + real = verify.hash_file + monkeypatch.setattr(verify, "hash_file", + lambda path, *a, **k: (hashed.append(Path(path).name), + real(path, *a, **k))[1]) + report = verify.verify_manifest(_only_history(dest)) + assert report.passed, report.summary() + assert sorted(hashed) == ["B001.mov", "C001.mov", "C002.mov"] + + +def test_a_later_generation_answers_an_earlier_failure(tmp_path, monkeypatch): + card = _card(tmp_path, {"C001.mov": os.urandom(3000), + "C002.mov": os.urandom(3000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _fail_reads_of(patch, "C002.mov") + assert _offload("--source", str(card), "--dest", str(dest), + "--report", "ascmhl") == 1 + assert _offload("--source", str(card), "--dest", str(dest), + "--report", "ascmhl") == 0 + + report = verify.verify_manifest(_only_history(dest)) + assert report.passed, report.summary() + assert all(v.recorded_in is None for v in report.verdicts) + + +def test_an_unreadable_earlier_generation_is_an_error_not_a_pass( + tmp_path, capsys): + card = _card(tmp_path, {"C001.mov": os.urandom(3000)}) + other = _card(tmp_path, {"B001.mov": os.urandom(3000)}, name="A002") + dest = tmp_path / "dst" + for source in (card, other): + ascmhl.write_manifest(engine.run(source, _options(dest, algorithm="xxh64")), + dest) + (dest / "ascmhl" / _generation(dest, 1)).write_text(" Date: Sat, 28 Nov 2026 21:57:43 -0700 Subject: [PATCH 3/7] Fail a folder verify's entries that point outside the folder Manifest paths were never confined, so a manifest under D2 listing D1's files by absolute path or .. made verify D2 hash D1 and pass. Given a folder, an entry resolving outside it now fails as OUTSIDE and is not read; a manifest named directly stays unconfined. An ASC MHL path must always stay inside its history's root, the folder holding ascmhl/. --- CHANGELOG.md | 5 ++ README.md | 2 + docs/data-safety.md | 24 +++++++++ src/offloader/cli.py | 7 ++- src/offloader/verify.py | 70 ++++++++++++++++++++++++-- tests/test_verdict_integrity.py | 89 +++++++++++++++++++++++++++++++++ 6 files changed, 191 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 658b7f5..a3a078f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,11 @@ project uses [semantic versioning][semver]. is now verified as one view: each path is judged by the latest generation that lists it, each file is hashed once, and an earlier generation that cannot be read is an error. +- **`verify` on a folder could pass on files outside it.** A manifest under + `D2` listing `D1`'s files by absolute path or `..` made `verify D2` hash + `D1` and pass. Given a folder, an entry resolving outside it now fails as + `OUTSIDE` and is not read; a manifest named directly is unconfined. An ASC + MHL path must always stay inside its history's root. - **A timeline offload could call a partial cut complete.** With nothing to copy it printed "every reference is already here" and exited 0 while references were missing or ambiguous, and with gaps to copy it reported diff --git a/README.md b/README.md index 1b2cab9..e253812 100644 --- a/README.md +++ b/README.md @@ -255,6 +255,8 @@ not hash is reported as superseded, and stops failing, once a newer manifest for the same destination lists that file with a hash that still matches and the same source size and modification date; a hashed entry is never superseded. See [`docs/data-safety.md`](docs/data-safety.md#a-manifest-lists-what-did-not-arrive). +Given a folder, an entry pointing outside it fails as `OUTSIDE` and is not read; +name the manifest file to verify it wherever its paths point. `--allow-cache` skips the page-cache eviction: faster, and may verify memory rather than the device. diff --git a/docs/data-safety.md b/docs/data-safety.md index 1b19136..5a88203 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -189,6 +189,30 @@ even when it sat inside destination 2, which then skipped its own: `verify` on destination 2 re-hashed destination 1's copy and passed while its own copy was corrupt. +### A folder is verified only by what is inside it + +`verify D2` checks every manifest found under `D2`, and a manifest's paths +were never confined: one listing `D1`'s files, by absolute path or a run of +`..`, made `verify D2` hash `D1` and say VERIFIED about a folder it never read. +When `verify` is given a folder, an entry that resolves outside that folder now +fails as `OUTSIDE` and is not read, with the advice to verify the folder the +manifest describes or to name the manifest file itself. The check is on the +path as it would be opened (`..` resolved the way the long-path helpers +resolve it), not through links, so a destination reached through a junction +or a mapped drive still counts as itself. + +Naming a classic manifest file directly is unconfined: its entries go wherever +its paths say, which is what an old manifest written to a separate report +folder, or one carrying absolute paths, needs. An ASC MHL path is always +confined to its history's root, the folder holding `ascmhl/`, file or folder, +because the format defines its paths as relative to it. + +Nothing this tool writes is affected: a classic manifest always sits inside its +own destination and lists `../` paths that stay there, and a `--report-dir` +outside every destination receives no manifest. Pointing `verify` at a +`_Reports` folder itself, rather than the destination holding it, now +fails as `OUTSIDE` instead of checking the media one level up. + ### A manifest lists what did not arrive A manifest used to list only the files that copied. A clip that failed was diff --git a/src/offloader/cli.py b/src/offloader/cli.py index d754dd0..cc12f2d 100644 --- a/src/offloader/cli.py +++ b/src/offloader/cli.py @@ -617,6 +617,10 @@ def cmd_verify(args: argparse.Namespace) -> int: from . import verify as verify_mod target = Path(args.path) + # A folder is a claim about that folder, so every entry must stay inside + # it: a manifest found there that lists files elsewhere cannot pass it. + # A manifest named directly is taken at its word. + confine_to = None if target.is_file() else target if target.is_file(): manifests = [target] else: @@ -637,7 +641,8 @@ def progress(index: int, total: int, path: Path) -> None: for manifest in manifests: try: reports.append(verify_mod.verify_manifest( - manifest, progress=progress, bypass_cache=not args.allow_cache)) + manifest, progress=progress, bypass_cache=not args.allow_cache, + confine_to=confine_to)) except Exception as exc: print(f"error: could not read {manifest}: {exc}", file=sys.stderr) worst = max(worst, 2) diff --git a/src/offloader/verify.py b/src/offloader/verify.py index 925cb61..e5673ce 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -50,6 +50,7 @@ class EntryResult(str, Enum): MISSING = "missing" # the file is gone UNREADABLE = "unreadable" # present but cannot be read NO_CHECKSUM = "no-checksum" # the manifest recorded none + OUTSIDE = "outside" # the entry points outside what is verified @dataclass @@ -92,6 +93,8 @@ def describe(self) -> str: return f"UNREADABLE {self.path} ({self.detail}){where}" if self.result is EntryResult.NO_CHECKSUM: return f"no hash {self.path}{where}" + if self.result is EntryResult.OUTSIDE: + return f"OUTSIDE {self.path}{where}\n {self.detail}" return (f"MISMATCH {self.path}{where}\n" f" expected {self.expected}\n" f" actual {self.actual}") @@ -328,6 +331,30 @@ def _entries(manifest: Path) -> Iterator[_Entry]: _moment(node.findtext("lastmodificationdate"))) +def _as_opened(path: Path) -> str: + """The absolute path a read of `path` opens, normalised the way `longpath` + normalises it: lexically when a name in it is one Win32 would rewrite, + through `abspath` otherwise. So the containment check below judges the + file that would actually be read, `..` included.""" + text = str(path) + if longpath.needs_literal(text): + return os.path.normpath(os.path.join(os.getcwd(), text)) + return os.path.abspath(text) + + +def _inside(path: Path, folder: Path) -> bool: + """Whether `path` is `folder` or below it, by path rather than by link. + + Lexical on purpose: a destination reached through a junction or a mapped + drive is still the folder the operator named, and following links would + call it outside. What this guards against is a manifest's own path text, + an absolute path or a run of `..`, pointing at another folder or drive. + """ + target = os.path.normcase(_as_opened(path)) + base = os.path.normcase(_as_opened(folder)).rstrip(os.sep) + return target == base or target.startswith(base + os.sep) + + def verify_manifest( manifest: Path, *, @@ -335,6 +362,7 @@ def verify_manifest( bypass_cache: bool = True, find_unlisted: bool = True, check_directories: bool = True, + confine_to: Path | None = None, ) -> VerifyReport: """Re-hash everything an MHL describes and compare. @@ -353,6 +381,14 @@ def verify_manifest( its history, so passing the newest one verifies the whole history: each path is judged by the latest generation that lists it, and each file is hashed once. Directory hashes stay the verified generation's own. + + `confine_to` is the folder a tree verify was asked about. A classic entry + that resolves outside it fails as `OUTSIDE` and is never read: a manifest + found under one destination must not pass that destination on the + strength of files somewhere else. Verifying a manifest file directly + passes no folder, and its entries go wherever its paths say. An ASC MHL + entry is always confined to the history's own root, the folder holding + `ascmhl/`, because the format defines its paths as relative to it. """ manifest = Path(manifest) entries = list(_entries(manifest)) @@ -362,14 +398,30 @@ def verify_manifest( # Appended after the manifest's own entries, so the algorithm below # is still this generation's whenever it hashed anything. entries += _earlier_generation_entries(manifest, entries) - report = VerifyReport(manifest=manifest, - algorithm=next((e.algorithm for e in entries if e.algorithm), - "unknown")) # ASC MHL keeps its manifests in `ascmhl/` at the root of the managed data, # so the folder above is what the recorded paths are relative to. managed_root = manifest.parent.parent - listed = {e.path.resolve() for e in entries} + #: Entry index -> why it is not read at all. + outside: dict[int, str] = {} + for index, entry in enumerate(entries): + if parsed is not None and not _inside(entry.path, managed_root): + outside[index] = (f"outside the history's root {managed_root}: an " + "ASC MHL path must stay inside the folder holding " + f"{ASCMHL_DIRNAME}/") + elif confine_to is not None and not _inside(entry.path, confine_to): + outside[index] = (f"outside {confine_to}: this manifest does not " + "describe the folder being verified; verify the " + "folder it describes, or pass the manifest file " + "itself") + report = VerifyReport(manifest=manifest, + algorithm=next((e.algorithm for i, e in enumerate(entries) + if e.algorithm and i not in outside), + "unknown")) + + # Only what will be read describes the root: an entry pointing at another + # drive would otherwise widen the unlisted scan to everything between. + listed = {e.path.resolve() for i, e in enumerate(entries) if i not in outside} report.root = (managed_root if parsed is not None else _described_root(manifest, listed)) report.recorded_at = _recorded_at(manifest) @@ -427,6 +479,12 @@ def _evict(path: Path) -> None: if progress: progress(index, len(entries), path) + if index in outside: + report.verdicts.append(FileVerdict(path, EntryResult.OUTSIDE, + expected=expected, + detail=outside[index], + **as_recorded)) + continue if algorithm_key is None or not expected: # Including a hash the manifest itself disowned would contradict the # writer, which left it out of the directory hashes for the same @@ -1006,7 +1064,9 @@ def supersede(reports: list[VerifyReport]) -> None: def verify_tree(root: Path, **options) -> list[VerifyReport]: - """Verify every MHL found under `root`, with `supersede` applied.""" + """Verify every MHL found under `root`, with `supersede` applied. Every + entry is confined to `root`; see `verify_manifest`.""" + options.setdefault("confine_to", Path(root)) reports = [verify_manifest(manifest, **options) for manifest in find_manifests(root)] supersede(reports) diff --git a/tests/test_verdict_integrity.py b/tests/test_verdict_integrity.py index 030c7ba..7f3ee3c 100644 --- a/tests/test_verdict_integrity.py +++ b/tests/test_verdict_integrity.py @@ -1109,3 +1109,92 @@ def test_an_unreadable_earlier_generation_is_an_error_not_a_pass( verify.verify_manifest(_only_history(dest)) assert cli.main(["verify", str(dest), "--quiet"]) == 2 assert "earlier generation" in capsys.readouterr().err + + +# ---------------- P1: a manifest under one folder cannot pass files elsewhere + + +def _count_hashes(monkeypatch) -> list[str]: + hashed: list[str] = [] + real = verify.hash_file + monkeypatch.setattr(verify, "hash_file", + lambda path, *a, **k: (hashed.append(Path(path).name), + real(path, *a, **k))[1]) + return hashed + + +def test_a_manifest_found_under_one_folder_cannot_pass_files_outside_it( + tmp_path, monkeypatch, capsys): + """A manifest under D2 listing D1's files, by absolute path or by `..`, + made `verify D2` hash D1 and say VERIFIED about a folder it never read.""" + d1, d2 = tmp_path / "D1", tmp_path / "D2" + d1.mkdir() + for name in ("C001.mov", "C002.mov"): + (d1 / name).write_bytes(os.urandom(3000)) + manifest = _classic_manifest( + d2 / "A001_Reports" / "JobReport.mhl", SAME, + {str(d1 / "C001.mov"): hash_file(d1 / "C001.mov", "xxh3-64"), + "../../D1/C002.mov": hash_file(d1 / "C002.mov", "xxh3-64")}) + + hashed = _count_hashes(monkeypatch) + (report,) = verify.verify_tree(d2) + assert [(v.path.name, v.result) for v in report.failures] == [ + ("C001.mov", verify.EntryResult.OUTSIDE), + ("C002.mov", verify.EntryResult.OUTSIDE)] + assert hashed == [] + assert not report.unlisted + + assert cli.main(["verify", str(d2), "--quiet"]) == 1 + out = capsys.readouterr().out + assert "OUTSIDE" in out and "does not describe the folder being verified" in out + + # Named directly, the manifest is taken at its word. + assert verify.verify_manifest(manifest).passed + assert cli.main(["verify", str(manifest), "--quiet"]) == 0 + + +def test_a_tree_verify_still_follows_the_reports_folders_own_dot_dot(tmp_path): + """The legitimate `..`: a classic manifest lives in `_Reports/` and + its media one level up, all inside the folder being verified. Pointing + verify at the reports folder itself is now refused rather than passed.""" + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + job = engine.run(card, _options(dest)) + write_mhl(job, dest / "A001_Reports" / "JobReport.mhl") + + (report,) = verify.verify_tree(dest) + assert report.passed, report.summary() + (inner,) = verify.verify_tree(dest / "A001_Reports") + assert [v.result for v in inner.failures] == [verify.EntryResult.OUTSIDE] + + +@pytest.mark.parametrize("escape", ["relative", "absolute"]) +def test_an_ascmhl_path_must_stay_inside_its_history_root( + tmp_path, monkeypatch, capsys, escape): + """ASC MHL defines its paths relative to the folder holding `ascmhl/`. A + path escaping it was hashed wherever it pointed, so a history without + directory hashes passed on another folder's bytes. Refused even when the + manifest is named directly.""" + card = _card(tmp_path, {"C001.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + job = engine.run(card, _options(dest, algorithm="xxh64")) + manifest = ascmhl.write_manifest(job, dest, directory_hashes=False) + elsewhere = tmp_path / "elsewhere" / "C001.mov" + elsewhere.parent.mkdir() + elsewhere.write_bytes((dest / "C001.mov").read_bytes()) + pointed = "../elsewhere/C001.mov" if escape == "relative" else str(elsewhere) + namespace = f"{{{ascmhl.NAMESPACE}}}" + tree = ET.parse(manifest) + for node in tree.getroot().iter(f"{namespace}path"): + if node.text == "C001.mov": + node.text = pointed + tree.write(manifest, encoding="utf-8", xml_declaration=True) + + hashed = _count_hashes(monkeypatch) + report = verify.verify_manifest(manifest) + assert [v.result for v in report.failures] == [verify.EntryResult.OUTSIDE] + assert "history's root" in report.failures[0].detail + assert hashed == [] + assert cli.main(["verify", str(manifest), "--quiet"]) == 1 + assert cli.main(["verify", str(dest), "--quiet"]) == 1 + assert "OUTSIDE" in capsys.readouterr().out From 381f5d685a7ec6ca67fd4d4e7c811058f6cddb14 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:17:31 -0700 Subject: [PATCH 4/7] Let a rerun answer the files a cancelled job never reached A never-reached file is listed with no hash, size or date, so requiring a matching size and date left a cancelled job's manifest failing verify on the folder for good, after the rerun had copied everything. An entry that records neither is now answered by a matching file in a newer manifest that names the same job, the rule a folder marker already gets. The rerun suffix is only recognised without a leading zero, which is how the queue writes it, so two jobs from an {index} template (Shoot-003, Shoot-004) are not taken for one job. --- CHANGELOG.md | 6 ++-- docs/data-safety.md | 29 ++++++++++------- src/offloader/naming.py | 10 +++--- src/offloader/verify.py | 20 +++++++++++- tests/test_naming.py | 4 +++ tests/test_verdict_integrity.py | 58 +++++++++++++++++++++++++++++++++ 6 files changed, 108 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a3a078f..27d692a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,9 +32,9 @@ project uses [semantic versioning][semver]. A002's clip at the same relative path superseded A001's unhashed entry and `verify` passed with A001's clip never copied. An unhashed entry is now superseded only when both entries record the same source size and - modification date. A folder marker, which records neither, is superseded - only by a manifest naming the same job; ASC MHL records no job name, so - its markers are never superseded. + modification date. A folder marker, or a file a cancelled job never + reached, records neither and is superseded only by a manifest naming the + same job; ASC MHL records no job name, so its markers are never superseded. - **An ASC MHL history hid what its earlier generations recorded.** `verify` checked only the newest generation, so a clip an earlier card's run had recorded as failed passed once a second card wrote a generation of its own, diff --git a/docs/data-safety.md b/docs/data-safety.md index 5a88203..08316fa 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -236,8 +236,9 @@ An unhashed entry has nothing to pass against, so on its own it keeps failing. After a failed run has been resumed, its manifest still lists the files it could not read. When `verify` checks a folder, such an entry is **superseded** if a newer manifest for the same destination root lists the same path with a hash, -that file matches it now, and both entries record the same size and the same -last-modification date. The entry is printed as `superseded by `, not +that file matches it now, and the two entries can be tied to the same source +(the same recorded size and last-modification date, or, for an entry that +records neither, the same job name). The entry is printed as `superseded by `, not dropped, and the older manifest passes only if nothing else in it failed. Supersession runs one way only: @@ -253,10 +254,13 @@ Supersession runs one way only: never copied. Dates are compared as instants, so the same moment written with a different UTC offset (MHL 1.1 writes local time, ASC MHL writes UTC) matches, and a date with an offset never matches one without. An entry that - records no size or no date, on either side, is not superseded. A file a - cancelled job never reached is recorded that way, so the cancelled job's - manifest keeps failing `verify` on the folder even after a rerun copied the - file; check the rerun's manifest on its own, by file. + records one of the two and not the other is not superseded. +- A file a cancelled job never reached is recorded with neither a size nor a + date: the job knew its path and nothing else. Cancel and rerun is the + ordinary way to recover, so such an entry is superseded when the newer + manifest lists the same path with a hash that matches and both manifests + name the same job, the rule a folder marker gets below, with the same + limit. - A folder marker (a source folder that could not be listed, or a skipped link, recorded as one unhashed entry at the folder's path) is superseded by a newer manifest for the same destination root when that manifest lists at @@ -267,11 +271,14 @@ Supersession runs one way only: exact-path matching could never clear it. A marker records no size or date, so the job name (MHL 1.1 `creatorinfo/name`) is what ties the rerun to the card. Names are compared ignoring case and the `-2`, `-3` suffix the queue - adds to a name already taken. ASC MHL records no job name, so a marker in an - ASC MHL history is never superseded. **Limit:** two different cards given - the same job name (a naming template without `{card}`, or `--name` reused) - still clear each other's folder markers; file entries are protected by - their size and date. + adds to a name already taken (written without a leading zero, so the + `{index}` in `Shoot-003` is never mistaken for it). ASC MHL records no job + name, so a marker in an ASC MHL history is never superseded and keeps + failing `verify` even after a rerun copied the folder. **Limit:** two + different cards given the same job name (a naming template without + `{card}`, or `--name` reused) still clear each other's folder markers and + never-reached entries; entries that record a size and date are protected + by them. - Only a hashed entry that matched can supersede. A later run that could not read the file lists it unhashed, and that entry fails on its own. - "Newer" is the manifest's own recorded time (MHL 1.1 `finishdate`, ASC MHL diff --git a/src/offloader/naming.py b/src/offloader/naming.py index 60770b5..85bdcba 100644 --- a/src/offloader/naming.py +++ b/src/offloader/naming.py @@ -112,7 +112,7 @@ def build(template: str, source: Path, *, volume_label: str | None = None, #: The `-2`, `-3` suffix `build` appends to a name that is already taken. -_TAKEN_SUFFIX = re.compile(r"^(?P.+)-(?P[0-9]+)$") +_TAKEN_SUFFIX = re.compile(r"^(?P.+)-(?P[1-9][0-9]*)$") def base_name(name: str) -> str: @@ -120,9 +120,11 @@ def base_name(name: str) -> str: Two queue entries for the same card come out as `A001` and `A001-2`, and they are still the same job as far as the card is concerned. Only a - number from 2 up is removed, since `build` never appends `-1` or `-0`. - A name that genuinely ends in `-2` loses it too; nothing in the name can - tell the two apart. + number from 2 up is removed, since `build` never appends `-1` or `-0`, + and only one written without a leading zero, which is how `build` writes + it: `{index}` renders as `003`, so `Shoot-003` and `Shoot-004` stay two + different jobs. A name that genuinely ends in `-2` loses it too; nothing + in the name can tell the two apart. """ match = _TAKEN_SUFFIX.match(name) if match and int(match.group("number")) >= 2: diff --git a/src/offloader/verify.py b/src/offloader/verify.py index e5673ce..d591704 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -987,6 +987,16 @@ def _same_source(older: FileVerdict, newer: FileVerdict) -> bool: and _same_instant(older.expected_modified, newer.expected_modified)) +def _records_nothing(entry: FileVerdict) -> bool: + """An entry with neither a size nor a modification date. + + That is how a file a cancelled job never reached is written: the job knew + its path and nothing else. There is no source fact to compare, so only + the job name can tie a rerun's entry to it; see `supersede`. + """ + return entry.expected_size is None and entry.expected_modified is None + + def _same_job(a: VerifyReport, b: VerifyReport) -> bool: """Both manifests name the same job, ignoring case and the `-2` suffix the naming adds when a name is already taken. A manifest with no job name @@ -1023,7 +1033,12 @@ def supersede(reports: list[VerifyReport]) -> None: source file, so they are what ties the entries to one card: without them card A002's clip would answer card A001's failed clip at the same relative path, and the tree would pass with A001's clip never copied. An entry - missing either value is not superseded. + that records one of the two and not the other is not superseded. + + An entry that records neither is a file a cancelled job never reached. + Cancel and rerun is the ordinary way to recover, so that entry is answered + by a matching file in a newer manifest that names the same job + (`_same_job`), the same rule a folder marker gets below. A hashed entry is never superseded, so a copy corrupted since an earlier run cannot hide behind a later manifest; and an unhashed entry never @@ -1059,6 +1074,9 @@ def supersede(reports: list[VerifyReport]) -> None: answer = matched.get(key) if answer is not None and _same_source(verdict, answer): verdict.superseded_by = newer.manifest + elif (answer is not None and same_job + and _records_nothing(verdict)): + verdict.superseded_by = newer.manifest elif same_job and _folder_answered(key, newer): verdict.superseded_by = newer.manifest diff --git a/tests/test_naming.py b/tests/test_naming.py index ef0c152..9a38921 100644 --- a/tests/test_naming.py +++ b/tests/test_naming.py @@ -55,6 +55,10 @@ def test_base_name_removes_exactly_the_suffix_build_appends(): assert naming.base_name("A001-1") == "A001-1" assert naming.base_name("A001-0") == "A001-0" assert naming.base_name("Roll_003") == "Roll_003" + assert naming.base_name("A001-10") == "A001" + # `{index}` is zero-padded and `build`'s suffix never is, so two jobs + # from an indexed template are not one job. + assert naming.base_name("Shoot-003") == "Shoot-003" assert naming.base_name("-2") == "-2" diff --git a/tests/test_verdict_integrity.py b/tests/test_verdict_integrity.py index 7f3ee3c..19a20be 100644 --- a/tests/test_verdict_integrity.py +++ b/tests/test_verdict_integrity.py @@ -11,6 +11,7 @@ from __future__ import annotations +import datetime as _dt import os import platform import subprocess @@ -923,6 +924,63 @@ def test_an_unhashed_entry_is_superseded_only_by_the_same_source_file( assert bool(report.superseded) is passes +@pytest.mark.parametrize( + "older_name, newer_name, passes", + [ + ("A001", "A001", True), + ("A001", "A001-2", True), # the queue's name for the rerun + ("A001", "A002", False), # another card's clip at this path + ("Shoot-003", "Shoot-004", False), # `{index}`, not a rerun suffix + (None, "A001", False), + ("A001", None, False), + ]) +def test_a_file_a_cancelled_job_never_reached_is_superseded_by_the_same_job( + tmp_path, older_name, newer_name, passes): + """A cancelled job lists the files it never reached with no hash, size or + date. Requiring a size and date to match left those entries failing + `verify` on the folder for good, after the rerun had copied every one. + With nothing of the source recorded, the job name is what ties the two.""" + dest = tmp_path / "dst" + clip = dest / "Clips" / "C0001.MXF" + clip.parent.mkdir(parents=True) + clip.write_bytes(os.urandom(3000)) + relative = "../Clips/C0001.MXF" + older = _classic_manifest(dest / "A001_Reports" / "JobReport.mhl", EARLIER, + {relative: None}, size=None, modified=None, + name=older_name) + _classic_manifest(dest / "A001_Reports-2" / "JobReport.mhl", SAME, + {relative: hash_file(clip, "xxh3-64")}, name=newer_name) + + report = _report_for(verify.verify_tree(dest), older) + assert report.passed is passes + assert bool(report.superseded) is passes + + +def test_cancel_then_rerun_leaves_the_folder_verified(tmp_path): + """End to end with the real writer: the manifest of a job cancelled before + its second file is answered by the rerun's, and the folder passes.""" + card = _card(tmp_path, {"C001.mov": os.urandom(2000), + "C002.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + cancelled = engine.run(card, _options(dest)) + # What a cancel before C002 leaves behind: no destination record for it, + # and the file itself absent. + reached = [f for f in cancelled.files if f.source.name == "C001.mov"] + cancelled.not_attempted = [card / "C002.mov"] + cancelled.files = reached + (dest / "C002.mov").unlink() + first = write_mhl(cancelled, dest / "A001_Reports" / "JobReport.mhl") + assert not _report_for(verify.verify_tree(dest), first).passed + + rerun = engine.run(card, _options(dest)) + rerun.finished = cancelled.finished + _dt.timedelta(seconds=5) + write_mhl(rerun, dest / "A001_Reports-2" / "JobReport.mhl") + + reports = verify.verify_tree(dest) + assert all(report.passed for report in reports) + assert [v.path.name for v in _report_for(reports, first).superseded] == ["C002.mov"] + + @pytest.mark.parametrize( "older_name, newer_name, passes", [ From 42e26c66ac64f5a565d4916ad00a4641a1278d62 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:19:22 -0700 Subject: [PATCH 5/7] Order supersession by the manifest that recorded each entry An ASC MHL report carries the entries of every generation of its history but was dated by the newest one. A checksum from generation 1 could then answer a failure written after it, and a repair written between two generations stopped answering generation 1's failure once any later generation existed. Each entry is now compared by the manifest that recorded it, and superseded_by names that manifest. Two source-identity gaps are closed with it. Merging a history dropped an earlier failure for any later record of the same path; it is now dropped only for a later hashed record with the same size and modification date. The folder-marker rule applied to any unhashed entry; it now applies only to one that records no size or date. --- CHANGELOG.md | 9 +- docs/ascmhl.md | 4 +- docs/data-safety.md | 25 +++++- src/offloader/verify.py | 115 +++++++++++++++++++------ tests/test_verdict_integrity.py | 148 ++++++++++++++++++++++++++++++++ 5 files changed, 270 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27d692a..dd5874a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,14 +34,19 @@ project uses [semantic versioning][semver]. superseded only when both entries record the same source size and modification date. A folder marker, or a file a cancelled job never reached, records neither and is superseded only by a manifest naming the - same job; ASC MHL records no job name, so its markers are never superseded. + same job; ASC MHL records no job name, so its markers and never-reached + entries are never superseded. Only an entry with no size or date counts as + a folder marker. Which entry is later is judged by the manifest that + recorded it, not by the newest generation of the history it was read from. - **An ASC MHL history hid what its earlier generations recorded.** `verify` checked only the newest generation, so a clip an earlier card's run had recorded as failed passed once a second card wrote a generation of its own, and files a `--skip-existing` rerun skipped were never re-hashed. A history is now verified as one view: each path is judged by the latest generation that lists it, each file is hashed once, and an earlier generation that - cannot be read is an error. + cannot be read is an error. An earlier failure is dropped only for a later + hashed record of the same source file, so a different card's clip at the + same path does not hide it. - **`verify` on a folder could pass on files outside it.** A manifest under `D2` listing `D1`'s files by absolute path or `..` made `verify D2` hash `D1` and pass. Given a folder, an entry resolving outside it now fails as diff --git a/docs/ascmhl.md b/docs/ascmhl.md index 14a40a7..e622674 100644 --- a/docs/ascmhl.md +++ b/docs/ascmhl.md @@ -118,7 +118,9 @@ handled (a second card into the same root, a `--skip-existing` rerun), so the newest one alone can omit a failure or a file an earlier one recorded. Every path any generation lists is judged by the latest generation that lists it: a `failed` or unhashed latest record fails, a hashed one is checked, and each -file is hashed once however many generations list it. Directory hashes are the +file is hashed once however many generations list it. An earlier failure is +dropped only for a later hashed record of the same source file (same size and +modification date); otherwise it is still reported. Directory hashes are the newest generation's, over the files it lists. The rules and limits are in [data-safety.md](data-safety.md#an-asc-mhl-history-is-verified-as-one). diff --git a/docs/data-safety.md b/docs/data-safety.md index 08316fa..ee88be9 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -260,7 +260,9 @@ Supersession runs one way only: ordinary way to recover, so such an entry is superseded when the newer manifest lists the same path with a hash that matches and both manifests name the same job, the rule a folder marker gets below, with the same - limit. + limit. ASC MHL records no job name, so in an ASC MHL history such an entry + keeps failing `verify` after the rerun; the classic manifest of the same + jobs is answered. - A folder marker (a source folder that could not be listed, or a skipped link, recorded as one unhashed entry at the folder's path) is superseded by a newer manifest for the same destination root when that manifest lists at @@ -270,7 +272,9 @@ Supersession runs one way only: rerun lists the files inside a folder, never the folder itself, so exact-path matching could never clear it. A marker records no size or date, so the job name (MHL 1.1 `creatorinfo/name`) is what ties the rerun to the - card. Names are compared ignoring case and the `-2`, `-3` suffix the queue + card. Only an entry that records neither is treated as a marker: a failed + file records both, and files a later run lists under its path never answer + it. Names are compared ignoring case and the `-2`, `-3` suffix the queue adds to a name already taken (written without a leading zero, so the `{index}` in `Shoot-003` is never mistaken for it). ASC MHL records no job name, so a marker in an ASC MHL history is never superseded and keeps @@ -286,6 +290,13 @@ Supersession runs one way only: missing, the numbering decides (`_Reports-2`, `JobReport-2.mhl`), and only between manifests in the same numbered series. File modification times are never used. When neither says which is newer, nothing is superseded. +- "Newer" is judged entry by entry, by the manifest that recorded each one. + An ASC MHL history is read as one view (below), so its entries come from + several generations with different dates. A checksum generation 1 recorded + never answers a failure written after generation 1, however many + generations followed; and a repair written between two generations still + answers generation 1's failure. `superseded by` names the manifest that + recorded the answer. - Same destination root means the root `verify` already derives for each manifest: the folder above `_Reports*`, or the folder above `ascmhl/`. A manifest for a subfolder (another job whose destination was @@ -310,7 +321,15 @@ copy the rerun skipped was never re-hashed, however corrupt. any generation lists is judged by the latest generation that lists it: - A path whose latest record is labelled `failed`, or has no hash, fails as - `no hash`, unless a later generation lists it with a hash that matches. + `no hash`. +- An earlier failed or unhashed record is dropped only when the later record + of that path has a hash and the same source size and modification date, + the rule supersession uses between manifests. A different card's clip at + the same relative path is a later record of the path and no evidence the + first clip was copied, so the earlier failure is still reported, beside the + check of the later file. An earlier record with no size or date (a file a + cancelled job never reached) has nothing to compare and stays failing; see + the limit on job names above. - A path whose latest record has a hash is checked against it, missing, mismatched and unreadable all failing, even when the newest generation does not list it. The verdict names the generation the record came from. diff --git a/src/offloader/verify.py b/src/offloader/verify.py index d591704..75642c5 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -791,10 +791,29 @@ def _earlier_generation_entries(manifest: Path, own: list[_Entry]) -> list[_Entr unhashed fails, exactly as an unhashed entry of the newest one does; one whose latest record has a hash is checked against it. + An earlier *failure* is only dropped for a later record of the same + source file: one with a hash, the same size and the same modification + date, the rule `supersede` applies between manifests. Card A002's clip + landing on the path card A001's clip failed at is a later record of that + path and no evidence at all that A001's clip was copied, so A001's failed + entry stays, and fails, beside it. An earlier failure that records no + size or date (a file a cancelled job never reached) has nothing to + compare, and a history records no job name to tie a rerun to it, so it + stays too. + An earlier generation that cannot be read is an error, never skipped: it may be the only record of a failure. """ - seen = {_entry_key(entry.path) for entry in own} + #: Path -> the record it is judged by, the latest one. + latest: dict[str, _Entry] = {} + #: Failures already reported, so one source failing in three generations + #: is one line. + failed: set[tuple[str, int | None, _dt.datetime | None]] = set() + for entry in own: + key = _entry_key(entry.path) + latest.setdefault(key, entry) + if not _hashed(entry): + failed.add((key, entry.size, entry.modified)) found: list[_Entry] = [] for generation in reversed(_earlier_generations(manifest)): try: @@ -807,13 +826,30 @@ def _earlier_generation_entries(manifest: Path, own: list[_Entry]) -> list[_Entr "history is not an ASC MHL manifest") for entry in _ascmhl_entries(generation, root): key = _entry_key(entry.path) - if key in seen: + entry = entry._replace(recorded_in=generation) + judged = latest.get(key) + if judged is None: + latest[key] = entry + elif _hashed(entry): + # A hash a later generation replaced: the later one is the + # record of what is at this path now. + continue + elif _hashed(judged) and _same_facts(entry.size, entry.modified, + judged.size, judged.modified): continue - seen.add(key) - found.append(entry._replace(recorded_in=generation)) + if not _hashed(entry): + mark = (key, entry.size, entry.modified) + if mark in failed: + continue + failed.add(mark) + found.append(entry) return found +def _hashed(entry: _Entry) -> bool: + return bool(entry.algorithm and entry.digest) + + def _described_root(manifest: Path, listed: set[Path]) -> Path: """The managed root a classic manifest belongs to. @@ -922,15 +958,16 @@ def _numbering(manifest: Path) -> tuple[tuple[str, ...], tuple[int, ...]]: return series, (folder_number, file_number) -def _is_newer(candidate: VerifyReport, than: VerifyReport) -> bool: - """Whether `candidate` is known to have been written after `than`. +def _is_newer(candidate: Path, than: Path, + when: Callable[[Path], _dt.datetime | None] = _recorded_at) -> bool: + """Whether manifest `candidate` is known to have been written after `than`. - The manifests' own timestamps decide when both have one and they differ. - Otherwise (equal to the second, which two quick runs manage, or missing) - the numbering decides, and only within one series. Anything else is not - known to be newer, which keeps the older entry failing. + The manifests' own timestamps (`when`) decide when both have one and they + differ. Otherwise (equal to the second, which two quick runs manage, or + missing) the numbering decides, and only within one series. Anything else + is not known to be newer, which keeps the older entry failing. """ - a, b = candidate.recorded_at, than.recorded_at + a, b = when(candidate), when(than) if a is not None and b is not None: try: if a != b: @@ -938,8 +975,8 @@ def _is_newer(candidate: VerifyReport, than: VerifyReport) -> bool: except TypeError: # One carries a UTC offset and the other does not. pass - series_a, position_a = _numbering(candidate.manifest) - series_b, position_b = _numbering(than.manifest) + series_a, position_a = _numbering(candidate) + series_b, position_b = _numbering(than) return series_a == series_b and position_a > position_b @@ -982,9 +1019,14 @@ def _same_source(older: FileVerdict, newer: FileVerdict) -> bool: card's clip at the same relative path almost never does. Either value missing on either side is not a match: the older entry keeps failing. """ - return (older.expected_size is not None - and older.expected_size == newer.expected_size - and _same_instant(older.expected_modified, newer.expected_modified)) + return _same_facts(older.expected_size, older.expected_modified, + newer.expected_size, newer.expected_modified) + + +def _same_facts(size_a: int | None, modified_a: _dt.datetime | None, + size_b: int | None, modified_b: _dt.datetime | None) -> bool: + return (size_a is not None and size_a == size_b + and _same_instant(modified_a, modified_b)) def _records_nothing(entry: FileVerdict) -> bool: @@ -1052,8 +1094,28 @@ def supersede(reports: list[VerifyReport]) -> None: that folder, when every entry it lists under the folder matched and none of them is unhashed. A marker records no size or date, so here the two manifests must also name the same job (`_same_job`); an ASC MHL manifest - records no job name, so its markers are never superseded this way. + records no job name, so its markers are never superseded this way. Only + an entry that records no size or date is treated as a marker: a failed + *file* records both, and is answered by the same source file or not at + all. + + "Later" is judged entry by entry, by the manifest that *recorded* each + one. An ASC MHL report carries the entries of every generation of its + history (`FileVerdict.recorded_in`), so the report's own date is only its + newest generation's. Going by that date let a checksum recorded in + generation 1 answer a failure written after it, once any later generation + existed, and stopped a repair written between two generations from + answering generation 1's failure. `superseded_by` names the manifest + that recorded the answer. """ + moments: dict[Path, _dt.datetime | None] = { + report.manifest: report.recorded_at for report in reports} + + def when(manifest: Path) -> _dt.datetime | None: + if manifest not in moments: + moments[manifest] = _recorded_at(manifest) + return moments[manifest] + for older in reports: pending = [v for v in older.verdicts if v.result is EntryResult.NO_CHECKSUM and v.superseded_by is None] @@ -1062,22 +1124,25 @@ def supersede(reports: list[VerifyReport]) -> None: for newer in reports: if newer is older or not _same_root(newer, older): continue - if not _is_newer(newer, older): - continue matched = {_entry_key(v.path): v for v in newer.verdicts if v.result is EntryResult.OK and v.expected} same_job = _same_job(older, newer) for verdict in pending: if verdict.superseded_by is not None: continue + failed_in = verdict.recorded_in or older.manifest key = _entry_key(verdict.path) answer = matched.get(key) - if answer is not None and _same_source(verdict, answer): - verdict.superseded_by = newer.manifest - elif (answer is not None and same_job - and _records_nothing(verdict)): - verdict.superseded_by = newer.manifest - elif same_job and _folder_answered(key, newer): + if answer is not None: + answered_in = answer.recorded_in or newer.manifest + if not _is_newer(answered_in, failed_in, when): + continue + if _same_source(verdict, answer) or ( + same_job and _records_nothing(verdict)): + verdict.superseded_by = answered_in + elif (same_job and _records_nothing(verdict) + and _is_newer(newer.manifest, failed_in, when) + and _folder_answered(key, newer)): verdict.superseded_by = newer.manifest diff --git a/tests/test_verdict_integrity.py b/tests/test_verdict_integrity.py index 19a20be..a46e5fd 100644 --- a/tests/test_verdict_integrity.py +++ b/tests/test_verdict_integrity.py @@ -14,6 +14,7 @@ import datetime as _dt import os import platform +import re import subprocess import xml.etree.ElementTree as ET from pathlib import Path @@ -1153,6 +1154,153 @@ def test_a_later_generation_answers_an_earlier_failure(tmp_path, monkeypatch): assert all(v.recorded_in is None for v in report.verdicts) +def test_a_different_cards_clip_does_not_answer_an_earlier_generations_failure( + tmp_path, monkeypatch, capsys): + """Card A001's clip failed in generation 1. Card A002 then put its own + clip at the same relative path, in generation 2. A later record of the + path used to drop the earlier failure, so the history passed with A001's + clip never copied.""" + first_card = _card(tmp_path, {"Clips/C001.mov": os.urandom(4000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _fail_reads_of(patch, "C001.mov") + failed = engine.run(first_card, _options(dest, algorithm="xxh64")) + first = ascmhl.write_manifest(failed, dest, when=_at(10)) + second_card = _card(tmp_path, {"Clips/C001.mov": os.urandom(5000)}, + name="A002") + ascmhl.write_manifest( + engine.run(second_card, _options(dest, algorithm="xxh64")), dest, + when=_at(11)) + + report = verify.verify_manifest(_only_history(dest)) + assert [(v.path.name, v.result, v.recorded_in.name) + for v in report.failures] == [ + ("C001.mov", verify.EntryResult.NO_CHECKSUM, first.name)] + # A002's own clip is still checked, once, against generation 2. + assert [(v.path.name, v.recorded_in) for v in report.verdicts if v.ok] == [ + ("C001.mov", None)] + assert cli.main(["verify", str(dest), "--quiet"]) == 1 + capsys.readouterr() + + +def test_a_history_cannot_tie_a_rerun_to_a_file_a_cancelled_job_never_reached( + tmp_path): + """A never-reached entry records no size or date, and a history records + no job name, so nothing ties the rerun's file to it: it keeps failing. + A classic manifest names its job and is answered; see + `test_cancel_then_rerun_leaves_the_folder_verified`.""" + card = _card(tmp_path, {"C001.mov": os.urandom(2000), + "C002.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + cancelled = engine.run(card, _options(dest, algorithm="xxh64")) + cancelled.not_attempted = [card / "C002.mov"] + cancelled.files = [f for f in cancelled.files if f.source.name == "C001.mov"] + (dest / "C002.mov").unlink() + first = ascmhl.write_manifest(cancelled, dest, when=_at(10)) + ascmhl.write_manifest(engine.run(card, _options(dest, algorithm="xxh64")), + dest, when=_at(11)) + + report = verify.verify_manifest(_only_history(dest)) + assert [(v.path.name, v.result, v.recorded_in.name) + for v in report.failures] == [ + ("C002.mov", verify.EntryResult.NO_CHECKSUM, first.name)] + + +# ---------- P1: "later" is judged by the manifest that recorded each entry + + +def _at(hour: int) -> _dt.datetime: + return _dt.datetime(2026, 10, 11, hour, tzinfo=_dt.timezone.utc) + + +def _stamp(manifest: Path, moment: _dt.datetime) -> Path: + """Rewrite when a classic manifest says it was written, so that two runs + a test makes within one second have a known order.""" + text = manifest.read_text(encoding="utf-8") + for tag in ("startdate", "finishdate"): + text = re.sub(rf"<{tag}>[^<]*", + f"<{tag}>{moment.isoformat()}", text) + manifest.write_text(text, encoding="utf-8") + return manifest + + +def test_a_repair_written_between_two_generations_still_answers_the_first( + tmp_path, monkeypatch): + """Generation 1 records a read failure and a classic rerun repairs it. + Offloading an unrelated card then wrote generation 2, and the report for + the history took generation 2's date: the repair was no longer "later" + than the failure it answered, and a verified folder began to fail.""" + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(4000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _fail_reads_of(patch, "C001.mov") + failed = engine.run(card, _options(dest, algorithm="xxh64")) + first = ascmhl.write_manifest(failed, dest, when=_at(10)) + repair = _stamp( + write_mhl(engine.run(card, _options(dest, algorithm="xxh64")), + dest / "A001_Reports" / "JobReport.mhl"), _at(11)) + before = verify.verify_tree(dest) + assert all(r.passed for r in before), [r.summary() for r in before] + + other = _card(tmp_path, {"Clips/B001.mov": os.urandom(4000)}, name="A002") + second = ascmhl.write_manifest( + engine.run(other, _options(dest, algorithm="xxh64")), dest, when=_at(12)) + + reports = verify.verify_tree(dest) + assert all(r.passed for r in reports), [r.summary() for r in reports] + (verdict,) = _report_for(reports, second).superseded + assert (verdict.path.name, verdict.recorded_in.name, + verdict.superseded_by) == ("C001.mov", first.name, repair) + + +def test_a_checksum_from_an_earlier_generation_does_not_answer_a_later_failure( + tmp_path): + """The other direction. Generation 1 hashed the clip, a later classic + manifest records the same clip unread, and generation 2 lists something + else. The history's report is dated by generation 2, which let generation + 1's checksum answer a failure written after it.""" + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(4000)}) + dest = tmp_path / "dst" + first = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest, when=_at(10)) + recorded = next( + node for node in ET.parse(first).getroot().iter(f"{{{ascmhl.NAMESPACE}}}path") + if node.text.endswith("C001.mov")) + # The later failed run, exactly as it would record the same source file. + later = _classic_manifest( + dest / "A001_Reports" / "JobReport.mhl", _at(11).isoformat(), + {"../Clips/C001.mov": None}, size=int(recorded.get("size")), + modified=recorded.get("lastmodificationdate")) + assert not _report_for(verify.verify_tree(dest), later).passed + + other = _card(tmp_path, {"Clips/B001.mov": os.urandom(4000)}, name="A002") + ascmhl.write_manifest( + engine.run(other, _options(dest, algorithm="xxh64")), dest, when=_at(12)) + + report = _report_for(verify.verify_tree(dest), later) + assert not report.passed + assert not report.superseded + + +def test_a_failed_file_is_never_answered_as_if_it_were_a_folder(tmp_path): + """The folder rule is for a marker, which records no size or date. A + failed file records both, and files a later run of the same job lists + *under* its path say nothing about the file itself.""" + dest = tmp_path / "dst" + inner = dest / "Clips" / "C001.mov" / "inner.mov" + inner.parent.mkdir(parents=True) + inner.write_bytes(os.urandom(3000)) + older = _classic_manifest(dest / "A001_Reports" / "JobReport.mhl", EARLIER, + {"../Clips/C001.mov": None}, name="A001") + _classic_manifest(dest / "A001_Reports-2" / "JobReport.mhl", SAME, + {"../Clips/C001.mov/inner.mov": hash_file(inner, "xxh3-64")}, + name="A001") + + report = _report_for(verify.verify_tree(dest), older) + assert not report.passed + assert not report.superseded + + def test_an_unreadable_earlier_generation_is_an_error_not_a_pass( tmp_path, capsys): card = _card(tmp_path, {"C001.mov": os.urandom(3000)}) From a9aaa6e84951d527a305127e7cbf100b7e706880 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:55:07 -0700 Subject: [PATCH 6/7] Record the job's own name, and recheck only a generation's own directory hashes A manifest recorded the queue's name for a job, and verify took a trailing number back off to find the job. That made Shoot-100 and Shoot-101 one job, and kept a card really called A001-2 from matching its own retry, A001-2-2. The queue now keeps the name from before it added a suffix, the manifest records that, and names are compared whole. An ASC MHL generation that hashed nothing of its own has directory hashes over no files. An entry inherited from an earlier generation switched the recheck on for it, so a tree a later manifest had repaired was reported with its directories changed. The recheck now goes by what the generation itself hashed. --- CHANGELOG.md | 3 ++ docs/data-safety.md | 9 ++-- src/offloader/engine.py | 5 +++ src/offloader/gui/worker.py | 19 +++++--- src/offloader/models.py | 11 +++++ src/offloader/naming.py | 47 ++++++++++---------- src/offloader/presets.py | 4 +- src/offloader/reports/mhl.py | 4 +- src/offloader/verify.py | 29 ++++++++++--- tests/test_gui.py | 3 ++ tests/test_naming.py | 40 ++++++++++++----- tests/test_verdict_integrity.py | 77 ++++++++++++++++++++++++++++++--- 12 files changed, 194 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd5874a..dc463e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,9 @@ project uses [semantic versioning][semver]. entries are never superseded. Only an entry with no size or date counts as a folder marker. Which entry is later is judged by the manifest that recorded it, not by the newest generation of the history it was read from. + A classic manifest now records the job's own name, without the `-2` the + app's queue adds to a second entry for the same card, and names are + compared whole. - **An ASC MHL history hid what its earlier generations recorded.** `verify` checked only the newest generation, so a clip an earlier card's run had recorded as failed passed once a second card wrote a generation of its own, diff --git a/docs/data-safety.md b/docs/data-safety.md index ee88be9..b42dda8 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -274,9 +274,12 @@ Supersession runs one way only: so the job name (MHL 1.1 `creatorinfo/name`) is what ties the rerun to the card. Only an entry that records neither is treated as a marker: a failed file records both, and files a later run lists under its path never answer - it. Names are compared ignoring case and the `-2`, `-3` suffix the queue - adds to a name already taken (written without a leading zero, so the - `{index}` in `Shoot-003` is never mistaken for it). ASC MHL records no job + it. Names are compared whole, ignoring case. A manifest records the job's + own name: when the app's queue renames a second entry for a card `A001-2` + to keep report folders apart, its manifest still says `A001`, so a queued + retry names the same job as the run it repeats. The suffix is never worked + back out of a name, since a card can really be called `A001-2` and + `Shoot-100` and `Shoot-101` are two jobs. ASC MHL records no job name, so a marker in an ASC MHL history is never superseded and keeps failing `verify` even after a rerun copied the folder. **Limit:** two different cards given the same job name (a naming template without diff --git a/src/offloader/engine.py b/src/offloader/engine.py index 4bbdaa9..0315992 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -561,6 +561,9 @@ class OffloadOptions: #: order. See `order_for_transfer`. proxies_first: bool = True job_name: str | None = None + #: The job's own name when `job_name` was made unique by the queue; see + #: `Job.identity`. Leave unset when `job_name` is the name as given. + job_identity: str | None = None thumbnail_dir: Path | None = None extra_probe: bool = True #: The workflow this offload is. `Profile.DATA` is a generic large-data @@ -1196,6 +1199,7 @@ def run(source_root: Path, options: OffloadOptions, verification=options.verification, profile=options.profile, hash_label=algorithm.label, + identity=options.job_identity, started=_dt.datetime.now(), os_version=host.os_version, processors=host.processors, @@ -1780,6 +1784,7 @@ def rescan(source_root: Path, destination_roots: Sequence[Path], verification=options.verification, profile=options.profile, hash_label=algorithm.label, + identity=options.job_identity, started=_dt.datetime.now(), os_version=host.os_version, processors=host.processors, diff --git a/src/offloader/gui/worker.py b/src/offloader/gui/worker.py index ce00b5b..1338c02 100644 --- a/src/offloader/gui/worker.py +++ b/src/offloader/gui/worker.py @@ -50,6 +50,9 @@ class QueueItem: source: Path name: str preset: Preset + #: The job's own name, without the suffix auto-naming adds to a taken + #: one. What the manifests record; see `Job.identity`. + identity: str | None = None state: JobState = JobState.QUEUED fraction: float = 0.0 stage: str = "" @@ -150,7 +153,8 @@ def _on_progress(self, event: engine.ProgressEvent) -> None: def run(self) -> None: # noqa: D102 - QThread entry point item = self._item try: - options = item.preset.to_options(job_name=item.name) + options = item.preset.to_options(job_name=item.name, + job_identity=item.identity) job = engine.run(item.source, options, self._on_progress, item.control) reports = self._write_reports(job, item.preset) self.completed.emit(item.identifier, job, reports, None) @@ -188,15 +192,20 @@ def __init__(self, parent: QObject | None = None) -> None: # ---------------------------------------------------------------- queue def enqueue(self, source: Path, preset: Preset, name: str | None = None) -> QueueItem: source = Path(source) - resolved = name or naming.build( - preset.naming_template, source, - volume_label=default_source_name(source), taken=self._taken_names() - ) + if name: + resolved = identity = name + else: + resolved, identity = naming.build_with_identity( + preset.naming_template, source, + volume_label=default_source_name(source), + taken=self._taken_names() + ) item = QueueItem( identifier=self._next_id, source=source, name=resolved, preset=preset, + identity=identity, ) self._next_id += 1 self.items.append(item) diff --git a/src/offloader/models.py b/src/offloader/models.py index 0b2a0e4..63a6de9 100644 --- a/src/offloader/models.py +++ b/src/offloader/models.py @@ -353,6 +353,10 @@ class Job: #: manifests can list them unhashed instead of reading as complete, and #: counted in the summary of a cancelled job. not_attempted: list[Path] = field(default_factory=list) + #: The job's own name, where `name` carries a `-2` the queue added to + #: tell two entries for one card apart (`naming.build_with_identity`). + #: None when the name was never disambiguated, which is every CLI job. + identity: str | None = None #: For a selection (a timeline offload), each source's path beneath every #: destination root, as the selector laid it out. Empty for a scanned #: card, whose layout is derived from `source_root`. Needed to say where a @@ -372,6 +376,13 @@ class Job: #: depends on the manifest that is missing. report_failures: list[str] = field(default_factory=list) + @property + def recorded_name(self) -> str: + """The name manifests record for this job: its identity, so a rerun + the queue renamed `A001-2` still names the job `A001`. `verify` ties + a rerun to the entries only a job name can answer by this name.""" + return self.identity or self.name + @property def reports_folder(self) -> str: """The paperwork folder's name inside a destination root.""" diff --git a/src/offloader/naming.py b/src/offloader/naming.py index 85bdcba..7b015c5 100644 --- a/src/offloader/naming.py +++ b/src/offloader/naming.py @@ -80,8 +80,28 @@ def replace(match: re.Match[str]) -> str: def build(template: str, source: Path, *, volume_label: str | None = None, when: _dt.datetime | None = None, taken: Iterable[str] = ()) -> str: + """The name alone; see `build_with_identity`.""" + return build_with_identity(template, source, volume_label=volume_label, + when=when, taken=taken)[0] + + +def build_with_identity( + template: str, source: Path, *, volume_label: str | None = None, + when: _dt.datetime | None = None, taken: Iterable[str] = (), +) -> tuple[str, str]: """Render `template`, incrementing `{index}` until the name is unused. + Returns `(name, identity)`. The name is unique among `taken`. The + identity is the job's own name, before the `-2` that only tells two queue + entries apart: a card queued twice comes out as `A001` and `A001-2`, and + both are the job `A001`. Manifests record the identity, which is how a + rerun is known to be the same job as the run it repeats. It is kept + rather than worked back out of the name, because nothing in a name says + whether its last number was appended here: a card really called `A001-2` + and the hundredth job of `Shoot-{index}` both end in one that was not. + A name that took an `{index}` is its own identity, since each index is a + job of its own. + Templates without `{index}` get a `-2`, `-3` suffix instead, so a name collision can never silently overwrite an earlier job's reports. @@ -96,37 +116,16 @@ def build(template: str, source: Path, *, volume_label: str | None = None, for index in range(1, len(used) + 2): candidate = render(template, context(source, volume_label, when, index)) if candidate.casefold() not in used: - return candidate + return candidate, candidate # A template whose `{index}` does not survive sanitising renders the # same name every time. Fall through to the suffix search rather than # handing back a name we know is taken. base = render(template, context(source, volume_label, when)) if base.casefold() not in used: - return base + return base, base for suffix in range(2, len(used) + 3): candidate = f"{base}-{suffix}" if candidate.casefold() not in used: - return candidate + return candidate, base raise AssertionError("unreachable: more candidates than taken names") - - -#: The `-2`, `-3` suffix `build` appends to a name that is already taken. -_TAKEN_SUFFIX = re.compile(r"^(?P.+)-(?P[1-9][0-9]*)$") - - -def base_name(name: str) -> str: - """`name` without the suffix `build` appends when the name is taken. - - Two queue entries for the same card come out as `A001` and `A001-2`, and - they are still the same job as far as the card is concerned. Only a - number from 2 up is removed, since `build` never appends `-1` or `-0`, - and only one written without a leading zero, which is how `build` writes - it: `{index}` renders as `003`, so `Shoot-003` and `Shoot-004` stay two - different jobs. A name that genuinely ends in `-2` loses it too; nothing - in the name can tell the two apart. - """ - match = _TAKEN_SUFFIX.match(name) - if match and int(match.group("number")) >= 2: - return match.group("base") - return name diff --git a/src/offloader/presets.py b/src/offloader/presets.py index c829d47..7640f10 100644 --- a/src/offloader/presets.py +++ b/src/offloader/presets.py @@ -98,7 +98,8 @@ def mark_used(self) -> None: self.last_used = _dt.datetime.now().isoformat(timespec="seconds") # ---------------------------------------------------------------- engine - def to_options(self, job_name: str | None = None) -> OffloadOptions: + def to_options(self, job_name: str | None = None, + job_identity: str | None = None) -> OffloadOptions: return OffloadOptions( destinations=list(self.destinations), algorithm=self.algorithm, @@ -109,6 +110,7 @@ def to_options(self, job_name: str | None = None) -> OffloadOptions: skip_existing=self.skip_existing, proxies_first=self.proxies_first, job_name=job_name, + job_identity=job_identity, # Metadata is cheap next to the copy itself and useful even when # thumbnails are switched off, so it is always collected — unless # this is a data-transfer preset, where OffloadOptions turns media diff --git a/src/offloader/reports/mhl.py b/src/offloader/reports/mhl.py index c3106e6..ac0d7d2 100644 --- a/src/offloader/reports/mhl.py +++ b/src/offloader/reports/mhl.py @@ -90,7 +90,9 @@ def write_mhl(job: Job, path: Path, *, destination_index: int = 0, **_options) - root = ET.Element("hashlist", {"version": _MHL_VERSION}) info = ET.SubElement(root, "creatorinfo") - ET.SubElement(info, "name").text = _xml_safe(job.name) + # The job's own name, not the queue's `-2` variant of it: see + # `Job.recorded_name`. + ET.SubElement(info, "name").text = _xml_safe(job.recorded_name) ET.SubElement(info, "username").text = _xml_safe(_safe_user()) ET.SubElement(info, "hostname").text = _xml_safe(platform.node()) ET.SubElement(info, "tool", {"version": __version__}).text = PRODUCT_NAME diff --git a/src/offloader/verify.py b/src/offloader/verify.py index 75642c5..63e4beb 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -36,7 +36,6 @@ from .engine import DEFAULT_EXCLUDES, is_excluded from .hashers import ALGORITHMS, get_algorithm, hash_file from .integrity import evict_from_cache -from .naming import base_name #: Where this tool files its own paperwork, as a pattern, for manifests that #: do not record the directory itself. A current ASC MHL history carries the @@ -418,6 +417,12 @@ def verify_manifest( algorithm=next((e.algorithm for i, e in enumerate(entries) if e.algorithm and i not in outside), "unknown")) + #: What this generation itself hashed with, None when it hashed nothing. + #: Its directory hashes are only recomputed against that: an entry + #: inherited from an earlier generation says nothing about them. + own_algorithm = next((e.algorithm for i, e in enumerate(entries) + if e.algorithm and i not in outside + and e.recorded_in is None), None) # Only what will be read describes the root: an entry pointing at another # drive would otherwise widen the unlisted scan to everything between. @@ -431,8 +436,12 @@ def verify_manifest( if ascmhl_root is not None: recorded, directory_algorithm = _ascmhl_directory_hashes(ascmhl_root) # Recomputing is only meaningful when the directory hashes and the file - # hashes were taken with the same algorithm. - if not recorded or directory_algorithm != report.algorithm: + # hashes were taken with the same algorithm, by this generation. One + # that hashed nothing of its own (every file it lists failed) has + # directory hashes over no files; an inherited entry's algorithm used + # to switch the check on for it, and a tree a later manifest had + # repaired was then reported as changed. + if not recorded or directory_algorithm != own_algorithm: ascmhl_root, recorded = None, {} #: Relative POSIX path -> what it hashes to now, feeding the directory pass. @@ -1040,12 +1049,18 @@ def _records_nothing(entry: FileVerdict) -> bool: def _same_job(a: VerifyReport, b: VerifyReport) -> bool: - """Both manifests name the same job, ignoring case and the `-2` suffix - the naming adds when a name is already taken. A manifest with no job name - (every ASC MHL one) matches nothing.""" + """Both manifests name the same job, ignoring case. A manifest with no + job name (every ASC MHL one) matches nothing. + + The names are compared whole. A manifest records the job's own name + (`Job.recorded_name`), without the `-2` the queue adds to a name that is + taken, so a rerun already carries the name of the run it repeats. Taking + a trailing number off here instead made `Shoot-100` and `Shoot-101` one + job, and kept a card really called `A001-2` from ever matching its own + rerun, `A001-2-2`.""" if not a.job_name or not b.job_name: return False - return base_name(a.job_name).casefold() == base_name(b.job_name).casefold() + return a.job_name.casefold() == b.job_name.casefold() def _folder_answered(folder_key: str, newer: VerifyReport) -> bool: diff --git a/tests/test_gui.py b/tests/test_gui.py index b7f1234..3802fc2 100644 --- a/tests/test_gui.py +++ b/tests/test_gui.py @@ -179,6 +179,9 @@ def test_auto_naming_avoids_collisions(qapp, controller, source_tree, tmp_path): assert first.name == source_tree.name assert second.name != first.name + # Two entries for one card are still one job, and say so in the manifest. + assert first.identity == second.identity == source_tree.name + assert controller.enqueue(source_tree, preset, "Given").identity == "Given" def test_a_failing_job_surfaces_its_error(qapp, controller, source_tree, tmp_path): diff --git a/tests/test_naming.py b/tests/test_naming.py index 9a38921..84be2c1 100644 --- a/tests/test_naming.py +++ b/tests/test_naming.py @@ -46,20 +46,38 @@ def test_collision_without_index_gets_a_suffix(): assert naming.build("{card}", card, when=WHEN, taken=["A001", "A001-2"]) == "A001-3" -def test_base_name_removes_exactly_the_suffix_build_appends(): +def test_the_identity_is_the_name_before_the_suffix_for_a_taken_one(): taken: list[str] = [] + names = [] for _ in range(3): - name = naming.build("{card}", Path("A001"), when=WHEN, taken=taken) - assert naming.base_name(name) == "A001" + name, identity = naming.build_with_identity( + "{card}", Path("A001"), when=WHEN, taken=taken) + assert identity == "A001" + assert naming.build("{card}", Path("A001"), when=WHEN, taken=taken) == name + names.append(name) taken.append(name) - assert naming.base_name("A001-1") == "A001-1" - assert naming.base_name("A001-0") == "A001-0" - assert naming.base_name("Roll_003") == "Roll_003" - assert naming.base_name("A001-10") == "A001" - # `{index}` is zero-padded and `build`'s suffix never is, so two jobs - # from an indexed template are not one job. - assert naming.base_name("Shoot-003") == "Shoot-003" - assert naming.base_name("-2") == "-2" + assert names == ["A001", "A001-2", "A001-3"] + + +def test_a_card_whose_own_name_ends_in_a_number_keeps_it_as_its_identity(): + """Nothing in `A001-2` says whether the queue appended the `-2`. Taking + it back off made this card's first run `A001` and its rerun `A001-2`, + two different jobs.""" + card = Path("A001-2") + assert naming.build_with_identity("{card}", card, when=WHEN) == ( + "A001-2", "A001-2") + assert naming.build_with_identity( + "{card}", card, when=WHEN, taken=["A001-2"]) == ("A001-2-2", "A001-2") + + +def test_each_index_of_an_indexed_template_is_its_own_identity(): + taken = [f"Shoot-{index:03d}" for index in range(1, 100)] + hundredth = naming.build_with_identity( + "Shoot-{index}", Path("A001"), when=WHEN, taken=taken) + assert hundredth == ("Shoot-100", "Shoot-100") + assert naming.build_with_identity( + "Shoot-{index}", Path("A001"), when=WHEN, + taken=taken + ["Shoot-100"]) == ("Shoot-101", "Shoot-101") def test_collision_check_is_case_insensitive(): diff --git a/tests/test_verdict_integrity.py b/tests/test_verdict_integrity.py index a46e5fd..fa95907 100644 --- a/tests/test_verdict_integrity.py +++ b/tests/test_verdict_integrity.py @@ -929,9 +929,13 @@ def test_an_unhashed_entry_is_superseded_only_by_the_same_source_file( "older_name, newer_name, passes", [ ("A001", "A001", True), - ("A001", "A001-2", True), # the queue's name for the rerun + ("A001", "a001", True), ("A001", "A002", False), # another card's clip at this path - ("Shoot-003", "Shoot-004", False), # `{index}`, not a rerun suffix + # A manifest records the job's own name, so a number on the end is + # part of it and never a rerun: these are all different jobs. + ("A001", "A001-2", False), + ("Shoot-003", "Shoot-004", False), + ("Shoot-100", "Shoot-101", False), (None, "A001", False), ("A001", None, False), ]) @@ -982,15 +986,47 @@ def test_cancel_then_rerun_leaves_the_folder_verified(tmp_path): assert [v.path.name for v in _report_for(reports, first).superseded] == ["C002.mov"] +@pytest.mark.parametrize("card_name, queue_names", [ + ("A001", ["A001", "A001-2"]), # an ordinary queued retry + ("A001-2", ["A001-2", "A001-2-2"]), # a card whose own name ends so + ("A001", ["A001-2", "A001-3"]), # two retries, the first run gone +]) +def test_a_queued_retry_answers_the_cancelled_run_whatever_the_card_is_called( + tmp_path, card_name, queue_names): + """The queue renames a retry to keep report folders apart, and the + manifest records the job's own name either way. Working the job back out + of the queue's name failed for a card called `A001-2`, whose retry is + `A001-2-2`.""" + card = _card(tmp_path, {"C001.mov": os.urandom(2000), + "C002.mov": os.urandom(2000)}, name=card_name) + dest = tmp_path / "dst" + first_name, retry_name = queue_names + cancelled = engine.run(card, _options(dest, job_name=first_name, + job_identity=card_name)) + cancelled.not_attempted = [card / "C002.mov"] + cancelled.files = [f for f in cancelled.files if f.source.name == "C001.mov"] + (dest / "C002.mov").unlink() + first = write_mhl(cancelled, dest / f"{first_name}_Reports" / "JobReport.mhl") + assert verify.verify_manifest(first).job_name == card_name + + retry = engine.run(card, _options(dest, job_name=retry_name, + job_identity=card_name)) + retry.finished = cancelled.finished + _dt.timedelta(seconds=5) + write_mhl(retry, dest / f"{retry_name}_Reports" / "JobReport.mhl") + + reports = verify.verify_tree(dest) + assert all(report.passed for report in reports), [r.summary() for r in reports] + assert [v.path.name for v in _report_for(reports, first).superseded] == ["C002.mov"] + + @pytest.mark.parametrize( "older_name, newer_name, passes", [ ("A001", "A001", True), ("A001", "a001", True), - ("A001", "A001-2", True), # the suffix a taken name gets - ("A001-3", "A001", True), ("A001", "A002", False), - ("A001", "A001-1", False), # never appended, so a different name + ("A001", "A001-2", False), # recorded names are compared whole + ("Shoot-100", "Shoot-101", False), (None, "A001", False), ("A001", None, False), ("", "", False), @@ -1253,6 +1289,37 @@ def test_a_repair_written_between_two_generations_still_answers_the_first( verdict.superseded_by) == ("C001.mov", first.name, repair) +def test_a_generation_that_hashed_nothing_has_no_directory_hashes_to_recheck( + tmp_path, monkeypatch): + """Generation 1 hashed a clip, generation 2 lists only one it could not + read, and a classic manifest then repairs that one. Generation 1's entry + is inherited, and its algorithm switched on the recheck of generation 2's + directory hashes, which cover no files: the repaired tree was reported + with its root and `Clips` changed, and no file failing.""" + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(4000)}) + dest = tmp_path / "dst" + ascmhl.write_manifest(engine.run(card, _options(dest, algorithm="xxh64")), + dest, when=_at(10)) + (card / "Clips" / "C002.mov").write_bytes(os.urandom(3000)) + with monkeypatch.context() as patch: + _fail_reads_of(patch, "C002.mov") + failed = engine.run(card, _options(dest, algorithm="xxh64", + skip_existing=True)) + second = ascmhl.write_manifest(failed, dest, when=_at(11)) + repair = _stamp( + write_mhl(engine.run(card, _options(dest, algorithm="xxh64", + skip_existing=True)), + dest / "A001_Reports" / "JobReport.mhl"), _at(12)) + + reports = verify.verify_tree(dest) + history = _report_for(reports, second) + assert [(v.path.name, v.superseded_by) for v in history.superseded] == [ + ("C002.mov", repair)] + assert not history.failures + assert not history.directory_failures, history.summary() + assert all(r.passed for r in reports), [r.summary() for r in reports] + + def test_a_checksum_from_an_earlier_generation_does_not_answer_a_later_failure( tmp_path): """The other direction. Generation 1 hashed the clip, a later classic From 83ece81ff6dcd9db80b7ec8c7fe41f9219c50b33 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:22:06 -0700 Subject: [PATCH 7/7] Make the job identity fields keyword-only job_identity sat between job_name and thumbnail_dir, so a caller passing ten positional arguments had its thumbnail folder taken for the job's identity and written into the manifest as its name. Both new fields are keyword-only now, and every existing position is what it was. --- docs/data-safety.md | 5 +++++ src/offloader/engine.py | 4 +++- src/offloader/models.py | 3 ++- tests/test_engine.py | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/docs/data-safety.md b/docs/data-safety.md index b42dda8..64830cc 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -286,6 +286,11 @@ Supersession runs one way only: `{card}`, or `--name` reused) still clear each other's folder markers and never-reached entries; entries that record a size and date are protected by them. +- Manifests written by an earlier version of the app recorded the queue's + name, suffix included. Such a manifest stored as `A001-2` is a different + job from `A001` here, so its folder markers and never-reached entries stay + unresolved after a retry on this version. That is the conservative + result: nothing in the old manifest says whether the `-2` was the queue's. - Only a hashed entry that matched can supersede. A later run that could not read the file lists it unhashed, and that entry fails on its own. - "Newer" is the manifest's own recorded time (MHL 1.1 `finishdate`, ASC MHL diff --git a/src/offloader/engine.py b/src/offloader/engine.py index 0315992..565fa4c 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -563,7 +563,9 @@ class OffloadOptions: job_name: str | None = None #: The job's own name when `job_name` was made unique by the queue; see #: `Job.identity`. Leave unset when `job_name` is the name as given. - job_identity: str | None = None + #: Keyword-only, so the fields after it keep the positions they had: a + #: caller passing `thumbnail_dir` tenth must not find it has named a job. + job_identity: str | None = field(default=None, kw_only=True) thumbnail_dir: Path | None = None extra_probe: bool = True #: The workflow this offload is. `Profile.DATA` is a generic large-data diff --git a/src/offloader/models.py b/src/offloader/models.py index 63a6de9..a41c119 100644 --- a/src/offloader/models.py +++ b/src/offloader/models.py @@ -356,7 +356,8 @@ class Job: #: The job's own name, where `name` carries a `-2` the queue added to #: tell two entries for one card apart (`naming.build_with_identity`). #: None when the name was never disambiguated, which is every CLI job. - identity: str | None = None + #: Keyword-only, so the fields after it keep their positions. + identity: str | None = field(default=None, kw_only=True) #: For a selection (a timeline offload), each source's path beneath every #: destination root, as the selector laid it out. Empty for a scanned #: card, whose layout is derived from `source_root`. Needed to say where a diff --git a/tests/test_engine.py b/tests/test_engine.py index 8a6eb50..32482b2 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -547,3 +547,35 @@ def test_data_profile_keeps_tree_order_even_with_proxies_first(proxy_card: Path, proxies_first=True) assert moved == ["C001.braw", "C002.braw", "C003.braw", "C001.mp4", "C002.mp4", "C003.mp4"] + + +def test_the_job_identity_fields_do_not_shift_positional_arguments(tmp_path: Path): + """`job_identity` was added between `job_name` and `thumbnail_dir`. A + caller passing ten positional arguments then found its thumbnail folder + taken for the job's identity, and written into the manifest as its name. + Both new fields are keyword-only, so every position is what it was.""" + import dataclasses + + from offloader.models import Job + + thumbs = tmp_path / "thumbs" + options = engine.OffloadOptions( + [tmp_path / "dst"], "xxh64", VerificationMode.FULL, 0, (), True, False, + True, "A001", thumbs) + assert options.thumbnail_dir == thumbs + assert options.job_name == "A001" + assert options.job_identity is None + + def positional(cls) -> list[str]: + return [f.name for f in dataclasses.fields(cls) if f.init and not f.kw_only] + + assert positional(engine.OffloadOptions)[8:11] == [ + "job_name", "thumbnail_dir", "extra_probe"] + assert "identity" not in positional(Job) + assert "job_identity" not in positional(engine.OffloadOptions) + + card = tmp_path / "A001" + card.mkdir() + (card / "C001.mov").write_bytes(b"clip" * 500) + job = engine.run(card, options) + assert job.name == job.recorded_name == "A001"