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…

                oa = obs_eval["primary_hla"]["parsed_panels"].get(al)
                ca = cur_eval["primary_hla"]["parsed_panels"].get(al)
                if oa is not None and ca is not None:
                    for subk, ov in oa.items():
                        if subk in ca:
                            cv = ca[subk]
                            if type(ov) is bool or type(cv) is bool:
                                if cv is not ov:
                                    fail_reasons.append(f"INS_ASSAY_BINDING_MISMATCH:hla.{al}.{subk}:{cv}!={ov}")
                            elif cv != ov:
                                fail_reasons.append(f"INS_ASSAY_BINDING_MISMATCH:hla.{al}.{subk}:{cv!r}!={ov!r}")

            # Cross-check archive summary & canonical donor sets against parent observations
            if obs_eval["hla"]["donor_lists_complete"] and cur_eval["hla"]["donor_lists_complete"]:
                if cur_eval["hla"]["unique_donor_count"] != obs_eval["hla"]["unique_donor_count"]:
                    fail_reasons.append(
                        f"INS_ASSAY_BINDING_MISMATCH:unique_hla_donors:archive={cur_eval['hla']['unique_donor_count']}!=parent={obs_eval['hla']['unique_donor_count']}"
                    )
                if cur_eval["hla"]["unique_donor_canon_keys"] != obs_eval["hla"]["unique_donor_canon_keys"]:
                    fail_reasons.append("INS_ASSAY_BINDING_MISMATCH:canonical_donor_key_set")

            # Strict 1-to-1 raw-vs-canonical consistency across BOTH parent and archive rosters!
            parent_archive_raw = _merge_seen_raw_maps(
                obs_eval["merged_seen_raw_by_canon_key"], cur_eval["merged_seen_raw_by_canon_key"]
            )
            for ckey, raws in sorted(parent_archive_raw.items()):
                if len(raws) > 1:
                    fail_reasons.append(
                        f"INS_INCONSISTENT_DONOR_ID_FORMATTING_VARIANT:parent_vs_archive:{ckey}:{sorted(r[:32] for r in raws)}"
                    )

            # Mandatory positive canonical ASCII HLA registry issuer enforcement across ALL present roster forms (Audit R9-04):
            # NEVER treat omitted issuers (None == None) as agreeing or equivalent!
            # - Archive omits issuer (absent, None, or "") on ANY present archived roster form -> HOLD!
            # - Archive establishes positive canonical issuer across ALL present archived forms ->
            #     Current omits issuer on ANY present form OR disagrees -> FAIL!
            # - Conflicting positive issuers across parent & archive scopes -> FAIL!
            union_issuers = obs_eval["all_observed_issuers"] | cur_eval["all_observed_issuers"]
            if len(union_issuers) > 1:
                fail_reasons.append(
                    f"INS_ASSAY_BINDING_MISMATCH:donor_issuer_id:{sorted(union_issuers)}"
                )

            arch_forms: dict[str, dict[str, Any]] = cur_eval["present_roster_forms"]
            obs_forms: dict[str, dict[str, Any]] = obs_eval["present_roster_forms"]
            arch_missing_forms = [fname for fname, fres in arch_forms.items() if fres["issuer_missing"]]

            if not arch_forms:
                hold_reasons.append("HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER:no_archived_roster_present")
            elif arch_missing_forms:
                for fname in arch_missing_forms:
                    hold_reasons.append(f"HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER:{fname}")

            archive_established_issuer: str | None = cur_eval["effective_issuer_id"]
            if archive_established_issuer is not None:
                obs_missing_forms = [fname for fname, fres in obs_forms.items() if fres["issuer_missing"]]
                for fname in obs_missing_forms:
                    fail_reasons.append(
                        f"INS_MISSING_CURRENT_HLA_REGISTRY_ISSUER:{fname}:archive={archive_established_issuer!r}"
                    )
                if len(obs_forms) == 2 and len(obs_missing_forms) == 1:
                    obs_p = obs_forms["hla_allele_panel_records"]["effective_issuer_id"]
                    obs_a = obs_forms["per_allele_panels"]["effective_issuer_id"]
                    fail_reasons.append(
                        f"INS_ROSTER_DONOR_ISSUER_ID_MISMATCH:"
                        f"hla_allele_panel_records={obs_p!r}!=per_allele_panels={obs_a!r}"
                    )
                for fname, fres in obs_forms.items():
                    if not fres["issuer_missing"] and fres["effective_issuer_id"] is not None:
                        if fres["effective_issuer_id"] != archive_established_issuer:
                            fail_reasons.append(
                                f"INS_ASSAY_BINDING_MISMATCH:donor_issuer_id:{fname}:"
                                f"archive={archive_established_issuer!r}!=parent={fres['effective_issuer_id']!r}"
                            )
                if obs_eval["top_issuers"]:
                    for ti in sorted(set(obs_eval["top_issuers"])):
                        if ti != archive_established_issuer:
                            fail_reasons.append(
                                f"INS_ASSAY_BINDING_MISMATCH:donor_issuer_id:top_level:"
                                f"archive={archive_established_issuer!r}!=parent={ti!r}"
                            )
                if obs_eval["top_empty"]:
                    fail_reasons.append(
                        f"INS_MISSING_CURRENT_HLA_REGISTRY_ISSUER:top_level:archive={archive_established_issuer!r}"
                    )

            # Determine exact caller-vs-archive HLA roster & issuer reconciliation (Audit R10-03)
            if (
                cur_eval["has_primary_hla"]
                and cur_eval["primary_hla_complete"]
                and not cur_eval["internal_archive_roster_conflict"]
                and archive_established_issuer is not None
                and not cur_eval["archive_issuer_missing"]
            ):
                obs_alias = obs_eval["alias_hla"]
                alias_reconciles = (
                    obs_alias is None
                    or (
                        obs_alias["alleles_complete"]
                        and obs_alias["donor_lists_complete"]
                        and obs_alias["reactive_lists_complete"]
                        and obs_alias["parsed_panels"] == cur_eval["primary_hla"]["parsed_panels"]
                        and obs_alias["unique_donor_canon_keys"] == cur_eval["primary_hla"]["unique_donor_canon_keys"]
                        and obs_alias["unique_reactive_canon_keys"] == cur_eval["primary_hla"]["unique_reactive_canon_keys"]
                    )
                )
                caller_roster_matches_archive = bool(
                    obs_eval["has_primary_hla"]
                    and obs_eval["primary_hla_complete"]
                    and not obs_eval["internal_archive_roster_conflict"]
                    and obs_eval["primary_hla"]["parsed_panels"] == cur_eval["primary_hla"]["parsed_panels"]
                    and obs_eval["primary_hla"]["unique_donor_canon_keys"] == cur_eval["primary_hla"]["unique_donor_canon_keys"]
                    and obs_eval["primary_hla"]["unique_reactive_canon_keys"] == cur_eval["primary_hla"]["unique_reactive_canon_keys"]
                    and alias_reconciles
                    and obs_eval["merged_seen_raw_by_canon_key"] == cur_eval["merged_seen_raw_by_canon_key"]
                    and obs_eval["effective_issuer_id"] == archive_established_issuer
                    and obs_eval["all_observed_issuers"] == {archive_established_issuer}
                    and not obs_eval["top_empty"]
                    and not obs_eval["archive_issuer_missing"]
                )
        else:
            hold_reasons.append("HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER:current_assay_evidence_record_missing")

        def _caller_ins_unverified() -> dict[str, Any]:
            c_hla = obs_eval["hla"]
            if (
                c_hla["alleles_complete"]
                and c_hla["donor_lists_complete"]
                and c_hla["reactive_lists_complete"]
                and c_hla["unique_donor_count"] > 0
                and c_hla["exact_u95_pct"] is not None
            ):
                return {
                    "caller_reported_unverified_unique_donors": c_hla["unique_donor_count"],
                    "caller_reported_unverified_reactive_donors": c_hla["unique_reactive_count"],
                    "caller_reported_unverified_u95_pct": c_hla["exact_u95_pct"],
                }
            return {
                "caller_reported_unverified_unique_donors": None,
                "caller_reported_unverified_reactive_donors": None,
                "caller_reported_unverified_u95_pct": None,
            }

        def _build_ins_extra(auth_ctx: dict[str, Any]) -> dict[str, Any]:
            null_official = {
                "unique_hla_donors_verified": None,
                "pooled_allele_panel_observations": None,
                "total_hla_donors_verified": None,
                "total_reactive_donors": None,
                "exact_one_sided_95pct_u95_pct": None,
            }
            null_caller = {
                "caller_reported_unverified_unique_donors": None,
                "caller_reported_unverified_reactive_donors": None,
                "caller_reported_unverified_u95_pct": None,
            }
            is_auth_wetlab = auth_ctx["archive_authenticated"]
            is_sealed_synth = auth_ctx["synthetic_archive_sealed"]
            is_fail_verdict = auth_ctx["final_verdict"] == "FAIL" or str(auth_ctx["final_verdict"]).startswith("FAIL")

            # State 1a: Unauthenticated / missing archive / missing or failed trusted store (Audit R12-07: final_verdict-aware, NEVER *_HOLD_* on FAIL!)
            if cur_eval is None or (not is_auth_wetlab and not is_sealed_synth):
                src_label = (
                    "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE"
                )
                return {
                    **null_official,
                    "ins_statistics_derivation_source": src_label,
                    "caller_roster_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_ins_unverified(),
                }

            # State 2: Internally conflicting / invalid archive (roster or non-roster internal archive conflict)
            if cur_eval["internal_archive_roster_conflict"] or cur_eval["internal_archive_non_roster_conflict"]:
                return {
                    **null_official,
                    "ins_statistics_derivation_source": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    "caller_roster_reconciliation_status": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    **_caller_ins_unverified(),
                }

            # State 1b: Archive omits mandatory primary roster or omits positive canonical HLA registry issuer
            if not cur_eval["has_primary_hla"] or not cur_eval["primary_hla_complete"]:
                src_label = (
                    "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE"
                )
                return {
                    **null_official,
                    "ins_statistics_derivation_source": src_label,
                    "caller_roster_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_ins_unverified(),
                }
            if cur_eval["effective_issuer_id"] is None or cur_eval["archive_issuer_missing"]:
                src_label = (
                    "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_MISSING_ARCHIVED_ISSUER"
                )
                return {
                    **null_official,
                    "ins_statistics_derivation_source": src_label,
                    "caller_roster_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_ins_unverified(),
                }

            # State 1c: Authenticated archive omits any other mandatory archived field (e.g. study_id, editor_class, ELISA/summary fields)
            if not cur_eval["archive_complete_ok"]:
                src_label = (
                    "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE"
                )
                return {
                    **null_official,
                    "ins_statistics_derivation_source": src_label,
                    "caller_roster_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_ins_unverified(),
                }

            # Archive is authenticated (or sealed synthetic), internally complete, non-conflicting, with explicit positive issuer.
            # Official statistics are computed 100% STRICTLY from cur_eval["primary_hla"] (ZERO caller contamination!).
            arch_hla = cur_eval["primary_hla"]
            if arch_hla["unique_donor_count"] <= 0 or arch_hla["exact_u95_pct"] is None:
                return {
                    **null_official,
                    "ins_statistics_derivation_source": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    "caller_roster_reconciliation_status": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    **_caller_ins_unverified(),
                }

            official_stats = {
                "unique_hla_donors_verified": arch_hla["unique_donor_count"],
                "pooled_allele_panel_observations": arch_hla["pooled_panel_entries"],
                "total_hla_donors_verified": arch_hla["unique_donor_count"],
                "total_reactive_donors": arch_hla["unique_reactive_count"],
                "exact_one_sided_95pct_u95_pct": arch_hla["exact_u95_pct"],
            }

            if caller_roster_matches_archive:
                # State 3: Clean caller reconciliation
                src_label = (
                    "AUTHENTICATED_ARCHIVE_ROSTER_VERIFIED"
                    if is_auth_wetlab
                    else "SYNTHETIC_FIXTURE_ARCHIVE_SELF_TEST"
                )
                return {