scripts/verify_iip0035_d1b_auto_and_portfolio.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0035_d1b_auto_and_portfolio.py · SHA-256: fedb990aeaedd116…
_cat = _am.get("coverage_category")
if _cat == "UNIT_ASSUMED":
flags.append(f"{_ak}:UNIT_RECOVERY_AND_ELIGIBILITY_ASSUMED")
else:
_da = _am.get("default_calibration_assumptions")
if isinstance(_da, list):
for _item in _da:
flags.append(f"{_ak}:{_item}")
return flags
def evaluate_stage0_d1b_auto_v2_gates_iip0035(
observations: Dict[str, Any],
*,
product_def: Dict[str, Any] | None = None,
product_variant_id: str | None = None,
declared_product_variant_id: str | None = None,
evaluated_lot_id: str | None = None,
extra_lot_bindings: Dict[str, Any] | None = None,
global_gate0v_record: Any = _MISSING_ARG,
outer_gate0v_explicit_null: bool = False,
decision_tree_block: Dict[str, Any] | None = None,
repo_root: Path = ROOT,
require_canonical_sha: bool = True,
) -> Dict[str, Any]:
"""Standalone fail-closed Stage-0 reference evaluator driven directly by the 45-cell DEC-114 contract (D1-01..D1-09).
Zero wetlab_contract.py dependency. Enforces unified integrity across equivalent observation envelopes
under default strict mode (verifying both stage0_decision_tree_v1.json and CommonMark Playbook §4.1.20
SHA-256s), parses numeric/branch rules directly from the 45-cell contract, reconciles conflicting
product identity declarations symmetrically, and explicitly distinguishes reference-scenario arithmetic
(keyed to a single-locus L1 donor record) from assembled multi-locus manifests or clinical/batch release
authorization (`clinical_or_batch_release_authorized` is always False).
"""
invalid_or_oob_keys: List[str] = []
explicitly_unavailable: List[str] = []
if not isinstance(observations, dict):
return {
"gate_id": "STAGE0_GATE_AUTOLOGOUS_D1B_AUTO_C_V2_D101_D109_IIP_0035",
"decision_id": "DEC-114",
"contribution_id": "IIP-0035",
"evaluation_kind": "REFERENCE_CONTRACT_COMPUTATION_NOT_EMPIRICAL_RELEASE_DECISION",
"clinical_or_batch_release_authorized": False,
"assembled_multilocus_manifest_bound": False,
"empirical_clearance_status": "HOLD_INVALID_OBSERVATION_PAYLOAD",
"reference_criteria_met": False,
"status": "FAIL_D1_INVALID_OR_OUT_OF_RANGE_OBSERVATION",
"reasons": ["FAIL_D1_INVALID_OR_OUT_OF_RANGE_OBSERVATION"],
}
def _dec(key: str) -> Decimal | None:
raw = observations.get(key)
if isinstance(raw, str) and raw == "UNAVAILABLE":
explicitly_unavailable.append(key)
return None
if raw is None:
return None
dv = _safe_exact_decimal(raw)
if dv is None:
invalid_or_oob_keys.append(key)
return None
bounds = _D1_ENDPOINT_BOUNDS.get(key)
if bounds is not None:
if dv < Decimal(str(bounds[0])) or (bounds[1] is not None and dv > Decimal(str(bounds[1]))):
invalid_or_oob_keys.append(key)
return None
return dv
def _strict_int(key: str) -> int | None:
raw = observations.get(key)
if isinstance(raw, str) and raw == "UNAVAILABLE":
explicitly_unavailable.append(key)
return None
if raw is None:
return None
if isinstance(raw, bool) or not isinstance(raw, int):
invalid_or_oob_keys.append(key)
return None
if raw < 0:
invalid_or_oob_keys.append(key)
return None
return raw
reasons: List[str] = []
obs_pdef_inner = observations.get("product_def")
has_pdef_obj_conflict = False
if product_def is not None and not isinstance(product_def, dict):
reasons.append("FAIL_D1_INVALID_OR_TAMPERED_PRODUCT_DEFINITION")
if obs_pdef_inner is not None and not isinstance(obs_pdef_inner, dict):
reasons.append("FAIL_D1_CONFLICTING_PRODUCT_IDENTITY_DECLARATIONS")
has_pdef_obj_conflict = True
elif isinstance(product_def, dict) and isinstance(obs_pdef_inner, dict) and not _strict_typed_equal(obs_pdef_inner, product_def):
reasons.append("FAIL_D1_CONFLICTING_PRODUCT_IDENTITY_DECLARATIONS")
has_pdef_obj_conflict = True
# Feed embedded product_variant_id from EVERY supplied product_def (both outer and inner) symmetrically!
outer_pdef_id = product_def.get("product_variant_id") if isinstance(product_def, dict) else None
inner_pdef_id = obs_pdef_inner.get("product_variant_id") if isinstance(obs_pdef_inner, dict) else None
declared_pvids: List[str] = []
pvid_invalid = False
for _cand_pvid in (outer_pdef_id, inner_pdef_id, product_variant_id, declared_product_variant_id, observations.get("product_variant_id")):
if _cand_pvid is None:
continue
if _is_canonical_identifier(_cand_pvid):
if _cand_pvid not in declared_pvids:
declared_pvids.append(_cand_pvid)
else:
pvid_invalid = True
invalid_or_oob_keys.append("product_variant_id")
has_pvid_conflict = len(declared_pvids) > 1 or has_pdef_obj_conflict
if len(declared_pvids) > 1:
reasons.append("FAIL_D1_CONFLICTING_PRODUCT_IDENTITY_DECLARATIONS")
eff_product_def = product_def if isinstance(product_def, dict) else (obs_pdef_inner if isinstance(obs_pdef_inner, dict) else None)
# Under ANY identity or object conflict, keep identity symmetrically unresolved (order-independent!).
if has_pvid_conflict:
pvid = ""
eff_product_def = None
elif eff_product_def is None and len(declared_pvids) == 1 and not pvid_invalid:
_loaded_pc = pc.load_product_contracts(repo_root, require_staged_fastas=require_canonical_sha)
_pc_by_id = {p["product_variant_id"]: p for p in _loaded_pc["products"]}
_single_pvid = declared_pvids[0]
if _single_pvid in _pc_by_id:
eff_product_def = _pc_by_id[_single_pvid]
pvid = _single_pvid
else:
pvid = _single_pvid
else:
pvid = declared_pvids[0] if (len(declared_pvids) == 1 and not pvid_invalid) else ""
product_def = eff_product_def
contract = _load_controlling_contract_for_product(
pvid,
decision_tree_block=decision_tree_block,
repo_root=repo_root,
require_canonical_sha=require_canonical_sha,
)
thr = contract["thresholds"]
cell_mdd = contract["cell_missing_dispositions"]
is_fullstack = pvid in D1B_FULLSTACK_CANDIDATE_IDS
is_component = (pvid in D1B_COMPONENT_DONOR_IDS) or contract["is_component_excluded"]
if not pvid:
if not has_pvid_conflict:
reasons.append("HOLD_D1_CANONICAL_PRODUCT_VARIANT_ID_REQUIRED")
elif not (is_fullstack or is_component):
reasons.append("FAIL_D1_CANONICAL_PRODUCT_NOT_D1B_AUTO_V2")
elif not isinstance(product_def, dict):
reasons.append("FAIL_D1_INVALID_OR_TAMPERED_PRODUCT_DEFINITION")
else:
if is_component:
reasons.append("HOLD_D1_COMPONENT_DONOR_EXCLUDED_FROM_FULLSTACK_CLEARANCE")
exp_rec = pc.D1B_AUTO_V2_DONOR_BINDINGS.get(pvid) or {}
try:
canon_pdef = _canonicalize_json_for_digest(product_def)
got_p_sha = hashlib.sha256(
json.dumps(canon_pdef, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
).hexdigest()
except Exception:
got_p_sha = ""
if (
product_def.get("execution_supported") is not False
or product_def.get("physical_route_id") != "ROUTE_3P_MODULAR_PLANAR_ENVELOPE"
or product_def.get("lifecycle_state") != "STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC"
or not exp_rec.get("full_record_sha256")
or got_p_sha != exp_rec["full_record_sha256"]
):
reasons.append("FAIL_D1_INVALID_OR_TAMPERED_PRODUCT_DEFINITION")
canon_l1_arm: str | None = None
if pvid == "ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN":
canon_l1_arm = "D1AUTO_V2_L1A_IL1RN_CD64T_PRIMARY"
elif pvid == "ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR":
canon_l1_arm = "D1AUTO_V2_L1B_CD46WT_CD64T_GATE0V_COMPARATOR"
l1_arm = observations.get("d1_auto_locus1_donor_arm")
if isinstance(l1_arm, str) and l1_arm == "UNAVAILABLE":
explicitly_unavailable.append("d1_auto_locus1_donor_arm")
l1_arm = None
elif l1_arm is not None and not isinstance(l1_arm, str):
invalid_or_oob_keys.append("d1_auto_locus1_donor_arm")
l1_arm = None
elif l1_arm is not None and l1_arm not in ALLOWED_LOCUS1_ARMS:
reasons.append("HOLD_D1_01_UNKNOWN_LOCUS1_DONOR_ARM")
elif canon_l1_arm is not None and l1_arm is not None and l1_arm != canon_l1_arm:
reasons.append("FAIL_D1_01_CANONICAL_PRODUCT_LOCUS1_ARM_MISMATCH")
effective_l1_arm = None if has_pvid_conflict else (canon_l1_arm if canon_l1_arm is not None else l1_arm)
# Strict lot-ID binding using the single shared _LOT_ALIAS_KEY_SET across Python and CLI!
lot_candidates: List[str] = []
lot_invalid = False
lot_pairs: List[tuple[str, Any]] = [
("evaluated_lot_id_arg", evaluated_lot_id),
("mcb_lot_id", observations.get("mcb_lot_id")),
("lot_id", observations.get("lot_id")),
("evaluated_lot_id", observations.get("evaluated_lot_id")),
("batch_id", observations.get("batch_id")),
("mcb_batch_id", observations.get("mcb_batch_id")),
]
if extra_lot_bindings is not None:
if not isinstance(extra_lot_bindings, dict):
lot_invalid = True
else:
# Validate key types & membership in _LOT_ALIAS_KEY_SET BEFORE sorting (prevents TypeError on mixed keys & rejects unknown alias keys!)
valid_ek_pairs: List[tuple[str, Any]] = []
for ek, ev in extra_lot_bindings.items():
if not isinstance(ek, str) or ek not in _LOT_ALIAS_KEY_SET:
lot_invalid = True
invalid_or_oob_keys.append("extra_lot_bindings")
else:
valid_ek_pairs.append((ek, ev))
for ek, ev in sorted(valid_ek_pairs, key=lambda kv: kv[0]):
lot_pairs.append((f"envelope.{ek}", ev))
for lot_src_key, lot_raw in lot_pairs:
if lot_raw is None:
continue
if isinstance(lot_raw, str) and lot_raw == "UNAVAILABLE":
explicitly_unavailable.append(lot_src_key)
continue
if not _is_canonical_identifier(lot_raw):
lot_invalid = True
continue
if lot_raw not in lot_candidates:
lot_candidates.append(lot_raw)
if lot_invalid:
reasons.append("HOLD_D1_INVALID_OR_MISSING_EVALUATED_LOT_ID")
lot_conflict = len(lot_candidates) > 1
if lot_conflict:
reasons.append("HOLD_D1_CONFLICTING_LOT_ID_BINDING")
lot_id_eff = lot_candidates[0] if (len(lot_candidates) == 1 and not lot_invalid) else None
if lot_id_eff is None and not lot_conflict and not lot_invalid:
reasons.append("HOLD_D1_INVALID_OR_MISSING_EVALUATED_LOT_ID")
# Resolve global_gate0v_record symmetrically across Python (private _MISSING_ARG sentinel + explicit None == JSON null!) and CLI
obs_g0v_present = "global_gate0v_record" in observations
obs_g0v_rec = observations.get("global_gate0v_record")
outer_g0v_present = (global_gate0v_record is not _MISSING_ARG) or bool(outer_gate0v_explicit_null)
outer_g0v_val = None if global_gate0v_record is _MISSING_ARG else global_gate0v_record
g0v_supplied_records: List[Any] = []
if outer_g0v_present:
g0v_supplied_records.append(outer_g0v_val)
if obs_g0v_present:
g0v_supplied_records.append(obs_g0v_rec)
g0v_conflict = bool(
outer_g0v_present
and obs_g0v_present
and not _strict_typed_equal(outer_g0v_val, obs_g0v_rec)
)
g0v_any_positive_k = any(_has_positive_gate0v_event(c) for c in g0v_supplied_records)
if g0v_conflict:
reasons.append("FAIL_D1_CONFLICTING_GLOBAL_GATE0V_DECLARATIONS")