OpenIslet

scripts/verify_iip0044_foundry_v1_3_biologics.py

IIP-0044 / DEC-123 (CAND-035 / EXP-032): OpenIslet Foundry v1.3 Clean-Room

script Release v0.8.0 gen-eb955f8266035aba 619 KB · 44 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_iip0044_foundry_v1_3_biologics.py · SHA-256: 1d6c53a0817f6254…

        # R09 B2: Fixed pre-registered roster Bonferroni denominator N_roster NEVER shrinks under exclusions,
        # and NEVER authorizes biological cytotoxicity FAIL unless authorization_grade_fwer_bound_valid is True!
        alpha_donor: float | None = (
            _SHIELD_CYTO_DONOR_FAMILY_ALPHA_ONE_SIDED / float(bonferroni_family_denominator_n)
            if bonferroni_family_denominator_n is not None
            else None
        )
        derived_summary["per_donor_bonferroni_alpha_one_sided"] = round(alpha_donor, 10) if alpha_donor is not None else None

        if len(valid_donor_cyto_rates) >= 1:
            unadjusted_donor_l95_diag = max(valid_donor_cp_l95s_unadj)
            worst_cp_u95 = max(valid_donor_cp_u95s)
            total_k = sum(valid_donor_k_list)
            total_neff = sum(valid_donor_neff_list)
            max_obs_rate = max(valid_donor_cyto_rates)

            worst_donor_bonf_lower: float | None = None
            if alpha_donor is not None:
                bonf_donor_lowers = [
                    _clopper_pearson_one_sided_95_pct(k_i, n_i, alpha=alpha_donor)[0]
                    for k_i, n_i in zip(valid_donor_k_list, valid_donor_neff_list)
                ]
                worst_donor_bonf_lower = max(bonf_donor_lowers)

            derived_summary["cytotoxicity_total_k_obs"] = total_k
            derived_summary["cytotoxicity_total_n_eff"] = total_neff
            derived_summary["cytotoxicity_min_n_eff_per_donor"] = min(valid_donor_neff_list)
            derived_summary["cytotoxicity_max_donor_observed_pct"] = round(max_obs_rate, 6)
            derived_summary["simultaneous_worst_donor_bonferroni_lower_pct"] = (
                round(worst_donor_bonf_lower, 6) if worst_donor_bonf_lower is not None else None
            )
            derived_summary["cytotoxicity_calibrated_simultaneous_lower_pct"] = (
                round(worst_donor_bonf_lower, 6) if worst_donor_bonf_lower is not None else None
            )
            derived_summary["unadjusted_donor_l95_diagnostic_only"] = round(unadjusted_donor_l95_diag, 6)

            cohort_t_lower_diag: float | None = None
            cyto_mean = sum(valid_donor_cyto_rates) / float(len(valid_donor_cyto_rates))
            eff_u95 = worst_cp_u95
            derived_summary["cytotoxicity_mean_observed_pct"] = round(cyto_mean, 6)

            if len(valid_donor_cyto_rates) >= _SHIELD_MIN_DONORS_N:
                # Non-authorizing descriptive cohort Student-t summary ONLY (NEVER drives biological FAIL).
                cyto_mean, cohort_t_lower_diag, cohort_u975 = _shield_student_t_ci_pct(
                    valid_donor_cyto_rates,
                    lo_bound=0.0,
                    hi_bound=100.0,
                )
                eff_u95 = max(cohort_u975, worst_cp_u95)
                derived_summary["cytotoxicity_mean_observed_pct"] = round(cyto_mean, 6)
                derived_summary["cohort_mean_cytotoxicity_t_lower_diagnostic_only_pct"] = round(cohort_t_lower_diag, 6)
                derived_summary["cytotoxicity_conservative_u95_pct"] = round(eff_u95, 6)
                derived_summary["cytotoxicity_full_roster_u95_pct"] = (
                    round(eff_u95, 6) if full_roster_cyto_measured_complete else None
                )

                if total_neff < _SHIELD_MIN_CYTO_N_EFF_PER_DONOR:
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Total cytotoxicity n_eff={total_neff} < {_SHIELD_MIN_CYTO_N_EFF_PER_DONOR}")

                # Two-sided validation of optional top-level reported cytotoxicity summary (<= 0.05 pp tolerance)
                top_obs = observation.get("cytotoxicity_observed_pct")
                top_l95 = observation.get("cytotoxicity_l95_pct")
                top_u95 = observation.get("cytotoxicity_u95_pct")
                if top_obs is not None or top_l95 is not None or top_u95 is not None:
                    t_o, t_o_err = _shield_check_num(top_obs, "cytotoxicity_observed_pct", lo=0.0, hi=100.0) if top_obs is not None else (None, None)
                    t_l, t_l_err = _shield_check_num(top_l95, "cytotoxicity_l95_pct", lo=0.0, hi=100.0) if top_l95 is not None else (None, None)
                    t_u, t_u_err = _shield_check_num(top_u95, "cytotoxicity_u95_pct", lo=0.0, hi=100.0) if top_u95 is not None else (None, None)
                    for err in (t_o_err, t_l_err, t_u_err):
                        if err is not None:
                            _escalate("HOLD_INVALID_OR_MISSING_INPUT", err)
                    if t_l is not None and t_u is not None and t_l > t_u:
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Top-level inverted cytotoxicity CI L={t_l} > U95={t_u}")
                    if t_o is not None and t_l is not None and t_o == 0.0 and t_l > 0.0:
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Top-level inconsistent cytotoxicity CI: observed=0.0% with L={t_l:.3f}%")
                    if t_o is not None and abs(t_o - cyto_mean) > _SHIELD_CYTO_CI_TOL_PP:
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"Top-level cytotoxicity observed_pct={t_o:.3f}% disagrees with recomputed cohort mean={cyto_mean:.3f}%",
                        )
                    if t_l is not None and total_k == 0 and t_l > 0.0:
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Top-level cytotoxicity lower bound={t_l:.3f}% contradicts 0 observed events across donors")
                    if t_l is not None and worst_donor_bonf_lower is not None and abs(t_l - worst_donor_bonf_lower) > _SHIELD_CYTO_CI_TOL_PP:
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"Top-level cytotoxicity lower bound={t_l:.3f}% disagrees with fixed-roster Bonferroni lower bound={worst_donor_bonf_lower:.3f}% (two-sided tol {_SHIELD_CYTO_CI_TOL_PP:.2f} pp)",
                        )
                    if t_u is not None and abs(t_u - eff_u95) > _SHIELD_CYTO_CI_TOL_PP:
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"Top-level cytotoxicity U95={t_u:.3f}% disagrees with recomputed conservative U95={eff_u95:.3f}% (two-sided tol {_SHIELD_CYTO_CI_TOL_PP:.2f} pp)",
                        )

            if authorization_grade_fwer_bound_valid and worst_donor_bonf_lower is not None and worst_donor_bonf_lower > 5.0:
                donor_based_bio_fail = True
                diag_txt = f"{cohort_t_lower_diag:.3f}%" if cohort_t_lower_diag is not None else "n/a(<3 valid)"
                _escalate(
                    "FAIL",
                    f"Off-target APC cytotoxicity exact fixed-roster Bonferroni lower bound (H0_all: max_i p_i <= 5.0%, FWER<=0.05) "
                    f"exceeds 5.0% FAIL bar: simultaneous_worst_donor_bonf_lower={worst_donor_bonf_lower:.3f}% "
                    f"(N_roster={bonferroni_family_denominator_n}, N_valid={len(valid_donor_cyto_rates)}, "
                    f"alpha_donor={alpha_donor:.6f}; diagnostic_only_cohort_t_lower={diag_txt})",
                )
            elif authorization_grade_fwer_bound_valid and len(valid_donor_cyto_rates) >= _SHIELD_MIN_DONORS_N:
                if total_k > 0:
                    if eff_u95 > 5.0:
                        _escalate(
                            "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT",
                            f"Positive observed off-target APC cytotoxicity (max_donor={max_obs_rate:.3f}%, mean={cyto_mean:.3f}%) "
                            f"with calibrated simultaneous lower={worst_donor_bonf_lower:.3f}% <= 5.0% AND conservative U95={eff_u95:.3f}% > 5.0%",
                        )
                    else:
                        _escalate(
                            "HOLD_OBSERVED_NONZERO_CYTOTOXICITY",
                            f"Positive observed off-target APC cytotoxicity (max_donor={max_obs_rate:.3f}%, mean={cyto_mean:.3f}%) "
                            f"while conservative U95={eff_u95:.3f}% <= 5.0%; cannot PASS",
                        )
                elif eff_u95 > 5.0:
                    _escalate(
                        "HOLD",
                        f"Underpowered 0% cytotoxicity: conservative U95={eff_u95:.3f}% > 5.0% PASS ceiling",
                    )
            if authorization_grade_fwer_bound_valid and not full_roster_cyto_measured_complete and len(valid_excluded_donor_ids) > 0:
                _escalate(
                    "HOLD",
                    f"INCOMPLETE_ROSTER_CYTOTOXICITY_EXCLUSION_PRECLUDES_FULL_ROSTER_PASS: "
                    f"{len(valid_excluded_donor_ids)} of {bonferroni_family_denominator_n} pre-registered rostered "
                    f"donors were excluded pre-assay ({sorted(valid_excluded_donor_ids)}); confirmatory full-roster "
                    f"cytotoxicity PASS and Track-B eligibility require 100% measured valid cytotoxicity evidence across all "
                    f"N_roster={bonferroni_family_denominator_n} rostered donors (conservative full-roster "
                    f"Bonferroni FAIL adjudication remains active at N_roster={bonferroni_family_denominator_n})",
                )

    # 8. Cross-block construct-bound linked expression_batch_ids replication checks
    #    (>= 3 distinct Comp1 batches linked across Comp1 assays; >= 3 distinct Comp2 batches linked across
    #     Comp2 assays; >= 3 distinct Comp1 and >= 3 distinct Comp2 batches linked across cocktail assays)
    derived_summary["distinct_referenced_expression_batches_count"] = len(referenced_batches)
    derived_summary["distinct_linked_comp1_assay_batches_count"] = len(comp1_assay_batches)
    derived_summary["distinct_linked_comp2_assay_batches_count"] = len(comp2_assay_batches)
    derived_summary["distinct_linked_cocktail_comp1_batches_count"] = len(cocktail_comp1_batches)
    derived_summary["distinct_linked_cocktail_comp2_batches_count"] = len(cocktail_comp2_batches)
    if len(referenced_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Assay records reference only {len(referenced_batches)} distinct declared passing expression batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )
    if len(comp1_assay_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Comp1 assays link only {len(comp1_assay_batches)} distinct passing {_SHIELD_COMP1_LEAD} batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )
    if len(comp2_assay_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Comp2 assays link only {len(comp2_assay_batches)} distinct passing {_SHIELD_COMP2_LEAD} batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )
    if len(cocktail_comp1_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Cocktail assays link only {len(cocktail_comp1_batches)} distinct passing {_SHIELD_COMP1_LEAD} batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )
    if len(cocktail_comp2_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Cocktail assays link only {len(cocktail_comp2_batches)} distinct passing {_SHIELD_COMP2_LEAD} batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )

    if worst_state != "FAIL":
        failure_domain: str | None = None
    elif spr_bio_fail and donor_based_bio_fail:
        failure_domain = "BOTH_INDEPENDENT_SPR_AND_ROSTERED_DONOR_COHORT"
    elif spr_bio_fail:
        failure_domain = "INDEPENDENT_NON_DONOR_SPR"
    else:
        failure_domain = "ROSTERED_DONOR_COHORT"
    derived_summary["failure_domain"] = failure_domain

    # R13 0037-B3: Explicit machine-checked Track-B SHIELD trigger state (ZERO new input fields;
    # requires complete zero-hold evidence across all 7 blocks before classifying SHIELD-1-only vs overall fail!)
    all_comp1_on_target_passed = comp1_on_target_passed_analytes == set(_SHIELD_COMP1_ON_TARGET_ANALYTES)
    all_comp1_off_target_passed = comp1_off_target_passed_controls == set(_SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS)
    comp1_complete_spr_pass = bool(
        hip11_exchange_qc_valid
        and all_comp1_on_target_passed
        and all_comp1_off_target_passed
        and not comp1_spr_bio_fail
    )
    hold_reasons_count = sum(1 for rs in reasons if not rs.startswith("[FAIL]"))
    if (
        worst_state != "FAIL"
        or hold_reasons_count > 0
        or not full_roster_cyto_measured_complete
        or not derived_summary.get("comparator_mandatory_register_coverage_verified")
    ):
        trackb_shield_trigger_state = "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
    elif comp1_complete_spr_pass and comp2_spr_bio_fail and not donor_based_bio_fail:
        trackb_shield_trigger_state = (
            "ELIGIBLE_CANDIDATE_SHIELD1_ONLY_COMP2_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        )
    else:
        trackb_shield_trigger_state = (
            "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        )
    derived_summary["trackb_shield_trigger_state"] = trackb_shield_trigger_state
    derived_summary["trackb_shield_trigger_adjudicator"] = (
        "GATE30_SHIELD_SPR_SOFTWARE_PLUS_GATE30_ATG_XREACT_PASS_PLUS_OWNER_REAUTHORIZATION"
    )
    derived_summary["comp1_complete_spr_pass"] = comp1_complete_spr_pass
    derived_summary["comp1_spr_bio_fail"] = comp1_spr_bio_fail
    derived_summary["comp2_spr_bio_fail"] = comp2_spr_bio_fail
    derived_summary["non_fail_hold_or_invalid_reasons_count"] = hold_reasons_count

    return {
        "gate_id": "GATE_30_SHIELD_SPR",
        "verdict": worst_state,
        "pre_adjudication_nonfinite_rejection": "ValueError",
        "precedence_order": list(_SHIELD_SPR_PRECEDENCE_ORDER),
        "derived_summary": derived_summary,
        "analytes_verified_count": len(analyte_derived),
        "reasons": reasons,
    }


def run_gate30_shield_spr_decision_table_self_tests() -> dict[str, Any]:
    """Verify full typed Gate 30-SHIELD-SPR evidence enforcement, mandatory cryptographically hash-pinned
    outcome-blind pre-registered donor roster & 100% reconciliation (R09 B2), exact distribution-free
    Clopper-Pearson responder-proportion suppression inference & anti-enhancement guard (R09 B3),
    mandatory structured GY-018 independence justification (R09 M1), two-pass order-independent canonical
    key uniqueness across all evidence lists (R08 B3), row-level SPR validity gating (R07 B1),
    construct-bound expression-batch provenance, Comp1+Comp2 off-targets, quantitative SEC-MALS/DLS,
    optional physical 1JK8 policy (omitted & explicit null), mandatory typed T1D donor eligibility
    (R08 B5), qualifying donor HLA, exact GY-018 deff==1.0 preserved as Decimal through JSON decoding
    (R07 B2) & invalid-donor gating, fixed pre-exclusion roster Bonferroni FWER<=0.05 cytotoxicity
    FAIL rule under H0_all: max_i p_i <= 5% (R08 B4 + R09 B2), two-sided CI checks, >1e300 float
    rejection, and 6-level precedence.
    """
    base_pass = build_valid_shield_spr_observation(n_eff_per_donor=60)
    r_pass = evaluate_gate30_shield_spr(base_pass)
    if (
        r_pass["verdict"] != "PASS"
        or r_pass["derived_summary"]["roster_donor_count_n"] != 9
        or r_pass["derived_summary"]["suppression_responder_l95_clopper_pearson_pct"] < 70.0
        or r_pass["derived_summary"]["authorization_grade_fwer_bound_valid"] is not True
    ):
        raise RuntimeError(f"SHIELD-SPR clean 9-donor PASS failed: {r_pass}")

    # 1. Scalar-only summary lacking typed evidence blocks -> HOLD_INVALID_OR_MISSING_INPUT
    c_scalar_only = {
        "n_expression_batches": 3,
        "n_technical_spr_replicates": 3,