scripts/verify_wave7_cellgemma_2p24_rebase.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_wave7_cellgemma_2p24_rebase.py · SHA-256: 5f31a6369f25031d…
for idx, drow in enumerate(drecs):
if not isinstance(drow, Mapping):
fails.append(f"FAIL_GATE_B2_MALFORMED_DONOR_ROW:{idx}"); b2_ok = False; continue
_check_allowed_keys(drow, d_allowed, fails, f"GATE_B2_DONOR_{idx}")
raw_did = drow.get("donor_id")
if not is_nonempty_str(raw_did):
fails.append("FAIL_GATE_B2_UNDERPOWERED_OR_DUPLICATE_DONORS_LT_6"); b2_ok = False; continue
did_n = str(raw_did).strip().upper()
if did_n in seen_d_norm:
fails.append("FAIL_GATE_B2_UNDERPOWERED_OR_DUPLICATE_DONORS_LT_6"); b2_ok = False; continue
seen_d_norm.add(did_n)
# Derived per-donor control validity (no redundant unverified boolean!)
for ck, clo, chi in (
("pos_ctrl_tat_fold", 3.0, 1e6),
("pos_ctrl_c3a_fold", 2.0, 1e6),
("pos_ctrl_plt_drop_pct", 25.0, 100.0),
("neg_ctrl_tat_fold", 0.0, 1.5),
("neg_ctrl_plt_retention_pct", 85.0, 120.0),
):
cv = drow.get(ck)
if not (is_finite_num(cv) and clo <= float(cv) <= chi):
fails.append(f"FAIL_GATE_B2_NUMERIC_DONOR_CONTROL_INVALID:{ck}"); b2_ok = False
tv, tc = drow.get("tat_vehicle_ng_ml"), drow.get("tat_coated_ng_ml")
cv_, cc_ = drow.get("c3a_vehicle_ng_ml"), drow.get("c3a_coated_ng_ml")
pb_, pv_, pc_ = drow.get("platelet_baseline_k_ul"), drow.get("platelet_vehicle_k_ul"), drow.get("platelet_coated_k_ul")
if not (is_finite_num(tv) and is_finite_num(tc) and float(tv) > 0.0 and float(tc) >= 0.0):
fails.append(f"FAIL_GATE_B2_TAT_RAW_VALUES_INVALID:{did_n}"); b2_ok = False
else:
red_t = 100.0 * (float(tv) - float(tc)) / float(tv)
if red_t > 100.0 + 1e-9:
fails.append(f"FAIL_GATE_B2_TAT_REDUCTION_EXCEEDS_100PCT:{did_n}"); b2_ok = False
else:
tat_reds.append(red_t)
if not (is_finite_num(cv_) and is_finite_num(cc_) and float(cv_) > 0.0 and float(cc_) >= 0.0):
fails.append(f"FAIL_GATE_B2_C3A_RAW_VALUES_INVALID:{did_n}"); b2_ok = False
else:
red_c = 100.0 * (float(cv_) - float(cc_)) / float(cv_)
if red_c > 100.0 + 1e-9:
fails.append(f"FAIL_GATE_B2_C3A_REDUCTION_EXCEEDS_100PCT:{did_n}"); b2_ok = False
else:
c3a_reds.append(red_c)
if not (
is_finite_num(pb_) and is_finite_num(pv_) and is_finite_num(pc_)
and float(pb_) > 0.0 and 0.0 <= float(pv_) <= float(pb_) * 1.10 and 0.0 <= float(pc_) <= float(pb_) * 1.10
):
fails.append(f"FAIL_GATE_B2_PLATELET_RAW_VALUES_INVALID:{did_n}"); b2_ok = False
else:
rec_p = 100.0 * (float(pc_) - float(pv_)) / float(pb_)
if not (-100.0 <= rec_p <= 100.0):
fails.append(f"FAIL_GATE_B2_PLATELET_RECOVERY_OUT_OF_BOUNDS:{did_n}"); b2_ok = False
else:
plt_recs.append(rec_p)
nd = len(seen_d_norm)
if is_strict_int(enr_d) and is_strict_int(exc_d):
if (len(drecs) + int(exc_d)) != int(enr_d):
fails.append("FAIL_GATE_B2_DONOR_DENOMINATOR_RECONCILIATION_MISMATCH"); b2_ok = False
if not _validate_structured_exclusions(exc_log, expected_n=int(exc_d), analyzed_ids_norm=seen_d_norm, id_key="donor_id", fails=fails, prefix="GATE_B2"):
b2_ok = False
for ename, vals, min_mean in (
("TAT", tat_reds, 25.0), ("C3A", c3a_reds, 25.0), ("PLATELET", plt_recs, 20.0),
):
if len(vals) == len(drecs) and nd == len(drecs):
stat = paired_t_summary(vals)
if stat is None:
fails.append(f"FAIL_GATE_B2_{ename}_DEGENERATE_VARIANCE"); b2_ok = False
else:
mean_v, _, p_v, l95_v = stat
if mean_v < min_mean or p_v >= 0.05 or l95_v <= 0.0:
fails.append(f"FAIL_GATE_B2_{ename}_PAIRED_DONOR_BENEFIT_FAILED"); b2_ok = False
else:
for j in range(nd):
loo_s = paired_t_summary(vals[:j] + vals[j + 1:])
if loo_s is None or loo_s[3] <= 0.0:
fails.append(f"FAIL_GATE_B2_{ename}_LEAVE_ONE_DONOR_OUT_FRAGILE"); b2_ok = False; break
for ikey, ilo, ihi, icode in (
("iec_sprouting_pct_ctrl", 90.0, 200.0, "FAIL_GATE_B2_IEC_SPROUTING_LT_90PCT"),
("iec_birc5_viability_pct", 90.0, 100.0, "FAIL_GATE_B2_IEC_VIABILITY_LT_90PCT"),
("iec_txnip_fold", 0.0, 1.5, "FAIL_GATE_B2_IEC_TXNIP_GT_1P5"),
("iec_ros_fold", 0.0, 1.2, "FAIL_GATE_B2_IEC_ROS_GT_1P2"),
("iec_cd274_pct_ctrl", 85.0, 200.0, "FAIL_GATE_B2_IEC_CD274_LT_85PCT"),
("iec_hlae_pct_ctrl", 85.0, 200.0, "FAIL_GATE_B2_IEC_HLAE_LT_85PCT"),
("iec_pgf_pct_ctrl", 80.0, 200.0, "FAIL_GATE_B2_IEC_PGF_LT_80PCT"),
("iec_c3_fold_vs_ctrl", 0.0, 1.2, "FAIL_GATE_B2_IEC_C3_GT_1P2"),
):
iv = b2_ev.get(ikey)
if not (is_finite_num(iv) and ilo <= float(iv) <= ihi):
fails.append(icode); b2_ok = False
b2_ledger = b2_ev.get("analytical_sample_ledger")
b2_ledger_map: dict[str, tuple[float, str, str, str, str]] = {}
b2_lkeys = frozenset({"sample_id", "hour_h", "source_stage", "assay_matrix", "recirc_assay_matrix", "biological_unit_id", "raw_analytical_row_sha256"})
if not isinstance(b2_ledger, list) or len(b2_ledger) < 3:
holds.append("HOLD_GATE_B2_MISSING_ANALYTICAL_SAMPLE_LEDGER"); b2_ok = False
else:
for _lrow in b2_ledger:
if (
not isinstance(_lrow, Mapping) or set(_lrow.keys()) != b2_lkeys
or not is_nonempty_str(_lrow.get("sample_id"))
or _lrow.get("assay_matrix") not in REQUIRED_3_MATRICES
or _lrow.get("recirc_assay_matrix") not in REQUIRED_3_MATRICES
or not is_nonempty_str(_lrow.get("biological_unit_id"))
or _lrow.get("source_stage") != "B-2"
or not (is_finite_num(_lrow.get("hour_h")) and float(_lrow["hour_h"]) > 0.0)
or not is_valid_sha256_hex(_lrow.get("raw_analytical_row_sha256"))
):
fails.append("FAIL_GATE_B2_INVALID_ANALYTICAL_SAMPLE_LEDGER"); b2_ok = False; break
_sid = str(_lrow["sample_id"]).strip().upper()
if _sid in b2_ledger_map or _sid in b1_ledger_map:
fails.append("FAIL_GATE_B2_INVALID_ANALYTICAL_SAMPLE_LEDGER"); b2_ok = False; break
b2_ledger_map[_sid] = (float(_lrow["hour_h"]), str(_lrow["raw_analytical_row_sha256"]).lower(), str(_lrow["assay_matrix"]).strip(), str(_lrow["recirc_assay_matrix"]).strip(), str(_lrow["biological_unit_id"]).strip().upper())
else:
b2_ledger_map = {}
b12_combined_ledger: Optional[dict[str, tuple[float, str, str, str, str]]] = ({**b1_ledger_map, **b2_ledger_map} if (b1_ledger_map and b2_ledger_map) else None)
b2b_common_extras = frozenset({
"used_marginal_u95_sum", "alpha_conc", "alpha_fu_parent", "alpha_fu_bmt",
"local_assay_matrix", "recirc_assay_matrix",
"u95_joint_peak_free_nM", "days0_10_parent_lower_free_nM",
"timepoint_replicate_records",
"fu_parent_replicates", "fu_bmt_replicates",
"recirc_fu_bmt_replicates", "alpha_fu_bmt_recirc",
"additional_matrix_calibrations", "common_exposure_basis",
"c_bmt_local_total_u_alloc_nM", "c_bmt_local_free_u_alloc_nM",
"c_bmt_recirc_total_u_alloc_nM", "c_bmt_recirc_free_u_alloc_nM",
"local_measurement_includes_recirculation",
"censoring_audit_passed", "intersample_peak_envelope_justified",
"intersample_pk_envelope",
"systemic_exposure_below_cap", "systemic_kbp_calibration",
"mixture_requalified", "mixture_requalification_receipt",
})
b2bb_ev = _validate_content_receipt(
rec.get("b2b_bench_evidence"),
expected_stage="B-2b-bench", expected_prod=prod_s, expected_bank=bank_s,
expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
expected_coating_identity=coat_id,
expected_parent=b2_ev, min_prereq_receipts=[("B-1", b1_ev), ("B-2", b2_ev)],
allowed_extra_keys=b2b_common_extras,
fails=fails, holds=holds,
missing_hold="HOLD_GATE_B2B_BENCH_MISSING",
fail_code="FAIL_GATE_B2B_BENCH_FAILED",
mismatch_code="FAIL_GATE_B2B_BENCH_SCOPE_MISMATCH",
)
b2bb_ok = False
if b2bb_ev is not None and ec50_u95 is not None and csafe_bench is not None and lloq_parent_map_f is not None and lloq_bmt_map_f is not None and fu_parent_map_f is not None and fu_bmt_map_f is not None:
b2bb_ok = _validate_b2b_exposure_block(
b2bb_ev, ec50_u95=ec50_u95, lloq_parent_by_matrix=lloq_parent_map_f,
lloq_bmt_by_matrix=lloq_bmt_map_f, fu_parent_by_matrix=fu_parent_map_f,
fu_bmt_by_matrix=fu_bmt_map_f, ceiling_l95=csafe_bench,
expected_prod=prod_s, expected_bank=bank_s, expected_lot=lot_s, expected_route=route_s,
expected_scope="bench_unedited", expected_coating_identity=coat_id,
fails=fails, holds=holds, prefix="GATE_B2B_BENCH",
upstream_sample_ledger=b12_combined_ledger,
)
if phase == "BENCH_UNEDITED":
verdict = "FAIL" if fails else ("HOLD" if holds else "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION")
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,
}
# Dedicated measured exact-product cassette ceiling receipt (B-0a-exact) — NOW BINDS COATING_IDENTITY_KEYS + API_BATCH_ID!
b0a_exact_extras = frozenset({
"endpoints_bracketed", "analysis_record_sha256",
"tested_free_conc_grid_nM", "cassette_retention_pct_grid",
"cassette_retention_replicates_by_conc",
"c_safe_max_exact_l95_free_nM",
"exact_cassette_retention_at_csafe_pct", "hour0_density_at_csafe_by_lineage",
})
b0a_ex_ev = _validate_content_receipt(
rec.get("b0a_exact_evidence"),
expected_stage="B-0a-exact", expected_prod=prod_s, expected_bank=bank_s,
expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
expected_coating_identity=coat_id,
expected_parent=mat_ev, min_prereq_receipts=[("B-0a", b0a_ev), ("B-2b-bench", b2bb_ev), ("BANK_MATERIALIZATION", mat_ev)],
allowed_extra_keys=b0a_exact_extras, fails=fails, holds=holds,
missing_hold="HOLD_GATE_B0A_EXACT_CASSETTE_CEILING_MISSING",
fail_code="FAIL_GATE_B0A_EXACT_CASSETTE_CEILING_FAILED",
mismatch_code="FAIL_GATE_B0A_EXACT_SCOPE_MISMATCH",
)
b0a_ex_ok = b0a_ex_ev is not None and b0a_ex_ev.get("verdict") == "PASS"
csafe_exact: Optional[float] = None
if b0a_ex_ev is not None:
if not (is_strict_bool(b0a_ex_ev.get("endpoints_bracketed")) and b0a_ex_ev["endpoints_bracketed"]):
fails.append("FAIL_GATE_B0A_EXACT_ENDPOINTS_UNBRACKETED"); b0a_ex_ok = False
if not is_valid_sha256_hex(b0a_ex_ev.get("analysis_record_sha256")):
fails.append("FAIL_GATE_B0A_EXACT_MISSING_ANALYSIS_RECORD_SHA256"); b0a_ex_ok = False
cse = b0a_ex_ev.get("c_safe_max_exact_l95_free_nM")
ret = b0a_ex_ev.get("exact_cassette_retention_at_csafe_pct")
if not (is_finite_num(cse) and float(cse) > 0.0):
fails.append("FAIL_GATE_B0A_EXACT_INVALID_CSAFE"); b0a_ex_ok = False
else:
csafe_exact = float(cse)
eg_c = b0a_ex_ev.get("tested_free_conc_grid_nM")
eg_r = b0a_ex_ev.get("cassette_retention_pct_grid")
if not (isinstance(eg_c, list) and isinstance(eg_r, list) and len(eg_c) == len(eg_r) and len(eg_c) >= 5 and all(is_finite_num(x) for x in eg_c + eg_r)):
fails.append("FAIL_GATE_B0A_EXACT_MISSING_CONC_RESPONSE_GRID"); b0a_ex_ok = False
else:
cg_e = [float(x) for x in eg_c]
rg_e = [float(x) for x in eg_r]
if cg_e[0] != 0.0 or any(cg_e[i] >= cg_e[i + 1] for i in range(len(cg_e) - 1)) or not (cg_e[1] <= csafe_exact < cg_e[-1]):
fails.append("FAIL_GATE_B0A_EXACT_CSAFE_NOT_BRACKETED_BY_GRID"); b0a_ex_ok = False
else:
creps = b0a_ex_ev.get("cassette_retention_replicates_by_conc")
ex_row_keys = frozenset({"unit_ids", "matched_vehicle_record_id", "technical_replicates_per_unit_pct", "cassette_retention_pct", "raw_unit_measurements"})
if not (isinstance(creps, list) and len(creps) == len(cg_e)):
fails.append("FAIL_GATE_B0A_EXACT_MISSING_CASSETTE_REPLICATES"); b0a_ex_ok = False
elif any(not isinstance(r, Mapping) or not {"unit_ids", "matched_vehicle_record_id"}.issubset(set(r.keys())) for r in creps):
holds.append("HOLD_GATE_B0A_EXACT_MISSING_BIOLOGICAL_UNIT_DENOMINATOR"); b0a_ex_ok = False
elif any(r.get("raw_unit_measurements") is None for r in creps):
holds.append("HOLD_GATE_B0A_EXACT_MISSING_MATCHED_VEHICLE_RAW_DATA"); b0a_ex_ok = False
else:
q_idx_e = -1
ex_first_uids: Optional[list[str]] = None
ex_rows_ok = True
for i_e, rmap_e in enumerate(creps):
if set(rmap_e.keys()) != ex_row_keys or not is_nonempty_str(rmap_e.get("matched_vehicle_record_id")):
fails.append(f"FAIL_GATE_B0A_EXACT_MALFORMED_UNIT_REPLICATES:{i_e}"); ex_rows_ok = False; b0a_ex_ok = False; break
mv_rec_ex = str(rmap_e["matched_vehicle_record_id"]).strip().upper()
raw_ex = rmap_e.get("raw_unit_measurements")
eu_raw = rmap_e.get("unit_ids")
tr_e = rmap_e.get("technical_replicates_per_unit_pct")
arr_e = rmap_e.get("cassette_retention_pct")
if not (isinstance(eu_raw, list) and len(eu_raw) >= 3 and all(is_nonempty_str(u) for u in eu_raw)):
fails.append(f"FAIL_GATE_B0A_EXACT_INVALID_OR_MISMATCHED_UNIT_IDS:{i_e}"); ex_rows_ok = False; b0a_ex_ok = False; break
eu_norm = [str(u).strip().upper() for u in eu_raw]
if len(set(eu_norm)) != len(eu_norm):
fails.append(f"FAIL_GATE_B0A_EXACT_INVALID_OR_MISMATCHED_UNIT_IDS:{i_e}"); ex_rows_ok = False; b0a_ex_ok = False; break
if ex_first_uids is None:
ex_first_uids = eu_norm
elif eu_norm != ex_first_uids:
fails.append(f"FAIL_GATE_B0A_EXACT_INVALID_OR_MISMATCHED_UNIT_IDS:{i_e}"); ex_rows_ok = False; b0a_ex_ok = False; break
if not (
isinstance(arr_e, list) and len(arr_e) == len(eu_norm) and all(is_finite_num(x) for x in arr_e)
and isinstance(tr_e, list) and len(tr_e) == len(eu_norm)
and all(isinstance(tw, list) and len(tw) >= 1 and all(is_finite_num(x) for x in tw) for tw in tr_e)
and isinstance(raw_ex, Mapping) and set(raw_ex.keys()) == {"vehicle_record_id", "treated_by_unit_tech", "vehicle_by_unit_tech"}
and is_nonempty_str(raw_ex.get("vehicle_record_id"))
and str(raw_ex["vehicle_record_id"]).strip().upper() == mv_rec_ex
and isinstance(raw_ex.get("treated_by_unit_tech"), list) and len(raw_ex["treated_by_unit_tech"]) == len(eu_norm)
and isinstance(raw_ex.get("vehicle_by_unit_tech"), list) and len(raw_ex["vehicle_by_unit_tech"]) == len(eu_norm)
and all(
isinstance(raw_ex["treated_by_unit_tech"][uj], list) and isinstance(raw_ex["vehicle_by_unit_tech"][uj], list)
and len(raw_ex["treated_by_unit_tech"][uj]) == len(tr_e[uj]) and len(raw_ex["vehicle_by_unit_tech"][uj]) == len(tr_e[uj])