shiftpar.py

Checks: COORDINATES: The parity variant criterion; COORDINATES: The parity variant's reach rule; pattern; observation.

Cited on: COORDINATES.

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

"""shiftpar.py — the shifted checksum's parity variant as its text
states it and as its code computes it: the check value under either
reading, and the least error of two data bits and a residue bit that
the code's reading misses.

USE. In Python, with numpy and sympy installed, from the folder holding
shiftpar.py and shiftsum.py. The variant of arXiv:2304.13496 sends an
r-bit residue X 2^t mod M, M <= 2^r <= 2^t, with a parity bit below it.
koopman is that check on your bytes, in 8-bit blocks from seed 0:
reading "C" takes the parity of the data alone, as the paper's code
does, reading "T" of the data and the residue, as its text says.
least_miss(M, t, r, cap) gives the least j below cap at which the
congruence a miss of the code's reading needs is solved, by flips of
data bits i < j with a flip of residue bit l, and, where its draw
builds one, a data word at which the code misses them. At the paper's
15-bit modulus:

    >>> from shiftpar import koopman, least_miss
    >>> koopman(b"123456789", 32749, 16)
    5521
    >>> koopman(b"123456789", 32749, 16, "T")
    5520
    >>> j, i, l, word = least_miss(32749, 16, 15, 400)
    >>> j, i, l, len(word)
    (94, 65, 0, 12)
    >>> x = int.from_bytes(word, "big") ^ (1 << i) ^ (1 << j)
    >>> bad = x.to_bytes(len(word), "big")     # two data bits flipped
    >>> koopman(bad, 32749, 16) ^ koopman(word, 32749, 16)
    2
    >>> koopman(bad, 32749, 16, "T") ^ koopman(word, 32749, 16, "T")
    3
    >>> from shiftsum import reach
    >>> reach(32749, 16, block=8)              # the text's reading, bytes
    (2044, 2045)

The code's check moves in bit l + 1 alone, the residue's bit l, so
with that bit flipped the error of three bits passes; the text's moves
in the parity bit too, and catches it. The code's reading catches
every error of at most three bits through the lesser of j // 8 bytes
and the text's reach, here 11, and misses this one at 12. Each call
returns None outside its setting, which its own docstring states; the
search costs at most about the square of cap.

QUESTION. Does the shifted checksum's parity variant reach HD = 4?
arXiv:2304.13496 section V packs a (k-1)-bit shifted checksum
with one parity bit: R = X 2^t mod M in r bits, M <= 2^r <= 2^t, and a
bit p. Its text puts the check in the parity ("the final check value
... must be included in the parity computation"); its Appendix C and E
code XORs the data bytes alone into psum. Two readings:
  T: p = par(X) xor par(R);   C: p = par(X).
What is each reading's HD = 4 length?

THE DESIGN AND PREDICTIONS, frozen before this engine. L*_t = D(m') -
t + a, the shifted law with the shift t for k (shiftsum.law(M, t)),
its L* + 1 criterion shiftsum.crit_y(M, t). By hand: T catches every
odd weight, so its HD = 4 length is the residue's own HD = 3 length,
L*_t bits; C catches (data, residue) by the parity, but (data,
residue, parity) is T's cross term again, and (data i, data j, residue
l) keeps par(X): missed iff (e_i 2^i + e_j 2^j) 2^t = e_l 2^l mod M,
its range met.
  PT under T, at every swept (M, t, r) with L*_t >= 0 and L*_t + 1 in
     the cap: the first failing L is L*_t + 1 where the criterion holds,
     later where not; no odd weight is ever missed.
  PC under C: every miss of weight <= 3 below D + 1 bits is of type
     (d, r, p) or (d, d, r); C's first failing L = min(T's, the (d, d,
     r) first); (d, d, r) fires first at most rows of L*_t >= 8.
  PW at the paper's moduli (8-bit bytes; t = 8, 16, 32; r = 7, 15, 31;
     M = 125, 32749, 2147483629): a data word and a 3-bit error that a
     transcription of Appendix C/E misses, its length about sqrt(D/r)
     bits (tens at 32749, thousands at 2147483629).
KILL, as printed: "PW M ...: code misses a 3-bit error at L = ...
  bits (L*_t = ...)". The conjecture (the code's HD = 4 claim is short)
  dies if at 32749 or 2147483629 no witness at L <= L*_t prints, or if
  the transcription with the residue in the parity (T) misses it too.
  PT dies at one swept row off, or any missed odd weight.
CONTROLS, read first.
  K1 the hand witness: M = 59, t = r = 6, X = 16 (L = 5), flips at data
     bits 0 and 4 and residue bit 4: missed under C, caught under T.
  K2 the engine with no parity bit, weight <= 2, t = r = k, equals
     shiftsum.first_fail at b = 1 at every M, k = 3..6.
  K3 the algebraic (d, d, r) search, its range read on X directly,
     against the engine's first (d, d, r) miss at every swept row.
  K4 the transcription catches every 1-bit error of each witness word
     (it reads the bytes the way the brute reads bits).

CHANGES TO WHAT WAS FROZEN. K3's first form read only pairs with j =
L - 1, so a pair whose range needs a longer word was missed: off at 5
of 294 rows (r 5..6; M 21 at t 7 read 5 against the engine's 4); it
now reads every i < j < L. Its range read is itself an enumeration
over X, so it checks the congruence and the engine's type bookkeeping,
not the range. PW also prints the congruence's least j. K4 reads the
data bits alone, and its byte-order clause is K5's, added after a
second read of the code: the transcription against the engine's
table, both readings, every 2-byte word at M 125, t 8.
The engine was vectorized after the rehearsal; its prints held.
For the calls of USE: witness is split into congruence, the search, and
word, the data word's draw, its returns as before; koopman takes bytes
and refuses outside its setting; least_miss wraps the two.

FINDINGS (the run's lines copied, the PW (H) and K4 lines merged over
the three moduli; K5's planted counts from runs with each plant in).
  K1 M 59, t = r = 6, L 5: the hand triple holds (21 -> 5): True; C
  misses [(2, 1, 0)], T misses []
  K2 no parity bit, weight <= 2: engine = shiftsum's first_fail at 116
  of 116 (k, M)
  PT no odd weight missed under T at 294 of 294 rows
  PT T's first failing L = L*_t + 1 by the criterion at 104 of 104 rows
  PC every C miss below D + 1 bits is (d, r, p) or (d, d, r): 0 stray
  K3 the congruence's (d, d, r) first = the engine's at 294 of 294 rows
  PC C's first = min(T's, (d, d, r)'s), its (d, r, p) first = T's (d,
  r): 0 rows off
  PC (d, d, r) fires before T's first at 26 of 26 rows with L*_t >= 8
  PW M 125: code misses a 3-bit error at L = 8 bits (L*_t = 42); data
  bits 0, 5, check bit 7; T misses it: False
    the congruence's least j over i < j < 60: 5, so the code holds HD =
    4 to 0 bytes, the text's reading to 5
  PW M 32749: code misses a 3-bit error at L = 96 bits (L*_t = 16358);
  data bits 65, 94, check bit 1; T misses it: False
    least j over i < j < 400: 94, so the code holds HD = 4 to 11 bytes,
    the text's reading to 2044
  PW M 2147483629: code misses a 3-bit error at L = 29552 bits (L*_t =
  1073741782); data bits 9802, 29546, check bit 1; T misses it: False
    least j over i < j < 40000: 29546, so the code holds HD = 4 to 3693
    bytes, the text's reading to 134217722
  PW (H) 2^(L*_t) >= m' holds: True at each, so the text's reading fails
  at 6, 2045 and 134217723 bytes.
  K4 caught every 1-bit data error of each witness word.
  K5 the transcription = the engine's check at every 2-byte word, both
  readings, M 125: 0 off (planted: bytes swapped, 62910 off; the code
  read against T's table, 33027 off).
  The kill missed: the text's reading is the shifted law with t for k,
  the paper's HD = 4 figures its L*_t (2044 and 5 bytes exact; 134217720
  against 134217722 at 32 bits); the code's reading fails at 12 and 3694
  bytes, two (d, d, r) flips. Why only those types, by hand: under C an
  odd count of data flips moves par(X), caught unless the parity bit
  flips too, which leaves (d, r, p), T's cross term; an even count with
  no residue flip is the data pair, D apart; (d, d, r) is the one left.
  The scale guess, sqrt(D/r) bits (33 and 5885 by hand), was 2.8 and
  5.0 times low (94, 29546): tens of thousands, not thousands, at 32
  bits. Koopman8P has no code in the paper: its row
  assumes Appendix C's. Toy scale for PT, PC: r <= 6, words of 12 bits.
  Read against the paper's four versions: the first has no parity
  variant; the second's and third's code (16-bit blocks) computes T,
  the check in the parity; the fourth's rewrite to bytes computes C.
  The calls of USE:
    CALLS least_miss(32749, 16, 15, 400): j 94, i 65, l 0, 12 bytes;
    the two data flips move the code's check by 2, the text's by 3
    CALLS least_miss(32749, 16, 15, 94), the cap at its j: (None, None,
    None, None)
    CALLS refused outside the setting: 13 of 13

RUN RECORD. 75.8 s wall under a 2048 MB cap, peak commit 534.0 MB,
one process, exit 0; with K5, 85.7 s, 534.7 MB, exit 0; K4's bit loop
at 32 bits takes most of it. With the (H) print, under the 512 MB cap:
73.0 s, peak 90.4 MB, exit 0, once shiftsum.law read (H) by bit length,
not by the integer 2^(L*), 128 MB at 32 bits. With the calls, K4's
words as bytes: 41.7 s, 91.3 MB, exit 0.
"""

import os
import random
import sys

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import numpy as np

from shiftsum import crit_y, dee, first_fail, law, split  # noqa: E402

CAP = 12            # data bits the engine reads at most
RS = range(3, 7)    # residue widths swept
TS = (0, 1, 2)      # the shift t = r + these
WIDEST = 64         # koopman and least_miss refuse a longer shift
REACH = 1 << 16     # least_miss reads data bits below this at most


def par(v):
    """Parity of each int64 entry."""
    v = v.copy()
    out = np.zeros_like(v)
    while v.any():
        out ^= v & 1
        v >>= 1
    return out


def table(M, t, r, L, reading):
    """The check sent for every data word X < 2^L: (R << 1) | p, or R
    alone at reading 'N' (no parity bit)."""
    X = np.arange(1 << L, dtype=np.int64)
    R = (X << t) % M
    if reading == "N":
        return R
    p = par(X) if reading == "C" else par(X) ^ par(R)
    return (R << 1) | p


def masks(L, r, reading, top):
    """Every error of weight 1..top over the codeword, with its type
    (data, residue, parity) counts."""
    cw = r + (0 if reading == "N" else 1)
    n = L + cw
    out = []

    def kind(bits):
        d = sum(b >= cw for b in bits)
        p = 0 if reading == "N" else sum(b == 0 for b in bits)
        return (d, len(bits) - d - p, p)
    for i in range(n):
        out.append((1 << i, kind([i])))
        if top < 2:
            continue
        for j in range(i + 1, n):
            out.append(((1 << i) | (1 << j), kind([i, j])))
            if top < 3:
                continue
            for k in range(j + 1, n):
                out.append(((1 << i) | (1 << j) | (1 << k),
                            kind([i, j, k])))
    return out, cw


def missed(M, t, r, L, reading, top=3):
    """The set of error types missed at L data bits, every data word
    against every mask of a type at once."""
    chk = table(M, t, r, L, reading)
    ms, cw = masks(L, r, reading, top)
    W = (np.arange(1 << L, dtype=np.int64) << cw) | chk
    lo = (1 << cw) - 1
    by = {}
    for e, ty in ms:
        by.setdefault(ty, []).append(e)
    got = set()
    for ty, es in by.items():
        E = np.array(es, dtype=np.int64)
        for q in range(0, len(E), 256):
            V = W[None, :] ^ E[q:q + 256, None]
            if (chk[V >> cw] == (V & lo)).any():
                got.add(ty)
                break
    return got


def firsts(M, t, r, reading, top=3, cap=CAP):
    """The first L at which each type is missed, to the cap."""
    seen = {}
    for L in range(1, cap + 1):
        for ty in missed(M, t, r, L, reading, top):
            seen.setdefault(ty, L)
    return seen


def ddr_first(M, t, r, cap=CAP):
    """K3: the least L with a (data, data, residue) miss, by the
    congruence (e_i 2^i + e_j 2^j) 2^t = e_l 2^l mod M and the range
    read on X directly; None to the cap."""
    for L in range(2, cap + 1):
        for i, j in ((i, j) for j in range(1, L) for i in range(j)):
            for ei in (1, -1):
                for ej in (1, -1):
                    dl = ((ei << i) + (ej << j)) * (1 << t) % M
                    for l in range(r):
                        for el in (1, -1):
                            if dl != (el * (1 << l)) % M:
                                continue
                            if range_met(M, t, L, i, j, ei, ej, l, el):
                                return L
    return None


def range_met(M, t, L, i, j, ei, ej, l, el):
    """Some X < 2^L with bits i, j set to flip by ei, ej, whose residue's
    bit l flips by el to the residue of the flipped word."""
    for X in range(1 << L):
        if ((X >> i) & 1) != (ei < 0) or ((X >> j) & 1) != (ej < 0):
            continue
        R = (X << t) % M
        if ((R >> l) & 1) != (el < 0):
            continue
        X2 = X + (ei << i) + (ej << j)
        if (X2 << t) % M == R + el * (1 << l):
            return True
    return False


def koopman(data, M, t, reading="C"):
    """Appendix C/E transcribed: 8-bit blocks, seed 0, t appended zero
    bits, the residue shifted up one, parity in bit 0. reading 'C' is
    the code (psum XORs data bytes); 'T' adds the residue to psum.
    None unless data is bytes, not empty, 3 <= M <= 2^t, M no power of
    2 and t <= WIDEST."""
    if (type(M) is not int or type(t) is not int or not 1 <= t <= WIDEST
            or not 3 <= M <= 2 ** t or split(M)[1] == 1
            or reading not in ("C", "T")
            or not isinstance(data, (bytes, bytearray)) or len(data) == 0):
        return None
    s = data[0]
    psum = s
    for b in data[1:]:
        s = ((s << 8) + b) % M
        psum ^= b
    s = (s << t) % M
    if reading == "T":
        psum ^= s
    return (s << 1) | (bin(psum).count("1") & 1)


def congruence(M, t, r, lmax):
    """The solution of least j, over i < j < lmax, of (1 + sg 2^(j-i))
    2^(i+t) = el 2^l mod M with l < r: (j, i, j - i, sg, el, l), or None.
    Its products are int64, so M < 2^31."""
    pw = np.array([pow(2, n, M) for n in range(lmax + t + 1)],
                  dtype=np.int64)
    best = None
    lim = lmax
    for d in range(1, lmax):
        if d >= lim:
            break
        for sg in (1, -1):
            v = (1 + sg * pow(2, d, M)) % M
            w = pw[t:t + lim - d] * v % M
            for el, z in ((1, w), (-1, (M - w) % M)):
                hit = np.nonzero((z > 0) & ((z & (z - 1)) == 0)
                                 & (z < (1 << r)))[0]
                if len(hit) and int(hit[0]) + d < lim:
                    i = int(hit[0])
                    lim = i + d
                    best = (i + d, i, d, sg, el, int(z[i]).bit_length() - 1)
    return best


def word(M, t, i, j, sg, el, l, seed=1):
    """A data word of whole bytes holding bits i < j, built to meet the
    range of the congruence's solution: (L bits, X), or None when 4000
    draws a sign find none."""
    rng = random.Random(seed)
    for ei in (1, -1):
        ej = ei * sg
        e_l = el * ei
        nbytes = (j + 8) // 8
        for _ in range(4000):
            X = rng.getrandbits(8 * nbytes)
            X = X & ~(1 << i) & ~(1 << j)
            X |= (ei < 0) << i
            X |= (ej < 0) << j
            R = (X << t) % M
            if ((R >> l) & 1) != (e_l < 0):
                continue
            X2 = X + (ei << i) + (ej << j)
            if (X2 << t) % M == R + e_l * (1 << l):
                return 8 * nbytes, X
    return None


def witness(M, t, r, lmax, seed=1):
    """A (d, d, r) miss of least j found by the congruence over i < j <
    lmax, its data word built to meet the range: (L bits, X, i, j, l);
    the least j alone when no word is built, None when there is no j."""
    best = congruence(M, t, r, lmax)
    if best is None:
        return None
    j, i, d, sg, el, l = best
    w = word(M, t, i, j, sg, el, l, seed)
    return j if w is None else (w[0], w[1], i, j, l)


def least_miss(M, t, r, cap):
    """(j, i, l, word): the least j < cap at which the congruence a
    miss of the code's reading needs is solved, by flips of data bits
    i < j with a flip of residue bit l, and a data word, bytes with the
    first highest, that it does miss them at; word is None when the
    draw, over words of (j + 8) // 8 bytes, built none. All four are
    None when no j
    lies below cap: the reading then misses no such triple whose data
    bits both lie below cap. None itself outside the setting: integers,
    3 <= M <= 2^r <= 2^t, M no power of 2, r <= 31, t <= WIDEST, 2 <=
    cap <= REACH."""
    if (not all(type(v) is int for v in (M, t, r, cap))
            or not 1 <= r <= min(t, 31) or t > WIDEST
            or not 3 <= M <= 2 ** r or split(M)[1] == 1
            or not 2 <= cap <= REACH):
        return None
    best = congruence(M, t, r, cap)
    if best is None:
        return None, None, None, None
    j, i, d, sg, el, l = best
    w = word(M, t, i, j, sg, el, l)
    return j, i, l, None if w is None else w[1].to_bytes(w[0] // 8, "big")


def to_bytes(X, nbytes):
    return X.to_bytes(nbytes, "big")


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


def main():
    good = True
    # K1: the hand witness.
    X, X2, M, t = 16, 1, 59, 6
    R, R2 = (X << t) % M, (X2 << t) % M
    c_ok = (R ^ (1 << 4)) == R2 and bin(X).count("1") % 2 == \
        bin(X2).count("1") % 2
    gotC = missed(M, t, 6, 5, "C")
    gotT = missed(M, t, 6, 5, "T")
    good &= check(f"K1 M 59, t = r = 6, L 5: the hand triple holds "
                  f"({R} -> {R2}): {c_ok}; C misses {sorted(gotC)}, T "
                  f"misses {sorted(gotT)}", c_ok and (2, 1, 0) in gotC
                  and not gotT)
    # K2: the engine with no parity bit against shiftsum's brute.
    off, n = [], 0
    for k in RS:
        for M in range(2, 2 ** k + 1):
            mine = next((L for L in range(1, 15)
                         if missed(M, k, k, L, "N", top=2)), None)
            n += 1
            if mine != first_fail(M, k, 1):
                off.append((k, M))
    good &= check(f"K2 no parity bit, weight <= 2: engine = shiftsum's "
                  f"first_fail at {n - len(off)} of {n} (k, M)", not off)
    # K5: the transcription against the engine's table.
    eng = {rd: table(125, 8, 7, 16, rd) for rd in ("C", "T")}
    k5 = sum(koopman(bytes([X >> 8, X & 0xFF]), 125, 8, rd) != int(eng[rd][X])
             for rd in ("C", "T") for X in range(1 << 16))
    good &= check(f"K5 the transcription = the engine's check at every "
                  f"2-byte word, both readings, M 125: {k5} off", k5 == 0)
    if not good:
        print("controls failed: no verdict")
        return 1
    # The sweep.
    rows = []
    for r in RS:
        for M in range(3, 2 ** r + 1):
            a, mo = split(M)
            if mo == 1:
                continue
            for dt in TS:
                t = r + dt
                ls = law(M, t)[0]
                fT = firsts(M, t, r, "T")
                fC = firsts(M, t, r, "C")
                rows.append((r, t, M, ls, dee(mo), fT, fC))
    odd = [x for x in rows if any(sum(ty) % 2 for ty in x[5])]
    good &= check(f"PT no odd weight missed under T at {len(rows) - len(odd)}"
                  f" of {len(rows)} rows", not odd)
    arm = [x for x in rows if x[3] >= 0 and x[3] + 1 <= CAP]
    offT = []
    for r, t, M, ls, D, fT, fC in arm:
        first = min(fT.values()) if fT else None
        want = ls + 1 if crit_y(M, t) else None
        if want is not None and first != want:
            offT.append((r, t, M, ls, first))
        if want is None and first is not None and first <= ls + 1:
            offT.append((r, t, M, ls, first))
    good &= check(f"PT T's first failing L = L*_t + 1 by the criterion at "
                  f"{len(arm) - len(offT)} of {len(arm)} rows", not offT)
    for x in offT[:8]:
        print(f"      OFF T: r {x[0]}, t {x[1]}, M {x[2]}, L*_t {x[3]}, "
              f"first {x[4]}")
    allowed = {(1, 1, 1), (2, 1, 0)}
    stray = [(x[:3], ty, L) for x in rows for ty, L in x[6].items()
             if ty not in allowed and L <= x[4]]
    good &= check(f"PC every C miss below D + 1 bits is (d, r, p) or "
                  f"(d, d, r): {len(stray)} stray", not stray)
    for s in stray[:6]:
        print(f"      stray: {s}")
    offC, ddr_wins, big = [], 0, 0
    k3off = []
    for r, t, M, ls, D, fT, fC in rows:
        tT = min(fT.values()) if fT else None
        tC = min(fC.values()) if fC else None
        dd = fC.get((2, 1, 0))
        pred = ddr_first(M, t, r)
        if pred != dd:
            k3off.append((r, t, M, pred, dd))
        cand = [v for v in (tT, dd) if v is not None]
        if tC != (min(cand) if cand else None):
            offC.append((r, t, M, tT, dd, tC))
        drp = fC.get((1, 1, 1))
        if drp != fT.get((1, 1, 0)):
            offC.append((r, t, M, "drp", drp, fT.get((1, 1, 0))))
        if ls >= 8:
            big += 1
            ddr_wins += dd is not None and (tT is None or dd < tT)
    good &= check(f"K3 the congruence's (d, d, r) first = the engine's at "
                  f"{len(rows) - len(k3off)} of {len(rows)} rows", not k3off)
    for x in k3off[:6]:
        print(f"      K3 off: {x}")
    good &= check(f"PC C's first = min(T's, (d, d, r)'s), its (d, r, p) "
                  f"first = T's (d, r): {len(offC)} rows off", not offC)
    for x in offC[:6]:
        print(f"      OFF C: {x}")
    print(f"PC (d, d, r) fires before T's first at {ddr_wins} of {big} rows "
          f"with L*_t >= 8")
    # PW: the paper's moduli by the transcription.
    for M, t, r, lmax in ((125, 8, 7, 60), (32749, 16, 15, 400),
                          (2147483629, 32, 31, 40000)):
        ls, h = law(M, t)
        w = witness(M, t, r, lmax)
        if not isinstance(w, tuple):
            good &= check(f"PW M {M}: no witness below {lmax} bits "
                          f"(L*_t = {ls}; least j {w})", False)
            continue
        L, X, i, j, l = w
        nb = L // 8
        data = to_bytes(X, nb)
        bad = to_bytes(X ^ (1 << i) ^ (1 << j), nb)
        res = {}
        for rd in ("C", "T"):
            c = koopman(data, M, t, rd)
            res[rd] = koopman(bad, M, t, rd) == c ^ (1 << (l + 1))
        ones = all(koopman(to_bytes(X ^ (1 << q), nb), M, t) !=
                   koopman(data, M, t) for q in range(L))
        good &= check(f"K4 M {M}: every 1-bit data error of the word "
                      f"caught: {ones}", ones)
        good &= check(f"PW M {M}: code misses a 3-bit error at L = {L} bits "
                      f"(L*_t = {ls}); data bits {i}, {j}, check bit "
                      f"{l + 1}; T misses it: {res['T']}",
                      res["C"] and not res["T"] and L <= ls)
        print(f"      the congruence's least j over i < j < {lmax}: {j}, so "
              f"the code holds HD = 4 to {j // 8} bytes, the text's "
              f"reading to {ls // 8}")
        good &= check(f"PW M {M}: (H) 2^(L*_t) >= m' holds: {h}, so the "
                      f"text's reading fails at {ls // 8 + 1} bytes", h)
    # The calls: least_miss against the witness above, a modulus with
    # no j below the cap, and the refusals.
    j, i, l, w = least_miss(32749, 16, 15, 400)
    x = int.from_bytes(w, "big") ^ (1 << i) ^ (1 << j)
    bad = x.to_bytes(len(w), "big")
    dC = koopman(bad, 32749, 16) ^ koopman(w, 32749, 16)
    dT = koopman(bad, 32749, 16, "T") ^ koopman(w, 32749, 16, "T")
    good &= check(f"CALLS least_miss(32749, 16, 15, 400): j {j}, i {i}, l "
                  f"{l}, {len(w)} bytes; the two data flips move the code's "
                  f"check by {dC}, the text's by {dT}",
                  (j, i, l, len(w), dC, dT) == (94, 65, 0, 12, 2, 3))
    none = least_miss(32749, 16, 15, 94)
    good &= check(f"CALLS least_miss(32749, 16, 15, 94), the cap at its j: "
                  f"{none}", none == (None, None, None, None))
    refused = [least_miss(32768, 16, 15, 400), least_miss(32749, 16, 14, 400),
               least_miss(32749, 14, 15, 400), least_miss(32749, 16, 15, 1),
               least_miss(32749, 16, 15, REACH + 1),
               least_miss(2 ** 32 - 5, 32, 32, 400),
               least_miss(32749.0, 16, 15, 400), koopman(b"", 125, 8),
               koopman([1, 2], 125, 8), koopman(7, 125, 8),
               koopman(b"ab", 128, 8),
               koopman(b"ab", 257, 8), koopman(b"ab", 125, 8, "X")]
    good &= check(f"CALLS refused outside the setting: "
                  f"{sum(q is None for q in refused)} of {len(refused)}",
                  all(q is None for q in refused))
    return 0 if good else 1


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