OpenIslet

scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated)

script Release v0.8.0 gen-eb955f8266035aba 1008 KB · 76 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_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…

        "clustered_disposition": sol_paired["adjudication_disposition"],
        "independent_certified": indep_ref["exact_directional_confidence_certified"],
        "passed": r11_b3_ok,
    })

    # 18. R11-M1: Zero-denominator boundary conventions:
    #     (a) 0/0 -> empirical point is None and bounds_ordered_l_le_point_le_u is None (NOT True!)
    #     (b) k > 0 / 0 -> empirical point is +Infinity, u_ratio is +Infinity, bounds_ordered_l_le_point_le_u is True.
    z00 = exact_paired_vehicle_ratio_bounds(0, 100, 0, 100, prec=60)
    z50 = exact_paired_vehicle_ratio_bounds(5, 100, 0, 100, prec=60)
    r11_m1_ok = bool(
        z00["empirical_ratio_point_estimate_dec"] is None
        and z00["bounds_ordered_l_le_u"] is True
        and z00["bounds_ordered_l_le_point_le_u"] is None
        and z00["u_ratio_dec"] == Decimal("Infinity")
        and z00["zero_denominator_boundary_convention"] == "UNDEFINED_0_OVER_0_POINT_AND_POINT_ORDERING_FLAG_NONE"
        and z50["empirical_ratio_point_estimate_dec"] == Decimal("Infinity")
        and z50["bounds_ordered_l_le_u"] is True
        and z50["bounds_ordered_l_le_point_le_u"] is True
        and z50["u_ratio_dec"] == Decimal("Infinity")
        and z50["zero_denominator_boundary_convention"] == "POSITIVE_NUMERATOR_ZERO_DENOMINATOR_POINT_PLUS_INFINITY"
    )
    checks.append({
        "test": "r11_m1_zero_denominator_boundary_conventions_0over0_none_and_kpos_over0_infinity",
        "zero_over_zero_point": z00["empirical_ratio_point_estimate_dec"],
        "zero_over_zero_point_ordering_flag": z00["bounds_ordered_l_le_point_le_u"],
        "pos_over_zero_point": str(z50["empirical_ratio_point_estimate_dec"]),
        "pos_over_zero_point_ordering_flag": z50["bounds_ordered_l_le_point_le_u"],
        "passed": r11_m1_ok,
    })

    # 19. R16-M2: Exact arbitrary-precision integer floor `n_eff = floor(n / deff)` via
    #     `Fraction(n) // Fraction(deff)` — eliminates 80-digit Decimal rounding down for huge
    #     admitted counts such as `n = 10**80 + 1, deff = 1 -> exact 10**80 + 1`!
    n_huge = 10 ** 80 + 1
    r_huge_u = exact_component_probability_ratio_upper(
        0, n_huge, Decimal("0.025"), (Decimal("1.0"),), deff=Decimal("1.0"), prec=80
    )
    r_huge_p = exact_paired_vehicle_ratio_bounds(
        0, n_huge, 100, 100, alpha_treated=Decimal("0.025"), alpha_veh=Decimal("0.025"), deff=Decimal("1.000"), prec=80
    )
    r_huge_d2 = exact_component_probability_ratio_upper(
        0, 2 * (10 ** 80) + 2, Decimal("0.025"), (Decimal("1.0"),), deff=Decimal("2.0"), prec=80
    )
    r_huge_d15 = exact_component_probability_ratio_upper(
        0, 3 * (10 ** 80) + 3, Decimal("0.025"), (Decimal("1.0"),), deff=Decimal("1.5"), prec=80
    )
    sub_ulp_deff = Decimal("1.00000000000000001")
    r_huge_sub = exact_component_probability_ratio_upper(
        0, n_huge, Decimal("0.025"), (Decimal("1.0"),), deff=sub_ulp_deff, prec=80
    )
    exp_sub_eff = int(Fraction(n_huge) // Fraction(sub_ulp_deff))
    r16_m2_ok = bool(
        r_huge_u["n_treated_eff"] == n_huge
        and r_huge_p["n_treated_eff"] == n_huge
        and r_huge_d2["n_treated_eff"] == n_huge
        and r_huge_d15["n_treated_eff"] == 2 * (10 ** 80) + 2
        and r_huge_sub["n_treated_eff"] == exp_sub_eff
        and r_huge_sub["exact_directional_confidence_certified"] is False
    )
    checks.append({
        "test": "r16_m2_exact_integer_floor_n_eff_for_huge_counts_10pow80_plus_1",
        "n_10pow80_plus_1_deff1_exact_match": bool(r_huge_u["n_treated_eff"] == n_huge),
        "n_2e80_plus_2_deff2_exact_match": bool(r_huge_d2["n_treated_eff"] == n_huge),
        "n_3e80_plus_3_deff1p5_exact_match": bool(r_huge_d15["n_treated_eff"] == 2 * (10 ** 80) + 2),
        "sub_ulp_deff_exact_rational_floor_match": bool(r_huge_sub["n_treated_eff"] == exp_sub_eff),
        "passed": r16_m2_ok,
    })

    # 20. R17-B2: Provably outward-conservative upper-enclosed standard-normal 95% quantile z_{0.95}
    #     (80-digit Phi(z) > 0.95 -> tail 1 - Phi(z) < 0.05 strictly, while old 1.6448536269514722
    #     and 1.6448536269514726 strictly under-cover!) AND upward-rounded IEEE-754 float64 native
    #     solver vascular scaling on Sol's exact sub-ULP positive-SE example (1.097, SE=1e-20, df=5)
    #     plus 1.2067 + SE=1e-20 under BOTH clean and hostile Decimal contexts!
    p95_d = Decimal("0.95")
    phi_z_dec = _exact_standard_normal_cdf_dec(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC, prec=80)
    phi_z_f64 = _exact_standard_normal_cdf_dec(Decimal.from_float(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95), prec=80)
    phi_z_str = _exact_standard_normal_cdf_dec(Decimal(str(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95)), prec=80)
    phi_old_722 = _exact_standard_normal_cdf_dec(Decimal.from_float(1.6448536269514722), prec=80)
    phi_old_726 = _exact_standard_normal_cdf_dec(Decimal.from_float(1.6448536269514726), prec=80)

    t5_upper_d = Decimal.from_float(exact_student_t_one_sided_95(5))
    with _clean_dec_ctx(60, ROUND_CEILING):
        sol_u95_t5_d = Decimal("1.097") + t5_upper_d * Decimal("1e-20")
        sol_u95_ks_d = Decimal("1.097") + MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC * Decimal("1e-20")
        sol_u95_12067_d = Decimal("1.2067") + t5_upper_d * Decimal("1e-20")

    sc_det_1097, eff_det_1097 = _compute_conservative_upper_float64_vasc_scale(Decimal("1.097"), 1.097, Decimal("1.097"))
    sc_det_12067, eff_det_12067 = _compute_conservative_upper_float64_vasc_scale(Decimal("1.2067"), 1.2067, Decimal("1.2067"))
    sc_t5_1097, eff_t5_1097 = _compute_conservative_upper_float64_vasc_scale(sol_u95_t5_d, 1.097, Decimal("1.097"))
    sc_ks_1097, eff_ks_1097 = _compute_conservative_upper_float64_vasc_scale(sol_u95_ks_d, 1.097, Decimal("1.097"))
    sc_t5_12067, eff_t5_12067 = _compute_conservative_upper_float64_vasc_scale(sol_u95_12067_d, 1.2067, Decimal("1.2067"))

    hostile_r17_ok = True
    with localcontext(Context(prec=4, rounding=ROUND_FLOOR, Emin=-2, Emax=100, traps=[decimal.Inexact])):
        try:
            sc_h, eff_h = _compute_conservative_upper_float64_vasc_scale(sol_u95_t5_d, 1.097, Decimal("1.097"))
            phi_h = _exact_standard_normal_cdf_dec(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC, prec=80)
            if sc_h != sc_t5_1097 or eff_h != eff_t5_1097 or phi_h != phi_z_dec:
                hostile_r17_ok = False
        except Exception:
            hostile_r17_ok = False

    r17_b2_dec_ok = bool(
        phi_z_dec > p95_d
        and phi_z_f64 > p95_d
        and phi_z_str > p95_d
        and phi_old_722 < p95_d
        and phi_old_726 < p95_d
        and sc_det_1097 == 1.0
        and sc_det_12067 == 1.0
        and sc_t5_1097 > 1.0
        and Fraction(sc_t5_1097) >= Fraction(sol_u95_t5_d) / Fraction(Decimal("1.097"))
        and Fraction(eff_t5_1097) >= Fraction(sol_u95_t5_d)
        and sc_ks_1097 > 1.0
        and Fraction(sc_ks_1097) >= Fraction(sol_u95_ks_d) / Fraction(Decimal("1.097"))
        and Fraction(eff_ks_1097) >= Fraction(sol_u95_ks_d)
        and sc_t5_12067 > 1.0
        and Fraction(sc_t5_12067) >= Fraction(sol_u95_12067_d) / Fraction(Decimal("1.2067"))
        and Fraction(eff_t5_12067) >= Fraction(sol_u95_12067_d)
        and hostile_r17_ok
    )
    checks.append({
        "test": "r17_b2_known_sigma_z95_strict_upper_enclosure_and_upward_float64_solver_scale",
        "z95_dec_strictly_above_0p95": bool(phi_z_dec > p95_d),
        "z95_float64_strictly_above_0p95": bool(phi_z_f64 > p95_d),
        "old_1p6448536269514722_undercovers": bool(phi_old_722 < p95_d),
        "old_1p6448536269514726_undercovers": bool(phi_old_726 < p95_d),
        "sub_ulp_t5_1p097_scale_f64": sc_t5_1097,
        "sub_ulp_t5_1p097_eff_ocr_f64": eff_t5_1097,
        "sub_ulp_t5_1p2067_scale_f64": sc_t5_12067,
        "hostile_decimal_context_immune": hostile_r17_ok,
        "passed": r17_b2_dec_ok,
    })

    passed_n = sum(1 for c in checks if c["passed"])
    return {
        "total_checks": len(checks),
        "passed_checks": passed_n,
        "all_passed": passed_n == len(checks),
        "checks": checks,
    }


def run_adversarial_contract_tests(openislet_root: Path | None = None) -> Dict[str, Any]:
    resolved_root = openislet_root.resolve() if openislet_root is not None else _resolve_roots(None, None)[0]
    cases: List[Dict[str, Any]] = []

    def _record(
        name: str,
        expected_verdict: str,
        payload: Dict[str, Any],
        expected_token: str | None = None,
        *,
        store_path: Path | None = None,
    ):
        res = evaluate_wholegraft_gate0v_and_stress_ap1903(
            payload,
            trusted_qualification_store=store_path,
            openislet_root=resolved_root,
        )
        ok = res["verdict"] == expected_verdict
        if expected_token is not None:
            all_msgs = res["hard_stops"] + res["holds"]
            ok = ok and any(expected_token in m for m in all_msgs)
        cases.append({
            "case": name,
            "expected_verdict": expected_verdict,
            "actual_verdict": res["verdict"],
            "expected_token": expected_token,
            "hard_stops": res["hard_stops"][:3],
            "holds": res["holds"][:3],
            "passed": ok,
        })
        return res

    # 1. Clean 3-pathogen x 5-lineage + 5-regime BANK_QUALIFICATION -> PASS_WHOLEGRAFT_BANK_QUALIFICATION (B6)
    _record("clean_bank_qualification_twostage_pass", "PASS_WHOLEGRAFT_BANK_QUALIFICATION", build_passing_reference_payload(openislet_root=resolved_root))

    # 2. Reconciled non-zero viral-negative survivors (2==2 on high-input beta arm clearing 4-log) -> PASS_WHOLEGRAFT_BANK_QUALIFICATION
    p_rec_nz = build_passing_reference_payload(openislet_root=resolved_root)
    p_rec_nz["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["ap1903_72h_viable_survivors_k"] = 2
    p_rec_nz["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_survivors_total_n"] = 2
    p_rec_nz["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["survivors_scored_n"] = 2
    reconcile_fixture_per_unit_counts(p_rec_nz)
    _record("reconciled_nonzero_viral_negative_survivors_passes", "PASS_WHOLEGRAFT_BANK_QUALIFICATION", _seal(p_rec_nz))

    # 2B. Survivor reconciliation regression: unreconciled 72h survivors (0) vs infected-arm viable survivors (3) -> HOLD!
    p_unrec = build_passing_reference_payload(openislet_root=resolved_root)
    p_unrec["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["ap1903_72h_viable_survivors_k"] = 0
    p_unrec["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_survivors_total_n"] = 3
    p_unrec["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["survivors_scored_n"] = 3
    _record("unreconciled_72h_vs_infected_survivors_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_unrec), "ALIQUOT_SURVIVOR_COUNT_MISMATCH")

    # 2C. B4 + R06-B1 Exact <= 0.050 Bonferroni union-bound budgets across 24h, 72h, E1, Direct E2 & Indirect E2,
    #     with release-authorizing PASS restricted strictly to DIRECT_INFECTED_VEHICLE_DENOMINATOR and
    #     indirect-only marginal mode strictly held as CONDITIONAL_INDIRECT_DIAGNOSTIC_ONLY_UNVERIFIED_SURVIVAL_INEQUALITY!
    p_dir_e2 = build_passing_reference_payload(use_direct_infected_veh_survivor_mode=True, openislet_root=resolved_root)
    res_dir_e2 = evaluate_wholegraft_gate0v_and_stress_ap1903(p_dir_e2, openislet_root=resolved_root)
    res_ind_e2 = evaluate_wholegraft_gate0v_and_stress_ap1903(
        build_passing_reference_payload(use_direct_infected_veh_survivor_mode=False, openislet_root=resolved_root),
        openislet_root=resolved_root,
    )
    ind_per = res_ind_e2["stress_ap1903_regimes"]["active_or_persistent_cvb4_infection"]["lineages"]["pericyte"]
    dir_per = res_dir_e2["stress_ap1903_regimes"]["active_or_persistent_cvb4_infection"]["lineages"]["pericyte"]
    b_ok = bool(
        res_dir_e2["verdict"] == "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
        and dir_per["infected_cell_escape_mode"] == "DIRECT_INFECTED_VEHICLE_DENOMINATOR"
        and dir_per["estimand2_release_authorizing_eligible"] is True
        and res_ind_e2["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE" in res_ind_e2["holds"]
        and ind_per["infected_cell_escape_mode"] == "CONDITIONAL_INDIRECT_DIAGNOSTIC_ONLY_UNVERIFIED_SURVIVAL_INEQUALITY"
        and ind_per["estimand2_release_authorizing_eligible"] is False
        and Decimal(ind_per["bonferroni_alpha_budget_24h"]["union_bound_sum"]) <= Decimal("0.050")
        and Decimal(ind_per["bonferroni_alpha_budget_72h"]["union_bound_sum"]) <= Decimal("0.050")
        and Decimal(ind_per["estimand1_bonferroni_alpha_budget"]["union_bound_sum"]) <= Decimal("0.050")
        and Decimal(ind_per["estimand2_bonferroni_alpha_budget"]["union_bound_sum"]) == Decimal("0.050")
        and Decimal(dir_per["estimand2_bonferroni_alpha_budget"]["union_bound_sum"]) == Decimal("0.050")
        and ind_per["estimand2_bonferroni_alpha_budget"]["alpha_veh"] == "0.015"
        and ind_per["estimand2_bonferroni_alpha_budget"]["alpha_prev"] == "0.015"
        and ind_per["estimand2_bonferroni_alpha_budget"]["alpha_eta"] == "0.005"
        and ind_per["estimand2_bonferroni_alpha_budget"]["alpha_escape"] == "0.015"
        and dir_per["estimand2_bonferroni_alpha_budget"]["alpha_inf_veh"] == "0.025"
        and dir_per["estimand2_bonferroni_alpha_budget"]["alpha_eta"] == "0.005"
        and dir_per["estimand2_bonferroni_alpha_budget"]["alpha_escape"] == "0.020"
    )
    cases.append({
        "case": "b4_r06_b1_bonferroni_budgets_direct_pass_and_indirect_diagnostic_hold",
        "expected_verdict": "DIRECT_PASS_INDIRECT_HOLD_ALL_BUDGETS_LE_0P050",
        "actual_verdict": "DIRECT_PASS_INDIRECT_HOLD_ALL_BUDGETS_LE_0P050" if b_ok else f"FAILED({res_dir_e2['verdict']},{res_ind_e2['verdict']})",
        "expected_token": "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE",
        "hard_stops": [],
        "holds": res_ind_e2["holds"][:3],
        "passed": b_ok,
    })

    # 3. Lot-binding tamper: payload_sha256 mismatch -> HOLD
    p_tamper = build_passing_reference_payload(openislet_root=resolved_root)
    p_tamper["lot_id"] = "LOT-TAMPERED-999"
    _record("payload_sha256_tamper_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", p_tamper, "MISMATCHED_PAYLOAD_SHA256")

    # 3B. B2 Unregistered product_variant_id rejected fail-closed!
    p_unreg = build_passing_reference_payload(product_variant_id="ISLET1_DESIGN_A_LEAD", openislet_root=resolved_root)
    _record("b2_unregistered_product_variant_id_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", p_unreg, "UNREGISTERED_PRODUCT_VARIANT_ID")

    # 3C. B2 Canonical TYK2_PE product declaring TYK2_WT genotype rejected!
    p_tyk2_confl = build_passing_reference_payload(
        product_variant_id="ISLET1_A4_ARM1B_TYK2_PE",
        antiviral_genotype_stratum="TYK2_WT__IFIH1_WT_OR_A946T",
        openislet_root=resolved_root,