File size: 28,495 Bytes
8f94cdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
"""Validate the adjacent ReInterHand shared-v1.1 tree and fingerprint its bytes.

Adapted from the RHD second-generation validator: numeric components are read
through their registered bundle keys instead of one ``.pt`` per component, media
validity must still be a standalone bool Tensor, and a merged field may not leave a
standalone ``*_valid.pt`` behind (CONTRACT 6.1, 6.5).  ReInterHand's own rules are
added on top, and every one of them is a fact measured over the release
(``tmp/reinterhand-tools/surface_recon.json``) rather than a schema wish:

* 6,750 views in 500 sequences, addressed by a ``camera_id`` that is either a Mugsy
  camera number or the literal ``"ego"`` -- nothing here may assume ``range(9)`` or
  one camera per sequence;
* the release is four render cells, and each cell fixes its own view count, its
  cameras per sequence and its frame rule (``EXPECTED_CELLS``, and
  ``reinterhand_common.RENDER_CELLS`` for the per-view half);
* ``frames.jsonl`` has no ``annotation_index``, so the alignment rule RHD and ARCTIC
  use has no field to read; ``sync_id`` joins cameras instead;
* the media layer is not materialised in this working copy, so a declared
  ``rgb.mkv``/``mask.mkv`` may be *absent by declaration* -- and the declaration is
  checked from both sides, so a half-pulled sequence fails;
* the published v1.0 media metadata does not satisfy the shared schema, uniformly
  over all 6,750 views.  A numeric-only migration may not repair that, so the gaps
  are declared, counted, and asserted to be exactly the declared set.

Scope: this checks the released content and layout.  It does not independently prove
official source correctness, and it is not human visual acceptance (CONTRACT 6).

Run: python shared-v1.1/script/reinterhand_v1_1/validate.py \
        --report shared-v1.1/doc/validation/validate_report.json

``--views``/``--limit`` are for checking a corner of the tree while working on it, and
a run that uses either is a *subset* run: it asserts only what its selected views can
support, marks its report partial, writes it to tmp rather than over the acceptance
report, and leaves the release manifest alone.  Run it with no selection for the
acceptance pass -- that is the one that checks the 6,750-view count and the
1,134,281/392,514 frame census.

``--strict-media`` ignores the media declaration, which is the honest way to see what
the declaration does: the same sweep then fails on the first ``rgb.mkv``.
"""

from __future__ import annotations

import argparse
import collections
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

from reinterhand_common import (  # noqa: E402
    CAMERA_FAMILY_BY_VIEW_TYPE,
    DECLARED_MEDIA_SCHEMA_GAPS,
    DEFAULT_MEDIA_DECLARATION,
    EXO_CAMERAS_BY_POLICY,
    REGISTRY,
    REGISTRY_READER,
    RELEASE_ROOT,
    TMP_ROOT,
    MediaDeclaration,
    audit,
    load,
    save,
    sha256,
    stray_validity,
    walk_leaf,
)
from warehouse import BundleReader, BundleWriter, raw_bytes  # noqa: E402

#: the manifest is written outside the release tree.  A file inside the tree cannot
#: describe its own final bytes, and a copy that excludes itself leaves one release
#: file that no digest covers; RHD, ARCTIC, H2O and dex-ycb keep theirs in
#: ``tmp/<dataset>-tools/`` for the same reason.
MANIFEST_PATH = TMP_ROOT / "PUBLISH_MANIFEST.json"

#: The release census, keyed by the split the view metadata declares.  Measured:
#: InterWild's official capture split puts 368 captures in ``train`` and 132 in
#: ``test``, and no capture contributes to both -- which is why ``split`` is uniform
#: across the views of a sequence and is asserted that way below.
EXPECTED_SPLIT = {"train": {"views": 4968, "sequences": 368, "frames": 1134281},
                  "test": {"views": 1782, "sequences": 132, "frames": 392514}}
EXPECTED_SEQUENCES = 500
EXPECTED_VIEWS = 6750
#: The four render cells and how many views each holds.  Every sequence also has exactly
#: one ``ego`` view and its policy's exo cameras (``EXO_CAMERAS_BY_POLICY``), so a
#: per-frame sequence has 21 camera directories and a per-segment one 6 -- 250 sequences
#: per cell, measured, and the reason a sequence count is not 500/4 in the per-view check.
EXPECTED_CELLS = {("exo", "envmap_per_frame"): 5000, ("exo", "envmap_per_segment"): 1250,
                  ("ego", "envmap_per_frame"): 250, ("ego", "envmap_per_segment"): 250}
EXPECTED_CELL_SEQUENCES = 250
#: Every view declares exactly one ``rgb.mkv`` and one ``mask.mkv``: 2 x 6,750.
MEDIA_REFS_PER_VIEW = 2
SCOPE = ("released content and layout; does not independently prove official source "
         "correctness or visual quality")
PARTIAL_SCOPE = (SCOPE + "; this run covered a selected subset of the release, so it is "
                 "not the release-wide acceptance run")
#: where a subset run writes instead of the release's own report path.  The name is load
#: bearing: it must not be the acceptance report, which describes the whole release and is
#: what FULL_MIGRATION_SUMMARY.json cites.
PARTIAL_REPORT = TMP_ROOT / "validate-partial.json"
ACCEPTANCE_REPORT = RELEASE_ROOT / "doc/validation/validate_report.json"


def release_files():
    """Every file of the release, in path order -- one definition, used twice.

    Both the report (written before the manifest) and the manifest itself need this
    set.  Two filters that could drift apart would let the report name a file count
    the manifest it cites does not have.
    """
    for path in sorted(RELEASE_ROOT.rglob("*")):
        #: bytecode caches are not release content.  Nothing else is skipped: the
        #: manifest lives outside the tree, so it never has to exclude itself and the
        #: release's byte total is the manifest's own total.
        if not path.is_file() or ".cache" in path.parts or "__pycache__" in path.parts:
            continue
        yield path


def rewrite_check(view_dir, meta, work):
    """Rebuild a view's bundles with ``BundleWriter`` and compare leaf bytes.

    ``verify.py`` proves the released bytes equal the *source* bytes; this proves the
    writer that produced them is reproducible from the released metadata alone, which
    is what makes the bundles readable by something other than the migration.

    ReInterHand declares no bundled attributes, so every field is a component's own
    ``data_key``; the loop stays key-driven all the same, so a future attribute shows
    up as a missing leaf rather than as a silently thinner comparison.
    """
    where = f"{meta['sequence_id']}/{meta['camera_id']}"
    rebuilt_root = Path(work) / f"{meta['sequence_id']}__{meta['camera_id']}"
    writers, bundles = {}, []
    for component in meta["components"].values():
        if "data_key" not in component:
            continue
        ref = component["data_ref"]
        if ref not in writers:
            writers[ref] = BundleWriter(rebuilt_root, ref)
            bundles.append(ref)
        data, valid = REGISTRY_READER.field(view_dir, component)
        writers[ref].put(component["data_key"][:-1], data, valid)
    for ref in bundles:
        writers[ref].save()

    compared = 0
    for ref in sorted(bundles):
        released = REGISTRY_READER.bundle(view_dir, ref)
        rebuilt = REGISTRY_READER.bundle(rebuilt_root, ref)
        got = dict(walk_leaf(rebuilt))
        #: the key set has to match too: a field the writer dropped would otherwise
        #: compare as zero leaves and pass as "nothing left to disagree about"
        assert set(got) == set(dict(walk_leaf(released))), (where, ref, sorted(got))
        for keys, leaf in walk_leaf(released):
            for terminal in ("data", "valid"):
                left, right = leaf[terminal], got[keys][terminal]
                assert left.dtype == right.dtype and tuple(left.shape) == tuple(right.shape), (
                    where, ref, keys, terminal)
                assert raw_bytes(left) == raw_bytes(right), (where, ref, keys, terminal)
                compared += 1
    return {"sequence_id": meta["sequence_id"], "camera_id": meta["camera_id"],
            "bundles": sorted(bundles), "tensors_compared": compared}


def census_checks(views, counts, cell_views, cell_sequences, sequence_cameras,
                  sequence_frames, sequence_policy):
    """The release-wide census, asserted only where it can hold.

    A subset's counts are a fraction of these by construction, so comparing them would
    fail a working check for a reason that has nothing to do with the views it read.
    """
    assert len(views) == EXPECTED_VIEWS, len(views)
    assert counts == EXPECTED_SPLIT, counts
    assert len(sequence_policy) == EXPECTED_SEQUENCES, len(sequence_policy)
    for cell, expected_views in EXPECTED_CELLS.items():
        view_type, policy = cell
        assert cell_views[cell] == expected_views, (cell, cell_views[cell], expected_views)
        sequences = cell_sequences[cell]
        assert len(sequences) == EXPECTED_CELL_SEQUENCES, (cell, len(sequences))
        for sequence in sorted(sequences):
            exo = sequence_cameras[sequence].get("exo", set())
            ego = sequence_cameras[sequence].get("ego", set())
            assert len(exo) == EXO_CAMERAS_BY_POLICY[policy], (sequence, cell, sorted(exo))
            assert ego == {"ego"}, (sequence, cell, sorted(ego))
            #: the render cell fixes the frame counts, and only there: a per-segment
            #: render writes one video frame per source frame for every camera, while the
            #: per-frame ego render keeps the whole capture and its exo renders sample it.
            #: This is what ties the cell in the sequence id to the frame table's length.
            frames = sequence_frames[sequence]
            if policy == "envmap_per_segment":
                assert len(set().union(*frames.values())) == 1, (sequence, sorted(frames.items()))
            else:
                assert max(frames["exo"]) < min(frames["ego"]), (sequence, sorted(frames.items()))
    #: the two view types of a policy render the same sequences: every sequence has its
    #: exo cameras *and* its single ego view, so a missing ego render cannot pass as a
    #: smaller release
    for policy in sorted({cell[1] for cell in EXPECTED_CELLS}):
        assert cell_sequences[("ego", policy)] == cell_sequences[("exo", policy)], policy


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--views", nargs="*", default=None, help="restrict to these sequences")
    parser.add_argument("--limit", type=int, default=None, help="validate at most N views")
    parser.add_argument("--rewrite-check", type=int, default=0, metavar="N",
                        help="also re-serialise N views with BundleWriter and compare leaf bytes")
    parser.add_argument("--expect-views", type=int, default=None, metavar="N",
                        help=f"fail unless exactly N views were checked (default: {EXPECTED_VIEWS}, "
                             "the full ReInterHand release, for a run with no --views/--limit; a "
                             "subset run defaults to the number of views it selected).  Without it a "
                             "run that silently covered a fraction of the tree would still report a "
                             "pass.")
    parser.add_argument("--media-declaration", type=Path, default=DEFAULT_MEDIA_DECLARATION,
                        help="where this copy of the tree declares which preserved media it ships "
                             f"(default: {DEFAULT_MEDIA_DECLARATION}).  A missing file means every "
                             "declared media file must exist, which is what a published tree looks "
                             "like.")
    parser.add_argument("--strict-media", action="store_true",
                        help="ignore the media declaration and require every declared media file to "
                             "exist.  On this working copy that fails by design -- it is how the "
                             "declaration's own effect is shown to be real.")
    parser.add_argument("--report", type=Path, default=None,
                        help="where the structural report is written (default: the release's "
                             "doc/validation/validate_report.json for a full run, "
                             f"{PARTIAL_REPORT} for a subset run).  Naming the acceptance "
                             "report explicitly does not override that: a subset run is "
                             "refused, and the file is left as it was.")
    parser.add_argument("--no-manifest", action="store_true",
                        help=f"do not rebuild the release manifest ({MANIFEST_PATH}). It hashes "
                             "the whole release tree whatever --views says, so an incremental "
                             "check would pay for a manifest the final run overwrites anyway. "
                             "The accepting run must not pass this (CONTRACT 6.4).")
    args = parser.parse_args(argv)
    if args.limit is not None and args.limit < 1:
        parser.error("--limit must be positive")
    if args.views is not None and not args.views:
        parser.error("--views requires at least one sequence")
    if args.report is not None and args.report.resolve() == MANIFEST_PATH.resolve():
        parser.error("--report must not overwrite the publication manifest")

    all_views = sorted((RELEASE_ROOT / "data").glob("*/*/metainfo.json"))
    wanted = set(args.views) if args.views else None
    if wanted is not None:
        #: a name that matches nothing is a typo, and silently checking the other views
        #: would let it pass as a green run over the wrong set
        known = {view.parent.parent.name for view in all_views}
        assert wanted <= known, ("no such sequence", sorted(wanted - known))
        views = [view for view in all_views if view.parent.parent.name in wanted]
    else:
        views = all_views
    if args.limit:
        views = views[: args.limit]
    assert views, "no metainfo.json found under data/*/*/"

    #: "is this release complete?" and "is this view sound?" are different questions.
    #: The frame census and the view count only mean anything over the whole tree, so a
    #: run with --views/--limit checks its own selection instead and says so everywhere
    #: its result is reported (see SCOPE/PARTIAL_SCOPE, the report's ``coverage``, and
    #: the manifest it deliberately does not rebuild).
    full = wanted is None and not args.limit
    expect_views = args.expect_views if args.expect_views is not None else (
        EXPECTED_VIEWS if full else len(views))
    report_path = args.report or (ACCEPTANCE_REPORT if full else PARTIAL_REPORT)
    #: Decided here, before the first view is read, and asserted rather than commented:
    #: an explicit ``--report`` does not make a subset run the acceptance run.  The
    #: report at the release's own path is what FULL_MIGRATION_SUMMARY.json cites as the
    #: release-wide structural evidence, and a run that selected views cannot speak for
    #: the release it would be overwriting -- the refusing run leaves the file untouched.
    assert full or report_path.resolve() != ACCEPTANCE_REPORT.resolve(), (
        f"--report names the release's acceptance report ({ACCEPTANCE_REPORT}), but "
        "--views/--limit makes this a subset run; drop --report to write "
        f"{PARTIAL_REPORT} instead, or drop the selection to run the acceptance pass")

    media = MediaDeclaration("all") if args.strict_media else MediaDeclaration.load(args.media_declaration)
    gaps, failures, rewrites = collections.Counter(), [], []
    split_views, split_frames, split_sequences = collections.Counter(), collections.Counter(), collections.defaultdict(set)
    cell_views, cell_sequences, cell_steps = collections.Counter(), collections.defaultdict(set), collections.defaultdict(collections.Counter)
    cell_gap_hist = collections.defaultdict(collections.Counter)
    #: per-sequence bookkeeping.  A sequence is one directory, so all of its views are
    #: adjacent in path order and these collapse to one entry per sequence -- which is
    #: what lets the sequence-wide facts be asserted below instead of trusted.
    sequence_split, sequence_policy = collections.defaultdict(set), collections.defaultdict(set)
    sequence_spans = collections.defaultdict(set)
    sequence_cameras = collections.defaultdict(lambda: collections.defaultdict(set))
    sequence_frames = collections.defaultdict(lambda: collections.defaultdict(set))
    capture_splits = collections.defaultdict(set)
    family_by_view_type = collections.defaultdict(set)
    files_total, frames_total, declared_media, expected_media_on_disk, mkv_on_disk = 0, 0, 0, 0, 0

    for position, path in enumerate(views, 1):
        view_dir, meta = path.parent, load(path)
        if position % 250 == 1 or position == len(views):
            print(f"  view {position}/{len(views)}: {view_dir.relative_to(RELEASE_ROOT)}", flush=True)
        #: the path and the metadata have to name the same view, or a misplaced or
        #: duplicated directory tree would validate as its own sound copy
        assert meta["sequence_id"] == view_dir.parent.name, (path, meta.get("sequence_id"))
        assert meta["camera_id"] == view_dir.name, (path, meta.get("camera_id"))

        sequence, camera = meta["sequence_id"], meta["camera_id"]
        rendering = meta["source_rendering"]
        cell = (meta["view_type"], rendering["background_policy"])
        family_by_view_type[meta["view_type"]].add(rendering["camera_family"])
        capture_splits[meta["source_capture_id"]].add(meta["split"])
        sequence_split[sequence].add(meta["split"])
        sequence_policy[sequence].add(rendering["background_policy"])
        sequence_spans[sequence].add(tuple(meta["source_frame_span"]))
        sequence_cameras[sequence][meta["view_type"]].add(camera)
        sequence_frames[sequence][meta["view_type"]].add(meta["num_frames"])
        cell_views[cell] += 1
        cell_sequences[cell].add(sequence)
        split_views[meta["split"]] += 1
        split_frames[meta["split"]] += meta["num_frames"]
        split_sequences[meta["split"]].add(sequence)
        frames_total += meta["num_frames"]

        #: a fresh reader per view.  A view's components share their bundles, so the cache
        #: is what makes the pass read each file once -- but keeping it across the sweep
        #: would hold 6,750 views x 2 bundles in memory, so the whole-tree tools scope it
        #: to the view they are looking at (the module-level reader backs the single-view
        #: tools, and rewrite_check below).
        _consumed, view_gaps, view_failures, frames = audit(view_dir, meta, REGISTRY, BundleReader(),
                                                            media, None)
        gaps.update(view_gaps)
        failures.extend(view_failures)
        if frames is not None:
            cell_steps[cell][frames["modal_step"]] += 1
            cell_gap_hist[cell][frames["source_gaps"]] += 1

        present = sorted(p.relative_to(view_dir).as_posix()
                         for p in view_dir.rglob("*") if p.is_file())
        files_total += len(present)
        stray = [name for name in present if stray_validity(name)]
        assert not stray, (view_dir, "merged field left a standalone validity file", stray)
        #: media tallies, from both sides at once: what the metainfo declares, what the
        #: declaration says this copy ships, and what the tree actually holds
        mkv_refs = {c["data_ref"] for c in meta["components"].values()
                    if c["data_ref"].endswith(".mkv")}
        declared_media += len(mkv_refs)
        if media.ships(sequence):
            expected_media_on_disk += len(mkv_refs)
        mkv_on_disk += sum(1 for name in present if name.endswith(".mkv"))
        if len(rewrites) < args.rewrite_check:
            rewrites.append(rewrite_check(view_dir, meta, TMP_ROOT / "rewrite-check"))

    #: Everything from here on is an invariant of a *sound* tree, so it is asserted only
    #: when the per-view sweep found nothing.  A defective view can make several of these
    #: meaningless -- a missing media file stops ``check_view`` before it tallies the
    #: declaration gaps, and asserting the tally first would replace the named per-view
    #: failure with an unrelated one, which is the failure mode ``audit`` exists to avoid.
    #: A run with failures already reports itself as failed either way.
    if not failures:
        #: each of the nine declared gaps fires exactly once per view, so a gap that
        #: *stopped* occurring is as much a finding as a new one: it would mean the media
        #: metadata was repaired outside a numeric-only migration's contract.
        assert dict(gaps) == {token: len(views) for token in DECLARED_MEDIA_SCHEMA_GAPS}, (
            "declared media schema gaps", dict(gaps))
        #: a subset may hold only exo views, so this checks the families it saw and leaves
        #: "all four cells are present" to the census, the run that can speak for the
        #: whole release
        assert set(family_by_view_type) <= set(CAMERA_FAMILY_BY_VIEW_TYPE), sorted(family_by_view_type)
        for view_type, families in family_by_view_type.items():
            assert families == {CAMERA_FAMILY_BY_VIEW_TYPE[view_type]}, (view_type, sorted(families))
        for label, mapping in (("capture", capture_splits), ("sequence", sequence_split),
                               ("sequence", sequence_policy), ("sequence", sequence_spans)):
            multiple = sorted(name for name, seen in mapping.items() if len(seen) > 1)
            assert not multiple, (f"{label} with more than one value", multiple[:5])
        #: the render cell is named in the sequence id, so a mislabelled policy cannot pass
        for sequence, policy in sequence_policy.items():
            name = sorted(policy)[0]
            assert f"__{name}__" in sequence, (sequence, name)

        #: the media declaration, checked from both sides.  ``expected_media_on_disk``
        #: counts the streams the declaration says this copy ships and ``mkv_on_disk`` what
        #: the tree holds: equal means no declared stream is missing *and* no undeclared one
        #: is lying around -- which is what "half-pulled sequence" looks like from here.
        assert declared_media == MEDIA_REFS_PER_VIEW * len(views), (declared_media, len(views))
        assert mkv_on_disk == expected_media_on_disk, (
            "media on disk disagrees with the declaration", mkv_on_disk, expected_media_on_disk)

    counts = {split: {"views": split_views[split], "sequences": len(split_sequences.get(split, ())),
                      "frames": split_frames[split]} for split in sorted(split_views)}
    cells = {}
    for (view_type, policy), count in sorted(cell_views.items()):
        #: the modal step and the gap histogram are reported, not asserted: the source
        #: captures genuinely skip frames, so a bound would encode this tree's accidents
        #: as a rule.  ``check_frames`` asserts the one thing that is a rule -- that the
        #: modal step is one the cell declares.
        cells[f"{view_type}/{policy}"] = {
            "views": count, "sequences": len(cell_sequences[(view_type, policy)]),
            "modal_source_step": {str(step): n for step, n in sorted(cell_steps[(view_type, policy)].items())},
            "source_gap_histogram": {str(gap): n for gap, n in sorted(cell_gap_hist[(view_type, policy)].items())}}

    if full and not failures:
        census_checks(views, counts, cell_views, cell_sequences, sequence_cameras,
                      sequence_frames, sequence_policy)
    #: per-view contract: the parts that hold release-wide rather than per view
    assert len(views) == expect_views, (len(views), expect_views)

    result = {
        "passed": not failures,
        "coverage": "full release" if full else "partial subset",
        "views": len(views), "sequences": len(sequence_policy), "counts": counts, "cells": cells,
        "frames": frames_total,
        "files_per_view": files_total // len(views),
        "schema_version": REGISTRY.schema["view_metadata"]["schema_version"],
        "release_id": REGISTRY.schema["view_metadata"]["release_id"],
        "bundles_per_view": len({c["data_ref"] for c in load(views[0])["components"].values()
                                 if "data_key" in c}),
        "declared_media_schema_gaps": dict(gaps),
        "media": {"declaration": media.origin,
                  "materialised": sorted(media.materialised) if isinstance(media.materialised, set)
                  else media.materialised,
                  "declared_media_files": declared_media, "files_on_disk": mkv_on_disk},
        "rewrite_check": rewrites,
        "failures": failures,
        "scope": SCOPE if full else PARTIAL_SCOPE,
    }
    #: The tmp copy is a convenience for the migration loop, and its *name* is load
    #: bearing.  It must not be "acceptance.json": the documented chain writes verify.py's
    #: byte-level acceptance report to tmp/reinterhand-tools/acceptance.json, so a
    #: structural report saved under that name silently destroys the evidence
    #: FULL_MIGRATION_SUMMARY.json is built from.
    save(TMP_ROOT / "validate-latest.json", result)
    save(report_path, result)

    skip_manifest = None
    if failures:
        #: the manifest is a claim about the whole release, so a run that found a defect
        #: must not leave one behind that reads like an accepted tree
        skip_manifest = "failed run; the release manifest is rebuilt only by a passing acceptance run"
    elif args.no_manifest:
        #: reported as skipped rather than as a manifest of 0 files, which would read
        #: like an empty release
        skip_manifest = "incremental check; not an acceptance run"
    elif not full:
        #: The manifest is a claim about the whole release -- it hashes every file -- and
        #: the documented chain reads it together with the acceptance report.  A subset run
        #: must not leave the two disagreeing about what was accepted, so it reports the
        #: manifest as skipped instead of rebuilding one to sit beside a partial report.
        skip_manifest = "partial run; the release manifest is rebuilt by the full acceptance run"
    if skip_manifest:
        result["release_manifest"] = {"skipped": skip_manifest, "path": str(MANIFEST_PATH)}
        save(TMP_ROOT / "validate-latest.json", result)
        save(report_path, result)
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return 0 if result["passed"] else 1

    #: Named, and counted, here -- before the manifest is rebuilt -- because the manifest
    #: has to cover this report's final bytes, so the report cannot carry the manifest's
    #: digest.  The count is exact all the same: nothing adds or removes a release file
    #: between this walk and the hash pass below.
    result["release_manifest"] = {
        "path": str(MANIFEST_PATH),
        "in_release_tree": False,
        "files": sum(1 for _ in release_files()),
        "note": "rebuilt by this run after this report was written, so it covers the "
                "report's final bytes; kept outside the release because a manifest inside "
                "it cannot hash itself",
    }
    save(TMP_ROOT / "validate-latest.json", result)
    save(report_path, result)

    manifest = []
    for path in release_files():
        rel = path.relative_to(RELEASE_ROOT).as_posix()
        manifest.append({"path": rel, "size": path.stat().st_size, "sha256": sha256(path)})
    payload = {
        "release": REGISTRY.schema["view_metadata"]["release_id"],
        "scope": result["scope"],
        "location": f"{MANIFEST_PATH} (outside the release tree, as in the published "
                    "RHD, ARCTIC, H2O and dex-ycb sets)",
        "excludes": ["__pycache__/"],
        "files": manifest,
        "bytes": sum(entry["size"] for entry in manifest),
    }
    save(MANIFEST_PATH, payload)
    print(f"manifest: {len(manifest)} files, {payload['bytes']} B -> {MANIFEST_PATH}")

    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    sys.dont_write_bytecode = True
    raise SystemExit(main())