OpenIslet

scripts/evaluate_gate0v_composite_release.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031) Executable Dual-Evaluator Composite Release Wrapper

script Release v0.8.0 gen-eb955f8266035aba 357 KB · 28 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/evaluate_gate0v_composite_release.py · SHA-256: 2be0252340222fe4…

        "qualification_tier_allowed_for_product_family": bool(tier_allowed_for_product),
        "canonical_product_registry_source": (
            canonical_product_def.get("registry_source") if canonical_product_def is not None else None
        ),
        "canonical_product_execution_supported": (
            canonical_product_def.get("execution_supported") if canonical_product_def is not None else None
        ),
        "supplied_payload_sha256": top_sha if isinstance(top_sha, str) else None,
        "computed_payload_sha256": computed_comp_sha,
        "payload_sha256_verified": bool(isinstance(top_sha, str) and top_sha == computed_comp_sha),
        "planned_nw08_route_id": env.get("planned_nw08_route_id"),
        "planned_nw08_route_errors": list(env.get("planned_nw08_route_errors") or []),
        "planned_nw08_measurement_evidence_sha256": env.get("planned_nw08_measurement_evidence_sha256"),
        "planned_nw08_measurement_not_before_utc": env.get("planned_nw08_measurement_not_before_utc"),
        "require_trusted_nw08_ocr_record": effective_require_trusted_ocr,
    }

    # R10-B1 + R11-B1: Enforce coupled NW-08 measured-OCR binding/dispatch when provided, AND fail
    # closed whenever `require_trusted_nw08_ocr_record = True` is declared on the lot (or trusted
    # store record) and no OCR input is supplied — across BOTH Python API and CLI!
    nw08_ocr_dispatch_res: Dict[str, Any] | None = None
    nw08_required_ocr_missing = False
    if nw08_ocr_json_path is not None and nw08_ocr_record is not None:
        if "HOLD_NW08_AMBIGUOUS_DUPLICATE_OCR_INPUTS" not in holds:
            holds.append("HOLD_NW08_AMBIGUOUS_DUPLICATE_OCR_INPUTS")
        nw08_ocr_dispatch_res = {
            "adjudicated_verdict": "HOLD",
            "release_authorizing": False,
            "solver_cleared_oxygen_floor_diagnostic": False,
            "solver_executed": False,
            "binding_mode": "COUPLED_COMPOSITE_LOT_BOUND",
            "lot_binding_verified": False,
            "holds": ["HOLD_NW08_AMBIGUOUS_DUPLICATE_OCR_INPUTS"],
        }
    elif nw08_ocr_json_path is not None:
        ocr_res, ocr_rc = v38.evaluate_nw08_measured_ocr_file(
            nw08_ocr_json_path,
            openislet_root=resolved_root,
            coupled_lot_binding=lot_binding_dict,
            trusted_qualification_store=trusted_qualification_store,
        )
        nw08_ocr_dispatch_res = ocr_res
        if ocr_rc == 3:
            if "FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR" not in hard_stops:
                hard_stops.append("FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR")
        elif ocr_rc != 0:
            for oh in (ocr_res.get("holds") or ["HOLD_NW08_MEASURED_OCR_DISPATCH_FAILED"]):
                if oh not in holds:
                    holds.append(oh)
    elif nw08_ocr_record is not None:
        ocr_res, ocr_rc = v38.evaluate_nw08_measured_ocr_record(
            nw08_ocr_record,
            openislet_root=resolved_root,
            coupled_lot_binding=lot_binding_dict,
            trusted_qualification_store=trusted_qualification_store,
        )
        nw08_ocr_dispatch_res = ocr_res
        if ocr_rc == 3:
            if "FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR" not in hard_stops:
                hard_stops.append("FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR")
        elif ocr_rc != 0:
            for oh in (ocr_res.get("holds") or ["HOLD_NW08_MEASURED_OCR_DISPATCH_FAILED"]):
                if oh not in holds:
                    holds.append(oh)
    elif effective_require_trusted_ocr and qual_tier != "BANK_QUALIFICATION":
        nw08_required_ocr_missing = True
        if "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING" not in holds:
            holds.append("HOLD_NW08_REQUIRED_OCR_RECORD_MISSING")
        nw08_ocr_dispatch_res = {
            "adjudicated_verdict": "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
            "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": "COUPLED_COMPOSITE_LOT_BOUND",
            "lot_binding_verified": False,
            "required_by_lot": True,
            "ocr_input_supplied": False,
            "holds": ["HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"],
        }

    auth_bank_record: Dict[str, Any] | None = None
    if hard_stops:
        comp_verdict = "FAIL_HARD_STOP_COMPOSITE_RELEASE"
    elif holds:
        if "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION" in holds and all(
            h in (
                "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
                "HOLD_COMPOSITE_GATE0V_NOT_PASSED:HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
            )
            for h in holds
        ):
            comp_verdict = "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION"
        elif nw08_required_ocr_missing and all(
            h in (
                "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
                "HOLD_COMPOSITE_GATE0V_NOT_PASSED:HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
            )
            for h in holds
        ):
            comp_verdict = "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"
        elif "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in holds and all(
            h == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
            or h.startswith("HOLD_GATE0V_KILL_")
            or h.startswith("HOLD_COMPOSITE_GATE0V_NOT_PASSED:HOLD_CLUSTERED_DEFF_GT_1")
            for h in holds
        ):
            comp_verdict = "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        else:
            comp_verdict = "HOLD_COMPOSITE_RELEASE"
    elif qual_tier == "BANK_QUALIFICATION":
        bank_geno = gate0v_obs.get("antiviral_genotype_stratum") if isinstance(gate0v_obs, dict) else None
        if not (isinstance(bank_geno, str) and bank_geno in v38.ALLOWED_ANTIVIRAL_GENOTYPES):
            holds.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
            comp_verdict = "HOLD_COMPOSITE_RELEASE"
        else:
            comp_verdict = "PASS_COMPOSITE_BANK_QUALIFICATION"
            auth_bank_record = v38.build_authenticated_bank_qualification_record(
                mcb_id=str(top_mcb),
                product_variant_id=str(canonical_pvid),
                bank_lot_id=str(top_lot),
                bank_payload_sha256=computed_comp_sha,
                verdict="PASS_COMPOSITE_BANK_QUALIFICATION",
                operational_tier="BANK_QUALIFICATION",
                legacy_tier=str((legacy_summary or {}).get("lot_release_readiness_tier")),
                legacy_evaluator_passed=bool((legacy_summary or {}).get("legacy_evaluator_passed")),
                legacy_safety_kill_s9_triggered=bool((legacy_summary or {}).get("safety_kill_s9_triggered")),
                gate0v_verdict=str((gate0v_summary or {}).get("verdict")),
                gate0v_evaluator_passed=bool((gate0v_summary or {}).get("gate0v_evaluator_passed")),
                gate0v_hard_stops_count=int((gate0v_summary or {}).get("hard_stops_count") or 0),
                gate0v_holds_count=int((gate0v_summary or {}).get("holds_count") or 0),
                antiviral_genotype_stratum=str(bank_geno),
            )
    elif qual_tier == "LOT_RELEASE_SURROGATE":
        if (
            prior_qual_auth.get("archived_bank_payload_verified") is not True
            or prior_qual_auth.get("archived_bank_payload_live_revalidation_passed") is not True
            or prior_qual_auth.get("archived_bank_payload_live_g0v_revalidation_passed") is not True
            or prior_qual_auth.get("archived_bank_payload_live_legacy_revalidation_passed") is not True
            or prior_qual_auth.get("archived_bank_payload_live_composite_revalidation_passed") is not True
        ):
            if (
                prior_qual_auth.get("archived_bank_payload_live_legacy_revalidation_passed") is not True
                and prior_qual_auth.get("archived_bank_payload_format")
                in ("standalone_gate0v_bank_payload_missing_legacy_for_composite_release", "canonical_gate0v_bank_payload")
                and "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE" not in holds
            ):
                holds.append("HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
            if "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" not in holds:
                holds.append("HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD")
            if "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" not in holds:
                holds.append("HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE")
            comp_verdict = "HOLD_COMPOSITE_RELEASE"
        else:
            comp_verdict = "PASS_COMPOSITE_CLINICAL_RELEASE"
    elif qual_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL":
        comp_verdict = "PASS_COMPOSITE_AUTOLOGOUS_CLINICAL_RELEASE"
    else:
        comp_verdict = "HOLD_COMPOSITE_RELEASE"

    out_doc: Dict[str, Any] = {
        "composite_verdict": comp_verdict,
        "release_authorizing": bool(comp_verdict in CLINICAL_RELEASE_PASS_VERDICTS),
        "bank_qualification_authorized": bool(comp_verdict == "PASS_COMPOSITE_BANK_QUALIFICATION"),
        "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
        "physical_qualification_complete": False,
        "operational_tier": qual_tier,
        "lot_binding": lot_binding_dict,
        "tested_vs_inherited_scope": g0v_scope,
        "prior_qualification_authentication": prior_qual_auth,
        "hard_stops": hard_stops,
        "holds": holds,
        "legacy_result_summary": legacy_summary,
        "gate0v_result_summary": gate0v_summary,
        "authenticated_bank_qualification_record": auth_bank_record,
    }
    if nw08_ocr_dispatch_res is not None:
        out_doc["nw08_measured_ocr_dispatch_result"] = nw08_ocr_dispatch_res
    return out_doc


def evaluate_composite_lot_file(
    lot_json_path: Path,
    *,
    legacy_evaluator: Callable[..., Dict[str, Any]] | None,
    gate0v_evaluator: Callable[..., Dict[str, Any]] | None,
    trusted_qualification_store: Path | str | None = None,
    openislet_root: Path | None = None,
    nw08_ocr_json_path: Path | str | None = None,
) -> Tuple[Dict[str, Any], int]:
    """
    Fail-closed CLI boundary loader: uses the single canonical strict RFC-8259 JSON decoder
    (`v38.strict_json_loads`, enforcing bounded nesting depth `MAX_JSON_NESTING_DEPTH = 64` and
    rejecting `RecursionError`, duplicate keys at any depth, NaN/Infinity constants, overflowing
    floats, signed negative zero `-0`/`-0.0`, nonzero underflow, and out-of-range integers), catches
    missing files, OSError, UnicodeDecodeError, StrictJSONDecodeError, json.JSONDecodeError,
    TypeError, ValueError, OverflowError, and RecursionError, and ALWAYS emits a structured JSON
    HOLD (exit 2, `release_authorizing = False`) — ZERO uncaught tracebacks! Delegates coupled
    `--nw08-ocr-json` and mandatory `require_trusted_nw08_ocr_record = True` enforcement directly
    into `evaluate_composite_clinical_release(...)` so CLI and Python API behave identically.
    """
    v38 = _get_v38_module()
    if not lot_json_path.is_file():
        return (
            {
                "composite_verdict": "HOLD_COMPOSITE_RELEASE",
                "release_authorizing": False,
                "bank_qualification_authorized": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "operational_tier": None,
                "hard_stops": [],
                "holds": [f"HOLD_COMPOSITE_LOT_FILE_NOT_FOUND:{lot_json_path.name}"],
                "lot_binding": None,
                "tested_vs_inherited_scope": None,
                "prior_qualification_authentication": None,
                "legacy_result_summary": None,
                "gate0v_result_summary": None,
                "authenticated_bank_qualification_record": None,
            },
            2,
        )
    try:
        raw_text = lot_json_path.read_text(encoding="utf-8")
        doc = v38.strict_json_loads(
            raw_text,
            max_int_abs=v38.MAX_STRICT_JSON_INT_ABS,
            max_depth=v38.MAX_JSON_NESTING_DEPTH,
        )
    except v38.StrictJSONDecodeError as exc:
        strict_holds = [
            "HOLD_INVALID_INPUT_JSON",
            f"HOLD_COMPOSITE_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:{exc.reason_code}",
            f"HOLD_COMPOSITE_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 (
            {
                "composite_verdict": "HOLD_COMPOSITE_RELEASE",
                "release_authorizing": False,
                "bank_qualification_authorized": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "operational_tier": None,
                "hard_stops": [],
                "holds": strict_holds,
                "lot_binding": None,
                "tested_vs_inherited_scope": None,