OpenIslet

scripts/verify_cellgemma_islet_v0_1.py

Standalone Zero-GPU / Pure-CPU Fail-Closed Verifier for OpenIslet CellGemma-Islet v0.9.0.

script Release v0.8.0 gen-eb955f8266035aba 77 KB · 6 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_cellgemma_islet_v0_1.py · SHA-256: 31b99284adcaabe1…

    cols_b_upa = _md_cells(_find_single_line(draft_texts["B"], "| **Upadacitinib**", "Draft B"), "Draft B Upadacitinib")
    require(cols_b_bar[1].count("NR (<0.05)") >= 2 and cols_b_upa[1].count("NR (<0.05)") >= 2, "Draft B unreported F3/SERPINE1 cell must tag NR (<0.05) twice")
    require(f"{bar_s1b['vascular_rescue_score']:+.4f}" in cols_b_bar[2] and f"{bar_s1b['pre_iec_safety_score']:+.4f}" in cols_b_bar[2], "Draft B Baricitinib S1B cell mismatch")
    require(f"{bar_gzmb['s1_norm_rank']:+.3f}" in cols_b_bar[4] and f"{bar_gzmb['s2_lfc']:+.3f}" in cols_b_bar[4], "Draft B Baricitinib NK GZMB cell mismatch")
    require(f"{upa_s1b['vascular_rescue_score']:+.4f}" in cols_b_upa[2] and f"{upa_s1b['pre_iec_safety_score']:+.4f}" in cols_b_upa[2], "Draft B Upadacitinib S1B cell mismatch")

    # Draft C: MAP3K7 stressed self_kd (-0.321 in Col 3) + BCL2L11/PMAIP1/BBC3/JAK2 promoted scalars
    s2 = ev["screen2_beta_stressed_and_resting"]
    s2r = ev["screen2_resting_h3_top6_followup"]
    map3k7_skd = s2["BETA_CM_STRESSED_CRISPRI__MAP3K7"]["extra"]["self_kd_s1_norm_rank"]
    cols_c_map = _md_cells(_find_single_line(draft_texts["C"], "| **`MAP3K7`**", "Draft C"), "Draft C MAP3K7")
    require(f"{map3k7_skd:+.3f}" in cols_c_map[3], f"Draft C MAP3K7 Col 3 stressed self_kd mismatch (expected {map3k7_skd:+.3f})")

    bim_s_imm = s2["BETA_CM_STRESSED_CRISPRI__BCL2L11"]["panels"]["immune_chemokine_mhc_bad"]["nonzero_panel_genes"]
    bim_r_imm = s2r["BETA_RESTING_CRISPRI__BCL2L11"]["panels"]["immune_chemokine_mhc_bad"]["nonzero_panel_genes"]
    cols_c_bim = _md_cells(_find_single_line(draft_texts["C"], "| **`BCL2L11`**", "Draft C"), "Draft C BCL2L11")
    require(
        f"HLA-E {bim_s_imm['HLA-E']['s1_norm_rank']:+.3f}" in cols_c_bim[4]
        and f"HLA-C {bim_s_imm['HLA-C']['s1_norm_rank']:+.3f}" in cols_c_bim[4]
        and f"HLA-E {bim_r_imm['HLA-E']['s1_norm_rank']:+.3f}" in cols_c_bim[4]
        and f"HLA-C {bim_r_imm['HLA-C']['s1_norm_rank']:+.3f}" in cols_c_bim[4]
        and f"HLA-B {bim_r_imm['HLA-B']['s1_norm_rank']:+.3f}" in cols_c_bim[4],
        "Draft C BCL2L11 Col 4 HLA-E/HLA-C/HLA-B watch-item scalar mismatch",
    )

    noxa_s_imm = s2["BETA_CM_STRESSED_CRISPRI__PMAIP1"]["panels"]["immune_chemokine_mhc_bad"]["nonzero_panel_genes"]
    noxa_r_imm = s2r["BETA_RESTING_CRISPRI__PMAIP1"]["panels"]["immune_chemokine_mhc_bad"]["nonzero_panel_genes"]
    cols_c_noxa = _md_cells(_find_single_line(draft_texts["C"], "| **`PMAIP1`**", "Draft C"), "Draft C PMAIP1")
    require(
        f"HLA-C {noxa_s_imm['HLA-C']['s1_norm_rank']:+.3f}" in cols_c_noxa[4]
        and f"HLA-E {noxa_s_imm['HLA-E']['s1_norm_rank']:+.3f}" in cols_c_noxa[4]
        and f"HLA-B {noxa_r_imm['HLA-B']['s1_norm_rank']:+.3f}" in cols_c_noxa[4]
        and f"HLA-C {noxa_r_imm['HLA-C']['s1_norm_rank']:+.3f}" in cols_c_noxa[4]
        and f"HLA-E {noxa_r_imm['HLA-E']['s1_norm_rank']:+.3f}" in cols_c_noxa[4],
        "Draft C PMAIP1 Col 4 HLA-B/HLA-C/HLA-E watch-item scalar mismatch",
    )

    bbc3_r = s2r["BETA_RESTING_CRISPRI__BBC3"]
    cols_c_bbc3 = _md_cells(_find_single_line(draft_texts["C"], "| **`BBC3`**", "Draft C"), "Draft C BBC3")
    require(
        f"{bbc3_r['composite']['ring1_safety_score']:+.4f}" in cols_c_bbc3[2]
        and f"{bbc3_r['panels']['identity_gsis_good']['mean_s1_norm_rank']:+.4f}" in cols_c_bbc3[2],
        "Draft C BBC3 Col 2 resting ring1_safety/identity_mean mismatch",
    )

    # Verify Draft C stressed immune_bad composite share disclosures directly from receipt
    for g, marker in (("PMAIP1", "78.3%"), ("JAK2", "95.8%"), ("BCL2L11", "193.4%")):
        st = s2[f"BETA_CM_STRESSED_CRISPRI__{g}"]
        share = 100.0 * (-st["panels"]["immune_chemokine_mhc_bad"]["mean_s1_norm_rank"]) / st["composite"]["h3_bystander_rescue_score"]
        require(f"{share:.1f}%" == marker and marker in draft_texts["C"], f"Draft C {g} immune_bad share mismatch ({share:.1f}%)")

    # Draft D: PVR resting self_kd (-0.466 in Col 3) and TNFRSF1A stressed self_kd (-0.227 in Col 3)
    pvr_rkd = s2["BETA_RESTING_CRISPRI__PVR"]["extra"]["self_kd_s1_norm_rank"]
    tnf_skd = s2["BETA_CM_STRESSED_CRISPRI__TNFRSF1A"]["extra"]["self_kd_s1_norm_rank"]
    cols_d_pvr = _md_cells(_find_single_line(draft_texts["D"], "| **`PVR` (`CD155`)**", "Draft D"), "Draft D PVR")
    cols_d_tnf = _md_cells(_find_single_line(draft_texts["D"], "| **`STAT1` & `TNFRSF1A`**", "Draft D"), "Draft D STAT1/TNFRSF1A")
    require(f"{pvr_rkd:+.3f}" in cols_d_pvr[3], f"Draft D PVR Col 3 resting self_kd mismatch (expected {pvr_rkd:+.3f})")
    require(f"{tnf_skd:+.3f}" in cols_d_tnf[3], f"Draft D TNFRSF1A Col 3 stressed self_kd mismatch (expected {tnf_skd:+.3f})")


def verify_local_sources(receipt: dict[str, Any], project_root: Path) -> None:
    """Explicit local-source mode: open every file in source_file_sha256_manifest, verify bytes & SHA-256, and cross-check NCBI snapshot."""
    src_man = receipt["source_file_sha256_manifest"]
    for rel, meta in src_man.items():
        fp = project_root / rel
        require(fp.is_file(), f"Missing local source file: {rel}")
        data = fp.read_bytes()
        require(len(data) == meta["bytes"], f"Byte size mismatch for {rel}: {len(data)} != {meta['bytes']}")
        got_sha = hashlib.sha256(data).hexdigest()
        require(got_sha == meta["sha256"], f"SHA-256 mismatch for {rel}: {got_sha} != {meta['sha256']}")

    snap_rel = receipt["claim_to_source_map"]["snapshot_file_relpath"]
    snap = load_strict_json((project_root / snap_rel).read_text(encoding="utf-8"))
    snap_recs = snap["records"]
    for pmid, reg_rec in receipt["verified_pubmed_registry"].items():
        require(pmid in snap_recs, f"PMID {pmid} missing from authoritative snapshot {snap_rel}")
        sr = snap_recs[pmid]
        require(reg_rec["title"] == sr["title"].strip(), f"Title mismatch vs NCBI snapshot for PMID:{pmid}")
        require(reg_rec["doi"] == sr["doi"], f"DOI mismatch vs NCBI snapshot for PMID:{pmid}")
        require(reg_rec["journal"] == sr["journal"], f"Journal mismatch vs NCBI snapshot for PMID:{pmid}")
        require(reg_rec["pubtypes_ncbi"] == sr["pubtypes_ncbi"], f"pubtypes_ncbi mismatch for PMID:{pmid}")


def main() -> None:
    ap = argparse.ArgumentParser(description="Fail-closed zero-GPU verifier for CellGemma-Islet v0.9.0.")
    ap.add_argument(
        "--verify-local-sources",
        action="store_true",
        help="Rehash all 31 local files listed in source_file_sha256_manifest relative to the parent directory and cross-check all 60 dated NLM snapshot records.",
    )
    args = ap.parse_args()

    require(RECEIPT_PATH.is_file(), f"Missing receipt file {RECEIPT_PATH}")
    patterns = _build_portable_preflight_hygiene_patterns()

    # 1. Strict JSON + nonfinite guard + exact payload & file SHA-256
    raw_bytes = RECEIPT_PATH.read_bytes()
    receipt_file_sha = hashlib.sha256(raw_bytes).hexdigest()
    raw_text = raw_bytes.decode("utf-8")
    receipt = load_strict_json(raw_text)

    claimed_sha = receipt["portable_payload_sha256"]
    payload_no_hash = {k: v for k, v in receipt.items() if k != "portable_payload_sha256"}
    canon = json.dumps(payload_no_hash, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
    actual_sha = hashlib.sha256(canon.encode("utf-8")).hexdigest()
    require(actual_sha == claimed_sha, f"Payload SHA-256 mismatch: {actual_sha} != {claimed_sha}")
    require(receipt["schema_version"] == "openislet.cellgemma_islet_provenance.v0.9.0", "Unexpected schema_version")
    print(f"[PASS 1/10] Strict JSON + nonfinite guard + SHA-256 verified (payload={actual_sha[:16]}..., file={receipt_file_sha[:16]}...)")

    # 2. Fixed host-independent portable preflight hygiene across ALL 6 runtime inputs + 31-file manifest syntax / optional local rehash
    check_public_hygiene(raw_text, RECEIPT_PATH.name, patterns)
    check_decoded_json_hygiene(receipt, f"{RECEIPT_PATH.name}:decoded", patterns)
    check_public_hygiene(VERIFIER_PATH.read_text(encoding="utf-8"), VERIFIER_PATH.name, patterns)
    draft_texts: dict[str, str] = {}
    for did, fname in IIP_DRAFT_FILES.items():
        dp = (HERE / fname) if (HERE / fname).is_file() else (HERE.parent / "docs" / fname)
        require(dp.is_file(), f"Missing draft file {fname}")
        txt = dp.read_text(encoding="utf-8")
        check_public_hygiene(txt, fname, patterns)
        draft_texts[did] = txt
    require(receipt["evidence_tier"] == "cellgemma_e4b_in_silico_prior", "Unexpected evidence_tier")
    require(receipt["live_headline_delta_pp_today"] == 0.0, "live_headline_delta_pp_today must be 0.0")
    src_man = receipt["source_file_sha256_manifest"]
    require(len(src_man) == 31, f"Expected 31 listed local dependencies in manifest, got {len(src_man)}")
    for req_dep in (
        "STEP0_PREREGISTERED_BENCHMARK_PLAN.md",
        "build_cellgemma_islet_receipt.py",
        "processed/gse254985_d20276_full.npz",
        "processed/gse254985_d20276_full_summary.json",
        "tmp_pubmed/ncbi_60_authoritative_snapshot.json",
    ):
        require(req_dep in src_man, f"Missing required dependency in source_file_sha256_manifest: {req_dep}")
    for rel_k, meta in src_man.items():
        require(bool(re.fullmatch(r"[0-9a-f]{64}", meta["sha256"])), f"Invalid source SHA-256 syntax for {rel_k}")
        require(isinstance(meta["bytes"], int) and meta["bytes"] > 0, f"Invalid byte size for {rel_k}")
    if args.verify_local_sources:
        verify_local_sources(receipt, HERE.parent)
        print("[PASS 2/10] Host-independent preflight hygiene (6/6 inputs + decoded JSON) AND local-source rehash verified (31/31 listed files + 60/60 dated NLM snapshot parity)")
    else:
        print("[PASS 2/10] Host-independent preflight hygiene passed on 6/6 inputs (incl. verifier + decoded JSON) + 31-file manifest syntax checked (pass --verify-local-sources to rehash listed files)")

    # 3. Track-specific falsifying Step-0 G1 checks (T1 >=0.25/0.25; T2 >=0.15/0.20), 3x1 vs 5x3, 8/8 RQC targets in Draft C, & summed embedded per-file cap counts
    s0 = receipt["step0_benchmark_audit"]
    require(sum(s0["generation_count_breakdown"].values()) == s0["total_benchmark_and_phase1_generations"] == 534, "Generation count mismatch")
    gsp = s0["generation_evidence_split"]
    require(gsp["per_draw_truncated_gene_array_backed_in_raw_jsons"] == 498 and gsp["author_recorded_summary_without_per_draw_arrays"] == 36, "Generation split mismatch")
    gcap = s0["generation_cap_and_truncation_audit"]
    by_rf = gcap["by_raw_file"]
    s0_cap_sum = sum(v["capped_runs"] for k, v in by_rf.items() if k.startswith("step0_"))
    s0_tot_sum = sum(v["total_runs_with_token_counts"] for k, v in by_rf.items() if k.startswith("step0_"))
    p1_cap_sum = sum(v["capped_runs"] for k, v in by_rf.items() if k.startswith("phase1_"))
    p1_tot_sum = sum(v["total_runs_with_token_counts"] for k, v in by_rf.items() if k.startswith("phase1_"))
    require([s0_cap_sum, s0_tot_sum] == gcap["step0_4096_token_cap_hits"] == [142, 147], "Embedded per-file Step-0 cap sum mismatch")
    require([p1_cap_sum, p1_tot_sum] == gcap["phase1_retained_3072_token_cap_hits"] == [272, 351], "Embedded per-file Phase-1 cap sum mismatch")
    require(gcap["phase1_unknown_stopping_reason_runs"] == 36, "Unknown stopping-reason count mismatch")
    bf16 = s0["bf16_vs_mlx8_parity_receipt"]
    require(bf16["evidence_status"] == "author_recorded_summary_without_per_draw_portable_arrays", "BF16 evidence status missing")
    dv = s0["domain_verdicts"]
    p5_dv = dv["pure_human_islet_endothelium_p5_ifng"]
    require(p5_dv["status"] == "PASS_DIRECTIONAL_MICROBENCHMARK" and p5_dv["n_fdr05_genes_in_p5_summary"] == 0, "Pure P5 metadata mismatch")
    require(p5_dv["regime4"]["top100_roc_auc_s2"] >= 0.90 and p5_dv["regime1"]["top100_roc_auc_s2"] < 0.70, "P5 R4/R1 contrast missing")
    c1_beta = dv["beta_alpha_multi_cytokine_and_synergy_c1"]["gse254985_beta_cm"]
    flex_dv = dv["tenx_flex_probe_capture_endocrine"]
    flex_6_keys = ("gse237448_beta_ifng", "gse237448_beta_il1b", "gse237448_beta_il1bifng", "gse237448_beta_cm", "gse237448_beta_bfa", "gse237448_beta_tg")
    flex_6_mean_r = sum(flex_dv[k]["pearson_r_r4"] for k in flex_6_keys) / 6.0
    flex_6_mean_nr = sum(flex_dv[k]["nr_vs_b1_r4"] for k in flex_6_keys) / 6.0
    rqc_dv = dv["endoc_bh1_3p_crispri_zero_leakage"]
    rec_g1 = rqc_dv["preregistered_g1_reconciliation"]
    require(
        rec_g1["preregistered_input_pseudobulks"] == 5
        and rec_g1["preregistered_stochastic_draws_per_pseudobulk"] == 3
        and rec_g1["preregistered_generations_per_condition_per_regime"] == 15
        and rec_g1["executed_input_pseudobulks"] == 3
        and rec_g1["executed_stochastic_draws_per_pseudobulk"] == 1
        and rec_g1["executed_generations_per_condition_per_regime"] == 3,
        "5x3 -> 3x1 sampling-plan deviation fields mismatch",
    )
    require(rec_g1["superseding_preregistration_issued"] is False, "superseding_preregistration_issued must be False")
    rqc_targets_raw = {k.split("__")[-1]: v["pearson_r_r4"] for k, v in rqc_dv["all_8_rqc_targets"].items()}
    rqc_nr_raw = [v["nr_vs_b1_r4"] for v in rqc_dv["all_8_rqc_targets"].values()]
    require(len(rqc_targets_raw) == 8, "Expected 8 evaluated RQC targets")
    t1_r, t1_nr, t1_b3a = c1_beta["pearson_r_r4"], c1_beta["nr_vs_b1_r4"], c1_beta["b3a_r"]
    t2_mean_r = sum(rqc_targets_raw.values()) / 8.0
    t2_mean_nr = sum(rqc_nr_raw) / 8.0
    t1_r_floor = rec_g1["preregistered_track1_g1_pearson_floor"]
    t1_nr_floor = rec_g1["preregistered_track1_g1_norm_recovery_floor"]
    t2_r_floor = rec_g1["preregistered_track2_g1_pearson_floor"]
    t2_nr_floor = rec_g1["preregistered_track2_g1_norm_recovery_floor"]
    require(abs(t1_r_floor - 0.25) <= 1e-12 and abs(t1_nr_floor - 0.25) <= 1e-12, "Track-1 locked G1 floors must be 0.25/0.25")
    require(abs(t2_r_floor - 0.15) <= 1e-12 and abs(t2_nr_floor - 0.20) <= 1e-12, "Track-2 locked G1 floors must be 0.15/0.20")
    require(abs(t1_r - rec_g1["track1_post_cutoff_beta_cm_r4_pearson_r"]) <= 1e-6, "Track-1 beta CM r mismatch")
    require(abs(t1_nr - rec_g1["track1_post_cutoff_beta_cm_r4_norm_recovery"]) <= 1e-6, "Track-1 beta CM norm_recovery mismatch")
    require(abs(t1_b3a - rec_g1["track1_post_cutoff_beta_cm_b3a_naive_mean_shift_r"]) <= 1e-6, "Track-1 B3a mismatch")
    require(abs(flex_6_mean_r - rec_g1["track1_flex_6cond_beta_r4_mean_pearson_r"]) <= 1e-6, "Track-1 6-cond Flex mean r mismatch")
    require(abs(flex_6_mean_nr - rec_g1["track1_flex_6cond_beta_r4_mean_norm_recovery"]) <= 1e-6, "Track-1 6-cond Flex mean nr mismatch")
    require(abs(t2_mean_r - rec_g1["all_8_rqc_r4_mean_pearson_r"]) <= 1e-6, "RQC 8-target mean r mismatch")
    require(abs(t2_mean_nr - rec_g1["all_8_rqc_r4_mean_norm_recovery"]) <= 1e-5, "RQC 8-target mean norm_recovery mismatch")
    # Track-specific necessary G1 conditions (plan:159): Track 1 requires >=0.25/0.25 on post-cutoff CM AND 6-cond aggregate (separately checking G3 r < B3a); Track 2 requires >=0.15/0.20
    derived_t1_g1_necessary = (t1_r >= t1_r_floor) and (t1_nr >= t1_nr_floor) and (flex_6_mean_r >= t1_r_floor) and (flex_6_mean_nr >= t1_nr_floor)
    derived_t1_g3_beats_b3a = t1_r > t1_b3a
    derived_t2_g1_necessary = (t2_mean_r >= t2_r_floor) and (t2_mean_nr >= t2_nr_floor)
    derived_hard_stop = (not derived_t1_g1_necessary) and (not derived_t2_g1_necessary)
    require(derived_t1_g1_necessary is False and derived_t1_g3_beats_b3a is False and rec_g1["track1_cleared_preregistered_g1"] is False, "Track-1 necessary G1/G3 falsification mismatch")
    require(derived_t2_g1_necessary is False and rec_g1["cleared_preregistered_g1_floor"] is False, "Track-2 necessary G1 falsification mismatch")
    require(derived_hard_stop is True and rec_g1["hard_stop_triggered_under_locked_plan"] is True, "Derived Step-0 hard-stop mismatch")
    for tg, rv in sorted(rqc_targets_raw.items()):
        require(abs(rec_g1["evaluated_8_rqc_r4_pearson_by_target"][tg] - rv) <= 1e-4, f"RQC target {tg} map mismatch")
        tok = f"`{tg} {rv:+.4f}`"
        require(tok in draft_texts["C"], f"Draft C missing verified RQC target/score token {tok}")
    require(dv["beta_alpha_multi_cytokine_and_synergy_c1"]["status"] == "KILLED" and flex_dv["status"] == "KILLED", "Hard-kill check failed")
    print("[PASS 3/10] Track-specific Step-0 G1 falsifiers (T1 0.25/0.25, T2 0.15/0.20, 3x1 vs 5x3), 8/8 RQC targets in Draft C, & embedded per-file cap sums (142/147, 272/351, 36 unknown) verified")

    # 4. Panel-gene (S1 + S2 + n_up/n_down) & composite checks across ALL 139 evaluations (120 4-decimal NPZ + 19 thresholded raw-JSON residual accounting)
    scoring_panels = receipt["scoring_panels"]
    tot = {
        "n": 0,
        "full_vec": 0,
        "thresh": 0,
        "full_genes": 0,
        "thresh_panels": 0,
        "thresh_s1_nz": 0,
        "thresh_s2_nz": 0,
        "thresh_prof_s1_nz": 0,
        "thresh_prof_s2_nz": 0,
    }
    for grp_name, grp in receipt["phase1_frozen_evaluations"].items():
        for item_name, item in grp.items():
            c = check_item_full(f"{grp_name}:{item_name}", item, scoring_panels)
            tot["n"] += 1
            for k in ("full_vec", "thresh", "full_genes", "thresh_panels", "thresh_s1_nz", "thresh_s2_nz", "thresh_prof_s1_nz", "thresh_prof_s2_nz"):
                tot[k] += c[k]
    cov = receipt["panel_evidence_coverage_audit"]
    require(tot["n"] == cov["total_profiles"] == 139, f"Expected 139 profiles, got {tot['n']}")
    require(tot["full_vec"] == cov["exact_full_vector_profiles"] == 120, "Full-vector count mismatch")
    require(tot["full_genes"] == cov["exact_full_vector_nonzero_panel_genes"] == 6263, "Full-vector gene count mismatch")
    require(tot["thresh"] == cov["thresholded_raw_json_profiles"] == 19, "Thresholded profile count mismatch")
    require(tot["thresh_panels"] == cov["thresholded_raw_json_panels_total"] == cov["thresholded_raw_json_panels_flagged_unverifiable_below_0p05"] == 70, "Thresholded flagged panel count mismatch")
    require(tot["thresh_s1_nz"] == cov["thresholded_raw_json_panels_with_nonzero_s1_residual"] == 46 and tot["thresh_prof_s1_nz"] == cov["thresholded_raw_json_profiles_with_nonzero_s1_residual"] == 17, "Nonzero S1 residual count mismatch")