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…

                    return None, "Trusted clinical store directory store_metadata.json failed authority/schema verification", "store_dir"
            elif (sp / "registry.json").is_file():
                return _lookup_gate28a_trusted_record(
                    sp / "registry.json",
                    category=category,
                    expected_sha256=expected_sha256,
                    allowed_issuers=allowed_issuers,
                )
            else:
                return None, "Trusted clinical store directory missing store_metadata.json", "store_dir"
            rec_file = sp / category / f"{expected_sha256}.json"
            if not rec_file.is_file():
                return None, f"Record {expected_sha256[:16]}... not found in trusted clinical store dir {category!r}", "store_dir"
            rec = load_strict_json_bytes(rec_file.read_bytes(), rec_file.name)
            if not isinstance(rec, dict):
                return None, f"Trusted clinical store record {rec_file.name} is not a JSON object", "store_dir"
            return rec, None, "store_dir"
    except Exception as exc:
        return None, f"Failed reading trusted clinical store ({type(exc).__name__}): {exc}", f"unreadable:{sp.name}"

    return None, "Unsupported trusted_clinical_store path type", f"unsupported:{sp.name}"


def _lookup_gate28a_trusted_cmc_ledger_bytes(
    store_path: pathlib.Path | str | None,
    *,
    expected_sha256: Any,
    allowed_issuers: frozenset[str] | set[str],
) -> tuple[bytes | None, str | None, str | None]:
    """Resolve raw PARALLEL_CMC_READINESS_LEDGER payload bytes strictly from trusted_clinical_store and verify byte SHA-256."""
    if store_path is None:
        return None, "trusted_clinical_store not provided", None
    if not isinstance(store_path, (pathlib.Path, str)):
        return None, "trusted_clinical_store has invalid path type", None
    sp = pathlib.Path(store_path)
    if not sp.exists():
        return None, f"trusted_clinical_store path missing: {sp.name}", f"missing:{sp.name}"
    if not _is_valid_sha256_hex(expected_sha256):
        return None, f"Invalid 64-hex parallel_cmc_readiness_ledger_sha256={expected_sha256!r}", f"store:{sp.name}"

    try:
        if sp.is_file():
            doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_clinical_store:{sp.name}")
            if not isinstance(doc, dict):
                return None, "Trusted clinical store registry JSON must be an object", f"registry_file:{sp.name}"
            if doc.get("schema_version") != TRUSTED_CLINICAL_STORE_SCHEMA_VERSION:
                return None, f"Trusted clinical store schema_version mismatch: {doc.get('schema_version')!r}", f"registry_file:{sp.name}"
            if _strict_literal_id(doc.get("store_authority_id")) not in allowed_issuers:
                return None, f"Trusted clinical store authority {doc.get('store_authority_id')!r} not in allowlist", f"registry_file:{sp.name}"
            bucket = doc.get("parallel_cmc_readiness_ledgers")
            if not isinstance(bucket, dict):
                return None, "Trusted clinical store missing bucket 'parallel_cmc_readiness_ledgers'", f"registry_file:{sp.name}"
            entry = bucket.get(expected_sha256)
            if not isinstance(entry, dict) or not isinstance(entry.get("raw_payload_utf8"), str):
                return None, f"PARALLEL_CMC_READINESS_LEDGER bytes {expected_sha256[:16]}... not found in trusted clinical store", f"registry_file:{sp.name}"
            raw_b = entry["raw_payload_utf8"].encode("utf-8")
            if entry.get("payload_sha256") is not None and entry.get("payload_sha256") != expected_sha256:
                return None, "Stored PARALLEL_CMC_READINESS_LEDGER payload_sha256 mismatch", f"registry_file:{sp.name}"
            if sha256_bytes(raw_b) != expected_sha256:
                return None, "Stored PARALLEL_CMC_READINESS_LEDGER raw bytes SHA-256 verification failed", f"registry_file:{sp.name}"
            return raw_b, None, f"registry_file:{sp.name}"

        if sp.is_dir():
            meta_file = sp / "store_metadata.json"
            if meta_file.is_file():
                meta = load_strict_json_bytes(meta_file.read_bytes(), "store_metadata.json")
                if (
                    not isinstance(meta, dict)
                    or meta.get("schema_version") != TRUSTED_CLINICAL_STORE_SCHEMA_VERSION
                    or _strict_literal_id(meta.get("store_authority_id")) not in allowed_issuers
                ):
                    return None, "Trusted clinical store directory store_metadata.json failed authority/schema verification", "store_dir"
            elif (sp / "registry.json").is_file():
                return _lookup_gate28a_trusted_cmc_ledger_bytes(
                    sp / "registry.json",
                    expected_sha256=expected_sha256,
                    allowed_issuers=allowed_issuers,
                )
            else:
                return None, "Trusted clinical store directory missing store_metadata.json", "store_dir"
            rec_file = sp / "parallel_cmc_readiness_ledgers" / f"{expected_sha256}.json"
            if not rec_file.is_file():
                return None, f"PARALLEL_CMC_READINESS_LEDGER file {expected_sha256[:16]}... not found in store_dir", "store_dir"
            raw_b = rec_file.read_bytes()
            if sha256_bytes(raw_b) != expected_sha256:
                return None, "Stored PARALLEL_CMC_READINESS_LEDGER raw file SHA-256 verification failed", "store_dir"
            return raw_b, None, "store_dir"
    except Exception as exc:
        return None, f"Failed reading trusted clinical store CMC ledger ({type(exc).__name__}): {exc}", f"unreadable:{sp.name}"

    return None, "Unsupported trusted_clinical_store path type", f"unsupported:{sp.name}"


def _derive_reconciling_cmc_lot_ledger_from_recipients(
    recipients: list[dict[str, Any]],
    lot_to_mcb_manifest: dict[str, str],
    lot_to_wcb_manifest: dict[str, str] | None = None,
) -> list[dict[str, Any]]:
    """Derive a valid, reconciling single/split-lot CMC readiness ledger from a clinical recipient list."""
    by_lot: dict[str, list[dict[str, Any]]] = {}
    for rec in recipients:
        by_lot.setdefault(str(rec["lot_id"]), []).append(rec)

    wcb_map = dict(lot_to_wcb_manifest or {})
    lot_ledger: list[dict[str, Any]] = []
    rescue_idx = 0
    for lid in sorted(by_lot):
        lot_recs = by_lot[lid]
        mcb_id = lot_to_mcb_manifest.get(lid, str(lot_recs[0]["mcb_id"]))
        lot_wcb: str | None = wcb_map.get(lid)
        if lot_wcb is None:
            for rec_w in lot_recs:
                w_cand = rec_w.get("wcb_id") if rec_w.get("wcb_id") is not None else rec_w.get("working_cell_bank_id")
                if isinstance(w_cand, str) and w_cand:
                    lot_wcb = w_cand
                    break
        outcomes: dict[str, int] = {}
        rids: list[str] = []
        rescued_in_lot: list[tuple[str, list[str] | None]] = []
        for rec in sorted(lot_recs, key=lambda x: str(x["recipient_id"])):
            rid = str(rec["recipient_id"])
            ie = str(rec.get("intercurrent_event", "NONE"))
            met_c2b = bool(rec.get("met_c2b_criteria", False))
            fu_d = _strict_decimal_in_range(rec.get("followup_months", 0), min_val=Decimal("0"))
            fu_ge_6 = (fu_d is not None) and (Fraction(fu_d) >= Fraction(6, 1))
            raw_rlids = rec.get("rescue_lot_ids")
            has_rlid_list = isinstance(raw_rlids, list) and len(raw_rlids) > 0
            resc_flag = (
                ie == "RESCUE_REPEAT_INFUSION"
                or rec.get("rescue_infusion_occurred") is True
                or rec.get("rescue_lot_id") is not None
                or has_rlid_list
            )
            outc = 1 if (ie == "NONE" and not resc_flag and met_c2b and fu_ge_6) else 0
            outcomes[rid] = outc
            rids.append(rid)
            if resc_flag:
                if has_rlid_list:
                    rlids_clean = [str(x) for x in raw_rlids if isinstance(x, str) and x]
                    rescued_in_lot.append((rid, rlids_clean if rlids_clean else None))
                else:
                    rlid_raw = rec.get("rescue_lot_id")
                    rlid_str = str(rlid_raw) if isinstance(rlid_raw, str) and rlid_raw else None
                    rescued_in_lot.append((rid, [rlid_str] if rlid_str is not None else None))
        lt = "SINGLE_RECIPIENT" if len(lot_recs) == 1 else "SPLIT_LOT"
        lot_row: dict[str, Any] = {
            "lot_id": lid,
            "mcb_id": mcb_id,
            "lot_type": lt,
            "disposition": "RELEASED_INFUSED",
            "planned_doses_n": len(lot_recs),
            "infused_doses_n": len(lot_recs),
            "c2b_responder_doses_n": sum(outcomes.values()),
            "recipient_ids": rids,
            "recipient_outcomes": outcomes,
        }
        if lot_wcb is not None:
            lot_row["wcb_id"] = lot_wcb
        lot_ledger.append(lot_row)
        for rrid, explicit_rlids in rescued_in_lot:
            target_rlids = explicit_rlids if explicit_rlids is not None else [None]
            for explicit_rlid in target_rlids:
                rescue_idx += 1
                rlid_final = explicit_rlid or f"RESCUE-{lid}-{rescue_idx:03d}"
                resc_row: dict[str, Any] = {
                    "lot_id": rlid_final,
                    "mcb_id": lot_to_mcb_manifest.get(rlid_final, mcb_id),
                    "lot_type": "RESCUE_REPEAT_LOT",
                    "disposition": "RELEASED_INFUSED",
                    "planned_doses_n": 1,
                    "infused_doses_n": 1,
                    "c2b_responder_doses_n": 1,
                    "recipient_ids": [rrid],
                    "recipient_outcomes": {rrid: 1},
                    "rescued_recipient_id": rrid,
                    "rescued_primary_lot_id": lid,
                }
                if rlid_final in wcb_map:
                    resc_row["wcb_id"] = wcb_map[rlid_final]
                lot_ledger.append(resc_row)
    return lot_ledger


def build_valid_gate28a_reference_bundle(
    store_path: pathlib.Path | str,
    recipients: list[dict[str, Any]],
    *,
    cohort_id: str = "COHORT-GATE28A-REF-001",
    lot_to_mcb_manifest: dict[str, Any] | None = None,
    lot_to_wcb_manifest: dict[str, str] | None = None,
    parallel_cmc_lot_ledger: list[dict[str, Any]] | None = None,
    protocol_or_sap_id: str = "SAP-GATE28A-2026-V1",
    primary_source_citation_id: str = "PMID:99999999",
    manifest_source_id: str = "QA-BANK-MANIFEST-2026-V1",
    issuer_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
    store_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
    **overrides: Any,
) -> tuple[dict[str, Any], dict[str, Any]]:
    """
    Build a complete, contract-valid Gate 28-A cohort payload AND write all 4 independently stored records
    (PRESPECIFICATION_ATTESTATION, SOURCE_VERIFICATION_ATTESTATION, VERIFIED_LOT_TO_BANK_MANIFEST, and
    raw PARALLEL_CMC_READINESS_LEDGER bytes) into `store_path`.
    Returns (cohort_payload_without_inline_attestations, store_records_dict).
    """
    if lot_to_mcb_manifest is None:
        mcb_map: dict[str, str] = {}
        derived_wcb_map: dict[str, str] = {}
        for rec in recipients:
            lid = str(rec["lot_id"])
            if lid not in mcb_map:
                mcb_map[lid] = str(rec["mcb_id"])
            wid = rec.get("wcb_id") if rec.get("wcb_id") is not None else rec.get("working_cell_bank_id")
            if wid is not None and lid not in derived_wcb_map:
                derived_wcb_map[lid] = str(wid)
        eff_derive_wcb = lot_to_wcb_manifest if lot_to_wcb_manifest is not None else (derived_wcb_map or None)
        cmc_ledger_list = (
            copy.deepcopy(parallel_cmc_lot_ledger)
            if parallel_cmc_lot_ledger is not None
            else _derive_reconciling_cmc_lot_ledger_from_recipients(recipients, mcb_map, lot_to_wcb_manifest=eff_derive_wcb)
        )
        # Ensure all clinically infused CMC lots (primary/split AND rescue lots) carry verified manifest ancestry!
        for cmc_row in cmc_ledger_list:
            if cmc_row.get("disposition") == "RELEASED_INFUSED":
                clid = str(cmc_row["lot_id"])
                if clid not in mcb_map:
                    mcb_map[clid] = str(cmc_row["mcb_id"])
                cwid = cmc_row.get("wcb_id") if cmc_row.get("wcb_id") is not None else cmc_row.get("working_cell_bank_id")
                if cwid is not None and clid not in derived_wcb_map:
                    derived_wcb_map[clid] = str(cwid)
        payload_mcb_manifest: dict[str, Any] = dict(sorted(mcb_map.items()))
        payload_wcb_manifest: dict[str, str] | None = (
            copy.deepcopy(lot_to_wcb_manifest)
            if lot_to_wcb_manifest is not None
            else (dict(sorted(derived_wcb_map.items())) if derived_wcb_map else None)
        )
    else:
        payload_mcb_manifest = copy.deepcopy(lot_to_mcb_manifest)
        mcb_norm_tmp, emb_wcb_tmp, _ = _normalize_lot_to_mcb_manifest(payload_mcb_manifest)
        mcb_map = dict(mcb_norm_tmp or {})
        if lot_to_wcb_manifest is not None:
            payload_wcb_manifest = copy.deepcopy(lot_to_wcb_manifest)
        elif emb_wcb_tmp:
            payload_wcb_manifest = dict(sorted(emb_wcb_tmp.items()))
        else:
            payload_wcb_manifest = None
        cmc_ledger_list = (
            copy.deepcopy(parallel_cmc_lot_ledger)
            if parallel_cmc_lot_ledger is not None
            else _derive_reconciling_cmc_lot_ledger_from_recipients(
                recipients, mcb_map, lot_to_wcb_manifest=payload_wcb_manifest