#!/usr/bin/env python3
r"""c5-ladder-xy-evaluate.py -- Phi^(3)(X,Y): the three-loop C5 ladder of the mpl-suite page as a function of BOTH mass
ratios, evaluated from its closed form inside the region where that form is real, checked against an independent
one-fold integral representation and against the values of record, and linked to the served one-variable slice
function f_3(x) of c5-ladder-evaluate.py by the holomorphic-block identity.  Second script of the row, beside
c5-ladder-evaluate.py (which is unchanged: it evaluates f_3(x) alone).  python3 + mpmath only; the sibling
c5-ladder-evaluate.py is imported by path for the identity and is sha256-pinned; the data file
vendor_row04_xy/points.json (the points, the values of record, the fit-independent x values) is sha256-pinned.

THE OBJECT (Usyukina-Davydychev conventions, arXiv:1303.6909 eqs 2.2 / 2.3)
    X = z zbar,   Y = (1-z)(1-zbar)                      (X = p1^2/p3^2, Y = p2^2/p3^2 of the off-shell three-point ladder)
    Phi^(L)(X,Y) = -f^(L)(w, wbar)/(z - zbar),   w = z/(z-1),  wbar = zbar/(zbar-1)                                 [eq 2.2]
    f^(L)(w,wbar) = sum_{r=0}^{L} c_r log^r(w wbar) (Li_{2L-r}(w) - Li_{2L-r}(wbar)),  c_r = (-1)^r (2L-r)!/(r!(L-r)!L!)  [eq 2.3]
    L = 3: c_r = {20, -10, 2, -1/6}.  Given exact (X,Y):  z = [(1+X-Y) + i sqrt(4XY-(X+Y-1)^2)]/2  (Im z > 0), since
    (z-zbar)^2 = (X+Y-1)^2 - 4XY and z + zbar = 1 + X - Y.  Phi^(3) is real there.

THE REGION OF THE z-FORM (--point; exit 2 by name outside it):   X > 0,  Y > 0,  4XY > (X+Y-1)^2,
    i.e. the Kallen function lambda(1,X,Y) = (X+Y-1)^2 - 4XY is negative, i.e. z is not real.  In the z-language
    lambda > 0 means z = zbar: the prefactor 1/(z-zbar) is singular and f^(3) vanishes, so the z-form above is a 0/0
    limit there (and the angle form of Davydychev, arXiv:1007.0237 eq. Phi_L_3b, reads 0/(imaginary)).  But the
    original real-lambda form of Usyukina and Davydychev (1993),
        Phi^(L)(x,y) = -(1/(L! lam)) sum_{j=L}^{2L} (-1)^j j! ln^(2L-j)(y/x) / ((j-L)! (2L-j)!) [Li_j(-1/(rho x)) - Li_j(-rho y)],
        lam = sqrt((1-x-y)^2 - 4xy),   rho = 2/(1-x-y+lam),   arguments ordered (x, y) = (max, min) of (X, Y) (Phi is symmetric),
    covers X, Y > 0 with lambda > 0 directly and is real-analytic there; inside the region the same expression in
    complex arithmetic equals the z-form.  Geometry: lambda(1,X,Y) = (1-(sqrt X+sqrt Y)^2)(1-(sqrt X-sqrt Y)^2) < 0
    exactly when (1, sqrt X, sqrt Y) satisfy the strict triangle inequalities: lambda < 0 is where real Euclidean
    three-point momenta with these virtualities exist, lambda > 0 with X, Y > 0 is reached by same-sign virtualities
    without a real momentum configuration.  This script evaluates lambda > 0 by the real-lambda form (the
    --lambda-positive tier below) and gates it at two points; --point keeps the z-form's region and refuses by name
    outside it, naming the tier.  (Until 2026-09-11 this docstring said that no formula for lambda > 0 was implemented
    and called the fence the physical region rather than a property of the z-form; the real-lambda form settles both.)
Y -> 0: NO LIMIT EXISTS.  Phi^(3)(X,Y) carries ln(Y/X) factors and grows like ln^3 Y; at fixed X != 1 the ray Y -> 0
    also leaves the region (4XY-(X+Y-1)^2 -> -(X-1)^2 < 0), so the fence refuses first.  The link between Phi^(3)(X,Y)
    and the served f_3(x) is therefore NOT a limit and NOT a value of Phi^(3) at some (X,Y): it is the block identity.

THE HOLOMORPHIC-BLOCK IDENTITY (the --identity tier)
    Write f^(3)(w,wbar) = B(ell; w) - B(ell; wbar) with ell = log(w wbar) and the holomorphic block
        B(ell; w) := sum_{r=0}^{3} c_r ell^r Li_{6-r}(w).
    The served slice function is the block with ell and w specialised INDEPENDENTLY,
        f_3(x) = 3! B(ell = ln x; w = -x) = 120 Li_6(-x) - 60 ln x Li_5(-x) + 12 ln^2 x Li_4(-x) - ln^3 x Li_3(-x),
    i.e. C3 = {120, -60, 12, -1} = 3! c_r exactly (a coefficient/basis identity linking the two normalisations; the
    identity specialises ell = ln x independently of log(w wbar), which on the slice w = wbar = -x is 2 ln x while
    log w + log wbar = 2 ln x + 2 pi i).  The exact statement of what the block is inside Phi^(3): f_3(x) is 3! times
    the finite part of (1-X) Phi^(3)(X,Y) as Y -> 0 at X = x/(1+x), organised in powers of ln((1-X)/Y), after the two
    polylog-inversion constants 31 pi^6/756 and (7 pi^4/180) ln^2 x are removed (the identity record cited in
    points.json, 93 digits at x = 1/3 and 2/9); it is not the coefficient of any single power of ln Y.
    What --identity x checks: (i) exact, 6 c_r == C3[r] for r = 0..3 with the served script's own C3; (ii) numeric,
    3! B(ln x; -x) built here from the exact c_r against the served f_3(x) imported from c5-ladder-evaluate.py (bar
    30 digits); (iii) at the three x values off every fit grid of the row (x = 1/3, 2/9, 7/9; the row's fits sampled
    x = k/1000, k = 10..710, and k/100, k = 3, 8, ..., 73), the closed form f_L(x) = L! sum_r c_r ln^r x Li_{2L-r}(-x)
    at L = 1, 2, 3, two ways (mpmath polylog, and the alternating series to a tail bound), against the shipped
    PREDICTIONS of the row's fit (the recognised exact coefficients of the weight-2L word basis, evaluated by nested
    sums; strings of 472/492 digits at dps 462/482, from the record): bar 461 digits at dps >= 462, the floor of the
    record (461.36 at x = 7/9, L = 1).  The shipped oracle strings of the record are compared string for string.

THE (X,Y) GATE (the --point tier and the default battery)
    route A   the closed form above, transcribed statement for statement from the evaluator of record; every value
              string is printed with dps+10 digits and every digit count is recomputed FROM THE STRINGS
              (-log10 |a-b|/|b| with b the reference; equal parses quote the working dps as a cap and say so);
    control   the one-fold integral representation of the same function (eq 2.2 with xi = e^{-t}),
              Phi^(L) = -1/(L!(L-1)!) int_0^inf dt e^{-t} (-t)^{L-1} (a-t)^{L-1} (a-2t) / (Y e^{-2t} + (1-X-Y) e^{-t} + X),
              a = log(Y/X), taken to the unit interval by t = s/(1-s), dt = ds/(1-s)^2, so that both endpoints are
              finite and the integrand is an ordinary function on [0, 1) (it vanishes like s^2 at s = 0 and like
              exp(-1/(1-s)) at s = 1; the integrand-call count and the number of nodes at s = 1 exactly, none for
              mpmath's tanh-sinh, are printed), integrated here by mpmath's quad (an independent representation
              computed live, not a certified quadrature: bar 30 digits, the record's own bar for this pair);
    reference the value of record at the shipped points: at P1, P2 the record's certified one-fold value (its
              double-refinement quadrature at dps 80, 90 printed digits, agreed with its closed form to 80.9 / 80.8
              digits), at PA, PB a 100-digit reference value from a separate two-representation computation;
              bar 60 digits at dps >= 60 (the count of record: the floor of the record's minimum over its two
              precisions and two routes at the two points not used in any fit, 61.03 / 60.69), dps-2 below;
              at PF = (2/3, 3/4) a Feynman-family value: the eps^0 coefficient of the top-sector integral of the
              nine-line off-shell ladder family (all three legs off shell) by auxiliary-mass flow, AMFlow solve_integrals
              at q = (-2/3, -3/4, -1), goal 60 (its goal-40 twin beside), every pole coefficient zero, normalised by
              q3^3 = -1 to Phi^(3); the closed form at dps 80 agrees with it to 72.49 digits, with the goal-40 twin to
              49.63, and the twins agree to 49.63: the count of record there is the pair floor 49.63, so the bar at PF
              is 49 (points.json: reference.bar; min(49, dps-2) below dps 60), never the 60 of the polylog references;
              the run prints the agreement with the twin and the pair of record beside the gate;
    --check   the two-precision pair (dps, dps+20) -- at dps 60 the record's own pair (60, 80) -- gated at the same bar;
    strings   at the dps of record (60, 80) the printed route-A string is compared string for string with the
              record's own (printed, not gated: a different mpmath build may differ in the last places).

THE lambda > 0 TIER (--lambda-positive [X,Y])
    the real-lambda form at the two gate points (X, Y) = (1/10, 1/10) [lambda = 3/5] and (3, 1/3) [lambda = 13/9] at
    dps 40 (--dps N otherwise) against (a) the live one-fold control of the (X,Y) gate above, which needs no
    continuation: with (x, y) = (max, min) its denominator y e^{-2t} + (1-x-y) e^{-t} + x has no zero on the path when
    lambda > 0 (bar 30 digits; the ordering is essential: at (1/3, 3) taken as written it vanishes twice on the path);
    (b) the values of record
    Phi^(3)(1/10, 1/10) = 183.3093184519... and Phi^(3)(3, 1/3) = Phi^(3)(1/3, 3) = 18.33352124370... (the dps-40 strings
    in LP_STRINGS below, 37 digits printed; bar 30); (c) at PA (inside the region) the real-lambda form in complex
    arithmetic against the z-form of route A (bar 30; |Im/Re| printed); (d) the L = 1 member Phi^(1)(3, 1/3) against
    a two-dimensional Feynman-parameter quadrature of the one-loop triangle with three off-shell Euclidean legs,
    T(A,B,C) = int dx dy / (x y A + y z B + z x C) over the simplex, z = 1-x-y, at (A,B,C) = (3, 1/3, 1) -- an object
    that shares nothing with the polylogarithms (dps 30, bar 20; the quadrature of record 2.097883279502...).  An extra
    X,Y with lambda > 0 given on the command line is evaluated the same way against the live one-fold control (no value
    of record there, said by name).  --plant-c4-flip flips the sign of the j = 4 term of the form: the gates of the
    tier must then FAIL by name (exit 1).  --check adds the pair (dps, dps+20) of the real-lambda value at each point.

USAGE
  python3 c5-ladder-xy-evaluate.py                           # the battery: PA, PB, P1, P2 at dps 60 and 80 (route A,
        # the live one-fold control, the references, the pairs), the block identity at x = 11/20, 7/25, 1/50 at dps
        # 60 and 80, and the three fit-independent x at dps 462 and 482 (L = 1, 2, 3) -- the record's whole gate
  python3 c5-ladder-xy-evaluate.py --point P2 --dps 60 --check      # one shipped point, the pair (60, 80)
  python3 c5-ladder-xy-evaluate.py --point 421/1225,596/1225        # = --point P1 (exact rationals X,Y)
  python3 c5-ladder-xy-evaluate.py --z 3/7+i*2/5                    # the same point given as exact z
  python3 c5-ladder-xy-evaluate.py --point 7/10,1/2 --dps 40        # any (X,Y) inside the region: the closed form vs
        # the live one-fold control only (no reference shipped there, said by name)
  python3 c5-ladder-xy-evaluate.py --point 2/3,3/4                  # = --point PF: the closed form vs the Feynman-family
        # value of record (auxiliary-mass flow, goal 60; bar = that reference's pair floor 49; the goal-40 twin beside)
  python3 c5-ladder-xy-evaluate.py --point 3,1/3                    # outside the z-form's region: REFUSED by name (exit 2), naming --lambda-positive
  python3 c5-ladder-xy-evaluate.py --lambda-positive                # the lambda > 0 tier: (1/10,1/10), (3,1/3), the PA cross-check, the L = 1 quadrature
  python3 c5-ladder-xy-evaluate.py --lambda-positive 5,1/7 --dps 60 # + one more lambda > 0 point (the real-lambda form vs the live one-fold control)
  python3 c5-ladder-xy-evaluate.py --lambda-positive --plant-c4-flip # control: the j = 4 term sign-flipped; the run must FAIL (exit 1)
  python3 c5-ladder-xy-evaluate.py --identity 1/3                   # the block identity at x = 1/3 (dps 462, L = 1..3)
  python3 c5-ladder-xy-evaluate.py --identity 11/20 --dps 60        # the block vs the served f_3 at a slice reference x
  python3 c5-ladder-xy-evaluate.py --mutate                         # control: every closed-form value scaled by
        # (1 + 1e-9) before the gates; the run must FAIL (exit 1)
  --out JSON writes the run receipt (values as full strings, every digit entry with the two strings it came from,
        gates, walls); it never overwrites an existing file.

EXIT CODES  0 PASS (every gate met) | 1 FAIL (a gate missed, named) | 2 usage or a point outside the region (refused
  by name; --dps < 15; an unknown point name) | 3 REFUSED (a pinned file's sha256 does not match: the recorded and the
  recomputed hashes and the first differing position are printed; nothing is computed) | 4 a pinned file, or mpmath,
  MISSING.

MEASURED WALLS: see the epilog of --help (GNU time wall clock, one process, nice 10, a shared 96-core host).
"""
import argparse
import hashlib
import importlib.util
import json
import os
import re
import subprocess
import sys
import time
from fractions import Fraction
from math import factorial

try:
    import mpmath as mp
except ImportError:
    print("c5-ladder-xy-evaluate MISSING: mpmath is not installed (pip install mpmath); nothing computed")
    sys.exit(4)

HERE = os.path.dirname(os.path.abspath(__file__))
VENDOR = os.path.join(HERE, "vendor_row04_xy")
POINTS_JSON = os.path.join(VENDOR, "points.json")
SERVED_SLICE = os.path.join(HERE, "c5-ladder-evaluate.py")
RC_FAIL, RC_USAGE, RC_REFUSED, RC_MISSING = 1, 2, 3, 4
L_DEFAULT = 3
BAR = 30.0                 # the record's bar for closed form vs one-fold and for the block identity
BAR_XY = 60                # the count of record at the two points not used in any fit (floor of 61.03 / 60.69)
BAR_RIDER = 461            # the floor of the record at the three fit-independent x (461.36 at x = 7/9, L = 1)
DPS_PAIR_GAP = 20          # the record's two-precision pair (60, 80); (462, 482) for the x values
GATE_X = ("11/20", "7/25", "1/50")   # the slice reference points of the served script (its printed literals)
RIDER_DPS = (462, 482)
GATE_DPS = (60, 80)

# --- PINS (script-emitted from the shipped bytes: the data file and the sibling served slice evaluator) ---
PINS = {
    "c5-ladder-evaluate.py": "2b05b821d431cd8996708c7739515ab739bfba42f6d5a344f92a041dc34e49ad",
    "vendor_row04_xy/points.json": "47d32582171d1d69d38bbc502f152292636918fb4d4b9370e224f474729c6efc",
}
# --- END PINS ---

# measured walls (GNU time, the delivered bytes; written by the build from its captures)
WALLS = {
    "default (the battery: PA, PB, P1, P2 at dps 60/80; the block identity at three x at dps 60/80; the three fit-independent x at dps 462/482)": "4.29 s",
    "--point P2 --dps 60 --check (the pair 60/80)": "0.35 s",
    "--point P1 --dps 60 --check": "0.52 s",
    "--identity 1/3 (dps 462, L = 1, 2, 3)": "0.31 s",
    "--identity 7/9 --check (the pair 462/482)": "3.84 s",
    "--point 7/10,1/2 --dps 40 (no reference shipped there)": "0.20 s",
    "--point PF (the auxiliary-mass-flow reference point; bar 49)": "0.20 s",
    "--mutate (the battery; must FAIL)": "4.33 s",
    "--lambda-positive (the two gate points at dps 40, the live one-fold control, the PA cross-check, the L = 1 quadrature at dps 30)": "5.67 s",
    "--lambda-positive --plant-c4-flip (must FAIL)": "7.01 s",
}

MUTATE = [False]


# ----------------------------------------------------------------------------- helpers (no mp constants at import)
def sha256_file(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def utc_stamp():
    return subprocess.run(["date", "-u", "+%Y-%m-%dT%H:%M:%SZ"], capture_output=True,
                          text=True, check=True).stdout.strip()


def load_module(name, path):
    if not os.path.isfile(path):
        raise FileNotFoundError(path)
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def fr2mp(f):
    """Exact Fraction -> mpf at the CURRENT working precision (call inside workdps/workprec)."""
    return mp.mpf(f.numerator) / mp.mpf(f.denominator)


def parse_rat(s):
    return Fraction(s.strip())


_Z_RE = re.compile(r"^\s*([+-]?\d+(?:/\d+)?)\s*([+-])\s*(?:i\s*\*?\s*(\d+(?:/\d+)?)|(\d+(?:/\d+)?)\s*\*?\s*i)\s*$")


def parse_z(s):
    m = _Z_RE.match(s)
    if not m:
        raise ValueError("--z must look like p/q+i*r/s (also p/q+i r/s, p/q+ir/s, p/q+r/s*i); got %r" % s)
    zr = Fraction(m.group(1))
    zi = Fraction(m.group(3) or m.group(4))
    if m.group(2) == "-":
        zi = -zi
    return zr, zi


def xy_of_z(zr, zi):
    return zr * zr + zi * zi, (1 - zr) * (1 - zr) + zi * zi


def mu2_exact(X, Y):
    return 4 * X * Y - (X + Y - 1) ** 2


def vstr(val, dps):
    """Value string of record: dps+10 digits (tools/nestor/oracle.py line 133 precedent)."""
    return mp.nstr(val, dps + 10, strip_zeros=False)


def ndigits(s):
    return sum(ch.isdigit() for ch in s.split("e")[0])


def digits_from_strings(sa, sb, path_a, path_b, cap):
    """The receipt's digit entry: digits recomputed from the two value STRINGS (never from live mpf objects), with
    the JSON paths of the strings so a reader reproduces the number from the receipt alone (recompute_digits.py)."""
    with mp.workdps(max(len(sa), len(sb)) + 10):
        a, b = mp.mpf(sa), mp.mpf(sb)
        eq = (a == b)
        d = None if eq else float(-mp.log10(abs((a - b) / b)))
    q = float(cap) if eq else d
    return dict(digits=round(q, 2), from_strings=[path_a, path_b], equal_parsed=eq,
                cap_at_working_dps=(cap if eq else None), n_digits_printed=[ndigits(sa), ndigits(sb)])


def f_coeffs(L):
    """c_r of eq (2.3), exact Fractions (transcribed from compute_phi.py line 29 / ladder_reference.py f_coeffs)."""
    return [Fraction((-1) ** r * factorial(2 * L - r), factorial(r) * factorial(L - r) * factorial(L))
            for r in range(L + 1)]


# ----------------------------------------------------------------------------- route A (the closed form of record)
def z_of_xy(X, Y):
    """z with Im z > 0 from exact (X,Y) inside the region; call inside workdps."""
    mu2 = mu2_exact(X, Y)
    assert mu2 > 0
    return mp.mpc((1 + fr2mp(X) - fr2mp(Y)) / 2, mp.sqrt(fr2mp(mu2)) / 2)


def phi_closed(L, z):
    """Route A: transcription of compute_phi.py phi_closed/f_L (lines 26-42): Phi = -f^(L)(w,wbar)/(z-zbar)."""
    zbar = mp.conj(z)
    w = z / (z - 1)
    wbar = zbar / (zbar - 1)
    ell = mp.log(w * wbar)
    s = mp.mpc(0)
    for r, c in enumerate(f_coeffs(L)):
        s += fr2mp(c) * ell ** r * (mp.polylog(2 * L - r, w) - mp.polylog(2 * L - r, wbar))
    return -s / (z - zbar)


# ----------------------------------------------------------------------------- the real-lambda form (Usyukina-Davydychev 1993; covers lambda > 0)
LP_POINTS = (("1/10", "1/10"), ("3", "1/3"))   # the two gate points of the --lambda-positive tier (lambda = 3/5 and 13/9)
LP_STRINGS = {                                 # Phi^(3) there at dps 40: the values of record (2026-09-11)
    "1/10,1/10": "183.3093184519275832844768905006741605",
    "3,1/3": "18.33352124370254176706930147063374904",
}
LP_L1 = ("3", "1/3", "2.09788327950223454980457")   # the L = 1 member Phi^(1)(3, 1/3): the triangle's Feynman-parameter quadrature of record (dps 30)
LP_DPS, LP_QUAD_DPS, LP_BAR_QUAD = 40, 30, 20
PLANT = [None]                                 # --plant-c4-flip sets 4: the j = 4 term of the real-lambda form sign-flipped (a control; the run must FAIL)


def phi_real_lambda(L, X, Y):
    """Phi^(L)(X,Y) = -(1/(L! lam)) sum_{j=L}^{2L} (-1)^j j! ln^(2L-j)(y/x) / ((j-L)! (2L-j)!) [Li_j(-1/(rho x)) - Li_j(-rho y)],
    lam = sqrt((1-x-y)^2 - 4xy), rho = 2/(1-x-y+lam), with (x, y) = (max, min)(X, Y) (Phi is symmetric): real for lambda > 0;
    inside the region (lambda < 0) the same expression in complex arithmetic.  X, Y exact Fractions; call inside workdps."""
    x, y = fr2mp(max(X, Y)), fr2mp(min(X, Y))
    lam2 = (1 - x - y) ** 2 - 4 * x * y
    lam = mp.sqrt(lam2) if lam2 > 0 else mp.sqrt(mp.mpc(lam2))
    rho = 2 / (1 - x - y + lam)
    lyx = mp.log(y / x)
    tot = 0
    for j in range(L, 2 * L + 1):
        c = mp.mpf((-1) ** j * factorial(j)) / (factorial(j - L) * factorial(2 * L - j))
        if PLANT[0] == j:
            c = -c
        tot += c * lyx ** (2 * L - j) * (mp.polylog(j, -1 / (rho * x)) - mp.polylog(j, -rho * y))
    return -tot / (factorial(L) * lam)


def triangle_feynman(A, B, C):
    """The one-loop triangle with three off-shell Euclidean legs as its two-dimensional Feynman-parameter integral,
    T(A,B,C) = int_{x,y>0, x+y<1} dx dy / (x y A + y z B + z x C), z = 1-x-y (= Phi^(1)(A/C, B/C) / C), by nested mp.quad."""
    return mp.quad(lambda s: mp.quad(lambda t: 1 / (s * t * A + t * (1 - s - t) * B + (1 - s - t) * s * C), [0, 1 - s]), [0, 1])


# ----------------------------------------------------------------------------- the one-fold control (eq 2.2, xi = e^{-t}; t = s/(1-s) on [0, 1])
def make_integrand(L, X, Y):
    cache = {}

    def consts():
        key = mp.mp.prec
        if key not in cache:
            u = fr2mp(X)
            v = fr2mp(Y)
            cache[key] = (u, v, mp.log(v / u))
        return cache[key]

    def integrand(t):
        u, v, a = consts()
        et = mp.exp(-t)
        num = et * (-t) ** (L - 1) * (a - t) ** (L - 1) * (a - 2 * t)
        den = v * et * et + (1 - u - v) * et + u
        return num / den
    return integrand


def make_integrand_s(L, X, Y):
    """The same integrand on the unit interval: g(s) = f(s/(1-s)) / (1-s)^2, s in [0, 1).  The counter records every
    call and every node at s = 1 exactly (the exact limit 0 is returned there; mpmath's tanh-sinh places no node at an
    endpoint, and the count is printed so a reader sees it)."""
    f = make_integrand(L, X, Y)
    count = {"calls": 0, "exact_endpoint": 0}

    def g(s):
        count["calls"] += 1
        oms = 1 - s
        if oms <= 0:
            count["exact_endpoint"] += 1
            return mp.mpf(0)
        return f(s / oms) / (oms * oms)
    return g, count


def fence(X, Y):
    mu2 = mu2_exact(X, Y)
    return mu2, (mu2 > 0 and X > 0 and Y > 0)


# ----------------------------------------------------------------------------- the slice closed form (the x values off the fit grids)
def c_r(L):
    """c_r = (-1)^r (2L-r)! / (r! (L-r)! L!), r = 0..L, exact."""
    return [Fraction((-1) ** r * factorial(2 * L - r), factorial(r) * factorial(L - r) * factorial(L)) for r in range(L + 1)]


def C_int(L):
    """C_r = L! c_r (integers)."""
    out = []
    for r, c in enumerate(c_r(L)):
        v = c * factorial(L)
        assert v.denominator == 1
        out.append(int(v))
    return out


def li_series(n, x, dps):
    """Li_n(-x) = sum_{k>=1} (-x)^k / k^n, x in (0,1); N from x^(N+1)/(N+1)^n < 10^-(dps+20). Returns (value, N, |last term|)."""
    target = mp.mpf(10) ** (-(dps + 20))
    N = 16
    while x ** (N + 1) / mp.mpf(N + 1) ** n >= target:
        N = int(N * 1.1) + 1
    s = mp.mpf(0)
    z = -x
    zk = mp.mpf(1)
    term = mp.mpf(0)
    for k in range(1, N + 1):
        zk *= z
        term = zk / mp.mpf(k) ** n
        s += term
    return s, N, abs(term)


def f_route_A(L, x, lnx):
    C = C_int(L)
    return sum(C[r] * lnx ** r * mp.polylog(2 * L - r, -x) for r in range(L + 1))


def f_route_S(L, x, lnx, dps):
    C = C_int(L)
    tot = mp.mpf(0)
    Ns, lasts = [], []
    for r in range(L + 1):
        v, N, lt = li_series(2 * L - r, x, dps)
        tot += C[r] * lnx ** r * v
        Ns.append(N)
        lasts.append(lt)
    return tot, Ns, lasts


# ----------------------------------------------------------------------------- front end
def die(rc, msg):
    print(msg, flush=True)
    sys.exit(rc)


def mutated(val):
    """the --mutate control: every closed-form value scaled by (1 + 1e-9) before the gates (the numeric units above
    are untouched)."""
    if MUTATE[0]:
        return val * (1 + mp.mpf(10) ** (-9))
    return val


def check_pins():
    for rel, want in PINS.items():
        p = os.path.join(HERE, rel)
        if not os.path.exists(p):
            die(RC_MISSING, f"c5-ladder-xy-evaluate MISSING: pinned file {rel} is absent (recorded sha256 {want}); download "
                            f"vendor_row04_xy/points.json and c5-ladder-evaluate.py from the same page beside this script; "
                            f"nothing computed")
        got = sha256_file(p)
        if got != want:
            pos = next(i + 1 for i in range(64) if got[i] != want[i])
            die(RC_REFUSED, f"c5-ladder-xy-evaluate REFUSED: {rel} integrity pin mismatch (recorded {want}, recomputed {got}; "
                            f"first differing hex position {pos} of 64, 1-based) -- the shipped file was altered; nothing computed")
    return len(PINS)


def bar_xy(dps):
    return BAR_XY if dps >= 60 else max(1, dps - 2)


def bar_rider(dps):
    return BAR_RIDER if dps >= RIDER_DPS[0] else max(1, dps - 2)


class Run:
    def __init__(self, out_path):
        self.gates = []
        self.rec = {"tool": "c5-ladder-xy-evaluate", "stamp_utc_start": utc_stamp(), "strings": {}, "digits": [], "legs": {}}
        self.out_path = out_path

    def gate(self, name, entry, bar, note=""):
        d = entry["digits"]
        ok = d >= bar
        self.gates.append({"gate": name, "digits": d, "bar": bar, "pass": ok, "equal_parsed": entry["equal_parsed"],
                           "from_strings": entry["from_strings"], "note": note})
        cap = " (equal parses; quoted at the working-dps cap)" if entry["equal_parsed"] else ""
        print(f"  [gate] {name}: {d:.2f} d vs bar >= {bar} -> {'PASS' if ok else 'FAIL'}{cap}{(' (' + note + ')') if note else ''}")
        return ok

    def info(self, name, entry):
        d = entry["digits"]
        self.rec["digits"].append({"name": name, "digits": d, "equal_parsed": entry["equal_parsed"], "from_strings": entry["from_strings"]})
        cap = " (equal parses; quoted at the working-dps cap)" if entry["equal_parsed"] else ""
        print(f"  [info] {name}: {d:.2f} d{cap}")

    def put(self, path, s):
        self.rec["strings"][path] = s
        return path


def route_A_str(L, X, Y, dps):
    with mp.workdps(dps):
        z = z_of_xy(X, Y)
        val = mutated(phi_closed(L, z))
        re_, im_ = mp.re(val), mp.im(val)
        im_rel = float(abs(im_) / abs(re_)) if re_ != 0 else float("nan")
        s = vstr(re_, dps)
    return s, im_rel


def onefold_str(L, X, Y, dps):
    with mp.workdps(dps):
        g, count = make_integrand_s(L, X, Y)
        I = mp.quad(g, [0, 1])
        val = -I / (factorial(L) * factorial(L - 1))
        s = vstr(val, dps)
    return s, count


def point_leg(run, tag, X, Y, dps, shipped, L=L_DEFAULT):
    """route A at dps + the live one-fold control at dps + (at a shipped point) the reference of record."""
    t0 = time.time()
    key = f"{tag}.dps{dps}"
    sA, im_rel = route_A_str(L, X, Y, dps)
    pA = run.put(f"{key}.A", sA)
    tA = time.time() - t0
    sQ, cnt = onefold_str(L, X, Y, dps)
    pQ = run.put(f"{key}.onefold", sQ)
    tQ = time.time() - t0 - tA
    print(f"[{tag}] dps {dps}  closed form (route A)      = {sA}   (|Im/Re| {im_rel:.1e}; {tA:.2f} s)")
    print(f"[{tag}] dps {dps}  one-fold control (mp.quad, t = s/(1-s) on [0, 1]) = {sQ}   ({tQ:.2f} s; {cnt['calls']} integrand calls, "
          f"{cnt['exact_endpoint']} at s = 1)")
    run.gate(f"{tag} dps {dps}: closed form vs the live one-fold control", digits_from_strings(sA, sQ, pA, pQ, dps), BAR)
    if shipped:
        ref = shipped["reference"]
        pR = run.put(f"{tag}.reference", ref["value_str"])
        bar, note = bar_xy(dps), ""
        if "bar" in ref:
            # a reference whose count of record is its own pair floor (PF: the auxiliary-mass-flow value, goal 60, vs its
            # goal-40 twin and the closed form at dps 80): the bar is that floor, never above the count of record
            bar = min(bar, ref["bar"])
            note = f"bar = min(the count of record {bar_xy(dps)}, the reference's pair floor int({ref['pair']['floor']}) = {ref['bar']})"
        run.gate(f"{tag} dps {dps}: closed form vs the reference of record ({ref['what_short']})",
                 digits_from_strings(sA, ref["value_str"], pA, pR, dps), bar, note=note)
        if "value_str_twin" in ref:
            pT = run.put(f"{tag}.reference_twin", ref["value_str_twin"])
            run.info(f"{tag} dps {dps}: closed form vs the reference's {ref['twin_short']}", digits_from_strings(sA, ref["value_str_twin"], pA, pT, dps))
            print(f"  [pair] the reference's pair of record: {ref['pair']['floor_prose']}; poles zero; {ref['pair']['identical_to_dps40']}")
        rs = shipped["record_strings"].get(f"A{dps}")
        if rs is not None:
            same = (rs == sA)
            print(f"  [record] the record's own dps-{dps} closed-form string: {'identical' if same else 'DIFFERENT'} "
                  f"(record digits at this point: pair {shipped['record_digits']['A60_vs_A80']}, closed form vs its one-fold at dps 80 "
                  f"{shipped['record_digits']['A80_vs_B80']})")
            run.rec["legs"].setdefault(key, {})["record_string_identical"] = same
    run.rec["legs"].setdefault(key, {}).update({"X": str(X), "Y": str(Y), "L": L, "A": sA, "onefold": sQ, "im_over_re": im_rel,
                                               "onefold_map": "t = s/(1-s) on [0, 1]", "onefold_integrand_calls": cnt["calls"],
                                               "onefold_nodes_at_s_equal_1": cnt["exact_endpoint"],
                                               "wall_s": round(time.time() - t0, 3)})
    return sA


def point_tier(run, tag, X, Y, dps, check, shipped):
    mu2 = mu2_exact(X, Y)
    label = f"{tag} = " if tag and not tag.startswith("(") else ""
    print(f"[point] {label}(X, Y) = ({X}, {Y}), 4XY-(X+Y-1)^2 = {mu2} > 0 (inside the region), dps {dps}"
          + (f" with --check (pair {dps}, {dps + DPS_PAIR_GAP})" if check else "") + (" [MUTATED control]" if MUTATE[0] else ""))
    if shipped:
        print(f"  [reference] {shipped['reference']['what']}")
    else:
        print(f"  [reference] NO value of record is shipped at (X, Y) = ({X}, {Y}): the closed form is checked against the live "
              f"one-fold control only (the shipped points: PA, PB, P1, P2, PF)")
    s1 = point_leg(run, tag, X, Y, dps, shipped)
    if check:
        d2 = dps + DPS_PAIR_GAP
        s2 = point_leg(run, tag, X, Y, d2, shipped)
        run.gate(f"{tag} two-precision pair ({dps}, {d2}) of the closed form",
                 digits_from_strings(s1, s2, f"{tag}.dps{dps}.A", f"{tag}.dps{d2}.A", dps), bar_xy(dps))
    return s1


def identity_tier(run, served, xs, dps, pts):
    """the block identity at x: exact 6 c_r == C3; 3! B(ln x; -x) vs the served f_3(x); at a fit-independent x the closed
    form f_L (two ways) vs the shipped predictions of the fit, L = 1, 2, 3."""
    cs = f_coeffs(3)
    C3 = list(served.C3)
    exact_ok = all(Fraction(6) * cs[r] == C3[r] for r in range(4))
    print(f"[identity] c_r = {[str(c) for c in cs]}; served C3 = {C3}; 6 c_r == C3 exactly: {exact_ok}")
    if not exact_ok:
        run.gates.append({"gate": "exact 6 c_r == C3", "digits": 0.0, "bar": 1, "pass": False, "equal_parsed": False, "from_strings": [], "note": ""})
        print("  [gate] exact 6 c_r == C3: FAIL")
    rider = pts["fit_independent_x"]
    for xs_ in xs:
        x_fr = Fraction(xs_)
        key = f"identity.x={xs_}.dps{dps}"
        t0 = time.time()
        with mp.workdps(dps):
            x = fr2mp(x_fr)
            lnx = mp.log(x)
            blk = mp.mpf(0)
            for r in range(4):
                blk += fr2mp(cs[r]) * lnx ** r * mp.polylog(6 - r, -x)
            blk *= 6
            blk = mutated(blk)
            f3 = served.f3(x)
            sB, sF = vstr(blk, dps), vstr(f3, dps)
        pB, pF = run.put(f"{key}.block", sB), run.put(f"{key}.served_f3", sF)
        print(f"[identity] x = {xs_}, dps {dps}: 3! B(ln x; -x) = {sB}")
        print(f"[identity] x = {xs_}, dps {dps}: served f_3(x)  = {sF}")
        run.gate(f"x = {xs_} dps {dps}: 3! B(ln x; -x) vs the served f_3(x)", digits_from_strings(sB, sF, pB, pF, dps), BAR)
        run.rec["legs"][key] = {"x": xs_, "dps": dps, "block": sB, "served_f3": sF}
        if xs_ in rider["per_x"]:
            rx = rider["per_x"][xs_]
            print(f"  [fit] x = {xs_} is one of the three x values off every fit grid of the row: the closed form f_L(x), L = 1, 2, 3, "
                  f"two ways, vs the shipped predictions of the fit (bar {bar_rider(dps)})")
            with mp.workdps(dps):
                for L in (1, 2, 3):
                    vA = mutated(f_route_A(L, x, lnx))
                    vS, Ns, lasts = f_route_S(L, x, lnx, dps)
                    vS = mutated(vS)
                    sA = mp.nstr(vA, dps + 10, strip_zeros=False)
                    sS = mp.nstr(vS, dps + 10, strip_zeros=False)
                    pA, pS = run.put(f"{key}.L{L}.oracle_A", sA), run.put(f"{key}.L{L}.oracle_S", sS)
                    rec = rx[str(L)]
                    print(f"  L = {L}: f_{L}({xs_}) polylog = {sA[:48]}... series (N = {Ns}) = {sS[:48]}...")
                    run.gate(f"x = {xs_} L = {L} dps {dps}: polylog vs series", digits_from_strings(sA, sS, pA, pS, dps), BAR)
                    ds = str(dps)
                    if ds in rec["prediction_word"]:
                        pW = run.put(f"{key}.L{L}.prediction_word", rec["prediction_word"][ds])
                        pP = run.put(f"{key}.L{L}.prediction_polylog", rec["prediction_polylog"][ds])
                        run.gate(f"x = {xs_} L = {L} dps {dps}: the fit's prediction (word basis) vs the closed form",
                                 digits_from_strings(rec["prediction_word"][ds], sA, pW, pA, dps), bar_rider(dps),
                                 note=f"record {rec['record_digits']['prediction_word_vs_oracle_A'][ds]} d")
                        run.info(f"x = {xs_} L = {L} dps {dps}: the fit's prediction (polylog basis) vs the closed form",
                                 digits_from_strings(rec["prediction_polylog"][ds], sA, pP, pA, dps))
                        same = (rec["oracle_A"][ds] == sA, rec["oracle_S"][ds] == sS)
                        print(f"  [record] x = {xs_} L = {L} dps {dps}: the record's own strings: polylog {'identical' if same[0] else 'DIFFERENT'}, "
                              f"series {'identical' if same[1] else 'DIFFERENT'}")
                        run.rec["legs"][key][f"L{L}_record_strings_identical"] = same
                    else:
                        # a dps other than the record's: the prediction strings of the deeper record precision serve as the reference
                        dref = max(rec["prediction_word"], key=int)
                        pW = run.put(f"{key}.L{L}.prediction_word_dps{dref}", rec["prediction_word"][dref])
                        run.gate(f"x = {xs_} L = {L} dps {dps}: the fit's prediction (word basis, record dps {dref}) vs the closed form",
                                 digits_from_strings(rec["prediction_word"][dref], sA, pW, pA, dps), bar_rider(dps))
                    run.rec["legs"][key][f"L{L}"] = {"oracle_A": sA, "oracle_S": sS, "series_N": Ns}
        run.rec["legs"][key]["wall_s"] = round(time.time() - t0, 3)


def real_lambda_str(L, X, Y, dps):
    with mp.workdps(dps):
        val = mutated(phi_real_lambda(L, X, Y))
        re_, im_ = (mp.re(val), mp.im(val)) if isinstance(val, mp.mpc) else (val, mp.mpf(0))
        im_rel = float(abs(im_) / abs(re_)) if re_ != 0 else float("nan")
        s = vstr(re_, dps)
    return s, im_rel


def lambda_positive_tier(run, dps, check, extra, pts):
    """The --lambda-positive tier: the real-lambda form at the two gate points (and an extra point) against the live one-fold
    control with (max, min) ordering and the values of record; the PA cross-check against the z-form; the L = 1 quadrature."""
    todo = [(Fraction(a), Fraction(b), True) for a, b in LP_POINTS] + ([(extra[0], extra[1], False)] if extra else [])
    for X, Y, gate_pt in todo:
        lam = -mu2_exact(X, Y)
        tag = f"({X},{Y})"
        print(f"[lambda-positive] (X, Y) = ({X}, {Y}), lambda = (X+Y-1)^2 - 4XY = {lam} > 0, dps {dps}"
              + (f" with --check (pair {dps}, {dps + DPS_PAIR_GAP})" if check else "") + (" [PLANTED c_4 flip]" if PLANT[0] else "") + (" [MUTATED control]" if MUTATE[0] else ""))
        for d in ((dps, dps + DPS_PAIR_GAP) if check else (dps,)):
            key = f"lp.{tag}.dps{d}"
            t0 = time.time()
            sR, im_rel = real_lambda_str(L_DEFAULT, X, Y, d)
            pR = run.put(f"{key}.real_lambda", sR)
            tR = time.time() - t0
            sQ, cnt = onefold_str(L_DEFAULT, max(X, Y), min(X, Y), d)
            pQ = run.put(f"{key}.onefold", sQ)
            print(f"  dps {d}  real-lambda form                                       = {sR}   (|Im/Re| {im_rel:.1e}; {tR:.2f} s)")
            print(f"  dps {d}  one-fold control ((x, y) = (max, min); t = s/(1-s) on [0, 1]) = {sQ}   ({time.time() - t0 - tR:.2f} s; {cnt['calls']} integrand calls, {cnt['exact_endpoint']} at s = 1)")
            run.gate(f"{tag} dps {d}: the real-lambda form vs the live one-fold control", digits_from_strings(sR, sQ, pR, pQ, d), BAR)
            if gate_pt:
                ref = LP_STRINGS[f"{X},{Y}"]
                pS = run.put(f"lp.{tag}.record", ref)
                run.gate(f"{tag} dps {d}: the real-lambda form vs the value of record (the dps-{LP_DPS} string)", digits_from_strings(sR, ref, pR, pS, min(d, LP_DPS)), BAR)
            elif d == dps:
                print(f"  [reference] NO value of record is shipped at (X, Y) = ({X}, {Y}): the real-lambda form is checked against the live one-fold control only")
            run.rec["legs"][key] = {"X": str(X), "Y": str(Y), "L": L_DEFAULT, "lambda": str(lam), "real_lambda": sR, "onefold": sQ, "im_over_re": im_rel,
                                    "onefold_ordering": "(max, min)", "onefold_integrand_calls": cnt["calls"], "wall_s": round(time.time() - t0, 3)}
        if check:
            a, b = run.rec["strings"][f"lp.{tag}.dps{dps}.real_lambda"], run.rec["strings"][f"lp.{tag}.dps{dps + DPS_PAIR_GAP}.real_lambda"]
            run.gate(f"{tag} two-precision pair ({dps}, {dps + DPS_PAIR_GAP}) of the real-lambda form",
                     digits_from_strings(a, b, f"lp.{tag}.dps{dps}.real_lambda", f"lp.{tag}.dps{dps + DPS_PAIR_GAP}.real_lambda", dps), BAR)
    X1, Y1 = Fraction(LP_POINTS[1][0]), Fraction(LP_POINTS[1][1])
    sXY, sYX = run.rec["strings"][f"lp.({X1},{Y1}).dps{dps}.real_lambda"], real_lambda_str(L_DEFAULT, Y1, X1, dps)[0]
    print(f"[symmetry] Phi^(3)({Y1}, {X1}) vs Phi^(3)({X1}, {Y1}): {'identical strings' if sXY == sYX else 'DIFFERENT'} (the form orders its arguments (max, min))")
    pa = pts["points"]["PA"]
    XA, YA = Fraction(pa["X"]), Fraction(pa["Y"])
    sA, _ = route_A_str(L_DEFAULT, XA, YA, dps)
    sR, im_rel = real_lambda_str(L_DEFAULT, XA, YA, dps)
    pA, pR = run.put(f"lp.PA.dps{dps}.A", sA), run.put(f"lp.PA.dps{dps}.real_lambda", sR)
    print(f"[PA] (X, Y) = ({XA}, {YA}) inside the region, dps {dps}: the z-form (route A)          = {sA}")
    print(f"[PA] the real-lambda form in complex arithmetic                          = {sR}   (|Im/Re| {im_rel:.1e})")
    run.gate(f"PA dps {dps}: the real-lambda form vs the z-form of record (route A)", digits_from_strings(sR, sA, pR, pA, dps), BAR)
    A_, B_ = Fraction(LP_L1[0]), Fraction(LP_L1[1])
    t0 = time.time()
    with mp.workdps(LP_QUAD_DPS):
        T = triangle_feynman(fr2mp(A_), fr2mp(B_), mp.mpf(1))
        ph = mutated(phi_real_lambda(1, A_, B_))
        sT, sP = vstr(T, LP_QUAD_DPS), vstr(ph, LP_QUAD_DPS)
    pT, pP, pRec = run.put("lp.L1.quadrature", sT), run.put("lp.L1.real_lambda", sP), run.put("lp.L1.record", LP_L1[2])
    print(f"[L = 1] Phi^(1)({A_}, {B_}) by the real-lambda form = {sP}; the triangle's two-dimensional Feynman-parameter quadrature "
          f"T({A_}, {B_}, 1) = {sT} ({time.time() - t0:.2f} s, dps {LP_QUAD_DPS}); the quadrature of record {LP_L1[2]}")
    run.gate(f"L = 1 dps {LP_QUAD_DPS}: the real-lambda form vs the live Feynman-parameter quadrature", digits_from_strings(sP, sT, pP, pT, LP_QUAD_DPS), LP_BAR_QUAD)
    run.info("L = 1: the live quadrature vs the quadrature of record", digits_from_strings(sT, LP_L1[2], pT, pRec, LP_QUAD_DPS))


def shipped_point(pts, tag):
    p = pts["points"][tag]
    return {"reference": p["reference"], "record_strings": p["record_strings"], "record_digits": p["record_digits"]}


def main():
    ap = argparse.ArgumentParser(
        description="Phi^(3)(X,Y), the three-loop C5 ladder in both mass ratios: the closed form inside its region against a live one-fold "
                    "control and the values of record, and the block identity to the served f_3(x).",
        epilog="measured walls (GNU time wall clock, one process, nice 10, a shared 96-core host): "
               + "; ".join(f"{k}: {v}" for k, v in WALLS.items()) + ".  Exit codes: 0 PASS, 1 FAIL, 2 usage / outside the region, "
               "3 REFUSED by a pin, 4 MISSING.")
    ap.add_argument("--point", metavar="P|X,Y", help="PA, PB, P1, P2, PF or exact rationals X,Y (e.g. 421/1225,596/1225)")
    ap.add_argument("--z", metavar="p/q+i*r/s", help="the point as exact z; (X, Y) = (|z|^2, |1-z|^2)")
    ap.add_argument("--identity", metavar="x", action="append", default=[], help="the block identity at x > 0 (repeatable); x = 1/3, 2/9, 7/9 are the fit-independent values of record")
    ap.add_argument("--dps", type=int, default=None, help="working precision (default 60; 462 for --identity at a fit-independent x)")
    ap.add_argument("--check", action="store_true", help=f"two-precision rule: the pair (dps, dps+{DPS_PAIR_GAP}) gated too")
    ap.add_argument("--mutate", action="store_true", help="control: every closed-form value scaled by (1 + 1e-9) before the gates; the run must exit nonzero")
    ap.add_argument("--lambda-positive", nargs="?", const="", default=None, metavar="X,Y",
                    help="the lambda > 0 tier: the Usyukina-Davydychev real-lambda form at (1/10,1/10) and (3,1/3) (+ an optional X,Y with lambda > 0) against the live one-fold control and the values of record, the PA cross-check against the z-form, the L = 1 quadrature")
    ap.add_argument("--plant-c4-flip", action="store_true", help="control for --lambda-positive: the j = 4 term of the real-lambda form sign-flipped; the run must exit nonzero")
    ap.add_argument("--out", default=None, metavar="JSON", help="write the run receipt here (never overwrites)")
    args = ap.parse_args()
    try:
        sys.stdout.reconfigure(line_buffering=True)
    except AttributeError:
        pass
    if args.out and os.path.exists(args.out):
        ap.error(f"--out {args.out} exists; receipts are never overwritten")
    if args.point and args.z:
        ap.error("give --point or --z, not both")
    t_all = time.time()
    MUTATE[0] = bool(args.mutate)
    if args.plant_c4_flip and args.lambda_positive is None:
        die(RC_USAGE, "c5-ladder-xy-evaluate REFUSED (usage): --plant-c4-flip belongs to the --lambda-positive tier")
    if args.lambda_positive is not None and (args.point or args.z or args.identity):
        die(RC_USAGE, "c5-ladder-xy-evaluate REFUSED (usage): --lambda-positive does not combine with --point, --z or --identity")
    PLANT[0] = 4 if args.plant_c4_flip else None
    npins = check_pins()
    pts = json.load(open(POINTS_JSON))
    served = load_module("c5_ladder_evaluate_served", SERVED_SLICE)
    print(f"[pins] {npins} shipped files verified by sha256 (vendor_row04_xy/points.json; the sibling c5-ladder-evaluate.py)")
    run = Run(args.out)
    run.rec["args"] = vars(args)
    mode = "battery"
    if args.lambda_positive is not None:
        mode = "lambda-positive"
    elif args.point or args.z:
        mode = "point"
    elif args.identity:
        mode = "identity"
    dps = args.dps
    if mode in ("battery",) and dps is not None:
        ap.error("the default battery runs at the precisions of record (60/80 and 462/482); give --point or --identity with --dps")
    # ---------------------------------------------------------------- point
    if mode == "point":
        dps = 60 if dps is None else dps
        if dps < 15:
            die(RC_USAGE, "c5-ladder-xy-evaluate REFUSED (usage): --dps must be >= 15")
        tag = None
        if args.z:
            try:
                zr, zi = parse_z(args.z)
            except ValueError as e:
                die(RC_USAGE, f"c5-ladder-xy-evaluate REFUSED (usage): {e}")
            X, Y = xy_of_z(zr, zi)
        elif args.point in pts["points"]:
            tag = args.point
            X, Y = Fraction(pts["points"][tag]["X"]), Fraction(pts["points"][tag]["Y"])
        elif args.point.upper().startswith("P") and args.point[1:].isalnum() and "," not in args.point:
            die(RC_USAGE, f"c5-ladder-xy-evaluate REFUSED (usage): unknown point name '{args.point}': the shipped points are "
                          f"{', '.join(pts['points'])} (or give X,Y as exact rationals)")
        else:
            try:
                xs_, ys_ = args.point.split(",")
                X, Y = parse_rat(xs_), parse_rat(ys_)
            except Exception as e:
                die(RC_USAGE, f"c5-ladder-xy-evaluate REFUSED (usage): --point must be X,Y exact rationals or a point name: {e}")
        if tag is None:
            tag = next((k for k, p in pts["points"].items() if Fraction(p["X"]) == X and Fraction(p["Y"]) == Y), None)
        mu2, ok = fence(X, Y)
        if not ok:
            die(RC_USAGE, f"c5-ladder-xy-evaluate REFUSED: (X, Y) = ({X}, {Y}) lies outside the region X > 0, Y > 0, 4XY > (X+Y-1)^2 "
                          f"(4XY-(X+Y-1)^2 = {mu2}): there z is real and the z-form of --point is a 0/0 limit; X, Y > 0 with "
                          f"lambda = (X+Y-1)^2 - 4XY > 0 is evaluated by the real-lambda form of the --lambda-positive tier "
                          f"(python3 c5-ladder-xy-evaluate.py --lambda-positive {X},{Y}); nothing computed here")
        shipped = shipped_point(pts, tag) if tag else None
        point_tier(run, tag or f"({X},{Y})", X, Y, dps, args.check, shipped)
    # ---------------------------------------------------------------- identity
    elif mode == "identity":
        xs = []
        for s in args.identity:
            try:
                xf = Fraction(s)
            except (ValueError, ZeroDivisionError):
                die(RC_USAGE, f"c5-ladder-xy-evaluate REFUSED (usage): --identity takes x > 0 as an exact rational (got '{s}')")
            if xf <= 0:
                die(RC_USAGE, f"c5-ladder-xy-evaluate REFUSED (usage): --identity needs x > 0 (the slice's documented domain; got {xf})")
            xs.append(str(xf))
        rider = any(x in pts["fit_independent_x"]["per_x"] for x in xs)
        dps = (RIDER_DPS[0] if rider else 60) if dps is None else dps
        if dps < 15:
            die(RC_USAGE, "c5-ladder-xy-evaluate REFUSED (usage): --dps must be >= 15")
        print(f"[identity] the holomorphic-block identity at x = {', '.join(xs)}, dps {dps}"
              + (f" with --check (pair {dps}, {dps + DPS_PAIR_GAP})" if args.check else "") + (" [MUTATED control]" if MUTATE[0] else ""))
        identity_tier(run, served, xs, dps, pts)
        if args.check:
            identity_tier(run, served, xs, dps + DPS_PAIR_GAP, pts)
            for x in xs:
                a, b = run.rec["strings"][f"identity.x={x}.dps{dps}.block"], run.rec["strings"][f"identity.x={x}.dps{dps + DPS_PAIR_GAP}.block"]
                run.gate(f"x = {x} two-precision pair ({dps}, {dps + DPS_PAIR_GAP}) of the block",
                         digits_from_strings(a, b, f"identity.x={x}.dps{dps}.block", f"identity.x={x}.dps{dps + DPS_PAIR_GAP}.block", dps),
                         BAR if x not in pts["fit_independent_x"]["per_x"] else bar_rider(dps))
    # ---------------------------------------------------------------- the lambda > 0 tier
    elif mode == "lambda-positive":
        dps = LP_DPS if dps is None else dps
        if dps < 15:
            die(RC_USAGE, "c5-ladder-xy-evaluate REFUSED (usage): --dps must be >= 15")
        extra = None
        if args.lambda_positive:
            try:
                xs_, ys_ = args.lambda_positive.split(",")
                extra = (parse_rat(xs_), parse_rat(ys_))
            except Exception as e:
                die(RC_USAGE, f"c5-ladder-xy-evaluate REFUSED (usage): --lambda-positive takes X,Y as exact rationals: {e}")
            lam = -mu2_exact(*extra)
            if not (extra[0] > 0 and extra[1] > 0 and lam > 0):
                die(RC_USAGE, f"c5-ladder-xy-evaluate REFUSED: --lambda-positive takes X, Y > 0 with lambda = (X+Y-1)^2 - 4XY > 0 "
                              f"(got ({extra[0]}, {extra[1]}), lambda = {lam}); a point inside the region belongs to --point; nothing computed")
        print(f"[lambda-positive] the Usyukina-Davydychev real-lambda form at X, Y > 0 with lambda > 0: the gate points "
              + ", ".join("(%s, %s)" % p for p in LP_POINTS) + (f" and the extra point ({extra[0]}, {extra[1]})" if extra else "")
              + f", dps {dps}; the PA cross-check; the L = 1 quadrature" + (" [PLANTED c_4 flip]" if PLANT[0] else "") + (" [MUTATED control]" if MUTATE[0] else ""))
        lambda_positive_tier(run, dps, args.check, extra, pts)
    # ---------------------------------------------------------------- the battery (the record's whole gate)
    else:
        print(f"[battery] the record's gate: PA, PB, P1, P2 at dps {GATE_DPS[0]} and {GATE_DPS[1]}; the block identity at x = "
              f"{', '.join(GATE_X)}; the three fit-independent x at dps {RIDER_DPS[0]} and {RIDER_DPS[1]}" + (" [MUTATED control]" if MUTATE[0] else ""))
        strings = {}
        for tag in ("PA", "PB", "P1", "P2"):
            p = pts["points"][tag]
            X, Y = Fraction(p["X"]), Fraction(p["Y"])
            shipped = shipped_point(pts, tag)
            print(f"[point] {tag}: (X, Y) = ({X}, {Y}); {p['role']}")
            print(f"  [reference] {shipped['reference']['what']}")
            for d in GATE_DPS:
                strings[(tag, d)] = point_leg(run, tag, X, Y, d, shipped)
            run.gate(f"{tag} two-precision pair ({GATE_DPS[0]}, {GATE_DPS[1]}) of the closed form",
                     digits_from_strings(strings[(tag, GATE_DPS[0])], strings[(tag, GATE_DPS[1])], f"{tag}.dps{GATE_DPS[0]}.A", f"{tag}.dps{GATE_DPS[1]}.A", GATE_DPS[0]),
                     bar_xy(GATE_DPS[0]))
        for d in GATE_DPS:
            identity_tier(run, served, list(GATE_X), d, pts)
        xs = list(pts["fit_independent_x"]["x"])
        for d in RIDER_DPS:
            identity_tier(run, served, xs, d, pts)
        for x in xs:
            a, b = run.rec["strings"][f"identity.x={x}.dps{RIDER_DPS[0]}.block"], run.rec["strings"][f"identity.x={x}.dps{RIDER_DPS[1]}.block"]
            run.gate(f"x = {x} two-precision pair ({RIDER_DPS[0]}, {RIDER_DPS[1]}) of the block",
                     digits_from_strings(a, b, f"identity.x={x}.dps{RIDER_DPS[0]}.block", f"identity.x={x}.dps{RIDER_DPS[1]}.block", RIDER_DPS[0]), bar_rider(RIDER_DPS[0]))
    # ---------------------------------------------------------------- verdict
    ok = all(g["pass"] for g in run.gates)
    wall = round(time.time() - t_all, 2)
    worst = min(run.gates, key=lambda g: g["digits"] - g["bar"]) if run.gates else None
    n_ok = sum(1 for g in run.gates if g["pass"])
    print(f"\nVERDICT {'PASS' if ok else 'FAIL'}: {n_ok} of {len(run.gates)} gates met"
          + (f"; the thinnest margin: {worst['gate']} at {worst['digits']:.2f} d vs bar {worst['bar']}" if worst else "")
          + f"; total wall {wall} s" + ("; MUTATED control -- a FAIL here is the expected outcome" if MUTATE[0] else "")
          + ("; PLANTED c_4 flip -- a FAIL here is the expected outcome" if PLANT[0] else ""))
    if not ok:
        for g in run.gates:
            if not g["pass"]:
                print(f"  FAILED: {g['gate']}: {g['digits']:.2f} d < {g['bar']}")
    run.rec.update({"mode": mode, "verdict": "PASS" if ok else "FAIL", "gates": run.gates, "wall_s": wall, "stamp_utc_end": utc_stamp(),
                    "digits_rule": "every digits entry: -log10 |a-b|/|b| with a, b parsed from the two strings at from_strings inside "
                                   "mp.workdps(max(len(a_str), len(b_str)) + 10); equal parses are quoted as the working dps with equal_parsed true; "
                                   "value strings are mp.nstr(val, dps + 10, strip_zeros=False)",
                    "PRODUCER": {"script": os.path.basename(__file__), "script_sha256": sha256_file(os.path.abspath(__file__)), "pins": PINS,
                                 "pins_verified": npins, "python": sys.version.split()[0], "mpmath": mp.__version__, "mpmath_backend": mp.libmp.BACKEND,
                                 "stamp_source": "date -u", "mutated": MUTATE[0], "planted_c4_flip": bool(PLANT[0])}})
    if args.out:
        with open(args.out, "x") as fh:
            json.dump(run.rec, fh, indent=1)
        print(f"receipt -> {args.out}")
    return 0 if ok else RC_FAIL


if __name__ == "__main__":
    sys.exit(main())
