"""Reconstruct and seed-sample paired CoQAR dev inputs from pinned raw data. Sampling is uniform over mechanically eligible question turns, not stories. Answerability judgments, gold-answer survival, and model outcomes never determine eligibility. Every selected turn retains both original and sentence-ablated text. """ from __future__ import annotations from collections import Counter from copy import deepcopy import hashlib import importlib.metadata import json import os from pathlib import Path import random import tempfile from typing import Any from urllib.request import urlopen import build_dataset from build_dataset import ( EnglishSentenceSegmenter, inspect_span, overlaps, quality_summary, sha256_file, transform_split, write_json, ) DEV_SHA256 = "3d093e1bf45e44f7cc4e3b8e07a37ded9162ded4ac88e90bb9e4c5657be3251f" DEV_URL = ( "https://raw.githubusercontent.com/Orange-OpenSource/COQAR/" f"{build_dataset.SOURCE_REVISION}/data/CoQAR/dev/coqar-dev-v1.0.json" ) SCHEMA_VERSION = "coqar-dev-paired-subset-v1" DEFAULT_SIZE = 1000 DEFAULT_SEED = 20260911 def ensure_raw_source(raw_path: Path) -> Path: """Verify an existing source or atomically install a pinned official download. The request uses the public source URL without authentication. A failed or mismatched download is deleted; an existing destination is never overwritten. """ raw_path = Path(raw_path).resolve() if raw_path.exists(): actual = sha256_file(raw_path) if actual != DEV_SHA256: raise ValueError(f"Existing CoQAR dev SHA256 mismatch: expected {DEV_SHA256}, got {actual}") return raw_path raw_path.parent.mkdir(parents=True, exist_ok=True) temporary_path = None try: with tempfile.NamedTemporaryFile( dir=raw_path.parent, prefix=f".{raw_path.name}.", suffix=".tmp", delete=False) as handle: temporary_path = Path(handle.name) digest = hashlib.sha256() with urlopen(DEV_URL, timeout=60) as response: for chunk in iter(lambda: response.read(1024 * 1024), b""): digest.update(chunk) handle.write(chunk) handle.flush() os.fsync(handle.fileno()) actual = digest.hexdigest() if actual != DEV_SHA256: raise ValueError(f"Downloaded CoQAR dev SHA256 mismatch: expected {DEV_SHA256}, got {actual}") try: # Same-directory hard linking atomically creates the destination and # fails if another process already installed a file at this path. os.link(temporary_path, raw_path) except FileExistsError: if sha256_file(raw_path) != DEV_SHA256: raise ValueError("A different file appeared at the raw source path during download") from None return raw_path finally: if temporary_path is not None: temporary_path.unlink(missing_ok=True) def _canonical_hash(value: Any) -> str: return hashlib.sha256(json.dumps( value, ensure_ascii=False, sort_keys=True, separators=(",", ":") ).encode("utf-8")).hexdigest() def _validate_row(row: dict[str, Any], story_record: dict[str, Any], question: dict[str, Any], answer: dict[str, Any] | None) -> None: """Verify unchanged inputs and deletion by exact source-character identity.""" story = story_record["story"] if row["original_story"] != story or row["source_question_annotation"] != question: raise ValueError(f"Original source text or question changed: {row['id']}") rewrites = question.get("paraphrase", []) canonical = next((text for text in rewrites if isinstance(text, str) and text.strip()), None) if (row["original_question"] != question.get("input_text") or row["rewrites"] != rewrites or row["question"] != canonical): raise ValueError(f"Question rewrite changed: {row['id']}") span = inspect_span(story, answer) if row["gold_answer_annotation"] != answer or row["span_diagnostics"] != span: raise ValueError(f"Source answer annotation changed: {row['id']}") previous_end = 0 for sentence in row["sentences"]: start, end = sentence["start"], sentence["end"] if (not 0 <= previous_end <= start < end <= len(story) or story[start:end] != sentence["text"] or story[previous_end:start].strip()): raise ValueError(f"Invalid exact sentence coverage: {row['id']}") previous_end = end if not row["flags"]["sentence_segmentation_failed"] and story[previous_end:].strip(): raise ValueError(f"Uncovered sentence suffix: {row['id']}") expected_removed = [sentence for sentence in row["sentences"] if span["valid_for_deletion"] and overlaps( sentence["start"], sentence["end"], span["start"], span["end"])] if row["removed_sentences"] != expected_removed: raise ValueError(f"Deletion did not cover exactly the overlapping sentences: {row['id']}") fragments, cursor = [], 0 for sentence in expected_removed: fragments.append(story[cursor:sentence["start"]]) cursor = sentence["end"] fragments.append(story[cursor:]) if row["modified_story"] != "".join(fragments): raise ValueError(f"Deletion changed retained source characters: {row['id']}") if row["removed_characters"] != sum(s["end"] - s["start"] for s in expected_removed): raise ValueError(f"Incorrect removed-character count: {row['id']}") eligible = bool(canonical and expected_removed and row["modified_story"].strip()) if row["eligible_for_sampling"] != eligible: raise ValueError(f"Eligibility is not purely mechanical: {row['id']}") def _length_summary(examples: list[dict[str, Any]]) -> dict[str, Any]: def describe(values: list[int]) -> dict[str, int | float]: return {"min": min(values), "max": max(values), "total": sum(values), "mean": sum(values) / len(values)} return { field: describe([len(row[field]) for row in examples]) for field in ("original_story", "modified_story", "question") } | { "removed_characters": describe([row["removed_characters"] for row in examples]), "removed_sentence_counts": dict(sorted(Counter( str(len(row["removed_sentences"])) for row in examples).items())), "unit": "Python Unicode characters; sentence counts separately labeled", } def prepare_subset(raw_path: Path, output_path: Path, size: int = DEFAULT_SIZE, seed: int = DEFAULT_SEED, exclude_ids: list[str] | None = None, metadata: dict[str, Any] | None = None) -> dict[str, Any]: """Build a paired subset, or verify and reuse an identical existing artifact. Caller supplies clean-checkout experiment metadata. On resume the original metadata is retained; input/config/code hashes and every reconstructed example must still match. No previously generated derivative is trusted as input. """ if isinstance(size, bool) or not isinstance(size, int) or size < 1: raise ValueError("size must be a positive integer") if isinstance(seed, bool) or not isinstance(seed, int): raise ValueError("seed must be an integer") if not isinstance(metadata, dict): raise ValueError("metadata must be a dictionary supplied by the experiment runner") if exclude_ids is None: exclude_ids = [] if not isinstance(exclude_ids, list) or any(not isinstance(eid, str) for eid in exclude_ids): raise ValueError("exclude_ids must be a list of dataset ID strings") raw_path, output_path = Path(raw_path).resolve(), Path(output_path).resolve() source_hash = sha256_file(raw_path) if source_hash != DEV_SHA256: raise ValueError(f"Raw CoQAR dev SHA256 mismatch: expected {DEV_SHA256}, got {source_hash}") source = json.loads(raw_path.read_text(encoding="utf-8")) if not isinstance(source, dict) or not isinstance(source.get("data"), list): raise ValueError("Raw CoQAR source must contain a data list") config = { "size": size, "seed": seed, "split": "dev", "excluded_ids": sorted(set(exclude_ids)), "sampling_unit": "question turn; multiple turns per story are allowed", "sampling_algorithm": "random.Random(seed).sample(sorted(eligible_rows, key=id), size)", "sampling_without_replacement": True, "eligibility": ["nonempty standalone rewrite", "valid primary annotated rationale", "exact sentence coverage", "at least one overlapping sentence removed", "nonempty text remaining after sentence deletion"], "outcome_filters": [], "question_rewrite": "first nonempty source paraphrase, in source order", "sentence_segmenter": "spacy.blank('en') + sentencizer; default punctuation", "spacy_version": importlib.metadata.version("spacy"), "overlap": "sentence.start < span.end and span.start < sentence.end", "offsets": "Python Unicode character offsets, half-open [start,end)", "whitespace": "exact surviving source characters, including sentence separators", } preparation = { "schema_version": SCHEMA_VERSION, "config": config, "source": {"path": str(raw_path), "sha256": source_hash, "bytes": raw_path.stat().st_size, "version": source.get("version"), "download_url": DEV_URL, "repository": build_dataset.SOURCE_REPO, "revision": build_dataset.SOURCE_REVISION}, "code_sha256": { "scale_prepare.py": sha256_file(Path(__file__)), "build_dataset.py": sha256_file(Path(build_dataset.__file__)), }, } rows = transform_split(source, "dev", EnglishSentenceSegmenter()) rows_by_id = {row["id"]: row for row in rows} for story_record in source["data"]: answers = {answer["turn_id"]: answer for answer in story_record["answers"]} for question in story_record["questions"]: eid = f"dev:{story_record['id']}:{question['turn_id']}" _validate_row(rows_by_id[eid], story_record, question, answers.get(question["turn_id"])) excluded = set(config["excluded_ids"]) eligible = sorted((row for row in rows if row["eligible_for_sampling"] and row["id"] not in excluded), key=lambda row: row["id"]) if size > len(eligible): raise ValueError(f"Requested {size} examples, but only {len(eligible)} are eligible after exclusions") examples = random.Random(seed).sample(eligible, size) ineligible = [row for row in rows if not row["eligible_for_sampling"]] reason_counts = Counter() ineligible_reasons = [] for row in ineligible: reasons = [] if row["flags"]["missing_rewrite"]: reasons.append("missing_rewrite") if row["flags"]["span_validation_failed"]: reasons.append("span:" + row["span_diagnostics"]["status"]) if row["flags"]["sentence_segmentation_failed"]: reasons.append("sentence_segmentation_failed") if not row["removed_sentences"]: reasons.append("no_overlapping_sentence_removed") if row["flags"]["story_empty_after_removal"]: reasons.append("empty_text_after_removal") reason_counts.update(reasons) ineligible_reasons.append({"id": row["id"], "reasons": reasons}) selection = { "raw_turns": len(rows), "raw_stories": len(source["data"]), "mechanically_eligible_before_exclusions": sum(row["eligible_for_sampling"] for row in rows), "ineligible_turns": len(ineligible), "ineligible_reason_counts_overlapping": dict(sorted(reason_counts.items())), "ineligible_turn_details": sorted(ineligible_reasons, key=lambda item: item["id"]), "excluded_ids_present": sorted(excluded & rows_by_id.keys()), "excluded_ids_not_in_source": sorted(excluded - rows_by_id.keys()), "excluded_eligible_ids": sorted(row["id"] for row in rows if row["eligible_for_sampling"] and row["id"] in excluded), "eligible_pool_size": len(eligible), "eligible_pool_ids_sha256": _canonical_hash([row["id"] for row in eligible]), "selected_ids": [row["id"] for row in examples], "selected_count": len(examples), "paired_condition_count": 2 * len(examples), "selected_distinct_stories": len({row["story_id"] for row in examples}), "source_counts": dict(sorted(Counter(row["source"] for row in examples).items())), "lengths": _length_summary(examples), "raw_quality_summary": quality_summary(rows), "selection_limitation": "Mechanical rationale removal does not guarantee semantic unanswerability.", } artifact = { "metadata": {**deepcopy(metadata), "subset_preparation": preparation}, "selection": selection, "examples_sha256": _canonical_hash(examples), "examples": examples, } if output_path.exists(): previous = json.loads(output_path.read_text(encoding="utf-8")) if (previous.get("metadata", {}).get("subset_preparation") != preparation or previous.get("selection") != selection or previous.get("examples_sha256") != artifact["examples_sha256"] or previous.get("examples") != examples): raise ValueError("Existing subset differs from the reconstructed source/configuration; use a new output path") return previous write_json(output_path, artifact) written = json.loads(output_path.read_text(encoding="utf-8")) if written != artifact: raise RuntimeError("Written subset did not round-trip exactly") return artifact