From 3baa8c885a00d493669e212bc6fdb9bb049d47b6 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 13 Nov 2026 18:35:47 -0500 Subject: [PATCH 1/2] Add temporary Core 3.36 parameter validation workflow --- .github/us10783-validation/Dockerfile | 15 + .github/us10783-validation/atomic.py | 26 + .github/us10783-validation/comparison_data.py | 405 ++++++ .../us10783-validation/parameter_export.py | 462 +++++++ .github/us10783-validation/remote.py | 1101 +++++++++++++++++ .github/us10783-validation/test_entry.py | 416 +++++++ .github/workflows/docs.yaml | 102 +- .../us10783-core336-validation.changed.md | 1 + 8 files changed, 2456 insertions(+), 72 deletions(-) create mode 100644 .github/us10783-validation/Dockerfile create mode 100644 .github/us10783-validation/atomic.py create mode 100644 .github/us10783-validation/comparison_data.py create mode 100644 .github/us10783-validation/parameter_export.py create mode 100644 .github/us10783-validation/remote.py create mode 100644 .github/us10783-validation/test_entry.py create mode 100644 changelog.d/us10783-core336-validation.changed.md diff --git a/.github/us10783-validation/Dockerfile b/.github/us10783-validation/Dockerfile new file mode 100644 index 00000000000..94ce865f3b1 --- /dev/null +++ b/.github/us10783-validation/Dockerfile @@ -0,0 +1,15 @@ +FROM python:3.14.7-slim-bookworm@sha256:998acd06f485adfd6890e3e15a4b542543e0cf22ff904310095da328a5e3e561 + +ENV PYTHONDONTWRITEBYTECODE=1 \ + UV_PYTHON_DOWNLOADS=never \ + UV_PROJECT_ENVIRONMENT=/sources/C/.venv \ + UV_CACHE_DIR=/validation/uv-cache +COPY sources /sources +COPY helpers /validation +COPY evidence /validation/evidence +COPY core.whl /validation/evidence/core.whl +COPY uv.tar.gz /validation/evidence/uv.tar.gz +RUN tar -xzf /validation/evidence/uv.tar.gz -C /opt +WORKDIR /sources/C +RUN /opt/uv-x86_64-unknown-linux-gnu/uv sync --locked --extra dev --no-python-downloads --python /usr/local/bin/python3.14 +RUN /sources/C/.venv/bin/python -B /validation/remote.py qualify diff --git a/.github/us10783-validation/atomic.py b/.github/us10783-validation/atomic.py new file mode 100644 index 00000000000..7a88700c0ab --- /dev/null +++ b/.github/us10783-validation/atomic.py @@ -0,0 +1,26 @@ +"""Hash files and publish new JSON records without replacing evidence.""" + +import hashlib +import json +import os +from pathlib import Path + + +def sha256_file(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_new_json(path, value): + path = Path(path) + temporary = path.with_name(path.name + ".partial") + with temporary.open("x") as stream: + json.dump(value, stream, indent=2, sort_keys=True, allow_nan=False) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.link(temporary, path) + temporary.unlink() diff --git a/.github/us10783-validation/comparison_data.py b/.github/us10783-validation/comparison_data.py new file mode 100644 index 00000000000..ea7a9ee99f0 --- /dev/null +++ b/.github/us10783-validation/comparison_data.py @@ -0,0 +1,405 @@ +"""Pure typed parameter records, complete grids, and union comparisons. + +No country imports or process actions belong in this module. +""" + +from __future__ import annotations + +import argparse +import hashlib +import itertools +import json +import math +from pathlib import Path + +ORIGINAL_YEARS = ( + 2013, + 2015, + 2018, + 2020, + 2024, + 2025, + 2026, + 2027, + 2028, + 2029, + 2030, + 2031, + 2032, + 2033, + 2034, + 2035, + 2036, + 2037, + 2040, + 2045, + 2050, + 2060, + 2075, + 2090, + 2100, + 2110, +) +TRUSTEES_VIEW_YEARS = ( + 2027, + 2034, + 2035, + 2036, + 2037, + 2040, + 2045, + 2050, + 2060, + 2075, + 2090, + 2100, +) +HISTORY_PATH = "gov.irs.deductions.standard.dependent.additional_earned_income" +HISTORY_DATES = tuple(f"{year:04d}-01-01" for year in (1, 1997, *range(1998, 2013))) +ORIGINAL_DATES = tuple(f"{year}-01-01" for year in ORIGINAL_YEARS) +ABSENT_SIDE = {"kind": "ABSENT_SIDE"} + + +def digest(path: Path) -> str: + result = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + result.update(block) + return result.hexdigest() + + +def type_name(value) -> str: + return f"{type(value).__module__}.{type(value).__qualname__}" + + +def encode_value(value) -> dict: + """Preserve type and float identity; unsupported values remain explicit.""" + # NumPy float64/str_ inherit Python built-ins but still need item() to + # become exact native scalars before type validation and repr capture. + if ( + type(value).__module__.startswith("numpy") + and getattr(value, "shape", None) == () + ): + try: + scalar = value.item() + if type(scalar) is type(value): + raise TypeError("Scalar item() did not produce a native scalar") + return encode_value(scalar) + except Exception as error: + return { + "kind": "UNSUPPORTED", + "python_type": type_name(value), + "repr": repr(value), + "conversion_error": repr(error), + } + if value is None: + return {"kind": "NULL", "value": None} + if isinstance(value, bool): + return {"kind": "BOOL", "value": value} + if isinstance(value, int): + return {"kind": "INT", "value": value} + if isinstance(value, float): + if not math.isfinite(value): + name = "nan" if math.isnan(value) else ("+inf" if value > 0 else "-inf") + return {"kind": "NONFINITE", "value": name, "float_hex": value.hex()} + return { + "kind": "FLOAT", + "value": value, + "decimal": repr(value), + "float_hex": value.hex(), + } + if isinstance(value, str): + return {"kind": "STRING", "value": value} + result = { + "kind": "UNSUPPORTED", + "python_type": type_name(value), + "repr": repr(value), + } + if hasattr(value, "shape"): + result["shape"] = list(value.shape) + if hasattr(value, "dtype"): + result["dtype"] = str(value.dtype) + if hasattr(value, "tolist"): + try: + result["data_repr"] = repr(value.tolist()) + except Exception as error: + result["conversion_error"] = repr(error) + return result + + +def lookup_value(parameter, date: str) -> dict: + try: + value = parameter(date) + except Exception as error: + return { + "kind": "LOOKUP_ERROR", + "exception_type": type_name(error), + "message": str(error), + } + try: + return encode_value(value) + except Exception as error: + return { + "kind": "UNSUPPORTED", + "python_type": type_name(value), + "repr": "", + "conversion_error": repr(error), + } + + +def names_catalog(names) -> list[str]: + names = list(names) + if any(not isinstance(name, str) or not name for name in names): + raise ValueError("Invalid Parameter catalog name") + if len(names) != len(set(names)): + raise ValueError("Duplicate Parameter catalog name") + return sorted(names) + + +def dates_for(path: str, dates, history: dict) -> list[str]: + return sorted(set(dates) | set(history.get(path, ()))) + + +def expected_keys(catalog, dates, history, mode): + for name in names_catalog(catalog): + for date in dates_for(name, dates, history): + yield name, date, mode + + +def row_key(row): + return row["path"], row["date"], row["mode"] + + +def validate_typed(value): + kind = value.get("kind") + if kind == "FLOAT": + number = value.get("value") + if type(number) is not float or not math.isfinite(number): + raise ValueError("Invalid finite float") + if value.get("float_hex") != number.hex() or value.get("decimal") != repr( + number + ): + raise ValueError("Float identity does not match") + elif kind == "INT" and type(value.get("value")) is not int: + raise ValueError("Invalid integer") + elif kind == "BOOL" and type(value.get("value")) is not bool: + raise ValueError("Invalid boolean") + elif kind == "STRING" and type(value.get("value")) is not str: + raise ValueError("Invalid string") + elif kind == "NULL" and value.get("value") is not None: + raise ValueError("Invalid null") + elif kind == "NONFINITE" and value.get("value") not in {"nan", "+inf", "-inf"}: + raise ValueError("Invalid nonfinite value") + elif kind == "LOOKUP_ERROR" and not {"exception_type", "message"} <= value.keys(): + raise ValueError("Incomplete lookup error") + elif kind == "UNSUPPORTED" and not {"python_type", "repr"} <= value.keys(): + raise ValueError("Incomplete unsupported value") + elif kind not in { + "FLOAT", + "INT", + "BOOL", + "STRING", + "NULL", + "NONFINITE", + "LOOKUP_ERROR", + "UNSUPPORTED", + }: + raise ValueError(f"Unknown export value kind: {kind}") + + +def validated_rows(catalog, dates, history, mode, rows): + """Ordered full-grid validation without allocating millions of key tuples.""" + if not dates or len(dates) != len(set(dates)): + raise ValueError("Invalid date profile") + sentinel = object() + for expected, row in itertools.zip_longest( + expected_keys(catalog, dates, history, mode), rows, fillvalue=sentinel + ): + if row is sentinel: + raise ValueError(f"MISSING_EXPORT_ROW: {expected}") + if expected is sentinel: + raise ValueError(f"EXTRA_EXPORT_ROW: {row_key(row)}") + actual = row_key(row) + if actual != expected: + reason = ( + "MISSING_EXPORT_ROW" if actual > expected else "EXTRA_OR_DUPLICATE_ROW" + ) + raise ValueError(f"{reason}: expected {expected}, observed {actual}") + validate_typed(row["value"]) + yield row + + +def exact_equal(left, right): + return left == right + + +def tolerance_equal(left, right): + if left["kind"] in {"INT", "FLOAT"} and right["kind"] in {"INT", "FLOAT"}: + return math.isclose(left["value"], right["value"], rel_tol=1e-12, abs_tol=1e-9) + return exact_equal(left, right) + + +def compare_streams(sides: dict, *, allow_cross_mode=False): + """Validate each independent grid, then join their catalog union as typed data. + + A side supplies catalog/dates/history/mode/rows. Row generators are consumed + completely; a matching dropped path cannot certify itself via emitted counts. + """ + if len(sides) < 2: + raise ValueError("At least two sides required") + profiles = { + (tuple(s["dates"]), json.dumps(s["history"], sort_keys=True)) + for s in sides.values() + } + if len(profiles) != 1: + raise ValueError("Incompatible date/history profiles") + modes = {name: side["mode"] for name, side in sides.items()} + if len(set(modes.values())) != 1 and not allow_cross_mode: + raise ValueError("Cross-mode comparison requires explicit opt-in") + cursors, present = {}, {} + for name, side in sides.items(): + side["catalog"] = names_catalog(side["catalog"]) + present[name] = set(side["catalog"]) + cursors[name] = iter( + validated_rows( + side["catalog"], + side["dates"], + side["history"], + side["mode"], + side["rows"], + ) + ) + first = next(iter(sides.values())) + union = sorted(set().union(*present.values())) + for path in union: + for date in dates_for(path, first["dates"], first["history"]): + values = {} + for name in sides: + if path not in present[name]: + values[name] = dict(ABSENT_SIDE) + else: + row = next(cursors[name]) + if row_key(row) != (path, date, sides[name]["mode"]): + raise ValueError("Grid cursor mismatch") + values[name] = row["value"] + baseline = next(iter(values.values())) + exact = all(exact_equal(baseline, value) for value in values.values()) + tolerated = all( + tolerance_equal(baseline, value) for value in values.values() + ) + if not exact: + yield { + "path": path, + "date": date, + "mode": first["mode"] + if len(set(modes.values())) == 1 + else "cross_mode", + "side_modes": modes, + "sides": values, + "legacy_tolerance_equal": tolerated, + } + for cursor in cursors.values(): + if next(cursor, None) is not None: + raise ValueError("EXTRA_EXPORT_ROW after union") + + +def read_export(manifest_path): + path = Path(manifest_path).resolve() + manifest = json.loads(path.read_text()) + if ( + manifest.get("complete") is not True + or manifest.get("grid_validated") is not True + ): + raise ValueError("Incomplete export") + records = manifest["outputs"] + for record in records.values(): + if digest(Path(record["path"])) != record["sha256"]: + raise ValueError("Output checksum mismatch") + catalog_record = json.loads(Path(records["catalog"]["path"]).read_text()) + if ( + catalog_record["source_commit"] != manifest["source"]["commit"] + or catalog_record["mode"] != manifest["mode"] + ): + raise ValueError("Catalog source/mode identity mismatch") + catalog = catalog_record["names"] + + def rows(): + with Path(records["values"]["path"]).open() as stream: + for line in stream: + yield json.loads(line) + + return manifest, { + "catalog": catalog, + "dates": manifest["dates"], + "history": manifest["history"], + "mode": manifest["mode"], + "rows": rows(), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--side", action="append", required=True, help="NAME=completed-manifest.json" + ) + parser.add_argument("--out", required=True) + parser.add_argument("--legacy-out", required=True) + parser.add_argument("--cross-mode", action="store_true") + args = parser.parse_args() + sides, manifests = {}, {} + for spec in args.side: + name, path = spec.split("=", 1) + if name in sides: + raise ValueError("Duplicate side name") + manifests[name], sides[name] = read_export(path) + runtime_ids = {m["runtime_binding_sha256"] for m in manifests.values()} + if len(runtime_ids) != 1: + raise ValueError("Different runtime bindings") + if ( + args.cross_mode + and len({m["source"]["commit"] for m in manifests.values()}) != 1 + ): + raise ValueError("Cross-mode changed-set comparison requires one source commit") + out = Path(args.out) + legacy_out = Path(args.legacy_out) + if out.resolve() == legacy_out.resolve(): + raise ValueError("Raw and tolerance outputs must remain separate") + partial = out.with_name(out.name + ".partial") + legacy_partial = legacy_out.with_name(legacy_out.name + ".partial") + count = legacy_count = 0 + with partial.open("x") as stream, legacy_partial.open("x") as legacy: + for row in compare_streams(sides, allow_cross_mode=args.cross_mode): + text = json.dumps(row, sort_keys=True, allow_nan=False) + "\n" + stream.write(text) + if not row["legacy_tolerance_equal"]: + legacy.write(text) + legacy_count += 1 + count += 1 + from atomic import write_new_json + import os + + for temporary, final in ((partial, out), (legacy_partial, legacy_out)): + os.link(temporary, final) + temporary.unlink() + summary = { + "complete": True, + "exact_difference_rows": count, + "legacy_difference_rows": legacy_count, + "raw": {"path": str(out), "sha256": digest(out)}, + "legacy": {"path": str(legacy_out), "sha256": digest(legacy_out)}, + "inputs": { + name: { + "source": m["source"], + "mode": m["mode"], + "bindings_sha256": m["bindings_sha256"], + } + for name, m in manifests.items() + }, + "parity_approved": False, + } + write_new_json(out.with_name(out.name + ".manifest.json"), summary) + print(json.dumps(summary)) + + +if __name__ == "__main__": + main() diff --git a/.github/us10783-validation/parameter_export.py b/.github/us10783-validation/parameter_export.py new file mode 100644 index 00000000000..0113737f665 --- /dev/null +++ b/.github/us10783-validation/parameter_export.py @@ -0,0 +1,462 @@ +"""Export actual parameter trees after Linux source and resource checks.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import importlib +import importlib.util +import json +import os +from pathlib import Path +import platform +import sys +import time + +from atomic import sha256_file, write_new_json +from remote import ( + capture_resources, + publish_provenance, + resource_record, + resource_snapshot, + validate_source_record, +) +from comparison_data import ( + HISTORY_DATES, + HISTORY_PATH, + ORIGINAL_DATES, + TRUSTEES_VIEW_YEARS, + encode_value, + lookup_value, + names_catalog, + validated_rows, +) + + +def frozen_json(record): + path = Path(record["path"]).resolve() + if sha256_file(path) != record["sha256"]: + raise ValueError(f"Frozen input checksum mismatch: {path}") + return json.loads(path.read_text()) + + +def verify_source(source): + """Verify a complete frozen manifest; this never creates a source archive.""" + root = Path(source["root"]).resolve() + manifest = frozen_json(source["manifest"]) + if (manifest["commit"], manifest["tree"]) != (source["commit"], source["tree"]): + raise ValueError("Source manifest identity mismatch") + files = manifest["files"] + expected_package = set() + for relative, expected in files.items(): + path = (root / relative).resolve() + if Path(relative).is_absolute() or not path.is_relative_to(root): + raise ValueError("Unsafe source-manifest path") + if sha256_file(path) != expected: + raise ValueError(f"Source bytes changed: {relative}") + if relative.startswith("policyengine_us/"): + expected_package.add(relative) + actual_package = { + path.relative_to(root).as_posix() + for path in (root / "policyengine_us").rglob("*") + if path.is_file() and "__pycache__" not in path.parts and path.suffix != ".pyc" + } + if not expected_package or actual_package != expected_package: + raise ValueError("Frozen country package catalog differs") + return root + + +def verify_runtime(binding): + """Recheck Root's qualification evidence; no environment repair or resolver.""" + qualification = frozen_json(binding["qualification"]) + if qualification.get("core_version") != "3.36.0" or not qualification[ + "status" + ].startswith("PASS"): + raise ValueError("Released-Core qualification missing") + if Path(sys.executable).resolve() != Path(binding["python_realpath"]).resolve(): + raise ValueError("Wrong interpreter") + if str(Path(sys.prefix).resolve()) != str(Path(binding["prefix"]).resolve()): + raise ValueError("Wrong private prefix") + if ( + platform.machine() != binding["machine"] + or platform.python_version() != binding["python_version"] + ): + raise ValueError("Wrong native Python/platform") + core_root = Path(binding["core_root"]).resolve() + import importlib.metadata + + if ( + importlib.metadata.version("policyengine-core") != qualification["core_version"] + or importlib.metadata.version("policyengine-us") + != qualification["country_distribution_version"] + ): + raise ValueError("Installed project/Core metadata changed after qualification") + files = qualification["core_files_matched"] + if len(files) != 195 or len({record["path"] for record in files}) != 195: + raise ValueError("Incomplete Core wheel-file qualification") + for record in files: + path = (core_root.parent / record["path"]).resolve() + if not path.is_relative_to(core_root) or sha256_file(path) != record["sha256"]: + raise ValueError("Installed Core bytes changed") + dependency = frozen_json(binding["dependency_evidence"]) + check = dependency.get("locked_environment_check", dependency) + if check.get("exit") != 0: + raise ValueError("Dependency evidence did not pass") + argv = check["argv"] + if not {"--check", "--dry-run", "--locked", "--offline", "dev"} <= set(argv): + raise ValueError("Dependency evidence lacks the reviewed strict check flags") + if "--inexact" in argv or "--no-install-project" in argv: + raise ValueError("Final qualification requires the actual strict full check") + return qualification + + +def verify_tables(tables): + if tables["dates"] != list(ORIGINAL_DATES): + raise ValueError("Original26 date profile changed") + if tables["history"] != {HISTORY_PATH: list(HISTORY_DATES)}: + raise ValueError("Known pre2013 history profile changed") + if tables["trustees_view_dates"] != [ + f"{year}-01-01" for year in TRUSTEES_VIEW_YEARS + ]: + raise ValueError("Original Trustees view changed") + if tables["trustees_defaults"] != { + "start_year": 2035, + "end_year": 2100, + "projection_base_year": 2026, + }: + raise ValueError("Genuine Trustees defaults changed") + + +def assert_imports(root, core_root): + for name, module in tuple(sys.modules.items()): + if name == "policyengine_us" or name.startswith("policyengine_us."): + base = root / "policyengine_us" + elif name == "policyengine_core" or name.startswith("policyengine_core."): + base = core_root + else: + continue + location = getattr(module, "__file__", None) + if location and not Path(location).resolve().is_relative_to(base): + raise ValueError(f"Unexpected imported module origin: {name}") + + +def selector_metadata(module, baseline_parameters): + assumption = module.TRUSTEES_CORE_THRESHOLD_ASSUMPTION + key = ( + "uprating_parameters" + if "uprating_parameters" in assumption + else "uprating_parameter" + ) + initial = module._iter_updatable_parameters( + baseline_parameters.gov.irs, uprating_parameter=assumption[key] + ) + public = getattr(module, "trustees_core_threshold_parameters", None) + effective = public(baseline_parameters) if public else None + return { + "assumption": encode_value(assumption), + "uprating_key": key, + "uprating_indices": encode_value(assumption[key]), + "initial": names_catalog(p.name for p in initial), + "effective_available": effective is not None, + "effective": names_catalog(p.name for p in effective) + if effective is not None + else None, + "followers": [ + {"path": p.name, "uprating": encode_value(p.metadata.get("uprating"))} + for p in (effective or initial) + ], + } + + +def export_entry(args): + """Check the frozen runtime and construct one source/mode in a cold process.""" + bindings_path = Path(args.bindings).resolve() + binding_sha = sha256_file(bindings_path) + resources = resource_snapshot() + resource_start_path = ( + Path(args.manifest_out) + .resolve() + .with_name(Path(args.manifest_out).name + ".resources-start.json") + ) + start_record = resource_record("start", resources) + start_record.update( + bindings_sha256=binding_sha, + source_sha_command=args.source_sha, + tree_sha_command=args.tree_sha, + mode_command=args.mode, + at=datetime.now(timezone.utc).isoformat(), + ) + write_new_json(resource_start_path, start_record) + publish_provenance() + image_id = os.environ.get("US10783_IMAGE_ID", "") + if not image_id.startswith("sha256:") or len(image_id) != 71: + raise ValueError("Missing frozen remote image identity") + bindings = json.loads(bindings_path.read_text()) + if bindings.get("schema_version") != 1: + raise ValueError("Unknown frozen binding schema") + source = bindings["source"] + validate_source_record(source) + if (args.source_sha, args.tree_sha) != (source["commit"], source["tree"]): + raise ValueError("Command/source identity mismatch") + if os.environ.get("PYTHONDONTWRITEBYTECODE") != "1": + raise ValueError("Bytecode writes must remain disabled") + if any( + name == "policyengine_us" + or name.startswith("policyengine_us.") + or name == "policyengine_core" + or name.startswith("policyengine_core.") + for name in sys.modules + ): + raise RuntimeError("Refuse a preloaded/warm country or Core") + tables = bindings["tables"] + verify_tables(tables) + root = verify_source(source) + qualification = verify_runtime(bindings["runtime"]) + core_root = Path(bindings["runtime"]["core_root"]).resolve() + started = datetime.now(timezone.utc).isoformat() + clock = time.monotonic() + sys.path.insert(0, str(root)) + for package, expected in ( + ("policyengine_us", root / "policyengine_us/__init__.py"), + ("policyengine_core", core_root / "__init__.py"), + ): + spec = importlib.util.find_spec(package) + if spec is None or Path(spec.origin).resolve() != expected.resolve(): + raise ValueError(f"Wrong cold import origin: {package}") + # Actual original dump API; no simulation, dataset or household is constructed. + country = importlib.import_module("policyengine_us") + core = importlib.import_module("policyengine_core") + system_module = importlib.import_module("policyengine_us.system") + parameter_module = importlib.import_module("policyengine_core.parameters") + Parameter = parameter_module.Parameter + assert_imports(root, core_root) + baseline_parameters = system_module.system.parameters + parameters = baseline_parameters + selectors = None + if args.mode == "trustees": + trustees = importlib.import_module( + "policyengine_us.reforms.ssa.trustees_core_thresholds" + ) + selectors = selector_metadata(trustees, baseline_parameters) + # Preserve the genuine original constructor and explicit unchanged defaults. + reformed_system = country.CountryTaxBenefitSystem( + reform=( + trustees.create_trustees_core_thresholds_reform( + **tables["trustees_defaults"] + ), + ) + ) + parameters = reformed_system.parameters + catalog = names_catalog( + p.name for p in parameters.get_descendants() if isinstance(p, Parameter) + ) + runtime_sha = hashlib.sha256( + json.dumps(bindings["runtime"], sort_keys=True).encode() + ).hexdigest() + common = { + "schema_version": 1, + "source": source, + "bindings_sha256": binding_sha, + "runtime_binding_sha256": runtime_sha, + "mode": args.mode, + "dates": tables["dates"], + "history": tables["history"], + "trustees_view_dates": tables["trustees_view_dates"], + "reform_arguments": tables["trustees_defaults"] + if args.mode == "trustees" + else None, + "country_origin": country.__file__, + "core_origin": core.__file__, + "qualification": bindings["runtime"]["qualification"], + "qualified_core_version": qualification["core_version"], + "python": sys.executable, + "python_realpath": str(Path(sys.executable).resolve()), + "python_version": platform.python_version(), + "machine": platform.machine(), + "prefix": sys.prefix, + "argv": sys.argv, + "thread_environment": { + name: os.environ.get(name) + for name in ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", + "NUMEXPR_NUM_THREADS", + ) + }, + "started_utc": started, + "parameter_count_observed": len(catalog), + "helper_sha256": sha256_file(__file__), + "selectors": selectors, + "remote_resources": resources, + "resource_start_sidecar": { + "path": str(resource_start_path), + "sha256": sha256_file(resource_start_path), + }, + "image_id": image_id, + } + out = Path(args.out).resolve() + manifest_out = Path(args.manifest_out).resolve() + if args.probe_only: + common["remote_resources_final"] = resource_snapshot() + common.update( + probe_only=True, + complete=False, + probe=lookup_value( + parameters.gov.irs.deductions.standard.amount.SINGLE, "2027-01-01" + ), + ) + assert_imports(root, core_root) + verify_source(source) + common["elapsed_seconds"] = time.monotonic() - clock + write_new_json(manifest_out, common) + return common + # Independent second traversal. Grid completeness derives from the earlier catalog. + by_name = {} + for parameter in parameters.get_descendants(): + if isinstance(parameter, Parameter): + if parameter.name in by_name: + raise ValueError("Duplicate parameter on emission traversal") + by_name[parameter.name] = parameter + if set(by_name) != set(catalog): + raise ValueError("Parameter catalog changed between traversals") + + def rows(): + for name in sorted(by_name): + dates = sorted(set(tables["dates"]) | set(tables["history"].get(name, ()))) + for date in dates: + yield { + "path": name, + "date": date, + "mode": args.mode, + "value": lookup_value(by_name[name], date), + } + + partial = out.with_name(out.name + ".partial") + counts = {} + row_count = 0 + with partial.open("x") as stream: + for row in validated_rows( + catalog, tables["dates"], tables["history"], args.mode, rows() + ): + stream.write(json.dumps(row, sort_keys=True, allow_nan=False) + "\n") + kind = row["value"]["kind"] + counts[kind] = counts.get(kind, 0) + 1 + row_count += 1 + stream.flush() + os.fsync(stream.fileno()) + assert_imports(root, core_root) + verify_source(source) + verify_runtime(bindings["runtime"]) + common["remote_resources_final"] = resource_snapshot() + if out.exists(): + raise FileExistsError(out) + os.link(partial, out) + partial.unlink() # Only this export's newly created temporary output. + catalog_out = out.with_name(out.name + ".catalog.json") + write_new_json( + catalog_out, + {"names": catalog, "source_commit": source["commit"], "mode": args.mode}, + ) + history = {} + for name in tables["history"]: + if name in by_name: + parameter = by_name[name] + history[name] = { + "metadata": encode_value(parameter.metadata), + "stated": [ + { + "instant": value.instant_str, + "value": encode_value(value.value), + "file_path": str(value.file_path) + if getattr(value, "file_path", None) + else None, + "is_stated": getattr(value, "file_path", None) is not None, + } + for value in parameter.values_list + ], + } + common.update( + complete=True, + probe_only=False, + grid_validated=True, + rows_observed=row_count, + value_kinds=counts, + review_required=bool(counts.get("LOOKUP_ERROR") or counts.get("UNSUPPORTED")), + history_details=history, + elapsed_seconds=time.monotonic() - clock, + ended_utc=datetime.now(timezone.utc).isoformat(), + outputs={ + "values": {"path": str(out), "sha256": sha256_file(out)}, + "catalog": {"path": str(catalog_out), "sha256": sha256_file(catalog_out)}, + }, + ) + write_new_json(manifest_out, common) # Completion manifest publishes last. + return common + + +def run_export(args): + failure = None + try: + return export_entry(args) + except BaseException as error: + failure = repr(error)[:1024] + raise + finally: + record = capture_resources("final", failure) + record.update( + source_sha_command=args.source_sha, + tree_sha_command=args.tree_sha, + mode_command=args.mode, + at=datetime.now(timezone.utc).isoformat(), + ) + path = ( + Path(args.manifest_out) + .resolve() + .with_name(Path(args.manifest_out).name + ".resources-final.json") + ) + try: + write_new_json(path, record) + except Exception as error: + print( + json.dumps( + { + "final_resources_status": "UNAVAILABLE", + "sidecar_error": repr(error)[:1024], + } + ), + file=sys.stderr, + ) + if failure is None: + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--bindings", required=True) + parser.add_argument("--source-sha", required=True) + parser.add_argument("--tree-sha", required=True) + parser.add_argument("--mode", choices=("baseline", "trustees"), required=True) + parser.add_argument("--year-profile", choices=("original26",), required=True) + parser.add_argument("--history-path", choices=(HISTORY_PATH,), required=True) + parser.add_argument("--probe-only", action="store_true") + parser.add_argument("--out", required=True) + parser.add_argument("--manifest-out", required=True) + args = parser.parse_args() + result = run_export(args) + print( + json.dumps( + { + "complete": result["complete"], + "probe_only": result["probe_only"], + "parameter_count_observed": result["parameter_count_observed"], + "parity_approved": False, + } + ) + ) + + +if __name__ == "__main__": + main() diff --git a/.github/us10783-validation/remote.py b/.github/us10783-validation/remote.py new file mode 100644 index 00000000000..f908ab42ce7 --- /dev/null +++ b/.github/us10783-validation/remote.py @@ -0,0 +1,1101 @@ +"""Run a bounded, serial parameter comparison on a task-owned Linux runner.""" + +from __future__ import annotations + +import argparse +from contextlib import ExitStack +from datetime import datetime, timezone +import gzip +import hashlib +import importlib.metadata as md +import importlib.util +import json +import os +from pathlib import Path +import platform +import re +import shutil +import signal +import subprocess +import sys +import tarfile +import time +import zipfile + +from atomic import sha256_file, write_new_json +from comparison_data import ( + HISTORY_DATES, + HISTORY_PATH, + ORIGINAL_DATES, + TRUSTEES_VIEW_YEARS, + compare_streams, + exact_equal, + read_export, + tolerance_equal, +) + +REF = "refs/heads/codex/us10783-core336-validation-20261113" +SOURCES = { + "A": ( + "3386304d28eeb148254313bc6c1b790c57749933", + "92e6eed37b5e1ed041ffca6848bab793dbb071d9", + ), + "B": ( + "47c4e8720bb6ef1d5818ff026ed3d9e862e32c76", + "bb89147a46c5a9affcb2ae7d778654c009af286b", + ), + "C": ( + "561afc58501cbe98a76342f1dd6377a220c5c6f2", + "254d690fe960e58dae42ac6a43c0ab1f6f184033", + ), +} +LOCK = "5e3c82e8f3215dd57172c81855b931cb42703e6b906b2f1c8a3003c3d462c604" +PROJECT = "a4b47e273ebcae7c4d0cee66945d151896f724e2e660a8f0ffcf35230e7bab79" +CORE = "eb7943fe5f1c63a3b70d60e673924a0703d5608dee330a4bcadb6911e0243b98" +UV = "2b428396f12572d4429cf210ca234dd599a33b3af0958a4d5ed569d63e3f344f" +MEMORY = 2 * 1024**3 +ARTIFACT_LIMIT = 1024**3 +HELPERS = ( + "remote.py", + "atomic.py", + "parameter_export.py", + "comparison_data.py", + "Dockerfile", +) +THREADS = ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", + "NUMEXPR_NUM_THREADS", +) + + +def validate_limits(snapshot): + if snapshot["memory.max"] != str(MEMORY) or snapshot["memory.swap.max"] != "0": + raise ValueError("Require a real 2GiB cgroup with no swap") + quota, period = snapshot["cpu.max"].split() + if quota == "max" or not 0 < int(quota) <= int(period): + raise ValueError("Require a positive CPU quota no greater than one CPU") + if snapshot["threads"] != {name: "1" for name in THREADS}: + raise ValueError("Require serial numerical-library thread limits") + return snapshot + + +def resource_snapshot(deadline=None): + root = Path("/sys/fs/cgroup") + deadline = time.monotonic() + 2 if deadline is None else deadline + snapshot = {} + for name in ( + "memory.max", + "memory.swap.max", + "memory.peak", + "memory.events", + "cpu.max", + ): + remaining(deadline, 2) + with (root / name).open() as stream: + value = stream.read(16385) + remaining(deadline, 2) + if len(value) > 16384: + raise ValueError("Unexpectedly large cgroup resource record") + snapshot[name] = value.strip() + snapshot["threads"] = {name: os.environ.get(name) for name in THREADS} + return validate_limits(snapshot) + + +def resource_record(stage, snapshot, error=None): + return { + "stage": stage, + "status": "AVAILABLE" if snapshot is not None else "UNAVAILABLE", + "snapshot": snapshot, + "error": error, + } + + +def capture_resources(stage, failure=None): + try: + record = resource_record(stage, resource_snapshot(time.monotonic() + 2)) + except Exception as error: + record = resource_record(stage, None, repr(error)[:1024]) + record["export_failure"] = failure + return record + + +def final_resource_record(sidecar, docker_state): + killed = docker_state["OOMKilled"] or docker_state["ExitCode"] in (137, 143) + if sidecar is None or killed: + record = resource_record( + "final", None, "No final cgroup measurement after process exit/kill" + ) + record["last_sidecar"] = sidecar + else: + record = dict(sidecar) + record["docker_state"] = docker_state + return record + + +def validate_context(env): + expected = { + "GITHUB_REPOSITORY": "PolicyEngine/policyengine-us", + "GITHUB_EVENT_NAME": "workflow_dispatch", + "GITHUB_REF": REF, + "GITHUB_WORKFLOW_REF": "PolicyEngine/policyengine-us/.github/workflows/docs.yaml@" + + REF, + } + if any(env.get(key) != value for key, value in expected.items()): + raise ValueError("Wrong canonical workflow dispatch identity") + if not re.fullmatch(r"[0-9a-f]{40}", env.get("GITHUB_SHA", "")): + raise ValueError("Missing immutable workflow SHA") + if any( + not re.fullmatch(r"[0-9]+", env.get(key, "")) + for key in ("GITHUB_RUN_ID", "GITHUB_RUN_ATTEMPT") + ): + raise ValueError("Missing run identity") + return { + key: env[key] + for key in (*expected, "GITHUB_SHA", "GITHUB_RUN_ID", "GITHUB_RUN_ATTEMPT") + } + + +def validate_source_record(source): + sides = [side for side in SOURCES if source["root"] == "/sources/" + side] + if len(sides) != 1 or (source["commit"], source["tree"]) != SOURCES[sides[0]]: + raise ValueError("Source differs from the fixed A/B/C comparison") + if ( + source["manifest"]["path"] + != "/validation/evidence/" + sides[0] + "-source.json" + ): + raise ValueError("Source manifest path differs") + + +def validate_export_receipt(receipt, side, mode, image): + if ( + receipt.get("complete") is not True + or receipt.get("grid_validated") is not True + or receipt.get("probe_only") is not False + or receipt.get("mode") != mode + or receipt.get("image_id") != image + or (receipt["source"]["commit"], receipt["source"]["tree"]) != SOURCES[side] + ): + raise ValueError("Incomplete or misidentified full export") + expected = { + "values": f"/output/{side}-{mode}.jsonl", + "catalog": f"/output/{side}-{mode}.jsonl.catalog.json", + } + if set(receipt["outputs"]) != set(expected): + raise ValueError("Unexpected export output catalog") + for key, path in expected.items(): + if receipt["outputs"][key]["path"] != path or not re.fullmatch( + r"[0-9a-f]{64}", receipt["outputs"][key]["sha256"] + ): + raise ValueError("Unexpected original Linux receipt path/hash") + + +def validate_container(info, container_id, image_id, owner): + host = info["HostConfig"] + if ( + info["Id"] != container_id + or info["Image"] != image_id + or info["Config"]["Labels"].get("us10783.run") != owner + ): + raise ValueError("Container ownership/image identity changed") + if ( + host["Memory"] != MEMORY + or host["MemorySwap"] != MEMORY + or host["NanoCpus"] != 1_000_000_000 + or host["NetworkMode"] != "none" + or not host["ReadonlyRootfs"] + or host["CapDrop"] != ["ALL"] + ): + raise ValueError("Container isolation differs from the reviewed limits") + + +def remaining(deadline, maximum): + seconds = min(maximum, deadline - time.monotonic()) + if seconds <= 0: + raise TimeoutError("Global deadline reached; no retry or timeout increase") + return seconds + + +def pipeline_budget(stop_at, now): + if not 0 < stop_at - now <= 1020: + raise ValueError("Invalid absolute job deadline") + seconds = min(900, stop_at - now - 150) + if seconds <= 0: + raise TimeoutError("Bootstrap consumed the execution window") + return seconds + + +def command(argv, *, timeout, cwd=None, out=None): + return subprocess.run( + argv, + cwd=cwd, + stdin=subprocess.DEVNULL, + stdout=out or subprocess.PIPE, + stderr=subprocess.STDOUT, + text=out is None, + check=True, + timeout=timeout, + ) + + +def bounded_blocks(stream, deadline, clock=time.monotonic): + while True: + if clock() >= deadline: + raise TimeoutError("Read deadline reached") + block = stream.read(1024 * 1024) + if clock() >= deadline: + raise TimeoutError("Read deadline reached") + if not block: + return + yield block + + +def stream_digest(stream, deadline, clock=time.monotonic): + digest = hashlib.sha256() + for block in bounded_blocks(stream, deadline, clock): + digest.update(block) + return digest.hexdigest() + + +def file_digest(path, deadline): + with path.open("rb") as stream: + return stream_digest(stream, deadline) + + +def download_plan(url, target, seconds): + if not 0 < seconds <= 30: + raise ValueError("Require a positive transfer bound no greater than 30 seconds") + return [ + "curl", + "--disable", + "--fail", + "--show-error", + "--silent", + "--location", + "--proto", + "=https", + "--proto-redir", + "=https", + "--max-redirs", + "5", + "--max-time", + str(seconds), + "--output", + str(target), + url, + ] + + +def download(url, target, expected, deadline): + seconds = remaining(deadline, 30) + argv = download_plan(url, target, seconds) + with target.open("xb"): + pass + command(argv, timeout=remaining(deadline, seconds)) + if file_digest(target, deadline) != expected: + raise ValueError("Downloaded release bytes differ") + + +def prepare(repo, build, deadline): + build.mkdir() + (build / "sources").mkdir() + (build / "evidence").mkdir() + (build / "helpers").mkdir() + for name in HELPERS: + shutil.copyfile(Path(__file__).parent / name, build / "helpers" / name) + for side, (commit, tree) in SOURCES.items(): + command( + [ + "git", + "fetch", + "--no-tags", + "--depth=1", + "https://github.com/PolicyEngine/policyengine-us.git", + commit, + ], + cwd=repo, + timeout=remaining(deadline, 90), + ) + observed = command( + ["git", "rev-parse", commit + "^{tree}"], + cwd=repo, + timeout=remaining(deadline, 10), + ).stdout.strip() + if observed != tree: + raise ValueError("Source tree differs") + catalog = command( + ["git", "ls-tree", "-rz", commit], cwd=repo, timeout=remaining(deadline, 20) + ).stdout + entries = {} + for record in catalog.split("\0"): + if record: + attributes, path = record.split("\t", 1) + mode, kind, blob = attributes.split() + if ( + mode not in ("100644", "100755") + or kind != "blob" + or Path(path).is_absolute() + or ".." in Path(path).parts + ): + raise ValueError("Unsupported tracked source entry") + entries[path] = (mode, blob) + archive = build / (side + ".tar") + with archive.open("xb") as stream: + command( + ["git", "archive", "--format=tar", commit], + cwd=repo, + timeout=remaining(deadline, 30), + out=stream, + ) + if archive.stat().st_size > 512 * 1024**2: + raise ValueError("Source archive exceeds its disk allowance") + root = build / "sources" / side + root.mkdir() + with tarfile.open(archive) as stream: + if any(not (item.isfile() or item.isdir()) for item in stream.getmembers()): + raise ValueError("Source archive contains links or devices") + stream.extractall(root, filter="data") + files = {} + actual = { + p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file() + } + if actual != set(entries): + raise ValueError("Tracked source catalog differs after extraction") + for path, (mode, blob) in entries.items(): + content = (root / path).read_bytes() + if ( + hashlib.sha1( + b"blob " + str(len(content)).encode() + b"\0" + content + ).hexdigest() + != blob + ): + raise ValueError("Tracked Git blob differs") + if bool((root / path).stat().st_mode & 0o111) != (mode == "100755"): + raise ValueError("Tracked source mode differs") + files[path] = hashlib.sha256(content).hexdigest() + write_new_json( + build / "evidence" / (side + "-source.json"), + { + "commit": commit, + "tree": tree, + "files": files, + "archive_sha256": sha256_file(archive), + }, + ) + archive.unlink() + if ( + sha256_file(build / "sources/C/uv.lock") != LOCK + or sha256_file(build / "sources/C/pyproject.toml") != PROJECT + ): + raise ValueError("C lock/project differs") + download( + "https://github.com/astral-sh/uv/releases/download/0.13.4/uv-x86_64-unknown-linux-gnu.tar.gz", + build / "uv.tar.gz", + UV, + deadline, + ) + download( + "https://files.pythonhosted.org/packages/d6/07/f0d649c065a12ca9ef35543ced8bb5b1b51bc1b2373c90c6f5c5ad39b69b/policyengine_core-3.36.0-py3-none-any.whl", + build / "core.whl", + CORE, + deadline, + ) + + +def qualify(): + evidence = Path("/validation/evidence") + if ( + sys.version_info[:3] != (3, 14, 7) + or platform.machine() != "x86_64" + or sys.platform != "linux" + ): + raise ValueError("Wrong Linux interpreter") + root = Path("/sources/C") + if ( + sha256_file(root / "uv.lock") != LOCK + or sha256_file(root / "pyproject.toml") != PROJECT + ): + raise ValueError("Wrong C project metadata") + if sha256_file(evidence / "uv.tar.gz") != UV: + raise ValueError("Wrong pinned uv archive") + if command( + ["/opt/uv-x86_64-unknown-linux-gnu/uv", "--version"], timeout=10 + ).stdout.split()[:2] != ["uv", "0.13.4"]: + raise ValueError("Wrong uv binary version") + argv = [ + "/opt/uv-x86_64-unknown-linux-gnu/uv", + "sync", + "--check", + "--dry-run", + "--locked", + "--offline", + "--extra", + "dev", + "--no-python-downloads", + "--python", + sys.executable, + ] + check = command(argv, cwd=root, timeout=30) + dependency = { + "exit": check.returncode, + "argv": argv, + "output_sha256": hashlib.sha256(check.stdout.encode()).hexdigest(), + "installed": sorted( + (d.metadata["Name"], d.version) for d in md.distributions() + ), + } + write_new_json(evidence / "dependencies.json", dependency) + core = md.distribution("policyengine-core") + country = md.distribution("policyengine-us") + if ( + core.version != "3.36.0" + or country.version != "2.118.10" + or sha256_file(evidence / "core.whl") != CORE + ): + raise ValueError("Wrong released Core/project installation") + direct = json.loads(country.read_text("direct_url.json")) + if direct != {"url": root.as_uri(), "dir_info": {"editable": True}}: + raise ValueError("Wrong editable country origin") + matched = [] + with zipfile.ZipFile(evidence / "core.whl") as wheel: + for name in wheel.namelist(): + if name.startswith("policyengine_core/") and not name.endswith("/"): + expected = hashlib.sha256(wheel.read(name)).hexdigest() + if sha256_file(core.locate_file(name)) != expected: + raise ValueError("Installed Core wheel bytes differ") + matched.append({"path": name, "sha256": expected}) + if len(matched) != 195: + raise ValueError("Incomplete Core package verification") + core_root = Path(core.locate_file("policyengine_core")).resolve() + if ( + sha256_file(core_root / "parameters/operations/uprate_parameters.py") + != "21099b3aabc79777036d588d336f1b555cb649c39804e7b8437183121cd94a68" + ): + raise ValueError("Wrong uprating implementation") + for name, expected in ( + ("policyengine_us", root / "policyengine_us/__init__.py"), + ("policyengine_core", core_root / "__init__.py"), + ): + if Path(importlib.util.find_spec(name).origin).resolve() != expected: + raise ValueError("Wrong cold package origin") + if any( + n == "policyengine_us" + or n.startswith("policyengine_us.") + or n == "policyengine_core" + or n.startswith("policyengine_core.") + for n in sys.modules + ): + raise ValueError("Qualification imported a model") + qualification = { + "status": "PASS metadata and installed bytes only", + "core_version": core.version, + "country_distribution_version": country.version, + "core_files_matched": matched, + "core_wheel_sha256": CORE, + "lock_sha256": LOCK, + "project_sha256": PROJECT, + "uv_archive_sha256": UV, + "installed_dependencies": dependency["installed"], + "python": sys.version, + "python_realpath": str(Path(sys.executable).resolve()), + "machine": platform.machine(), + "platform": platform.platform(), + } + write_new_json(evidence / "qualification.json", qualification) + runtime = { + "python_realpath": str(Path(sys.executable).resolve()), + "prefix": sys.prefix, + "machine": platform.machine(), + "python_version": platform.python_version(), + "core_root": str(core_root), + "qualification": { + "path": str(evidence / "qualification.json"), + "sha256": sha256_file(evidence / "qualification.json"), + }, + "dependency_evidence": { + "path": str(evidence / "dependencies.json"), + "sha256": sha256_file(evidence / "dependencies.json"), + }, + } + for side, (commit, tree) in SOURCES.items(): + manifest = evidence / (side + "-source.json") + write_new_json( + evidence / (side + "-bindings.json"), + { + "schema_version": 1, + "source": { + "root": "/sources/" + side, + "commit": commit, + "tree": tree, + "manifest": { + "path": str(manifest), + "sha256": sha256_file(manifest), + }, + }, + "runtime": runtime, + "tables": { + "dates": list(ORIGINAL_DATES), + "history": {HISTORY_PATH: list(HISTORY_DATES)}, + "trustees_view_dates": [ + f"{year}-01-01" for year in TRUSTEES_VIEW_YEARS + ], + "trustees_defaults": { + "start_year": 2035, + "end_year": 2100, + "projection_base_year": 2026, + }, + }, + }, + ) + + +def publish_provenance(): + evidence = Path("/validation/evidence") + for source in sorted(evidence.glob("*.json")): + target = Path("/output") / ("runtime-" + source.name) + if target.exists(): + if sha256_file(target) != sha256_file(source): + raise ValueError("Published runtime provenance changed") + else: + with source.open("rb") as original, target.open("xb") as copy: + shutil.copyfileobj(original, copy) + + +def container(argv, label, output, image, owner, deadline, maximum): + name = "us10783-" + owner + "-" + label + create = [ + "docker", + "create", + "--name", + name, + "--label", + "us10783.run=" + owner, + "--memory", + str(MEMORY), + "--memory-swap", + str(MEMORY), + "--cpus", + "1", + "--network", + "none", + "--read-only", + "--cap-drop", + "ALL", + "--security-opt", + "no-new-privileges", + "--pids-limit", + "64", + "--tmpfs", + "/tmp:rw,size=67108864", + "--mount", + "type=bind,src=" + str(output) + ",dst=/output", + ] + for key in THREADS: + create += ["--env", key + "=1"] + create += [ + "--env", + "US10783_IMAGE_ID=" + image, + image, + "/sources/C/.venv/bin/python", + "-B", + *argv, + ] + try: + cid = command(create, timeout=remaining(deadline, 20)).stdout.strip() + except BaseException: + # Reconcile a timed-out Docker client before treating creation as absent. + observed = subprocess.run( + ["docker", "inspect", name], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + timeout=10, + ) + if observed.returncode == 0: + info = json.loads(observed.stdout)[0] + validate_container(info, info["Id"], image, owner) + if info["State"]["Running"]: + raise RuntimeError( + "Unexpected running container after failed create; cleanup pending" + ) + command(["docker", "rm", info["Id"]], timeout=10) + write_new_json( + output / (label + ".create-failure.json"), + { + "reconciled": observed.returncode == 0, + "inspect_exit": observed.returncode, + "model_started": False, + }, + ) + raise + if not re.fullmatch(r"[0-9a-f]{64}", cid): + raise ValueError("Docker did not return an owned container ID") + + def inspect(): + info = json.loads(command(["docker", "inspect", cid], timeout=10).stdout)[0] + validate_container(info, cid, image, owner) + return info + + process = None + failure = None + started = time.monotonic() + try: + inspect() + with (output / (label + ".log")).open("x") as log: + process = subprocess.Popen( + ["docker", "start", "--attach", cid], + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + ) + end = min(deadline, started + maximum) + while process.poll() is None: + if time.monotonic() >= end: + raise TimeoutError("Model or global wall deadline reached") + if shutil.disk_usage(output).free < 1024**3: + raise OSError("Runner disk headroom fell below 1GiB") + time.sleep(0.25) + info = inspect() + if ( + process.returncode + or info["State"]["ExitCode"] + or info["State"]["OOMKilled"] + ): + raise RuntimeError("Container failed or reached its memory cap") + except BaseException as error: + failure = repr(error) + raise + finally: + try: + info = inspect() + if info["State"]["Running"]: + command(["docker", "stop", "--time", "10", cid], timeout=15) + info = inspect() + if info["State"]["Running"]: + raise RuntimeError("Owned container cleanup pending") + if process is not None: + process.wait(timeout=15) + command(["docker", "rm", cid], timeout=10) + except BaseException as cleanup_error: + write_new_json( + output / (label + ".container.json"), + { + "id": cid, + "image": image, + "owner": owner, + "failure": failure, + "cleanup_verified": False, + "cleanup_error": repr(cleanup_error), + "final_resources": resource_record( + "final", None, "Docker cleanup/inspection did not complete" + ), + }, + ) + raise + final_sidecar_path = output / (label + ".manifest.json.resources-final.json") + sidecar = None + sidecar_error = None + if final_sidecar_path.exists(): + try: + sidecar = json.loads(final_sidecar_path.read_text()) + except Exception as error: + sidecar_error = repr(error)[:1024] + final_resources = final_resource_record(sidecar, info["State"]) + final_resources["sidecar_read_error"] = sidecar_error + write_new_json(output / (label + ".resources-host-final.json"), final_resources) + write_new_json( + output / (label + ".container.json"), + { + "id": cid, + "image": image, + "owner": owner, + "state": info["State"], + "final_resources_status": final_resources["status"], + "limits": { + key: info["HostConfig"][key] + for key in ( + "Memory", + "MemorySwap", + "NanoCpus", + "NetworkMode", + "ReadonlyRootfs", + "CapDrop", + ) + }, + "elapsed_seconds": time.monotonic() - started, + "failure": failure, + "cleanup_verified": True, + }, + ) + + +def compare(): + output = Path("/output") + manifests = {} + for side, (commit, _) in SOURCES.items(): + for mode in ("baseline", "trustees"): + manifest, _ = read_export(output / f"{side}-{mode}.manifest.json") + if ( + manifest["source"]["commit"] != commit + or manifest["mode"] != mode + or manifest.get("probe_only") + ): + raise ValueError("Wrong final export identity") + manifests[side, mode] = manifest + if len({m["runtime_binding_sha256"] for m in manifests.values()}) != 1: + raise ValueError("Exports used different runtime bindings") + if {m["image_id"] for m in manifests.values()} != {os.environ["US10783_IMAGE_ID"]}: + raise ValueError("Exports used another image") + counts = {} + changed = {} + with ExitStack() as stack: + streams = {} + + def ensure(name): + if name not in streams: + streams[name] = stack.enter_context( + (output / (name + ".jsonl")).open("x") + ) + counts[name] = 0 + + def emit(name, row): + ensure(name) + streams[name].write(json.dumps(row, sort_keys=True, allow_nan=False) + "\n") + counts[name] = counts.get(name, 0) + 1 + + for mode in ("baseline", "trustees"): + for pair in ("AC", "AB", "BC"): + for kind in ("raw", "legacy"): + ensure(mode + "-" + pair + "-" + kind) + ensure(mode + "-ABC-raw") + ensure(mode + "-earned-history-raw") + ensure("trustees-original12-raw") + sides = { + s: read_export(output / f"{s}-{mode}.manifest.json")[1] for s in SOURCES + } + for row in compare_streams(sides): + values = row["sides"] + ab, bc, ac = ( + exact_equal(values[x], values[y]) + for x, y in (("A", "B"), ("B", "C"), ("A", "C")) + ) + row["attribution"] = ( + "PR-only" + if ab + else ( + "upstream-only" + if bc + else ("unresolved-interaction" if ac else "both") + ) + ) + row["catalog_addition_or_removal"] = any( + v["kind"] == "ABSENT_SIDE" for v in values.values() + ) + emit(mode + "-ABC-raw", row) + if mode == "trustees" and row["date"] in { + f"{y}-01-01" for y in TRUSTEES_VIEW_YEARS + }: + emit("trustees-original12-raw", row) + if row["path"] == HISTORY_PATH and row["date"] in HISTORY_DATES: + emit(mode + "-earned-history-raw", row) + for x, y in (("A", "C"), ("A", "B"), ("B", "C")): + if not exact_equal(values[x], values[y]): + emit(mode + "-" + x + y + "-raw", row) + if not tolerance_equal(values[x], values[y]): + emit(mode + "-" + x + y + "-legacy", row) + for side in SOURCES: + ensure(side + "-baseline-trustees-raw") + ensure(side + "-baseline-trustees-legacy") + sides = { + m: read_export(output / f"{side}-{m}.manifest.json")[1] + for m in ("baseline", "trustees") + } + paths = set() + for row in compare_streams(sides, allow_cross_mode=True): + emit(side + "-baseline-trustees-raw", row) + if not row["legacy_tolerance_equal"]: + emit(side + "-baseline-trustees-legacy", row) + paths.add(row["path"]) + changed[side] = sorted(paths) + selection = {} + for x, y in (("A", "C"), ("A", "B"), ("B", "C")): + selection[x + y] = {} + for key in ("initial", "effective"): + left, right = ( + manifests[s, "trustees"]["selectors"].get(key) for s in (x, y) + ) + selection[x + y][key] = ( + None + if left is None or right is None + else { + "only_" + x: sorted(set(left) - set(right)), + "only_" + y: sorted(set(right) - set(left)), + } + ) + followers = [ + { + v["path"]: v["uprating"] + for v in manifests[s, "trustees"]["selectors"]["followers"] + } + for s in (x, y) + ] + selection[x + y]["follower_differences"] = [ + { + "path": path, + x: followers[0].get(path, {"kind": "ABSENT_SIDE"}), + y: followers[1].get(path, {"kind": "ABSENT_SIDE"}), + } + for path in sorted(set(followers[0]) | set(followers[1])) + if followers[0].get(path) != followers[1].get(path) + ] + write_new_json( + output / "comparison.json", + { + "complete": True, + "counts": counts, + "actual_changed_paths": changed, + "selection_symmetric_differences": selection, + "outputs": { + name + ".jsonl": sha256_file(output / (name + ".jsonl")) + for name in streams + }, + "review_required": any(m["review_required"] for m in manifests.values()), + "parity_approved": False, + }, + ) + + +def package(output, artifact): + staging = artifact.with_name(artifact.name + ".partial") + staging.mkdir() + records = {} + total = 0 + deadline = time.monotonic() + 75 + for path in sorted(output.iterdir()): + if not path.is_file() or path.suffix not in ( + ".json", + ".jsonl", + ".log", + ".partial", + ): + raise ValueError("Unexpected output artifact path") + target = staging / (path.name + ".gz") + with path.open("rb") as source, target.open("xb") as compressed: + with gzip.GzipFile( + filename="", mode="wb", compresslevel=1, fileobj=compressed, mtime=0 + ) as stream: + for block in bounded_blocks(source, deadline): + stream.write(block) + if total + target.stat().st_size > ARTIFACT_LIMIT - 2 * 1024**2: + raise ValueError( + "Compressed evidence reached its upload allowance" + ) + total += target.stat().st_size + if total > ARTIFACT_LIMIT: + raise ValueError("Compressed artifacts exceed 1GiB; no upload") + with gzip.open(target, "rb") as stream: + digest = stream_digest(stream, deadline) + if digest != file_digest(path, deadline): + raise ValueError("Compressed evidence differs") + records[target.name] = { + "compressed_sha256": file_digest(target, deadline), + "raw_sha256": digest, + "compressed_bytes": target.stat().st_size, + "raw_bytes": path.stat().st_size, + } + write_new_json( + staging / "MANIFEST.json", + { + "files": records, + "compressed_bytes": total, + "six_exports_complete": (output / "exports.json").exists(), + "parity_approved": False, + }, + ) + staging.rename(artifact) + + +def run(repo, work): + context = validate_context(os.environ) + if ( + command(["git", "rev-parse", "HEAD"], cwd=repo, timeout=10).stdout.strip() + != context["GITHUB_SHA"] + ): + raise ValueError("Checkout differs from the workflow commit") + work.mkdir() + output = work / "output" + output.mkdir() + artifact = work / "artifact" + budget = pipeline_budget(int(os.environ["US10783_STOP_AT"]), time.time()) + deadline = time.monotonic() + budget + owner = context["GITHUB_RUN_ID"] + "-" + context["GITHUB_RUN_ATTEMPT"] + write_new_json( + output / "run.json", + { + "github": context, + "sources": SOURCES, + "helpers": {n: sha256_file(Path(__file__).parent / n) for n in HELPERS}, + "pipeline_budget_seconds": budget, + "maximum_pipeline_seconds": 900, + "cleanup_and_packaging_reserve_seconds": 150, + "outer_job_minutes": 20, + "artifact_retention_days": 1, + }, + ) + + def cancelled(number, frame): + raise InterruptedError("Runner requested cancellation") + + signal.signal(signal.SIGTERM, cancelled) + error = None + try: + if shutil.disk_usage(work).free < 8 * 1024**3: + raise OSError("Require 8GiB free before source/image preparation") + prepare(repo, work / "build", deadline) + with (output / "build.log").open("x") as log: + command( + [ + "docker", + "build", + "--platform", + "linux/amd64", + "--iidfile", + str(work / "image.id"), + "-f", + str(work / "build/helpers/Dockerfile"), + str(work / "build"), + ], + timeout=remaining(deadline, 300), + out=log, + ) + image = (work / "image.id").read_text().strip() + if not re.fullmatch(r"sha256:[0-9a-f]{64}", image): + raise ValueError("Missing immutable image identity") + write_new_json( + output / "image.json", + {"id": image, "core_wheel_sha256": CORE, "uv_archive_sha256": UV}, + ) + for side, mode in ( + ("C", "baseline"), + ("C", "trustees"), + ("A", "baseline"), + ("A", "trustees"), + ("B", "baseline"), + ("B", "trustees"), + ): + label = side + "-" + mode + commit, tree = SOURCES[side] + argv = [ + "/validation/parameter_export.py", + "--bindings", + "/validation/evidence/" + side + "-bindings.json", + "--source-sha", + commit, + "--tree-sha", + tree, + "--mode", + mode, + "--year-profile", + "original26", + "--history-path", + HISTORY_PATH, + "--out", + "/output/" + label + ".jsonl", + "--manifest-out", + "/output/" + label + ".manifest.json", + ] + container(argv, label, output, image, owner, deadline, 600) + runtime_ids = set() + relocation = {} + for side in SOURCES: + for mode in ("baseline", "trustees"): + receipt_path = output / f"{side}-{mode}.manifest.json" + receipt = json.loads(receipt_path.read_text()) + validate_export_receipt(receipt, side, mode, image) + runtime_ids.add(receipt["runtime_binding_sha256"]) + for record in receipt["outputs"].values(): + target = output / Path(record["path"]).name + remaining(deadline, 600) + if file_digest(target, deadline) != record["sha256"]: + raise ValueError("Completed export output hash differs") + relocation[record["path"]] = { + "member": target.name + ".gz", + "raw_sha256": record["sha256"], + } + if len(runtime_ids) != 1: + raise ValueError("Completed exports used different runtime bindings") + for target in output.glob("runtime-*.json"): + original = "/validation/evidence/" + target.name.removeprefix("runtime-") + relocation[original] = { + "member": target.name + ".gz", + "raw_sha256": sha256_file(target), + } + write_new_json( + output / "relocation.json", + { + "original_linux_paths": relocation, + "receipt_bytes_unchanged": True, + "local_paths": None, + }, + ) + write_new_json( + output / "exports.json", + { + "status": "SIX_EXPORTS_COMPLETE", + "parity_approved": False, + "comparison_status": "OFFLINE_COMPARISONS_REQUIRED", + "runtime_binding_sha256": runtime_ids.pop(), + }, + ) + except BaseException as failure: + error = repr(failure) + finally: + write_new_json( + output / "terminal.json", + { + "error": error, + "six_exports_complete": (output / "exports.json").exists(), + "at": datetime.now(timezone.utc).isoformat(), + "parity_approved": False, + }, + ) + try: + package(output, artifact) + except BaseException as packaging_error: + artifact.mkdir() + write_new_json( + artifact / "ERROR.json", + { + "error": repr(packaging_error), + "raw_evidence_uploaded": False, + "complete_comparison": False, + "parity_approved": False, + }, + ) + for name in ("run.json", "terminal.json"): + shutil.copyfile(output / name, artifact / name) + if error is None: + error = repr(packaging_error) + if error: + raise RuntimeError(error) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("run", "qualify", "compare")) + parser.add_argument("--repo", type=Path) + parser.add_argument("--work", type=Path) + args = parser.parse_args() + if args.action == "qualify": + qualify() + elif args.action == "compare": + compare() + else: + run(args.repo.resolve(), args.work.resolve()) + + +if __name__ == "__main__": + main() diff --git a/.github/us10783-validation/test_entry.py b/.github/us10783-validation/test_entry.py new file mode 100644 index 00000000000..cd97fc35089 --- /dev/null +++ b/.github/us10783-validation/test_entry.py @@ -0,0 +1,416 @@ +"""Check platform decisions with inert data and compare the preserved source AST.""" + +import argparse +import ast +import hashlib +import io +import json +from pathlib import Path +import sys +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +DENIED = [] + + +def audit(event, arguments): + forbidden = event in { + "subprocess.Popen", + "os.system", + "os.posix_spawn", + "os.kill", + "os.killpg", + "socket.connect", + } + if event == "import" and arguments[0].split(".")[0] in { + "policyengine_us", + "policyengine_core", + }: + forbidden = True + if forbidden: + DENIED.append(event) + raise RuntimeError( + "Pure checks prohibit model imports and process/network actions" + ) + + +sys.addaudithook(audit) +import remote + + +class Decisions(unittest.TestCase): + def test_download_plan_limits_the_entire_transfer_without_executing_it(self): + argv = remote.download_plan( + "https://nonexistent.invalid/mock-release", + Path("/nonexistent-download"), + 10, + ) + self.assertEqual(argv[:2], ["curl", "--disable"]) + self.assertEqual(argv[argv.index("--max-time") + 1], "10") + self.assertNotIn("--retry", argv) + self.assertEqual(argv[argv.index("--proto") + 1], "=https") + for seconds in (0, -1, 31, float("inf"), float("nan")): + with self.subTest(seconds=seconds), self.assertRaises(ValueError): + remote.download_plan( + "https://nonexistent.invalid/mock-release", + Path("/nonexistent-download"), + seconds, + ) + + def test_stream_verification_checks_the_deadline_after_each_chunk(self): + class MockReader: + calls = 0 + + def read(self, maximum): + self.calls += 1 + return b"MOCK_CHUNK" + + reader = MockReader() + ticks = iter((0, 0, 0, 2)) + with self.assertRaises(TimeoutError): + remote.stream_digest(reader, 1, clock=lambda: next(ticks)) + self.assertEqual(reader.calls, 2) + with self.assertRaises(TimeoutError): + remote.stream_digest(io.BytesIO(b"MOCK_BYTES"), 1, clock=lambda: 2) + self.assertEqual( + remote.stream_digest(io.BytesIO(b"MOCK_BYTES"), 1, clock=lambda: 0), + hashlib.sha256(b"MOCK_BYTES").hexdigest(), + ) + + def test_failure_resource_records_do_not_invent_final_peaks(self): + mock_snapshot = {"memory.peak": "123", "memory.events": "oom_kill 0"} + observed = remote.resource_record("final", mock_snapshot) + normal = {"OOMKilled": False, "ExitCode": 0, "Running": False} + self.assertEqual( + remote.final_resource_record(observed, normal)["snapshot"], mock_snapshot + ) + for state in ( + {"OOMKilled": True, "ExitCode": 137, "Running": False}, + {"OOMKilled": False, "ExitCode": 137, "Running": False}, + ): + result = remote.final_resource_record(observed, state) + self.assertEqual(result["status"], "UNAVAILABLE") + self.assertIsNone(result["snapshot"]) + self.assertEqual(result["docker_state"], state) + absent = remote.final_resource_record(None, normal) + self.assertEqual(absent["status"], "UNAVAILABLE") + self.assertIsNone(absent["snapshot"]) + unavailable = remote.resource_record("final", None, "MOCK_READ_FAILURE") + self.assertEqual( + remote.final_resource_record(unavailable, normal)["error"], + "MOCK_READ_FAILURE", + ) + + def test_exporter_persists_start_resources_before_any_model_import(self): + entry = functions(Path(__file__).resolve().parent / "parameter_export.py")[ + "export_entry" + ] + writes = [ + i + for i, node in enumerate(entry.body) + if isinstance(node, ast.Expr) + and isinstance(node.value, ast.Call) + and isinstance(node.value.func, ast.Name) + and node.value.func.id == "write_new_json" + and isinstance(node.value.args[0], ast.Name) + and node.value.args[0].id == "resource_start_path" + ] + imports = [ + i + for i, node in enumerate(entry.body) + if isinstance(node, ast.Assign) + and isinstance(node.value, ast.Call) + and isinstance(node.value.func, ast.Attribute) + and isinstance(node.value.func.value, ast.Name) + and node.value.func.value.id == "importlib" + and node.value.func.attr == "import_module" + ] + self.assertEqual(len(writes), 1) + self.assertLess(writes[0], min(imports)) + + def limits(self): + return { + "memory.max": str(remote.MEMORY), + "memory.swap.max": "0", + "cpu.max": "100000 100000", + "threads": {name: "1" for name in remote.THREADS}, + } + + def context(self): + return { + "GITHUB_REPOSITORY": "PolicyEngine/policyengine-us", + "GITHUB_EVENT_NAME": "workflow_dispatch", + "GITHUB_REF": remote.REF, + "GITHUB_WORKFLOW_REF": "PolicyEngine/policyengine-us/.github/workflows/docs.yaml@" + + remote.REF, + "GITHUB_SHA": "0" * 40, + "GITHUB_RUN_ID": "000000000000000000", + "GITHUB_RUN_ATTEMPT": "000000000000000000", + } + + def info(self): + return { + "Id": "0" * 64, + "Image": "sha256:" + "0" * 64, + "Config": {"Labels": {"us10783.run": "nonexistent-owner"}}, + "HostConfig": { + "Memory": remote.MEMORY, + "MemorySwap": remote.MEMORY, + "NanoCpus": 1_000_000_000, + "NetworkMode": "none", + "ReadonlyRootfs": True, + "CapDrop": ["ALL"], + }, + } + + def test_limits_require_memory_swap_cpu_and_serial_threads(self): + remote.validate_limits(self.limits()) + for key, value in ( + ("memory.max", "max"), + ("memory.max", str(remote.MEMORY + 1)), + ("memory.swap.max", "1"), + ("cpu.max", "max 100000"), + ("cpu.max", "100001 100000"), + ("cpu.max", "0 100000"), + ("cpu.max", "1 0"), + ("threads", {}), + ): + data = self.limits() + data[key] = value + with self.subTest(key=key, value=value), self.assertRaises(ValueError): + remote.validate_limits(data) + + def test_dispatch_context_rejects_wrong_source_workflow_or_ref(self): + remote.validate_context(self.context()) + for key, value in ( + ("GITHUB_REPOSITORY", "nonexistent/repo"), + ("GITHUB_EVENT_NAME", "push"), + ("GITHUB_REF", "refs/heads/nonexistent"), + ("GITHUB_WORKFLOW_REF", "nonexistent"), + ("GITHUB_SHA", "missing"), + ("GITHUB_RUN_ATTEMPT", "missing"), + ): + data = self.context() + data[key] = value + with self.subTest(key=key), self.assertRaises(ValueError): + remote.validate_context(data) + + def test_container_decision_rejects_wrong_identity_or_unbounded_resources(self): + remote.validate_container( + self.info(), "0" * 64, "sha256:" + "0" * 64, "nonexistent-owner" + ) + for key, value in ( + ("Memory", 0), + ("MemorySwap", -1), + ("NanoCpus", 2_000_000_000), + ("NetworkMode", "default"), + ("ReadonlyRootfs", False), + ("CapDrop", []), + ): + data = self.info() + data["HostConfig"][key] = value + with self.subTest(key=key), self.assertRaises(ValueError): + remote.validate_container( + data, "0" * 64, "sha256:" + "0" * 64, "nonexistent-owner" + ) + for key in ("Id", "Image"): + data = self.info() + data[key] = "nonexistent" + with self.subTest(key=key), self.assertRaises(ValueError): + remote.validate_container( + data, "0" * 64, "sha256:" + "0" * 64, "nonexistent-owner" + ) + data = self.info() + data["Config"]["Labels"]["us10783.run"] = "another-nonexistent-owner" + with self.assertRaises(ValueError): + remote.validate_container( + data, "0" * 64, "sha256:" + "0" * 64, "nonexistent-owner" + ) + + def test_elapsed_deadline_refuses_any_launch(self): + with self.assertRaises(TimeoutError): + remote.remaining(-1, 600) + + def test_bootstrap_consumes_the_same_global_budget(self): + self.assertEqual(remote.pipeline_budget(1020, 0), 870) + self.assertEqual(remote.pipeline_budget(1020, 400), 470) + for stop_at, now in ((0, 1), (1021, 0)): + with self.subTest(stop_at=stop_at, now=now), self.assertRaises(ValueError): + remote.pipeline_budget(stop_at, now) + with self.assertRaises(TimeoutError): + remote.pipeline_budget(1020, 900) + + def test_fixed_source_rejects_another_commit_tree_or_manifest(self): + commit, tree = remote.SOURCES["C"] + source = { + "root": "/sources/C", + "commit": commit, + "tree": tree, + "manifest": {"path": "/validation/evidence/C-source.json"}, + } + remote.validate_source_record(source) + for key in ("root", "commit", "tree"): + data = dict(source) + data[key] = "nonexistent" + with self.subTest(key=key), self.assertRaises(ValueError): + remote.validate_source_record(data) + data = dict(source, manifest={"path": "/nonexistent-source.json"}) + with self.assertRaises(ValueError): + remote.validate_source_record(data) + + def test_full_receipt_requires_complete_grid_fixed_source_and_original_paths(self): + commit, tree = remote.SOURCES["C"] + image = "sha256:" + "0" * 64 + receipt = { + "complete": True, + "grid_validated": True, + "probe_only": False, + "mode": "baseline", + "image_id": image, + "source": {"commit": commit, "tree": tree}, + "outputs": { + "values": {"path": "/output/C-baseline.jsonl", "sha256": "0" * 64}, + "catalog": { + "path": "/output/C-baseline.jsonl.catalog.json", + "sha256": "0" * 64, + }, + }, + } + remote.validate_export_receipt(receipt, "C", "baseline", image) + for key, value in ( + ("complete", False), + ("grid_validated", False), + ("probe_only", True), + ("mode", "trustees"), + ("image_id", "nonexistent-image"), + ): + data = dict(receipt) + data[key] = value + with self.subTest(key=key), self.assertRaises(ValueError): + remote.validate_export_receipt(data, "C", "baseline", image) + data = dict( + receipt, + outputs={ + "values": {"path": "/nonexistent.jsonl", "sha256": "0" * 64}, + "catalog": receipt["outputs"]["catalog"], + }, + ) + with self.assertRaises(ValueError): + remote.validate_export_receipt(data, "C", "baseline", image) + + +def functions(path): + return { + node.name: node + for node in ast.parse(path.read_text()).body + if isinstance(node, ast.FunctionDef) + } + + +def normalized(node): + return ast.dump(node, include_attributes=False) + + +def assigned(node, name): + return isinstance(node, ast.Assign) and any( + isinstance(t, ast.Name) and t.id == name for t in node.targets + ) + + +def slice_body(body, first, last): + start = next(i for i, node in enumerate(body) if assigned(node, first)) + end = next(i for i, node in enumerate(body) if assigned(node, last)) + return normalized(ast.Module(body=body[start : end + 1], type_ignores=[])) + + +def preservation(exporter, comparator): + root = Path(__file__).resolve().parent + old, new = functions(exporter), functions(root / "parameter_export.py") + kept = ( + "frozen_json", + "verify_source", + "verify_runtime", + "verify_tables", + "assert_imports", + "selector_metadata", + ) + for name in kept: + if normalized(old[name]) != normalized(new[name]): + raise ValueError("Changed protected exporter function: " + name) + left, right = old["export_entry"].body, new["export_entry"].body + if slice_body(left, "country", "catalog") != slice_body( + right, "country", "catalog" + ): + raise ValueError("Changed real model construction or catalog traversal") + protected = [] + history = [] + for body in (left, right): + start = next(i for i, node in enumerate(body) if assigned(node, "by_name")) + end = next( + i + for i, node in enumerate(body[start:], start) + if isinstance(node, ast.With) + ) + protected.append( + normalized(ast.Module(body=body[start : end + 1], type_ignores=[])) + ) + history_start = next( + i for i, node in enumerate(body) if assigned(node, "history") + ) + history.append( + normalized(ast.Module(body=body[history_start:], type_ignores=[])) + ) + if protected[0] != protected[1]: + raise ValueError( + "Changed export row traversal/validation or atomic output preparation" + ) + if history[0] != history[1]: + raise ValueError("Changed stated history or completion publication") + before, after = ( + ast.parse(comparator.read_text()), + ast.parse((root / "comparison_data.py").read_text()), + ) + for node in ast.walk(before): + if isinstance(node, ast.ImportFrom) and node.module == "admission_protocol": + node.module = "atomic" + if normalized(before) != normalized(after): + raise ValueError("Changed frozen comparison algorithms") + return { + "functions_ast_equal": list(kept), + "model_constructor_and_catalog_ast_equal": True, + "value_traversal_ast_equal": True, + "stated_history_and_completion_ast_equal": True, + "comparison_module_ast_equal_except_neutral_import": True, + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--reference-exporter", type=Path, required=True) + parser.add_argument("--reference-comparator", type=Path, required=True) + args = parser.parse_args() + proof = preservation(args.reference_exporter, args.reference_comparator) + result = unittest.TextTestRunner(verbosity=2).run( + unittest.defaultTestLoader.loadTestsFromTestCase(Decisions) + ) + modules = sorted( + n + for n in sys.modules + if n == "policyengine_us" + or n.startswith("policyengine_us.") + or n == "policyengine_core" + or n.startswith("policyengine_core.") + ) + print( + json.dumps( + { + "source_proof": proof, + "tests": result.testsRun, + "success": result.wasSuccessful(), + "model_modules": modules, + "denied_attempts": DENIED, + }, + sort_keys=True, + ) + ) + sys.exit(0 if result.wasSuccessful() and not modules and not DENIED else 1) diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index 69dad564775..7d03568c4d7 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -1,21 +1,6 @@ -name: Documentation +name: US10783 parameter validation +run-name: US10783 Core 3.36.0 validation at 561afc5 on: - pull_request: - branches: [main] - paths: - - "docs/**" - - "Makefile" - - "policyengine_us/tools/add_plotly_to_book.py" - - "policyengine_us/tools/render_plotly_outputs.py" - - ".github/workflows/docs.yaml" - push: - branches: [main] - paths: - - "docs/**" - - "Makefile" - - "policyengine_us/tools/add_plotly_to_book.py" - - "policyengine_us/tools/render_plotly_outputs.py" - - ".github/workflows/docs.yaml" workflow_dispatch: permissions: @@ -23,66 +8,39 @@ permissions: jobs: Build: - name: Build documentation + if: >- + github.repository == 'PolicyEngine/policyengine-us' && + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/codex/us10783-core336-validation-20261113' runs-on: ubuntu-latest timeout-minutes: 20 concurrency: - group: docs-build-${{ github.ref }} - cancel-in-progress: true + group: us10783-parameter-validation-${{ github.ref }} + cancel-in-progress: false steps: - - uses: actions/checkout@v6 - - name: Set up Python - uses: actions/setup-python@v6 + - name: Reserve the artifact window + run: echo "US10783_STOP_AT=$(( $(date +%s) + 1020 ))" >> "$GITHUB_ENV" + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: - python-version: "3.13" - - name: Install uv - uses: astral-sh/setup-uv@v8.1.0 + persist-credentials: false + - name: Set up the bootstrap interpreter + id: python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: - version: "0.13.4" - # The book is Jupyter Book 1 (docs/_config.yml, docs/_toc.yml), but - # uv.lock resolves jupyter-book 2, so the docs toolchain is installed - # here rather than with `uv sync --extra dev`. docs/_config.yml loads - # sphinxarg.ext, which needs sphinx-argparse. The book renders stored - # outputs and never imports policyengine_us; plotly (pinned to the - # uv.lock version) is only needed to render the stored charts. - - name: Install the Jupyter Book 1 toolchain - run: | - uv venv --python 3.13 .venv - uv pip install --python .venv/bin/python "jupyter-book>=1.0.4.post1,<2" "furo>=2024.8.6" sphinx-argparse "plotly==5.24.1" - - name: Render stored Plotly outputs - run: .venv/bin/python policyengine_us/tools/render_plotly_outputs.py docs - - name: Build the book - run: | - source .venv/bin/activate - make documentation - - uses: actions/upload-artifact@v4 + python-version: "3.14.7" + - name: Qualify one image and export parameters serially + timeout-minutes: 17 + run: >- + "${{ steps.python.outputs.python-path }}" -B -S + .github/us10783-validation/remote.py run + --repo "$GITHUB_WORKSPACE" --work "$RUNNER_TEMP/us10783-validation" + - name: Preserve complete or failed validation evidence + if: always() + timeout-minutes: 2 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: - name: documentation - path: docs/_build/html + name: us10783-core336-validation-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/us10783-validation/artifact/ if-no-files-found: error - - Deploy: - name: Deploy documentation to GitHub Pages - needs: Build - timeout-minutes: 10 - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'PolicyEngine/policyengine-us' - runs-on: ubuntu-latest - permissions: - contents: write - concurrency: - group: docs-deploy - cancel-in-progress: false - steps: - - uses: actions/checkout@v6 - - uses: actions/download-artifact@v4 - with: - name: documentation - path: site - # GitHub Pages serves the gh-pages branch with Jekyll unless .nojekyll - # is present, and Jekyll drops Sphinx's _static/ and _sources/ folders. - - name: Disable Jekyll - run: touch site/.nojekyll - - uses: JamesIves/github-pages-deploy-action@v4 - with: - branch: gh-pages - folder: site + retention-days: 1 + compression-level: 0 diff --git a/changelog.d/us10783-core336-validation.changed.md b/changelog.d/us10783-core336-validation.changed.md new file mode 100644 index 00000000000..40c9e660bc6 --- /dev/null +++ b/changelog.d/us10783-core336-validation.changed.md @@ -0,0 +1 @@ +Add a temporary workflow to compare complete sampled parameter trees against released Core 3.36.0. From d0feec3dcea2d8272059fdd63db4a23395ae31ad Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 13 Nov 2026 19:14:00 -0500 Subject: [PATCH 2/2] Run validation containers as the output owner --- .github/us10783-validation/remote.py | 54 +++++++++++++++++- .github/us10783-validation/test_entry.py | 70 +++++++++++++++++++----- 2 files changed, 108 insertions(+), 16 deletions(-) diff --git a/.github/us10783-validation/remote.py b/.github/us10783-validation/remote.py index f908ab42ce7..645870e16c7 100644 --- a/.github/us10783-validation/remote.py +++ b/.github/us10783-validation/remote.py @@ -101,6 +101,7 @@ def resource_snapshot(deadline=None): raise ValueError("Unexpectedly large cgroup resource record") snapshot[name] = value.strip() snapshot["threads"] = {name: os.environ.get(name) for name in THREADS} + snapshot["process_identity"] = {"uid": os.getuid(), "gid": os.getgid()} return validate_limits(snapshot) @@ -192,14 +193,35 @@ def validate_export_receipt(receipt, side, mode, image): raise ValueError("Unexpected original Linux receipt path/hash") -def validate_container(info, container_id, image_id, owner): +def caller_user_options(uid, gid, output_uid, output_mode): + if any( + type(value) is not int or not 0 <= value < 2**32 - 1 for value in (uid, gid) + ): + raise ValueError("Invalid caller UID/GID") + if output_uid != uid or output_mode & 0o300 != 0o300: + raise ValueError( + "Caller must own the output directory with write/search permission" + ) + return ["--user", f"{uid}:{gid}"] + + +def validate_container(info, container_id, image_id, owner, user, output_path): host = info["HostConfig"] if ( info["Id"] != container_id or info["Image"] != image_id or info["Config"]["Labels"].get("us10783.run") != owner + or info["Config"].get("User") != user ): raise ValueError("Container ownership/image identity changed") + if not any( + mount.get("Type") == "bind" + and mount.get("Source") == output_path + and mount.get("Destination") == "/output" + and mount.get("RW") is True + for mount in info.get("Mounts", []) + ): + raise ValueError("Container output mount differs or is read-only") if ( host["Memory"] != MEMORY or host["MemorySwap"] != MEMORY @@ -565,9 +587,24 @@ def publish_provenance(): def container(argv, label, output, image, owner, deadline, maximum): name = "us10783-" + owner + "-" + label + output_stat = output.stat() + uid, gid = os.getuid(), os.getgid() + user_options = caller_user_options( + uid, gid, output_stat.st_uid, output_stat.st_mode + ) + identity = { + "caller_uid": uid, + "caller_gid": gid, + "container_user": user_options[1], + "output_uid": output_stat.st_uid, + "output_gid": output_stat.st_gid, + "output_mode": oct(output_stat.st_mode & 0o7777), + } + write_new_json(output / (label + ".identity.json"), identity) create = [ "docker", "create", + *user_options, "--name", name, "--label", @@ -616,7 +653,9 @@ def container(argv, label, output, image, owner, deadline, maximum): ) if observed.returncode == 0: info = json.loads(observed.stdout)[0] - validate_container(info, info["Id"], image, owner) + validate_container( + info, info["Id"], image, owner, user_options[1], str(output) + ) if info["State"]["Running"]: raise RuntimeError( "Unexpected running container after failed create; cleanup pending" @@ -628,6 +667,7 @@ def container(argv, label, output, image, owner, deadline, maximum): "reconciled": observed.returncode == 0, "inspect_exit": observed.returncode, "model_started": False, + "caller_and_output_identity": identity, }, ) raise @@ -636,7 +676,7 @@ def container(argv, label, output, image, owner, deadline, maximum): def inspect(): info = json.loads(command(["docker", "inspect", cid], timeout=10).stdout)[0] - validate_container(info, cid, image, owner) + validate_container(info, cid, image, owner, user_options[1], str(output)) return info process = None @@ -688,6 +728,7 @@ def inspect(): "owner": owner, "failure": failure, "cleanup_verified": False, + "caller_and_output_identity": identity, "cleanup_error": repr(cleanup_error), "final_resources": resource_record( "final", None, "Docker cleanup/inspection did not complete" @@ -713,6 +754,13 @@ def inspect(): "image": image, "owner": owner, "state": info["State"], + "caller_and_output_identity": identity, + "inspected_user": info["Config"]["User"], + "inspected_output_mount": [ + mount + for mount in info["Mounts"] + if mount.get("Destination") == "/output" + ], "final_resources_status": final_resources["status"], "limits": { key: info["HostConfig"][key] diff --git a/.github/us10783-validation/test_entry.py b/.github/us10783-validation/test_entry.py index cd97fc35089..aa2d1016e23 100644 --- a/.github/us10783-validation/test_entry.py +++ b/.github/us10783-validation/test_entry.py @@ -152,7 +152,18 @@ def info(self): return { "Id": "0" * 64, "Image": "sha256:" + "0" * 64, - "Config": {"Labels": {"us10783.run": "nonexistent-owner"}}, + "Config": { + "Labels": {"us10783.run": "nonexistent-owner"}, + "User": "2147483001:2147483002", + }, + "Mounts": [ + { + "Type": "bind", + "Source": "/nonexistent-output", + "Destination": "/output", + "RW": True, + } + ], "HostConfig": { "Memory": remote.MEMORY, "MemorySwap": remote.MEMORY, @@ -163,6 +174,47 @@ def info(self): }, } + def check_container(self, data): + remote.validate_container( + data, + "0" * 64, + "sha256:" + "0" * 64, + "nonexistent-owner", + "2147483001:2147483002", + "/nonexistent-output", + ) + + def test_explicit_caller_user_can_write_owned_0755_output_without_extra_capabilities( + self, + ): + # Nonexistent identities and command options remain inert data. + options = remote.caller_user_options( + 2147483001, 2147483002, 2147483001, 0o40755 + ) + self.assertEqual(options, ["--user", "2147483001:2147483002"]) + for uid, gid, owner, mode in ( + (2147483001, 2147483002, 2147483003, 0o40755), + (2147483001, 2147483002, 2147483001, 0o40555), + (2147483001, 2147483002, 2147483001, 0o40644), + (-1, 2147483002, 2147483001, 0o40755), + (2147483001, 2**32 - 1, 2147483001, 0o40755), + ): + with ( + self.subTest(uid=uid, gid=gid, owner=owner, mode=mode), + self.assertRaises(ValueError), + ): + remote.caller_user_options(uid, gid, owner, mode) + for user in ("", "2147483003:2147483002"): + data = self.info() + data["Config"]["User"] = user + with self.subTest(user=user), self.assertRaises(ValueError): + self.check_container(data) + for key, value in (("RW", False), ("Source", "/another-nonexistent-output")): + data = self.info() + data["Mounts"][0][key] = value + with self.subTest(key=key), self.assertRaises(ValueError): + self.check_container(data) + def test_limits_require_memory_swap_cpu_and_serial_threads(self): remote.validate_limits(self.limits()) for key, value in ( @@ -196,9 +248,7 @@ def test_dispatch_context_rejects_wrong_source_workflow_or_ref(self): remote.validate_context(data) def test_container_decision_rejects_wrong_identity_or_unbounded_resources(self): - remote.validate_container( - self.info(), "0" * 64, "sha256:" + "0" * 64, "nonexistent-owner" - ) + self.check_container(self.info()) for key, value in ( ("Memory", 0), ("MemorySwap", -1), @@ -210,22 +260,16 @@ def test_container_decision_rejects_wrong_identity_or_unbounded_resources(self): data = self.info() data["HostConfig"][key] = value with self.subTest(key=key), self.assertRaises(ValueError): - remote.validate_container( - data, "0" * 64, "sha256:" + "0" * 64, "nonexistent-owner" - ) + self.check_container(data) for key in ("Id", "Image"): data = self.info() data[key] = "nonexistent" with self.subTest(key=key), self.assertRaises(ValueError): - remote.validate_container( - data, "0" * 64, "sha256:" + "0" * 64, "nonexistent-owner" - ) + self.check_container(data) data = self.info() data["Config"]["Labels"]["us10783.run"] = "another-nonexistent-owner" with self.assertRaises(ValueError): - remote.validate_container( - data, "0" * 64, "sha256:" + "0" * 64, "nonexistent-owner" - ) + self.check_container(data) def test_elapsed_deadline_refuses_any_launch(self): with self.assertRaises(TimeoutError):