OpenIslet

scripts/verify_iip0045_cao2_coupled_gate31.py

Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Lot Evaluator for

script Release v0.8.0 gen-eb955f8266035aba 68 KB · 6 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0045_cao2_coupled_gate31.py · SHA-256: 00443954dd735914…

        "policy_decision_id": "DEC-134",
        "authoritative_vascular_midpoint_h": 60.0,
        "sub_15mmhg_excursion_cap_h": 4.0,
        "hard_hypoxia_floor_mmhg": 10.0,
        "obs_po2_below_15mmhg_cumulative_h": float(sub15_h) if _is_finite_real(sub15_h) else None,
        "obs_po2_min_mmhg": float(po2_min) if _is_finite_real(po2_min) else None,
        "authoritative_h2o2_coordinate": "BARRIER_TISSUE_INTERFACE_Z_70P0_UM",
        "gate31c_one_sided_95_paired_contrast": dec134_g31c,
        "dec134_legacy_36h_default_physical_lots_count": 0,
    }

    if hard_stops:
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "policy_decision_id": "DEC-134",
            "verdict": "FAIL_HARD_STOP_GATE_31_COUPLED_CAO2_LOT",
            "exit_code": 3,
            "release_authorizing": False,
            "hard_stops": hard_stops,
            "holds": holds,
            "diagnostics": diag,
        }
    if holds:
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "policy_decision_id": "DEC-134",
            "verdict": "HOLD_GATE_31_INCOMPLETE_OR_TIER1_MARGIN",
            "exit_code": 2,
            "release_authorizing": False,
            "hard_stops": [],
            "holds": holds,
            "diagnostics": diag,
        }
    return {
        "gate_id": GATE_ID,
        "contribution_id": CONTRIBUTION_ID,
        "decision_id": DECISION_ID,
        "policy_decision_id": "DEC-134",
        "verdict": "PASS_GATE_31_COUPLED_CAO2_LOT",
        "exit_code": 0,
        "release_authorizing": True,
        "hard_stops": [],
        "holds": [],
        "diagnostics": diag,
    }


def run_zero_lims_touch_invariance_checks(repo_root: Path) -> Dict[str, Any]:
    if "wetlab_contract" in sys.modules:
        raise RuntimeError("Zero-LIMS-Touch violation: wetlab_contract imported")
    lims_verified: Dict[str, Dict[str, Any]] = {}
    for rel, expected in FROZEN_LIMS_SHA256.items():
        actual = sha256_file(repo_root / rel)
        if actual != expected:
            raise RuntimeError(f"Frozen LIMS SHA-256 mismatch on {rel}: {actual} != {expected}")
        lims_verified[rel] = {"sha256": actual, "matches_pin": True}

    pareto_sha = sha256_file(repo_root / "data/extracted/islet1_combinatorial_pareto_and_ladder_v0.8.0.json")
    if pareto_sha != EXPECTED_PARETO_SHA256:
        raise RuntimeError(f"Frozen Pareto SHA-256 mismatch: {pareto_sha} != {EXPECTED_PARETO_SHA256}")

    pb_sec4120_sha = _extract_playbook_sec4120_sha256(repo_root)
    if pb_sec4120_sha != EXPECTED_PLAYBOOK_SEC4120_SHA256:
        raise RuntimeError(f"Playbook §4.1.20 SHA-256 mismatch: {pb_sec4120_sha} != {EXPECTED_PLAYBOOK_SEC4120_SHA256}")

    return {
        "wetlab_contract_not_imported": True,
        "frozen_lims_files": lims_verified,
        "frozen_pareto_sha256": pareto_sha,
        "playbook_sec4120_sha256": pb_sec4120_sha,
        "all_invariants_passed": True,
    }


def build_verification_artifact(repo_root: Path) -> Dict[str, Any]:
    lims_audit = run_zero_lims_touch_invariance_checks(repo_root)
    shell_ledger = compute_per_bead_shell_unbuildability_ledger()
    fvm_sweeps = run_live_3d_fvm_conserved_inventory_coupled_sweeps()

    ref_pass = evaluate_gate31_coupled_cao2_lot(_reference_passing_lot_fixture())
    if ref_pass["exit_code"] != 0:
        raise RuntimeError(f"Reference Gate 31 fixture unexpectedly failed: {ref_pass}")

    # Deterministic negative controls verifying fail-closed coupling
    neg_cases: Dict[str, Dict[str, Any]] = {}
    base = _reference_passing_lot_fixture()

    neg_specs = {
        "decoupled_lot_id_fail": {**base, "kinetics_336h_lot_id": "LOT-OTHER-999"},
        "per_bead_conformal_shell_fail": {**base, "barrier_geometry_mode": "PER_BEAD_CONFORMAL_SHELL"},
        "short_burst_t12_20h_fail": {**base, "obs_cao2_release_half_life_h": 20.0, "obs_cao2_release_half_life_se_h": 1.0},
        "third_coupling_o2_lag_0p50_fail": {**base, "obs_hour0_to_24h_o2_delivery_ratio": 0.50, "obs_hour0_to_24h_o2_delivery_ratio_se": 0.02},
        "sealed_chamber_only_hold": {**base, "kinetics_assay_regime": "SEALED_CHAMBER_ONLY"},
        "design_b_non_cao2_out_of_scope_hold": {**base, "design_family": "B"},
        "ginstling_brounshtein_at_60h_fail": {**base, "vascular_midpoint_horizon_h": 60.0, "obs_cao2_kinetic_law_code": 2},
    }
    for name, fx in neg_specs.items():
        res = evaluate_gate31_coupled_cao2_lot(fx)
        if res["release_authorizing"] is not False or res["exit_code"] == 0:
            raise RuntimeError(f"Negative control {name} unexpectedly authorized release!")
        neg_cases[name] = {
            "verdict": res["verdict"],
            "exit_code": res["exit_code"],
            "release_authorizing": res["release_authorizing"],
            "hard_stops": res["hard_stops"],
            "holds": res["holds"],
        }

    dec134_ref_pass = evaluate_gate31_stage0_release_dec134(_reference_dec134_stage0_release_lot_fixture())
    if dec134_ref_pass["exit_code"] != 0 or not dec134_ref_pass["release_authorizing"]:
        raise RuntimeError(f"DEC-134 reference Stage-0 release fixture failed: {dec134_ref_pass}")
    dec134_base = _reference_dec134_stage0_release_lot_fixture()
    dec134_neg_specs = {
        "sensitivity_36h_hold": {**dec134_base, "vascular_midpoint_horizon_h": 36.0},
        "excursion_over_4h_fail": {**dec134_base, "obs_po2_below_15mmhg_cumulative_h": 4.5},
        "hypoxia_below_10mmhg_fail": {**dec134_base, "obs_po2_min_mmhg": 9.5},
        "h2o2_cell_center_72p5um_hold": {
            **dec134_base,
            "obs_h2o2_measurement_site": "FIRST_TISSUE_CELL_CENTER_Z_72P5_UM",
            "obs_h2o2_z_um": 72.5,
        },
        "paired_blocks_n4_lt_6_hold": {
            **dec134_base,
            "obs_paired_blocks": dec134_base["obs_paired_blocks"][:4],
        },
        "unpaired_summary_only_hold": {
            k: v for k, v in dec134_base.items() if k != "obs_paired_blocks"
        },
    }
    dec134_neg_cases: Dict[str, Dict[str, Any]] = {}
    for name, fx in dec134_neg_specs.items():
        r_d = evaluate_gate31_stage0_release_dec134(fx)
        if r_d["release_authorizing"] is not False or r_d["exit_code"] == 0:
            raise RuntimeError(f"DEC-134 negative control {name} unexpectedly authorized release!")
        dec134_neg_cases[name] = {
            "verdict": r_d["verdict"],
            "exit_code": r_d["exit_code"],
            "release_authorizing": r_d["release_authorizing"],
            "hard_stops": r_d["hard_stops"],
            "holds": r_d["holds"],
        }

    side_contract_sha = sha256_file(repo_root / SIDE_CONTRACT_REL)
    return {
        "schema_version": "iip0045_cao2_coupled_gate31_verification_v0.8.0",
        "contribution_id": CONTRIBUTION_ID,
        "decision_id": DECISION_ID,
        "gate_id": GATE_ID,
        "graveyard_card_id": GRAVEYARD_CARD_ID,
        "generated_date": GENERATED_DATE,
        "live_odds_delta_pp": 0.0,
        "side_contract_path": SIDE_CONTRACT_REL,
        "side_contract_sha256": side_contract_sha,
        "zero_lims_touch_invariance": lims_audit,
        "per_bead_20um_conformal_shell_unbuildability_ledger": shell_ledger,
        "live_3d_fvm_conserved_791p5mg_coupled_sweeps": fvm_sweeps,
        "gate31_reference_lot_evaluation": ref_pass,
        "gate31_negative_control_matrix": neg_cases,
        "dec134_stage0_release_policy_verification": {
            "policy_decision_id": "DEC-134",
            "legacy_36h_default_physical_lots_count": 0,
            "reference_release_lot_evaluation": dec134_ref_pass,
            "negative_control_matrix": dec134_neg_cases,
        },
    }


def main(argv: Optional[List[str]] = None) -> int:
    parser = argparse.ArgumentParser(description="IIP-0045 / DEC-125 / Gate 31 Coupled CaO2 Verifier")
    parser.add_argument("--repo-root", type=Path, default=REPO_ROOT)
    parser.add_argument("--write-verification", action="store_true")
    parser.add_argument("--check", action="store_true")
    parser.add_argument("--evaluate-lot", type=Path, default=None)
    parser.add_argument("--evaluate-stage0-release", type=Path, default=None)
    args = parser.parse_args(argv)

    eval_path = args.evaluate_stage0_release or args.evaluate_lot
    if eval_path is not None:
        try:
            raw = eval_path.read_text(encoding="utf-8")
            parsed = strict_json_loads(raw)
        except Exception as exc:
            err_out = {
                "gate_id": GATE_ID,
                "contribution_id": CONTRIBUTION_ID,
                "decision_id": DECISION_ID,
                "verdict": "HOLD_GATE31_STRICT_JSON_PARSE_ERROR",
                "exit_code": 2,
                "release_authorizing": False,
                "hard_stops": [],
                "holds": [str(exc)],
                "diagnostics": {},
            }
            print(json.dumps(err_out, indent=2, allow_nan=False))
            return 2
        res = (
            evaluate_gate31_stage0_release_dec134(parsed)
            if args.evaluate_stage0_release is not None
            else evaluate_gate31_coupled_cao2_lot(parsed)
        )
        print(json.dumps(res, indent=2, allow_nan=False))
        return int(res["exit_code"])

    payload = build_verification_artifact(args.repo_root)
    serialized = json.dumps(payload, indent=2, allow_nan=False) + "\n"
    out_path = args.repo_root / VERIFICATION_REL

    if args.write_verification:
        out_path.write_text(serialized, encoding="utf-8")
        print(f"Wrote {out_path} ({len(serialized)} bytes, sha256={hashlib.sha256(serialized.encode('utf-8')).hexdigest()})")
        return 0

    if args.check:
        if not out_path.is_file():
            print(f"MISSING verification artifact: {out_path}", file=sys.stderr)
            return 1
        existing = out_path.read_text(encoding="utf-8")
        if existing != serialized:
            print(f"DRIFT detected in {out_path}", file=sys.stderr)
            return 1
        print(f"OK: {out_path} byte-identical (sha256={hashlib.sha256(existing.encode('utf-8')).hexdigest()})")
        return 0

    print(serialized)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())