#!/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())