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…

    tier_allowed_for_product = env["tier_allowed_for_product"]

    # B1 / R04-B1 / R04-B2 / R07-B1 / R08-B1: Resolve prior bank/process qualification SOLELY from
    # independent external trusted store, executing live composite bank replay on archived bank bundles!
    prior_qual_auth: Dict[str, Any] = {
        "required": False,
        "authenticated": True,
        "resolution_source": "direct_bank_qualification_current_lot",
    }
    if qual_tier == "LOT_RELEASE_SURROGATE" and isinstance(gate0v_obs, dict):
        inline_prior = composite_doc.get("prior_bank_qualification_record")
        if inline_prior is None:
            inline_prior = gate0v_obs.get("bridged_mcb_qualification_record")

        def _replay_archived_composite_bank(arch_doc: Dict[str, Any]) -> Dict[str, Any]:
            return evaluate_composite_clinical_release(
                arch_doc,
                legacy_evaluator=legacy_evaluator,
                gate0v_evaluator=gate0v_evaluator,
                trusted_qualification_store=None,
                openislet_root=resolved_root,
                _revalidating_archived_bank=True,
            )

        pq_ok, pq_errs, pq_meta = v38.resolve_and_verify_trusted_bank_qualification(
            trusted_qualification_store,
            expected_sha256=gate0v_obs.get("bridged_mcb_qualification_sha256"),
            expected_mcb_id=top_mcb,
            expected_product_variant_id=canonical_pvid,
            expected_genotype_stratum=gate0v_obs.get("antiviral_genotype_stratum"),
            inline_record_if_supplied=inline_prior,
            openislet_root=resolved_root,
            hold_prefix="HOLD_COMPOSITE_PRIOR_BANK_QUAL",
            legacy_evaluator=legacy_evaluator,
            composite_bank_revalidator=(
                _replay_archived_composite_bank
                if (legacy_evaluator is not None and gate0v_evaluator is not None and not _revalidating_archived_bank)
                else None
            ),
            _revalidating_archived_bank=_revalidating_archived_bank,
        )
        prior_qual_auth = {"required": True, **pq_meta}
        for pe in pq_errs:
            if pe not in holds:
                holds.append(pe)
        # R07-B1 + R08-B1: Composite clinical release STRICTLY REQUIRES canonical composite envelope
        # parity AND live Gate-0V + live legacy + live composite bank replay on a complete composite bank archive!
        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 (
                    legacy_evaluator is None
                    or prior_qual_auth.get("archived_bank_payload_format")
                    in ("standalone_gate0v_bank_payload_missing_legacy_for_composite_release", "canonical_gate0v_bank_payload")
                )
            ):
                if "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")
    elif qual_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL" and isinstance(gate0v_obs, dict):
        inline_proc = composite_doc.get("prior_process_qualification_record")
        if inline_proc is None:
            inline_proc = gate0v_obs.get("process_qualification_record")
        pq_ok, pq_errs, pq_meta = v38.resolve_and_verify_trusted_process_qualification(
            trusted_qualification_store,
            expected_sha256=gate0v_obs.get("process_qualification_ref_sha256"),
            expected_product_variant_id=canonical_pvid,
            inline_record_if_supplied=inline_proc,
            openislet_root=resolved_root,
            hold_prefix="HOLD_COMPOSITE_AUTOLOGOUS_PROC_QUAL",
        )
        prior_qual_auth = {"required": True, **pq_meta}
        for pe in pq_errs:
            if pe not in holds:
                holds.append(pe)

    legacy_summary: Dict[str, Any] | None = None
    gate0v_summary: Dict[str, Any] | None = None
    g0v_scope: Dict[str, Any] | None = None

    # B2: Invoke legacy wetlab_contract.py WITH preserved canonical product_variant_id, current_lot_id & mcb_id!
    if legacy_evaluator is not None and isinstance(legacy_obs, dict):
        if (
            canonical_product_def is not None
            and canonical_product_def.get("registry_source") == "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json"
        ):
            # Side-contract-only ABX_L2_v2_* donors have execution_supported=False and are NOT promoted in wetlab_contract.py
            legacy_summary = {
                "lot_release_readiness_tier": "SIDE_CONTRACT_COMPARATOR_UNSUPPORTED_FOR_CLINICAL_RELEASE",
                "resolved_product_variant_id": canonical_pvid,
                "product_execution_supported": False,
                "safety_kill_s9_triggered": False,
                "legacy_evaluator_passed": False,
                "canonical_scope_reconciled": True,
                "legacy_obs_gate0v_beta_cells_scored": legacy_obs.get("obs_gate0v_day28_persistent_vp1_ie1_cells_scored"),
                "legacy_omitted_acute_cvb4_72h_titer": "obs_cvb4_10moi_72h_viral_titer_log10_pfu" not in legacy_obs,
            }
            holds.append("HOLD_COMPOSITE_LEGACY_EVALUATOR_NOT_READY:SIDE_CONTRACT_COMPARATOR_UNSUPPORTED_FOR_CLINICAL_RELEASE")
        else:
            try:
                # Preserve canonical contract metadata keys (product_variant_id, current_lot_id, mcb_id)!
                # Strip ONLY non-contract wrapper aliases (lot_id, product_variant) AFTER verifying reconciliation above.
                legacy_input = {
                    k: v for k, v in legacy_obs.items()
                    if k not in ("lot_id", "product_variant")
                }
                if leg_pvid_canon is not None:
                    legacy_input["product_variant_id"] = leg_pvid_canon
                if _is_clean_nonempty_str(top_lot) and "current_lot_id" not in legacy_input:
                    legacy_input["current_lot_id"] = top_lot
                if _is_clean_nonempty_str(top_mcb) and "mcb_id" not in legacy_input:
                    legacy_input["mcb_id"] = top_mcb

                leg_res = _call_with_optional_kwargs(legacy_evaluator, legacy_input, {"root": resolved_root})
                resolved_arch = leg_res.get("resolved_architecture_assignments") or {}
                leg_tier = str(
                    leg_res.get("lot_release_readiness_tier")
                    or resolved_arch.get("lot_release_readiness_tier")
                    or "UNKNOWN"
                )
                leg_resolved_pvid = resolved_arch.get("product_variant_id")
                leg_exec_supported = resolved_arch.get("product_execution_supported")
                leg_s9 = bool(leg_res.get("safety_kill_s9_triggered"))
                leg_pvid_matched = bool(canonical_pvid is not None and leg_resolved_pvid == canonical_pvid)
                if canonical_pvid is not None and not leg_pvid_matched:
                    holds.append("HOLD_COMPOSITE_LEGACY_RESOLVED_PRODUCT_VARIANT_ID_MISMATCH")

                leg_pass = bool(leg_tier == LEGACY_PASS_TIER and not leg_s9 and leg_pvid_matched)
                legacy_summary = {
                    "lot_release_readiness_tier": leg_tier,
                    "resolved_product_variant_id": leg_resolved_pvid,
                    "product_execution_supported": leg_exec_supported,
                    "canonical_scope_reconciled": leg_pvid_matched,
                    "safety_kill_s9_triggered": leg_s9,
                    "legacy_evaluator_passed": leg_pass,
                    "legacy_obs_gate0v_beta_cells_scored": legacy_obs.get("obs_gate0v_day28_persistent_vp1_ie1_cells_scored"),
                    "legacy_omitted_acute_cvb4_72h_titer": "obs_cvb4_10moi_72h_viral_titer_log10_pfu" not in legacy_obs,
                }
                if leg_s9 or leg_tier == "HARD_SAFETY_STOP_REJECTED":
                    hard_stops.append(f"FAIL_HARD_STOP_LEGACY_EVALUATOR:{leg_tier}")
                elif not leg_pass:
                    holds.append(f"HOLD_COMPOSITE_LEGACY_EVALUATOR_NOT_READY:{leg_tier}")
            except Exception as exc:
                holds.append(f"HOLD_COMPOSITE_LEGACY_EVALUATOR_EXCEPTION:{type(exc).__name__}")

    has_coupled_ocr_input = bool(nw08_ocr_json_path is not None or nw08_ocr_record is not None)
    if gate0v_evaluator is not None and isinstance(gate0v_obs, dict):
        try:
            g0v_res = _call_with_optional_kwargs(
                gate0v_evaluator,
                gate0v_obs,
                {
                    "trusted_qualification_store": trusted_qualification_store,
                    "openislet_root": resolved_root,
                    "_nw08_ocr_adjudicated_externally": has_coupled_ocr_input,
                },
            )
            g0v_verdict = str(g0v_res.get("verdict") or "UNKNOWN")
            expected_g0v_pass = GATE0V_PASS_VERDICTS_BY_TIER.get(str(qual_tier))
            g0v_lot_bind = g0v_res.get("lot_binding") or {}
            g0v_resolved_pvid = g0v_lot_bind.get("canonical_product_variant_id")
            if canonical_pvid is not None and g0v_resolved_pvid != canonical_pvid:
                holds.append("HOLD_COMPOSITE_GATE0V_RESOLVED_PRODUCT_VARIANT_ID_MISMATCH")
            g0v_pass = bool(
                expected_g0v_pass is not None
                and g0v_verdict == expected_g0v_pass
                and g0v_res.get("exact_directional_confidence_certified") is True
                and (canonical_pvid is None or g0v_resolved_pvid == canonical_pvid)
            )
            g0v_scope = g0v_res.get("tested_vs_inherited_scope")
            gate0v_summary = {
                "verdict": g0v_verdict,
                "expected_tier_pass_verdict": expected_g0v_pass,
                "gate0v_evaluator_passed": g0v_pass,
                "qualification_scope": g0v_res.get("qualification_scope"),
                "physical_qualification_complete": g0v_res.get("physical_qualification_complete"),
                "qualification_tier": g0v_lot_bind.get("qualification_tier"),
                "canonical_product_variant_id": g0v_resolved_pvid,
                "ectopic_viral_receptors_evaluated": g0v_res.get("ectopic_viral_receptors_evaluated", []),
                "exact_directional_confidence_certified": g0v_res.get("exact_directional_confidence_certified"),
                "confidence_scope": g0v_res.get("confidence_scope"),
                "clustering_design_effect_deff": g0v_res.get("clustering_design_effect_deff"),
                "submitted_clustering_design_effect_deff_unvalidated": g0v_res.get("submitted_clustering_design_effect_deff_unvalidated"),
                "sampling_unit_basis": g0v_res.get("sampling_unit_basis"),
                "hard_stops_count": len(g0v_res.get("hard_stops") or []),
                "holds_count": len(g0v_res.get("holds") or []),
                "hard_stops_sample": (g0v_res.get("hard_stops") or [])[:4],
                "holds_sample": (g0v_res.get("holds") or [])[:4],
            }
            if g0v_verdict == "FAIL_HARD_STOP":
                hard_stops.extend(g0v_res.get("hard_stops") or ["FAIL_HARD_STOP_GATE0V"])
            elif not g0v_pass:
                holds.append(f"HOLD_COMPOSITE_GATE0V_NOT_PASSED:{g0v_verdict}")
                g0v_holds_all = list(g0v_res.get("holds") or [])
                sentinel_holds = (
                    "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE",
                    "HOLD_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD",
                    "HOLD_NON_SAME_ALIQUOT_UNVERIFIED_COUNT_RECONCILIATION",
                    "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE",
                    "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
                    "HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH",
                    "HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH",
                    "HOLD_COMPOSITE_MISSING_TOP_PRODUCT_VARIANT_ID",
                    "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
                    "HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
                    "HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM",
                    "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
                    "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
                    "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
                    "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE",
                    "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION",
                    "HOLD_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS",
                    "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS",
                    "HOLD_GATE0V_MISSING_CLUSTERING_AND_INDEPENDENCE_SPEC",
                    "HOLD_GATE0V_INVALID_CLUSTERING_DESIGN_EFFECT_DEFF",
                    "HOLD_GATE0V_INVALID_OR_MISSING_INDEPENDENT_SAMPLING_UNIT_CLASS",
                )
                for sh in sentinel_holds:
                    if sh in g0v_holds_all and sh not in holds:
                        holds.append(sh)
                for h_item in g0v_holds_all[:5]:
                    if h_item not in holds:
                        holds.append(h_item)
        except Exception as exc:
            holds.append(f"HOLD_COMPOSITE_GATE0V_EVALUATOR_EXCEPTION:{type(exc).__name__}")

    effective_require_trusted_ocr = bool(
        env.get("require_trusted_nw08_ocr_record") is True
        or prior_qual_auth.get("record_require_trusted_nw08_ocr_record") is True
    )
    lot_binding_dict: Dict[str, Any] = {
        "lot_id": top_lot if isinstance(top_lot, str) else None,
        "mcb_id": top_mcb if isinstance(top_mcb, str) else None,
        "supplied_product_variant_id": top_pvid_raw if isinstance(top_pvid_raw, str) else None,
        "canonical_product_variant_id": canonical_pvid,
        "canonical_product_tier_family": (
            canonical_product_def.get("product_tier_family") if canonical_product_def is not None else None
        ),
        "allowed_qualification_tiers_for_product": (
            canonical_product_def.get("allowed_qualification_tiers") if canonical_product_def is not None else None
        ),