barbet-sft / code /src /barbet_bgd /validation.py
voidful's picture
Release reviewed Taiwan-centric Barbet SFT 1M with fixed-schema messages and full audits
0bf2389 verified
Raw History Blame Contribute Delete
26.9 kB
"""Dependency-free semantic validation for BGD canonical records.
The JSON Schema next to this module documents the serialised shape. This
module intentionally performs the checks that JSON Schema cannot express:
stable-ID referential integrity, evidence discipline, and the distinction
between positive zh-TW supervision and intentional negative examples.
"""
from __future__ import annotations
from collections.abc import Iterable, Mapping, Sequence
import math
import re
from typing import Any
PRIMITIVES = frozenset(
{
"COPY",
"EDIT",
"CLASSIFY",
"EXTRACT",
"LOCATE",
"ALIGN",
"MATCH",
"RANK",
"VERIFY",
"ROUTE",
}
)
ERROR_TYPES = frozenset(
{
"MISSING_REALIZATION",
"UNSUPPORTED_ADDITION",
"VALUE_CORRUPTION",
"IDENTITY_MISMATCH",
"ORDER_VIOLATION",
"BOUNDARY_SHIFT",
"DUPLICATION",
"STRUCTURE_BREAK",
"CONSTRAINT_VIOLATION",
"INSUFFICIENT_EVIDENCE",
}
)
# This is deliberately finite. Adding a tool is a schema change, rather than
# something an individual record may silently invent.
ACTION_TOOLS = frozenset(
{
"COPY",
"EDIT",
"CLASSIFY",
"RETURN_LABEL",
"EXTRACT",
"LOCATE",
"ALIGN",
"MATCH",
"RANK",
"VERIFY",
"ROUTE",
"RETRIEVE",
"POINT_TEXT",
"POINT_TIME",
"POINT_BOX",
"POINT_TABLE",
"POINT_GRAPH",
"ACCEPT",
"REJECT",
"NO_OP",
"ABSTAIN",
"REQUEST_MORE_EVIDENCE",
"REGENERATE_SEGMENT",
"HUMAN_REVIEW",
"UPDATE_LEDGER",
"LINK_EVIDENCE",
"FIND_ACTIVE_VALUE",
"DETECT_CONTRADICTION",
"FIND_SUPERSEDED_DECISION",
"FIND_UNRESOLVED_ISSUE",
"ATTRIBUTE_CLAIM",
}
)
REQUIRED_RECORD_FIELDS = (
"record_id",
"schema_version",
"primitive",
"mixture_category",
"task_family",
"domain",
"language",
"locale",
"split",
"source_group",
"task_spec",
"inputs",
"target",
"component_targets",
"presentation",
"provenance",
"quality",
)
_ID_RE = re.compile(r"^[^\s]+$")
# High-signal simplified forms. Ambiguous characters that are also normal in
# Taiwan text (for example 后, 里, 台, 干) are intentionally excluded.
_SIMPLIFIED_CHARS = frozenset(
"这们为发现会说对从还让进过边开关问间种样点应当无并动产业东书车马门"
"风气长乐见观觉学术语体国万亿网软线标数据处务别选择确认级类则导广"
"场层块张头条项节录页图声转换获给结构复杂简将与仅请传统华汉湾医药"
"银钱历区县乡镇际参报备责权资码库档盘记汇验适响隐审个"
)
# Terms remain disallowed after mechanical OpenCC conversion because they are
# strongly associated with PRC usage rather than native Taiwan usage.
_MAINLAND_TERMS = frozenset(
{
"軟件",
"软件",
"硬件",
"視頻",
"音頻",
"網絡",
"互聯網",
"文件夾",
"數據庫",
"打印機",
"公交車",
"出租車",
"地鐵",
"信息化",
"用戶名",
"屏幕",
"硬盤",
"芯片",
"默認值",
"加載",
"文檔",
"賬號",
"內存",
"接口",
"鼠標",
"服務器",
"短信",
"二維碼",
"身份證",
"居民身份證",
"人民幣",
"高考",
"街道辦",
"公積金",
"小區",
"網盤",
"雲計算",
}
)
_NEGATIVE_MARKERS = (
"hypothesis",
"candidate",
"corrupted",
"corruption",
"noisy",
"prediction",
"generated",
"asr_output",
"ocr_output",
"model_output",
"negative",
)
_POSITIVE_ROLES = frozenset({"source", "reference", "gold", "clean", "positive"})
_NEGATIVE_INPUT_IDS = frozenset(
{"hyp", "hypothesis", "candidate", "candidates", "cand", "corrupted", "noisy"}
)
_INPUT_TEXT_KEYS = frozenset(
{
"text",
"content",
"sentence",
"transcript",
"source_text",
"reference_text",
"spoken_text",
"translation",
"value_text",
}
)
_TARGET_POSITIVE_TEXT_KEYS = frozenset(
{
"output",
"output_text",
"answer",
"response",
"post_edit",
"post-edit",
"replacement",
"corrected_text",
"normalized_text",
"clean_text",
"translation",
"spoken_text",
}
)
_REFERENCE_CONTAINER_KEYS = frozenset(
{
"evidence",
"source_evidence",
"target_evidence",
"supporting_evidence",
"contradicting_evidence",
"locations",
"location_ids",
"copy",
"copies",
"copy_ids",
"copied_ids",
"alignment",
"alignments",
"alignment_ids",
"aligned_ids",
"target_ranking",
"ranking",
"ordered_ids",
}
)
_EVIDENCE_CONTAINER_KEYS = _REFERENCE_CONTAINER_KEYS - frozenset(
{"target_ranking", "ranking", "ordered_ids"}
)
_DIRECT_REFERENCE_KEYS = frozenset(
{
"unit_id",
"unit_ids",
"source_unit_id",
"source_unit_ids",
"target_unit_id",
"target_unit_ids",
"left_id",
"right_id",
"start_id",
"end_id",
"candidate_id",
"candidate_ids",
"canonical_id",
"match_ids",
"matches",
"copy_units",
"copied_units",
"source_units",
"ordered_ids",
"target",
"targets",
"candidate",
"activate",
"supersede",
}
)
_REFERENCE_OBJECT_KEYS = _DIRECT_REFERENCE_KEYS | frozenset(
{"id", "source", "target", "left", "right", "from", "to", "units"}
)
_REFERENCE_METADATA_KEYS = frozenset(
{
"type",
"kind",
"label",
"severity",
"reason",
"reason_code",
"relation",
"modality",
"text",
"quote",
"description",
"operation",
}
)
class RecordValidationError(ValueError):
"""Raised by :func:`assert_valid_record` for an invalid record."""
def __init__(self, errors: Sequence[str]) -> None:
self.errors = list(errors)
super().__init__("Invalid BGD canonical record:\n- " + "\n- ".join(self.errors))
def find_disallowed_terms(text: str) -> list[str]:
"""Return deterministic literal simplified/PRC-usage hits in *text*."""
if not isinstance(text, str):
return []
hits = {char for char in text if char in _SIMPLIFIED_CHARS}
hits.update(term for term in _MAINLAND_TERMS if term in text)
return sorted(hits, key=lambda value: (-len(value), value))
def _is_nonempty_string(value: Any) -> bool:
return isinstance(value, str) and bool(value.strip())
def _is_list(value: Any) -> bool:
return isinstance(value, list)
def _is_json_object(value: Any) -> bool:
return isinstance(value, Mapping)
def _string_values(value: Any) -> Iterable[str]:
if isinstance(value, str):
yield value
elif isinstance(value, Mapping):
for child in value.values():
yield from _string_values(child)
elif isinstance(value, list):
for child in value:
yield from _string_values(child)
def _iter_named_text(
value: Any,
path: str,
names: frozenset[str],
*,
skip_subtrees: frozenset[str] = frozenset(),
) -> Iterable[tuple[str, str]]:
if isinstance(value, Mapping):
for raw_key, child in value.items():
key = str(raw_key)
child_path = f"{path}.{key}"
if key.lower() in skip_subtrees:
continue
if key.lower() in names:
for index, text in enumerate(_string_values(child)):
suffix = "" if isinstance(child, str) else f"[{index}]"
yield child_path + suffix, text
elif isinstance(child, (Mapping, list)):
yield from _iter_named_text(
child,
child_path,
names,
skip_subtrees=skip_subtrees,
)
elif isinstance(value, list):
for index, child in enumerate(value):
yield from _iter_named_text(
child,
f"{path}[{index}]",
names,
skip_subtrees=skip_subtrees,
)
def _input_is_negative(input_item: Mapping[str, Any]) -> bool:
role = str(input_item.get("role", "")).strip().lower()
if role in _POSITIVE_ROLES:
return False
if input_item.get("is_intentional_negative") is True:
return True
input_id = str(input_item.get("id", "")).strip().lower()
if input_id in _NEGATIVE_INPUT_IDS or input_id.startswith(("hyp:", "cand:")):
return True
descriptor = " ".join(
str(input_item.get(key, "")).lower() for key in ("type", "role", "kind")
)
return any(marker in descriptor for marker in _NEGATIVE_MARKERS)
def _extract_reference_strings(value: Any, path: str) -> Iterable[tuple[str, str]]:
if isinstance(value, str):
if value:
yield path, value
return
if isinstance(value, list):
for index, child in enumerate(value):
yield from _extract_reference_strings(child, f"{path}[{index}]")
return
if not isinstance(value, Mapping):
return
for raw_key, child in value.items():
key = str(raw_key).lower()
child_path = f"{path}.{raw_key}"
if key in _REFERENCE_METADATA_KEYS:
continue
if key in _REFERENCE_OBJECT_KEYS or key in _REFERENCE_CONTAINER_KEYS:
yield from _extract_reference_strings(child, child_path)
elif isinstance(child, (Mapping, list)):
# Nested pointer structures are allowed; scalar prose under an
# unknown key is deliberately not interpreted as an ID.
yield from _extract_reference_strings(child, child_path)
def _collect_references(value: Any, path: str = "target") -> list[tuple[str, str]]:
found: list[tuple[str, str]] = []
if isinstance(value, Mapping):
for raw_key, child in value.items():
key = str(raw_key).lower()
child_path = f"{path}.{raw_key}"
if key in _REFERENCE_CONTAINER_KEYS or key in _DIRECT_REFERENCE_KEYS:
found.extend(_extract_reference_strings(child, child_path))
else:
found.extend(_collect_references(child, child_path))
elif isinstance(value, list):
for index, child in enumerate(value):
found.extend(_collect_references(child, f"{path}[{index}]"))
return found
def _contains_nonempty_evidence(value: Any) -> bool:
if isinstance(value, Mapping):
for raw_key, child in value.items():
key = str(raw_key).lower()
if key in _EVIDENCE_CONTAINER_KEYS:
if child not in (None, "", [], {}):
return True
if _contains_nonempty_evidence(child):
return True
elif isinstance(value, list):
return any(_contains_nonempty_evidence(child) for child in value)
return False
def _has_insufficient_evidence_marker(target: Mapping[str, Any]) -> bool:
return any(value.strip().upper() == "INSUFFICIENT_EVIDENCE" for value in _string_values(target))
def _is_abstention(target: Mapping[str, Any]) -> bool:
decision_values = {
value.strip().upper() for value in _string_values(target.get("decision"))
}
action = target.get("action")
action_tool = ""
if isinstance(action, Mapping):
action_tool = str(action.get("tool", "")).strip().upper()
return "ABSTAIN" in decision_values or action_tool == "ABSTAIN"
def _add_unique(errors: list[str], message: str) -> None:
if message not in errors:
errors.append(message)
def _check_positive_text(path: str, text: str, errors: list[str]) -> None:
hits = find_disallowed_terms(text)
if hits:
_add_unique(
errors,
f"{path} must use native Traditional Chinese; disallowed hit(s): {', '.join(hits)}",
)
def _validate_task_spec(task_spec: Any, errors: list[str]) -> Mapping[str, Any] | None:
if not _is_json_object(task_spec):
errors.append("task_spec must be an object")
return None
instruction = task_spec.get("instruction")
if not _is_nonempty_string(instruction):
errors.append("task_spec.instruction must be a non-empty string")
else:
_check_positive_text("task_spec.instruction", instruction, errors)
for key in ("required_evidence", "abstention_allowed"):
if not isinstance(task_spec.get(key), bool):
errors.append(f"task_spec.{key} must be a boolean")
allowed_errors = task_spec.get("allowed_error_types")
if allowed_errors is not None:
if not _is_list(allowed_errors) or not all(
isinstance(value, str) and value in ERROR_TYPES for value in allowed_errors
):
errors.append(
"task_spec.allowed_error_types must contain only closed-world error types"
)
for field in ("allowed_actions", "allowed_tools"):
allowed_tools = task_spec.get(field)
if allowed_tools is not None:
if not _is_list(allowed_tools) or not all(
isinstance(value, str) and value in ACTION_TOOLS for value in allowed_tools
):
errors.append(
f"task_spec.{field} must contain only closed-world action tools"
)
return task_spec
def _validate_target(
target: Any,
task_spec: Mapping[str, Any] | None,
errors: list[str],
) -> Mapping[str, Any] | None:
if not _is_json_object(target):
errors.append("target must be an object")
return None
if "decision" not in target or target.get("decision") is None:
errors.append("target.decision is required and cannot be null")
confidence = target.get("confidence_target")
if (
isinstance(confidence, bool)
or not isinstance(confidence, (int, float))
or not math.isfinite(float(confidence))
or not 0.0 <= float(confidence) <= 1.0
):
errors.append("target.confidence_target must be a finite number in [0, 1]")
action = target.get("action")
if not _is_json_object(action):
errors.append("target.action must be an object")
else:
tool = action.get("tool")
if tool not in ACTION_TOOLS:
errors.append("target.action.tool must be a closed-world action tool")
if not _is_json_object(action.get("arguments")):
errors.append("target.action.arguments must be an object")
configured_actions: Any = None
configured_field = "allowed_actions"
if task_spec is not None:
configured_actions = task_spec.get("allowed_actions")
if configured_actions is None:
configured_field = "allowed_tools"
configured_actions = task_spec.get("allowed_tools")
if isinstance(configured_actions, list):
if tool in ACTION_TOOLS and tool not in configured_actions:
errors.append(
f"target.action.tool is not permitted by task_spec.{configured_field}"
)
target_errors = target.get("errors")
if target_errors is not None:
if not _is_list(target_errors):
errors.append("target.errors must be an array when present")
else:
allowed_error_types = (
task_spec.get("allowed_error_types") if task_spec is not None else None
)
for index, item in enumerate(target_errors):
if not _is_json_object(item):
errors.append(f"target.errors[{index}] must be an object")
continue
error_type = item.get("type")
if error_type not in ERROR_TYPES:
errors.append(
f"target.errors[{index}].type must be a closed-world error type"
)
elif (
isinstance(allowed_error_types, list)
and error_type not in allowed_error_types
):
errors.append(
f"target.errors[{index}].type is not permitted by "
"task_spec.allowed_error_types"
)
for path, text in _iter_named_text(
target,
"target",
_TARGET_POSITIVE_TEXT_KEYS,
skip_subtrees=frozenset({"errors", "negative_examples", "candidates"}),
):
_check_positive_text(path, text, errors)
return target
def _validate_inputs(
inputs: Any,
errors: list[str],
) -> tuple[set[str], dict[str, set[str]]]:
addressable_ids: set[str] = set()
unit_ids: set[str] = set()
negative_hits: dict[str, set[str]] = {}
if not _is_list(inputs) or not inputs:
errors.append("inputs must be a non-empty array")
return addressable_ids, negative_hits
for input_index, input_item in enumerate(inputs):
input_path = f"inputs[{input_index}]"
if not _is_json_object(input_item):
errors.append(f"{input_path} must be an object")
continue
input_id = input_item.get("id")
if not _is_nonempty_string(input_id) or not _ID_RE.fullmatch(input_id):
errors.append(f"{input_path}.id must be a non-empty whitespace-free string")
input_id = None
elif input_id in addressable_ids:
errors.append(f"duplicate input/addressable ID: {input_id}")
else:
addressable_ids.add(input_id)
if not _is_nonempty_string(input_item.get("type")):
errors.append(f"{input_path}.type must be a non-empty string")
negative = _input_is_negative(input_item)
# Text stored directly on the input object is addressable by input.id.
direct_item = {key: value for key, value in input_item.items() if key != "units"}
for path, text in _iter_named_text(direct_item, input_path, _INPUT_TEXT_KEYS):
hits = set(find_disallowed_terms(text))
if not hits:
continue
if negative and input_id is not None:
negative_hits.setdefault(input_id, set()).update(hits)
else:
_check_positive_text(path, text, errors)
units = input_item.get("units")
if not _is_list(units) or not units:
errors.append(f"{input_path}.units must be a non-empty array")
continue
for unit_index, unit in enumerate(units):
unit_path = f"{input_path}.units[{unit_index}]"
if not _is_json_object(unit):
errors.append(f"{unit_path} must be an object")
continue
unit_id = unit.get("id")
if not _is_nonempty_string(unit_id) or not _ID_RE.fullmatch(unit_id):
errors.append(f"{unit_path}.id must be a non-empty whitespace-free string")
unit_id = None
elif unit_id in unit_ids:
errors.append(f"duplicate input unit ID: {unit_id}")
elif unit_id in addressable_ids:
errors.append(f"input unit ID collides with another addressable ID: {unit_id}")
else:
unit_ids.add(unit_id)
addressable_ids.add(unit_id)
for path, text in _iter_named_text(unit, unit_path, _INPUT_TEXT_KEYS):
hits = set(find_disallowed_terms(text))
if not hits:
continue
if negative and unit_id is not None:
negative_hits.setdefault(unit_id, set()).update(hits)
else:
_check_positive_text(path, text, errors)
return addressable_ids, negative_hits
def _validate_intentional_negative_audit(
quality: Mapping[str, Any],
negative_hits: Mapping[str, set[str]],
target: Mapping[str, Any] | None,
addressable_ids: set[str],
errors: list[str],
) -> None:
raw_entries = quality.get("intentional_negative_simplified_hits", [])
if not _is_list(raw_entries):
errors.append("quality.intentional_negative_simplified_hits must be an array")
return
declared: dict[str, set[str]] = {}
for index, entry in enumerate(raw_entries):
path = f"quality.intentional_negative_simplified_hits[{index}]"
if not _is_json_object(entry):
errors.append(f"{path} must be an object")
continue
unit_id = entry.get("unit_id")
hits = entry.get("hits")
if not _is_nonempty_string(unit_id):
errors.append(f"{path}.unit_id must be a non-empty string")
continue
if unit_id not in addressable_ids:
errors.append(f"{path}.unit_id references unknown input ID: {unit_id}")
if unit_id in declared:
errors.append(f"duplicate intentional-negative audit entry for ID: {unit_id}")
if not _is_list(hits) or not hits or not all(_is_nonempty_string(hit) for hit in hits):
errors.append(f"{path}.hits must be a non-empty array of strings")
declared[unit_id] = set()
else:
declared[unit_id] = set(hits)
error_evidence_ids: set[str] = set()
if target is not None and isinstance(target.get("errors"), list):
error_evidence_ids = {
reference for _, reference in _collect_references(target["errors"], "target.errors")
}
for unit_id, actual_hits in negative_hits.items():
if unit_id not in error_evidence_ids:
errors.append(
f"intentional negative ID {unit_id} contains disallowed term(s) but is not "
"captured by target.errors evidence"
)
if unit_id not in declared:
errors.append(
f"quality.intentional_negative_simplified_hits is missing ID: {unit_id}"
)
continue
missing_hits = actual_hits - declared[unit_id]
if missing_hits:
errors.append(
f"intentional-negative audit for {unit_id} is missing hit(s): "
+ ", ".join(sorted(missing_hits))
)
for unit_id, declared_hits in declared.items():
actual_hits = negative_hits.get(unit_id, set())
if not actual_hits:
errors.append(f"intentional-negative audit for {unit_id} has no detected hit")
continue
stale_hits = declared_hits - actual_hits
if stale_hits:
errors.append(
f"intentional-negative audit for {unit_id} has stale hit(s): "
+ ", ".join(sorted(stale_hits))
)
def validate_record(record: Mapping[str, Any]) -> list[str]:
"""Return all validation errors for one canonical record.
An empty list means the record is valid. The function never mutates the
supplied mapping and uses only Python's standard library.
"""
errors: list[str] = []
if not _is_json_object(record):
return ["record must be an object"]
for field in REQUIRED_RECORD_FIELDS:
if field not in record:
errors.append(f"missing required field: {field}")
for field in (
"record_id",
"schema_version",
"mixture_category",
"task_family",
"domain",
"split",
"source_group",
):
if field in record and not _is_nonempty_string(record.get(field)):
errors.append(f"{field} must be a non-empty string")
if _is_nonempty_string(record.get("record_id")) and not _ID_RE.fullmatch(
record["record_id"]
):
errors.append("record_id must not contain whitespace")
primitive = record.get("primitive")
if primitive not in PRIMITIVES:
errors.append("primitive must be one of: " + ", ".join(sorted(PRIMITIVES)))
language = record.get("language")
if not _is_list(language) or not language or not all(
_is_nonempty_string(item) for item in language
):
errors.append("language must be a non-empty array of language tags")
elif language[0] != "zh-TW":
errors.append("language[0] must be zh-TW")
if record.get("locale") != "zh-TW":
errors.append("locale must be zh-TW")
task_spec = _validate_task_spec(record.get("task_spec"), errors)
target = _validate_target(record.get("target"), task_spec, errors)
addressable_ids, negative_hits = _validate_inputs(record.get("inputs"), errors)
for field in ("component_targets", "presentation", "provenance", "quality"):
if field in record and not _is_json_object(record.get(field)):
errors.append(f"{field} must be an object")
if target is not None:
for path, reference in _collect_references(target):
if reference not in addressable_ids:
errors.append(f"{path} references unknown input ID: {reference}")
if task_spec is not None:
required_evidence = task_spec.get("required_evidence") is True
abstention_allowed = task_spec.get("abstention_allowed") is True
abstention = _is_abstention(target)
insufficient = _has_insufficient_evidence_marker(target)
if (abstention or insufficient) and not abstention_allowed:
errors.append("target abstains but task_spec.abstention_allowed is false")
if required_evidence and not _contains_nonempty_evidence(target):
if not (abstention_allowed and (abstention or insufficient)):
errors.append(
"task_spec.required_evidence is true but target has no evidence"
)
quality = record.get("quality")
if isinstance(quality, Mapping):
_validate_intentional_negative_audit(
quality,
negative_hits,
target,
addressable_ids,
errors,
)
return errors
def assert_valid_record(record: Mapping[str, Any]) -> None:
"""Raise :class:`RecordValidationError` unless *record* is valid."""
errors = validate_record(record)
if errors:
raise RecordValidationError(errors)
__all__ = [
"ACTION_TOOLS",
"ERROR_TYPES",
"PRIMITIVES",
"REQUIRED_RECORD_FIELDS",
"RecordValidationError",
"assert_valid_record",
"find_disallowed_terms",
"validate_record",
]