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…

      - Composite clinical release (`legacy_evaluator is not None`): REQUIRES a complete
        composite bank archive containing BOTH `gate0v_wholegraft_payload` AND
        `legacy_stage0_observations`, validates the archived composite envelope through the EXACT
        SAME `validate_canonical_composite_envelope(...)` contract as direct composite submission
        (mandatory canonical top-level `product_variant_id`, exhaustive reconciliation of EVERY
        supplied tier field against `"BANK_QUALIFICATION"`), and requires BOTH live Gate-0V
        revalidation (`archived_bank_payload_live_g0v_revalidation_passed == True`), live legacy
        `wetlab_contract` revalidation (`archived_bank_payload_live_legacy_revalidation_passed == True`),
        and (when provided by the composite wrapper) live composite bank replay
        (`archived_bank_payload_live_composite_revalidation_passed == True`). Plain standalone
        whole-graft-only bank archives lacking archived legacy observations are REJECTED immediately
        with `HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE`.
      - Standalone `verify_iip0043` evidence boundary (`legacy_evaluator is None`): accepts
        either a complete canonical standalone Gate-0V `BANK_QUALIFICATION` payload (requiring
        canonical `product_variant_id` and reconciling any `operational_tier` against
        `"BANK_QUALIFICATION"`) OR a complete canonical composite bank bundle validated by
        `validate_canonical_composite_envelope(...)`, requiring live Gate-0V revalidation.
    """
    require_composite_legacy_replay: bool = legacy_evaluator is not None
    if _revalidating_archived_bank:
        return False, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD", f"{hold_prefix}_RECURSIVE_REVALIDATION_BARRED"], {
            "authenticated": False,
            "resolution_source": None,
            "self_attested_inline_record_ignored": inline_record_if_supplied is not None,
            "archived_bank_payload_verified": False,
            "archived_bank_payload_status": "recursive_revalidation_barred",
            "archived_bank_payload_live_revalidation_passed": False,
            "archived_bank_payload_live_g0v_revalidation_passed": False,
            "archived_bank_payload_live_legacy_revalidation_required": require_composite_legacy_replay,
            "archived_bank_payload_live_legacy_revalidation_passed": False if require_composite_legacy_replay else None,
            "archived_bank_payload_live_composite_revalidation_passed": False if composite_bank_revalidator is not None else None,
        }
    rec, archived_payload, lookup_errs, store_src, archive_status = (
        _lookup_in_trusted_qualification_store_with_archive_status(
            trusted_qualification_store,
            category="bank_qualifications",
            expected_sha256=expected_sha256,
        )
    )
    if lookup_errs or rec is None:
        return False, lookup_errs, {
            "authenticated": False,
            "resolution_source": store_src,
            "self_attested_inline_record_ignored": inline_record_if_supplied is not None,
            "archived_bank_payload_verified": False,
            "archived_bank_payload_status": archive_status,
            "archived_bank_payload_live_revalidation_passed": False,
            "archived_bank_payload_live_g0v_revalidation_passed": False,
            "archived_bank_payload_live_legacy_revalidation_required": require_composite_legacy_replay,
            "archived_bank_payload_live_legacy_revalidation_passed": False if require_composite_legacy_replay else None,
            "archived_bank_payload_live_composite_revalidation_passed": False if composite_bank_revalidator is not None else None,
        }

    errs: List[str] = []

    def _add_err(tok: str) -> None:
        if tok not in errs:
            errs.append(tok)

    rec_sha = rec.get("sha256")
    computed_sha = _safe_canonical_qualification_artifact_sha256(rec)
    if computed_sha is None or not _is_valid_sha256_hex(rec_sha) or rec_sha != computed_sha:
        _add_err(f"{hold_prefix}_RECORD_INTERNAL_SHA256_MISMATCH")
    elif rec_sha != expected_sha256:
        _add_err(f"{hold_prefix}_RECORD_SHA256_DOES_NOT_MATCH_BRIDGED_DIGEST")

    if not _is_valid_identifier(rec.get("approved_by_authority_id")):
        _add_err(f"{hold_prefix}_MISSING_APPROVED_BY_AUTHORITY_ID")
    if rec.get("operational_tier") != "BANK_QUALIFICATION":
        _add_err(f"{hold_prefix}_WRONG_OPERATIONAL_TIER")
    if "qualification_tier" in rec and rec.get("qualification_tier") != "BANK_QUALIFICATION":
        _add_err(f"{hold_prefix}_WRONG_OPERATIONAL_TIER")
    if rec.get("verdict") != "PASS_COMPOSITE_BANK_QUALIFICATION":
        _add_err(f"{hold_prefix}_VERDICT_NOT_PASS_COMPOSITE_BANK_QUALIFICATION")
    if rec.get("mcb_id") != expected_mcb_id:
        _add_err(f"{hold_prefix}_MCB_ID_MISMATCH")

    rec_pvid_raw = rec.get("product_variant_id")
    if not _is_clean_nonempty_str(rec_pvid_raw):
        _add_err(f"{hold_prefix}_MISSING_RECORD_PRODUCT_VARIANT_ID")
    rec_pvid_res = (
        resolve_canonical_product_variant(rec_pvid_raw, openislet_root=openislet_root)
        if _is_clean_nonempty_str(rec_pvid_raw)
        else None
    )
    rec_pvid_canon = rec_pvid_res["product_variant_id"] if rec_pvid_res is not None else rec_pvid_raw
    if rec_pvid_canon != expected_product_variant_id:
        _add_err(f"{hold_prefix}_PRODUCT_VARIANT_ID_MISMATCH")
    if "product_variant" in rec and rec.get("product_variant") is not None:
        rpv_res = resolve_canonical_product_variant(rec.get("product_variant"), openislet_root=openislet_root)
        if rpv_res is None or rpv_res["product_variant_id"] != expected_product_variant_id:
            _add_err(f"{hold_prefix}_PRODUCT_VARIANT_ID_MISMATCH")

    # R04-B1: Bank qualification & LOT_RELEASE_SURROGATE require an allogeneic MCB-banked product family!
    exp_pvid_res = resolve_canonical_product_variant(expected_product_variant_id, openislet_root=openislet_root)
    if rec_pvid_res is None:
        errs.append(f"{hold_prefix}_UNREGISTERED_RECORD_PRODUCT_VARIANT_ID")
    else:
        tier_ok_rec, tier_errs_rec = is_qualification_tier_allowed_for_product(rec_pvid_res, "BANK_QUALIFICATION")
        if not tier_ok_rec:
            errs.extend(tier_errs_rec)
    if exp_pvid_res is not None:
        tier_ok_exp, tier_errs_exp = is_qualification_tier_allowed_for_product(exp_pvid_res, "LOT_RELEASE_SURROGATE")
        if not tier_ok_exp:
            for te in tier_errs_exp:
                if te not in errs:
                    errs.append(te)

    # Verify underlying dual-evaluator PASS outcomes recorded in the trusted bank approval!
    if rec.get("legacy_tier") != "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE":
        errs.append(f"{hold_prefix}_UNDERLYING_LEGACY_TIER_NOT_READY")
    if rec.get("legacy_evaluator_passed") is not True or rec.get("legacy_safety_kill_s9_triggered") is not False:
        errs.append(f"{hold_prefix}_UNDERLYING_LEGACY_EVALUATOR_NOT_PASSED")
    if rec.get("gate0v_verdict") != "PASS_WHOLEGRAFT_BANK_QUALIFICATION":
        errs.append(f"{hold_prefix}_UNDERLYING_GATE0V_VERDICT_NOT_PASS_BANK")
    if rec.get("gate0v_evaluator_passed") is not True:
        errs.append(f"{hold_prefix}_UNDERLYING_GATE0V_EVALUATOR_NOT_PASSED")
    if rec.get("gate0v_hard_stops_count") != 0 or rec.get("gate0v_holds_count") != 0:
        errs.append(f"{hold_prefix}_UNDERLYING_GATE0V_NONZERO_STOPS_OR_HOLDS")
    if not _is_valid_sha256_hex(rec.get("bank_payload_sha256")) or not _is_valid_identifier(rec.get("bank_lot_id")):
        errs.append(f"{hold_prefix}_MISSING_BANK_PAYLOAD_DIGEST_OR_LOT_ID")

    rec_req_ocr = False
    if "require_trusted_nw08_ocr_record" in rec:
        if not _is_strict_bool(rec.get("require_trusted_nw08_ocr_record")):
            _add_err("HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG")
            _add_err(f"{hold_prefix}_INVALID_REQUIRE_TRUSTED_OCR_FLAG")
        else:
            rec_req_ocr = bool(rec.get("require_trusted_nw08_ocr_record"))

    # R04-B2: antiviral_genotype_stratum is MANDATORY (recognized canonical stratum) on EVERY
    # bank qualification record AND strictly bound to BOTH current lot AND archived bank payload!
    rec_geno = rec.get("antiviral_genotype_stratum")
    rec_geno_valid = isinstance(rec_geno, str) and rec_geno in ALLOWED_ANTIVIRAL_GENOTYPES
    exp_geno_valid = isinstance(expected_genotype_stratum, str) and expected_genotype_stratum in ALLOWED_ANTIVIRAL_GENOTYPES
    if not rec_geno_valid:
        errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
        errs.append(f"{hold_prefix}_MISSING_OR_UNRECOGNIZED_BANK_GENOTYPE_STRATUM")
    elif rec_pvid_res is not None:
        rec_tyk2_cls = rec_pvid_res.get("tyk2_product_genotype_class")
        if rec_tyk2_cls == "TYK2_PE_P1104A" and rec_geno not in ("TYK2_P1104A_HOM__IFIH1_WT", "TYK2_P1104A_HET__IFIH1_WT"):
            errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
            errs.append(f"{hold_prefix}_BANK_GENOTYPE_CONFLICTS_WITH_PRODUCT_DEFINITION")
        elif rec_tyk2_cls == "TYK2_KO_PROPOSED":
            errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
            errs.append(f"{hold_prefix}_BANK_TYK2_KO_UNQUALIFIED")

    if not exp_geno_valid:
        if "HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM" not in errs:
            errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
        errs.append(f"{hold_prefix}_MISSING_OR_UNRECOGNIZED_CURRENT_LOT_GENOTYPE_STRATUM")
    elif rec_geno_valid and rec_geno != expected_genotype_stratum:
        if "HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM" not in errs:
            errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
        errs.append(f"{hold_prefix}_GENOTYPE_STRATUM_MISMATCH")

    # R05-B1 + R06-B4 + R07-B1 + R08-B1: Verified original archived BANK_QUALIFICATION payload is MANDATORY
    # in BOTH external trusted-store layouts (embedded dict registry JSON AND file-backed directory
    # store), enforcing the EXACT SAME canonical composite envelope contract as direct composite
    # submission (`validate_canonical_composite_envelope`: mandatory canonical top-level
    # `product_variant_id`, exhaustive reconciliation of EVERY supplied tier field against
    # "BANK_QUALIFICATION"), plus optional live composite bank replay (`composite_bank_revalidator`),
    # rejecting metadata-only stubs, tampered internal self-digests, conflicting tier/envelope fields,
    # alias-only envelopes, nested-identity contradictions, and archives that fail live Gate-0V or
    # (in composite release mode when legacy_evaluator is provided) live legacy wetlab_contract revalidation!
    archived_verified: bool = False
    arch_geno: Any = None
    arch_format: str = "absent_or_non_object"
    arch_self_digest_ok: bool = False
    arch_nested_ok: bool = False
    arch_envelope_ok: bool = False
    arch_reval_verdict: str | None = None
    live_reval_ok: bool = False
    arch_leg_reval_ok: bool | None = False if require_composite_legacy_replay else None
    arch_comp_reval_ok: bool | None = False if composite_bank_revalidator is not None else None
    arch_fail_reasons: List[str] = []

    if not isinstance(archived_payload, dict):
        _add_err("HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD")
        _add_err(f"{hold_prefix}_ARCHIVED_BANK_PAYLOAD_{archive_status.upper().replace(':', '_')}")
        arch_fail_reasons.append(f"archive_status:{archive_status}")
    else:
        arch_sha = _safe_canonical_lot_sha256(archived_payload)
        arch_supplied_sha = archived_payload.get("payload_sha256")
        arch_self_digest_ok = bool(
            arch_sha is not None
            and _is_valid_sha256_hex(arch_supplied_sha)
            and arch_supplied_sha == arch_sha
            and arch_sha == rec.get("bank_payload_sha256")
        )
        if not arch_self_digest_ok:
            arch_fail_reasons.append("top_level_payload_sha256_missing_or_mismatch")
            _add_err(f"{hold_prefix}_ARCHIVED_PAYLOAD_SELF_DIGEST_MISMATCH")

        # R08-B1: NEVER fall back to alias-only `product_variant`! Require canonical `product_variant_id`!
        arch_pvid_raw = archived_payload.get("product_variant_id")
        arch_pvid_present = _is_clean_nonempty_str(arch_pvid_raw)
        arch_pvid_res = (
            resolve_canonical_product_variant(arch_pvid_raw, openislet_root=openislet_root)
            if arch_pvid_present
            else None
        )
        arch_pvid_canon = arch_pvid_res["product_variant_id"] if arch_pvid_res is not None else None
        top_alias_ok = True
        if archived_payload.get("product_variant") is not None:
            top_pv_res = resolve_canonical_product_variant(archived_payload.get("product_variant"), openislet_root=openislet_root)
            top_alias_ok = bool(top_pv_res is not None and top_pv_res["product_variant_id"] == expected_product_variant_id)

        top_identity_ok = bool(
            archived_payload.get("mcb_id") == expected_mcb_id
            and arch_pvid_present
            and arch_pvid_canon == expected_product_variant_id
            and top_alias_ok
            and archived_payload.get("lot_id") == rec.get("bank_lot_id")
        )
        if not top_identity_ok:
            arch_fail_reasons.append("top_level_identity_mismatch")

        has_comp_leg = "legacy_stage0_observations" in archived_payload
        has_comp_g0v = "gate0v_wholegraft_payload" in archived_payload
        target_g0v_payload: Dict[str, Any] | None = None
        nested_reconcile_ok = True
        arch_envelope_ok = True

        if has_comp_leg or has_comp_g0v:
            arch_format = "composite_bank_bundle"
            # R08-B1: Enforce the EXACT SAME shared canonical composite envelope contract as direct submission!
            env_res = validate_canonical_composite_envelope(
                archived_payload,
                openislet_root=openislet_root,
                expected_tier="BANK_QUALIFICATION",
                expected_lot_id=rec.get("bank_lot_id"),
                expected_mcb_id=expected_mcb_id,
                expected_product_variant_id=expected_product_variant_id,
            )
            if not env_res["valid"]:
                arch_envelope_ok = False
                nested_reconcile_ok = False
                _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")
                for eh in env_res["holds"]:
                    _add_err(eh)
                    arch_fail_reasons.append(f"archived_composite_envelope:{eh}")

            arch_leg = archived_payload.get("legacy_stage0_observations")
            arch_g0v = archived_payload.get("gate0v_wholegraft_payload")
            if not isinstance(arch_leg, dict) or not isinstance(arch_g0v, dict):
                nested_reconcile_ok = False
                arch_fail_reasons.append("incomplete_composite_bundle_missing_legacy_or_gate0v_section")
                if require_composite_legacy_replay and not isinstance(arch_leg, dict):
                    arch_leg_reval_ok = False