diff --git a/CHANGELOG.md b/CHANGELOG.md index dc463e7..d828fc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,13 +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 and never-reached - entries are never superseded. Only an entry with no size or date counts as + same job. 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. +- **A cancel and rerun left an ASC MHL history failing `verify`.** A file a + cancelled job never reached, or a folder that could not be listed, records + no size or date, and a generation recorded no job name to tie the rerun to + it. Each generation now names its job as `Job: ` in + `creatorinfo/comment`, and `verify` uses it inside a history and between a + history and a classic manifest. A generation written before this names no + job, so its entries of that kind still fail. - **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/ascmhl.md b/docs/ascmhl.md index e622674..9a7510e 100644 --- a/docs/ascmhl.md +++ b/docs/ascmhl.md @@ -48,6 +48,17 @@ comparison with the previous generation is per algorithm: hex digests case-insensitively, C4 exactly, so another tool's uppercase hex is not recorded as `failed`. +Each generation names the job that wrote it, as `Job: ` in +`creatorinfo/comment`. The schema has no field for a job, and `comment` is its +free-text one. `verify` reads the name back to tie a rerun to an entry that +records no size or date (a file a cancel never reached, a folder that could not +be listed), so cancelling a job and running it again leaves the history +passing. The name is the job's own: a retry the app's queue shows as `A001-2` +still records `Job: A001`. The convention is only read from a generation whose +`creatorinfo/tool` is Offloader, since `comment` is free text and another +exporter's operator may have typed the same words; and a comment that does not +start with `Job: ` is never read as a name. + ## Directory hashes Each directory gets a `content` and a `structure` hash, and the root gets both @@ -120,7 +131,8 @@ 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. 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 +modification date) or, when it records neither, for a later generation of the +same job; 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). @@ -149,7 +161,7 @@ one reproduces exactly: And the end-to-end check: rebuilding that scenario and diffing the manifest against the one the reference project shipped produces **no differences** beyond -hostname, tool name and file modification times. That test is in +hostname, tool name, the job comment and file modification times. That test is in `tests/test_ascmhl.py` and skips cleanly when the reference tree is not present. Getting there took two corrections worth recording: diff --git a/docs/data-safety.md b/docs/data-safety.md index 64830cc..306e3b1 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -260,9 +260,8 @@ 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. 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. + limit. The same holds inside an ASC MHL history, whose generations each + record the job name as well, and between a history and a classic manifest. - 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 @@ -271,17 +270,18 @@ Supersession runs one way only: 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. Only an entry that records neither is treated as a marker: a failed + so the job name (MHL 1.1 `creatorinfo/name`; in ASC MHL the `Job: ` text + in `creatorinfo/comment`) 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 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 + `Shoot-100` and `Shoot-101` are two jobs. An ASC MHL generation + written before the job name was recorded, or by another tool, names no job: + a marker or never-reached entry in it is never answered and keeps failing + `verify`, and it answers none in other manifests. **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 @@ -336,8 +336,34 @@ any generation lists is judged by the latest generation that lists it: 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. + cancelled job never reached, or a folder marker) has nothing of the source + to compare, so the job name decides: it is dropped for a later generation + that names the same job and lists the path with a hash, or lists hashed + files under the folder and nothing unhashed there. Those files are then + checked like any other. With no job name on either side it stays failing; + see the limit on job names above. +- The record that answers an earlier failure need not be the latest one. When + job A's retry copied a clip and job B later listed the same bytes under its + own name, A's failure is still answered by A's retry, because the retry + recorded the digest the path is checked against now. A record the latest + one disagrees with answers nothing. The same goes for a folder marker: a + retry that listed the folder's files answers it only while every one of + those records still agrees with the latest record of its path, so content + that later replaced one of them puts the marker back. All of this holds + between a history and a classic manifest too: a classic folder marker is + answered by a generation of the same job only while that generation's own + listing of the folder still stands whole, not because some file under the + folder happens to match. Another job's unhashed entry under the folder + does not hold the marker open once that entry has itself been superseded; + files are settled first, then folders. +- For this a report keeps, per path, one earlier record for each distinct + job and source that agrees with the latest record: the one with the latest + recorded time, so a generation with a later number and an earlier date + (two hosts whose clocks disagree) does not hide a repair that is properly + dated. A path listed by twelve differently named jobs carries eleven such + records; listed twelve times by one job, none. +- Failures with no size or date are kept apart by job: two jobs cancelled at + the same path are two failures, and each is answered only by its own job. - 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/ascmhl.py b/src/offloader/ascmhl.py index 12b4011..924f962 100644 --- a/src/offloader/ascmhl.py +++ b/src/offloader/ascmhl.py @@ -45,6 +45,31 @@ _MANIFEST_PATTERN = re.compile(r"^(\d{4,})_.*\.mhl$", re.IGNORECASE) +#: How a generation names the job that wrote it, in `creatorinfo/comment`. +#: The schema has no field for a job; `comment` is its free-text one. `verify` +#: reads the name back, because it is the only thing that ties a rerun to an +#: entry that records no size or date (a file a cancelled job never reached, +#: a folder that could not be listed). +JOB_COMMENT_PREFIX = "Job: " + + +def job_name_from(root: ET.Element) -> str | None: + """The job name an ASC MHL generation records, or None. + + None for a manifest another tool wrote, or one written before the name + was recorded. `comment` is ordinary free text, and an operator of some + other exporter may well have typed `Job: A001` into it, so the convention + is only read from a generation whose `creatorinfo/tool` is this tool. A + comment that does not start with the prefix is never taken for a name. + """ + creator = f"{{{NAMESPACE}}}creatorinfo/{{{NAMESPACE}}}" + if (root.findtext(f"{creator}tool") or "").strip() != PRODUCT_NAME: + return None + text = root.findtext(f"{creator}comment") or "" + if not text.startswith(JOB_COMMENT_PREFIX): + return None + return text[len(JOB_COMMENT_PREFIX):].strip() or None + def _utc(when: _dt.datetime | float) -> _dt.datetime: if isinstance(when, (int, float)): @@ -379,6 +404,11 @@ def write_manifest(job: Job, root: Path, *, destination_index: int = 0, ET.SubElement(creator, "creationdate").text = _iso(moment) ET.SubElement(creator, "hostname").text = platform.node() ET.SubElement(creator, "tool", {"version": __version__}).text = PRODUCT_NAME + if job.recorded_name and job.recorded_name.strip(): + # After `tool`, where the schema's sequence puts it. The job's own + # name, not the queue's `-2` variant of it: `Job.recorded_name`. + ET.SubElement(creator, "comment").text = ( + JOB_COMMENT_PREFIX + job.recorded_name) info = ET.SubElement(manifest, "processinfo") ET.SubElement(info, "process").text = process diff --git a/src/offloader/verify.py b/src/offloader/verify.py index 63e4beb..3ce5537 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -33,6 +33,7 @@ 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 .ascmhl import job_name_from as ascmhl_job_name from .engine import DEFAULT_EXCLUDES, is_excluded from .hashers import ALGORITHMS, get_algorithm, hash_file from .integrity import evict_from_cache @@ -73,6 +74,11 @@ class FileVerdict: #: the generation being verified does not list the file. `None` for an #: entry of the manifest itself. recorded_in: Path | None = None + #: Earlier generations of the same history that recorded the digest this + #: entry was checked against, where they differ from `recorded_in` in job + #: or source facts. A match on disk is evidence for each of them too, so + #: `supersede` can credit a retry whose record a later job's replaced. + agreed_by: tuple[_Witness, ...] = () @property def ok(self) -> bool: @@ -169,9 +175,17 @@ 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. + #: The job name the manifest records (MHL 1.1 `creatorinfo/name`, the + #: `Job: ` comment of an ASC MHL generation), or `None`. job_name: str | None = None + #: For an ASC MHL history: each generation that names a job -> the + #: folders it lists files under whose hashes still stand, and the folders + #: it lists anything else under (see `_earlier_generation_entries`). What + #: `supersede` needs to tell whether a generation still accounts for a + #: folder another manifest could only mark. Folder names only, shared + #: between generations that list the same ones. + listings: dict[Path, tuple[frozenset[str], frozenset[str]]] = field( + default_factory=dict) @property def checked(self) -> int: @@ -391,12 +405,16 @@ def verify_manifest( """ manifest = Path(manifest) entries = list(_entries(manifest)) + #: Path -> earlier generations that agree with its latest record. + witnesses: dict[str, list[_Witness]] = {} 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) + history = _earlier_generation_entries(manifest, entries) + entries += history.entries + witnesses = history.witnesses # 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. @@ -431,6 +449,8 @@ def verify_manifest( else _described_root(manifest, listed)) report.recorded_at = _recorded_at(manifest) report.job_name = _recorded_job_name(manifest) + if parsed is not None: + report.listings = history.listings ascmhl_root = parsed if check_directories else None recorded: dict[str, tuple[str, str]] = {} if ascmhl_root is not None: @@ -484,7 +504,8 @@ def _evict(path: Path) -> None: path, algorithm_key, expected = entry.path, entry.algorithm, entry.digest as_recorded = dict(expected_size=entry.size, expected_modified=entry.modified, - recorded_in=entry.recorded_in) + recorded_in=entry.recorded_in, + agreed_by=tuple(witnesses.get(_entry_key(path), ()))) if progress: progress(index, len(entries), path) @@ -786,7 +807,18 @@ def _earlier_generations(manifest: Path) -> list[Path]: return earlier -def _earlier_generation_entries(manifest: Path, own: list[_Entry]) -> list[_Entry]: +class _History(NamedTuple): + """What `_earlier_generation_entries` learned from a history.""" + + #: Entries of earlier generations to check with the manifest's own. + entries: list[_Entry] + #: Path -> the earlier records that agree with its latest one. + witnesses: dict[str, tuple[_Witness, ...]] + #: Generation -> its folder evidence, see `VerifyReport.listings`. + listings: dict[Path, tuple[frozenset[str], frozenset[str]]] + + +def _earlier_generation_entries(manifest: Path, own: list[_Entry]) -> _History: """What earlier generations of an ASC MHL history record and `manifest` does not, the latest record of each path. @@ -805,24 +837,100 @@ def _earlier_generation_entries(manifest: Path, own: list[_Entry]) -> list[_Entr 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. + entry stays, and fails, beside it. + + An earlier failure that records no size or date has nothing of the source + to compare. It is a file a cancelled job never reached, or a marker for a + folder that could not be listed, and the job name each generation records + (`ascmhl.job_name_from`) is what ties a rerun to it, as it is between + classic manifests in `supersede`. It is dropped for a later generation + that names the same job and lists the same path with a hash, or lists + hashed files under the folder and nothing unhashed there. A generation + with no job name (another tool's, or one written before the name was + recorded) answers nothing this way, and nothing answers it. + + The record that answers a failure need not be the latest one. Job A's + retry copies the clip its cancelled run never reached; job B later lists + the same file, byte for byte, under its own name. B's is now the latest + record of the path, and A's failure is still answered by A's retry, + because the retry recorded the digest the path is being checked against. + A record the latest one disagrees with answers nothing: what it described + is no longer what is at the path. That holds for a folder marker as well: + a retry that listed the folder's files answers the marker only while + every one of those records still agrees with the latest record of its + path. Once later content has replaced a file the retry listed, the retry + is no evidence about the folder any more, and the marker stands. + + Of the records that agree with the latest one, one is kept per path for + each distinct job and source (`FileVerdict.agreed_by`): the one with the + latest recorded time, since `supersede` orders evidence by that time and + a generation with a later number can carry an earlier date when two + hosts' clocks disagree. So a path listed by twelve differently named + jobs carries eleven, and one listed twelve times by the same job none. + + Failures are told apart by job as well as by path. Two jobs cancelled at + one path are two failures, each answered by its own rerun; folded into + one line, whichever job was repaired cleared the only record of both. + + Only a record per path and a set of folders per job is kept while + reading, never a generation's whole list: a history of many generations + that all list the same files costs what one of them does. An earlier generation that cannot be read is an error, never skipped: it may be the only record of a failure. """ + root_key = _entry_key(manifest.parent.parent) + own_job = _recorded_job_name(manifest) + #: Generation (None for `manifest` itself) -> the job it names. + jobs: dict[Path | None, str | None] = {None: own_job} + #: Generation -> when it says it was written. + moments: dict[Path | None, _dt.datetime | None] = { + None: _recorded_at(manifest)} #: Path -> the record it is judged by, the latest one. latest: dict[str, _Entry] = {} + #: Path -> earlier hashed records that agree with the latest on the + #: digest, by (job, size, date): who else recorded what is at the path + #: now. One per identity, the one with the latest recorded time. + repairs: dict[str, dict[_Identity, _Witness]] = {} + #: Generation -> its folder evidence, for the caller. + evidence: dict[Path, tuple[frozenset[str], frozenset[str]]] = {} + #: So generations listing the same folders share one set. + shared: dict[frozenset[str], frozenset[str]] = {} + #: (job, folders it lists files under whose hashes still stand, folders + #: it lists anything else under), for the generations read so far. A hash + #: stands while the latest record of its path agrees with it. + listings: set[tuple[str, frozenset[str], frozenset[str]]] = set() #: Failures already reported, so one source failing in three generations #: is one line. - failed: set[tuple[str, int | None, _dt.datetime | None]] = set() + failed: set[tuple[str, int | None, _dt.datetime | None, str | None]] = set() + + def mark(key: str, entry: _Entry, job: str | None, + ) -> tuple[str, int | None, _dt.datetime | None, str | None]: + # An entry with a size and date is its source, whoever listed it. + # One with neither is only told apart by the job. + return (key, entry.size, entry.modified, + (job or "").casefold() if _nameless(entry) else None) + + def listed(generation: Path, job: str | None, hashed_in: set[str], + unhashed_in: set[str]) -> None: + if job: + pair = tuple(shared.setdefault(folders, folders) for folders in + (frozenset(hashed_in), frozenset(unhashed_in))) + evidence[generation] = pair + listings.add((job.casefold(), *pair)) + + hashed_in: set[str] = set() + unhashed_in: set[str] = set() for entry in own: key = _entry_key(entry.path) - latest.setdefault(key, entry) + judged = latest.setdefault(key, entry) + if own_job: + _add_folders(key, hashed_in if _stands(entry, judged) + else unhashed_in, root_key) if not _hashed(entry): - failed.add((key, entry.size, entry.modified)) + failed.add(mark(key, entry, own_job)) + listed(manifest, own_job, hashed_in, unhashed_in) + found: list[_Entry] = [] for generation in reversed(_earlier_generations(manifest)): try: @@ -833,28 +941,158 @@ def _earlier_generation_entries(manifest: Path, own: list[_Entry]) -> list[_Entr if root.tag != f"{{{ASCMHL_NAMESPACE}}}hashlist": raise ValueError(f"earlier generation {generation.name} of this " "history is not an ASC MHL manifest") + job = jobs[generation] = ascmhl_job_name(root) + moment = moments[generation] = _recorded_at_root(root) + hashed_in, unhashed_in = set(), set() for entry in _ascmhl_entries(generation, root): key = _entry_key(entry.path) - entry = entry._replace(recorded_in=generation) judged = latest.get(key) + if job: + _add_folders(key, hashed_in if _stands(entry, judged or entry) + else unhashed_in, root_key) + if _hashed(entry): + if judged is None: + entry = entry._replace(recorded_in=generation) + latest[key] = entry + found.append(entry) + elif _hashed(judged) and _same_digest(entry, judged): + # A hash a later generation replaced with the same one: + # the later record is what the path is checked against, + # and this one says who else vouched for those bytes. + # One per job and source. Of two alike, the one with + # the later recorded time, and a record like the latest + # one only when it is dated after it. + identity = _identity(job, entry) + rival = repairs.get(key, {}).get(identity) + if rival is not None: + wanted = _later(moment, rival.moment) + elif identity == _identity(jobs[judged.recorded_in], judged): + wanted = _later(moment, moments[judged.recorded_in]) + else: + wanted = True + if wanted: + repairs.setdefault(key, {})[identity] = _Witness( + job, entry.size, entry.modified, generation, moment) + continue + 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. + if _nameless(entry) and _folder_listed(key, job, listings): + continue + latest[key] = entry = entry._replace(recorded_in=generation) + elif _hashed(judged) and any( + _answers(witness, entry, job) for witness in ( + _Witness(jobs[judged.recorded_in], judged.size, + judged.modified, judged.recorded_in), + *repairs.get(key, {}).values())): continue - elif _hashed(judged) and _same_facts(entry.size, entry.modified, - judged.size, judged.modified): + else: + entry = entry._replace(recorded_in=generation) + marked = mark(key, entry, job) + if marked in failed: continue - if not _hashed(entry): - mark = (key, entry.size, entry.modified) - if mark in failed: - continue - failed.add(mark) + failed.add(marked) found.append(entry) - return found + # Only now: a marker is answered by a later generation, never by the + # one it is in. + listed(generation, job, hashed_in, unhashed_in) + return _History(found, + {key: tuple(kept.values()) for key, kept in repairs.items()}, + evidence) + + +#: (job, size, date) of a hashed record: what it can answer a failure by. +_Identity = tuple[str, "int | None", "_dt.datetime | None"] + + +def _identity(job: str | None, entry: _Entry) -> _Identity: + return ((job or "").casefold(), entry.size, entry.modified) + + +def _later(moment: _dt.datetime | None, than: _dt.datetime | None) -> bool: + """Whether `moment` is known to be after `than`. A record with no date is + never preferred; one with a date is preferred to one without.""" + if moment is None: + return False + if than is None: + return True + try: + return moment > than + except TypeError: # one carries a UTC offset, the other does not + return False + + +class _Witness(NamedTuple): + """A hashed record of a path, as far as it can answer an earlier failure: + the job that wrote it, the source facts it recorded, and the generation + it is in (None for the generation being verified).""" + + job: str | None + size: int | None + modified: _dt.datetime | None + recorded_in: Path | None = None + #: When that generation says it was written. + moment: _dt.datetime | None = None +def _stands(entry: _Entry, judged: _Entry) -> bool: + """Whether `entry`'s hash is still the record of what is at its path: + it has one, and the latest record of the path (`judged`, which may be + the entry itself) has the same one.""" + if not _hashed(entry): + return False + return judged is entry or (_hashed(judged) and _same_digest(entry, judged)) + + +def _answers(witness: _Witness, failure: _Entry, job: str | None) -> bool: + """Whether a hashed record answers an earlier unhashed one of its path: + the same source file, or, when the failure records nothing of its source, + the same job.""" + return (_same_facts(failure.size, failure.modified, + witness.size, witness.modified) + or (_nameless(failure) and _same_job(job, witness.job))) + + +def _nameless(entry: _Entry) -> bool: + """Unhashed, with no size and no date: a file a cancelled job never + reached, or a folder marker.""" + return (not _hashed(entry) and entry.size is None + and entry.modified is None) + + +def _same_digest(a: _Entry, b: _Entry) -> bool: + if a.algorithm != b.algorithm or not a.algorithm: + return False + try: + return get_algorithm(a.algorithm).digests_match(a.digest, b.digest) + except (KeyError, ValueError): + return False + + +def _add_folders(key: str, into: set[str], stop: str) -> None: + """Add every folder above the entry at `key`, up to the history's root. + Stops at a folder already there, whose own ancestors were added with it.""" + folder = os.path.dirname(key) + while len(folder) >= len(stop) and folder not in into: + into.add(folder) + above = os.path.dirname(folder) + if above == folder: + break + folder = above + + +def _folder_listed(folder_key: str, job: str | None, + listings: set[tuple[str, frozenset[str], frozenset[str]]], + ) -> bool: + """Whether a later generation of the same job lists the inside of a folder + an earlier one could only mark: at least one hashed file under it, and + nothing unhashed. Those files are then checked like any other.""" + if not job: + return False + folder, name = folder_key.rstrip(os.sep), job.casefold() + return any(listed_by == name and folder in hashed_in + and folder not in unhashed_in + for listed_by, hashed_in, unhashed_in in listings) + def _hashed(entry: _Entry) -> bool: return bool(entry.algorithm and entry.digest) @@ -903,6 +1141,11 @@ def _recorded_at(manifest: Path) -> _dt.datetime | None: root = ET.parse(manifest).getroot() except (OSError, ET.ParseError): return None + return _recorded_at_root(root) + + +def _recorded_at_root(root: ET.Element) -> _dt.datetime | None: + """`_recorded_at` for a manifest that is already parsed.""" prefix = (f"{{{ASCMHL_NAMESPACE}}}" if root.tag == f"{{{ASCMHL_NAMESPACE}}}hashlist" else "") info = root.find(f"{prefix}creatorinfo") @@ -918,18 +1161,19 @@ def _recorded_at(manifest: Path) -> _dt.datetime | None: def _recorded_job_name(manifest: Path) -> str | None: - """The job name a classic manifest records in `creatorinfo/name`. + """The job name a manifest records: `creatorinfo/name` in a classic one, + the `Job: ` comment in an ASC MHL generation (`ascmhl.job_name_from`). - 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. + None when it records none. A generation written before the name was + recorded, or by another tool, 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 + return ascmhl_job_name(root) name = (root.findtext("creatorinfo/name") or "").strip() return name or None @@ -1048,9 +1292,9 @@ def _records_nothing(entry: FileVerdict) -> bool: 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. A manifest with no - job name (every ASC MHL one) matches nothing. +def _same_job(a: str | None, b: str | None) -> bool: + """Two recorded job names are the same job, ignoring case. A manifest + that records no job name 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 @@ -1058,22 +1302,53 @@ def _same_job(a: VerifyReport, b: VerifyReport) -> bool: 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: + if not a or not b: return False - return a.job_name.casefold() == 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. - - At least one hashed file must match, and nothing it lists under the folder - may be anything but a match: an unhashed, missing, mismatched or - unreadable entry there means the folder is still not accounted for. + return a.casefold() == b.casefold() + + +def _folder_answered(folder_key: str, newer: VerifyReport, + counts: Callable[[Path], bool]) -> Path | None: + """The manifest that answers a folder marker from `newer`, or None. + + Everything `newer` lists under the folder must be accounted for: matched + now, or an unhashed entry that has itself been superseded. A missing, + mismatched or unreadable entry there, or an unhashed one nothing has + answered, means the folder is not; and at least one file must have + matched. And a manifest that `counts`, that is, one that names the + marker's job and was written after it, must be what accounts for it. + + The superseded entries matter in a history, whose report holds every + job's records. Job B failing to read its own clip in the folder, and + repairing it, leaves an unhashed entry there that B's repair answers. + That entry is settled, and is no reason to take back the credit job A's + retry earned for the folder. So `supersede` settles files before + folders. + + For a classic manifest that is the manifest itself. An ASC MHL report + lists files from every generation of its history, and a file matching + now says nothing about which generation it is evidence for. So there the + answer is a generation that counts and whose own listing of the folder + still stands whole (`VerifyReport.listings`): it lists hashed files + under the folder, and every one of them is still the latest record of + its path. A retry that listed two clips, one of which later content has + replaced, no longer accounts for the folder, though its other clip still + matches. """ prefix = folder_key.rstrip(os.sep) + os.sep under = [v for v in newer.verdicts if _entry_key(v.path).startswith(prefix)] - return bool(under) and all(v.result is EntryResult.OK and v.expected - for v in under) + matched = [v for v in under if v.result is EntryResult.OK and v.expected] + settled = [v for v in under if v.result is EntryResult.NO_CHECKSUM + and v.superseded_by is not None] + if not matched or len(matched) + len(settled) != len(under): + return None + if not newer.listings: + return newer.manifest if counts(newer.manifest) else None + folder = folder_key.rstrip(os.sep) + for generation, (standing, other) in newer.listings.items(): + if folder in standing and folder not in other and counts(generation): + return generation + return None def supersede(reports: list[VerifyReport]) -> None: @@ -1108,11 +1383,12 @@ def supersede(reports: list[VerifyReport]) -> None: 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. 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. 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. + manifests must also name the same job (`_same_job`); a manifest that + records no job name (an ASC MHL generation written before the name was + recorded, or by another tool) answers no marker and has none answered. + 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 @@ -1121,44 +1397,91 @@ def supersede(reports: list[VerifyReport]) -> None: 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. + that recorded the answer. The job name is read the same way, from the + manifest that recorded each entry. + + Entries of one ASC MHL history never answer each other here: that is + settled when the history is read, by `_earlier_generation_entries`. """ moments: dict[Path, _dt.datetime | None] = { report.manifest: report.recorded_at for report in reports} + jobs: dict[Path, str | None] = { + report.manifest: report.job_name 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] - if not pending: - continue - for newer in reports: - if newer is older or not _same_root(newer, older): + def job_of(manifest: Path) -> str | None: + if manifest not in jobs: + jobs[manifest] = _recorded_job_name(manifest) + return jobs[manifest] + + def sweep(folders: bool) -> bool: + """One pass over every pair of reports, answering files or folder + markers. Returns whether anything was superseded.""" + changed = False + for older in reports: + pending = [v for v in older.verdicts + if v.result is EntryResult.NO_CHECKSUM + and v.superseded_by is None] + if not pending: 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: + for newer in reports: + if newer is older or not _same_root(newer, older): continue - failed_in = verdict.recorded_in or older.manifest - key = _entry_key(verdict.path) - answer = matched.get(key) - if answer is not None: - answered_in = answer.recorded_in or newer.manifest - if not _is_newer(answered_in, failed_in, when): + matched = {_entry_key(v.path): v for v in newer.verdicts + if v.result is EntryResult.OK and v.expected} + for verdict in pending: + if verdict.superseded_by is not None: 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 + failed_in = verdict.recorded_in or older.manifest + + def same_job_later(manifest: Path, + failed_in: Path = failed_in) -> bool: + return (_same_job(job_of(failed_in), job_of(manifest)) + and _is_newer(manifest, failed_in, when)) + + key = _entry_key(verdict.path) + answer = matched.get(key) + if folders: + if answer is None and _records_nothing(verdict): + verdict.superseded_by = _folder_answered( + key, newer, same_job_later) + elif answer is not None: + # The record the file was checked against, then any + # earlier generation that recorded the same digest: + # job A's retry still answers A's failure after job B + # listed the same bytes and became the latest record. + candidates = [ + (answer.recorded_in or newer.manifest, + answer.expected_size, answer.expected_modified), + *((w.recorded_in, w.size, w.modified) + for w in answer.agreed_by + if w.recorded_in is not None)] + for answered_in, size, modified in candidates: + if _same_facts(verdict.expected_size, + verdict.expected_modified, + size, modified): + if _is_newer(answered_in, failed_in, when): + verdict.superseded_by = answered_in + break + elif (_records_nothing(verdict) + and same_job_later(answered_in)): + verdict.superseded_by = answered_in + break + changed = changed or verdict.superseded_by is not None + return changed + + # Files first. A folder is accounted for only when everything listed + # under it is, and an unhashed file there may be answered by a manifest + # that comes later in the list than the one being asked about the + # folder. Then folders, until nothing changes: a marker can sit under + # another marker's folder. + sweep(folders=False) + while sweep(folders=True): + pass def verify_tree(root: Path, **options) -> list[VerifyReport]: diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py index 639301d..6e53dd8 100644 --- a/tests/test_ascmhl.py +++ b/tests/test_ascmhl.py @@ -703,6 +703,8 @@ def test_manifest_is_identical_to_the_reference_implementations(tmp_path: Path): def normalise(text: str) -> str: text = re.sub(r"[^<]*", "H", text) text = re.sub(r'[^<]*', "T", text) + # The job name this tool adds; the reference names no job. + text = re.sub(r"\s*Job: [^<]*", "", text) return re.sub(r'lastmodificationdate="[^"]*"', 'lastmodificationdate="M"', text).strip() diff --git a/tests/test_verdict_integrity.py b/tests/test_verdict_integrity.py index 67c44d1..dfa6755 100644 --- a/tests/test_verdict_integrity.py +++ b/tests/test_verdict_integrity.py @@ -1068,14 +1068,77 @@ def test_a_folder_marker_is_superseded_only_by_the_same_job( 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): +def _set_comment(manifest: Path, text: str | None) -> None: + """Rewrite an ASC MHL generation's `creatorinfo/comment`; None removes it, + which is what a generation written before the job name was recorded, or + by another tool, looks like.""" + namespace = f"{{{ascmhl.NAMESPACE}}}" + tree = ET.parse(manifest) + creator = tree.getroot().find(f"{namespace}creatorinfo") + comment = creator.find(f"{namespace}comment") + if text is None: + creator.remove(comment) + else: + comment.text = text + tree.write(manifest, encoding="utf-8", xml_declaration=True) + + +def test_the_job_name_comes_from_either_kind_of_manifest(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 == "A001" + + # The schema's CreatorInfoType is a sequence, so the order is part of it: + # creationdate, hostname, tool, author*, location?, comment?. + creator = ET.parse(history).getroot().find( + f"{{{ascmhl.NAMESPACE}}}creatorinfo") + assert [child.tag.split("}")[1] for child in creator] == [ + "creationdate", "hostname", "tool", "comment"] + assert creator[-1].text == "Job: A001" + + +def test_another_tools_comment_is_never_read_as_a_job_name(tmp_path): + """`comment` is free text. An operator of some other exporter typing + `Job: A001` into it has not named a job in this tool's sense, and + reading it as one would change how that tool's histories verify.""" + card = _card(tmp_path, {"C001.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + history = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest) + assert verify.verify_manifest(history).job_name == "A001" + + namespace = f"{{{ascmhl.NAMESPACE}}}" + tree = ET.parse(history) + tool = tree.getroot().find(f"{namespace}creatorinfo/{namespace}tool") + tool.text = "Some Other Exporter" + tree.write(history, encoding="utf-8", xml_declaration=True) + assert ET.parse(history).getroot().findtext( + f"{namespace}creatorinfo/{namespace}comment") == "Job: A001" + assert verify.verify_manifest(history).job_name is None + + +def test_a_generation_records_the_jobs_own_name_not_the_queues(tmp_path): + card = _card(tmp_path, {"C001.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + job = engine.run(card, _options(dest, algorithm="xxh64", + job_name="A001-2", job_identity="A001")) + assert job.name == "A001-2" + assert verify.verify_manifest(ascmhl.write_manifest(job, dest)).job_name == "A001" + + +@pytest.mark.parametrize("comment", [ + None, "", "shot on the B camera", "job: A001", "Job:", "Job: ", + "see Job: A001"]) +def test_a_comment_that_is_not_this_tools_names_no_job(tmp_path, comment): + card = _card(tmp_path, {"C001.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + history = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest) + _set_comment(history, comment) assert verify.verify_manifest(history).job_name is None @@ -1235,12 +1298,12 @@ def test_a_different_cards_clip_does_not_answer_an_earlier_generations_failure( 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`.""" +# ------------- the job name a generation records ties a rerun to its job + + +def _cancelled_before_c002(tmp_path: Path): + """A job cancelled before its second file, as it stands afterwards: no + destination record for C002 and the file itself absent.""" card = _card(tmp_path, {"C001.mov": os.urandom(2000), "C002.mov": os.urandom(2000)}) dest = tmp_path / "dst" @@ -1248,9 +1311,48 @@ def test_a_history_cannot_tie_a_rerun_to_a_file_a_cancelled_job_never_reached( cancelled.not_attempted = [card / "C002.mov"] cancelled.files = [f for f in cancelled.files if f.source.name == "C001.mov"] (dest / "C002.mov").unlink() + return card, dest, cancelled + + +def _skipping_alias(monkeypatch) -> None: + real = engine._is_directory_link + monkeypatch.setattr(engine, "_is_directory_link", + lambda path: Path(path).name == "Alias" or real(path)) + + +def test_cancel_then_rerun_leaves_an_ascmhl_history_verified(tmp_path, capsys): + """A never-reached entry records no size or date. A generation recorded + no job name either, so nothing tied the rerun's file to it and the + history failed `verify` for good after an ordinary cancel and rerun.""" + card, dest, cancelled = _cancelled_before_c002(tmp_path) first = ascmhl.write_manifest(cancelled, dest, when=_at(10)) + assert [(v.path.name, v.result) for v in + verify.verify_manifest(first).failures] == [ + ("C002.mov", verify.EntryResult.NO_CHECKSUM)] + ascmhl.write_manifest(engine.run(card, _options(dest, algorithm="xxh64")), dest, when=_at(11)) + report = verify.verify_manifest(_only_history(dest)) + assert report.passed, report.summary() + assert sorted(v.path.name for v in report.verdicts) == ["C001.mov", "C002.mov"] + assert cli.main(["verify", str(dest), "--quiet"]) == 0 + capsys.readouterr() + + +@pytest.mark.parametrize("change", [ + "another job", "the cancelled run names no job", "the rerun names no job"]) +def test_a_never_reached_file_in_a_history_is_answered_only_by_its_own_job( + tmp_path, change): + card, dest, cancelled = _cancelled_before_c002(tmp_path) + first = ascmhl.write_manifest(cancelled, dest, when=_at(10)) + rerun = engine.run(card, _options( + dest, algorithm="xxh64", + job_name="B001" if change == "another job" else None)) + second = ascmhl.write_manifest(rerun, dest, when=_at(11)) + if change == "the cancelled run names no job": + _set_comment(first, None) + if change == "the rerun names no job": + _set_comment(second, None) report = verify.verify_manifest(_only_history(dest)) assert [(v.path.name, v.result, v.recorded_in.name) @@ -1258,6 +1360,440 @@ def test_a_history_cannot_tie_a_rerun_to_a_file_a_cancelled_job_never_reached( ("C002.mov", verify.EntryResult.NO_CHECKSUM, first.name)] +@pytest.mark.parametrize("rerun_name, rerun_identity, passes", [ + (None, None, True), + ("A001-2", "A001", True), # the queue's name for a retry of A001 + ("A001-2", None, False), # a job really called that is another job + ("B001", None, False), +]) +def test_a_folder_marker_in_a_history_is_answered_by_a_rerun_of_its_job( + tmp_path, monkeypatch, rerun_name, rerun_identity, passes): + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(3000), + "Alias/C002.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _skipping_alias(patch) + skipped = engine.run(card, _options(dest, algorithm="xxh64")) + first = ascmhl.write_manifest(skipped, dest, when=_at(10)) + assert [v.path.name for v in verify.verify_manifest(first).failures] == [ + "Alias"] + + rerun = engine.run(card, _options(dest, algorithm="xxh64", + job_name=rerun_name, + job_identity=rerun_identity)) + ascmhl.write_manifest(rerun, dest, when=_at(11)) + report = verify.verify_manifest(_only_history(dest)) + assert report.passed is passes, report.summary() + assert [v.path.name for v in report.failures] == ([] if passes else ["Alias"]) + + +def test_a_folder_marker_in_a_history_stays_while_the_rerun_lists_a_failure( + tmp_path, monkeypatch): + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(3000), + "Alias/C002.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _skipping_alias(patch) + skipped = engine.run(card, _options(dest, algorithm="xxh64")) + ascmhl.write_manifest(skipped, dest, when=_at(10)) + (card / "Alias" / "C003.mov").write_bytes(os.urandom(1500)) + with monkeypatch.context() as patch: + _fail_reads_of(patch, "C003.mov") + rerun = engine.run(card, _options(dest, algorithm="xxh64")) + ascmhl.write_manifest(rerun, dest, when=_at(11)) + + report = verify.verify_manifest(_only_history(dest)) + assert sorted(v.path.name for v in report.failures) == ["Alias", "C003.mov"] + + +def _cancel_before_c002(job, card: Path, dest: Path): + """Make a finished job look as it would had it been cancelled before + C002: no destination record for the file, and the file itself absent.""" + job.not_attempted = [card / "C002.mov"] + job.files = [f for f in job.files if f.source.name == "C001.mov"] + (dest / "C002.mov").unlink() + return job + + +def test_a_retry_still_answers_after_another_job_lists_the_same_bytes(tmp_path): + """Job A is cancelled, A's retry copies the clip, and the history + passes. Job B then lists the same files with the same checksums. B's is + now the latest record of the path, and comparing A's failure with the + latest record alone brought the repaired `no hash` back.""" + card, dest, cancelled = _cancelled_before_c002(tmp_path) + ascmhl.write_manifest(cancelled, dest, when=_at(10)) + ascmhl.write_manifest(engine.run(card, _options(dest, algorithm="xxh64")), + dest, when=_at(11)) + assert verify.verify_manifest(_only_history(dest)).passed + + ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64", job_name="B001")), + dest, when=_at(12)) + report = verify.verify_manifest(_only_history(dest)) + assert report.passed, report.summary() + assert sorted(v.path.name for v in report.verdicts) == ["C001.mov", "C002.mov"] + + +def test_a_retry_another_job_then_overwrote_no_longer_answers(tmp_path): + """The other side of it: when job B's file at the path is a different + one, A's retry described bytes that are no longer there.""" + card, dest, cancelled = _cancelled_before_c002(tmp_path) + first = ascmhl.write_manifest(cancelled, dest, when=_at(10)) + ascmhl.write_manifest(engine.run(card, _options(dest, algorithm="xxh64")), + dest, when=_at(11)) + other = _card(tmp_path, {"C002.mov": os.urandom(2500)}, name="B001") + replaced = engine.run(other, _options(dest, algorithm="xxh64", + replace_existing=True)) + assert replaced.final_status == "Verified" + ascmhl.write_manifest(replaced, dest, when=_at(12)) + + # The writer labels a hash that differs from the previous generation's + # `failed`, so the newest record of the path fails on its own account; + # and job A's never-reached entry is still there beside it, unanswered. + report = verify.verify_manifest(_only_history(dest)) + assert sorted((v.path.name, v.result, + v.recorded_in.name if v.recorded_in else "") + for v in report.failures) == [ + ("C002.mov", verify.EntryResult.NO_CHECKSUM, ""), + ("C002.mov", verify.EntryResult.NO_CHECKSUM, first.name)] + + +def test_two_jobs_cancelled_at_one_path_are_two_failures(tmp_path): + """Jobs A and B are each cancelled before the same path. Reported as one + line, repairing B cleared the only record there was, and A's clip passed + without ever having been copied.""" + card, dest, cancelled = _cancelled_before_c002(tmp_path) + first = ascmhl.write_manifest(cancelled, dest, when=_at(10)) + second = ascmhl.write_manifest( + _cancel_before_c002( + engine.run(card, _options(dest, algorithm="xxh64", job_name="B001")), + card, dest), + dest, when=_at(11)) + + report = verify.verify_manifest(second) + assert sorted((v.path.name, v.recorded_in.name if v.recorded_in else "") + for v in report.failures) == [ + ("C002.mov", ""), ("C002.mov", first.name)] + + # B's retry, as a classic manifest, answers B's entry and not A's. + repair = _stamp( + write_mhl(engine.run(card, _options(dest, algorithm="xxh64", + job_name="B001")), + dest / "B001_Reports" / "JobReport.mhl"), _at(12)) + history = _report_for(verify.verify_tree(dest), second) + assert [(v.recorded_in, v.superseded_by) for v in history.superseded] == [ + (None, repair)] + assert [(v.path.name, v.recorded_in.name) for v in history.failures] == [ + ("C002.mov", first.name)] + + # And B's retry as a third generation leaves A's failure standing too. + third = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64", job_name="B001")), + dest, when=_at(13)) + assert [(v.path.name, v.recorded_in.name) + for v in verify.verify_manifest(third).failures] == [ + ("C002.mov", first.name)] + + +def test_reading_a_history_keeps_no_generations_whole_list(tmp_path, monkeypatch): + """Twelve generations listing the same files answer nothing between + them, so nothing of the earlier ones is worth keeping: reading them must + not hold on to every record of every generation.""" + card = _card(tmp_path, {f"Clips/C{n:03d}.mov": os.urandom(64) + for n in range(40)}) + dest = tmp_path / "dst" + for hour in range(12): + ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest, + when=_at(hour)) + + import gc + + class Tracked(verify._Entry): + """An entry that can be told apart from any other tuple.""" + + #: How many entries were still alive as each generation began to be read. + alive: list[int] = [] + real = verify._ascmhl_entries + + def tracking(manifest, root): + gc.collect() + alive.append(sum(isinstance(o, Tracked) for o in gc.get_objects())) + for entry in real(manifest, root): + yield Tracked(*entry) + + monkeypatch.setattr(verify, "_ascmhl_entries", tracking) + newest = _only_history(dest) + own = list(verify._entries(newest)) + history = verify._earlier_generation_entries(newest, own) + assert (history.entries, history.witnesses) == ([], {}) + # Twelve generations of one job listing the same folders: one pair of + # folder sets, shared. + assert len(history.listings) == 12 + assert len({id(pair[0]) for pair in history.listings.values()}) == 1 + # The newest generation's own list is the caller's. Nothing of the + # generations already read is still held when the next one is opened. + assert len(alive) == 12 + # (One more for the last entry read, still in the reader's hand.) + assert max(alive) <= len(own) + 1 + + +def test_a_folder_marker_stands_once_the_retrys_file_has_been_replaced( + tmp_path, monkeypatch): + """Generation 1 could only mark `Alias`. Job A's retry lists the file in + it, which answers the marker. Later content then replaces that file under + a hash of its own, and the retry's record of it is gone from the view: + the retry was still credited with the folder, on a checksum nothing + checks any more.""" + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(3000), + "Alias/C002.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _skipping_alias(patch) + skipped = engine.run(card, _options(dest, algorithm="xxh64")) + first = ascmhl.write_manifest(skipped, dest, when=_at(10)) + ascmhl.write_manifest(engine.run(card, _options(dest, algorithm="xxh64")), + dest, when=_at(11)) + assert verify.verify_manifest(_only_history(dest)).passed + + other = _card(tmp_path, {"Alias/C002.mov": os.urandom(2600)}, name="B001") + third = ascmhl.write_manifest( + engine.run(other, _options(dest, algorithm="xxh64", + replace_existing=True)), + dest, when=_at(12)) + # This tool's writer labels a hash that differs from the last generation's + # `failed`. Another tool's generation, or a file deliberately replaced, + # records it as a hash in good standing, which is the case that matters. + namespace = f"{{{ascmhl.NAMESPACE}}}" + tree = ET.parse(third) + (replaced,) = [node for node in tree.getroot().iter(f"{namespace}xxh64") + if node.get("action") == "failed"] + replaced.set("action", "original") + tree.write(third, encoding="utf-8", xml_declaration=True) + + report = verify.verify_manifest(third) + assert [(v.path.name, v.result) for v in report.verdicts + if v.path.name == "C002.mov"] == [("C002.mov", verify.EntryResult.OK)] + assert [(v.path.name, v.recorded_in.name) for v in report.failures] == [ + ("Alias", first.name)] + + +def test_a_history_retry_still_answers_a_classic_failure_after_another_job( + tmp_path): + """Across the formats: a cancelled classic job A, A's retry as generation + 1, then job B listing the same bytes as generation 2. `supersede` saw + only B as the recorder of the clip, and the classic manifest's `no hash` + came back.""" + card, dest, cancelled = _cancelled_before_c002(tmp_path) + first = _stamp(write_mhl(cancelled, dest / "A001_Reports" / "JobReport.mhl"), + _at(10)) + retry = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest, when=_at(11)) + before = verify.verify_tree(dest) + assert all(r.passed for r in before), [r.summary() for r in before] + + ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64", job_name="B001")), + 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, first).superseded + assert (verdict.path.name, verdict.superseded_by.name) == ( + "C002.mov", retry.name) + + +def test_a_history_retry_still_answers_a_classic_folder_marker_after_another_job( + tmp_path, monkeypatch): + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(3000), + "Alias/C002.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _skipping_alias(patch) + skipped = engine.run(card, _options(dest, algorithm="xxh64")) + first = _stamp(write_mhl(skipped, dest / "A001_Reports" / "JobReport.mhl"), + _at(10)) + retry = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest, when=_at(11)) + ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64", job_name="B001")), + 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, first).superseded + assert (verdict.path.name, verdict.superseded_by.name) == ("Alias", retry.name) + + +def test_differently_named_jobs_leave_one_witness_each_per_path(tmp_path): + """What a report keeps of a healthy history: for each path, one earlier + record per distinct job and source, and no more however often a job + recurs. Twelve jobs listing forty files is eleven witnesses a path.""" + card = _card(tmp_path, {f"Clips/C{n:03d}.mov": os.urandom(64) + for n in range(40)}) + dest = tmp_path / "dst" + for hour in range(12): + for _again in range(2): # each job twice: no extra witness + ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64", + job_name=f"Job{hour:02d}")), + dest, when=_at(hour)) + + report = verify.verify_manifest(_only_history(dest)) + assert report.passed, report.summary() + assert len(report.verdicts) == 40 + assert {len(v.agreed_by) for v in report.verdicts} == {11} + assert {len({w.job for w in v.agreed_by}) for v in report.verdicts} == {11} + + +def test_a_retry_dated_before_a_later_generation_still_answers(tmp_path): + """A classic cancellation at 12:00, an ASC MHL retry at 13:00, then the + same job listing the same files in a generation dated 11:00, as happens + when two hosts' clocks disagree. The 11:00 generation is the latest by + number and cannot answer a 12:00 failure; keeping only it lost the 13:00 + record that can.""" + card, dest, cancelled = _cancelled_before_c002(tmp_path) + first = _stamp(write_mhl(cancelled, dest / "A001_Reports" / "JobReport.mhl"), + _at(12)) + retry = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest, when=_at(13)) + assert all(r.passed for r in verify.verify_tree(dest)) + + ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest, when=_at(11)) + reports = verify.verify_tree(dest) + assert all(r.passed for r in reports), [r.summary() for r in reports] + (verdict,) = _report_for(reports, first).superseded + assert (verdict.path.name, verdict.superseded_by.name) == ( + "C002.mov", retry.name) + + +def test_a_classic_folder_marker_stands_once_one_of_the_retrys_files_is_replaced( + tmp_path, monkeypatch): + """A classic manifest could only mark `Alias`, and an ASC MHL retry of + the job lists the two clips in it. Later content replaces one of them. + The other still matches the retry, and that one match credited the retry + with the whole folder.""" + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(3000), + "Alias/C002.mov": os.urandom(2000), + "Alias/C003.mov": os.urandom(2100)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _skipping_alias(patch) + skipped = engine.run(card, _options(dest, algorithm="xxh64")) + first = _stamp(write_mhl(skipped, dest / "A001_Reports" / "JobReport.mhl"), + _at(10)) + retry = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest, when=_at(11)) + before = verify.verify_tree(dest) + assert all(r.passed for r in before), [r.summary() for r in before] + assert [v.superseded_by.name for v in _report_for(before, first).superseded] == [ + retry.name] + + other = _card(tmp_path, {"Alias/C003.mov": os.urandom(2600)}, name="B001") + third = ascmhl.write_manifest( + engine.run(other, _options(dest, algorithm="xxh64", + replace_existing=True)), + dest, when=_at(12)) + # As another tool would record a replaced file: a hash in good standing. + namespace = f"{{{ascmhl.NAMESPACE}}}" + tree = ET.parse(third) + (replaced,) = [node for node in tree.getroot().iter(f"{namespace}xxh64") + if node.get("action") == "failed"] + replaced.set("action", "original") + tree.write(third, encoding="utf-8", xml_declaration=True) + + reports = verify.verify_tree(dest) + history = _report_for(reports, third) + # Every file matches. (The edit above leaves that generation's directory + # hashes stale, which is beside the point here.) + assert not history.failures, history.summary() + classic = _report_for(reports, first) + assert [v.path.name for v in classic.failures] == ["Alias"] + assert not classic.superseded + + +def test_another_jobs_repaired_clip_does_not_reopen_a_folder_marker( + tmp_path, monkeypatch, capsys): + """Job A's classic manifest could only mark `Alias`, and A's ASC MHL + retry cleared it. Job B then failed to read a clip of its own in that + folder, and repaired it in a classic run. Every clip matches and every + failure has its answer, but B's old unhashed entry is still a line in + the history's report, and the folder check read it as the folder not + being accounted for: A's marker came back and `verify` exited 1.""" + card = _card(tmp_path, {"Clips/C001.mov": os.urandom(3000), + "Alias/C002.mov": os.urandom(2000)}) + dest = tmp_path / "dst" + with monkeypatch.context() as patch: + _skipping_alias(patch) + skipped = engine.run(card, _options(dest, algorithm="xxh64")) + marker = _stamp(write_mhl(skipped, dest / "A001_Reports" / "JobReport.mhl"), + _at(10)) + retry = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest, when=_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, {"Alias/C003.mov": os.urandom(2500)}, name="B001") + with monkeypatch.context() as patch: + _fail_reads_of(patch, "C003.mov") + failed = engine.run(other, _options(dest, algorithm="xxh64")) + newest = ascmhl.write_manifest(failed, dest, when=_at(12)) + # Not repaired yet: B's clip fails, and A's folder is not accounted for. + during = verify.verify_tree(dest) + assert [v.path.name for v in _report_for(during, newest).failures] == ["C003.mov"] + assert [v.path.name for v in _report_for(during, marker).failures] == ["Alias"] + + repair = _stamp( + write_mhl(engine.run(other, _options(dest, algorithm="xxh64")), + dest / "B001_Reports" / "JobReport.mhl"), _at(13)) + reports = verify.verify_tree(dest) + assert all(r.passed for r in reports), [r.summary() for r in reports] + assert [(v.path.name, v.superseded_by) for v in + _report_for(reports, newest).superseded] == [("C003.mov", repair)] + assert [(v.path.name, v.superseded_by.name) for v in + _report_for(reports, marker).superseded] == [("Alias", retry.name)] + assert cli.main(["verify", str(dest), "--quiet"]) == 0 + capsys.readouterr() + + +def test_a_classic_rerun_answers_a_never_reached_file_in_a_history(tmp_path): + """Across the two formats, through `supersede`: the job name is read from + the manifest that recorded each entry, whichever kind it is.""" + card, dest, cancelled = _cancelled_before_c002(tmp_path) + first = ascmhl.write_manifest(cancelled, dest, when=_at(10)) + repair = _stamp( + write_mhl(engine.run(card, _options(dest, algorithm="xxh64")), + dest / "A001_Reports" / "JobReport.mhl"), _at(11)) + + reports = verify.verify_tree(dest) + assert all(r.passed for r in reports), [r.summary() for r in reports] + assert first == _only_history_of(dest) + (verdict,) = _report_for(reports, first).superseded + assert (verdict.path.name, verdict.superseded_by) == ("C002.mov", repair) + + +def test_a_history_rerun_answers_a_never_reached_file_in_a_classic_manifest( + tmp_path): + card, dest, cancelled = _cancelled_before_c002(tmp_path) + first = _stamp(write_mhl(cancelled, dest / "A001_Reports" / "JobReport.mhl"), + _at(10)) + second = ascmhl.write_manifest( + engine.run(card, _options(dest, algorithm="xxh64")), dest, when=_at(11)) + + reports = verify.verify_tree(dest) + assert all(r.passed for r in reports), [r.summary() for r in reports] + (verdict,) = _report_for(reports, first).superseded + assert (verdict.path.name, verdict.superseded_by.name) == ( + "C002.mov", second.name) + + +def _only_history_of(dest: Path) -> Path: + """The newest ASC MHL generation under `dest`, classic manifests aside.""" + (manifest,) = [m for m in verify.find_manifests(dest) + if m.parent.name == "ascmhl"] + return manifest + + # ---------- P1: "later" is judged by the manifest that recorded each entry