#!/usr/bin/env python3 """ IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated) Standalone 80-Digit Outward-Directed Taylor Interval Decimal Verifier for: - Part A (NW-18): Hardened 3-Pathogen (CVB4-E2, CVB3, HCMV) x 5-Lineage Whole-Graft Viral Safety Gate 0V (two-stage FPR-calibrated screen + orthogonal ddPCR confirmation, latent HCMV + CVB 5'-deletion genome arm, dual-marker <=5% unassigned lineage cap, fragile infected-cell spike control, fixed 500 ng/mL non-vacuous Gate 0V-A with >=2.0-fold induction in >=3/4 markers/lineage + controls, strain-specific ectopic CD46_WT / CD55 viral addenda across A/B/X, Y-FullStack v2, and D1b-Auto L1B, operational bank-qualification vs lot-release vs autologous D1b split, explicit clustering/independence design-effect adjustment, raw-count recomputed Gate 0V-Kill separating per-total-input and conditional per-pre-treatment-infected-at-risk estimands, viral caspase-9/3 blockade check in infected HCMV/CVB4 arms, reconciled survivors_scored_n, assay volume/LOD, SHA-256 evidence digests, and lot/MCB/product/ payload_sha256 binding with CLI --evaluate-lot ) - Part B (NW-08): True 3D FVM Vascular-Voxel (m_vasc = 1.3164) Layer-4 Oxygen Replay across all 8 live Route 1 / Route 2 / Route 3P cases (D_O2_ISLET = 1.3e-5 cm^2/s), margin + measurement-uncertainty-to-15-mmHg triggering (replacing the flawed +20% trigger), and source-typed 5-lineage calibration matrix (literature group means, whole-islet proxies, cell-line stress sensitivities, model allowances) - Part C (CEG-DELTA V3.3 + Option-2 Governance): Parameterized Protected-File Manifest (--protected-manifest), Playbook §4.1.20 Canonical Section-Hash Check, In-Memory render_documentation.py Verification for docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md, Dual-Evaluator Composite Release Governance, Case-Normalized CEG-DELTA Live Diff (7 real staging repairs + 1 confirmed Zenodo CC-BY-4.0 dataset record 10813168), and De-Collided Idea Graveyard Guardrail GY-030 (OFFGRID_GUARD_020_*) - Part D (OQ-016 §5.5): +0.00 pp Headline Odds Invariance & Corrected Pre-IND Detection Power (99.833392% / 1.6661e-3 / 1.2513e-14) Strict Option-2 Zero-LIMS-Touch & Cross-Runtime Design: - Core Gate 0V evaluator uses Python standard library only; ZERO imports of scripts/wetlab_contract.py or scripts/ingest_wetlab_results.py (composite dual evaluation lives in standalone evaluate_gate0v_composite_release.py); ZERO `assert` statements (`python3 -O -B` safe). - ZERO reliance on Python Decimal.ln() / Decimal.exp() for sound bounds (exact Fraction argument reduction + elementary +, -, *, / outward-directed Taylor interval arithmetic with full ambient-context & Inexact-trap immunity). - ZERO hardcoded user home paths; fully portable via Path(__file__).resolve() / CLI flags. Run with: PYTHONDONTWRITEBYTECODE=1 python3 -B verify_exp031_wholegraft_gate0v_and_calibration.py PYTHONDONTWRITEBYTECODE=1 python3 -O -B verify_exp031_wholegraft_gate0v_and_calibration.py PYTHONDONTWRITEBYTECODE=1 python3 -B verify_exp031_wholegraft_gate0v_and_calibration.py --evaluate-lot """ from __future__ import annotations import argparse import copy from datetime import datetime, timezone import decimal from decimal import Context, Decimal, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_EVEN, localcontext from fractions import Fraction from functools import lru_cache import glob import hashlib import importlib.util import inspect import json import math import os from pathlib import Path import re import shutil import subprocess import sys import tempfile import threading from typing import Any, Dict, List, Tuple sys.dont_write_bytecode = True # Process-wide thread-safe cache lock & root-keyed native float64 caches shared across ALL loaded # instances of verify_iip0043 (direct import, composite wrapper, or importlib copies) (R03-B2 + R14-B3 + R18-B1/B2). # Native 3D FVM solves execute inside isolated child Python subprocesses bound strictly to the # requested `openislet_root / "scripts"` so parent `sys.path`, `sys.modules`, and Layer-4 callbacks # are NEVER mutated. _FVM_SOLVER_LOCK: threading.RLock = threading.__dict__.setdefault( "_OPENISLET_IIP0043_FVM_SOLVER_LOCK", threading.RLock() ) _NATIVE_BASELINE_MMHG_CACHE: Dict[Tuple[str, str, float, float], float] = threading.__dict__.setdefault( "_OPENISLET_IIP0043_NATIVE_BASELINE_MMHG_CACHE", {} ) _NATIVE_BASELINE_META_CACHE: Dict[Tuple[str, str, float, float], Dict[str, Any]] = threading.__dict__.setdefault( "_OPENISLET_IIP0043_NATIVE_BASELINE_META_CACHE", {} ) _MESH_REFINEMENT_SOLVE_CACHE: Dict[Tuple[str, str, float, float, int, int, str], Tuple[float, float]] = threading.__dict__.setdefault( "_OPENISLET_IIP0043_MESH_REFINEMENT_SOLVE_CACHE", {} ) # --------------------------------------------------------------------------- # Portable Path Resolution (Zero Hardcoded User Paths) # --------------------------------------------------------------------------- SCRIPT_DIR = Path(__file__).resolve().parent DEFAULT_RECEIPT_PATH = ( SCRIPT_DIR.parent / "data" / "extracted" / "iip0043_wholegraft_gate0v_and_calibration_v0.8.0.json" if SCRIPT_DIR.name == "scripts" else SCRIPT_DIR / "exp031_verification_receipt.json" ) _LOT_ALIAS_KEYS: Tuple[str, ...] = ("evaluated_lot_id", "lot_id", "batch_id", "mcb_lot_id", "mcb_batch_id") _LOT_PLANNED_ROUTE_KEYS: Tuple[str, ...] = ( "nw08_route_id", "planned_nw08_route_id", "planned_route_id", "geometry_route_id", ) _PLACEHOLDER_TOKEN_RE = re.compile(r"(?i)\b(?:TBD|TODO|PLACEHOLDER|FIXME|XXX|PENDING_VALUE|DUMMY)\b|\?\?\?") _FORBIDDEN_ID_CHARS_RE = re.compile(r"[\x00-\x1f\x7f\u200b-\u200f\u2028-\u202f\u2060-\u206f\ufeff]") _HEX64_RE = re.compile(r"^[0-9a-f]{64}$") _UTC_ISO8601_RE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?)(?:Z|\+00:00)$") MAX_STRICT_JSON_INT_ABS: int = 10 ** 300 MAX_JSON_NESTING_DEPTH: int = 64 def _check_json_nesting_depth_iterative(raw_text: str, *, max_depth: int = MAX_JSON_NESTING_DEPTH) -> None: """ R11-B4 Purely iterative O(n), string/escape-aware JSON container nesting-depth validator. Enforces `depth <= max_depth` BEFORE invoking `json.loads` with ZERO recursion so deeply nested documents (e.g. > 64 nested `{`/`[` frames) fail closed cleanly with `StrictJSONDecodeError` (`JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED`) instead of exhausting Python's recursion limit. """ depth = 0 in_string = False escaped = False for ch in raw_text: if in_string: if escaped: escaped = False elif ch == "\\": escaped = True elif ch == '"': in_string = False continue if ch == '"': in_string = True elif ch == "{" or ch == "[": depth += 1 if depth > max_depth: raise StrictJSONDecodeError( f"JSON nesting depth exceeds supported limit {max_depth}", reason_code="JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED", ) elif ch == "}" or ch == "]": if depth > 0: depth -= 1 def _enforce_release_authorizing_false_iterative(root_obj: Any) -> Any: """ R11-B2 Purely iterative stack walk ensuring NO dict anywhere inside a standalone diagnostic payload carries `release_authorizing == True` (forces every occurrence to `False`). """ stack: List[Any] = [root_obj] seen_ids: set[int] = set() while stack: cur = stack.pop() if isinstance(cur, dict): cid = id(cur) if cid in seen_ids: continue seen_ids.add(cid) if "release_authorizing" in cur: cur["release_authorizing"] = False for v in cur.values(): if isinstance(v, (dict, list, tuple)): stack.append(v) elif isinstance(cur, (list, tuple)): cid = id(cur) if cid in seen_ids: continue seen_ids.add(cid) for item in cur: if isinstance(item, (dict, list, tuple)): stack.append(item) return root_obj class StrictJSONDecodeError(ValueError): """Raised on ambiguous, non-canonical, non-finite, or out-of-range JSON.""" def __init__(self, message: str, *, reason_code: str = "STRICT_JSON_ERROR") -> None: super().__init__(message) self.reason_code = reason_code _EXACT_DECIMAL_PRESERVED_JSON_KEYS: frozenset[str] = frozenset({ # Clustering / independence design-effect boundary keys (R12-B2) "clustering_design_effect_deff", "deff", # NW-08 measured OCR / FVM boundary keys "measured_ocr", "uncertainty_se", "measured_ocr_u95_override", "p_bed_mmhg", "baseline_vasc_ocr_mult", "baseline_min_face_mmhg", "local_3d_slope_mmhg_per_pct", "z_one_sided_95", "z_score", "floor_mmhg", # Gate 0V-A / 0V-B / 0V-Geno / 0V-Kill / CD46 / CD55 exact threshold keys "caspase9_3_activity_fold_over_vehicle", "poly_ic_dose_ng_ml", "assay_duration_h", "IFNB1_or_IFNL1_fold", "ISG15_fold", "MX1_fold", "OAS1_fold", "beta", "alpha", "delta", "plvap_iec", "pericyte", "endocrine_72h_log10_pfu_u95", "vascular_72h_log10_pfu_u95", "coculture_72h_log10_pfu_u95", "endocrine_day14_log10_reduction_l95", "vascular_day14_log10_reduction_l95", "day28_supernatant_infectious_pfu_ml", "day28_supernatant_assay_volume_ml", "day28_supernatant_lod_pfu_ml", "edited_minus_wt_day14_log10_reduction_l95", "reactivation_7d_outgrowth_pfu_ml", "reactivation_assay_volume_ml", "reactivation_lod_pfu_ml", "titer_72h_log10_pfu_u95", "day14_log10_reduction_l95", "day28_supernatant_pfu_ml", "day28_assay_volume_ml", "day28_lod_pfu_ml", "echovirus_titer_72h_log10_pfu_u95", "echovirus_day14_log10_reduction_l95", "echovirus_day28_supernatant_pfu_ml", }) def _coerce_non_dict_decimals_to_float(val: Any) -> Any: """Convert raw parsed Decimal tokens outside preserved exact-boundary keys to IEEE-754 float64 without mutating child dicts whose keys were already finalized by object_pairs_hook.""" if isinstance(val, Decimal): return float(val) if isinstance(val, list): return [_coerce_non_dict_decimals_to_float(item) for item in val] return val def _make_strict_json_object_pairs_hook(preserve_boundary_decimals: bool): def _hook(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]: obj: Dict[str, Any] = {}