Expand description
§Integer-sequence description-length codec (the MDL primitive)
A pure, self-contained engine that describes an &[i64] by the shortest program in a fixed
menu of closed-form generators — affine (base + i·stride), geometric (base · ratioⁱ), a
degree-≤4 polynomial (finite-difference seeds), a periodic block, a sparse dominant-value form, a
sandboxed GenExpr generator, and the columnar fallbacks (delta, delta-of-delta,
frame-of-reference bit-pack, run-length, dictionary, raw byte column, plain zig-zag varint). Each
candidate is a complete self-delimiting byte string; consider keeps the smallest, so the
result is never larger than plain varint.
describe_int_seq is a computable upper bound on the Kolmogorov complexity of the sequence
over this description language, and decode_int_seq is its exact inverse — decode reproduces
the sequence bit-for-bit, so the encoded bytes are a re-checkable witness for that bound.
This is the same codec the wire layer (logicaffeine_compile’s marshal) uses for its
WireStructure::Auto int columns; it lives here in the leaf crate so both the wire codec and the
proof layer share one implementation of the format. The crate has no I/O and no receiver policy,
so the DoS bound (max_elements) is a parameter, supplied by each caller.
Structs§
- Annihilator
Witness - A re-checkable annihilator witness:
coeffsis the ANF (over [monomials](n_vars, degree)) of a nonzerogof degreedegreethat vanishes onC’s support (annihilates_complement = false) or onC’s zero-set (= true, i.e.gannihilatesC ⊕ 1). - Correlation
Attack - The certified result of a correlation attack on one target LFSR: the recovered initial state and the
statistical edge it carries. The
init_stateis a re-checkable witness — regenerate the LFSR from it and it reproduces the register the keystream leaks. - Gf2
- GF(2) — a single bit.
- Gf256
- GF(2⁸) — the Rijndael/AES field (reduction polynomial
x⁸+x⁴+x³+x²+1), one byte per element.
Enums§
- GenCmp
- GenExpr
- A restricted, pure, TOTAL expression over the element index
i. Every op is total (div/mod by zero is 0, wrapping i64 arithmetic), and a malformed/hostile tree is bounded at decode by a node budget + depth cap, so evaluation can never panic, diverge, overflow, or escape. - Poly
Solve Result - The outcome of an XL solve over GF(2).
Constants§
- MAX_
GEN_ DEPTH - …or this deep — bounds both decode recursion and eval.
- MAX_
GEN_ NODES - A hostile/garbage
GenExprtree is rejected past this many nodes. - MAX_
POLY_ DEGREE - The highest polynomial degree the generator detector will fit (degree 1 is the affine case).
- MAX_
RECUR_ ORDER - The highest constant-coefficient linear-recurrence order the detector will fit. Order 2 already covers Fibonacci / Lucas / Pell and any LFSR of that length (this is Berlekamp–Massey over ℤ).
- T_BYTES
- T_GEN
- T_INTS
- T_
INTS_ AFFINE - T_
INTS_ DELTA - T_
INTS_ DICT - T_
INTS_ DOD - T_
INTS_ FCSR - T_
INTS_ FOR - T_
INTS_ GEOMETRIC - T_
INTS_ LFSR - T_
INTS_ LRECUR - T_
INTS_ PERIODIC - T_
INTS_ POLY - T_
INTS_ RLE - T_
INTS_ SPARSE
Traits§
- Field
Elem - The minimal field interface Berlekamp–Massey needs.
Functions§
- algebraic_
complexity - The algebraic complexity of a bit sequence at maximal degree
max_degree: the smallest orderlfor whichdetect_algebraic_recurrencerecovers a degree-≤ max_degreefeedback, together with the ANF coefficient countM(the true description size —O(lᵈ), not the2^ltruth table).Noneif no order≤ bits.len()/2admits such a feedback at that degree. - algebraic_
degree - The algebraic degree of a Boolean function: the largest number of variables in any monomial present in
its ANF (0 for a constant, 1 for affine, up to
n).Nonefor a malformed table. - algebraic_
filter_ attack - Recover the initial state of a filter generator by the algebraic attack: a length-
lLFSR with feedbacktapsdrives a filterC(truth tablefilter_truthover itsm = log₂inputs, read asmCONSECUTIVE state bits), emittingkeystream[t] = C(seq[t], …, seq[t+m−1]). Using a min-degree annihilatorgofC, each applicable keystream bit becomesg(⟨r_t,s₀⟩, …) = 0, a degree-AIequation in the initial states₀; expanding overs₀-monomials of degree≤ AIand solving the GF(2) system recoverss₀. Returns thel-bit initial state (verified by regeneration), orNoneif there is no low-AI annihilator, the system is underdetermined, orl > 64. - algebraic_
generate - Replay a degree-
d, order-lalgebraic feedback register from ANF coefficients over [monomials](l, d)and anl-bit seed:s[i] = ⊕ₘ coeffsₘ · monomialₘ(s[i-1],…,s[i-l]). The inverse ofdetect_algebraic_recurrence. - algebraic_
immunity - The algebraic immunity of a Boolean function given as its
2ⁿtruth table: the minimum degree of a nonzero annihilator ofCor ofC ⊕ 1, together with a re-checkable witness. Searching degrees ascending, the first hit is the minimum (no lower-degree annihilator exists, or an earlier degree would have found it).Nonefor a malformed table.AI ≤ ⌈n/2⌉always. - anf
- The algebraic normal form (ANF) of a Boolean function: coefficients over the
2ⁿmonomials∏_{i∈S} xᵢ(S a variable bitmask), via the binary Möbius transform — the GF(2) dual of the Walsh–Hadamard butterfly, and its own inverse over GF(2) (applying it to the ANF returns the truth table).anf[S]istrueiff the monomial∏_{i∈S} xᵢis present.Nonefor a malformed table. - attack_
shrinking_ generator - Attack the shrinking generator: recover the initial states of both the clock register
A(feedbacka_taps) and the data registerS(feedbacks_taps) fromoutputalone, by divide-and-conquer on the clock. Each of the2^{L_A}clock states is tried; a guess fixes the emit positions, turning every output bit into a linear equation⟨r_{iₖ}, s₀⟩ = output[k]inS’s initial state, solved over GF(2) and verified by regeneration. Returns(a_state, s_state)for the first guess that reproduces the output, orNone(clock register too large —L_A > 22— or no consistent state). Exponential inL_Aonly, notL_A + L_S. - autocorrelation
- The autocorrelation spectrum of a Boolean function:
r_f(a) = Σ_x (−1)^{f(x) ⊕ f(x⊕a)}, the correlation offwith its shift bya. Computed by Wiener–Khinchin — the Walsh transform of the squared Walsh spectrum, scaled by2ⁿ— so it costs one extra butterfly overwalsh_spectrum.r_f(0) = 2ⁿalways;|r_f(a)| = 2ⁿexactly when the derivativef(x⊕a) ⊕ f(x)is CONSTANT — i.e.ais a linear structure.Nonefor a malformed table. - berlekamp_
massey_ field - Berlekamp–Massey over a field. Returns
(L, taps)whereLis the linear complexity andtapsare the connection-polynomial coefficientsc₁..c_L; the recurrence iss[i] = -Σⱼ c_{j+1}·s[i-1-j]. - berlekamp_
massey_ gf2 - Berlekamp–Massey over GF(2) — the shortest bit-LFSR. Thin wrapper over
berlekamp_massey_field(see it for the full semantics). For an LFSR keystreamLis the register length; for random ≈ n/2. - best_
linear_ approximation - The best linear approximation of a Boolean function: the mask
wmaximizing|Ŵ(w)|, with its bias|Pr[C(x)=⟨w,x⟩] − ½| = |Ŵ(w)| / 2^{n+1}. Whenskip_zero, the trivial constant maskw = 0(which measuresC’s own imbalance) is excluded. Returns(mask, bias), orNonefor a malformed table. - bitpack
- Pack
valsLSB-first atwidthbits each (1..=64). The inverse ofbitunpack. - bits_
to_ bytes - Pack an LSB-first bit sequence back into bytes (the inverse of
bytes_to_bits); a trailing partial group is zero-padded. - bitunpack
- Read
countLSB-firstwidth-bit values frombytes.Noneifbytesis too short. The inverse ofbitpack. - bytes_
to_ bits - Expand a byte column to its LSB-first bit sequence (bit
jof byteiis(byte_i >> j) & 1). - consider
- Keep
candif it is smaller than the currentbest— the MDL argmin over candidate encodings. - correlation_
attack - Siegenthaler’s basic correlation attack: recover the initial state of the length-
LLFSR with feedbacktapsthat best correlates withkeystream, by exhaustive search over the2^L − 1nonzero initial states (each scored by agreement with the keystream). Returns the best state with its bias — significant only whenbiasclearsspurious_bias_floor(L, n). CostO(2^L·n); returnsNonefor an empty register, a register longer than the keystream, orL > 20(past the exhaustive cap — the domain of the fast-correlation attack, its scaling successor). - correlation_
immunity_ order - The correlation-immunity order of a Boolean function (Xiao–Massey): the largest
msuch that every Walsh coefficient at a mask of Hamming weight1..=mvanishes. Order≥ 1⇒ IMMUNE to the first-order correlation attack (Rung E finds nothing) — yet a higher-weight coefficient may still leak, whichbest_linear_approximationsurfaces.Nonefor a malformed table. - decode_
int_ column_ body - Decode one int column whose tag byte has already been read as
tag. The inverse ofemit_best_int_column; returnsNonefor a non-int tag or a corrupt/hostile body.max_elementscaps generator expansion;depthbounds the periodic-block recursion. - decode_
int_ seq - Decode a full
describe_int_seqbyte string back to the exact sequence. Requires the whole buffer to be consumed (a clean round-trip witness). Uses a default element cap. - delta_
encode - Delta: first value then zig-zag successive differences. Wins on monotone columns.
- describe_
int_ seq - The computable upper bound on Kolmogorov complexity of
vover this description language: the shortest self-delimiting program (from the generator menu) that reproducesv. The returned bytes are a re-checkable witness —decode_int_seqreproducesvexactly. - deserialize_
gen - Parse a generator under a node
budgetanddepthcap — a garbage/hostile tree returnsNone. - detect_
affine - If
vis an exact affine progressionbase + stride·i, return(base, stride). - detect_
algebraic_ recurrence - Recover the algebraic normal form of a degree-
≤ d, order-lnonlinear feedback: the ANF coefficient vector over [monomials](l, d)such that replayings[i] = ⊕ₘ cₘ · monomialₘ(window)reproducesbitsexactly. ReturnsNoneif no such low-degree feedback fits (the GF(2) system is inconsistent, or the recovered coefficients fail to regenerate the sequence). This is the degree-dgeneralization ofberlekamp_massey_gf2(which is thed = 1case): it compresses low-degree nonlinear generators that fool the linear, 2-adic, and maximal-order tests. - detect_
geometric - If
vis an exact geometric progressionbase · ratioⁱ(≥3 elements, confirmed by replaying the decoder’s wrapping arithmetic), return(base, ratio). - detect_
linear_ recurrence - Recognize
vas a constant-coefficient linear recurrencev[i] = Σⱼ cⱼ·v[i-1-j]of minimal orderk ≤ [MAX_RECUR_ORDER]with integer coefficients, and return(coeffs, seeds)—kcoefficients + the firstkvalues. This is exactly Berlekamp–Massey over ℤ: it captures Fibonacci, Lucas, Pell, and any linear-feedback sequence — none of which the polynomial detector can reach (their finite differences never settle). The coefficients are solved exactly (Cramer overi128) from the smallest2kterms and then CONFIRMED by replaying the recurrence with the SAME wrapping arithmetic the decoder uses, so a match certifies a bit-exact reconstruction. - detect_
modular_ affine - Recognize
v[i] = a + b·(i mod p)for a small periodpand synthesize the generator. - detect_
period - If
vis an exact cyclic repetition of a minimal block of period2 ≤ p ≤ min(len/2, cap), returnp. - detect_
poly_ generator - Recognize
vas a polynomial column (degree ≤MAX_POLY_DEGREE) via finite differences and return(degree, seeds)— the k+1 leading-edge seeds, confirmed by exact reconstruction. - detect_
sparse - If one value dominates the column (covers ≥ ¾), return it and the sorted
(index, value)exceptions. - dict_
encode - Dictionary: distinct values (first-seen order) then a bit-packed index column. Wins on low-cardinality columns.
- dod_
encode - Delta-of-delta: first value, first delta, then zig-zag second differences. Wins on near-linear progressions (timestamps with jitter).
- emit_
best_ int_ column - Build every applicable column encoding and append the smallest to
out. The plain-varint baseline is always a candidate, so the result is never larger than the varint form. - fast_
correlation_ attack - Meier–Staffelbach fast correlation attack: recover the initial state of the length-
LLFSR with feedbacktapsfrom a noisy keystreamkeystream(az = a ⊕ noisebinary symmetric channel), by iterative bit-flip decoding against the low-weight parity checks the feedback recurrence and its Frobenius squares generate. Returns the recoveredL-bit initial state when decoding converges to a valid LFSR output that agrees with the keystream noticeably better than chance, elseNone(too much noise or too few low-weight checks — the register resists). Polynomial inL— no2^Lsearch. - fast_
walsh_ hadamard - The Walsh–Hadamard transform in place (the
±1butterfly), on a slice whose length is a power of 2.a[w]becomesΣₓ a[x]·(−1)^{⟨w,x⟩}. - fcsr_
generate - Generate
nbits of the FCSR keystream forp/q(qodd) — the 2-adic expansion, by repeated 2-adic division. The inverse oftwo_adic_reconstruct. - for_
encode - Frame-of-reference: subtract the column minimum, bit-pack the residuals. Wins on clustered columns (a small range around any base).
- gen_
eval - Evaluate a generator at index
i. TOTAL: div/mod by zero is 0; all arithmetic wraps. - leb128_
encode - The plain baseline column (
T_INTS): an adaptive-sign header ((n << 1) | signed) then a varint per element — zig-zag when any value is negative, plain LEB128 otherwise. - lfsr_
generate - Replay a GF(2) LFSR:
s[i] = ⊕ⱼ tapsⱼ · s[i-1-j]. The inverse ofberlekamp_massey_gf2. - lfsr_
generate_ field - Replay a field LFSR: emit
seed, thens[i] = -Σⱼ tapsⱼ·s[i-1-j](the connection recurrence). - maximal_
order_ complexity - The maximal order complexity (Jansen) of a bit sequence: the length of the shortest feedback
shift register — linear OR nonlinear — that generates it, i.e. the smallest
Lsuch that every length-Lwindow has a unique successor (s[i] = f(s[i-1],…,s[i-L])for some feedback functionf). It is the TOP of the FSR complexity hierarchy —MOC ≤ 2-adic complexityandMOC ≤ linear complexity— so it catches nonlinear generators (NFSRs, algebraic combiners with memory) that fool both Berlekamp–Massey and the 2-adic Rational Approximation. Low relative ton⇒ a short-register generator;≈ n/2for a random sequence. Consistency is monotone inL, so we binary-search it. - nonlinearity
- The nonlinearity of a Boolean function:
2^{n-1} − ½·maxₘ|Ŵ(w)|— its Hamming distance to the nearest affine function. High ⇒ resistant to linear approximation; maximal (bent,neven) ⇒2^{n-1} − 2^{n/2−1}.Nonefor a malformed table. - read_
uvarint - Read a LEB128 unsigned varint.
Noneon an overlong/overflowing encoding or a short buffer. - reconstruct_
poly - Replay a polynomial column from its finite-difference seeds via a difference engine.
- rle_
encode - Run-length: (value, run-length) pairs. Wins on columns of repeated runs.
- serialize_
gen - Serialize a generator pre-order: a 1-byte node tag, then children. Self-delimiting.
- shrinking_
generator - The shrinking generator: clock register
A(feedbacka_taps, seeda_seed) gates data registerS(feedbacks_taps, seeds_seed), emittingS’s bit exactly whenA’s bit is1, untilout_lenbits are produced. Its output is a data-dependent decimation ofSwith very high linear complexity. - solve_
polynomial_ system_ gf2 - Solve a Boolean polynomial system over GF(2) by XL (eXtended Linearization). Each equation is an
XOR of monomials (bitmasks over the
n_varsvariables,x²=x; mask0is the constant) that must be0. For each operating degreed = 1..=max_degree, every equation is multiplied by all monomials of degree≤ d − deg(eq), the enlarged system is linearized over the degree-≤ dmonomials (with the constant pinned to1) and solved: an inconsistency proves the system unsatisfiable (Refuted), a solution whose degree-1 part satisfies the original equations is returned (Solved), otherwise the degree is raised. This solves systems the plain degree-dlinearization cannot, and refutes ones it cannot see contradictory. - spurious_
bias_ floor - The spurious-bias floor: the expected maximum
|agreement − ½|when the best of2^register_lenuncorrelated states is chosen onnsamples —≈ √(L·ln2 / 2n), from the tail of the maximum of2^Lcentered binomials. A recoveredCorrelationAttack::biaswell above this floor is a genuine correlation (a certified combiner leak); at or below it, the register does not measurably leak. - two_
adic_ complexity - The 2-adic complexity of a bit sequence:
≈ log₂ max(|p|,|q|)for its FCSR rationalp/q. Low ⇒ a carry-based keystream (an FCSR / add-with-carry generator);≈ n/2for a random sequence. - two_
adic_ reconstruct - Rational reconstruction of a bit sequence as a 2-adic number. Returns
(p, q)withqodd and positive andp/q ≡ Σ sᵢ2ⁱ (mod 2ⁿ)— the shortest FCSR generating the sequence.Nonewhen no odd-denominator rational fits (an algorithmically-random sequence has no small FCSR). - unzigzag
- The inverse of
zigzag. - uvarint_
byte_ len - The number of bytes
write_uvarintwould emit forx. - verify_
annihilator - Re-check an
AnnihilatorWitnessagainst a truth table with zero trust in the producer: the witness is nonzero and vanishes on the required set (support ofC, or ofC ⊕ 1). Confirms the algebraic-immunity claim independently. - walsh_
spectrum - The Walsh spectrum of a Boolean function given as its
2ⁿ-entry truth table:Ŵ(w) = Σₓ (−1)^{C(x) ⊕ ⟨w,x⟩}, the signed correlation ofCwith every linear function⟨w,x⟩. Indexwis the linear mask (bitiselects variablei).Noneif the length is not a positive power of two. - write_
uvarint - LEB128 unsigned varint: 7 bits per byte, high bit = continuation.
- zigzag
- Map a signed integer to an unsigned one with small magnitudes near zero (for varint).