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…

                    _add_err("HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
                    _add_err(f"{hold_prefix}_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
            else:
                # Reconcile legacy_stage0_observations identities & non-stub observation keys
                leg_lot_vals = [
                    arch_leg.get(lk)
                    for lk in ("current_lot_id", "lot_id", "batch_id")
                    if lk in arch_leg and arch_leg.get(lk) is not None
                ]
                leg_lot_ok = bool(leg_lot_vals and all(v == rec.get("bank_lot_id") for v in leg_lot_vals))
                leg_mcb_ok = bool(arch_leg.get("mcb_id") == expected_mcb_id)
                leg_pvid_raw_a = arch_leg.get("product_variant_id")
                leg_pvid_res = (
                    resolve_canonical_product_variant(leg_pvid_raw_a, openislet_root=openislet_root)
                    if _is_clean_nonempty_str(leg_pvid_raw_a)
                    else None
                )
                leg_pvid_ok = bool(leg_pvid_res is not None and leg_pvid_res["product_variant_id"] == expected_product_variant_id)
                leg_alias_ok = True
                if arch_leg.get("product_variant") is not None:
                    la_res = resolve_canonical_product_variant(arch_leg.get("product_variant"), openislet_root=openislet_root)
                    leg_alias_ok = bool(la_res is not None and la_res["product_variant_id"] == expected_product_variant_id)
                required_leg_obs_keys = (
                    "obs_icasp9_log10_kill",
                    "obs_tp53_ppm1d_bcor_vaf",
                    "obs_mcb_effective_clonogenic_trials",
                    "obs_gate0v_day28_persistent_vp1_ie1_cells_scored",
                )
                leg_structure_ok = all(k in arch_leg and arch_leg.get(k) is not None for k in required_leg_obs_keys)
                if not (leg_lot_ok and leg_mcb_ok and leg_pvid_ok and leg_alias_ok and leg_structure_ok):
                    nested_reconcile_ok = False
                    arch_fail_reasons.append("composite_legacy_section_identity_or_structure_invalid")

                # Reconcile nested gate0v_wholegraft_payload identities & internal self-digest
                g0v_lot_ok = bool(arch_g0v.get("lot_id") == rec.get("bank_lot_id"))
                g0v_mcb_ok = bool(arch_g0v.get("mcb_id") == expected_mcb_id)
                g0v_pvid_raw_a = arch_g0v.get("product_variant_id")
                g0v_pvid_res = (
                    resolve_canonical_product_variant(g0v_pvid_raw_a, openislet_root=openislet_root)
                    if _is_clean_nonempty_str(g0v_pvid_raw_a)
                    else None
                )
                g0v_pvid_ok = bool(g0v_pvid_res is not None and g0v_pvid_res["product_variant_id"] == expected_product_variant_id)
                g0v_alias_ok = True
                if arch_g0v.get("product_variant") is not None:
                    ga_res = resolve_canonical_product_variant(arch_g0v.get("product_variant"), openislet_root=openislet_root)
                    g0v_alias_ok = bool(ga_res is not None and ga_res["product_variant_id"] == expected_product_variant_id)
                g0v_tier_ok = bool(
                    arch_g0v.get("qualification_tier") == "BANK_QUALIFICATION"
                    and ("operational_tier" not in arch_g0v or arch_g0v.get("operational_tier") == "BANK_QUALIFICATION")
                )
                g0v_supplied_sha = arch_g0v.get("payload_sha256")
                g0v_computed_sha = _safe_canonical_lot_sha256(arch_g0v)
                g0v_self_sha_ok = bool(
                    g0v_computed_sha is not None
                    and _is_valid_sha256_hex(g0v_supplied_sha)
                    and g0v_supplied_sha == g0v_computed_sha
                )
                if not g0v_self_sha_ok:
                    nested_reconcile_ok = False
                    arch_fail_reasons.append("composite_nested_gate0v_payload_sha256_mismatch")
                    _add_err(f"{hold_prefix}_ARCHIVED_NESTED_GATE0V_SELF_DIGEST_MISMATCH")
                if not (g0v_lot_ok and g0v_mcb_ok and g0v_pvid_ok and g0v_alias_ok and g0v_tier_ok):
                    nested_reconcile_ok = False
                    arch_fail_reasons.append("composite_nested_gate0v_identity_or_tier_mismatch")

                # R07-B1 + R08-B1: Mandatory live legacy revalidation when called from composite wrapper
                # (Zero-LIMS-Touch preserved in standalone verify_iip0043 when legacy_evaluator is None!)
                if require_composite_legacy_replay:
                    if not arch_envelope_ok:
                        arch_leg_reval_ok = False
                        nested_reconcile_ok = False
                        arch_fail_reasons.append("archived_legacy_revalidation_blocked_by_invalid_composite_envelope")
                    elif (
                        rec_pvid_res is not None
                        and rec_pvid_res.get("registry_source") == "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json"
                    ):
                        arch_leg_reval_ok = False
                        nested_reconcile_ok = False
                        arch_fail_reasons.append("archived_legacy_revalidation_failed:SIDE_CONTRACT_COMPARATOR_UNSUPPORTED_FOR_CLINICAL_RELEASE")
                        _add_err(f"{hold_prefix}_ARCHIVED_LEGACY_REVALIDATION_FAILED")
                    elif leg_lot_ok and leg_mcb_ok and leg_pvid_ok and leg_alias_ok:
                        try:
                            leg_in = {k: v for k, v in arch_leg.items() if k not in ("lot_id", "product_variant")}
                            leg_in["product_variant_id"] = expected_product_variant_id
                            leg_in.setdefault("current_lot_id", rec.get("bank_lot_id"))
                            leg_in.setdefault("mcb_id", expected_mcb_id)
                            sig = inspect.signature(legacy_evaluator)
                            params = sig.parameters
                            if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) or "root" in params:
                                leg_out = legacy_evaluator(leg_in, root=openislet_root)
                            else:
                                leg_out = legacy_evaluator(leg_in)
                            leg_arch_out = leg_out.get("resolved_architecture_assignments") or {}
                            leg_tier_out = str(
                                leg_out.get("lot_release_readiness_tier")
                                or leg_arch_out.get("lot_release_readiness_tier")
                                or "UNKNOWN"
                            )
                            leg_s9_out = bool(leg_out.get("safety_kill_s9_triggered"))
                            leg_pvid_out = leg_arch_out.get("product_variant_id")
                            arch_leg_reval_ok = bool(
                                leg_structure_ok
                                and leg_tier_out == "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE"
                                and not leg_s9_out
                                and leg_pvid_out == expected_product_variant_id
                            )
                            if not arch_leg_reval_ok:
                                nested_reconcile_ok = False
                                arch_fail_reasons.append(f"archived_legacy_revalidation_failed:{leg_tier_out}")
                                _add_err(f"{hold_prefix}_ARCHIVED_LEGACY_REVALIDATION_FAILED")
                        except Exception as exc:
                            arch_leg_reval_ok = False
                            nested_reconcile_ok = False
                            arch_fail_reasons.append(f"archived_legacy_revalidation_exception:{type(exc).__name__}")
                            _add_err(f"{hold_prefix}_ARCHIVED_LEGACY_REVALIDATION_FAILED")
                    else:
                        arch_leg_reval_ok = False
                        nested_reconcile_ok = False
                        arch_fail_reasons.append("archived_legacy_revalidation_skipped_due_to_identity_mismatch")
                        _add_err(f"{hold_prefix}_ARCHIVED_LEGACY_REVALIDATION_FAILED")

                # R08-B1: When invoked from composite release wrapper, ALSO execute live composite
                # bank replay on the archived composite bank payload itself so it is IMPOSSIBLE for
                # any archived composite bank bundle that direct composite holds to pass the archive path!
                if composite_bank_revalidator is not None:
                    try:
                        comp_reval = composite_bank_revalidator(archived_payload)
                        cr_lb = comp_reval.get("lot_binding") or {}
                        cr_leg = comp_reval.get("legacy_result_summary") or {}
                        cr_g0v = comp_reval.get("gate0v_result_summary") or {}
                        arch_comp_reval_ok = bool(
                            comp_reval.get("composite_verdict") == "PASS_COMPOSITE_BANK_QUALIFICATION"
                            and len(comp_reval.get("hard_stops") or []) == 0
                            and len(comp_reval.get("holds") or []) == 0
                            and cr_lb.get("payload_sha256_verified") is True
                            and cr_lb.get("lot_id") == rec.get("bank_lot_id")
                            and cr_lb.get("mcb_id") == expected_mcb_id
                            and cr_lb.get("canonical_product_variant_id") == expected_product_variant_id
                            and cr_leg.get("legacy_evaluator_passed") is True
                            and cr_g0v.get("gate0v_evaluator_passed") is True
                        )
                        if not arch_comp_reval_ok:
                            nested_reconcile_ok = False
                            if not arch_envelope_ok:
                                _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")
                            for cr_h in (comp_reval.get("holds") or []):
                                if isinstance(cr_h, str):
                                    _add_err(cr_h)
                            arch_fail_reasons.append(
                                f"archived_composite_bank_live_replay_failed:{comp_reval.get('composite_verdict')}"
                            )
                    except Exception as exc:
                        arch_comp_reval_ok = False
                        nested_reconcile_ok = False
                        arch_fail_reasons.append(f"archived_composite_bank_live_replay_exception:{type(exc).__name__}")
                        _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")

                target_g0v_payload = arch_g0v
        else:
            # Direct canonical BANK_QUALIFICATION Gate-0V payload (standalone evidence boundary ONLY!)
            # R08-B1: Standalone plain whole-graft archives MUST also carry canonical product_variant_id
            # (never alias-only) AND reconcile any supplied operational_tier against BANK_QUALIFICATION!
            standalone_tier_ok = bool(
                archived_payload.get("qualification_tier") == "BANK_QUALIFICATION"
                and ("operational_tier" not in archived_payload or archived_payload.get("operational_tier") == "BANK_QUALIFICATION")
            )
            if not arch_pvid_present:
                arch_envelope_ok = False
                nested_reconcile_ok = False
                _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")
                _add_err("HOLD_GATE0V_MISSING_CANONICAL_PRODUCT_VARIANT_ID")
                arch_fail_reasons.append("standalone_archive_missing_canonical_product_variant_id")
            if "operational_tier" in archived_payload and archived_payload.get("operational_tier") != "BANK_QUALIFICATION":
                arch_envelope_ok = False
                nested_reconcile_ok = False
                _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")
                _add_err("HOLD_GATE0V_OPERATIONAL_TIER_MISMATCH")
                arch_fail_reasons.append("standalone_archive_conflicting_operational_tier")

            has_core_g0v_blocks = (
                isinstance(archived_payload.get("gate0v_a_poly_ic_sensing"), dict)
                and isinstance(archived_payload.get("gate0v_b_infectious_challenge"), dict)
                and isinstance(archived_payload.get("gate0v_kill_stress_ap1903"), dict)
                and isinstance(archived_payload.get("clustering_and_independence_spec"), dict)
            )
            if has_core_g0v_blocks and standalone_tier_ok and arch_pvid_present:
                target_g0v_payload = archived_payload
                if require_composite_legacy_replay:
                    # R07-B1: Composite clinical release STRICTLY REQUIRES a complete composite bank
                    # archive containing BOTH whole-graft AND archived legacy wetlab_contract observations!
                    arch_format = "standalone_gate0v_bank_payload_missing_legacy_for_composite_release"
                    nested_reconcile_ok = False
                    arch_leg_reval_ok = False
                    if composite_bank_revalidator is not None:
                        arch_comp_reval_ok = False
                    arch_fail_reasons.append("missing_archived_legacy_stage0_observations_for_composite_release")
                    _add_err("HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
                    _add_err(f"{hold_prefix}_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
                else:
                    arch_format = "canonical_gate0v_bank_payload"
            else:
                arch_format = "incomplete_or_metadata_only_stub_rejected"
                nested_reconcile_ok = False
                if require_composite_legacy_replay:
                    arch_leg_reval_ok = False
                if composite_bank_revalidator is not None:
                    arch_comp_reval_ok = False
                arch_fail_reasons.append("metadata_only_or_incomplete_bank_archive_rejected")

        # Strict genotype reconciliation across top-level, nested Gate-0V, bank record, and current lot
        arch_geno_top = archived_payload.get("antiviral_genotype_stratum")
        arch_geno_nested = target_g0v_payload.get("antiviral_genotype_stratum") if isinstance(target_g0v_payload, dict) else None
        if arch_format == "composite_bank_bundle":
            arch_geno = arch_geno_nested
            arch_geno_self_consistent = bool(arch_geno_top is None or arch_geno_top == arch_geno_nested)
        else:
            arch_geno = arch_geno_top
            arch_geno_self_consistent = True

        arch_geno_ok = bool(
            arch_geno_self_consistent
            and isinstance(arch_geno, str)
            and arch_geno in ALLOWED_ANTIVIRAL_GENOTYPES
            and rec_geno_valid
            and exp_geno_valid
            and arch_geno == rec_geno
            and arch_geno == expected_genotype_stratum
        )
        if not arch_geno_ok:
            _add_err("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
            _add_err(f"{hold_prefix}_ARCHIVED_PAYLOAD_GENOTYPE_STRATUM_MISMATCH")
            arch_fail_reasons.append("archived_genotype_stratum_mismatch_or_contradiction")

        # Verify mandatory canonical BANK_QUALIFICATION evidence sections on target_g0v_payload
        g0v_evidence_blocks_ok = False
        live_reval_ok = False
        if isinstance(target_g0v_payload, dict):
            g0v_a_blk = target_g0v_payload.get("gate0v_a_poly_ic_sensing")
            g0v_b_blk = target_g0v_payload.get("gate0v_b_infectious_challenge")
            g0v_b_paths = g0v_b_blk.get("pathogens") if isinstance(g0v_b_blk, dict) else None
            g0v_k_blk = target_g0v_payload.get("gate0v_kill_stress_ap1903")
            g0v_evidence_blocks_ok = bool(
                target_g0v_payload.get("qualification_tier") == "BANK_QUALIFICATION"
                and ("operational_tier" not in target_g0v_payload or target_g0v_payload.get("operational_tier") == "BANK_QUALIFICATION")
                and isinstance(g0v_a_blk, dict)
                and isinstance(g0v_b_paths, dict)
                and set(GATE0V_PATHOGENS).issubset(set(g0v_b_paths.keys()))
                and isinstance(g0v_k_blk, dict)
                and set(STRESS_AP1903_REGIMES).issubset(set(g0v_k_blk.keys()))