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…

                reasons.append(f"{desc} explicitly failed ({req_bool_key}=False).")

    req_upstream_specs: dict[str, dict[str, str]] = gate_cfg["required_authenticated_upstream_records"]
    inline_upstream = payload.get("upstream_qualification_records")
    inline_comp = payload.get("paired_comparator_record")
    self_attested_inline_ignored = (inline_upstream is not None) or (inline_comp is not None)

    # Still fail closed on malformed or tampered inline records if supplied!
    if inline_upstream is not None and not isinstance(inline_upstream, dict):
        reasons.append("upstream_qualification_records must be a dict if supplied (and is NEVER trusted without trusted_qualification_store).")
    elif isinstance(inline_upstream, dict):
        for rec_key, spec in req_upstream_specs.items():
            irec = inline_upstream.get(rec_key)
            if irec is None:
                continue
            if not isinstance(irec, dict):
                reasons.append(f"Inline upstream record {rec_key} must be a dict.")
                continue
            rsha = irec.get("record_sha256")
            if not _is_valid_sha256_hex(rsha) or compute_upstream_record_sha256(irec) != rsha:
                reasons.append(f"Inline upstream record {rec_key} SHA-256 tamper/mismatch rejected fail-closed.")
            if lot_id is not None and irec.get("lot_id") != lot_id:
                reasons.append(f"Inline upstream record {rec_key} lot_id={irec.get('lot_id')!r} != payload lot_id={lot_id!r}.")
            if mcb_id is not None and irec.get("mcb_id") != mcb_id:
                reasons.append(f"Inline upstream record {rec_key} mcb_id={irec.get('mcb_id')!r} != payload mcb_id={mcb_id!r}.")

    refs_raw = payload.get("upstream_record_refs")
    if refs_raw is not None and not isinstance(refs_raw, dict):
        reasons.append("upstream_record_refs must be a dict mapping record reference keys to 64-hex SHA-256 digests.")
        refs: dict[str, Any] = {}
    else:
        refs = dict(refs_raw or {})

    top_comp_sha = payload.get("paired_comparator_record_sha256")
    if top_comp_sha is not None:
        if "paired_comparator_record_sha256" in refs and refs["paired_comparator_record_sha256"] != top_comp_sha:
            reasons.append("Conflicting paired_comparator_record_sha256 between top-level payload and upstream_record_refs.")
        refs["paired_comparator_record_sha256"] = top_comp_sha

    authenticated_upstream_digests: dict[str, str] = {}
    trusted_store_issuers: dict[str, str] = {}
    trusted_store_source: str | None = None
    derived_incumbent_state: str | None = None
    derived_incumbent_details: dict[str, Any] = {}
    paired_comparator_summary: dict[str, Any] | None = None
    head_to_head_reconciled = False

    if trusted_qualification_store is None:
        pending_full_fields.append("trusted_qualification_store")
        for rec_key in req_upstream_specs:
            pending_full_fields.append(f"trusted_{rec_key}")
        pending_full_fields.append("trusted_paired_comparator_record")
    else:
        # Resolve all 3 upstream records from independent trusted_qualification_store
        for rec_key, spec in req_upstream_specs.items():
            ref_field = f"{rec_key}_sha256"
            ref_sha = refs.get(ref_field)
            if ref_sha is None:
                pending_full_fields.append(f"trusted_{rec_key}")
                continue
            rec, lerr, src_lbl = _lookup_gate28b_trusted_record(
                trusted_qualification_store,
                category=spec.get("store_category", "upstream_qualifications"),
                expected_sha256=ref_sha,
                allowed_issuers=allowed_issuers,
            )
            if src_lbl is not None:
                trusted_store_source = src_lbl
            if lerr is not None or rec is None:
                reasons.append(f"Trusted store resolution failed for {rec_key}: {lerr}.")
                continue
            recomputed = compute_upstream_record_sha256(rec)
            if not _is_valid_sha256_hex(rec.get("record_sha256")) or recomputed != rec.get("record_sha256") or recomputed != ref_sha:
                reasons.append(f"Trusted store record {rec_key} SHA-256 verification failed.")
                continue
            issuer = _strict_literal_id(rec.get("issuer_authority_id"))
            if issuer not in allowed_issuers:
                reasons.append(f"Trusted store record {rec_key} issuer_authority_id={rec.get('issuer_authority_id')!r} not in allowlist.")
            if _strict_literal_id(rec.get("assay_id")) is None:
                reasons.append(f"Trusted store record {rec_key} missing literal assay_id.")
            ev_sum = rec.get("evidence_summary")
            if not isinstance(ev_sum, dict) or len(ev_sum) == 0:
                reasons.append(f"Trusted store record {rec_key} missing mandatory non-empty evidence_summary.")
            if rec.get("gate_id") != spec["gate_id"]:
                reasons.append(f"Trusted store record {rec_key} gate_id={rec.get('gate_id')!r} != expected {spec['gate_id']!r}.")
            if rec.get("verdict") != spec["required_verdict"]:
                reasons.append(f"Trusted store record {rec_key} verdict={rec.get('verdict')!r} != required {spec['required_verdict']!r}.")
            if lot_id is not None and rec.get("lot_id") != lot_id:
                reasons.append(f"Trusted store record {rec_key} lot_id={rec.get('lot_id')!r} != payload lot_id={lot_id!r}.")
            if mcb_id is not None and rec.get("mcb_id") != mcb_id:
                reasons.append(f"Trusted store record {rec_key} mcb_id={rec.get('mcb_id')!r} != payload mcb_id={mcb_id!r}.")
            if rec.get("construct_id") != construct_id:
                reasons.append(f"Trusted store record {rec_key} construct_id={rec.get('construct_id')!r} != payload construct_id={construct_id!r}.")
            if rec.get("product_variant_id") != product_variant_id:
                reasons.append(f"Trusted store record {rec_key} product_variant_id={rec.get('product_variant_id')!r} != {product_variant_id!r}.")
            if chassis_id is not None and rec.get("chassis_id") != chassis_id:
                reasons.append(f"Trusted store record {rec_key} chassis_id={rec.get('chassis_id')!r} != payload chassis_id={chassis_id!r}.")
            if rec.get("product_track") != product_track:
                reasons.append(f"Trusted store record {rec_key} product_track={rec.get('product_track')!r} != {product_track!r}.")
            if isinstance(inline_upstream, dict) and isinstance(inline_upstream.get(rec_key), dict):
                if compute_upstream_record_sha256(inline_upstream[rec_key]) != recomputed:
                    reasons.append(f"Inline {rec_key} contradicts trusted qualification store record.")
            authenticated_upstream_digests[rec_key] = recomputed
            if issuer is not None:
                trusted_store_issuers[rec_key] = issuer

        # Resolve paired head-to-head comparator record binding BOTH candidate & incumbent arms + matched panel!
        comp_cfg = gate_cfg["required_trusted_paired_comparator_record"]
        comp_ref_sha = refs.get("paired_comparator_record_sha256")
        if comp_ref_sha is None:
            pending_full_fields.append("trusted_paired_comparator_record")
        else:
            crec, cerr, csrc = _lookup_gate28b_trusted_record(
                trusted_qualification_store,
                category=comp_cfg.get("store_category", "paired_comparator_records"),
                expected_sha256=comp_ref_sha,
                allowed_issuers=allowed_issuers,
            )
            if csrc is not None:
                trusted_store_source = csrc
            if cerr is not None or crec is None:
                reasons.append(f"Trusted store resolution failed for paired_comparator_record: {cerr}.")
            else:
                crecomp = compute_upstream_record_sha256(crec)
                if not _is_valid_sha256_hex(crec.get("record_sha256")) or crecomp != crec.get("record_sha256") or crecomp != comp_ref_sha:
                    reasons.append("Trusted store paired_comparator_record SHA-256 verification failed.")
                else:
                    h2h_mismatches: list[str] = []
                    c_issuer = _strict_literal_id(crec.get("issuer_authority_id"))
                    if c_issuer not in allowed_issuers:
                        h2h_mismatches.append(f"Paired comparator issuer_authority_id={crec.get('issuer_authority_id')!r} not in allowlist.")
                    if crec.get("gate_id") != comp_cfg["gate_id"]:
                        h2h_mismatches.append(f"Paired comparator gate_id={crec.get('gate_id')!r} != expected {comp_cfg['gate_id']!r}.")
                    if crec.get("product_track") != product_track:
                        h2h_mismatches.append(f"Paired comparator product_track={crec.get('product_track')!r} != {product_track!r}.")
                    if chassis_id is not None and crec.get("chassis_id") != chassis_id:
                        h2h_mismatches.append(f"Paired comparator chassis_id={crec.get('chassis_id')!r} != {chassis_id!r}.")
                    if crec.get("candidate_construct_id") != construct_id:
                        h2h_mismatches.append(f"Paired comparator candidate_construct_id={crec.get('candidate_construct_id')!r} != {construct_id!r}.")
                    if crec.get("product_variant_id") != product_variant_id:
                        h2h_mismatches.append(f"Paired comparator product_variant_id={crec.get('product_variant_id')!r} != {product_variant_id!r}.")
                    if lot_id is not None and crec.get("candidate_lot_id") != lot_id:
                        h2h_mismatches.append(f"Paired comparator candidate_lot_id={crec.get('candidate_lot_id')!r} != {lot_id!r}.")
                    if mcb_id is not None and crec.get("candidate_mcb_id") != mcb_id:
                        h2h_mismatches.append(f"Paired comparator candidate_mcb_id={crec.get('candidate_mcb_id')!r} != {mcb_id!r}.")
                    if inc_comp_id is not None and crec.get("incumbent_comparator_construct_id") != inc_comp_id:
                        h2h_mismatches.append(f"Paired comparator incumbent_comparator_construct_id={crec.get('incumbent_comparator_construct_id')!r} != {inc_comp_id!r}.")
                    if inc_comp_lot_id is not None and crec.get("incumbent_comparator_lot_id") != inc_comp_lot_id:
                        h2h_mismatches.append(f"Paired comparator incumbent_comparator_lot_id={crec.get('incumbent_comparator_lot_id')!r} != {inc_comp_lot_id!r}.")
                    if _strict_literal_id(crec.get("incumbent_comparator_mcb_id")) is None:
                        h2h_mismatches.append("Paired comparator missing literal incumbent_comparator_mcb_id.")

                    # Reconcile paired_assay_run_id, sera/NK/diff panel IDs, and panel_digest EXACTLY against payload!
                    c_run_id = _strict_literal_id(crec.get("paired_assay_run_id"))
                    if c_run_id is None:
                        h2h_mismatches.append("Paired comparator missing literal paired_assay_run_id.")
                    elif payload_run_id is not None and c_run_id != payload_run_id:
                        h2h_mismatches.append(
                            f"Head-to-head paired_assay_run_id mismatch: payload={payload_run_id!r} != trusted_record={c_run_id!r}."
                        )

                    c_sera_ids, cs_errs = _validate_literal_panel_id_list(crec.get("t1d_sera_panel_ids"), field_name="paired_record.t1d_sera_panel_ids", min_count=min_sera)
                    c_nk_ids, cn_errs = _validate_literal_panel_id_list(crec.get("nk_donor_panel_ids"), field_name="paired_record.nk_donor_panel_ids", min_count=min_nk)
                    c_diff_ids, cd_errs = _validate_literal_panel_id_list(crec.get("differentiation_batch_ids"), field_name="paired_record.differentiation_batch_ids", min_count=min_diff)
                    h2h_mismatches.extend(cs_errs + cn_errs + cd_errs)

                    c_sera_n = _strict_int(crec.get("independent_t1d_sera_n"), min_val=min_sera)
                    c_nk_n = _strict_int(crec.get("independent_nk_donors_n"), min_val=min_nk)
                    c_diff_n = _strict_int(crec.get("independent_differentiations_n"), min_val=min_diff)
                    if c_sera_n is None or (c_sera_ids is not None and c_sera_n != len(c_sera_ids)):
                        h2h_mismatches.append("Paired comparator independent_t1d_sera_n invalid or inconsistent with t1d_sera_panel_ids.")
                    if c_nk_n is None or (c_nk_ids is not None and c_nk_n != len(c_nk_ids)):
                        h2h_mismatches.append("Paired comparator independent_nk_donors_n invalid or inconsistent with nk_donor_panel_ids.")
                    if c_diff_n is None or (c_diff_ids is not None and c_diff_n != len(c_diff_ids)):
                        h2h_mismatches.append("Paired comparator independent_differentiations_n invalid or inconsistent with differentiation_batch_ids.")

                    if c_run_id is not None and c_sera_ids is not None and c_nk_ids is not None and c_diff_ids is not None:
                        c_panel_digest = compute_paired_assay_panel_digest(c_run_id, c_sera_ids, c_nk_ids, c_diff_ids)
                        if crec.get("panel_digest") != c_panel_digest:
                            h2h_mismatches.append("Paired comparator panel_digest failed canonical verification.")
                        if p_sera_ids is not None and p_sera_ids != c_sera_ids:
                            h2h_mismatches.append("Head-to-head t1d_sera_panel_ids mismatch between payload and trusted paired comparator record.")
                        if p_nk_ids is not None and p_nk_ids != c_nk_ids:
                            h2h_mismatches.append("Head-to-head nk_donor_panel_ids mismatch between payload and trusted paired comparator record.")
                        if p_diff_ids is not None and p_diff_ids != c_diff_ids:
                            h2h_mismatches.append("Head-to-head differentiation_batch_ids mismatch between payload and trusted paired comparator record.")
                        if payload_panel_digest is not None and payload_panel_digest != c_panel_digest:
                            h2h_mismatches.append("Head-to-head panel_digest mismatch between payload and trusted paired comparator record.")

                    # Reconcile ALL candidate-arm quantitative head-to-head endpoints EXACTLY against trusted record!
                    c_cand_parsed, c_cand_errs = _validate_candidate_arm_evidence(crec.get("candidate_arm_evidence"))
                    if c_cand_errs or c_cand_parsed is None:
                        h2h_mismatches.extend(c_cand_errs)
                    else:
                        for copy_lbl in ("copy1_monoallelic", "copy2_biallelic"):
                            p_sub = payload_cand_head_to_head.get(copy_lbl)
                            if p_sub is None:
                                h2h_mismatches.append(f"Cannot reconcile missing payload {copy_lbl} metrics against paired comparator record.")
                                continue
                            for mk, c_frac in c_cand_parsed[copy_lbl].items():
                                if p_sub.get(mk) != c_frac:
                                    h2h_mismatches.append(
                                        f"Head-to-head candidate metric mismatch for {copy_lbl}.{mk}: "
                                        f"payload={float(p_sub[mk]) if mk in p_sub else None} != trusted_paired_record={float(c_frac)}."
                                    )
                        for c4_k in (
                            "classical_c4b2a_l95_pct",
                            "classical_c4b2a_u95_pct",
                            "lectin_c4b2a_l95_pct",
                            "lectin_c4b2a_u95_pct",
                        ):
                            if payload_cand_head_to_head.get(c4_k) != c_cand_parsed[c4_k]:
                                h2h_mismatches.append(
                                    f"Head-to-head candidate metric mismatch for {c4_k}: "
                                    f"payload={float(payload_cand_head_to_head[c4_k]) if c4_k in payload_cand_head_to_head else None} "
                                    f"!= trusted_paired_record={float(c_cand_parsed[c4_k])}."
                                )

                    # Derive 3-state incumbent adjudication (CONCLUSIVELY_BROKEN / UNRESOLVED_STRADDLING_CAP / INTACT_WITHIN_CAPS)
                    c_state, c_inc_details, c_ev_errs = _derive_paired_comparator_incumbent_adjudication(
                        crec.get("evidence_summary"),
                        adcc_cap=adcc_max,
                        ap_cap=ap_max,
                        nhs_cap=nhs_max,
                        classical_c4b2a_cap=cl_max,
                        lectin_c4b2a_cap=lec_max,
                    )
                    if c_ev_errs or c_state is None:
                        h2h_mismatches.extend(c_ev_errs or ["Failed to derive quantitative 3-state paired comparator adjudication."])
                    else:
                        expected_c_verdict = INCUMBENT_STATE_TO_RECORD_VERDICT[c_state]
                        if crec.get("verdict") != expected_c_verdict:
                            h2h_mismatches.append(
                                f"Paired comparator verdict={crec.get('verdict')!r} contradicts quantitative measurements ({expected_c_verdict!r})."
                            )
                        if crec.get("incumbent_adjudication_state") != c_state:
                            h2h_mismatches.append(
                                f"Paired comparator incumbent_adjudication_state={crec.get('incumbent_adjudication_state')!r} != derived {c_state!r}."
                            )
                        # Caller legacy boolean cannot contradict a conclusive store state (broken vs intact)!
                        if c_state == "INCUMBENT_CONCLUSIVELY_BROKEN" and caller_l2v3_broken is False:
                            h2h_mismatches.append(
                                "Caller l2v3_broken_by_t1d_sera_gt_5pct=False contradicts trusted paired comparator state INCUMBENT_CONCLUSIVELY_BROKEN."
                            )