OpenIslet

scripts/product_contract.py

Versioned exact-product identifiers shared by the ranking and scenario planes.

script Release v0.8.0 gen-eb955f8266035aba 52 KB · 4 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/product_contract.py · SHA-256: cdea1adb1914ce0e…

        "donor_sha256": "4ff3748792ecf8d8cb6f0e17f9b016552a67a3f81b7677c524984703986a4b97",
        "donor_length_bp": 4100,
        "nominal_aav6_packaged_bp": 4390,
        "tu_count": 2,
        "pigk_ectopic_gpi_count": 0,
        "encoded_2a_motifs_6frame": 0,
        "role": "SECONDARY_GATE0V_LOCUS1_CIITA_CD46WT_CD64T_COMPARATOR",
        "stage0_promotion_gates": "D1-01..D1-09 + structured lot-matched global_gate0v_record (secondary single-locus CIITA donor keyed as full-panel comparator scenario; assembled multi-locus manifest binding L1B+L2+L3+L4 required for clinical product identity)",
        "full_record_sha256": "3aeb50de51ba8e1f09f75ce90563be4ddafe10b5b893ce6c7da420f838c1cc18",
        "expected_alias": "D1AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR",
    },
    "ISLET1_D1_AUTO_V2_L2_CXCL10_SERPINB9_PDL1": {
        "proposal_id": "IIP-0035",
        "decision_id": "DEC-114",
        "fasta_record_id": "D1AUTO_v2_L2_CXCL10_SERPINB9_PDL1",
        "donor_sha256": "8f2dd931b41d1c00de5d62832008b7da765286d5b0f6c7d6c9ed730b3c9416c8",
        "donor_length_bp": 3701,
        "nominal_aav6_packaged_bp": 3991,
        "tu_count": 2,
        "pigk_ectopic_gpi_count": 0,
        "encoded_2a_motifs_6frame": 0,
        "role": "LOCUS2_CXCL10_SERPINB9_PDL1_SINGLE_AAV6",
        "stage0_promotion_gates": "COMPONENT_ONLY_EXCLUDED_FROM_FULLSTACK_CLEARANCE (L2 chr4 CXCL10::SERPINB9+PD-L1 D1-08 component evidence only)",
        "full_record_sha256": "6efbfab3f513426566eac64ab4fd8c5b06611c033a1a057d3b219c20776d2bd6",
        "expected_alias": "D1AUTO_V2_L2_CXCL10_SERPINB9_PDL1",
    },
    "ISLET1_D1_AUTO_V2_L3_AAVS1_VTCN1_UCOE2S_ICASP9": {
        "proposal_id": "IIP-0035",
        "decision_id": "DEC-114",
        "fasta_record_id": "D1AUTO_v2_L3_AAVS1_VTCN1_UCOE2S_ICASP9",
        "donor_sha256": "440d8b0399d79e239f6f9ec6fb6964ce1f3d70ac62ac5ef22336cf2a3f965092",
        "donor_length_bp": 4320,
        "nominal_aav6_packaged_bp": 4610,
        "tu_count": 2,
        "pigk_ectopic_gpi_count": 0,
        "encoded_2a_motifs_6frame": 0,
        "role": "LOCUS3_AAVS1_VTCN1_UCOE2S_ICASP9_DEC053_SW1",
        "stage0_promotion_gates": "COMPONENT_ONLY_EXCLUDED_FROM_FULLSTACK_CLEARANCE (L3 chr19 AAVS1 Switch #1 + VTCN1 D1-04/D1-05/D1-07 component evidence only)",
        "full_record_sha256": "4688e2a2c30fc3e39d6391c17c42e391a7243825435d7bad906e3e720751ee91",
        "expected_alias": "D1AUTO_V2_L3_AAVS1_VTCN1_UCOE2S_ICASP9",
    },
    "ISLET1_D1_AUTO_V2_L4_CLYBL_TANDEM_TUBA1B_FSP1_CHS4_CDK1_HTMPK_F105Y": {
        "proposal_id": "IIP-0035",
        "decision_id": "DEC-114",
        "fasta_record_id": "D1AUTO_v2_L4_CLYBL_TANDEM_TUBA1B_FSP1_CHS4_CDK1_HTMPK_F105Y",
        "donor_sha256": "fae0a4f597297aefc0b774532ef36885b5f65ba625df257e4fe9c0410adbc7f8",
        "donor_length_bp": 4067,
        "nominal_aav6_packaged_bp": 4357,
        "tu_count": 2,
        "pigk_ectopic_gpi_count": 0,
        "encoded_2a_motifs_6frame": 0,
        "role": "LOCUS4_CHR13_CLYBL_TANDEM_FSP1_CDK1_HTMPK_DEC053_SW2",
        "stage0_promotion_gates": "COMPONENT_ONLY_EXCLUDED_FROM_FULLSTACK_CLEARANCE (L4 chr13 CLYBL tandem FSP1+CDK1::hTMPK-F105Y D1-04/D1-05 component evidence only)",
        "full_record_sha256": "fb74dd5d7b22a32c02a6e18fa5164f091dfbe575b82d2569c2af008c63fd8416",
        "expected_alias": "D1AUTO_V2_L4_CLYBL_TANDEM_TUBA1B_FSP1_CHS4_CDK1_HTMPK_F105Y",
    },
}
STAGED_D1B_AUTO_V2_PRODUCT_IDS = frozenset(D1B_AUTO_V2_DONOR_BINDINGS.keys())
STAGED_D1B_AUTO_V2_DONOR_ALIASES = frozenset(str(spec["expected_alias"]) for spec in D1B_AUTO_V2_DONOR_BINDINGS.values())


def _reject_nonfinite_product_json(token: str) -> Any:
    raise ValueError(f"Non-standard JSON constant rejected in product registry: {token!r}")


def _parse_finite_product_json_float(token: str) -> float:
    val = float(token)
    if not math.isfinite(val):
        raise ValueError(f"Non-finite JSON float overflow rejected in product registry: {token!r}")
    try:
        if Decimal(str(val)) != Decimal(token):
            raise ValueError(f"Precision-losing or underflowing JSON float rejected in product registry: {token!r}")
    except InvalidOperation as exc:
        raise ValueError(f"Malformed JSON float token in product registry: {token!r}") from exc
    return val


def _is_valid_kinship_pi_hat(val: object) -> bool:
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        return False
    if isinstance(val, float) and not math.isfinite(val):
        return False
    try:
        d = Decimal(str(val))
    except InvalidOperation:
        return False
    return d.is_finite() and Decimal("0") < d <= Decimal("0.05")
ALLOWED_DESIGN_B_LIFECYCLE_STATES = frozenset({
    "STAGED_REFERENCE_FASTA_ARTIFACT",
    "REGISTRY_DONOR_REFERENCE_BOUND",
    "STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC",
    "EXECUTION_SUPPORTED_QUALIFIED_PRODUCT",
})


def _reject_duplicate_json_keys(pairs: list[tuple[str, object]]) -> dict[str, object]:
    out: dict[str, object] = {}
    for key, value in pairs:
        if key in out:
            raise ValueError(f"Duplicate JSON key in product registry: {key!r}")
        out[key] = value
    return out


def _strict_json_equal(a: object, b: object) -> bool:
    if type(a) is not type(b):
        return False
    if isinstance(a, dict):
        return a.keys() == b.keys() and all(_strict_json_equal(a[k], b[k]) for k in a)
    if isinstance(a, list):
        return len(a) == len(b) and all(_strict_json_equal(x, y) for x, y in zip(a, b))
    if isinstance(a, float):
        return math.isnan(a) == math.isnan(b) and a == b
    return a == b


def _parse_fasta_map(fasta_text: str) -> dict[str, str]:
    records: dict[str, str] = {}
    cur_id: str | None = None
    buf: list[str] = []
    for raw in fasta_text.splitlines():
        ln = raw.strip()
        if not ln:
            continue
        if ln.startswith(">"):
            if cur_id is not None:
                raw_seq = "".join(buf)
                if not raw_seq or not all(ch in "ACGTacgt" for ch in raw_seq):
                    raise ValueError(f"Empty or non-ACGT sequence in FASTA record {cur_id!r}")
                records[cur_id] = raw_seq.upper()
            tokens = ln[1:].split()
            if not tokens:
                raise ValueError("Empty FASTA record header")
            cur_id = tokens[0]
            if cur_id in records:
                raise ValueError(f"Duplicate FASTA record identifier: {cur_id!r}")
            buf = []
        else:
            if cur_id is None:
                raise ValueError("FASTA sequence data encountered before first header")
            buf.append(ln)
    if cur_id is not None:
        raw_seq = "".join(buf)
        if not raw_seq or not all(ch in "ACGTacgt" for ch in raw_seq):
            raise ValueError(f"Empty or non-ACGT sequence in FASTA record {cur_id!r}")
        records[cur_id] = raw_seq.upper()
    if not records:
        raise ValueError("Empty FASTA file")
    return records


def _validate_staged_design_b_binding(binding: object, product_variant_id: str) -> None:
    if (
        not isinstance(binding, dict)
        or binding.get("fasta_path") != str(DESIGN_B_FASTA_PATH)
        or binding.get("fasta_sha256") != DESIGN_B_FASTA_SHA256
        or binding.get("cxcl10_locus5_primary_donor_id") != DESIGN_B_C1_ID
        or binding.get("cxcl10_locus5_primary_donor_sha256") != DESIGN_B_C1_SHA256
        or binding.get("aavs1_locus6_primary_donor_id") != DESIGN_B_C5_ID
        or binding.get("aavs1_locus6_primary_donor_sha256") != DESIGN_B_C5_SHA256
        or binding.get("bound_c1_c5_pair_sha256") != DESIGN_B_BOUND_C1_C5_PAIR_SHA256
    ):
        raise ValueError(
            f"Invalid or mismatched staged Design B donor binding for {product_variant_id} (IIP-0026; DEC-105)"
        )
    if "cxcl10_locus5_primary_donor_length_bp" in binding and (
        type(binding["cxcl10_locus5_primary_donor_length_bp"]) is not int
        or binding["cxcl10_locus5_primary_donor_length_bp"] != DESIGN_B_C1_LENGTH_BP
    ):
        raise ValueError(f"Invalid cxcl10_locus5_primary_donor_length_bp for {product_variant_id}")
    if "aavs1_locus6_primary_donor_length_bp" in binding and (
        type(binding["aavs1_locus6_primary_donor_length_bp"]) is not int
        or binding["aavs1_locus6_primary_donor_length_bp"] != DESIGN_B_C5_LENGTH_BP
    ):
        raise ValueError(f"Invalid aavs1_locus6_primary_donor_length_bp for {product_variant_id}")


def load_product_contracts(
    root: Path | str | None = None,
    *,
    require_staged_fastas: bool = True,
) -> dict:
    if type(require_staged_fastas) is not bool:
        raise ValueError("require_staged_fastas must be a bool")
    root = Path(root) if root is not None else Path(__file__).resolve().parents[1]
    contract_file = root / CONTRACT_PATH
    if not contract_file.is_file():
        raise ValueError(f"Missing or non-regular product registry file: {contract_file}")
    try:
        raw_json = contract_file.read_text(encoding="utf-8")
    except UnicodeDecodeError as exc:
        raise ValueError(f"Product registry is not valid UTF-8: {contract_file}") from exc
    payload = json.loads(raw_json, object_pairs_hook=_reject_duplicate_json_keys, parse_constant=_reject_nonfinite_product_json, parse_float=_parse_finite_product_json_float)
    if not isinstance(payload, dict) or not isinstance(payload.get("products"), list):
        raise ValueError("Product registry must contain a products list")
    if require_staged_fastas and ("mcb_donor_blocking_policy" not in payload or "design_b_four_state_lifecycle_policy" not in payload):
        raise ValueError("Product registry missing required mcb_donor_blocking_policy or design_b_four_state_lifecycle_policy")
    if "mcb_donor_blocking_policy" in payload:
        pol = payload["mcb_donor_blocking_policy"]
        if (
            not isinstance(pol, dict)
            or type(pol.get("min_independent_abo_oo_seedlines")) is not int
            or pol["min_independent_abo_oo_seedlines"] < 2
            or not _is_valid_kinship_pi_hat(pol.get("kinship_pi_hat_lt"))
            or type(pol.get("donor1_paired_lot_blocks_min")) is not int
            or pol["donor1_paired_lot_blocks_min"] < 6
            or type(pol.get("confirmatory_welch_tost_lots_per_bank")) is not int
            or pol["confirmatory_welch_tost_lots_per_bank"] < 6
        ):
            raise ValueError("Invalid mcb_donor_blocking_policy in product registry (IIP-0024; DEC-103)")
    if "design_b_four_state_lifecycle_policy" in payload:
        lc_pol = payload["design_b_four_state_lifecycle_policy"]
        states = lc_pol.get("states") if isinstance(lc_pol, dict) else None
        required_state_keys = {
            "STATE_1_STAGED_REFERENCE_FASTA_ARTIFACT",
            "STATE_2_REGISTRY_DONOR_REFERENCE_BOUND",
            "STATE_3_STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC",
            "STATE_4_EXECUTION_SUPPORTED_QUALIFIED_PRODUCT",
        }
        if (
            not isinstance(states, dict)
            or set(states.keys()) != required_state_keys
            or any(not isinstance(v, dict) for v in states.values())
            or states["STATE_1_STAGED_REFERENCE_FASTA_ARTIFACT"].get("fasta_sha256") != DESIGN_B_FASTA_SHA256
            or (
                "construct_count" in states["STATE_1_STAGED_REFERENCE_FASTA_ARTIFACT"]
                and (
                    type(states["STATE_1_STAGED_REFERENCE_FASTA_ARTIFACT"]["construct_count"]) is not int
                    or states["STATE_1_STAGED_REFERENCE_FASTA_ARTIFACT"]["construct_count"] != 6
                )
            )
            or states["STATE_2_REGISTRY_DONOR_REFERENCE_BOUND"].get("bound_c1_c5_pair_sha256") != DESIGN_B_BOUND_C1_C5_PAIR_SHA256
            or states["STATE_3_STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC"].get("execution_supported") is not False
            or type(states["STATE_4_EXECUTION_SUPPORTED_QUALIFIED_PRODUCT"].get("currently_achieved_family_b_count")) is not int
            or states["STATE_4_EXECUTION_SUPPORTED_QUALIFIED_PRODUCT"].get("currently_achieved_family_b_count") != 0
        ):
            raise ValueError("Invalid design_b_four_state_lifecycle_policy in product registry (IIP-0026; DEC-105)")

    products = payload["products"]
    if not products or any(not isinstance(p, dict) for p in products):
        raise ValueError("Product registry products must be a nonempty list of dictionaries")
    for product in products:
        validate_product_definition(product)
    if len({p["product_variant_id"] for p in products}) != len(products):
        raise ValueError("Product variants must be nonempty and unique")
    identifiers: set[str] = set()
    by_id: dict[str, dict] = {}
    for product in products:
        by_id[product["product_variant_id"]] = product
        for identifier in [product["product_variant_id"], *product.get("aliases", [])]: