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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
#!/usr/bin/env python3
"""Build every verified Bactrainus train configuration as Parquet.

By default the script downloads the complete, revision-pinned official
``hotpotqa/hotpot_qa`` distractor training split. A complete official JSON or
JSONL export may be supplied instead. The builder refuses partial inputs,
writes into private staging, validates the result, and only then installs it.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
import subprocess
import sys
import tempfile
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any

try:
    import pyarrow as pa
    import pyarrow.parquet as pq
except ModuleNotFoundError:  # pragma: no cover - concise CLI error in main()
    pa = None  # type: ignore[assignment]
    pq = None  # type: ignore[assignment]


EXPECTED_ROWS = 90_447
DEFAULT_SHARD_SIZE = 10_000
UPSTREAM_REPO_ID = "hotpotqa/hotpot_qa"
UPSTREAM_CONFIG = "distractor"
UPSTREAM_SPLIT = "train"
UPSTREAM_REVISION = "1908d6afbbead072334abe2965f91bd2709910ab"
PATCH_MANIFEST = Path(__file__).resolve().parents[1] / "SOURCE_PATCHES.json"


def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
    package_root = Path(__file__).resolve().parents[1]
    parser = argparse.ArgumentParser(
        description="Build and validate all Bactrainus HotpotQA train-only Parquet views."
    )
    parser.add_argument(
        "source",
        type=Path,
        nargs="?",
        help=(
            "optional complete official HotpotQA train JSON/JSONL export; "
            "omitted downloads the pinned Hugging Face source"
        ),
    )
    parser.add_argument(
        "--root",
        type=Path,
        default=package_root,
        help=f"dataset checkout root (default: {package_root})",
    )
    parser.add_argument(
        "--shard-size",
        type=int,
        default=DEFAULT_SHARD_SIZE,
        help=f"rows per Parquet shard (default: {DEFAULT_SHARD_SIZE})",
    )
    return parser.parse_args(argv)


def view_builders() -> tuple[tuple[str, Any], ...]:
    """Construct every task view approved by the release contract."""

    try:
        from bactrainus.data import (
            CotReaderViewBuilder,
            DecomposedSentenceSelectorViewBuilder,
            JointViewBuilder,
            ParagraphSelectorViewBuilder,
            QuestionDecomposerViewBuilder,
            ReaderViewBuilder,
            SentenceSelectorViewBuilder,
            StructuredViewBuilder,
        )
    except ModuleNotFoundError as error:
        raise RuntimeError(
            "Install the clean Bactrainus package before building the dataset"
        ) from error

    return (
        ("structured", StructuredViewBuilder()),
        ("reader-sft", ReaderViewBuilder()),
        ("cot-reader-sft", CotReaderViewBuilder()),
        ("paragraph-selector-sft", ParagraphSelectorViewBuilder()),
        ("question-decomposer-sft", QuestionDecomposerViewBuilder()),
        ("sentence-selector-sft", SentenceSelectorViewBuilder()),
        (
            "decomposed-sentence-selector-sft",
            DecomposedSentenceSelectorViewBuilder(),
        ),
        ("joint-selector-reader-sft", JointViewBuilder()),
    )


def _sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
    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 load_annotation_patches() -> dict[tuple[str, str, int], int | None]:
    """Load the reviewed repairs for invalid upstream sentence indices."""

    payload = json.loads(PATCH_MANIFEST.read_text(encoding="utf-8"))
    if payload.get("upstream_revision") != UPSTREAM_REVISION:
        raise ValueError(
            "SOURCE_PATCHES.json does not match the pinned upstream revision"
        )
    declared = payload.get("invalid_fact_count")
    records = payload.get("patches")
    if not isinstance(records, list) or declared != len(records):
        raise ValueError("SOURCE_PATCHES.json has an invalid patch count")

    patches: dict[tuple[str, str, int], int | None] = {}
    for record in records:
        if not isinstance(record, Mapping):
            raise TypeError("every source patch must be an object")
        key = (
            str(record["source_id"]),
            str(record["title"]),
            int(record["invalid_sentence_index"]),
        )
        if key in patches:
            raise ValueError(f"duplicate source patch: {key!r}")
        action = record.get("action")
        if action == "drop_redundant":
            patches[key] = None
        elif action == "replace":
            replacement = record.get("replacement_sentence_index")
            if isinstance(replacement, bool) or not isinstance(replacement, int):
                raise ValueError(f"source patch has invalid replacement: {key!r}")
            patches[key] = replacement
        else:
            raise ValueError(f"source patch has invalid action: {key!r}")
    return patches


def apply_annotation_patches(
    raw: dict[str, Any],
    patches: Mapping[tuple[str, str, int], int | None],
) -> dict[str, Any]:
    """Apply only manifest-listed repairs while preserving fact order."""

    source_id = raw.get("_id", raw.get("id"))
    resolved: list[list[Any]] = []
    for title, sentence_index in raw["supporting_facts"]:
        key = (source_id, title, sentence_index)
        if key not in patches:
            resolved.append([title, sentence_index])
            continue
        replacement = patches[key]
        if replacement is not None:
            resolved.append([title, replacement])
    raw["supporting_facts"] = resolved
    return raw


def _hub_row_to_raw(
    row: dict[str, Any],
    patches: Mapping[tuple[str, str, int], int | None],
) -> dict[str, Any]:
    """Convert the official Hugging Face feature layout to HotpotQA JSON."""

    context = row["context"]
    facts = row["supporting_facts"]
    titles = context["title"]
    sentences = context["sentences"]
    fact_titles = facts["title"]
    sentence_ids = facts["sent_id"]
    if len(titles) != len(sentences):
        raise ValueError(
            f"context columns are misaligned for source ID {row.get('id')!r}"
        )
    if len(fact_titles) != len(sentence_ids):
        raise ValueError(
            f"supporting-fact columns are misaligned for source ID {row.get('id')!r}"
        )
    return apply_annotation_patches(
        {
            "_id": row["id"],
            "question": row["question"],
            "answer": row["answer"],
            "type": row["type"],
            "level": row["level"],
            "context": [
                [title, values] for title, values in zip(titles, sentences, strict=True)
            ],
            "supporting_facts": [
                [title, sentence_id]
                for title, sentence_id in zip(fact_titles, sentence_ids, strict=True)
            ],
        },
        patches,
    )


def _load_local_records(path: Path) -> list[dict[str, Any]]:
    text = path.read_text(encoding="utf-8")
    if not text.strip():
        raise ValueError(f"source dataset is empty: {path}")
    if text.lstrip().startswith("["):
        payload = json.loads(text)
        if not isinstance(payload, list):
            raise ValueError("JSON dataset root must be a list")
        candidates = payload
    else:
        candidates = [json.loads(line) for line in text.splitlines() if line.strip()]
    if any(not isinstance(record, dict) for record in candidates):
        raise ValueError("every source record must be a JSON object")
    return candidates


def load_source_examples(source: Path | None) -> tuple[tuple[Any, ...], dict[str, Any]]:
    """Load a complete local export or the immutable official Hub revision."""

    try:
        from bactrainus.data import parse_hotpot_examples
    except ModuleNotFoundError as error:
        raise RuntimeError(
            "Install the clean Bactrainus package before building the dataset"
        ) from error

    patches = load_annotation_patches()
    if source is not None:
        resolved = source.resolve()
        if not resolved.is_file():
            raise FileNotFoundError(resolved)
        records = [
            apply_annotation_patches(record, patches)
            for record in _load_local_records(resolved)
        ]
        examples = parse_hotpot_examples(records, split=UPSTREAM_SPLIT)
        provenance = {
            "mode": "official-local-export",
            "filename": resolved.name,
            "bytes": resolved.stat().st_size,
            "sha256": _sha256_file(resolved),
        }
        return examples, provenance

    try:
        from datasets import load_dataset
    except ModuleNotFoundError as error:
        raise RuntimeError(
            "Install the 'datasets' package to build directly from Hugging Face"
        ) from error

    dataset = load_dataset(
        UPSTREAM_REPO_ID,
        UPSTREAM_CONFIG,
        split=UPSTREAM_SPLIT,
        revision=UPSTREAM_REVISION,
    )
    examples = parse_hotpot_examples(
        (_hub_row_to_raw(row, patches) for row in dataset), split=UPSTREAM_SPLIT
    )
    provenance = {
        "mode": "huggingface-datasets",
        "repository": UPSTREAM_REPO_ID,
        "revision": UPSTREAM_REVISION,
        "config": UPSTREAM_CONFIG,
        "split": UPSTREAM_SPLIT,
    }
    return examples, provenance


def write_source_manifest(
    destination: Path,
    provenance: dict[str, Any],
    configs: Sequence[str],
) -> None:
    """Write machine-readable source identity and release coverage."""

    payload = {
        "schema_version": 1,
        "upstream": {**provenance, "row_count": EXPECTED_ROWS},
        "annotation_patches": {
            "manifest": PATCH_MANIFEST.name,
            "invalid_fact_count": len(load_annotation_patches()),
            "sha256": _sha256_file(PATCH_MANIFEST),
        },
        "release": {
            "row_count_per_config": EXPECTED_ROWS,
            "identity_key": "source_id",
            "configs": list(configs),
        },
    }
    destination.write_text(
        json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )


def write_view(
    examples: Sequence[Any],
    builder: Any,
    destination: Path,
    shard_size: int,
) -> int:
    """Write one deterministic view with a stable schema across shards."""

    assert pa is not None and pq is not None
    destination.mkdir(parents=True, exist_ok=False)
    shard_count = math.ceil(len(examples) / shard_size)
    reference_schema: Any | None = None
    for shard_index, start in enumerate(range(0, len(examples), shard_size)):
        stop = min(start + shard_size, len(examples))
        rows = [builder.build(example).to_dict() for example in examples[start:stop]]
        table = pa.Table.from_pylist(rows, schema=reference_schema)
        if reference_schema is None:
            reference_schema = table.schema
        shard_name = f"train-{shard_index:05d}-of-{shard_count:05d}.parquet"
        pq.write_table(
            table,
            destination / shard_name,
            compression="zstd",
            use_dictionary=True,
            write_statistics=True,
        )
    return shard_count


def build_release(source: Path | None, root: Path, shard_size: int) -> None:
    """Build in staging, validate, and atomically install release artifacts."""

    if shard_size <= 0:
        raise ValueError("--shard-size must be positive")
    root = root.resolve()
    if not root.is_dir():
        raise FileNotFoundError(root)
    target_data = root / "data"
    target_manifest = root / "CHECKSUMS.sha256"
    target_source_manifest = root / "SOURCE_MANIFEST.json"
    if (
        target_data.exists()
        or target_manifest.exists()
        or target_source_manifest.exists()
    ):
        raise FileExistsError(
            "Refusing to overwrite existing release artifacts; use a clean checkout"
        )

    examples, provenance = load_source_examples(source)
    if len(examples) != EXPECTED_ROWS:
        raise ValueError(
            f"source contains {len(examples):,} records; expected {EXPECTED_ROWS:,}"
        )

    validator = Path(__file__).with_name("validate_release.py").resolve()
    with tempfile.TemporaryDirectory(
        prefix=".bactrainus-build-", dir=root
    ) as temporary:
        staging = Path(temporary)
        builders = view_builders()
        for config, builder in builders:
            shards = write_view(
                examples,
                builder,
                staging / "data" / config,
                shard_size,
            )
            print(f"built {config}: {len(examples):,} rows in {shards} shard(s)")

        subprocess.run(
            [sys.executable, str(validator), "--root", str(staging)],
            check=True,
        )
        write_source_manifest(
            staging / "SOURCE_MANIFEST.json",
            provenance,
            [config for config, _ in builders],
        )
        os.replace(staging / "data", target_data)
        os.replace(staging / "CHECKSUMS.sha256", target_manifest)
        os.replace(staging / "SOURCE_MANIFEST.json", target_source_manifest)


def main(argv: Sequence[str] | None = None) -> int:
    args = parse_args(argv)
    if pa is None or pq is None:
        print(
            "error: pyarrow is required; install Bactrainus with the 'data' extra",
            file=sys.stderr,
        )
        return 2
    try:
        build_release(args.source, args.root, args.shard_size)
    except (FileNotFoundError, FileExistsError, RuntimeError, ValueError) as error:
        print(f"error: {error}", file=sys.stderr)
        return 1
    print("Release build completed only after full validation.")
    return 0


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