scripts/verify_iip0045_cao2_coupled_gate31.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0045_cao2_coupled_gate31.py · SHA-256: 00443954dd735914…
)
else:
holds_out.append(
f"OPEN_SINK_PAIRED_CONTRAST_95CI_BELOW_ZERO:d_mean={d_mean:.4f}h,d_se={d_se:.4f}h,l95_two={d_l95_two:.4f}h,r={r_val:.3f},df={df}"
)
return {
"mode": "PAIRED_SUMMARY_STUDENT_T",
"n_blocks": raw_n,
"df": df,
"paired_correlation": round(r_val, 6),
"contrast_mean_h": round(d_mean, 6),
"contrast_se_h": round(d_se, 6),
"contrast_l95_two_sided_h": round(d_l95_two, 6),
"contrast_l95_one_sided_h": round(d_l95_one, 6),
"legacy_numerator_only_ratio_diagnostic": round(legacy_shortcut_ratio, 6),
"clears_95pct_two_sided": clears_two,
"clears_95pct_one_sided": clears_one,
"holds": holds_out,
}
# Mode 3: Summary-only without pairing covariance -> propagate denominator uncertainty conservatively (worst-case r = -1)
d_mean = os_th_m - ratio_threshold * th_m
d_se_worst = os_th_se + ratio_threshold * th_se
d_se_indep = math.sqrt(os_th_se**2 + (ratio_threshold * th_se) ** 2)
d_l95_worst = d_mean - Z_95_TWO_SIDED * d_se_worst
d_l95_indep = d_mean - Z_95_TWO_SIDED * d_se_indep
clears = bool(d_l95_worst >= 0.0)
if not clears:
holds_out.append(
f"OPEN_SINK_RATIO_UNPAIRED_DENOMINATOR_UNCERTAINTY_INCONCLUSIVE:d_mean={d_mean:.4f}h,se_worst={d_se_worst:.4f}h,l95_worst={d_l95_worst:.4f}h"
)
return {
"mode": "UNPAIRED_CONSERVATIVE_DENOMINATOR_PROPAGATION",
"contrast_mean_h": round(d_mean, 6),
"contrast_se_worst_case_h": round(d_se_worst, 6),
"contrast_se_uncorrelated_h": round(d_se_indep, 6),
"contrast_l95_worst_case_h": round(d_l95_worst, 6),
"contrast_l95_uncorrelated_h": round(d_l95_indep, 6),
"legacy_numerator_only_ratio_diagnostic": round(legacy_shortcut_ratio, 6),
"clears_95pct_two_sided": clears,
"holds": holds_out,
}
def evaluate_gate31_coupled_cao2_lot(payload: Any) -> Dict[str, Any]:
"""
Fail-closed executable Stage-0 Gate 31 lot evaluator.
Returns structured dict with:
- verdict: 'PASS_GATE_31_COUPLED_CAO2_LOT' | 'HOLD_...' | 'FAIL_HARD_STOP_...'
- exit_code: 0 (PASS), 2 (HOLD), 3 (FAIL_HARD_STOP)
- release_authorizing: bool (True ONLY on PASS_GATE_31_COUPLED_CAO2_LOT)
"""
hard_stops: List[str] = []
holds: List[str] = []
diagnostics: Dict[str, Any] = {}
if not isinstance(payload, dict):
return {
"gate_id": GATE_ID,
"contribution_id": CONTRIBUTION_ID,
"decision_id": DECISION_ID,
"verdict": "HOLD_GATE31_INVALID_PAYLOAD_TYPE",
"exit_code": 2,
"release_authorizing": False,
"hard_stops": [],
"holds": ["PAYLOAD_MUST_BE_JSON_OBJECT"],
"diagnostics": {},
}
# --- 1. Gate 31-Scope (Strictly CaO2-bearing Route 1 in Designs A & X; exclude Design B / Z / Y / D1) ---
design = payload.get("design_family")
route = payload.get("product_route_id")
if design in EXCLUDED_NON_CAO2_DESIGNS or (isinstance(route, str) and "ZERO_CAO2" in route.upper()):
return {
"gate_id": GATE_ID,
"contribution_id": CONTRIBUTION_ID,
"decision_id": DECISION_ID,
"verdict": "HOLD_GATE31_OUT_OF_SCOPE_NON_CAO2_ROUTE",
"exit_code": 2,
"release_authorizing": False,
"hard_stops": [],
"holds": [f"OUT_OF_SCOPE_NON_CAO2_ROUTE:design={design!r},route={route!r}"],
"diagnostics": {"design_family": design, "product_route_id": route},
}
if design not in ALLOWED_CAO2_DESIGNS or route not in ALLOWED_CAO2_ROUTES:
holds.append(f"MISSING_OR_UNRECOGNIZED_CAO2_ROUTE_SCOPE:design={design!r},route={route!r}")
# --- 2. Same-Lot Identity Binding across Bead PSD, Planar Barrier, Kinetics, and Open-Sink ---
lot_id = payload.get("lot_id")
sub_lot_ids = {
"bead_psd_lot_id": payload.get("bead_psd_lot_id"),
"barrier_film_lot_id": payload.get("barrier_film_lot_id"),
"kinetics_336h_lot_id": payload.get("kinetics_336h_lot_id"),
"open_sink_lot_id": payload.get("open_sink_lot_id"),
}
if not isinstance(lot_id, str) or not lot_id.strip():
holds.append("MISSING_OR_INVALID_LOT_ID")
else:
for k, v in sub_lot_ids.items():
if not isinstance(v, str) or not v.strip():
holds.append(f"MISSING_SAME_LOT_BINDING:{k}")
elif v != lot_id:
hard_stops.append(f"DECOUPLED_LOT_MISMATCH:{k}={v!r}!=lot_id={lot_id!r}")
# --- 3. Gate 31-A: Bead/Crystal PSD & Planar Barrier Film Geometry ---
barrier_mode = payload.get("barrier_geometry_mode")
if barrier_mode in FORBIDDEN_BARRIER_MODES:
hard_stops.append(f"FORBIDDEN_BARRIER_GEOMETRY_MODE:{barrier_mode}")
elif barrier_mode not in ALLOWED_BARRIER_MODES:
holds.append(f"MISSING_OR_UNRECOGNIZED_BARRIER_GEOMETRY_MODE:{barrier_mode!r}")
slab_mode = payload.get("reconciled_slab_geometry_mode")
if slab_mode not in ALLOWED_SLAB_MODES:
holds.append(f"INVALID_OR_MISSING_RECONCILED_SLAB_MODE:{slab_mode!r}")
cat_acc = payload.get("catalase_uniprot_accession")
if cat_acc != "P04040":
if isinstance(cat_acc, str) and cat_acc.strip():
hard_stops.append(f"NON_HUMAN_CATALASE_DISQUALIFIED:{cat_acc}")
else:
holds.append("MISSING_CATALASE_UNIPROT_ACCESSION")
d99_m, _, d99_u95, err = _extract_ci(payload, "obs_microbead_volume_d99_um", "obs_microbead_volume_d99_se")
if err:
holds.append(err)
elif d99_u95 is not None and d99_u95 > 50.0:
hard_stops.append(f"MICROBEAD_D99_EXCEEDS_50UM:u95={d99_u95:.4f}")
d50_m, d50_l95, _, err = _extract_ci(payload, "obs_microbead_volume_d50_um", "obs_microbead_volume_d50_se")
if err:
holds.append(err)
crys_m, _, crys_u95, err = _extract_ci(payload, "obs_cao2_crystal_d99_um", "obs_cao2_crystal_d99_se")
if err:
holds.append(err)
elif crys_u95 is not None and d50_l95 is not None and crys_u95 >= d50_l95:
hard_stops.append(
f"CAO2_CRYSTAL_D99_NOT_ENCAPSULATED_IN_BEAD_D50:crystal_u95={crys_u95:.4f}>=bead_d50_l95={d50_l95:.4f}"
)
film_m, film_l95, _, err = _extract_ci(
payload, "obs_planar_barrier_film_um_per_face", "obs_planar_barrier_film_se_um"
)
if err:
holds.append(err)
elif film_l95 is not None and film_l95 < 20.0:
hard_stops.append(f"PLANAR_BARRIER_FILM_LT_20UM:l95={film_l95:.4f}")
# --- 4. Gate 31-B: Same-Lot Conserved Inventory, t_1/2, Kinetic Law, Anti-Lag O2, H2O2 & Catalase ---
inv_mg = payload.get("conserved_patient_cao2_inventory_mg")
if not _is_finite_real(inv_mg):
holds.append("MISSING_OR_INVALID_CONSERVED_CAO2_INVENTORY_MG")
else:
inv_f = float(inv_mg)
if not (CONSERVED_CAO2_MG_MIN <= inv_f <= CONSERVED_CAO2_MG_MAX):
hard_stops.append(
f"CAO2_INVENTORY_OUTSIDE_CONSERVED_791P5MG_BAND:mg={inv_f:.2f}_not_in_[{CONSERVED_CAO2_MG_MIN},{CONSERVED_CAO2_MG_MAX}]"
)
t50_valid = False
t50_horizon: Optional[float] = None
t_half_upper_limit: Optional[float] = None
if "vascular_midpoint_horizon_h" not in payload:
holds.append("MISSING_VASCULAR_MIDPOINT_HORIZON_H")
else:
raw_t50 = payload.get("vascular_midpoint_horizon_h")
if not _is_finite_real(raw_t50) or float(raw_t50) not in (36.0, 60.0):
holds.append(f"INVALID_VASCULAR_MIDPOINT_HORIZON_H:{raw_t50!r}")
else:
t50_valid = True
t50_horizon = float(raw_t50)
t_half_upper_limit = 87.0 if t50_horizon == 36.0 else 68.0
th_m, th_l95, th_u95, err = _extract_ci(payload, "obs_cao2_release_half_life_h", "obs_cao2_release_half_life_se_h")
if err:
holds.append(err)
else:
assert th_l95 is not None and th_u95 is not None
if th_l95 < 34.0:
hard_stops.append(f"CAO2_HALFLIFE_BURST_BELOW_34H_FLOOR:l95={th_l95:.4f}")
if t50_valid and t_half_upper_limit is not None and t50_horizon is not None:
if th_u95 > t_half_upper_limit:
hard_stops.append(
f"CAO2_HALFLIFE_EXCEEDS_UPPER_WINDOW:u95={th_u95:.4f}>limit={t_half_upper_limit:.1f}_at_t50={t50_horizon:.0f}h"
)
elif th_u95 > 87.0:
# Exceeds maximum allowed window under BOTH explicit timings (36 h and 60 h) -> hard stop keeps precedence.
hard_stops.append(
f"CAO2_HALFLIFE_EXCEEDS_UPPER_WINDOW_BOTH_TIMINGS:u95={th_u95:.4f}>max_limit=87.0"
)
kl_code = payload.get("obs_cao2_kinetic_law_code")
if not isinstance(kl_code, int) or isinstance(kl_code, bool) or kl_code not in (0, 1, 2):
holds.append(f"MISSING_OR_INVALID_KINETIC_LAW_CODE:{kl_code!r}")
elif kl_code == 2 and t50_valid and t50_horizon == 60.0:
hard_stops.append("GINSTLING_BROUNSHTEIN_DIFFUSION_LAW_NO_PASSING_WINDOW_AT_T50_60H")
elif kl_code == 2 and not t50_valid:
holds.append("GINSTLING_BROUNSHTEIN_REQUIRES_EXPLICIT_VASCULAR_HORIZON_AND_60H_RESCUE")
elif kl_code == 2:
holds.append("GINSTLING_BROUNSHTEIN_REQUIRES_S9_ESCALATION_AND_60H_RESCUE")
# Third coupling: anti-lag Hour 0-24 O2 delivery & 0-72 h cumulative O2 yield
o2_24_m, o2_24_l95, _, err = _extract_ci(
payload, "obs_hour0_to_24h_o2_delivery_ratio", "obs_hour0_to_24h_o2_delivery_ratio_se"
)
if err:
holds.append(err)
elif o2_24_l95 is not None and o2_24_l95 < 0.70:
hard_stops.append(f"BARRIER_INDUCED_EARLY_O2_LAG_BELOW_0P70_FLOOR:l95={o2_24_l95:.4f}")
o2_72_m, o2_72_l95, _, err = _extract_ci(
payload, "obs_cumulative_0_to_72h_o2_demand_fraction", "obs_cumulative_0_to_72h_o2_demand_fraction_se"
)
if err:
holds.append(err)
elif o2_72_l95 is not None and o2_72_l95 < 0.25:
hard_stops.append(f"CUMULATIVE_72H_O2_DELIVERY_BELOW_0P25_FLOOR:l95={o2_72_l95:.4f}")
h2o2_m, _, h2o2_u95, err = _extract_ci(payload, "obs_islet_plane_h2o2_max_uM", "obs_islet_plane_h2o2_max_se_uM")
if err:
holds.append(err)
elif h2o2_u95 is not None:
if h2o2_u95 > 5.0:
hard_stops.append(f"ISLET_PLANE_H2O2_BREACHES_5P0UM_TIER2_HARD_STOP:u95={h2o2_u95:.4f}")
elif h2o2_u95 > 2.5:
holds.append(f"ISLET_PLANE_H2O2_EXCEEDS_2P5UM_TIER1_TARGET:u95={h2o2_u95:.4f}")
d7_m, d7_l95, _, err = _extract_ci(payload, "obs_day7_catalase_retention_pct", "obs_day7_catalase_retention_se_pct")
if err:
holds.append(err)
elif d7_l95 is not None and d7_l95 < 70.0:
hard_stops.append(f"DAY7_CATALASE_RETENTION_BELOW_70PCT:l95={d7_l95:.4f}")
d14_m, d14_l95, _, err = _extract_ci(
payload, "obs_day14_retained_catalase_iu_333cm2", "obs_day14_retained_catalase_se_iu"
)
if err:
holds.append(err)
elif d14_l95 is not None and d14_l95 < 73800.0:
hard_stops.append(f"DAY14_RETAINED_CATALASE_BELOW_73800IU:l95={d14_l95:.2f}")
precure_iu = payload.get("pre_cure_catalase_load_iu_333cm2")
if not _is_finite_real(precure_iu):
holds.append("MISSING_OR_INVALID_PRE_CURE_CATALASE_LOAD_IU")
elif float(precure_iu) > 158300.0:
hard_stops.append(f"PRE_CURE_CATALASE_EXCEEDS_158300IU_CAP:val={float(precure_iu):.1f}")
# --- 5. Gate 31-C: Sealed-Chamber vs Dynamic Open-Sink Physiological Transfer ---
assay_regime = payload.get("kinetics_assay_regime")
if assay_regime == "SEALED_CHAMBER_ONLY":