fail_reasons.append(f"SHIELD_ASSAY_BINDING_MISMATCH:{fld}:{cur_v}!={obs_v}") caller_matches_archive = False elif cur_v != obs_v: fail_reasons.append(f"SHIELD_ASSAY_BINDING_MISMATCH:{fld}:{cur_v!r}!={obs_v!r}") caller_matches_archive = False if obs_eval["off_target_kd_u95_um"] is not None and cur_eval["off_target_kd_u95_um"] is not None: if cur_eval["off_target_kd_u95_um"] != obs_eval["off_target_kd_u95_um"]: fail_reasons.append( f"SHIELD_ASSAY_BINDING_MISMATCH:off_target_kd_u95_um:{cur_eval['off_target_kd_u95_um']!r}!={obs_eval['off_target_kd_u95_um']!r}" ) caller_matches_archive = False def _fmt_ro(val: float | None) -> float | None: return round(val, 4) if val is not None and math.isfinite(val) else None def _caller_shield_unverified() -> dict[str, Any]: c_ratio = obs_eval["recomputed_ratio"] if obs_eval["kd_on_calibrated"] else None return { "caller_reported_unverified_pan_dq_peak_ro_pct": _fmt_ro(obs_eval["pan_dq_peak_ro"]), "caller_reported_unverified_pan_dq_plasma_trough_ro_pct": _fmt_ro(obs_eval["pan_dq_plasma_trough_ro"]), "caller_reported_unverified_pan_dq_dln_trough_ro_pct": _fmt_ro(obs_eval["pan_dq_dln_trough_ro"]), "caller_reported_unverified_dln_trough_on_target_ro_pct": _fmt_ro(obs_eval["on_target_dln_trough_ro"]), "caller_reported_unverified_recomputed_selectivity_ratio": _fmt_ro(c_ratio), } def _build_shield_extra(auth_ctx: dict[str, Any]) -> dict[str, Any]: null_official = { "occupancy_convention": OCCUPANCY_CONVENTION, "pan_dq_peak_ro_pct": None, "pan_dq_plasma_trough_ro_pct": None, "pan_dq_dln_trough_ro_pct": None, "dln_trough_on_target_ro_pct": None, "recomputed_selectivity_ratio": None, } null_caller = { "caller_reported_unverified_pan_dq_peak_ro_pct": None, "caller_reported_unverified_pan_dq_plasma_trough_ro_pct": None, "caller_reported_unverified_pan_dq_dln_trough_ro_pct": None, "caller_reported_unverified_dln_trough_on_target_ro_pct": None, "caller_reported_unverified_recomputed_selectivity_ratio": 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 store / tampered store / broken envelope 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, "shield_statistics_derivation_source": src_label, "caller_measurements_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE", **_caller_shield_unverified(), } # State 2: Any internal archive consistency check fails (always FAIL verdict) if not cur_eval["archive_internally_consistent_ok"]: return { **null_official, "shield_statistics_derivation_source": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT", "caller_measurements_reconciliation_status": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT", **_caller_shield_unverified(), } # State 1b: Authenticated archive is incomplete (omitted mandatory archived field e.g. study_id, or unconverged periodic PK) 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, "shield_statistics_derivation_source": src_label, "caller_measurements_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE", **_caller_shield_unverified(), } arch_ratio = cur_eval["recomputed_ratio"] if cur_eval["kd_on_calibrated"] else None official_stats = { "occupancy_convention": OCCUPANCY_CONVENTION, "pan_dq_peak_ro_pct": _fmt_ro(cur_eval["pan_dq_peak_ro"]), "pan_dq_plasma_trough_ro_pct": _fmt_ro(cur_eval["pan_dq_plasma_trough_ro"]), "pan_dq_dln_trough_ro_pct": _fmt_ro(cur_eval["pan_dq_dln_trough_ro"]), "dln_trough_on_target_ro_pct": _fmt_ro(cur_eval["on_target_dln_trough_ro"]), "recomputed_selectivity_ratio": _fmt_ro(arch_ratio), } if any( official_stats[k] is None for k in ( "pan_dq_peak_ro_pct", "pan_dq_plasma_trough_ro_pct", "pan_dq_dln_trough_ro_pct", "dln_trough_on_target_ro_pct", "recomputed_selectivity_ratio", ) ): return { **null_official, "shield_statistics_derivation_source": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT", "caller_measurements_reconciliation_status": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT", **_caller_shield_unverified(), } if caller_matches_archive: # State 3: Authenticated, complete, internally consistent archive + clean caller reconciliation src_label = ( "AUTHENTICATED_ARCHIVE_VERIFIED" if is_auth_wetlab else "SYNTHETIC_FIXTURE_ARCHIVE_SELF_TEST" ) return { **official_stats, "shield_statistics_derivation_source": src_label, "caller_measurements_reconciliation_status": "MATCHED", **null_caller, } # State 4: Authenticated, complete, internally consistent archive contradicted ONLY by caller src_label = ( "AUTHENTICATED_ARCHIVE_ONLY_CALLER_CONFLICT" if is_auth_wetlab else "SYNTHETIC_FIXTURE_ARCHIVE_ONLY_CALLER_CONFLICT" ) return { **official_stats, "shield_statistics_derivation_source": src_label, "caller_measurements_reconciliation_status": "CONFLICT_CALLER_MISMATCH", **_caller_shield_unverified(), } return _verify_upstream_evidence_and_finalize( obs, CANONICAL_GATE36_MODULE_SOURCES["shield"], None, arm_entry, trusted_evidence_store, fail_reasons, missing_fields, hold_reasons, verified_manifest=verified_manifest, extra_builder=_build_shield_extra, require_live_gate32_debris_recall=True, ) except ValueError as exc: return _malformed_rejection(exc, empty_ro) def _is_more_conservative_hla(cand: dict[str, Any], base: dict[str, Any], *, prefer_equal: bool = False) -> bool: """Return True if HLA panel summary `cand` is strictly more conservative than `base` (lower unique donors / higher U95).""" if not cand.get("donor_lists_complete"): return False if not base.get("donor_lists_complete"): return True c_n = cand.get("unique_donor_count", 0) b_n = base.get("unique_donor_count", 0) if c_n == 0 and b_n > 0: return True if b_n == 0 and c_n > 0: return False c_u95 = cand.get("exact_u95_pct") b_u95 = base.get("exact_u95_pct") if c_u95 is not None and b_u95 is None: return True if c_u95 is not None and b_u95 is not None: if c_u95 > b_u95: return True if c_u95 < b_u95: return False if c_n < b_n: return True if c_n > b_n: return False return prefer_equal def _merge_seen_raw_maps(*maps: dict[str, set[str]]) -> dict[str, set[str]]: merged: dict[str, set[str]] = {} for mp in maps: for ckey, raws in mp.items(): merged.setdefault(ckey, set()).update(raws) return merged def _evaluate_ins_hla_panels( hrec_raw: Any, *, pfx: str, rtag: str, field_label: str, fail_reasons: list[str], missing_fields: list[str], hold_reasons: list[str], local_missing_fields: list[str] | None = None, ) -> dict[str, Any]: """Validate per-allele HLA panels with strict canonical ASCII donor IDs, separator-first canonical deduplication, & shared issuer identity.""" if not isinstance(hrec_raw, dict): raise ValueError(f"{pfx}{field_label} must be dict") def _miss_panel(field_path: str) -> None: missing_fields.append(field_path) if local_missing_fields is not None: local_missing_fields.append(field_path) pooled_panel_entries = 0 unique_donor_canon_keys: set[str] = set() unique_reactive_canon_keys: set[str] = set() seen_raw_by_canon_key: dict[str, set[str]] = {} observed_peptides: dict[str, str] = {} parsed_panels: dict[str, dict[str, Any]] = {} alleles_complete = True donor_lists_complete = True reactive_lists_complete = True panel_internal_conflict = False container_issuers, container_valid, container_noncanon, container_empty = _extract_and_validate_issuer_ids( hrec_raw, location=f"{pfx}{field_label}", rtag=rtag, fail_reasons=fail_reasons ) if len(set(container_issuers)) > 1: fail_reasons.append( f"{rtag}INS_INCONSISTENT_DONOR_ISSUER_ID_FAIL:{field_label}:{sorted(set(container_issuers))}" ) panel_internal_conflict = True observed_issuer_ids: set[str] = set(container_issuers) valid_issuer_ids: set[str] = set(container_valid) has_noncanonical_issuer = container_noncanon saw_empty_issuer = container_empty allele_issuer_presence_count = 0 for allele in MANDATORY_INS_HLA_ALLELES: if allele not in hrec_raw or hrec_raw[allele] is None: alleles_complete = False donor_lists_complete = False reactive_lists_complete = False panel_internal_conflict = True fail_reasons.append(f"{rtag}MISSING_MANDATORY_HLA_ALLELE_RECORD:{allele}") continue arec = hrec_raw[allele] if not isinstance(arec, dict): raise ValueError(f"{pfx}{field_label}.{allele} must be dict") p_al: dict[str, Any] = {} al_issuers, al_valid, al_noncanon, al_empty = _extract_and_validate_issuer_ids( arec, location=f"{pfx}{field_label}.{allele}", rtag=rtag, fail_reasons=fail_reasons ) if al_noncanon: has_noncanonical_issuer = True