File size: 38,862 Bytes
fde9a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
#!/usr/bin/env python3
"""Read-only integrity validator for the Figure 4 visualization dataset.

The validator never creates, edits, or deletes dataset files.  It checks the
private manifest, the deliberately minimal public baseline jobs, source-image
integrity, ordinal instance metadata, paired-edit invariants, and (when
present) SAM2 masks plus their evaluator-only visualizations.

Use ``--allow-missing-derived`` while the SAM2 outputs are still being built.
All other structural or privacy-hygiene failures remain fatal in that mode.
"""

from __future__ import annotations

import argparse
import json
import math
import re
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable

from PIL import Image, ImageOps


DEFAULT_DATASET_ROOT = Path(__file__).resolve().parents[1]
EXPECTED_CHECKPOINT = Path("/workspace/models_weight/sam/sam2.1_hiera_large.pt")
BASELINE_FIELDS = frozenset({"case_id", "pair", "source_image", "prompt_full"})
PRIVATE_KEY_FRAGMENTS = (
    "bbox",
    "bounding_box",
    "box_xy",
    "mask",
    "locator",
    "target_expression",
    "target_instance",
    "instance_order",
    "sam2_prompt",
    "positive_point",
    "negative_point",
)
CASE_ID_PATTERN = re.compile(r"^[a-z0-9][a-z0-9_\-]*$")


@dataclass(frozen=True)
class Issue:
    level: str
    code: str
    location: str
    message: str


class Validator:
    def __init__(self) -> None:
        self.issues: list[Issue] = []
        self.checks = 0
        self.stats: Counter[str] = Counter()

    @property
    def errors(self) -> list[Issue]:
        return [issue for issue in self.issues if issue.level == "ERROR"]

    @property
    def warnings(self) -> list[Issue]:
        return [issue for issue in self.issues if issue.level == "WARNING"]

    def require(self, condition: bool, code: str, location: str, message: str) -> bool:
        self.checks += 1
        if not condition:
            self.issues.append(Issue("ERROR", code, location, message))
        return condition

    def warning(self, condition: bool, code: str, location: str, message: str) -> bool:
        self.checks += 1
        if not condition:
            self.issues.append(Issue("WARNING", code, location, message))
        return condition


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset-root", type=Path, default=DEFAULT_DATASET_ROOT)
    parser.add_argument("--manifest", type=Path, default=None)
    parser.add_argument("--baseline-jobs", type=Path, default=None)
    parser.add_argument(
        "--allow-missing-derived",
        action="store_true",
        help="Treat absent masks, overlays, box previews, and SAM2 audit files as warnings.",
    )
    parser.add_argument(
        "--max-issues",
        type=int,
        default=80,
        help="Maximum number of individual issues printed (all are still counted).",
    )
    return parser.parse_args()


def nonempty_string(value: Any) -> bool:
    return isinstance(value, str) and bool(value.strip())


def is_int(value: Any) -> bool:
    return isinstance(value, int) and not isinstance(value, bool)


def read_json_object(path: Path, validator: Validator, location: str) -> dict[str, Any] | None:
    if not validator.require(path.is_file(), "file.missing", location, f"Missing file: {path}"):
        return None
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, UnicodeError, json.JSONDecodeError) as exc:
        validator.require(False, "json.invalid", location, f"Cannot parse {path}: {exc}")
        return None
    if not validator.require(isinstance(value, dict), "json.not_object", location, "Expected a JSON object"):
        return None
    return value


def read_jsonl(path: Path, validator: Validator, location: str) -> list[dict[str, Any]] | None:
    if not validator.require(path.is_file(), "file.missing", location, f"Missing file: {path}"):
        return None
    rows: list[dict[str, Any]] = []
    try:
        lines = path.read_text(encoding="utf-8").splitlines()
    except (OSError, UnicodeError) as exc:
        validator.require(False, "file.unreadable", location, f"Cannot read {path}: {exc}")
        return None
    for line_number, line in enumerate(lines, start=1):
        if not line.strip():
            validator.warning(False, "jsonl.blank_line", f"{location}:{line_number}", "Blank JSONL line")
            continue
        try:
            value = json.loads(line)
        except json.JSONDecodeError as exc:
            validator.require(False, "jsonl.invalid", f"{location}:{line_number}", str(exc))
            continue
        if not isinstance(value, dict):
            validator.require(False, "jsonl.not_object", f"{location}:{line_number}", "Row must be an object")
            continue
        rows.append(value)
    return rows


def safe_dataset_path(
    root: Path,
    relative: Any,
    validator: Validator,
    location: str,
) -> Path | None:
    if not validator.require(nonempty_string(relative), "path.invalid", location, "Path must be a non-empty string"):
        return None
    path_value = Path(relative)
    if not validator.require(not path_value.is_absolute(), "path.absolute", location, "Dataset path must be relative"):
        return None
    root_resolved = root.resolve()
    candidate = (root_resolved / path_value).resolve(strict=False)
    try:
        candidate.relative_to(root_resolved)
    except ValueError:
        validator.require(False, "path.escape", location, f"Path escapes dataset root: {relative}")
        return None
    return candidate


def validate_normalized_box(value: Any, validator: Validator, location: str) -> tuple[float, ...] | None:
    valid_sequence = isinstance(value, (list, tuple)) and len(value) == 4
    if not validator.require(valid_sequence, "bbox.shape", location, "bbox_xyxy_norm must contain four numbers"):
        return None
    try:
        box = tuple(float(item) for item in value)
    except (TypeError, ValueError):
        validator.require(False, "bbox.type", location, "bbox_xyxy_norm values must be numeric")
        return None
    if not validator.require(all(math.isfinite(item) for item in box), "bbox.nonfinite", location, "Box contains NaN/inf"):
        return None
    validator.require(all(0.0 <= item <= 1.0 for item in box), "bbox.range", location, "Box values must be in [0, 1]")
    validator.require(box[0] < box[2] and box[1] < box[3], "bbox.degenerate", location, "Expected x1 < x2 and y1 < y2")
    return box


def validate_normalized_points(value: Any, validator: Validator, location: str) -> None:
    if value is None:
        return
    if not validator.require(isinstance(value, list), "points.type", location, "Points must be a list"):
        return
    for index, point in enumerate(value):
        point_location = f"{location}[{index}]"
        if not validator.require(isinstance(point, (list, tuple)) and len(point) == 2, "points.shape", point_location, "Point must contain two numbers"):
            continue
        try:
            coordinates = [float(item) for item in point]
        except (TypeError, ValueError):
            validator.require(False, "points.value", point_location, "Point values must be numeric")
            continue
        validator.require(
            all(math.isfinite(item) and 0.0 <= item <= 1.0 for item in coordinates),
            "points.range",
            point_location,
            "Point values must be finite and in [0, 1]",
        )


def validate_rights(value: Any, validator: Validator, location: str) -> None:
    if isinstance(value, str):
        validator.require(bool(value.strip()), "rights.empty", location, "Rights string is empty")
        return
    if isinstance(value, dict):
        validator.require(bool(value), "rights.empty", location, "Rights object is empty")
        validator.require(
            any(nonempty_string(value.get(key)) for key in ("license", "license_name", "status")),
            "rights.no_license",
            location,
            "Rights object needs license, license_name, or status",
        )
        return
    validator.require(False, "rights.type", location, "rights must be a non-empty string or object")


def validate_provenance(case: dict[str, Any], validator: Validator, location: str) -> None:
    """Require enough provenance to reproduce the local rights audit."""
    source = case.get("source")
    if validator.require(isinstance(source, dict), "source.type", f"{location}.source", "source must be an object"):
        validator.require(
            nonempty_string(source.get("source_url")),
            "source.url",
            f"{location}.source.source_url",
            "source_url must be a non-empty string",
        )
        if nonempty_string(source.get("source_url")):
            validator.require(
                str(source["source_url"]).startswith(("https://", "http://")),
                "source.url_scheme",
                f"{location}.source.source_url",
                "source_url must be an HTTP(S) URL",
            )
        validator.require(
            nonempty_string(source.get("creator")),
            "source.creator",
            f"{location}.source.creator",
            "creator must be a non-empty string",
        )
    rights = case.get("rights")
    if isinstance(rights, dict):
        validator.require(
            nonempty_string(rights.get("license_url")),
            "rights.license_url",
            f"{location}.rights.license_url",
            "rights object must include a license_url",
        )
        if nonempty_string(rights.get("license_url")):
            validator.require(
                str(rights["license_url"]).startswith(("https://", "http://")),
                "rights.license_url_scheme",
                f"{location}.rights.license_url",
                "license_url must be an HTTP(S) URL",
            )
    validator.require(
        nonempty_string(case.get("processing")),
        "case.processing",
        f"{location}.processing",
        "processing must record the source-to-input transform",
    )
    validator.require(
        nonempty_string(case.get("release_guidance")),
        "case.release_guidance",
        f"{location}.release_guidance",
        "release_guidance must document redistribution/caveats",
    )


def image_dimensions(path: Path, validator: Validator, location: str) -> tuple[int, int] | None:
    if not validator.require(path.is_file(), "image.missing", location, f"Missing image: {path}"):
        return None
    try:
        with Image.open(path) as raw:
            raw.load()
            displayed = ImageOps.exif_transpose(raw)
            dimensions = displayed.size
    except (OSError, ValueError) as exc:
        validator.require(False, "image.invalid", location, f"Cannot decode image: {exc}")
        return None
    validator.require(dimensions[0] > 0 and dimensions[1] > 0, "image.empty", location, "Image dimensions must be positive")
    return dimensions


def validate_instance_order(
    entries: Any,
    instance_count: int | None,
    validator: Validator,
    location: str,
) -> tuple[dict[str, dict[str, Any]], dict[str, tuple[float, ...]]]:
    by_id: dict[str, dict[str, Any]] = {}
    boxes: dict[str, tuple[float, ...]] = {}
    if not validator.require(isinstance(entries, list), "instances.type", location, "instance_order must be a list"):
        return by_id, boxes
    if instance_count is not None:
        validator.require(len(entries) == instance_count, "instances.count", location, f"Expected {instance_count} entries, got {len(entries)}")

    ordinals_by_row: dict[str, list[int]] = defaultdict(list)
    seen_row_positions: set[tuple[str, int]] = set()
    for index, entry in enumerate(entries):
        entry_location = f"{location}[{index}]"
        if not validator.require(isinstance(entry, dict), "instance.type", entry_location, "Instance entry must be an object"):
            continue
        instance_id = entry.get("instance_id")
        row = entry.get("row")
        ordinal = entry.get("ordinal_from_left")
        id_ok = validator.require(nonempty_string(instance_id), "instance.id", f"{entry_location}.instance_id", "instance_id must be non-empty")
        row_ok = validator.require(nonempty_string(row), "instance.row", f"{entry_location}.row", "row must be non-empty")
        ordinal_ok = validator.require(is_int(ordinal) and ordinal >= 1, "instance.ordinal", f"{entry_location}.ordinal_from_left", "ordinal_from_left must be a positive integer")
        box = validate_normalized_box(entry.get("bbox_xyxy_norm"), validator, f"{entry_location}.bbox_xyxy_norm")

        if id_ok:
            instance_key = str(instance_id)
            validator.require(instance_key not in by_id, "instance.duplicate_id", entry_location, f"Duplicate instance_id: {instance_key}")
            if instance_key not in by_id:
                by_id[instance_key] = entry
                if box is not None:
                    boxes[instance_key] = box
        if row_ok and ordinal_ok:
            row_key = str(row)
            position = (row_key, int(ordinal))
            validator.require(position not in seen_row_positions, "instance.duplicate_position", entry_location, f"Duplicate row/ordinal: {position}")
            seen_row_positions.add(position)
            ordinals_by_row[row_key].append(int(ordinal))

    validator.require(1 <= len(ordinals_by_row) <= 2, "layout.row_count", location, f"Expected one or two rows, found {len(ordinals_by_row)}")
    for row, observed in ordinals_by_row.items():
        expected = list(range(1, len(observed) + 1))
        validator.require(observed == expected, "instance.row_order", f"{location}[row={row}]", f"Expected list order/ordinals {expected}, got {observed}")
    validator.require(len(set(boxes.values())) == len(boxes), "instance.duplicate_bbox", location, "Two instances have identical boxes")
    return by_id, boxes


def validate_sam_prompt(value: Any, validator: Validator, location: str) -> tuple[float, ...] | None:
    if not validator.require(isinstance(value, dict), "sam_prompt.type", location, "sam2_prompt must be an object"):
        return None
    box = validate_normalized_box(value.get("bbox_xyxy_norm"), validator, f"{location}.bbox_xyxy_norm")
    validate_normalized_points(value.get("positive_points_norm", []), validator, f"{location}.positive_points_norm")
    validate_normalized_points(value.get("negative_points_norm", []), validator, f"{location}.negative_points_norm")
    if "sam_candidate_index" in value:
        index = value["sam_candidate_index"]
        validator.require(is_int(index) and 0 <= index <= 2, "sam_prompt.candidate", f"{location}.sam_candidate_index", "SAM candidate index must be 0, 1, or 2")
    return box


def validate_variants(
    case: dict[str, Any],
    instance_ids: dict[str, dict[str, Any]],
    instance_boxes: dict[str, tuple[float, ...]],
    validator: Validator,
    location: str,
) -> dict[str, dict[str, Any]]:
    raw_variants = case.get("variants")
    if not validator.require(isinstance(raw_variants, list), "variants.type", f"{location}.variants", "variants must be a list"):
        return {}
    validator.require(len(raw_variants) == 2, "variants.count", f"{location}.variants", "Exactly two variants are required")
    variants: dict[str, dict[str, Any]] = {}
    boxes: dict[str, tuple[float, ...]] = {}
    normalized_prompts: dict[str, str] = {}

    for index, variant in enumerate(raw_variants):
        variant_location = f"{location}.variants[{index}]"
        if not validator.require(isinstance(variant, dict), "variant.type", variant_location, "Variant must be an object"):
            continue
        pair = variant.get("pair")
        pair_ok = validator.require(pair in ("A", "B"), "variant.pair", f"{variant_location}.pair", "pair must be A or B")
        if pair_ok:
            validator.require(pair not in variants, "variant.duplicate_pair", variant_location, f"Duplicate pair {pair}")
            variants[str(pair)] = variant

        prompt = variant.get("prompt_full")
        target = variant.get("target_expression")
        prompt_ok = validator.require(nonempty_string(prompt), "variant.prompt", f"{variant_location}.prompt_full", "prompt_full must be non-empty")
        target_ok = validator.require(nonempty_string(target), "variant.target", f"{variant_location}.target_expression", "target_expression must be non-empty")
        if prompt_ok and target_ok:
            occurrences = str(prompt).count(str(target))
            validator.require(occurrences == 1, "variant.target_occurrence", variant_location, f"target_expression must occur exactly once in prompt_full, found {occurrences}")
            if pair_ok and occurrences == 1:
                normalized_prompts[str(pair)] = str(prompt).replace(str(target), "<TARGET>")

        operation_id = variant.get("operation_id")
        validator.require(nonempty_string(operation_id), "variant.operation_id", f"{variant_location}.operation_id", "operation_id must be non-empty")
        edit_spec = variant.get("edit_spec")
        validator.require(
            (isinstance(edit_spec, str) and bool(edit_spec.strip())) or (isinstance(edit_spec, dict) and bool(edit_spec)),
            "variant.edit_spec",
            f"{variant_location}.edit_spec",
            "edit_spec must be a non-empty string or object",
        )
        box = validate_sam_prompt(variant.get("sam2_prompt"), validator, f"{variant_location}.sam2_prompt")
        if pair_ok and box is not None:
            boxes[str(pair)] = box

        target_instance_id = variant.get("target_instance_id")
        if target_instance_id is not None:
            known = nonempty_string(target_instance_id) and str(target_instance_id) in instance_ids
            validator.require(known, "variant.unknown_instance", f"{variant_location}.target_instance_id", f"Unknown target instance: {target_instance_id!r}")
            if known and box is not None and str(target_instance_id) in instance_boxes:
                validator.require(
                    box == instance_boxes[str(target_instance_id)],
                    "variant.instance_box_mismatch",
                    variant_location,
                    "sam2_prompt box must exactly match target instance bbox",
                )

    validator.require(set(variants) == {"A", "B"}, "variants.pairs", f"{location}.variants", f"Expected A and B, got {sorted(variants)}")
    if set(variants) == {"A", "B"}:
        a, b = variants["A"], variants["B"]
        validator.require(a.get("target_expression") != b.get("target_expression"), "variants.same_target", f"{location}.variants", "A and B must target different expressions")
        validator.require(a.get("operation_id") == b.get("operation_id"), "variants.operation_mismatch", f"{location}.variants", "A/B operation_id must be identical")
        validator.require(a.get("edit_spec") == b.get("edit_spec"), "variants.edit_spec_mismatch", f"{location}.variants", "A/B edit_spec must be identical")
        if set(normalized_prompts) == {"A", "B"}:
            validator.require(
                normalized_prompts["A"] == normalized_prompts["B"],
                "variants.prompt_mismatch",
                f"{location}.variants",
                "After exact target_expression replacement, A/B prompt_full must be byte-for-byte identical",
            )
        if set(boxes) == {"A", "B"}:
            validator.require(boxes["A"] != boxes["B"], "variants.same_box", f"{location}.variants", "A and B must not use the same target box")
        if a.get("target_instance_id") is not None and b.get("target_instance_id") is not None:
            validator.require(a.get("target_instance_id") != b.get("target_instance_id"), "variants.same_instance", f"{location}.variants", "A and B must target different instances")
    return variants


def validate_manifest(
    manifest: dict[str, Any],
    root: Path,
    validator: Validator,
) -> tuple[dict[str, dict[str, Any]], dict[str, tuple[int, int]], dict[tuple[str, str], dict[str, Any]]]:
    count_policy = manifest.get("count_policy")
    if validator.require(
        isinstance(count_policy, dict),
        "manifest.count_policy",
        "manifest.count_policy",
        "count_policy must be an object",
    ):
        expected_policy = {"preferred_min": 4, "preferred_max": 8, "hard_max": 10}
        for field, expected in expected_policy.items():
            validator.require(
                count_policy.get(field) == expected,
                "manifest.count_policy_value",
                f"manifest.count_policy.{field}",
                f"Expected {expected!r}, got {count_policy.get(field)!r}",
            )

    raw_cases = manifest.get("cases")
    if not validator.require(isinstance(raw_cases, list), "manifest.cases", "manifest.cases", "cases must be a list"):
        return {}, {}, {}
    validator.require(bool(raw_cases), "manifest.empty", "manifest.cases", "At least one case is required")
    cases: dict[str, dict[str, Any]] = {}
    dimensions: dict[str, tuple[int, int]] = {}
    variants_flat: dict[tuple[str, str], dict[str, Any]] = {}

    for index, case in enumerate(raw_cases):
        location = f"manifest.cases[{index}]"
        if not validator.require(isinstance(case, dict), "case.type", location, "Case must be an object"):
            continue
        case_id = case.get("case_id")
        id_ok = validator.require(nonempty_string(case_id), "case.id", f"{location}.case_id", "case_id must be non-empty")
        if id_ok:
            case_id = str(case_id)
            validator.require(bool(CASE_ID_PATTERN.fullmatch(case_id)), "case.id_format", f"{location}.case_id", "Use lowercase letters, digits, underscores, or hyphens")
            validator.require(case_id not in cases, "case.duplicate", location, f"Duplicate case_id: {case_id}")
            cases.setdefault(case_id, case)
        else:
            case_id = f"<invalid-{index}>"

        validator.require(nonempty_string(case.get("category")), "case.category", f"{location}.category", "category must be non-empty")
        image_rel = case.get("image")
        image_path = safe_dataset_path(root, image_rel, validator, f"{location}.image")
        if image_path is not None:
            dims = image_dimensions(image_path, validator, f"{location}.image")
            if dims is not None and id_ok:
                dimensions[str(case_id)] = dims
            declared_dims = case.get("image_dimensions")
            if declared_dims is not None and dims is not None:
                valid_declared = isinstance(declared_dims, (list, tuple)) and len(declared_dims) == 2 and all(is_int(item) for item in declared_dims)
                validator.require(valid_declared, "case.image_dimensions", f"{location}.image_dimensions", "image_dimensions must be [width, height]")
                if valid_declared:
                    validator.require(tuple(declared_dims) == dims, "case.dimension_mismatch", location, f"Declared {declared_dims}, decoded {list(dims)}")

        count = case.get("instance_count")
        count_ok = validator.require(is_int(count), "case.instance_count", f"{location}.instance_count", "instance_count must be an integer")
        if count_ok:
            count_value = int(count)
            validator.require(
                4 <= count_value <= 10,
                "case.instance_range",
                f"{location}.instance_count",
                "Dataset policy requires 4-10 instances (4-8 preferred; 10 hard maximum)",
            )
            if count_value in (9, 10):
                validator.require(
                    case.get("count_exception") is True,
                    "case.count_exception",
                    f"{location}.count_exception",
                    "Cases with 9 or 10 instances must set count_exception=true",
                )
                validator.require(
                    nonempty_string(case.get("count_exception_note")),
                    "case.count_exception_note",
                    f"{location}.count_exception_note",
                    "Cases with 9 or 10 instances need a non-empty exception note",
                )
        validator.require(nonempty_string(case.get("layout")), "case.layout", f"{location}.layout", "layout must be a non-empty string")
        validate_rights(case.get("rights"), validator, f"{location}.rights")
        validate_provenance(case, validator, location)
        instance_ids, instance_boxes = validate_instance_order(
            case.get("instance_order"), int(count) if count_ok else None, validator, f"{location}.instance_order"
        )
        variants = validate_variants(case, instance_ids, instance_boxes, validator, location)
        if id_ok:
            for pair, variant in variants.items():
                key = (str(case_id), pair)
                if key not in variants_flat:
                    variants_flat[key] = variant

    validator.stats["cases"] = len(cases)
    validator.stats["variants"] = len(variants_flat)
    return cases, dimensions, variants_flat


def key_contains_private_fragment(key: str) -> bool:
    normalized = key.casefold().replace("-", "_")
    return any(fragment in normalized for fragment in PRIVATE_KEY_FRAGMENTS)


def validate_baseline_jobs(
    path: Path,
    root: Path,
    cases: dict[str, dict[str, Any]],
    variants: dict[tuple[str, str], dict[str, Any]],
    validator: Validator,
) -> None:
    rows = read_jsonl(path, validator, "baseline_jobs")
    if rows is None:
        return
    seen: set[tuple[str, str]] = set()
    for index, row in enumerate(rows):
        location = f"baseline_jobs:{index + 1}"
        keys = set(row)
        validator.require(keys == BASELINE_FIELDS, "baseline.fields", location, f"Fields must be exactly {sorted(BASELINE_FIELDS)}; got {sorted(keys)}")
        leaked_keys = sorted(key for key in keys if key_contains_private_fragment(str(key)))
        validator.require(not leaked_keys, "baseline.private_key", location, f"Evaluator-private keys found: {leaked_keys}")
        for field in BASELINE_FIELDS:
            validator.require(nonempty_string(row.get(field)), "baseline.value", f"{location}.{field}", f"{field} must be a non-empty string")
        case_id, pair = row.get("case_id"), row.get("pair")
        if not (nonempty_string(case_id) and pair in ("A", "B")):
            continue
        key = (str(case_id), str(pair))
        validator.require(key not in seen, "baseline.duplicate", location, f"Duplicate job: {key}")
        seen.add(key)
        validator.require(key in variants, "baseline.unknown_job", location, f"No matching manifest variant for {key}")
        if key not in variants:
            continue
        case = cases[str(case_id)]
        variant = variants[key]
        validator.require(row.get("source_image") == case.get("image"), "baseline.image_mismatch", location, "source_image differs from manifest case image")
        validator.require(row.get("prompt_full") == variant.get("prompt_full"), "baseline.prompt_mismatch", location, "prompt_full differs from manifest variant")
        safe_dataset_path(root, row.get("source_image"), validator, f"{location}.source_image")

    expected = set(variants)
    validator.require(seen == expected, "baseline.coverage", "baseline_jobs", f"Expected {len(expected)} unique jobs; missing={sorted(expected - seen)}, extra={sorted(seen - expected)}")
    validator.stats["baseline_jobs"] = len(rows)


def derived_paths(root: Path, case_id: str, pair: str) -> dict[str, Path]:
    return {
        "mask": root / "masks" / case_id / f"{case_id}_{pair}.png",
        "overlay": root / "mask_overlays" / case_id / f"{case_id}_{pair}_overlay.jpg",
        "target_box_image": root / "target_boxes" / case_id / f"{case_id}_{pair}_box.jpg",
    }


def mask_details(
    path: Path,
    expected_size: tuple[int, int],
    validator: Validator,
    location: str,
) -> dict[str, Any] | None:
    try:
        with Image.open(path) as raw:
            raw.load()
            size = raw.size
            grayscale = raw.convert("L")
            colors = grayscale.getcolors(maxcolors=3)
            histogram = grayscale.histogram()
    except (OSError, ValueError) as exc:
        validator.require(False, "mask.invalid", location, f"Cannot decode mask: {exc}")
        return None
    validator.require(size == expected_size, "derived.dimension_mismatch", location, f"Mask size {size} != source {expected_size}")
    if colors is None:
        validator.require(False, "mask.not_binary", location, "Mask contains more than two grayscale values")
        return None
    values = {value for _, value in colors}
    validator.require(values.issubset({0, 255}), "mask.not_binary", location, f"Mask values must be 0/255, got {sorted(values)}")
    foreground = int(histogram[255])
    total = int(sum(histogram))
    validator.require(foreground > 0, "mask.empty", location, "Mask has no foreground")
    validator.require(foreground < total, "mask.full", location, "Mask covers the entire image")
    return {"size": size, "foreground": foreground, "total": total}


def validate_visualization(path: Path, expected_size: tuple[int, int], validator: Validator, location: str) -> None:
    try:
        with Image.open(path) as image:
            image.load()
            size = image.size
    except (OSError, ValueError) as exc:
        validator.require(False, "derived.invalid", location, f"Cannot decode image: {exc}")
        return
    validator.require(size == expected_size, "derived.dimension_mismatch", location, f"Visualization size {size} != source {expected_size}")


def validate_derived(
    root: Path,
    cases: dict[str, dict[str, Any]],
    dimensions: dict[str, tuple[int, int]],
    variants: dict[tuple[str, str], dict[str, Any]],
    allow_missing: bool,
    validator: Validator,
) -> None:
    missing: list[str] = []
    mask_info: dict[tuple[str, str], dict[str, Any]] = {}
    expected_paths: dict[tuple[str, str], dict[str, Path]] = {}
    for key in sorted(variants):
        case_id, pair = key
        paths = derived_paths(root, case_id, pair)
        expected_paths[key] = paths
        for kind, path in paths.items():
            if not path.is_file():
                missing.append(str(path.relative_to(root)))
                continue
            expected_size = dimensions.get(case_id)
            if expected_size is None:
                continue
            if kind == "mask":
                details = mask_details(path, expected_size, validator, f"derived.{case_id}/{pair}.mask")
                if details is not None:
                    mask_info[key] = details
            else:
                validate_visualization(path, expected_size, validator, f"derived.{case_id}/{pair}.{kind}")

    if missing:
        sample = ", ".join(missing[:6])
        if len(missing) > 6:
            sample += f", ... (+{len(missing) - 6})"
        if allow_missing:
            validator.warning(False, "derived.missing", "derived", f"{len(missing)} derived files are not present: {sample}")
        else:
            validator.require(False, "derived.missing", "derived", f"{len(missing)} derived files are not present: {sample}")
    else:
        validator.checks += 1
    validator.stats["derived_expected"] = len(variants) * 3
    validator.stats["derived_present"] = len(variants) * 3 - len(missing)

    audit_path = root / "metadata/sam2_masks.jsonl"
    summary_path = root / "metadata/sam2_run.json"
    audit_rows: list[dict[str, Any]] | None
    if audit_path.is_file():
        audit_rows = read_jsonl(audit_path, validator, "sam2_masks")
    else:
        audit_rows = None
        message = f"Missing SAM2 audit: {audit_path}"
        if allow_missing:
            validator.warning(False, "derived.audit_missing", "sam2_masks", message)
        else:
            validator.require(False, "derived.audit_missing", "sam2_masks", message)

    seen: set[tuple[str, str]] = set()
    if audit_rows is not None:
        for index, row in enumerate(audit_rows):
            location = f"sam2_masks:{index + 1}"
            case_id, pair = row.get("case_id"), row.get("pair")
            key_valid = nonempty_string(case_id) and pair in ("A", "B")
            validator.require(key_valid, "sam_audit.key", location, "case_id/pair must identify an A/B job")
            if not key_valid:
                continue
            key = (str(case_id), str(pair))
            validator.require(key not in seen, "sam_audit.duplicate", location, f"Duplicate audit row: {key}")
            seen.add(key)
            validator.require(key in variants, "sam_audit.unknown", location, f"Unknown manifest job: {key}")
            if key not in variants:
                continue
            expected = expected_paths[key]
            expected_relative = {
                name: str(path.relative_to(root)) for name, path in expected.items()
            }
            validator.require(row.get("image") == cases[str(case_id)].get("image"), "sam_audit.image", location, "Audit image differs from manifest")
            validator.require(row.get("target_expression") == variants[key].get("target_expression"), "sam_audit.target", location, "Audit target_expression differs from manifest")
            validator.require(row.get("mask") == expected_relative["mask"], "sam_audit.mask_path", location, "Unexpected mask path")
            validator.require(row.get("overlay") == expected_relative["overlay"], "sam_audit.overlay_path", location, "Unexpected overlay path")
            validator.require(row.get("target_box_image") == expected_relative["target_box_image"], "sam_audit.box_path", location, "Unexpected box-preview path")
            expected_size = dimensions.get(str(case_id))
            if expected_size is not None:
                validator.require(row.get("image_dimensions") == list(expected_size), "sam_audit.dimensions", location, "Audit dimensions differ from source")
            checkpoint = row.get("sam2_checkpoint")
            validator.require(nonempty_string(checkpoint) and Path(str(checkpoint)).resolve() == EXPECTED_CHECKPOINT.resolve(), "sam_audit.checkpoint", location, f"Expected checkpoint {EXPECTED_CHECKPOINT}")
            details = mask_info.get(key)
            if details is not None:
                validator.require(row.get("mask_area_pixels") == details["foreground"], "sam_audit.area", location, "mask_area_pixels differs from decoded mask")
                ratio = row.get("mask_area_ratio")
                valid_ratio = isinstance(ratio, (int, float)) and not isinstance(ratio, bool) and math.isfinite(float(ratio))
                validator.require(valid_ratio, "sam_audit.ratio", location, "mask_area_ratio must be finite")
                if valid_ratio:
                    expected_ratio = details["foreground"] / details["total"]
                    validator.require(math.isclose(float(ratio), expected_ratio, rel_tol=1e-9, abs_tol=1e-12), "sam_audit.ratio_mismatch", location, "mask_area_ratio differs from decoded mask")

        expected_keys = set(variants)
        coverage_ok = seen == expected_keys
        message = f"Expected {len(expected_keys)} SAM audit rows; missing={sorted(expected_keys - seen)}, extra={sorted(seen - expected_keys)}"
        if allow_missing:
            validator.warning(coverage_ok, "sam_audit.coverage", "sam2_masks", message)
        else:
            validator.require(coverage_ok, "sam_audit.coverage", "sam2_masks", message)

    if summary_path.is_file():
        summary = read_json_object(summary_path, validator, "sam2_run")
        if summary is not None:
            validator.require(summary.get("checkpoint") is not None and Path(str(summary.get("checkpoint"))).resolve() == EXPECTED_CHECKPOINT.resolve(), "sam_summary.checkpoint", "sam2_run.checkpoint", f"Expected checkpoint {EXPECTED_CHECKPOINT}")
            validator.require(summary.get("cases") == len(cases), "sam_summary.cases", "sam2_run.cases", f"Expected {len(cases)}")
            validator.require(summary.get("masks") == len(variants), "sam_summary.masks", "sam2_run.masks", f"Expected {len(variants)}")
            validator.require(summary.get("all_masks_nonempty") is True, "sam_summary.nonempty", "sam2_run.all_masks_nonempty", "Must be true")
    else:
        message = f"Missing SAM2 summary: {summary_path}"
        if allow_missing:
            validator.warning(False, "derived.summary_missing", "sam2_run", message)
        else:
            validator.require(False, "derived.summary_missing", "sam2_run", message)


def print_report(root: Path, validator: Validator, max_issues: int) -> None:
    status = "PASS" if not validator.errors else "FAIL"
    print(f"Dataset validation: {status}")
    print(f"Root: {root}")
    print(
        "Summary: "
        f"cases={validator.stats['cases']}, "
        f"variants={validator.stats['variants']}, "
        f"baseline_jobs={validator.stats['baseline_jobs']}, "
        f"derived={validator.stats['derived_present']}/{validator.stats['derived_expected']}, "
        f"checks={validator.checks}, errors={len(validator.errors)}, warnings={len(validator.warnings)}"
    )
    if validator.issues:
        print("Issues:")
        limit = max(0, max_issues)
        for issue in validator.issues[:limit]:
            print(f"  {issue.level} [{issue.code}] {issue.location}: {issue.message}")
        omitted = len(validator.issues) - limit
        if omitted > 0:
            print(f"  ... {omitted} additional issues omitted; increase --max-issues to display them")


def main() -> int:
    args = parse_args()
    root = args.dataset_root.resolve()
    validator = Validator()
    validator.require(root.is_dir(), "root.missing", "dataset_root", f"Dataset root is not a directory: {root}")
    manifest_path = (args.manifest or root / "metadata/manifest.json").resolve()
    baseline_path = (args.baseline_jobs or root / "metadata/baseline_jobs.jsonl").resolve()

    manifest = read_json_object(manifest_path, validator, "manifest")
    if manifest is None:
        print_report(root, validator, args.max_issues)
        return 1

    cases, dimensions, variants = validate_manifest(manifest, root, validator)
    validate_baseline_jobs(baseline_path, root, cases, variants, validator)
    validate_derived(root, cases, dimensions, variants, args.allow_missing_derived, validator)
    print_report(root, validator, args.max_issues)
    return 1 if validator.errors else 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except KeyboardInterrupt:
        print("Validation interrupted", file=sys.stderr)
        raise SystemExit(130)