from __future__ import annotations import hashlib import json import tempfile import unittest from pathlib import Path from barbet_bgd.audit import StatsAccumulator, write_manifest, write_report from barbet_bgd.io import ( iter_gzip_jsonl, iter_jsonl_gz, sha256_file, write_gzip_jsonl_atomic, write_jsonl_gz_atomic, ) def _record( record_id: str, *, split: str = "train", source_text: str = "模型將於九月十五日上線。", evidence: str = "src:w03", context_bucket: str = "0.5K-4K", intentional_simplified: bool = False, ) -> dict: return { "record_id": record_id, "schema_version": "bgd.canonical.v1", "primitive": "VERIFY", "mixture_category": "VERIFICATION_QE_ERROR_LOCALIZATION", "task_family": "ASR_QUALITY", "domain": "meeting", "language": ["zh-TW", "en"], "locale": "zh-TW", "split": split, "source_group": "synthetic-test", "task_spec": {"instruction": "判斷候選是否忠實,並引用證據。"}, "inputs": [ { "id": "src", "type": "reference_text", "units": [ {"id": "src:w01", "text": "模型"}, {"id": "src:w03", "text": source_text}, ], }, { "id": "hyp", "type": "asr_hypothesis", "units": [{"id": "hyp:w03", "text": "模型將於九月五日上線。"}], }, ], "target": { "decision": "FAIL", "confidence_target": 0.98, "errors": [ { "type": "VALUE_CORRUPTION", "source_evidence": [evidence], "target_evidence": ["hyp:w03"], } ], "action": {"tool": "EDIT", "arguments": {"target": "hyp:w03"}}, }, "component_targets": {}, "presentation": { "serializer": "JSON", "serializer_version": "1", }, "provenance": {"source_hash": "0" * 64}, "quality": { "context_length_bucket": context_bucket, "intentional_negative_simplified_hits": ( [{"unit_id": "src:w03", "hits": ["这"]}] if intentional_simplified else [] ) }, } class AtomicGzipJsonlTests(unittest.TestCase): def test_round_trip_digest_and_deterministic_bytes(self) -> None: rows = [_record("bgd-001"), _record("bgd-002", split="validation")] with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) first = write_gzip_jsonl_atomic(root / "first.jsonl.gz", rows) second = write_gzip_jsonl_atomic(root / "second.jsonl.gz", rows) self.assertEqual(list(iter_gzip_jsonl(first.path)), rows) self.assertEqual(first.records, 2) self.assertEqual(first.record_count, 2) self.assertEqual(first.sha256, sha256_file(first.path)) self.assertEqual(first.sha256, second.sha256) self.assertEqual( first.sha256, hashlib.sha256(first.path.read_bytes()).hexdigest(), ) self.assertFalse((root / "first.jsonl.gz.incomplete").exists()) alias = write_jsonl_gz_atomic(root / "alias.jsonl.gz", rows) self.assertEqual(list(iter_jsonl_gz(alias.path)), rows) def test_failed_write_preserves_published_file_and_cleans_incomplete(self) -> None: with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "shard.jsonl.gz" path.write_bytes(b"published") def bad_rows(): yield _record("bgd-001") yield {"not_json": object()} with self.assertRaises(TypeError): write_gzip_jsonl_atomic(path, bad_rows()) self.assertEqual(path.read_bytes(), b"published") self.assertFalse(Path(f"{path}.incomplete").exists()) class StatsAccumulatorTests(unittest.TestCase): def test_ingest_counts_distributions_and_integrity_findings(self) -> None: stats = StatsAccumulator() stats.ingest(_record("same-id")) stats.ingest( _record( "same-id", split="test", source_text="这个模型将上线。", evidence="src:missing", context_bucket="4K-16K", ) ) result = stats.to_dict() self.assertEqual(result["total_records"], 2) self.assertEqual(result["split"], {"test": 1, "train": 1}) self.assertEqual(result["primitive"], {"VERIFY": 2}) self.assertEqual( result["mixture_category"], {"VERIFICATION_QE_ERROR_LOCALIZATION": 2} ) self.assertEqual(result["task_family"], {"ASR_QUALITY": 2}) self.assertEqual(result["domain"], {"meeting": 2}) self.assertEqual(result["serializer"], {"JSON": 2}) self.assertEqual(result["decision"], {"FAIL": 2}) self.assertEqual(result["error_type"], {"VALUE_CORRUPTION": 2}) self.assertEqual(result["action"], {"EDIT": 2}) self.assertEqual(result["context_bucket"], {"0.5K-4K": 1, "4K-16K": 1}) self.assertEqual(result["primary_zh_tw_records"], 2) self.assertEqual(result["primary_zh_tw_ratio"], 1.0) self.assertEqual(result["simplified_only_hit_records"], 1) self.assertEqual(result["duplicate_record_ids"], 1) self.assertEqual(result["duplicate_record_id_occurrences"], 1) self.assertEqual(result["evidence_reference_missing"], 1) self.assertEqual(result["evidence_reference_missing_records"], 1) def test_merge_detects_cross_shard_duplicates_and_annotations(self) -> None: left = StatsAccumulator().ingest(_record("shared")) right = StatsAccumulator().ingest( _record( "shared", source_text="这个模型将上线。", intentional_simplified=True, ) ) merged = left.merge(right).to_dict() self.assertEqual(merged["total_records"], 2) self.assertEqual(merged["duplicate_record_ids"], 1) self.assertEqual(merged["duplicate_record_id_occurrences"], 1) self.assertEqual(merged["simplified_only_hit_records"], 1) self.assertEqual(merged["intentional_negative_simplified_hit_records"], 1) self.assertEqual(merged["unannotated_simplified_only_hit_records"], 0) def test_manifest_and_report_are_atomic_json(self) -> None: rows = [_record("bgd-001")] with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) shard = write_gzip_jsonl_atomic(root / "shard.jsonl.gz", rows) stats = StatsAccumulator().ingest(rows[0]) manifest_path = write_manifest( root / "manifest.json", [shard], stats=stats, metadata={"dataset_name": "unit-test"}, ) report_path = write_report(root / "report.json", stats) manifest = json.loads(manifest_path.read_text(encoding="utf-8")) report = json.loads(report_path.read_text(encoding="utf-8")) self.assertEqual(manifest["totals"]["records"], 1) self.assertEqual(manifest["shards"][0]["sha256"], shard.sha256) self.assertEqual(manifest["metadata"]["dataset_name"], "unit-test") self.assertTrue(report["checks"]["all_records_primary_zh_tw"]) self.assertTrue(report["checks"]["record_ids_unique"]) self.assertFalse(Path(f"{manifest_path}.incomplete").exists()) self.assertFalse(Path(f"{report_path}.incomplete").exists()) if __name__ == "__main__": unittest.main()