"""Materialise and independently verify one quality verdict per BGD record. The canonical dataset is immutable input. This command streams each canonical shard into a corresponding deterministic gzip JSONL sidecar, then performs a second pass over both datasets to prove record-for-record alignment. Exact regeneration intentionally uses the explicitly supplied, immutable generation configuration. It does not use ``config.snapshot.json`` because snapshot publication can rewrite serialization details; this also keeps the audit contract valid for historical generators that were key-order sensitive. """ from __future__ import annotations import argparse import hashlib import json import sys from collections import Counter, defaultdict from collections.abc import Mapping, Sequence from concurrent.futures import ProcessPoolExecutor, as_completed from dataclasses import dataclass, field from pathlib import Path from typing import Any, Iterator from .generation import GenerationPlan from .io import ( ShardResult, iter_jsonl_gz, sha256_file, write_json_atomic, write_jsonl_gz_atomic, ) from .quality import QUALITY_SCHEMA_VERSION, canonical_sha256, validate_record_quality QUALITY_MANIFEST_VERSION = "bgd.quality.manifest.v1" QUALITY_REPORT_VERSION = "bgd.quality.report.v1" QUALITY_POSTWRITE_VERSION = "bgd.quality.postwrite.v1" QUALITY_MARKER_VERSION = "bgd.quality.marker.v1" SOURCE_BUNDLE_VERSION = "bgd.quality.source-bundle.v1" DEFAULT_PROJECT_ROOT = Path(__file__).resolve().parents[2] _MAX_FINDING_EXAMPLES = 100 _MAX_POSTWRITE_ISSUES = 100 def _sorted_counter(counter: Counter[str]) -> dict[str, int]: return {key: counter[key] for key in sorted(counter)} def _cross_table(table: Mapping[str, Counter[str]]) -> dict[str, dict[str, int]]: return {key: _sorted_counter(table[key]) for key in sorted(table)} @dataclass(slots=True) class QualityStats: """Small, mergeable aggregate of the materialised verdict stream.""" total_records: int = 0 disposition: Counter[str] = field(default_factory=Counter) hard_failures: Counter[str] = field(default_factory=Counter) structural_failures: Counter[str] = field(default_factory=Counter) reproducibility_failures: Counter[str] = field(default_factory=Counter) semantic_blockers: Counter[str] = field(default_factory=Counter) review_flags: Counter[str] = field(default_factory=Counter) check_passed: Counter[str] = field(default_factory=Counter) check_failed: Counter[str] = field(default_factory=Counter) primitive: Counter[str] = field(default_factory=Counter) task_family: Counter[str] = field(default_factory=Counter) split: Counter[str] = field(default_factory=Counter) disposition_by_primitive: dict[str, Counter[str]] = field( default_factory=lambda: defaultdict(Counter) ) disposition_by_task_family: dict[str, Counter[str]] = field( default_factory=lambda: defaultdict(Counter) ) disposition_by_split: dict[str, Counter[str]] = field( default_factory=lambda: defaultdict(Counter) ) target_decision_by_task_family: dict[str, Counter[str]] = field( default_factory=lambda: defaultdict(Counter) ) confidence_target_histogram: Counter[str] = field(default_factory=Counter) rank_top_candidate_id: Counter[str] = field(default_factory=Counter) match_winner_candidate_id: Counter[str] = field(default_factory=Counter) winner_candidate_id_by_task_family: dict[str, Counter[str]] = field( default_factory=lambda: defaultdict(Counter) ) integrity_passed: int = 0 structural_integrity_passed: int = 0 reproducibility_passed: int = 0 semantic_passed: int = 0 strict_fitness_passed: int = 0 training_ready: int = 0 exact_hash_match: int = 0 validator_exceptions: int = 0 def ingest( self, verdict: Mapping[str, Any], canonical_record: Mapping[str, Any] | None = None, ) -> None: self.total_records += 1 disposition = str(verdict.get("disposition", "")) primitive = str(verdict.get("primitive", "")) task_family = str(verdict.get("task_family", "")) split = str(verdict.get("split", "")) self.disposition[disposition] += 1 self.primitive[primitive] += 1 self.task_family[task_family] += 1 self.split[split] += 1 self.disposition_by_primitive[primitive][disposition] += 1 self.disposition_by_task_family[task_family][disposition] += 1 self.disposition_by_split[split][disposition] += 1 hard_failures = verdict.get("hard_failures", []) if isinstance(hard_failures, Sequence) and not isinstance( hard_failures, (str, bytes, bytearray) ): self.hard_failures.update(str(value) for value in hard_failures) for field_name in ( "structural_failures", "reproducibility_failures", "semantic_blockers", ): values = verdict.get(field_name, []) if isinstance(values, Sequence) and not isinstance( values, (str, bytes, bytearray) ): getattr(self, field_name).update(str(value) for value in values) review_flags = verdict.get("review_flags", []) if isinstance(review_flags, Sequence) and not isinstance( review_flags, (str, bytes, bytearray) ): self.review_flags.update(str(value) for value in review_flags) checks = verdict.get("checks", {}) if isinstance(checks, Mapping): for name, passed in checks.items(): (self.check_passed if bool(passed) else self.check_failed)[str(name)] += 1 self.integrity_passed += bool(verdict.get("integrity_passed")) self.structural_integrity_passed += bool( verdict.get("structural_integrity_passed") ) self.reproducibility_passed += bool(verdict.get("reproducibility_passed")) self.semantic_passed += bool(verdict.get("semantic_passed")) self.strict_fitness_passed += bool(verdict.get("strict_fitness_passed")) self.training_ready += bool(verdict.get("training_ready")) self.exact_hash_match += ( verdict.get("canonical_sha256") is not None and verdict.get("canonical_sha256") == verdict.get("reproduced_sha256") ) self.validator_exceptions += "QUALITY_VALIDATOR_EXCEPTION" in hard_failures if canonical_record is not None: target = canonical_record.get("target", {}) if isinstance(target, Mapping): decision = target.get("decision", "") decision_key = str(decision) self.target_decision_by_task_family[task_family][decision_key] += 1 confidence = target.get("confidence_target", "") confidence_key = ( confidence if isinstance(confidence, str) else json.dumps( confidence, ensure_ascii=False, sort_keys=True, separators=(",", ":"), ) ) self.confidence_target_histogram[str(confidence_key)] += 1 ranking = target.get("ranking") if isinstance(ranking, list) and ranking: winner = str(ranking[0]) self.rank_top_candidate_id[winner] += 1 self.winner_candidate_id_by_task_family[task_family][winner] += 1 canonical_id = target.get("canonical_id") if isinstance(canonical_id, str) and canonical_id: self.match_winner_candidate_id[canonical_id] += 1 self.winner_candidate_id_by_task_family[task_family][canonical_id] += 1 def merge(self, other: "QualityStats") -> None: self.total_records += other.total_records for name in ( "disposition", "hard_failures", "structural_failures", "reproducibility_failures", "semantic_blockers", "review_flags", "check_passed", "check_failed", "primitive", "task_family", "split", "confidence_target_histogram", "rank_top_candidate_id", "match_winner_candidate_id", ): getattr(self, name).update(getattr(other, name)) for name in ( "disposition_by_primitive", "disposition_by_task_family", "disposition_by_split", "target_decision_by_task_family", "winner_candidate_id_by_task_family", ): target = getattr(self, name) for key, counter in getattr(other, name).items(): target[key].update(counter) self.integrity_passed += other.integrity_passed self.structural_integrity_passed += other.structural_integrity_passed self.reproducibility_passed += other.reproducibility_passed self.semantic_passed += other.semantic_passed self.strict_fitness_passed += other.strict_fitness_passed self.training_ready += other.training_ready self.exact_hash_match += other.exact_hash_match self.validator_exceptions += other.validator_exceptions def to_dict(self) -> dict[str, Any]: check_names = sorted(set(self.check_passed) | set(self.check_failed)) checks = { name: { "passed": self.check_passed[name], "failed": self.check_failed[name], } for name in check_names } total = self.total_records return { "total_records": total, "disposition": _sorted_counter(self.disposition), "hard_failures": _sorted_counter(self.hard_failures), "structural_failures": _sorted_counter(self.structural_failures), "reproducibility_failures": _sorted_counter(self.reproducibility_failures), "semantic_blockers": _sorted_counter(self.semantic_blockers), "review_flags": _sorted_counter(self.review_flags), "checks": checks, "primitive": _sorted_counter(self.primitive), "task_family": _sorted_counter(self.task_family), "split": _sorted_counter(self.split), "disposition_by_primitive": _cross_table(self.disposition_by_primitive), "disposition_by_task_family": _cross_table(self.disposition_by_task_family), "disposition_by_split": _cross_table(self.disposition_by_split), "target_decision_by_task_family": _cross_table( self.target_decision_by_task_family ), "confidence_target_histogram": _sorted_counter( self.confidence_target_histogram ), "rank_top_candidate_id": _sorted_counter(self.rank_top_candidate_id), "match_winner_candidate_id": _sorted_counter( self.match_winner_candidate_id ), "winner_candidate_id_by_task_family": _cross_table( self.winner_candidate_id_by_task_family ), "integrity_passed_records": self.integrity_passed, "integrity_passed_ratio": round(self.integrity_passed / total, 8) if total else 0.0, "strict_fitness_passed_records": self.strict_fitness_passed, "strict_fitness_passed_ratio": ( round(self.strict_fitness_passed / total, 8) if total else 0.0 ), "structural_integrity_passed_records": self.structural_integrity_passed, "reproducibility_passed_records": self.reproducibility_passed, "semantic_passed_records": self.semantic_passed, "training_ready_records": self.training_ready, "training_ready_false_records": total - self.training_ready, "canonical_reproduction_hash_match_records": self.exact_hash_match, "quality_validator_exception_records": self.validator_exceptions, } @dataclass(frozen=True, slots=True) class ShardTask: canonical_path: str canonical_sha256: str canonical_manifest_records: int records_to_process: int start_index: int verdict_path: str config: dict[str, Any] compresslevel: int @dataclass(slots=True) class QualityShardResult: canonical_path: str canonical_sha256: str canonical_manifest_records: int records_processed: int start_index: int verdict: ShardResult stats: QualityStats finding_examples: list[dict[str, Any]] def _load_json_object(path: str | Path) -> dict[str, Any]: source = Path(path) value = json.loads(source.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError(f"expected a JSON object: {source}") return value def _semantic_sha256(value: Mapping[str, Any]) -> str: encoded = json.dumps( dict(value), ensure_ascii=False, sort_keys=True, separators=(",", ":") ).encode("utf-8") return hashlib.sha256(encoded).hexdigest() def _order_sensitive_sha256(value: Mapping[str, Any]) -> str: encoded = json.dumps( dict(value), ensure_ascii=False, sort_keys=False, separators=(",", ":") ).encode("utf-8") return hashlib.sha256(encoded).hexdigest() def _mapping_key_order_equal(left: Any, right: Any) -> bool: if isinstance(left, Mapping) and isinstance(right, Mapping): if list(left) != list(right): return False return all(_mapping_key_order_equal(left[key], right[key]) for key in left) if isinstance(left, list) and isinstance(right, list): return len(left) == len(right) and all( _mapping_key_order_equal(a, b) for a, b in zip(left, right, strict=True) ) return left == right def _generation_plan_sha256(config: Mapping[str, Any]) -> str: """Hash every order-sensitive decision that defines the global plan.""" plan = GenerationPlan(dict(config)) payload = { "primitive_cycle": plan.primitive_cycle, "mixture_cycle": plan.mixture_cycle, "serializer_cycle": plan.serializer_cycle, "long_slots": plan.long_slots, "train_end": plan.train_end, "validation_end": plan.validation_end, "total": plan.total, } return _semantic_sha256(payload) def _source_bundle( project_root: Path, generation_config_path: Path, config_snapshot_path: Path, ) -> dict[str, Any]: """Hash the executable Python, schema, and configuration inputs.""" paths: list[tuple[str, Path]] = [] for root_name in ("src", "schema", "configs"): root = project_root / root_name if not root.exists(): continue for path in sorted(candidate for candidate in root.rglob("*") if candidate.is_file()): if "__pycache__" in path.parts or path.suffix in {".pyc", ".pyo"}: continue paths.append((path.relative_to(project_root).as_posix(), path.resolve())) pyproject = project_root / "pyproject.toml" if pyproject.is_file(): paths.append(("pyproject.toml", pyproject.resolve())) explicit = ( ("runtime/generation-config.json", generation_config_path.resolve()), ("dataset/config.snapshot.json", config_snapshot_path.resolve()), ) paths.extend(explicit) # Logical names, rather than absolute path names, make the aggregate hash # stable while still retaining the resolved path for auditability. entries: list[dict[str, Any]] = [] seen: set[tuple[str, Path]] = set() for logical_path, path in sorted(paths, key=lambda item: item[0]): key = (logical_path, path) if key in seen: continue seen.add(key) entries.append( { "logical_path": logical_path, "path": str(path), "sha256": sha256_file(path), "bytes": path.stat().st_size, } ) digest_payload = [ { "logical_path": entry["logical_path"], "sha256": entry["sha256"], "bytes": entry["bytes"], } for entry in entries ] digest = hashlib.sha256( json.dumps(digest_payload, sort_keys=True, separators=(",", ":")).encode("utf-8") ).hexdigest() return { "version": SOURCE_BUNDLE_VERSION, "sha256": digest, "files": entries, } def _validator_exception_verdict(record: Mapping[str, Any], exc: Exception) -> dict[str, Any]: """Preserve one sidecar row even if an individual validator raises.""" record_id = record.get("record_id") try: record_index = int(str(record_id).rsplit("_", 1)[-1]) except ValueError: record_index = None return { "record_id": record_id, "record_index": record_index, "quality_schema_version": QUALITY_SCHEMA_VERSION, "primitive": record.get("primitive"), "task_family": record.get("task_family"), "split": record.get("split"), "canonical_sha256": canonical_sha256(record), "reproduced_sha256": None, "reproducibility_passed": False, "structural_integrity_passed": False, "integrity_passed": False, "semantic_passed": False, "strict_fitness_passed": False, "training_ready": False, "disposition": "REJECT", "check_pass_ratio": 0.0, "checks": {"quality_validator_execution": False}, "hard_failures": ["QUALITY_VALIDATOR_EXCEPTION"], "structural_failures": ["QUALITY_VALIDATOR_EXCEPTION"], "reproducibility_failures": [], "semantic_blockers": [], "review_flags": [], "scope_limitations": [ "SYNTHETIC_TEMPLATE_ONLY", "NO_HUMAN_REVIEW", "NO_REAL_MODALITY_SIGNAL", ], "canonical_validation_errors": [], "metrics": {}, "runner_error": { "type": type(exc).__name__, "message": str(exc)[:500], }, } def _validate_shard(task: ShardTask) -> QualityShardResult: canonical_path = Path(task.canonical_path) actual_source_sha = sha256_file(canonical_path) if actual_source_sha != task.canonical_sha256: raise ValueError( f"canonical checksum mismatch for {canonical_path}: " f"{actual_source_sha} != {task.canonical_sha256}" ) if not 1 <= task.records_to_process <= task.canonical_manifest_records: raise ValueError(f"invalid record limit for {canonical_path}") plan = GenerationPlan(task.config) stats = QualityStats() examples: list[dict[str, Any]] = [] canonical_iter = iter_jsonl_gz(canonical_path) def verdict_stream() -> Iterator[dict[str, Any]]: for ordinal in range(task.records_to_process): try: record = next(canonical_iter) except StopIteration as exc: raise ValueError( f"short canonical shard {canonical_path}: stopped at {ordinal}, " f"expected {task.records_to_process}" ) from exc try: verdict = validate_record_quality(record, task.config, plan) except Exception as exc: # one bad checker must still receive a verdict verdict = _validator_exception_verdict(record, exc) verdict = dict(verdict) verdict["source_shard"] = canonical_path.name verdict["source_line"] = ordinal + 1 verdict["expected_record_index"] = task.start_index + ordinal stats.ingest(verdict, record) if verdict.get("disposition") != "KEEP" and len(examples) < 10: examples.append( { "record_id": verdict.get("record_id"), "disposition": verdict.get("disposition"), "hard_failures": verdict.get("hard_failures", []), "structural_failures": verdict.get("structural_failures", []), "semantic_blockers": verdict.get("semantic_blockers", []), "review_flags": verdict.get("review_flags", []), } ) yield verdict if task.records_to_process == task.canonical_manifest_records: try: extra = next(canonical_iter) except StopIteration: return raise ValueError( f"canonical shard {canonical_path} contains more than manifest count; " f"first extra record={extra.get('record_id')}" ) verdict_result = write_jsonl_gz_atomic( task.verdict_path, verdict_stream(), compresslevel=task.compresslevel, ) if verdict_result.records != task.records_to_process: raise RuntimeError( f"short quality sidecar {verdict_result.path}: " f"{verdict_result.records} != {task.records_to_process}" ) return QualityShardResult( canonical_path=str(canonical_path), canonical_sha256=actual_source_sha, canonical_manifest_records=task.canonical_manifest_records, records_processed=task.records_to_process, start_index=task.start_index, verdict=verdict_result, stats=stats, finding_examples=examples, ) def _resolve_manifest_path(raw_path: str, manifest_path: Path) -> Path: path = Path(raw_path) if not path.is_absolute(): path = manifest_path.parent / path return path.resolve() def _sidecar_name(canonical_path: Path) -> str: name = canonical_path.name suffix = ".jsonl.gz" stem = name[: -len(suffix)] if name.endswith(suffix) else name return f"{stem}.quality.jsonl.gz" def _build_tasks( manifest: Mapping[str, Any], manifest_path: Path, output_root: Path, config: dict[str, Any], requested_records: int, compresslevel: int, ) -> list[ShardTask]: raw_shards = manifest.get("shards") if not isinstance(raw_shards, list) or not raw_shards: raise ValueError("canonical manifest has no shards") remaining = requested_records source_start_index = 0 tasks: list[ShardTask] = [] source_paths: set[Path] = set() sidecar_names: set[str] = set() for entry in raw_shards: if remaining == 0: break if not isinstance(entry, Mapping): raise ValueError("canonical manifest shard entry is not an object") canonical_path = _resolve_manifest_path(str(entry.get("path", "")), manifest_path) if not canonical_path.is_file(): raise FileNotFoundError(canonical_path) if canonical_path in source_paths: raise ValueError(f"duplicate canonical shard path: {canonical_path}") source_paths.add(canonical_path) manifest_records = int(entry.get("records", 0)) if manifest_records <= 0: raise ValueError(f"invalid canonical record count: {canonical_path}") expected_sha = str(entry.get("sha256", "")) if len(expected_sha) != 64: raise ValueError(f"invalid canonical checksum: {canonical_path}") take = min(remaining, manifest_records) sidecar_name = _sidecar_name(canonical_path) if sidecar_name in sidecar_names: raise ValueError(f"duplicate sidecar name: {sidecar_name}") sidecar_names.add(sidecar_name) tasks.append( ShardTask( canonical_path=str(canonical_path), canonical_sha256=expected_sha, canonical_manifest_records=manifest_records, records_to_process=take, start_index=source_start_index, verdict_path=str((output_root / "verdicts" / sidecar_name).resolve()), config=config, compresslevel=compresslevel, ) ) remaining -= take source_start_index += manifest_records if remaining: raise ValueError( f"canonical manifest contains fewer records than requested: missing {remaining}" ) return tasks def _run_tasks(tasks: list[ShardTask], workers: int) -> list[QualityShardResult]: worker_count = max(1, min(int(workers), len(tasks))) results: list[QualityShardResult] = [] if worker_count == 1: for index, task in enumerate(tasks, 1): result = _validate_shard(task) results.append(result) print( f"quality {index}/{len(tasks)} {result.verdict.path.name} " f"records={result.records_processed}", flush=True, ) return results with ProcessPoolExecutor(max_workers=worker_count) as executor: futures = {executor.submit(_validate_shard, task): task for task in tasks} completed = 0 for future in as_completed(futures): task = futures[future] result = future.result() results.append(result) completed += 1 print( f"quality {completed}/{len(tasks)} {Path(task.verdict_path).name} " f"records={result.records_processed}", flush=True, ) return results def _aggregate_results( results: Sequence[QualityShardResult], ) -> tuple[QualityStats, list[dict[str, Any]]]: stats = QualityStats() examples: list[dict[str, Any]] = [] for result in sorted(results, key=lambda item: item.start_index): stats.merge(result.stats) for example in result.finding_examples: if len(examples) < _MAX_FINDING_EXAMPLES: examples.append(example) return stats, examples def _pin_metadata( *, project_root: Path, generation_config_path: Path, config_snapshot_path: Path, canonical_manifest_path: Path, config: Mapping[str, Any], snapshot: Mapping[str, Any], ) -> tuple[dict[str, Any], list[str]]: order_equal = _mapping_key_order_equal(config, snapshot) warnings: list[str] = [] if not order_equal: warnings.append( "config.snapshot.json is semantically equal but mapping key order differs; " "the immutable explicit generation config was used for exact regeneration" ) pins = { "generation_config": { "path": str(generation_config_path.resolve()), "raw_sha256": sha256_file(generation_config_path), "semantic_sha256": _semantic_sha256(config), "order_sensitive_sha256": _order_sensitive_sha256(config), "generation_plan_sha256": _generation_plan_sha256(config), "used_for_exact_regeneration": True, }, "config_snapshot": { "path": str(config_snapshot_path.resolve()), "raw_sha256": sha256_file(config_snapshot_path), "semantic_sha256": _semantic_sha256(snapshot), "order_sensitive_sha256": _order_sensitive_sha256(snapshot), "generation_plan_sha256": _generation_plan_sha256(snapshot), "semantically_equal_to_generation_config": snapshot == config, "mapping_key_order_equal_to_generation_config": order_equal, "used_for_exact_regeneration": False, }, "canonical_manifest": { "path": str(canonical_manifest_path.resolve()), "raw_sha256": sha256_file(canonical_manifest_path), "bytes": canonical_manifest_path.stat().st_size, }, "source_bundle": _source_bundle( project_root, generation_config_path, config_snapshot_path ), } return pins, warnings def _pins_unchanged( initial: Mapping[str, Any], *, project_root: Path, generation_config_path: Path, config_snapshot_path: Path, canonical_manifest_path: Path, ) -> bool: current_bundle = _source_bundle(project_root, generation_config_path, config_snapshot_path) return ( sha256_file(generation_config_path) == initial["generation_config"]["raw_sha256"] and sha256_file(config_snapshot_path) == initial["config_snapshot"]["raw_sha256"] and sha256_file(canonical_manifest_path) == initial["canonical_manifest"]["raw_sha256"] and current_bundle["sha256"] == initial["source_bundle"]["sha256"] and current_bundle["files"] == initial["source_bundle"]["files"] ) def _quality_gates( stats: QualityStats, requested_records: int, source_total_records: int, config: Mapping[str, Any], ) -> dict[str, bool]: all_audited = stats.total_records == requested_records full_corpus_audited = all_audited and requested_records == source_total_records all_reproduced = ( stats.reproducibility_passed == requested_records and stats.exact_hash_match == requested_records ) all_structural = stats.structural_integrity_passed == requested_records zero_semantic_blockers = not stats.semantic_blockers zero_not_training_ready = stats.training_ready == requested_records redistribution_cleared = config.get("redistribution") != "pending-owner-policy" internal_promotion = all( ( full_corpus_audited, all_reproduced, all_structural, zero_semantic_blockers, zero_not_training_ready, stats.validator_exceptions == 0, ) ) return { "all_records_audited": all_audited, "full_corpus_audited": full_corpus_audited, "exact_requested_record_count": all_audited, "all_records_received_verdict": all_audited, "all_records_exactly_reproduced": all_reproduced, "all_records_structural_integrity_passed": all_structural, "zero_semantic_blockers": zero_semantic_blockers, "zero_training_ready_false": zero_not_training_ready, "no_quality_validator_exceptions": stats.validator_exceptions == 0, "all_records_integrity_passed": stats.integrity_passed == requested_records, "all_records_strict_fitness_passed": stats.strict_fitness_passed == requested_records, "redistribution_cleared_for_public_release": redistribution_cleared, "internal_training_promotion_passed": internal_promotion, "public_release_promotion_passed": internal_promotion and redistribution_cleared, } def _manifest_payload( *, results: Sequence[QualityShardResult], stats: QualityStats, pins: Mapping[str, Any], warnings: Sequence[str], requested_records: int, source_total_records: int, ) -> dict[str, Any]: ordered_results = sorted(results, key=lambda result: result.start_index) shards = [ { "canonical_path": result.canonical_path, "canonical_sha256": result.canonical_sha256, "canonical_manifest_records": result.canonical_manifest_records, "records": result.records_processed, "start_index": result.start_index, "verdict_path": str(result.verdict.path), "verdict_sha256": result.verdict.sha256, "verdict_compressed_bytes": result.verdict.compressed_bytes, "verdict_uncompressed_bytes": result.verdict.uncompressed_bytes, } for result in ordered_results ] return { "manifest_version": QUALITY_MANIFEST_VERSION, "quality_schema_version": QUALITY_SCHEMA_VERSION, "metadata": { "requested_records": requested_records, "source_total_records": source_total_records, "partial_run": requested_records != source_total_records, "pins": dict(pins), "warnings": list(warnings), }, "shards": shards, "statistics": stats.to_dict(), "totals": { "records": sum(result.records_processed for result in results), "shards": len(results), "verdict_compressed_bytes": sum( result.verdict.compressed_bytes for result in results ), "verdict_uncompressed_bytes": sum( result.verdict.uncompressed_bytes for result in results ), }, } def _append_issue(issues: list[dict[str, Any]], **issue: Any) -> None: if len(issues) < _MAX_POSTWRITE_ISSUES: issues.append(issue) def _verdict_shape_valid(verdict: Mapping[str, Any]) -> bool: return ( isinstance(verdict.get("record_id"), str) and isinstance(verdict.get("record_index"), int) and verdict.get("quality_schema_version") == QUALITY_SCHEMA_VERSION and verdict.get("disposition") in {"KEEP", "REVIEW", "REJECT", "QUARANTINE"} and isinstance(verdict.get("checks"), Mapping) and isinstance(verdict.get("hard_failures"), list) and isinstance(verdict.get("structural_failures"), list) and isinstance(verdict.get("reproducibility_failures"), list) and isinstance(verdict.get("semantic_blockers"), list) and isinstance(verdict.get("review_flags"), list) and isinstance(verdict.get("canonical_sha256"), str) and isinstance(verdict.get("source_shard"), str) and isinstance(verdict.get("source_line"), int) and isinstance(verdict.get("expected_record_index"), int) and isinstance(verdict.get("training_ready"), bool) ) def _verify_postwrite( *, quality_manifest_path: Path, complete_path: Path, report_path: Path, output_root: Path, project_root: Path, generation_config_path: Path, config_snapshot_path: Path, canonical_manifest_path: Path, ) -> dict[str, Any]: """Independently re-read every sidecar and its paired canonical records.""" quality_manifest = _load_json_object(quality_manifest_path) issues: list[dict[str, Any]] = [] gates = { "quality_manifest_shape_valid": True, "generation_config_pin_matches": True, "config_snapshot_pin_matches": True, "canonical_manifest_pin_matches": True, "source_bundle_pin_matches": True, "canonical_shard_checksums_match": True, "verdict_shard_checksums_match": True, "record_counts_match": True, "record_ids_align": True, "record_indices_contiguous": True, "canonical_record_hashes_align": True, "verdict_shapes_valid": True, "statistics_recomputed_exactly": True, } if quality_manifest.get("manifest_version") != QUALITY_MANIFEST_VERSION: gates["quality_manifest_shape_valid"] = False _append_issue(issues, code="QUALITY_MANIFEST_VERSION_INVALID") metadata = quality_manifest.get("metadata", {}) pins = metadata.get("pins", {}) if isinstance(metadata, Mapping) else {} try: current_bundle = _source_bundle( project_root, generation_config_path, config_snapshot_path ) if sha256_file(generation_config_path) != pins["generation_config"]["raw_sha256"]: gates["generation_config_pin_matches"] = False _append_issue(issues, code="GENERATION_CONFIG_PIN_MISMATCH") if sha256_file(config_snapshot_path) != pins["config_snapshot"]["raw_sha256"]: gates["config_snapshot_pin_matches"] = False _append_issue(issues, code="CONFIG_SNAPSHOT_PIN_MISMATCH") if sha256_file(canonical_manifest_path) != pins["canonical_manifest"]["raw_sha256"]: gates["canonical_manifest_pin_matches"] = False _append_issue(issues, code="CANONICAL_MANIFEST_PIN_MISMATCH") if ( current_bundle["sha256"] != pins["source_bundle"]["sha256"] or current_bundle["files"] != pins["source_bundle"]["files"] ): gates["source_bundle_pin_matches"] = False _append_issue(issues, code="SOURCE_BUNDLE_PIN_MISMATCH") except (KeyError, TypeError, OSError, ValueError) as exc: gates["quality_manifest_shape_valid"] = False _append_issue( issues, code="PIN_METADATA_INVALID", detail=f"{type(exc).__name__}: {exc}"[:500], ) recomputed = QualityStats() shard_entries = quality_manifest.get("shards") if not isinstance(shard_entries, list) or not shard_entries: gates["quality_manifest_shape_valid"] = False shard_entries = [] _append_issue(issues, code="QUALITY_MANIFEST_SHARDS_INVALID") for shard_index, entry in enumerate(shard_entries): if not isinstance(entry, Mapping): gates["quality_manifest_shape_valid"] = False _append_issue(issues, code="QUALITY_SHARD_ENTRY_INVALID", shard=shard_index) continue canonical_path = Path(str(entry.get("canonical_path", ""))) verdict_path = Path(str(entry.get("verdict_path", ""))) expected_records = int(entry.get("records", -1)) canonical_manifest_records = int(entry.get("canonical_manifest_records", -1)) start_index = int(entry.get("start_index", -1)) try: actual = sha256_file(canonical_path) if actual != entry.get("canonical_sha256"): gates["canonical_shard_checksums_match"] = False _append_issue( issues, code="CANONICAL_SHARD_CHECKSUM_MISMATCH", shard=shard_index, path=str(canonical_path), ) except OSError as exc: gates["canonical_shard_checksums_match"] = False _append_issue( issues, code="CANONICAL_SHARD_READ_FAILED", shard=shard_index, detail=str(exc)[:500], ) continue try: actual = sha256_file(verdict_path) if actual != entry.get("verdict_sha256"): gates["verdict_shard_checksums_match"] = False _append_issue( issues, code="VERDICT_SHARD_CHECKSUM_MISMATCH", shard=shard_index, path=str(verdict_path), ) except OSError as exc: gates["verdict_shard_checksums_match"] = False _append_issue( issues, code="VERDICT_SHARD_READ_FAILED", shard=shard_index, detail=str(exc)[:500], ) continue canonical_iter = iter_jsonl_gz(canonical_path) verdict_iter = iter_jsonl_gz(verdict_path) paired = 0 for ordinal in range(max(expected_records, 0)): try: canonical_record = next(canonical_iter) except StopIteration: gates["record_counts_match"] = False _append_issue( issues, code="CANONICAL_SHORT_DURING_POSTWRITE", shard=shard_index, ordinal=ordinal, ) break try: verdict = next(verdict_iter) except StopIteration: gates["record_counts_match"] = False _append_issue( issues, code="VERDICT_SHORT_DURING_POSTWRITE", shard=shard_index, ordinal=ordinal, ) break paired += 1 if canonical_record.get("record_id") != verdict.get("record_id"): gates["record_ids_align"] = False _append_issue( issues, code="RECORD_ID_ALIGNMENT_MISMATCH", shard=shard_index, ordinal=ordinal, canonical_record_id=canonical_record.get("record_id"), verdict_record_id=verdict.get("record_id"), ) expected_index = start_index + ordinal if ( verdict.get("record_index") != expected_index or verdict.get("expected_record_index") != expected_index or verdict.get("source_line") != ordinal + 1 or verdict.get("source_shard") != canonical_path.name ): gates["record_indices_contiguous"] = False _append_issue( issues, code="RECORD_INDEX_OR_SOURCE_POSITION_MISMATCH", shard=shard_index, ordinal=ordinal, expected_record_index=expected_index, verdict_record_index=verdict.get("record_index"), verdict_expected_record_index=verdict.get("expected_record_index"), source_line=verdict.get("source_line"), source_shard=verdict.get("source_shard"), ) if canonical_sha256(canonical_record) != verdict.get("canonical_sha256"): gates["canonical_record_hashes_align"] = False _append_issue( issues, code="CANONICAL_RECORD_HASH_MISMATCH", shard=shard_index, ordinal=ordinal, record_id=canonical_record.get("record_id"), ) if not _verdict_shape_valid(verdict): gates["verdict_shapes_valid"] = False _append_issue( issues, code="VERDICT_SHAPE_INVALID", shard=shard_index, ordinal=ordinal, record_id=verdict.get("record_id"), ) recomputed.ingest(verdict, canonical_record) try: extra_verdict = next(verdict_iter) except StopIteration: extra_verdict = None if extra_verdict is not None: gates["record_counts_match"] = False _append_issue( issues, code="VERDICT_HAS_EXTRA_RECORDS", shard=shard_index, first_extra_record_id=extra_verdict.get("record_id"), ) if expected_records == canonical_manifest_records: try: extra_canonical = next(canonical_iter) except StopIteration: extra_canonical = None if extra_canonical is not None: gates["record_counts_match"] = False _append_issue( issues, code="CANONICAL_HAS_EXTRA_RECORDS", shard=shard_index, first_extra_record_id=extra_canonical.get("record_id"), ) if paired != expected_records: gates["record_counts_match"] = False expected_stats = quality_manifest.get("statistics") actual_stats = recomputed.to_dict() if actual_stats != expected_stats: gates["statistics_recomputed_exactly"] = False _append_issue(issues, code="QUALITY_STATISTICS_MISMATCH") all_gates_passed = all(gates.values()) postwrite = { "verification_version": QUALITY_POSTWRITE_VERSION, "quality_manifest": str(quality_manifest_path.resolve()), "quality_manifest_sha256": sha256_file(quality_manifest_path), "complete_marker": str(complete_path.resolve()), "complete_marker_sha256": sha256_file(complete_path), "source_report": str(report_path.resolve()), "source_report_sha256": sha256_file(report_path), "records_reread": recomputed.total_records, "shards_reread": len(shard_entries), "gates": gates, "all_artifact_verification_gates_passed": all_gates_passed, "issues": issues, "recomputed_statistics": actual_stats, } postwrite_path = output_root / "reports" / "postwrite-verification.json" write_json_atomic(postwrite_path, postwrite) if not all_gates_passed: failed = { "marker_version": QUALITY_MARKER_VERSION, "quality_artifacts_verified": False, "postwrite_verification": str(postwrite_path.resolve()), "postwrite_verification_sha256": sha256_file(postwrite_path), "failed_gates": [name for name, passed in gates.items() if not passed], } write_json_atomic(output_root / "_QUALITY_FAILED.json", failed) raise RuntimeError(f"quality postwrite verification failed; inspect {postwrite_path}") quality_gates = quality_manifest.get("metadata", {}).get("quality_gates", {}) verified = { "marker_version": QUALITY_MARKER_VERSION, "quality_artifacts_verified": True, "records": recomputed.total_records, "shards": len(shard_entries), "quality_manifest": str(quality_manifest_path.resolve()), "quality_manifest_sha256": sha256_file(quality_manifest_path), "quality_report": str(report_path.resolve()), "quality_report_sha256": sha256_file(report_path), "complete_marker": str(complete_path.resolve()), "complete_marker_sha256": sha256_file(complete_path), "postwrite_verification": str(postwrite_path.resolve()), "postwrite_verification_sha256": sha256_file(postwrite_path), "artifact_verification_gates": gates, "quality_gates": quality_gates, "disposition": actual_stats["disposition"], } verified_path = output_root / "_QUALITY_VERIFIED.json" write_json_atomic(verified_path, verified) return verified def run_quality_validation( *, dataset_root: str | Path, generation_config_path: str | Path, output_root: str | Path, manifest_path: str | Path | None = None, project_root: str | Path = DEFAULT_PROJECT_ROOT, workers: int = 1, max_records: int | None = None, compresslevel: int | None = None, ) -> dict[str, Any]: dataset_root = Path(dataset_root).resolve() project_root = Path(project_root).resolve() output_root = Path(output_root).resolve() generation_config_path = Path(generation_config_path).resolve() canonical_manifest_path = Path(manifest_path or dataset_root / "manifest.json").resolve() config_snapshot_path = (dataset_root / "config.snapshot.json").resolve() if output_root == dataset_root: raise ValueError("quality output must be a child path, not the dataset root itself") if generation_config_path == config_snapshot_path: raise ValueError( "--config must name the immutable original generation config, not " "DATASET_ROOT/config.snapshot.json" ) if output_root.exists() and any(output_root.iterdir()): raise FileExistsError(f"quality output directory is not empty: {output_root}") for required in ( generation_config_path, canonical_manifest_path, config_snapshot_path, ): if not required.is_file(): raise FileNotFoundError(required) config = _load_json_object(generation_config_path) snapshot = _load_json_object(config_snapshot_path) canonical_manifest = _load_json_object(canonical_manifest_path) GenerationPlan(config) if snapshot != config: raise ValueError( "config.snapshot.json is not semantically equal to the explicit generation config" ) manifest_semantic_config_hash = canonical_manifest.get("metadata", {}).get("config_sha256") if manifest_semantic_config_hash != _semantic_sha256(config): raise ValueError( "canonical manifest config_sha256 does not match the explicit generation config" ) raw_shards = canonical_manifest.get("shards", []) source_total_records = sum( int(entry.get("records", 0)) for entry in raw_shards if isinstance(entry, Mapping) ) declared_total = canonical_manifest.get("totals", {}).get("records") if int(declared_total or -1) != source_total_records or source_total_records <= 0: raise ValueError("canonical manifest total does not equal its shard record counts") requested_records = source_total_records if max_records is None else int(max_records) if not 1 <= requested_records <= source_total_records: raise ValueError(f"--max-records must be between 1 and {source_total_records}") if int(workers) < 1: raise ValueError("--workers must be at least 1") if compresslevel is None: compresslevel = int(config.get("gzip_compresslevel", 6)) if not 0 <= int(compresslevel) <= 9: raise ValueError("--compresslevel must be between 0 and 9") pins, warnings = _pin_metadata( project_root=project_root, generation_config_path=generation_config_path, config_snapshot_path=config_snapshot_path, canonical_manifest_path=canonical_manifest_path, config=config, snapshot=snapshot, ) output_root.mkdir(parents=True, exist_ok=True) tasks = _build_tasks( canonical_manifest, canonical_manifest_path, output_root, config, requested_records, int(compresslevel), ) results = _run_tasks(tasks, int(workers)) if not _pins_unchanged( pins, project_root=project_root, generation_config_path=generation_config_path, config_snapshot_path=config_snapshot_path, canonical_manifest_path=canonical_manifest_path, ): raise RuntimeError("configuration, manifest, or source bundle changed during validation") stats, finding_examples = _aggregate_results(results) quality_gates = _quality_gates( stats, requested_records, source_total_records, config, ) config_contract = { "explicit_generation_config_used": True, "snapshot_used_for_exact_regeneration": False, "snapshot_semantically_equal": snapshot == config, "snapshot_mapping_key_order_equal": _mapping_key_order_equal(config, snapshot), "snapshot_generation_plan_equal": ( _generation_plan_sha256(config) == _generation_plan_sha256(snapshot) ), "canonical_manifest_semantic_config_hash_matches": ( manifest_semantic_config_hash == _semantic_sha256(config) ), } manifest = _manifest_payload( results=results, stats=stats, pins=pins, warnings=warnings, requested_records=requested_records, source_total_records=source_total_records, ) manifest["metadata"]["quality_gates"] = quality_gates manifest["metadata"]["config_contract"] = config_contract quality_manifest_path = output_root / "manifest.json" write_json_atomic(quality_manifest_path, manifest) report = { "report_version": QUALITY_REPORT_VERSION, "quality_schema_version": QUALITY_SCHEMA_VERSION, "dataset_root": str(dataset_root), "output_root": str(output_root), "requested_records": requested_records, "source_total_records": source_total_records, "partial_run": requested_records != source_total_records, "all_records_audited": quality_gates["all_records_audited"], "training_promotion_passed": quality_gates[ "internal_training_promotion_passed" ], "public_release_promotion_passed": quality_gates[ "public_release_promotion_passed" ], "statistics": stats.to_dict(), "quality_gates": quality_gates, "config_contract": config_contract, "pins": pins, "warnings": warnings, "finding_examples": finding_examples, "interpretation": { "KEEP": "all integrity and strict task-family fitness checks passed", "REVIEW": "integrity passed, but at least one strict fitness flag requires review", "REJECT": "structural failures or semantic blockers make the record unusable", "QUARANTINE": "exact regeneration failed without a structural or semantic rejection", "artifact_verification_is_separate_from_quality_outcome": True, }, } report_path = output_root / "report.json" write_json_atomic(report_path, report) complete = { "marker_version": QUALITY_MARKER_VERSION, "quality_sidecars_complete": True, "records": stats.total_records, "shards": len(results), "quality_manifest": str(quality_manifest_path), "quality_manifest_sha256": sha256_file(quality_manifest_path), "quality_report": str(report_path), "quality_report_sha256": sha256_file(report_path), "quality_gates": quality_gates, "disposition": stats.to_dict()["disposition"], } complete_path = output_root / "_QUALITY_COMPLETE.json" write_json_atomic(complete_path, complete) verified = _verify_postwrite( quality_manifest_path=quality_manifest_path, complete_path=complete_path, report_path=report_path, output_root=output_root, project_root=project_root, generation_config_path=generation_config_path, config_snapshot_path=config_snapshot_path, canonical_manifest_path=canonical_manifest_path, ) return verified def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Materialise and independently verify one quality verdict per BGD record" ) parser.add_argument("--dataset-root", required=True) parser.add_argument( "--config", required=True, help="original order-preserving generation config; never use config.snapshot.json", ) parser.add_argument("--output", required=True) parser.add_argument("--manifest", help="canonical manifest; defaults to DATASET_ROOT/manifest.json") parser.add_argument("--project-root", default=str(DEFAULT_PROJECT_ROOT)) parser.add_argument("--workers", type=int, default=1) parser.add_argument("--max-records", type=int) parser.add_argument("--compresslevel", type=int) return parser def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) try: verified = run_quality_validation( dataset_root=args.dataset_root, generation_config_path=args.config, output_root=args.output, manifest_path=args.manifest, project_root=args.project_root, workers=args.workers, max_records=args.max_records, compresslevel=args.compresslevel, ) except Exception as exc: print(f"ERROR: {exc}", file=sys.stderr) return 1 print(json.dumps(verified, ensure_ascii=False, indent=2, sort_keys=True), flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())