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…

        pf = part_c.get("protected_files")
        if isinstance(pf, dict):
            for redacted_rel in PUBLIC_BUNDLE_REDACTED_FILES_SHA256:
                entry = pf.get(redacted_rel)
                if isinstance(entry, dict) and entry.get("matches") is True:
                    # Only normalize if the digest is one of the two exact known pins (private or public-redacted)
                    valid_pair = {
                        IIP0035_17_PROTECTED_FILES_SHA256[redacted_rel],
                        PUBLIC_BUNDLE_REDACTED_FILES_SHA256[redacted_rel],
                    }
                    if entry.get("expected_sha256") in valid_pair and entry.get("actual_sha256") in valid_pair:
                        entry["category"] = "mode_verified_redacted_study_pin"
                        entry["expected_sha256"] = "<mode_verified_pin>"
                        entry["actual_sha256"] = "<mode_verified_pin>"
    return proj


def evaluate_wholegraft_gate0v_lot_file(
    lot_json_path: Path | str,
    *,
    trusted_qualification_store: Path | str | None = None,
    openislet_root: Path | None = None,
) -> Tuple[Dict[str, Any], int]:
    """
    R09-B1 + R10-B2 + R11-B4 Fail-closed standalone file intake boundary using `strict_json_load_file`:
    rejects missing files, nesting depth > MAX_JSON_NESTING_DEPTH (64), parser RecursionError,
    duplicate JSON object keys (at any nesting depth), non-standard NaN/Infinity constants,
    out-of-range integers, and syntax/type errors with structured HOLD (exit 2, release_authorizing=False).
    """
    lp = Path(lot_json_path)
    if not lp.is_file():
        return (
            {
                "verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
                "release_authorizing": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "hard_stops": [],
                "holds": [f"HOLD_GATE0V_LOT_FILE_NOT_FOUND:{lp.name}"],
            },
            2,
        )
    try:
        lot_payload = strict_json_load_file(lp, 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_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:{exc.reason_code}",
            f"HOLD_GATE0V_MALFORMED_LOT_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 (
            {
                "verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
                "release_authorizing": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "hard_stops": [],
                "holds": strict_holds,
            },
            2,
        )
    except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError, RecursionError) as exc:
        err_holds = ["HOLD_INVALID_INPUT_JSON", f"HOLD_GATE0V_MALFORMED_LOT_JSON:{type(exc).__name__}"]
        if isinstance(exc, RecursionError):
            err_holds.insert(1, "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED")
        return (
            {
                "verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
                "release_authorizing": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "hard_stops": [],
                "holds": err_holds,
            },
            2,
        )
    res = evaluate_wholegraft_gate0v_and_stress_ap1903(
        lot_payload,
        trusted_qualification_store=trusted_qualification_store,
        openislet_root=openislet_root,
    )
    if res["verdict"] in GATE0V_ALL_PASS_VERDICTS:
        return res, 0
    if res["verdict"] == "FAIL_HARD_STOP":
        return res, 3
    return res, 2


_NW08_OCR_BINDING_REQUIRED_KEYS: Tuple[str, ...] = (
    "lot_id",
    "mcb_id",
    "product_variant_id",
    "lot_payload_sha256",
    "measurement_record_id",
    "measurement_evidence_sha256",
    "measurement_timestamp_utc",
    "ocr_record_sha256",
)

_NW08_OCR_ALLOWED_KEYS = frozenset({
    "route_id",
    "measured_ocr",
    "uncertainty_se",
    "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",
    *_NW08_OCR_BINDING_REQUIRED_KEYS,
})


def evaluate_nw08_measured_ocr_record(
    req: Any,
    *,
    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]:
    """
    R10-B1 + R11-B1 + R11-B2 + R11-B4 Core in-memory & file-shared NW-08 measured-OCR evaluator:
      - In coupled composite release mode (`coupled_lot_binding is not None`), enforces cryptographic
        and structural binding to the lot and optional/required external QA store BEFORE dispatching
        the live 3D FVM solver.
      - In standalone unbound diagnostic mode (`coupled_lot_binding is None`), ALWAYS forces
        `release_authorizing = False` at top-level and recursively across all nested sub-dicts,
        recording floor clearance strictly in `solver_cleared_oxygen_floor_diagnostic`.
    """
    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], binding_meta: Dict[str, Any] | None = None) -> Tuple[Dict[str, Any], int]:
        out: Dict[str, Any] = {
            "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,
        }
        if binding_meta is not None:
            out["nw08_lot_binding"] = binding_meta
        return out, 2

    if not isinstance(req, dict):
        return _hold(["HOLD_NW08_OCR_PAYLOAD_NOT_OBJECT"])
    extra_keys = sorted(set(req.keys()) - _NW08_OCR_ALLOWED_KEYS)
    if extra_keys:
        return _hold([f"HOLD_NW08_OCR_UNRECOGNIZED_KEYS:{','.join(extra_keys)}"])
    for rk in ("route_id", "measured_ocr", "uncertainty_se"):
        if rk not in req:
            return _hold([f"HOLD_NW08_OCR_MISSING_REQUIRED_KEY:{rk}"])
    if not isinstance(req["route_id"], str) or not req["route_id"].strip():
        return _hold(["HOLD_NW08_OCR_INVALID_ROUTE_ID_TYPE"])
    if "always_solve_3d" in req and not isinstance(req["always_solve_3d"], bool):
        return _hold(["HOLD_NW08_OCR_INVALID_ALWAYS_SOLVE_3D_TYPE"])
    if "force_mesh_convergence_check" in req and not isinstance(req["force_mesh_convergence_check"], bool):
        return _hold(["HOLD_NW08_OCR_INVALID_FORCE_MESH_CONVERGENCE_CHECK_TYPE"])

    resolved_root = openislet_root.resolve() if openislet_root is not None else _resolve_roots(None, None)[0]

    # Validate self-digest and any optional binding fields even in standalone mode whenever supplied
    standalone_binding_holds: List[str] = []
    if "ocr_record_sha256" in req:
        recomp_self = _safe_nw08_ocr_record_sha256(req)
        if not (_is_valid_sha256_hex(req.get("ocr_record_sha256")) and recomp_self == req.get("ocr_record_sha256")):
            standalone_binding_holds.append("HOLD_NW08_OCR_RECORD_SHA256_MISMATCH")
    if "measurement_evidence_sha256" in req and not _is_valid_sha256_hex(req.get("measurement_evidence_sha256")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_MEASUREMENT_EVIDENCE_SHA256")
    if "lot_payload_sha256" in req and not _is_valid_sha256_hex(req.get("lot_payload_sha256")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_LOT_PAYLOAD_SHA256")
    if "measurement_record_id" in req and not _is_valid_identifier(req.get("measurement_record_id")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_MEASUREMENT_RECORD_ID")
    if "measurement_timestamp_utc" in req and _parse_strict_utc_timestamp(req.get("measurement_timestamp_utc")) is None:
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_MEASUREMENT_TIMESTAMP_UTC")
    if "lot_id" in req and not _is_valid_identifier(req.get("lot_id")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_LOT_ID")
    if "mcb_id" in req and not _is_valid_identifier(req.get("mcb_id")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_MCB_ID")
    if "product_variant_id" in req:
        pvid_chk = req.get("product_variant_id")
        if not _is_clean_nonempty_str(pvid_chk) or resolve_canonical_product_variant(pvid_chk, openislet_root=resolved_root) is None:
            standalone_binding_holds.append("HOLD_NW08_COUPLED_UNREGISTERED_PRODUCT_VARIANT_ID")

    nw08_lot_binding_meta: Dict[str, Any] = {
        "binding_mode": binding_mode,
        "binding_verified": False,
        "external_ocr_store_verification": None,
    }

    if is_coupled:
        bind_holds: List[str] = list(standalone_binding_holds)

        def _add_bh(tok: str) -> None:
            if tok not in bind_holds:
                bind_holds.append(tok)

        if not isinstance(coupled_lot_binding, dict):
            _add_bh("HOLD_NW08_COUPLED_INVALID_LOT_BINDING_CONTEXT")
            return _hold(bind_holds, nw08_lot_binding_meta)

        exp_lot_id = coupled_lot_binding.get("lot_id")
        exp_mcb_id = coupled_lot_binding.get("mcb_id")
        exp_pvid = coupled_lot_binding.get("canonical_product_variant_id")
        exp_lot_sha = coupled_lot_binding.get("computed_payload_sha256")
        exp_lot_sha_ok = bool(coupled_lot_binding.get("payload_sha256_verified") is True and _is_valid_sha256_hex(exp_lot_sha))
        exp_route = coupled_lot_binding.get("planned_nw08_route_id")
        exp_route_errs = list(coupled_lot_binding.get("planned_nw08_route_errors") or [])
        exp_ev_sha = coupled_lot_binding.get("planned_nw08_measurement_evidence_sha256")
        exp_not_before = coupled_lot_binding.get("planned_nw08_measurement_not_before_utc")
        req_trusted_ocr = bool(coupled_lot_binding.get("require_trusted_nw08_ocr_record") is True)

        for re_tok in exp_route_errs:
            _add_bh(str(re_tok))
        if not exp_route_errs:
            if not _is_clean_nonempty_str(exp_route):
                _add_bh("HOLD_NW08_COUPLED_LOT_MISSING_PLANNED_ROUTE")
            elif exp_route not in CANONICAL_NW08_ROUTE_IDS:
                _add_bh("HOLD_NW08_COUPLED_INVALID_LOT_PLANNED_ROUTE")
        if not exp_lot_sha_ok:
            _add_bh("HOLD_NW08_COUPLED_LOT_PAYLOAD_SHA256_UNVERIFIED")
        if not _is_valid_identifier(exp_lot_id):
            _add_bh("HOLD_NW08_COUPLED_LOT_MISSING_VALID_LOT_ID")
        if not _is_valid_identifier(exp_mcb_id):
            _add_bh("HOLD_NW08_COUPLED_LOT_MISSING_VALID_MCB_ID")
        if not _is_clean_nonempty_str(exp_pvid):
            _add_bh("HOLD_NW08_COUPLED_LOT_MISSING_CANONICAL_PRODUCT_VARIANT_ID")

        for bk in _NW08_OCR_BINDING_REQUIRED_KEYS:
            if bk not in req:
                _add_bh(f"HOLD_NW08_COUPLED_MISSING_REQUIRED_BINDING_KEY:{bk}")

        if "lot_id" in req and _is_valid_identifier(exp_lot_id) and req.get("lot_id") != exp_lot_id:
            _add_bh("HOLD_NW08_COUPLED_LOT_ID_MISMATCH")
        if "mcb_id" in req and _is_valid_identifier(exp_mcb_id) and req.get("mcb_id") != exp_mcb_id:
            _add_bh("HOLD_NW08_COUPLED_MCB_ID_MISMATCH")
        if "product_variant_id" in req and _is_clean_nonempty_str(exp_pvid):