File size: 27,121 Bytes
93a180e
 
 
7f3a1d4
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
 
 
 
 
 
 
 
 
 
 
 
 
93a180e
 
 
 
 
 
 
 
 
7f3a1d4
93a180e
7f3a1d4
93a180e
7f3a1d4
93a180e
 
7f3a1d4
 
 
 
 
 
 
 
 
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
93a180e
 
 
 
7f3a1d4
93a180e
7f3a1d4
 
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
 
 
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
 
 
 
 
 
 
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
 
 
 
 
93a180e
 
 
 
 
7f3a1d4
 
 
 
 
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3a1d4
93a180e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
#!/usr/bin/env python3
"""Validate a Bactrainus HotpotQA dataset release and write SHA-256 checksums.

The validator is intentionally strict. It accepts only the documented,
train-only configurations and writes the checksum manifest only after every
schema, identity, content, and cross-configuration check succeeds.
"""

from __future__ import annotations

import argparse
import hashlib
import os
import re
import sys
import tempfile
from collections import Counter
from collections.abc import Iterable, Iterator, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

try:
    import pyarrow as pa
    import pyarrow.parquet as pq
except ModuleNotFoundError:  # Report a concise installation hint in main().
    pa = None  # type: ignore[assignment]
    pq = None  # type: ignore[assignment]


EXPECTED_ROWS = 90_447
MIN_PARAGRAPHS = 2
MAX_PARAGRAPHS = 10
EXPECTED_PARAGRAPH_COUNTS = {
    2: 262,
    3: 156,
    4: 94,
    5: 88,
    6: 53,
    7: 77,
    8: 60,
    9: 48,
    10: 89_609,
}
EXPECTED_DIFFICULTY_COUNTS = {
    "easy": 17_972,
    "medium": 56_814,
    "hard": 15_661,
}

CONFIGS = (
    "structured",
    "reader-sft",
    "cot-reader-sft",
    "paragraph-selector-sft",
    "question-decomposer-sft",
    "sentence-selector-sft",
    "decomposed-sentence-selector-sft",
    "joint-selector-reader-sft",
)
EXPECTED_TASKS = {
    "reader-sft": "reader",
    "cot-reader-sft": "cot_reader",
    "paragraph-selector-sft": "paragraph_selector",
    "question-decomposer-sft": "question_decomposer",
    "sentence-selector-sft": "sentence_selector",
    "decomposed-sentence-selector-sft": "decomposed_sentence_selector",
    "joint-selector-reader-sft": "joint_selector_reader",
}

STRUCTURED_FIELDS = frozenset(
    {
        "source_id",
        "question",
        "answer",
        "question_type",
        "difficulty",
        "candidate_paragraphs",
        "supporting_facts",
        "gold_paragraph_titles",
    }
)
SFT_FIELDS = frozenset({"source_id", "task", "messages"})

ALLOWED_QUESTION_TYPES = frozenset({"bridge", "comparison"})
ALLOWED_DIFFICULTIES = frozenset(EXPECTED_DIFFICULTY_COUNTS)
ALLOWED_MESSAGE_ROLES = frozenset({"system", "user", "assistant"})

# These names indicate benchmark leakage or bundled experimental outputs. The
# check applies recursively to nested Parquet fields after identifier tokenizing.
FORBIDDEN_FIELD_TOKENS = frozenset(
    {
        "dev",
        "test",
        "validation",
        "eval",
        "evaluation",
        "prediction",
        "predictions",
        "metric",
        "metrics",
        "score",
        "scores",
        "result",
        "results",
        "leaderboard",
        "accuracy",
        "f1",
        "exactmatch",
        "response",
        "responses",
        "output",
        "outputs",
        "generation",
        "generations",
    }
)
FORBIDDEN_FILENAME_TOKENS = FORBIDDEN_FIELD_TOKENS


@dataclass
class Problems:
    """Collect a bounded number of actionable validation errors."""

    limit: int = 100
    items: list[str] = field(default_factory=list)
    suppressed: int = 0

    def add(self, message: str) -> None:
        if len(self.items) < self.limit:
            self.items.append(message)
        else:
            self.suppressed += 1

    @property
    def any(self) -> bool:
        return bool(self.items) or self.suppressed > 0

    def render(self) -> str:
        lines = [f"  - {item}" for item in self.items]
        if self.suppressed:
            lines.append(f"  - ... {self.suppressed} additional error(s) suppressed")
        return "\n".join(lines)


@dataclass(frozen=True)
class ConfigStats:
    """Validated summary for one configuration."""

    name: str
    rows: int
    unique_ids: int
    shards: int


def identifier_tokens(value: str) -> set[str]:
    """Normalize a field or filename into lowercase alphanumeric tokens."""

    return {token for token in re.split(r"[^a-z0-9]+", value.lower()) if token}


def walk_arrow_type(data_type: Any, prefix: str) -> Iterator[str]:
    """Yield nested paths contained by an Arrow type."""

    assert pa is not None
    if pa.types.is_struct(data_type):
        for child in data_type:
            child_path = f"{prefix}.{child.name}"
            yield child_path
            yield from walk_arrow_type(child.type, child_path)
    elif (
        pa.types.is_list(data_type)
        or pa.types.is_large_list(data_type)
        or pa.types.is_fixed_size_list(data_type)
    ):
        yield from walk_arrow_type(data_type.value_type, prefix)
    elif pa.types.is_map(data_type):
        yield from walk_arrow_type(data_type.key_type, f"{prefix}.key")
        yield from walk_arrow_type(data_type.item_type, f"{prefix}.value")


def iter_schema_paths(schema: Any) -> Iterator[str]:
    """Yield every top-level and nested Arrow field path."""

    for arrow_field in schema:
        yield arrow_field.name
        yield from walk_arrow_type(arrow_field.type, arrow_field.name)


def check_schema_for_forbidden_fields(
    config: str,
    schema: Any,
    problems: Problems,
) -> None:
    """Reject fields associated with evaluation records or experimental output."""

    for path in iter_schema_paths(schema):
        matched = identifier_tokens(path) & FORBIDDEN_FIELD_TOKENS
        if matched:
            labels = ", ".join(sorted(matched))
            problems.add(
                f"{config}: forbidden evaluation/result field '{path}' "
                f"(matched: {labels})"
            )


def require_fields(
    config: str,
    available: set[str],
    required: frozenset[str],
    problems: Problems,
) -> bool:
    """Check that a Parquet schema contains its documented required fields."""

    missing = sorted(required - available)
    if missing:
        problems.add(f"{config}: missing required field(s): {', '.join(missing)}")
        return False
    return True


def clean_source_id(value: Any, context: str, problems: Problems) -> str | None:
    """Validate and return a canonical source ID."""

    if not isinstance(value, str) or not value.strip():
        problems.add(f"{context}: source_id must be a non-empty string")
        return None
    if value != value.strip():
        problems.add(f"{context}: source_id contains leading or trailing whitespace")
        return None
    return value


def validate_candidate_paragraphs(
    value: Any,
    context: str,
    problems: Problems,
) -> dict[str, list[str]] | None:
    """Validate the canonical candidate set and return title-to-sentences."""

    if not isinstance(value, list):
        problems.add(f"{context}: candidate_paragraphs must be a list")
        return None
    if not MIN_PARAGRAPHS <= len(value) <= MAX_PARAGRAPHS:
        problems.add(
            f"{context}: expected {MIN_PARAGRAPHS} to {MAX_PARAGRAPHS} "
            f"candidate paragraphs, found {len(value)}"
        )

    by_title: dict[str, list[str]] = {}
    structurally_valid = True
    for position, paragraph in enumerate(value):
        item_context = f"{context}.candidate_paragraphs[{position}]"
        if not isinstance(paragraph, dict):
            problems.add(f"{item_context}: paragraph must be a struct")
            structurally_valid = False
            continue

        title = paragraph.get("title")
        sentences = paragraph.get("sentences")
        if not isinstance(title, str) or not title.strip():
            problems.add(f"{item_context}.title: expected a non-empty string")
            structurally_valid = False
            continue
        if title in by_title:
            problems.add(f"{item_context}.title: duplicate candidate title {title!r}")
            structurally_valid = False
            continue
        if not isinstance(sentences, list) or not sentences:
            problems.add(f"{item_context}.sentences: expected a non-empty list")
            structurally_valid = False
            continue
        if any(not isinstance(sentence, str) for sentence in sentences):
            problems.add(f"{item_context}.sentences: every sentence must be a string")
            structurally_valid = False
            continue
        by_title[title] = sentences

    if not structurally_valid or not MIN_PARAGRAPHS <= len(value) <= MAX_PARAGRAPHS:
        return None
    return by_title


def validate_supporting_facts(
    value: Any,
    paragraphs: dict[str, list[str]] | None,
    context: str,
    problems: Problems,
) -> list[str] | None:
    """Validate evidence title/index pairs and return unique titles in order."""

    if not isinstance(value, list) or not value:
        problems.add(f"{context}: supporting_facts must be a non-empty list")
        return None

    valid = True
    ordered_titles: list[str] = []
    seen_titles: set[str] = set()
    for position, fact in enumerate(value):
        item_context = f"{context}.supporting_facts[{position}]"
        if not isinstance(fact, dict):
            problems.add(f"{item_context}: supporting fact must be a struct")
            valid = False
            continue

        title = fact.get("title")
        sentence_index = fact.get("sentence_index")
        if not isinstance(title, str) or not title.strip():
            problems.add(f"{item_context}.title: expected a non-empty string")
            valid = False
            continue
        if not isinstance(sentence_index, int) or isinstance(sentence_index, bool):
            problems.add(f"{item_context}.sentence_index: expected an integer")
            valid = False
            continue
        if paragraphs is None:
            valid = False
            continue
        if title not in paragraphs:
            problems.add(f"{item_context}: evidence title {title!r} is not a candidate")
            valid = False
            continue
        if sentence_index < 0 or sentence_index >= len(paragraphs[title]):
            problems.add(
                f"{item_context}: sentence_index {sentence_index} is outside "
                f"[0, {len(paragraphs[title])}) for {title!r}"
            )
            valid = False
            continue
        if title not in seen_titles:
            seen_titles.add(title)
            ordered_titles.append(title)

    return ordered_titles if valid else None


def validate_gold_titles(
    value: Any,
    expected: list[str] | None,
    context: str,
    problems: Problems,
) -> None:
    """Check the order-preserving unique supporting-paragraph title list."""

    if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
        problems.add(f"{context}: gold_paragraph_titles must be a list of strings")
        return
    if expected is not None and value != expected:
        problems.add(
            f"{context}: gold_paragraph_titles does not equal the order-preserving "
            "unique supporting-fact titles"
        )


def validate_nonempty_text(
    value: Any, field_name: str, context: str, problems: Problems
) -> None:
    """Require a non-empty textual scalar."""

    if not isinstance(value, str) or not value.strip():
        problems.add(f"{context}.{field_name}: expected a non-empty string")


def validate_messages(value: Any, context: str, problems: Problems) -> None:
    """Validate the documented role/content SFT chat representation."""

    if not isinstance(value, list) or len(value) < 2:
        problems.add(
            f"{context}: messages must contain at least user and assistant turns"
        )
        return

    roles: list[str] = []
    for position, message in enumerate(value):
        item_context = f"{context}.messages[{position}]"
        if not isinstance(message, dict):
            problems.add(f"{item_context}: message must be a struct")
            continue
        role = message.get("role")
        content = message.get("content")
        if role not in ALLOWED_MESSAGE_ROLES:
            problems.add(
                f"{item_context}.role: expected one of "
                f"{sorted(ALLOWED_MESSAGE_ROLES)}, found {role!r}"
            )
        else:
            roles.append(role)
        if not isinstance(content, str) or not content.strip():
            problems.add(f"{item_context}.content: expected a non-empty string")

    if "user" not in roles:
        problems.add(f"{context}: messages does not contain a user turn")
    if roles and roles[-1] != "assistant":
        problems.add(f"{context}: final message must be the assistant training target")


def validate_structured_row(
    row: dict[str, Any],
    context: str,
    problems: Problems,
    difficulty_counts: Counter[str],
    paragraph_counts: Counter[int],
) -> None:
    """Validate one canonical HotpotQA record."""

    validate_nonempty_text(row.get("question"), "question", context, problems)
    validate_nonempty_text(row.get("answer"), "answer", context, problems)

    question_type = row.get("question_type")
    if question_type not in ALLOWED_QUESTION_TYPES:
        problems.add(
            f"{context}.question_type: expected one of "
            f"{sorted(ALLOWED_QUESTION_TYPES)}, found {question_type!r}"
        )

    difficulty = row.get("difficulty")
    if difficulty not in ALLOWED_DIFFICULTIES:
        problems.add(
            f"{context}.difficulty: expected one of "
            f"{sorted(ALLOWED_DIFFICULTIES)}, found {difficulty!r}"
        )
    else:
        difficulty_counts[difficulty] += 1

    paragraphs = validate_candidate_paragraphs(
        row.get("candidate_paragraphs"), context, problems
    )
    candidate_value = row.get("candidate_paragraphs")
    if isinstance(candidate_value, list):
        paragraph_counts[len(candidate_value)] += 1
    evidence_titles = validate_supporting_facts(
        row.get("supporting_facts"), paragraphs, context, problems
    )
    validate_gold_titles(
        row.get("gold_paragraph_titles"), evidence_titles, context, problems
    )


def validate_sft_row(row: dict[str, Any], context: str, problems: Problems) -> None:
    """Validate one deterministic supervised-fine-tuning record."""

    validate_nonempty_text(row.get("task"), "task", context, problems)
    validate_messages(row.get("messages"), context, problems)

    # If a task view retains canonical evidence columns, validate them rather
    # than allowing malformed duplicated provenance to pass unnoticed.
    has_paragraphs = "candidate_paragraphs" in row
    has_facts = "supporting_facts" in row
    if has_paragraphs != has_facts:
        problems.add(
            f"{context}: candidate_paragraphs and supporting_facts must be retained together"
        )
    elif has_paragraphs:
        paragraphs = validate_candidate_paragraphs(
            row.get("candidate_paragraphs"), context, problems
        )
        validate_supporting_facts(
            row.get("supporting_facts"), paragraphs, context, problems
        )


def parquet_files_for_config(root: Path, config: str, problems: Problems) -> list[Path]:
    """Return the complete, train-only shard set for a configuration."""

    config_dir = root / "data" / config
    if not config_dir.is_dir():
        problems.add(f"{config}: missing directory {config_dir.relative_to(root)}")
        return []

    all_parquet = sorted(config_dir.rglob("*.parquet"))
    shards = sorted(config_dir.glob("train-*.parquet"))
    if not shards:
        problems.add(f"{config}: no data/{config}/train-*.parquet shards found")

    unexpected = sorted(set(all_parquet) - set(shards))
    for path in unexpected:
        problems.add(
            f"{config}: unexpected Parquet file {path.relative_to(root).as_posix()}; "
            "only direct train-*.parquet shards are allowed"
        )

    for path in all_parquet:
        matched = identifier_tokens(path.name) & FORBIDDEN_FILENAME_TOKENS
        if matched:
            problems.add(
                f"{config}: forbidden filename {path.name!r} "
                f"(matched: {', '.join(sorted(matched))})"
            )
    return shards


def reject_unsupported_configs(root: Path, problems: Problems) -> None:
    """Allow only documented config directories and Parquet data files."""

    data_dir = root / "data"
    if not data_dir.is_dir():
        problems.add("missing data directory")
        return
    allowed = set(CONFIGS)
    for child in sorted(data_dir.iterdir()):
        if child.is_dir() and child.name not in allowed:
            problems.add(
                f"unsupported dataset configuration directory: data/{child.name}"
            )
        elif child.is_file() and child.suffix.lower() == ".parquet":
            problems.add(
                f"Parquet files must be stored under data/<config>: data/{child.name}"
            )

    for path in sorted(data_dir.rglob("*")):
        if path.is_file() and path.suffix.lower() != ".parquet":
            problems.add(
                f"unexpected non-Parquet data artifact: "
                f"{path.relative_to(root).as_posix()}"
            )


def iter_rows(
    parquet_file: Any, columns: Sequence[str], batch_size: int
) -> Iterator[dict[str, Any]]:
    """Yield selected Parquet columns as Python records in bounded batches."""

    for batch in parquet_file.iter_batches(
        batch_size=batch_size, columns=list(columns)
    ):
        yield from batch.to_pylist()


def validate_config(
    root: Path,
    config: str,
    problems: Problems,
    batch_size: int,
) -> tuple[ConfigStats, set[str], list[Path]]:
    """Validate all shards in one configuration."""

    assert pq is not None
    shards = parquet_files_for_config(root, config, problems)
    if not shards:
        return ConfigStats(config, 0, 0, 0), set(), []

    required = STRUCTURED_FIELDS if config == "structured" else SFT_FIELDS
    reference_schema = None
    ids: set[str] = set()
    row_count = 0
    difficulty_counts: Counter[str] = Counter()
    paragraph_counts: Counter[int] = Counter()
    observed_tasks: set[str] = set()

    for shard in shards:
        relative = shard.relative_to(root).as_posix()
        try:
            parquet_file = pq.ParquetFile(shard)
            schema = parquet_file.schema_arrow
        except (OSError, TypeError, ValueError) as exc:
            problems.add(f"{config}: cannot open {relative}: {exc}")
            continue

        if reference_schema is None:
            reference_schema = schema
        elif not reference_schema.equals(schema, check_metadata=False):
            problems.add(f"{config}: schema drift detected in {relative}")

        available = set(schema.names)
        check_schema_for_forbidden_fields(config, schema, problems)
        if not require_fields(config, available, required, problems):
            continue

        if config != "structured" and (
            ("candidate_paragraphs" in available) != ("supporting_facts" in available)
        ):
            problems.add(
                f"{config}: candidate_paragraphs and supporting_facts must be "
                f"retained together in {relative}"
            )

        selected = list(required)
        if config != "structured" and {
            "candidate_paragraphs",
            "supporting_facts",
        }.issubset(available):
            selected.extend(["candidate_paragraphs", "supporting_facts"])

        try:
            for row in iter_rows(parquet_file, selected, batch_size):
                row_count += 1
                context = f"{config}[row={row_count}, shard={shard.name}]"
                source_id = clean_source_id(row.get("source_id"), context, problems)
                if source_id is not None:
                    if source_id in ids:
                        problems.add(f"{context}: duplicate source_id {source_id!r}")
                    else:
                        ids.add(source_id)

                if config == "structured":
                    validate_structured_row(
                        row,
                        context,
                        problems,
                        difficulty_counts,
                        paragraph_counts,
                    )
                else:
                    task = row.get("task")
                    if isinstance(task, str) and task.strip():
                        observed_tasks.add(task)
                    validate_sft_row(row, context, problems)
        except (OSError, TypeError, ValueError) as exc:
            problems.add(f"{config}: failed while reading {relative}: {exc}")

    if row_count != EXPECTED_ROWS:
        problems.add(f"{config}: expected {EXPECTED_ROWS:,} rows, found {row_count:,}")
    if len(ids) != EXPECTED_ROWS:
        problems.add(
            f"{config}: expected {EXPECTED_ROWS:,} unique source IDs, found {len(ids):,}"
        )
    if config == "structured" and dict(difficulty_counts) != EXPECTED_DIFFICULTY_COUNTS:
        problems.add(
            f"structured: unexpected difficulty counts; expected "
            f"{EXPECTED_DIFFICULTY_COUNTS}, found {dict(difficulty_counts)}"
        )
    if config == "structured" and dict(paragraph_counts) != EXPECTED_PARAGRAPH_COUNTS:
        problems.add(
            "structured: unexpected candidate-paragraph distribution; expected "
            f"{EXPECTED_PARAGRAPH_COUNTS}, found {dict(paragraph_counts)}"
        )
    if config != "structured" and len(observed_tasks) != 1:
        problems.add(
            f"{config}: expected one stable non-empty task identifier, "
            f"found {sorted(observed_tasks)!r}"
        )
    if config != "structured" and observed_tasks != {EXPECTED_TASKS[config]}:
        problems.add(
            f"{config}: expected task {EXPECTED_TASKS[config]!r}, "
            f"found {sorted(observed_tasks)!r}"
        )

    return ConfigStats(config, row_count, len(ids), len(shards)), ids, shards


def compare_id_sets(id_sets: dict[str, set[str]], problems: Problems) -> None:
    """Require every deterministic task view to use the canonical ID set."""

    canonical = id_sets.get("structured", set())
    for config in CONFIGS[1:]:
        current = id_sets.get(config, set())
        missing = canonical - current
        extra = current - canonical
        if missing or extra:
            missing_sample = sorted(missing)[:5]
            extra_sample = sorted(extra)[:5]
            problems.add(
                f"{config}: source-ID set differs from structured "
                f"(missing={len(missing):,}, extra={len(extra):,}, "
                f"missing_sample={missing_sample!r}, extra_sample={extra_sample!r})"
            )


def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
    """Compute a file SHA-256 digest without loading it into memory."""

    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(chunk_size), b""):
            digest.update(chunk)
    return digest.hexdigest()


def resolve_manifest_path(root: Path, manifest_argument: str) -> Path:
    """Resolve a manifest path and prevent writes outside the release root."""

    candidate = Path(manifest_argument)
    target = (candidate if candidate.is_absolute() else root / candidate).resolve()
    try:
        target.relative_to(root)
    except ValueError as exc:
        raise ValueError("checksum manifest must be located inside --root") from exc
    return target


def write_checksum_manifest(root: Path, files: Iterable[Path], manifest: Path) -> None:
    """Atomically write sorted SHA-256 entries for validated Parquet shards."""

    unique_files = sorted(
        set(files), key=lambda path: path.relative_to(root).as_posix()
    )
    entries = [
        f"{sha256_file(path)}  {path.relative_to(root).as_posix()}"
        for path in unique_files
    ]
    manifest.parent.mkdir(parents=True, exist_ok=True)
    temp_name = ""
    try:
        with tempfile.NamedTemporaryFile(
            mode="w",
            encoding="utf-8",
            newline="\n",
            dir=manifest.parent,
            prefix=f".{manifest.name}.",
            suffix=".tmp",
            delete=False,
        ) as handle:
            temp_name = handle.name
            handle.write("\n".join(entries) + "\n")
        os.replace(temp_name, manifest)
    finally:
        if temp_name:
            Path(temp_name).unlink(missing_ok=True)


def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
    """Parse command-line arguments."""

    package_root = Path(__file__).resolve().parents[1]
    parser = argparse.ArgumentParser(
        description=(
            "Validate all Bactrainus HotpotQA train configurations and "
            "write a SHA-256 manifest after success."
        )
    )
    parser.add_argument(
        "--root",
        type=Path,
        default=package_root,
        help=f"dataset repository root (default: {package_root})",
    )
    parser.add_argument(
        "--manifest",
        default="CHECKSUMS.sha256",
        help="manifest path relative to --root (default: CHECKSUMS.sha256)",
    )
    parser.add_argument(
        "--batch-size",
        type=int,
        default=2_048,
        help="Parquet validation batch size (default: 2048)",
    )
    return parser.parse_args(argv)


def main(argv: Sequence[str] | None = None) -> int:
    """Run release validation and checksum generation."""

    args = parse_args(argv)
    if pa is None or pq is None:
        print(
            "error: pyarrow is required; install it with `python -m pip install pyarrow`",
            file=sys.stderr,
        )
        return 2
    if args.batch_size <= 0:
        print("error: --batch-size must be positive", file=sys.stderr)
        return 2

    root = args.root.resolve()
    if not root.is_dir():
        print(f"error: dataset root does not exist: {root}", file=sys.stderr)
        return 2
    try:
        manifest = resolve_manifest_path(root, args.manifest)
    except ValueError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 2

    problems = Problems()
    reject_unsupported_configs(root, problems)

    stats: list[ConfigStats] = []
    id_sets: dict[str, set[str]] = {}
    parquet_files: list[Path] = []
    for config in CONFIGS:
        config_stats, config_ids, config_files = validate_config(
            root, config, problems, args.batch_size
        )
        stats.append(config_stats)
        id_sets[config] = config_ids
        parquet_files.extend(config_files)

    compare_id_sets(id_sets, problems)
    if problems.any:
        print("Release validation failed:\n" + problems.render(), file=sys.stderr)
        print("The checksum manifest was not updated.", file=sys.stderr)
        return 1

    write_checksum_manifest(root, parquet_files, manifest)
    for item in stats:
        print(
            f"{item.name}: {item.rows:,} rows, {item.unique_ids:,} unique IDs, "
            f"{item.shards} shard(s)"
        )
    print(
        f"Validated {len(CONFIGS)} configurations and {len(parquet_files)} Parquet shards."
    )
    print(f"Wrote SHA-256 manifest: {manifest.relative_to(root).as_posix()}")
    return 0


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