elif not _is_finite_number(total_implanted_cells): fail_reasons.append(f"INVALID_{prefix}_TOTAL_IMPLANTED_CELLS") ok = False else: n_imp_d = _to_exact_decimal(total_implanted_cells) if n_imp_d <= ZERO_DEC or n_imp_d > Decimal("1e12"): fail_reasons.append(f"INVALID_{prefix}_TOTAL_IMPLANTED_CELLS") ok = False if residual_viable_cells_measured is None: any_missing = True elif not _is_finite_number(residual_viable_cells_measured): fail_reasons.append(f"INVALID_{prefix}_RESIDUAL_VIABLE_CELLS_MEASURED") ok = False else: n_res_d = _to_exact_decimal(residual_viable_cells_measured) if n_res_d < ZERO_DEC or n_res_d > Decimal("1e12"): fail_reasons.append(f"INVALID_{prefix}_RESIDUAL_VIABLE_CELLS_MEASURED") ok = False if residual_sampling_fraction is None: any_missing = True elif not _is_finite_number(residual_sampling_fraction): fail_reasons.append(f"INVALID_{prefix}_RESIDUAL_SAMPLING_FRACTION_OUT_OF_0P01_TO_1P0") ok = False else: f_samp_d = _to_exact_decimal(residual_sampling_fraction) if f_samp_d < MIN_RESIDUAL_SAMPLING_FRACTION_DEC or f_samp_d > ONE_DEC: fail_reasons.append(f"INVALID_{prefix}_RESIDUAL_SAMPLING_FRACTION_OUT_OF_0P01_TO_1P0") ok = False if not ok or any_missing or r_pct_d is None or n_imp_d is None or n_res_d is None or f_samp_d is None: return False if n_res_d > n_imp_d: fail_reasons.append(f"{prefix}_RESIDUAL_CELLS_EXCEED_IMPLANTED_CELLS_FAIL") ok = False if r_pct_d >= Decimal("99.999999999999"): cap_100_d = max(Decimal("1e5"), _dec_mul(Decimal("0.0005"), n_imp_d)) if n_res_d > cap_100_d or _ratio_gt_dec(n_res_d, f_samp_d, cap_100_d): fail_reasons.append(f"{prefix}_RETRIEVAL_100PCT_CONTRADICTS_RESIDUAL_VIABLE_CELLS_FAIL") ok = False rem_frac_d = max(_dec_mul(_dec_sub(Decimal("100"), r_pct_d), Decimal("0.01")), Decimal("0.001")) max_allowed_extrap_d = _dec_add(_dec_mul(_dec_mul(n_imp_d, rem_frac_d), Decimal("2")), Decimal("1e5")) if _ratio_gt_dec(n_res_d, f_samp_d, max_allowed_extrap_d): fail_reasons.append(f"{prefix}_RETRIEVAL_VS_RESIDUAL_CELL_DENOMINATOR_INCONSISTENT_FAIL") ok = False return ok def _check_subject_typed_complications_and_aliases( s: Mapping[str, Any], *, gate_tag: str, species_tag: str, fail_reasons: List[str], hold_reasons: List[str], ) -> Tuple[bool, bool]: """Validate typed monitored complication fields and defensive complication aliases on a subject row (Audit R5-04). Returns (complications_resolved, has_adverse_or_invalid_complication). """ resolved = True has_adverse = False for fkey, inv_code, fail_code in ( ("bowel_obstruction_event", f"INVALID_{species_tag}_BOWEL_OBSTRUCTION_EVENT_BOOL", f"{gate_tag}_{species_tag}_BOWEL_OBSTRUCTION_EVENT_FAIL"), ("omental_torsion_event", f"INVALID_{species_tag}_OMENTAL_TORSION_EVENT_BOOL", f"{gate_tag}_{species_tag}_OMENTAL_TORSION_EVENT_FAIL"), ("grade3_adhesion_event", f"INVALID_{species_tag}_GRADE3_ADHESION_EVENT_BOOL", f"{gate_tag}_{species_tag}_GRADE3_ADHESION_EVENT_FAIL"), ): val = s.get(fkey) if val is None: hold_reasons.append(f"MISSING_{species_tag}_SUBJECT_FIELD:{fkey}") resolved = False elif not _is_strict_bool(val): fail_reasons.append(inv_code) has_adverse = True elif val is True: fail_reasons.append(fail_code) has_adverse = True mc = s.get("monitored_complications") if mc is None: hold_reasons.append(f"MISSING_{species_tag}_SUBJECT_FIELD:monitored_complications") resolved = False elif not isinstance(mc, list) or not all(_is_literal_nonempty_str(x) for x in mc): fail_reasons.append(f"INVALID_{species_tag}_MONITORED_COMPLICATIONS_LIST") has_adverse = True elif len(mc) > 0: fail_reasons.append(f"{gate_tag}_{species_tag}_MONITORED_COMPLICATIONS_NONEMPTY_FAIL") has_adverse = True for akey in SUBJECT_COMPLICATION_BOOL_ALIAS_KEYS: if akey in s and s[akey] is not None: aval = s[akey] if not _is_strict_bool(aval): fail_reasons.append(f"INVALID_{species_tag}_COMPLICATION_ALIAS_BOOL:{akey}") has_adverse = True elif aval is True: fail_reasons.append(f"{gate_tag}_{species_tag}_COMPLICATION_ALIAS_TRUE_FAIL:{akey}") has_adverse = True for akey in SUBJECT_COMPLICATION_LIST_ALIAS_KEYS: if akey in s and s[akey] is not None: aval = s[akey] if isinstance(aval, list): if len(aval) > 0: fail_reasons.append(f"{gate_tag}_{species_tag}_COMPLICATION_ALIAS_LIST_NONEMPTY_FAIL:{akey}") has_adverse = True else: fail_reasons.append(f"INVALID_OR_ADVERSE_{species_tag}_COMPLICATION_ALIAS:{akey}") has_adverse = True # Round-8 Audit R7-08: Detect pairwise disagreement within any complication bool/list alias group for grp in SUBJECT_COMPLICATION_BOOL_ALIAS_GROUPS: grp_bools = [s[k] for k in grp if k in s and s[k] is not None and _is_strict_bool(s[k])] if len(set(grp_bools)) > 1: fail_reasons.append(f"{species_tag}_CONFLICTING_COMPLICATION_ALIAS_GROUP") has_adverse = True comp_list_vals: List[Tuple[str, ...]] = [] for k in ("monitored_complications",) + SUBJECT_COMPLICATION_LIST_ALIAS_KEYS: if k in s and isinstance(s[k], list) and all(_is_literal_nonempty_str(x) for x in s[k]): comp_list_vals.append(tuple(s[k])) if len(set(comp_list_vals)) > 1: fail_reasons.append(f"{species_tag}_CONFLICTING_COMPLICATION_ALIAS_GROUP") has_adverse = True return resolved, has_adverse def _check_subject_date_aliases( s: Mapping[str, Any], *, gate_tag: str, species_tag: str, min_days: Decimal, min_days_tag: str, followup_val: Optional[Decimal], capsule_day_val: Optional[Decimal], retrieval_day_val: Optional[Decimal], omentectomy_day_val: Optional[Decimal], cpep_day_val: Optional[Decimal], portal_day_val: Optional[Decimal], fail_reasons: List[str], ) -> bool: """Defensively validate optional subject date alias keys using exact decimal.Decimal arithmetic (ZERO ungoverned tolerance) against minimum follow-up, canonical dates, intra-group alias consistency (even when canonical key is absent), NHP omentectomy/extinction/portal chronology, and strict exact [0, 14] day post-omentectomy assessment window (Audit R5-04 / R6-05 / R7-08 / R7-13 / R8-05). """ adverse = False def _check_group( keys: Tuple[str, ...], endpoint_tag: str, canonical_val: Optional[Decimal], check_le_followup: bool, ) -> List[Tuple[str, Decimal]]: nonlocal adverse parsed_vals: List[Tuple[str, Decimal]] = [] for akey in keys: if akey in s and s[akey] is not None: aval = s[akey] if not _is_finite_number(aval) or _to_exact_decimal(aval) <= Decimal("0"): fail_reasons.append(f"INVALID_{species_tag}_DATE_ALIAS:{akey}") adverse = True else: av = _to_exact_decimal(aval) parsed_vals.append((akey, av)) if av < min_days: fail_reasons.append(f"{gate_tag}_{species_tag}_{endpoint_tag}_DATE_ALIAS_LT_{min_days_tag}_FAIL:{akey}") adverse = True if canonical_val is not None and av != canonical_val: fail_reasons.append(f"{gate_tag}_{species_tag}_{endpoint_tag}_DATE_ALIAS_CONTRADICTION:{akey}") adverse = True if check_le_followup and followup_val is not None and av > followup_val: fail_reasons.append(f"{gate_tag}_{species_tag}_{endpoint_tag}_DATE_ALIAS_EXCEEDS_FOLLOWUP:{akey}") adverse = True all_group_vals: List[Decimal] = [] if canonical_val is not None: all_group_vals.append(canonical_val) all_group_vals.extend(av for _, av in parsed_vals) if len(all_group_vals) >= 2: ref_v = all_group_vals[0] if any(v != ref_v for v in all_group_vals[1:]): fail_reasons.append(f"{species_tag}_CONFLICTING_DATE_ALIAS_GROUP") fail_reasons.append(f"{gate_tag}_{species_tag}_{endpoint_tag}_CONFLICTING_DATE_ALIAS_GROUP") adverse = True return parsed_vals _check_group(SUBJECT_FOLLOWUP_DATE_ALIAS_KEYS, "FOLLOWUP", followup_val, check_le_followup=False) _check_group(SUBJECT_CAPSULE_DATE_ALIAS_KEYS, "CAPSULE", capsule_day_val, check_le_followup=True) if species_tag == "PORCINE": _check_group(SUBJECT_RETRIEVAL_DATE_ALIAS_KEYS, "RETRIEVAL", retrieval_day_val, check_le_followup=True) elif species_tag == "NHP": _check_group(NHP_TERMINAL_DATE_ALIAS_KEYS, "RETRIEVAL", None, check_le_followup=True) proc_alias_vals = _check_group( NHP_OMENTECTOMY_PROCEDURE_DATE_ALIAS_KEYS, "OMENTECTOMY", omentectomy_day_val, check_le_followup=True, ) cpep_alias_vals = _check_group( NHP_CPEP_EXTINCTION_DATE_ALIAS_KEYS, "C_PEPTIDE_EXTINCTION", cpep_day_val, check_le_followup=True, ) port_alias_vals = _check_group( NHP_PORTAL_GRADIENT_DATE_ALIAS_KEYS, "PORTAL_GRADIENT", portal_day_val, check_le_followup=True, ) for akey, av in proc_alias_vals: if cpep_day_val is not None: if cpep_day_val < av: fail_reasons.append("NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE") fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_PRECEDES_PROCEDURE_ALIAS_FAIL:{akey}") adverse = True elif _dec_diff_exceeds(cpep_day_val, av, MAX_POST_OMENTECTOMY_CPEP_EXTINCTION_WINDOW_DAYS_DEC): fail_reasons.append("NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW") fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_EXCEEDS_14D_WINDOW_VS_PROCEDURE_ALIAS_FAIL:{akey}") adverse = True if portal_day_val is not None and portal_day_val > av: fail_reasons.append("NHP_PORTAL_GRADIENT_POST_OMENTECTOMY_INVALID") fail_reasons.append(f"R4O_05_NHP_PORTAL_GRADIENT_POST_PROCEDURE_ALIAS_FAIL:{akey}") adverse = True for akey, av in cpep_alias_vals: if omentectomy_day_val is not None: if av < omentectomy_day_val: fail_reasons.append("NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE") fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_ALIAS_PRECEDES_OMENTECTOMY_FAIL:{akey}") adverse = True elif _dec_diff_exceeds(av, omentectomy_day_val, MAX_POST_OMENTECTOMY_CPEP_EXTINCTION_WINDOW_DAYS_DEC): fail_reasons.append("NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW") fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_ALIAS_EXCEEDS_14D_WINDOW_FAIL:{akey}") adverse = True for pakey, pav in proc_alias_vals: if av < pav: fail_reasons.append("NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE") fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_ALIAS_PRECEDES_PROCEDURE_ALIAS_FAIL:{akey}:{pakey}") adverse = True elif _dec_diff_exceeds(av, pav, MAX_POST_OMENTECTOMY_CPEP_EXTINCTION_WINDOW_DAYS_DEC): fail_reasons.append("NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW") fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_ALIAS_EXCEEDS_14D_WINDOW_VS_PROCEDURE_ALIAS_FAIL:{akey}:{pakey}") adverse = True for akey, av in port_alias_vals: if omentectomy_day_val is not None and av > omentectomy_day_val: fail_reasons.append("NHP_PORTAL_GRADIENT_POST_OMENTECTOMY_INVALID") fail_reasons.append(f"R4O_05_NHP_PORTAL_GRADIENT_ALIAS_POST_OMENTECTOMY_FAIL:{akey}") adverse = True for pakey, pav in proc_alias_vals: if av > pav: fail_reasons.append("NHP_PORTAL_GRADIENT_POST_OMENTECTOMY_INVALID")