scripts/verify_iip0041_clinical_h1_cd64t_siglec.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…
f"CLINICAL_RESCUE_MISSING_EXPLICIT_LOT_ID: recipient {rid_label} declares rescue repeat infusion "
"without an explicit clinical rescue_lot_id / rescue_lot_ids (exact rescue-lot identity is required)."
)
return {
"intercurrent_event": ie,
"ie_valid": ie_valid,
"rescue_declared": rescue_declared,
"rescue_lot_id": declared_rescue_lot_id,
"rescue_lot_ids": tuple(declared_rescue_lot_ids_sorted),
"explicit_rescue_ids_provided": explicit_rescue_ids_provided,
"missing_explicit_rescue_lot_id": missing_explicit_rescue_lot_id,
"rescue_parse_error": rescue_parse_error,
"parse_errors": parse_errors,
}
CMC_LEDGER_KNOWN_BANK_KEYS = frozenset({
"mcb_id",
"master_cell_bank_id",
"bank_id",
"wcb_id",
"working_cell_bank_id",
})
class CMCAncestryValidationError(ValueError):
"""Typed ValueError subclass raised when a CMC ledger fails lot/MCB/WCB ancestry validation."""
def __init__(self, message: str, *, error_code: str = "CMC_LEDGER_ANCESTRY_CONFLICT") -> None:
super().__init__(message)
self.error_code = error_code
def _parse_strict_binary_outcome(val: Any, context: str) -> int:
"""Validate explicit binary clinical responder outcome (strict bool or exact int in {0, 1})."""
if type(val) is bool:
return 1 if val else 0
if type(val) is int and val in (0, 1):
return val
raise ValueError(f"{context}: outcome must be strict bool or exact int in {{0, 1}}, got {val!r}")
def _canonical_cmc_lot_sort_key(entry: Any) -> tuple[int, str, str]:
"""Canonical sort key for CMC lot_ledger entries ensuring 100% order-independent validation and diagnostics."""
cjson = json.dumps(
_canonicalize_gate28a_value(entry),
sort_keys=True,
ensure_ascii=False,
separators=(",", ":"),
)
if isinstance(entry, dict):
lid = _strict_literal_id(entry.get("lot_id"))
return (0, lid if lid is not None else "", cjson)
return (1, "", cjson)
def evaluate_cmc_attempted_lot_readiness(
lot_ledger: list[dict[str, Any]],
*,
h1_blueprint_override: float | Decimal | None = None,
) -> dict[str, Any]:
"""
Executable CMC Readiness Ledger evaluator (order-independent, fail-closed) enforcing:
- Standalone release-only operational yield: P_release_CMC = released_lots_n / attempted_lots_n
- Primary-course-equivalent weighted infusion rate per released lot (unit:
infused_primary_course_equivalents_per_released_lot; distinct from raw physical-lot utilization —
e.g., under a 2-lot pooled course both physical lots are infused [100% physical-lot utilization]
while course-equivalent P_infuse_given_released = 1.0 / 2 = 0.50):
P_infuse_given_released = infused_primary_course_equivalents / released_lots_n
- Projected attempted-lot readiness (separate from measured weighted readiness):
projected_cmc_attempted_lot_readiness = P_release_CMC * P_infuse_given_released * H1_Blueprint
(uses locked live H1_Blueprint = 0.88 unless h1_blueprint_override is supplied)
- Measured weighted attempted-lot readiness (separate from projected readiness):
measured_weighted_cmc_readiness = lot_weighted_primary_successes / attempted_lots_n
- Matching conditioning (w_infuse) and primary outcome (w_success) weights across every topology:
* SINGLE_RECIPIENT: w_infuse = 1, w_success = y_r
* SPLIT_LOT (planned P >= 2, infused I <= P): w_infuse = I / P, w_success = sum(y_r) / P,
requiring explicit recipient-keyed outcomes (recipient_outcomes dict or recipient_records list;
ZERO positional inference from recipient_ids order!)
* MULTI_LOT_COURSE (m >= 2 pooled lots -> 1 recipient): reconciled complete membership against
declared course_lot_ids / pooled_lot_count, single agreed primary_lot_id, matching w_infuse = 1 / m
and w_success = y_r / m per constituent lot (zero double-counting!)
* RESCUE_REPEAT_LOT: MUST reference an existing infused initial primary lot & recipient (rejecting
orphan rescue-only rows fail-closed), carries primary-course w_infuse = 0 and w_success = 0, and
forces the rescued recipient's primary single-infusion outcome to 0.
"""
if not isinstance(lot_ledger, list) or len(lot_ledger) == 0:
raise ValueError("lot_ledger must be a non-empty list of lot dicts")
h1_proj_frac = Fraction(88, 100)
if h1_blueprint_override is not None:
h1_dec = _strict_decimal_in_range(h1_blueprint_override, min_val=Decimal("0"), max_val=Decimal("1"))
if h1_dec is None:
raise ValueError(f"Invalid h1_blueprint_override={h1_blueprint_override!r}; require finite number in [0, 1]")
h1_proj_frac = Fraction(h1_dec)
valid_lot_types = {
"SINGLE_RECIPIENT",
"SPLIT_LOT",
"MULTI_LOT_COURSE_PRIMARY",
"MULTI_LOT_COURSE_CONSTITUENT",
"RESCUE_REPEAT_LOT",
}
valid_dispositions = {"FAILED_RELEASE", "RELEASED_UNINFUSED", "RELEASED_INFUSED"}
seen_lots: set[str] = set()
attempted_lots_n = 0
released_lots_n = 0
failed_release_lots_n = 0
uninfused_released_lots_n = 0
split_lots_n = 0
rescue_lots_n = 0
rescue_infused_lots_n = 0
multi_lot_courses: dict[str, dict[str, Any]] = {}
normalized_lots: list[dict[str, Any]] = []
cmc_wcb_to_mcbs: dict[str, set[str]] = {}
ordered_ledger = sorted(lot_ledger, key=_canonical_cmc_lot_sort_key)
for idx, entry in enumerate(ordered_ledger):
if not isinstance(entry, dict):
raise ValueError(f"Lot entry[{idx}] must be a dict")
lot_id = _strict_literal_id(entry.get("lot_id"))
mcb_id = _strict_literal_id(entry.get("mcb_id"))
lot_type = _strict_literal_id(entry.get("lot_type"))
disposition = _strict_literal_id(entry.get("disposition"))
if lot_id is None or mcb_id is None:
raise CMCAncestryValidationError(
f"Lot entry[{idx}] missing literal lot_id or mcb_id",
error_code="CMC_MISSING_LOT_OR_MCB_ID",
)
for ek, ev in sorted(entry.items(), key=lambda kv: str(kv[0])):
if ev is None or not isinstance(ek, str) or ek in CMC_LEDGER_KNOWN_BANK_KEYS:
continue
ek_lo = ek.lower()
if any(tok in ek_lo for tok in ("mcb", "wcb", "cell_bank", "bank_id")):
raise CMCAncestryValidationError(
f"UNRECOGNIZED_BANK_ALIAS in CMC ledger lot {lot_id!r}: unsupported bank key {ek!r}",
error_code="UNRECOGNIZED_BANK_ALIAS",
)
for mcb_alias in ("master_cell_bank_id", "bank_id"):
if mcb_alias in entry and entry[mcb_alias] is not None:
amid = _strict_literal_id(entry[mcb_alias])
if amid is None or amid != mcb_id:
raise CMCAncestryValidationError(
f"CONFLICTING_MCB_ALIAS in CMC ledger lot {lot_id!r}: {mcb_alias}={entry[mcb_alias]!r} contradicts mcb_id={mcb_id!r}",
error_code="CONFLICTING_MCB_ALIAS",
)
wcb_id: str | None = None
wcb_raw = entry.get("wcb_id")
wcb_alias_raw = entry.get("working_cell_bank_id")
if wcb_raw is not None:
wcb_id = _strict_literal_id(wcb_raw)
if wcb_id is None:
raise CMCAncestryValidationError(
f"Lot {lot_id!r} has invalid literal wcb_id={wcb_raw!r}",
error_code="CMC_INVALID_WCB_ID",
)
if wcb_alias_raw is not None:
wcb_alias_id = _strict_literal_id(wcb_alias_raw)
if wcb_alias_id is None:
raise CMCAncestryValidationError(
f"Lot {lot_id!r} has invalid literal working_cell_bank_id={wcb_alias_raw!r}",
error_code="CMC_INVALID_WCB_ID",
)
if wcb_id is not None and wcb_alias_id != wcb_id:
raise CMCAncestryValidationError(
f"CONFLICTING_WCB_ALIAS in CMC ledger lot {lot_id!r}: working_cell_bank_id={wcb_alias_id!r} contradicts wcb_id={wcb_id!r}",
error_code="CONFLICTING_WCB_ALIAS",
)
wcb_id = wcb_alias_id
if wcb_id is not None:
cmc_wcb_to_mcbs.setdefault(wcb_id, set()).add(mcb_id)
if lot_id in seen_lots:
raise CMCAncestryValidationError(
f"DUPLICATE_LOT_ID_IN_CMC_LEDGER: Duplicate lot_id in CMC ledger: {lot_id!r}",
error_code="DUPLICATE_LOT_ID_IN_CMC_LEDGER",
)
seen_lots.add(lot_id)
if lot_type not in valid_lot_types:
raise ValueError(f"Lot {lot_id!r} invalid lot_type={lot_type!r}")
if disposition not in valid_dispositions:
raise ValueError(f"Lot {lot_id!r} invalid disposition={disposition!r}")
planned = entry.get("planned_doses_n")
infused = entry.get("infused_doses_n")
if type(planned) is not int or planned < 1:
raise ValueError(f"Lot {lot_id!r} planned_doses_n must be exact int >= 1")
if type(infused) is not int or infused < 0 or infused > planned:
raise ValueError(f"Lot {lot_id!r} infused_doses_n must be exact int in [0, {planned}]")
if lot_type == "SINGLE_RECIPIENT" and planned != 1:
raise ValueError(f"SINGLE_RECIPIENT lot {lot_id!r} must have planned_doses_n == 1")
if lot_type == "SPLIT_LOT" and planned < 2:
raise ValueError(f"SPLIT_LOT {lot_id!r} must have planned_doses_n >= 2")
if lot_type in ("MULTI_LOT_COURSE_PRIMARY", "MULTI_LOT_COURSE_CONSTITUENT", "RESCUE_REPEAT_LOT") and planned != 1:
raise ValueError(f"{lot_type} lot {lot_id!r} must have planned_doses_n == 1")
if disposition in ("FAILED_RELEASE", "RELEASED_UNINFUSED") and infused != 0:
raise ValueError(f"Lot {lot_id!r} with disposition {disposition!r} must have infused_doses_n == 0")
if disposition == "RELEASED_INFUSED" and infused < 1:
raise ValueError(f"Lot {lot_id!r} with disposition RELEASED_INFUSED must have infused_doses_n >= 1")
# Parse explicit recipient-keyed outcomes (ZERO positional inference!)
bind_err_code = (
"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT"
if lot_type == "RESCUE_REPEAT_LOT"
else "CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT"
)
raw_out_dict = entry.get("recipient_outcomes")
raw_out_recs = entry.get("recipient_records")
parsed_from_dict: dict[str, int] | None = None
parsed_from_recs: dict[str, int] | None = None
if raw_out_dict is not None:
if not isinstance(raw_out_dict, dict):
raise CMCAncestryValidationError(
f"{bind_err_code}: Lot {lot_id!r} recipient_outcomes must be a dict mapping recipient_id -> outcome",
error_code=bind_err_code,
)
parsed_from_dict = {}
for rk, rv in sorted(raw_out_dict.items(), key=lambda kv: repr(kv[0])):
lr = _strict_literal_id(rk)
if lr is None:
raise CMCAncestryValidationError(
f"{bind_err_code}: Lot {lot_id!r} recipient_outcomes contains invalid recipient_id={rk!r}",
error_code=bind_err_code,
)
parsed_from_dict[lr] = _parse_strict_binary_outcome(rv, f"Lot {lot_id!r} recipient_outcomes[{lr!r}]")
if raw_out_recs is not None:
if not isinstance(raw_out_recs, list):
raise CMCAncestryValidationError(
f"{bind_err_code}: Lot {lot_id!r} recipient_records must be a list of recipient outcome dicts",
error_code=bind_err_code,
)
parsed_from_recs = {}
for r_i, r_obj in enumerate(raw_out_recs):
if not isinstance(r_obj, dict):
raise CMCAncestryValidationError(
f"{bind_err_code}: Lot {lot_id!r} recipient_records[{r_i}] must be a dict",
error_code=bind_err_code,
)
lr = _strict_literal_id(r_obj.get("recipient_id"))
if lr is None:
raise CMCAncestryValidationError(
f"{bind_err_code}: Lot {lot_id!r} recipient_records[{r_i}] missing literal recipient_id",
error_code=bind_err_code,
)
if lr in parsed_from_recs: