File size: 24,052 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
from __future__ import annotations

import json
import pickle
import unittest
from copy import deepcopy
from pathlib import Path
from typing import Any, Callable

from barbet_bgd.generation_v2 import GenerationPlanV2, generate_record_v2
from barbet_bgd.quality_v2 import (
    EXPECTED_TASK_FAMILIES_V2,
    PromotionAccumulator,
    expected_source_hash_v2,
    validate_record_quality_v2,
)


ROOT = Path(__file__).resolve().parents[1]


def _rehash(record: dict[str, Any]) -> None:
    record["provenance"]["source_hash"] = expected_source_hash_v2(record)


def _replace_strings(value: Any, replacements: dict[str, str]) -> Any:
    if isinstance(value, str):
        return replacements.get(value, value)
    if isinstance(value, list):
        return [_replace_strings(item, replacements) for item in value]
    if isinstance(value, dict):
        return {
            replacements.get(key, key): _replace_strings(item, replacements)
            for key, item in value.items()
        }
    return value


class QualityV2Tests(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls.config = json.loads(
            (ROOT / "configs/selected_sft_1m_v2.json").read_text(encoding="utf-8")
        )
        cls.plan = GenerationPlanV2(cls.config)
        cls.records = [generate_record_v2(cls.config, cls.plan, index) for index in range(1_200)]

    @classmethod
    def one(cls, predicate: Callable[[dict[str, Any]], bool]) -> dict[str, Any]:
        return deepcopy(next(record for record in cls.records if predicate(record)))

    def assert_rejected(self, record: dict[str, Any], failure: str) -> dict[str, Any]:
        verdict = validate_record_quality_v2(record)
        self.assertEqual(verdict["disposition"], "REJECT")
        self.assertFalse(verdict["training_ready"])
        self.assertIn(failure, verdict["hard_failures"])
        return verdict

    def test_positive_one_record_from_every_family(self):
        by_family = {}
        for record in self.records:
            by_family.setdefault(record["task_family"], record)
        self.assertEqual(set(by_family), set(EXPECTED_TASK_FAMILIES_V2))
        for family, record in by_family.items():
            with self.subTest(family=family):
                verdict = validate_record_quality_v2(record)
                self.assertEqual(verdict["hard_failures"], [])
                self.assertEqual(verdict["disposition"], "KEEP")

    def test_visible_query_and_schema_are_hard_gates(self):
        record = self.one(lambda row: row["primitive"] == "EXTRACT")
        del record["task_spec"]["query"]
        del record["task_spec"]["requested_schema"]
        _rehash(record)
        verdict = self.assert_rejected(record, "MODEL_VISIBLE_QUERY_FIELD_MISSING_OR_INVALID")
        self.assertIn("MODEL_VISIBLE_REQUESTED_SCHEMA_MISSING", verdict["hard_failures"])

    def test_family_input_signature_mutation_is_rejected(self):
        record = self.one(lambda row: row["task_family"] == "ASR_NBEST_RANKING")
        record["inputs"][0]["type"] = "generic_retrieval_query"
        _rehash(record)
        self.assert_rejected(record, "TASK_FAMILY_INPUT_SIGNATURE_MISMATCH")

    def test_locate_found_wrong_valid_unit_is_rejected(self):
        record = self.one(
            lambda row: row["primitive"] == "LOCATE"
            and row["target"]["decision"] == "FOUND"
            and not row["task_family"].startswith("LONG_CONTEXT")
        )
        correct = record["target"]["locations"][0]
        wrong = next(
            unit["id"]
            for item in record["inputs"]
            for unit in item["units"]
            if unit["id"] != correct
        )
        record["target"]["locations"] = [wrong]
        record["target"]["evidence"] = [wrong]
        record["target"]["action"]["arguments"]["unit_ids"] = [wrong]
        self.assert_rejected(
            record, "LOCATE_GOLD_NOT_REPRODUCIBLE_FROM_VISIBLE_ATTRIBUTES"
        )

    def test_locate_contradictory_abstention_is_rejected(self):
        record = self.one(
            lambda row: row["primitive"] == "LOCATE"
            and row["target"]["decision"] == "ABSTAIN"
            and not row["task_family"].startswith("LONG_CONTEXT")
        )
        required = record["task_spec"]["constraints"]["required_attributes"]
        unit = record["inputs"][0]["units"][0]
        unit.setdefault("attributes", {}).update(required)
        unit["text"] += ";" + ";".join(str(value) for value in required.values())
        _rehash(record)
        self.assert_rejected(
            record, "LOCATE_ABSTAIN_CONTRADICTED_BY_VISIBLE_INPUT"
        )

    def test_rank_synchronised_winner_tamper_is_rejected(self):
        record = self.one(lambda row: row["primitive"] == "RANK")
        ranking = record["target"]["ranking"]
        ranking[0], ranking[1] = ranking[1], ranking[0]
        # Make every target field internally agree with the false winner.
        descending = sorted(record["target"]["graded_relevance"].values(), reverse=True)
        record["target"]["graded_relevance"] = dict(zip(ranking, descending))
        record["target"]["evidence"] = [ranking[0]]
        record["target"]["action"]["arguments"]["ordered_ids"] = list(ranking)
        self.assert_rejected(
            record, "RANK_GRADES_NOT_REPRODUCIBLE_FROM_VISIBLE_ATTRIBUTES"
        )

    def test_rank_relevance_leak_is_rejected(self):
        record = self.one(lambda row: row["primitive"] == "RANK")
        candidates = next(item for item in record["inputs"] if "candidate" in item["type"])
        candidates["units"][0]["relevance"] = 3
        _rehash(record)
        self.assert_rejected(record, "GOLD_SIGNAL_EXPOSED_IN_CANDIDATE_INPUT")

    def test_match_synchronised_id_tamper_is_rejected(self):
        record = self.one(lambda row: row["primitive"] == "MATCH")
        candidates = next(item for item in record["inputs"] if "candidate" in item["type"])
        winner = record["target"]["canonical_id"]
        wrong = next(unit["id"] for unit in candidates["units"] if unit["id"] != winner)
        record["target"]["decision"] = wrong
        record["target"]["canonical_id"] = wrong
        record["target"]["matches"] = [wrong]
        record["target"]["action"]["arguments"]["candidate_id"] = wrong
        record["target"]["evidence"] = [record["inputs"][0]["units"][0]["id"], wrong]
        self.assert_rejected(
            record, "MATCH_GOLD_NOT_REPRODUCIBLE_FROM_VISIBLE_ATTRIBUTES"
        )

    def test_align_suffix_shortcut_is_rejected(self):
        record = self.one(lambda row: row["primitive"] == "ALIGN")
        replacements = {}
        for index, alignment in enumerate(record["target"]["alignments"], 1):
            replacements[alignment["source"][0]] = f"src:u{index:02d}"
            replacements[alignment["target"][0]] = f"tgt:u{index:02d}"
        mutated = _replace_strings(record, replacements)
        _rehash(mutated)
        verdict = self.assert_rejected(mutated, "ALIGNMENT_IDS_NOT_OPAQUE")
        self.assertIn("ALIGNMENT_ID_SUFFIX_LEAKS_GOLD", verdict["hard_failures"])

    def test_align_opaque_destination_swap_is_rejected(self):
        record = self.one(lambda row: row["primitive"] == "ALIGN")
        alignments = record["target"]["alignments"]
        alignments[0]["target"], alignments[1]["target"] = (
            alignments[1]["target"],
            alignments[0]["target"],
        )
        self.assert_rejected(
            record, "ALIGN_GOLD_NOT_REPRODUCIBLE_FROM_VISIBLE_CONTENT"
        )

    def test_edit_replacement_and_output_tamper_is_rejected(self):
        record = self.one(
            lambda row: row["primitive"] == "EDIT"
            and row["target"]["action"]["arguments"].get("op") == "REPLACE"
        )
        operation = record["target"]["edit_operations"][0]
        operation["replacement"] = "這是同步竄改後的錯誤內容。"
        record["target"]["action"]["arguments"] = deepcopy(operation)
        hypothesis = next(item for item in record["inputs"] if item["id"] == "hyp")
        record["target"]["output_text"] = "".join(
            operation["replacement"] if unit["id"] == operation["target"] else unit["text"]
            for unit in hypothesis["units"]
        )
        self.assert_rejected(record, "EDIT_OPERATION_NOT_EXECUTABLE_TO_GOLD_OUTPUT")

    def test_classify_synchronised_label_tamper_is_rejected(self):
        record = self.one(lambda row: row["primitive"] == "CLASSIFY")
        old = record["target"]["decision"]
        wrong = next(label for label in record["task_spec"]["allowed_labels"] if label != old)
        record["target"]["decision"] = wrong
        record["target"]["label"] = wrong
        record["target"]["action"]["arguments"]["label"] = wrong
        self.assert_rejected(record, "CLASSIFY_GOLD_DIFFERS_FROM_VISIBLE_CONTENT_RULE")

    def test_domain_cue_ignores_domain_words_inside_organisation_name(self):
        record = generate_record_v2(self.config, self.plan, 30_033)
        self.assertEqual(record["task_family"], "DOMAIN_CLASSIFICATION")
        self.assertIn("南風教育科技室", record["inputs"][0]["units"][0]["text"])
        self.assertIn("文化典藏領域", record["inputs"][0]["units"][0]["text"])
        self.assertEqual(record["target"]["decision"], "CULTURE")
        self.assertEqual(validate_record_quality_v2(record)["hard_failures"], [])

    def test_extract_alternate_substring_tamper_is_rejected(self):
        record = self.one(lambda row: row["primitive"] == "EXTRACT")
        field = record["target"]["fields"][0]
        evidence_text = next(
            unit["text"]
            for item in record["inputs"]
            for unit in item["units"]
            if unit["id"] == field["evidence"][0]
        )
        field["value"] = evidence_text[:2]
        self.assert_rejected(
            record, "EXTRACT_GOLD_NOT_REPRODUCIBLE_FROM_FIELD_ORACLE"
        )

    def test_extract_swapped_field_values_are_rejected(self):
        record = self.one(lambda row: row["primitive"] == "EXTRACT")
        fields = record["target"]["fields"]
        fields[0]["value"], fields[1]["value"] = fields[1]["value"], fields[0]["value"]
        self.assert_rejected(
            record, "EXTRACT_GOLD_NOT_REPRODUCIBLE_FROM_FIELD_ORACLE"
        )

    def test_verify_pass_candidate_tamper_is_rejected(self):
        record = self.one(
            lambda row: row["primitive"] == "VERIFY"
            and row["target"]["decision"] == "PASS"
            and not row["task_family"].startswith("LONG_CONTEXT")
        )
        candidate = next(item for item in record["inputs"] if "candidate" in item["type"] or "hypothesis" in item["type"])
        candidate["units"][0]["text"] += "錯誤增補"
        _rehash(record)
        self.assert_rejected(record, "VERIFY_PASS_REFERENCE_CANDIDATE_NOT_EQUAL")

    def test_verify_false_pass_target_tamper_is_rejected(self):
        record = self.one(
            lambda row: row["primitive"] == "VERIFY"
            and row["target"]["decision"] == "FAIL"
            and not row["task_family"].startswith("LONG_CONTEXT")
        )
        candidate = next(item for item in record["inputs"] if "candidate" in item["type"] or "hypothesis" in item["type"])
        record["target"].update(
            {
                "decision": "PASS",
                "quality_score": 1.0,
                "errors": [],
                "action": {"tool": "ACCEPT", "arguments": {"candidate_id": candidate["units"][0]["id"]}},
            }
        )
        self.assert_rejected(record, "VERIFY_PASS_REFERENCE_CANDIDATE_NOT_EQUAL")

    def test_verify_repair_tamper_is_rejected(self):
        record = self.one(
            lambda row: row["primitive"] == "VERIFY"
            and row["target"]["decision"] == "FAIL"
            and not row["task_family"].startswith("LONG_CONTEXT")
        )
        record["target"]["action"]["arguments"]["replacement"] = "錯誤修復結果。"
        self.assert_rejected(record, "VERIFY_REPAIR_DOES_NOT_REACH_REFERENCE")

    def test_long_context_verify_all_three_outcomes_are_executable(self):
        outcomes = {}
        for record in self.records:
            if record["task_family"] == "LONG_CONTEXT_CONTRADICTION":
                outcomes.setdefault(record["target"]["decision"], record)
        self.assertEqual(set(outcomes), {"PASS", "FAIL", "UNCERTAIN"})
        for outcome, record in outcomes.items():
            with self.subTest(outcome=outcome):
                self.assertEqual(validate_record_quality_v2(record)["disposition"], "KEEP")

    def test_long_context_uncertainty_without_two_conflicts_is_rejected(self):
        record = self.one(
            lambda row: row["task_family"] == "LONG_CONTEXT_CONTRADICTION"
            and row["target"]["decision"] == "UNCERTAIN"
        )
        conflict = next(
            unit
            for item in record["inputs"]
            for unit in item["units"]
            if unit.get("attributes", {}).get("status") == "active_conflict"
        )
        conflict["attributes"]["status"] = "context"
        _rehash(record)
        self.assert_rejected(record, "VERIFY_UNCERTAIN_LEDGER_CONFLICT_NOT_REPRODUCIBLE")

    def test_route_synchronised_action_tamper_is_rejected(self):
        record = self.one(
            lambda row: row["primitive"] == "ROUTE"
            and row["task_family"] == "TOOL_ROUTING"
            and row["target"]["decision"] == "EDIT"
        )
        record["target"]["decision"] = "RETRIEVE"
        record["target"]["action"] = {
            "tool": "RETRIEVE",
            "arguments": {"query": "查詢另一份紀錄"},
        }
        self.assert_rejected(record, "ROUTE_GOLD_NOT_REPRODUCIBLE_FROM_VISIBLE_ATTRIBUTES")

    def test_verify_uncertainty_is_rejected_when_any_authority_restores_date(self):
        for family in ("ASR_QUALITY", "OCR_QUALITY", "MT_QUALITY"):
            record = self.one(lambda row: row["task_family"] == family and row["target"]["decision"] == "UNCERTAIN")
            candidate = next(item for item in record["inputs"] if item["id"] == "hyp")
            dated_text = next(unit["text"] for unit in candidate["units"] if " 年 " in unit["text"])
            authority = next(item for item in record["inputs"] if item["id"] == ("source" if family == "MT_QUALITY" else "ref"))
            authority["units"].append({"id": "ref:restored", "text": dated_text})
            _rehash(record)
            self.assert_rejected(record, "VERIFY_UNCERTAIN_DECISIVE_DATE_STILL_VISIBLE")

    def test_candidate_state_gold_leak_is_rejected(self):
        for primitive in ("VERIFY", "ROUTE"):
            record = self.one(lambda row: row["primitive"] == primitive)
            record["inputs"][0]["units"][0].setdefault("attributes", {})["candidate_state"] = "consistent"
            _rehash(record)
            self.assert_rejected(record, "GOLD_ANNOTATION_EXPOSED_IN_INPUT")

    def test_character_confusion_is_not_a_numeric_value_error(self):
        for family in ("ASR_CORRECTION", "OCR_CORRECTION"):
            record = self.one(lambda row: row["task_family"] == family)
            record["target"]["errors"][0]["type"] = "VALUE_CORRUPTION"
            self.assert_rejected(record, "VALUE_CORRUPTION_WITHOUT_NUMERIC_CHANGE")

    def test_rank_error_sentinel_is_rejected(self):
        record = self.one(lambda row: row["primitive"] == "RANK")
        record["inputs"][1]["units"][0]["text"] += " 不符-location-1-9"
        _rehash(record)
        self.assert_rejected(record, "GOLD_SIGNAL_EXPOSED_IN_CANDIDATE_TEXT")

    def test_route_edit_must_modify_candidate_not_observation(self):
        record = self.one(lambda row: row["task_family"] == "TOOL_ROUTING" and row["target"]["decision"] == "EDIT")
        record["target"]["action"]["arguments"]["target"] = "obs:u01"
        self.assert_rejected(record, "ROUTE_EDIT_TARGET_NOT_CANDIDATE")

    def test_route_pointer_must_address_matching_coordinate_unit(self):
        record = self.one(lambda row: row["task_family"] == "MODALITY_ROUTING" and row["target"]["decision"] == "POINT_TIME")
        record["target"]["action"]["arguments"]["unit_ids"] = ["modality:u01"]
        self.assert_rejected(record, "ROUTE_POINTER_COORDINATE_TYPE_MISMATCH")

    def test_classifier_corpus_gate_detects_missing_labels(self):
        record = self.one(lambda row: row["task_family"] == "EMOTION_CLASSIFICATION")
        accumulator = PromotionAccumulator(minimum_family_records=1, minimum_template_variants=1)
        for split in ("train", "validation", "test"):
            example = deepcopy(record)
            example["split"] = split
            accumulator.add(example, {"disposition": "KEEP", "hard_failures": []})
        gate = accumulator.finalize()["gates"]["classification_label_coverage:EMOTION_CLASSIFICATION"]
        self.assertFalse(gate["passed"])
        self.assertEqual(len(gate["missing_by_split"]["train"]), 3)

    def test_provenance_source_content_hash_tamper_is_rejected(self):
        record = deepcopy(self.records[0])
        record["provenance"]["source_hash"] = "0" * 64
        self.assert_rejected(record, "PROVENANCE_SOURCE_CONTENT_HASH_MISMATCH")

    def test_serializer_target_non_json_tamper_is_rejected(self):
        record = deepcopy(self.records[0])
        record["target"]["non_json_probe"] = ("tuple", "is", "not", "canonical-json")
        self.assert_rejected(record, "SERIALIZER_SEMANTIC_ROUNDTRIP_FAILED")

    def test_confidence_cannot_claim_calibration_gold(self):
        record = deepcopy(self.records[0])
        record["target"]["confidence_semantics"] = "calibration_gold"
        self.assert_rejected(record, "TARGET_CONFIDENCE_SEMANTICS_MISLABELLED")

    def test_traditional_chinese_term_gate(self):
        record = deepcopy(self.records[0])
        record["inputs"][0]["units"][0]["text"] += "软件與服務器"
        _rehash(record)
        self.assert_rejected(record, "SIMPLIFIED_OR_NON_TW_TERM_DETECTED")

    def test_long_ledger_repetition_gate(self):
        record = self.one(lambda row: row["task_family"] == "LONG_CONTEXT_ACTIVE_VALUE")
        repeated = "更新:同一段填充內容反覆出現。"
        for unit in record["inputs"][0]["units"]:
            unit["text"] = repeated
        _rehash(record)
        verdict = validate_record_quality_v2(record)
        self.assertIn("WITHIN_RECORD_TEMPLATE_REPETITION_HIGH", verdict["hard_failures"])
        self.assertIn("LONG_LEDGER_TEMPLATE_DIVERSITY_TOO_LOW", verdict["hard_failures"])

    def test_ledger_event_type_must_agree_with_visible_sentence(self):
        record = self.one(lambda row: row["task_family"] == "LONG_CONTEXT_ACTIVE_VALUE")
        event = record["inputs"][0]["units"][0]
        event["attributes"]["event_type"] = "not_the_visible_event"
        _rehash(record)
        self.assert_rejected(record, "LEDGER_EVENT_TYPE_CONTRADICTS_VISIBLE_TEXT")

    def test_context_bucket_and_measure_tamper_are_rejected(self):
        record = self.one(lambda row: row["quality"]["context_length_bucket"] == "SHORT_LT_0.5K")
        record["quality"]["context_length_bucket"] = "64K-128K"
        record["quality"]["context_length_measure"] = "pangolin_tokens"
        verdict = self.assert_rejected(
            record, "CONTEXT_LENGTH_BUCKET_DOES_NOT_MATCH_VISIBLE_TEXT_CHARS"
        )
        self.assertIn("CONTEXT_LENGTH_MEASURE_MISSING_OR_MISLABELLED", verdict["hard_failures"])

    def test_accumulator_merge_matches_single_pass_and_is_pickle_safe(self):
        records = self.records[:120]
        single = PromotionAccumulator(minimum_family_records=1, minimum_template_variants=1)
        left = PromotionAccumulator(minimum_family_records=1, minimum_template_variants=1)
        right = PromotionAccumulator(minimum_family_records=1, minimum_template_variants=1)
        for index, record in enumerate(records):
            verdict = validate_record_quality_v2(record)
            single.add(record, verdict)
            (left if index < 60 else right).add(record, verdict)
        pickle.loads(pickle.dumps(left))
        left.merge(right)
        self.assertEqual(left.finalize(), single.finalize())

    def test_accumulator_fails_closed_for_missing_families_and_splits(self):
        accumulator = PromotionAccumulator(minimum_family_records=1, minimum_template_variants=1)
        record = self.records[0]
        accumulator.add(record, validate_record_quality_v2(record))
        report = accumulator.finalize()
        self.assertFalse(report["promotion_passed"])
        self.assertFalse(report["gates"]["task_family_coverage"]["passed"])
        self.assertFalse(report["gates"]["split_coverage"]["passed"])

    def test_accumulator_detects_source_group_split_conflict(self):
        accumulator = PromotionAccumulator(minimum_family_records=1, minimum_template_variants=1)
        first = deepcopy(self.records[0])
        second = deepcopy(first)
        second["split"] = "validation"
        second["presentation"]["template_profile"] = "heldout_validation"
        accumulator.add(first, {"disposition": "KEEP", "hard_failures": []})
        accumulator.add(second, {"disposition": "KEEP", "hard_failures": []})
        gate = accumulator.finalize()["gates"]["source_group_split_lock"]
        self.assertFalse(gate["passed"])
        self.assertEqual(gate["conflict_count"], 1)

    def test_accumulator_detects_heldout_template_overlap_and_profile_mismatch(self):
        accumulator = PromotionAccumulator(minimum_family_records=1, minimum_template_variants=1)
        base = deepcopy(self.records[0])
        for split, profile in (
            ("train", "train_core"),
            ("validation", "heldout_validation"),
            ("test", "wrong_profile"),
        ):
            record = deepcopy(base)
            record["record_id"] = f"bgd_tw_v2_{len(accumulator.family_counts):07d}"
            record["source_group"] = f"template-overlap:{split}"
            record["split"] = split
            record["presentation"]["template_profile"] = profile
            record["presentation"]["template_id"] = "deliberately-shared-template"
            accumulator.add(record, {"disposition": "KEEP", "hard_failures": []})
        report = accumulator.finalize()
        self.assertFalse(report["gates"]["heldout_template_isolation"]["passed"])
        self.assertFalse(report["gates"]["template_profile_split_contract"]["passed"])
        self.assertFalse(report["gates"]["context_bucket_distribution"]["passed"])

    def test_accumulator_rejects_skewed_winner_position(self):
        record = self.one(lambda row: row["primitive"] == "RANK")
        family = record["task_family"]
        accumulator = PromotionAccumulator(minimum_family_records=40, minimum_template_variants=1)
        verdict = validate_record_quality_v2(record)
        for _ in range(40):
            accumulator.add(record, verdict)
        gate = accumulator.finalize()["gates"][f"winner_position_balance:{family}"]
        self.assertFalse(gate["passed"])
        self.assertGreater(gate["max_relative_deviation"], 0.25)

    def test_accumulator_verify_outcome_distribution(self):
        family = "ASR_QUALITY"
        outcomes = {}
        for record in self.records:
            if record["task_family"] == family:
                outcomes.setdefault(record["target"]["decision"], record)
        self.assertEqual(set(outcomes), {"PASS", "FAIL", "UNCERTAIN"})
        accumulator = PromotionAccumulator(minimum_family_records=3, minimum_template_variants=1)
        for record in outcomes.values():
            accumulator.add(record, validate_record_quality_v2(record))
        report = accumulator.finalize()
        gate = report["gates"][f"verify_outcome_balance:{family}"]
        self.assertTrue(gate["passed"])
        self.assertEqual(gate["decisions"], {"FAIL": 1, "PASS": 1, "UNCERTAIN": 1})
        self.assertIn(family, report["family_confidence_distribution"])
        self.assertIn(family, report["family_normalized_template_counts"])


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