File size: 27,831 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""``explicit-data`` — ingest, decontamination, rendering, and group assembly.

Implemented subcommands:

  freeze-eval    Freeze the evaluation registry write-once before any training
                 ingest (``docs/02`` §3). Refuses to overwrite a frozen registry.
  ingest         Normalize one training source to ``normalized/<source>/<split>``.
                 Hard-refuses MathVista (training-prohibited) and skips BBox DocVQA
                 when its dual approval gate is not cleared.
  fingerprint    Compute exact/pHash/MinHash fingerprints into a SQLite index
                 (``docs/02`` §5.1). Operates on normalized items.jsonl files or,
                 for eval, the registry's companion items file.
  decontaminate  Match train fingerprints against the eval index and
                 automatically reject exact and near duplicates.
  scan-plotqa-prefix
                 Verify and summarize the pinned PlotQA source prefixes.
  build-certified-release
                 Build the fixed C1 five-state train/evaluation release.
  replay-certificates
                 Independently replay every persisted view certificate.

The remaining subcommands are documented but not yet implemented: they exit 2
(never a silent success, per the runbook).
"""

from __future__ import annotations

import argparse
import json
import sys
from collections.abc import Callable, Mapping
from pathlib import Path
from typing import Any

from .. import contamination, ingest
from ..atomic_io import read_jsonl
from ..config import (
    ConfigError,
    ExperimentConfig,
    ResourcesManifest,
    load_config_pair,
    load_resources,
)
from ..ingest import base as ingest_base
from ..ingest.base import IngestError
from ..logging_setup import get_logger
from ..paths import data_root, repo_root
from ..resources import load_approval
from ._stub import dispatch

_PROG = "explicit-data"
logger = get_logger("data")

_SUBCOMMANDS = {
    "freeze-eval": "Freeze the evaluation registry before any training ingest (P2).",
    "ingest": "Normalize a source dataset to the common item schema (P2).",
    "fingerprint": "Compute exact/pHash/MinHash fingerprints into SQLite (P3).",
    "decontaminate": "Reject/near-duplicate match train vs eval (P3).",
    "scan-plotqa-prefix": "Compile and count executable D15 PlotQA prefix rows.",
    "build-certified-release": "Build the fixed PlotQA C1 train/eval release.",
    "replay-certificates": "Replay every persisted certificate in one split.",
    "build-evi-core-release": "Build PlotQA+GQA+CLEVR EVI core v2.",
    "replay-evi-core-release": "Replay every certificate in EVI core v2.",
    "validate-evi-core-release": "Schema/admission-check EVI core v2.",
    "validate-full": "Teacher/verifier blind validation of FULL problems (P4/P7).",
    "propose-dependencies": "Teacher dependency/region proposal (P5).",
    "localize": "OCR/SAM/CV region localization (P5).",
    "render": "Deterministic intervention rendering (P6).",
    "blind-relabel": "Teacher/verifier blind re-solve of transformed views (P7).",
    "reconcile": "Reconcile solver labels into states (P7).",
    "build-groups": "Assemble intervention groups (P7).",
    "validate-groups": "Validate groups against schema + invariants (P7).",
    "manifest": "Build a dataset manifest (P7).",
    "sample-candidates": "Sample dry-run candidates (P6).",
    "build-pilot": "Build the accepted 2K pilot (P6).",
    "produce-silver": "Produce silver train at scale (P7).",
}


def _add_config_args(parser: argparse.ArgumentParser) -> None:
    parser.add_argument(
        "--resources",
        type=Path,
        default=repo_root() / "configs" / "resources.yaml",
    )
    parser.add_argument(
        "--experiment",
        type=Path,
        default=repo_root() / "configs" / "experiment.yaml",
    )


def _utc_now() -> str:
    from datetime import UTC, datetime

    return datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")


class _Handled(Exception):
    """Internal control-flow signal that a nonzero exit has already been printed."""

    def __init__(self, code: int) -> None:
        super().__init__()
        self.code = code


def _load_pair(
    args: argparse.Namespace,
) -> tuple[ResourcesManifest, ExperimentConfig]:
    try:
        return load_config_pair(args.resources, args.experiment)
    except (ConfigError, FileNotFoundError) as exc:
        print(f"{_PROG}: config load failed: {exc}", file=sys.stderr)
        raise _Handled(1) from exc


# --- freeze-eval -----------------------------------------------------------


def cmd_freeze_eval(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(prog=f"{_PROG} freeze-eval")
    _add_config_args(parser)
    parser.add_argument(
        "--rows-dir",
        type=Path,
        required=True,
        help="directory holding <source>.<split>.jsonl native-row files.",
    )
    parser.add_argument(
        "--image-root",
        type=Path,
        default=None,
        help="root directory for native image refs (visual eval sources).",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help="registry output (default <data_root>/registry/evaluation_items.v1.jsonl).",
    )
    parser.add_argument(
        "--force", action="store_true", help="overwrite an existing frozen registry."
    )
    parser.add_argument(
        "--resume",
        action="store_true",
        help="verify an existing registry matches the computed freeze (idempotent).",
    )
    args = parser.parse_args(argv)

    try:
        resources, experiment = _load_pair(args)
    except _Handled as exc:
        return exc.code

    plan = ingest.eval_freeze_plan(experiment)
    resolved_plan = [
        ingest.EvalSourceSpec(
            name=spec.name,
            config=spec.config,
            split=spec.split if spec.from_gold else ingest.default_split_for(spec.name, resources),
            from_gold=spec.from_gold,
        )
        for spec in plan
    ]

    output = args.output or (data_root() / "registry" / "evaluation_items.v1.jsonl")
    try:
        frozen = ingest.freeze_eval(
            resolved_plan,
            resources,
            rows_dir=args.rows_dir,
            image_root=args.image_root,
            output_path=output,
            force=args.force,
            resume=args.resume,
        )
    except ingest.RegistryFrozenError as exc:
        print(f"{_PROG} freeze-eval: {exc}", file=sys.stderr)
        return 1
    except ingest.IngestError as exc:
        print(f"{_PROG} freeze-eval: {exc}", file=sys.stderr)
        return 1

    print(
        json.dumps(
            {
                "registry_path": str(frozen.path),
                "registry_sha256": frozen.sha256,
                "row_count": frozen.row_count,
                "sources": [s.name for s in resolved_plan],
            },
            sort_keys=True,
        )
    )
    return 0


# --- ingest ----------------------------------------------------------------


def cmd_ingest(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(prog=f"{_PROG} ingest")
    src_group = parser.add_mutually_exclusive_group(required=True)
    src_group.add_argument(
        "--source",
        help="structured source name (plotqa/geometry3k); reads from raw/<source>.",
    )
    src_group.add_argument("--resource", help="HF dataset resource logical name.")
    parser.add_argument("--split", required=True, help="source split to ingest.")
    parser.add_argument(
        "--rows",
        type=Path,
        default=None,
        help="native-row JSONL file for this source/split (HF --resource path).",
    )
    parser.add_argument(
        "--image-root",
        type=Path,
        default=None,
        help="root directory for native image refs (HF --resource path).",
    )
    parser.add_argument(
        "--raw-dir",
        type=Path,
        default=None,
        help="materialized raw dir for a structured --source (default <data_root>/raw/<source>).",
    )
    parser.add_argument(
        "--config",
        default="default",
        help="source config name (MMMU: subject).",
    )
    parser.add_argument("--approval", type=Path, default=None, help="resource_approval.json path.")
    parser.add_argument(
        "--resources",
        type=Path,
        default=repo_root() / "configs" / "resources.yaml",
    )
    parser.add_argument(
        "--eval-registry",
        type=Path,
        default=None,
        help="frozen evaluation registry path (required for train ingest).",
    )
    parser.add_argument(
        "--no-require-eval-registry",
        action="store_true",
        help="allow train ingest before the eval registry is frozen (testing only).",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help="output dir (default <data_root>/normalized/<name>/<split>).",
    )
    parser.add_argument(
        "--config-sha256",
        default="",
        help="canonical config hash to record in the ingest manifest.",
    )
    args = parser.parse_args(argv)

    try:
        resources = load_resources(args.resources)
    except (ConfigError, FileNotFoundError) as exc:
        print(f"{_PROG} ingest: resources load failed: {exc}", file=sys.stderr)
        return 1

    # Structured-source path (PlotQA/Geometry3K C1): reads from a materialized
    # raw dir; --rows/--image-root do not apply.
    if args.source is not None:
        return _ingest_structured(args, resources)

    return _ingest_dataset(args, resources)


def _ingest_structured(args: argparse.Namespace, resources: Any) -> int:
    name = args.source
    assert name is not None
    if name not in resources.structured_sources:
        print(f"{_PROG} ingest: unknown structured source {name!r}", file=sys.stderr)
        return 1
    cfg = resources.structured_sources[name]
    revision = cfg.get("revision", "")
    raw_dir = args.raw_dir or (data_root() / "raw" / name)
    output = args.output or (data_root() / "normalized" / name / args.split)
    expected_sha256 = cfg.get("expected_sha256") or None
    try:
        result = ingest.ingest_structured_source(
            name,
            args.split,
            raw_dir,
            output,
            revision=revision,
            source_config=cfg,
            expected_sha256=expected_sha256,
            eval_registry_path=args.eval_registry,
            require_eval_registry=not args.no_require_eval_registry,
            config_sha256=args.config_sha256,
            created_at=_utc_now(),
        )
    except ingest.IngestError as exc:
        print(f"{_PROG} ingest: {exc}", file=sys.stderr)
        return 1

    print(
        json.dumps(
            {
                "source": result.source,
                "split": result.split,
                "written": result.written,
                "dropped": result.dropped,
                "output": str(result.output_path),
            },
            sort_keys=True,
        )
    )
    return 0


def _ingest_dataset(args: argparse.Namespace, resources: Any) -> int:
    if args.resource not in resources.datasets:
        print(f"{_PROG} ingest: unknown resource {args.resource!r}", file=sys.stderr)
        return 1
    revision = resources.datasets[args.resource].revision
    approval = load_approval(args.approval)

    if args.rows is None or not args.rows.exists():
        print(f"{_PROG} ingest: rows file not found: {args.rows}", file=sys.stderr)
        return 1
    rows = ingest.read_native_rows(args.rows)
    resolver = ingest_base.DirectoryImageResolver(args.image_root) if args.image_root else None
    if resolver is None and args.resource != "bbox_docvqa_train":
        print(
            f"{_PROG} ingest: --image-root is required for source {args.resource!r}",
            file=sys.stderr,
        )
        return 1

    output = args.output or (data_root() / "normalized" / args.resource / args.split)
    try:
        result = ingest.ingest_source(
            args.resource,
            args.split,
            rows,
            resolver,  # type: ignore[arg-type]
            output,
            revision=revision,
            config=args.config,
            approval=approval,
            eval_registry_path=args.eval_registry,
            require_eval_registry=not args.no_require_eval_registry,
            config_sha256=args.config_sha256,
            created_at=_utc_now(),
        )
    except ingest.IngestError as exc:
        print(f"{_PROG} ingest: {exc}", file=sys.stderr)
        return 1

    print(
        json.dumps(
            {
                "source": result.source,
                "split": result.split,
                "written": result.written,
                "dropped": result.dropped,
                "output": str(result.output_path),
            },
            sort_keys=True,
        )
    )
    return 0


# --- fingerprint -----------------------------------------------------------


def _collect_input_files(args: argparse.Namespace) -> list[Path]:
    if args.input is not None:
        path = Path(args.input)
        if path.is_dir():
            return sorted(path.rglob("items.jsonl"))
        # A single items.jsonl (or a registry path whose companion is read later).
        return [path] if path.is_file() else []
    return sorted(Path(args.input_root).rglob("items.jsonl"))


def _is_registry_row(row: Mapping[str, Any]) -> bool:
    """A frozen registry row carries ``native_id`` but no ``question`` text."""
    return "question" not in row and "native_id" in row


def _pick_image_base(file_path: Path, rows: list[dict[str, Any]]) -> Path | None:
    """Auto-detect the image root for a file's rows, or None if text-only."""
    for row in rows:
        paths = row.get("image_paths") or []
        if paths:
            first = paths[0]
            for candidate in (file_path.parent, file_path.parent / "eval_images"):
                if (candidate / first).exists():
                    return candidate
            raise IngestError(f"cannot resolve image {first!r} for {file_path}; pass --image-base")
    return None


def _make_resolver(base_dir: Path) -> Callable[[str], Path]:
    def resolve(ref: str) -> Path:
        path = base_dir / ref
        if not path.exists():
            raise IngestError(f"image not found: {path}")
        return path

    return resolve


def cmd_fingerprint(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(prog=f"{_PROG} fingerprint")
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--input", type=Path, help="items.jsonl file or directory.")
    group.add_argument("--input-root", type=Path, help="root to glob items.jsonl under.")
    parser.add_argument(
        "--image-base", type=Path, default=None, help="image root (auto-detected if omitted)."
    )
    parser.add_argument("--db", type=Path, required=True, help="SQLite index output.")
    args = parser.parse_args(argv)

    files = _collect_input_files(args)
    if not files:
        print(f"{_PROG} fingerprint: no items.jsonl found", file=sys.stderr)
        return 1

    fingerprints: list[contamination.Fingerprints] = []
    sources: set[str] = set()
    for file_path in files:
        rows = [dict(r) for r in read_jsonl(file_path)]
        # A frozen registry has no text/pixels; use its companion items file when present.
        if rows and _is_registry_row(rows[0]):
            companion = file_path.with_name(file_path.stem + ".items.jsonl")
            if companion.exists():
                rows = [dict(r) for r in read_jsonl(companion)]
                file_path = companion
            else:
                print(
                    f"{_PROG} fingerprint: {file_path} is a registry without a companion "
                    "items file; text/pHash fingerprints unavailable",
                    file=sys.stderr,
                )
        base_dir = (
            args.image_base if args.image_base is not None else _pick_image_base(file_path, rows)
        )
        resolve_image = _make_resolver(base_dir) if base_dir is not None else None
        try:
            for row in rows:
                fp = contamination.fingerprint_row(row, resolve_image=resolve_image)
                fingerprints.append(fp)
                sources.add(fp.source)
        except IngestError as exc:
            print(f"{_PROG} fingerprint: {exc}", file=sys.stderr)
            return 1

    count = contamination.index.write_fingerprints(args.db, fingerprints)
    print(
        json.dumps(
            {"db": str(args.db), "row_count": count, "sources": sorted(sources)}, sort_keys=True
        )
    )
    return 0


# --- decontaminate ---------------------------------------------------------


def cmd_decontaminate(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(prog=f"{_PROG} decontaminate")
    parser.add_argument("--train-db", type=Path, required=True)
    parser.add_argument("--eval-db", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True, help="train allowlist JSONL.")
    parser.add_argument(
        "--near-duplicate-rejects",
        "--review-queue",
        dest="near_duplicate_rejects",
        type=Path,
        required=True,
        help="immutable auto-rejected near-duplicate JSONL (legacy alias: --review-queue).",
    )
    args = parser.parse_args(argv)

    for label, path in (("train-db", args.train_db), ("eval-db", args.eval_db)):
        if not path.exists():
            print(f"{_PROG} decontaminate: {label} not found: {path}", file=sys.stderr)
            return 1

    summary = contamination.match.decontaminate_dbs(
        str(args.train_db),
        str(args.eval_db),
        allowlist_path=str(args.output),
        review_path=str(args.near_duplicate_rejects),
    )
    # The full rejected list is available in the summary; print counts only.
    printable = {k: v for k, v in summary.items() if k != "rejected"}
    print(json.dumps(printable, sort_keys=True))
    return 0


# --- fixed PlotQA C1 release ----------------------------------------------


def cmd_scan_plotqa_prefix(argv: list[str]) -> int:
    from ..datasets.plotqa_prefix import collect_plotqa_candidates

    parser = argparse.ArgumentParser(prog=f"{_PROG} scan-plotqa-prefix")
    parser.add_argument("--annotations", type=Path, required=True)
    parser.add_argument("--qa", type=Path, required=True)
    args = parser.parse_args(argv)
    try:
        result = collect_plotqa_candidates(args.annotations, args.qa)
    except (OSError, ValueError) as exc:
        print(f"{_PROG} scan-plotqa-prefix: {exc}", file=sys.stderr)
        return 1
    print(
        json.dumps(
            {
                "accepted_candidates": len(result.candidates),
                "complete_annotation_items": result.complete_annotation_items,
                "complete_qa_items": result.complete_qa_items,
                "d15_items": result.d15_items,
                "rejection_counts": result.rejection_counts,
            },
            sort_keys=True,
        )
    )
    return 0


def cmd_build_certified_release(argv: list[str]) -> int:
    from ..datasets.release import (
        ReleaseError,
        build_plotqa_release,
        load_release_config,
    )

    parser = argparse.ArgumentParser(prog=f"{_PROG} build-certified-release")
    parser.add_argument("--annotations", type=Path, required=True)
    parser.add_argument("--qa", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument(
        "--release-config",
        type=Path,
        default=repo_root() / "configs" / "release.plotqa-prefix.json",
    )
    parser.add_argument(
        "--code-commit",
        required=True,
        help="clean 40-hex commit containing the exact generator implementation.",
    )
    parser.add_argument(
        "--workers",
        type=int,
        default=8,
        help="Ordered generation worker processes (default: 8; output bytes are invariant).",
    )
    args = parser.parse_args(argv)
    try:
        config = load_release_config(args.release_config)
        summary = build_plotqa_release(
            annotations_prefix=args.annotations,
            qa_prefix=args.qa,
            output_dir=args.output,
            pipeline_code_commit=args.code_commit,
            config=config,
            workers=args.workers,
        )
    except (OSError, ValueError, ReleaseError) as exc:
        print(f"{_PROG} build-certified-release: {exc}", file=sys.stderr)
        return 1
    print(json.dumps(summary.__dict__, sort_keys=True))
    return 0


def cmd_replay_certificates(argv: list[str]) -> int:
    from ..certificates.replay import replay_dataset

    parser = argparse.ArgumentParser(prog=f"{_PROG} replay-certificates")
    parser.add_argument("--dataset", type=Path, required=True)
    parser.add_argument("--report", type=Path, default=None)
    parser.add_argument(
        "--workers",
        type=int,
        default=8,
        help="Ordered certificate-replay worker processes (default: 8).",
    )
    args = parser.parse_args(argv)
    try:
        results = replay_dataset(args.dataset, workers=args.workers)
    except (OSError, ValueError) as exc:
        print(f"{_PROG} replay-certificates: {exc}", file=sys.stderr)
        return 1
    failures = [
        {"view_dir": row.view_dir, "errors": list(row.errors)} for row in results if not row.ok
    ]
    report = {
        "dataset": str(args.dataset),
        "view_count": len(results),
        "passed": len(results) - len(failures),
        "failed": len(failures),
        "failures": failures,
    }
    if args.report is not None:
        from ..atomic_io import atomic_write_json

        atomic_write_json(args.report, report)
    print(json.dumps({key: value for key, value in report.items() if key != "failures"}))
    return 1 if failures else 0


# --- multi-domain EVI core release ----------------------------------------


def cmd_build_evi_core_release(argv: list[str]) -> int:
    from ..datasets.evi_core_release import (
        EviCoreReleaseError,
        build_evi_core_release,
        load_evi_core_release_config,
    )

    parser = argparse.ArgumentParser(prog=f"{_PROG} build-evi-core-release")
    parser.add_argument("--plotqa-release", type=Path, required=True)
    parser.add_argument("--gqa-train-questions", type=Path, required=True)
    parser.add_argument("--gqa-train-scene-graphs", type=Path, required=True)
    parser.add_argument("--gqa-val-questions", type=Path, required=True)
    parser.add_argument("--gqa-val-scene-graphs", type=Path, required=True)
    parser.add_argument("--gqa-image-cache", type=Path, required=True)
    parser.add_argument("--clevr-train-questions", type=Path, required=True)
    parser.add_argument("--clevr-train-scenes", type=Path, required=True)
    parser.add_argument("--clevr-val-questions", type=Path, required=True)
    parser.add_argument("--clevr-val-scenes", type=Path, required=True)
    parser.add_argument("--clevr-blender-executable", type=Path, required=True)
    parser.add_argument("--clevr-dataset-gen-root", type=Path, required=True)
    parser.add_argument("--clevr-blender-runtime-library-dir", type=Path, default=None)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument(
        "--release-config",
        type=Path,
        default=repo_root() / "configs" / "release.evi-core-v2.json",
    )
    parser.add_argument("--code-commit", required=True)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--download-workers", type=int, default=24)
    args = parser.parse_args(argv)
    try:
        summary = build_evi_core_release(
            plotqa_release=args.plotqa_release,
            gqa_train_questions=args.gqa_train_questions,
            gqa_train_scene_graphs=args.gqa_train_scene_graphs,
            gqa_val_questions=args.gqa_val_questions,
            gqa_val_scene_graphs=args.gqa_val_scene_graphs,
            gqa_image_cache=args.gqa_image_cache,
            clevr_train_questions=args.clevr_train_questions,
            clevr_train_scenes=args.clevr_train_scenes,
            clevr_val_questions=args.clevr_val_questions,
            clevr_val_scenes=args.clevr_val_scenes,
            clevr_blender_executable=args.clevr_blender_executable,
            clevr_dataset_gen_root=args.clevr_dataset_gen_root,
            clevr_blender_runtime_library_dir=args.clevr_blender_runtime_library_dir,
            output_dir=args.output,
            pipeline_code_commit=args.code_commit,
            config=load_evi_core_release_config(args.release_config),
            workers=args.workers,
            download_workers=args.download_workers,
        )
    except (OSError, ValueError, EviCoreReleaseError) as exc:
        print(f"{_PROG} build-evi-core-release: {exc}", file=sys.stderr)
        return 1
    print(json.dumps(summary.__dict__, sort_keys=True))
    return 0


def cmd_replay_evi_core_release(argv: list[str]) -> int:
    from ..datasets.evi_core_release import replay_evi_core_release

    parser = argparse.ArgumentParser(prog=f"{_PROG} replay-evi-core-release")
    parser.add_argument("--release", type=Path, required=True)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--report", type=Path, default=None)
    args = parser.parse_args(argv)
    try:
        results = replay_evi_core_release(args.release, workers=args.workers)
    except (OSError, ValueError) as exc:
        print(f"{_PROG} replay-evi-core-release: {exc}", file=sys.stderr)
        return 1
    failures = [
        {"view_dir": row.view_dir, "errors": list(row.errors)} for row in results if not row.ok
    ]
    report = {
        "release": str(args.release),
        "view_count": len(results),
        "passed": len(results) - len(failures),
        "failed": len(failures),
        "failures": failures,
    }
    if args.report is not None:
        from ..atomic_io import atomic_write_json

        atomic_write_json(args.report, report)
    print(json.dumps({key: value for key, value in report.items() if key != "failures"}))
    return 1 if failures else 0


def cmd_validate_evi_core_release(argv: list[str]) -> int:
    from ..datasets.evi_core_release import (
        EviCoreReleaseError,
        validate_evi_core_release,
    )

    parser = argparse.ArgumentParser(prog=f"{_PROG} validate-evi-core-release")
    parser.add_argument("--release", type=Path, required=True)
    args = parser.parse_args(argv)
    try:
        counts = validate_evi_core_release(args.release)
    except (EviCoreReleaseError, OSError, ValueError) as exc:
        print(f"{_PROG} validate-evi-core-release: {exc}", file=sys.stderr)
        return 1
    print(
        json.dumps(
            {
                "release": str(args.release),
                "group_counts": counts,
                "validation_mode": "structural_no_content_hash_replay",
            },
            sort_keys=True,
        )
    )
    return 0


_IMPLEMENTATIONS = {
    "freeze-eval": cmd_freeze_eval,
    "ingest": cmd_ingest,
    "fingerprint": cmd_fingerprint,
    "decontaminate": cmd_decontaminate,
    "scan-plotqa-prefix": cmd_scan_plotqa_prefix,
    "build-certified-release": cmd_build_certified_release,
    "replay-certificates": cmd_replay_certificates,
    "build-evi-core-release": cmd_build_evi_core_release,
    "replay-evi-core-release": cmd_replay_evi_core_release,
    "validate-evi-core-release": cmd_validate_evi_core_release,
}


def main(argv: list[str] | None = None) -> int:
    if argv is None:
        argv = sys.argv[1:]
    return dispatch(_PROG, argv, _SUBCOMMANDS, _IMPLEMENTATIONS)


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