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…

    else:
        hold_tok = str(mesh_conv.get("hold_reason_token") or NW08_HOLD_TOKEN_STRADDLES_FLOOR)
        adj_decision = hold_tok
        adj_holds = [hold_tok]
    return {
        **trig,
        "release_authorizing": False,
        "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
        "physical_qualification_complete": False,
        "solver_isolation_mode": "ISOLATED_CHILD_SUBPROCESS",
        "resolved_solver_module_origins": solve_origins,
        "resolved_solver_module_relpaths": solve_relpaths,
        "all_solver_module_origins_within_repo_root": solve_origins_ok,
        "native_solver_vascular_operand_audit": solve_operand_audit,
        "solver_cleared_oxygen_floor_diagnostic": bool(passed_canonical_15mmhg),
        "nw08_oxygen_floor_adjudication_authoritative": True,
        "linear_screen_trigger_dispatched": linear_screen_triggered,
        "triggered_by_non_monotone_or_override_guard": triggered_by_non_monotone_or_override_guard,
        "within_provably_monotone_no_increase_domain": within_provably_monotone_no_increase_domain,
        "trigger_dispatched": effective_trigger_dispatched,
        "decision": (
            "TRIGGER_3D_FVM_RESOLVE_AND_PRECOMMITTED_DERATING_CHECK"
            if effective_trigger_dispatched
            else "FORCED_3D_FVM_RESOLVE_WITHIN_MONOTONE_DOMAIN"
        ),
        "catalog_default_p_bed_mmhg": catalog_default_p_bed,
        "effective_p_bed_mmhg": eff_p_bed,
        "p_bed_override_applied": p_bed_override_applied,
        "baseline_ocr_override_applied": baseline_ocr_override_applied,
        "any_parameter_override_applied": any_override_applied,
        "solver_p_bed_mmhg_verified": verified_solver_p_bed,
        "baseline_source": baseline_source,
        "solver_executed": True,
        "solved_at_vascular_ocr_u95": round(ocr_u95, 6),
        "solved_at_vascular_ocr_u95_exact_dec": str(ocr_u95_exact),
        "vascular_voxel_scale_factor": round(vasc_scale, 6),
        "native_solver_vasc_scale_float64": vasc_scale,
        "native_solver_effective_vascular_ocr_float64": effective_solver_ocr_f64,
        "face_min_mmhg_unrounded": solved_raw_mmhg,
        "face_min_mmhg": round(solved_raw_mmhg, 4),
        "canonical_floor_mmhg": CANONICAL_NW08_PO2_FLOOR_MMHG,
        "floor_mmhg": CANONICAL_NW08_PO2_FLOOR_MMHG,
        "margin_above_floor_unrounded_mmhg": solved_raw_mmhg - CANONICAL_NW08_PO2_FLOOR_MMHG,
        "passes_15mmhg_floor_unrounded": passed_canonical_15mmhg,
        "mesh_convergence_verification": mesh_conv,
        "mesh_convergence_resolved": mesh_resolved,
        "holds": adj_holds,
        "adjudicated_verdict": mesh_verdict,
        "adjudicated_decision": adj_decision,
        "diagnostic_custom_floor_mmhg": diag_floor,
        "diagnostic_margin_above_custom_floor_unrounded_mmhg": solved_raw_mmhg - diag_floor,
        "diagnostic_passes_custom_floor": diagnostic_passed_custom,
        "diagnostic_custom_floor_non_authorizing": True,
    }


def _run_r18_b1_concurrent_raw_native_isolation_test(openislet_root: Path) -> Dict[str, Any]:
    """
    R18-B1: Verify that a simultaneous raw native Layer-4 call (executed directly on
    `run_layer4_tissue_and_metabolic_twin.compute_design_z_140um_parameterized_case` WITHOUT
    acquiring `_FVM_SOLVER_LOCK`) agrees bit-for-bit before, during, and after concurrent
    modified NW-08 calls (`R2_DZ40`, bed=40, base=5.0, meas=10.0 -> ~13.1032 mmHg), while
    parent Layer-4 callbacks remain completely untouched throughout.
    """
    from concurrent.futures import ThreadPoolExecutor

    resolved_root = Path(openislet_root).resolve()
    r2_native_kw = {
        "bed_po2_mmhg": 40.0,
        "ocr_multiplier": 1.097,
        "d_gel_cm2_s": 1.5e-5,
        "k_perf_s_inv": 0.1358,
    }
    scripts_str = str(resolved_root / "scripts")
    added = False
    if scripts_str not in sys.path:
        sys.path.insert(0, scripts_str)
        added = True
    try:
        import run_layer4_tissue_and_metabolic_twin as raw_l4  # noqa: E402

        orig_solve_cb = raw_l4._solve_3d_oxygen_strict_iip_0019
        orig_fv_cb = raw_l4._compute_exact_fv_interface_stats_iip_0019

        # 1. Raw native BEFORE (NO _FVM_SOLVER_LOCK)
        raw_before = float(
            raw_l4.compute_design_z_140um_parameterized_case(**r2_native_kw)["fv_harmonic_face_min_unrounded_mmhg"]
        )
        # 2. Serial modified NW-08 baseline (~13.1032 mmHg, FAIL)
        nw08_serial = dispatch_and_solve_nw08_measured_ocr(
            "R2_DZ40",
            10.0,
            0.0,
            openislet_root=resolved_root,
            p_bed_mmhg=40.0,
            baseline_vasc_ocr_mult=5.0,
            always_solve_3d=True,
        )
        nw08_serial_val = float(nw08_serial["face_min_mmhg_unrounded"])

        # 3. Concurrent execution: background thread runs 3 consecutive NW-08 solves while main thread
        #    calls raw native Layer-4 directly WITHOUT acquiring _FVM_SOLVER_LOCK.
        nw08_started = threading.Event()
        nw08_done = threading.Event()

        def _bg_nw08_runner() -> List[Tuple[float, str]]:
            out_list: List[Tuple[float, str]] = []
            nw08_started.set()
            try:
                for _ in range(3):
                    res_bg = dispatch_and_solve_nw08_measured_ocr(
                        "R2_DZ40",
                        10.0,
                        0.0,
                        openislet_root=resolved_root,
                        p_bed_mmhg=40.0,
                        baseline_vasc_ocr_mult=5.0,
                        always_solve_3d=True,
                    )
                    out_list.append((float(res_bg["face_min_mmhg_unrounded"]), str(res_bg["adjudicated_verdict"])))
            finally:
                nw08_done.set()
            return out_list

        raw_during_vals: List[float] = []
        callbacks_untouched = True
        with ThreadPoolExecutor(max_workers=1) as pool_b1:
            fut_nw08 = pool_b1.submit(_bg_nw08_runner)
            nw08_started.wait(timeout=10.0)
            for iter_idx in range(8):
                if (
                    raw_l4._solve_3d_oxygen_strict_iip_0019 is not orig_solve_cb
                    or raw_l4._compute_exact_fv_interface_stats_iip_0019 is not orig_fv_cb
                ):
                    callbacks_untouched = False
                v_during = float(
                    raw_l4.compute_design_z_140um_parameterized_case(**r2_native_kw)[
                        "fv_harmonic_face_min_unrounded_mmhg"
                    ]
                )
                raw_during_vals.append(v_during)
                if (
                    raw_l4._solve_3d_oxygen_strict_iip_0019 is not orig_solve_cb
                    or raw_l4._compute_exact_fv_interface_stats_iip_0019 is not orig_fv_cb
                ):
                    callbacks_untouched = False
                if iter_idx >= 1 and nw08_done.is_set():
                    break
            nw08_conc_results = fut_nw08.result()

        # 4. Raw native AFTER (NO _FVM_SOLVER_LOCK)
        raw_after = float(
            raw_l4.compute_design_z_140um_parameterized_case(**r2_native_kw)["fv_harmonic_face_min_unrounded_mmhg"]
        )
        if (
            raw_l4._solve_3d_oxygen_strict_iip_0019 is not orig_solve_cb
            or raw_l4._compute_exact_fv_interface_stats_iip_0019 is not orig_fv_cb
        ):
            callbacks_untouched = False
    finally:
        if added and scripts_str in sys.path:
            sys.path.remove(scripts_str)

    raw_during_bit_exact = bool(len(raw_during_vals) >= 1 and all(v == raw_before for v in raw_during_vals))
    nw08_conc_bit_exact = bool(
        len(nw08_conc_results) == 3
        and all(v == nw08_serial_val and verd == "FAIL" for v, verd in nw08_conc_results)
    )
    ok_32 = bool(
        abs(raw_before - 24.0468) < 0.001
        and abs(nw08_serial_val - 13.1032) < 0.001
        and nw08_serial.get("adjudicated_verdict") == "FAIL"
        and nw08_serial.get("solver_isolation_mode") == "ISOLATED_CHILD_SUBPROCESS"
        and raw_before == raw_after
        and raw_during_bit_exact
        and nw08_conc_bit_exact
        and callbacks_untouched
    )
    return {
        "test": "r18_b1_concurrent_raw_native_layer4_and_nw08_bit_for_bit_isolation",
        "raw_native_before_mmhg": raw_before,
        "raw_native_after_mmhg": raw_after,
        "raw_native_during_matches_before_bit_for_bit": raw_during_bit_exact,
        "nw08_modified_serial_mmhg": nw08_serial_val,
        "nw08_concurrent_matches_serial_bit_for_bit": nw08_conc_bit_exact,
        "raw_native_callbacks_untouched_throughout": callbacks_untouched,
        "passed": ok_32,
    }


def _run_r18_b2_cross_root_sequential_isolation_test(openislet_root: Path) -> Dict[str, Any]:
    """
    R18-B2: Verify that sequential `dispatch_and_solve_nw08_measured_ocr` calls targeting two
    distinct repo copies (`copy_A` then `copy_B`) execute strictly from the requested copy's
    `scripts/` tree across R2, R3P, and R1 (reporting exact `resolved_solver_module_origins`
    under `copy_A` on call 1 and under `copy_B` on call 2, never reusing `copy_A` or parent
    `sys.modules`), while failing closed if a solver script symlinks outside `repo_root`, and
    emitting ZERO absolute host paths into the portable receipt dict.
    """
    resolved_src = Path(openislet_root).resolve()
    required_scripts = (
        "run_layer4_tissue_and_metabolic_twin.py",
        "verify_iip0033_bilayer_and_resp1.py",
        "verify_iip0034_planar_and_portfolio.py",
        "rank_islet1_stacks.py",
        "product_contract.py",
        "engineering_priors.py",
        "public_excerpt_policy.py",
    )
    required_jsons = (
        "iip0033_bilayer_and_respirometry_verification_v0.8.0.json",
        "iip0034_planar_and_portfolio_verification_v0.8.0.json",
        "layer4_tissue_and_metabolic_twin_atlas.json",
    )
    route_cases: Tuple[Tuple[str, float, float, Tuple[str, ...]], ...] = (
        ("R2_DZ40", 1.3164, 0.0, ("run_layer4_tissue_and_metabolic_twin",)),
        (
            "R3P_35",
            1.3164,
            0.0,
            (
                "run_layer4_tissue_and_metabolic_twin",
                "verify_iip0034_planar_and_portfolio",
                "rank_islet1_stacks",
                "product_contract",
            ),
        ),
        (
            "R1_390_nominal",
            1.097,
            0.0,
            (
                "run_layer4_tissue_and_metabolic_twin",
                "verify_iip0033_bilayer_and_resp1",
                "rank_islet1_stacks",
            ),
        ),
    )

    def _populate_minimal_copy(dst_root: Path) -> None:
        (dst_root / "scripts").mkdir(parents=True, exist_ok=True)
        (dst_root / "data" / "extracted").mkdir(parents=True, exist_ok=True)
        for fn in required_scripts:
            shutil.copy2(resolved_src / "scripts" / fn, dst_root / "scripts" / fn)
        for jn in required_jsons:
            shutil.copy2(resolved_src / "data" / "extracted" / jn, dst_root / "data" / "extracted" / jn)

    def _purge_temp_caches(roots_to_purge: Tuple[Path, ...]) -> None:
        purge_strs = {str(p.resolve()) for p in roots_to_purge}
        with _FVM_SOLVER_LOCK: