raise ValueError( f"Typed cell external_ref mismatch on {pvid}:{gid}: got {cell['external_ref']!r}, expected {exp_ext_ref!r}" ) # Enforce fail-closed missing_data_disposition (MUST start with HOLD_ on all 45 cells, NEVER PASS!) mdd = cell["missing_data_disposition"] if not mdd.startswith("HOLD_") or re.search(r"\bPASS\b", mdd, re.IGNORECASE): raise ValueError( f"Typed cell missing_data_disposition must be fail-closed HOLD_* (never PASS) on {pvid}:{gid}: {mdd!r}" ) # Enforce exact full-string threshold equality on ALL 45 cells (no extra smuggled conflicting thresholds!) if cell["threshold"] != exp_thr: raise ValueError( f"Typed cell threshold exact-equality violation on {pvid}:{gid}: " f"got {cell['threshold']!r}, expected {exp_thr!r}" ) # 5. Contradiction guards across ALL controlling texts, typed cells, and registry records rules_dict = dec114_blk.get("rules") or {} dt_rules_blob = "\n".join(str(rules_dict.get(k) or "") for k in sorted(rules_dict)) pb_clean = pb_sec_full.replace("`", "") forbidden_patterns = ( (r"k==0_unconditional_veto", "ambiguous k==0_unconditional_veto shorthand"), (r"3,701 bp", "CHK-19 forbidden '3,701 bp' comma literal"), (r"n_eff\s*=\s*floor\(", "forbidden floor(n_raw*eta) approximation"), (r"(?i)bare\s+boolean\s+is\s+sufficient", "prohibited bare-boolean Gate 0V claim"), ) all_checked_texts: List[tuple[str, str]] = [ ("decision_tree.rules", dt_rules_blob), ("playbook.sec4120", pb_clean), ] for (cpvid, cgid), cobj in sorted(cell_map.items()): all_checked_texts.append((f"typed_cell.{cpvid}:{cgid}", json.dumps(cobj, ensure_ascii=False))) for pvid in sorted(pc.STAGED_D1B_AUTO_V2_PRODUCT_IDS): all_checked_texts.append((f"registry.{pvid}", json.dumps(by_id[pvid], ensure_ascii=False))) for dlabel, dtxt in all_checked_texts: for pat, desc in forbidden_patterns: if re.search(pat, dtxt): raise ValueError(f"Contradiction guard tripped ({desc}) in {dlabel}") # 6. Direct semantic predicate concordance checked across BOTH typed cells AND decision-tree rules AND Playbook s4.1.20 AND full-product registry! # ZERO skipped predicates (pre-empting job-18 Caveat #2)! shared_predicates: List[tuple[str, str, str, str]] = [ ("D1-01_sp3c4c_exclusion", "D1-01", r"exclude_SP3C_SP4C_C07_C17_C1801_homozygotes_and_compound_heterozygotes", r"SP-3C/SP-4C[^\n]{0,160}C\*18:01[^\n]{0,160}compound\s+heterozygotes"), ("D1-02_offgrid_guard_011_thresholds", "D1-02", r"min_mm_to_HLAC_E_valid_range_0_to_25;wt_hlac_retention_pct>=99\.0;bystander_ct_pct<0\.5;chr6p21_interlocus_del_pct==0\.0", r"OFFGRID_GUARD_011[^\n]{0,200}>=\s*99\.0%[^\n]{0,120}<\s*0\.5%[^\n]{0,120}0\.0%"), ("D1-03_chrm_1000x_and_1pct", "D1-03", r"chrm_numt_amplicon_depth_x>=1000\.0;chrm_novel_nonsyn_het_pct<1\.0", r">=\s*1,000x\s+NUMT-filtered\s+chrM[^\n]{0,160}<\s*1\.0%"), ("D1-04_htmpk_leak_elispot_azt", "D1-04", r"G0_beta_htmpk_leak_pct<=0\.1;hlac07_ryafsgvay_elispot_above_bg_pct<=0\.1;.*azt_kill_measured_after_forced_chr19_loss==True;AZT_dividing_log10_kill>=4\.0", r"<=\s*0\.1%[^\n]{0,140}RYAFSGVAY[^\n]{0,40}<=\s*0\.1%[^\n]{0,160}>=\s*4\.0-log10"), ("D1-04_ap1903_explicit_k_ge_1_and_299573226", "D1-04", r"AP1903_k>=1_is_FAIL_HARD_STOP;AP1903_k==0_exact_80digit_sound_Decimal_U95<=1\.0e-8\(math_count_subgate_only:exact_binomial_N_eff=299573226_PASS_vs_299573225_HOLD;Poisson_ceiling=299573228\)", r"k\s*>=\s*1\s+is\s+FAIL_HARD_STOP[^\n]{0,160}<=\s*1\.0e-8[^\n]{0,480}299,573,226[^\n]{0,60}299,573,225\s+HOLD"), ("D1-05_per_locus_l3_l4_and_fsp1", "D1-05", r"L3_stage7_day28_retention_pct>=80\.0;L4_stage7_day28_retention_pct>=80\.0;min_L3_L4_stage7_day28_retention_pct>=80\.0;RSL3_fsp1_ferroptosis_survival_pct>=80\.0", r">=\s*80\.0%[^\n]{0,140}min\(L3,\s*L4\)\s*>=\s*80\.0%[^\n]{0,120}RSL3[^\n]{0,100}>=\s*80\.0%"), ("D1-06_kir3dl1_nk_8pct", "D1-06", r"kir3dl1_missing_bw4_autologous_nk_lysis_pct<=8\.0", r"KIR3DL1\+[^\n]{0,100}<=\s*8\.0%"), ("D1-07_vtcn1_shedding_10pct", "D1-07", r"vtcn1_nrd1_soluble_sb7h4_shedding_pct<=10\.0", r"VTCN1/NRD1[^\n]{0,100}<=\s*10\.0%"), ("D1-08_hlac0304_c5b9_explicit_k_ge_1_and_59_vs_58", "D1-08", r"d1_08_patient_carries_hlac0304_bool_or_derived_from_patient_hla_c_alleles\(omitted_derives_from_raw_alleles_requiring_both_alleles_in_23_allele_Lin2023_Table1_inventory_for_negative_derivation;contradiction_FAIL;null_or_UNAVAILABLE_or_unlisted_allele_blocks_negative_derivation_HOLD\);if_C0304_pos:hlac0304_positive_control_valid==True_and_HLAC0304_assay;if_C0304_neg:matched_allele_positive_control_valid==True_and_matched_allele_cd8_screen_passed==True;HLAC0304_k>=1_is_FAIL_HARD_STOP;HLAC0304_k==0_exact_80digit_sound_Decimal_U95<=5\.0%;T1D_serum_C5b9_k>=1_is_FAIL_HARD_STOP;T1D_serum_C5b9_k==0_exact_80digit_sound_Decimal_U95<=5\.0%\(math_count_subgate_only:N=59_PASS_4\.9508%_vs_N=58_HOLD_5\.0340%_conservative_ceiling\)", r"HLA-C\*03:04[^\n]{0,520}C5b-9[^\n]{0,180}k\s*>=\s*1\s+is\s+FAIL_HARD_STOP[^\n]{0,200}<=\s*5\.0%[^\n]{0,280}N\s*=\s*59[^\n]{0,80}4\.9508%[^\n]{0,60}N\s*=\s*58\s+HOLD[^\n]{0,60}5\.0340%"), ("D1-09_turnaround_41_weeks", "D1-09", r"autologous_sequential_6locus_gmp_turnaround_weeks<=41\.0", r"<=\s*41\.0\s*weeks"), ] l1b_specific_predicates: List[tuple[str, str, str, str]] = [ ("D1-09_l1b_lot_matched_gate0v_record", "D1-09", r"structured_global_gate0v_record_required_with_mcb_lot_id==evaluated_lot_id;Gate0V_day14_log10_reduction>=3\.0;Gate0V_day14_log10_reduction_l95>=3\.0;Gate0V_cvb4_72h_early_titer_log10_pfu_u95<=2\.0;Gate0V_day28_VP1_IE1_k>=1_is_FAIL_HARD_STOP;Gate0V_day28_VP1_IE1_k==0_U95<=0\.0005\(n>=5990\);Gate0V_verdict==PASS;never_bare_caller_boolean", r"global_gate0v_record[^\n]{0,140}mcb_lot_id[^\n]{0,220}>=\s*3\.0-log10[^\n]{0,340}<=\s*0\.0005[^\n]{0,60}>=\s*5,990[^\n]{0,80}gate0v_verdict\s*==\s*\"?PASS\"?[^\n]{0,120}bare\s+caller\s+boolean"), ] for doc_name, blob in (("decision_tree.rules", dt_rules_blob), ("playbook.sec4120", pb_clean)): for pred_name, _gid, _cell_pat, prose_pat in shared_predicates + l1b_specific_predicates: if not re.search(prose_pat, blob): raise ValueError(f"Typed predicate parity failure ({pred_name}) in {doc_name}") product_summaries: List[Dict[str, Any]] = [] for pvid in sorted(pc.STAGED_D1B_AUTO_V2_PRODUCT_IDS): prod = by_id[pvid] bind = prod["staged_d1b_auto_v2_donor_binding"] role = str(bind["role"]) gates_txt = " ".join(prod.get("pending_assay_gates") or []) if pvid == "ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN": for pred_name, gid, cell_pat, prose_pat in shared_predicates: if not re.search(cell_pat, cell_map[(pvid, gid)]["threshold"]): raise ValueError(f"Typed cell threshold semantic mismatch ({pred_name}) on {pvid}:{gid}") if not re.search(prose_pat, gates_txt): raise ValueError(f"Registry predicate mismatch ({pred_name}) on {pvid}") elif pvid == "ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR": for pred_name, gid, cell_pat, prose_pat in shared_predicates + l1b_specific_predicates: if not re.search(cell_pat, cell_map[(pvid, gid)]["threshold"]): raise ValueError(f"Typed cell threshold semantic mismatch ({pred_name}) on {pvid}:{gid}") if not re.search(prose_pat, gates_txt): raise ValueError(f"Registry predicate mismatch ({pred_name}) on {pvid}") else: if "COMPONENT_ONLY_EXCLUDED_FROM_FULLSTACK_CLEARANCE" not in gates_txt: raise ValueError(f"Component donor {pvid} pending_assay_gates must declare COMPONENT_ONLY_EXCLUDED_FROM_FULLSTACK_CLEARANCE") if "Not encoded by this standalone" not in str((prod.get("hla_retention") or {}).get("classical_MHC_I") or ""): raise ValueError(f"Component donor {pvid} must distinguish encoded payload from intended host genotype") for gid in sorted(COMPONENT_APPLICABLE_GATES[pvid]): if "EXCLUDED_FROM_FULLSTACK_CLEARANCE" not in cell_map[(pvid, gid)]["threshold"]: raise ValueError(f"Component cell {pvid}:{gid} missing EXCLUDED_FROM_FULLSTACK_CLEARANCE marker") product_summaries.append({ "product_variant_id": pvid, "role": role, "fullstack_clearance_eligible": pvid in D1B_FULLSTACK_CANDIDATE_IDS, "gate_dispositions": {g: cell_map[(pvid, g)]["disposition"] for g in EXPECTED_45_GATES}, "typed_cell_operators_and_thresholds_verified": True, "registry_predicates_verified_against_typed_contract": True, }) audit = { "registry_loaded_via_product_contract": True, "dec114_decision_tree_sha256_verified": dec114_sha, "dec114_playbook_sec4120_sha256_verified": pb_sha, "playbook_commonmark_parser": { "rendered_4120_headings_found": len(matched_4120), "heading_kind": h4120["kind"], "heading_level": h4120["level"], "container_depth": h4120["container_depth"], "headings_up_to_sec4120": sum(1 for h in all_headings if h["start_offset"] <= h4120["start_offset"]), }, "typed_product_by_gate_contract_audit": { "products_checked": len(product_summaries), "gates_per_product": len(EXPECTED_45_GATES), "cells_verified": len(cell_map), "contradiction_guards_passed": len(forbidden_patterns), "shared_predicates_verified_zero_skipped": len(shared_predicates), "l1b_specific_predicates_verified_zero_skipped": len(l1b_specific_predicates), "product_gate_matrix": product_summaries, }, "staged_fasta_sha256_verified": pc.D1B_AUTO_V2_FASTA_SHA256, "staged_d1b_auto_v2_record_count": len(pc.STAGED_D1B_AUTO_V2_PRODUCT_IDS), "resolved_fullstack_candidate_ids": resolved_fullstack_ids, "resolved_excluded_component_ids": resolved_excluded_ids, "resolved_d1b_auto_v2_routes_from_registry": sorted(resolved_route_codes), "author_declared_sequence_motif_metadata_note": ( "Sequence motif tallies (0 introns, 0x 2A, 0 uATG, 0 foreign peptides) are author-declared staging " "metadata on the product definitions and are not independently recomputed by this verifier." ), } return audit, by_id def _verify_protected_lims_and_frozen_artifacts(repo_root: Path) -> Dict[str, Any]: """Verify exact 0-byte-diff SHA-256 invariance of the 3 protected LIMS files & frozen IIP-0034/Pareto artifacts.""" lims_verified: Dict[str, Dict[str, Any]] = {} for rel, exp_sha in sorted(PROTECTED_LIMS_SHA256.items()): fp = repo_root / rel if not fp.is_file(): raise ValueError(f"Missing protected LIMS file for 0-byte invariance verification: {fp}") raw = fp.read_bytes() got_sha = hashlib.sha256(raw).hexdigest() if got_sha != exp_sha: raise ValueError(f"Protected LIMS file {rel} mutated: found SHA-256 {got_sha}, expected {exp_sha}") lims_verified[rel] = {"sha256": got_sha, "bytes": len(raw), "zero_byte_diff_verified": True} ct = _load_json_strict(repo_root / "data" / "protocols" / "wetlab_endpoint_contract_v0.8.0.json") lims_counts = { "stage0_decision_tree_endpoints": len(ct.get("stage0_decision_tree_endpoints", [])), "metadata_keys": len(ct.get("metadata_keys", [])), "boolean_policy_keys": len(ct.get("boolean_policy_keys", [])), } if (lims_counts["stage0_decision_tree_endpoints"], lims_counts["metadata_keys"], lims_counts["boolean_policy_keys"]) != (366, 77, 122): raise ValueError(f"Protected LIMS contract counts drifted from 366/77/122: {lims_counts}") frozen_checks: Dict[str, str] = {} for rel, exp_sha in ( (PARETO_REL_PATH, EXPECTED_PARETO_SHA256), (FROZEN_IIP0034_PORTFOLIO_REL_PATH, EXPECTED_IIP0034_PORTFOLIO_SHA256), (FROZEN_IIP0034_VERIF_REL_PATH, EXPECTED_IIP0034_VERIF_SHA256), ): fp = repo_root / rel if not fp.is_file(): raise ValueError(f"Missing frozen artifact for invariance verification: {fp}") got_sha = hashlib.sha256(fp.read_bytes()).hexdigest() if got_sha != exp_sha: raise ValueError(f"Frozen artifact {rel} drifted: found SHA-256 {got_sha}, expected {exp_sha}") frozen_checks[rel] = got_sha return { "protected_lims_files_zero_byte_diff": lims_verified, "protected_lims_contract_counts_unchanged": lims_counts, "frozen_upstream_artifacts_sha256_verified": frozen_checks, } def compute_full_verification(repo_root: Path | None = None) -> Dict[str, Any]: active_root = ROOT if repo_root is None else Path(repo_root) registry_audit, by_id = _resolve_and_verify_d1b_auto_v2_registry(active_root) rare_event_and_gate_audit = compute_rare_event_and_gate_matrix_audit(by_id, repo_root=active_root) invariance_audit = _verify_protected_lims_and_frozen_artifacts(active_root) # Independent replay of the 5-arm autologous portfolio artifact via rank_islet1_stacks p5 = rank_mod.compute_5arm_autologous_portfolio_iip0035(repo_root=active_root) wavec_4 = list(p5.get("stage0_gated_4arm_autologous_d1b_auto_v2", [])) wavebc_5 = list(p5.get("stage0_gated_5arm_unified_waveBC_portfolio", [])) phi_c_cex = list(p5.get("stage0_gated_5arm_phi_c_sensitivity_counterexamples", [])) if len(wavec_4) != 11 or len(wavebc_5) != 12 or len(phi_c_cex) != 2: raise ValueError( f"Unexpected 5-arm portfolio row counts: wavec_4={len(wavec_4)}, wavebc_5={len(wavebc_5)}, phi_c_cex={len(phi_c_cex)}" ) all_new_rows = wavec_4 + wavebc_5 + phi_c_cex max_4096_err = max(float(r["incumbent_4096_state_max_abs_err"]) for r in all_new_rows) if not math.isfinite(max_4096_err) or max_4096_err > 1e-12: raise ValueError(f"4,096-state incumbent parity violation: {max_4096_err}") alias_map = p5.get("scenario_alias_deduplication_map") or {} if float(alias_map.get("alias_full_joint_state_max_abs_diff", 1.0)) > 1e-12: raise ValueError(f"1,048,576-state alias verification exceeded 1e-12: {alias_map}") # Inadmissible diagonal self-check (unhardened A/B/X barred from R3P -> 0.0% survival) pa = (0.88, 0.78, 0.57, 0.69) pb = (0.88, 0.79, 0.64, 0.70) px = (0.88, 0.82, 0.73, 0.69) c_base = (0.88, 0.87, 0.89, 0.85) live = rank_mod.compute_common_shock_2pow12_portfolio_tree(pa, pb, px, c_base) inadm_diag = rank_mod._run_dp_and_verify_parity_iip0034( "IIP0035_INADMISSIBLE_DIAGONAL_SELF_CHECK", [pa, pb, px], rank_mod._live_canonical_incumbent_dists_iip0034(), list(c_base), float(live["locked_2route_shared_ax_pouch_exact"]), float(live["modular_2route_shared_ax_pouch_exact"]), math.prod(c_base), stage0_status="SELF_CHECK_INADMISSIBLE_DIAGONAL", cell_classes=("UNHARDENED_A_B_X", "UNHARDENED_A_B_X", "UNHARDENED_A_B_X"), route_ids=("R3P", "R3P", "R3P"), ) if not (inadm_diag["locked_pct"] == 0.0 and inadm_diag["modular_k100_pct"] == 0.0 and inadm_diag["modular_k90_pct"] == 0.0): raise ValueError(f"Inadmissible diagonal leaked non-zero survival: {inadm_diag}") by_4 = {r["scenario"]: r for r in wavec_4} by_5 = {r["scenario"]: r for r in wavebc_5} p1_exact = p5["autologous_p1_continuous_breakeven_exact"] if abs(float(p1_exact["phi_0p25_p1_star"]) - 0.672989) > 1e-6 or abs(float(p1_exact["phi_0p50_p1_star"]) - 0.746615) > 1e-6: raise ValueError(f"Continuous p1* break-even drifted: {p1_exact}") return { "schema_version": "openislet_iip0035_d1b_auto_and_portfolio_verification_v0.8.0", "proposal_id": "IIP-0035", "decision_id": "DEC-114", "license": "CC-BY-4.0", "option_2_zero_lims_touch": True, "epistemic_status": "DETERMINISTIC_STAGE0_CONTRACT_RARE_EVENT_AND_5ARM_PORTFOLIO_REPLAY_STAGE0_PENDING", "live_headline_odds_delta_pp": 0.0, "d1b_auto_v2_product_registry_audit": registry_audit, "rare_event_and_stage0_gate_matrix_audit": rare_event_and_gate_audit, "protected_lims_and_frozen_artifact_invariance": invariance_audit, "five_arm_autologous_portfolio_audit": { "wave_c_4arm_count": len(wavec_4), "wave_bc_5arm_count": len(wavebc_5), "phi_c_counterexamples_count": len(phi_c_cex), "p1_sweep_points_count": len(p5.get("autologous_p1_breakeven_sweep", [])), "max_4096_state_incumbent_abs_err": max_4096_err, "inadmissible_diagonal_locked_pct": inadm_diag["locked_pct"], "inadmissible_diagonal_modular_k100_pct": inadm_diag["modular_k100_pct"], "five_arm_bridge_registration_status": p5["five_arm_bridge_registration_status"], "w_c0_negative_control_locked_pct": by_4["W_C0_CTRL_Unedited_Auto_RecurrenceStress@R2 (modeled p3=0.10; motivated by Sutherland1989 & Vendrame2010)"]["locked_pct"], "w_c4_p1_0p62_phi25_locked_pct": by_4["W_C4_4Arm_D1b@R3P_S2_Screened_p1=0.62_c4u0.92_phi=0.25"]["locked_pct"], "w_c4_p1_0p62_phi25_registered_route_modular_pct": by_4["W_C4_4Arm_D1b@R3P_S2_Screened_p1=0.62_c4u0.92_phi=0.25"]["modular_registered_route_only_k100_pct"], "w_c4_p1_0p62_phi25_r2_only_modular_pct": by_4["W_C4_4Arm_D1b@R3P_S2_Screened_p1=0.62_c4u0.92_phi=0.25"]["modular_k100_under_r2_only_expansion_pct"],