Skip to main content

logicaffeine_proof/
ait.rs

1//! # Algorithmic information theory — certified description-length objects
2//!
3//! The provers already *measure* algorithmic information (`hypercube::symmetry_entropy_bits` =
4//! log₂|Aut(F)|; the clause-orbit quotient as "the computable shadow of Kolmogorov complexity").
5//! This module promotes those measurements into **certified objects**: a description length that
6//! carries a re-checkable witness, so "this object compresses to N bytes" is something a checker
7//! confirms rather than trusts.
8//!
9//! Kolmogorov complexity `K(x)` is uncomputable, so we work with the two honest sides of it:
10//!
11//! - **Upper bounds** `K̄(x)` are computable — the shortest program in a *fixed* description language
12//!   that reproduces `x`. [`DescriptionBound`] carries such a program together with the bytes that,
13//!   when decoded, reproduce `x` (the witness). The description language is layered: [`Descriptor::IntSeq`]
14//!   is the closed-form generator menu of [`logicaffeine_base::describe`] (affine / geometric /
15//!   polynomial / periodic / sparse / …), a computable upper bound with a lossless decode witness.
16//!
17//! Lower bounds (the incompressibility side) and the two-sided structural bound live alongside this,
18//! gated by a budget so we never claim a bound past what the prover can itself re-check (the
19//! operational Chaitin ceiling).
20
21use logicaffeine_base::describe;
22
23use crate::cdcl::{Lit, Var};
24use crate::proof::Perm;
25use std::collections::BTreeSet;
26
27/// The description language. Each variant is a *program* in a fixed language whose length is the
28/// description bound and whose execution (decode) reproduces the object.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum Descriptor {
31    /// Layer 1: the closed-form generator menu of [`logicaffeine_base::describe`] applied to a raw
32    /// integer sequence. `encoded` is the shortest menu encoding; decoding it reproduces the sequence.
33    IntSeq { encoded: Vec<u8> },
34    /// Layer 3: a Boolean function described by its recursive symmetry decomposition ([`structure_tree`]).
35    /// Decoding replays the tree to reproduce the `2ⁿ` truth table.
36    BooleanFunction {
37        num_vars: usize,
38        tree: StructureTree,
39    },
40}
41
42/// A **computable upper bound** `K̄(x)` on the Kolmogorov complexity of an object `x`, over the fixed
43/// description language, carrying a re-checkable decode witness.
44///
45/// `bytes` is the program length (the bound). `object_hash` is a stable content hash of `x`.
46/// [`DescriptionBound::verify`] decodes the descriptor and confirms it reproduces `x` — an upper
47/// bound is only trustworthy because *decode(program) = x*.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct DescriptionBound {
50    /// A stable content hash of the described object (order- and value-sensitive).
51    pub object_hash: u64,
52    /// The description length in bytes — the certified upper bound `K̄(x)`.
53    pub bytes: usize,
54    /// The program (in the description language) that reproduces the object.
55    pub descriptor: Descriptor,
56}
57
58impl DescriptionBound {
59    /// Describe an integer sequence by its shortest generator-menu encoding (Layer 1). The result's
60    /// `bytes` is never larger than the plain-varint length of the sequence.
61    pub fn of_int_seq(v: &[i64]) -> DescriptionBound {
62        let encoded = describe::describe_int_seq(v);
63        DescriptionBound {
64            object_hash: hash_ints(v),
65            bytes: encoded.len(),
66            descriptor: Descriptor::IntSeq { encoded },
67        }
68    }
69
70    /// Describe a Boolean function by its recursive symmetry decomposition (Layer 3), the same certified
71    /// upper bound as [`kolmogorov_bound`] but inside the unified `DescriptionBound` framework. `bytes` is
72    /// the tree's total description size rounded up to bytes. `None` if `truth.len()` is not a power of two.
73    pub fn of_boolean(truth: &[bool]) -> Option<DescriptionBound> {
74        let num_vars = truth.len().trailing_zeros() as usize;
75        let tree = structure_tree(truth)?;
76        let bytes = tree.total_description_bits().div_ceil(8).max(1);
77        Some(DescriptionBound {
78            object_hash: hash_bools(truth),
79            bytes,
80            descriptor: Descriptor::BooleanFunction { num_vars, tree },
81        })
82    }
83
84    /// Re-check the decode witness: decode the descriptor and confirm it reproduces the object whose
85    /// hash we recorded. This is the whole point of an upper bound — it is trusted only because the
86    /// program actually reconstructs `x`. A tampered/corrupt descriptor fails here.
87    pub fn verify(&self) -> bool {
88        match &self.descriptor {
89            Descriptor::IntSeq { encoded } => {
90                encoded.len() == self.bytes
91                    && describe::decode_int_seq(encoded)
92                        .map_or(false, |v| hash_ints(&v) == self.object_hash)
93            }
94            Descriptor::BooleanFunction { num_vars, tree } => {
95                tree.total_description_bits().div_ceil(8).max(1) == self.bytes
96                    && tree.reconstruct().map_or(false, |t| {
97                        t.len() == (1usize << num_vars) && hash_bools(&t) == self.object_hash
98                    })
99            }
100        }
101    }
102}
103
104/// A stable content hash of a Boolean truth table (FNV-1a over the bits, salted by length).
105fn hash_bools(v: &[bool]) -> u64 {
106    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
107    const PRIME: u64 = 0x0000_0100_0000_01b3;
108    let mut h = OFFSET;
109    let mut mix = |b: u8| {
110        h ^= b as u64;
111        h = h.wrapping_mul(PRIME);
112    };
113    for b in (v.len() as u64).to_le_bytes() {
114        mix(b);
115    }
116    for &x in v {
117        mix(x as u8);
118    }
119    h
120}
121
122/// A stable, portable content hash (FNV-1a over the little-endian value bytes, salted by the count so
123/// a trailing zero can't alias a shorter sequence). Deterministic across runs and machines.
124fn hash_ints(v: &[i64]) -> u64 {
125    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
126    const PRIME: u64 = 0x0000_0100_0000_01b3;
127    let mut h = OFFSET;
128    let mut mix = |bytes: [u8; 8]| {
129        for b in bytes {
130            h ^= b as u64;
131            h = h.wrapping_mul(PRIME);
132        }
133    };
134    mix((v.len() as u64).to_le_bytes());
135    for &x in v {
136        mix(x.to_le_bytes());
137    }
138    h
139}
140
141// ---- The two-sided structural bound: K̄(F) ≤ K̄(rep) + K̄(gens) + O(1) -----------------------
142//
143// A formula with a large automorphism group is *compressible*: one representative clause per orbit,
144// plus the generators of the group, reconstructs the whole formula. This is the "symmetry = compression"
145// thesis made into a re-checkable certificate — `symmetry_entropy_bits` (log₂|Aut|) is exactly the bits
146// the group saves, and here that saving is realized as bytes and independently verified.
147
148/// The fixed byte cost of the group-expansion decoder ("take `rep`, apply the group generated by
149/// `gens`, output the union"). A documented constant so the inequality `K̄(F) ≤ K̄(rep) + K̄(gens) + O(1)`
150/// is concrete.
151pub const GROUP_DECODER_OVERHEAD: usize = 8;
152
153/// A certified statement that `F` is described by an orbit-representative set plus automorphism
154/// generators — with all three description lengths, the group-entropy, and a self-contained decode
155/// witness. [`StructuralBound::verify`] re-derives `F`, `rep`, and the generators from the three
156/// descriptors and confirms the generators are automorphisms and that expanding `rep` by the group
157/// they generate reproduces `F` exactly.
158#[derive(Clone, Debug)]
159pub struct StructuralBound {
160    /// The number of Boolean variables `F` is defined over.
161    pub num_vars: usize,
162    /// K̄(F): the flat description of the whole formula.
163    pub whole: DescriptionBound,
164    /// K̄(rep): the description of one clause per orbit.
165    pub rep: DescriptionBound,
166    /// K̄(gens): the description of the automorphism generators.
167    pub gens: DescriptionBound,
168    /// log₂|Aut(F)| — the bits of symmetry the group compresses out.
169    pub group_entropy_bits: f64,
170}
171
172impl StructuralBound {
173    /// The group description length: `K̄(rep) + K̄(gens) + O(1)`.
174    pub fn group_bytes(&self) -> usize {
175        self.rep.bytes + self.gens.bytes + GROUP_DECODER_OVERHEAD
176    }
177
178    /// Whether the group description is strictly shorter than the flat one — a *certified compression*
179    /// by symmetry. (When it is not, we honestly report the flat encoding as the better bound.)
180    pub fn is_compression(&self) -> bool {
181        self.group_bytes() < self.whole.bytes
182    }
183
184    /// The best certified upper bound on `K(F)`: the smaller of the flat and group descriptions.
185    pub fn best_bytes(&self) -> usize {
186        self.whole.bytes.min(self.group_bytes())
187    }
188
189    /// Re-check the whole certificate from scratch, trusting nothing the producer computed:
190    /// (1) all three decode witnesses round-trip; (2) every recovered generator is a genuine
191    /// automorphism of the recovered `F`; (3) expanding `rep` by the group the generators generate
192    /// reproduces `F` exactly (so `rep` + `gens` is a *complete* description).
193    pub fn verify(&self) -> bool {
194        // (1) all three decode witnesses round-trip.
195        if !(self.whole.verify() && self.rep.verify() && self.gens.verify()) {
196            return false;
197        }
198        // Recover F, rep, and the generators from the descriptors alone — trust nothing precomputed.
199        let (nv_f, f_clauses) = match decode_cnf(&self.whole.descriptor) {
200            Some(x) => x,
201            None => return false,
202        };
203        let (_, rep_clauses) = match decode_cnf(&self.rep.descriptor) {
204            Some(x) => x,
205            None => return false,
206        };
207        let (nv_g, gens) = match decode_gens(&self.gens.descriptor) {
208            Some(x) => x,
209            None => return false,
210        };
211        if nv_f != self.num_vars || nv_g != self.num_vars {
212            return false;
213        }
214        // (2) every recovered generator is a genuine automorphism of the recovered F.
215        if !gens
216            .iter()
217            .all(|p| crate::symmetry_detect::perm_is_automorphism(&f_clauses, p))
218        {
219            return false;
220        }
221        // (3) expanding rep by the group the generators generate reproduces F exactly.
222        reconstructs(&f_clauses, &rep_clauses, &gens)
223    }
224}
225
226/// Decode a CNF descriptor back to `(num_vars, clauses)` — `None` on a corrupt/tampered witness.
227fn decode_cnf(d: &Descriptor) -> Option<(usize, Vec<Vec<Lit>>)> {
228    let Descriptor::IntSeq { encoded } = d else {
229        return None;
230    };
231    unflatten_cnf(&describe::decode_int_seq(encoded)?)
232}
233
234/// Decode a generator descriptor back to `(num_vars, generators)` — `None` on a corrupt/tampered witness.
235fn decode_gens(d: &Descriptor) -> Option<(usize, Vec<Perm>)> {
236    let Descriptor::IntSeq { encoded } = d else {
237        return None;
238    };
239    unflatten_gens(&describe::decode_int_seq(encoded)?)
240}
241
242/// Build the structural bound for `F` under a set of candidate `generators`. Returns `None` if any
243/// generator is not an automorphism, or if `rep` + generators does not reconstruct `F` (so we never
244/// issue a certificate we could not re-check).
245pub fn structural_bound(
246    num_vars: usize,
247    clauses: &[Vec<Lit>],
248    generators: &[Perm],
249) -> Option<StructuralBound> {
250    if !generators
251        .iter()
252        .all(|g| crate::symmetry_detect::perm_is_automorphism(clauses, g))
253    {
254        return None;
255    }
256    let orbits = crate::hypercube::clause_orbits(clauses, generators);
257    let rep_clauses: Vec<Vec<Lit>> = orbits
258        .iter()
259        .filter_map(|o| o.first().map(|&i| clauses[i].clone()))
260        .collect();
261    // The representative set plus the group must reconstruct the whole formula.
262    if !reconstructs(clauses, &rep_clauses, generators) {
263        return None;
264    }
265    Some(StructuralBound {
266        num_vars,
267        whole: DescriptionBound::of_int_seq(&flatten_cnf(num_vars, clauses)),
268        rep: DescriptionBound::of_int_seq(&flatten_cnf(num_vars, &rep_clauses)),
269        gens: DescriptionBound::of_int_seq(&flatten_gens(num_vars, generators)),
270        group_entropy_bits: crate::hypercube::symmetry_entropy_bits(num_vars, clauses),
271    })
272}
273
274/// Whether `rep_clauses` plus the group generated by `gens` reconstructs `f_clauses` exactly — checked
275/// WITHOUT enumerating the (astronomically large) group. The caller has verified `f_clauses` is closed
276/// under each generator (`perm_is_automorphism`), so `group·rep ⊆ F` follows from `rep ⊆ F`, and
277/// `F ⊆ group·rep` holds iff every orbit of F under the generators contains a rep clause (any F clause
278/// shares an orbit — hence a group element — with the rep of that orbit).
279fn reconstructs(f_clauses: &[Vec<Lit>], rep_clauses: &[Vec<Lit>], gens: &[Perm]) -> bool {
280    let f_keys = clause_set(f_clauses);
281    let rep_keys = clause_set(rep_clauses);
282    if !rep_keys.is_subset(&f_keys) {
283        return false; // rep must be clauses of F
284    }
285    let orbits = crate::hypercube::clause_orbits(f_clauses, gens);
286    orbits.iter().all(|orbit| {
287        orbit
288            .iter()
289            .any(|&i| rep_keys.contains(&crate::symmetry_detect::clause_key(&f_clauses[i])))
290    })
291}
292
293/// The set of canonical clause keys — order- and literal-order-independent, so two formulas compare
294/// equal iff they are the same clause set.
295fn clause_set(clauses: &[Vec<Lit>]) -> BTreeSet<Vec<u32>> {
296    clauses
297        .iter()
298        .map(|c| crate::symmetry_detect::clause_key(c))
299        .collect()
300}
301
302/// Encode a literal as `2·var + sign` (0 = positive), the dense non-negative code.
303fn lit_code(l: Lit) -> i64 {
304    (l.var() as i64) * 2 + if l.is_positive() { 0 } else { 1 }
305}
306
307/// The inverse of [`lit_code`]. `None` on a negative/garbage code (a tampered descriptor).
308fn lit_from_code(code: i64) -> Option<Lit> {
309    if code < 0 {
310        return None;
311    }
312    Some(Lit::new((code / 2) as Var, code % 2 == 0))
313}
314
315/// Flatten a CNF to `[num_vars, num_clauses, len₀, lit₀₀, …, len₁, …]` for description.
316fn flatten_cnf(num_vars: usize, clauses: &[Vec<Lit>]) -> Vec<i64> {
317    let mut out = vec![num_vars as i64, clauses.len() as i64];
318    for c in clauses {
319        out.push(c.len() as i64);
320        for &l in c {
321            out.push(lit_code(l));
322        }
323    }
324    out
325}
326
327/// The inverse of [`flatten_cnf`]. `None` on a malformed/tampered sequence.
328fn unflatten_cnf(flat: &[i64]) -> Option<(usize, Vec<Vec<Lit>>)> {
329    let mut it = flat.iter().copied();
330    let num_vars = usize::try_from(it.next()?).ok()?;
331    let num_clauses = usize::try_from(it.next()?).ok()?;
332    let mut clauses = Vec::with_capacity(num_clauses.min(4096));
333    for _ in 0..num_clauses {
334        let len = usize::try_from(it.next()?).ok()?;
335        let mut c = Vec::with_capacity(len.min(4096));
336        for _ in 0..len {
337            c.push(lit_from_code(it.next()?)?);
338        }
339        clauses.push(c);
340    }
341    if it.next().is_some() {
342        return None; // trailing garbage
343    }
344    Some((num_vars, clauses))
345}
346
347/// Flatten generators to `[num_gens, num_vars, σ₀(+0), σ₀(+1), …, σ₁(+0), …]` for description.
348fn flatten_gens(num_vars: usize, gens: &[Perm]) -> Vec<i64> {
349    let mut out = vec![gens.len() as i64, num_vars as i64];
350    for g in gens {
351        for v in 0..num_vars {
352            out.push(lit_code(g.apply(Lit::pos(v as Var))));
353        }
354    }
355    out
356}
357
358/// The inverse of [`flatten_gens`]. `None` on a malformed/tampered sequence.
359fn unflatten_gens(flat: &[i64]) -> Option<(usize, Vec<Perm>)> {
360    let mut it = flat.iter().copied();
361    let num_gens = usize::try_from(it.next()?).ok()?;
362    let num_vars = usize::try_from(it.next()?).ok()?;
363    let mut gens = Vec::with_capacity(num_gens.min(4096));
364    for _ in 0..num_gens {
365        let mut images = Vec::with_capacity(num_vars.min(4096));
366        for _ in 0..num_vars {
367            images.push(lit_from_code(it.next()?)?);
368        }
369        gens.push(Perm::from_images(images));
370    }
371    if it.next().is_some() {
372        return None;
373    }
374    Some((num_vars, gens))
375}
376
377// ---- Class-relative incompressibility: "no linear (GF(2)) symmetry shortcut" -----------------
378//
379// A formula's parity (GF(2)) structure is *exactly* characterized by the rank and null space of the
380// XOR system latent in its clauses. When that structure is fully exposed — every parity constraint
381// recovered, the solution space pinned to exactly 2^k over the k-dimensional kernel — there is no
382// further LINEAR collapse to find: any residual hardness is non-linear. This turns the par32-style
383// "linearly-rigid kernel" *measurement* into a re-checkable *certificate*, class-relative to the
384// linear/parity class 𝒟 (an exact claim, no appeal to uncomputable universal K).
385
386/// The maximum variable count for which we ship an explicit GF(2) kernel basis (the strongest
387/// witness): `gf2::solve_gf2` packs each row into a `u64`. Larger systems (par32-scale) are a
388/// documented follow-on requiring incremental kernel-basis extraction from [`crate::xor_engine`].
389const RIGIDITY_MAX_VARS: usize = 64;
390
391/// The prover's own description budget — **the operational Chaitin ceiling.** Kolmogorov complexity
392/// lower bounds are only certifiable up to what the prover can itself re-check; beyond a resource
393/// bound we decline rather than over-claim. Every *lower-bound* (incompressibility) path is gated by
394/// a `Budget` and returns a documented [`Refusal`] instead of a certificate when a bound is exceeded.
395/// (Upper bounds — [`DescriptionBound`] — are always safe to compute: you can only be pleasantly
396/// surprised by a shorter description.)
397#[derive(Clone, Copy, Debug)]
398pub struct Budget {
399    /// The largest GF(2) system (in variables) whose kernel basis we will materialize and re-check.
400    pub max_gaussian_dim: usize,
401}
402
403impl Budget {
404    /// The standard budget: caps the GF(2) kernel-basis materialization at `RIGIDITY_MAX_VARS`.
405    pub fn standard() -> Budget {
406        Budget {
407            max_gaussian_dim: RIGIDITY_MAX_VARS,
408        }
409    }
410}
411
412/// Why a lower-bound certificate was **not** issued — the documented refusal that makes the Chaitin
413/// ceiling operational. A refusal is never a claim that no bound exists; it is an honest "this is
414/// beyond what I can re-check within budget."
415#[derive(Clone, Debug, PartialEq, Eq)]
416pub enum Refusal {
417    /// The GF(2) system exceeds the budget's variable cap (par32-scale needs the incremental engine).
418    OverBudgetGaussian { dim: usize, cap: usize },
419    /// There is no linear (parity) structure in the formula to certify rigid.
420    NoLinearStructure,
421}
422
423/// A re-checkable certificate that `F`'s parity structure admits no linear symmetry shortcut beyond
424/// its exposed kernel: the GF(2) coefficient system has rank `rank`, its solution space is exactly
425/// `2^solution_count_log2` (spanned by `kernel_basis`), and this is the complete linear structure.
426#[derive(Clone, Debug, PartialEq, Eq)]
427pub struct LinearRigidityCert {
428    /// The number of Boolean variables `F` is over.
429    pub num_vars: usize,
430    /// The GF(2) coefficient rows recovered from `F` — bit `v` set iff variable `v` occurs in that
431    /// parity equation (the right-hand side is irrelevant to the linear structure).
432    pub rows: Vec<u64>,
433    /// The rank of the coefficient system — the number of independent parity constraints.
434    pub rank: usize,
435    /// A basis for the null space (the linear symmetry directions). Exactly `num_vars − rank` vectors.
436    pub kernel_basis: Vec<Vec<bool>>,
437    /// `log₂` of the number of GF(2) solutions — `= kernel_basis.len()`.
438    pub solution_count_log2: u32,
439}
440
441/// Certify the linear (GF(2)) rigidity of `F` under the standard budget — `None` on any refusal
442/// (no parity structure, or over budget). See [`certify_linear_rigidity_within`] for the documented
443/// refusal.
444pub fn certify_linear_rigidity(
445    num_vars: usize,
446    clauses: &[Vec<Lit>],
447) -> Option<LinearRigidityCert> {
448    certify_linear_rigidity_within(num_vars, clauses, &Budget::standard()).ok()
449}
450
451/// Certify the linear (GF(2)) rigidity of `F`, failing **closed** to `budget`: a system that exceeds
452/// the budget's Gaussian cap returns [`Refusal::OverBudgetGaussian`] — the operational Chaitin
453/// ceiling — rather than a certificate we could not re-check.
454pub fn certify_linear_rigidity_within(
455    num_vars: usize,
456    clauses: &[Vec<Lit>],
457    budget: &Budget,
458) -> Result<LinearRigidityCert, Refusal> {
459    if num_vars > budget.max_gaussian_dim {
460        return Err(Refusal::OverBudgetGaussian {
461            dim: num_vars,
462            cap: budget.max_gaussian_dim,
463        });
464    }
465    let eqs = crate::lyapunov::extract_xor(num_vars, clauses);
466    if eqs.is_empty() {
467        return Err(Refusal::NoLinearStructure);
468    }
469    let rows = eqs_to_rows(&eqs, num_vars);
470    let sol = crate::gf2::solve_gf2(num_vars, &rows, &vec![false; rows.len()])
471        .ok_or(Refusal::NoLinearStructure)?;
472    let rank = num_vars - sol.kernel_basis.len();
473    Ok(LinearRigidityCert {
474        num_vars,
475        rows,
476        rank,
477        solution_count_log2: sol.kernel_basis.len() as u32,
478        kernel_basis: sol.kernel_basis,
479    })
480}
481
482/// Re-check a [`LinearRigidityCert`] against `F`, trusting nothing the producer computed: re-extract
483/// the parity system, independently recompute its kernel, and confirm the certificate's basis is a
484/// genuine, independent, complete null-space of the recovered rows.
485pub fn check_linear_rigidity(cert: &LinearRigidityCert, clauses: &[Vec<Lit>]) -> bool {
486    if cert.num_vars > RIGIDITY_MAX_VARS {
487        return false;
488    }
489    // Re-extract the parity system straight from the clauses.
490    let eqs = crate::lyapunov::extract_xor(cert.num_vars, clauses);
491    if eqs.is_empty() {
492        return false;
493    }
494    let rows = eqs_to_rows(&eqs, cert.num_vars);
495    // The recovered coefficient rows must match the certificate's.
496    let recovered: BTreeSet<u64> = rows.iter().copied().collect();
497    let claimed: BTreeSet<u64> = cert.rows.iter().copied().collect();
498    if recovered != claimed {
499        return false;
500    }
501    // Independently recompute the true rank / kernel dimension from the recovered rows.
502    let sol = match crate::gf2::solve_gf2(cert.num_vars, &rows, &vec![false; rows.len()]) {
503        Some(s) => s,
504        None => return false,
505    };
506    let true_kernel_dim = sol.kernel_basis.len();
507    if cert.rank != cert.num_vars - true_kernel_dim
508        || cert.solution_count_log2 as usize != true_kernel_dim
509        || cert.kernel_basis.len() != true_kernel_dim
510    {
511        return false;
512    }
513    // Every certificate basis vector must be a genuine homogeneous solution (rows·v = 0)…
514    for v in &cert.kernel_basis {
515        if v.len() != cert.num_vars || rows.iter().any(|&row| gf2_dot(row, v)) {
516            return false;
517        }
518    }
519    // …and the basis must be linearly independent (hence a complete null-space by its dimension).
520    independent_gf2(&cert.kernel_basis)
521}
522
523/// The par32-scale linear-structure certificate: the GF(2) rank and kernel dimension of `F`'s parity
524/// system, valid for **any** number of variables (beyond the `u64` cap of [`LinearRigidityCert`]).
525/// It carries no explicit kernel basis — at this scale the witness is *recomputation*: re-extract the
526/// parity system, re-reduce it, and confirm the same rank and kernel dimension. This is the object
527/// par32's "157-dim linearly-rigid kernel" measurement becomes.
528#[derive(Clone, Debug, PartialEq, Eq)]
529pub struct LinearStructureCert {
530    /// The number of Boolean variables `F` is over.
531    pub num_vars: usize,
532    /// The number of XOR (parity) equations recovered from `F`.
533    pub num_xor_eqs: usize,
534    /// The rank of the GF(2) system (independent parity constraints), from RREF reduction.
535    pub rank: usize,
536    /// The dimension of the linear choice space — the free variables occurring in the reduced matrix.
537    pub kernel_dim: usize,
538}
539
540/// Certify the GF(2) linear structure of `F` at any scale via the incremental engine, or `None` if
541/// there is no parity structure to characterize.
542pub fn certify_linear_structure(
543    num_vars: usize,
544    clauses: &[Vec<Lit>],
545) -> Option<LinearStructureCert> {
546    let eqs = crate::lyapunov::extract_xor(num_vars, clauses);
547    if eqs.is_empty() {
548        return None;
549    }
550    let inc = crate::xor_engine::IncXor::new(num_vars, &eqs);
551    Some(LinearStructureCert {
552        num_vars,
553        num_xor_eqs: eqs.len(),
554        rank: inc.rank(),
555        kernel_dim: inc.kernel_dim(),
556    })
557}
558
559/// Re-check a [`LinearStructureCert`] by re-extracting `F`'s parity system, re-reducing it, and
560/// confirming the certificate's rank, kernel dimension, and equation count are exactly reproduced.
561pub fn check_linear_structure(cert: &LinearStructureCert, clauses: &[Vec<Lit>]) -> bool {
562    let eqs = crate::lyapunov::extract_xor(cert.num_vars, clauses);
563    if eqs.len() != cert.num_xor_eqs {
564        return false;
565    }
566    let inc = crate::xor_engine::IncXor::new(cert.num_vars, &eqs);
567    inc.rank() == cert.rank && inc.kernel_dim() == cert.kernel_dim
568}
569
570/// The honest verdict on whether `F` admits a **linear (GF(2)) symmetry shortcut** — the certified,
571/// re-checkable "no shortcut of this class" answer the dispatcher and diagnostics can report instead
572/// of silently spinning a symmetry search. Class-relative (linear/parity), with the Chaitin ceiling
573/// as the documented frame: we certify the linear structure exactly, never claim an absolute bound.
574#[derive(Clone, Debug)]
575pub enum LinearShortcut {
576    /// `F`'s parity structure is fully exposed and rigid — no linear shortcut beyond the certified
577    /// `2^kernel_dim` solution space. The strongest available witness is attached: an explicit kernel
578    /// basis ([`LinearRigidityCert`]) when the system fits the `u64` budget, always the incremental
579    /// dimensions ([`LinearStructureCert`]).
580    None {
581        rigidity: Option<LinearRigidityCert>,
582        structure: LinearStructureCert,
583    },
584    /// `F` carries no parity structure at all — the linear class offers no leverage (and nothing to
585    /// break), so a linear-symmetry search would find nothing.
586    NoLinearStructure,
587}
588
589/// Decide the linear-shortcut verdict for `F` (fail-closed via [`certify_linear_structure`]).
590pub fn linear_shortcut_verdict(num_vars: usize, clauses: &[Vec<Lit>]) -> LinearShortcut {
591    match certify_linear_structure(num_vars, clauses) {
592        None => LinearShortcut::NoLinearStructure,
593        Some(structure) => {
594            let rigidity = certify_linear_rigidity(num_vars, clauses);
595            LinearShortcut::None {
596                rigidity,
597                structure,
598            }
599        }
600    }
601}
602
603/// The variable cap for the exact rigidity check in [`incompressibility_gate`]: the automorphism search
604/// is superpolynomial, so past this size the gate declines (conservative) rather than pay for it.
605const GATE_SYMMETRY_MAX_VARS: usize = 48;
606
607/// The SAT-dispatcher gate: `Some(cert)` iff `F`'s parity structure is fully exposed AND `F` is provably
608/// rigid (`|Aut| = 1`), so the symmetry arsenal is **provably useless** and the solver may go straight to
609/// CDCL with an honest "no shortcut of this class" verdict. The exact rigidity check
610/// (`symmetry_entropy_bits == 0`) is size-gated — past `GATE_SYMMETRY_MAX_VARS` the gate declines rather
611/// than run the superpolynomial automorphism search (there is no cheap sound global-asymmetry test; it is
612/// graph-isomorphism-hard). Fail-closed throughout: any doubt returns `None` and the arsenal runs as usual.
613pub fn incompressibility_gate(
614    num_vars: usize,
615    clauses: &[Vec<Lit>],
616) -> Option<LinearStructureCert> {
617    let structure = certify_linear_structure(num_vars, clauses)?;
618    if num_vars > GATE_SYMMETRY_MAX_VARS {
619        return None; // conservative: the exact rigidity check would be too expensive at this size
620    }
621    if crate::hypercube::symmetry_entropy_bits(num_vars, clauses) == 0.0 {
622        Some(structure) // linear structure + |Aut| = 1 ⇒ genuinely no symmetry shortcut
623    } else {
624        None
625    }
626}
627
628/// Pack each XOR equation's variable set into a `u64` coefficient row.
629fn eqs_to_rows(eqs: &[crate::xorsat::XorEquation], num_vars: usize) -> Vec<u64> {
630    eqs.iter()
631        .map(|e| {
632            e.vars
633                .iter()
634                .filter(|&&v| v < num_vars.min(64))
635                .fold(0u64, |m, &v| m | (1u64 << v))
636        })
637        .collect()
638}
639
640/// GF(2) dot product of a coefficient row (bitmask) with a solution vector: the parity of the
641/// selected entries.
642fn gf2_dot(row: u64, v: &[bool]) -> bool {
643    let mut acc = false;
644    let mut r = row;
645    while r != 0 {
646        let i = r.trailing_zeros() as usize;
647        if i < v.len() {
648            acc ^= v[i];
649        }
650        r &= r - 1;
651    }
652    acc
653}
654
655// ---- The incompressibility lemma (the lower-bound / "prove" direction) ----------------------
656//
657// The counting core of algorithmic information theory: over a binary alphabet there are `2ⁿ` strings
658// of length `n` but only `Σ_{i<n} 2ⁱ = 2ⁿ − 1` programs *shorter* than `n`. Fewer descriptions than
659// objects ⇒ by pigeonhole at least one length-`n` string has no shorter program: it is incompressible,
660// `K(x) ≥ n`. This is a *lower* bound proved by a shortage of descriptions — the incompressibility
661// method — and it is certified by the very same `O(1)` pigeonhole engine the SAT side already trusts.
662
663/// The **incompressibility lemma** for length `n`, as a re-checkable counting certificate: `2ⁿ`
664/// strings (pigeons) against `2ⁿ − 1` shorter programs (holes) ⇒ an incompressible string exists.
665/// `None` only when `n` is out of the exact-`u128` range (`1 ≤ n ≤ 127`). Re-check with
666/// [`crate::pigeonhole::check_counting_cert`].
667pub fn incompressible_string_exists(n: u32) -> Option<crate::pigeonhole::CountingCert> {
668    if n == 0 || n > 127 {
669        return None; // n=0 is the trivial K(ε) ≥ 0; beyond 127, 2ⁿ overflows u128
670    }
671    let strings: u128 = 1u128 << n;
672    let shorter_programs: u128 = strings - 1; // 2⁰ + … + 2ⁿ⁻¹ = 2ⁿ − 1
673    crate::pigeonhole::certify_pigeonhole_unsat(strings, shorter_programs)
674}
675
676/// A kernel-re-checkable counting certificate that an incompressible Boolean function on `n` variables MUST
677/// exist. A function is its `2ⁿ`-bit truth table, and there are only `2^{2ⁿ} − 1` programs shorter than
678/// `2ⁿ` bits — too few to name all `2^{2ⁿ}` functions — so at least one has no shorter description. This is
679/// the certified REASON the census residue is nonempty: [`boolean_function_census`] measures it, counting
680/// guarantees it. Any such function necessarily sits in the residue (no arsenal compresses the truly
681/// incompressible). `None` for `n = 0` or `n > 6` (a `2⁷`-bit truth table overflows the exact-`u128`
682/// counting range). Re-check with [`crate::pigeonhole::check_counting_cert`].
683pub fn certified_incompressible_function_exists(n: u32) -> Option<crate::pigeonhole::CountingCert> {
684    if n == 0 || n > 6 {
685        return None;
686    }
687    incompressible_string_exists(1u32 << n)
688}
689
690// ---- Incompressibility as a cryptographic diagnostic ----------------------------------------
691//
692// A key or ciphertext must be *incompressible*: if the description engine finds a shorter program
693// for it, THAT program is the attack — a short description means the data is predictable (low
694// Kolmogorov complexity). This is the algorithmic-information view of "looks random". It is honest
695// and one-sided: by the Chaitin ceiling we can certify WEAKNESS (exhibit a compression witness that
696// re-decodes to the data) but never absolute strength — incompressibility here is NECESSARY for a
697// secure key/ciphertext, not sufficient, and only relative to this fixed generator class. (Finding
698// the shortest *linear* recurrence is exactly the classic LFSR / Berlekamp–Massey attack.)
699
700/// The algorithmic-information verdict on key or ciphertext material (a byte string).
701#[derive(Clone, Debug)]
702pub enum CryptoStrength {
703    /// A description shorter than the raw bytes exists — a **certified structural weakness**. `witness`
704    /// decodes back to the data (the concrete attack), and `ratio` = K̄/n < 1 quantifies predictability.
705    Weak {
706        witness: DescriptionBound,
707        ratio: f64,
708    },
709    /// No description beats storing the raw bytes — incompressible relative to the engine's generator
710    /// class. A necessary (not sufficient) condition for cryptographic randomness; no weakness of this
711    /// class. (`ratio ≥ 1`.)
712    IncompressibleInClass { ratio: f64 },
713}
714
715/// The incompressibility ratio `K̄(x)/n` for an `n`-byte string — the shortest menu description
716/// measured against storing the bytes raw (the incompressible size for byte material). ≈ 1.0 ⇒
717/// incompressible (no exploitable structure of this class); well below 1.0 ⇒ compressible (a short,
718/// predictable description exists).
719pub fn incompressibility_ratio(data: &[u8]) -> f64 {
720    if data.is_empty() {
721        return 1.0;
722    }
723    let ints: Vec<i64> = data.iter().map(|&b| b as i64).collect();
724    describe::describe_int_seq(&ints).len() as f64 / data.len() as f64
725}
726
727/// The **GF(2⁸) word linear complexity** of a byte string — the length of the shortest *byte-oriented*
728/// (GF(256)) LFSR that generates it, via Berlekamp–Massey over the AES field. The word analogue of the
729/// bit linear complexity: low relative to `n/2` ⇒ a word-LFSR keystream, a certified weakness. (Runs in
730/// `O(n²)` byte-ops — 64× fewer than the bit-level BM on the same data.)
731pub fn gf256_word_complexity(data: &[u8]) -> usize {
732    let elems: Vec<describe::Gf256> = data.iter().map(|&b| describe::Gf256(b)).collect();
733    describe::berlekamp_massey_field(&elems).0
734}
735
736/// The **2-adic complexity** of a byte string (its LSB-first bit expansion) — the size of the shortest
737/// FCSR (feedback-with-carry / add-with-carry) generating it. Low relative to the bit count ⇒ a
738/// carry-based keystream that **fools every linear-complexity test** (Berlekamp–Massey over any field
739/// sees high complexity; the carry is nonlinear over GF(2)). The certified weakness the linear tools miss.
740pub fn two_adic_complexity_of_bytes(data: &[u8]) -> usize {
741    let bits: Vec<bool> = data
742        .iter()
743        .flat_map(|&b| (0..8).map(move |j| (b >> j) & 1 == 1))
744        .collect();
745    describe::two_adic_complexity(&bits)
746}
747
748/// The **maximal order complexity** of a byte string (its LSB-first bit expansion) — the length of the
749/// shortest feedback register, LINEAR OR NONLINEAR, generating it. The TOP of the FSR hierarchy: it
750/// catches nonlinear generators (NFSRs, algebraic combiners) that fool every linear-complexity measure.
751/// Low relative to the bit count ⇒ a short-register generator. This is the last cheap rung — a general
752/// nonlinear feedback function is a full truth table (as large as the data), so a low MOC is a certified
753/// STRUCTURAL weakness (a short register exists) even though recovering its *sparse* form is the (hard)
754/// algebraic attack. For a real cipher MOC `≈ n/2`: the incompressible residue, the Chaitin ceiling.
755pub fn maximal_order_complexity_of_bytes(data: &[u8]) -> usize {
756    let bits: Vec<bool> = data
757        .iter()
758        .flat_map(|&b| (0..8).map(move |j| (b >> j) & 1 == 1))
759        .collect();
760    describe::maximal_order_complexity(&bits)
761}
762
763/// The certified result of an **algebraic-recurrence attack**: a low-degree nonlinear feedback register
764/// that regenerates a byte string, recovered by [`describe::detect_algebraic_recurrence`]. This is the
765/// OPEN rung — where maximal order complexity can only *measure* a nonlinear register (its `2^order`
766/// truth table), the algebraic attack *recovers* it as a sparse ANF and thereby *compresses* it, when
767/// the feedback has low degree. The `anf` is a re-checkable witness (replay it with the seed).
768#[derive(Clone, Debug, PartialEq, Eq)]
769pub struct AlgebraicAttack {
770    /// The register length `L` — how many past bits the feedback reads.
771    pub order: usize,
772    /// The ANF degree bound `d` the recovery used.
773    pub degree: usize,
774    /// The number of active ANF coefficients — the description size, `O(Lᵈ)`.
775    pub anf_terms: usize,
776    /// The recovered ANF over `monomials(order, degree)` — the witness (`algebraic_generate` replays it).
777    pub anf: Vec<bool>,
778    /// `2^order` — the truth-table size maximal order complexity would need for the same register.
779    pub truth_table: usize,
780}
781
782/// Run the algebraic attack on `data` (its LSB-first bit expansion) at maximal ANF degree `max_degree`,
783/// searching register orders `1..=max_order`: return the shortest low-degree nonlinear feedback that
784/// regenerates the whole bit stream, with its sparse ANF. `None` when no degree-≤`max_degree` register
785/// up to `max_order` fits — the genuine high-degree / incompressible residue (a real cipher's keystream,
786/// the Chaitin ceiling). `max_order` bounds the cost: the solve is `O(rows · M²/64)` with `M = O(Lᵈ)`.
787pub fn algebraic_attack_on_bytes(
788    data: &[u8],
789    max_degree: usize,
790    max_order: usize,
791) -> Option<AlgebraicAttack> {
792    let bits: Vec<bool> = data
793        .iter()
794        .flat_map(|&b| (0..8).map(move |j| (b >> j) & 1 == 1))
795        .collect();
796    let cap = max_order.min(bits.len() / 2);
797    for l in 1..=cap {
798        if let Some(anf) = describe::detect_algebraic_recurrence(&bits, l, max_degree) {
799            return Some(AlgebraicAttack {
800                order: l,
801                degree: max_degree,
802                anf_terms: anf.iter().filter(|&&c| c).count().max(1),
803                anf,
804                truth_table: 1usize.checked_shl(l as u32).unwrap_or(usize::MAX),
805            });
806        }
807    }
808    None
809}
810
811/// A certified **combiner leak**: one candidate LFSR that a keystream measurably correlates with,
812/// recovered by [`describe::correlation_attack`]. The `attack.init_state` is the re-checkable witness.
813#[derive(Clone, Debug, PartialEq)]
814pub struct CombinerLeak {
815    /// Index into the candidate menu of the leaking register.
816    pub candidate_index: usize,
817    /// The recovered register (initial state + correlation edge).
818    pub attack: describe::CorrelationAttack,
819    /// The spurious-bias floor for this register length and sample count.
820    pub floor: f64,
821    /// `bias / floor` — how far above the noise the correlation sits (the significance).
822    pub margin: f64,
823}
824
825/// Scan a byte keystream against a menu of candidate LFSR feedback tap-sets: return every register the
826/// keystream correlates with beyond `significance ×` the spurious floor. Each hit is a certified break of
827/// a nonlinear **combiner** generator — a HIDDEN constituent register recovered *independently*
828/// (Siegenthaler divide-and-conquer), collapsing a `2^(Σ Lⱼ)` search to `Σ 2^Lⱼ`. This reaches the
829/// combiners the algebraic-recurrence rung structurally cannot (their output is a function of the hidden
830/// register outputs, not of the keystream's own past). Empty ⇒ no first-order correlation with any
831/// candidate: correlation-immune, or not this combiner — the ceiling, where higher-order and
832/// fast-correlation attacks take over.
833pub fn scan_for_combiner_leaks(
834    keystream: &[u8],
835    candidates: &[Vec<bool>],
836    significance: f64,
837) -> Vec<CombinerLeak> {
838    let bits: Vec<bool> = keystream
839        .iter()
840        .flat_map(|&b| (0..8).map(move |j| (b >> j) & 1 == 1))
841        .collect();
842    let mut leaks = Vec::new();
843    for (i, taps) in candidates.iter().enumerate() {
844        let Some(attack) = describe::correlation_attack(&bits, taps) else {
845            continue;
846        };
847        let floor = describe::spurious_bias_floor(taps.len(), attack.samples);
848        if floor > 0.0 && attack.bias > significance * floor {
849            leaks.push(CombinerLeak {
850                candidate_index: i,
851                margin: attack.bias / floor,
852                floor,
853                attack,
854            });
855        }
856    }
857    leaks
858}
859
860/// Fast correlation attack (Meier–Staffelbach): recover a leaking LFSR's initial state from a noisy
861/// keystream by DECODING the register-as-linear-code, in time polynomial in `L` — where the exhaustive
862/// correlation attack ([`scan_for_combiner_leaks`], Rung E) needs `O(2^L)`. This is what scales the
863/// correlation break to the register lengths real ciphers use. See [`describe::fast_correlation_attack`].
864pub fn fast_correlation_attack(
865    keystream: &[bool],
866    taps: &[bool],
867    max_iters: usize,
868) -> Option<Vec<bool>> {
869    describe::fast_correlation_attack(keystream, taps, max_iters)
870}
871
872/// Break a shrinking (clock-controlled) generator: recover both register states from the output alone by
873/// guessing the clock register and linear-solving the data register. Reaches a generator whose output is
874/// a data-dependent decimation — not a fixed function of any register's own past — that no feedback,
875/// correlation, algebraic, or linear rung can touch. See [`describe::attack_shrinking_generator`].
876pub fn attack_shrinking_generator(
877    output: &[bool],
878    a_taps: &[bool],
879    s_taps: &[bool],
880) -> Option<(Vec<bool>, Vec<bool>)> {
881    describe::attack_shrinking_generator(output, a_taps, s_taps)
882}
883
884// ---- The auto-lens-finder: a portfolio meta-dispatcher that forces every lens to declare itself -------
885//
886// The whole campaign is a menu of LENSES, each compressing (and thereby breaking) a different structured
887// family. The covering question is: run them ALL against an object and see which one — if any — fires.
888// The union of the lenses covers the union of their families; whatever no lens compresses is the
889// incompressible residue relative to this arsenal — the operational Chaitin ceiling. No arrangement can
890// cover the WHOLE space (counting says most sequences are incompressible, and Chaitin forbids certifying
891// which), but we can cover the structured families and MEASURE the hole. Lenses are tried cheapest-first.
892
893/// One lens's verdict on a sequence: the number of bits it needs to DESCRIBE the sequence (`usize::MAX`
894/// if the lens finds no exploitable structure). Lower ⇒ the lens compresses it more.
895#[derive(Clone, Debug, PartialEq, Eq)]
896pub struct LensCoverage {
897    pub lens: &'static str,
898    pub description_bits: usize,
899}
900
901/// The result of running the whole lens portfolio against a bit sequence.
902#[derive(Clone, Debug)]
903pub struct LensReport {
904    pub length_bits: usize,
905    /// Every lens's description-length verdict (the covering menu, laid out).
906    pub coverage: Vec<LensCoverage>,
907    /// The lens achieving the shortest description — the one that "covers" the sequence.
908    pub best_lens: &'static str,
909    pub best_description_bits: usize,
910    /// Whether the best lens compresses by at least 2× — i.e. the sequence is genuinely covered, not
911    /// in the incompressible residue.
912    pub covered: bool,
913}
914
915/// The **auto-lens-finder**: run every sequence lens in the arsenal against `bits` and report which one
916/// compresses it (covers it) and by how much — or that none do, placing it in the incompressible residue.
917/// This makes the covering explicit: each structured family is caught by its own lens, and a
918/// cryptographically-random sequence falls through all of them (the ceiling). Lenses are ordered
919/// cheapest-first so a covered sequence is recognized quickly.
920pub fn lens_report(bits: &[bool]) -> LensReport {
921    let n = bits.len();
922    let mut coverage = Vec::new();
923
924    // Linear (LFSR): a length-L register describes it in ~2L bits (taps + seed).
925    let lc = describe::berlekamp_massey_gf2(bits).0;
926    coverage.push(LensCoverage {
927        lens: "linear (LFSR / Berlekamp–Massey)",
928        description_bits: lc.saturating_mul(2),
929    });
930
931    // 2-adic (FCSR): a carry register of complexity c describes it in ~2c bits.
932    let tc = describe::two_adic_complexity(bits);
933    coverage.push(LensCoverage {
934        lens: "2-adic (FCSR)",
935        description_bits: tc.saturating_mul(2),
936    });
937
938    // Maximal-order: a nonlinear register of order L, but its feedback is a 2^L truth table — it only
939    // COMPRESSES when the register is tiny (otherwise it merely measures).
940    let moc = describe::maximal_order_complexity(bits);
941    let moc_bits = if moc < 20 {
942        (1usize << moc).saturating_add(moc)
943    } else {
944        usize::MAX
945    };
946    coverage.push(LensCoverage {
947        lens: "maximal-order (nonlinear FSR)",
948        description_bits: moc_bits,
949    });
950
951    // Algebraic recurrence (degree ≤ 2): a low-degree nonlinear feedback, sparse ANF (bounded order search).
952    let alg = (1..=12).find_map(|l| {
953        describe::detect_algebraic_recurrence(bits, l, 2)
954            .map(|c| l + c.iter().filter(|&&b| b).count())
955    });
956    coverage.push(LensCoverage {
957        lens: "algebraic-recurrence (deg-2 ANF)",
958        description_bits: alg.unwrap_or(usize::MAX),
959    });
960
961    // MDL codec menu: affine / geometric / polynomial / periodic / sparse / RLE / … over the byte packing.
962    let bytes = describe::bits_to_bytes(bits);
963    let enc = describe::describe_int_seq(&bytes).len().saturating_mul(8);
964    coverage.push(LensCoverage {
965        lens: "MDL codec menu",
966        description_bits: enc,
967    });
968
969    let best = coverage
970        .iter()
971        .min_by_key(|c| c.description_bits)
972        .expect("nonempty");
973    let covered = best.description_bits.saturating_mul(2) < n;
974    LensReport {
975        length_bits: n,
976        best_lens: best.lens,
977        best_description_bits: best.description_bits,
978        covered,
979        coverage,
980    }
981}
982
983/// A coverage census over a corpus of sequences: how many the lens arsenal covers, how many fall in the
984/// uncovered residue, and which lens covered how many. This is the covering problem made countable.
985#[derive(Clone, Debug)]
986pub struct CoverageCensus {
987    pub total: usize,
988    /// Covered by some lens (compressed ≥ 2×).
989    pub covered: usize,
990    /// The incompressible residue — covered by nothing in the arsenal.
991    pub uncovered: usize,
992    /// How many sequences each lens was the best cover for.
993    pub by_lens: Vec<(&'static str, usize)>,
994}
995
996/// Census a corpus of bit sequences through the [`lens_report`] portfolio: tally what each lens covers
997/// and what lands in the uncovered residue.
998pub fn census(corpus: &[Vec<bool>]) -> CoverageCensus {
999    let mut counts: std::collections::BTreeMap<&'static str, usize> =
1000        std::collections::BTreeMap::new();
1001    let mut covered = 0;
1002    for seq in corpus {
1003        let r = lens_report(seq);
1004        if r.covered {
1005            covered += 1;
1006            *counts.entry(r.best_lens).or_insert(0) += 1;
1007        }
1008    }
1009    CoverageCensus {
1010        total: corpus.len(),
1011        covered,
1012        uncovered: corpus.len() - covered,
1013        by_lens: counts.into_iter().collect(),
1014    }
1015}
1016
1017/// Exhaustively census EVERY length-`len` bit sequence (`2^len` of them): what fraction of the WHOLE
1018/// space does the lens arsenal cover? The answer is a small sliver — most sequences are incompressible,
1019/// the residue — which is the concrete, countable face of the Chaitin ceiling. The structured families
1020/// our lenses catch are real and important, but they are a vanishing fraction of the space; you cannot
1021/// arrange lenses to cover it all (counting forbids it), and you cannot even certify which points are
1022/// uncovered (Chaitin forbids that). `len ≤ ~18` to stay tractable.
1023pub fn exhaustive_coverage(len: usize) -> CoverageCensus {
1024    let corpus: Vec<Vec<bool>> = (0u64..(1u64 << len))
1025        .map(|code| (0..len).map(|i| (code >> i) & 1 == 1).collect())
1026        .collect();
1027    census(&corpus)
1028}
1029
1030/// The trace of recursively symmetry-breaking an object down to its incompressible core.
1031#[derive(Clone, Debug)]
1032pub struct RecursiveReduction {
1033    /// The size (bytes) at each recursion level — level 0 is the input, the last is the fixed point.
1034    pub sizes: Vec<usize>,
1035    /// How many symmetry breaks (compressions) before the fixed point.
1036    pub depth: usize,
1037    /// The size of the irreducible core: what the arsenal cannot reduce further.
1038    pub irreducible_bytes: usize,
1039    /// Whether any reduction happened at all.
1040    pub compressed: bool,
1041}
1042
1043/// **Recursively symmetry-break** an object until nothing reduces it further. Each level applies the
1044/// compression lens (the MDL description menu) and recurses on the DESCRIPTION — each compression is a
1045/// symmetry break, and its output becomes the next object. The recursion terminates at the FIXED POINT:
1046/// the point where no lens shrinks it, the incompressible core.
1047///
1048/// The terminus is `no lens fires` — which is *"irreducible by this arsenal"*, and is NOT, and can never
1049/// be, *"structureless."* Proving no structure exists would be certifying a Kolmogorov lower bound
1050/// `K(x) > c`, which the kernel-certified Chaitin theorem in this module says a bounded system can do for
1051/// no object past its budget. So this function computes the fixed point; the thing it can never output is
1052/// a proof that the fixed point has no structure.
1053pub fn recursive_reduce(bytes: &[u8]) -> RecursiveReduction {
1054    let mut cur: Vec<i64> = bytes.iter().map(|&b| b as i64).collect();
1055    let mut sizes = vec![cur.len()];
1056    loop {
1057        let enc = describe::describe_int_seq(&cur);
1058        if enc.len() >= cur.len() {
1059            break; // no lens shrinks it — the incompressible fixed point (relative to the arsenal)
1060        }
1061        cur = enc.iter().map(|&b| b as i64).collect();
1062        sizes.push(cur.len());
1063    }
1064    RecursiveReduction {
1065        depth: sizes.len() - 1,
1066        irreducible_bytes: *sizes.last().expect("nonempty"),
1067        compressed: sizes.len() > 1,
1068        sizes,
1069    }
1070}
1071
1072/// The linear-cryptanalytic profile of a Boolean combining/filter function, from its Walsh spectrum: the
1073/// best linear approximation (the distinguisher), its nonlinearity, and its correlation-immunity order.
1074#[derive(Clone, Debug, PartialEq)]
1075pub struct LinearDistinguisher {
1076    /// The linear mask `w` of the best approximation `z ≈ ⟨w, inputs⟩`.
1077    pub mask: usize,
1078    /// The bias `|Pr[C=⟨w,x⟩] − ½|` of that approximation — the distinguishing advantage.
1079    pub bias: f64,
1080    /// The Hamming weight of `mask`: how many registers the approximation combines (weight 1 = Rung E).
1081    pub mask_weight: u32,
1082    /// Distance to the nearest affine function; maximal ⇒ bent ⇒ no exploitable linear approximation.
1083    pub nonlinearity: u64,
1084    /// The correlation-immunity order — how many registers the first-order correlation attack must miss.
1085    pub immunity_order: usize,
1086}
1087
1088/// The linear-cryptanalysis profile of a combining/filter function given as its `2ⁿ` truth table: the
1089/// whole Walsh spectrum distilled into the best linear approximation, its nonlinearity, and its
1090/// correlation-immunity order. Where [`scan_for_combiner_leaks`] (Rung E) reads only weight-1 masks, this
1091/// reads them ALL — surfacing the multi-register approximation (`mask_weight ≥ 2`) that E is blind to,
1092/// even on a first-order correlation-immune function. `None` for a malformed table.
1093pub fn linear_cryptanalysis(truth: &[bool]) -> Option<LinearDistinguisher> {
1094    let (mask, bias) = describe::best_linear_approximation(truth, true)?;
1095    Some(LinearDistinguisher {
1096        mask,
1097        bias,
1098        mask_weight: mask.count_ones(),
1099        nonlinearity: describe::nonlinearity(truth)?,
1100        immunity_order: describe::correlation_immunity_order(truth)?,
1101    })
1102}
1103
1104/// The algebraic-immunity profile of a filter/combining function: the minimum degree of an annihilator
1105/// (the algebraic attack's leverage), the maximum possible `⌈n/2⌉`, and whether it sits at that ceiling.
1106#[derive(Clone, Debug, PartialEq, Eq)]
1107pub struct AlgebraicImmunityReport {
1108    /// `AI(C)` — the minimum degree of a nonzero annihilator of `C` or `C ⊕ 1`.
1109    pub immunity: usize,
1110    /// `⌈n/2⌉` — the maximum algebraic immunity any `n`-variable function can have.
1111    pub max_possible: usize,
1112    /// A re-checkable minimum-degree annihilator (the attack's leverage).
1113    pub witness: describe::AnnihilatorWitness,
1114    /// `AI(C) == ⌈n/2⌉` — maximal algebraic immunity, the algebraic-incompressible residue (the ceiling).
1115    pub is_maximal: bool,
1116}
1117
1118/// The algebraic-immunity profile of a Boolean function given as its `2ⁿ` truth table. Low immunity is a
1119/// certified structural weakness: a degree-`AI` annihilator turns each keystream bit of a filter
1120/// generator using `C` into a degree-`AI` equation in the secret state ([`algebraic_filter_attack`]).
1121/// Maximal immunity (`AI = ⌈n/2⌉`) is the ceiling — no low-degree relation to exploit. `None` for a
1122/// malformed table.
1123pub fn algebraic_immunity_of(truth: &[bool]) -> Option<AlgebraicImmunityReport> {
1124    let (immunity, witness) = describe::algebraic_immunity(truth)?;
1125    let n = truth.len().trailing_zeros() as usize;
1126    let max_possible = n.div_ceil(2);
1127    Some(AlgebraicImmunityReport {
1128        immunity,
1129        max_possible,
1130        witness,
1131        is_maximal: immunity == max_possible,
1132    })
1133}
1134
1135/// Recover the initial state of a filter generator (a length-`L` LFSR with feedback `taps` filtered by
1136/// `filter_truth`) via the algebraic attack — the certified break of a target the correlation and Walsh
1137/// rungs only glimpse statistically. See [`describe::algebraic_filter_attack`]. Returns the secret
1138/// initial state (verified by regeneration) or `None`.
1139pub fn algebraic_filter_attack(
1140    keystream: &[bool],
1141    taps: &[bool],
1142    filter_truth: &[bool],
1143) -> Option<Vec<bool>> {
1144    describe::algebraic_filter_attack(keystream, taps, filter_truth)
1145}
1146
1147// ---- The hypercube structure finder: classify a Boolean function by walking its cube -----------------
1148//
1149// A length-`2ⁿ` truth table IS a labeling of the corners of the `n`-cube. The structure finder walks that
1150// cube through each structural lens — each lens is a genuine traversal of the cube along one axis of
1151// structure — and reports the TIGHTEST class that describes the whole function in far fewer than `2ⁿ`
1152// bits, with a re-checkable decode witness:
1153//
1154//   • Constant       — every corner equal (1 bit).                      walk: read the corners.
1155//   • Junta(k)       — only k of n variables ever change the output.    walk: probe each coordinate edge.
1156//   • Affine         — degree ≤ 1: f(x) = ⊕ aᵢxᵢ ⊕ c (n+1 bits).        walk: the Walsh–Hadamard butterfly.
1157//   • Symmetric      — depends only on Hamming weight (n+1 bits).        walk: the weight shells.
1158//   • LowDegree(d)   — a sparse ANF: few monomials describe it.         walk: the Möbius butterfly.
1159//   • ResistedArsenal— dense high-degree ANF, all vars, high nonlin.    the residue: no lens fires.
1160//
1161// The residue is `irreducible by this arsenal`, NOT `structureless` — the Chaitin ceiling (this module)
1162// forbids certifying the latter. It is exactly the class that indistinguishability obfuscation must live
1163// in: a function whose structure NO adversary lens reads off. The 2001 impossibility of *ideal*
1164// obfuscation is the cryptographic cousin of Chaitin — the code always reveals at least itself — which is
1165// why iO settles for *indistinguishability*, hiding which structured program you hold inside the residue.
1166
1167/// The compressibility class of a Boolean function on the hypercube, tightest description first. Each
1168/// variant carries a re-checkable witness ([`CubeStructure::reconstruct`]) except the residue.
1169#[derive(Clone, Debug, PartialEq, Eq)]
1170pub enum CubeStructure {
1171    /// Every corner carries the same value — the whole cube in one bit.
1172    Constant(bool),
1173    /// A junta: the output depends only on `relevant` (a strict subset of the variables); `subtable` is
1174    /// its `2^{|relevant|}` truth table over those variables (indexed LSB-first in `relevant` order).
1175    Junta {
1176        relevant: Vec<usize>,
1177        subtable: Vec<bool>,
1178    },
1179    /// Affine (degree ≤ 1): `f(x) = ⊕ᵢ coeffs[i]·xᵢ ⊕ constant`.
1180    Affine { coeffs: Vec<bool>, constant: bool },
1181    /// Symmetric: the output depends only on the Hamming weight of the input; `by_weight[w]` is its value
1182    /// on every corner of weight `w` (length `n+1`).
1183    Symmetric { by_weight: Vec<bool> },
1184    /// Low algebraic degree with a sparse ANF: `anf` is the `2ⁿ` Möbius-transform witness, `degree` its top.
1185    LowDegree { degree: usize, anf: Vec<bool> },
1186    /// No lens compresses it: dense high-degree ANF, all variables relevant, high nonlinearity. The
1187    /// incompressible residue relative to this arsenal — NOT a proof of structurelessness (Chaitin).
1188    ResistedArsenal { nonlinearity: u64, degree: usize },
1189}
1190
1191impl CubeStructure {
1192    /// Rebuild the `2ⁿ` truth table from this description — the re-checkable decode witness. `None` for the
1193    /// residue (which carries no compressed description) or a malformed witness.
1194    pub fn reconstruct(&self, n: usize) -> Option<Vec<bool>> {
1195        let size = 1usize << n;
1196        match self {
1197            CubeStructure::Constant(b) => Some(vec![*b; size]),
1198            CubeStructure::Junta { relevant, subtable } => {
1199                if subtable.len() != 1usize << relevant.len() {
1200                    return None;
1201                }
1202                Some(
1203                    (0..size)
1204                        .map(|x| {
1205                            let c = relevant.iter().enumerate().fold(0usize, |acc, (bit, &v)| {
1206                                if x & (1 << v) != 0 {
1207                                    acc | (1 << bit)
1208                                } else {
1209                                    acc
1210                                }
1211                            });
1212                            subtable[c]
1213                        })
1214                        .collect(),
1215                )
1216            }
1217            CubeStructure::Affine { coeffs, constant } => {
1218                if coeffs.len() != n {
1219                    return None;
1220                }
1221                Some(
1222                    (0..size)
1223                        .map(|x| {
1224                            coeffs
1225                                .iter()
1226                                .enumerate()
1227                                .fold(*constant, |acc, (i, &a)| acc ^ (a && (x & (1 << i) != 0)))
1228                        })
1229                        .collect(),
1230                )
1231            }
1232            CubeStructure::Symmetric { by_weight } => {
1233                if by_weight.len() != n + 1 {
1234                    return None;
1235                }
1236                Some(
1237                    (0..size)
1238                        .map(|x| by_weight[(x as u64).count_ones() as usize])
1239                        .collect(),
1240                )
1241            }
1242            // The ANF↔truth Möbius transform is its own inverse over GF(2).
1243            CubeStructure::LowDegree { anf, .. } => {
1244                if anf.len() != size {
1245                    return None;
1246                }
1247                describe::anf(anf)
1248            }
1249            CubeStructure::ResistedArsenal { .. } => None,
1250        }
1251    }
1252}
1253
1254/// The verdict of the hypercube structure finder: the tightest structural class, its description size in
1255/// bits, and how that compares to the raw `2ⁿ`-bit truth table.
1256#[derive(Clone, Debug)]
1257pub struct StructureReport {
1258    pub num_vars: usize,
1259    pub class: CubeStructure,
1260    /// `2ⁿ` — the bits to store the truth table corner-by-corner.
1261    pub raw_bits: usize,
1262    /// The bits of the tightest structural description found.
1263    pub description_bits: usize,
1264    /// Whether any lens beat storing the raw truth table.
1265    pub compressed: bool,
1266}
1267
1268/// Bits needed to name one of `n` variables.
1269fn var_index_bits(n: usize) -> usize {
1270    if n <= 1 {
1271        1
1272    } else {
1273        (usize::BITS - (n - 1).leading_zeros()) as usize
1274    }
1275}
1276
1277/// `Σ_{k=0}^{d} C(n,k)` — the number of ANF coefficient bits for all monomials of degree `≤ d`, i.e. the
1278/// DENSE encoding size of a degree-`d` function (vs the sparse `weight · n` monomial list).
1279fn partial_binomial_sum(n: usize, d: usize) -> usize {
1280    let mut sum = 0usize;
1281    let mut c = 1usize;
1282    for k in 0..=d.min(n) {
1283        sum = sum.saturating_add(c);
1284        c = c.saturating_mul(n - k) / (k + 1);
1285    }
1286    sum
1287}
1288
1289/// If the function depends only on Hamming weight, its value on each weight shell `0..=n`; else `None`.
1290fn symmetric_profile(truth: &[bool], n: usize) -> Option<Vec<bool>> {
1291    let mut by_weight: Vec<Option<bool>> = vec![None; n + 1];
1292    for (x, &val) in truth.iter().enumerate() {
1293        let w = (x as u64).count_ones() as usize;
1294        match by_weight[w] {
1295            None => by_weight[w] = Some(val),
1296            Some(v) if v != val => return None,
1297            _ => {}
1298        }
1299    }
1300    Some(by_weight.into_iter().map(|o| o.unwrap_or(false)).collect())
1301}
1302
1303/// **Walk the hypercube** of a Boolean function (its `2ⁿ` truth table) and return the tightest structural
1304/// class that describes it, with the achieved description size and a re-checkable witness. Every lens is a
1305/// traversal of the cube along one axis of structure (coordinate edges, Walsh butterfly, weight shells,
1306/// Möbius butterfly); the finder reports whichever yields the shortest description, or the residue
1307/// ([`CubeStructure::ResistedArsenal`]) when none beats storing the table raw. `None` if `truth.len()` is
1308/// not a power of two.
1309pub fn find_structure(truth: &[bool]) -> Option<StructureReport> {
1310    if truth.is_empty() || !truth.len().is_power_of_two() {
1311        return None;
1312    }
1313    let n = truth.len().trailing_zeros() as usize;
1314    let raw = truth.len();
1315    let mut cands: Vec<(CubeStructure, usize)> = Vec::new();
1316
1317    // Constant — the tightest lens: the whole cube in one bit.
1318    if truth.iter().all(|&b| b == truth[0]) {
1319        cands.push((CubeStructure::Constant(truth[0]), 1));
1320    }
1321
1322    // Junta — probe each coordinate edge: a variable is relevant iff flipping it ever changes the output.
1323    let relevant: Vec<usize> = (0..n)
1324        .filter(|&i| (0..truth.len()).any(|x| truth[x] != truth[x ^ (1 << i)]))
1325        .collect();
1326    if !relevant.is_empty() && relevant.len() < n {
1327        let k = relevant.len();
1328        let subtable: Vec<bool> = (0..1usize << k)
1329            .map(|c| {
1330                let x = relevant.iter().enumerate().fold(0usize, |acc, (bit, &v)| {
1331                    if c & (1 << bit) != 0 {
1332                        acc | (1 << v)
1333                    } else {
1334                        acc
1335                    }
1336                });
1337                truth[x]
1338            })
1339            .collect();
1340        let bits = k * var_index_bits(n) + (1usize << k);
1341        cands.push((CubeStructure::Junta { relevant, subtable }, bits));
1342    }
1343
1344    // Affine — the Walsh butterfly: nonlinearity 0 ⇔ degree ≤ 1. Read coeffs by walking the n axes.
1345    if describe::nonlinearity(truth) == Some(0) {
1346        let constant = truth[0];
1347        let coeffs: Vec<bool> = (0..n).map(|i| truth[1 << i] ^ constant).collect();
1348        cands.push((CubeStructure::Affine { coeffs, constant }, n + 1));
1349    }
1350
1351    // Symmetric — the weight shells: the output depends only on Hamming weight.
1352    if let Some(by_weight) = symmetric_profile(truth, n) {
1353        cands.push((CubeStructure::Symmetric { by_weight }, n + 1));
1354    }
1355
1356    // Low degree — the Möbius butterfly. Account the TIGHTER of the sparse monomial list (`weight · n`) and
1357    // the dense coefficient vector (`Σ_{k≤deg} C(n,k)`), so a DENSE bounded-degree function compresses too.
1358    if let Some(anf) = describe::anf(truth) {
1359        let weight = anf.iter().filter(|&&c| c).count();
1360        let degree = anf
1361            .iter()
1362            .enumerate()
1363            .filter(|(_, &c)| c)
1364            .map(|(m, _)| (m as u64).count_ones() as usize)
1365            .max()
1366            .unwrap_or(0);
1367        // The dense coefficient vector only counts for genuinely bounded degree (`≤ n−2`); at degree `n−1`
1368        // it would save a single trivial bit and swallow the honest residue.
1369        let dense = if degree + 2 <= n {
1370            partial_binomial_sum(n, degree)
1371        } else {
1372            usize::MAX
1373        };
1374        let bits = weight.saturating_mul(n).min(dense).max(1);
1375        cands.push((CubeStructure::LowDegree { degree, anf }, bits));
1376    }
1377
1378    let (class, description_bits) = cands
1379        .into_iter()
1380        .min_by_key(|(_, b)| *b)
1381        .filter(|(_, b)| *b < raw)
1382        .unwrap_or_else(|| {
1383            let degree = describe::algebraic_degree(truth).unwrap_or(n);
1384            let nonlinearity = describe::nonlinearity(truth).unwrap_or(0);
1385            (
1386                CubeStructure::ResistedArsenal {
1387                    nonlinearity,
1388                    degree,
1389                },
1390                raw,
1391            )
1392        });
1393
1394    Some(StructureReport {
1395        num_vars: n,
1396        compressed: description_bits < raw,
1397        description_bits,
1398        raw_bits: raw,
1399        class,
1400    })
1401}
1402
1403/// A **cover of the cube by structural class**: the ANF degree stratification of a Boolean function. Every
1404/// function is a XOR of monomials `∏_{i∈S} xᵢ`, and each monomial is a structural class — its degree `|S|`
1405/// is the order of variable interaction it encodes. Peeling low-degree slices (constant, linear,
1406/// quadratic, …) covers most of the `2ⁿ` corners with a handful of terms; what remains is the residue: the
1407/// high-degree core no lower-order slice explains. This is why the peel is more efficient than walking the
1408/// cube corner by corner — each class-slice accounts for many corners at once, and you reason about the
1409/// small residue directly instead of labeling all `2ⁿ` of them.
1410#[derive(Clone, Debug)]
1411pub struct StructureCover {
1412    pub num_vars: usize,
1413    /// `monomials_by_degree[d]` = ANF monomials of degree exactly `d` — the size of the degree-`d` slice.
1414    pub monomials_by_degree: Vec<usize>,
1415    /// The total ANF monomials across all slices — the whole description in monomials.
1416    pub total_monomials: usize,
1417    /// The highest degree present: the residue's interaction order (0 if the function is a constant).
1418    pub residue_degree: usize,
1419    /// The number of monomials at the residue degree — the irreducible high-degree core.
1420    pub residue_monomials: usize,
1421    /// Bits to store the ANF as monomial indices (`total · n`), against `2ⁿ` raw.
1422    pub description_bits: usize,
1423    pub raw_bits: usize,
1424    /// Whether the peel is a genuine compression — a sparse ANF beats storing the truth table.
1425    pub compressed: bool,
1426}
1427
1428/// **Peel the cube apart by structural class** and examine the residue: return the ANF degree
1429/// stratification of a Boolean function (its `2ⁿ` truth table). Each degree is a slice of structure; the
1430/// top nonempty degree is the residue — the interaction order that survives every lower-order peel, and
1431/// the honest answer to *what remains and why*. `None` if `truth.len()` is not a power of two.
1432pub fn structure_cover(truth: &[bool]) -> Option<StructureCover> {
1433    let anf = describe::anf(truth)?;
1434    let n = truth.len().trailing_zeros() as usize;
1435    let mut by_degree = vec![0usize; n + 1];
1436    for (m, &c) in anf.iter().enumerate() {
1437        if c {
1438            by_degree[(m as u64).count_ones() as usize] += 1;
1439        }
1440    }
1441    let total: usize = by_degree.iter().sum();
1442    let residue_degree = by_degree.iter().rposition(|&c| c > 0).unwrap_or(0);
1443    let residue_monomials = by_degree[residue_degree];
1444    let raw = truth.len();
1445    let description_bits = if total == 0 { 1 } else { total * n };
1446    Some(StructureCover {
1447        num_vars: n,
1448        compressed: description_bits < raw,
1449        monomials_by_degree: by_degree,
1450        total_monomials: total,
1451        residue_degree,
1452        residue_monomials,
1453        description_bits,
1454        raw_bits: raw,
1455    })
1456}
1457
1458// ---- Linear structures: the derivative symmetry the coordinate lenses miss ---------------------------
1459//
1460// The lenses above read structure in the GIVEN coordinates. But a function can be simple in a ROTATED
1461// basis and look dense here: a rotated junta is invariant under some direction `a` that is not an axis, so
1462// the coordinate walk sees every variable as relevant and the finder calls it residue. The autocorrelation
1463// exposes exactly this: `a` is a LINEAR STRUCTURE when `f(x⊕a) ⊕ f(x)` is constant (`|r_f(a)| = 2ⁿ`). The
1464// set of linear structures forms a GF(2) subspace `V(f)`, and `dim V(f) = k > 0` means `f` collapses to an
1465// `(n−k)`-variable function after a linear change of basis. Peeling `V(f)` is the affine-group symmetry
1466// break the whole arsenal was missing — and a genuinely random function still has `V(f) = {0}`, the residue
1467// that survives even this.
1468
1469/// The linear space `V(f)` of a Boolean function: the directions along which the derivative is constant.
1470#[derive(Clone, Debug)]
1471pub struct LinearStructureReport {
1472    pub num_vars: usize,
1473    /// A GF(2) echelon basis of `V(f)`; each element is a nonzero variable bitmask.
1474    pub basis: Vec<usize>,
1475    /// For each basis vector `a`, the constant value of `f(x⊕a) ⊕ f(x)`: `false` = an invariance (period),
1476    /// `true` = a complement (always flips the output).
1477    pub derivative: Vec<bool>,
1478}
1479
1480impl LinearStructureReport {
1481    /// `dim V(f)` — the number of dimensions a linear change of basis can peel off.
1482    pub fn dim(&self) -> usize {
1483        self.basis.len()
1484    }
1485    /// Whether the function carries any linear structure the coordinate lenses miss.
1486    pub fn is_reducible(&self) -> bool {
1487        !self.basis.is_empty()
1488    }
1489    /// Re-check the witness against the truth table: each basis vector is nonzero and independent, and its
1490    /// recorded derivative is genuinely constant across the whole cube.
1491    pub fn verify(&self, truth: &[bool]) -> bool {
1492        if self.basis.len() != self.derivative.len() {
1493            return false;
1494        }
1495        if gf2_echelon_basis(&self.basis).len() != self.basis.len() {
1496            return false; // the recorded basis is not independent
1497        }
1498        for (&a, &c) in self.basis.iter().zip(&self.derivative) {
1499            if a == 0 || a >= truth.len() {
1500                return false;
1501            }
1502            if !(0..truth.len()).all(|x| (truth[x] ^ truth[x ^ a]) == c) {
1503                return false;
1504            }
1505        }
1506        true
1507    }
1508}
1509
1510/// A xor-basis (echelon over GF(2)) of the span of `vectors` — each returned mask has a distinct highest
1511/// set bit, and the count is the GF(2) rank.
1512fn gf2_echelon_basis(vectors: &[usize]) -> Vec<usize> {
1513    let mut basis: Vec<usize> = Vec::new();
1514    for &v in vectors {
1515        let mut x = v;
1516        for &b in &basis {
1517            x = x.min(x ^ b);
1518        }
1519        if x != 0 {
1520            basis.push(x);
1521            basis.sort_unstable_by(|a, b| b.cmp(a));
1522        }
1523    }
1524    basis
1525}
1526
1527/// Reduce `x` modulo an echelon basis, clearing every pivot bit (leaving the coset representative that is
1528/// zero on all pivot positions).
1529fn reduce_by_basis(mut x: usize, basis: &[usize]) -> usize {
1530    for &b in basis {
1531        let hb = 1usize << (usize::BITS - 1 - b.leading_zeros());
1532        if x & hb != 0 {
1533            x ^= b;
1534        }
1535    }
1536    x
1537}
1538
1539/// Detect the linear space `V(f)` of a Boolean function from its autocorrelation. `None` if `truth.len()`
1540/// is not a power of two.
1541pub fn linear_structures(truth: &[bool]) -> Option<LinearStructureReport> {
1542    if truth.is_empty() || !truth.len().is_power_of_two() {
1543        return None;
1544    }
1545    let n = truth.len().trailing_zeros() as usize;
1546    let r = describe::autocorrelation(truth)?;
1547    let full = truth.len() as i64;
1548    let structs: Vec<usize> = (1..truth.len()).filter(|&a| r[a].abs() == full).collect();
1549    let basis = gf2_echelon_basis(&structs);
1550    let derivative = basis.iter().map(|&a| truth[a] ^ truth[0]).collect();
1551    Some(LinearStructureReport {
1552        num_vars: n,
1553        basis,
1554        derivative,
1555    })
1556}
1557
1558/// The genuine domain compression from the INVARIANCE subspace `V₀(f) = {a : f(x⊕a) = f(x) ∀x}`: an
1559/// `(n − dim V₀)`-variable truth table carrying all the information, over the surviving `free_positions`. A
1560/// rotated junta collapses here even though the coordinate junta lens saw every variable as relevant.
1561#[derive(Clone, Debug)]
1562pub struct InvarianceReduction {
1563    pub original_vars: usize,
1564    pub reduced_vars: usize,
1565    /// The surviving variable positions (a complement of the invariance pivots).
1566    pub free_positions: Vec<usize>,
1567    /// The reduced function over `free_positions`, in the same LSB-first index order.
1568    pub reduced_truth: Vec<bool>,
1569}
1570
1571impl InvarianceReduction {
1572    /// Re-check that the reduction reproduces the original: every corner maps to the reduced value of its
1573    /// coset representative.
1574    pub fn verify(&self, truth: &[bool], invariance_basis: &[usize]) -> bool {
1575        if self.reduced_truth.len() != 1 << self.reduced_vars {
1576            return false;
1577        }
1578        (0..truth.len()).all(|x| {
1579            let rep = reduce_by_basis(x, invariance_basis);
1580            let y = self
1581                .free_positions
1582                .iter()
1583                .enumerate()
1584                .fold(0usize, |acc, (i, &p)| {
1585                    if rep & (1 << p) != 0 {
1586                        acc | (1 << i)
1587                    } else {
1588                        acc
1589                    }
1590                });
1591            self.reduced_truth[y] == truth[x]
1592        })
1593    }
1594}
1595
1596/// Reduce an echelon xor-basis to reduced row echelon: each vector keeps its pivot bit, cleared from all
1597/// others.
1598fn gf2_rref(basis: &[usize]) -> Vec<usize> {
1599    let mut b = basis.to_vec();
1600    let pivots: Vec<usize> = b
1601        .iter()
1602        .map(|&v| 1usize << (usize::BITS - 1 - v.leading_zeros()))
1603        .collect();
1604    for i in 0..b.len() {
1605        for j in 0..b.len() {
1606            if i != j && b[j] & pivots[i] != 0 {
1607                b[j] ^= b[i];
1608            }
1609        }
1610    }
1611    b
1612}
1613
1614/// The affine reduction of a Boolean function: `f(x) = h(reduced) ⊕ ℓ(x)`, where `ℓ` is a linear form and
1615/// `h` collapses onto the free coordinates. This peels the COMPLEMENT linear structures (`D_a f = 1`) that
1616/// [`reduce_by_invariance`] cannot — a residue XOR a linear form is invisible to every other axis but folds
1617/// here.
1618#[derive(Clone, Debug, PartialEq, Eq)]
1619pub struct AffineReduction {
1620    pub num_vars: usize,
1621    /// The linear form `ℓ(x) = ⟨c, x⟩` peeled off (as a coefficient bitmask).
1622    pub linear_form: usize,
1623    pub invariance_basis: Vec<usize>,
1624    pub free_positions: Vec<usize>,
1625    /// The reduced function `h` over `free_positions`.
1626    pub reduced_truth: Vec<bool>,
1627}
1628
1629impl AffineReduction {
1630    /// Rebuild the truth table: `f(x) = h(coset-rep of x) ⊕ ⟨c, x⟩`.
1631    pub fn reconstruct(&self) -> Option<Vec<bool>> {
1632        if self.reduced_truth.len() != 1 << self.free_positions.len() {
1633            return None;
1634        }
1635        Some(
1636            (0..1usize << self.num_vars)
1637                .map(|x| {
1638                    let rep = reduce_by_basis(x, &self.invariance_basis);
1639                    let y = self
1640                        .free_positions
1641                        .iter()
1642                        .enumerate()
1643                        .fold(0usize, |acc, (j, &p)| {
1644                            if rep & (1 << p) != 0 {
1645                                acc | (1 << j)
1646                            } else {
1647                                acc
1648                            }
1649                        });
1650                    self.reduced_truth[y] ^ ((self.linear_form & x).count_ones() % 2 == 1)
1651                })
1652                .collect(),
1653        )
1654    }
1655}
1656
1657/// Peel a linear form off a Boolean function so its complement linear structures become invariances, then
1658/// reduce. Catches `f = h ⊕ ℓ` where `ℓ` is linear and `h` collapses — the residue-plus-a-linear-form class
1659/// every other axis misses. Fail-closed: returns `Some` only if the reconstruction re-checks exactly.
1660/// `None` when there are no complement structures (pure invariance is [`reduce_by_invariance`]'s job).
1661pub fn affine_reduce(truth: &[bool]) -> Option<AffineReduction> {
1662    if truth.is_empty() || !truth.len().is_power_of_two() {
1663        return None;
1664    }
1665    let n = truth.len().trailing_zeros() as usize;
1666    let ls = linear_structures(truth)?;
1667    if !ls.derivative.iter().any(|&d| d) {
1668        return None; // no complement structure — nothing beyond invariance
1669    }
1670    // The linear form: 1 on the pivots whose RREF basis vector has a complement derivative.
1671    let rref = gf2_rref(&ls.basis);
1672    let mut c = 0usize;
1673    for &b in &rref {
1674        if truth[b] ^ truth[0] {
1675            c |= 1usize << (usize::BITS - 1 - b.leading_zeros());
1676        }
1677    }
1678    let h: Vec<bool> = (0..truth.len())
1679        .map(|x| truth[x] ^ ((c & x).count_ones() % 2 == 1))
1680        .collect();
1681    let (red, inv_basis) = reduce_by_invariance(&h)?;
1682    let out = AffineReduction {
1683        num_vars: n,
1684        linear_form: c,
1685        invariance_basis: inv_basis,
1686        free_positions: red.free_positions,
1687        reduced_truth: red.reduced_truth,
1688    };
1689    (out.reconstruct().as_deref() == Some(truth)).then_some(out)
1690}
1691
1692/// Peel the invariance subspace off a Boolean function: quotient out every direction `a` with `f(x⊕a) =
1693/// f(x)` and return the smaller function on the surviving coordinates, together with the invariance basis
1694/// that certifies it. `None` when the invariance subspace is trivial (nothing to reduce).
1695pub fn reduce_by_invariance(truth: &[bool]) -> Option<(InvarianceReduction, Vec<usize>)> {
1696    if truth.is_empty() || !truth.len().is_power_of_two() {
1697        return None;
1698    }
1699    let n = truth.len().trailing_zeros() as usize;
1700    let r = describe::autocorrelation(truth)?;
1701    let full = truth.len() as i64;
1702    let invariances: Vec<usize> = (1..truth.len()).filter(|&a| r[a] == full).collect();
1703    let basis = gf2_echelon_basis(&invariances);
1704    if basis.is_empty() {
1705        return None;
1706    }
1707    let pivots: Vec<usize> = basis
1708        .iter()
1709        .map(|&b| (usize::BITS - 1 - b.leading_zeros()) as usize)
1710        .collect();
1711    let free_positions: Vec<usize> = (0..n).filter(|p| !pivots.contains(p)).collect();
1712    let reduced_vars = free_positions.len();
1713    let reduced_truth: Vec<bool> = (0..1usize << reduced_vars)
1714        .map(|y| {
1715            let x = free_positions
1716                .iter()
1717                .enumerate()
1718                .fold(0usize, |acc, (i, &p)| {
1719                    if y & (1 << i) != 0 {
1720                        acc | (1 << p)
1721                    } else {
1722                        acc
1723                    }
1724                });
1725            truth[x]
1726        })
1727        .collect();
1728    Some((
1729        InvarianceReduction {
1730            original_vars: n,
1731            reduced_vars,
1732            free_positions,
1733            reduced_truth,
1734        },
1735        basis,
1736    ))
1737}
1738
1739// ---- Affine equivalence: the AGL(n,2)-invariant signature, the rung above linear structures ----------
1740//
1741// Linear structures peel ONE rotation; the rung above asks whether two functions are the SAME up to any
1742// invertible linear change of basis (the affine group AGL(n,2)). The Walsh-spectrum MULTISET is the
1743// invariant: applying a linear map `x → Ax` only PERMUTES the Walsh coefficients, so the multiset of
1744// amplitudes is unchanged — affine-equivalent functions share it. A single nonzero amplitude is the
1745// PLATEAUED class (bent when that amplitude is `2^{n/2}`), and the amplitude `2^{(n+k)/2}` reads off the
1746// linear-space dimension `k` — unifying this rung with the one below it. A generic function has a spread
1747// of amplitudes and belongs to no small affine class: the residue.
1748
1749/// The AGL(n,2)-invariant signature of a Boolean function: its Walsh amplitude distribution and the
1750/// plateaued/bent classification that distribution induces.
1751#[derive(Clone, Debug, PartialEq, Eq)]
1752pub struct AffineSignature {
1753    pub num_vars: usize,
1754    /// The multiset `|Ŵ(w)| → count`, sorted by amplitude — invariant under any affine change of variables.
1755    pub walsh_abs_distribution: Vec<(u64, usize)>,
1756    /// Exactly one nonzero amplitude ⇒ PLATEAUED (maximal nonlinearity for its linear-space dimension).
1757    pub is_plateaued: bool,
1758    /// The plateau amplitude `2^{(n+k)/2}` when plateaued, else `None`.
1759    pub amplitude: Option<u64>,
1760    /// Plateaued with amplitude `2^{n/2}` ⇒ BENT: perfectly nonlinear, trivial linear space (`k = 0`).
1761    pub is_bent: bool,
1762}
1763
1764impl AffineSignature {
1765    /// The linear-space dimension `k` implied by the plateau amplitude `2^{(n+k)/2}` (so `k = 2·log₂amp −
1766    /// n`), matching [`linear_structures`]`.dim()`. `None` when not plateaued.
1767    pub fn implied_linear_dim(&self) -> Option<usize> {
1768        let amp = self.amplitude?;
1769        if !amp.is_power_of_two() {
1770            return None;
1771        }
1772        let log = amp.trailing_zeros() as usize;
1773        (2 * log).checked_sub(self.num_vars)
1774    }
1775}
1776
1777/// Compute the affine-equivalence signature of a Boolean function from its Walsh spectrum. `None` if
1778/// `truth.len()` is not a power of two.
1779pub fn affine_signature(truth: &[bool]) -> Option<AffineSignature> {
1780    let n = truth.len().trailing_zeros() as usize;
1781    let spec = describe::walsh_spectrum(truth)?;
1782    let mut counts: std::collections::BTreeMap<u64, usize> = std::collections::BTreeMap::new();
1783    for &c in &spec {
1784        *counts.entry(c.unsigned_abs()).or_default() += 1;
1785    }
1786    let nonzero: Vec<u64> = counts.keys().copied().filter(|&v| v != 0).collect();
1787    let is_plateaued = nonzero.len() == 1;
1788    let amplitude = is_plateaued.then(|| nonzero[0]);
1789    let bent_amp = (n % 2 == 0).then(|| 1u64 << (n / 2));
1790    let is_bent = amplitude.is_some() && amplitude == bent_amp;
1791    Some(AffineSignature {
1792        num_vars: n,
1793        walsh_abs_distribution: counts.into_iter().collect(),
1794        is_plateaued,
1795        amplitude,
1796        is_bent,
1797    })
1798}
1799
1800// ---- Separability: the direct-sum symmetry — independent blocks solved apart ------------------------
1801//
1802// A different axis than the linear-group rungs: does the function SPLIT into independent pieces? `f(x) =
1803// g(x_A) ⊕ h(x_B)` on disjoint variable sets `A, B` is the cube analogue of a SAT instance whose clause
1804// graph has two components — you solve the pieces apart instead of the whole. The blocks are exactly the
1805// connected components of the ANF variable-interaction graph (two variables are linked when a monomial
1806// contains both), because every monomial lives inside one component. Splitting turns one `2ⁿ` table into
1807// `Σ 2^{|Bᵢ|}` — an exponential collapse — and surfaces the true independent subsystems. A function whose
1808// interaction graph is connected is a single irreducible block: no direct-sum symmetry to break.
1809
1810/// A direct-sum decomposition `f = constant ⊕ ⊕ᵢ fᵢ(x_{Bᵢ})` over independent variable blocks.
1811#[derive(Clone, Debug)]
1812pub struct SeparableDecomposition {
1813    pub num_vars: usize,
1814    /// The XOR of the empty monomial — the standalone constant term.
1815    pub constant: bool,
1816    /// A partition of the RELEVANT variables into independent blocks (each sorted; irrelevant vars omitted).
1817    pub blocks: Vec<Vec<usize>>,
1818    /// Each block's function as a `2^{|Bᵢ|}` truth table, aligned with `blocks` (LSB-first in block order).
1819    pub block_truths: Vec<Vec<bool>>,
1820}
1821
1822impl SeparableDecomposition {
1823    /// Whether the function splits into two or more independent blocks.
1824    pub fn is_separable(&self) -> bool {
1825        self.blocks.len() >= 2
1826    }
1827    /// The total bits of the block tables — `Σ 2^{|Bᵢ|}`, against `2ⁿ` for the whole truth table.
1828    pub fn table_bits(&self) -> usize {
1829        self.block_truths.iter().map(|t| t.len()).sum()
1830    }
1831    /// Rebuild the `2ⁿ` truth table — the re-checkable witness. `None` for a malformed decomposition.
1832    pub fn reconstruct(&self, n: usize) -> Option<Vec<bool>> {
1833        let size = 1usize << n;
1834        let mut out = vec![self.constant; size];
1835        for (b, t) in self.blocks.iter().zip(&self.block_truths) {
1836            if t.len() != 1 << b.len() {
1837                return None;
1838            }
1839            for (x, slot) in out.iter_mut().enumerate() {
1840                let y = b.iter().enumerate().fold(0usize, |acc, (j, &i)| {
1841                    if x & (1 << i) != 0 {
1842                        acc | (1 << j)
1843                    } else {
1844                        acc
1845                    }
1846                });
1847                *slot ^= t[y];
1848            }
1849        }
1850        Some(out)
1851    }
1852}
1853
1854fn uf_find(parent: &mut [usize], mut x: usize) -> usize {
1855    while parent[x] != x {
1856        parent[x] = parent[parent[x]];
1857        x = parent[x];
1858    }
1859    x
1860}
1861
1862/// Decompose a Boolean function into its independent direct-sum blocks (the connected components of its ANF
1863/// interaction graph). `None` if `truth.len()` is not a power of two.
1864pub fn separable_decomposition(truth: &[bool]) -> Option<SeparableDecomposition> {
1865    if truth.is_empty() || !truth.len().is_power_of_two() {
1866        return None;
1867    }
1868    let n = truth.len().trailing_zeros() as usize;
1869    let anf = describe::anf(truth)?;
1870    let constant = anf[0];
1871    let mut parent: Vec<usize> = (0..n).collect();
1872    let mut relevant = vec![false; n];
1873    for (m, &c) in anf.iter().enumerate() {
1874        if !c || m == 0 {
1875            continue;
1876        }
1877        let bits: Vec<usize> = (0..n).filter(|&i| m & (1 << i) != 0).collect();
1878        for &i in &bits {
1879            relevant[i] = true;
1880        }
1881        for w in bits.windows(2) {
1882            let (ra, rb) = (uf_find(&mut parent, w[0]), uf_find(&mut parent, w[1]));
1883            parent[ra] = rb;
1884        }
1885    }
1886    let mut comp: std::collections::BTreeMap<usize, Vec<usize>> = std::collections::BTreeMap::new();
1887    for i in 0..n {
1888        if relevant[i] {
1889            let r = uf_find(&mut parent, i);
1890            comp.entry(r).or_default().push(i);
1891        }
1892    }
1893    let blocks: Vec<Vec<usize>> = comp.into_values().collect();
1894    let mut block_truths = Vec::with_capacity(blocks.len());
1895    for b in &blocks {
1896        let bmask: usize = b.iter().fold(0, |acc, &i| acc | (1 << i));
1897        let mut sub = vec![false; 1usize << b.len()];
1898        for (m, &c) in anf.iter().enumerate() {
1899            if !c || m == 0 || m & !bmask != 0 {
1900                continue;
1901            }
1902            let sub_m = b.iter().enumerate().fold(0usize, |acc, (j, &i)| {
1903                if m & (1 << i) != 0 {
1904                    acc | (1 << j)
1905                } else {
1906                    acc
1907                }
1908            });
1909            sub[sub_m] = true;
1910        }
1911        block_truths.push(describe::anf(&sub)?); // Möbius is its own inverse: sub-ANF → sub-truth
1912    }
1913    Some(SeparableDecomposition {
1914        num_vars: n,
1915        constant,
1916        blocks,
1917        block_truths,
1918    })
1919}
1920
1921// ---- Variable automorphisms: the permutation-symmetry group Aut(f) ----------------------------------
1922//
1923// The `symmetric` lens is the special case `Aut(f) = Sₙ` — invariance under EVERY variable permutation.
1924// This rung finds the whole permutation group `Aut(f) = {σ : f(σ·x) = f(x)}` and certifies it with a
1925// Schreier–Sims BSGS. It catches partial symmetry the full-symmetric lens declares residue: a
1926// ROTATION-symmetric function (invariant under a cyclic shift of the variables — an entire class in stream
1927// ciphers) is a permutation symmetry, NOT a linear one, so every rung of the linear ladder misses it. The
1928// group compresses the `2ⁿ` table to one value per input-orbit — exactly `n+1` weight classes when the
1929// group is `Sₙ`, recovering the symmetric lens as the top of this ladder.
1930
1931/// The variable-permutation symmetry of a Boolean function: a certified subgroup `G ≤ Aut(f)` and the
1932/// input-orbit compression it induces.
1933#[derive(Clone, Debug, PartialEq, Eq)]
1934pub struct VariableSymmetry {
1935    pub num_vars: usize,
1936    /// Generators of `G` (each a permutation of the `n` variables) — every one a verified automorphism.
1937    pub generators: Vec<Vec<usize>>,
1938    /// `|G|` — the certified group order from Schreier–Sims.
1939    pub order: u128,
1940    /// The number of orbits of inputs `{0,1}ⁿ` under `G`: the compressed table size (one value per orbit).
1941    pub orbit_count: usize,
1942    /// One value per orbit, indexed by the orbit's minimal representative in ascending order.
1943    pub orbit_values: Vec<bool>,
1944}
1945
1946impl VariableSymmetry {
1947    /// Whether the function has any nontrivial variable-permutation symmetry.
1948    pub fn is_nontrivial(&self) -> bool {
1949        self.order > 1
1950    }
1951    /// Rebuild the `2ⁿ` truth table by replaying the group action and painting each orbit its value — the
1952    /// re-checkable witness. `None` for a malformed report.
1953    pub fn reconstruct(&self, n: usize) -> Option<Vec<bool>> {
1954        let size = 1usize << n;
1955        if self.orbit_values.len() != self.orbit_count {
1956            return None;
1957        }
1958        let mut orbs = self.input_orbits(size)?;
1959        orbs.sort_by_key(|o| *o.iter().min().expect("nonempty orbit"));
1960        if orbs.len() != self.orbit_count {
1961            return None;
1962        }
1963        let mut out = vec![false; size];
1964        for (k, o) in orbs.iter().enumerate() {
1965            for &x in o {
1966                out[x] = self.orbit_values[k];
1967            }
1968        }
1969        Some(out)
1970    }
1971    /// Re-check: every generator is a genuine automorphism and the orbit painting reproduces `f`.
1972    pub fn verify(&self, truth: &[bool]) -> bool {
1973        for s in &self.generators {
1974            if s.len() != self.num_vars || !is_variable_automorphism(truth, s) {
1975                return false;
1976            }
1977        }
1978        self.reconstruct(self.num_vars).as_deref() == Some(truth)
1979    }
1980    fn input_orbits(&self, size: usize) -> Option<Vec<Vec<usize>>> {
1981        let lifted: Vec<Vec<usize>> = self
1982            .generators
1983            .iter()
1984            .map(|s| (0..size).map(|x| permute_input_bits(x, s)).collect())
1985            .collect();
1986        Some(if lifted.is_empty() {
1987            (0..size).map(|x| vec![x]).collect()
1988        } else {
1989            crate::permgroup::orbits(size, &lifted)
1990        })
1991    }
1992}
1993
1994/// Permute the input bits of `x` by the variable permutation `sigma`: bit `i` moves to bit `sigma[i]`.
1995fn permute_input_bits(x: usize, sigma: &[usize]) -> usize {
1996    sigma.iter().enumerate().fold(0usize, |acc, (i, &si)| {
1997        if x & (1 << i) != 0 {
1998            acc | (1 << si)
1999        } else {
2000            acc
2001        }
2002    })
2003}
2004
2005/// Whether `f(σ·x) = f(x)` for all `x` — i.e. `sigma` is a variable automorphism of the function.
2006fn is_variable_automorphism(truth: &[bool], sigma: &[usize]) -> bool {
2007    (0..truth.len()).all(|x| truth[x] == truth[permute_input_bits(x, sigma)])
2008}
2009
2010/// Find the variable-permutation symmetry group of a Boolean function: test every transposition and the
2011/// cyclic shift, certify the subgroup they generate with Schreier–Sims, and compress by input-orbits.
2012/// `None` if `truth.len()` is not a power of two.
2013pub fn variable_symmetry(truth: &[bool]) -> Option<VariableSymmetry> {
2014    if truth.is_empty() || !truth.len().is_power_of_two() {
2015        return None;
2016    }
2017    let n = truth.len().trailing_zeros() as usize;
2018    let mut generators: Vec<Vec<usize>> = Vec::new();
2019    for i in 0..n {
2020        for j in i + 1..n {
2021            let mut s: Vec<usize> = (0..n).collect();
2022            s.swap(i, j);
2023            if is_variable_automorphism(truth, &s) {
2024                generators.push(s);
2025            }
2026        }
2027    }
2028    // Products of two disjoint transpositions — the symmetries no single transposition realizes (e.g. a
2029    // reflection, or an even permutation fixing f that its transposition factors do not).
2030    for a in 0..n {
2031        for b in a + 1..n {
2032            for c in 0..n {
2033                if c == a || c == b {
2034                    continue;
2035                }
2036                for d in c + 1..n {
2037                    if d == a || d == b {
2038                        continue;
2039                    }
2040                    let mut s: Vec<usize> = (0..n).collect();
2041                    s.swap(a, b);
2042                    s.swap(c, d);
2043                    if is_variable_automorphism(truth, &s) {
2044                        generators.push(s);
2045                    }
2046                }
2047            }
2048        }
2049    }
2050    if n > 1 {
2051        let rho: Vec<usize> = (0..n).map(|i| (i + 1) % n).collect();
2052        if is_variable_automorphism(truth, &rho) {
2053            generators.push(rho);
2054        }
2055    }
2056    let order = crate::permgroup::schreier_sims(n, &generators).order();
2057    let size = 1usize << n;
2058    let sym = VariableSymmetry {
2059        num_vars: n,
2060        generators,
2061        order,
2062        orbit_count: 0,
2063        orbit_values: Vec::new(),
2064    };
2065    let mut orbs = sym.input_orbits(size)?;
2066    orbs.sort_by_key(|o| *o.iter().min().expect("nonempty orbit"));
2067    let orbit_values: Vec<bool> = orbs
2068        .iter()
2069        .map(|o| truth[*o.iter().min().expect("nonempty")])
2070        .collect();
2071    Some(VariableSymmetry {
2072        orbit_count: orbs.len(),
2073        orbit_values,
2074        ..sym
2075    })
2076}
2077
2078// ---- The unified deep finder: the tightest description across every axis ----------------------------
2079//
2080// Each rung is a different symmetry axis, and a function may be simple on one while dense on all the
2081// others: separable-but-high-degree, rotation-symmetric-but-not-linear, a rotated junta the coordinate
2082// walk calls residue. The deep finder runs EVERY axis — coordinate lenses, direct-sum separability, the
2083// Aut(f) permutation group, and linear-invariance reduction — and returns whichever gives the shortest
2084// description. Only when all of them fail to beat the raw truth table is the verdict `residue`: the honest
2085// incompressible core relative to the whole arsenal (never a proof of structurelessness — Chaitin).
2086
2087/// The winning axis and description size of the unified deep structure finder.
2088#[derive(Clone, Debug)]
2089pub struct DeepStructureReport {
2090    pub num_vars: usize,
2091    pub raw_bits: usize,
2092    pub description_bits: usize,
2093    /// Which axis gave the tightest description (`coordinate:*`, `separable`, `permutation`,
2094    /// `linear-invariance`, or `residue`).
2095    pub winner: &'static str,
2096    pub compressed: bool,
2097}
2098
2099/// Run every structural axis and return the globally tightest description of a Boolean function. `None` if
2100/// `truth.len()` is not a power of two.
2101pub fn find_structure_deep(truth: &[bool]) -> Option<DeepStructureReport> {
2102    if truth.is_empty() || !truth.len().is_power_of_two() {
2103        return None;
2104    }
2105    let n = truth.len().trailing_zeros() as usize;
2106    let raw = truth.len();
2107    let mut cands: Vec<(&'static str, usize)> = Vec::new();
2108
2109    if let Some(r) = find_structure(truth) {
2110        if r.compressed {
2111            let name = match r.class {
2112                CubeStructure::Constant(_) => "coordinate:constant",
2113                CubeStructure::Junta { .. } => "coordinate:junta",
2114                CubeStructure::Affine { .. } => "coordinate:affine",
2115                CubeStructure::Symmetric { .. } => "coordinate:symmetric",
2116                CubeStructure::LowDegree { .. } => "coordinate:low-degree",
2117                CubeStructure::ResistedArsenal { .. } => "coordinate:residue",
2118            };
2119            cands.push((name, r.description_bits));
2120        }
2121    }
2122    if let Some(d) = separable_decomposition(truth) {
2123        if d.is_separable() {
2124            cands.push(("separable", d.table_bits()));
2125        }
2126    }
2127    if let Some(s) = variable_symmetry(truth) {
2128        if s.is_nontrivial() {
2129            cands.push(("permutation", s.orbit_count));
2130        }
2131    }
2132    if let Some((red, _)) = reduce_by_invariance(truth) {
2133        cands.push(("linear-invariance", 1usize << red.reduced_vars));
2134    }
2135    if let Some(ar) = affine_reduce(truth) {
2136        cands.push(("affine", ar.reduced_truth.len() + n));
2137    }
2138
2139    let (winner, description_bits) = cands
2140        .into_iter()
2141        .filter(|(_, b)| *b < raw)
2142        .min_by_key(|(_, b)| *b)
2143        .unwrap_or(("residue", raw));
2144    Some(DeepStructureReport {
2145        num_vars: n,
2146        raw_bits: raw,
2147        description_bits,
2148        winner,
2149        compressed: description_bits < raw,
2150    })
2151}
2152
2153// ---- The recursive peel: structure all the way down to the fixed point -----------------------------
2154//
2155// The deep finder picks the tightest axis for the WHOLE function. The recursive peel goes further: it
2156// peels that axis and re-runs itself on the smaller function(s) it exposes — each block of a separable
2157// split, the reduced function of a linear-invariance peel — until it bottoms out in a coordinate leaf or
2158// the residue. A function like `((x0⊕x1)∧x2) ⊕ (x3∧x4∧x5)` splits into two blocks, and the first block
2159// then peels its rotated-junta invariance: a two-level tree the single-pass finder cannot express. The
2160// whole tree's `reconstruct` is one re-checkable witness for the entire decomposition. Recursion
2161// terminates because every peel strictly reduces the variable count.
2162
2163/// A recursive structural decomposition of a Boolean function: the fixed point of the deep finder.
2164#[derive(Clone, Debug, PartialEq, Eq)]
2165pub enum StructureTree {
2166    /// A coordinate-lens leaf (constant/junta/affine/symmetric/low-degree), reconstructable from `class`.
2167    Coordinate {
2168        class: CubeStructure,
2169        num_vars: usize,
2170        bits: usize,
2171    },
2172    /// A permutation-symmetry leaf: the orbit painting reconstructs it.
2173    Permutation {
2174        sym: VariableSymmetry,
2175        num_vars: usize,
2176    },
2177    /// The incompressible residue — stored raw (no axis compressed it).
2178    Residue { truth: Vec<bool> },
2179    /// Split into independent blocks, each recursively decomposed.
2180    Separable {
2181        num_vars: usize,
2182        constant: bool,
2183        blocks: Vec<(Vec<usize>, StructureTree)>,
2184    },
2185    /// Reduced by an invariance subspace; `inner` is the decomposition of the smaller function.
2186    LinearReduced {
2187        num_vars: usize,
2188        invariance_basis: Vec<usize>,
2189        free_positions: Vec<usize>,
2190        inner: Box<StructureTree>,
2191    },
2192    /// Peeled a linear form `⟨c,x⟩`, then reduced; `inner` decomposes the residual `h`.
2193    AffineReduced {
2194        num_vars: usize,
2195        linear_form: usize,
2196        invariance_basis: Vec<usize>,
2197        free_positions: Vec<usize>,
2198        inner: Box<StructureTree>,
2199    },
2200}
2201
2202impl StructureTree {
2203    /// The nesting depth of the decomposition (0 for a leaf).
2204    pub fn depth(&self) -> usize {
2205        match self {
2206            StructureTree::Coordinate { .. }
2207            | StructureTree::Permutation { .. }
2208            | StructureTree::Residue { .. } => 0,
2209            StructureTree::Separable { blocks, .. } => {
2210                1 + blocks.iter().map(|(_, t)| t.depth()).max().unwrap_or(0)
2211            }
2212            StructureTree::LinearReduced { inner, .. }
2213            | StructureTree::AffineReduced { inner, .. } => 1 + inner.depth(),
2214        }
2215    }
2216    /// The total description size in bits: the sum over the leaves, with a small charge per structural node.
2217    pub fn total_description_bits(&self) -> usize {
2218        match self {
2219            StructureTree::Coordinate { bits, .. } => *bits,
2220            StructureTree::Permutation { sym, .. } => sym.orbit_count,
2221            StructureTree::Residue { truth } => truth.len(),
2222            StructureTree::Separable { blocks, .. } => {
2223                1 + blocks
2224                    .iter()
2225                    .map(|(v, t)| v.len() + t.total_description_bits())
2226                    .sum::<usize>()
2227            }
2228            StructureTree::LinearReduced {
2229                invariance_basis,
2230                inner,
2231                ..
2232            } => invariance_basis.len() + inner.total_description_bits(),
2233            StructureTree::AffineReduced {
2234                num_vars, inner, ..
2235            } => *num_vars + inner.total_description_bits(),
2236        }
2237    }
2238    /// Rebuild the full `2ⁿ` truth table by composing the recursive descriptions — the whole-tree witness.
2239    pub fn reconstruct(&self) -> Option<Vec<bool>> {
2240        match self {
2241            StructureTree::Coordinate {
2242                class, num_vars, ..
2243            } => class.reconstruct(*num_vars),
2244            StructureTree::Permutation { sym, num_vars } => sym.reconstruct(*num_vars),
2245            StructureTree::Residue { truth } => Some(truth.clone()),
2246            StructureTree::Separable {
2247                num_vars,
2248                constant,
2249                blocks,
2250            } => {
2251                let size = 1usize << num_vars;
2252                let mut out = vec![*constant; size];
2253                for (vars, sub) in blocks {
2254                    let bt = sub.reconstruct()?;
2255                    for (x, slot) in out.iter_mut().enumerate() {
2256                        let y = vars.iter().enumerate().fold(0usize, |acc, (j, &i)| {
2257                            if x & (1 << i) != 0 {
2258                                acc | (1 << j)
2259                            } else {
2260                                acc
2261                            }
2262                        });
2263                        *slot ^= bt[y];
2264                    }
2265                }
2266                Some(out)
2267            }
2268            StructureTree::LinearReduced {
2269                num_vars,
2270                invariance_basis,
2271                free_positions,
2272                inner,
2273            } => {
2274                let inner_truth = inner.reconstruct()?;
2275                Some(
2276                    (0..1usize << num_vars)
2277                        .map(|x| {
2278                            let rep = reduce_by_basis(x, invariance_basis);
2279                            let y =
2280                                free_positions
2281                                    .iter()
2282                                    .enumerate()
2283                                    .fold(0usize, |acc, (j, &p)| {
2284                                        if rep & (1 << p) != 0 {
2285                                            acc | (1 << j)
2286                                        } else {
2287                                            acc
2288                                        }
2289                                    });
2290                            inner_truth[y]
2291                        })
2292                        .collect(),
2293                )
2294            }
2295            StructureTree::AffineReduced {
2296                num_vars,
2297                linear_form,
2298                invariance_basis,
2299                free_positions,
2300                inner,
2301            } => {
2302                let inner_truth = inner.reconstruct()?;
2303                Some(
2304                    (0..1usize << num_vars)
2305                        .map(|x| {
2306                            let rep = reduce_by_basis(x, invariance_basis);
2307                            let y =
2308                                free_positions
2309                                    .iter()
2310                                    .enumerate()
2311                                    .fold(0usize, |acc, (j, &p)| {
2312                                        if rep & (1 << p) != 0 {
2313                                            acc | (1 << j)
2314                                        } else {
2315                                            acc
2316                                        }
2317                                    });
2318                            inner_truth[y] ^ ((linear_form & x).count_ones() % 2 == 1)
2319                        })
2320                        .collect(),
2321                )
2322            }
2323        }
2324    }
2325}
2326
2327/// Recursively decompose a Boolean function to the fixed point of the deep finder: peel the tightest axis,
2328/// then re-run on the smaller function(s) it exposes, until a coordinate leaf or the residue. `None` if
2329/// `truth.len()` is not a power of two.
2330pub fn structure_tree(truth: &[bool]) -> Option<StructureTree> {
2331    if truth.is_empty() || !truth.len().is_power_of_two() {
2332        return None;
2333    }
2334    let n = truth.len().trailing_zeros() as usize;
2335    let deep = find_structure_deep(truth)?;
2336    let tree = match deep.winner {
2337        "separable" => {
2338            let d = separable_decomposition(truth)?;
2339            let mut blocks = Vec::with_capacity(d.blocks.len());
2340            for (vars, bt) in d.blocks.iter().zip(&d.block_truths) {
2341                blocks.push((vars.clone(), structure_tree(bt)?));
2342            }
2343            StructureTree::Separable {
2344                num_vars: n,
2345                constant: d.constant,
2346                blocks,
2347            }
2348        }
2349        "linear-invariance" => {
2350            let (red, basis) = reduce_by_invariance(truth)?;
2351            StructureTree::LinearReduced {
2352                num_vars: n,
2353                invariance_basis: basis,
2354                free_positions: red.free_positions.clone(),
2355                inner: Box::new(structure_tree(&red.reduced_truth)?),
2356            }
2357        }
2358        "affine" => {
2359            let ar = affine_reduce(truth)?;
2360            StructureTree::AffineReduced {
2361                num_vars: n,
2362                linear_form: ar.linear_form,
2363                invariance_basis: ar.invariance_basis,
2364                free_positions: ar.free_positions,
2365                inner: Box::new(structure_tree(&ar.reduced_truth)?),
2366            }
2367        }
2368        "permutation" => StructureTree::Permutation {
2369            sym: variable_symmetry(truth)?,
2370            num_vars: n,
2371        },
2372        "residue" => StructureTree::Residue {
2373            truth: truth.to_vec(),
2374        },
2375        _ => StructureTree::Coordinate {
2376            class: find_structure(truth)?.class,
2377            num_vars: n,
2378            bits: deep.description_bits,
2379        },
2380    };
2381    Some(tree)
2382}
2383
2384/// An exhaustive census of the whole Boolean-function space on `n` variables: which structural axis the
2385/// deep finder wins on, for every one of the `2^{2ⁿ}` functions.
2386#[derive(Clone, Debug)]
2387pub struct BooleanCensus {
2388    pub num_vars: usize,
2389    /// `2^{2ⁿ}` — the number of Boolean functions on `n` variables.
2390    pub total: usize,
2391    /// Each winning axis paired with how many functions it is the tightest description for.
2392    pub by_winner: Vec<(&'static str, usize)>,
2393    /// Functions some axis compressed (`total − residue`).
2394    pub compressed: usize,
2395    /// Functions no axis compressed — the incompressible residue relative to the whole arsenal.
2396    pub residue: usize,
2397}
2398
2399/// Exhaustively classify **every** Boolean function on `n` variables by the deep finder's winning axis.
2400/// `None` for `n = 0` or `n > 4` (beyond `2^{2⁴} = 65536` functions the space is astronomically large).
2401/// The residue count is the concrete, countable face of the Chaitin ceiling: it is a growing fraction of
2402/// the space as `n` rises — structured functions are `2^{poly}`, the space is `2^{2ⁿ}`.
2403pub fn boolean_function_census(n: usize) -> Option<BooleanCensus> {
2404    if n == 0 || n > 4 {
2405        return None;
2406    }
2407    let dim = 1usize << n;
2408    let total = 1u64 << dim;
2409    let mut counts: std::collections::BTreeMap<&'static str, usize> =
2410        std::collections::BTreeMap::new();
2411    for code in 0..total {
2412        let truth: Vec<bool> = (0..dim).map(|i| (code >> i) & 1 == 1).collect();
2413        *counts
2414            .entry(find_structure_deep(&truth)?.winner)
2415            .or_default() += 1;
2416    }
2417    let residue = counts.get("residue").copied().unwrap_or(0);
2418    Some(BooleanCensus {
2419        num_vars: n,
2420        total: total as usize,
2421        by_winner: counts.into_iter().collect(),
2422        compressed: total as usize - residue,
2423        residue,
2424    })
2425}
2426
2427/// A sampled census of the Boolean-function space on `n` variables, for `n` too large to enumerate.
2428#[derive(Clone, Debug)]
2429pub struct SampledCensus {
2430    pub num_vars: usize,
2431    pub samples: usize,
2432    /// How many sampled functions no axis compressed.
2433    pub residue: usize,
2434    pub by_winner: Vec<(&'static str, usize)>,
2435}
2436
2437impl SampledCensus {
2438    /// The estimated fraction of the space that is the incompressible residue.
2439    pub fn residue_fraction(&self) -> f64 {
2440        self.residue as f64 / self.samples.max(1) as f64
2441    }
2442}
2443
2444/// Estimate the coverage map at `n` variables (where `2^{2ⁿ}` is unenumerable) from a uniform random sample
2445/// of `samples` functions, classified by the deep finder's winning axis. `None` for `n = 0` or `n > 12`.
2446/// The residue fraction climbs toward `1` as `n` grows — the asymptotic form of the exhaustive census, and
2447/// the whole thesis: structured functions vanish and almost every function is incompressible.
2448pub fn sampled_boolean_census(n: usize, samples: usize, seed: u64) -> Option<SampledCensus> {
2449    if n == 0 || n > 12 {
2450        return None;
2451    }
2452    let dim = 1usize << n;
2453    let mut counts: std::collections::BTreeMap<&'static str, usize> =
2454        std::collections::BTreeMap::new();
2455    for s in 0..samples {
2456        let truth: Vec<bool> = (0..dim)
2457            .map(|i| {
2458                let mut z = seed
2459                    .wrapping_add((s as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15))
2460                    .wrapping_add(i as u64 + 1);
2461                z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
2462                z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
2463                (z ^ (z >> 31)) & 1 == 1
2464            })
2465            .collect();
2466        *counts
2467            .entry(find_structure_deep(&truth)?.winner)
2468            .or_default() += 1;
2469    }
2470    let residue = counts.get("residue").copied().unwrap_or(0);
2471    Some(SampledCensus {
2472        num_vars: n,
2473        samples,
2474        residue,
2475        by_winner: counts.into_iter().collect(),
2476    })
2477}
2478
2479/// A **certified Kolmogorov upper bound** on a Boolean function: the recursive structure decomposition and
2480/// its total description size, with a re-checkable decode witness. This is a `K̄` — an UPPER bound only.
2481/// The kernel-certified Chaitin theorem in this module forbids certifying `K(f) > c` for any function past
2482/// budget, so a bound that equals the raw `2ⁿ` means "irreducible by this arsenal," never "incompressible."
2483#[derive(Clone, Debug)]
2484pub struct KolmogorovBound {
2485    pub num_vars: usize,
2486    /// `K̄(f)` — the total description size of the recursive decomposition (a computable upper bound).
2487    pub bits: usize,
2488    /// `2ⁿ` — the cost of storing the truth table outright.
2489    pub raw_bits: usize,
2490    /// The recursive decomposition itself — the decode witness.
2491    pub tree: StructureTree,
2492}
2493
2494impl KolmogorovBound {
2495    /// `K̄(f) / 2ⁿ` — → 0 for the algorithmically simplest functions, 1 for the residue.
2496    pub fn ratio(&self) -> f64 {
2497        self.bits as f64 / self.raw_bits.max(1) as f64
2498    }
2499    /// Whether the decomposition beats storing the truth table.
2500    pub fn is_compressed(&self) -> bool {
2501        self.bits < self.raw_bits
2502    }
2503    /// Re-check the bound: the decomposition must decode back to the exact function.
2504    pub fn verify(&self, truth: &[bool]) -> bool {
2505        self.tree.reconstruct().as_deref() == Some(truth)
2506    }
2507}
2508
2509/// Compute a certified Kolmogorov upper bound for a Boolean function via its recursive structure
2510/// decomposition. `None` if `truth.len()` is not a power of two.
2511pub fn kolmogorov_bound(truth: &[bool]) -> Option<KolmogorovBound> {
2512    let n = truth.len().trailing_zeros() as usize;
2513    let tree = structure_tree(truth)?;
2514    Some(KolmogorovBound {
2515        num_vars: n,
2516        bits: tree.total_description_bits(),
2517        raw_bits: truth.len(),
2518        tree,
2519    })
2520}
2521
2522// ---- Vectorial Boolean functions (S-boxes): the ladder lifted to n→m bit maps ------------------------
2523//
2524// A block cipher's S-box is a vectorial Boolean function `S : {0,1}ⁿ → {0,1}ᵐ`, and its cryptographic
2525// STRENGTH is the absence of the very structure this whole module hunts. Every nonzero output mask `b`
2526// gives a component function `S_b(x) = ⟨b, S(x)⟩` — a single-output function we feed to the lenses above.
2527// The S-box is weak exactly when those components carry structure: low LINEARITY (a good linear
2528// approximation → linear cryptanalysis), low DIFFERENTIAL UNIFORMITY breached (a biased difference →
2529// differential cryptanalysis), low DEGREE (an algebraic relation), or outright affinity. A strong S-box —
2530// AES's — is the residue: high nonlinearity, differential uniformity 4, degree 7. "We broke AES" is not a
2531// claim these numbers support; they are exactly what certifies its S-box is sound.
2532
2533/// The cryptographic structural profile of an S-box.
2534#[derive(Clone, Debug, PartialEq, Eq)]
2535pub struct SboxProfile {
2536    pub in_bits: usize,
2537    pub out_bits: usize,
2538    /// The maximum count `#{x : S(x⊕a) ⊕ S(x) = b}` over `a≠0, b` — differential-cryptanalysis resistance
2539    /// (lower is stronger; `2` is the optimal APN bound).
2540    pub differential_uniformity: u32,
2541    /// `maxₐ,_{b≠0} |Σₓ (−1)^{⟨b,S(x)⟩ ⊕ ⟨a,x⟩}|` — linear-cryptanalysis resistance (lower is stronger).
2542    pub linearity: u64,
2543    /// The minimum algebraic degree over the nonzero component functions.
2544    pub min_degree: usize,
2545    /// Every component is affine — the trivially-broken S-box.
2546    pub is_affine: bool,
2547    /// A permutation (`n = m` and injective).
2548    pub is_bijective: bool,
2549    /// Almost perfect nonlinear: differential uniformity `2`, the optimal differential resistance.
2550    pub is_apn: bool,
2551}
2552
2553/// Profile an S-box `S : {0,1}ⁿ → {0,1}ᵐ` given as its output table (`sbox[x] = S(x)`, `out_bits = m`):
2554/// differential uniformity, linearity, minimum component degree, and the affine/bijective/APN flags.
2555/// `None` if the table length is not a power of two.
2556pub fn sbox_profile(sbox: &[u32], out_bits: usize) -> Option<SboxProfile> {
2557    if sbox.is_empty() || !sbox.len().is_power_of_two() {
2558        return None;
2559    }
2560    let n = sbox.len().trailing_zeros() as usize;
2561    let m = out_bits;
2562    let size = sbox.len();
2563
2564    let mut differential_uniformity = 0u32;
2565    for a in 1..size {
2566        let mut count = vec![0u32; 1usize << m];
2567        for x in 0..size {
2568            count[(sbox[x] ^ sbox[x ^ a]) as usize] += 1;
2569        }
2570        differential_uniformity = differential_uniformity.max(*count.iter().max().unwrap_or(&0));
2571    }
2572
2573    let mut linearity = 0u64;
2574    let mut min_degree = usize::MAX;
2575    let mut is_affine = true;
2576    for b in 1..(1usize << m) {
2577        let comp: Vec<bool> = sbox
2578            .iter()
2579            .map(|&y| (b as u32 & y).count_ones() % 2 == 1)
2580            .collect();
2581        let spec = describe::walsh_spectrum(&comp)?;
2582        linearity = linearity.max(spec.iter().map(|&c| c.unsigned_abs()).max().unwrap_or(0));
2583        let deg = describe::algebraic_degree(&comp)?;
2584        min_degree = min_degree.min(deg);
2585        if deg > 1 {
2586            is_affine = false;
2587        }
2588    }
2589
2590    let mut seen = vec![false; 1usize << m];
2591    let is_bijective = n == m
2592        && sbox.iter().all(|&y| {
2593            let u = y as usize;
2594            u < seen.len() && !std::mem::replace(&mut seen[u], true)
2595        });
2596
2597    Some(SboxProfile {
2598        in_bits: n,
2599        out_bits: m,
2600        differential_uniformity,
2601        linearity,
2602        min_degree: if min_degree == usize::MAX {
2603            0
2604        } else {
2605            min_degree
2606        },
2607        is_affine,
2608        is_bijective,
2609        is_apn: n == m && differential_uniformity == 2,
2610    })
2611}
2612
2613/// The affine-invariant spectra of an S-box: the fingerprints for classification up to affine equivalence.
2614#[derive(Clone, Debug, PartialEq, Eq)]
2615pub struct SboxSpectra {
2616    pub in_bits: usize,
2617    pub out_bits: usize,
2618    /// The differential spectrum: the multiset of DDT entries `#{x : S(x⊕a)⊕S(x)=b}` over `a≠0`, as
2619    /// `(value → count)` sorted. Invariant under any affine change of input or output coordinates.
2620    pub differential_spectrum: Vec<(u32, usize)>,
2621    /// The linear (Walsh) spectrum: the multiset of amplitudes `|Σₓ(−1)^{⟨b,S(x)⟩⊕⟨a,x⟩}|` over `a, b≠0`.
2622    pub walsh_spectrum: Vec<(u64, usize)>,
2623}
2624
2625/// The affine-equivalence fingerprint of an S-box: its differential and linear spectra. Two S-boxes that
2626/// are affine-equivalent (`S′(x) = B·S(A·x⊕a)⊕c` for invertible `A,B`) share both spectra, so a difference
2627/// in either certifies inequivalence — the necessary test at the heart of S-box classification. `None` if
2628/// the table length is not a power of two.
2629pub fn sbox_spectra(sbox: &[u32], out_bits: usize) -> Option<SboxSpectra> {
2630    if sbox.is_empty() || !sbox.len().is_power_of_two() {
2631        return None;
2632    }
2633    let n = sbox.len().trailing_zeros() as usize;
2634    let m = out_bits;
2635    let size = sbox.len();
2636
2637    let mut ddt_hist: std::collections::BTreeMap<u32, usize> = std::collections::BTreeMap::new();
2638    for a in 1..size {
2639        let mut count = vec![0u32; 1usize << m];
2640        for x in 0..size {
2641            count[(sbox[x] ^ sbox[x ^ a]) as usize] += 1;
2642        }
2643        for &c in &count {
2644            *ddt_hist.entry(c).or_default() += 1;
2645        }
2646    }
2647
2648    let mut walsh_hist: std::collections::BTreeMap<u64, usize> = std::collections::BTreeMap::new();
2649    for b in 1..(1usize << m) {
2650        let comp: Vec<bool> = sbox
2651            .iter()
2652            .map(|&y| (b as u32 & y).count_ones() % 2 == 1)
2653            .collect();
2654        for &w in &describe::walsh_spectrum(&comp)? {
2655            *walsh_hist.entry(w.unsigned_abs()).or_default() += 1;
2656        }
2657    }
2658
2659    Some(SboxSpectra {
2660        in_bits: n,
2661        out_bits: m,
2662        differential_spectrum: ddt_hist.into_iter().collect(),
2663        walsh_spectrum: walsh_hist.into_iter().collect(),
2664    })
2665}
2666
2667/// The **boomerang uniformity** of an S-box permutation — the third cryptanalytic pillar after
2668/// differential and linear. `BCT[a][b] = #{x : S⁻¹(S(x)⊕b) ⊕ S⁻¹(S(x⊕a)⊕b) = a}`; the uniformity is the
2669/// maximum over `a≠0, b≠0` and measures resistance to the boomerang attack (lower is stronger; `2` is
2670/// optimal, attained exactly by APN permutations). `None` if `sbox` is not a permutation.
2671pub fn boomerang_uniformity(sbox: &[u32]) -> Option<u32> {
2672    if sbox.is_empty() || !sbox.len().is_power_of_two() {
2673        return None;
2674    }
2675    let size = sbox.len();
2676    let mut inv = vec![u32::MAX; size];
2677    for (x, &y) in sbox.iter().enumerate() {
2678        let u = y as usize;
2679        if u >= size || inv[u] != u32::MAX {
2680            return None; // not a permutation
2681        }
2682        inv[u] = x as u32;
2683    }
2684    let mut bu = 0u32;
2685    for a in 1..size {
2686        for b in 1..size {
2687            let mut count = 0u32;
2688            for x in 0..size {
2689                let lhs = inv[(sbox[x] as usize) ^ b] ^ inv[(sbox[x ^ a] as usize) ^ b];
2690                if lhs as usize == a {
2691                    count += 1;
2692                }
2693            }
2694            bu = bu.max(count);
2695        }
2696    }
2697    Some(bu)
2698}
2699
2700/// The structural-security verdict on an S-box — the vectorial analogue of [`rsa_full_audit`]. It flags
2701/// only PROVABLE weaknesses (an exact linear relation, a deterministic difference, a quadratic system); a
2702/// clean profile is the honest ceiling, "no structural weakness of these classes," never a proof of
2703/// security (the Chaitin frame in the symmetric world).
2704#[derive(Clone, Debug, PartialEq, Eq)]
2705pub enum SboxVerdict {
2706    /// Every component is affine — trivially broken; linear cryptanalysis is exact.
2707    Affine,
2708    /// Some component `⟨b, S(x)⟩` is affine (`linearity = 2ⁿ`): a linear relation among the outputs holds
2709    /// with probability 1.
2710    LinearComponent,
2711    /// Some input difference forces a single output difference (`differential uniformity = 2ⁿ`).
2712    DeterministicDifference,
2713    /// Algebraic degree 2 — the S-box is a system of quadratic equations, the classic algebraic-attack target.
2714    Quadratic,
2715    /// No structural weakness of the above classes. The profile is the honest ceiling, not a security proof.
2716    NoStructuralWeaknessFound {
2717        differential_uniformity: u32,
2718        linearity: u64,
2719        min_degree: usize,
2720        boomerang_uniformity: Option<u32>,
2721    },
2722}
2723
2724/// Audit an S-box with the full structural arsenal — differential, linear, algebraic, and boomerang — and
2725/// return the first provable weakness, else the honest ceiling with the measured profile. `None` if the
2726/// table length is not a power of two. Threshold-free: it never fabricates a "weak" verdict from an
2727/// arbitrary cutoff, only from a structure that is exact.
2728pub fn sbox_full_audit(sbox: &[u32], out_bits: usize) -> Option<SboxVerdict> {
2729    let p = sbox_profile(sbox, out_bits)?;
2730    let full = 1u64 << p.in_bits;
2731    if p.is_affine {
2732        return Some(SboxVerdict::Affine);
2733    }
2734    if p.linearity == full {
2735        return Some(SboxVerdict::LinearComponent);
2736    }
2737    if p.differential_uniformity as u64 == full {
2738        return Some(SboxVerdict::DeterministicDifference);
2739    }
2740    if p.min_degree == 2 {
2741        return Some(SboxVerdict::Quadratic);
2742    }
2743    Some(SboxVerdict::NoStructuralWeaknessFound {
2744        differential_uniformity: p.differential_uniformity,
2745        linearity: p.linearity,
2746        min_degree: p.min_degree,
2747        boomerang_uniformity: if p.is_bijective {
2748            boomerang_uniformity(sbox)
2749        } else {
2750            None
2751        },
2752    })
2753}
2754
2755// ---- RSA: the thesis in the public-key world (structural weakness vs the number-theoretic ceiling) ---
2756//
2757// The compressibility ladder attacks SYMMETRIC keystreams through sequence structure; RSA rests on
2758// integer factorization instead, so none of those rungs touch it. But the same principle governs a
2759// modulus: a WEAK RSA key carries exploitable structure (a small factor, primes too close, a smooth
2760// `p−1`, a shared prime, a small private exponent), and each such structure is a compression — a short
2761// description of the secret — recovered as a certified factorization by `crate::factor`. A
2762// SOUND modulus has none: it is the number-theoretic incompressible residue, the Chaitin ceiling in the
2763// public-key world. Crush every structured form; the sound form stands, and that standing is the proof.
2764
2765/// The structural-security verdict on an RSA modulus.
2766#[derive(Clone, Debug, PartialEq, Eq)]
2767pub enum RsaStrength {
2768    /// A certified structural break: `p·q = N`, found by the named attack (a re-checkable witness).
2769    Factored {
2770        p: logicaffeine_base::BigInt,
2771        q: logicaffeine_base::BigInt,
2772        method: &'static str,
2773    },
2774    /// The whole structural arsenal declined within budget — no structural shortcut exists. Only the
2775    /// general sub-exponential algorithms remain, which real key sizes push out of reach: the ceiling.
2776    SoundAgainstStructuralAttacks,
2777}
2778
2779/// Audit an RSA modulus with the full structural factoring arsenal (see [`crate::factor`]):
2780/// return a certified factorization if any structural weakness exists, else the soundness verdict — the
2781/// number-theoretic incompressible residue. Uses the default triage budget.
2782pub fn rsa_structural_audit(n: &logicaffeine_base::BigInt) -> RsaStrength {
2783    match crate::factor::structural_factor(n, Default::default()) {
2784        Some(w) => RsaStrength::Factored {
2785            p: w.p,
2786            q: w.q,
2787            method: w.method,
2788        },
2789        None => RsaStrength::SoundAgainstStructuralAttacks,
2790    }
2791}
2792
2793/// The verdict of throwing the ENTIRE arsenal at an RSA public key.
2794#[derive(Clone, Debug, PartialEq, Eq)]
2795pub enum RsaAuditVerdict {
2796    /// The structural factoring suite split the modulus (the method names the structure it exploited).
2797    Factored {
2798        method: &'static str,
2799        p: logicaffeine_base::BigInt,
2800        q: logicaffeine_base::BigInt,
2801    },
2802    /// Wiener's attack found a small private exponent.
2803    WeakExponent,
2804    /// The compressibility classifier found exploitable structure in the modulus bytes.
2805    CompressibleModulus(CompressibilityClass),
2806    /// No lens in the arsenal compresses or factors it. This is NOT a proof of security — by the
2807    /// kernel-certified Chaitin bound (this module) no such proof exists — it is "resists everything we
2808    /// have built," the honest ceiling.
2809    ResistsFullArsenal,
2810}
2811
2812/// Throw the **entire arsenal** at an RSA public key `(N, e)`: the structural factoring suite (small
2813/// factor / close primes / smooth `p−1` / Pollard rho), Wiener's small-exponent attack, and the
2814/// compressibility classifier on the modulus bytes. This is the pre-release safety gate — if any of our
2815/// own mathematics broke RSA, this is where it would surface. `ResistsFullArsenal` is the honest ceiling,
2816/// not a security proof: we certify weakness whenever structure exists and can never certify its absence.
2817pub fn rsa_full_audit(
2818    n: &logicaffeine_base::BigInt,
2819    e: &logicaffeine_base::BigInt,
2820) -> RsaAuditVerdict {
2821    use crate::factor;
2822    if let Some(w) = factor::structural_factor(n, Default::default()) {
2823        return RsaAuditVerdict::Factored {
2824            method: w.method,
2825            p: w.p,
2826            q: w.q,
2827        };
2828    }
2829    if factor::wiener(e, n).is_some() {
2830        return RsaAuditVerdict::WeakExponent;
2831    }
2832    let (_, bytes) = n.to_le_bytes();
2833    let report = classify_bytes(&bytes);
2834    if report.class != CompressibilityClass::Incompressible {
2835        return RsaAuditVerdict::CompressibleModulus(report.class);
2836    }
2837    RsaAuditVerdict::ResistsFullArsenal
2838}
2839
2840/// Assess key/ciphertext bytes: `Weak` (with a re-checkable compression witness — the concrete attack)
2841/// when the engine describes the data in fewer bytes than storing it raw, else `IncompressibleInClass`.
2842pub fn assess_key_material(data: &[u8]) -> CryptoStrength {
2843    let ints: Vec<i64> = data.iter().map(|&b| b as i64).collect();
2844    let witness = DescriptionBound::of_int_seq(&ints);
2845    let ratio = if data.is_empty() {
2846        1.0
2847    } else {
2848        witness.bytes as f64 / data.len() as f64
2849    };
2850    // A description shorter than the raw bytes is a certified weakness — the witness IS the attack.
2851    if witness.bytes < data.len() {
2852        CryptoStrength::Weak { witness, ratio }
2853    } else {
2854        CryptoStrength::IncompressibleInClass { ratio }
2855    }
2856}
2857
2858// ---- Compressibility classes: where an input sits on the ordered → random spectrum --------------
2859//
2860// The description engine tries a whole menu of generators and keeps the shortest. The SHAPE of the
2861// winner is the input's *compressibility class* — a computable, certified shadow of Kolmogorov
2862// complexity — and how far it beats storing the raw bytes is the *degree*. From most to least
2863// structured: Generated (a tiny closed-form program) → Periodic → LowEntropy → Smooth → Incompressible
2864// (algorithmically random relative to this class).
2865
2866/// The compressibility class of an input, read off the winning description-menu generator.
2867#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2868pub enum CompressibilityClass {
2869    /// A closed-form program reproduces it (affine / geometric / polynomial / general generator) —
2870    /// algorithmically simplest: K̄ = O(1) regardless of length.
2871    Generated,
2872    /// A repeating block (cyclic / periodic).
2873    Periodic,
2874    /// Low per-symbol entropy: a dominant value, long runs, or a tiny alphabet (sparse / RLE / dict).
2875    LowEntropy,
2876    /// Smoothly varying: small successive differences or a narrow value range (delta / DoD / frame-of-reference).
2877    Smooth,
2878    /// Incompressible: nothing beats storing it raw — algorithmically random relative to this class.
2879    Incompressible,
2880}
2881
2882/// A full compressibility report: the class, the degree (`K̄/n`), and the raw vs described sizes.
2883#[derive(Clone, Debug)]
2884pub struct CompressibilityReport {
2885    pub class: CompressibilityClass,
2886    /// `K̄ / n` — described bytes over raw bytes. ≈ 1 incompressible; → 0 algorithmically simple.
2887    pub ratio: f64,
2888    pub described_bytes: usize,
2889    pub raw_bytes: usize,
2890}
2891
2892/// Classify a byte string by its compressibility class and degree.
2893pub fn classify_bytes(data: &[u8]) -> CompressibilityReport {
2894    let ints: Vec<i64> = data.iter().map(|&b| b as i64).collect();
2895    let described = describe::describe_int_seq(&ints);
2896    let raw = data.len();
2897    let ratio = if raw == 0 {
2898        1.0
2899    } else {
2900        described.len() as f64 / raw as f64
2901    };
2902    let class = if described.len() >= raw.max(1) {
2903        // Nothing beat storing the bytes raw ⇒ incompressible, whatever the nominal winning tag.
2904        CompressibilityClass::Incompressible
2905    } else {
2906        class_of_tag(described.first().copied().unwrap_or(describe::T_INTS))
2907    };
2908    CompressibilityReport {
2909        class,
2910        ratio,
2911        described_bytes: described.len(),
2912        raw_bytes: raw,
2913    }
2914}
2915
2916/// Classify a text string by the compressibility class of its UTF-8 bytes.
2917pub fn classify_text(text: &str) -> CompressibilityReport {
2918    classify_bytes(text.as_bytes())
2919}
2920
2921/// Classify an integer sequence (numeric data, not bytes) by its compressibility class, measured
2922/// against the plain varint encoding — so a linear recurrence (Fibonacci-class) is recognized as a
2923/// closed-form `Generated` program even though it grows past byte range.
2924pub fn classify_int_seq(data: &[i64]) -> CompressibilityReport {
2925    let described = describe::describe_int_seq(data);
2926    let mut baseline = vec![describe::T_INTS];
2927    describe::leb128_encode(&mut baseline, data.iter().copied(), data.len());
2928    let raw = baseline.len();
2929    let ratio = if raw == 0 {
2930        1.0
2931    } else {
2932        described.len() as f64 / raw as f64
2933    };
2934    let class = if described.len() >= raw {
2935        CompressibilityClass::Incompressible
2936    } else {
2937        class_of_tag(described.first().copied().unwrap_or(describe::T_INTS))
2938    };
2939    CompressibilityReport {
2940        class,
2941        ratio,
2942        described_bytes: described.len(),
2943        raw_bytes: raw,
2944    }
2945}
2946
2947/// Map a winning description-menu tag to its compressibility class.
2948fn class_of_tag(tag: u8) -> CompressibilityClass {
2949    use describe::*;
2950    match tag {
2951        t if t == T_INTS_AFFINE
2952            || t == T_INTS_GEOMETRIC
2953            || t == T_INTS_POLY
2954            || t == T_GEN
2955            || t == T_INTS_LRECUR =>
2956        {
2957            CompressibilityClass::Generated
2958        }
2959        t if t == T_INTS_PERIODIC => CompressibilityClass::Periodic,
2960        t if t == T_INTS_SPARSE || t == T_INTS_RLE || t == T_INTS_DICT => {
2961            CompressibilityClass::LowEntropy
2962        }
2963        t if t == T_INTS_DELTA || t == T_INTS_DOD || t == T_INTS_FOR => {
2964            CompressibilityClass::Smooth
2965        }
2966        _ => CompressibilityClass::Incompressible, // T_INTS / T_BYTES: no exploitable structure of this class
2967    }
2968}
2969
2970/// Whether the given GF(2) vectors (each ≤ 64-wide) are linearly independent — Gaussian elimination
2971/// over GF(2), full rank iff rank equals the count.
2972fn independent_gf2(vectors: &[Vec<bool>]) -> bool {
2973    let mut rows: Vec<u64> = vectors
2974        .iter()
2975        .map(|v| {
2976            v.iter().enumerate().fold(
2977                0u64,
2978                |m, (i, &b)| if b && i < 64 { m | (1u64 << i) } else { m },
2979            )
2980        })
2981        .collect();
2982    let mut rank = 0usize;
2983    for col in 0..64u32 {
2984        if let Some(piv) = (rank..rows.len()).find(|&r| rows[r] & (1u64 << col) != 0) {
2985            rows.swap(rank, piv);
2986            let pr = rows[rank];
2987            for r in 0..rows.len() {
2988                if r != rank && rows[r] & (1u64 << col) != 0 {
2989                    rows[r] ^= pr;
2990                }
2991            }
2992            rank += 1;
2993        }
2994    }
2995    rank == vectors.len()
2996}
2997
2998#[cfg(test)]
2999#[path = "../../logicaffeine_tests/unit/logicaffeine_proof/ait/tests.rs"]
3000mod tests;