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…

        huge_cases = (
            ("pos_1e400", f'{{"qualification_tier": "BANK_QUALIFICATION", "huge_int": {10**400}}}', "OUT_OF_RANGE_JSON_INTEGER"),
            ("neg_1e400", f'{{"qualification_tier": "BANK_QUALIFICATION", "huge_int": {-10**400}}}', "OUT_OF_RANGE_JSON_INTEGER"),
            ("float_1e500", '{"qualification_tier": "BANK_QUALIFICATION", "huge_flt": 1e500}', "NON_FINITE_JSON_FLOAT"),
        )
        r10_huge_ok = True
        r10_huge_holds: List[str] = []
        for h_tag, h_raw, h_reason in huge_cases:
            hf = td_r10_p / f"r10_huge_{h_tag}.json"
            hf.write_text(h_raw, encoding="utf-8")
            h_res, h_rc = evaluate_wholegraft_gate0v_lot_file(hf, openislet_root=resolved_root)
            r10_huge_holds = h_res.get("holds") or []
            if not (
                h_rc == 2
                and h_res.get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and f"HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:{h_reason}" in r10_huge_holds
            ):
                r10_huge_ok = False
        cases.append({
            "case": "r10_b2_out_of_float64_range_integers_and_1e500_standalone_lot_file_structured_hold_exit_2",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if r10_huge_ok else "UNHANDLED_OVERFLOW_OR_WRONG_RC",
            "expected_token": "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:OUT_OF_RANGE_JSON_INTEGER",
            "hard_stops": [],
            "holds": r10_huge_holds[:3],
            "passed": r10_huge_ok,
        })

    # ------------------------------------------------------------------
    # Round-11 Final-Closure Adversarial Regressions (R11-B1, R11-B3, R11-B4)
    # ------------------------------------------------------------------
    # 50. R11-B3: Sol's exact exchangeable mixture deff = 2.0161290322580645 even when ALL sample sizes
    #     are scaled up 3x (so naive n_eff clears every threshold!) MUST STILL route to non-authorizing
    #     HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE (`exact_directional_confidence_certified=False`,
    #     `release_authorizing=False`), while deterministic biological FAIL_HARD_STOP (`vk=1`) is preserved!
    p_sol_scaled = build_passing_reference_payload(openislet_root=resolved_root)
    p_sol_scaled["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "2.0161290322580645"
    for _pid, _pb in p_sol_scaled["gate0v_b_infectious_challenge"]["pathogens"].items():
        _pb["total_viable_cells_acquired_n"] = _pb["total_viable_cells_acquired_n"] * 3
        _pb["lineage_unassigned_cells_n"] = _pb["lineage_unassigned_cells_n"] * 3
        _pb["unassigned_fraction_viral_readout"]["unassigned_cells_screened_n"] = _pb["lineage_unassigned_cells_n"]
        _pb["day28_latent_and_defective_genome_arm"]["ddpcr_cell_equivalents_screened_n"] *= 3
        for _tentry in _pb["day28_latent_and_defective_genome_arm"]["ddpcr_targets"].values():
            _tentry["n"] *= 3
        for _lentry in _pb["day28_persistence_by_lineage"].values():
            _lentry["cells_assigned_n"] *= 3
            _lentry["cells_scored_n"] *= 3
    for _reg, _rb in p_sol_scaled["gate0v_kill_stress_ap1903"].items():
        for _lin, _lb in _rb.items():
            _lb["ap1903_24h_input_n"] *= 3
            _lb["ap1903_72h_input_n"] *= 3
            if "pre_ap1903_lineage_input_cells_n" in _lb:
                _lb["pre_ap1903_lineage_input_cells_n"] *= 3
    reconcile_fixture_per_unit_counts(p_sol_scaled)
    r_sol_scaled = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_sol_scaled), openislet_root=resolved_root)
    det_sol_arm = r_sol_scaled["stress_ap1903_regimes"]["active_or_persistent_cvb4_infection"]["lineages"]["beta"]
    p_sol_bio_fail = copy.deepcopy(p_sol_scaled)
    p_sol_bio_fail["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_viral_pos_k"] = 1
    reconcile_fixture_per_unit_counts(p_sol_bio_fail)
    r_sol_bio_fail = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_sol_bio_fail), openislet_root=resolved_root)
    p_sol_cp_only = copy.deepcopy(p_sol_scaled)
    p_sol_cp_only["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["alpha"]["ap1903_24h_viable_survivors_k"] = 30
    reconcile_fixture_per_unit_counts(p_sol_cp_only)
    r_sol_cp_only = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_sol_cp_only), openislet_root=resolved_root)
    ok_r11_b3 = bool(
        r_sol_scaled["verdict"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        and r_sol_scaled["release_authorizing"] is False
        and r_sol_scaled["exact_directional_confidence_certified"] is False
        and r_sol_scaled["confidence_scope"] == "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
        and "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in r_sol_scaled["holds"]
        and det_sol_arm["exact_directional_confidence_certified"] is False
        and det_sol_arm["bonferroni_alpha_budget_24h"]["joint_confidence_lower_bound"] is None
        and det_sol_arm["bonferroni_alpha_budget_72h"]["joint_confidence_lower_bound"] is None
        and det_sol_arm["estimand1_bonferroni_alpha_budget"]["joint_confidence_lower_bound"] is None
        and det_sol_arm["estimand2_bonferroni_alpha_budget"]["joint_confidence_lower_bound"] is None
        and det_sol_arm["estimand2_release_authorizing_eligible"] is False
        and r_sol_bio_fail["verdict"] == "FAIL_HARD_STOP"
        and r_sol_cp_only["verdict"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
    )
    cases.append({
        "case": "r11_b3_sol_deff_2p0161_high_n_held_cluster_inference_bio_fail_preserved",
        "expected_verdict": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
        "actual_verdict": r_sol_scaled["verdict"],
        "expected_token": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
        "hard_stops": r_sol_bio_fail["hard_stops"][:2],
        "holds": r_sol_scaled["holds"][:3],
        "passed": ok_r11_b3,
    })

    # 51. R11-B1 + R13-B3: Standalone clinical `LOT_RELEASE_SURROGATE` Gate-0V payload declaring
    #     `require_trusted_nw08_ocr_record = True` without coupled OCR emits
    #     `HOLD_NW08_REQUIRED_OCR_RECORD_MISSING` (exit 2, release_authorizing=False), non-bool
    #     flag fails closed to HOLD, and independent biological FAIL_HARD_STOP is preserved!
    with tempfile.TemporaryDirectory() as td_r11_b1_sa:
        td_b1_sa = Path(td_r11_b1_sa)
        b_ref_51 = build_passing_reference_payload(
            lot_id="BANK-R11B1-SA-001",
            mcb_id="MCB-R11B1-SA-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )
        brec_51 = build_authenticated_bank_qualification_record(
            mcb_id="MCB-R11B1-SA-001",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-R11B1-SA-001",
            bank_payload_sha256=b_ref_51["payload_sha256"],
        )
        st_51 = td_b1_sa / "trusted_store_51.json"
        write_record_to_trusted_qualification_store(
            st_51, brec_51, category="bank_qualifications", archived_payload=b_ref_51
        )
        p_req_ocr = build_passing_reference_payload(
            lot_id="LOT-R11B1-SA-001",
            mcb_id="MCB-R11B1-SA-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=brec_51["sha256"],
            openislet_root=resolved_root,
        )
        p_req_ocr["require_trusted_nw08_ocr_record"] = True
        r_req_ocr = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_req_ocr), trusted_qualification_store=st_51, openislet_root=resolved_root
        )
        p_req_ocr_fail = copy.deepcopy(p_req_ocr)
        p_req_ocr_fail["cxadr_ko_present"] = True
        r_req_ocr_fail = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_req_ocr_fail), trusted_qualification_store=st_51, openislet_root=resolved_root
        )
        p_req_ocr_badtype = copy.deepcopy(p_req_ocr)
        p_req_ocr_badtype["require_trusted_nw08_ocr_record"] = "true"
        r_req_ocr_badtype = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_req_ocr_badtype), trusted_qualification_store=st_51, openislet_root=resolved_root
        )
        p_req_ocr_null = copy.deepcopy(p_req_ocr)
        p_req_ocr_null["require_trusted_nw08_ocr_record"] = None
        r_req_ocr_null = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_req_ocr_null), trusted_qualification_store=st_51, openislet_root=resolved_root
        )
    ok_r11_b1_sa = bool(
        r_req_ocr["verdict"] == "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"
        and r_req_ocr["release_authorizing"] is False
        and "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING" in r_req_ocr["holds"]
        and r_req_ocr_fail["verdict"] == "FAIL_HARD_STOP"
        and "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING" in r_req_ocr_fail["holds"]
        and r_req_ocr_badtype["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and "HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG" in r_req_ocr_badtype["holds"]
        and r_req_ocr_null["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and "HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG" in r_req_ocr_null["holds"]
    )
    cases.append({
        "case": "r11_b1_standalone_require_trusted_nw08_ocr_missing_hold_nonbool_hold_fail_preserved",
        "expected_verdict": "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
        "actual_verdict": r_req_ocr["verdict"],
        "expected_token": "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
        "hard_stops": r_req_ocr_fail["hard_stops"][:2],
        "holds": r_req_ocr["holds"][:3],
        "passed": ok_r11_b1_sa,
    })

    # 52. R11-B4: JSON nesting depth > 64 AND monkeypatched parser RecursionError on `{}` map cleanly
    #     to structured HOLD exit 2 (`release_authorizing=False`, `JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED`)
    #     across standalone lot intake AND trusted qualification store (registry JSON + dir store + OCR store)!
    with tempfile.TemporaryDirectory() as td_r11_b4_sa:
        td_b4s = Path(td_r11_b4_sa)
        deep_70_txt = '{"a":' * 70 + "1" + "}" * 70
        f_deep_lot = td_b4s / "deep_70_lot.json"
        f_deep_lot.write_text(deep_70_txt, encoding="utf-8")
        f_empty_lot = td_b4s / "empty_lot.json"
        f_empty_lot.write_text("{}", encoding="utf-8")
        f_deep_store = td_b4s / "deep_70_store.json"
        f_deep_store.write_text(deep_70_txt, encoding="utf-8")

        r_dl, rc_dl = evaluate_wholegraft_gate0v_lot_file(f_deep_lot, openislet_root=resolved_root)
        _rec_ds, _arch_ds, errs_ds, _src_ds, _ast_ds = _lookup_in_trusted_qualification_store_with_archive_status(
            f_deep_store, category="bank_qualifications", expected_sha256=_valid_digest("r11_b4_ref")
        )
        ok_ocr_ds, errs_ocr_ds, _meta_ocr_ds = resolve_and_verify_trusted_nw08_ocr_record(
            f_deep_store,
            expected_ocr_record_sha256=_valid_digest("r11_b4_ocr"),
            submitted_ocr_record={"route_id": "R2_DZ40"},
            require_store_entry=True,
        )

        orig_jl = json.loads

        def _boom_rec(*_a: Any, **_kw: Any) -> Any:
            raise RecursionError("simulated parser recursion error")

        json.loads = _boom_rec  # type: ignore[assignment]
        try:
            r_rl, rc_rl = evaluate_wholegraft_gate0v_lot_file(f_empty_lot, openislet_root=resolved_root)
            _rec_rs, _arch_rs, errs_rs, _src_rs, _ast_rs = _lookup_in_trusted_qualification_store_with_archive_status(
                f_empty_lot, category="bank_qualifications", expected_sha256=_valid_digest("r11_b4_ref")
            )
            ok_ocr_rs, errs_ocr_rs, _meta_ocr_rs = resolve_and_verify_trusted_nw08_ocr_record(
                f_empty_lot,
                expected_ocr_record_sha256=_valid_digest("r11_b4_ocr"),
                submitted_ocr_record={"route_id": "R2_DZ40"},
                require_store_entry=True,
            )
        finally:
            json.loads = orig_jl  # type: ignore[assignment]
    ok_r11_b4_sa = bool(
        rc_dl == 2
        and r_dl.get("release_authorizing") is False
        and "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in (r_dl.get("holds") or [])
        and rc_rl == 2
        and r_rl.get("release_authorizing") is False
        and "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in (r_rl.get("holds") or [])
        and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in errs_ds
        and any("JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in e for e in errs_ds)
        and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in errs_rs
        and any("JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in e for e in errs_rs)
        and ok_ocr_ds is False
        and any("JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in e for e in errs_ocr_ds)
        and ok_ocr_rs is False
        and any("JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in e for e in errs_ocr_rs)
    )
    cases.append({
        "case": "r11_b4_depth_gt_64_and_injected_recursion_error_standalone_lot_and_trusted_store_hold_exit_2",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if ok_r11_b4_sa else "UNHANDLED_RECURSION_OR_WRONG_RC",
        "expected_token": "JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED",
        "hard_stops": [],
        "holds": (r_rl.get("holds") or [])[:3],
        "passed": ok_r11_b4_sa,
    })

    # ------------------------------------------------------------------
    # Round-12 Final-Closure Adversarial Regressions (R12-B1 & R12-B2)
    # ------------------------------------------------------------------
    # 53. R12-B1 (a): Missing or invalid clustering_and_independence_spec NEVER defaults deff=1.0,
    #     sets deff=None, exact_directional_confidence_certified=False,
    #     confidence_scope="UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC", release_authorizing=False,
    #     and preserves deterministic biological FAIL_HARD_STOP (cxadr_ko_present, vk=1, caspase<5, k>n)!
    p_miss_spec = build_passing_reference_payload(openislet_root=resolved_root)
    p_miss_spec.pop("clustering_and_independence_spec", None)
    r_miss_spec = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_miss_spec), openislet_root=resolved_root)

    p_bad_deff = build_passing_reference_payload(openislet_root=resolved_root)
    p_bad_deff["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "bad_deff"
    r_bad_deff = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_bad_deff), openislet_root=resolved_root)

    p_lt1_deff = build_passing_reference_payload(openislet_root=resolved_root)
    p_lt1_deff["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "0.5"
    r_lt1_deff = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_lt1_deff), openislet_root=resolved_root)

    p_miss_cx = copy.deepcopy(p_miss_spec)
    p_miss_cx["cxadr_ko_present"] = True