Download scripts/validate.py from TeskesLab/privacy-context-pairs: direct link, hf CLI and curl.
- Browser
- Download file 73.7 kB
-
https://huggingface.co/datasets/TeskesLab/privacy-context-pairs/resolve/main/scripts/validate.py
- Command line
-
hf download hf://datasets/TeskesLab/privacy-context-pairs/scripts/validate.py
-
curl -L -o validate.py https://huggingface.co/datasets/TeskesLab/privacy-context-pairs/resolve/main/scripts/validate.py
73.7 kB
| #!/usr/bin/env python3 | |
| """Independently validate every Privacy Context Pairs v1.0.0 construction record. | |
| Only the new, external report is written. This program uses the standard library, | |
| never imports the builder, and performs no network, model, or tokenizer calls. | |
| Passing establishes the frozen mechanical contract, not semantic privacy truth. | |
| """ | |
| import argparse | |
| import hashlib | |
| import itertools | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import traceback | |
| import unicodedata | |
| from collections import Counter, defaultdict | |
| from dataclasses import dataclass | |
| from datetime import date, datetime, timezone | |
| from pathlib import Path, PurePosixPath | |
| from urllib.parse import urlsplit | |
| NAME = "Privacy Context Pairs" | |
| VERSION = "1.0.0" | |
| PROTOCOL_SHA256 = "2319f14b79f755d9b7e3a0ed6ddf397fc16c1dac784f21b6dd6fee30956d80f1" | |
| SEED = "privacy-context-pairs-v1.0.0" | |
| TYPES = ( | |
| "person", | |
| "address", | |
| "email", | |
| "phone", | |
| "url", | |
| "date", | |
| "account_number", | |
| "secret", | |
| ) | |
| LANGUAGES = ("en", "pt-BR") | |
| SPLITS = ("train", "validation", "test") | |
| ROLES = ("alternative", "attribute") | |
| SIDES = ("left", "right") | |
| ORDINARY = ("a", "b") | |
| KINDS = ("role", "ordinary", "cue_side") | |
| CONTEXT_FIELDS = ( | |
| "attribute_cue", | |
| "alternative_cue", | |
| "control", | |
| "ordinary_a", | |
| "ordinary_b", | |
| ) | |
| SOURCE_FIELDS = ( | |
| "case_id", | |
| "family_id", | |
| "language", | |
| "target_type", | |
| "target", | |
| "scenario_domain", | |
| "attribute_reference", | |
| "alternative_reference", | |
| "attribute_cue", | |
| "alternative_cue", | |
| "control", | |
| "ordinary_a", | |
| "ordinary_b", | |
| "synthetic_target_notes", | |
| ) | |
| SOURCE_SCHEMA = dict.fromkeys(SOURCE_FIELDS, str) | |
| CASE_SCHEMA = {**SOURCE_SCHEMA, "split": str, "case_sha256": str} | |
| SPAN_SCHEMA = {"start": int, "end": int} | |
| TEXT_SCHEMA = { | |
| "id": str, | |
| "case_id": str, | |
| "family_id": str, | |
| "language": str, | |
| "target_type": str, | |
| "split": str, | |
| "scenario_domain": str, | |
| "text": str, | |
| "target": {"text": str, "start": int, "end": int}, | |
| "construction": { | |
| "role": str, | |
| "cue_side": str, | |
| "ordinary": str, | |
| "intended_reference": str, | |
| }, | |
| "slots": {"left": SPAN_SCHEMA, "right": SPAN_SCHEMA, "ordinary": SPAN_SCHEMA}, | |
| "provenance": { | |
| "source_type": str, | |
| "authoring": str, | |
| "privacy_annotation_status": str, | |
| "classifier_screening": str, | |
| }, | |
| "case_sha256": str, | |
| "text_sha256": str, | |
| "version": str, | |
| } | |
| PAIR_SCHEMA = { | |
| "id": str, | |
| "kind": str, | |
| "case_id": str, | |
| "family_id": str, | |
| "language": str, | |
| "target_type": str, | |
| "split": str, | |
| "base_id": str, | |
| "changed_id": str, | |
| "direction": str, | |
| } | |
| PROVENANCE = { | |
| "source_type": "synthetic", | |
| "authoring": "ai_assisted", | |
| "privacy_annotation_status": "not_human_adjudicated", | |
| "classifier_screening": "none", | |
| } | |
| TOTALS = {"records": 2048, "cases": 256, "families": 128, "contrasts": 3072} | |
| SPLIT_TOTALS = { | |
| "train": {"records": 1280, "cases": 160, "families": 80, "contrasts": 1920}, | |
| "validation": {"records": 256, "cases": 32, "families": 16, "contrasts": 384}, | |
| "test": {"records": 512, "cases": 64, "families": 32, "contrasts": 768}, | |
| } | |
| TYPE_TOTALS = {"records": 256, "cases": 32, "families": 16, "contrasts": 384} | |
| LANGUAGE_TOTALS = {"records": 1024, "cases": 128, "contrasts": 1536} | |
| INPUT_PATHS = tuple( | |
| sorted( | |
| [".construction/protocol.json", "scripts/build.py", "scripts/validate.py"] | |
| + [f"source/{kind}.json" for kind in TYPES] | |
| ) | |
| ) | |
| PAYLOAD_PATHS = tuple( | |
| sorted( | |
| [ | |
| f"{directory}/{split}.jsonl" | |
| for directory in ("data", "cases", "pairs") | |
| for split in SPLITS | |
| ] | |
| + ["stats.json"] | |
| ) | |
| ) | |
| RELEASE_PATHS = set(PAYLOAD_PATHS) | {"manifest.json", "manifest.sha256"} | |
| EXCLUDED = ( | |
| "May", | |
| "Amber", | |
| "Rosa", | |
| "Violeta", | |
| "2001-02-03", | |
| "1987-06-14", | |
| "2025550183", | |
| "24681013570", | |
| ) | |
| EN_MONTHS = ( | |
| "january", | |
| "february", | |
| "march", | |
| "april", | |
| "may", | |
| "june", | |
| "july", | |
| "august", | |
| "september", | |
| "october", | |
| "november", | |
| "december", | |
| ) | |
| PT_MONTHS = ( | |
| "janeiro", | |
| "fevereiro", | |
| "março", | |
| "abril", | |
| "maio", | |
| "junho", | |
| "julho", | |
| "agosto", | |
| "setembro", | |
| "outubro", | |
| "novembro", | |
| "dezembro", | |
| ) | |
| LIMITATIONS = [ | |
| "Structural validation cannot certify fluent language, semantic scenario distinctness, bilingual equivalence, intended referents, or ordinary-sentence relevance.", | |
| "Construction roles and references are AI-assisted authoring intentions, not human annotation, human privacy adjudication, privacy gold, masking decisions, or expected classifier predictions.", | |
| "Mechanical category checks establish permitted string forms and reserved-domain/phone-pool constraints; they cannot certify that a name, date, account-like string, address, or credential-like fixture never coincides with real data or has never been issued.", | |
| "Synthetic provenance, absence of copied credentials or recovery mnemonics, no consultation of prior outputs or external records, and no model-guided selection are authoring-process declarations, not facts provable from these files.", | |
| "No tokenizer was run; tokenizer matching, token lengths, token positions, and model-specific comparability are not certified.", | |
| "No classifier or model was run; this is not classifier screening or evaluation and does not establish policy exclusion for alternative contexts.", | |
| "This structured, family-disjoint construction is not representative sampling, a natural corpus, a template-disjoint corpus, or proof of statistical independence or generalizability.", | |
| "This validator does not establish publication approval, human construction review, license ownership, or reproducible rebuild execution; those require separately retained evidence and authorization.", | |
| ] | |
| def digest(blob): | |
| return hashlib.sha256(blob).hexdigest() | |
| def compact(value): | |
| return json.dumps( | |
| value, | |
| sort_keys=True, | |
| ensure_ascii=False, | |
| separators=(",", ":"), | |
| allow_nan=False, | |
| ) | |
| def pretty_bytes(value): | |
| return ( | |
| json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) | |
| + "\n" | |
| ).encode("utf-8") | |
| def normalized(value): | |
| return unicodedata.normalize("NFC", unicodedata.normalize("NFC", value).casefold()) | |
| def one_line(value): | |
| return ( | |
| bool(value) | |
| and value == value.strip() | |
| and not any( | |
| unicodedata.category(char) in {"Cc", "Cs", "Zl", "Zp"} for char in value | |
| ) | |
| ) | |
| def phone_digits(value): | |
| digits = "".join(char for char in value if "0" <= char <= "9") | |
| return digits[1:] if len(digits) == 11 and digits.startswith("1") else digits | |
| def target_keys(kind, value): | |
| keys = {("literal", normalized(value))} | |
| if kind == "phone": | |
| keys.add(("numeric", phone_digits(value))) | |
| elif kind == "account_number" and re.fullmatch(r"[0-9\s()./+-]+", value): | |
| keys.add( | |
| ( | |
| "numeric", | |
| "".join(char for char in value if char.isascii() and char.isdigit()), | |
| ) | |
| ) | |
| return keys | |
| def occurrences(haystack, needle): | |
| if not needle: | |
| return 0 | |
| return sum(1 for _ in re.finditer("(?=" + re.escape(needle) + ")", haystack)) | |
| def example_host(host): | |
| if not isinstance(host, str) or not host or len(host) > 253: | |
| return False | |
| host = host.lower() | |
| if any( | |
| not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label) | |
| for label in host.split(".") | |
| ): | |
| return False | |
| return any( | |
| host == root or host.endswith("." + root) | |
| for root in ("example.com", "example.net", "example.org") | |
| ) | |
| def calendar_date(value, language): | |
| """Parse explicitly unambiguous formats without locale or third-party parsers.""" | |
| match = re.fullmatch(r"([0-9]{4})([-/.])([0-9]{2})\2([0-9]{2})", value) | |
| if match: | |
| return date(int(match[1]), int(match[3]), int(match[4])) | |
| folded = normalized(value) | |
| months = EN_MONTHS if language == "en" else PT_MONTHS | |
| month_pattern = "(" + "|".join(months) + ")" | |
| if language == "en": | |
| match = re.fullmatch(month_pattern + r" ([0-9]{1,2}), ([0-9]{4})", folded) | |
| if match: | |
| return date(int(match[3]), months.index(match[1]) + 1, int(match[2])) | |
| match = re.fullmatch(r"([0-9]{1,2}) " + month_pattern + r" ([0-9]{4})", folded) | |
| else: | |
| match = re.fullmatch( | |
| r"([0-9]{1,2}) de " + month_pattern + r" de ([0-9]{4})", folded | |
| ) | |
| if match: | |
| return date(int(match[3]), months.index(match[2]) + 1, int(match[1])) | |
| raise ValueError( | |
| "use YYYY-MM-DD (or another year-first numeric format), a full English month form, or D de mês de YYYY" | |
| ) | |
| def no_duplicate_keys(pairs): | |
| result = {} | |
| for key, value in pairs: | |
| if key in result: | |
| raise ValueError(f"duplicate JSON object key {key!r}") | |
| result[key] = value | |
| return result | |
| def reject_constant(value): | |
| raise ValueError(f"non-JSON numeric constant {value}") | |
| def decode_json(text): | |
| return json.loads( | |
| text, object_pairs_hook=no_duplicate_keys, parse_constant=reject_constant | |
| ) | |
| def preview(value): | |
| rendered = repr(value) | |
| return rendered if len(rendered) <= 220 else rendered[:217] + "..." | |
| class Record: | |
| value: object | |
| split: str | |
| location: str | |
| class Validator: | |
| def __init__(self, root, release, producer): | |
| self.root = root | |
| self.release = release | |
| self.producer = producer | |
| self.errors = [] | |
| self.checks = {} | |
| self.inputs = {} | |
| self.payloads = {} | |
| self.sources = {} | |
| self.records = {"cases": [], "data": [], "pairs": []} | |
| self.expected = {"cases": {}, "data": {}, "pairs": {}} | |
| self.split_for = {} | |
| self.safety = {kind: [] for kind in TYPES} | |
| self.observed = {} | |
| self.manifest_blob = None | |
| def check(self, condition, check, location, message): | |
| summary = self.checks.setdefault(check, {"evaluated": 0, "failed": 0}) | |
| summary["evaluated"] += 1 | |
| if not condition: | |
| summary["failed"] += 1 | |
| self.errors.append( | |
| {"check": check, "location": location, "message": message} | |
| ) | |
| return bool(condition) | |
| def equal(self, actual, expected, location, check="exact_values"): | |
| """Compare all fields strictly, including bool versus int and unexpected keys.""" | |
| if type(actual) is not type(expected): | |
| return self.check( | |
| False, | |
| check, | |
| location, | |
| f"expected {type(expected).__name__}, got {type(actual).__name__}: {preview(actual)}", | |
| ) | |
| valid = True | |
| if isinstance(expected, dict): | |
| valid &= self.check( | |
| set(actual) == set(expected), | |
| check, | |
| location, | |
| f"keys differ: missing={sorted(set(expected) - set(actual))}, extra={sorted(set(actual) - set(expected))}", | |
| ) | |
| for key in sorted(set(actual) & set(expected)): | |
| valid &= self.equal( | |
| actual[key], expected[key], f"{location}.{key}", check | |
| ) | |
| elif isinstance(expected, list): | |
| valid &= self.check( | |
| len(actual) == len(expected), | |
| check, | |
| location, | |
| f"expected {len(expected)} entries, got {len(actual)}", | |
| ) | |
| for index, (left, right) in enumerate(zip(actual, expected)): | |
| valid &= self.equal(left, right, f"{location}[{index}]", check) | |
| else: | |
| valid &= self.check( | |
| actual == expected, | |
| check, | |
| location, | |
| f"expected {preview(expected)}, got {preview(actual)}", | |
| ) | |
| return bool(valid) | |
| def shape(self, value, schema, location): | |
| if isinstance(schema, dict): | |
| if not self.check( | |
| type(value) is dict, "schema", location, "expected a JSON object" | |
| ): | |
| return False | |
| valid = self.check( | |
| set(value) == set(schema), | |
| "schema", | |
| location, | |
| f"keys differ: missing={sorted(set(schema) - set(value))}, extra={sorted(set(value) - set(schema))}", | |
| ) | |
| for key in sorted(set(value) & set(schema)): | |
| valid &= self.shape(value[key], schema[key], f"{location}.{key}") | |
| return bool(valid) | |
| valid = self.check( | |
| type(value) is schema, | |
| "schema", | |
| location, | |
| f"expected {schema.__name__}, got {type(value).__name__}", | |
| ) | |
| if valid and schema is str: | |
| valid &= self.check( | |
| bool(value.strip()), "schema", location, "string must be nonempty" | |
| ) | |
| valid &= self.check( | |
| not any(unicodedata.category(char) == "Cs" for char in value), | |
| "unicode", | |
| location, | |
| "unpaired Unicode surrogate is not valid UTF-8 corpus content", | |
| ) | |
| return bool(valid) | |
| def read_blob(self, scope, relative, check): | |
| path = scope / relative | |
| try: | |
| resolved = path.resolve(strict=True) | |
| if not self.check( | |
| resolved.is_relative_to(scope), | |
| check, | |
| relative, | |
| "path resolves outside its declared root", | |
| ): | |
| return None | |
| if not self.check( | |
| resolved.is_file(), check, relative, "expected a regular file" | |
| ): | |
| return None | |
| return resolved.read_bytes() | |
| except (OSError, RuntimeError, ValueError) as exc: | |
| self.check(False, check, relative, f"cannot read file: {exc}") | |
| return None | |
| def parse(self, blob, location): | |
| if blob is None: | |
| return None | |
| try: | |
| return decode_json(blob.decode("utf-8")) | |
| except (UnicodeError, ValueError, RecursionError) as exc: | |
| self.check(False, "json_parse", location, f"invalid UTF-8 JSON: {exc}") | |
| return None | |
| def inventories(self): | |
| self.check( | |
| self.root.is_dir(), | |
| "input_inventory", | |
| str(self.root), | |
| "root must be an existing directory", | |
| ) | |
| self.check( | |
| self.release.is_dir(), | |
| "release_inventory", | |
| str(self.release), | |
| "release must be an existing directory", | |
| ) | |
| source_dir = self.root / "source" | |
| try: | |
| resolved_source = source_dir.resolve(strict=True) | |
| if self.check( | |
| resolved_source.is_relative_to(self.root), | |
| "input_inventory", | |
| "source", | |
| "source directory escapes root", | |
| ): | |
| names = {entry.name for entry in source_dir.iterdir()} | |
| self.equal( | |
| sorted(names), | |
| sorted(f"{kind}.json" for kind in TYPES), | |
| "source", | |
| "input_inventory", | |
| ) | |
| except (OSError, RuntimeError) as exc: | |
| self.check( | |
| False, | |
| "input_inventory", | |
| "source", | |
| f"cannot enumerate source directory: {exc}", | |
| ) | |
| found = set() | |
| def walk_error(exc): | |
| self.check( | |
| False, | |
| "release_inventory", | |
| str(self.release), | |
| f"cannot enumerate release: {exc}", | |
| ) | |
| if self.release.is_dir(): | |
| for directory, dirs, files in os.walk( | |
| self.release, followlinks=False, onerror=walk_error | |
| ): | |
| base = Path(directory) | |
| for name in dirs: | |
| path = base / name | |
| relative = path.relative_to(self.release).as_posix() | |
| self.check( | |
| not path.is_symlink(), | |
| "release_inventory", | |
| relative, | |
| "release directories must not be symlinks", | |
| ) | |
| self.check( | |
| relative in {"cases", "data", "pairs"}, | |
| "release_inventory", | |
| relative, | |
| "unexpected release directory", | |
| ) | |
| for name in files: | |
| path = base / name | |
| relative = path.relative_to(self.release).as_posix() | |
| found.add(relative) | |
| self.check( | |
| not path.is_symlink(), | |
| "release_inventory", | |
| relative, | |
| "release files must not be symlinks", | |
| ) | |
| self.equal(sorted(found), sorted(RELEASE_PATHS), "release", "release_inventory") | |
| for relative in INPUT_PATHS: | |
| blob = self.read_blob(self.root, relative, "input_files") | |
| if blob is not None: | |
| self.inputs[relative] = blob | |
| for relative in PAYLOAD_PATHS: | |
| blob = self.read_blob(self.release, relative, "release_files") | |
| if blob is not None: | |
| self.payloads[relative] = blob | |
| protocol = self.inputs.get(".construction/protocol.json") | |
| if protocol is not None: | |
| self.equal( | |
| digest(protocol), | |
| PROTOCOL_SHA256, | |
| ".construction/protocol.json.sha256", | |
| "frozen_protocol", | |
| ) | |
| self.check( | |
| type(self.parse(protocol, ".construction/protocol.json")) is dict, | |
| "frozen_protocol", | |
| ".construction/protocol.json", | |
| "protocol must be a JSON object", | |
| ) | |
| validator_blob = self.inputs.get("scripts/validate.py") | |
| if validator_blob is not None: | |
| self.equal( | |
| digest(validator_blob), | |
| self.producer["sha256"], | |
| "scripts/validate.py.sha256", | |
| "producer_identity", | |
| ) | |
| def category(self, case, location): | |
| kind, target, language = case["target_type"], case["target"], case["language"] | |
| item = { | |
| "case_id": case["case_id"], | |
| "family_id": case["family_id"], | |
| "target": target, | |
| "normalized_target": normalized(target), | |
| "synthetic_target_notes": case["synthetic_target_notes"], | |
| } | |
| if kind not in TYPES: | |
| return | |
| if kind == "person": | |
| self.check( | |
| any(char.isalpha() for char in target) | |
| and all( | |
| unicodedata.category(char)[0] in {"L", "M"} or char in " .-'’" | |
| for char in target | |
| ), | |
| "person_form", | |
| location, | |
| "person target must be a name-like letter string, not an identifier or record", | |
| ) | |
| elif kind == "address": | |
| marker = "Example" if language == "en" else "Exemplo" | |
| item["required_fictional_marker"] = marker | |
| self.check( | |
| marker.casefold() in target.casefold(), | |
| "address_safety", | |
| location, | |
| f"invented address must contain {marker!r}", | |
| ) | |
| elif kind == "email": | |
| match = re.fullmatch( | |
| r"([A-Za-z0-9!#$%&'*+/=?^_`{|}~.-]+)@([^@\s]+)", target | |
| ) | |
| host = match[2] if match else "" | |
| item["host"] = host.lower() | |
| self.check( | |
| bool(match) | |
| and not match[1].startswith(".") | |
| and not match[1].endswith(".") | |
| and ".." not in match[1] | |
| and example_host(host), | |
| "email_safety", | |
| location, | |
| "email must have a valid unquoted local part and an example.com/.net/.org host or subdomain", | |
| ) | |
| elif kind == "phone": | |
| canonical = phone_digits(target) | |
| item["canonical_digits"] = canonical | |
| self.check( | |
| bool(re.fullmatch(r"[+0-9(). /-]+", target)) | |
| and bool(re.fullmatch(r"20255501[0-9]{2}", canonical)), | |
| "phone_safety", | |
| location, | |
| "phone must contain only permitted formatting and 20255501xx, optionally prefixed by country digit 1", | |
| ) | |
| self.check( | |
| canonical != "2025550183", | |
| "excluded_targets", | |
| location, | |
| "earlier phone fixture is excluded in every punctuation form", | |
| ) | |
| elif kind == "url": | |
| try: | |
| parsed = urlsplit(target) | |
| host = parsed.hostname or "" | |
| item["host"] = host.lower() | |
| port = parsed.port | |
| self.check( | |
| parsed.scheme == "https" | |
| and example_host(host) | |
| and parsed.username is None | |
| and parsed.password is None | |
| and not any(char.isspace() or ord(char) < 32 for char in target) | |
| and "\\" not in target, | |
| "url_safety", | |
| location, | |
| "URL must use https on an example.com/.net/.org host or subdomain, without userinfo, backslashes, or whitespace", | |
| ) | |
| if port is not None: | |
| self.check( | |
| 0 < port <= 65535, | |
| "url_safety", | |
| location, | |
| "URL port must be between 1 and 65535", | |
| ) | |
| except ValueError as exc: | |
| self.check(False, "url_safety", location, f"invalid URL: {exc}") | |
| elif kind == "date": | |
| try: | |
| parsed_date = calendar_date(target, language) | |
| item["iso_date"] = parsed_date.isoformat() | |
| self.check( | |
| parsed_date.isoformat() not in {"2001-02-03", "1987-06-14"}, | |
| "excluded_targets", | |
| location, | |
| "earlier calendar date is excluded in every supported display form", | |
| ) | |
| except ValueError as exc: | |
| self.check( | |
| False, | |
| "date_safety", | |
| location, | |
| f"invalid or ambiguous calendar date: {exc}", | |
| ) | |
| elif kind == "account_number": | |
| self.check( | |
| any("0" <= char <= "9" for char in target) | |
| and bool(re.fullmatch(r"[A-Za-z0-9 ._/#()+-]+", target)), | |
| "account_form", | |
| location, | |
| "account-like fixture must contain ASCII digits and only letters or ordinary identifier separators", | |
| ) | |
| item["numeric_format_normalization"] = sorted( | |
| value for key, value in target_keys(kind, target) if key == "numeric" | |
| ) | |
| self.check( | |
| not any( | |
| value == "24681013570" | |
| for key, value in target_keys(kind, target) | |
| if key == "numeric" | |
| ), | |
| "excluded_targets", | |
| location, | |
| "earlier numeric account fixture is excluded in every punctuation form", | |
| ) | |
| elif kind == "secret": | |
| item["ascii_length"] = len(target) | |
| self.check( | |
| 12 <= len(target) <= 64 | |
| and all(32 <= ord(char) <= 126 for char in target), | |
| "secret_safety", | |
| location, | |
| "credential-like fixture must be 12–64 printable ASCII characters", | |
| ) | |
| self.check( | |
| "-----BEGIN" not in target.upper() | |
| and "PRIVATE KEY" not in target.upper(), | |
| "secret_safety", | |
| location, | |
| "private-key block markers are forbidden", | |
| ) | |
| self.safety[kind].append(item) | |
| def source_cases(self): | |
| family_cases = defaultdict(list) | |
| target_owners = defaultdict(set) | |
| tuple_owners = defaultdict(set) | |
| excluded = {normalized(value) for value in EXCLUDED} | |
| for kind in TYPES: | |
| relative = f"source/{kind}.json" | |
| values = self.parse(self.inputs.get(relative), relative) | |
| if not self.check( | |
| type(values) is list, | |
| "source_inventory", | |
| relative, | |
| "expected a source JSON array", | |
| ): | |
| continue | |
| self.equal(len(values), 32, relative + ".length", "source_inventory") | |
| expected_ids = { | |
| f"{kind}-{number:02d}-{language}" | |
| for number in range(1, 17) | |
| for language in LANGUAGES | |
| } | |
| observed_ids = [] | |
| for index, case in enumerate(values): | |
| location = f"{relative}[{index}]" | |
| if not self.shape(case, SOURCE_SCHEMA, location): | |
| continue | |
| case_id, family, language = ( | |
| case["case_id"], | |
| case["family_id"], | |
| case["language"], | |
| ) | |
| observed_ids.append(case_id) | |
| identity_ok = self.check( | |
| case["target_type"] == kind, | |
| "source_identity", | |
| location, | |
| f"target_type must be {kind!r}", | |
| ) | |
| identity_ok &= self.check( | |
| language in LANGUAGES, | |
| "source_identity", | |
| location, | |
| f"unsupported language {language!r}", | |
| ) | |
| identity_ok &= self.check( | |
| family in {f"{kind}-{number:02d}" for number in range(1, 17)}, | |
| "source_identity", | |
| location, | |
| f"invalid family_id {family!r}", | |
| ) | |
| identity_ok &= self.check( | |
| case_id == f"{family}-{language}", | |
| "source_identity", | |
| location, | |
| "case_id must be family_id + '-' + language", | |
| ) | |
| self.check( | |
| bool( | |
| re.fullmatch( | |
| r"[a-z][a-z0-9]*(?:_[a-z0-9]+)*", case["scenario_domain"] | |
| ) | |
| ), | |
| "source_text_rules", | |
| location + ".scenario_domain", | |
| "expected an English ASCII snake_case domain", | |
| ) | |
| target = case["target"] | |
| self.check( | |
| one_line(target), | |
| "source_text_rules", | |
| location + ".target", | |
| "target must be a nonempty single line without outer whitespace or control characters", | |
| ) | |
| self.check( | |
| normalized(target) not in excluded, | |
| "excluded_targets", | |
| location + ".target", | |
| "target reuses an excluded earlier fixture", | |
| ) | |
| for field in CONTEXT_FIELDS: | |
| sentence = case[field] | |
| self.check( | |
| one_line(sentence) and sentence.endswith("."), | |
| "source_text_rules", | |
| location + "." + field, | |
| "context slot must be a single-line sentence ending in a period, with no outer whitespace", | |
| ) | |
| self.check( | |
| normalized(target) not in normalized(sentence), | |
| "target_exclusivity", | |
| location + "." + field, | |
| f"context contains target {target!r} under NFC/casefold, including substrings", | |
| ) | |
| self.check( | |
| len( | |
| { | |
| normalized(case[field]) | |
| for field in ("attribute_cue", "alternative_cue", "control") | |
| } | |
| ) | |
| == 3, | |
| "source_distinctions", | |
| location, | |
| "attribute cue, alternative cue, and control must differ", | |
| ) | |
| self.check( | |
| normalized(case["ordinary_a"]) != normalized(case["ordinary_b"]), | |
| "source_distinctions", | |
| location, | |
| "ordinary_a and ordinary_b must differ", | |
| ) | |
| for cue in ("attribute_cue", "alternative_cue"): | |
| for ordinary in ("ordinary_a", "ordinary_b"): | |
| self.check( | |
| normalized(case[ordinary]) not in normalized(case[cue]), | |
| "source_distinctions", | |
| location + "." + cue, | |
| f"role cue must not contain the entire {ordinary} sentence", | |
| ) | |
| self.category(case, location + ".target") | |
| if not identity_ok: | |
| continue | |
| self.check( | |
| case_id not in self.sources, | |
| "source_uniqueness", | |
| location, | |
| f"duplicate case_id {case_id!r}", | |
| ) | |
| if case_id not in self.sources: | |
| self.sources[case_id] = case | |
| family_cases[family].append(case) | |
| for key in target_keys(kind, target): | |
| target_owners[key].add(family) | |
| tuple_owners[ | |
| tuple(normalized(case[field]) for field in CONTEXT_FIELDS) | |
| ].add(family) | |
| self.equal( | |
| sorted(observed_ids), | |
| sorted(expected_ids), | |
| relative + ".case_ids", | |
| "source_inventory", | |
| ) | |
| self.equal(len(self.sources), 256, "source.cases", "source_inventory") | |
| self.equal(len(family_cases), 128, "source.families", "source_inventory") | |
| for family, cases in sorted(family_cases.items()): | |
| self.equal( | |
| sorted(case["language"] for case in cases), | |
| sorted(LANGUAGES), | |
| family + ".languages", | |
| "bilingual_families", | |
| ) | |
| self.check( | |
| len({case["scenario_domain"] for case in cases}) == 1, | |
| "bilingual_families", | |
| family, | |
| "paired languages must share scenario_domain", | |
| ) | |
| for key, families in sorted(target_owners.items()): | |
| self.check( | |
| len(families) == 1, | |
| "source_target_reuse", | |
| preview(key), | |
| f"target reused by different families: {sorted(families)}", | |
| ) | |
| for families in tuple_owners.values(): | |
| self.check( | |
| len(families) == 1, | |
| "source_scenario_duplicates", | |
| "source.context_tuples", | |
| f"distinct families share an identical NFC/casefold cue/control/ordinary tuple: {sorted(families)}", | |
| ) | |
| for kind in TYPES: | |
| families = [f"{kind}-{number:02d}" for number in range(1, 17)] | |
| ranked = sorted( | |
| families, key=lambda family: digest(f"{SEED}|{family}".encode("utf-8")) | |
| ) | |
| for rank, family in enumerate(ranked): | |
| self.split_for[family] = ( | |
| "train" if rank < 10 else "validation" if rank < 12 else "test" | |
| ) | |
| for key, families in sorted(target_owners.items()): | |
| splits = {self.split_for[family] for family in families} | |
| self.check( | |
| len(splits) == 1, | |
| "source_target_leakage", | |
| preview(key), | |
| f"normalized target crosses splits: {sorted(splits)}; families={sorted(families)}", | |
| ) | |
| def reconstruct(self): | |
| for case_id, source in sorted(self.sources.items()): | |
| split = self.split_for[source["family_id"]] | |
| case_hash = digest(compact(source).encode("utf-8")) | |
| self.expected["cases"][case_id] = { | |
| **source, | |
| "split": split, | |
| "case_sha256": case_hash, | |
| } | |
| shared = { | |
| field: source[field] | |
| for field in ( | |
| "case_id", | |
| "family_id", | |
| "language", | |
| "target_type", | |
| "scenario_domain", | |
| ) | |
| } | |
| shared["split"] = split | |
| cell_ids = {} | |
| for role, side, ordinary in itertools.product(ROLES, SIDES, ORDINARY): | |
| active = source[role + "_cue"] | |
| left, right = ( | |
| (active, source["control"]) | |
| if side == "left" | |
| else (source["control"], active) | |
| ) | |
| ending = source["ordinary_" + ordinary] | |
| target = source["target"] | |
| start = len(left) + 2 | |
| end = start + len(target) | |
| right_start = end + 3 | |
| ordinary_start = right_start + len(right) + 2 | |
| text = "\n\n".join((left, target + ".", right, ending)) | |
| identifier = f"pcp-v1-{case_id}-{role}-{side}-{ordinary}" | |
| cell_ids[role, side, ordinary] = identifier | |
| self.expected["data"][identifier] = { | |
| **shared, | |
| "id": identifier, | |
| "text": text, | |
| "target": {"text": target, "start": start, "end": end}, | |
| "construction": { | |
| "role": role, | |
| "cue_side": side, | |
| "ordinary": ordinary, | |
| "intended_reference": source[role + "_reference"], | |
| }, | |
| "slots": { | |
| "left": {"start": 0, "end": len(left)}, | |
| "right": { | |
| "start": right_start, | |
| "end": right_start + len(right), | |
| }, | |
| "ordinary": {"start": ordinary_start, "end": len(text)}, | |
| }, | |
| "provenance": dict(PROVENANCE), | |
| "case_sha256": case_hash, | |
| "text_sha256": digest(text.encode("utf-8")), | |
| "version": VERSION, | |
| } | |
| pair_shared = { | |
| key: value for key, value in shared.items() if key != "scenario_domain" | |
| } | |
| specs = [] | |
| for side, ordinary in itertools.product(SIDES, ORDINARY): | |
| specs.append( | |
| ( | |
| f"{case_id}:role:{side}:{ordinary}", | |
| "role", | |
| ("alternative", side, ordinary), | |
| ("attribute", side, ordinary), | |
| "attribute - alternative", | |
| ) | |
| ) | |
| for role, side in itertools.product(ROLES, SIDES): | |
| specs.append( | |
| ( | |
| f"{case_id}:ordinary:{role}:{side}", | |
| "ordinary", | |
| (role, side, "a"), | |
| (role, side, "b"), | |
| "b - a", | |
| ) | |
| ) | |
| for role, ordinary in itertools.product(ROLES, ORDINARY): | |
| specs.append( | |
| ( | |
| f"{case_id}:cue_side:{role}:{ordinary}", | |
| "cue_side", | |
| (role, "left", ordinary), | |
| (role, "right", ordinary), | |
| "right - left", | |
| ) | |
| ) | |
| for identifier, kind, base, changed, direction in specs: | |
| self.expected["pairs"][identifier] = { | |
| **pair_shared, | |
| "id": identifier, | |
| "kind": kind, | |
| "base_id": cell_ids[base], | |
| "changed_id": cell_ids[changed], | |
| "direction": direction, | |
| } | |
| for directory, count in (("cases", 256), ("data", 2048), ("pairs", 3072)): | |
| self.equal( | |
| len(self.expected[directory]), | |
| count, | |
| "reconstructed." + directory, | |
| "complete_reconstruction", | |
| ) | |
| def load_records(self): | |
| schemas = {"cases": CASE_SCHEMA, "data": TEXT_SCHEMA, "pairs": PAIR_SCHEMA} | |
| for directory in ("cases", "data", "pairs"): | |
| key = "case_id" if directory == "cases" else "id" | |
| seen = {} | |
| for split in SPLITS: | |
| relative = f"{directory}/{split}.jsonl" | |
| blob = self.payloads.get(relative) | |
| if blob is None: | |
| continue | |
| self.check( | |
| bool(blob) and blob.endswith(b"\n") and b"\r" not in blob, | |
| "jsonl_encoding", | |
| relative, | |
| "JSONL must be nonempty UTF-8 with LF after every row and no CR bytes", | |
| ) | |
| try: | |
| text = blob.decode("utf-8") | |
| except UnicodeError as exc: | |
| self.check( | |
| False, "jsonl_encoding", relative, f"invalid UTF-8: {exc}" | |
| ) | |
| continue | |
| lines = text.split("\n") | |
| if lines[-1] == "": | |
| lines.pop() | |
| identifiers = [] | |
| for number, line in enumerate(lines, 1): | |
| location = f"{relative}:{number}" | |
| try: | |
| value = decode_json(line) | |
| except (ValueError, RecursionError) as exc: | |
| self.check( | |
| False, "jsonl_parse", location, f"invalid JSON row: {exc}" | |
| ) | |
| continue | |
| record = Record(value, split, location) | |
| self.records[directory].append(record) | |
| self.shape(value, schemas[directory], location) | |
| try: | |
| self.equal( | |
| line, compact(value), location, "jsonl_canonical_bytes" | |
| ) | |
| except (ValueError, UnicodeError) as exc: | |
| self.check( | |
| False, | |
| "jsonl_canonical_bytes", | |
| location, | |
| f"cannot serialize canonical UTF-8: {exc}", | |
| ) | |
| if not isinstance(value, dict): | |
| continue | |
| self.equal( | |
| value.get("split"), | |
| split, | |
| location + ".split", | |
| "file_split_membership", | |
| ) | |
| identifier = value.get(key) | |
| if not self.check( | |
| type(identifier) is str and bool(identifier), | |
| "record_identity", | |
| location, | |
| f"missing or invalid {key}", | |
| ): | |
| continue | |
| identifiers.append(identifier) | |
| self.check( | |
| identifier not in seen, | |
| "record_uniqueness", | |
| location, | |
| f"duplicate {key} {identifier!r}; first seen at {seen.get(identifier)}", | |
| ) | |
| seen.setdefault(identifier, location) | |
| expected = self.expected[directory].get(identifier) | |
| if self.check( | |
| expected is not None, | |
| "record_identity", | |
| location, | |
| f"unexpected {key} {identifier!r}", | |
| ): | |
| self.equal(value, expected, location, "reconstructed_records") | |
| self.equal(identifiers, sorted(identifiers), relative, "record_sorting") | |
| expected_ids = sorted( | |
| identifier | |
| for identifier, row in self.expected[directory].items() | |
| if row["split"] == split | |
| ) | |
| self.equal( | |
| sorted(identifiers), | |
| expected_ids, | |
| relative + ".identifiers", | |
| "complete_record_inventory", | |
| ) | |
| self.equal( | |
| sorted(seen), | |
| sorted(self.expected[directory]), | |
| directory + ".identifiers", | |
| "complete_record_inventory", | |
| ) | |
| def text_invariants(self): | |
| texts = {} | |
| cells = defaultdict(Counter) | |
| targets = defaultdict(lambda: {"families": set(), "splits": set()}) | |
| for record in self.records["data"]: | |
| row, location = record.value, record.location | |
| if not isinstance(row, dict): | |
| continue | |
| text, target, slots, construction = ( | |
| row.get(key) for key in ("text", "target", "slots", "construction") | |
| ) | |
| if not isinstance(text, str): | |
| continue | |
| self.check( | |
| text not in texts, | |
| "text_uniqueness", | |
| location, | |
| f"duplicate text; first seen at {texts.get(text)}", | |
| ) | |
| texts.setdefault(text, location) | |
| try: | |
| self.equal( | |
| row.get("text_sha256"), | |
| digest(text.encode("utf-8")), | |
| location + ".text_sha256", | |
| "text_hashes", | |
| ) | |
| except UnicodeError as exc: | |
| self.check( | |
| False, | |
| "text_hashes", | |
| location, | |
| f"text is not encodable as UTF-8: {exc}", | |
| ) | |
| if isinstance(target, dict) and isinstance(target.get("text"), str): | |
| literal = target["text"] | |
| self.check( | |
| one_line(literal), | |
| "target_spans", | |
| location, | |
| "target text must be a nonempty single line without outer whitespace", | |
| ) | |
| self.equal( | |
| occurrences(text, literal), | |
| 1, | |
| location + ".literal_occurrences", | |
| "target_exclusivity", | |
| ) | |
| self.equal( | |
| occurrences(normalized(text), normalized(literal)), | |
| 1, | |
| location + ".normalized_occurrences", | |
| "target_exclusivity", | |
| ) | |
| start, end = target.get("start"), target.get("end") | |
| if self.check( | |
| type(start) is int | |
| and type(end) is int | |
| and 0 <= start < end <= len(text), | |
| "target_spans", | |
| location, | |
| "target start/end must be valid nonempty Unicode codepoint offsets", | |
| ): | |
| self.equal( | |
| text[start:end], | |
| literal, | |
| location + ".target_slice", | |
| "target_spans", | |
| ) | |
| if isinstance(slots, dict): | |
| expected_boundaries = { | |
| "left": (0, start - 2), | |
| "right": (end + 3, None), | |
| "ordinary": (None, len(text)), | |
| } | |
| valid_slots = {} | |
| for name in ("left", "right", "ordinary"): | |
| span = slots.get(name) | |
| if not isinstance(span, dict): | |
| continue | |
| begin, finish = span.get("start"), span.get("end") | |
| if self.check( | |
| type(begin) is int | |
| and type(finish) is int | |
| and 0 <= begin < finish <= len(text), | |
| "slot_spans", | |
| location + ".slots." + name, | |
| "slot must be a nonempty valid Unicode codepoint span", | |
| ): | |
| valid_slots[name] = (begin, finish) | |
| self.check( | |
| one_line(text[begin:finish]) | |
| and text[begin:finish].endswith("."), | |
| "slot_spans", | |
| location + ".slots." + name, | |
| "span must extract one complete period-terminated sentence", | |
| ) | |
| first, last = expected_boundaries[name] | |
| if first is not None: | |
| self.equal( | |
| begin, | |
| first, | |
| location + ".slots." + name + ".start", | |
| "carrier", | |
| ) | |
| if last is not None: | |
| self.equal( | |
| finish, | |
| last, | |
| location + ".slots." + name + ".end", | |
| "carrier", | |
| ) | |
| self.equal( | |
| text[start - 2 : start], | |
| "\n\n", | |
| location + ".before_target", | |
| "carrier", | |
| ) | |
| self.equal( | |
| text[end : end + 3], | |
| ".\n\n", | |
| location + ".after_target", | |
| "carrier", | |
| ) | |
| if "right" in valid_slots and "ordinary" in valid_slots: | |
| right_end = valid_slots["right"][1] | |
| ordinary_start = valid_slots["ordinary"][0] | |
| self.equal( | |
| ordinary_start, | |
| right_end + 2, | |
| location + ".ordinary_start", | |
| "carrier", | |
| ) | |
| self.equal( | |
| text[right_end:ordinary_start], | |
| "\n\n", | |
| location + ".before_ordinary", | |
| "carrier", | |
| ) | |
| family, kind = row.get("family_id"), row.get("target_type") | |
| if isinstance(family, str) and isinstance(kind, str): | |
| for key in target_keys(kind, literal): | |
| targets[key]["families"].add(family) | |
| targets[key]["splits"].add(record.split) | |
| case_id = row.get("case_id") | |
| if isinstance(construction, dict) and isinstance(case_id, str): | |
| factors = tuple( | |
| construction.get(key) for key in ("role", "cue_side", "ordinary") | |
| ) | |
| if all(isinstance(value, str) for value in factors): | |
| cells[case_id][factors] += 1 | |
| if isinstance(case_id, str) and case_id in self.sources: | |
| expected_hash = digest(compact(self.sources[case_id]).encode("utf-8")) | |
| self.equal( | |
| row.get("case_sha256"), | |
| expected_hash, | |
| location + ".case_sha256", | |
| "case_hashes", | |
| ) | |
| self.equal( | |
| row.get("provenance"), | |
| PROVENANCE, | |
| location + ".provenance", | |
| "construction_provenance", | |
| ) | |
| self.equal( | |
| row.get("version"), VERSION, location + ".version", "release_version" | |
| ) | |
| grid = Counter({cell: 1 for cell in itertools.product(ROLES, SIDES, ORDINARY)}) | |
| for case_id in sorted(set(self.sources) | set(cells)): | |
| self.equal( | |
| dict(cells[case_id]), | |
| dict(grid), | |
| case_id + ".factorial", | |
| "eight_cell_factorial", | |
| ) | |
| self.equal(len(texts), 2048, "data.unique_texts", "text_uniqueness") | |
| for key, ownership in sorted(targets.items()): | |
| self.check( | |
| len(ownership["splits"]) == 1, | |
| "release_target_leakage", | |
| preview(key), | |
| f"normalized target appears in multiple file splits: {sorted(ownership['splits'])}", | |
| ) | |
| self.check( | |
| len(ownership["families"]) == 1, | |
| "release_target_reuse", | |
| preview(key), | |
| f"normalized target appears in multiple families: {sorted(ownership['families'])}", | |
| ) | |
| def case_and_pair_invariants(self): | |
| family_splits = defaultdict(set) | |
| for directory, records in self.records.items(): | |
| for record in records: | |
| row = record.value | |
| if not isinstance(row, dict): | |
| continue | |
| family = row.get("family_id") | |
| if isinstance(family, str): | |
| family_splits[family].add(record.split) | |
| if family in self.split_for: | |
| self.equal( | |
| record.split, | |
| self.split_for[family], | |
| record.location, | |
| "split_sha_ranking", | |
| ) | |
| else: | |
| self.check( | |
| False, | |
| "split_sha_ranking", | |
| record.location, | |
| f"unknown family {family!r}", | |
| ) | |
| if directory == "cases" and all( | |
| type(row.get(key)) is str for key in SOURCE_FIELDS | |
| ): | |
| source_view = {key: row[key] for key in SOURCE_FIELDS} | |
| try: | |
| self.equal( | |
| row.get("case_sha256"), | |
| digest(compact(source_view).encode("utf-8")), | |
| record.location + ".case_sha256", | |
| "case_hashes", | |
| ) | |
| except UnicodeError as exc: | |
| self.check( | |
| False, | |
| "case_hashes", | |
| record.location, | |
| f"case source view is not UTF-8: {exc}", | |
| ) | |
| for family, splits in sorted(family_splits.items()): | |
| self.check( | |
| len(splits) == 1, | |
| "family_split_isolation", | |
| family, | |
| f"family crosses file splits: {sorted(splits)}", | |
| ) | |
| by_id = {} | |
| for record in self.records["data"]: | |
| row = record.value | |
| if isinstance(row, dict) and isinstance(row.get("id"), str): | |
| by_id.setdefault(row["id"], row) | |
| pair_counts = defaultdict(Counter) | |
| pair_edges = defaultdict(Counter) | |
| expected_order = { | |
| "role": ("alternative", "attribute"), | |
| "ordinary": ("a", "b"), | |
| "cue_side": ("left", "right"), | |
| } | |
| directions = { | |
| "role": "attribute - alternative", | |
| "ordinary": "b - a", | |
| "cue_side": "right - left", | |
| } | |
| for record in self.records["pairs"]: | |
| pair, location = record.value, record.location | |
| if not isinstance(pair, dict): | |
| continue | |
| kind, case_id = pair.get("kind"), pair.get("case_id") | |
| if isinstance(kind, str) and isinstance(case_id, str): | |
| pair_counts[case_id][kind] += 1 | |
| base_id, changed_id = pair.get("base_id"), pair.get("changed_id") | |
| if not isinstance(base_id, str) or not isinstance(changed_id, str): | |
| continue | |
| if isinstance(case_id, str): | |
| pair_edges[case_id][(base_id, changed_id)] += 1 | |
| base, changed = by_id.get(base_id), by_id.get(changed_id) | |
| if not self.check( | |
| base is not None and changed is not None, | |
| "pair_references", | |
| location, | |
| f"pair endpoints must exist: base={base_id!r}, changed={changed_id!r}", | |
| ): | |
| continue | |
| for field in ("case_id", "family_id", "language", "target_type", "split"): | |
| self.equal( | |
| base.get(field), | |
| pair.get(field), | |
| location + ".base." + field, | |
| "pair_identity", | |
| ) | |
| self.equal( | |
| changed.get(field), | |
| pair.get(field), | |
| location + ".changed." + field, | |
| "pair_identity", | |
| ) | |
| self.equal( | |
| base.get("target", {}).get("text") | |
| if isinstance(base.get("target"), dict) | |
| else None, | |
| changed.get("target", {}).get("text") | |
| if isinstance(changed.get("target"), dict) | |
| else None, | |
| location + ".target_literal", | |
| "pair_fixed_factors", | |
| ) | |
| a, b = base.get("construction"), changed.get("construction") | |
| if ( | |
| not isinstance(a, dict) | |
| or not isinstance(b, dict) | |
| or not isinstance(kind, str) | |
| ): | |
| continue | |
| if self.check( | |
| kind in KINDS, "pair_kind", location, f"unknown contrast kind {kind!r}" | |
| ): | |
| differences = [ | |
| factor | |
| for factor in ("role", "cue_side", "ordinary") | |
| if a.get(factor) != b.get(factor) | |
| ] | |
| self.equal( | |
| differences, | |
| [kind], | |
| location + ".changed_factors", | |
| "pair_fixed_factors", | |
| ) | |
| self.equal( | |
| [a.get(kind), b.get(kind)], | |
| list(expected_order[kind]), | |
| location + ".factor_order", | |
| "pair_direction", | |
| ) | |
| self.equal( | |
| pair.get("direction"), | |
| directions[kind], | |
| location + ".direction", | |
| "pair_direction", | |
| ) | |
| for case_id in sorted(set(self.sources) | set(pair_counts)): | |
| self.equal( | |
| dict(pair_counts[case_id]), | |
| {kind: 4 for kind in KINDS}, | |
| case_id + ".contrasts", | |
| "twelve_pair_factorial", | |
| ) | |
| self.equal( | |
| len(pair_edges[case_id]), | |
| 12, | |
| case_id + ".unique_edges", | |
| "twelve_pair_factorial", | |
| ) | |
| for edge, count in pair_edges[case_id].items(): | |
| self.equal( | |
| count, | |
| 1, | |
| case_id + ".edge." + preview(edge), | |
| "twelve_pair_factorial", | |
| ) | |
| def statistics(self): | |
| def dimension(record, key): | |
| value = record.value.get(key) if isinstance(record.value, dict) else None | |
| return value if isinstance(value, str) else "<invalid>" | |
| def measures(texts, cases, pairs, families=True): | |
| result = { | |
| "records": len(texts), | |
| "cases": len(cases), | |
| "contrasts": len(pairs), | |
| } | |
| if families: | |
| result["families"] = len( | |
| {dimension(record, "family_id") for record in cases} | |
| ) | |
| return result | |
| texts, cases, pairs = (self.records[key] for key in ("data", "cases", "pairs")) | |
| by_split = {} | |
| for split in SPLITS: | |
| by_split[split] = measures( | |
| [record for record in texts if record.split == split], | |
| [record for record in cases if record.split == split], | |
| [record for record in pairs if record.split == split], | |
| ) | |
| grouped = {} | |
| for field, expected_values in (("target_type", TYPES), ("language", LANGUAGES)): | |
| values = set(expected_values) | |
| values.update(dimension(record, field) for record in texts + cases + pairs) | |
| grouped[field] = { | |
| value: measures( | |
| [record for record in texts if dimension(record, field) == value], | |
| [record for record in cases if dimension(record, field) == value], | |
| [record for record in pairs if dimension(record, field) == value], | |
| families=field == "target_type", | |
| ) | |
| for value in sorted(values) | |
| } | |
| kinds = Counter(dimension(record, "kind") for record in pairs) | |
| contrast_counts = { | |
| kind: kinds[kind] for kind in sorted(set(KINDS) | set(kinds)) | |
| } | |
| lengths = [ | |
| len(record.value["text"]) | |
| for record in texts | |
| if isinstance(record.value, dict) | |
| and isinstance(record.value.get("text"), str) | |
| ] | |
| totals = measures(texts, cases, pairs) | |
| self.observed = { | |
| "schema_version": 1, | |
| "name": NAME, | |
| "version": VERSION, | |
| **totals, | |
| "gold_privacy_labels": 0, | |
| "by_split": by_split, | |
| "by_target_type": grouped["target_type"], | |
| "by_language": grouped["language"], | |
| "by_contrast_kind": contrast_counts, | |
| "text_codepoint_length": { | |
| "min": min(lengths) if lengths else None, | |
| "max": max(lengths) if lengths else None, | |
| }, | |
| } | |
| self.equal(totals, TOTALS, "observed.totals", "counts") | |
| self.equal(by_split, SPLIT_TOTALS, "observed.by_split", "counts") | |
| self.equal( | |
| grouped["target_type"], | |
| {kind: TYPE_TOTALS for kind in TYPES}, | |
| "observed.by_target_type", | |
| "counts", | |
| ) | |
| self.equal( | |
| grouped["language"], | |
| {language: LANGUAGE_TOTALS for language in LANGUAGES}, | |
| "observed.by_language", | |
| "counts", | |
| ) | |
| self.equal( | |
| contrast_counts, | |
| {kind: 1024 for kind in KINDS}, | |
| "observed.by_contrast_kind", | |
| "counts", | |
| ) | |
| blob = self.payloads.get("stats.json") | |
| document = self.parse(blob, "stats.json") | |
| if document is not None: | |
| self.equal(document, self.observed, "stats.json", "recomputed_statistics") | |
| self.canonical_document(blob, document, "stats.json") | |
| def canonical_document(self, blob, document, location): | |
| try: | |
| expected = pretty_bytes(document) | |
| self.check( | |
| blob == expected, | |
| "pretty_json_bytes", | |
| location, | |
| "JSON must use indent=2, sorted keys, ensure_ascii=False, UTF-8, and one trailing LF", | |
| ) | |
| except (ValueError, UnicodeError, RecursionError) as exc: | |
| self.check( | |
| False, | |
| "pretty_json_bytes", | |
| location, | |
| f"cannot serialize canonical UTF-8 JSON: {exc}", | |
| ) | |
| def file_entry(self, relative, blob): | |
| return {"path": relative, "bytes": len(blob), "sha256": digest(blob)} | |
| def manifest_entries(self, entries, scope, expected_paths, blobs, location): | |
| if not self.check( | |
| type(entries) is list, | |
| "manifest_inventory", | |
| location, | |
| "expected a list of file entries", | |
| ): | |
| return | |
| paths = [] | |
| for index, entry in enumerate(entries): | |
| item_location = f"{location}[{index}]" | |
| if not self.shape( | |
| entry, {"path": str, "bytes": int, "sha256": str}, item_location | |
| ): | |
| continue | |
| relative = entry["path"] | |
| paths.append(relative) | |
| posix = PurePosixPath(relative) | |
| valid_path = ( | |
| not posix.is_absolute() | |
| and relative == posix.as_posix() | |
| and "\\" not in relative | |
| and "\x00" not in relative | |
| and all(part not in {"", ".", ".."} for part in posix.parts) | |
| ) | |
| if not self.check( | |
| valid_path, | |
| "manifest_paths", | |
| item_location, | |
| "path must be a normalized relative POSIX path without traversal", | |
| ): | |
| continue | |
| try: | |
| self.check( | |
| (scope / relative).resolve().is_relative_to(scope), | |
| "manifest_paths", | |
| item_location, | |
| "declared path resolves outside its declared root", | |
| ) | |
| except (OSError, RuntimeError, ValueError) as exc: | |
| self.check( | |
| False, | |
| "manifest_paths", | |
| item_location, | |
| f"cannot resolve declared path: {exc}", | |
| ) | |
| self.check( | |
| entry["bytes"] >= 0, | |
| "manifest_hashes", | |
| item_location + ".bytes", | |
| "byte count cannot be negative", | |
| ) | |
| self.check( | |
| bool(re.fullmatch(r"[0-9a-f]{64}", entry["sha256"])), | |
| "manifest_hashes", | |
| item_location + ".sha256", | |
| "SHA256 must be 64 lowercase hexadecimal characters", | |
| ) | |
| if self.check( | |
| relative in expected_paths, | |
| "manifest_inventory", | |
| item_location, | |
| f"undeclared-contract path {relative!r} is not permitted", | |
| ): | |
| if relative in blobs: | |
| self.equal( | |
| entry, | |
| self.file_entry(relative, blobs[relative]), | |
| item_location, | |
| "manifest_hashes", | |
| ) | |
| else: | |
| self.check( | |
| False, | |
| "manifest_hashes", | |
| item_location, | |
| "expected file was unavailable; cannot verify bytes/hash", | |
| ) | |
| self.equal( | |
| paths, sorted(expected_paths), location + ".paths", "manifest_inventory" | |
| ) | |
| def manifests(self): | |
| self.manifest_blob = self.read_blob( | |
| self.release, "manifest.json", "release_files" | |
| ) | |
| checksum_blob = self.read_blob(self.release, "manifest.sha256", "release_files") | |
| manifest = self.parse(self.manifest_blob, "manifest.json") | |
| if self.manifest_blob is not None and checksum_blob is not None: | |
| expected_checksum = ( | |
| digest(self.manifest_blob) + " manifest.json\n" | |
| ).encode("ascii") | |
| self.check( | |
| checksum_blob == expected_checksum, | |
| "manifest_checksum", | |
| "manifest.sha256", | |
| "expected exactly SHA256(manifest.json), two spaces, manifest.json, and LF", | |
| ) | |
| if manifest is None: | |
| return | |
| self.shape( | |
| manifest, | |
| { | |
| "schema_version": int, | |
| "name": str, | |
| "version": str, | |
| "protocol_sha256": str, | |
| "inputs": list, | |
| "files": list, | |
| "counts": { | |
| "records": int, | |
| "cases": int, | |
| "families": int, | |
| "contrasts": int, | |
| }, | |
| }, | |
| "manifest.json", | |
| ) | |
| self.canonical_document(self.manifest_blob, manifest, "manifest.json") | |
| if not isinstance(manifest, dict): | |
| return | |
| self.manifest_entries( | |
| manifest.get("inputs"), | |
| self.root, | |
| INPUT_PATHS, | |
| self.inputs, | |
| "manifest.json.inputs", | |
| ) | |
| self.manifest_entries( | |
| manifest.get("files"), | |
| self.release, | |
| PAYLOAD_PATHS, | |
| self.payloads, | |
| "manifest.json.files", | |
| ) | |
| expected = { | |
| "schema_version": 1, | |
| "name": NAME, | |
| "version": VERSION, | |
| "protocol_sha256": PROTOCOL_SHA256, | |
| "inputs": [ | |
| self.file_entry(path, self.inputs[path]) | |
| for path in INPUT_PATHS | |
| if path in self.inputs | |
| ], | |
| "files": [ | |
| self.file_entry(path, self.payloads[path]) | |
| for path in PAYLOAD_PATHS | |
| if path in self.payloads | |
| ], | |
| "counts": dict(TOTALS), | |
| } | |
| self.equal(manifest, expected, "manifest.json", "recomputed_manifest") | |
| if self.observed: | |
| self.equal( | |
| manifest.get("counts"), | |
| {key: self.observed[key] for key in TOTALS}, | |
| "manifest.json.counts", | |
| "manifest_observed_counts", | |
| ) | |
| def run(self): | |
| self.inventories() | |
| self.source_cases() | |
| self.reconstruct() | |
| self.load_records() | |
| self.text_invariants() | |
| self.case_and_pair_invariants() | |
| self.statistics() | |
| self.manifests() | |
| def report(self): | |
| manifest_identity = { | |
| "path": str(self.release / "manifest.json"), | |
| "bytes": None, | |
| "sha256": None, | |
| } | |
| if self.manifest_blob is not None: | |
| manifest_identity.update( | |
| bytes=len(self.manifest_blob), sha256=digest(self.manifest_blob) | |
| ) | |
| protocol_blob = self.inputs.get(".construction/protocol.json") | |
| return { | |
| "schema_version": 1, | |
| "name": NAME, | |
| "version": VERSION, | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| "producer": self.producer, | |
| "root": { | |
| "path": str(self.root), | |
| "protocol_sha256": digest(protocol_blob) | |
| if protocol_blob is not None | |
| else None, | |
| }, | |
| "release": { | |
| "path": str(self.release), | |
| "manifest_sha256": manifest_identity["sha256"], | |
| }, | |
| "manifest": manifest_identity, | |
| "status": "failure" if self.errors else "pass", | |
| "counts": { | |
| "expected": dict(TOTALS), | |
| "source_cases_reconstructed": len(self.sources), | |
| "parsed_release_rows": { | |
| key: len(value) for key, value in self.records.items() | |
| }, | |
| "observed_statistics": self.observed, | |
| "errors": len(self.errors), | |
| }, | |
| "checks": { | |
| name: {**summary, "status": "failure" if summary["failed"] else "pass"} | |
| for name, summary in sorted(self.checks.items()) | |
| }, | |
| "safety_inventories": { | |
| kind: sorted(items, key=lambda item: item["case_id"]) | |
| for kind, items in self.safety.items() | |
| }, | |
| "errors": self.errors, | |
| "limitations": list(LIMITATIONS), | |
| } | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser( | |
| description="Validate the complete frozen construction corpus without executing a builder, model, or tokenizer.", | |
| epilog="A pass is mechanical validation only: not semantic/privacy adjudication, representative sampling, tokenizer matching, or classifier evaluation.", | |
| ) | |
| parser.add_argument( | |
| "--root", | |
| type=Path, | |
| default=Path(__file__).resolve().parent.parent, | |
| help="source repository root (default: this script's repository)", | |
| ) | |
| parser.add_argument( | |
| "--release", | |
| type=Path, | |
| required=True, | |
| help="existing generated release directory; read-only", | |
| ) | |
| parser.add_argument( | |
| "--report", | |
| type=Path, | |
| required=True, | |
| help="new report JSON path outside the release; parent must exist", | |
| ) | |
| args = parser.parse_args(argv) | |
| try: | |
| root = args.root.expanduser().resolve() | |
| release = args.release.expanduser().resolve() | |
| requested_report = args.report.expanduser() | |
| if os.path.lexists(requested_report): | |
| raise ValueError( | |
| f"report already exists; refusing to overwrite: {requested_report}" | |
| ) | |
| report_path = requested_report.resolve() | |
| if report_path.is_relative_to(release): | |
| raise ValueError(f"report must be outside release: {report_path}") | |
| if not report_path.parent.is_dir(): | |
| raise ValueError( | |
| f"report parent directory does not exist: {report_path.parent}" | |
| ) | |
| producer_path = Path(__file__).resolve(strict=True) | |
| producer_blob = producer_path.read_bytes() | |
| producer = { | |
| "path": str(producer_path), | |
| "bytes": len(producer_blob), | |
| "sha256": digest(producer_blob), | |
| } | |
| # Exclusive creation closes the overwrite race. No release or input file | |
| # is opened for writing, and no report directory is implicitly created. | |
| report_stream = report_path.open("x", encoding="utf-8", newline="\n") | |
| except (OSError, RuntimeError, ValueError) as exc: | |
| print(f"validation refused: {exc}", file=sys.stderr) | |
| return 1 | |
| validator = Validator(root, release, producer) | |
| with report_stream: | |
| try: | |
| validator.run() | |
| except Exception as exc: | |
| validator.check( | |
| False, | |
| "validator_internal_error", | |
| "validator", | |
| f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}", | |
| ) | |
| report = validator.report() | |
| try: | |
| # Escaping report strings also preserves failures containing an | |
| # invalid surrogate from corrupt input. Release serialization is | |
| # checked separately against ensure_ascii=False. | |
| json.dump( | |
| report, | |
| report_stream, | |
| indent=2, | |
| sort_keys=True, | |
| ensure_ascii=True, | |
| allow_nan=False, | |
| ) | |
| report_stream.write("\n") | |
| report_stream.flush() | |
| os.fsync(report_stream.fileno()) | |
| except (OSError, UnicodeError, ValueError) as exc: | |
| print( | |
| f"cannot persist complete validation report at {report_path}: {exc}", | |
| file=sys.stderr, | |
| ) | |
| return 1 | |
| if validator.errors: | |
| print( | |
| f"FAIL: {len(validator.errors)} validation errors. Complete retained report: {report_path}", | |
| file=sys.stderr, | |
| ) | |
| for error in validator.errors[:20]: | |
| print( | |
| f" [{error['check']}] {error['location']}: {error['message']}", | |
| file=sys.stderr, | |
| ) | |
| if len(validator.errors) > 20: | |
| print( | |
| f" {len(validator.errors) - 20} additional errors retained in the report.", | |
| file=sys.stderr, | |
| ) | |
| return 1 | |
| print( | |
| f"PASS: 256 cases, 128 families, 2048 texts, 3072 contrasts. Report: {report_path}" | |
| ) | |
| print( | |
| "Mechanical validation only; no semantic/privacy gold, representativeness, tokenizer matching, or classifier evaluation." | |
| ) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |