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…

                if e2_ratio_factors is not None and e2_alpha_escape is not None:
                    if eta_kill <= Decimal(0):
                        u_esc_cond = Decimal(1)
                        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}ESTIMAND2_CONDITIONAL_INFECTED_TOO_SMALL_{reg_tag}_{lin_tag}")
                        arm_pass = False
                    else:
                        e2_ratio = exact_component_probability_ratio_upper(
                            vk,
                            n_in,
                            e2_alpha_escape,
                            e2_ratio_factors,
                            deff=deff,
                            prec=80,
                        )
                        u_esc_cond = e2_ratio["u_ratio_dec"]
                        lin_detail["estimand2_u_esc_conditional_per_infected_80d"] = format(u_esc_cond, "f")[:24]
                        lin_detail["estimand2_clears_3log10_conditional"] = bool(is_exact_independent and u_esc_cond <= cap_frac_kill_esc_cond)
                        lin_detail["estimand2_clears_4log10_conditional"] = bool(is_exact_independent and u_esc_cond <= cap_frac_kill_esc_total)
                        if vk == 0 and u_esc_cond > cap_frac_kill_esc_cond:
                            holds.append(f"HOLD_GATE0V_KILL_{sup_hd}ESTIMAND2_CONDITIONAL_INFECTED_TOO_SMALL_{reg_tag}_{lin_tag}")
                            arm_pass = False

    return arm_pass, lin_detail


def _adjudicate_supplemental_kill_regime_adverse_data(
    reg: str,
    rblock: Any,
    *,
    deff: Decimal | None,
    hard_stops: List[str],
    holds: List[str],
    adjudicated_log: List[str],
    sampling_spec_valid: bool = True,
    sampling_unit_class: str | None = None,
    indep_units_n: int | None = None,
    sampling_tracker: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
    """
    R03-B1 / B6 rule: Apply FULL consistent fail-closed raw-count, calibration, aliquot,
    caspase, and dual-estimand adjudication (same rigor as the required branch!) to EVERY
    submitted supplemental stress regime / lineage arm in abbreviated tiers.
    NEVER silently skip a survivor count exceeding n_eff, invalid counts, or bad calibration!
    """
    reg_tag = str(reg).upper()
    adjudicated_log.append(f"supplemental_kill_regime:{reg}")

    if reg not in STRESS_AP1903_REGIMES:
        holds.append(f"HOLD_GATE0V_KILL_SUPPLEMENTAL_UNRECOGNIZED_REGIME_{reg_tag}")
    if not isinstance(rblock, dict) or len(rblock) == 0:
        holds.append(f"HOLD_GATE0V_KILL_SUPPLEMENTAL_INVALID_OR_EMPTY_REGIME_{reg_tag}")
        return {"passed": False, "lineages": {}}

    reg_pass = reg in STRESS_AP1903_REGIMES
    reg_lineage_details: Dict[str, Any] = {}
    for lin_name, lblock in rblock.items():
        lin_tag = str(lin_name).upper()
        if lin_name not in GRAFT_LINEAGES:
            holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_KILL_SUPPLEMENTAL_{reg_tag}_{lin_tag}")
            holds.append(f"HOLD_GATE0V_KILL_SUPPLEMENTAL_UNRECOGNIZED_LINEAGE_{reg_tag}_{lin_tag}")
            reg_pass = False
        if not isinstance(lblock, dict):
            holds.append(f"HOLD_GATE0V_KILL_SUPPLEMENTAL_INVALID_LINEAGE_BLOCK_{reg_tag}_{lin_tag}")
            reg_pass = False
            continue
        arm_ok, lin_detail = _adjudicate_kill_regime_lineage_arm(
            reg,
            lin_name,
            lblock,
            deff=deff,
            hard_stops=hard_stops,
            holds=holds,
            is_supplemental=True,
            sampling_spec_valid=sampling_spec_valid,
            sampling_unit_class=sampling_unit_class,
            indep_units_n=indep_units_n,
            sampling_tracker=sampling_tracker,
        )
        if not arm_ok:
            reg_pass = False
        reg_lineage_details[lin_name] = lin_detail
    return {"passed": reg_pass, "lineages": reg_lineage_details}


def evaluate_wholegraft_gate0v_and_stress_ap1903(
    payload: Dict[str, Any],
    *,
    trusted_qualification_store: Path | str | None = None,
    openislet_root: Path | None = None,
    _revalidating_archived_bank: bool = False,
    _nw08_ocr_adjudicated_externally: bool = False,
) -> Dict[str, Any]:
    """
    Fail-closed evaluator for EXP-031 / IIP-0043 / DEC-122 Whole-Graft Gate 0V & Stress-State AP1903
    (Round-02 remediated across B1-B8 and M1-M4):
      - B1: Prior BANK_QUALIFICATION / AUTOLOGOUS_D1B_PROCESS_QUAL approval is resolved SOLELY
            from an independent external `--trusted-qualification-store`; inline self-attested
            records inside the lot bundle are NEVER accepted.
      - B2: Canonical `product_variant_id` resolution against `islet1_product_definitions_v0.8.0.json`
            plus allowlisted `IIP-0041` side-contract `ABX_L2_v2_*` donors (ZERO substring inference),
            with strict genotype compatibility against canonical product definitions.
      - B3: Enforces TRUE Clopper-Pearson `U95 <= 0.15%` on uninfected negative controls (n >= 20,000;
            20/20,000 U95 = 0.145277% PASS vs 21/20,000 U95 = 0.151167% HOLD).
      - B4: Exact <= 0.050 Bonferroni joint confidence budget across EVERY estimated parameter per
            lineage x regime estimand (Indirect E2: 0.015+0.015+0.005+0.015=0.050; Direct E2:
            0.025+0.005+0.020=0.050; Paired 24h/72h: 0.025+0.025=0.050; Estimand 1: 0.025+0.005+0.005=0.035).
      - B5: Mandatory dual-target ddPCR panel validation (HCMV UL138+UL55; CVB pos+neg 5'-del RNA),
            powered exact-Decimal Clopper-Pearson CD55 echovirus addendum, and exact lineage ledger
            reconciliation (`total_acquired_n == sum(lineage_assigned_n) + unassigned_n`) plus
            mandatory unassigned-fraction viral readout.
      - B6: Adjudicates ALL submitted adverse data across abbreviated tiers (never silently drops
            supplemental pathogen/regime/addendum findings), keeps edited-genotype non-inferiority
            active in AUTOLOGOUS_D1B_PROCESS_QUAL, and emits tier-distinct PASS codes with explicit
            tested-vs-inherited scope.
    """
    hard_stops: List[str] = []
    holds: List[str] = []

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

    cap_frac_persist = Decimal("0.0005")         # 0.05% per-lineage viral persistence cap (proposed)
    cap_frac_kill_esc_total = Decimal("0.0001")  # 0.01% (4.0 log10) per total input at risk (proposed)
    cap_frac_kill_esc_cond = Decimal("0.001")    # 0.10% (3.0 log10) conditional per infected cell (proposed)
    alpha_3p = _alpha_3pathogen_global_floor(prec=120)  # 0.05 / 30 = floor(1/600)
    alpha_1p = Decimal("0.005")                  # 0.05 / 10 (single-pathogen / 5-lineage)
    alpha_05 = Decimal("0.05")
    # B4 exact Bonferroni allocations (every per-estimand union-bound sum <= 0.050 -> >= 95.0% joint confidence!)
    alpha_paired_veh = Decimal("0.025")          # 24h & 72h paired ratios: 0.025 + 0.025 = 0.050
    alpha_paired_surv = Decimal("0.025")
    alpha_e1_eta = Decimal("0.005")              # Estimand 1: 0.025 (veh) + 0.005 (eta) + 0.005 (esc) = 0.035 <= 0.050
    alpha_e1_esc = Decimal("0.005")
    alpha_e2_ind_veh = Decimal("0.015")          # Indirect E2: 0.015 + 0.015 + 0.005 + 0.015 = 0.050
    alpha_e2_ind_prev = Decimal("0.015")
    alpha_e2_ind_eta = Decimal("0.005")
    alpha_e2_ind_esc = Decimal("0.015")
    alpha_e2_dir_inf_veh = Decimal("0.025")      # Direct E2: 0.025 + 0.005 + 0.020 = 0.050
    alpha_e2_dir_eta = Decimal("0.005")
    alpha_e2_dir_esc = Decimal("0.020")

    min_eta_cal = Decimal("0.80")
    min_s_veh = Decimal("0.10")
    max_unassigned_frac = Decimal("0.05")
    # B3: True one-sided Clopper-Pearson U95 cap <= 0.15% at n >= 20,000 (admits <= 20/20,000 [U95=0.145277%], rejects 21/20,000 [U95=0.151167%])
    max_neg_ctrl_fpr_u95 = Decimal("0.0015")
    max_stage1_screen_frac = Decimal("0.002")
    min_neg_rna_wells = 6
    min_uninfected_ctrl_n = 20_000
    min_noninf_replicates = 6

    if not isinstance(payload, dict):
        return {
            "verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "release_authorizing": False,
            "gate0v_component_passed": False,
            "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
            "physical_qualification_complete": False,
            "clustering_design_effect_deff": None,
            "submitted_clustering_design_effect_deff_unvalidated": None,
            "lot_binding": None,
            "tested_vs_inherited_scope": None,
            "hard_stops": [],
            "holds": ["HOLD_GATE0V_PAYLOAD_NOT_DICT"],
            "all_required_pathogens_and_5_lineages_calibrated": False,
            "pathogen_results": {},
            "cd46_addendum_results": {},
            "cd55_addendum_results": {},
            "stress_ap1903_regimes": {},
        }

    # ------------------------------------------------------------------
    # 0A. Shared Lot, MCB, Canonical Product Variant ID, Qualification Tier & SHA-256 Binding
    # ------------------------------------------------------------------
    lot_id = payload.get("lot_id")
    mcb_id = payload.get("mcb_id")
    pvid_raw = payload.get("product_variant_id")
    pv_legacy_raw = payload.get("product_variant")
    qual_tier = payload.get("qualification_tier")
    supplied_sha = payload.get("payload_sha256")
    computed_sha = _safe_canonical_lot_sha256(payload)
    if computed_sha is None:
        holds.append("HOLD_GATE0V_NONCANONICAL_OR_NONFINITE_PAYLOAD")

    if not _is_valid_identifier(lot_id):
        holds.append("HOLD_GATE0V_MISSING_OR_INVALID_LOT_ID")
    else:
        for ak in _LOT_ALIAS_KEYS:
            if ak in payload and ak != "lot_id" and payload.get(ak) is not None and payload.get(ak) != lot_id:
                holds.append(f"HOLD_GATE0V_CONFLICTING_LOT_ALIAS_{ak.upper()}")
    if not _is_valid_identifier(mcb_id):
        holds.append("HOLD_GATE0V_MISSING_OR_INVALID_MCB_ID")

    # B2 + R08-B1: Canonical product_variant_id resolution (no unregistered IDs, no alias-only omission, no silent alias mismatch)
    canonical_product_def: Dict[str, Any] | None = None
    canonical_pvid: str | None = None
    if not _is_clean_nonempty_str(pvid_raw):
        holds.append("HOLD_GATE0V_MISSING_CANONICAL_PRODUCT_VARIANT_ID")
    else:
        canonical_product_def = resolve_canonical_product_variant(pvid_raw, openislet_root=resolved_root)
        if canonical_product_def is None:
            holds.append("HOLD_GATE0V_UNREGISTERED_PRODUCT_VARIANT_ID")
        else:
            canonical_pvid = canonical_product_def["product_variant_id"]

    if pv_legacy_raw is not None:
        pv_leg_res = resolve_canonical_product_variant(pv_legacy_raw, openislet_root=resolved_root)
        if pv_leg_res is None:
            holds.append("HOLD_GATE0V_UNREGISTERED_PRODUCT_VARIANT_ALIAS")
        elif canonical_pvid is not None and pv_leg_res["product_variant_id"] != canonical_pvid:
            holds.append("HOLD_GATE0V_CONFLICTING_PRODUCT_VARIANT_ALIAS")

    qual_tier_valid = isinstance(qual_tier, str) and qual_tier in ALLOWED_QUALIFICATION_TIERS
    if not qual_tier_valid:
        holds.append("HOLD_GATE0V_MISSING_OR_INVALID_QUALIFICATION_TIER")
    if "operational_tier" in payload and payload.get("operational_tier") != qual_tier:
        holds.append("HOLD_GATE0V_OPERATIONAL_TIER_MISMATCH")
    if not _is_valid_sha256_hex(supplied_sha) or supplied_sha != computed_sha:
        holds.append("HOLD_GATE0V_MISSING_OR_MISMATCHED_PAYLOAD_SHA256")

    # R04-B1: Strict canonical product-family-to-qualification-tier allowlist enforcement!
    tier_allowed_for_product = True
    if canonical_product_def is not None and qual_tier_valid:
        tier_allowed_for_product, tier_family_errs = is_qualification_tier_allowed_for_product(
            canonical_product_def, qual_tier
        )
        for te in tier_family_errs:
            if te not in holds:
                holds.append(te)

    geno = payload.get("antiviral_genotype_stratum")

    # B1 / R04-B1 / R04-B2: Resolve prior bank/process approval SOLELY from independent external trusted store!
    prior_qual_auth: Dict[str, Any] = {
        "required": qual_tier != "BANK_QUALIFICATION",
        "authenticated": qual_tier == "BANK_QUALIFICATION",
        "resolution_source": "direct_bank_qualification_current_lot" if qual_tier == "BANK_QUALIFICATION" else None,
    }
    if qual_tier == "LOT_RELEASE_SURROGATE":
        pq_ok, pq_errs, pq_meta = resolve_and_verify_trusted_bank_qualification(
            trusted_qualification_store,
            expected_sha256=payload.get("bridged_mcb_qualification_sha256"),
            expected_mcb_id=mcb_id,
            expected_product_variant_id=canonical_pvid,
            expected_genotype_stratum=geno,
            inline_record_if_supplied=payload.get("bridged_mcb_qualification_record"),
            openislet_root=resolved_root,
            hold_prefix="HOLD_GATE0V_PRIOR_BANK_QUAL",
            _revalidating_archived_bank=_revalidating_archived_bank,
        )
        prior_qual_auth = {"required": True, **pq_meta}
        for pe in pq_errs: