out[k] = v return out def _no_nonfinite(tok: str) -> Any: raise ValueError(f"Non-finite JSON constant {tok!r} rejected (fail-closed) in {source_name}") def _parse_exact_decimal(tok: str) -> Decimal: try: dec = Decimal(tok) except (InvalidOperation, DecimalException) as exc: raise ValueError(f"Out-of-range or invalid JSON decimal {tok!r} rejected (fail-closed) in {source_name}") from exc if not dec.is_finite(): raise ValueError(f"Non-finite JSON decimal {tok!r} rejected (fail-closed) in {source_name}") return dec return json.loads( text, object_pairs_hook=_no_dup_pairs, parse_float=_parse_exact_decimal, parse_constant=_no_nonfinite, ) def _is_strict_bool(val: Any) -> bool: return type(val) is bool def _is_strict_int(val: Any) -> bool: return type(val) is int and abs(val) <= MAX_SAFE_INT_ABS def _is_safe_decimal_magnitude(val: Decimal) -> bool: """100% context-independent Decimal finiteness and magnitude guard (Audit R10-05). Uses ONLY context-independent Decimal methods (is_finite, is_zero, adjusted, copy_abs) BEFORE any comparison so extreme finite exponents (e.g. 1e1000, 1e99999999, -1e99999999, 1e-99999999, 9.999999999999999e+99999999) NEVER trigger decimal.Overflow/Underflow under ANY active Decimal context. """ if not val.is_finite(): return False if val.is_zero(): return True adj = val.adjusted() if adj > MAX_SAFE_DECIMAL_ADJUSTED or adj < MIN_SAFE_DECIMAL_ADJUSTED: return False if adj == MAX_SAFE_DECIMAL_ADJUSTED: return val.copy_abs() <= MAX_SAFE_DECIMAL_ABS return True def _is_finite_number(val: Any) -> bool: """Safe numeric check for int, float, and decimal.Decimal (never bool/str; context-independent bounds).""" if isinstance(val, bool): return False if type(val) is int: return abs(val) <= MAX_SAFE_INT_ABS if type(val) is float: return math.isfinite(val) and abs(val) <= MAX_SAFE_FLOAT_ABS if type(val) is Decimal: return _is_safe_decimal_magnitude(val) return False def _to_exact_decimal(val: Any) -> Decimal: """Convert a validated finite Decimal, int, float, or exact finite decimal str to exact decimal.Decimal. Authoritative precision contract (Audit R9-06 / R10-05): - Decimal (including all JSON float tokens loaded via load_strict_json_text): checked with context-independent magnitude guard and returned verbatim (ZERO float(); zeros normalized to Decimal(0)). - int: bounded exact Decimal(val) (ZERO float()). - Exact decimal str (if invoked directly on a lexical token): bounded exact Decimal(val) (ZERO float()). - In-memory IEEE-754 float: bounded shortest round-trip Decimal(str(val)) (callers requiring sub-ULP < 1e-14 precision MUST pass Decimal or parse raw JSON via load_strict_json_text). """ if isinstance(val, bool): raise TypeError("bool is not a numeric Decimal value") if type(val) is Decimal: if not _is_safe_decimal_magnitude(val): raise ValueError(f"Non-finite or out-of-range Decimal rejected: {val!r}") return Decimal(0) if val.is_zero() else val if type(val) is int: if abs(val) > MAX_SAFE_INT_ABS: raise ValueError(f"Out-of-range int rejected: {val!r}") return Decimal(val) if type(val) is float: if not math.isfinite(val) or abs(val) > MAX_SAFE_FLOAT_ABS: raise ValueError(f"Non-finite or out-of-range float rejected: {val!r}") return Decimal(str(val)) if type(val) is str: s = val.strip() if not s or s != val or not _STRICT_DECIMAL_STR_RE.fullmatch(s): raise ValueError(f"Invalid decimal string token rejected: {val!r}") try: dec = Decimal(s) except (InvalidOperation, DecimalException) as exc: raise ValueError(f"Unparseable decimal string token rejected: {val!r}") from exc if not _is_safe_decimal_magnitude(dec): raise ValueError(f"Non-finite or out-of-range decimal string token rejected: {val!r}") return Decimal(0) if dec.is_zero() else dec raise TypeError(f"Unsupported type for exact Decimal conversion: {type(val).__name__}") def _dec_add(a: Decimal, b: Decimal) -> Decimal: """Exact, context-independent, zero-rounding Decimal sum (zero caller-context leakage).""" if not (a.is_finite() and b.is_finite()): raise ValueError("Non-finite Decimal operand in _dec_add") if a.is_zero(): return ZERO_DEC if b.is_zero() else b if b.is_zero(): return a t_a = a.as_tuple() t_b = b.as_tuple() exp_a = t_a.exponent if isinstance(t_a.exponent, int) else 0 exp_b = t_b.exponent if isinstance(t_b.exponent, int) else 0 hi = max(a.adjusted(), b.adjusted(), 0) lo = min(exp_a, exp_b, 0) needed = (hi - lo) + 16 prec_use = max(120, needed) emax_use = min(MAX_EMAX, max(999_999, abs(hi) + 1000, abs(lo) + 1000)) with localcontext(Context(prec=prec_use, Emax=emax_use, Emin=-emax_use)): return a + b def _dec_sub(a: Decimal, b: Decimal) -> Decimal: """Exact, context-independent, zero-rounding Decimal difference (zero caller-context leakage).""" if not (a.is_finite() and b.is_finite()): raise ValueError("Non-finite Decimal operand in _dec_sub") if b.is_zero(): return ZERO_DEC if a.is_zero() else a return _dec_add(a, b.copy_negate()) def _dec_mul(a: Decimal, b: Decimal) -> Decimal: """Exact, context-independent, zero-rounding Decimal product (zero caller-context leakage).""" if not (a.is_finite() and b.is_finite()): raise ValueError("Non-finite Decimal operand in _dec_mul") if a.is_zero() or b.is_zero(): return ZERO_DEC t_a = a.as_tuple() t_b = b.as_tuple() exp_a = t_a.exponent if isinstance(t_a.exponent, int) else 0 exp_b = t_b.exponent if isinstance(t_b.exponent, int) else 0 needed = len(t_a.digits) + len(t_b.digits) + 16 prec_use = max(120, needed) emax_use = min(MAX_EMAX, max(999_999, abs(a.adjusted()) + abs(b.adjusted()) + abs(exp_a) + abs(exp_b) + 1000)) with localcontext(Context(prec=prec_use, Emax=emax_use, Emin=-emax_use)): return a * b def _exact_sum3_gt_zero(x: Decimal, y: Decimal, z: Decimal) -> bool: """Exact, context-independent, zero-rounding test for (x + y + z) > 0 across ALL finite Decimals (Audit R10-05). Never overflows, underflows, or allocates extreme precision even on 1e99999999 / -1e99999999 / 1e-99999999 or restricted caller contexts, while remaining 100% exact on sub-yoctosecond tokens. """ for v in (x, y, z): if not v.is_finite(): raise ValueError(f"Non-finite Decimal operand: {v!r}") nz = [v for v in (x, y, z) if not v.is_zero()] if not nz: return False if len(nz) == 1: return not nz[0].is_signed() if len(nz) == 2: return nz[0] > nz[1].copy_negate() nz.sort(key=lambda v: v.adjusted(), reverse=True) u, v, w = nz u_adj = u.adjusted() v_adj = v.adjusted() if u_adj - v_adj >= 2: return not u.is_signed() tu = u.as_tuple() tv = v.as_tuple() tw = w.as_tuple() shift = u_adj u_s = Decimal((tu.sign, tu.digits, tu.exponent - shift)) v_s = Decimal((tv.sign, tv.digits, tv.exponent - shift)) prec_need = max(len(tu.digits), len(tv.digits)) + 16 emax_need = min(MAX_EMAX, max(1000, prec_need + 100)) with localcontext(Context(prec=prec_need, Emax=emax_need, Emin=-emax_need)): s_s = u_s + v_s if s_s.is_zero(): return not w.is_signed() s_neg = s_s.is_signed() w_neg = w.is_signed() if s_neg == w_neg: return not s_neg s_adj = s_s.adjusted() + shift w_adj = w.adjusted() if s_adj > w_adj: return not s_neg if s_adj < w_adj: return not w_neg w_s = Decimal((tw.sign, tw.digits, tw.exponent - shift)) return s_s > w_s.copy_negate() def _dec_diff_exceeds(a: Decimal, b: Decimal, bound: Decimal) -> bool: """Exact zero-rounding test for (a - b) > bound across arbitrary finite Decimals (even extreme exponents).""" if not (a.is_finite() and b.is_finite() and bound.is_finite()): raise ValueError("Non-finite Decimal operand in _dec_diff_exceeds") return _exact_sum3_gt_zero(a, b.copy_negate(), bound.copy_negate()) def _dec_abs_diff_exceeds(a: Decimal, b: Decimal, bound: Decimal) -> bool: """Exact zero-rounding test for |a - b| > bound across arbitrary finite Decimals.""" hi_v, lo_v = (a, b) if a >= b else (b, a) return _dec_diff_exceeds(hi_v, lo_v, bound) def _ratio_lt_dec(num: Decimal, den: Decimal, bound: Decimal) -> bool: """Exact zero-rounding test for (num / den) < bound with den > 0.""" return num < _dec_mul(bound, den) def _ratio_le_dec(num: Decimal, den: Decimal, bound: Decimal) -> bool: """Exact zero-rounding test for (num / den) <= bound with den > 0.""" return num <= _dec_mul(bound, den) def _ratio_gt_dec(num: Decimal, den: Decimal, bound: Decimal) -> bool: """Exact zero-rounding test for (num / den) > bound with den > 0.""" return num > _dec_mul(bound, den) def _ratio_ge_dec(num: Decimal, den: Decimal, bound: Decimal) -> bool: """Exact zero-rounding test for (num / den) >= bound with den > 0.""" return num >= _dec_mul(bound, den) def _ratio_gt_ratio(n1: Decimal, d1: Decimal, n2: Decimal, d2: Decimal) -> bool: """Exact zero-rounding test for (n1 / d1) > (n2 / d2) with d1 > 0 and d2 > 0.""" return _dec_mul(n1, d2) > _dec_mul(n2, d1) def _max_ratio(ratios: Sequence[Tuple[Decimal, Decimal]]) -> Tuple[Decimal, Decimal]: """Return exact maximum (num, den) pair from a non-empty sequence of positive-denominator Decimal ratios.""" best = ratios[0] for cand in ratios[1:]: if _ratio_gt_ratio(cand[0], cand[1], best[0], best[1]): best = cand return best def _ratio_rel_diff_exceeds(num: Decimal, den: Decimal, ref: Decimal, rel_tol: Decimal) -> bool: """Exact zero-rounding test for |(num / den) - ref| / ref > rel_tol with den > 0, ref > 0.""" ref_den = _dec_mul(ref, den) return _dec_abs_diff_exceeds(num, ref_den, _dec_mul(rel_tol, ref_den))