ma = atx_re.match(inner) if ma: _flush_para_for_refs() level = len(ma.group(1)) title_raw = _cm_strip_ascii_ws(ma.group(2) or "") title_raw = _cm_strip_ascii_ws(re.sub(r"(?:^|[ \t]+)#+[ \t]*$", "", title_raw)) headings.append({ "kind": "atx", "level": level, "container_depth": depth, "start_line": idx, "end_line": idx, "start_offset": line_offsets[idx], "raw_first_line": raw_line, "raw_inline_title": title_raw, }) continue if thematic_re.match(inner): _flush_para_for_refs() continue if para_lines and para_lines[-1][2] != depth: _flush_para_for_refs() para_lines.append((idx, _cm_strip_ascii_ws(cur), depth)) _flush_para_for_refs() # Second pass: render visible inline heading titles with the complete document link-reference map for h in headings: raw_t = h.pop("raw_inline_title") h["rendered_title"] = _cm_render_inline_visible_text(raw_t, doc_link_refs) return headings def _exact_pct_to_frac(pct: Decimal) -> Decimal | None: """Divide a finite Decimal percentage by 100 with zero context-precision rounding; None if exponent underflows Decimal.""" if not isinstance(pct, Decimal) or not pct.is_finite(): return None tup = pct.as_tuple() new_exp = int(tup.exponent) - 2 if new_exp < decimal.MIN_ETINY: return None try: return Decimal((tup.sign, tup.digits, new_exp)) except Exception: return None def _dec_frac_bit_estimate(d: Decimal) -> int: """Upper-bound estimate of exact rational bit-length for Fraction(d) BEFORE constructing Fraction.""" tup = d.as_tuple() exp = int(tup.exponent) return len(tup.digits) * 4 + abs(exp) * 4 + 16 def _abs_diff_exceeds_tol(a: Decimal, b: Decimal, tol: Decimal) -> bool | None: """Context-isolated exact comparison for |a - b| > tol (immune to caller Decimal precision/rounding/traps). Uses exact Fraction arithmetic whenever the aligned decimal exponent span is within a bounded budget (<= 10,000 digits), falling back to a 120-digit directed outward interval enclosure (returning None if the mismatch straddles tol beyond the exact budget). """ if not (a.is_finite() and b.is_finite() and tol.is_finite()): return None if a == b: return False ea = int(a.as_tuple().exponent) eb = int(b.as_tuple().exponent) et = int(tol.as_tuple().exponent) span = max(abs(ea), abs(eb), abs(et)) + len(a.as_tuple().digits) + len(b.as_tuple().digits) + len(tol.as_tuple().digits) if span <= 10_000: return abs(Fraction(a) - Fraction(b)) > Fraction(tol) with _clean_dec_ctx(120, ROUND_FLOOR) as ctx_d: hi_v, lo_v = (a, b) if a >= b else (b, a) diff_lo = hi_v - lo_v ctx_d.rounding = ROUND_CEILING diff_hi = hi_v - lo_v if diff_lo > tol: return True if diff_hi <= tol: return False return None def _sound_one_minus_exp_neg(x_low: Decimal, x_high: Decimal, prec: int) -> tuple[Decimal, Decimal]: """Provable outward interval [p_lo, p_hi] enclosing 1 - exp(-x) for any x in [x_low, x_high] > 0. For x_high < 1e-6, iterates strictly in paired terms (2m-1, 2m) so the lower bound ALWAYS terminates at an even partial sum S_{2m}(x_low) and the upper bound ALWAYS terminates at an odd partial sum S_{2m+1}(x_high), guaranteeing p_lo <= 1 - exp(-x) <= p_hi at every exit and any precision. """ wprec = max(prec + 40, 140) if x_high < Decimal("1e-6"): max_pairs = max(64, prec) with _clean_dec_ctx(wprec, ROUND_FLOOR) as ctx_t: # 1. Provable lower bound on 1 - exp(-x_low) via even truncation S_{2m}(x_low) thresh_lo = x_low * Decimal(1).scaleb(-(prec + 8)) fact = 1 pow_lo = x_low pow_hi = x_low s_lo = Decimal(0) for pair_idx in range(1, max_pairs + 1): # Odd term k = 2*pair_idx - 1 (added with ROUND_FLOOR) ctx_t.rounding = ROUND_FLOOR term_odd_lo = pow_lo / Decimal(fact) s_lo = s_lo + term_odd_lo # Advance to even term k = 2*pair_idx k_even = 2 * pair_idx fact *= k_even ctx_t.rounding = ROUND_FLOOR pow_lo = pow_lo * x_low ctx_t.rounding = ROUND_CEILING pow_hi = pow_hi * x_low # Even term subtracted with ROUND_CEILING on magnitude & ROUND_FLOOR on sum ctx_t.rounding = ROUND_CEILING term_even_hi = pow_hi / Decimal(fact) ctx_t.rounding = ROUND_FLOOR s_lo = s_lo - term_even_hi if term_even_hi <= thresh_lo: break fact *= k_even + 1 ctx_t.rounding = ROUND_FLOOR pow_lo = pow_lo * x_low ctx_t.rounding = ROUND_CEILING pow_hi = pow_hi * x_low if s_lo < Decimal(0): s_lo = Decimal(0) # 2. Provable upper bound on 1 - exp(-x_high) via odd truncation S_{2m+1}(x_high) thresh_hi = x_high * Decimal(1).scaleb(-(prec + 8)) fact = 1 pow_lo = x_high pow_hi = x_high # Start with k = 1 (odd upper bound S_1 = x_high) ctx_t.rounding = ROUND_CEILING s_hi = x_high for pair_idx in range(1, max_pairs + 1): # Even term k = 2*pair_idx (subtracted with ROUND_FLOOR on magnitude & ROUND_CEILING on sum) k_even = 2 * pair_idx fact *= k_even ctx_t.rounding = ROUND_FLOOR pow_lo = pow_lo * x_high ctx_t.rounding = ROUND_CEILING pow_hi = pow_hi * x_high ctx_t.rounding = ROUND_FLOOR term_even_lo = pow_lo / Decimal(fact) ctx_t.rounding = ROUND_CEILING s_hi = s_hi - term_even_lo # Odd term k = 2*pair_idx + 1 (added with ROUND_CEILING -> guaranteed odd upper bound S_{2m+1}) k_odd = k_even + 1 fact *= k_odd ctx_t.rounding = ROUND_FLOOR pow_lo = pow_lo * x_high ctx_t.rounding = ROUND_CEILING pow_hi = pow_hi * x_high ctx_t.rounding = ROUND_CEILING term_odd_hi = pow_hi / Decimal(fact) s_hi = s_hi + term_odd_hi if term_odd_hi <= thresh_hi: break if s_hi > Decimal(1): s_hi = Decimal(1) with _clean_dec_ctx(prec, ROUND_FLOOR): p_lo_out = +s_lo with _clean_dec_ctx(prec, ROUND_CEILING): p_hi_out = +s_hi return p_lo_out, p_hi_out with _clean_dec_ctx(wprec, ROUND_FLOOR) as ctx_e: exp_lo = (-x_high).exp().next_minus() ctx_e.rounding = ROUND_CEILING p_hi_raw = Decimal(1) - exp_lo exp_hi = (-x_low).exp().next_plus() ctx_e.rounding = ROUND_FLOOR p_lo_raw = Decimal(1) - exp_hi if p_lo_raw < Decimal(0): p_lo_raw = Decimal(0) if p_hi_raw > Decimal(1): p_hi_raw = Decimal(1) with _clean_dec_ctx(prec, ROUND_FLOOR): p_lo_out = +p_lo_raw with _clean_dec_ctx(prec, ROUND_CEILING): p_hi_out = +p_hi_raw return p_lo_out, p_hi_out def _zero_event_u95_compare( alpha_d: Decimal, n_raw: int, f_d: Decimal, eta_d: Decimal, target_frac: Decimal, *, u95_lower: Decimal, u95_upper: Decimal, ) -> bool | None: """Sound three-valued decider for true U95 = (1 - alpha^(1/n)) / (f * eta) <= target_frac. Returns: - True: provably true_u95 <= target_frac - False: provably target_frac < true_u95 - None: beyond the 2,000,000-bit exact rational budget AND target_frac lies strictly inside the ~1e-258-relative-width 260-digit Taylor/exp outward enclosure [u_lo_260, u_hi_260]. """ if target_frac <= Decimal(0): return False if u95_upper <= target_frac: return True if target_frac < u95_lower: return False # Budget prospective Fraction conversions BEFORE constructing any Fraction (zero DoS on extreme exponents), # and compute 1 - f*eta*target directly in exact rational arithmetic (never rounding near-one bases!). max_in_bits = max( _dec_frac_bit_estimate(alpha_d), _dec_frac_bit_estimate(f_d), _dec_frac_bit_estimate(eta_d), _dec_frac_bit_estimate(target_frac), ) if max_in_bits <= 250_000: prod_frac = Fraction(f_d) * Fraction(eta_d) * Fraction(target_frac) b_frac = Fraction(1) - prod_frac if b_frac <= 0: return True a_frac = Fraction(alpha_d) max_base_bits = max(b_frac.numerator.bit_length(), b_frac.denominator.bit_length()) if n_raw * max_base_bits <= 2_000_000: lhs_num = pow(b_frac.numerator, n_raw) * a_frac.denominator rhs_num = a_frac.numerator * pow(b_frac.denominator, n_raw) return lhs_num <= rhs_num with _clean_dec_ctx(280, ROUND_FLOOR) as ctx_hi: eff_lo_hi = f_d * eta_d if eff_lo_hi <= Decimal(0): return False ctx_hi.rounding = ROUND_CEILING eff_hi_hi = f_d * eta_d ctx_hi.rounding = ROUND_FLOOR ln_a_lo = alpha_d.ln().next_minus() ctx_hi.rounding = ROUND_CEILING ln_a_hi = alpha_d.ln().next_plus() n_dec = Decimal(n_raw) ctx_hi.rounding = ROUND_FLOOR x_lo_260 = (-ln_a_hi) / n_dec ctx_hi.rounding = ROUND_CEILING x_hi_260 = (-ln_a_lo) / n_dec p_lo_260, p_hi_260 = _sound_one_minus_exp_neg(x_lo_260, x_hi_260, 260) ctx_hi.rounding = ROUND_FLOOR u_lo_260 = p_lo_260 / eff_hi_hi ctx_hi.rounding = ROUND_CEILING