File size: 10,117 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
from __future__ import annotations

from copy import deepcopy
import json
from pathlib import Path
import unittest

from barbet_bgd.validation import (
    ACTION_TOOLS,
    PRIMITIVES,
    RecordValidationError,
    assert_valid_record,
    find_disallowed_terms,
    validate_record,
)


def minimal_valid_record() -> dict:
    return {
        "record_id": "bgd_verify_000001",
        "schema_version": "1.0.0",
        "primitive": "VERIFY",
        "mixture_category": "VERIFICATION_QE_ERROR_LOCALIZATION",
        "task_family": "ASR_QUALITY",
        "domain": "meeting",
        "language": ["zh-TW", "en"],
        "locale": "zh-TW",
        "split": "train",
        "source_group": "meeting_session_001",
        "task_spec": {
            "instruction": "比較參考文字與辨識結果,標記有證據支持的錯誤。",
            "allowed_labels": ["PASS", "FAIL", "UNCERTAIN"],
            "allowed_error_types": ["VALUE_CORRUPTION"],
            "allowed_actions": ["EDIT", "ABSTAIN"],
            "required_evidence": True,
            "abstention_allowed": True,
        },
        "inputs": [
            {
                "id": "src",
                "type": "reference_text",
                "role": "reference",
                "units": [
                    {"id": "src:w01", "text": "模型將於九月十五日上線。"},
                ],
            },
            {
                "id": "hyp",
                "type": "asr_hypothesis",
                "units": [
                    {"id": "hyp:w01", "text": "模型將於九月五日上線。"},
                ],
            },
        ],
        "target": {
            "decision": "FAIL",
            "errors": [
                {
                    "type": "VALUE_CORRUPTION",
                    "severity": "major",
                    "source_evidence": ["src:w01"],
                    "target_evidence": ["hyp:w01"],
                }
            ],
            "post_edit": "模型將於九月十五日上線。",
            "action": {
                "tool": "EDIT",
                "arguments": {
                    "target": "hyp:w01",
                    "replacement": "模型將於九月十五日上線。",
                },
            },
            "confidence_target": 0.98,
        },
        "component_targets": {
            "source_token_span": [0, 1],
            "target_token_span": [0, 1],
            "audio_interval": None,
            "image_region": None,
        },
        "presentation": {
            "serializer": "json",
            "serializer_version": "1",
            "context_bucket": "0.5k-4k",
        },
        "provenance": {
            "source_dataset": "unit_test",
            "license": "CC0-1.0",
            "source_hash": "sha256:test",
            "transformation": "date_substitution_v1",
            "teacher_model": None,
            "validator_version": "1.0.0",
            "human_review": True,
        },
        "quality": {
            "intentional_negative_simplified_hits": [],
            "deterministic_verified": True,
        },
    }


class ValidationTests(unittest.TestCase):
    def test_minimal_record_is_valid(self) -> None:
        record = minimal_valid_record()
        self.assertEqual(validate_record(record), [])
        self.assertIsNone(assert_valid_record(record))

    def test_all_ten_primitives_are_accepted(self) -> None:
        self.assertEqual(
            PRIMITIVES,
            {
                "COPY",
                "EDIT",
                "CLASSIFY",
                "EXTRACT",
                "LOCATE",
                "ALIGN",
                "MATCH",
                "RANK",
                "VERIFY",
                "ROUTE",
            },
        )
        for primitive in PRIMITIVES:
            with self.subTest(primitive=primitive):
                record = minimal_valid_record()
                record["primitive"] = primitive
                self.assertEqual(validate_record(record), [])

    def test_required_root_field_and_invalid_primitive_are_reported(self) -> None:
        record = minimal_valid_record()
        del record["source_group"]
        record["primitive"] = "SUMMARIZE"
        errors = validate_record(record)
        self.assertIn("missing required field: source_group", errors)
        self.assertTrue(any("primitive must be one of" in error for error in errors))

    def test_language_and_locale_must_be_taiwan_first(self) -> None:
        record = minimal_valid_record()
        record["language"] = ["en", "zh-TW"]
        record["locale"] = "zh-Hant"
        errors = validate_record(record)
        self.assertIn("language[0] must be zh-TW", errors)
        self.assertIn("locale must be zh-TW", errors)

    def test_duplicate_unit_id_is_rejected(self) -> None:
        record = minimal_valid_record()
        record["inputs"][1]["units"][0]["id"] = "src:w01"
        errors = validate_record(record)
        self.assertIn("duplicate input unit ID: src:w01", errors)

    def test_all_symbolic_reference_families_must_resolve(self) -> None:
        cases = {
            "evidence": {"evidence": ["missing:evidence"]},
            "locations": {"locations": ["missing:location"]},
            "copy": {"copy_ids": ["missing:copy"]},
            "alignment": {
                "alignments": [{"source": "src:w01", "target": "missing:alignment"}]
            },
        }
        for name, extra in cases.items():
            with self.subTest(name=name):
                record = minimal_valid_record()
                record["target"].update(extra)
                errors = validate_record(record)
                self.assertTrue(
                    any("references unknown input ID" in error for error in errors),
                    errors,
                )

    def test_required_evidence_and_reasonable_abstention(self) -> None:
        record = minimal_valid_record()
        record["target"]["errors"] = []
        self.assertIn(
            "task_spec.required_evidence is true but target has no evidence",
            validate_record(record),
        )

        abstain = minimal_valid_record()
        abstain["task_spec"]["allowed_error_types"] = ["INSUFFICIENT_EVIDENCE"]
        abstain["target"] = {
            "decision": "ABSTAIN",
            "errors": [{"type": "INSUFFICIENT_EVIDENCE"}],
            "action": {"tool": "ABSTAIN", "arguments": {}},
            "confidence_target": 0.25,
        }
        self.assertEqual(validate_record(abstain), [])

        abstain["task_spec"]["abstention_allowed"] = False
        self.assertIn(
            "target abstains but task_spec.abstention_allowed is false",
            validate_record(abstain),
        )

    def test_positive_supervision_rejects_simplified_and_mainland_terms(self) -> None:
        record = minimal_valid_record()
        record["task_spec"]["instruction"] = "请检查这个软件的输出。"
        errors = validate_record(record)
        self.assertTrue(any("task_spec.instruction" in error for error in errors), errors)

        record = minimal_valid_record()
        record["target"]["post_edit"] = "請檢查這個軟件的輸出。"
        errors = validate_record(record)
        self.assertTrue(any("target.post_edit" in error for error in errors), errors)

    def test_intentional_negative_may_contain_simplified_text_when_audited(self) -> None:
        record = minimal_valid_record()
        bad_text = "这个软件会在九月上线。"
        record["inputs"][1]["units"][0]["text"] = bad_text
        record["task_spec"]["allowed_error_types"] = ["CONSTRAINT_VIOLATION"]
        record["target"]["errors"] = [
            {
                "type": "CONSTRAINT_VIOLATION",
                "severity": "major",
                "source_evidence": ["src:w01"],
                "target_evidence": ["hyp:w01"],
            }
        ]
        record["quality"]["intentional_negative_simplified_hits"] = [
            {
                "unit_id": "hyp:w01",
                "hits": find_disallowed_terms(bad_text),
            }
        ]
        self.assertEqual(validate_record(record), [])

    def test_intentional_negative_requires_error_evidence_and_quality_log(self) -> None:
        record = minimal_valid_record()
        record["inputs"][1]["units"][0]["text"] = "这个软件会在九月上线。"
        record["target"]["errors"] = []
        errors = validate_record(record)
        self.assertTrue(any("not captured by target.errors evidence" in error for error in errors))
        self.assertTrue(
            any("intentional_negative_simplified_hits is missing ID" in error for error in errors)
        )

    def test_tool_and_confidence_are_closed_and_bounded(self) -> None:
        self.assertNotIn("RUN_ARBITRARY_PYTHON", ACTION_TOOLS)
        record = minimal_valid_record()
        record["target"]["action"]["tool"] = "RUN_ARBITRARY_PYTHON"
        record["target"]["confidence_target"] = 1.01
        errors = validate_record(record)
        self.assertIn("target.action.tool must be a closed-world action tool", errors)
        self.assertIn(
            "target.confidence_target must be a finite number in [0, 1]", errors
        )

    def test_assert_valid_record_exposes_all_errors(self) -> None:
        record = minimal_valid_record()
        record["locale"] = "zh-CN"
        record["target"]["confidence_target"] = float("nan")
        with self.assertRaises(RecordValidationError) as raised:
            assert_valid_record(record)
        self.assertGreaterEqual(len(raised.exception.errors), 2)

    def test_schema_is_json_and_matches_closed_world_constants(self) -> None:
        schema_path = Path(__file__).parents[1] / "schema" / "canonical_record.schema.json"
        schema = json.loads(schema_path.read_text(encoding="utf-8"))
        self.assertEqual(set(schema["required"]), set(minimal_valid_record()))
        self.assertEqual(set(schema["$defs"]["primitive"]["enum"]), PRIMITIVES)
        self.assertEqual(set(schema["$defs"]["action_tool"]["enum"]), ACTION_TOOLS)


if __name__ == "__main__":
    unittest.main()