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…
id_key: str,
fails: list[str],
prefix: str,
require_arm: bool = False,
require_timing_and_ae: bool = False,
forbid_adverse_event_related: bool = False,
min_ts: Optional[datetime] = None,
max_ts: Optional[datetime] = None,
) -> bool:
"""Validate structured exclusion records (no nulls, allowed reason, pre-adjudication, timing, AE linkage, disjoint IDs)."""
if not isinstance(excl_log, list) or len(excl_log) != expected_n:
fails.append(f"FAIL_{prefix}_EXCLUSION_LOG_LENGTH_MISMATCH"); return False
ok = True
seen_exc: set[str] = set()
allowed = frozenset({id_key, "reason", "pre_adjudication_decision"})
if require_arm:
allowed = allowed | frozenset({"arm"})
if require_timing_and_ae:
allowed = allowed | frozenset({"excluded_at_utc", "adverse_event_related", "adverse_event_code"})
for idx, erow in enumerate(excl_log):
if not isinstance(erow, Mapping):
fails.append(f"FAIL_{prefix}_MALFORMED_OR_NULL_EXCLUSION_ROW:{idx}"); ok = False; continue
_check_allowed_keys(erow, allowed, fails, f"{prefix}_EXCL_{idx}")
raw_id = erow.get(id_key)
if not is_nonempty_str(raw_id):
fails.append(f"FAIL_{prefix}_EXCLUSION_MISSING_ID:{idx}"); ok = False; continue
nid = str(raw_id).strip().upper()
if nid in seen_exc or nid in analyzed_ids_norm:
fails.append(f"FAIL_{prefix}_EXCLUSION_DUPLICATE_OR_OVERLAPPING_ID:{nid}"); ok = False
seen_exc.add(nid)
if erow.get("reason") not in ALLOWED_EXCLUSION_REASONS:
fails.append(f"FAIL_{prefix}_EXCLUSION_UNALLOWED_REASON:{nid}"); ok = False
if not (is_strict_bool(erow.get("pre_adjudication_decision")) and erow["pre_adjudication_decision"]):
fails.append(f"FAIL_{prefix}_EXCLUSION_NOT_PRE_ADJUDICATED:{nid}"); ok = False
if require_arm and erow.get("arm") not in ("COATED", "BLANK_VEHICLE"):
fails.append(f"FAIL_{prefix}_EXCLUSION_INVALID_ARM:{nid}"); ok = False
if require_timing_and_ae:
t_ex = parse_utc_iso_ts(erow.get("excluded_at_utc"))
if t_ex is None or (min_ts is not None and t_ex < min_ts) or (max_ts is not None and t_ex > max_ts):
fails.append(f"FAIL_{prefix}_EXCLUSION_TIMESTAMP_INVALID:{nid}"); ok = False
ae_rel = erow.get("adverse_event_related")
ae_code = erow.get("adverse_event_code")
if not is_strict_bool(ae_rel) or not is_nonempty_str(ae_code):
fails.append(f"FAIL_{prefix}_EXCLUSION_MISSING_AE_LINKAGE:{nid}"); ok = False
elif ae_rel is True:
if str(ae_code).strip().upper() == "NONE":
fails.append(f"FAIL_{prefix}_EXCLUSION_AE_TRUE_REQUIRES_NON_NONE_CODE:{nid}"); ok = False
if forbid_adverse_event_related:
fails.append(f"FAIL_{prefix}_ADVERSE_EVENT_RELATED_EXCLUSION:{nid}"); ok = False
return ok
def _extract_and_validate_coating_identity(
ev: Mapping[str, Any],
*,
expected: Optional[Mapping[str, str]],
fails: list[str],
stage: str,
) -> Optional[dict[str, str]]:
"""Verify shared coating article, formulation revision, coating lot, blank vehicle, exposure protocol, & API batch."""
out: dict[str, str] = {}
for k in sorted(COATING_IDENTITY_KEYS):
v = ev.get(k)
if not is_nonempty_str(v):
fails.append(f"FAIL_{stage}_MISSING_COATING_IDENTITY:{k}")
return None
out[k] = str(v).strip()
if out["coating_lot_id"] == out["matched_blank_vehicle_lot_id"]:
fails.append(f"FAIL_{stage}_COATING_AND_BLANK_VEHICLE_LOT_IDENTICAL")
if expected is not None:
for k, exp_v in expected.items():
if out.get(k) != exp_v:
fails.append(f"FAIL_{stage}_COATING_IDENTITY_MISMATCH:{k}")
return out
def _validate_oq012_gate34_clonogenic_block(
ev: Any,
*,
fails: list[str],
holds: list[str],
prefix: str,
) -> bool:
"""
Canonical GATE-34 / OQ-012 rare-escape clonogenic switch block:
- strict integer survivors_k == 0
- strict integer raw_cells_tested (1 <= n <= 1e12)
- measured clonogenic_fraction_f in (0, 1] and detection_efficiency_eta in [0.30, 1.0]
(missing recovery terms -> HOLD)
- strict integer effective_trials_n_eff <= floor(raw_cells_tested * f * eta)
- n_eff >= 299,573,228 (underpowered -> HOLD)
- regrowth_assay_verified == True
- exact 75-digit Decimal U95(0, n_eff) <= 1e-8 reconciled against clonogenic_escape_u95
"""
if not isinstance(ev, Mapping):
holds.append(f"HOLD_{prefix}_OQ012_BLOCK_MISSING")
return False
allowed = frozenset({
"survivors_k", "raw_cells_tested", "clonogenic_fraction_f",
"detection_efficiency_eta", "effective_trials_n_eff",
"regrowth_assay_verified", "clonogenic_escape_u95",
})
_check_allowed_keys(ev, allowed, fails, f"{prefix}_OQ012")
k = ev.get("survivors_k")
raw_n = ev.get("raw_cells_tested")
f_clon = ev.get("clonogenic_fraction_f")
eta = ev.get("detection_efficiency_eta")
n_eff = ev.get("effective_trials_n_eff")
regrowth = ev.get("regrowth_assay_verified")
u95_sub = ev.get("clonogenic_escape_u95")
ok = True
if not is_strict_int(k) or int(k) < 0:
fails.append(f"FAIL_{prefix}_OQ012_INVALID_SURVIVOR_COUNT"); return False
if int(k) > 0:
fails.append(f"FAIL_{prefix}_OQ012_NONZERO_SURVIVORS"); ok = False
if not is_strict_int(raw_n) or not (1 <= int(raw_n) <= MAX_CLONOGENIC_CELLS):
fails.append(f"FAIL_{prefix}_OQ012_INVALID_RAW_CELLS_TESTED"); return False
if not is_strict_bool(regrowth) or not regrowth:
fails.append(f"FAIL_{prefix}_OQ012_REGROWTH_ASSAY_UNVERIFIED"); ok = False
f_dec = _to_exact_decimal(f_clon)
eta_dec = _to_exact_decimal(eta)
if f_dec is None or eta_dec is None:
holds.append(f"HOLD_{prefix}_OQ012_INCOMPLETE_RECOVERY_DENOMINATOR"); return False
if not (Decimal(0) < f_dec <= Decimal(1)):
fails.append(f"FAIL_{prefix}_OQ012_CLONOGENIC_FRACTION_OUT_OF_RANGE"); return False
if not (Decimal("0.30") <= eta_dec <= Decimal(1)):
fails.append(f"FAIL_{prefix}_OQ012_DETECTION_ETA_OUT_OF_RANGE"); return False
if not is_strict_int(n_eff) or int(n_eff) < 1:
fails.append(f"FAIL_{prefix}_OQ012_INVALID_INTEGER_EFFECTIVE_TRIALS"); return False
# Exact rational product before flooring (eliminates ambient 28-digit Decimal rounding drift at boundary!)
max_n_eff = math.floor(Fraction(int(raw_n)) * Fraction(f_dec) * Fraction(eta_dec))
if int(n_eff) > max_n_eff:
fails.append(f"FAIL_{prefix}_OQ012_NEFF_EXCEEDS_FLOOR_N_F_ETA"); return False
if int(n_eff) < GATE5_OQ012_MIN_EFFECTIVE_TRIALS:
holds.append(f"HOLD_{prefix}_OQ012_UNDERPOWERED_NEFF_LT_299573228"); return False
u95_dec = recompute_clopper_pearson_u95_decimal_n_eff(int(n_eff))
sub_dec = _to_exact_decimal(u95_sub)
if sub_dec is None or abs(sub_dec - u95_dec) > Decimal("1e-12"):
fails.append(f"FAIL_{prefix}_OQ012_U95_MISMATCH_VS_EXACT_DECIMAL"); ok = False
if u95_dec > Decimal("1e-8"):
fails.append(f"FAIL_{prefix}_OQ012_U95_EXCEEDS_1E_8"); ok = False
return ok
def _validate_matched_control_switch_parity(
parity_ev: Any,
*,
expected_control_lot_id: Optional[str],
fails: list[str],
holds: list[str],
prefix: str,
) -> bool:
"""
Content-hashed, data-backed matched-control native safety-switch non-inferiority block
(supersedes bare Boolean switch-parity checkboxes across GATE-40 A-3, GATE-41 B-4, GATE-42, GATE-43):
- Bound to comparator_control_lot_id (matched NT or blank-vehicle lot)
- Raw paired 24-h AND 72-h bulk-kill vectors (n >= 6 blocks)
- Recomputes exact paired Student-t one-sided 95% lower bound L95(treated - control):
L95_24h >= -0.05 pp AND L95_72h >= -0.01 pp
- Reconciles reported l95_24h_pp / l95_72h_pp against recomputed values
- Requires valid matched control OQ-012 block (confirming control arm kill assay operated cleanly)
"""
if parity_ev is None:
holds.append(f"HOLD_{prefix}_MATCHED_CONTROL_SWITCH_PARITY_MISSING")
return False
if not isinstance(parity_ev, Mapping):
fails.append(f"FAIL_{prefix}_MATCHED_CONTROL_SWITCH_PARITY_MALFORMED")
return False
allowed = frozenset({
"receipt_sha256", "comparator_control_lot_id", "block_ids",
"treated_24h_kill_pct_by_block", "control_24h_kill_pct_by_block",
"treated_72h_kill_pct_by_block", "control_72h_kill_pct_by_block",
"reported_l95_24h_delta_pp", "reported_l95_72h_delta_pp",
"control_oq012_clonogenic_block",
})
_check_allowed_keys(parity_ev, allowed, fails, f"{prefix}_SW_PARITY")
ok = True
rsha = parity_ev.get("receipt_sha256")
if not is_valid_sha256_hex(rsha) or compute_receipt_sha256(parity_ev) != rsha:
fails.append(f"FAIL_{prefix}_SW_PARITY_CONTENT_HASH_TAMPER"); ok = False
cid = str(parity_ev.get("comparator_control_lot_id", "")).strip()
if not cid or (expected_control_lot_id is not None and cid != expected_control_lot_id):
fails.append(f"FAIL_{prefix}_SW_PARITY_COMPARATOR_LOT_MISMATCH"); ok = False
bids = parity_ev.get("block_ids")
if not (isinstance(bids, list) and len(bids) >= 6 and all(is_nonempty_str(b) for b in bids) and len(set(str(b).strip().upper() for b in bids)) == len(bids)):
fails.append(f"FAIL_{prefix}_SW_PARITY_BLOCKS_LT_6_OR_DUPLICATE"); return False
n = len(bids)
for tag_h, tk, ck, rk, margin in (
("24H", "treated_24h_kill_pct_by_block", "control_24h_kill_pct_by_block", "reported_l95_24h_delta_pp", -0.05),
("72H", "treated_72h_kill_pct_by_block", "control_72h_kill_pct_by_block", "reported_l95_72h_delta_pp", -0.01),
):
tv = parity_ev.get(tk)
cv = parity_ev.get(ck)
rv = parity_ev.get(rk)
if not (isinstance(tv, list) and isinstance(cv, list) and len(tv) == n and len(cv) == n and all(is_finite_num(x) and 0.0 <= float(x) <= 100.0 for x in tv + cv)):
fails.append(f"FAIL_{prefix}_SW_PARITY_{tag_h}_VECTORS_INVALID"); ok = False; continue
diffs = [float(tv[i]) - float(cv[i]) for i in range(n)]
st = paired_t_summary(diffs)
if st is None:
# All-equal zero-variance diffs: L95 equals exact mean diff if mean >= margin
l95_calc = diffs[0]
else:
l95_calc = st[3]
if not is_finite_num(rv) or abs(float(rv) - l95_calc) > 1e-4:
fails.append(f"FAIL_{prefix}_SW_PARITY_{tag_h}_L95_MISMATCH"); ok = False
if l95_calc < margin:
fails.append(f"FAIL_{prefix}_SW_PARITY_{tag_h}_NONINFERIORITY_MARGIN_FAILED"); ok = False
if not _validate_oq012_gate34_clonogenic_block(parity_ev.get("control_oq012_clonogenic_block"), fails=fails, holds=holds, prefix=f"{prefix}_CTRL"):
ok = False
return ok
def _validate_content_receipt(
ev: Any,
*,
expected_stage: str,
expected_prod: Optional[str],
expected_bank: Optional[str],
expected_lot: Optional[str],
expected_route: Optional[str],
forbid_route: bool = False,
expected_scope: Optional[str] = None,
expected_candidate_gene: Optional[str] = None,
expected_comparator_nt_lot_id: Optional[str] = None,
expected_coating_identity: Optional[Mapping[str, str]] = None,
expected_parent: Optional[Mapping[str, Any]] = None,
min_prereq_receipts: Sequence[tuple[str, Optional[Mapping[str, Any]]]] = (),
allowed_extra_keys: FrozenSet[str] = frozenset(),
fails: list[str],
holds: list[str],
missing_hold: str,
fail_code: str,
mismatch_code: str,
) -> Optional[Mapping[str, Any]]:
if ev is None:
holds.append(missing_hold)
return None
if not isinstance(ev, Mapping):
fails.append(f"{mismatch_code}_MALFORMED")
return None
base_keys = frozenset({
"stage", "verdict", "receipt_sha256", "recorded_at_utc",
"product_id", "bank_id", "lot_id", "route_id", "evidence_scope",
"parent_receipt_sha256", "prerequisite_receipt_sha256s",
"candidate_gene", "comparator_nt_lot_id",