OpenIslet

scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py

W6-C3 (Provisional Next-Free IIP-0057 / DEC-138 / GATE-36 / GY-035; staging slot iip0057,

script Release v0.8.0 gen-eb955f8266035aba 412 KB · 32 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_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py · SHA-256: 1c63dcf649c42be4…

        if last_dose_day > -7:
            fail_reasons.append(f"{rtag}LAST_DOSE_DAY_POST_TRANSPLANT_OR_LATE_FAIL:day={last_dose_day}>-7")
        if admin_days is not None and last_dose_day != max(admin_days):
            fail_reasons.append(f"{rtag}LAST_DOSE_DAY_INCONSISTENT_WITH_SCHEDULE:{last_dose_day}!={max(admin_days)}")

    has_cday, cday_raw = _opt("clearance_sample_day")
    clearance_sample_day = _require_exact_int(cday_raw, f"{pfx}clearance_sample_day", lo=-365, hi=365) if has_cday else None
    if clearance_sample_day is not None:
        if clearance_sample_day > -4:
            fail_reasons.append(f"{rtag}CLEARANCE_SAMPLE_DAY_AFTER_DAY_MINUS4_FAIL:day={clearance_sample_day}>-4")
        if last_dose_day is not None and clearance_sample_day <= last_dose_day:
            fail_reasons.append(f"{rtag}CLEARANCE_SAMPLE_NOT_AFTER_LAST_DOSE_FAIL:sample={clearance_sample_day}<=dose={last_dose_day}")

    # Distinct matrix-specific governed validated assay registries
    has_paid, paid_raw = _opt("plasma_assay_id")
    plasma_assay_id = _require_canonical_ascii_id(paid_raw, f"{pfx}plasma_assay_id", rtag=rtag, fail_reasons=fail_reasons) if has_paid else None
    if plasma_assay_id is not None and plasma_assay_id not in GOVERNED_INVVAX_PLASMA_ASSAY_REGISTRY:
        fail_reasons.append(f"{rtag}UNREGISTERED_INVVAX_PLASMA_ASSAY_ID:{plasma_assay_id}")

    has_lnaid, lnaid_raw = _opt("lymph_node_assay_id")
    lymph_node_assay_id = _require_canonical_ascii_id(lnaid_raw, f"{pfx}lymph_node_assay_id", rtag=rtag, fail_reasons=fail_reasons) if has_lnaid else None
    if lymph_node_assay_id is not None and lymph_node_assay_id not in GOVERNED_INVVAX_LYMPH_NODE_ASSAY_REGISTRY:
        fail_reasons.append(f"{rtag}UNREGISTERED_INVVAX_LYMPH_NODE_ASSAY_ID:{lymph_node_assay_id}")

    if plasma_assay_id is not None and lymph_node_assay_id is not None and plasma_assay_id == lymph_node_assay_id:
        fail_reasons.append(f"{rtag}INVVAX_DUPLICATE_MATRIX_ASSAY_ID_FAIL:{plasma_assay_id}")

    _validate_optional_canonical_id_list(
        src,
        keys=("subject_ids", "donor_ids"),
        expected_count=None,
        min_unique=None,
        pfx=pfx,
        rtag=rtag,
        module_tag="INVVAX",
        fail_reasons=fail_reasons,
    )

    # Qualified assay LLOD ceilings (<= 1.0) + STRICT quantitative measurements < LLOD (ZERO tolerance!)
    has_pllod, pllod_raw = _opt("plasma_llod_ng_ml")
    plasma_llod = _require_bounded_float(pllod_raw, f"{pfx}plasma_llod_ng_ml", lo=0.0, hi=1e12, strict_lo=True) if has_pllod else None
    if plasma_llod is not None and plasma_llod > 1.0:
        fail_reasons.append(f"{rtag}PLASMA_ASSAY_LLOD_UNQUALIFIED_ABOVE_1_NG_ML:{plasma_llod}")

    has_tllod, tllod_raw = _opt("tissue_llod_ng_g")
    tissue_llod = _require_bounded_float(tllod_raw, f"{pfx}tissue_llod_ng_g", lo=0.0, hi=1e12, strict_lo=True) if has_tllod else None
    if tissue_llod is not None and tissue_llod > 1.0:
        fail_reasons.append(f"{rtag}TISSUE_ASSAY_LLOD_UNQUALIFIED_ABOVE_1_NG_G:{tissue_llod}")
    if "lymph_node_llod_ng_ml" in src and src["lymph_node_llod_ng_ml"] is not None:
        ln_llod_alias = _require_bounded_float(src["lymph_node_llod_ng_ml"], f"{pfx}lymph_node_llod_ng_ml", lo=0.0, hi=1e12, strict_lo=True)
        if ln_llod_alias > 1.0:
            fail_reasons.append(f"{rtag}LYMPH_NODE_LLOD_ALIAS_ABOVE_1_FAIL:{ln_llod_alias}")
        if tissue_llod is not None and ln_llod_alias != tissue_llod:
            fail_reasons.append(f"{rtag}LYMPH_NODE_LLOD_ALIAS_MISMATCH:{ln_llod_alias}!={tissue_llod}")

    has_pconc, pconc_raw = _opt("measured_plasma_conc_ng_ml")
    plasma_conc = _require_bounded_float(pconc_raw, f"{pfx}measured_plasma_conc_ng_ml", lo=0.0, hi=1e12) if has_pconc else None
    if plasma_conc is not None and plasma_llod is not None and plasma_conc >= plasma_llod:
        fail_reasons.append(f"{rtag}PLASMA_CLEARANCE_NOT_BELOW_LLOD:{plasma_conc!r}>={plasma_llod!r}")
    if "plasma_conc_day0_ng_ml" in src and src["plasma_conc_day0_ng_ml"] is not None:
        pc_alias = _require_bounded_float(src["plasma_conc_day0_ng_ml"], f"{pfx}plasma_conc_day0_ng_ml", lo=0.0, hi=1e12)
        if plasma_llod is not None and pc_alias >= plasma_llod:
            fail_reasons.append(f"{rtag}PLASMA_CONC_DAY0_ALIAS_NOT_BELOW_LLOD:{pc_alias!r}>={plasma_llod!r}")
        if plasma_conc is not None and pc_alias != plasma_conc:
            fail_reasons.append(f"{rtag}PLASMA_CONC_DAY0_ALIAS_MISMATCH:{pc_alias!r}!={plasma_conc!r}")

    has_tconc, tconc_raw = _opt("measured_tissue_conc_ng_g")
    tissue_conc = _require_bounded_float(tconc_raw, f"{pfx}measured_tissue_conc_ng_g", lo=0.0, hi=1e12) if has_tconc else None
    if tissue_conc is not None and tissue_llod is not None and tissue_conc >= tissue_llod:
        fail_reasons.append(f"{rtag}TISSUE_CLEARANCE_NOT_BELOW_LLOD:{tissue_conc!r}>={tissue_llod!r}")
    if "lymph_node_conc_day0_ng_ml" in src and src["lymph_node_conc_day0_ng_ml"] is not None:
        tc_alias = _require_bounded_float(src["lymph_node_conc_day0_ng_ml"], f"{pfx}lymph_node_conc_day0_ng_ml", lo=0.0, hi=1e12)
        if tissue_llod is not None and tc_alias >= tissue_llod:
            fail_reasons.append(f"{rtag}LYMPH_NODE_CONC_DAY0_ALIAS_NOT_BELOW_LLOD:{tc_alias!r}>={tissue_llod!r}")
        if tissue_conc is not None and tc_alias != tissue_conc:
            fail_reasons.append(f"{rtag}LYMPH_NODE_CONC_DAY0_ALIAS_MISMATCH:{tc_alias!r}!={tissue_conc!r}")

    has_ae, ae_raw = _opt("max_ae_grade")
    ae = _require_exact_int(ae_raw, f"{pfx}max_ae_grade", lo=0, hi=5) if has_ae else None
    if ae is not None:
        if ae >= 2:
            fail_reasons.append(f"{rtag}ADVERSE_EVENT_GRADE_FAIL:{ae}")
        elif ae == 1:
            hold_reasons.append(f"{rtag}ADVERSE_EVENT_GRADE_1_HOLD:{ae}")

    has_d90, d90_raw = _opt("day90_cpeptide_retention_pct")
    d90 = _require_bounded_float(d90_raw, f"{pfx}day90_cpeptide_retention_pct", lo=0.0, hi=200.0) if has_d90 else None
    if d90 is not None:
        if d90 < 60.0:
            fail_reasons.append(f"{rtag}DAY90_CPEPTIDE_FAIL:{d90}%")
        elif d90 < 80.0:
            hold_reasons.append(f"{rtag}DAY90_CPEPTIDE_INTERMEDIATE:{d90}%")

    has_lym, lym_raw = _opt("lymphocyte_count_pct_of_baseline")
    lym = _require_bounded_float(lym_raw, f"{pfx}lymphocyte_count_pct_of_baseline", lo=0.0, hi=200.0) if has_lym else None
    if lym is not None:
        if lym < 80.0:
            fail_reasons.append(f"{rtag}LYMPHOPENIA_FAIL:{lym}%")
        elif lym < 90.0:
            hold_reasons.append(f"{rtag}LYMPHOPENIA_INTERMEDIATE:{lym}%")

    has_treg, treg_raw = _opt("treg_tr1_fold_expansion")
    treg = _require_bounded_float(treg_raw, f"{pfx}treg_tr1_fold_expansion", lo=0.0, hi=1e6) if has_treg else None
    if treg is not None:
        if treg < 1.2:
            fail_reasons.append(f"{rtag}TREG_TR1_EXPANSION_FAIL:{treg}x")
        elif treg < 2.0:
            hold_reasons.append(f"{rtag}TREG_TR1_EXPANSION_INTERMEDIATE:{treg}x")

    has_brd, brd_raw = _opt("islet_antigens_suppressed_count")
    brd = _require_exact_int(brd_raw, f"{pfx}islet_antigens_suppressed_count", lo=0, hi=10) if has_brd else None
    if brd is not None:
        if brd < 2:
            fail_reasons.append(f"{rtag}ANTIGEN_BREADTH_FAIL:{brd}<2")
        elif brd < 3:
            hold_reasons.append(f"{rtag}ANTIGEN_BREADTH_INTERMEDIATE:{brd}<3")

    has_idrop, idrop_raw = _opt("islet_ag_elispot_drop_pct")
    idrop = _require_bounded_float(idrop_raw, f"{pfx}islet_ag_elispot_drop_pct", lo=0.0, hi=100.0) if has_idrop else None
    if idrop is not None:
        if idrop < 50.0:
            fail_reasons.append(f"{rtag}ISLET_AG_SUPPRESSION_FAIL:{idrop}%")
        elif idrop < 80.0:
            hold_reasons.append(f"{rtag}ISLET_AG_SUPPRESSION_INTERMEDIATE:{idrop}%")

    has_vr, vr_raw = _opt("viral_vaccine_recall_retention_pct")
    vr = _require_bounded_float(vr_raw, f"{pfx}viral_vaccine_recall_retention_pct", lo=0.0, hi=200.0) if has_vr else None
    if vr is not None:
        if vr < 75.0:
            fail_reasons.append(f"{rtag}ZERO_IS_VIOLATION_VIRAL_RECALL_SUPPRESSED:{vr}%")
        elif vr < 85.0:
            hold_reasons.append(f"{rtag}VIRAL_RECALL_INTERMEDIATE:{vr}%")

    return {
        "fields": {
            "study_id": study_id,
            "administration_days": admin_days,
            "last_dose_day": last_dose_day,
            "clearance_sample_day": clearance_sample_day,
            "plasma_assay_id": plasma_assay_id,
            "lymph_node_assay_id": lymph_node_assay_id,
            "plasma_llod_ng_ml": plasma_llod,
            "tissue_llod_ng_g": tissue_llod,
            "measured_plasma_conc_ng_ml": plasma_conc,
            "measured_tissue_conc_ng_g": tissue_conc,
            "max_ae_grade": ae,
            "day90_cpeptide_retention_pct": d90,
            "lymphocyte_count_pct_of_baseline": lym,
            "treg_tr1_fold_expansion": treg,
            "islet_antigens_suppressed_count": brd,
            "islet_ag_elispot_drop_pct": idrop,
            "viral_vaccine_recall_retention_pct": vr,
        }
    }


def evaluate_gate34_invvax_recall(
    obs: dict[str, Any],
    arm_manifest: dict[str, Any] | None = None,
    *,
    trusted_evidence_store: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
    """Fail-closed Gate 34-INVVAX-RECALL evaluator (Round-5: ALL governing endpoints derived directly from verified current_assay_evidence_record, ZERO threshold tolerance)."""
    try:
        if not isinstance(obs, dict):
            raise ValueError("obs must be dict")
        check_strictly_finite(obs, "gate34_invvax_obs")

        fail_reasons: list[str] = []
        missing_fields: list[str] = []
        hold_reasons: list[str] = []

        verified_manifest = _verify_manifest_context(arm_manifest, obs, fail_reasons, missing_fields)
        _, arm_entry = _check_arm_and_design_a_invariants(obs, "invvax_eligible", verified_manifest, fail_reasons, missing_fields)

        obs_eval = _evaluate_invvax_measurements(
            obs, is_archive=False, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
        )

        cur_raw = obs.get("current_assay_evidence_record") if "current_assay_evidence_record" in obs else None
        if cur_raw is not None and not isinstance(cur_raw, dict):
            raise ValueError("current_assay_evidence_record must be dict")

        if isinstance(cur_raw, dict):
            cur_eval = _evaluate_invvax_measurements(
                cur_raw, is_archive=True, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
            )
            # Enforce EXACT equality (ZERO numeric tolerance!) across ALL 17 governing InvVax fields!
            for fld, obs_v in obs_eval["fields"].items():
                cur_v = cur_eval["fields"].get(fld)
                if obs_v is not None and cur_v is not None:
                    if cur_v != obs_v:
                        fail_reasons.append(f"INVVAX_ASSAY_BINDING_MISMATCH:{fld}:{cur_v!r}!={obs_v!r}")

        return _verify_upstream_evidence_and_finalize(
            obs,
            CANONICAL_GATE34_MODULE_SOURCES["invvax"],
            None,
            arm_entry,
            trusted_evidence_store,
            fail_reasons,
            missing_fields,
            hold_reasons,
            verified_manifest=verified_manifest,
        )
    except ValueError as exc:
        return _malformed_rejection(exc)


def _make_evidence_record_v2(
    *,
    record_id: str,
    gate_source: str,
    product_id: str,
    lot_id: str,
    bank_id: str,
    bank_origin: str,
    construct_manifest_sha256: str,
    evidence_tier: str = "SYNTHETIC_FIXTURE",
    decision: str | None = None,
    authority_scope: str | None = None,
    bank_qualified: bool | None = None,
    promotion_authorized: bool | None = None,
    extra_fields: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Create and canonically seal a v2_round5_unified 14-field evidence record."""
    if evidence_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
        dec = decision if decision is not None else "PASS"
        scope = authority_scope if authority_scope is not None else "CLINICAL_LOT_RELEASE"
        bq = True if bank_qualified is None else bank_qualified
        pa = True if promotion_authorized is None else promotion_authorized
    else:
        dec = decision if decision is not None else "SYNTHETIC_SELF_TEST_PASS"
        scope = authority_scope if authority_scope is not None else "SYNTHETIC_SELF_TEST"
        bq = False if bank_qualified is None else bank_qualified
        pa = False if promotion_authorized is None else promotion_authorized

    body: dict[str, Any] = {
        "record_id": record_id,
        "gate_source": gate_source,
        "product_id": product_id,
        "lot_id": lot_id,
        "bank_id": bank_id,
        "bank_origin": bank_origin,
        "canonical_arm_manifest_sha256": EXPECTED_ARM_MANIFEST_SHA256,
        "construct_manifest_sha256": construct_manifest_sha256,
        "evidence_tier": evidence_tier,
        "decision": dec,
        "authority_scope": scope,
        "bank_qualified": bq,