f"Inconsistent pooled course {course_id!r}: expected exactly one MULTI_LOT_COURSE_PRIMARY row " f"for primary_lot_id={c_info['primary_lot_id']!r}, saw {sorted(c_info['primary_rows_seen'])}" ) if "RELEASED_INFUSED" in c_info["dispositions_seen"] and c_info["dispositions_seen"] != {"RELEASED_INFUSED"}: raise ValueError( f"Inconsistent pooled course {course_id!r}: mixed dispositions {sorted(c_info['dispositions_seen'])} " "across constituent lots of an infused pooled course" ) # Pass 1: Populate 1:1 unique clinical recipients and primary-lot recipient ownership (order-independent!) # Bind ownership to a TYPED course identity tuple: # ("SINGLE_OR_SPLIT_LOT", lot_id) vs ("POOLED_COURSE", course_id) # so a pooled course_id sharing the same string value as a single-lot lot_id can NEVER collide or overwrite, # and reject ANY recipient appearing in more than one initial (non-rescue) course BEFORE writing any outcome! clinical_recipient_outcomes: dict[str, int] = {} seen_initial_course_by_recipient: dict[str, tuple[str, str]] = {} primary_lot_recipients: dict[str, set[str]] = {} for item in sorted(normalized_lots, key=lambda x: x["lot_id"]): if item["disposition"] != "RELEASED_INFUSED" or item["lot_type"] == "RESCUE_REPEAT_LOT": continue lt = item["lot_type"] if lt in ("MULTI_LOT_COURSE_PRIMARY", "MULTI_LOT_COURSE_CONSTITUENT"): rid = item["recipient_ids"][0] course_identity = ("POOLED_COURSE", item["course_id"]) if rid in seen_initial_course_by_recipient: if seen_initial_course_by_recipient[rid] != course_identity: raise ValueError( f"Recipient {rid!r} appears in multiple distinct initial courses " f"({seen_initial_course_by_recipient[rid]!r} vs {course_identity!r}) without rescue flag" ) else: seen_initial_course_by_recipient[rid] = course_identity clinical_recipient_outcomes[rid] = item["recipient_outcomes"][rid] if lt == "MULTI_LOT_COURSE_PRIMARY": primary_lot_recipients[item["lot_id"]] = {rid} else: course_identity = ("SINGLE_OR_SPLIT_LOT", item["lot_id"]) for rid, outc in sorted(item["recipient_outcomes"].items()): if rid in seen_initial_course_by_recipient: raise ValueError( f"Recipient {rid!r} appears in multiple distinct initial courses " f"({seen_initial_course_by_recipient[rid]!r} vs {course_identity!r}) without rescue flag" ) seen_initial_course_by_recipient[rid] = course_identity clinical_recipient_outcomes[rid] = outc primary_lot_recipients[item["lot_id"]] = set(item["recipient_outcomes"].keys()) # Pass 2: Validate EVERY RESCUE_REPEAT_LOT against an existing initial infused primary lot & recipient! # Never fabricate a recipient from an orphan rescue-only row. rescued_recipients: set[str] = set() for item in sorted(normalized_lots, key=lambda x: x["lot_id"]): if item["lot_type"] != "RESCUE_REPEAT_LOT": continue resc_rid = item["rescued_recipient_id"] resc_prim = item["rescued_primary_lot_id"] if resc_prim not in primary_lot_recipients: raise CMCAncestryValidationError( f"Orphan RESCUE_REPEAT_LOT {item['lot_id']!r}: rescued_primary_lot_id={resc_prim!r} " "does not match any infused initial primary lot/course in lot_ledger", error_code="CMC_ORPHAN_RESCUE_LOT", ) if resc_rid not in clinical_recipient_outcomes or resc_rid not in primary_lot_recipients[resc_prim]: raise CMCAncestryValidationError( f"Orphan or mismatched RESCUE_REPEAT_LOT {item['lot_id']!r}: rescued_recipient_id={resc_rid!r} " f"was not infused in initial primary lot/course {resc_prim!r}", error_code="CMC_ORPHAN_RESCUE_LOT", ) if item["disposition"] == "RELEASED_INFUSED": rescued_recipients.add(resc_rid) for resc_rid in rescued_recipients: clinical_recipient_outcomes[resc_rid] = 0 # Pass 3: Matching primary-course conditioning weights (w_infuse) AND outcome weights (w_success) in exact Fraction! infused_course_equiv_frac = Fraction(0) lot_weighted_primary_successes_frac = Fraction(0) for item in normalized_lots: if item["disposition"] != "RELEASED_INFUSED": continue lt = item["lot_type"] if lt == "RESCUE_REPEAT_LOT": # Rescue repeat lots consume manufacturing capacity (counted in attempted_lots_n, released_lots_n, rescue_lots_n) # without creating a new primary clinical course (w_infuse = 0, w_success = 0). continue if lt == "SINGLE_RECIPIENT": rid = item["recipient_ids"][0] infused_course_equiv_frac += Fraction(1, 1) lot_weighted_primary_successes_frac += Fraction(clinical_recipient_outcomes[rid], 1) elif lt == "SPLIT_LOT": infused_course_equiv_frac += Fraction(item["infused_doses_n"], item["planned_doses_n"]) non_rescued_resp = sum(clinical_recipient_outcomes[rid] for rid in item["recipient_outcomes"]) lot_weighted_primary_successes_frac += Fraction(non_rescued_resp, item["planned_doses_n"]) elif lt in ("MULTI_LOT_COURSE_PRIMARY", "MULTI_LOT_COURSE_CONSTITUENT"): m_lots = len(item["course_lot_ids"]) rid = item["recipient_ids"][0] infused_course_equiv_frac += Fraction(1, m_lots) lot_weighted_primary_successes_frac += Fraction(clinical_recipient_outcomes[rid], m_lots) unique_clinical_recipients_n = len(clinical_recipient_outcomes) clinical_primary_responders_n = sum(clinical_recipient_outcomes.values()) p_release_frac = Fraction(released_lots_n, attempted_lots_n) p_infuse_given_released_frac = ( infused_course_equiv_frac / released_lots_n if released_lots_n > 0 else Fraction(0) ) empirical_h1_frac = ( Fraction(clinical_primary_responders_n, unique_clinical_recipients_n) if unique_clinical_recipients_n > 0 else Fraction(0) ) projected_readiness_frac = p_release_frac * p_infuse_given_released_frac * h1_proj_frac measured_weighted_readiness_frac = lot_weighted_primary_successes_frac / attempted_lots_n empirical_product_readiness_frac = p_release_frac * p_infuse_given_released_frac * empirical_h1_frac omitted_infusion_error_frac = p_release_frac * h1_proj_frac return { "attempted_lots_n": attempted_lots_n, "released_lots_n": released_lots_n, "failed_release_lots_n": failed_release_lots_n, "uninfused_released_lots_n": uninfused_released_lots_n, "split_lots_n": split_lots_n, "rescue_lots_n": rescue_lots_n, "rescue_infused_lots_n": rescue_infused_lots_n, "multi_lot_courses_n": len(multi_lot_courses), "infused_lot_equivalents": round(float(infused_course_equiv_frac), 6), "infused_primary_course_equivalents": round(float(infused_course_equiv_frac), 6), "release_only_cmc_yield": round(float(p_release_frac), 6), "p_release_cmc": round(float(p_release_frac), 6), "p_infuse_given_released": round(float(p_infuse_given_released_frac), 6), "p_infuse_given_released_unit": "infused_primary_course_equivalents_per_released_lot", "unique_clinical_recipients_n": unique_clinical_recipients_n, "clinical_primary_responders_n": clinical_primary_responders_n, "empirical_h1_post_release": round(float(empirical_h1_frac), 6), "h1_blueprint_applied": round(float(h1_proj_frac), 6), "projected_cmc_attempted_lot_readiness": round(float(projected_readiness_frac), 6), "projected_cmc_attempted_lot_readiness_pct": round(100.0 * float(projected_readiness_frac), 4), "measured_weighted_cmc_readiness": round(float(measured_weighted_readiness_frac), 6), "measured_weighted_cmc_readiness_pct": round(100.0 * float(measured_weighted_readiness_frac), 4), "authoritative_attempted_lot_metric": "measured_weighted_cmc_readiness", "empirical_product_readiness": round(float(empirical_product_readiness_frac), 6), "empirical_product_readiness_scope": "DIAGNOSTIC_UNWEIGHTED_RECIPIENT_RATE_PRODUCT_ONLY", "diagnostic_unweighted_recipient_rate_product_readiness": round(float(empirical_product_readiness_frac), 6), "h1_cmc_attempted_lot_readiness": round(float(projected_readiness_frac), 6), "h1_cmc_attempted_lot_readiness_pct": round(100.0 * float(projected_readiness_frac), 4), "diagnostic_omitted_infusion_product": round(float(omitted_infusion_error_frac), 6), "lot_weighted_primary_successes": round(float(lot_weighted_primary_successes_frac), 6), "equation_projected": "projected_cmc_attempted_lot_readiness = P_release_CMC * P_infuse_given_released * H1_Blueprint", "equation_measured": "measured_weighted_cmc_readiness = lot_weighted_primary_successes / attempted_lots_n", "equation_empirical_product_diagnostic": ( "empirical_product_readiness = P_release_CMC * P_infuse_given_released * empirical_h1_post_release " "(diagnostic unweighted-recipient-rate product only; authoritative audited metric is measured_weighted_cmc_readiness)" ), "equation": "H1_CMC_ATTEMPTED_LOT_READINESS = P_release_CMC * P_infuse_given_released * H1_Blueprint", } def _extract_cmc_reconciliation_view( lot_ledger: list[dict[str, Any]], ) -> tuple[dict[str, dict[str, Any]], dict[str, dict[str, Any]], dict[str, dict[str, Any]]]: """ Extract exact infused clinical recipient bindings AND complete per-lot ancestry rows across EVERY disposition (primary, split, pooled, rescue, released-uninfused, manufacturing-failed) from a CMC lot_ledger that has ALREADY passed evaluate_cmc_attempted_lot_readiness(lot_ledger). Returns: - single_or_split_recipients: rid -> {lot_id, mcb_id, wcb_id, lot_type, rescued, rescue_lot_ids, rescued_primary_lot_ids, raw_primary_outcome, primary_outcome} - pooled_course_recipients: rid -> {course_id, primary_lot_id, course_lot_ids, rescued, rescue_lot_ids, rescued_primary_lot_ids, raw_primary_outcome, primary_outcome} - all_lot_rows: lot_id -> {lot_id, mcb_id, wcb_id, lot_type, disposition, rescued_recipient_id, rescued_primary_lot_id} """ single_or_split: dict[str, dict[str, Any]] = {} pooled: dict[str, dict[str, Any]] = {} all_lot_rows: dict[str, dict[str, Any]] = {} rescued_rids: set[str] = set() rescued_lots_by_rid: dict[str, list[str]] = {} rescued_primary_lots_by_rid: dict[str, list[str]] = {} for entry in lot_ledger: lid = str(entry["lot_id"]) mid = str(entry["mcb_id"]) wid_raw = entry.get("wcb_id") if entry.get("wcb_id") is not None else entry.get("working_cell_bank_id") wid = str(wid_raw) if isinstance(wid_raw, str) and wid_raw else None lt = str(entry.get("lot_type")) disp = str(entry.get("disposition")) all_lot_rows[lid] = { "lot_id": lid, "mcb_id": mid, "wcb_id": wid, "lot_type": lt, "disposition": disp, "rescued_recipient_id": str(entry["rescued_recipient_id"]) if isinstance(entry.get("rescued_recipient_id"), str) else None, "rescued_primary_lot_id": str(entry["rescued_primary_lot_id"]) if isinstance(entry.get("rescued_primary_lot_id"), str) else None, } if disp != "RELEASED_INFUSED": continue if lt == "RESCUE_REPEAT_LOT": resc_rid = entry.get("rescued_recipient_id") if isinstance(resc_rid, str): rescued_rids.add(resc_rid) rescued_lots_by_rid.setdefault(resc_rid, []).append(lid) resc_prim = entry.get("rescued_primary_lot_id") if isinstance(resc_prim, str): rescued_primary_lots_by_rid.setdefault(resc_rid, []).append(resc_prim) continue raw_out_dict = entry.get("recipient_outcomes") raw_out_recs = entry.get("recipient_records") outcomes: dict[str, int] = {} if isinstance(raw_out_dict, dict): for rk, rv in raw_out_dict.items(): outcomes[str(rk)] = _parse_strict_binary_outcome(rv, "cmc_reconcile") elif isinstance(raw_out_recs, list): for r_obj in raw_out_recs: lr = str(r_obj["recipient_id"]) val = r_obj["c2b_responder"] if "c2b_responder" in r_obj else r_obj["outcome"] outcomes[lr] = _parse_strict_binary_outcome(val, "cmc_reconcile") if lt in ("SINGLE_RECIPIENT", "SPLIT_LOT"): for rid, outc in outcomes.items(): single_or_split[rid] = { "lot_id": lid, "mcb_id": mid, "wcb_id": wid, "lot_type": lt, "rescued": False, "rescue_lot_ids": [], "rescued_primary_lot_ids": [], "raw_primary_outcome": outc, "primary_outcome": outc, } elif lt == "MULTI_LOT_COURSE_PRIMARY": cid = str(entry.get("pooled_course_id") or entry.get("course_id")) clots = entry.get("pooled_course_lot_ids") or entry.get("course_lot_ids") or [] for rid, outc in outcomes.items(): pooled[rid] = { "course_id": cid, "primary_lot_id": lid, "course_lot_ids": sorted(str(x) for x in clots), "rescued": False, "rescue_lot_ids": [], "rescued_primary_lot_ids": [], "raw_primary_outcome": outc, "primary_outcome": outc, } for rrid in sorted(rescued_rids): rlots = sorted(rescued_lots_by_rid.get(rrid, [])) rprims = sorted(rescued_primary_lots_by_rid.get(rrid, [])) if rrid in single_or_split: single_or_split[rrid]["rescued"] = True single_or_split[rrid]["rescue_lot_ids"] = rlots single_or_split[rrid]["rescued_primary_lot_ids"] = rprims