File size: 35,087 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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
#!/usr/bin/env python3
"""Migrate the adjacent shared-v1.0 tree of this dataset to shared-v1.1.

Only the tensor layout changes (CONTRACT 1-5): numeric tensors and their validity
move into per-group bundles, metainfo references gain ``data_key``/``valid_key``
with ``pt/tensor_bundle/v1`` storage, and the two version fields are bumped.
Sampling, frame counts, dtypes, values, NaN bit patterns, validity judgements,
units, coordinate frames, hand slots, split and ``valid_policy`` are carried over
untouched (CONTRACT 6.3).

The source tree is never written to: this is a copy-out.  Unchanged media and
JSONL are hardlinked by default, so nothing is re-encoded and no bytes are
duplicated (MIGRATION 2, 6).  Every view is checkpointed with source and output
digests so ``--resume`` re-verifies rather than trusting file existence
(MIGRATION 4.4).
"""

from __future__ import annotations

import argparse
import fcntl
import json
import os
import shutil
import sys
import time
import traceback
from contextlib import contextmanager
from pathlib import Path

import torch

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

from warehouse import (  # noqa: E402
    BUNDLE_PROFILE,
    DATA_TERMINAL,
    RELEASE_ID,
    SCHEMA_VERSION,
    VALID_TERMINAL,
    BundleWriter,
    Registry,
    expanded_all_known,
    sha256_bytes,
    sha256_file,
    same_tensor,
)

V10_SCHEMA_VERSION = "hand-warehouse/1.0"
TOOL_ID = "hw11-migrate"
TOOL_REVISION = "1"

#: this package lives in <dataset>/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


# --------------------------------------------------------------------------
# filesystem helpers
# --------------------------------------------------------------------------

@contextmanager
def migration_lock(work: Path):
    """MIGRATION 3: one migrator per dataset, held for the whole run.

    The lock file lives in ``tmp/`` beside the checkpoints it protects, outside
    the release tree.  A second run is refused rather than interleaved: two
    processes writing the same destination view would each leave behind a
    checkpoint describing a tree the other had already overwritten, and a
    checkpoint that cannot be trusted is worse than none.
    """
    work.mkdir(parents=True, exist_ok=True)
    path = work / "migration.lock"
    with path.open("a+", encoding="utf-8") as stream:
        try:
            fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError as error:
            holder = path.read_text(encoding="utf-8").strip() or "unknown"
            raise SystemExit(
                f"another migration already holds {path} ({holder}); "
                "refusing to run two at once (MIGRATION 3)"
            ) from error
        stream.seek(0)
        stream.truncate()
        stream.write(f"pid {os.getpid()} started {time.strftime('%Y-%m-%dT%H:%M:%S%z')}\n")
        stream.flush()
        try:
            yield
        finally:
            fcntl.flock(stream, fcntl.LOCK_UN)


def _clone(src: Path, dst: Path) -> None:
    """FICLONE (reflink) copy where the filesystem supports it."""
    with open(src, "rb") as reader, open(dst, "wb") as writer:
        fcntl.ioctl(writer.fileno(), 0x40049409, reader.fileno())


def materialise(src: Path, dst: Path, mode: str) -> str:
    """Place an unchanged file at ``dst`` without ever re-encoding it.

    An existing destination is never trusted on existence alone: it must be the
    same inode as the source, or match it by SHA256, otherwise it is replaced.
    """
    dst.parent.mkdir(parents=True, exist_ok=True)
    if dst.exists():
        if os.path.samefile(src, dst):
            return "same-inode"
        if dst.stat().st_size == src.stat().st_size and sha256_file(dst) == sha256_file(src):
            return "present-verified"
        temp = dst.with_name(dst.name + ".hw11-tmp")
        temp.unlink(missing_ok=True)
        shutil.copy2(src, temp)
        os.replace(temp, dst)
    if mode in ("hardlink", "reflink"):
        link = os.link if mode == "hardlink" else (lambda a, b: _clone(Path(a), Path(b)))
        try:
            link(src, dst)
            return mode
        except OSError:
            pass
    shutil.copy2(src, dst)
    return "copy"


def load_tensor(path: Path) -> torch.Tensor:
    tensor = torch.load(path, map_location="cpu", weights_only=True)
    if not isinstance(tensor, torch.Tensor):
        raise TypeError(f"{path}: expected a Tensor, got {type(tensor).__name__}")
    return tensor


# --------------------------------------------------------------------------
# registry conformance
# --------------------------------------------------------------------------

#: what a registered schema *is*, as opposed to what it is called
SCHEMA_IDENTITY_FIELDS = ("dtype", "shape", "valid_shape", "unit")


def schema_id_note(registry: Registry, owner: str, spec: dict, entry: dict,
                   bundle_rel: str, field: str):
    """Reconcile a v1.0 ``schema_id`` with the bundle entry's ``schema_ids`` list.

    A mismatch is recorded as a note, not raised.  CONTRACT 6.3 forbids changing
    ``schema_id``, so a v1.0 label the registry words differently cannot be
    corrected here; ``schema_ids`` is documented nowhere in CONTRACT.md or
    MIGRATION.md; and the registry's own ``note`` calls it "a declarative registry,
    not a JSON Schema document or executable validator".  The check keeps its real
    purpose by refusing only when the declared schema is not *structurally* the
    field the entry allows (dtype, shape, valid_shape, unit) -- which is what a
    wrong bundle entry actually looks like.

    The case this was written for is a v1.0 that labels a field with one of the
    entry's ``schema_ids`` while declaring a ``convention`` the registry pairs with
    a *different* one of them, the two definitions being identical in every identity
    field.  ``notes`` stays empty as long as no view does that; the pilot asserts it,
    and the check is the guard that keeps a schema mismatch from being silently
    accepted if one ever appears.
    """
    allowed = entry.get("schema_ids")
    schema_id = spec.get("schema_id")
    if allowed is None or schema_id in allowed:
        return None
    declared = registry.components.get(schema_id)
    if declared is None:
        raise ValueError(f"{owner}: schema_id {schema_id!r} is not registered")
    equivalent = [name for name in allowed
                  if all(declared.get(key) == (registry.components.get(name) or {}).get(key)
                         for key in SCHEMA_IDENTITY_FIELDS)]
    if not equivalent:
        raise ValueError(
            f"{owner}: schema_id {schema_id!r} not allowed in {bundle_rel}:{field} and "
            f"is not structurally equivalent to any of {list(allowed)}")
    return {
        "owner": owner,
        "entry": f"{bundle_rel}:{field}",
        "declared_schema_id": schema_id,
        "entry_schema_ids": list(allowed),
        "structurally_equivalent_to": equivalent,
        "reason": "CONTRACT 6.3 forbids changing schema_id; the entry allows a "
                  "schema identical in dtype, shape, valid_shape and unit",
    }


def shared_distortion_valid(registry: Registry, owner: dict, entry: dict,
                            data: torch.Tensor, owner_valid):
    """The bool an existing camera model pairs between intrinsic and distortion.

    CONTRACT 3: "既有相机模型要求内参与单独畸变向量共用有效性时,在两个字段内保存
    相同 bool 值并校验一致".  This is the path for a v1.0 that declares
    ``distortion_ref`` with no distortion validity of its own: the owning component's
    intrinsic validity is the pairing the model already had, so this restates it
    rather than expanding an all-true tensor that was never declared.

    ReInterHand's ego views reach this helper, and it is the interesting case.  Their
    v1.0 splits the two roles across two declarations: ``intrinsic`` carries the
    pointer (``distortion_ref``, no validity) while the standalone ``distortion``
    component carries the bool (``valid_ref = camera/distortion_valid.pt``).  The
    search below keys on the pointer, so ``camera_meta`` is ``intrinsic``, its
    ``distortion_valid_ref`` is absent, and the pairing falls to this helper -- which
    is exactly the CONTRACT 3 relationship the model requires.  The verdict is
    checked against the component's own declaration rather than trusted; see the
    staged-identity guard at the call site.
    """
    required = (registry.components.get(owner.get("schema_id")) or {}).get(
        "required_metadata") or []
    if not any(key.startswith("distortion") for key in required) or owner_valid is None:
        return None
    declared = _distortion_valid_shape(registry, entry, data)
    if declared is None or list(owner_valid.shape) != declared:
        return None
    return owner_valid


def _distortion_valid_shape(registry: Registry, entry: dict, data: torch.Tensor):
    """Resolve the declared ``valid_shape`` of whichever distortion schema fits ``data``.

    Which of the entry's schemas applies is decided structurally, by the declared
    ``shape`` matching the tensor, so nothing is assumed from the model's name.
    """
    for schema_id in entry.get("schema_ids") or []:
        shape = (registry.components.get(schema_id) or {}).get("shape")
        if not shape or len(shape) != data.ndim:
            continue
        if not all(isinstance(dim, str) or int(dim) == size
                   for dim, size in zip(shape, data.shape)):
            continue
        valid_shape = (registry.components.get(schema_id) or {}).get("valid_shape") or []
        return [data.shape[axis] if isinstance(dim, str) else int(dim)
                for axis, dim in enumerate(valid_shape)]
    return None


# --------------------------------------------------------------------------
# per-view migration
# --------------------------------------------------------------------------

def _declared_shape(registry: Registry, owner: str, spec: dict, kind: str):
    """The registry's declared ``(shape, valid_shape)`` for this field."""
    if kind == "attribute":
        return None, registry.visibility_valid_shape(spec["axes"])
    schema_id = spec.get("schema_id")
    entry = registry.components.get(schema_id)
    if entry is None:
        raise KeyError(f"{owner}: schema_id {schema_id!r} is not registered")
    return entry.get("shape"), entry.get("valid_shape")


def _rewrite_reference(spec: dict, bundle_rel: str, keys: list, valid: torch.Tensor) -> dict:
    """CONTRACT 5: same-file data/valid refs plus explicit dictionary keys."""
    before = {
        "data_ref": spec.get("data_ref"),
        "valid_ref": spec.get("valid_ref"),
        "valid": spec.pop("valid", "<absent>"),
        "valid_axes": spec.get("valid_axes"),
    }
    spec["data_ref"] = bundle_rel
    spec["data_key"] = list(keys) + [DATA_TERMINAL]
    spec["valid_ref"] = bundle_rel
    spec["valid_key"] = list(keys) + [VALID_TERMINAL]
    spec["storage"] = {"profile": BUNDLE_PROFILE}
    spec["valid_storage"] = {"profile": BUNDLE_PROFILE}
    # visibility metadata requires valid_axes (tensor_attributes.visibility);
    # v1.0 wrote it as axes[:valid.ndim], so deriving it restates the same value.
    axes = spec.get("axes")
    if axes and not spec.get("valid_axes"):
        spec["valid_axes"] = list(axes)[:valid.ndim]
    return before


def _stage(registry, src_view, dst_view, writers, consumed, records, staged, notes,
           owner, spec, kind, num_frames):
    """Stage one registered numeric field into its bundle.  No-op when unmerged.

    Returns the field's bool validity Tensor, or ``None`` when the reference is not
    a registered numeric field (media / JSONL / assets, preserved verbatim).  The
    caller needs that Tensor because this function rewrites ``spec`` in place via
    `_rewrite_reference`, so the same spec can no longer be resolved to its source
    field once staged.
    """
    ref = spec.get("data_ref")
    if not ref:
        return None
    resolved = registry.resolve(ref)
    if resolved is None:
        return None  # media / JSONL / assets: preserved verbatim
    bundle_rel, keys, entry = resolved
    field = "/".join(keys)

    note = schema_id_note(registry, owner, spec, entry, bundle_rel, field)
    if note is not None:
        notes.append(note)
    if entry.get("attribute_id") and kind != "attribute":
        raise ValueError(f"{owner}: {bundle_rel}:{field} is an attribute entry")
    if kind == "attribute" and not entry.get("attribute_id"):
        raise ValueError(f"{owner}: {bundle_rel}:{field} is not declared as an attribute")

    source = src_view / ref
    if not source.is_file():
        raise FileNotFoundError(f"{owner}: {ref} is registered but missing")

    data = load_tensor(source)
    declared_shape, declared_valid_shape = _declared_shape(registry, owner, spec, kind)
    if declared_shape and declared_shape[0] == "T" and data.shape[0] != num_frames:
        raise ValueError(
            f"{owner}: {ref} has {data.shape[0]} frames but metainfo says {num_frames}")

    valid_ref = spec.get("valid_ref")
    if valid_ref:
        valid = load_tensor(src_view / valid_ref)
        consumed.add(valid_ref)
        origin = f"source tensor {valid_ref}"
    else:
        if spec.get("valid") is not True:
            raise ValueError(f"{owner}: {ref} has neither valid_ref nor a declared all-known scalar")
        valid = expanded_all_known(data, declared_valid_shape)
        origin = "expanded declared all-known scalar (CONTRACT 3)"

    writer = writers.get(bundle_rel)
    if writer is None:
        writer = writers[bundle_rel] = BundleWriter(dst_view, bundle_rel)

    # The registry fixes one entry per numeric field, so two components may share
    # it (RHD's uv and xyz both read the same source visibility).  Staging it
    # once is correct; a second owner with different bytes is a registry mismatch.
    identity = (bundle_rel, field)
    prior = staged.get(identity)
    if prior is None:
        writer.put(keys, data, valid)
        staged[identity] = {"data": data, "valid": valid, "owners": [owner],
                            "source_data_ref": ref, "source_valid_ref": valid_ref}
        shared_with = None
    else:
        if not (same_tensor(prior["data"], data) and same_tensor(prior["valid"], valid)):
            raise ValueError(
                f"{owner}: {identity[0]}:{field} is already staged from "
                f"{prior['source_data_ref']} with different values")
        prior["owners"].append(owner)
        shared_with = list(prior["owners"])
    consumed.add(ref)

    before = _rewrite_reference(spec, bundle_rel, keys, valid)
    records.append({
        "owner": owner,
        "kind": kind,
        "entry": f"{bundle_rel}:{field}",
        "source_data_ref": before["data_ref"],
        "source_valid_ref": before["valid_ref"],
        "source_scalar_valid": before["valid"],
        "source_valid_axes": before["valid_axes"],
        "valid_origin": origin,
        "shared_entry_owners": shared_with,
        "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,
    })
    return valid


def normalize_storage_revision(registry: Registry, meta: dict) -> bool:
    """Point the view's ``storage_revision`` at the revision the registry itself declares.

    v1.0's converter stamped ``lossless-video-2026-09-25`` into all 6,750 views, and
    ``doc/schema.json`` -- including the copy v1.0 shipped -- declares no such revision:
    its own is ``lossless-video-2026-09-18``, the value the published v1.1 siblings
    (RHD, ARCTIC) carry in every view.  Nothing else about the key is a claim this
    migration may touch, so the value is read off the schema rather than restated here,
    and a view that declares no ``storage_revision`` keeps declaring none (the registry
    does not require the key, and H2O's published v1.1 omits it outright).  Returns
    whether this view's value actually changed.
    """
    if "storage_revision" not in meta:
        return False
    declared = registry.schema["storage_revision"]
    changed = meta["storage_revision"] != declared
    meta["storage_revision"] = declared
    return changed


def migrate_view(registry, src_root, dst_root, sequence, camera, link_mode):
    """Migrate one ``<sequence>/<camera>`` view and return its report entry."""
    src_view = src_root / sequence / camera
    dst_view = dst_root / sequence / camera
    meta_path = src_view / "metainfo.json"
    meta = json.loads(meta_path.read_text(encoding="utf-8"))
    if meta.get("schema_version") != V10_SCHEMA_VERSION:
        raise ValueError(f"{meta_path}: not {V10_SCHEMA_VERSION}")
    if (meta.get("sequence_id"), meta.get("camera_id")) != (sequence, camera):
        raise ValueError(f"{meta_path}: sequence_id/camera_id do not match the directory")
    num_frames = meta["num_frames"]

    dst_view.mkdir(parents=True, exist_ok=True)
    writers, consumed, records, staged, notes = {}, set(), [], {}, []

    #: each component's staged validity, for a camera model that pairs it with the
    #: separate distortion vector (CONTRACT 3).  Taken from _stage's return value:
    #: _stage rewrites the component in place, so re-resolving ``data_ref`` here
    #: would read the already-migrated bundle path and never match an entry.
    staged_valid = {}
    for name, component in meta["components"].items():
        if not component.get("available", True):
            continue
        staged_valid[name] = _stage(
            registry, src_view, dst_view, writers, consumed, records, staged, notes,
            name, component, "component", num_frames)
        for attribute, spec in (component.get("attributes") or {}).items():
            _stage(registry, src_view, dst_view, writers, consumed, records, staged, notes,
                   f"{name}.{attribute}", spec, "attribute", num_frames)

    # camera distortion lives beside the intrinsic parameters (CONTRACT 5).  v1.0
    # declares it on the camera component that owns the calibration -- ARCTIC puts
    # ``distortion_ref`` on ``intrinsic`` -- so the components are searched first
    # and the ``camera`` block is only a fallback.
    #
    # ReInterHand's ego views are the second shape: v1.0 declares the distortion
    # twice, as a standalone ``distortion`` component *and* as
    # ``intrinsic.distortion_ref``.  The loop above has therefore already staged
    # that entry (with the standalone component's own ``distortion_valid_ref``)
    # before this block runs, and the two declarations must agree.  ARCTIC's
    # unconditional ``writer.put`` below would silently overwrite the component's
    # declaration with the intrinsic validity; that is value-neutral here (all 500
    # ego views were verified byte-for-byte equal, see
    # ``tmp/reinterhand-tools/check_distortion_valid.py``) but it would discard a
    # declaration rather than checking it.  So the entry goes through the same
    # staged-identity guard ``_stage`` uses.
    distortion_meta, distortion_owner = None, None
    for name, component in meta["components"].items():
        if component.get("distortion_ref"):
            distortion_meta, distortion_owner = component, name
            break
    if distortion_meta is None and (meta.get("camera") or {}).get("distortion_ref"):
        distortion_meta = meta["camera"]
    if distortion_meta is not None:
        camera_meta = distortion_meta
        owner_label = (f"{distortion_owner}.distortion" if distortion_owner
                       else "camera.distortion")
        ref = camera_meta["distortion_ref"]
        resolved = registry.resolve(ref)
        if resolved is None:
            raise ValueError(f"camera.distortion_ref {ref!r} does not resolve to a bundle")
        bundle_rel, keys, entry = resolved
        data = load_tensor(src_view / ref)
        valid_ref = camera_meta.get("distortion_valid_ref")
        if valid_ref:
            valid = load_tensor(src_view / valid_ref)
            consumed.add(valid_ref)
            origin = f"source tensor {valid_ref}"
        else:
            valid = shared_distortion_valid(registry, distortion_meta, entry, data,
                                           staged_valid.get(distortion_owner))
            if valid is not None:
                origin = "shared with intrinsic validity (CONTRACT 3)"
            else:
                valid = expanded_all_known(data, camera_meta.get("distortion_valid_shape"))
                origin = "expanded declared all-known scalar (CONTRACT 3)"
        writer = writers.get(bundle_rel) or writers.setdefault(
            bundle_rel, BundleWriter(dst_view, bundle_rel))
        identity = (bundle_rel, "/".join(keys))
        prior = staged.get(identity)
        if prior is None:
            writer.put(keys, data, valid)
            staged[identity] = {"data": data, "valid": valid, "owners": [owner_label],
                                "source_data_ref": ref, "source_valid_ref": valid_ref}
            shared_with = None
        else:
            if not (same_tensor(prior["data"], data) and same_tensor(prior["valid"], valid)):
                raise ValueError(
                    f"{owner_label}: {identity[0]}:{identity[1]} is already staged from "
                    f"{prior['source_data_ref']} with different values")
            prior["owners"].append(owner_label)
            shared_with = list(prior["owners"])
            origin = (f"entry already staged from {prior['source_data_ref']}; "
                      f"{origin} agrees byte-for-byte")
        consumed.add(ref)
        camera_meta["distortion_ref"] = bundle_rel
        camera_meta["distortion_key"] = list(keys) + [DATA_TERMINAL]
        camera_meta["distortion_valid_ref"] = bundle_rel
        camera_meta["distortion_valid_key"] = list(keys) + [VALID_TERMINAL]
        records.append({
            "owner": owner_label,
            "kind": "component",
            "entry": f"{bundle_rel}:{'/'.join(keys)}",
            "source_data_ref": ref,
            "source_valid_ref": valid_ref,
            "source_scalar_valid": "<absent>",
            "source_valid_axes": camera_meta.get("distortion_valid_axes"),
            "valid_origin": origin,
            "shared_entry_owners": shared_with,
            "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,
        })

    # everything not consumed into a bundle is preserved byte-for-byte
    passthrough = {}
    for path in sorted(src_view.rglob("*")):
        if not path.is_file():
            continue
        rel = path.relative_to(src_view).as_posix()
        if rel in consumed or rel == "metainfo.json":
            continue
        passthrough[rel] = materialise(path, dst_view / rel, link_mode)

    # MIGRATION 4.2: write, re-read, compare field by field, byte-exactly
    verification = []
    for bundle_rel, writer in sorted(writers.items()):
        path = writer.save()
        if path is None:
            continue
        reloaded = torch.load(path, map_location="cpu", weights_only=True)
        for keys, leaf in _walk_leaf(writer.tree):
            node = reloaded
            for key in keys:
                node = node[key]
            for terminal in (DATA_TERMINAL, VALID_TERMINAL):
                if not same_tensor(leaf[terminal], node[terminal]):
                    raise AssertionError(f"{bundle_rel}:{'/'.join(keys)}:{terminal} not byte-identical")
        verification.append({
            "bundle": bundle_rel,
            "sha256": sha256_file(path),
            "size": path.stat().st_size,
            "fields": sum(1 for _ in _walk_leaf(writer.tree)),
            "comparison": "byte_view_exact_no_tolerance",
        })

    meta["schema_version"] = SCHEMA_VERSION
    meta["release_id"] = RELEASE_ID
    storage_revision_changed = normalize_storage_revision(registry, meta)
    _write_json(dst_view / "metainfo.json", meta)

    return {
        "sequence_id": sequence,
        "camera_id": camera,
        "num_frames": num_frames,
        "storage_revision_changed": storage_revision_changed,
        "source_metainfo_sha256": sha256_file(meta_path),
        "source_metainfo_size": meta_path.stat().st_size,
        "output_metainfo_sha256": sha256_file(dst_view / "metainfo.json"),
        "bundles": verification,
        "fields": records,
        "schema_notes": notes,
        "passthrough_files": len(passthrough),
        "passthrough_modes": sorted(set(passthrough.values())),
        "replaced_source_refs": sorted(
            {r["source_data_ref"] for r in records} | {r["source_valid_ref"] for r in records if r["source_valid_ref"]}),
    }


def _walk_leaf(tree, prefix=()):
    for key, value in tree.items():
        if isinstance(value, dict) and set(value) == {DATA_TERMINAL, VALID_TERMINAL}:
            yield prefix + (key,), value
        elif isinstance(value, dict):
            yield from _walk_leaf(value, prefix + (key,))


def _write_json(path: Path, value) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_name(path.name + ".tmp")
    temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n",
                    encoding="utf-8")
    temp.replace(path)


# --------------------------------------------------------------------------
# dataset driver
# --------------------------------------------------------------------------

def discover_views(src_root: Path):
    views = []
    for meta in sorted(src_root.glob("data/*/*/metainfo.json")):
        views.append((meta.parent.parent.name, meta.parent.name))
    return views


def tool_digest(script_dir: Path, schema_path: Path) -> dict:
    return {
        "tool": f"{TOOL_ID}/{TOOL_REVISION}",
        "migrate_sha256": sha256_file(Path(__file__).resolve()),
        "layout_sha256": sha256_file(script_dir / "warehouse.py"),
        "schema_sha256": sha256_file(schema_path),
        "python": sys.version.split()[0],
        "torch": torch.__version__,
    }


def source_manifest(path: Path | None) -> dict | None:
    """Describe the tree-API manifest the source bytes were pulled against.

    The registration has to be readable on its own: "this tree came from revision
    X" means little without the file list and digests that revision published, so
    the manifest's own digest and size travel with it (MIGRATION 3).
    """
    if path is None:
        return None
    entries = json.loads(path.read_text(encoding="utf-8"))
    entries = entries["files"] if isinstance(entries, dict) else entries
    return {
        "path": str(path.resolve()),
        "sha256": sha256_file(path),
        "files": len(entries),
        "bytes": sum(int(entry.get("size", 0)) for entry in entries),
    }


def checkpoint_ok(state_path: Path, expected: dict, digest: dict) -> bool:
    """MIGRATION 4.4: re-verify inputs, tool revision and artefacts, not existence."""
    if not state_path.is_file():
        return False
    try:
        prior = json.loads(state_path.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError):
        return False
    if prior.get("tool") != digest:
        return False
    # a checkpoint describes one destination; never let it vouch for another
    if prior.get("dst_view") != str(expected["dst_view"]):
        return False
    if prior.get("source_metainfo_sha256") != expected["source_metainfo_sha256"]:
        return False
    for bundle in prior.get("bundles", []):
        path = Path(prior["dst_view"]) / bundle["bundle"]
        if not path.is_file() or sha256_file(path) != bundle["sha256"]:
            return False
    meta = Path(prior["dst_view"]) / "metainfo.json"
    if not meta.is_file() or sha256_file(meta) != prior["output_metainfo_sha256"]:
        return False
    return True


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--src", type=Path, default=DATASET_ROOT,
                        help="dataset root holding shared-v1.0 (default: the dataset "
                             "this package is installed in)")
    parser.add_argument("--dst", type=Path, default=RELEASE_ROOT,
                        help="output release directory (default <src>/shared-v1.1)")
    parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json",
                        help="v1.1 schema.json (default <dst>/doc/schema.json)")
    parser.add_argument("--link", default="hardlink", choices=["hardlink", "reflink", "copy"],
                        help="how unchanged media/JSONL is placed (default hardlink)")
    parser.add_argument("--views", nargs="*", default=None,
                        help="restrict to these sequence ids")
    parser.add_argument("--limit", type=int, default=None, help="migrate at most N views")
    parser.add_argument("--resume", action="store_true",
                        help="skip views whose checkpoint re-verifies")
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--source-revision", default=None, metavar="SHA",
                        help="the pinned revision the shared-v1.0 bytes came from; "
                             "recorded in the registration (MIGRATION 3)")
    parser.add_argument("--source-manifest", type=Path, default=None,
                        help="tree-API manifest of that revision; its digest and file "
                             "count are recorded so the registration is self-contained")
    args = parser.parse_args(argv)

    src_release = args.src / "shared-v1.0"
    dst_release = args.dst or (args.src / "shared-v1.1")
    if not src_release.is_dir():
        parser.error(f"{src_release} is not a directory")
    schema_path = args.schema or (dst_release / "doc" / "schema.json")
    if not schema_path.is_file():
        parser.error(f"v1.1 schema not found at {schema_path} (pass --schema)")
    registry = Registry.load(schema_path)

    src_root, dst_root = src_release / "data", dst_release / "data"
    views = discover_views(src_release)
    if not views:
        parser.error(f"no <sequence>/<camera>/metainfo.json found under {src_root}")
    first = src_root / views[0][0] / views[0][1] / "metainfo.json"
    dataset_id = json.loads(first.read_text(encoding="utf-8"))["dataset_id"]

    work = args.src / "tmp" / "migration-v11"
    state_dir = work / "checkpoints"
    if args.views:
        wanted = set(args.views)
        views = [v for v in views if v[0] in wanted]
    if args.limit:
        views = views[:args.limit]

    digest = tool_digest(Path(__file__).resolve().parent, schema_path)
    print(f"dataset={dataset_id} views={len(views)} src={src_release} dst={dst_release}")
    print(f"tool={digest['tool']} link={args.link}")
    if args.dry_run:
        for sequence, camera in views:
            print(f"  would migrate {sequence}/{camera}")
        return 0

    with migration_lock(work):
        registration = {
            "dataset_id": dataset_id,
            "source": {"release": "shared-v1.0", "schema_version": V10_SCHEMA_VERSION,
                       "schema_sha256": sha256_file(src_release / "doc" / "schema.json")
                       if (src_release / "doc" / "schema.json").is_file() else None,
                       "path": str(src_release.resolve()),
                       "revision": args.source_revision,
                       "manifest": source_manifest(args.source_manifest)},
            "target": {"release": RELEASE_ID, "schema_version": SCHEMA_VERSION,
                       "schema_sha256": sha256_file(schema_path), "path": str(dst_release.resolve())},
            "tool": digest,
            "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "views_total": len(views),
            "views": [],
            "errors": [],
        }

        done = skipped = failed = 0
        for index, (sequence, camera) in enumerate(views, 1):
            state_path = state_dir / f"{sequence}__{camera}.json"
            dst_view = dst_root / sequence / camera
            try:
                if args.resume and checkpoint_ok(state_path, {
                    "dst_view": str(dst_view),
                    "source_metainfo_sha256": sha256_file(src_root / sequence / camera / "metainfo.json"),
                }, digest):
                    skipped += 1
                    print(f"[{index}/{len(views)}] {sequence}/{camera} skip (checkpoint re-verified)")
                    continue
                entry = migrate_view(registry, src_root, dst_root, sequence, camera, args.link)
                entry["dst_view"] = str(dst_view)
                entry["tool"] = digest
                entry["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
                _write_json(state_path, entry)
                registration["views"].append({k: entry[k] for k in (
                    "sequence_id", "camera_id", "num_frames", "source_metainfo_sha256",
                    "output_metainfo_sha256", "bundles", "passthrough_files",
                    "replaced_source_refs", "schema_notes")})
                done += 1
                print(f"[{index}/{len(views)}] {sequence}/{camera} ok "
                      f"fields={len(entry['fields'])} bundles={len(entry['bundles'])} "
                      f"passthrough={entry['passthrough_files']}")
            except Exception as error:  # noqa: BLE001 - recorded, never hidden
                failed += 1
                registration["errors"].append({
                    "sequence_id": sequence, "camera_id": camera,
                    "error": f"{type(error).__name__}: {error}",
                    "traceback": traceback.format_exc(),
                })
                print(f"[{index}/{len(views)}] {sequence}/{camera} FAILED: {error}", file=sys.stderr)
            _write_json(work / "registration.json", registration)

        registration["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
        registration["stage"] = "complete" if failed == 0 else "failed"
        registration["counts"] = {"migrated": done, "skipped": skipped, "failed": failed}
        _write_json(work / "registration.json", registration)
        print(f"done={done} skipped={skipped} failed={failed}")
        print(f"registration: {work / 'registration.json'}")
        return 1 if failed else 0


if __name__ == "__main__":
    raise SystemExit(main())