#!/usr/bin/env python3 """Acceptance checks for a shared-v1.0 -> shared-v1.1 migration (CONTRACT 6). Compares the migrated tree against the source it came from, so every claim is checked against real bytes rather than re-asserted from the migrator: 1. every component/attribute and its dictionary keys resolve; no stray files, no missing keys, no unregistered fields; merged numeric components leave no standalone ``*_valid.pt``; media/JSONL validity files survive untouched 2. every numeric field is identical to its source in dtype, shape, element-wise values, NaN positions and bool validity, compared as a unified contiguous byte view with no tolerance 3. ``num_frames``, sampling, hand slots, split, camera, view type, provenance and ``valid_policy`` are unchanged -- the metainfo diff must equal the allowed set 4. media and other preserved files match their source digests; the release manifest is regenerated because merged ``.pt`` digests necessarily changed 5. the new reader resolves RGB, camera and every annotation present on representative complete sequences The report distinguishes "repackaging is numerically identical" from "human visual acceptance"; this tool produces evidence for the former only. """ from __future__ import annotations import argparse import json import sys from pathlib import Path import torch sys.path.insert(0, str(Path(__file__).resolve().parent)) from warehouse import ( # noqa: E402 BundleReader, Registry, same_tensor, sha256_file, ) #: this package lives in /shared-v1.1/script/reinterhand_v1_1, so the #: release and the dataset root beside it need no arguments. RELEASE_ROOT = Path(__file__).resolve().parent.parent.parent DATASET_ROOT = RELEASE_ROOT.parent #: Where ``--manifest`` writes. The release manifest is a publication artifact and #: lives *outside* the release tree: a manifest inside it could not hash its own final #: bytes. ``reinterhand_common.MANIFEST_PATH`` holds the same path -- keep the two in #: step; validate.py is what the documented chain rebuilds the shipping manifest with. MANIFEST_PATH = DATASET_ROOT / "tmp" / "reinterhand-tools" / "PUBLISH_MANIFEST.json" #: The closing chain's CONTRACT 6 evidence: ``verify.py --complete`` writes it here (step #: 2) and ``FULL_MIGRATION_SUMMARY.json`` cites it for the whole release #: (``all_numeric_bytes_exact_evidence``), so it sits beside the manifest, outside the #: release tree, and only the acceptance pass may write it (see the refusal in ``main``). ACCEPTANCE_REPORT = MANIFEST_PATH.parent / "acceptance.json" V10_SCHEMA_VERSION = "hand-warehouse/1.0" EXPECTED_VIEWS = 6750 #: metainfo keys the migration is allowed to rewrite at the top level. Everything #: else is a claim the source made and must survive verbatim -- ReInterHand's release #: status flags (``upload_authorized``/``full_output_human_review``/ #: ``full_conversion_complete``/``conversion_scope``), the omitted-component reasons, #: the split bookkeeping. The version keys change by definition, and ``components`` #: changes wherever a numeric field joins a bundle. ALLOWED_TOP_LEVEL_CHANGES = {"schema_version", "release_id", "components"} #: the one key that is neither "bumped by definition" nor "preserved verbatim": v1.0's #: converter stamped ``lossless-video-2026-09-18``'s slot with a label of its own #: (``lossless-video-2026-09-25``), which ``doc/schema.json`` declares nowhere, so #: migration points it at the revision the registry itself declares -- the value every #: published v1.1 sibling view carries. It is handled on its own rather than by adding #: it to the set above, because the rewrite is allowed to one target value only, and a #: view that never declared the key must not acquire one. STORAGE_REVISION = "storage_revision" #: component fields the migration adds when a numeric field joins a bundle BUNDLE_FIELDS = {"data_key", "valid_key", "storage", "valid_storage"} #: component fields that must survive any migration untouched PRESERVED_FIELDS = ("provenance", "source_locator", "valid_policy", "axes", "valid_axes") class Failure(Exception): pass def check(condition, message): if not condition: raise Failure(message) def flatten(value, prefix=""): """Flatten a JSON object into dotted leaf paths.""" if isinstance(value, dict): out = {} for key, item in value.items(): out.update(flatten(item, f"{prefix}{key}.")) return out if isinstance(value, list) and value and not isinstance(value[0], (dict, list)): return {prefix[:-1]: json.dumps(value)} return {prefix[:-1]: json.dumps(value)} def is_stray_validity(registry: Registry, rel: str) -> bool: """True when a standalone ``*_valid.pt`` belongs to a field that was merged. Catches the failure CONTRACT 6.1 names explicitly: a numeric component's validity left behind as its own file because its name was not recognised. """ if not rel.endswith("_valid.pt"): return False return registry.resolve(rel[: -len("_valid.pt")] + ".pt") is not None def compare_metainfo(source: dict, target: dict, sequence: str, camera: str, registry: Registry): """Assert the metainfo diff is exactly the storage-layout change set.""" where = f"{sequence}/{camera}" check(source["schema_version"] == V10_SCHEMA_VERSION, f"{where}: source is not {V10_SCHEMA_VERSION}") for key in ("num_frames", "sampling", "hand_slots", "split", "camera", "view_type", "dataset_id", "sequence_id", "camera_id", "sample_type"): check(source.get(key) == target.get(key), f"{where}: {key} changed ({source.get(key)!r} -> {target.get(key)!r})") check(target["schema_version"] == "hand-warehouse/1.1", f"{where}: schema_version not bumped") check(target["release_id"] == "shared-v1.1", f"{where}: release_id not bumped") #: every remaining top level key, compared to this view's own source rather than #: to a constant: these are per-view claims made by the source, so "unchanged" #: has to mean unchanged against *this view's* v1.0 bytes, not equal to one #: expected value. ReInterHand's status flags happen to be uniform today (all #: 6,750 views carry ``upload_authorized=false``, ``full_output_human_review= #: "pending"``, ``full_conversion_complete=true``, ``conversion_scope="full"``); #: comparing per-view is what keeps a future re-render with a different status #: from being silently normalised into agreement. for key in sorted(set(source) | set(target)): if key in ALLOWED_TOP_LEVEL_CHANGES: continue check(key in source and key in target, f"{where}: top level key {key!r} exists on only one side") if key == STORAGE_REVISION: #: one target value only, read off the registry rather than restated here. check(target[key] == registry.schema[STORAGE_REVISION], f"{where}: {key} must be the registry's own " f"({target[key]!r} != {registry.schema[STORAGE_REVISION]!r})") continue check(source[key] == target[key], f"{where}: {key} changed ({source[key]!r} -> {target[key]!r})") source_components = source["components"] target_components = target["components"] check(set(source_components) == set(target_components), f"{where}: component set changed") for name, before in source_components.items(): after = target_components[name] for key in PRESERVED_FIELDS: check(before.get(key) == after.get(key), f"{where}/{name}: {key} changed") check(before.get("schema_id") == after.get("schema_id"), f"{where}/{name}: schema_id changed") check(before.get("available") == after.get("available"), f"{where}/{name}: availability changed") # attributes (e.g. visibility) follow the same rules as components before_attributes = before.get("attributes") or {} after_attributes = after.get("attributes") or {} check(set(before_attributes) == set(after_attributes), f"{where}/{name}: attribute set changed") for attribute, before_attribute in before_attributes.items(): after_attribute = after_attributes[attribute] for key in ("axes", "dtype", "visibility_type", "meaning", "provenance", "source_locator"): check(before_attribute.get(key) == after_attribute.get(key), f"{where}/{name}.{attribute}: {key} changed") if "data_key" in after_attribute: check(before_attribute.get("valid") is True, f"{where}/{name}.{attribute}: bundled without a declared all-known scalar") check("valid" not in after_attribute, f"{where}/{name}.{attribute}: scalar valid must give way to valid_key") check(after_attribute["data_ref"] == after_attribute["valid_ref"], f"{where}/{name}.{attribute}: data_ref and valid_ref must share a file") def verify_distortion(registry, v10_view, v11_view, reader, name, source_component, target_component, where, consumed): """CONTRACT 5/3: the separate distortion vector joins the camera's own bundle. v1.0 declares it on the component that owns the calibration, with no validity of its own: the camera model pairs the distortion vector with the intrinsic validity, so the two fields must carry the same bool values. Returns the field record, or ``None`` when the component declares no distortion. """ ref = source_component.get("distortion_ref") if not ref: return None resolved = registry.resolve(ref) if resolved is None: check(target_component.get("distortion_ref") == ref, f"{where}/{name}: distortion_ref changed for a preserved file") check((v10_view / ref).read_bytes() == (v11_view / ref).read_bytes(), f"{where}/{name}: preserved distortion {ref} differs") consumed.add(ref) return None bundle_rel, keys, _ = resolved check(target_component.get("distortion_ref") == bundle_rel and target_component.get("distortion_valid_ref") == bundle_rel, f"{where}/{name}: distortion refs must point at the camera bundle") check(target_component.get("distortion_key") == keys + ["data"], f"{where}/{name}: distortion_key mismatch") check(target_component.get("distortion_valid_key") == keys + ["valid"], f"{where}/{name}: distortion_valid_key mismatch") data = reader.get(v11_view, bundle_rel, keys + ["data"]) valid = reader.get(v11_view, bundle_rel, keys + ["valid"]) check(valid.dtype == torch.bool, f"{where}/{name}: distortion valid is not bool") check(same_tensor(torch.load(v10_view / ref, map_location="cpu", weights_only=True), data), f"{where}/{name}: distortion is not byte-identical") valid_ref = source_component.get("distortion_valid_ref") if valid_ref: check(same_tensor(torch.load(v10_view / valid_ref, map_location="cpu", weights_only=True), valid), f"{where}/{name}: distortion valid is not byte-identical") consumed.add(valid_ref) origin = f"source tensor {valid_ref}" else: # CONTRACT 3: with no validity of its own, the distortion vector either # shares the owning component's validity or expands a declared all-known # scalar. Both are checked against the source rather than re-asserted. owner_valid_ref = source_component.get("valid_ref") paired = (torch.load(v10_view / owner_valid_ref, map_location="cpu", weights_only=True) if owner_valid_ref else None) shared = (paired is not None and list(paired.shape) == list(valid.shape) and same_tensor(paired, valid)) check(shared or bool(valid.all()), f"{where}/{name}: distortion validity matches neither the paired camera " f"validity nor a declared all-known scalar") origin = ("shared with intrinsic validity (CONTRACT 3)" if shared else "expanded declared all-known scalar (CONTRACT 3)") consumed.add(ref) return { "owner": f"{name}.distortion", "entry": f"{bundle_rel}:{'/'.join(keys)}", "dtype": str(data.dtype), "shape": list(data.shape), "valid_shape": list(valid.shape), "valid_true": int(valid.sum()), "valid_false": int((~valid).sum()), "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None, "valid_origin": origin, "byte_exact": True, } def same_bytes(left: Path, right: Path) -> tuple: """``(same, how)`` for two paths: the same file, or the same bytes. Migration hardlinks media, so in the common case these are one inode and the answer is structural. Re-reading a file to compare it with itself proves nothing and costs the run, and on a published tree that read is most of the acceptance time. ReInterHand's *local* tree has no media at all (the ``*.mkv`` are deliberately outside the migration scope), so here the identity shortcut almost never fires and nearly every shared file is settled by content -- cheap, because the whole tree is ~2.7 GiB. When the inodes differ -- a tree that was *copied* rather than linked -- the bytes are hashed in streams, so nothing is assumed equal merely because the migration usually links. ``how`` travels into the report, so a reader can see which files were settled by identity and which by content instead of having to trust that either ran. """ left_stat, right_stat = left.stat(), right.stat() if (left_stat.st_dev, left_stat.st_ino) == (right_stat.st_dev, right_stat.st_ino): return True, "same inode" if left_stat.st_size != right_stat.st_size: return False, "size differs" return sha256_file(left) == sha256_file(right), "sha256" def same_preserved(left: Path, right: Path) -> tuple: """``(same, how)`` for a preserved file that may be *declared absent*. ReInterHand's local tree carries no ``*.mkv``: the media are 1.08 TB and were deliberately left out of the migration scope, to be copied server-side at publication time. A media ``data_ref`` is therefore missing from **both** trees, and asking whether the two copies match has no answer -- ``same_bytes`` raises ``FileNotFoundError`` on the first one. Absent on both sides is not a difference, it is the declared state: the claim being verified is that the migration left the media exactly as absent as it found them. Absent on *one* side only is a real failure and is reported as such, because that would mean the migration dropped a file it should have preserved (or invented one). """ if not left.exists() and not right.exists(): return True, "declared absent (absent from both trees)" if left.exists() != right.exists(): return False, "present on only one side" return same_bytes(left, right) def verify_view(registry, v10_view, v11_view, reader): """Run CONTRACT 6 checks for one view; return its evidence record.""" where = f"{v10_view.parent.name}/{v10_view.name}" source = json.loads((v10_view / "metainfo.json").read_text(encoding="utf-8")) target = json.loads((v11_view / "metainfo.json").read_text(encoding="utf-8")) compare_metainfo(source, target, v10_view.parent.name, v10_view.name, registry) consumed, fields, media = set(), [], [] for name, component in source["components"].items(): if not component.get("available", True): continue for owner, spec, kind in [(name, component, "component")] + [ (f"{name}.{attribute}", attribute_spec, "attribute") for attribute, attribute_spec in (component.get("attributes") or {}).items() ]: ref = spec.get("data_ref") if not ref: continue resolved = registry.resolve(ref) after = (target["components"][name] if kind == "component" else target["components"][name]["attributes"][owner.split(".", 1)[1]]) if resolved is None: # preserved verbatim: same reference, same bytes check(after.get("data_ref") == ref, f"{where}/{owner}: data_ref changed for a media file") check("data_key" not in after, f"{where}/{owner}: media must not carry data_key") same, how = same_preserved(v10_view / ref, v11_view / ref) check(same, f"{where}/{owner}: preserved file {ref} differs") valid_ref = spec.get("valid_ref") valid_how = None if valid_ref: check(after.get("valid_ref") == valid_ref, f"{where}/{owner}: media valid_ref changed") check("valid_key" not in after, f"{where}/{owner}: media must not carry valid_key") same, valid_how = same_preserved(v10_view / valid_ref, v11_view / valid_ref) check(same, f"{where}/{owner}: preserved validity {valid_ref} differs") media.append({"owner": owner, "data_ref": ref, "valid_ref": valid_ref, "verified": how, "valid_verified": valid_how}) continue bundle_rel, keys, entry = resolved check(after["data_ref"] == bundle_rel and after["valid_ref"] == bundle_rel, f"{where}/{owner}: bundled refs must be the same file") check(after["data_key"] == keys + ["data"], f"{where}/{owner}: data_key mismatch") check(after["valid_key"] == keys + ["valid"], f"{where}/{owner}: valid_key mismatch") for key in ("storage", "valid_storage"): check(after[key]["profile"] == "pt/tensor_bundle/v1", f"{where}/{owner}: {key} profile must be pt/tensor_bundle/v1") data, valid = reader.field(v11_view, after) check(valid.dtype == torch.bool, f"{where}/{owner}: valid is not bool") if kind == "attribute": check(after.get("valid_axes") == list(after["axes"])[:valid.ndim], f"{where}/{owner}: valid_axes must be axes[:valid.ndim]") check(after.get("valid_ref") == after.get("data_ref"), f"{where}/{owner}: visibility must share one bundle file") source_data = torch.load(v10_view / ref, map_location="cpu", weights_only=True) check(same_tensor(source_data, data), f"{where}/{owner}: data is not byte-identical") source_valid_ref = spec.get("valid_ref") if source_valid_ref: source_valid = torch.load(v10_view / source_valid_ref, map_location="cpu", weights_only=True) check(same_tensor(source_valid, valid), f"{where}/{owner}: valid is not byte-identical") origin = f"source tensor {source_valid_ref}" consumed.add(source_valid_ref) else: check(spec.get("valid") is True, f"{where}/{owner}: no valid_ref and no declared all-known scalar") check(bool(valid.all()), f"{where}/{owner}: expanded all-known validity must be all true") origin = "expanded declared all-known scalar" consumed.add(ref) fields.append({ "owner": owner, "entry": f"{bundle_rel}:{'/'.join(keys)}", "dtype": str(data.dtype), "shape": list(data.shape), "valid_shape": list(valid.shape), "valid_true": int(valid.sum()), "valid_false": int((~valid).sum()), "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None, "valid_origin": origin, "byte_exact": True, }) distortion = verify_distortion(registry, v10_view, v11_view, reader, name, component, target["components"][name], where, consumed) if distortion is not None: fields.append(distortion) # 1: no stray files, nothing lost source_files = {p.relative_to(v10_view).as_posix() for p in v10_view.rglob("*") if p.is_file()} target_files = {p.relative_to(v11_view).as_posix() for p in v11_view.rglob("*") if p.is_file()} expected = (source_files - consumed - {"metainfo.json"}) | {"metainfo.json"} | { f["entry"].split(":")[0] for f in fields} check(target_files == expected, f"{where}: file set mismatch; unexpected={sorted(target_files - expected)}, " f"missing={sorted(expected - target_files)}") strays = sorted(f for f in target_files if is_stray_validity(registry, f)) check(not strays, f"{where}: merged numeric fields left standalone validity files: {strays}") return { "sequence_id": v10_view.parent.name, "camera_id": v10_view.name, "num_frames": source["num_frames"], "source_files": len(source_files), "target_files": len(target_files), "merged_fields": len(fields), "preserved_files": len(media), "media_verified_by": {how: sum(1 for m in media if m["verified"] == how) for how in sorted({m["verified"] for m in media})}, "fields": fields, "media": media, } def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--v10", type=Path, default=DATASET_ROOT / "shared-v1.0", help="shared-v1.0 release directory") parser.add_argument("--v11", type=Path, default=RELEASE_ROOT, help="shared-v1.1 release directory") parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json", help="v1.1 schema.json") parser.add_argument("--manifest", type=Path, default=MANIFEST_PATH, help=f"write the v1.1 release manifest here (default: " f"{MANIFEST_PATH}, outside the release tree)") parser.add_argument("--report", type=Path, help="write the acceptance report here") parser.add_argument("--sample", type=int, default=None, help="verify at most N views (default: all migrated)") parser.add_argument("--views", nargs="*", default=None, help="restrict to these sequence ids") parser.add_argument("--complete", action="store_true", help="fail when a source view has no migrated counterpart") parser.add_argument("--no-manifest", action="store_true", help="skip regenerating the release manifest (CONTRACT 6.4). It " "hashes every file of the tree regardless of --views, so an " "incremental check while the pull is still running pays " "minutes for a manifest the final run overwrites anyway. " "The accepting run passes this as well: the manifest has to " "be the last thing built, because it must cover this " "release's own FULL_MIGRATION_SUMMARY.json and its rebuilt " "doc/*.md, which are written after the acceptance -- " "validate.py regenerates it at the end, so a manifest built " "here would be overwritten unread. CONTRACT 6.4 asks that the " "manifest be regenerated and correct, not that this tool be " "the one to write it.") args = parser.parse_args(argv) if args.sample is not None and args.sample < 1: parser.error("--sample must be positive") if args.views is not None and not args.views: parser.error("--views requires at least one sequence") acceptance_pass = args.complete and args.views is None and args.sample is None if args.report is not None: if args.report.resolve() in {MANIFEST_PATH.resolve(), args.manifest.resolve()}: parser.error("--report must not overwrite a publication manifest") if not acceptance_pass and args.report.resolve() == ACCEPTANCE_REPORT.resolve(): parser.error("the acceptance report requires --complete without --views/--sample") registry = Registry.load(args.schema) reader = BundleReader() source_data, target_data = args.v10 / "data", args.v11 / "data" if not source_data.is_dir() or not target_data.is_dir(): parser.error("both source and target data directories must exist") source_views = sorted(p.parent for p in source_data.glob("*/*/metainfo.json")) if not source_views: parser.error("source contains no views; no acceptance evidence was written") if acceptance_pass: source_set = {p.relative_to(source_data) for p in source_views} target_set = {p.parent.relative_to(target_data) for p in target_data.glob("*/*/metainfo.json")} if len(source_set) != EXPECTED_VIEWS or source_set != target_set: parser.error(f"full acceptance requires {EXPECTED_VIEWS} source views and " "the exact same target view set") migrated, absent = [], [] for view in source_views: relative = view.relative_to(args.v10 / "data") (migrated if (target_data / relative / "metainfo.json").is_file() else absent).append(view) if args.views: wanted = set(args.views) known = {view.parent.name for view in source_views} if not wanted <= known: parser.error(f"no such source sequence: {sorted(wanted - known)}") migrated = [v for v in migrated if v.parent.name in wanted] absent = [v for v in absent if v.parent.name in wanted] if args.sample: migrated = migrated[:args.sample] report = {"source": str(args.v10.resolve()), "target": str(args.v11.resolve()), "schema_sha256": sha256_file(args.schema), "views": [], "failures": [], "views_in_source": len(source_views), "views_migrated": len(migrated), "views_absent_from_target": [v.relative_to(args.v10 / "data").as_posix() for v in absent]} if args.complete: for view in absent: rel = view.relative_to(args.v10 / "data").as_posix() report["failures"].append({"view": rel, "error": "view was not migrated"}) print(f"FAIL {rel}: view was not migrated", file=sys.stderr) for view in migrated: relative = view.relative_to(args.v10 / "data") target_view = target_data / relative try: report["views"].append(verify_view(registry, view, target_view, reader)) except Failure as error: report["failures"].append({"view": relative.as_posix(), "error": str(error)}) print(f"FAIL {relative}: {error}", file=sys.stderr) # 4: regenerated release manifest if args.no_manifest or not acceptance_pass: #: reported as skipped, not as "0 files" -- an empty manifest in the report #: would read like a tree with nothing in it report["manifest"] = {"skipped": "incremental check; not an acceptance run"} else: manifest = {} #: The manifest normally lives outside the release (see MANIFEST_PATH), so it #: is not part of the tree being hashed and there is nothing to exclude. Only #: a ``--manifest`` pointed *into* the release has to be skipped: it cannot hash #: itself without recording the digest it is about to have. try: manifest_rel = args.manifest.relative_to(args.v11).as_posix() except ValueError: manifest_rel = None for path in sorted(args.v11.rglob("*")): rel = path.relative_to(args.v11).as_posix() if "__pycache__" in path.parts or rel == manifest_rel: continue if path.is_file(): manifest[rel] = {"size": path.stat().st_size, "sha256": sha256_file(path)} report["manifest"] = {"files": len(manifest), "bytes": sum(v["size"] for v in manifest.values()), "excludes": [x for x in (manifest_rel, "__pycache__/") if x]} if args.manifest: args.manifest.parent.mkdir(parents=True, exist_ok=True) args.manifest.write_text( json.dumps({"release": "shared-v1.1", "location": str(args.manifest), "in_release_tree": manifest_rel is not None, "files": manifest}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") report["passed"] = not report["failures"] report["scope"] = ("repackaging numerically identical; this is not human visual acceptance") if args.report: args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") total_fields = sum(v["merged_fields"] for v in report["views"]) media_modes = {} for view in report["views"]: for mode, count in view["media_verified_by"].items(): media_modes[mode] = media_modes.get(mode, 0) + count print(f"views={len(report['views'])} merged_fields={total_fields} " f"failures={len(report['failures'])} " + (f"manifest_files={report['manifest']['files']}" if "files" in report["manifest"] else "manifest=skipped") + f" media_verified_by={media_modes}") print("ACCEPTANCE_PASS" if report["passed"] else "ACCEPTANCE_FAIL") return 0 if report["passed"] else 1 if __name__ == "__main__": raise SystemExit(main())