File size: 73,667 Bytes
4022aae | 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 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 | #!/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] + "..."
@dataclass
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())
|