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…

            if not _is_clean_nonempty_str(req.get("product_variant_id")) or req.get("product_variant_id") != exp_pvid:
                _add_bh("HOLD_NW08_COUPLED_PRODUCT_VARIANT_ID_MISMATCH")
        if _is_clean_nonempty_str(exp_route) and exp_route in CANONICAL_NW08_ROUTE_IDS and req.get("route_id") != exp_route:
            _add_bh("HOLD_NW08_COUPLED_ROUTE_ID_MISMATCH")
        if "lot_payload_sha256" in req and exp_lot_sha_ok and req.get("lot_payload_sha256") != exp_lot_sha:
            _add_bh("HOLD_NW08_COUPLED_STALE_OR_MISMATCHED_LOT_PAYLOAD_SHA256")
        if (
            exp_ev_sha is not None
            and _is_valid_sha256_hex(exp_ev_sha)
            and "measurement_evidence_sha256" in req
            and req.get("measurement_evidence_sha256") != exp_ev_sha
        ):
            _add_bh("HOLD_NW08_COUPLED_MEASUREMENT_EVIDENCE_SHA256_MISMATCH")
        if exp_not_before is not None and "measurement_timestamp_utc" in req:
            nb_dt = _parse_strict_utc_timestamp(exp_not_before)
            meas_dt = _parse_strict_utc_timestamp(req.get("measurement_timestamp_utc"))
            if nb_dt is not None and meas_dt is not None and meas_dt < nb_dt:
                _add_bh("HOLD_NW08_COUPLED_STALE_MEASUREMENT_TIMESTAMP_UTC")

        store_ok, store_errs, store_meta = resolve_and_verify_trusted_nw08_ocr_record(
            trusted_qualification_store,
            expected_ocr_record_sha256=req.get("ocr_record_sha256"),
            submitted_ocr_record=req,
            require_store_entry=req_trusted_ocr,
        )
        for se_tok in store_errs:
            _add_bh(se_tok)

        nw08_lot_binding_meta = {
            "binding_mode": binding_mode,
            "binding_verified": bool(len(bind_holds) == 0 and store_ok),
            "expected_lot_id": exp_lot_id if isinstance(exp_lot_id, str) else None,
            "supplied_lot_id": req.get("lot_id") if isinstance(req.get("lot_id"), str) else None,
            "expected_mcb_id": exp_mcb_id if isinstance(exp_mcb_id, str) else None,
            "supplied_mcb_id": req.get("mcb_id") if isinstance(req.get("mcb_id"), str) else None,
            "expected_product_variant_id": exp_pvid if isinstance(exp_pvid, str) else None,
            "supplied_product_variant_id": req.get("product_variant_id") if isinstance(req.get("product_variant_id"), str) else None,
            "expected_planned_route_id": exp_route if isinstance(exp_route, str) else None,
            "supplied_route_id": req.get("route_id") if isinstance(req.get("route_id"), str) else None,
            "expected_lot_payload_sha256": exp_lot_sha if isinstance(exp_lot_sha, str) else None,
            "supplied_lot_payload_sha256": req.get("lot_payload_sha256") if isinstance(req.get("lot_payload_sha256"), str) else None,
            "measurement_record_id": req.get("measurement_record_id") if isinstance(req.get("measurement_record_id"), str) else None,
            "measurement_evidence_sha256": req.get("measurement_evidence_sha256") if isinstance(req.get("measurement_evidence_sha256"), str) else None,
            "measurement_timestamp_utc": req.get("measurement_timestamp_utc") if isinstance(req.get("measurement_timestamp_utc"), str) else None,
            "ocr_record_sha256": req.get("ocr_record_sha256") if isinstance(req.get("ocr_record_sha256"), str) else None,
            "external_ocr_store_verification": store_meta,
        }
        if bind_holds or not store_ok:
            return _hold(bind_holds, nw08_lot_binding_meta)
    elif standalone_binding_holds:
        return _hold(standalone_binding_holds, nw08_lot_binding_meta)

    try:
        kwargs: Dict[str, Any] = {
            "openislet_root": resolved_root,
            "_require_explicit_model_for_positive_se": True,
        }
        for opt_k in (
            "baseline_min_face_mmhg",
            "baseline_vasc_ocr_mult",
            "p_bed_mmhg",
            "local_3d_slope_mmhg_per_pct",
            "z_one_sided_95",
            "floor_mmhg",
            "always_solve_3d",
            "ocr_uncertainty_model",
            "ocr_replicates_n",
            "ocr_degrees_of_freedom",
            "ocr_uncertainty_provenance",
            "measured_ocr_u95_override",
            "force_mesh_convergence_check",
        ):
            if opt_k in req and req[opt_k] is not None:
                kwargs[opt_k] = req[opt_k]
        res = dispatch_and_solve_nw08_measured_ocr(
            req["route_id"],
            req["measured_ocr"],
            req["uncertainty_se"],
            **kwargs,
        )
    except (TypeError, ValueError, OverflowError, RuntimeError, RecursionError) as exc:
        exc_msg = str(exc)
        err_holds: List[str] = []
        if "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in exc_msg:
            err_holds.append("INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE")
        if "NONZERO_FLOAT_UNDERFLOW_REJECTED" in exc_msg:
            err_holds.append("NONZERO_FLOAT_UNDERFLOW_REJECTED")
        if ":" in exc_msg:
            lead_tok = exc_msg.split(":", 1)[0].strip()
            if lead_tok.startswith("HOLD_NW08_") and lead_tok not in err_holds:
                err_holds.append(lead_tok)
        err_holds.append(f"HOLD_NW08_OCR_INVALID_PARAMETERS:{type(exc).__name__}:{exc_msg}")
        return _hold(err_holds, nw08_lot_binding_meta)

    verdict_str = str(res.get("adjudicated_verdict") or "HOLD")
    cleared_floor = bool(verdict_str == "PASS" and res.get("passes_15mmhg_floor_unrounded") is True)
    res["binding_mode"] = binding_mode
    res["lot_binding_verified"] = bool(is_coupled)
    res["nw08_lot_binding"] = nw08_lot_binding_meta
    res["solver_cleared_oxygen_floor_diagnostic"] = cleared_floor
    res["qualification_scope"] = QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
    res["physical_qualification_complete"] = False
    # R11-B2: Standalone unbound diagnostic output MUST NEVER carry `release_authorizing = True`
    # (at top-level OR inside any nested sub-dict!). Even in coupled mode, clinical release
    # authorization belongs strictly to the composite release wrapper (`evaluate_composite_clinical_release`),
    # while this component reports `nw08_component_cleared_for_coupled_lot`.
    res["release_authorizing"] = False
    if is_coupled:
        res["nw08_component_cleared_for_coupled_lot"] = cleared_floor
    else:
        _enforce_release_authorizing_false_iterative(res)
    if verdict_str == "PASS":
        rc = 0
    elif verdict_str == "FAIL":
        rc = 3
    else:
        rc = 2
    return res, rc


def evaluate_nw08_measured_ocr_file(
    ocr_json_path: Path | str,
    *,
    openislet_root: Path | None = None,
    coupled_lot_binding: Dict[str, Any] | None = None,
    trusted_qualification_store: Path | str | None = None,
) -> Tuple[Dict[str, Any], int]:
    """
    R09-M1 + R09-B1 + R10-B1 + R10-B2 + R11-B2 + R11-B4 Explicit operator file/CLI entry point for
    `dispatch_and_solve_nw08_measured_ocr`:
      - Decodes the measured-OCR request strictly via `strict_json_load_file` (enforcing bounded
        nesting depth `MAX_JSON_NESTING_DEPTH = 64`, mapping `RecursionError`, duplicate keys,
        NaN/Infinity constants, overflowing floats like 1e500, and out-of-float64-range integers
        like 10**400 to structured exit-2 HOLD with `release_authorizing = False`).
      - Delegates validation, binding, and dispatch to `evaluate_nw08_measured_ocr_record(...)`.
    """
    is_coupled = coupled_lot_binding is not None
    binding_mode = "COUPLED_COMPOSITE_LOT_BOUND" if is_coupled else "STANDALONE_UNBOUND_DIAGNOSTIC_ONLY"

    def _hold(holds_list: List[str]) -> Tuple[Dict[str, Any], int]:
        return (
            {
                "adjudicated_verdict": "HOLD",
                "release_authorizing": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "solver_cleared_oxygen_floor_diagnostic": False,
                "solver_executed": False,
                "binding_mode": binding_mode,
                "lot_binding_verified": False,
                "holds": holds_list,
            },
            2,
        )

    op = Path(ocr_json_path)
    if not op.is_file():
        return _hold([f"HOLD_NW08_OCR_FILE_NOT_FOUND:{op.name}"])
    try:
        req = strict_json_load_file(op, max_int_abs=MAX_STRICT_JSON_INT_ABS, max_depth=MAX_JSON_NESTING_DEPTH)
    except StrictJSONDecodeError as exc:
        strict_holds = [
            "HOLD_INVALID_INPUT_JSON",
            f"HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:{exc.reason_code}",
            f"HOLD_NW08_MALFORMED_OCR_JSON:{type(exc).__name__}",
        ]
        if exc.reason_code in ("INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE", "NONZERO_FLOAT_UNDERFLOW_REJECTED"):
            strict_holds.append(exc.reason_code)
        return _hold(strict_holds)
    except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError, RecursionError) as exc:
        err_holds = ["HOLD_INVALID_INPUT_JSON", f"HOLD_NW08_MALFORMED_OCR_JSON:{type(exc).__name__}"]
        if isinstance(exc, RecursionError):
            err_holds.insert(1, "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED")
        return _hold(err_holds)

    return evaluate_nw08_measured_ocr_record(
        req,
        openislet_root=openislet_root,
        coupled_lot_binding=coupled_lot_binding,
        trusted_qualification_store=trusted_qualification_store,
    )


def main() -> int:
    parser = argparse.ArgumentParser(
        description="EXP-031 Round-02 hardened 80-digit outward Taylor Gate 0V, 3D FVM NW-08 & public-bundle portable verifier"
    )
    parser.add_argument("--out", type=Path, default=DEFAULT_RECEIPT_PATH, help="Output JSON receipt path")
    parser.add_argument("--repo-root", type=Path, default=None, help="Path to OpenIslet science repository (read-only)")
    parser.add_argument("--investigations-root", type=Path, default=None, help="Path to OpenIslet-Investigations repository")
    parser.add_argument("--protected-manifest", type=Path, default=None, help="Optional JSON manifest mapping protected relative file paths to SHA-256 hex digests")
    parser.add_argument("--evaluate-lot", type=Path, default=None, help="Evaluate a single measured-lot Gate 0V JSON payload (strict RFC-8259 JSON; fail-closed exit 0 ONLY on tier-matched PASS)")
    parser.add_argument(
        "--dispatch-nw08-ocr",
        type=Path,
        default=None,
        help=(
            "Explicit operator CLI path to dispatch_and_solve_nw08_measured_ocr: evaluate a measured-OCR "
            "JSON request (route_id, measured_ocr, uncertainty_se, optional p_bed_mmhg / baseline_vasc_ocr_mult / "
            "always_solve_3d) under strict JSON decoding and immutable 15.0 mmHg floor (exit 0 PASS, 3 FAIL, 2 HOLD)"
        ),
    )
    parser.add_argument("--trusted-qualification-store", type=Path, default=None, help="Independent external trusted qualification store (registry JSON or directory) required for LOT_RELEASE_SURROGATE / AUTOLOGOUS_D1B_PROCESS_QUAL")
    parser.add_argument("--skip-3d-fvm", action="store_true", help="Skip live 3D FVM vascular-voxel solves (default: False, runs full 3D FVM)")
    parser.add_argument("--check", action="store_true", help="Verify deterministic portable replay against pinned --out receipt without overwriting")
    args = parser.parse_args()

    openislet_root, inv_root = _resolve_roots(args.repo_root, args.investigations_root)

    # Single measured-lot evaluation mode (fail-closed structured JSON on ANY I/O, strict-JSON, or type error!)
    if args.evaluate_lot is not None:
        res, rc = evaluate_wholegraft_gate0v_lot_file(
            args.evaluate_lot,
            trusted_qualification_store=args.trusted_qualification_store,
            openislet_root=openislet_root,
        )
        print(json.dumps(res, indent=2, sort_keys=True, allow_nan=False))
        return rc

    # Explicit NW-08 measured-OCR 3D FVM solver dispatch CLI mode (R09-M1 + R09-B1)
    if args.dispatch_nw08_ocr is not None:
        ocr_res, ocr_rc = evaluate_nw08_measured_ocr_file(
            args.dispatch_nw08_ocr,
            openislet_root=openislet_root,
        )
        print(json.dumps(ocr_res, indent=2, sort_keys=True, allow_nan=False))
        return ocr_rc

    cap_persist = Decimal("0.0005")
    cap_kill_esc = Decimal("0.0001")
    alpha_1p_2way = Decimal("0.005")
    alpha_3p_2way = _alpha_3pathogen_global_floor(prec=120)

    legacy_beta_only = min_n_for_zero_event_cap(cap_persist, Decimal("0.05"), Decimal("1.0"), prec=80)
    fwer_5lin_1way = {
        f"eta_{eta}": min_n_for_zero_event_cap(cap_persist, Decimal("0.01"), Decimal(eta), prec=80)
        for eta in ("1.00", "0.90", "0.85", "0.80", "0.70")
    }
    fwer_1pathogen_5lin_2way = {
        f"eta_{eta}": min_n_for_zero_event_cap(cap_persist, alpha_1p_2way, Decimal(eta), prec=80)
        for eta in ("1.00", "0.90", "0.85", "0.80", "0.70")
    }
    fwer_3pathogen_5lin_2way = {
        f"eta_{eta}": min_n_for_zero_event_cap(cap_persist, alpha_3p_2way, Decimal(eta), prec=80)
        for eta in ("1.00", "0.90", "0.85", "0.80", "0.70")
    }

    calibrant_1p_thresholds = {}
    for rn in (23, 24, 25, 30, 50):
        eta_l = exact_clopper_pearson_lower_calibrant(rn, rn, alpha_1p_2way, prec=80)