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 ["other", type(val).__name__, repr(val)]


def _canonicalize_gate28a_presence_field(container: dict[str, Any], key: str) -> dict[str, Any]:
    """Injectively encode a decision-relevant field's presence/absence and typed canonical value."""
    if key in container:
        return {"present": True, "value": _canonicalize_gate28a_value(container[key])}
    return {"present": False}


def _canonicalize_gate28a_recipient(rec: dict[str, Any]) -> dict[str, Any]:
    """
    Canonicalize a Gate 28-A recipient dict before hashing:
      - Normalizes equivalent documented recipient WCB alias (`working_cell_bank_id` <-> `wcb_id`):
          * If ONLY `working_cell_bank_id` is non-None valid literal string (and `wcb_id` absent or None):
            canonicalizes to `"wcb_id": val` (omitting `working_cell_bank_id`).
          * If ONLY `wcb_id` is non-None valid literal string (and `working_cell_bank_id` absent or None):
            canonicalizes to `"wcb_id": val` (omitting `working_cell_bank_id`).
          * If BOTH `wcb_id` and `working_cell_bank_id` are non-None valid literal strings AND equal:
            canonicalizes to `"wcb_id": val` (dropping redundant matching `working_cell_bank_id`).
          * If EITHER is non-None with an invalid value (non-string, empty, or whitespace-padded) OR BOTH are
            present with CONFLICTING values: preserves BOTH raw keys untouched so conflicts ALWAYS alter
            `cohort_canonical_sha256` and fail closed!
    """
    normalized = dict(rec)
    has_wcb = "wcb_id" in normalized
    has_alias = "working_cell_bank_id" in normalized
    if has_wcb or has_alias:
        wcb_val = normalized.get("wcb_id")
        alias_val = normalized.get("working_cell_bank_id")
        wcb_non_none = has_wcb and (wcb_val is not None)
        alias_non_none = has_alias and (alias_val is not None)
        wcb_valid = _strict_literal_id(wcb_val) if wcb_non_none else None
        alias_valid = _strict_literal_id(alias_val) if alias_non_none else None

        if (not wcb_non_none) and (alias_valid is not None):
            normalized["wcb_id"] = alias_valid
            normalized.pop("working_cell_bank_id", None)
        elif (wcb_valid is not None) and (not alias_non_none):
            normalized["wcb_id"] = wcb_valid
            normalized.pop("working_cell_bank_id", None)
        elif (wcb_valid is not None) and (alias_valid is not None) and (wcb_valid == alias_valid):
            normalized["wcb_id"] = wcb_valid
            normalized.pop("working_cell_bank_id", None)
        # Conflicts (wcb_valid != alias_valid), invalid non-None values, or both-None keep raw keys untouched!

    return {
        str(k): _canonicalize_gate28a_value(v)
        for k, v in sorted(normalized.items(), key=lambda kv: str(kv[0]))
    }


def _resolve_payload_cmc_ledger_sha256(cohort_payload: dict[str, Any]) -> tuple[str | None, list[str]]:
    """Extract parallel_cmc_readiness_ledger_sha256 from payload/refs, rejecting any conflicting aliases."""
    errs: list[str] = []
    cands: list[tuple[str, Any]] = []
    if "parallel_cmc_readiness_ledger_sha256" in cohort_payload and cohort_payload["parallel_cmc_readiness_ledger_sha256"] is not None:
        cands.append(("parallel_cmc_readiness_ledger_sha256", cohort_payload["parallel_cmc_readiness_ledger_sha256"]))
    if "parallel_cmc_ledger_sha256" in cohort_payload and cohort_payload["parallel_cmc_ledger_sha256"] is not None:
        cands.append(("parallel_cmc_ledger_sha256", cohort_payload["parallel_cmc_ledger_sha256"]))
    refs = cohort_payload.get("clinical_store_refs")
    if isinstance(refs, dict) and refs.get("parallel_cmc_readiness_ledger_sha256") is not None:
        cands.append(("clinical_store_refs.parallel_cmc_readiness_ledger_sha256", refs["parallel_cmc_readiness_ledger_sha256"]))
    if not cands:
        return None, []
    first_val = cands[0][1]
    for lbl, val in cands[1:]:
        if val != first_val:
            errs.append(f"Conflicting {lbl}={val!r} vs {cands[0][0]}={first_val!r}.")
    if errs:
        return None, errs
    if not _is_valid_sha256_hex(first_val):
        return None, [f"Invalid 64-hex parallel_cmc_readiness_ledger_sha256={first_val!r}."]
    return str(first_val), []


def compute_gate28a_cohort_canonical_sha256(cohort_payload: dict[str, Any]) -> str:
    """
    Order-independent full canonical SHA-256 digest binding EVERY decision-relevant Gate 28-A declaration:
      - cohort_id
      - all 5 compatibility target declarations (product_class, transplant_site, disease_population,
        immunosuppression_protocol_class, dose_regimen)
      - includes_reichman
      - top-level decision-control flags (`primary_peer_reviewed_full_text_verified`,
        `parallel_cmc_readiness_ledger_disclosed`) with injective presence/absence tagging so adding,
        deleting, or toggling any control flag ALWAYS changes this digest and invalidates attestations
      - ICC inputs (rho_lot, rho_bank)
      - ALL supported manifest fields (lot_to_mcb_manifest, optional lot_to_wcb_manifest,
        optional lot_to_bank_manifest) AND any extra manifest alias keys
      - parallel_cmc_readiness_ledger_sha256 (preserving any alias conflict in the digest)
      - full canonical recipient ledger (preserving non-dict/non-list malformations, sorted by recipient_id)
    Semantic canonicalization: adding a matching top-level lot_to_wcb_manifest alongside identical nested WCB
    declarations inside lot_to_mcb_manifest AND replacing/adding a matching recipient `working_cell_bank_id`
    <-> `wcb_id` preserve semantic WCB ancestry identity and leave this digest invariant, whereas ANY semantic
    ancestry mutation, WCB alias conflict, invalid type, control-flag mutation/omission, widening, or
    post-attestation addition of lot_to_bank_manifest or unrecognized manifest alias keys alters this digest
    and fails closed.
    """
    recipients_raw = cohort_payload.get("recipients")
    if isinstance(recipients_raw, list):
        rec_items: list[tuple[int, str, str, Any]] = []
        for r in recipients_raw:
            if isinstance(r, dict):
                crec = _canonicalize_gate28a_recipient(r)
                cjson = json.dumps(crec, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
                rid_key = str(r.get("recipient_id", ""))
                rec_items.append((0, rid_key, cjson, ["rec", crec]))
            else:
                cval = _canonicalize_gate28a_value(r)
                cjson = json.dumps(cval, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
                rec_items.append((1, "", cjson, ["non_dict_rec", cval]))
        rec_items.sort(key=lambda item: (item[0], item[1], item[2]))
        norm_recs: Any = [item[3] for item in rec_items]
    else:
        norm_recs = ["non_list_recipients", _canonicalize_gate28a_value(recipients_raw)]

    mcb_raw = cohort_payload.get("lot_to_mcb_manifest")
    mcb_norm, emb_wcb, mcb_errs = _normalize_lot_to_mcb_manifest(mcb_raw, field_name="lot_to_mcb_manifest")
    wcb_raw = cohort_payload.get("lot_to_wcb_manifest")
    wcb_norm, wcb_errs = _normalize_lot_to_wcb_manifest(wcb_raw)
    if mcb_norm is not None and not mcb_errs:
        mcb_canon: Any = ["mcb_ok", dict(sorted(mcb_norm.items()))]
    else:
        mcb_canon = ["mcb_raw", _canonicalize_gate28a_value(mcb_raw)]
    if wcb_raw is None:
        wcb_canon: Any = ["wcb_ok", dict(sorted(emb_wcb.items()))] if emb_wcb else ["wcb_none"]
    elif wcb_norm is not None and not wcb_errs:
        has_wcb_conflict = any(lid in emb_wcb and emb_wcb[lid] != wid for lid, wid in wcb_norm.items())
        if has_wcb_conflict:
            wcb_canon = [
                "wcb_conflict",
                {
                    "embedded_wcb_manifest": dict(sorted(emb_wcb.items())),
                    "explicit_wcb_manifest": dict(sorted(wcb_norm.items())),
                },
            ]
        else:
            merged_wcb = dict(emb_wcb)
            merged_wcb.update(wcb_norm)
            wcb_canon = ["wcb_ok", dict(sorted(merged_wcb.items()))] if merged_wcb else ["wcb_none"]
    else:
        wcb_canon = ["wcb_raw", _canonicalize_gate28a_value(wcb_raw)]

    bank_alias_raw = cohort_payload.get("lot_to_bank_manifest")
    bank_alias_canon: Any = (
        ["bank_alias", _canonicalize_gate28a_value(bank_alias_raw)] if bank_alias_raw is not None else ["bank_alias_none"]
    )
    extra_aliases = _find_extra_manifest_alias_keys(cohort_payload)
    extra_aliases_canon: Any = (
        ["extra_aliases", _canonicalize_gate28a_value(extra_aliases)] if extra_aliases else ["extra_aliases_none"]
    )

    cmc_sha, cmc_sha_errs = _resolve_payload_cmc_ledger_sha256(cohort_payload)
    if cmc_sha_errs:
        refs_obj = cohort_payload.get("clinical_store_refs")
        cmc_sha_canon: Any = [
            "cmc_sha_error",
            {
                "parallel_cmc_readiness_ledger_sha256": _canonicalize_gate28a_presence_field(
                    cohort_payload, "parallel_cmc_readiness_ledger_sha256"
                ),
                "parallel_cmc_ledger_sha256": _canonicalize_gate28a_presence_field(
                    cohort_payload, "parallel_cmc_ledger_sha256"
                ),
                "clinical_store_refs_parallel_cmc_readiness_ledger_sha256": (
                    _canonicalize_gate28a_presence_field(refs_obj, "parallel_cmc_readiness_ledger_sha256")
                    if isinstance(refs_obj, dict)
                    else {"present": False}
                ),
            },
        ]
    elif cmc_sha is not None:
        cmc_sha_canon = ["cmc_sha_ok", cmc_sha]
    else:
        cmc_sha_canon = ["cmc_sha_none"]

    body = {
        "cohort_id": _canonicalize_gate28a_value(cohort_payload.get("cohort_id")),
        "compatibility_declarations": {
            k: _canonicalize_gate28a_value(cohort_payload.get(k))
            for k in sorted(GATE_28A_COMPATIBILITY_TARGET.keys())
        },
        "includes_reichman": _canonicalize_gate28a_value(cohort_payload.get("includes_reichman")),
        "primary_peer_reviewed_full_text_verified": _canonicalize_gate28a_presence_field(
            cohort_payload, "primary_peer_reviewed_full_text_verified"
        ),
        "parallel_cmc_readiness_ledger_disclosed": _canonicalize_gate28a_presence_field(
            cohort_payload, "parallel_cmc_readiness_ledger_disclosed"
        ),
        "rho_lot": _canonicalize_gate28a_value(cohort_payload.get("rho_lot", GATE_28A_RHO_LOT_MIN)),
        "rho_bank": _canonicalize_gate28a_value(cohort_payload.get("rho_bank", GATE_28A_RHO_BANK_MIN)),
        "lot_to_mcb_manifest": mcb_canon,
        "lot_to_wcb_manifest": wcb_canon,
        "lot_to_bank_manifest": bank_alias_canon,
        "extra_manifest_aliases": extra_aliases_canon,
        "parallel_cmc_readiness_ledger_sha256": cmc_sha_canon,
        "recipients": norm_recs,
    }
    return hashlib.sha256(
        json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    ).hexdigest()


def compute_gate28a_cohort_ledger_sha256(
    cohort_id_or_payload: str | dict[str, Any],
    recipients: list[dict[str, Any]] | None = None,
    lot_to_mcb_manifest: dict[str, Any] | None = None,
    *,
    lot_to_wcb_manifest: dict[str, Any] | None = None,
    lot_to_bank_manifest: dict[str, Any] | None = None,
    includes_reichman: bool = False,
    rho_lot: float | Decimal = GATE_28A_RHO_LOT_MIN,
    rho_bank: float | Decimal = GATE_28A_RHO_BANK_MIN,
    primary_peer_reviewed_full_text_verified: Any = _GATE28A_UNSET,
    parallel_cmc_readiness_ledger_disclosed: Any = _GATE28A_UNSET,
    parallel_cmc_readiness_ledger_sha256: str | None = None,
    compatibility_overrides: dict[str, Any] | None = None,
) -> str:
    """
    Compute the full canonical Gate 28-A attested cohort digest.
    Accepts either a full cohort_payload dict directly OR explicit arguments (binding compatibility
    declarations, includes_reichman, decision-control flags, rho_lot, rho_bank, manifests,
    parallel_cmc_readiness_ledger_sha256, and canonical recipients).
    """
    if isinstance(cohort_id_or_payload, dict):
        return compute_gate28a_cohort_canonical_sha256(cohort_id_or_payload)
    synth: dict[str, Any] = {
        "cohort_id": cohort_id_or_payload,
        **GATE_28A_COMPATIBILITY_TARGET,
        "includes_reichman": includes_reichman,
        "rho_lot": rho_lot,
        "rho_bank": rho_bank,
        "lot_to_mcb_manifest": lot_to_mcb_manifest,
        "lot_to_wcb_manifest": lot_to_wcb_manifest,
        "lot_to_bank_manifest": lot_to_bank_manifest,
        "parallel_cmc_readiness_ledger_sha256": parallel_cmc_readiness_ledger_sha256,
        "recipients": recipients or [],
    }
    if primary_peer_reviewed_full_text_verified is not _GATE28A_UNSET:
        synth["primary_peer_reviewed_full_text_verified"] = primary_peer_reviewed_full_text_verified
    if parallel_cmc_readiness_ledger_disclosed is not _GATE28A_UNSET:
        synth["parallel_cmc_readiness_ledger_disclosed"] = parallel_cmc_readiness_ledger_disclosed
    if compatibility_overrides:
        synth.update(compatibility_overrides)
    return compute_gate28a_cohort_canonical_sha256(synth)


def compute_gate28a_record_sha256(record: dict[str, Any]) -> str:
    """Canonical SHA-256 digest of a Gate 28-A store record excluding `record_sha256` and `attestation_sha256`."""
    body = {k: v for k, v in record.items() if k not in ("record_sha256", "attestation_sha256")}