def _strict_json_equal(a: Any, b: Any) -> bool: """Deep equality checking exact Python types (prevents True==1 or nested type spoofing).""" if type(a) is not type(b): return False if isinstance(a, dict): if len(a) != len(b): return False for k, va in a.items(): if k not in b or not _strict_json_equal(va, b[k]): return False return True if isinstance(a, list): if len(a) != len(b): return False return all(_strict_json_equal(x, y) for x, y in zip(a, b)) if type(a) is float: if not (math.isfinite(a) and math.isfinite(b)): return False return a == b return bool(a == b) def _to_exact_decimal(v: Any) -> Optional[Decimal]: """Convert bounded int/float/Decimal (never bool) into exact Decimal via str() for decimal-exact arithmetic.""" if _is_strict_bool(v): return None if isinstance(v, Decimal): if not v.is_finite() or abs(v) > Decimal(MAX_SAFE_ABS_NUMBER): return None return v if _is_finite_number(v): return Decimal(str(v)) return None CHS4_0C9_V090_SEQ_SHA256 = sha256_str( EMBEDDED_AUTHENTIC_ASSETS["authentic_genomic_and_regulatory"]["cHS4_0C9_v090"]["seq"] ) CBX3_700BP_UCOE_SEQ_SHA256 = sha256_str( EMBEDDED_AUTHENTIC_ASSETS["authentic_genomic_and_regulatory"]["CBX3_A2UCOE_GRCh38_700bp"]["seq"] ) def compute_canonical_record_sha256(record: Mapping[str, Any]) -> str: """Compute canonical JSON SHA-256 of an evidence record excluding digest fields.""" clone = {k: v for k, v in record.items() if k not in ("archive_sha256", "record_sha256")} canon = json.dumps(clone, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False) return sha256_str(canon) def verify_arm_manifest_dict_integrity(arm_manifest: Any) -> Tuple[bool, Optional[str]]: """Verify caller-supplied arm_manifest dict against the pinned canonical manifest digest.""" if not isinstance(arm_manifest, dict): return False, None try: canon_bytes = json.dumps( arm_manifest, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False ).encode("utf-8") except (TypeError, ValueError, OverflowError): return False, None if sha256_bytes(canon_bytes) != EXPECTED_ARM_MANIFEST_CANONICAL_SHA256: return False, None return True, EXPECTED_ARM_MANIFEST_SHA256 def _init_decimal_gamma_constants() -> Tuple[Tuple[Decimal, ...], Decimal]: """Precompute exact Stirling coefficients B_{2j}/(2j*(2j-1)) and 0.5*ln(2*pi) at 80-digit Decimal precision.""" with localcontext() as ctx: ctx.prec = 85 # Exact Bernoulli numbers via Akiyama-Tanigawa rational recurrence a_row: List[Fraction] = [] coeffs: List[Decimal] = [] for m in range(51): a_row.append(Fraction(1, m + 1)) for j in range(m, 0, -1): a_row[j - 1] = j * (a_row[j - 1] - a_row[j]) if m >= 2 and m % 2 == 0: bm = a_row[0] coeffs.append(Decimal(bm.numerator) / Decimal(bm.denominator * m * (m - 1))) def _atan_inv(inv_x: int) -> Decimal: x2 = Decimal(inv_x * inv_x) term = Decimal(1) / Decimal(inv_x) total = term idx = 1 while term != 0: term = -term / x2 add = term / (2 * idx + 1) if add == 0: break total += add idx += 1 return total pi_d = Decimal(16) * _atan_inv(5) - Decimal(4) * _atan_inv(239) half_ln_2pi = Decimal("0.5") * (Decimal(2) * pi_d).ln() return tuple(coeffs), half_ln_2pi _STIRLING_COEFFS_DEC, _HALF_LN_2PI_DEC = _init_decimal_gamma_constants() def _lgamma_pos_int_dec(n_int: int) -> Decimal: """High-precision ln(Gamma(n_int)) in active Decimal context (accurate to < 1e-55 for all n_int >= 1).""" shift_prod = 1 x_int = n_int while x_int < 60: shift_prod *= x_int x_int += 1 x = Decimal(x_int) inv_x = Decimal(1) / x inv_x2 = inv_x * inv_x series = Decimal(0) p_inv = inv_x eps_term = Decimal("1e-62") for coeff in _STIRLING_COEFFS_DEC: term = coeff * p_inv series += term p_inv *= inv_x2 if abs(term) < eps_term: break res = (x - Decimal("0.5")) * x.ln() - x + _HALF_LN_2PI_DEC + series if shift_prod > 1: res -= Decimal(shift_prod).ln() return res def _betacf_dec(a: Decimal, b: Decimal, x: Decimal) -> Decimal: """Modified Lentz continued fraction for regularized incomplete beta I_x(a, b) in active Decimal context.""" max_iter = 200_000 eps = Decimal("1e-45") fpmin = Decimal("1e-300") one = Decimal(1) qab = a + b qap = a + one qam = a - one c = one d = one - qab * x / qap if abs(d) < fpmin: d = fpmin d = one / d h = d for m in range(1, max_iter + 1): m2 = 2 * m aa = m * (b - m) * x / ((qam + m2) * (a + m2)) d = one + aa * d if abs(d) < fpmin: d = fpmin c = one + aa / c if abs(c) < fpmin: c = fpmin d = one / d h *= d * c aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)) d = one + aa * d if abs(d) < fpmin: d = fpmin c = one + aa / c if abs(c) < fpmin: c = fpmin d = one / d delta = d * c h *= delta if abs(delta - one) <= eps: return h raise RuntimeError(f"Decimal incomplete beta continued fraction did not converge (a={a}, b={b}, x={x})") def _reg_inc_beta_and_pdf_dec( k_plus_1: int, n_minus_k: int, x: Decimal, log_beta_inv: Decimal ) -> Tuple[Decimal, Decimal]: """High-precision regularized incomplete beta I_x(k+1, n-k) and d/dx I_x(k+1, n-k) in active Decimal context.""" one = Decimal(1) if x <= 0: return Decimal(0), Decimal(0) if x >= one: return one, Decimal(0) a = Decimal(k_plus_1) b = Decimal(n_minus_k) log_bt = log_beta_inv + a * x.ln() + b * (one - x).ln() bt = Decimal(0) if log_bt < Decimal("-50000") else log_bt.exp() if x < (a + one) / (a + b + 2): ib = bt * _betacf_dec(a, b, x) / a else: ib = one - bt * _betacf_dec(b, a, one - x) / b pdf = bt / (x * (one - x)) return ib, pdf def clopper_pearson_u95_decimal(k: int, n: int, alpha: float = 0.05) -> Decimal: """Error-controlled pure-stdlib Decimal one-sided (1 - alpha) Clopper-Pearson upper bound. Enforces exact integer domain 1 <= n <= 10^12 and 0 <= k <= n, evaluates Stirling ln(Gamma) and Lentz continued-fraction I_p(k+1, n-k) at 75-digit Decimal precision (zero float64 lgamma cancellation at n=10^12), and certifies a conservative upper bracket hi with I_lo < 1 - alpha <= I_hi and hi - lo <= 1e-28 * hi. """ require_cond(_is_strict_int(k) and _is_strict_int(n), "clopper_pearson_u95 requires bounded strict integers") require_cond(1 <= n <= MAX_CLONOGENIC_CELLS, f"clopper_pearson_u95 n out of domain [1, {MAX_CLONOGENIC_CELLS}]: {n}") require_cond(0 <= k <= n, f"clopper_pearson_u95 k out of domain [0, {n}]: {k}") require_cond(_is_finite_number(alpha) and 0.0 < float(alpha) < 1.0, f"Invalid alpha={alpha}") a_f = float(alpha) if k == n: return Decimal(1) with localcontext() as ctx: ctx.prec = 75 a_d = Decimal(str(a_f)) if k == 0: exact = Decimal(1) - (a_d.ln() / Decimal(n)).exp() return +exact target = Decimal(1) - a_d a_int = k + 1 b_int = n - k log_beta_inv = _lgamma_pos_int_dec(n + 1) - _lgamma_pos_int_dec(a_int) - _lgamma_pos_int_dec(b_int) p_hat = Decimal(k) / Decimal(n) lo = Decimal(0) hi = Decimal(1) z = Decimal("1.6448536269514722") if a_d <= Decimal("0.5") else Decimal("0") se = (p_hat * (Decimal(1) - p_hat) / Decimal(n)).sqrt() p = p_hat + z * se + Decimal("0.5") / Decimal(n) if not (lo < p < hi): p = (lo + hi) / Decimal(2) tol = Decimal("1e-28") for _ in range(200): ib, pdf = _reg_inc_beta_and_pdf_dec(a_int, b_int, p, log_beta_inv) err = ib - target if err < 0: lo = p else: hi = p if hi - lo <= tol * max(hi, Decimal("1e-35")): break step_ok = False if pdf > 0: step = err / pdf p_new = p - step if lo < p_new < hi: if abs(step) <= tol * max(p_new, Decimal("1e-35")): eps_b = max(tol * p_new, Decimal("1e-45")) p_hi = min(hi, p_new + eps_b) p_lo = max(lo, p_new - eps_b) ib_hi, _ = _reg_inc_beta_and_pdf_dec(a_int, b_int, p_hi, log_beta_inv) if ib_hi >= target: hi = p_hi ib_lo, _ = _reg_inc_beta_and_pdf_dec(a_int, b_int, p_lo, log_beta_inv) if ib_lo < target: lo = p_lo break p = p_new step_ok = True