OpenIslet

scripts/verify_wave7_cellgemma_2p24_rebase.py

Wave-7 CellGemma-Islet (IIP-0062 to IIP-0065 / GATE-40 to GATE-43) Pure-CPU

script Release v0.8.0 gen-eb955f8266035aba 1.37 MB · 90 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_wave7_cellgemma_2p24_rebase.py · SHA-256: 5f31a6369f25031d…

                fails.append("FAIL_GATE_B4_INVIVO_PARENT_FLOOR_BELOW_EC50")
            if float(iv_sys) >= 0.5:
                fails.append("FAIL_GATE_B4_INVIVO_SYSTEMIC_PLASMA_GE_0P5NM")
        _validate_matched_control_switch_parity(
            b4_ev.get("matched_control_switch_parity_evidence"),
            expected_control_lot_id=blank_veh_40, fails=fails, holds=holds, prefix="GATE_B4",
        )
        if not (b0a_ok and b0b_ok and b1_ok and b2_ok and b2bb_ok and b0a_ex_ok and b2be_ok and b3_ok):
            fails.append("FAIL_GATE_B4_ATTEMPTED_WITHOUT_ALL_PREDECESSORS")

    if fails:
        verdict = "FAIL"
    elif holds:
        verdict = "HOLD"
    elif scope_track == "PRIMARY":
        verdict = OFFLINE_VERDICT_PRIMARY
    elif scope_track == "SENSITIVITY_Z_R3P":
        verdict = "SENSITIVITY_TRACK_ONLY_NON_PRIMARY"
    elif scope_track == "SEPARATE_ROUTE4_VEHICLE":
        verdict = "SEPARATE_ROUTE4_VEHICLE_TRACK_NON_PRIMARY"
    else:
        verdict = "DEFERRED_TRACK_QUALIFICATION_NON_PRIMARY"

    return {
        "gate": "GATE-41", "phase": phase, "scope_track": scope_track, "verdict": verdict,
        "release_authorizing": False, "live_ledger_authenticated": False,
        "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
        "product_id": rec.get("product_id"),
        "required_switch": spec["required_switch"] if spec else None,
        "failures": fails, "holds": holds,
    }


# ---------------------------------------------------------------------------
# GATE-42 (IIP-0064 / DEC-145): 100% Drug-Free GY-032 Channel c Transient Screen
# ---------------------------------------------------------------------------

GATE42_ALLOWED_KEYS: FrozenSet[str] = frozenset({
    "target_arm", "product_id", "bank_id", "lot_id", "route_id",
    "drug_free_exposure_evidence", "materialization_evidence", "gate31_evidence",
    "foundry_v2_gate36_evidence",
    "native_switch_evidence", "gate0v_evidence",
    "zero_fasta_minted", "iip0049_foundry_attribution_evidence", "target_gene",
    "c1_preregistered_plan_receipt", "c1_evidence", "c2_evidence", "c3_nk_evidence", "c3_gsis_evidence",
})

REQUIRED_IIP0049_REFERENCE_BACKGROUNDS: FrozenSet[str] = frozenset({
    "PARENTAL_UNEDITED",
    "DESIGN_A_CHASSIS_REFERENCE",
    "MULTI_MIR_IL1R1_FAS_REFERENCE",
    "STANDALONE_IL1R1_FAS_CBE_REFERENCE",
    "CD64T_IL1RN_REFERENCE",
})

C1_FAMILY_GENES: FrozenSet[str] = frozenset({"BCL2L11", "PMAIP1", "PMAIP1+BCL2L11", "BBC3", "JAK2"})

C1_OXYGEN_ALLOWED_KEYS: FrozenSet[str] = frozenset({
    "assay_record_id", "assay_acquired_at_utc", "block_ids",
    "differentiation_batch_ids", "randomized_arm_orders_by_block", "target_kd_pct",
    "mrna_kd_pct", "protein_kd_pct", "mrna_assay_record_id", "protein_assay_record_id", "molecular_kd_provenance",
    "pmaip1_kd_pct", "bcl2l11_kd_pct",
    "pmaip1_mrna_kd_pct", "pmaip1_protein_kd_pct", "bcl2l11_mrna_kd_pct", "bcl2l11_protein_kd_pct",
    "casp9_stressed_ctrl_raw_by_block", "casp9_treated_raw_by_block",
    "casp9_reduction_pct_by_block", "family_raw_p_values_casp9", "holm_adjusted_casp9_p_value",
    "stressed_ctrl_beta_plated_t0_by_block", "stressed_ctrl_beta_surviving_by_block",
    "treated_beta_plated_t0_by_block", "treated_beta_surviving_by_block",
    "unstressed_vehicle_beta_plated_t0_by_block", "unstressed_vehicle_beta_surviving_by_block",
    "stressed_ctrl_beta_t0_pct_by_block", "treated_beta_t0_pct_by_block",
    "unstressed_vehicle_beta_t0_pct_by_block", "family_raw_p_values_beta", "holm_adjusted_beta_p_value",
    "all_five_arms_paired_data", "normality_diagnostic_record",
    "bcl2l11_comparator_beta_t0_pct_by_block", "head_to_head_vs_bcl2l11_l95_delta_pp",
    "gy001_cxcl10_inducible_shield_pct_ctrl",
    "nonbeta_lineage_min_surv_pct_ctrl", "stressed_ctrl_nonbeta_t0_survival_pct",
    "t0_original_plated_denominators_used", "pmlkl_flag_triggered",
    "gy016_nec1s_gsk872_orthogonal_rescue_cleared",
    "lineage_timecourse_counts", "death_pathway_diversion_assay",
    "mock_transfection_control_by_block",
})

C1_REQUIRED_5_LINEAGES: FrozenSet[str] = frozenset({
    "INS_beta", "GCG_alpha", "SST_delta", "PLVAP_iEC", "pericyte_stromal",
})


def _validate_transient_engagement_record(
    rec_obj: Optional[Mapping[str, Any]],
    *,
    target_gene: str,
    expected_cohort_id: Optional[str],
    expected_lot_id: Optional[str],
    expected_specimen_id: Optional[str],
    min_stage_ts: Optional[datetime],
    required_start_ts: Optional[datetime],
    required_end_ts: Optional[datetime],
    stage_tag: str,
    fails: list[str],
    holds: list[str],
    require_longitudinal_mode: bool = False,
    required_covering_ts: Sequence[datetime] = (),
) -> None:
    """Verify paired start+end OR longitudinal producer-linked target engagement
    spans the ENTIRE [assay_started, assay_completed] window on the exact specimen (requiring validated longitudinal
    timepoints spanning 0 h / 24 h / 72 h on 72-h safety switches), cleanly distinguishing missing temporal coverage
    from biological recovery/decay!"""
    if rec_obj is None:
        return
    eng = rec_obj.get("transient_target_engagement_record")
    if eng is None:
        holds.append(f"HOLD_GATE_C_MISSING_TRANSIENT_ENGAGEMENT_RECORD:{stage_tag}"); return
    if not isinstance(eng, Mapping):
        fails.append(f"FAIL_GATE_C_MALFORMED_TRANSIENT_ENGAGEMENT_RECORD:{stage_tag}"); return
    emode = eng.get("engagement_measurement_mode")
    if require_longitudinal_mode and emode != "VALIDATED_LONGITUDINAL_KINETICS":
        fails.append(f"FAIL_GATE_C_SAFETY_SWITCH_REQUIRES_VALIDATED_LONGITUDINAL_KINETICS:{stage_tag}"); return
    req_k = {
        "intervention_cohort_id", "stage_name", "specimen_lot_id", "specimen_id",
        "engagement_measurement_mode",
        "start_aliquot_assay_record_id", "end_aliquot_assay_record_id",
        "assay_window_start_utc", "assay_window_end_utc",
        "start_measured_at_utc", "end_measured_at_utc",
        "start_of_window_kd_pct", "end_of_window_kd_pct",
        "target_kd_pct", "recovered_to_control", "engagement_record_sha256",
    }
    if target_gene == "PMAIP1+BCL2L11":
        req_k |= {"pmaip1_start_kd_pct", "pmaip1_end_kd_pct", "bcl2l11_start_kd_pct", "bcl2l11_end_kd_pct"}
    if emode == "VALIDATED_LONGITUDINAL_KINETICS":
        req_k |= {"validated_kinetics_protocol_sha256", "longitudinal_kinetics_timepoints"}
    if set(eng.keys()) != req_k:
        fails.append(f"FAIL_GATE_C_MALFORMED_TRANSIENT_ENGAGEMENT_RECORD:{stage_tag}"); return
    esha = eng.get("engagement_record_sha256")
    s_aid = eng.get("start_aliquot_assay_record_id")
    e_aid = eng.get("end_aliquot_assay_record_id")
    t_ws = parse_utc_iso_ts(eng.get("assay_window_start_utc"))
    t_we = parse_utc_iso_ts(eng.get("assay_window_end_utc"))
    t_sm = parse_utc_iso_ts(eng.get("start_measured_at_utc"))
    t_em = parse_utc_iso_ts(eng.get("end_measured_at_utc"))
    t_rec = parse_utc_iso_ts(rec_obj.get("recorded_at_utc"))
    kd_st = eng.get("start_of_window_kd_pct")
    kd_en = eng.get("end_of_window_kd_pct")
    kd_min = eng.get("target_kd_pct")
    if (
        not is_valid_sha256_hex(esha)
        or sha256_bytes(canonical_json_bytes({k: v for k, v in eng.items() if k != "engagement_record_sha256"})) != str(esha)
        or emode not in ("PAIRED_START_AND_END_ALIQUOT_ASSAY", "VALIDATED_LONGITUDINAL_KINETICS")
        or not is_nonempty_str(s_aid) or not is_nonempty_str(e_aid)
        or not is_nonempty_str(eng.get("intervention_cohort_id"))
        or (expected_cohort_id is not None and str(eng["intervention_cohort_id"]).strip() != expected_cohort_id)
        or eng.get("stage_name") != stage_tag
        or not is_nonempty_str(eng.get("specimen_lot_id"))
        or (expected_lot_id is not None and str(eng["specimen_lot_id"]).strip() != expected_lot_id)
        or not is_nonempty_str(eng.get("specimen_id"))
        or (expected_specimen_id is not None and str(eng["specimen_id"]).strip() != expected_specimen_id)
        or t_ws is None or t_we is None or t_sm is None or t_em is None
        or t_ws > t_sm or t_sm > t_em or t_em > t_we
        or (t_we > t_ws and str(s_aid).strip().upper() == str(e_aid).strip().upper())
        or (t_rec is not None and t_we > t_rec)
        or (min_stage_ts is not None and t_ws < min_stage_ts)
        or (required_start_ts is not None and t_ws > required_start_ts)
        or (required_end_ts is not None and t_we < required_end_ts)
        or not is_strict_bool(eng.get("recovered_to_control"))
        or not (is_finite_num(kd_st) and is_finite_num(kd_en) and is_finite_num(kd_min))
    ):
        fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
    all_kd_vals = [float(kd_st), float(kd_en)]
    all_dual_vals: list[float] = []
    if target_gene == "PMAIP1+BCL2L11":
        for dk in ("pmaip1_start_kd_pct", "pmaip1_end_kd_pct", "bcl2l11_start_kd_pct", "bcl2l11_end_kd_pct"):
            if not is_finite_num(eng.get(dk)):
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            all_dual_vals.append(float(eng[dk]))
    t_ks: list[datetime] = []
    if emode == "VALIDATED_LONGITUDINAL_KINETICS":
        if not is_valid_sha256_hex(eng.get("validated_kinetics_protocol_sha256")):
            fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
        ltps = eng.get("longitudinal_kinetics_timepoints")
        tp_req_k = {
            "aliquot_assay_record_id", "specimen_lot_id", "specimen_id",
            "producer_record_sha256", "measured_at_utc", "target_kd_pct",
        }
        if target_gene == "PMAIP1+BCL2L11":
            tp_req_k |= {"pmaip1_kd_pct", "bcl2l11_kd_pct"}
        if not isinstance(ltps, list) or len(ltps) < 3:
            fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
        seen_t_aids: set[str] = set()
        tp_kds: list[float] = []
        for t_idx, trow in enumerate(ltps):
            if not isinstance(trow, Mapping) or set(trow.keys()) != tp_req_k:
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            taid = trow.get("aliquot_assay_record_id")
            tts = parse_utc_iso_ts(trow.get("measured_at_utc"))
            tkd = trow.get("target_kd_pct")
            tlot = trow.get("specimen_lot_id")
            tsp = trow.get("specimen_id")
            tpsha = trow.get("producer_record_sha256")
            if (
                not is_nonempty_str(taid) or tts is None or not is_finite_num(tkd)
                or not is_nonempty_str(tlot) or not is_nonempty_str(tsp)
                or not is_valid_sha256_hex(tpsha)
                or (expected_lot_id is not None and str(tlot).strip() != expected_lot_id)
                or (expected_specimen_id is not None and str(tsp).strip() != expected_specimen_id)
            ):
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            taid_n = str(taid).strip().upper()
            if taid_n in seen_t_aids:
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            seen_t_aids.add(taid_n)
            if t_ks and (tts <= t_ks[-1] or (tts - t_ks[-1]).total_seconds() > 48.0 * 3600.0 + 1e-6):
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            t_ks.append(tts)
            tp_kds.append(float(tkd))
            if target_gene == "PMAIP1+BCL2L11":
                if not (is_finite_num(trow.get("pmaip1_kd_pct")) and is_finite_num(trow.get("bcl2l11_kd_pct"))):
                    fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
                all_dual_vals.extend([float(trow["pmaip1_kd_pct"]), float(trow["bcl2l11_kd_pct"])])
        if (
            str(ltps[0]["aliquot_assay_record_id"]).strip().upper() != str(s_aid).strip().upper()
            or str(ltps[-1]["aliquot_assay_record_id"]).strip().upper() != str(e_aid).strip().upper()
            or t_ks[0] != t_sm or t_ks[-1] != t_em
            or abs(tp_kds[0] - float(kd_st)) > 1e-6 or abs(tp_kds[-1] - float(kd_en)) > 1e-6
        ):
            fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
        all_kd_vals.extend(tp_kds)
    if abs(float(kd_min) - min(all_kd_vals)) > 1e-6:
        fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
    # Distinct temporal-coverage HOLDs anchored strictly to ACTUAL assay boundaries (never hidden by a wide declared window!)
    if required_start_ts is not None:
        if require_longitudinal_mode:
            # Must have a producer-bound start observation at actual assay t=0 within [-1.0 h, +0.5 h] AND t_sm <= assay_start + 0.5 h
            if (t_sm - required_start_ts).total_seconds() > 1800.0 + 1e-6 or (required_start_ts - t_sm).total_seconds() > 7200.0 + 1e-6:
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:{stage_tag}"); return
            if not any(-3600.0 - 1e-6 <= (tk - required_start_ts).total_seconds() <= 1800.0 + 1e-6 for tk in t_ks):
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:{stage_tag}"); return
        else:
            if (t_sm - required_start_ts).total_seconds() > 3600.0 + 1e-6:
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:{stage_tag}"); return
    if (t_sm - t_ws).total_seconds() > 86400.0 + 1e-6:
        holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:{stage_tag}"); return
    if required_end_ts is not None:
        if require_longitudinal_mode:
            if (required_end_ts - t_em).total_seconds() > 3600.0 + 1e-6:
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:{stage_tag}"); return
            if not any(abs((tk - required_end_ts).total_seconds()) <= 3600.0 + 1e-6 for tk in t_ks):
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:{stage_tag}"); return
        else:
            if (required_end_ts - t_em).total_seconds() > 3600.0 + 1e-6:
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:{stage_tag}"); return
    if (t_we - t_em).total_seconds() > 86400.0 + 1e-6:
        holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:{stage_tag}"); return
    if emode == "VALIDATED_LONGITUDINAL_KINETICS":
        for t_cov in required_covering_ts: