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…

            if identifier in identifiers:
                raise ValueError("Product identifiers and aliases must be globally unique")
            identifiers.add(identifier)

    missing_b2 = STAGED_DESIGN_B2_PRODUCT_IDS - by_id.keys()
    if missing_b2:
        raise ValueError(f"Missing required staged Design B2 product definitions: {sorted(missing_b2)} (IIP-0026; DEC-105)")
    missing_l2_v3 = STAGED_LOCUS2_V3_PRODUCT_IDS - by_id.keys()
    if missing_l2_v3:
        raise ValueError(f"Missing required staged Locus-2 v3 product definitions: {sorted(missing_l2_v3)} (IIP-0031; DEC-110)")
    missing_dy2 = STAGED_DESIGN_Y_V2_PRODUCT_IDS - by_id.keys()
    if missing_dy2:
        raise ValueError(f"Missing required staged Design Y-FullStack v2 product definitions: {sorted(missing_dy2)} (IIP-0034; DEC-113)")
    missing_d1b = STAGED_D1B_AUTO_V2_PRODUCT_IDS - by_id.keys()
    if missing_d1b:
        raise ValueError(f"Missing required staged Autologous D1b-Auto-C v2 product definitions: {sorted(missing_d1b)} (IIP-0035; DEC-114)")

    fasta_file = root / DESIGN_B_FASTA_PATH
    if require_staged_fastas or fasta_file.exists():
        if not fasta_file.is_file():
            raise ValueError(f"Missing or non-regular staged Design B FASTA: {fasta_file} (IIP-0026; DEC-105)")
        raw_bytes = fasta_file.read_bytes()
        if hashlib.sha256(raw_bytes).hexdigest() != DESIGN_B_FASTA_SHA256:
            raise ValueError("Staged Design B FASTA SHA-256 mismatch against registry pin (IIP-0026; DEC-105)")
        try:
            seq_map = _parse_fasta_map(raw_bytes.decode("utf-8"))
        except UnicodeDecodeError as exc:
            raise ValueError("Staged Design B FASTA is not valid UTF-8 (IIP-0026; DEC-105)") from exc
        c1_seq = seq_map.get(DESIGN_B_C1_ID, "")
        c5_seq = seq_map.get(DESIGN_B_C5_ID, "")
        pair_sha = hashlib.sha256((c1_seq + "|" + c5_seq).encode("utf-8")).hexdigest()
        if (
            len(c1_seq) != DESIGN_B_C1_LENGTH_BP
            or len(c5_seq) != DESIGN_B_C5_LENGTH_BP
            or hashlib.sha256(c1_seq.encode("utf-8")).hexdigest() != DESIGN_B_C1_SHA256
            or hashlib.sha256(c5_seq.encode("utf-8")).hexdigest() != DESIGN_B_C5_SHA256
            or pair_sha != DESIGN_B_BOUND_C1_C5_PAIR_SHA256
        ):
            raise ValueError("Staged Design B c1+c5 pair digest or length mismatch against registry pin (IIP-0026; DEC-105)")

    l2_fasta_file = root / LOCUS2_V3_FASTA_PATH
    if require_staged_fastas or l2_fasta_file.exists():
        if not l2_fasta_file.is_file():
            raise ValueError(f"Missing or non-regular staged Locus-2 CIITA Mode-B v3 FASTA: {l2_fasta_file} (IIP-0031; DEC-110)")
        l2_raw = l2_fasta_file.read_bytes()
        if hashlib.sha256(l2_raw).hexdigest() != LOCUS2_V3_FASTA_SHA256:
            raise ValueError("Staged Locus-2 CIITA Mode-B v3 FASTA SHA-256 mismatch against registry pin (IIP-0031; DEC-110)")
        try:
            l2_map = _parse_fasta_map(l2_raw.decode("utf-8"))
        except UnicodeDecodeError as exc:
            raise ValueError("Staged Locus-2 CIITA Mode-B v3 FASTA is not valid UTF-8 (IIP-0031; DEC-110)") from exc
        for _pvid, _spec in LOCUS2_V3_DONOR_BINDINGS.items():
            _did = str(_spec["locus2_donor_id"])
            _seq = l2_map.get(_did, "")
            _exp_len = _spec["donor_length_bp"]
            if (
                type(_exp_len) is not int
                or len(_seq) != _exp_len
                or hashlib.sha256(_seq.encode("utf-8")).hexdigest() != str(_spec["locus2_donor_sha256"])
            ):
                raise ValueError(f"Staged Locus-2 donor digest or length mismatch for {_did} (IIP-0031; DEC-110)")

    dy2_fasta_file = root / DESIGN_Y_V2_FASTA_PATH
    if require_staged_fastas or dy2_fasta_file.exists():
        if not dy2_fasta_file.is_file():
            raise ValueError(f"Missing or non-regular staged Design Y-FullStack v2 FASTA: {dy2_fasta_file} (IIP-0034; DEC-113)")
        dy2_raw = dy2_fasta_file.read_bytes()
        if hashlib.sha256(dy2_raw).hexdigest() != DESIGN_Y_V2_FASTA_SHA256:
            raise ValueError("Staged Design Y-FullStack v2 FASTA SHA-256 mismatch against registry pin (IIP-0034; DEC-113)")
        try:
            dy2_map = _parse_fasta_map(dy2_raw.decode("utf-8"))
        except UnicodeDecodeError as exc:
            raise ValueError("Staged Design Y-FullStack v2 FASTA is not valid UTF-8 (IIP-0034; DEC-113)") from exc
        for _pvid, _spec in DESIGN_Y_V2_DONOR_BINDINGS.items():
            _rid = str(_spec["fasta_record_id"])
            _seq = dy2_map.get(_rid, "")
            if len(_seq) != int(_spec["donor_length_bp"]) or hashlib.sha256(_seq.encode("utf-8")).hexdigest() != str(_spec["donor_sha256"]):
                raise ValueError(f"Staged Design Y-FullStack v2 record digest or length mismatch for {_rid} (IIP-0034; DEC-113)")

    d1b_fasta_file = root / D1B_AUTO_V2_FASTA_PATH
    if require_staged_fastas or d1b_fasta_file.exists():
        if not d1b_fasta_file.is_file():
            raise ValueError(f"Missing or non-regular staged Autologous D1b-Auto-C v2 FASTA: {d1b_fasta_file} (IIP-0035; DEC-114)")
        d1b_raw = d1b_fasta_file.read_bytes()
        if hashlib.sha256(d1b_raw).hexdigest() != D1B_AUTO_V2_FASTA_SHA256:
            raise ValueError("Staged Autologous D1b-Auto-C v2 FASTA SHA-256 mismatch against registry pin (IIP-0035; DEC-114)")
        try:
            d1b_map = _parse_fasta_map(d1b_raw.decode("utf-8"))
        except UnicodeDecodeError as exc:
            raise ValueError("Staged Autologous D1b-Auto-C v2 FASTA is not valid UTF-8 (IIP-0035; DEC-114)") from exc
        for _pvid, _spec in D1B_AUTO_V2_DONOR_BINDINGS.items():
            _rid = str(_spec["fasta_record_id"])
            _seq = d1b_map.get(_rid, "")
            if len(_seq) != int(_spec["donor_length_bp"]) or hashlib.sha256(_seq.encode("utf-8")).hexdigest() != str(_spec["donor_sha256"]):
                raise ValueError(f"Staged Autologous D1b-Auto-C v2 record digest or length mismatch for {_rid} (IIP-0035; DEC-114)")

    return payload


def validate_product_definition(product: dict) -> dict:
    if not isinstance(product, dict):
        raise ValueError("Product definition must be a dictionary")
    required = {
        "product_variant_id", "family", "dsb_or_indel_loci", "base_or_prime_edit_loci",
        "alleles", "cassette_topology", "K", "B", "sequence_materialization_status",
        "physical_qualification_status", "execution_supported", "donor_lineage",
        "hla_retention", "pending_assay_gates", "physical_manufacturing_yield",
    }
    if required - product.keys():
        raise ValueError(f"Incomplete product definition: {sorted(required - product.keys())}")
    pvid = product["product_variant_id"]
    if not isinstance(pvid, str) or pvid != pvid.strip() or not re.fullmatch(r"ISLET1_[A-Z0-9_]+", pvid):
        raise ValueError("Invalid canonical product identifier")
    fam = product["family"]
    if not isinstance(fam, str) or fam not in {"A", "B"}:
        raise ValueError("Unknown product family")
    if type(product["execution_supported"]) is not bool:
        raise ValueError("execution_supported must be boolean")
    if not isinstance(product["sequence_materialization_status"], str):
        raise ValueError("sequence_materialization_status must be a string")
    if not isinstance(product["physical_qualification_status"], str):
        raise ValueError("physical_qualification_status must be a string")
    if "lifecycle_state" in product and (
        not isinstance(product["lifecycle_state"], str)
        or product["lifecycle_state"] not in ALLOWED_DESIGN_B_LIFECYCLE_STATES
    ):
        raise ValueError("Invalid lifecycle_state in product definition (IIP-0026; DEC-105)")
    if not (
        pvid.startswith("ISLET1_" + fam)
        or (fam == "A" and pvid.startswith("ISLET1_COMP_"))
        or (fam == "A" and pvid.startswith("ISLET1_Z_") and product["execution_supported"] is False)
        or (fam == "A" and pvid.startswith("ISLET1_Y_") and product["execution_supported"] is False)
        or (fam == "A" and pvid in STAGED_D1B_AUTO_V2_PRODUCT_IDS and product["execution_supported"] is False)
        or (pvid in {"ISLET1_DESIGN_A_V080_REF", "ISLET1_DESIGN_B_V090", "ISLET1_DESIGN_X_V090", "ISLET1_DESIGN_Y_V3", "ISLET1_DESIGN_D1B_LEAN_K2", "ISLET1_ARM_Z_ENSC_V090"} and product["execution_supported"] is False)
    ):
        raise ValueError("Product identifier conflicts with its family")
    if product["physical_manufacturing_yield"] is not None:
        raise ValueError("Physical manufacturing yield remains unmeasured in this release")
    if "aliases" in product and not isinstance(product["aliases"], list):
        raise ValueError("Aliases must be a list of bounded identifiers")
    aliases = product.get("aliases", [])
    if any(not isinstance(a, str) or not a or a != a.strip() or not re.fullmatch(r"[A-Z0-9_]+", a) for a in aliases):
        raise ValueError("Aliases must be bounded identifiers")
    if len(set(aliases)) != len(aliases) or pvid in aliases:
        raise ValueError("Product aliases must be unique and distinct from the canonical identifier")
    for key in ("alleles", "cassette_topology"):
        value = product[key]
        if not isinstance(value, dict) or not value or any(not isinstance(k, str) or not k.strip() or not isinstance(v, str) or not v.strip() for k, v in value.items()):
            raise ValueError(f"{key} must be a nonempty explicit mapping")
    for key in ("donor_lineage", "hla_retention"):
        if not isinstance(product[key], dict) or not product[key]:
            raise ValueError(f"{key} must explicitly define donor/HLA scope")
    if "donor_seedline_id_required" in product["donor_lineage"] and type(product["donor_lineage"]["donor_seedline_id_required"]) is not bool:
        raise ValueError("donor_seedline_id_required must be boolean (IIP-0024; DEC-103)")
    if "kinship_pi_hat_lt" in product["donor_lineage"] and not _is_valid_kinship_pi_hat(product["donor_lineage"]["kinship_pi_hat_lt"]):
        raise ValueError("kinship_pi_hat_lt must be a finite number in (0, 0.05] (IIP-0024; DEC-103)")
    if "physical_route_id" in product and (not isinstance(product["physical_route_id"], str) or not re.fullmatch(r"[A-Z0-9_]+", product["physical_route_id"])):
        raise ValueError("physical_route_id must be a bounded uppercase identifier (IIP-0024; DEC-103)")
    for k_bp, v_bp in product.items():
        if isinstance(k_bp, str) and k_bp.endswith("_bp") and v_bp is not None:
            if type(v_bp) is not int or v_bp <= 0:
                raise ValueError(f"{k_bp} must be a positive integer")
    gates = product["pending_assay_gates"]
    if not isinstance(gates, list) or not gates or any(not isinstance(g, str) or not g.strip() for g in gates):
        raise ValueError("Explicit pending assay gates are required")
    known_loci = {"B2M", "CIITA", "CXCL10", "AAVS1", "HLA-A", "HLA-B", "TYK2", "INS", "CLYBL", "TBP", "CDK1", "ACTB"}
    for loci_key, count_key in [("dsb_or_indel_loci", "K"), ("base_or_prime_edit_loci", "B")]:
        loci = product[loci_key]
        if not isinstance(loci, list) or any(not isinstance(x, str) or x not in known_loci for x in loci) or len(loci) != len(set(loci)):
            raise ValueError(f"{loci_key} must list unique loci")
        if type(product[count_key]) is not int or product[count_key] != len(loci):
            raise ValueError(f"{count_key} does not match the explicit locus list")
    if not (set(product["dsb_or_indel_loci"]) | set(product["base_or_prime_edit_loci"])) <= product["alleles"].keys():
        raise ValueError("Every edited locus needs an explicit allele definition")

    # Enforce 4-state Design B lifecycle while preserving Family A reference-compiler semantics (IIP-0026; DEC-105)
    # and binding all 8 unscored Locus-2 CIITA Mode-B v3 research comparators (IIP-0031; DEC-110):
    if pvid in STAGED_LOCUS2_V3_PRODUCT_IDS:
        l2_exp = LOCUS2_V3_DONOR_BINDINGS[pvid]
        expected_short_alias = str(l2_exp["locus2_donor_id"])
        if expected_short_alias not in aliases:
            raise ValueError(f"Locus-2 v3 comparator {pvid} must carry pinned donor alias {expected_short_alias} (IIP-0031; DEC-110)")
        for a in aliases:
            if a in STAGED_LOCUS2_V3_PRODUCT_IDS or (a in STAGED_LOCUS2_V3_DONOR_ALIASES and a != expected_short_alias):
                raise ValueError(f"Locus-2 v3 comparator {pvid} claims reserved staged identifier/alias {a!r} (IIP-0031; DEC-110)")
        if fam != l2_exp["family"]:
            raise ValueError("Locus-2 v3 research comparator family conflicts with registry binding (IIP-0031; DEC-110)")
        if product["execution_supported"] is not False:
            raise ValueError("Locus-2 v3 research comparators must keep execution_supported=False (IIP-0031; DEC-110)")
        if product.get("lifecycle_state") != "STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC":
            raise ValueError("Locus-2 v3 research comparators must stay at STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC (IIP-0031; DEC-110)")
        if fam == "A":
            if product["sequence_materialization_status"] != "REFERENCE_DONORS_AVAILABLE_REQUIRES_EDITED_ALLELE_QC":
                raise ValueError("Family A Locus-2 v3 comparator requires REFERENCE_DONORS_AVAILABLE_REQUIRES_EDITED_ALLELE_QC (IIP-0031; DEC-110)")
        else:
            if product["sequence_materialization_status"] != "STAGED_RESEARCH_COMPARATOR_DONORS_BOUND_PENDING_ALLELE_QC":
                raise ValueError("Family B Locus-2 v3 comparator requires STAGED_RESEARCH_COMPARATOR_DONORS_BOUND_PENDING_ALLELE_QC (IIP-0031; DEC-110)")
            _validate_staged_design_b_binding(product.get("staged_design_b_donor_reference_binding"), pvid)
        l2_bind = product.get("staged_locus2_modeb_donor_binding")
        if (
            not isinstance(l2_bind, dict)
            or l2_bind.get("fasta_path") != str(LOCUS2_V3_FASTA_PATH)
            or l2_bind.get("fasta_sha256") != LOCUS2_V3_FASTA_SHA256
            or l2_bind.get("locus2_donor_id") != l2_exp["locus2_donor_id"]
            or l2_bind.get("locus2_donor_sha256") != l2_exp["locus2_donor_sha256"]
            or type(l2_bind.get("donor_length_bp")) is not int
            or l2_bind.get("donor_length_bp") != l2_exp["donor_length_bp"]
            or type(l2_bind.get("nominal_packaged_aav6_bp")) is not int
            or l2_bind.get("nominal_packaged_aav6_bp") != l2_exp["nominal_packaged_aav6_bp"]
            or l2_bind.get("background_id") != l2_exp["background_id"]
            or type(l2_bind.get("has_intronic_mir")) is not bool
            or l2_bind.get("has_intronic_mir") is not l2_exp["has_intronic_mir"]
            or l2_bind.get("mir_class") != l2_exp["mir_class"]
            or l2_bind.get("unit2_cargo") != l2_exp["unit2_cargo"]
            or l2_bind.get("unit2_promoter") != l2_exp["unit2_promoter"]
            or l2_bind.get("barrier_variant_type") != l2_exp["barrier_variant_type"]
            or l2_bind.get("rule_s11_gate_id") != RULE_S11_GATE_ID
        ):
            raise ValueError(f"Invalid or mismatched staged_locus2_modeb_donor_binding for {pvid} (IIP-0031; DEC-110)")
    else:
        if "staged_locus2_modeb_donor_binding" in product:
            raise ValueError(f"Non-staged product {pvid} must not carry staged_locus2_modeb_donor_binding (IIP-0031; DEC-110)")
        for a in aliases:
            if a in STAGED_LOCUS2_V3_PRODUCT_IDS or a in STAGED_LOCUS2_V3_DONOR_ALIASES or a.startswith("L2_V3_"):
                raise ValueError(f"Non-staged product {pvid} must not claim reserved Locus-2 v3 identifier/alias {a!r} (IIP-0031; DEC-110)")
        if fam == "A":
            if product["sequence_materialization_status"] != "REFERENCE_DONORS_AVAILABLE_REQUIRES_EDITED_ALLELE_QC":
                raise ValueError("Sequence materialization status conflicts with the product family")
        elif pvid in STAGED_DESIGN_B2_PRODUCT_IDS:
            if product["sequence_materialization_status"] != "STAGED_RESEARCH_COMPARATOR_DONORS_BOUND_PENDING_ALLELE_QC":
                raise ValueError("Staged Design B2 variants require STAGED_RESEARCH_COMPARATOR_DONORS_BOUND_PENDING_ALLELE_QC (IIP-0026; DEC-105)")
            if product.get("lifecycle_state") != "STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC":
                raise ValueError("Staged Design B2 variants must remain at State 3 STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC (IIP-0026; DEC-105)")
            _validate_staged_design_b_binding(product.get("staged_design_b_donor_reference_binding"), pvid)
        else:
            if product["sequence_materialization_status"] != "NOT_MATERIALIZED_SEPARATE_DONOR_LEDGER_REQUIRED":
                raise ValueError("Sequence materialization status conflicts with the product family")

    if "staged_design_b_donor_pair_binding" in product:
        _validate_staged_design_b_binding(product["staged_design_b_donor_pair_binding"], pvid)
    if pvid in STAGED_DESIGN_Y_V2_PRODUCT_IDS:
        _dy2_exp = DESIGN_Y_V2_DONOR_BINDINGS[pvid]
        if product["execution_supported"] is not False:
            raise ValueError(f"Staged Design Y-FullStack v2 comparator {pvid} must keep execution_supported=False (IIP-0034; DEC-113)")
        if product.get("lifecycle_state") != "STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC":
            raise ValueError(f"Staged Design Y-FullStack v2 comparator {pvid} must stay at STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC (IIP-0034; DEC-113)")
        if product.get("physical_route_id") != "ROUTE_3P_MODULAR_PLANAR_ENVELOPE":
            raise ValueError(f"Staged Design Y-FullStack v2 comparator {pvid} must declare physical_route_id=ROUTE_3P_MODULAR_PLANAR_ENVELOPE (IIP-0034; DEC-113)")
        _dy2_bind = product.get("staged_design_y_fullstack_v2_donor_binding")
        _rec_sha = hashlib.sha256(json.dumps(product, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest()