Skip to main content

semi_persistent_egraph/
director.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Director bitmatrix primitives for the future alpha-equivalence design.
4//!
5//! See `egraph/doc/future/alpha-equivalence.md` for the full design.
6
7use core::fmt;
8use core::hash::Hash;
9
10use crate::containers::IndexLike;
11use crate::containers::Tagged;
12use crate::containers::{AppendOnlyVec, ShrinkPolicy, VecI, VecToken};
13
14// ---------------------------------------------------------------------------
15// PortArity — transparent newtype over u8 for matrix dimensions
16// ---------------------------------------------------------------------------
17
18/// Matrix dimension / e-class arity. Transparent wrapper over `u8`.
19/// Max value 255, checked arithmetic on increment.
20#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
21#[repr(transparent)]
22pub struct PortArity(pub u8);
23
24impl PortArity {
25    pub const ZERO: Self = PortArity(0);
26    pub const ONE: Self = PortArity(1);
27    pub const MAX: Self = PortArity(u8::MAX);
28
29    #[inline]
30    pub fn new(n: u8) -> Self {
31        PortArity(n)
32    }
33
34    /// Checked increment. Panics with diagnostic on overflow.
35    #[inline]
36    pub fn checked_add(self, d: PortArity) -> Self {
37        PortArity(self.0.checked_add(d.0).expect("arity overflow (max 255)"))
38    }
39
40    /// `max(self, other)` — used for merge.
41    #[inline]
42    pub fn max(self, other: Self) -> Self {
43        PortArity(self.0.max(other.0))
44    }
45
46    /// Product `self * other` as u32 (for bit count calculations).
47    #[inline]
48    pub fn product(self, other: Self) -> u32 {
49        (self.0 as u32) * (other.0 as u32)
50    }
51}
52
53impl From<PortArity> for u8 {
54    #[inline]
55    fn from(a: PortArity) -> u8 {
56        a.0
57    }
58}
59
60impl From<u8> for PortArity {
61    #[inline]
62    fn from(n: u8) -> PortArity {
63        PortArity(n)
64    }
65}
66
67impl From<PortArity> for u32 {
68    #[inline]
69    fn from(a: PortArity) -> u32 {
70        a.0 as u32
71    }
72}
73
74impl From<PortArity> for usize {
75    #[inline]
76    fn from(a: PortArity) -> usize {
77        a.0 as usize
78    }
79}
80
81impl fmt::Debug for PortArity {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        write!(f, "{}", self.0)
84    }
85}
86
87impl fmt::Display for PortArity {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        write!(f, "{}", self.0)
90    }
91}
92
93// ---------------------------------------------------------------------------
94// DirectorBits — compile-time word width for inline director storage
95// ---------------------------------------------------------------------------
96
97/// Trait selecting the inline bit width for director matrices.
98///
99/// `BITS = 0` (impl for `()`) disables binder support entirely.
100/// `BITS > 0` reserves the MSB as a spill tag, leaving `BITS - 1`
101/// inline matrix bits.
102pub trait DirectorBits: Copy + Eq + Hash + Ord + fmt::Debug + 'static {
103    const BITS: u32;
104    const SPILL_TAG: Self;
105    fn from_u64(v: u64) -> Self;
106    fn to_u64(self) -> u64;
107}
108
109// -- () : no director payload --
110
111impl DirectorBits for () {
112    const BITS: u32 = 0;
113    const SPILL_TAG: Self = ();
114    #[inline(always)]
115    fn from_u64(_: u64) -> Self {}
116    #[inline(always)]
117    fn to_u64(self) -> u64 {
118        0
119    }
120}
121
122// -- u16 : 15 inline bits --
123
124impl DirectorBits for u16 {
125    const BITS: u32 = 16;
126    const SPILL_TAG: Self = 0x8000;
127    #[inline(always)]
128    fn from_u64(v: u64) -> Self {
129        v as u16
130    }
131    #[inline(always)]
132    fn to_u64(self) -> u64 {
133        self as u64
134    }
135}
136
137// -- u32 : 31 inline bits --
138
139impl DirectorBits for u32 {
140    const BITS: u32 = 32;
141    const SPILL_TAG: Self = 0x8000_0000;
142    #[inline(always)]
143    fn from_u64(v: u64) -> Self {
144        v as u32
145    }
146    #[inline(always)]
147    fn to_u64(self) -> u64 {
148        self as u64
149    }
150}
151
152// -- u64 : 63 inline bits --
153
154impl DirectorBits for u64 {
155    const BITS: u32 = 64;
156    const SPILL_TAG: Self = 0x8000_0000_0000_0000;
157    #[inline(always)]
158    fn from_u64(v: u64) -> Self {
159        v
160    }
161    #[inline(always)]
162    fn to_u64(self) -> u64 {
163        self
164    }
165}
166
167// ---------------------------------------------------------------------------
168// Director<W> — inline or spilled director bitmatrix
169// ---------------------------------------------------------------------------
170
171/// Bit count of a k×n matrix, checked against the 64-bit ceiling [`ops`] imposes.
172///
173/// Every [`ops`] routine packs a whole matrix into one `u64`, so `k * n` must be at
174/// most 64. Nothing enforced that: `ops::identity(9, 9)` evaluates `1u64 << 80`, which
175/// panics in debug and — because Rust *masks* the shift amount in release — becomes
176/// `1u64 << 16` there, silently producing a matrix that is not the identity. Every
177/// dimension entering the typed `Director<W>` API now routes through here, so the cap
178/// fails loudly in both profiles.
179///
180/// The product itself cannot overflow: both factors are `u8`, so it is at most 65025.
181#[inline]
182fn matrix_bits(k: u8, n: u8) -> u32 {
183    let bits = (k as u32) * (n as u32);
184    assert!(
185        bits <= 64,
186        "director matrix {k}×{n} needs {bits} bits; the matrix ops pack a matrix into a \
187         single u64 and cannot exceed 64"
188    );
189    bits
190}
191
192/// The pool entry a spilled [`Director`] names, in the pool's own index word.
193///
194/// Infallible for an index the pool handed out, since it came from an `I`. Checked
195/// anyway because `Director::new_spilled` is public: a caller can name an entry the
196/// pool could not have created, and the read should refuse rather than wrap.
197#[inline]
198fn pool_start<I: IndexLike>(pool_index: usize) -> I {
199    <I as IndexLike>::try_from_usize(pool_index)
200        .expect("director spill index exceeds the pool's index word")
201}
202
203/// A k×n bit matrix stored inline (MSB=0) or as a spill pool reference (MSB=1).
204///
205/// When `W = ()`, the handle is a ZST. This is a layout fact about the handle,
206/// not a whole-engine code-generation or runtime-overhead claim.
207#[derive(Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
208pub struct Director<W: DirectorBits>(pub(crate) W);
209
210impl<W: DirectorBits> fmt::Debug for Director<W> {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        if W::BITS == 0 {
213            write!(f, "Dir(∅)")
214        } else if self.is_inline() {
215            write!(f, "Dir(0x{:x})", self.0.to_u64())
216        } else {
217            write!(f, "Dir(spill@{})", self.pool_index())
218        }
219    }
220}
221
222impl<W: DirectorBits> Director<W> {
223    /// All-zero matrix (ground edge, no variable ports).
224    #[inline]
225    pub fn zero() -> Self {
226        Director(W::from_u64(0))
227    }
228
229    /// Inline matrix from raw bits. Panics if bits overflow inline capacity.
230    #[inline]
231    pub fn new_inline(bits: u64) -> Self {
232        if W::BITS > 0 {
233            // Hard assert against the full payload width, not the tag bit alone —
234            // `new_spilled`'s doc records the two ways the old `debug_assert` was
235            // wrong, and this constructor had kept both: `0x1_0001` passed the
236            // one-bit test and truncated to `1` in `W::from_u64`.
237            assert!(
238                bits < W::SPILL_TAG.to_u64(),
239                "inline bits overflow the director word's payload"
240            );
241        }
242        Director(W::from_u64(bits))
243    }
244
245    /// Spilled matrix referencing a pool entry.
246    ///
247    /// # Capacity
248    ///
249    /// The index shares the director word with the spill tag, so only `BITS - 1` bits
250    /// are available to name a pool entry — 32768 entries for `W = u16`, a size a real
251    /// pool reaches easily. The bound is a hard `assert!` because the old
252    /// `debug_assert!` was wrong twice over: it vanished in release, and it compared
253    /// against the tag bit alone, so `0x8000` was rejected while `0x10000` passed and
254    /// then truncated to `0` in `W::from_u64`, aliasing pool entry 0.
255    #[inline]
256    pub fn new_spilled(pool_index: usize) -> Self {
257        assert!(W::BITS > 0, "cannot spill with DIRECTOR_BITS=0");
258        let idx = pool_index as u64;
259        let capacity = 1u64 << (W::BITS - 1);
260        assert!(
261            idx < capacity,
262            "director spill index {idx} does not fit the {} bits available beside the \
263             spill tag; configure a wider DirectorBits word",
264            W::BITS - 1
265        );
266        Director(W::from_u64(idx | W::SPILL_TAG.to_u64()))
267    }
268
269    /// True if the matrix data is stored inline (not spilled).
270    #[inline]
271    pub fn is_inline(&self) -> bool {
272        W::BITS == 0 || (self.0.to_u64() & W::SPILL_TAG.to_u64()) == 0
273    }
274
275    /// Raw inline bits. Panics if spilled.
276    ///
277    /// A hard `assert!`: as a `debug_assert!` this returned the *pool index* as if it
278    /// were matrix data in release builds — a silently wrong matrix, not a crash. The
279    /// hot path (`resolve`) reads the word directly inside its `is_inline()` branch, so
280    /// nothing pays for the check twice.
281    #[inline]
282    pub fn inline_bits(&self) -> u64 {
283        assert!(self.is_inline(), "called inline_bits on spilled matrix");
284        self.0.to_u64()
285    }
286
287    /// Pool start index. Panics if inline.
288    ///
289    /// A hard `assert!` for the mirror-image reason: in release this handed back matrix
290    /// bits as a pool index, reading an unrelated entry.
291    #[inline]
292    pub fn pool_index(&self) -> usize {
293        assert!(!self.is_inline(), "called pool_index on inline matrix");
294        (self.0.to_u64() & !W::SPILL_TAG.to_u64()) as usize
295    }
296
297    /// Raw word value (for hashing, sort keys).
298    #[inline]
299    pub fn raw(&self) -> W {
300        self.0
301    }
302
303    // -- Resolve / pack helpers -----------------------------------------------
304
305    /// Resolve to raw u64 bits. For inline, returns the bits directly.
306    /// For spilled, reads from pool and packs into a single u64.
307    /// Panics if spilled matrix exceeds 64 bits (caller must use
308    /// `resolve_pooled` for large matrices).
309    fn resolve<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
310        &self,
311        pool: &DirectorPool<I, TRACK, PROOFS>,
312    ) -> u64 {
313        if W::BITS == 0 {
314            return 0;
315        }
316        if self.is_inline() {
317            // The tag is already known clear, so read the word rather than paying for
318            // `inline_bits`'s assert again.
319            self.0.to_u64()
320        } else {
321            let spilled = (self.0.to_u64() & !W::SPILL_TAG.to_u64()) as usize;
322            let (bit_length, data) = pool.read(pool_start::<I>(spilled));
323            assert!(bit_length <= 64, "spilled matrix too large for resolve()");
324            // Reassemble across pool words. A word carries 63 matrix bits — its MSB is
325            // the `Tagged` capture bit — so a 64-bit matrix occupies two of them. The
326            // old body read `data[0]` alone and silently dropped bit 63.
327            let mut bits = 0u64;
328            for (i, w) in data.iter().enumerate() {
329                let shift = (i as u32) * PoolDirector::USABLE_BITS;
330                bits |= w
331                    .bits()
332                    .checked_shl(shift)
333                    .expect("spilled matrix wider than 64 bits reached resolve()");
334            }
335            bits
336        }
337    }
338
339    /// Pack raw u64 bits into a Director<W>. If the bits fit inline, store
340    /// directly. Otherwise spill to pool.
341    fn pack<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
342        bits: u64,
343        total_bits: u32,
344        pool: &mut DirectorPool<I, TRACK, PROOFS>,
345    ) -> Self {
346        if W::BITS == 0 {
347            return Self::zero();
348        }
349        let inline_cap = W::BITS - 1;
350        if total_bits <= inline_cap && (bits & W::SPILL_TAG.to_u64()) == 0 {
351            Self::new_inline(bits)
352        } else {
353            // Split across pool words. A word's MSB is the `Tagged` capture bit, so it
354            // carries 63 matrix bits and a 64-bit matrix needs two. The old body wrote
355            // the single word `PoolDirector::new(bits)`; for a 64-bit matrix
356            // (`identity(8, 8)` sets bit 63) that dropped the top bit *and* set the
357            // capture tag, corrupting rollback. Only a `debug_assert!` noticed.
358            let mut data = std::vec::Vec::with_capacity(2);
359            let mut rest = bits;
360            let mut remaining = total_bits;
361            loop {
362                data.push(PoolDirector::new(rest & PoolDirector::DATA_MASK));
363                if remaining <= PoolDirector::USABLE_BITS {
364                    break;
365                }
366                rest >>= PoolDirector::USABLE_BITS;
367                remaining -= PoolDirector::USABLE_BITS;
368            }
369            let start = pool.append(total_bits, &data);
370            Self::new_spilled(start.as_usize())
371        }
372    }
373
374    // -- Reads ----------------------------------------------------------------
375
376    /// Extract row `i` from a k×n matrix. Returns an n-bit value with
377    /// at most one bit set (the parent port that child port `i` maps to).
378    /// Zero means child port `i` is unbound (consumed by a binder).
379    pub fn row_extract<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
380        &self,
381        i: u8,
382        n: u8,
383        pool: &DirectorPool<I, TRACK, PROOFS>,
384    ) -> u64 {
385        // Row `i` occupies bits `i*n .. (i+1)*n`, so the row *past* it must still fit
386        // the single u64 `ops` works in — that is what bounds the `i*n` shift.
387        matrix_bits(i.checked_add(1).expect("row index 255 has no successor"), n);
388        ops::row_extract(self.resolve(pool), i, n)
389    }
390
391    /// Does any child port map to parent port `j`?
392    pub fn col_present<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
393        &self,
394        j: u8,
395        k: u8,
396        n: u8,
397        pool: &DirectorPool<I, TRACK, PROOFS>,
398    ) -> bool {
399        matrix_bits(k, n);
400        assert!(j < n, "column {j} out of range for a matrix of width {n}");
401        ops::col_present(self.resolve(pool), j, k, n)
402    }
403
404    /// OR of all rows: which parent ports are referenced by any child port?
405    pub fn embed_bitset<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
406        &self,
407        k: u8,
408        n: u8,
409        pool: &DirectorPool<I, TRACK, PROOFS>,
410    ) -> u64 {
411        matrix_bits(k, n);
412        ops::embed_bitset(self.resolve(pool), k, n)
413    }
414
415    // -- Transforms -----------------------------------------------------------
416
417    /// Chain two edges: outer (k_mid × n_outer) ∘ inner (k_inner × k_mid).
418    /// Result is k_inner × n_outer.
419    pub fn compose<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
420        outer: &Self,
421        inner: &Self,
422        k_inner: u8,
423        k_mid: u8,
424        n_outer: u8,
425        pool: &mut DirectorPool<I, TRACK, PROOFS>,
426    ) -> Self {
427        // All three matrices pass through `ops`, so each must fit its own u64.
428        matrix_bits(k_inner, k_mid);
429        matrix_bits(k_mid, n_outer);
430        let total = matrix_bits(k_inner, n_outer);
431        let ob = outer.resolve(pool);
432        let ib = inner.resolve(pool);
433        let result = ops::compose(ob, ib, k_inner, k_mid, n_outer);
434        Self::pack(result, total, pool)
435    }
436
437    /// Parent arity grew from old_n to new_n. Re-lay rows to wider width.
438    pub fn widen_columns<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
439        &self,
440        k: u8,
441        old_n: u8,
442        new_n: u8,
443        pool: &mut DirectorPool<I, TRACK, PROOFS>,
444    ) -> Self {
445        // `new_n >= old_n`, so the wider result dominates: one check bounds both.
446        let total = matrix_bits(k, new_n);
447        let bits = self.resolve(pool);
448        let result = ops::widen_columns(bits, k, old_n, new_n);
449        Self::pack(result, total, pool)
450    }
451
452    /// Child arity grew from old_k to new_k. New rows are zero.
453    pub fn add_zero_rows<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
454        &self,
455        old_k: u8,
456        new_k: u8,
457        n: u8,
458        pool: &mut DirectorPool<I, TRACK, PROOFS>,
459    ) -> Self {
460        // `new_k >= old_k`, so the taller result dominates: one check bounds both.
461        let total = matrix_bits(new_k, n);
462        let bits = self.resolve(pool);
463        let result = ops::add_zero_rows(bits, old_k, new_k, n);
464        Self::pack(result, total, pool)
465    }
466
467    /// Reorder rows according to a permutation (port reconciliation on merge).
468    pub fn permute_rows<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
469        &self,
470        perm: &[u8],
471        k: u8,
472        n: u8,
473        pool: &mut DirectorPool<I, TRACK, PROOFS>,
474    ) -> Self {
475        let total = matrix_bits(k, n);
476        let bits = self.resolve(pool);
477        let result = ops::permute_rows(bits, perm, k, n);
478        Self::pack(result, total, pool)
479    }
480
481    /// Introduce `d` bound variable ports. Input k×n → result (k+d)×(n+d).
482    pub fn shift<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
483        &self,
484        k: u8,
485        n: u8,
486        d: u8,
487        pool: &mut DirectorPool<I, TRACK, PROOFS>,
488    ) -> Self {
489        // `k + d` and `n + d` were unchecked `u8` adds. The grown matrix dominates the
490        // input, so checking it bounds both — including the `n + d` add `ops::shift`
491        // repeats internally.
492        let new_k = k.checked_add(d).expect("child arity overflow (max 255)");
493        let new_n = n.checked_add(d).expect("parent arity overflow (max 255)");
494        let total = matrix_bits(new_k, new_n);
495        let bits = self.resolve(pool);
496        let result = ops::shift(bits, k, n, d);
497        Self::pack(result, total, pool)
498    }
499
500    /// Eliminate parent port `j` (substitution). Input k×n → result k×(n-1).
501    pub fn delete_column<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
502        &self,
503        j: u8,
504        k: u8,
505        n: u8,
506        pool: &mut DirectorPool<I, TRACK, PROOFS>,
507    ) -> Self {
508        // `n - 1` was an unchecked `u8` sub: `n == 0` wrapped to 255 in release, and
509        // the `debug_assert!(n > 0)` inside `ops::delete_column` was gone by then.
510        let new_n = n
511            .checked_sub(1)
512            .expect("delete_column on a matrix with no columns");
513        assert!(j < n, "column {j} out of range for a matrix of width {n}");
514        // The input dominates the result (`k*n >= k*(n-1)`), so check it too.
515        matrix_bits(k, n);
516        let total = matrix_bits(k, new_n);
517        let bits = self.resolve(pool);
518        let result = ops::delete_column(bits, j, k, n);
519        Self::pack(result, total, pool)
520    }
521
522    // -- Constructors ---------------------------------------------------------
523
524    /// k×n identity matrix. Spills if k*n exceeds inline capacity.
525    pub fn identity<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
526        k: u8,
527        n: u8,
528        pool: &mut DirectorPool<I, TRACK, PROOFS>,
529    ) -> Self {
530        let total = matrix_bits(k, n);
531        let bits = ops::identity(k, n);
532        Self::pack(bits, total, pool)
533    }
534}
535
536// ---------------------------------------------------------------------------
537// Edge<G, W> — e-class id + director matrix
538// ---------------------------------------------------------------------------
539
540/// An edge from a parent e-node to a child e-class, carrying a director
541/// matrix that routes variable ports.
542///
543/// When `W = ()`, this has the same size and layout as `G`.
544#[derive(Clone, Copy, PartialEq, Eq, Hash)]
545pub struct Edge<G, W: DirectorBits> {
546    pub class: G,
547    pub director: Director<W>,
548}
549
550impl<G: fmt::Debug, W: DirectorBits> fmt::Debug for Edge<G, W> {
551    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552        if W::BITS == 0 {
553            write!(f, "{:?}", self.class)
554        } else {
555            write!(f, "({:?}, {:?})", self.class, self.director)
556        }
557    }
558}
559
560impl<G, W: DirectorBits> Edge<G, W> {
561    #[inline]
562    pub fn new(class: G, director: Director<W>) -> Self {
563        Self { class, director }
564    }
565
566    /// Ground edge (no variable ports).
567    #[inline]
568    pub fn ground(class: G) -> Self {
569        Self {
570            class,
571            director: Director::zero(),
572        }
573    }
574}
575
576// ---------------------------------------------------------------------------
577// PoolDirector — a u64 with MSB stolen for Tagged capture tracking
578// ---------------------------------------------------------------------------
579
580/// A 64-bit word stored in the spill pool. The MSB is reserved for the
581/// `Tagged` capture bit used by `SemiVec`, leaving 63 usable bits for
582/// director matrix data.
583#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
584pub struct PoolDirector(u64);
585
586// Filler for `resize_default` during restore; never observed. `new(0)` leaves
587// the MSB tag bit clear, so the all-zero word is niche-safe.
588impl Default for PoolDirector {
589    fn default() -> Self {
590        PoolDirector::new(0)
591    }
592}
593
594impl PoolDirector {
595    /// Usable bits per pool word (64 - 1 tag bit).
596    pub const USABLE_BITS: u32 = 63;
597    /// Mask selecting the usable bits, i.e. everything but the tag.
598    pub const DATA_MASK: u64 = !Self::TAG_BIT;
599    const TAG_BIT: u64 = 1 << 63;
600
601    #[inline]
602    pub fn new(bits: u64) -> Self {
603        debug_assert!(
604            bits & Self::TAG_BIT == 0,
605            "pool word overflow: bit 63 reserved"
606        );
607        PoolDirector(bits)
608    }
609
610    #[inline]
611    pub fn bits(self) -> u64 {
612        self.0 & !Self::TAG_BIT
613    }
614}
615
616impl Tagged for PoolDirector {
617    type Repr = Self;
618
619    #[inline]
620    fn into_repr(self) -> Self {
621        self
622    }
623
624    #[inline]
625    fn from_repr(r: &Self) -> Self {
626        PoolDirector(r.0 & !Self::TAG_BIT)
627    }
628
629    #[inline]
630    fn tag(r: &Self) -> bool {
631        r.0 & Self::TAG_BIT != 0
632    }
633
634    #[inline]
635    fn set_tag(r: &mut Self) {
636        r.0 |= Self::TAG_BIT;
637    }
638
639    #[inline]
640    fn clear_tag(r: &mut Self) {
641        r.0 &= !Self::TAG_BIT;
642    }
643}
644
645// ---------------------------------------------------------------------------
646// DirectorPool — append-only spill arena for oversized director matrices
647// ---------------------------------------------------------------------------
648
649/// Semi-persistent spill pool for oversized director matrices.
650///
651/// Each entry is length-prefixed:
652///   `pool[start]`     = bit_length (as PoolDirector)
653///   `pool[start+1..]` = matrix data, `ceil(bit_length / 63)` words
654///
655/// The working pool is a `VecI<PoolDirector, I, TRACK>` — supports in-place
656/// mutation (for re-canonization during rebuild) with capture tracking.
657///
658/// When `PROOFS = true`, a separate append-only proof pool snapshots
659/// spilled matrices at copy-on-first-recanonicalization time. The proof
660/// pool is never truncated during working rollback.
661///
662/// # Index width
663///
664/// `I` is the pool's index word. It was hard-coded to `u32`, capping the pool at 4 G
665/// words (32 GB) whatever id family the session configured — a ceiling a 63-bit
666/// configuration can reach. The word is also what the capture journal stores per
667/// touched entry, so it should be the narrowest type that spans the pool, not `usize`.
668/// A tighter bound applies from the other side: a `Director<W>` names an entry in
669/// `W::BITS - 1` bits (see [`Director::new_spilled`]), so an `I` wider than that buys
670/// nothing.
671pub struct DirectorPool<I: IndexLike = u32, const TRACK: bool = true, const PROOFS: bool = false> {
672    /// Working pool: mutable, capture-tracked, rollback by restore.
673    work: VecI<PoolDirector, I, TRACK>,
674    /// Proof pool: append-only, survives working rollback.
675    proof: AppendOnlyVec<PoolDirector, I, TRACK>,
676}
677
678impl<I: IndexLike, const TRACK: bool, const PROOFS: bool> Default
679    for DirectorPool<I, TRACK, PROOFS>
680{
681    fn default() -> Self {
682        Self::new()
683    }
684}
685
686impl<I: IndexLike, const TRACK: bool, const PROOFS: bool> DirectorPool<I, TRACK, PROOFS> {
687    pub fn new() -> Self {
688        Self {
689            work: VecI::new(),
690            proof: AppendOnlyVec::new(),
691        }
692    }
693
694    // -- Working pool ---------------------------------------------------------
695
696    /// Append a spilled matrix to the working pool. Returns the start index.
697    ///
698    /// Growth past `I`'s range is caught by the container's overflow protocol: `push`
699    /// carries no check of its own, and the next `len()` read — the one this method
700    /// starts with — traps.
701    pub fn append(&mut self, bit_length: u32, data: &[PoolDirector]) -> I {
702        let start = self.work.len();
703        self.work
704            .try_push(PoolDirector::new(bit_length as u64))
705            .expect("director pool sized by its index word");
706        for &w in data {
707            self.work
708                .try_push(w)
709                .expect("director pool sized by its index word");
710        }
711        start
712    }
713
714    /// Read bit_length from a working pool entry.
715    pub fn bit_length(&self, start: I) -> u32 {
716        u32::try_from(self.work.get(start).bits())
717            .expect("pool entry bit length exceeds u32: `start` does not name a header word")
718    }
719
720    /// Get a single working pool word by index.
721    pub fn get(&self, idx: I) -> PoolDirector {
722        self.work.get(idx)
723    }
724
725    /// Mutate a working pool word in place (for re-canonization).
726    pub fn set(&mut self, idx: I, val: PoolDirector) {
727        self.work.set(idx, val);
728    }
729
730    /// Read a spilled matrix from the working pool.
731    pub fn read(&self, start: I) -> (u32, std::vec::Vec<PoolDirector>) {
732        let bit_length = u32::try_from(self.work.get(start).bits())
733            .expect("pool entry bit length exceeds u32: `start` does not name a header word");
734        let word_count = ceil_div(bit_length, PoolDirector::USABLE_BITS);
735        let mut data = std::vec::Vec::with_capacity(word_count);
736        for i in 0..word_count {
737            // `start + 1 + i` was `(start + 1 + i) as u32`, which wrapped silently and
738            // read an unrelated entry. Checked, so a forged `start` cannot alias.
739            let at = crate::containers::index_like::checked_add_usize(start, i + 1)
740                .expect("director pool entry extends past the pool's index word");
741            data.push(self.work.get(at));
742        }
743        (bit_length, data)
744    }
745
746    /// Current working pool length, in the pool's index word.
747    pub fn len(&self) -> I {
748        self.work.len()
749    }
750
751    pub fn is_empty(&self) -> bool {
752        self.work.is_empty()
753    }
754
755    /// Mark for semi-persistent checkpoint.
756    pub fn mark(&mut self, shrink: ShrinkPolicy) -> VecToken {
757        self.work
758            .try_mark(shrink)
759            .expect("mark: frame depth is bounded by the saturation driver")
760    }
761
762    /// Restore to a previous checkpoint.
763    pub fn restore(&mut self, token: VecToken) {
764        self.work
765            .try_restore(token)
766            .expect("restore: token minted by this container's own mark");
767    }
768
769    // -- Proof pool -----------------------------------------------------------
770
771    /// Snapshot a spilled matrix into the proof pool (copy-on-first-recanon).
772    /// Returns the start index in the proof pool.
773    ///
774    /// The proof pool shares the working pool's index word: both address the same
775    /// spilled matrices, one live and one archived, so a start index that fits `I` in
776    /// the working pool fits `I` here.
777    pub fn snapshot_to_proof(&mut self, work_start: I) -> I {
778        assert!(PROOFS, "snapshot_to_proof called with PROOFS=false");
779        let (bit_length, data) = self.read(work_start);
780        let proof_start = self.proof.len();
781        self.proof
782            .try_push(PoolDirector::new(bit_length as u64))
783            .expect("proof pool sized by its index word");
784        for w in data {
785            self.proof
786                .try_push(w)
787                .expect("proof pool sized by its index word");
788        }
789        proof_start
790    }
791
792    /// Read a spilled matrix from the proof pool.
793    pub fn read_proof(&self, start: I) -> (u32, std::vec::Vec<PoolDirector>) {
794        let bit_length = self.proof.get(start).bits() as u32;
795        let word_count = ceil_div(bit_length, PoolDirector::USABLE_BITS);
796        let mut data = std::vec::Vec::with_capacity(word_count);
797        for i in 0..word_count {
798            // Same protocol as `read`: the header sits at `start` and the payload
799            // follows, so the last word is `start + word_count` and the sum is
800            // checked rather than wrapped.
801            let at = crate::containers::index_like::checked_add_usize(start, i + 1)
802                .expect("proof pool entry extends past the pool's index word");
803            data.push(*self.proof.get(at));
804        }
805        (bit_length, data)
806    }
807
808    /// Proof pool length.
809    pub fn proof_len(&self) -> I {
810        self.proof.len()
811    }
812}
813
814fn ceil_div(a: u32, b: u32) -> usize {
815    (a as usize).div_ceil(b as usize)
816}
817
818// ---------------------------------------------------------------------------
819// Matrix operations — work on inline bits only (spill variants later)
820// ---------------------------------------------------------------------------
821
822/// All matrix ops take raw inline bits + dimensions. Callers must resolve
823/// spilled matrices through the pool before calling these.
824///
825/// Layout: row-major, k rows of n bits each. Bit (i,j) at position i*n + j.
826/// Row i represents child port i. At most one bit set per row (injection).
827/// Bit (i,j) = 1 means child port i maps to parent port j.
828///
829/// # Preconditions
830///
831/// The whole matrix lives in one `u64`, so every caller owes `k * n <= 64`, `i < k`,
832/// and `j < n`. These are not checked here — the shifts would be masked rather than
833/// trap in release, so a violation is silently wrong rather than loud. The typed
834/// [`Director`] API validates them (see `matrix_bits`) before it
835/// calls in; a direct caller of these functions is on its own.
836pub mod ops {
837    /// Mask of the low `n` bits — one row's width.
838    ///
839    /// `1u64 << n` overflows at `n == 64`, which a 1×64 matrix reaches. Release builds
840    /// mask the shift amount, so `n == 64` yielded the mask for `n == 0`: zero, making
841    /// every read of such a matrix come back empty.
842    #[inline]
843    fn row_mask(n: u8) -> u64 {
844        match 1u64.checked_shl(n as u32) {
845            Some(v) => v - 1,
846            // n >= 64: the whole word is a single row.
847            None => u64::MAX,
848        }
849    }
850
851    /// Extract row `i` from a k×n matrix (n-bit value, at most one bit set).
852    #[inline]
853    pub fn row_extract(bits: u64, i: u8, n: u8) -> u64 {
854        let shift = (i as u32) * (n as u32);
855        (bits >> shift) & row_mask(n)
856    }
857
858    /// Set row `i` in a k×n matrix to `val`.
859    #[inline]
860    pub fn row_set(bits: u64, i: u8, n: u8, val: u64) -> u64 {
861        let shift = (i as u32) * (n as u32);
862        let mask = row_mask(n);
863        (bits & !(mask << shift)) | ((val & mask) << shift)
864    }
865
866    /// Is parent port `j` referenced by any child port?
867    #[inline]
868    pub fn col_present(bits: u64, j: u8, k: u8, n: u8) -> bool {
869        for i in 0..k {
870            if row_extract(bits, i, n) & (1u64 << j) != 0 {
871                return true;
872            }
873        }
874        false
875    }
876
877    /// Which parent ports are used? OR of all rows.
878    #[inline]
879    pub fn embed_bitset(bits: u64, k: u8, n: u8) -> u64 {
880        let mask = row_mask(n);
881        let mut result = 0u64;
882        for i in 0..k {
883            result |= row_extract(bits, i, n);
884        }
885        result & mask
886    }
887
888    /// Identity matrix for k×n (bit (i,i) = 1 for i < min(k,n)).
889    pub fn identity(k: u8, n: u8) -> u64 {
890        let mut bits = 0u64;
891        for i in 0..k.min(n) {
892            bits |= 1u64 << ((i as u32) * (n as u32) + (i as u32));
893        }
894        bits
895    }
896
897    /// Compose outer (k_mid × n_outer) with inner (k_inner × k_mid).
898    /// Result is k_inner × n_outer.
899    ///
900    /// Each row of inner has at most one bit at column p;
901    /// composed row = row p of outer. Zero row → zero row.
902    pub fn compose(outer: u64, inner: u64, k_inner: u8, k_mid: u8, n_outer: u8) -> u64 {
903        let mut result = 0u64;
904        for i in 0..k_inner {
905            let inner_row = row_extract(inner, i, k_mid);
906            if inner_row == 0 {
907                continue; // zero row stays zero
908            }
909            let p = inner_row.trailing_zeros() as u8;
910            let outer_row = row_extract(outer, p, n_outer);
911            result |= outer_row << ((i as u32) * (n_outer as u32));
912        }
913        result
914    }
915
916    /// Widen columns: parent arity grew from old_n to new_n.
917    /// Row values stay the same (bit j stays at j), rows just get wider.
918    pub fn widen_columns(bits: u64, k: u8, old_n: u8, new_n: u8) -> u64 {
919        debug_assert!(new_n >= old_n);
920        let mut result = 0u64;
921        for i in 0..k {
922            let row = row_extract(bits, i, old_n);
923            result |= row << ((i as u32) * (new_n as u32));
924        }
925        result
926    }
927
928    /// Add zero rows: child arity grew from old_k to new_k.
929    /// Existing rows unchanged, new rows are zero.
930    /// Re-lays bits because row width n is unchanged but total bit count grows.
931    pub fn add_zero_rows(bits: u64, old_k: u8, new_k: u8, n: u8) -> u64 {
932        debug_assert!(new_k >= old_k);
933        // Rows 0..old_k are at the same positions, new rows are zero.
934        // Since we store row-major and new rows go at the end, the
935        // existing bits are already correct — just mask to old_k*n.
936        let used = (old_k as u32) * (n as u32);
937        if used >= 64 {
938            bits
939        } else {
940            bits & ((1u64 << used) - 1)
941        }
942    }
943
944    /// Permute rows: row `i` of result = row `perm[i]` of input.
945    pub fn permute_rows(bits: u64, perm: &[u8], k: u8, n: u8) -> u64 {
946        debug_assert!(perm.len() == k as usize);
947        let mut result = 0u64;
948        for i in 0..k {
949            let row = row_extract(bits, perm[i as usize], n);
950            result |= row << ((i as u32) * (n as u32));
951        }
952        result
953    }
954
955    /// Shift: introduce d bound ports. Input is k×n, result is (k+d)×(n+d).
956    /// Rows 0..d are zero (bound ports). Row d+i = row i shifted right by d.
957    pub fn shift(bits: u64, k: u8, n: u8, d: u8) -> u64 {
958        let new_n = n.checked_add(d).expect("parent arity overflow (max 255)");
959        let mut result = 0u64;
960        // rows 0..d are zero (implicit)
961        for i in 0..k {
962            let row = row_extract(bits, i, n);
963            let shifted = row << (d as u32);
964            result |= shifted << (((d + i) as u32) * (new_n as u32));
965        }
966        result
967    }
968
969    /// Delete column j: input is k×n, result is k×(n-1).
970    /// Bits above column j shift down by 1.
971    pub fn delete_column(bits: u64, j: u8, k: u8, n: u8) -> u64 {
972        let new_n = n
973            .checked_sub(1)
974            .expect("delete_column on a matrix with no columns");
975        let mut result = 0u64;
976        for i in 0..k {
977            let row = row_extract(bits, i, n);
978            // Remove bit j: keep low bits, shift high bits down.
979            let lo = row & row_mask(j);
980            // `j + 1` reaches 64 when j is the top column of a 1×64 matrix, and `>>` by
981            // 64 is masked to a no-op in release — which left `hi == row`, reinstating
982            // the column being deleted.
983            let hi = row.checked_shr(j as u32 + 1).unwrap_or(0) << j;
984            result |= (lo | hi) << ((i as u32) * (new_n as u32));
985        }
986        result
987    }
988}
989
990// ---------------------------------------------------------------------------
991// Static size assertions + tests
992// ---------------------------------------------------------------------------
993
994#[cfg(test)]
995mod tests {
996    use super::*;
997
998    #[test]
999    fn zst_child_edge_same_size_as_g() {
1000        assert_eq!(
1001            core::mem::size_of::<Edge<u32, ()>>(),
1002            core::mem::size_of::<u32>(),
1003        );
1004    }
1005
1006    #[test]
1007    fn child_edge_sizes() {
1008        // u16 director pads to 8 due to u32 alignment
1009        assert_eq!(core::mem::size_of::<Edge<u32, u16>>(), 8);
1010        assert_eq!(core::mem::size_of::<Edge<u32, u32>>(), 8);
1011        assert_eq!(core::mem::size_of::<Edge<u32, u64>>(), 16);
1012    }
1013
1014    #[test]
1015    fn inline_roundtrip() {
1016        let m = Director::<u32>::new_inline(0b0110_1001);
1017        assert!(m.is_inline());
1018        assert_eq!(m.inline_bits(), 0b0110_1001);
1019    }
1020
1021    #[test]
1022    fn spill_roundtrip() {
1023        let m = Director::<u32>::new_spilled(42);
1024        assert!(!m.is_inline());
1025        assert_eq!(m.pool_index(), 42);
1026    }
1027
1028    #[test]
1029    fn zero_matrix() {
1030        let m = Director::<u64>::zero();
1031        assert!(m.is_inline());
1032        assert_eq!(m.inline_bits(), 0);
1033    }
1034
1035    #[test]
1036    fn zst_always_inline() {
1037        let m = Director::<()>::zero();
1038        assert!(m.is_inline());
1039    }
1040
1041    #[test]
1042    #[should_panic(expected = "cannot spill")]
1043    fn zst_cannot_spill() {
1044        Director::<()>::new_spilled(0);
1045    }
1046
1047    #[test]
1048    fn dir_word_u16_limits() {
1049        // max inline value: 15 bits set
1050        let m = Director::<u16>::new_inline(0x7FFF);
1051        assert!(m.is_inline());
1052        assert_eq!(m.inline_bits(), 0x7FFF);
1053    }
1054
1055    #[test]
1056    fn dir_word_u64_limits() {
1057        // max inline value: 63 bits set
1058        let m = Director::<u64>::new_inline(0x7FFF_FFFF_FFFF_FFFF);
1059        assert!(m.is_inline());
1060    }
1061
1062    #[test]
1063    fn ground_child_edge() {
1064        let e = Edge::<u32, u32>::ground(7);
1065        assert_eq!(e.class, 7);
1066        assert_eq!(e.director.inline_bits(), 0);
1067    }
1068
1069    #[test]
1070    fn pool_word_size() {
1071        assert_eq!(core::mem::size_of::<PoolDirector>(), 8);
1072    }
1073
1074    #[test]
1075    fn pool_word_roundtrip() {
1076        let w = PoolDirector::new(0x7FFF_FFFF_FFFF_FFFF);
1077        assert_eq!(w.bits(), 0x7FFF_FFFF_FFFF_FFFF);
1078    }
1079
1080    #[test]
1081    fn pool_word_tagged() {
1082        let mut w = PoolDirector::new(42);
1083        assert!(!PoolDirector::tag(&w));
1084        PoolDirector::set_tag(&mut w);
1085        assert!(PoolDirector::tag(&w));
1086        // bits() strips the tag
1087        assert_eq!(PoolDirector::from_repr(&w).bits(), 42);
1088        PoolDirector::clear_tag(&mut w);
1089        assert!(!PoolDirector::tag(&w));
1090        assert_eq!(w.bits(), 42);
1091    }
1092
1093    #[test]
1094    fn dir_pool_append_read() {
1095        let mut pool = DirectorPool::<u32, false, false>::new();
1096        let data = [PoolDirector::new(0b1010101), PoolDirector::new(0b1100110)];
1097        let start = pool.append(126, &data);
1098        let (len, words) = pool.read(start);
1099        assert_eq!(len, 126);
1100        assert_eq!(words.len(), 2);
1101        assert_eq!(words[0].bits(), 0b1010101);
1102        assert_eq!(words[1].bits(), 0b1100110);
1103    }
1104
1105    #[test]
1106    fn dir_pool_mark_restore() {
1107        let mut pool = DirectorPool::<u32, true, false>::new();
1108        let token = pool.mark(crate::containers::ShrinkPolicy::Never);
1109        pool.append(63, &[PoolDirector::new(0xFF)]);
1110        pool.append(63, &[PoolDirector::new(0xAA)]);
1111        assert_eq!(pool.len(), 4);
1112        pool.restore(token);
1113        assert!(pool.is_empty());
1114    }
1115
1116    #[test]
1117    fn dir_pool_mutate_in_place() {
1118        let mut pool = DirectorPool::<u32, false, false>::new();
1119        let start = pool.append(63, &[PoolDirector::new(0xFF)]);
1120        assert_eq!(pool.get(start + 1).bits(), 0xFF);
1121        pool.set(start + 1, PoolDirector::new(0xAB));
1122        assert_eq!(pool.get(start + 1).bits(), 0xAB);
1123    }
1124
1125    #[test]
1126    fn dir_pool_proof_snapshot() {
1127        let mut pool = DirectorPool::<u32, false, true>::new();
1128        let start = pool.append(63, &[PoolDirector::new(0x42)]);
1129        let proof_start = pool.snapshot_to_proof(start);
1130        // mutate working copy
1131        pool.set(start + 1, PoolDirector::new(0x99));
1132        // proof copy unchanged
1133        let (len, data) = pool.read_proof(proof_start);
1134        assert_eq!(len, 63);
1135        assert_eq!(data[0].bits(), 0x42);
1136        // working copy changed
1137        let (_, wdata) = pool.read(start);
1138        assert_eq!(wdata[0].bits(), 0x99);
1139    }
1140
1141    // -- Width / overflow regressions ------------------------------------------
1142
1143    #[test]
1144    #[should_panic(expected = "does not fit")]
1145    fn spill_index_past_word_capacity_panics() {
1146        // `u16` leaves 15 bits beside the spill tag, so 32768 entries is the ceiling —
1147        // a size a real pool reaches. The old `debug_assert!` compared against the tag
1148        // bit alone, which this value passes, and then `W::from_u64` truncated it to 0.
1149        Director::<u16>::new_spilled(1 << 15);
1150    }
1151
1152    #[test]
1153    fn spill_index_at_word_capacity_boundary() {
1154        let m = Director::<u16>::new_spilled((1 << 15) - 1);
1155        assert!(!m.is_inline());
1156        assert_eq!(m.pool_index(), (1 << 15) - 1);
1157    }
1158
1159    #[test]
1160    fn full_64_bit_matrix_survives_the_pool() {
1161        // 8×8 identity is exactly 64 bits and sets bit 63. A pool word has 63 usable
1162        // bits (its MSB is the `Tagged` capture bit), so this needs two words. Packing
1163        // it into one dropped bit 63 *and* set the capture tag on the word.
1164        let mut pool = DirectorPool::<u32, false, false>::new();
1165        let m = Director::<u64>::identity(8, 8, &mut pool);
1166        assert!(!m.is_inline(), "64 bits exceed u64's 63 inline bits");
1167        let (bit_length, words) = pool.read(pool_start::<u32>(m.pool_index()));
1168        assert_eq!(bit_length, 64);
1169        assert_eq!(words.len(), 2, "63 usable bits per pool word");
1170        for w in &words {
1171            assert!(!PoolDirector::tag(w), "capture tag must stay clear");
1172        }
1173        // Row 7 maps child port 7 to parent port 7 — bit 63, the one that was lost.
1174        assert_eq!(m.row_extract(7, 8, &pool), 1 << 7);
1175        assert_eq!(m.embed_bitset(8, 8, &pool), 0xFF);
1176    }
1177
1178    #[test]
1179    #[should_panic(expected = "cannot exceed 64")]
1180    fn oversized_matrix_dimensions_panic() {
1181        // 9×9 = 81 bits. `ops::identity` evaluated `1u64 << 80`, which release builds
1182        // mask to `<< 16`, silently returning a matrix that is not the identity.
1183        let mut pool = DirectorPool::<u32, false, false>::new();
1184        Director::<u64>::identity(9, 9, &mut pool);
1185    }
1186
1187    #[test]
1188    fn single_row_64_columns() {
1189        // n == 64 overflows `1u64 << n` in the row mask; release builds masked the
1190        // shift to 0, so every read of such a matrix came back empty.
1191        let mut pool = DirectorPool::<u32, false, false>::new();
1192        let m = Director::<u64>::identity(1, 64, &mut pool);
1193        assert_eq!(m.row_extract(0, 64, &pool), 1);
1194        // Deleting the top column shifts by `j + 1 == 64` — masked to a no-op in
1195        // release, which left the deleted column in place.
1196        let d = m.delete_column(63, 1, 64, &mut pool);
1197        assert_eq!(d.row_extract(0, 63, &pool), 1);
1198    }
1199
1200    #[test]
1201    #[should_panic(expected = "no columns")]
1202    fn delete_column_on_empty_width_panics() {
1203        // `n - 1` wrapped to 255 in release once the `debug_assert!(n > 0)` was gone.
1204        let mut pool = DirectorPool::<u32, false, false>::new();
1205        let m = Director::<u32>::zero();
1206        m.delete_column(0, 1, 0, &mut pool);
1207    }
1208
1209    #[test]
1210    #[should_panic(expected = "out of range")]
1211    fn delete_nonexistent_column_panics() {
1212        let mut pool = DirectorPool::<u32, false, false>::new();
1213        let m = Director::<u32>::identity(2, 2, &mut pool);
1214        m.delete_column(2, 2, 2, &mut pool);
1215    }
1216
1217    #[test]
1218    fn pool_index_word_narrower_than_u32() {
1219        // The pool is generic over its index word, so a small pool can be addressed in
1220        // a `u16` rather than paying 4 bytes per journal entry.
1221        let mut pool = DirectorPool::<u16, true, false>::new();
1222        let token = pool.mark(crate::containers::ShrinkPolicy::Never);
1223        let start: u16 = pool.append(63, &[PoolDirector::new(0x5A)]);
1224        assert_eq!(pool.len(), 2u16);
1225        assert_eq!(pool.read(start).1[0].bits(), 0x5A);
1226        pool.set(start + 1, PoolDirector::new(0xA5));
1227        assert_eq!(pool.get(start + 1).bits(), 0xA5);
1228        pool.restore(token);
1229        assert!(pool.is_empty());
1230    }
1231
1232    // -- Typed Director<W> API tests -------------------------------------------
1233
1234    #[test]
1235    fn typed_api_inline() {
1236        let mut pool = DirectorPool::<u32, false, false>::new();
1237        // 2×3 identity via typed API
1238        let m = Director::<u32>::identity(2, 3, &mut pool);
1239        assert!(m.is_inline());
1240        assert_eq!(m.row_extract(0, 3, &pool), 0b001);
1241        assert_eq!(m.row_extract(1, 3, &pool), 0b010);
1242        assert_eq!(m.embed_bitset(2, 3, &pool), 0b011);
1243        assert!(m.col_present(0, 2, 3, &pool));
1244        assert!(m.col_present(1, 2, 3, &pool));
1245        assert!(!m.col_present(2, 2, 3, &pool));
1246    }
1247
1248    #[test]
1249    fn typed_api_compose() {
1250        let mut pool = DirectorPool::<u32, false, false>::new();
1251        let id = Director::<u32>::identity(2, 2, &mut pool);
1252        let m = Director::<u32>::new_inline(0b10_01); // 2×2: row0=01, row1=10
1253        let c = Director::compose(&id, &m, 2, 2, 2, &mut pool);
1254        assert_eq!(c.inline_bits(), m.inline_bits());
1255    }
1256
1257    #[test]
1258    fn typed_api_shift_delete_roundtrip() {
1259        let mut pool = DirectorPool::<u32, false, false>::new();
1260        let m = Director::<u32>::identity(2, 2, &mut pool);
1261        let shifted = m.shift(2, 2, 1, &mut pool);
1262        // 3×3: row0=000, row1=010, row2=100
1263        assert_eq!(shifted.row_extract(0, 3, &pool), 0b000);
1264        assert_eq!(shifted.row_extract(1, 3, &pool), 0b010);
1265        assert_eq!(shifted.row_extract(2, 3, &pool), 0b100);
1266        // delete col 0, then remove row 0 manually
1267        let del = shifted.delete_column(0, 3, 3, &mut pool);
1268        // del is 3×2: row0=00, row1=01, row2=10
1269        assert_eq!(del.row_extract(0, 2, &pool), 0b00);
1270        assert_eq!(del.row_extract(1, 2, &pool), 0b01);
1271        assert_eq!(del.row_extract(2, 2, &pool), 0b10);
1272    }
1273
1274    #[test]
1275    fn typed_api_spill_and_read() {
1276        // Use u16 (15 inline bits) and force a matrix that needs > 15 bits
1277        let mut pool = DirectorPool::<u32, false, false>::new();
1278        // 4×4 identity = 16 bits, exceeds u16 inline (15 bits)
1279        let m = Director::<u16>::identity(4, 4, &mut pool);
1280        assert!(!m.is_inline(), "4×4 should spill with u16");
1281        // reads still work through pool
1282        assert_eq!(m.row_extract(0, 4, &pool), 0b0001);
1283        assert_eq!(m.row_extract(1, 4, &pool), 0b0010);
1284        assert_eq!(m.row_extract(2, 4, &pool), 0b0100);
1285        assert_eq!(m.row_extract(3, 4, &pool), 0b1000);
1286        assert_eq!(m.embed_bitset(4, 4, &pool), 0b1111);
1287    }
1288
1289    // -----------------------------------------------------------------------
1290    // Matrix operation unit tests
1291    // -----------------------------------------------------------------------
1292
1293    use super::ops::*;
1294
1295    #[test]
1296    fn identity_2x3() {
1297        // 2×3: row 0 = 001, row 1 = 010
1298        let m = identity(2, 3);
1299        assert_eq!(row_extract(m, 0, 3), 0b001);
1300        assert_eq!(row_extract(m, 1, 3), 0b010);
1301    }
1302
1303    #[test]
1304    fn identity_embed() {
1305        let m = identity(3, 4);
1306        assert_eq!(embed_bitset(m, 3, 4), 0b0111);
1307    }
1308
1309    #[test]
1310    fn compose_identity_left() {
1311        // compose(identity, M) == M
1312        let m = 0b010_001u64; // 2×3: row0=001, row1=010
1313        let id = identity(3, 3);
1314        assert_eq!(compose(id, m, 2, 3, 3), m);
1315    }
1316
1317    #[test]
1318    fn compose_identity_right() {
1319        // compose(M, identity) == M
1320        let m = 0b010_001u64; // 2×3
1321        let id = identity(2, 2);
1322        assert_eq!(compose(m, id, 2, 2, 3), m);
1323    }
1324
1325    #[test]
1326    fn compose_swap() {
1327        // swap = [[0,1],[1,0]], applied to identity 2×2 = swap
1328        let swap = 0b01_10u64; // 2×2: row0=10, row1=01
1329        let id = identity(2, 2);
1330        let result = compose(id, swap, 2, 2, 2);
1331        assert_eq!(result, swap);
1332    }
1333
1334    #[test]
1335    fn widen_preserves_rows() {
1336        let m = 0b10_01u64; // 2×2: row0=01, row1=10
1337        let w = widen_columns(m, 2, 2, 4);
1338        assert_eq!(row_extract(w, 0, 4), 0b0001);
1339        assert_eq!(row_extract(w, 1, 4), 0b0010);
1340    }
1341
1342    #[test]
1343    fn add_zero_rows_preserves() {
1344        let m = 0b10_01u64; // 2×2
1345        let r = add_zero_rows(m, 2, 4, 2);
1346        assert_eq!(row_extract(r, 0, 2), 0b01);
1347        assert_eq!(row_extract(r, 1, 2), 0b10);
1348        // new rows are zero (they're beyond the original bits)
1349    }
1350
1351    #[test]
1352    fn shift_1() {
1353        // 1×1 matrix [1], shift by 1 → 2×2 matrix [[0,0],[0,1]]
1354        let m = 0b1u64; // 1×1: row0=1
1355        let s = shift(m, 1, 1, 1);
1356        // result is 2×2: row0=00 (bound), row1=10 (shifted)
1357        assert_eq!(row_extract(s, 0, 2), 0b00);
1358        assert_eq!(row_extract(s, 1, 2), 0b10);
1359    }
1360
1361    #[test]
1362    fn shift_preserves_structure() {
1363        // 2×2 identity, shift by 1 → 3×3
1364        let m = identity(2, 2);
1365        let s = shift(m, 2, 2, 1);
1366        // row 0: zero (bound)
1367        assert_eq!(row_extract(s, 0, 3), 0b000);
1368        // row 1: original row 0 shifted: bit 0 → bit 1
1369        assert_eq!(row_extract(s, 1, 3), 0b010);
1370        // row 2: original row 1 shifted: bit 1 → bit 2
1371        assert_eq!(row_extract(s, 2, 3), 0b100);
1372    }
1373
1374    #[test]
1375    fn delete_column_middle() {
1376        // 2×3: row0=010 (port 1), row1=100 (port 2)
1377        let m = 0b100_010u64;
1378        // delete column 0 → 2×2: row0=01 (port 0, was 1), row1=10 (port 1, was 2)
1379        let d = delete_column(m, 0, 2, 3);
1380        assert_eq!(row_extract(d, 0, 2), 0b01);
1381        assert_eq!(row_extract(d, 1, 2), 0b10);
1382    }
1383
1384    #[test]
1385    fn delete_column_removes_reference() {
1386        // 2×3: row0=001 (port 0), row1=010 (port 1)
1387        let m = 0b010_001u64;
1388        // delete column 1 → 2×2: row0=01 (port 0), row1=00 (was port 1, deleted)
1389        let d = delete_column(m, 1, 2, 3);
1390        assert_eq!(row_extract(d, 0, 2), 0b01);
1391        assert_eq!(row_extract(d, 1, 2), 0b00);
1392    }
1393
1394    #[test]
1395    fn permute_swap() {
1396        // 2×2 identity, permute with [1,0] → swap
1397        let m = identity(2, 2);
1398        let p = permute_rows(m, &[1, 0], 2, 2);
1399        // row 0 of result = row 1 of input = 10
1400        assert_eq!(row_extract(p, 0, 2), 0b10);
1401        // row 1 of result = row 0 of input = 01
1402        assert_eq!(row_extract(p, 1, 2), 0b01);
1403    }
1404
1405    // -----------------------------------------------------------------------
1406    // Property-based tests
1407    // -----------------------------------------------------------------------
1408
1409    /// Properties tested:
1410    ///
1411    /// P1 (identity left):  compose(identity(k_mid, n), M) == M
1412    /// P2 (identity right): compose(M, identity(k, k_mid)) == M
1413    /// P3 (associativity):  compose(A, compose(B, C)) == compose(compose(A, B), C)
1414    /// P4 (embed subset):   embed_bitset(compose(A, B)) ⊆ embed_bitset(A)
1415    /// P5 (widen idempotent): widen(widen(m, k, a, b), k, b, c) == widen(m, k, a, c)
1416    /// P6 (shift zero rows): row_extract(shift(m,k,n,d), i, n+d) == 0 for i < d
1417    /// P7 (shift preserves): row_extract(shift(m,k,n,d), d+i, n+d) == row_extract(m,i,n) << d
1418    /// P8 (permute embed):   embed_bitset(permute(m,p,k,n)) == embed_bitset(m,k,n)
1419    /// P9 (permute inverse): permute(permute(m,p,k,n), inv(p), k, n) == m
1420    /// P10 (delete shrinks): total bits of result == k*(n-1)
1421    /// P11 (injection):      each row has at most one bit set (for identity, compose, shift)
1422    mod prop {
1423        use super::*;
1424        use proptest::prelude::*;
1425
1426        // -- Strategies -------------------------------------------------------
1427
1428        /// Random injection matrix: k rows of n bits, at most one bit per row.
1429        fn arb_matrix(k: u8, n: u8) -> impl Strategy<Value = u64> {
1430            proptest::collection::vec(0..=(n as usize), k as usize).prop_map(move |cols| {
1431                let mut bits = 0u64;
1432                for (i, &c) in cols.iter().enumerate() {
1433                    if c < n as usize {
1434                        bits |= 1u64 << (i * n as usize + c);
1435                    }
1436                }
1437                bits
1438            })
1439        }
1440
1441        fn arb_perm(k: u8) -> impl Strategy<Value = Vec<u8>> {
1442            Just((0..k).collect::<Vec<u8>>()).prop_shuffle()
1443        }
1444
1445        fn dims_and_matrix() -> impl Strategy<Value = (u8, u8, u64)> {
1446            (1u8..=5, 1u8..=5)
1447                .prop_filter("fits", |&(k, n)| (k as u32) * (n as u32) <= 63)
1448                .prop_flat_map(|(k, n)| arb_matrix(k, n).prop_map(move |m| (k, n, m)))
1449        }
1450
1451        fn two_composable() -> impl Strategy<Value = (u8, u8, u8, u64, u64)> {
1452            (1u8..=4, 1u8..=4, 1u8..=4)
1453                .prop_filter("fits", |&(ki, km, no)| {
1454                    [
1455                        ki as u32 * km as u32,
1456                        km as u32 * no as u32,
1457                        ki as u32 * no as u32,
1458                    ]
1459                    .iter()
1460                    .all(|&x| x <= 63)
1461                })
1462                .prop_flat_map(|(ki, km, no)| {
1463                    (arb_matrix(km, no), arb_matrix(ki, km))
1464                        .prop_map(move |(o, i)| (ki, km, no, o, i))
1465                })
1466        }
1467
1468        fn three_composable() -> impl Strategy<Value = (u8, u8, u8, u8, u64, u64, u64)> {
1469            (1u8..=3, 1u8..=3, 1u8..=3, 1u8..=3)
1470                .prop_filter("fits", |&(ka, kb, kc, nd)| {
1471                    [kb * nd, ka * kb, kc * ka, ka * nd, kc * kb, kc * nd]
1472                        .iter()
1473                        .all(|&x| (x as u32) <= 63)
1474                })
1475                .prop_flat_map(|(ka, kb, kc, nd)| {
1476                    (arb_matrix(kb, nd), arb_matrix(ka, kb), arb_matrix(kc, ka))
1477                        .prop_map(move |(a, b, c)| (ka, kb, kc, nd, a, b, c))
1478                })
1479        }
1480
1481        fn shift_args() -> impl Strategy<Value = (u8, u8, u8, u64)> {
1482            (1u8..=4, 1u8..=4, 1u8..=3)
1483                .prop_filter("fits", |&(k, n, d)| {
1484                    (k as u32 + d as u32) * (n as u32 + d as u32) <= 63
1485                })
1486                .prop_flat_map(|(k, n, d)| arb_matrix(k, n).prop_map(move |m| (k, n, d, m)))
1487        }
1488
1489        fn delete_args() -> impl Strategy<Value = (u8, u8, u8, u64)> {
1490            (1u8..=5, 2u8..=6)
1491                .prop_filter("fits", |&(k, n)| (k as u32) * (n as u32) <= 63)
1492                .prop_flat_map(|(k, n)| {
1493                    (0..n, arb_matrix(k, n)).prop_map(move |(j, m)| (k, n, j, m))
1494                })
1495        }
1496
1497        fn widen_args() -> impl Strategy<Value = (u8, u8, u8, u8, u64)> {
1498            (1u8..=4, 1u8..=4, 0u8..=3, 0u8..=3)
1499                .prop_filter("fits", |&(k, a, d1, d2)| {
1500                    (k as u32) * ((a + d1 + d2) as u32) <= 63
1501                })
1502                .prop_flat_map(|(k, a, d1, d2)| {
1503                    arb_matrix(k, a).prop_map(move |m| (k, a, a + d1, a + d1 + d2, m))
1504                })
1505        }
1506
1507        fn add_rows_args() -> impl Strategy<Value = (u8, u8, u8, u64)> {
1508            (1u8..=4, 1u8..=3, 1u8..=5)
1509                .prop_filter("fits", |&(k, extra, n)| {
1510                    ((k + extra) as u32) * (n as u32) <= 63
1511                })
1512                .prop_flat_map(|(k, extra, n)| arb_matrix(k, n).prop_map(move |m| (k, extra, n, m)))
1513        }
1514
1515        fn perm_args() -> impl Strategy<Value = (u8, u8, u64, Vec<u8>)> {
1516            (1u8..=5, 1u8..=5)
1517                .prop_filter("fits", |&(k, n)| (k as u32) * (n as u32) <= 63)
1518                .prop_flat_map(|(k, n)| {
1519                    (arb_matrix(k, n), arb_perm(k)).prop_map(move |(m, p)| (k, n, m, p))
1520                })
1521        }
1522
1523        // -- Properties -------------------------------------------------------
1524
1525        proptest! {
1526            // P1: identity is left unit for compose
1527            #[test]
1528            fn prop_identity_left((k, n, m) in dims_and_matrix()) {
1529                let id = identity(n, n);
1530                prop_assert_eq!(compose(id, m, k, n, n), m);
1531            }
1532
1533            // P2: identity is right unit for compose
1534            #[test]
1535            fn prop_identity_right((k, n, m) in dims_and_matrix()) {
1536                let id = identity(k, k);
1537                prop_assert_eq!(compose(m, id, k, k, n), m);
1538            }
1539
1540            // P3: compose is associative
1541            #[test]
1542            fn prop_compose_associative((ka, kb, kc, nd, a, b, c) in three_composable()) {
1543                let ab = compose(a, b, ka, kb, nd);
1544                let bc = compose(b, c, kc, ka, kb);
1545                prop_assert_eq!(compose(ab, c, kc, ka, nd), compose(a, bc, kc, kb, nd));
1546            }
1547
1548            // P4: compose can't introduce parent ports not in outer
1549            #[test]
1550            fn prop_compose_embed_subset((ki, km, no, outer, inner) in two_composable()) {
1551                let composed = compose(outer, inner, ki, km, no);
1552                prop_assert_eq!(embed_bitset(composed, ki, no) & !embed_bitset(outer, km, no), 0);
1553            }
1554
1555            // P5: widen is transitive
1556            #[test]
1557            fn prop_widen_transitive((k, a, b, c, m) in widen_args()) {
1558                let step = widen_columns(widen_columns(m, k, a, b), k, b, c);
1559                prop_assert_eq!(step, widen_columns(m, k, a, c));
1560            }
1561
1562            // P6+P7: shift structure — bound rows zero, free rows shifted
1563            #[test]
1564            fn prop_shift_structure((k, n, d, m) in shift_args()) {
1565                let s = shift(m, k, n, d);
1566                let nn = n + d;
1567                for i in 0..d {
1568                    prop_assert_eq!(row_extract(s, i, nn), 0);
1569                }
1570                for i in 0..k {
1571                    prop_assert_eq!(row_extract(s, d + i, nn), row_extract(m, i, n) << d);
1572                }
1573            }
1574
1575            // P8: permute preserves embed_bitset
1576            #[test]
1577            fn prop_permute_preserves_embed((k, n, m, p) in perm_args()) {
1578                prop_assert_eq!(embed_bitset(permute_rows(m, &p, k, n), k, n), embed_bitset(m, k, n));
1579            }
1580
1581            // P9: permute is reversible
1582            #[test]
1583            fn prop_permute_inverse((k, n, m, p) in perm_args()) {
1584                let mut inv = vec![0u8; k as usize];
1585                for (i, &pi) in p.iter().enumerate() { inv[pi as usize] = i as u8; }
1586                prop_assert_eq!(permute_rows(permute_rows(m, &p, k, n), &inv, k, n), m);
1587            }
1588
1589            // P10: delete preserves injection
1590            #[test]
1591            fn prop_delete_preserves_injection((k, n, j, m) in delete_args()) {
1592                let d = delete_column(m, j, k, n);
1593                for i in 0..k {
1594                    prop_assert!(row_extract(d, i, n - 1).count_ones() <= 1);
1595                }
1596            }
1597
1598            // P11: compose preserves injection
1599            #[test]
1600            fn prop_compose_preserves_injection((ki, km, no, outer, inner) in two_composable()) {
1601                let c = compose(outer, inner, ki, km, no);
1602                for i in 0..ki {
1603                    prop_assert!(row_extract(c, i, no).count_ones() <= 1);
1604                }
1605            }
1606
1607            // P12: delete remaps columns correctly
1608            #[test]
1609            fn prop_delete_column_remaps((k, n, j, m) in delete_args()) {
1610                let d = delete_column(m, j, k, n);
1611                for jp in 0..n-1 {
1612                    let orig = if jp < j { jp } else { jp + 1 };
1613                    prop_assert_eq!(col_present(d, jp, k, n-1), col_present(m, orig, k, n));
1614                }
1615            }
1616
1617            // P13: add_zero_rows preserves existing, new rows zero
1618            #[test]
1619            fn prop_add_rows_structure((k, extra, n, m) in add_rows_args()) {
1620                let r = add_zero_rows(m, k, k + extra, n);
1621                for i in 0..k {
1622                    prop_assert_eq!(row_extract(r, i, n), row_extract(m, i, n));
1623                }
1624                for i in k..k+extra {
1625                    prop_assert_eq!(row_extract(r, i, n), 0);
1626                }
1627            }
1628
1629            // P14: shift then peel bound ports recovers original
1630            #[test]
1631            fn prop_shift_delete_roundtrip((k, n, d, m) in shift_args()) {
1632                let mut s = shift(m, k, n, d);
1633                let mut ck = k + d;
1634                let mut cn = n + d;
1635                for _ in 0..d {
1636                    s = delete_column(s, 0, ck, cn);
1637                    cn -= 1;
1638                    let mut rebuilt = 0u64;
1639                    for i in 1..ck {
1640                        rebuilt |= row_extract(s, i, cn) << (((i-1) as u32) * (cn as u32));
1641                    }
1642                    s = rebuilt;
1643                    ck -= 1;
1644                }
1645                prop_assert_eq!(s, m);
1646            }
1647        }
1648    }
1649}