File size: 7,918 Bytes
0bf2389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
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
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()