def _dec_rel_diff_exceeds_ratio(claimed: Decimal, num: Decimal, den: Decimal, rel_tol: Decimal) -> bool: """Exact zero-rounding test for |claimed - (num / den)| / (num / den) > rel_tol with num > 0, den > 0.""" return _dec_abs_diff_exceeds(_dec_mul(claimed, den), num, _dec_mul(rel_tol, num)) def _dec_to_display_float(val: Optional[Decimal]) -> Optional[float]: """Convert an exact Decimal to IEEE-754 float ONLY for metadata/display AFTER policy decisions.""" if val is None or not val.is_finite(): return None if val.is_zero(): return 0.0 adj = val.adjusted() if adj > 308: return None if adj < -324: return 0.0 f = float(val) return f if math.isfinite(f) else None def _dec_div_to_display_float(num: Decimal, den: Decimal) -> Optional[float]: """Convert an exact Decimal ratio num / den to IEEE-754 float ONLY for metadata/display AFTER policy decisions.""" if not (num.is_finite() and den.is_finite()) or den.is_zero(): return None if num.is_zero(): return 0.0 emax_use = min(MAX_EMAX, max(999_999, abs(num.adjusted()) + abs(den.adjusted()) + 1000)) with localcontext(Context(prec=60, Emax=emax_use, Emin=-emax_use)): q = num / den return _dec_to_display_float(q) def _is_literal_nonempty_str(val: Any) -> bool: return isinstance(val, str) and len(val) > 0 and val == val.strip() def _is_canonical_id_str(val: Any) -> bool: """Strict ASCII canonical identifier: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$, isascii, NFKC==raw, zero C*/Z*/M*.""" if not isinstance(val, str) or len(val) == 0 or len(val) > 64: return False if not val.isascii(): return False if unicodedata.normalize("NFKC", val) != val: return False if any(unicodedata.category(ch)[0] in ("C", "Z", "M") for ch in val): return False return bool(_CANONICAL_ID_RE.fullmatch(val)) def _canonical_id_dedup_key(val: str) -> str: """NFKC-normalized, C*/Z*/M*-stripped, casefolded key for canonical subject/procedure duplicate detection.""" norm = unicodedata.normalize("NFKC", val) stripped = "".join(ch for ch in norm if unicodedata.category(ch)[0] not in ("C", "Z", "M")) return stripped.casefold() def _is_valid_sha256_hex(val: Any) -> bool: return isinstance(val, str) and bool(_SHA256_HEX_RE.match(val)) def _is_non_all_zero_sha256_hex(val: Any) -> bool: return _is_valid_sha256_hex(val) and val != ("0" * 64) def _format_canonical_json_number(val: Any) -> str: """Lossless canonical JSON number token for int, float, and exact Decimal. - Exact IEEE-754 float64 values (including Decimals that round-trip losslessly to float64, e.g. 14.0, 1.5e-05, 14.000000000000000) serialize identically to json.dumps(float, allow_nan=False), preserving 100% SHA-256 parity with existing canonical manifests, contracts, receipts, and archives. - Any sub-ULP or beyond-float64 Decimal (e.g. 104.000000000000001, 14.000000000000001, 1e-400) preserves EVERY exact significant digit without rounding or collision (Audit R9-06). """ if type(val) is int: return str(val) if type(val) is float: if not math.isfinite(val): raise ValueError(f"Out of range float value is not JSON compliant: {val!r}") return json.dumps(val, allow_nan=False) if type(val) is Decimal: if not val.is_finite(): raise ValueError(f"Out of range Decimal value is not JSON compliant: {val!r}") if val.is_zero(): return "-0.0" if val.is_signed() else "0.0" adj = val.adjusted() if -324 <= adj <= 308: f = float(val) if math.isfinite(f) and Decimal(repr(f)) == val and (val.is_signed() == (math.copysign(1.0, f) < 0.0)): return json.dumps(f, allow_nan=False) sign, digits, exp = val.as_tuple() if not isinstance(exp, int): raise ValueError(f"Non-finite Decimal value is not JSON compliant: {val!r}") if all(dg == 0 for dg in digits): return "-0.0" if sign else "0.0" end = len(digits) if exp < 0: while end > 1 and digits[end - 1] == 0 and exp < 0: end -= 1 exp += 1 elif exp > 0: while end > 1 and digits[end - 1] == 0: end -= 1 exp += 1 d_norm = Decimal((sign, digits[:end], exp)) return str(d_norm).lower() raise TypeError(f"Object of type {type(val).__name__} is not a JSON number") def canonical_json_dumps(obj: Any) -> str: """Deterministic canonical JSON serializer supporting exact Decimal without precision loss (Audit R9-06).""" if obj is None: return "null" if type(obj) is bool: return "true" if obj else "false" if type(obj) in (int, float, Decimal): return _format_canonical_json_number(obj) if type(obj) is str: return json.dumps(obj, ensure_ascii=False) if isinstance(obj, (list, tuple)): return "[" + ",".join(canonical_json_dumps(x) for x in obj) + "]" if isinstance(obj, Mapping): items: List[str] = [] for k in sorted(obj.keys()): if type(k) is not str: raise TypeError(f"Canonical JSON object key must be str, got {type(k).__name__}") items.append(json.dumps(k, ensure_ascii=False) + ":" + canonical_json_dumps(obj[k])) return "{" + ",".join(items) + "}" raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable") def _canonical_json_sha256(obj: Any) -> str: raw = canonical_json_dumps(obj).encode("utf-8") return sha256_bytes(raw) def _fmt_sci_float(val: float) -> float: return float(f"{float(val):.4e}") def _strict_json_equal(a: Any, b: Any) -> bool: """Strict type- and exact-Decimal-value-aware JSON equality (bool never equals int; rejects non-finite; ZERO float rounding).""" if type(a) is bool or type(b) is bool: return type(a) is type(b) and a is b if isinstance(a, (int, float, Decimal)) and isinstance(b, (int, float, Decimal)): if not (_is_finite_number(a) and _is_finite_number(b)): return False return _to_exact_decimal(a) == _to_exact_decimal(b) if type(a) is not type(b): return False if isinstance(a, list): return len(a) == len(b) and all(_strict_json_equal(x, y) for x, y in zip(a, b)) if isinstance(a, dict): return set(a.keys()) == set(b.keys()) and all(_strict_json_equal(a[k], b[k]) for k in a.keys()) return bool(a == b) 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(Context(prec=85, Emax=999_999, Emin=-999_999)): 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