File size: 28,355 Bytes
2b01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24b5890
2b01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24b5890
 
 
 
 
 
 
 
2b01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24b5890
2b01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24b5890
 
2b01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24b5890
 
2b01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Independent, offline checks for the Franka/FT OXT export.

This verifies preservation and declared numeric conversions, not physical sensor
calibration, canonical gripper alignment, image content, or source-file hashes.
It does not import the exporter or open an SVO/live camera. RGB chunks are sampled
at each episode's first/last row unless --scan-rgb-all is requested.
"""

from __future__ import annotations

import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import sys
from typing import Any

import h5py
import numpy as np
from scipy.spatial.transform import Rotation


TASKS = ("wipe_board", "push_button", "insert_pen", "hang_tape")
CAMERAS = {"camera_main": "36087771", "right_wrist_camera": "16478870"}
STANDARD_SHAPES = {
    "timestamps": (), "timestamp_unix_ns": (), "source_control_row": (),
    "right_arm_joints": (7,),
    "right_hand_joints": (1,), "right_hand_joints_idx": (1,),
    "sub_task_instruction": (), "action_joint_position": (7,),
    "action_eef_pose": (6,), "action_eef_pose_with_ft_offset": (6,),
    "state_eef_pose_with_ft_offset": (6,), "command_dispatched": (),
    "right_tactile_data_wrist_torque": (1, 3),
    "right_tactile_area_wrist_torque": (1,),
    "right_tactile_sensor_wrist_torque": (),
    "right_tactile_type_wrist_torque": (),
    "ft_wrench": (6,), "supplementary_tactile": (6,),
}
POSE_SOURCES = {
    "state_eef_pose_with_ft_offset": "observation/robot_state/cartesian_position_with_ft_offset",
    "action_eef_pose": "action/cartesian_position",
    "action_eef_pose_with_ft_offset": "action/cartesian_position_with_ft_offset",
}


def text_value(value: Any) -> str:
    return value.decode("utf-8") if isinstance(value, bytes) else str(value)


def episode_name_matches(original_name: str, exported_name: str) -> bool:
    """Allow only the exact native name or its documented ':' -> '-' variant."""
    return exported_name == original_name or exported_name == original_name.replace(":", "-")


def native_key(path: str) -> str:
    return "native__" + path.replace("/", "__")


def strings(values: Any) -> np.ndarray:
    arr = np.asarray(values)
    return np.asarray([text_value(v) for v in arr.reshape(-1)]).reshape(arr.shape)


def exactly_equal(actual: np.ndarray, expected: np.ndarray) -> bool:
    if actual.shape != expected.shape:
        return False
    if expected.dtype.kind in "OSU":
        return bool(np.array_equal(strings(actual), strings(expected)))
    return bool(np.array_equal(actual, expected, equal_nan=True))


class Checks:
    def __init__(self) -> None:
        self.errors: list[str] = []
        self.count = 0

    def require(self, condition: Any, message: str) -> bool:
        self.count += 1
        ok = bool(condition)
        if not ok:
            self.errors.append(message)
        return ok

    def equal(self, actual: Any, expected: Any, label: str) -> None:
        self.require(exactly_equal(np.asarray(actual), np.asarray(expected)), label + ": value mismatch")


def pose_check(actual: np.ndarray, source: np.ndarray, checks: Checks, label: str) -> None:
    if not checks.require(actual.shape == source.shape and actual.shape[-1:] == (6,), label + ": pose shape mismatch"):
        return
    if not checks.require(np.isfinite(actual).all() and np.isfinite(source).all(), label + ": nonfinite pose"):
        return
    checks.require(np.allclose(actual[:, :3], source[:, :3], atol=1e-10, rtol=0), label + ": position changed")
    expected_rotation = Rotation.from_euler("xyz", source[:, 3:]).as_matrix()
    exported_rotation = Rotation.from_rotvec(actual[:, 3:]).as_matrix()
    checks.require(np.allclose(exported_rotation, expected_rotation, atol=1e-10, rtol=0), label + ": Euler-to-rotvec rotation mismatch")
    roundtrip = Rotation.from_rotvec(Rotation.from_matrix(exported_rotation).as_rotvec()).as_matrix()
    checks.require(np.allclose(roundtrip, expected_rotation, atol=1e-10, rtol=0), label + ": rotation roundtrip mismatch")


def gripper_check(actual: np.ndarray, source_closure: np.ndarray, checks: Checks) -> None:
    """Independently verify slot 28 opening against untouched native closure."""
    checks.equal(actual, (1 - source_closure).reshape(-1, 1),
                 "normalized gripper opening must equal 1 - native closure")
    checks.require(np.isfinite(actual).all() and np.all((actual >= 0) & (actual <= 1)),
                   "normalized gripper opening must be finite and within [0, 1]")


def offset_check(original: np.ndarray, derived: np.ndarray, extension: float, checks: Checks, label: str) -> None:
    expected = original[:, :3] + Rotation.from_euler("xyz", original[:, 3:]).apply([0.0, 0.0, extension])
    checks.require(np.allclose(derived[:, :3], expected, atol=1e-10, rtol=0), label + ": local +Z offset formula mismatch")
    checks.equal(derived[:, 3:], original[:, 3:], label + ": offset must retain original orientation")


def scan_rgb_rows(rgb: Any, span: slice, checks: Checks, label: str) -> int:
    """Read every RGB row in batches, independently of Zarr's chunk length."""
    tested = 0
    for pos in range(span.start, span.stop, 32):
        stop = min(pos + 32, span.stop)
        image_rows = np.asarray(rgb[pos:stop])
        checks.require(image_rows.dtype == np.uint8 and image_rows.shape == (stop - pos, 360, 640, 3),
                       label + ": decoded RGB batch malformed")
        tested += len(image_rows)
    return tested


def find_audit(root: Path, explicit: Path | None) -> Path | None:
    if explicit is not None:
        return explicit
    for path in (root / "metadata/selected_sources_audit.json",
                 root / "provenance/selected_sources_audit.json",
                 root / "selected_sources_audit.json",
                 root.parent / "oxt_export_work/selected_sources_audit.json"):
        if path.is_file():
            return path
    return None


def validate_episode(data: Any, span: slice, package_root: Path, relative_native: str,
                     episode_id: str, episode_name: str, audit: dict | None,
                     scan_rgb_all: bool) -> dict:
    checks = Checks()
    result: dict[str, Any] = {"episode_id": episode_id, "episode_name": episode_name,
                              "native_path": relative_native, "errors": checks.errors}
    rel = Path(relative_native)
    if not checks.require(not rel.is_absolute() and ".." not in rel.parts and rel.parts[:1] == ("native",), "native path must be a relative path under native/"):
        return result
    source_dir = package_root / rel
    with h5py.File(source_dir / "trajectory.h5", "r") as source, h5py.File(source_dir / "ft_sensor.h5", "r") as ft:
        rows = np.asarray(data["source_control_row"][span])
        raw_T = int(source["action/joint_position"].shape[0])
        result.update(control_rows_exported=int(len(rows)), control_rows_native=raw_T,
                      control_rows_omitted=raw_T - len(rows))
        if not checks.require(rows.ndim == 1 and rows.dtype.kind in "iu" and rows.size > 0
                              and np.all(rows >= 0) and np.all(rows < raw_T)
                              and np.all(np.diff(rows.astype(np.int64)) > 0), "source_control_row must be increasing valid integer indices"):
            return result
        rows = rows.astype(np.int64)
        checks.require(bool(source.attrs.get("complete", False)), "native trajectory incomplete")
        checks.require(bool(source.attrs.get("success", False)), "native episode is not operator success")
        checks.require(not text_value(source.attrs.get("collection_error", "")), "native trajectory collection_error is nonempty")
        checks.require(text_value(source.attrs.get("episode_id", "")) == episode_id, "native episode_id mismatch")
        original_name = text_value(source.attrs.get("time", ""))
        result["original_episode_name"] = original_name
        result["episode_name_normalization"] = (
            "unchanged" if episode_name == original_name else "colon_to_hyphen_portable_variant"
            if episode_name_matches(original_name, episode_name) else "invalid"
        )
        checks.require(episode_name_matches(original_name, episode_name),
                       "native episode_name mismatch: expected exact original or colon-to-hyphen portable variant")
        checks.require(bool(ft.attrs.get("complete", False)), "native FT stream incomplete")

        # Check every raw row dataset, including controller diagnostics, actions,
        # camera calibration and clocks. Strings change storage dtype only.
        row_paths: list[str] = []
        source.visititems(lambda name, obj: row_paths.append(name)
                          if isinstance(obj, h5py.Dataset) and obj.ndim > 0 and obj.shape[0] == raw_T else None)
        result["native_row_datasets"] = len(row_paths)
        for path in row_paths:
            key = native_key(path)
            if not checks.require(key in data, "missing native field " + key):
                continue
            expected = source[path][rows]
            actual = np.asarray(data[key][span])
            checks.equal(actual, expected, key)
            if expected.dtype.kind not in "OSU":
                checks.require(actual.dtype == expected.dtype, key + ": numeric dtype changed")
            if actual.dtype.kind in "fc":
                checks.require(np.isfinite(actual).all(), key + ": contains nonfinite numeric values")
        exported_native = {key for key in data.array_keys() if key.startswith("native__")}
        checks.require(exported_native == {native_key(path) for path in row_paths}, "native field set differs from source row dataset set")

        def raw(path: str) -> np.ndarray:
            return np.asarray(source[path][rows])

        def out(key: str) -> np.ndarray:
            return np.asarray(data[key][span])

        checks.equal(out("right_arm_joints"), raw("observation/robot_state/joint_positions"), "standard arm state")
        gripper_check(out("right_hand_joints"), raw("observation/robot_state/gripper_position"), checks)
        checks.equal(out("action_joint_position"), raw("action/joint_position"), "actual joint targets")
        for key, path in POSE_SOURCES.items():
            pose_check(out(key), raw(path), checks, key)

        capture = json.loads(text_value(source.attrs.get("capture_metadata_json", "{}")))
        # The mounting value is also present in FT config metadata. Do not infer
        # a sensor or TCP transform from it.
        config = json.loads(text_value(ft.attrs.get("config_json", "{}")))
        mounting = capture.get("mounting") or config.get("mounting", {})
        extension = mounting.get("axial_extension_m")
        if checks.require(isinstance(extension, (int, float)) and not isinstance(extension, bool)
                          and np.isfinite(extension) and abs(extension - 0.063) < 1e-12,
                          "recorded mounting extension must be 0.063 m"):
            checks.require(mounting.get("axis") == "eef_local_+z", "mounting offset axis is not eef_local_+z")
            for prefix in ("action", "observation/robot_state"):
                offset_check(raw(prefix + "/cartesian_position"), raw(prefix + "/cartesian_position_with_ft_offset"),
                             float(extension), checks, prefix)

        unix_ns = raw("observation/timestamp/control/step_start_unix_ns")
        start_ns = int(source["observation/timestamp/control/step_start_unix_ns"][0])
        checks.equal(out("timestamp_unix_ns"), unix_ns, "exact host timestamp")
        expected_times = (unix_ns - start_ns).astype(np.float64) / 1e9
        checks.require(np.allclose(out("timestamps"), expected_times, atol=1e-12, rtol=0), "relative timestamps differ from native host step_start")
        checks.require(np.all(np.diff(out("timestamps")) > 0), "relative timestamps not strictly increasing")
        checks.require(np.all(np.diff(unix_ns) > 0), "host timestamps not strictly increasing")
        dispatched = raw("action/command_dispatched")
        skip = raw("observation/timestamp/skip_action")
        checks.equal(out("command_dispatched"), dispatched, "command dispatch extension")
        checks.equal(dispatched, ~skip, "command_dispatched must be inverse of skip_action")
        result["command_dispatched"] = int(np.count_nonzero(dispatched))
        result["skipped_actions"] = int(np.count_nonzero(skip))

        samples = ft["samples"]
        F = int(samples["wrench"].shape[0])
        result["ft_samples_native"] = F
        checks.require(F > 0 and samples["wrench"].shape == (F, 6), "full FT wrench shape invalid")
        for key, obj in samples.items():
            checks.require(obj.shape[0] == F, "FT sidecar length mismatch: " + key)
        checks.equal(samples["sample_index"][:], np.arange(F), "full FT sequence indices")
        checks.require(np.isfinite(samples["wrench"][:]).all(), "full FT stream contains nonfinite wrench")
        receive_ns = samples["receive_monotonic_ns"][:]
        request_ns = samples["request_monotonic_ns"][:]
        checks.require(np.all(np.diff(receive_ns) > 0), "full FT receive clock not strictly increasing")
        checks.require(np.all(request_ns <= receive_ns), "FT request occurs after receive")
        for attr in ("samples_received", "samples_written"):
            checks.require(int(ft.attrs.get(attr, -1)) == F, "FT " + attr + " differs from saved stream length")
        indices = raw("observation/ft_sensor/sample_index")
        if checks.require(indices.dtype.kind in "iu" and np.all(indices >= 0) and np.all(indices < F)
                          and np.all(np.diff(indices) >= 0), "FT snapshot indices invalid"):
            for key in ("sample_index", "wrench", "packet_no", "packet_delta", "packet_discontinuity",
                        "request_monotonic_ns", "request_unix_ns", "receive_monotonic_ns", "receive_unix_ns"):
                # Reading full small 100 Hz numeric arrays also allows repeated indices.
                checks.equal(raw("observation/ft_sensor/" + key), samples[key][:][indices], "FT snapshot " + key)
        checks.require(np.all(raw("observation/ft_sensor/valid")), "invalid FT snapshot exported")
        snapshot = raw("observation/ft_sensor/snapshot_monotonic_ns")
        received = raw("observation/ft_sensor/receive_monotonic_ns")
        checks.require(np.all(received <= snapshot), "FT snapshot uses future received sample")
        checks.require(np.all(snapshot <= raw("observation/timestamp/robot_state/read_start_monotonic_ns")), "FT snapshot follows robot read start")
        checks.require(np.allclose(raw("observation/ft_sensor/age_s"), (snapshot - received) / 1e9, atol=1e-12, rtol=0), "FT age does not match host monotonic clocks")
        wrench = raw("observation/ft_sensor/wrench")
        checks.equal(out("ft_wrench"), wrench, "full six-axis aligned FT")
        checks.equal(out("supplementary_tactile"), wrench, "supplementary six-axis FT")
        checks.equal(out("right_tactile_data_wrist_torque"), wrench[:, None, 3:], "standard wrist torque must be Mx/My/Mz only")

        camera_report = {}
        camera_audit = {c["serial"]: c for c in (audit or {}).get("replay_cameras", [])}
        for role, serial in CAMERAS.items():
            variants = ((role + "_frame_index", "camera_frame_index__" + serial),
                        (role + "_timestamp_ns", "camera_timestamp_unix_ns__" + serial))
            values = []
            for alternatives in variants:
                present = [key for key in alternatives if key in data]
                if not checks.require(bool(present), "missing camera provenance: " + "/".join(alternatives)):
                    values.append(None)
                    continue
                value = out(present[0])
                checks.require(value.shape == (len(rows),) and value.dtype.kind in "iu", present[0] + ": expected integer vector")
                for other in present[1:]:
                    checks.equal(value, out(other), "camera alias " + other)
                values.append(value)
            frame_indices, frame_times = values
            if frame_indices is not None:
                checks.require(np.all(frame_indices >= 0) and np.all(np.diff(frame_indices) > 0), role + ": invalid/repeated frame index")
            if frame_times is not None:
                checks.require(np.all(np.diff(frame_times) > 0), role + ": camera timestamps not strictly increasing")
                checks.equal(frame_times // 1_000_000, raw("observation/timestamp/cameras/" + serial + "_frame_received"), role + ": SDK timestamp must match original H5 milliseconds")
            known = camera_audit.get(serial)
            if known is not None and frame_indices is not None:
                N = int(known["decoded_frames"])
                checks.require(np.all(frame_indices < N), role + ": frame index exceeds audited SVO count")
                # The frozen selection has two complete, H5-aligned T-1 prefixes.
                if N == raw_T - 1 and int(known.get("svo_timestamps_matched_to_trajectory", -1)) == N:
                    checks.equal(rows, np.arange(N), role + ": not all audited real-image control rows retained")
                    checks.equal(frame_indices, np.arange(N), role + ": real-image frame index mapping differs from audited prefix")
                    if frame_times is not None:
                        checks.require(int(frame_times[0]) == int(known["first_image_unix_ns"]), role + ": first exact SDK timestamp differs from audit")
                        checks.require(int(frame_times[-1]) == int(known["last_image_unix_ns"]), role + ": last exact SDK timestamp differs from audit")
            rgb = data[role + "_rgb"]
            tested = 0
            if scan_rgb_all:
                tested = scan_rgb_rows(rgb, span, checks, role)
            else:
                for pos in sorted({span.start, span.stop - 1}):
                    frame = np.asarray(rgb[pos])
                    checks.require(frame.shape == (360, 640, 3) and frame.dtype == np.uint8, role + ": sampled RGB frame malformed")
                    tested += 1
            camera_report[serial] = {"role": role, "rows": len(rows), "rgb_rows_read": tested,
                                     "source_count_evidence": known is not None}
        result["cameras"] = camera_report
        if audit is not None:
            checks.require(int(audit["control_steps"]) == raw_T, "source audit native control count mismatch")
            checks.require(int(audit["ft_samples"]) == F, "source audit full FT count mismatch")
    result["checks"] = checks.count
    result["passed"] = not checks.errors
    return result


def validate_export(root: Path, source_audit: Path | None = None, scan_rgb_all: bool = False) -> dict:
    import zarr

    root = root.resolve()
    checks = Checks()
    audit_path = find_audit(root, source_audit)
    audit_doc = json.loads(audit_path.read_text()) if audit_path else None
    audit_by_id = {e["episode_id"]: e for e in (audit_doc or {}).get("episodes", [])}
    result: dict[str, Any] = {
        "schema": "franka-ft-oxt-validation-v1", "dataset_root": str(root),
        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
        "source_audit": str(audit_path) if audit_path else None,
        "errors": checks.errors, "tasks": {},
        "scope": {"native_row_arrays": "all retained rows and all original row datasets compared exactly",
                  "ft_stream": "all saved samples counted and checked; all aligned snapshots compared",
                  "rgb": "all chunks read" if scan_rgb_all else "first and last retained frame of each episode read",
                  "svo_decoding": "not repeated; existing source audit count/timestamp evidence used",
                  "hash_verification": "separate process; not performed here",
                  "physical_calibration": "not validated",
                  "oxt_canonical_wrist_or_tcp_alignment": "not established; standard right_wrist_pose omitted, right_arm_joints provided; native flange observations retained as native__ fields",
                  "gripper_slot_28": "normalized opening = 1 - native closure; 0=closed, 1=open; dimensionless"},
        "limitations": ["This report establishes preservation and numeric consistency, not physical accuracy or final OXT acceptance.",
                        "Native FT axes/origin and N/Nm unit confirmation remain as recorded; no TCP/base transform or software bias/gravity compensation is inferred.",
                        "Logged camera extrinsics are historical calibration estimates; validity after FT mounting is unconfirmed."],
    }
    if audit_doc is None:
        result["limitations"].append("No source selection audit supplied; exact selected episode membership and SVO count evidence were not verified.")
    found = {p.stem for p in (root / "zarr").glob("*.zarr")}
    checks.require(found == set(TASKS), "expected exactly four task Zarr groups: " + ", ".join(TASKS))
    exported_ids: list[str] = []
    for task in TASKS:
        task_result: dict[str, Any] = {"episodes": [], "errors": []}
        result["tasks"][task] = task_result
        local = Checks()
        task_result["errors"] = local.errors
        try:
            group = zarr.open_group(str(root / "zarr" / (task + ".zarr")), mode="r")
            local.require(int(group.metadata.zarr_format) == 2, "expected Zarr format 2")
            data, meta = group["data"], group["meta"]
            ends = np.asarray(meta["episode_ends"][:])
            if not local.require(ends.ndim == 1 and ends.dtype.kind in "iu" and len(ends) > 0
                                 and ends[0] > 0 and np.all(np.diff(ends.astype(np.int64)) > 0), "episode_ends must be positive increasing integer vector"):
                continue
            T = int(ends[-1])
            task_result["frames"] = T
            for key in data.array_keys():
                local.require(data[key].ndim >= 1 and data[key].shape[0] == T, key + ": inconsistent first dimension")
            for key, tail in STANDARD_SHAPES.items():
                local.require(key in data and data[key].shape == (T,) + tail, key + ": missing or wrong shape")
            local.require("right_wrist_pose" not in data,
                          "right_wrist_pose must be omitted until a verified FTP-1 gripper-frame transform is available")
            for role in CAMERAS:
                key = role + "_rgb"
                local.require(key in data and data[key].shape == (T, 360, 640, 3) and data[key].dtype == np.uint8, key + ": expected uint8(T,360,640,3)")
            for key in ("episode_ids", "episode_names", "source_episode_paths"):
                local.require(key in meta and meta[key].shape == ends.shape, "meta/" + key + ": missing or wrong shape")
            if local.errors:
                continue
            local.require(np.all(data["right_hand_joints_idx"][:] == 28), "gripper slot must be 28")
            local.require(data["right_hand_joints_idx"].dtype.kind in "iu", "gripper slot dtype must be integer")
            local.require(np.all(data["right_tactile_area_wrist_torque"][:] == 15), "wrist torque area must be 15")
            local.require(data["right_tactile_area_wrist_torque"].dtype.kind in "iu", "wrist torque area dtype must be integer")
            local.require(data["timestamp_unix_ns"].dtype == np.dtype("int64"), "timestamp_unix_ns must preserve int64 precision")
            local.require(data["command_dispatched"].dtype == np.dtype("bool"), "command_dispatched must retain boolean dtype")
            local.require(np.all(strings(data["right_tactile_type_wrist_torque"][:]) == "state"), "wrist torque type must be state")
            local.require(np.all(strings(data["right_tactile_sensor_wrist_torque"][:]) == "SRIM3813A1"), "unexpected wrist torque sensor identifier")
            instructions = strings(data["sub_task_instruction"][:])
            local.require(bool(np.all(np.char.str_len(np.char.strip(instructions)) > 0)), "empty task instruction")
            for key in STANDARD_SHAPES:
                if data[key].dtype.kind in "fc":
                    local.require(np.isfinite(data[key][:]).all(), key + ": nonfinite standard values")
            ids = strings(meta["episode_ids"][:]).tolist()
            names = strings(meta["episode_names"][:]).tolist()
            paths = strings(meta["source_episode_paths"][:]).tolist()
            local.require(len(ids) == len(set(ids)), "duplicate episode IDs within task")
            local.require(len(paths) == len(set(paths)), "duplicate native episode paths within task")
            start = 0
            for index, end in enumerate(ends):
                episode_id = ids[index]
                exported_ids.append(episode_id)
                known = audit_by_id.get(episode_id)
                if audit_doc is not None:
                    local.require(known is not None, "episode absent from source audit: " + episode_id)
                    if known is not None:
                        expected_task = "insert_pen" if known["task_slug"] == "insert" else known["task_slug"]
                        local.require(expected_task == task, "episode assigned to wrong task: " + episode_id)
                try:
                    ep = validate_episode(data, slice(start, int(end)), root, paths[index], episode_id,
                                          names[index], known, scan_rgb_all)
                except Exception as exc:
                    ep = {"episode_id": episode_id, "episode_name": names[index], "passed": False,
                          "errors": [f"{type(exc).__name__}: {exc}"]}
                task_result["episodes"].append(ep)
                start = int(end)
            task_result["checks"] = local.count
        except Exception as exc:
            local.errors.append(f"{type(exc).__name__}: {exc}")
        finally:
            task_result["passed"] = not local.errors and bool(task_result["episodes"]) and all(e.get("passed", False) for e in task_result["episodes"])
    checks.require(len(exported_ids) == len(set(exported_ids)), "duplicate episode IDs across tasks")
    if audit_doc is not None:
        checks.require(set(exported_ids) == set(audit_by_id), "exported episode set differs from frozen source audit")
    episodes = [e for task in result["tasks"].values() for e in task["episodes"]]
    result["summary"] = {
        "tasks": len(result["tasks"]), "episodes": len(episodes),
        "standard_frames": sum(t.get("frames", 0) for t in result["tasks"].values()),
        "native_control_rows": sum(e.get("control_rows_native", 0) for e in episodes),
        "omitted_standard_control_rows": sum(e.get("control_rows_omitted", 0) for e in episodes),
        "native_ft_samples": sum(e.get("ft_samples_native", 0) for e in episodes),
        "failed_episodes": sum(not e.get("passed", False) for e in episodes),
    }
    result["passed"] = not checks.errors and all(t["passed"] for t in result["tasks"].values())
    return result


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset-root", type=Path, required=True)
    parser.add_argument("--report", type=Path, required=True)
    parser.add_argument("--source-audit", type=Path)
    parser.add_argument("--scan-rgb-all", action="store_true", help="Read all exported RGB chunks instead of per-episode endpoints")
    args = parser.parse_args(argv)
    try:
        report = validate_export(args.dataset_root, args.source_audit, args.scan_rgb_all)
    except Exception as exc:
        report = {"schema": "franka-ft-oxt-validation-v1", "passed": False,
                  "errors": [f"{type(exc).__name__}: {exc}"]}
    args.report.parent.mkdir(parents=True, exist_ok=True)
    temporary = args.report.with_name(args.report.name + ".partial")
    temporary.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
    temporary.replace(args.report)
    print(json.dumps({"passed": report["passed"], "report": str(args.report), "summary": report.get("summary"),
                      "errors": report["errors"]}, ensure_ascii=False))
    return 0 if report["passed"] else 1


if __name__ == "__main__":
    sys.exit(main())