OpenIslet

scripts/verify_iip0041_clinical_h1_cd64t_siglec.py

EXP-028 (CAND-031 / Target IIP-0041 — Bucket 2A) Remediated Verification Suite

script Release v0.8.0 gen-eb955f8266035aba 984 KB · 69 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…

                trusted_store_source = csrc
            if cmc_err is not None or cmc_bytes is None:
                failure_reasons.append(f"Trusted clinical store resolution failed for PARALLEL_CMC_READINESS_LEDGER: {cmc_err}.")
            else:
                c_errs: list[str] = []
                c_issuer: str | None = None
                try:
                    cmc_doc = load_strict_json_bytes(cmc_bytes, "PARALLEL_CMC_READINESS_LEDGER")
                except Exception as exc:
                    cmc_doc = None
                    c_errs.append(
                        f"PARALLEL_CMC_READINESS_LEDGER failed strict JSON decode (CMC_LEDGER_ANCESTRY_UNVERIFIABLE): {exc}"
                    )
                    cmc_ancestry_conflict = True
                if not isinstance(cmc_doc, dict):
                    c_errs.append(
                        "PARALLEL_CMC_READINESS_LEDGER payload must be a JSON object (CMC_LEDGER_ANCESTRY_UNVERIFIABLE)."
                    )
                    cmc_ancestry_conflict = True
                else:
                    if cmc_doc.get("record_type") != "PARALLEL_CMC_READINESS_LEDGER":
                        c_errs.append(f"Unexpected PARALLEL_CMC_READINESS_LEDGER record_type={cmc_doc.get('record_type')!r}.")
                    if cohort_id is not None and cmc_doc.get("cohort_id") != cohort_id:
                        c_errs.append(f"PARALLEL_CMC_READINESS_LEDGER cohort_id={cmc_doc.get('cohort_id')!r} != {cohort_id!r}.")
                    c_issuer = _strict_literal_id(cmc_doc.get("issuer_authority_id"))
                    if c_issuer not in GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES:
                        c_errs.append(f"PARALLEL_CMC_READINESS_LEDGER issuer_authority_id={cmc_doc.get('issuer_authority_id')!r} not in allowlist.")
                    lot_ledger_raw = cmc_doc.get("lot_ledger")
                    ref_mcb_map: dict[str, str] = st_mcb if st_mcb is not None else (manifest_mcb_norm or {})
                    ref_wcb_map: dict[str, str] = st_eff_wcb if st_mcb is not None else effective_wcb_manifest

                    # UNCONDITIONAL PRE-VALIDATION RAW CMC ANCESTRY & BIDIRECTIONAL RESCUE RECONCILIATION
                    # Runs ONCE unconditionally BEFORE evaluate_cmc_attempted_lot_readiness so NO unrelated CMC
                    # validation/shape error (e.g., invalid planned_doses_n on another split lot) can EVER mask
                    # raw CMC ancestry conflicts OR clinical-vs-CMC rescue identity/cardinality/lineage conflicts!
                    raw_anc_errs, raw_anc_conflict = _audit_raw_cmc_ledger_ancestry(
                        lot_ledger_raw,
                        ref_mcb_map=ref_mcb_map,
                        ref_wcb_map=ref_wcb_map,
                        observed_wcb_to_mcbs=observed_wcb_to_mcbs,
                        clinical_recipient_meta=clinical_recipient_meta,
                        raw_ancestry_claims_by_rid=raw_ancestry_claims_by_rid,
                    )
                    for aerr in raw_anc_errs:
                        if aerr not in c_errs:
                            c_errs.append(aerr)
                    if raw_anc_conflict:
                        cmc_ancestry_conflict = True

                    raw_resc_errs, raw_resc_conflict = _reconcile_raw_clinical_and_cmc_rescues(
                        lot_ledger_raw,
                        seen_rids=seen_rids,
                        clinical_recipient_meta=clinical_recipient_meta,
                        raw_ancestry_claims_by_rid=raw_ancestry_claims_by_rid,
                        raw_rescue_claims_by_rid=raw_rescue_claims_by_rid,
                        duplicate_rids_set=duplicate_rids_set,
                        duplicate_rescue_errors_by_rid=duplicate_rescue_errors_by_rid,
                        ref_mcb_map=ref_mcb_map,
                        ref_wcb_map=ref_wcb_map,
                    )
                    for rerr in raw_resc_errs:
                        if rerr not in c_errs:
                            c_errs.append(rerr)
                    if raw_resc_conflict:
                        cmc_ancestry_conflict = True

                    try:
                        parallel_cmc_summary = evaluate_cmc_attempted_lot_readiness(lot_ledger_raw)
                    except CMCAncestryValidationError as exc:
                        c_errs.append(
                            f"PARALLEL_CMC_READINESS_LEDGER failed evaluate_cmc_attempted_lot_readiness "
                            f"({exc.error_code}): {exc}"
                        )
                        cmc_ancestry_conflict = True
                    except Exception as exc:
                        c_errs.append(f"PARALLEL_CMC_READINESS_LEDGER failed evaluate_cmc_attempted_lot_readiness: {exc}")
                    else:
                        single_map, pooled_map, _all_cmc_rows = _extract_cmc_reconciliation_view(lot_ledger_raw)
                        if pooled_map:
                            c_errs.append(
                                f"PARALLEL_CMC_READINESS_LEDGER contains {len(pooled_map)} pooled multi-lot course recipient(s); "
                                "pooled multi-lot courses are excluded from primary single-lot nested-cluster Gate 28-A promotion "
                                "unless a prespecified multi-membership cluster model is registered."
                            )
                        cmc_rids = set(single_map.keys())
                        missing_from_cmc = sorted(seen_rids - cmc_rids)
                        extra_in_cmc = sorted(cmc_rids - seen_rids)
                        if missing_from_cmc:
                            c_errs.append(
                                f"Clinical cohort recipients missing from PARALLEL_CMC_READINESS_LEDGER: {missing_from_cmc[:5]} (total {len(missing_from_cmc)})."
                            )
                            cmc_ancestry_conflict = True
                        if extra_in_cmc:
                            c_errs.append(
                                f"Infused recipients in PARALLEL_CMC_READINESS_LEDGER omitted from clinical cohort: {extra_in_cmc[:5]} (total {len(extra_in_cmc)})."
                            )
                            cmc_ancestry_conflict = True
                        for rid in sorted(seen_rids & cmc_rids):
                            cmeta = clinical_recipient_meta[rid]
                            sinfo = single_map[rid]
                            if cmeta["lot_id"] != sinfo["lot_id"]:
                                msg_lid = (
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation lot_id mismatch for recipient {rid!r}: clinical={cmeta['lot_id']!r} != cmc={sinfo['lot_id']!r}."
                                )
                                if msg_lid not in c_errs:
                                    c_errs.append(msg_lid)
                                cmc_ancestry_conflict = True
                            if cmeta["mcb_id"] != sinfo["mcb_id"]:
                                msg_mid = (
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation mcb_id mismatch for recipient {rid!r}: clinical={cmeta['mcb_id']!r} != cmc={sinfo['mcb_id']!r}."
                                )
                                if msg_mid not in c_errs:
                                    c_errs.append(msg_mid)
                                cmc_ancestry_conflict = True
                            if cmeta["wcb_id"] != sinfo["wcb_id"]:
                                if cmeta["lot_id"] == sinfo["lot_id"] and cmeta["wcb_id"] is not None and sinfo["wcb_id"] is None:
                                    msg_wid = (
                                        f"CMC_INFUSED_LOT_MISSING_DECLARED_WCB_ID: CMC reconciliation for recipient {rid!r} "
                                        f"(lot_id={sinfo['lot_id']!r}): clinical/manifest declares wcb_id={cmeta['wcb_id']!r} "
                                        "but raw CMC row omitted wcb_id."
                                    )
                                else:
                                    msg_wid = (
                                        f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation wcb_id mismatch "
                                        f"for recipient {rid!r}: clinical={cmeta['wcb_id']!r} != cmc={sinfo['wcb_id']!r}."
                                    )
                                if msg_wid not in c_errs:
                                    c_errs.append(msg_wid)
                                cmc_ancestry_conflict = True
                            if any(p_lid != cmeta["lot_id"] for p_lid in sinfo["rescued_primary_lot_ids"]):
                                msg_plid = (
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC rescue primary-lot mismatch "
                                    f"for recipient {rid!r}: clinical primary lot_id={cmeta['lot_id']!r} != cmc rescued_primary_lot_ids={sinfo['rescued_primary_lot_ids']!r}."
                                )
                                if msg_plid not in c_errs:
                                    c_errs.append(msg_plid)
                                msg_plid_resc = (
                                    f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: CMC rescue primary-lot mismatch "
                                    f"for recipient {rid!r}: clinical primary lot_id={cmeta['lot_id']!r} != cmc rescued_primary_lot_ids={sinfo['rescued_primary_lot_ids']!r}; "
                                    "ancestry verification and cluster statistics nullified fail-closed."
                                )
                                if msg_plid_resc not in c_errs:
                                    c_errs.append(msg_plid_resc)
                                cmc_ancestry_conflict = True

                            # Strict mandatory clinical-vs-CMC outcome reconciliation for EVERY primary CMC recipient:
                            # Compare against the RAW submitted initial-lot CMC outcome BEFORE rescue normalization
                            # zeroes primary_outcome so a rescued recipient whose initial CMC lot still claims
                            # responder outcome=1 fails closed with CMC_OUTCOME_MISMATCH!
                            raw_cmc_outcome = sinfo["raw_primary_outcome"]
                            if rid not in clinical_adjudicated_by_rid:
                                c_errs.append(
                                    f"CMC_OUTCOME_UNRECONCILED_MISSING_CLINICAL_ADJUDICATION: CMC reconciliation failed for "
                                    f"recipient {rid!r}: cmc={raw_cmc_outcome} lacks a reconciled clinical adjudication."
                                )
                            elif clinical_adjudicated_by_rid[rid] != raw_cmc_outcome:
                                c_errs.append(
                                    f"CMC_OUTCOME_MISMATCH: CMC reconciliation outcome mismatch for recipient {rid!r}: "
                                    f"clinical={clinical_adjudicated_by_rid[rid]} != cmc={raw_cmc_outcome}."
                                )
                if c_errs:
                    for cerr_item in c_errs:
                        if cerr_item not in failure_reasons:
                            failure_reasons.append(cerr_item)
                else:
                    cmc_ledger_verified = True
                    authenticated_store_digests["parallel_cmc_readiness_ledger"] = target_cmc_sha
                    if c_issuer is not None:
                        authenticated_store_issuers["parallel_cmc_readiness_ledger"] = c_issuer

    if duplicate_rescue_errors_by_rid or any(
        "CONFLICTING_CLINICAL_RESCUE_LOT_FIELDS" in fr for fr in failure_reasons
    ):
        cmc_ancestry_conflict = True

    if cmc_ancestry_conflict or store_manifest_failed_hierarchy or not store_manifest_verified:
        cmc_ledger_verified = False

    if store_manifest_failed_hierarchy or not store_manifest_verified or cmc_ancestry_conflict:
        return {
            "status": "HOLD_H1_AT_88PCT",
            "promotion_authorized": False,
            "external_clinical_store_verified": False,
            "cohort_id": cohort_id,
            "cohort_canonical_sha256": cohort_canonical_sha256,
            "cohort_ledger_sha256": cohort_canonical_sha256,
            "lot_bank_hierarchy_valid": False,
            "lot_to_mcb_manifest_verified": False,
            "lot_to_wcb_manifest_verified": False,
            "prespecification_attestation_verified": prespec_verified,
            "source_verification_attestation_verified": source_verified,
            "parallel_cmc_ledger_verified": False,
            "icc_sensitivity_report_attached": False,
            "icc_sensitivity_report": None,
            "boundary_sensitive_under_high_icc": False,
            "icc_sensitivity_review_status": None,
            "parallel_cmc_readiness_summary": parallel_cmc_summary,
            "self_attested_inline_records_rejected": self_attested_inline_rejected,
            "trusted_clinical_store_resolution_source": trusted_store_source,
            "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
            "k": k,
            "n": n,
            "deff": None,
            "n_eff": None,
            "k_eff": None,
            "intercurrent_event_counts": ie_counts,
            "secondary_steroid_exposed_c2b_count_excluded_from_primary": secondary_steroid_exposed_c2b,
            "failure_reasons": failure_reasons,
        }

    # Compute cluster counts strictly from the verified nested lot -> MCB hierarchy!
    lot_counts = Counter(lot_ids)
    bank_counts: Counter[str] = Counter()
    for lid, cnt in lot_counts.items():
        bank_counts[verified_lot_to_mcb[lid]] += cnt
    distinct_gmp_lots_n = len(lot_counts)
    distinct_mcb_n = len(bank_counts)
    max_single_lot_n = max(lot_counts.values())
    max_single_lot_share_frac = Fraction(max_single_lot_n, n)
    max_share_cap_frac = Fraction(GATE_28A_MAX_SINGLE_LOT_SHARE)

    if distinct_gmp_lots_n < GATE_28A_DISTINCT_LOTS_MIN:
        failure_reasons.append(
            f"distinct_gmp_lots_n={distinct_gmp_lots_n} < required minimum {GATE_28A_DISTINCT_LOTS_MIN}."
        )
    if distinct_mcb_n < GATE_28A_DISTINCT_MCB_MIN:
        failure_reasons.append(
            f"distinct_mcb_n={distinct_mcb_n} < required minimum {GATE_28A_DISTINCT_MCB_MIN} (single-bank risk blocked)."
        )
    if max_single_lot_share_frac > max_share_cap_frac:
        failure_reasons.append(
            f"max_single_lot_share={float(max_single_lot_share_frac):.4f} ({max_single_lot_n}/{n}) > allowed cap {float(max_share_cap_frac):.2f}."
        )

    if icc_domain_invalid:
        cp_lo, cp_hi = clopper_pearson_ci(k, n)
        external_clinical_store_verified = (
            prespec_verified and source_verified and store_manifest_verified and cmc_ledger_verified
        )
        return {
            "status": "HOLD_H1_AT_88PCT",
            "promotion_authorized": False,
            "external_clinical_store_verified": external_clinical_store_verified,
            "cohort_id": cohort_id,
            "cohort_canonical_sha256": cohort_canonical_sha256,
            "cohort_ledger_sha256": cohort_canonical_sha256,
            "lot_bank_hierarchy_valid": True,
            "lot_to_mcb_manifest_verified": store_manifest_verified,
            "lot_to_wcb_manifest_verified": store_wcb_verified,
            "prespecification_attestation_verified": prespec_verified,