shiftsum.py

Checks: COORDINATES: The shifted checksum criterion; COORDINATES: The best shifted moduli rule; COORDINATES: The parity variant's reach rule; pattern; observation.

Cited on: COORDINATES.

To run it: save shiftsum.py; needs numpy, sympy.

"""shiftsum.py — how long a message a shifted modular checksum protects
against every error of one or two bits: a length proved clean, closed
in the order of 2 up to sign, with the criterion for the next bit; the
modulus of longest reach at 8, 16, 32 and 64 bits; and the check value
itself.

USE. In Python, with numpy and sympy installed, from the folder holding
shiftsum.py. The checksum sends, beside the data read as one integer X
(the first byte highest), the k-bit check X 2^k mod M, M <= 2^k.
best_modulus gives the modulus of longest reach at 8, 16, 32 or 64
bits, with that reach in bits; reach, for a modulus of your own, the
length through which every error of one or two bits is caught and the
first length at which one is missed, in bits or in blocks of the size
you name; checksum, the check of your bytes:

    >>> from shiftsum import best_modulus, reach, checksum
    >>> best_modulus(16)
    (65519, 32743)
    >>> reach(65519, 16, block=8)              # bytes: caught through, missed at
    (4092, 4093)
    >>> reach(65521, 16, block=8)              # the largest 16-bit prime
    (71, 72)
    >>> data = bytearray(4093)                 # one byte past the reach
    >>> checksum(data, 65519, 16)
    0
    >>> data[0] ^= 0x80                        # one data bit flipped
    >>> checksum(data, 65519, 16)              # one check bit away: missed
    1
    >>> best_modulus(32)
    (4294967291, 2147483613)
    >>> reach(65536, 16) is None               # a power of two: refused
    True

reach's second value is None where the criterion below leaves the next
bit clean: the first failing length is then not read. Every call
returns None outside the law's setting, M a power of two or past 2^k,
and at a width past 64 bits, where no order is read; reach also at a
negative L*, where the law says nothing, and best_modulus at any width
but its four.

QUESTION. Is a shifted modular checksum's HD = 3 length the order of 2?
arXiv:2304.13496 (Figure 1, Appendix A) computes a k-bit check
value of a data word of L bits by sum = ((sum << b) + block) mod M over
b-bit blocks, then k appended zero bits, sum = (sum << k) mod M: the
check is C = (X * 2^k) mod M, X the data word as one integer, and the
receiver recomputes C from the received data and compares. The paper
screens every modulus to 16 bits by fault trial (HD = 3 to 13 bytes at
239, 4092 at 65519) and cannot confirm its 32-bit one. Is the HD = 3
length a closed form in M?

THE LAW (derived by hand before any code; the criterion after the
first run). Write M = 2^a m', m' odd,
a <= k, and D(m') the least d >= 1 with 2^d = +-1 mod m'. Then for
m' > 1 the code detects every error of one or two bits when

    L <= L*(M) := D(m') - k + a,

and at L* >= 0, L* + 1 fails exactly when s = 2^D mod m' is +1 or some
y < 2^(L*) has y 2^(k-a) mod m' odd (the criterion); 2^(L*) >= m' (H)
gives such a y, and so does y = 1 at M > 2^(k-1), L* >= 1. A data pair
i < j is missed only if m' | 2^(j-i) +- 1, so only at j - i >= D (the
data-pair half); a data flip at i with a check flip at j, the mixed
case, only if +-2^j = +-2^(i+k) mod M (the cross term), a congruence
that is necessary, its range apart. So no error is
missed at L <= L* (the proved half); the one pair L* + 1 can miss is a
flip of data bit
L* with a flip of check bit a, C = 2^a c', c' = X 2^(k-a) mod m', and
every longer word holds that pair; at s = +1 the word X = 0 misses it,
its check going 0 -> 2^a, and at s = -1 a word of c' = 1 with data bit
L* at 0, where (H) supplies one. The
criterion, found after the first run: with e1 = +1 when data bit L* goes
0 -> 1 and e2 = +1 when bit 0 of c' does, the recomputed check is 2^a
((c' + e1 s) mod m') and the received one 2^a (c' + e2), equal iff e2 =
e1 s and c' + e2 lies in [0, m'): so L* + 1 fails iff some X < 2^(L*+1)
has c' even, c' <= m' - 2 at e2 = +1, or c' odd at e2 = -1. At s = +1, X
= 0 serves; at s = -1, X = 2^(L*) + y has c' = c'(y) - 1 mod m', and
both branches ask c'(y) odd. At M > 2^(k-1), m' > 2^(k-a-1), so 2^(k-a)
mod m' = 2^(k-a) - m', odd: y = 1 serves once L* >= 1. At m' = 1 the
check is 0 and no data error is seen. TRANSPLANT, to re-derive: none;
the range condition the law first leaned on is (H), which tiny widths
break, so the exhaustive arm reads the boundary there with no (H).

By hand, the paper's moduli (D in bits, L* in bits, then bytes
floor(L*/8)): 239 = prime, 2 of order 119 (239 = 7 mod 8, odd order), D
119, L* 111, 13 bytes (paper: 13); 253 = 11 * 23, -1 not a power mod 23,
D = lcm(10, 11) = 110, L* 102, 12 bytes (paper: rollover 13 bytes, HD = 3
to 12); 65519, 2 of order 32759, D 32759, L* 32743,
4092 bytes (paper: 4092, HD = 2 from 4094, silent at 4093, which the law
fails; 32759 = 17 * 41 * 47 is not prime, the order 32759 read by the
engine); 4294967291 = 2^32 - 5 = 3 mod 8, if 2 is a primitive root D =
2147483645, L* 2147483613, 268,435,451 bytes (paper: 134,217,720).

D(m) <= phi(m)/2 <= (m - 1)/2 at every odd m > 1: an odd order divides
lambda/2; an even one at a prime power has 2^(ord/2) = -1, the cyclic
group's one involution; at two or more distinct primes lambda <= phi/2.
Equality only at a prime p whose D is (p - 1)/2. So the best k-bit M
is found by reading D at every M <= 2^k at 8 and 16 bits, and at 32
and 64 by the largest prime p <= 2^k with D = (p - 1)/2 beside every m in
(p, 2^k], each bounded by phi(m)/2 or read.

PREDICTIONS, frozen before any engine.
  P1 LAW: Figure 1's kernel, coded as printed, broken exhaustively (every
     data word, every one- and two-bit error over data and check) at
     k = 2..7, every M in 2..2^k, block sizes b = 1 and b = k, at every
     L read up to L* + 1 where 2^(L+k) fits the arm's cap: the largest
     clean L equals L* at every (k, M, b) where (H) holds; where (H)
     fails, printed apart, the brute value read as it falls.
  P2 the paper's own prints, as the law's positive control: 13 bytes at
     239, 12 at 253, 4092 at 65519.
  P3 TABLE: at 32 bits 4294967291, D 2147483645; at 64 bits the largest
     prime below 2^64 with D = (p - 1)/2, printed with its D.

THE KILL, as the script will print it (frozen at filing):
    ORDER: best 8-bit M ..., ... bits; best 16-bit M ..., ... bits
  the conjecture dies at anything but 239, 119 and 65519, 32759 (a tie
  at the top printed as a list counts as anything else); and the law
  dies at any (k, M, b) of P1 with (H) where brute and law differ.

CONTROLS, read before any verdict.
  C1 by hand: M = 7, k = 3, L = 1. D(7) = 3 (2^3 = 8 = 1), L* = 0: data
     0, C = 0; flipping the data bit (C must become 8 mod 7 = 1) and
     check bit 0 (C' = 1) is missed. The brute arm must name that pair.
  C2 a planted break: the kernel with its appended zeros dropped (C = X
     mod M, the paper's own vulnerability). Pushed toward misses: the
     brute arm must disagree with the law at a nonzero count of (k, M).
  C3 D(m) by its definition, a power loop, against the order engine at
     every odd m < 2^12.

FINDINGS (the run's lines copied; the row splits first counted by hand
over sweep(), now printed under the LAW line).
  Changes to what was frozen: the k = 8 arm added (b = 8 alone, data
  words to 16 bits); the cap bounds L, not L + k; at b = k the law is
  compared to the first failing block, L* read to the block.
  C3 2047 odd m read, 0 off; C1 missed, first witness (0, 9), the hand
  pair; C2 the plant off the law at 6 of the 6 rows read with (H).
  LAW: with (H), brute = law at 94 of 94 rows read (165 past the caps
  of 14 bits, 16 at k = 8); without (H), 451 of 488 read agree. The 94
  lie at k = 5..8 (none at k = 2..4 has (H)), (k, b) = (5, 1) 3, (5, 5)
  3, (6, 1) 9, (6, 6) 8, (7, 1) 17, (7, 7) 17, (8, 8) 37, of 259 rows
  with (H): moduli of small D, none of the paper's. At the other 37 the
  brute arm fails later than the law, never earlier, as the proved half
  says: one block at 35, two at (k 7, M 11 and 13, b 1); 27 of them
  have L* < 0. All 37 have s = 2^D = -1 mod m': at s = +1 the witness
  is X = 0 (c' = 0) and (H) is never used, so at L* >= 0 (H) is owed at
  s = -1 alone. Arm A1, added after the first run, reads it:
    A1 s = +1, L* >= 0, no (H): brute = law at 104 of 104 rows read
  The criterion, its arms added after the A1 run, its first form frozen
  before their code, the reduced form and the corollary by hand after
  the first print, before their checks ran (predicted: A2 the criterion
  decides L* + 1 at every s = -1 row, b = 1, no (H), L* >= 0, L* + 1 in
  the cap, KILL one row where they differ; A3 the reduced form = the first; A4 brute = law
  at M > 2^(k-1), L* >= 1; CONTROL the range clause dropped must
  disagree):
    A2 s = -1, no (H): the criterion decides L* + 1 at 40 of 40 rows;
    L* + 1 fails at 30
    A3 the reduced criterion = the first form at 74 of 74 rows
    CONTROL the range clause dropped: off at 10 of 74
    A4 M > 2^(k-1), L* >= 1, no (H): brute = law at 87 of 87 rows read
  The ten survivors have L* <= 2 and fail one bit later (M 11, 13, 22,
  26, 43, 44, 52, 57 at k 5..7). Toy scale: k <= 8, words of 14 bits.
  The criterion as one comparison (fails_next), its least y derived by
  hand and its line and two plants frozen before its code (predicted:
  equal to the loop at every M <= 2^k, k = 2..12, with L* >= 0, KILL
  one row off; plant E, every u read as even, off only at rows the
  loop fails; plant O, every u read as odd, only at rows it survives):
    A5 the closed criterion = the loop's at 7496 of 7496 rows (s = -1
    at 2751, L* + 1 surviving at 108)
    PLANT E: off at 87 rows, 87 of them rows the loop fails
    PLANT O: off at 59 rows, 59 of them rows the loop survives
    CAPS with (H), the 165 rows read clean to the caps = the 165 whose
    law fails past them
  At L* < 0 nothing is claimed: law_first_fail's 1 there is a
  placeholder, false beyond these widths:
    L* < 0: M = 21, k = 11 (L* -5) clean at one bit: True; at two: False
  P2:
  13, 12 and 4092 bytes, the paper's. The kill missed:
    ORDER: best 8-bit M 239, 119 bits; best 16-bit M 65519, 32759 bits
          in bytes: 13 at 8 bits, M [227, 239]; 4092 at 16 bits, M [65519]
  so 239 is unique in bits, tied with 227 in bytes. P3:
    TABLE 32: best M 4294967291 = 2^32 - 5, D 2147483645 bits, L*
    2147483613 bits = 268435451 bytes; 2 odd m above it, 0 not bounded
    below it
    TABLE 64: best M 18446744073709551557 = 2^64 - 59, D
    9223372036854775778 bits, L* 9223372036854775714 bits =
    1152921504606846964 bytes; 29 odd m above it, 0 not bounded below it
  So the paper's 32-bit HD = 3 length, 134,217,720 bytes, is about half the
  law's, and the law is proved there ((H) holds by a margin of 2^31
  bits); the paper's figure is the law's at its parity variant's
  modulus 2147483629 to two bytes:
    PARITY MODULI, (D - t) // 8 bytes: 125 at t = 8: D 50, 5; 32749 at
    t = 16: D 16374, 2044; 2147483629 at t = 31: D 1073741814,
    134217722; 2147483629 at t = 32: D 1073741814, 134217722
  and the paper's parity variant gives "Modulus 2147483629: Provides
  HD=4 up to 134217720 bytes", its 32-bit HD = 3 figure, beside "HD=4
  up to 5 byte" at 125 and "2044 byte" at 32749, the law's with the
  shift t for k.
  Each table row is the unique best: an odd m < p has
  D <= (m - 1)/2 < (p - 1)/2, an even M = 2^a m' has L* <= (2^(k-a) -
  1)/2 - k + a < (p - 1)/2 - k, the odd m above p are bounded by
  phi(m)/2, and where the law is not exact the true length is below
  D(m') + 1 bits (the pair at distance D is in every word that long),
  far under the winner's.
  Re-derived independently, the law is sound: the setting is M <= 2^k
  (so a <= k - 2 at m' > 1);
  the mixed case's congruence is necessary, not sufficient, the witness
  checking the range itself; "equality" above is D = (m - 1)/2, met
  only at primes (D = phi(m)/2 is met at composites: 9, 15, 21, ...),
  which is all the uniqueness uses.
  The incumbent, read in full: the paper names both mechanisms in words
  and screens; its 32-bit length is from limited trials. The data-pair
  half is the arithmetic codes' distance-3 bound, the least weight-2
  multiple of odd A being 2^e - s at e = D(A) (Brown 1960, Peterson
  1961, restated as Theorem 2.4.3 of Liu's 1972 Illinois report); the
  separate residue codes assume the check error-free. The cross term,
  the +a and L* itself were found nowhere. Unread: the paper's
  [Koopman24], a commercial book.
  The calls of USE, each against the engine it wraps:
    CALLS reach = the law's length and, by the criterion's loop, its
    first failing block at 392 of 392 (M, block) at 8 bits
    CALLS checksum = the kernel at every 2-byte word, M 239 and 65519:
    0 off
    CALLS M 65519: clean through 4092 bytes; 4093 zero bytes check to
    0, and to 1 with the top data bit set, one check bit away
    CALLS refused outside the setting: 11 of 11
    CALLS best_modulus at 8, 16, 32, 64 bits: [(239, 111), (65519,
    32743), (4294967291, 2147483613), (18446744073709551557,
    9223372036854775714)]

RUN RECORD. 5.4 s wall, one process, its peak unmeasured (arrays of 2^16
int64 at most), exit 0; with every arm above but the criterion's, bare
through the gate, 5.5 s, peak 58.5 MB, exit 0; with them, 5.5 s,
58.4 MB, exit 0. With A5, its plants and the calls: 4.9 s, 63.9 MB,
exit 0.
"""

import os
import sys

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import numpy as np
from functools import lru_cache
from math import gcd
from sympy import factorint, prevprime

CAP = 14            # the brute arm reads data words of at most CAP bits
KS = range(2, 8)    # P1's widths; k = 8 is read at b = 8 to two bytes
CAP8 = 16           # that arm's cap
WIDEST = 64         # reach, best_modulus and checksum refuse a wider check


def order2(m):
    """The multiplicative order of 2 mod odd m > 1, by lambda's factors."""
    lam = 1
    for p, e in factorint(m).items():
        l = (p - 1) * p ** (e - 1)
        lam = lam * l // gcd(lam, l)
    o = lam
    for q in factorint(lam):
        while o % q == 0 and pow(2, o // q, m) == 1:
            o //= q
    return o


@lru_cache(maxsize=None)
def dee(m):
    """D(m): the least d >= 1 with 2^d = +-1 mod odd m > 1."""
    o = order2(m)
    if o % 2 == 0 and pow(2, o // 2, m) == m - 1:
        return o // 2
    return o


def dee_loop(m):
    """D(m) by its definition, for the control C3."""
    x = 1
    for d in range(1, m + 1):
        x = 2 * x % m
        if x in (1, m - 1):
            return d
    raise ValueError(m)


def split(M):
    a = (M & -M).bit_length() - 1
    return a, M >> a


def law(M, k):
    """L*(M) in bits (None when m' = 1: no length clean) and (H)."""
    a, mo = split(M)
    if mo == 1:
        return None, False
    ls = dee(mo) - k + a
    return ls, ls >= 0 and ls >= (mo - 1).bit_length()  # 2^ls >= mo


def kernel(X, n, b, k, M, append=True):
    """Appendix A's kernel, Figure 1's step then k appended zero bits
    (its seed XOR omitted: it permutes the data words), vectorized over
    data words X of n b-bit blocks, the first block highest: sum =
    block_0; sum = ((sum << b) + block) % M per later block; then
    sum = (sum << k) % M."""
    mask = (1 << b) - 1
    s = (X >> (b * (n - 1))) & mask
    for t in range(1, n):
        s = ((s << b) + ((X >> (b * (n - 1 - t))) & mask)) % M
    if append:
        s = (s << k) % M
    else:
        s = s % M
    return s


def brute(M, k, b, n, append=True, witness=False):
    """Every data word of n blocks, every 1- and 2-bit error over the
    L + k codeword bits: True when none is missed, else False (and the
    first missed (X, error mask) when witness)."""
    L = n * b
    X = np.arange(1 << L, dtype=np.int64)
    chk = kernel(X, n, b, k, M, append)
    W = (X << k) | chk
    top = L + k
    km = (1 << k) - 1
    masks = [1 << i for i in range(top)]
    masks += [(1 << i) | (1 << j) for i in range(top)
              for j in range(i + 1, top)]
    for e in masks:
        V = W ^ e
        miss = chk[V >> k] == (V & km)
        if miss.any():
            if witness:
                return False, (int(X[miss.argmax()]), e)
            return False
    return (True, None) if witness else True


def first_fail(M, k, b, append=True, cap=CAP):
    """The least n with a missed error, n b <= cap, else None (unread)."""
    n = 1
    while n * b <= cap:
        if not brute(M, k, b, n, append):
            return n
        n += 1
    return None


def law_first_fail(M, k, b):
    ls, _ = law(M, k)
    if ls is None or ls < 0:
        return 1
    return ls // b + 1


def sign(M):
    """s = 2^D mod m', as +1 or -1."""
    mo = split(M)[1]
    return 1 if pow(2, dee(mo), mo) == 1 else -1


def sweep(append=True, ks=KS):
    """Rows (k, M, b, H, law's first failing n, brute's or None)."""
    rows = []
    for k in ks:
        for M in range(2, 2 ** k + 1):
            for b in sorted({1, k}):
                ls, h = law(M, k)
                rows.append((k, M, b, h, law_first_fail(M, k, b),
                             first_fail(M, k, b, append)))
    return rows


def best(k):
    """Every M <= 2^k at the largest L*, and that L*."""
    top, who = None, []
    for M in range(2, 2 ** k + 1):
        ls, _ = law(M, k)
        if ls is None:
            continue
        if top is None or ls > top:
            top, who = ls, [M]
        elif ls == top:
            who.append(M)
    return top, who


def phi(m):
    r = m
    for p in factorint(m):
        r = r // p * (p - 1)
    return r


def best_far(k):
    """The largest prime p <= 2^k with D = (p - 1)/2, and every odd m in
    (p, 2^k] bounded: D(m) <= phi(m)/2, read against (p - 1)/2."""
    p = prevprime(2 ** k)
    while dee(p) != (p - 1) // 2:
        p = prevprime(p)
    above = list(range(p + 2, 2 ** k + 1, 2))
    beaten = [m for m in above if phi(m) // 2 >= (p - 1) // 2]
    return p, dee(p), len(above), beaten


def crit(M, k, ranged=True):
    """Whether L* + 1 bits fail, by the criterion's first form: some X <
    2^(L* + 1) whose check moves by the pair (L*, a); ranged=False drops
    c' <= m' - 2, the control's plant."""
    a, mo = split(M)
    ls = dee(mo) - k + a
    s = sign(M)
    u = pow(2, k - a, mo)
    for X in range(1 << (ls + 1)):
        c = X * u % mo
        e2 = (1 if (X >> ls) & 1 == 0 else -1) * s
        if e2 == 1 and c % 2 == 0 and (c <= mo - 2 or not ranged):
            return True
        if e2 == -1 and c % 2 == 1:
            return True
    return False


def crit_y(M, k):
    """The criterion reduced: s = +1, or some y < 2^(L*) has y 2^(k-a)
    mod m' odd."""
    if sign(M) == 1:
        return True
    a, mo = split(M)
    ls = dee(mo) - k + a
    u = pow(2, k - a, mo)
    return any(y * u % mo % 2 for y in range(1 << ls))


def fails_next(M, k, plant=None):
    """Whether L* + 1 bits fail, at m' > 1 and L* >= 0: the criterion as
    one comparison. s = +1; or the least y >= 1 with y u mod m' odd, u =
    2^(k-a) mod m', lies below 2^(L*). That y is 1 at u odd, and at u
    even ceil(m'/u): y u is even while below m', and the first multiple
    past m' leaves y u - m', odd. The control's plants read every u as
    even ('E') or as odd ('O')."""
    if sign(M) == 1:
        return True
    a, mo = split(M)
    ls = dee(mo) - k + a
    u = pow(2, k - a, mo)
    odd = u % 2 == 1 if plant is None else plant == "O"
    y = 1 if odd else -(-mo // u)
    return y.bit_length() <= ls         # y < 2^(L*), never built


def setting(M, k):
    """Whether (M, k) lies where the law speaks and the calls below are
    priced: integers, k <= WIDEST, 3 <= M <= 2^k, M no power of 2."""
    return (type(M) is int and type(k) is int and 1 <= k <= WIDEST
            and 3 <= M <= 2 ** k and split(M)[1] > 1)


def reach(M, k, block=1):
    """(n, f): every error of one or two bits is caught through n
    blocks of data, each of block bits, and f blocks is the first length
    at which one is missed, None where the criterion leaves L* + 1 bits
    clean. None outside the setting, and at L* < 0, where the law says
    nothing."""
    if not setting(M, k) or type(block) is not int or block < 1:
        return None
    ls = law(M, k)[0]
    if ls < 0:
        return None
    n = ls // block
    return n, (n + 1 if fails_next(M, k) else None)


def best_modulus(k):
    """(M, L*): the one modulus of longest reach at k = 8, 16, 32 or 64
    bits, and that reach in bits. None at any other width, and should a
    tie or a modulus the bound does not settle appear."""
    if type(k) is not int or k not in (8, 16, 32, 64):
        return None
    if k <= 16:
        top, who = best(k)
        return (who[0], top) if len(who) == 1 else None
    p, d, _, beaten = best_far(k)
    return None if beaten else (p, d - k)


def checksum(data, M, k):
    """The k-bit check sent beside data, bytes with the first highest:
    X 2^k mod M, X the data as one integer. None outside the setting."""
    if not setting(M, k) or not isinstance(data, (bytes, bytearray)):
        return None
    return (int.from_bytes(data, "big") << k) % M


def check(label, ok):
    print(("PASS  " if ok else "FAIL  ") + label)
    return ok


def main():
    good = True
    # C3: the order engine against the definition.
    odd = range(3, 4096, 2)
    bad = [m for m in odd if dee(m) != dee_loop(m)]
    good &= check(f"C3 D(m) = its power loop at every odd m < 4096 "
                  f"({len(odd)} read, {len(bad)} off)", not bad)
    # C1: the hand case, M = 7, k = 3, one data bit.
    ok, wit = brute(7, 3, 1, 1, witness=True)
    X0, e0 = 0, (1 << 3) | 1
    c0 = int(kernel(np.array([X0]), 1, 1, 3, 7)[0])
    V0 = ((X0 << 3) | c0) ^ e0
    c1 = int(kernel(np.array([V0 >> 3]), 1, 1, 3, 7)[0])
    hand = c0 == 0 and c1 == 1 and (V0 & 7) == 1
    good &= check(f"C1 M = 7, k = 3, L = 1: missed (first witness {wit}); "
                  f"the hand pair, data 0 with flips at 3 and 0, missed: "
                  f"{hand}; L* = {law(7, 3)[0]}",
                  (not ok) and hand and law(7, 3)[0] == 0)
    # C2: the planted kernel, its appended zeros dropped.
    plant = sweep(append=False, ks=range(2, 6))
    read = [r for r in plant if r[3] and r[5] is not None]
    off = [r for r in read if r[5] != r[4]]
    good &= check(f"C2 the plant (no appended zeros) disagrees with the "
                  f"law at {len(off)} of {len(read)} rows read with (H)",
                  len(off) > 0)
    if not good:
        print("controls failed: no verdict")
        return 1
    # P1: the law against Figure 1 broken exhaustively.
    rows = sweep()
    rows += [(8, M, 8, law(M, 8)[1], law_first_fail(M, 8, 8),
              first_fail(M, 8, 8, cap=CAP8)) for M in range(2, 257)]
    withh = [r for r in rows if r[3]]
    readh = [r for r in withh if r[5] is not None]
    offh = [r for r in readh if r[5] != r[4]]
    noh = [r for r in rows if not r[3] and r[5] is not None]
    offn = [r for r in noh if r[5] != r[4]]
    print(f"LAW: with (H), brute = law at {len(readh) - len(offh)} of "
          f"{len(readh)} rows read ({len(withh) - len(readh)} past the caps "
          f"of {CAP} bits, {CAP8} at k = 8); without (H), {len(noh) - len(offn)} of "
          f"{len(noh)} read agree")
    for r in offn[:12]:
        print(f"      no (H): k {r[0]}, M {r[1]}, b {r[2]}: law fails at "
              f"n {r[4]}, brute at {r[5]}")
    good &= check("P1 the law holds at every row read with (H)", not offh)
    for r in offh[:12]:
        print(f"      OFF: k {r[0]}, M {r[1]}, b {r[2]}: law {r[4]}, "
              f"brute {r[5]}")
    kb = sorted({(r[0], r[2]) for r in readh})
    print("      read with (H), by (k, b): " + ", ".join(
        f"{key} {sum((r[0], r[2]) == key for r in readh)}" for key in kb))
    late = [r[5] - r[4] for r in offn]
    print(f"      no (H), off: {len(offn)}, late by one block "
          f"{late.count(1)}, by two {late.count(2)}, earlier "
          f"{sum(x < 0 for x in late)}; L* < 0 at "
          f"{sum(law(r[1], r[0])[0] < 0 for r in offn)}; s = -1 at "
          f"{sum(sign(r[1]) == -1 for r in offn)}")
    good &= check("P1 no row without (H) fails before the law",
                  all(x > 0 for x in late))
    # A1: s = +1 without (H), every row with L* >= 0 read.
    plus = [r for r in rows if not r[3] and split(r[1])[1] > 1
            and sign(r[1]) == 1 and law(r[1], r[0])[0] >= 0
            and r[5] is not None]
    poff = [r for r in plus if r[5] != r[4]]
    good &= check(f"A1 s = +1, L* >= 0, no (H): brute = law at "
                  f"{len(plus) - len(poff)} of {len(plus)} rows read",
                  not poff and len(plus) > 0)
    # The criterion at L* + 1 without (H): b = 1 rows, L* + 1 in the cap.
    arm = [r for r in rows if r[2] == 1 and not r[3]
           and split(r[1])[1] > 1 and law(r[1], r[0])[0] >= 0
           and law(r[1], r[0])[0] + 1 <= CAP]
    part = [r for r in arm if sign(r[1]) == -1]
    hit = [r for r in part if crit(r[1], r[0]) == (r[5] == r[4])]
    fails = sum(r[5] == r[4] for r in part)
    good &= check(f"A2 s = -1, no (H): the criterion decides L* + 1 at "
                  f"{len(hit)} of {len(part)} rows; L* + 1 fails at {fails}",
                  len(hit) == len(part) and bool(part))
    red = [r for r in arm if crit_y(r[1], r[0]) != crit(r[1], r[0])]
    good &= check(f"A3 the reduced criterion = the first form at "
                  f"{len(arm) - len(red)} of {len(arm)} rows", not red)
    loose = [r for r in arm if crit(r[1], r[0], ranged=False)
             != (r[5] == r[4])]
    good &= check(f"CONTROL the range clause dropped: off at {len(loose)} "
                  f"of {len(arm)}", len(loose) > 0)
    for r in [r for r in arm if sign(r[1]) == -1 and r[5] != r[4]]:
        print(f"      survives L* + 1: k {r[0]}, M {r[1]}, L* "
              f"{law(r[1], r[0])[0]}, brute's first failing n {r[5]}")
    top = [r for r in rows if not r[3] and 2 * r[1] > 2 ** r[0]
           and split(r[1])[1] > 1 and law(r[1], r[0])[0] >= 1
           and r[5] is not None]
    topoff = [r for r in top if r[5] != r[4]]
    good &= check(f"A4 M > 2^(k-1), L* >= 1, no (H): brute = law at "
                  f"{len(top) - len(topoff)} of {len(top)} rows read "
                  f"(b = 1 and b = k)", not topoff and bool(top))
    # A5: the criterion as one comparison against its loop, and the
    # two plants, each read in the direction it pushes.
    wide = [(k, M) for k in range(2, 13) for M in range(3, 2 ** k + 1)
            if split(M)[1] > 1 and law(M, k)[0] >= 0]
    loop = {km: crit_y(km[1], km[0]) for km in wide}
    off5 = [km for km in wide if fails_next(km[1], km[0]) != loop[km]]
    minus = sum(sign(M) == -1 for k, M in wide)
    good &= check(f"A5 the closed criterion = the loop's at "
                  f"{len(wide) - len(off5)} of {len(wide)} rows (s = -1 at "
                  f"{minus}, L* + 1 surviving at "
                  f"{sum(not v for v in loop.values())})", not off5)
    for name, push in (("E", True), ("O", False)):
        offp = [km for km in wide
                if fails_next(km[1], km[0], plant=name) != loop[km]]
        way = sum(loop[km] == push for km in offp)
        good &= check(f"PLANT {name}: off at {len(offp)} rows, {way} of them "
                      f"rows the loop {'fails' if push else 'survives'}",
                      len(offp) > 0 and way == len(offp))
    # Past the caps: with (H), the rows brute read clean are exactly
    # those whose law fails past the cap.
    past = [r for r in withh
            if r[4] * r[2] > (CAP8 if r[0] == 8 else CAP)]
    good &= check(f"CAPS with (H), the {len(withh) - len(readh)} rows read "
                  f"clean to the caps = the {len(past)} whose law fails "
                  f"past them", sorted(past) == sorted(
                      r for r in withh if r[5] is None))
    one = brute(21, 11, 1, 1)
    two = brute(21, 11, 1, 2)
    good &= check(f"L* < 0: M = 21, k = 11 (L* {law(21, 11)[0]}) clean at "
                  f"one bit: {one}; at two: {two}", one and not two)
    # P2: the paper's prints.
    paper = {(239, 8): 13, (253, 8): 12, (65519, 16): 4092}
    got = {key: law(*key)[0] // 8 for key in paper}
    good &= check(f"P2 bytes by the law {got} against the paper's {paper}",
                  got == paper)
    # The kill.
    t8, w8 = best(8)
    t16, w16 = best(16)
    d8 = [dee(split(M)[1]) for M in w8]
    d16 = [dee(split(M)[1]) for M in w16]
    print(f"ORDER: best 8-bit M {', '.join(map(str, w8))}, "
          f"{', '.join(map(str, d8))} bits; best 16-bit M "
          f"{', '.join(map(str, w16))}, {', '.join(map(str, d16))} bits")
    ties8 = [M for M in range(2, 257) if law(M, 8)[0] is not None
             and law(M, 8)[0] // 8 == t8 // 8]
    ties16 = [M for M in range(2, 2 ** 16 + 1) if law(M, 16)[0] is not None
              and law(M, 16)[0] // 8 == t16 // 8]
    print(f"      in bytes: {t8 // 8} at 8 bits, M {ties8}; {t16 // 8} at "
          f"16 bits, M {ties16}")
    good &= check("KILL missed: the ORDER line reads 239, 119 and 65519, "
                  "32759", w8 == [239] and d8 == [119]
                  and w16 == [65519] and d16 == [32759])
    # P3: the table past the screen.
    far = {}
    for k in (32, 64):
        p, d, n_above, beaten = far[k] = best_far(k)
        print(f"TABLE {k}: best M {p} = 2^{k} - {2 ** k - p}, D {d} bits, "
              f"L* {d - k} bits = {(d - k) // 8} bytes; {n_above} odd m "
              f"above it, {len(beaten)} not bounded below it")
    p32, p64 = far[32], far[64]
    good &= check("P3 at 32 bits 4294967291, D 2147483645",
                  p32[0] == 4294967291 and p32[1] == 2147483645
                  and not p32[3])
    good &= check("P3 at 64 bits 2^64 - 59, D 2^63 - 30, every odd m "
                  "above it bounded", p64[0] == 2 ** 64 - 59
                  and p64[1] == 2 ** 63 - 30 and not p64[3])
    # The parity variant's moduli, D - t at each shift t, in bytes.
    print("PARITY MODULI, (D - t) // 8 bytes: " + "; ".join(
        f"{q} at t = {t}: D {dee(q)}, {(dee(q) - t) // 8}"
        for q, t in ((125, 8), (32749, 16), (2147483629, 31),
                     (2147483629, 32))))
    # The calls: each against the engine it wraps, then its refusals.
    rows8 = [(M, b) for M in range(3, 257) if split(M)[1] > 1
             and law(M, 8)[0] >= 0 for b in (1, 8)]
    offr = [mb for mb in rows8 if reach(mb[0], 8, mb[1]) != (
        law(mb[0], 8)[0] // mb[1],
        law_first_fail(mb[0], 8, mb[1]) if crit_y(mb[0], 8) else None)]
    good &= check(f"CALLS reach = the law's length and, by the criterion's "
                  f"loop, its first failing block at {len(rows8) - len(offr)}"
                  f" of {len(rows8)} (M, block) at 8 bits", not offr)
    table = [best_modulus(k) for k in (8, 16, 32, 64)]
    good &= check(f"CALLS best_modulus at 8, 16, 32, 64 bits: {table}",
                  table == [(239, 111), (65519, 32743),
                            (2 ** 32 - 5, 2147483613),
                            (2 ** 64 - 59, 2 ** 63 - 94)])
    X = np.arange(1 << 16, dtype=np.int64)
    offk = sum(int((kernel(X, 2, 8, k, M) != np.array(
        [checksum(bytes([x >> 8, x & 255]), M, k) for x in range(1 << 16)]
    )).sum()) for M, k in ((239, 8), (65519, 16)))
    good &= check(f"CALLS checksum = the kernel at every 2-byte word, M 239 "
                  f"and 65519: {offk} off", offk == 0)
    n, f = reach(65519, 16, 8)
    word = bytearray(f)
    c0 = checksum(word, 65519, 16)
    word[0] ^= 0x80
    c1 = checksum(word, 65519, 16)
    good &= check(f"CALLS M 65519: clean through {n} bytes; {f} zero bytes "
                  f"check to {c0}, and to {c1} with the top data bit set, "
                  f"one check bit away", (n, f, c0, c1) == (4092, 4093, 0, 1))
    refused = [reach(256, 8), reach(257, 8), reach(21, 11), reach(239, 65),
               reach(239.0, 8), reach(239, 8, 0), best_modulus(24),
               best_modulus(8.0), checksum(b"ab", 256, 8),
               checksum([1, 2], 239, 8), checksum(2, 239, 8)]
    good &= check(f"CALLS refused outside the setting: "
                  f"{sum(r is None for r in refused)} of {len(refused)}",
                  all(r is None for r in refused))
    return 0 if good else 1


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