Skip to main content

semi_persistent_egraph/
caches.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Generic node caches — hash-consing tables parameterized by id types.
4//!
5//! - `FixedArityCache<G, O, L, K, TRACK>` — for Plain0..3 and Commutative
6//! - `VariableArityCache<G, O, C, L, TRACK>` — for PlainN, A, AC, ACI
7//! - `LitCache<G, O, V, L, TRACK>` — for literal leaves
8
9use std::hash::{BuildHasher, Hash, Hasher};
10
11use crate::canon::{FixedCanon, VarCanon};
12use crate::containers::DenseId;
13use crate::containers::IndexLike; // prod-parity: L::min() (was L::MIN)
14use crate::containers::Tagged;
15use crate::containers::{ShrinkPolicy, VecI, VecToken};
16use crate::node_types::{FixedArityNode, LitNode, VariableArityNode};
17
18// ---------------------------------------------------------------------------
19// Shared infrastructure
20// ---------------------------------------------------------------------------
21
22#[derive(Default, Clone)]
23struct PassthroughHasher(u64);
24
25impl Hasher for PassthroughHasher {
26    fn write(&mut self, _bytes: &[u8]) {}
27    fn write_u64(&mut self, i: u64) {
28        self.0 = i;
29    }
30    fn finish(&self) -> u64 {
31        self.0
32    }
33}
34
35#[derive(Default, Clone)]
36struct PassthroughBuildHasher;
37
38impl BuildHasher for PassthroughBuildHasher {
39    type Hasher = PassthroughHasher;
40    fn build_hasher(&self) -> PassthroughHasher {
41        PassthroughHasher(0)
42    }
43}
44
45/// A node's content hash, folded to 32 bits.
46///
47/// The index stores the fingerprint rather than the whole 64-bit hash. It is
48/// not a filter that has to be exact — every candidate the table returns is
49/// still confirmed against the node's operator and children — so its only job
50/// is to keep the table from reading the node arena on a near-miss, and 32
51/// bits do that: at a million nodes the expected number of colliding pairs in
52/// the whole table is under two hundred.
53///
54/// What the width buys is the entry: `(StoredKey<u32>, ())` is eight bytes
55/// where `(StoredKey<u64>, G)` was sixteen, so a probe of a million-node table
56/// touches half as many cache lines and a growth rehashes half as much memory.
57type Fingerprint = u32;
58
59/// Fold a 64-bit content hash into a fingerprint, mixing the high half in so
60/// every input bit reaches the result.
61#[inline]
62fn fold32(h: u64) -> Fingerprint {
63    (h ^ (h >> 32)) as Fingerprint
64}
65
66/// Spread a fingerprint over the 64 bits hashbrown reads.
67///
68/// hashbrown takes the bucket index from the low bits and the control byte
69/// from the top seven, so a fingerprint zero-extended into a `u64` would file
70/// every entry under the same control byte and turn each probe into a scan.
71/// Multiplying by an odd constant is a bijection on `u64`, so distinct
72/// fingerprints keep distinct hashes and equal ones keep equal hashes — which
73/// is what lets `remove` find an entry from its stored fingerprint.
74#[inline]
75fn spread(fp: Fingerprint) -> u64 {
76    (fp as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
77}
78
79#[derive(Clone, Copy, Debug)]
80struct StoredKey<L> {
81    fp: Fingerprint,
82    local_id: L,
83}
84
85impl<L> Hash for StoredKey<L> {
86    fn hash<H: Hasher>(&self, state: &mut H) {
87        state.write_u64(spread(self.fp));
88    }
89}
90impl<L: PartialEq> PartialEq for StoredKey<L> {
91    fn eq(&self, other: &Self) -> bool {
92        self.local_id == other.local_id
93    }
94}
95impl<L: Eq> Eq for StoredKey<L> {}
96
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub enum InsertResult<G, L> {
99    Hit { global_id: G },
100    Inserted { local_id: L },
101}
102
103/// One open mark, mirroring the frame the node arena pushed for the same mark.
104///
105/// `saved_len` splits the arena at restore time: local ids below it existed at
106/// the mark and keep their index entries, ids at or above it are the suffix the
107/// restore deletes. `dirty_start` cuts [`dirty`](FixedArityCache::dirty) into
108/// per-frame segments the same way the arena's `diff_start` cuts its diff log.
109#[derive(Clone, Copy, Debug)]
110struct CacheFrame {
111    saved_len: usize,
112    dirty_start: usize,
113    /// Set when the budget dropped a pre-mark write from `dirty`. Restore must
114    /// then rebuild: the dirty segment is incomplete. The ratio test reaches
115    /// the same verdict arithmetically (an overflowing segment already fails
116    /// it), and this flag states the requirement instead of relying on that
117    /// coupling.
118    dirty_overflow: bool,
119}
120
121/// Restore rebuilds the whole index once the incremental work would exceed
122/// `1 / REBUILD_RATIO` of it.
123///
124/// Deleting one index entry costs a fingerprint and a probe, about what
125/// inserting one during a rebuild costs, and the incremental path also
126/// re-inserts every recanonized pre-mark node, so the two paths break even
127/// near `suffix + 2 * dirty == live`. A quarter keeps the incremental path
128/// below that break-even point and bounds the cost of a restore that takes the
129/// rebuild it did not need to a quarter of one.
130pub(crate) const REBUILD_RATIO: usize = 4;
131
132/// Per-frame cap on recorded pre-mark writes: past it, restore is going to
133/// rebuild anyway (the fallback test below is already false), so recording
134/// more would only cost memory.
135#[inline]
136fn dirty_budget(saved_len: usize) -> usize {
137    saved_len / REBUILD_RATIO
138}
139
140/// Whether restore can fix the index in place rather than rebuilding it.
141#[inline]
142pub(crate) fn restore_incrementally(suffix_len: usize, dirty_len: usize, saved_len: usize) -> bool {
143    REBUILD_RATIO * (suffix_len + dirty_len) <= saved_len
144}
145
146#[derive(Clone, Copy, Debug)]
147pub struct CacheToken {
148    nodes: VecToken,
149    history: Option<VecToken>,
150    frame_index: usize,
151}
152
153#[derive(Clone, Copy, Debug)]
154pub struct PoolCacheToken {
155    nodes: VecToken,
156    children: VecToken,
157    history_nodes: Option<VecToken>,
158    history_children: Option<VecToken>,
159    frame_index: usize,
160}
161
162// ---------------------------------------------------------------------------
163// FixedArityCache<G, O, L, K, TRACK, PROOFS>
164// ---------------------------------------------------------------------------
165
166pub struct FixedArityCache<
167    G: DenseId,
168    O: DenseId,
169    L: DenseId,
170    const K: usize,
171    const TRACK: bool = true,
172    const PROOFS: bool = false,
173> {
174    /// One entry per node, so `L` (a local node id) is the index width.
175    nodes: VecI<FixedArityNode<G, O, K>, L, TRACK>,
176    index: hashbrown::HashMap<StoredKey<L>, (), PassthroughBuildHasher>,
177    /// Recanonicalization history, indexed at `usize`: its population is the number of
178    /// rewrites performed, not the number of nodes, and a single node can be recanonicalized
179    /// arbitrarily many times — so no id capacity bounds it and `L` here would be a cap.
180    history: Option<VecI<FixedArityNode<G, O, K>, usize, TRACK>>,
181    /// Local ids below the enclosing mark's `saved_len` whose content
182    /// `recanonize_node` changed. Their index entries were re-keyed at
183    /// recanonize time and the arena rolls their content back on restore, so
184    /// restore has to re-key them a second time, back to the mark's content.
185    /// Duplicates are allowed: re-keying a node twice is idempotent.
186    dirty: Vec<L>,
187    frames: Vec<CacheFrame>,
188}
189
190impl<
191    G: DenseId + Hash,
192    O: DenseId + Hash,
193    L: DenseId,
194    const K: usize,
195    const TRACK: bool,
196    const PROOFS: bool,
197> Default for FixedArityCache<G, O, L, K, TRACK, PROOFS>
198{
199    fn default() -> Self {
200        Self::new()
201    }
202}
203
204impl<
205    G: DenseId + Hash,
206    O: DenseId + Hash,
207    L: DenseId,
208    const K: usize,
209    const TRACK: bool,
210    const PROOFS: bool,
211> FixedArityCache<G, O, L, K, TRACK, PROOFS>
212{
213    pub fn new() -> Self {
214        Self {
215            nodes: VecI::new(),
216            index: hashbrown::HashMap::with_hasher(PassthroughBuildHasher),
217            history: if PROOFS { Some(VecI::new()) } else { None },
218            dirty: Vec::new(),
219            frames: Vec::new(),
220        }
221    }
222
223    pub fn len(&self) -> L {
224        self.nodes.len()
225    }
226
227    pub fn is_empty(&self) -> bool {
228        self.nodes.len() == <L as IndexLike>::min()
229    }
230
231    pub fn get(&self, id: L) -> FixedArityNode<G, O, K> {
232        self.nodes.get(id)
233    }
234
235    pub fn set(&mut self, id: L, node: FixedArityNode<G, O, K>) {
236        self.nodes.set(id, node);
237    }
238
239    pub fn probe(&self, op: &O, children: &[G; K]) -> Option<G> {
240        let fp = self.fingerprint(op, children);
241        self.index
242            .raw_entry()
243            .from_hash(spread(fp), |sk| {
244                sk.fp == fp && {
245                    let n = self.nodes.get(sk.local_id);
246                    n.op() == *op && n.children == *children
247                }
248            })
249            .map(|(sk, _)| self.nodes.get(sk.local_id).global_id())
250    }
251
252    pub fn insert(&mut self, global_id: G, op: O, children: [G; K]) -> L {
253        let node = FixedArityNode::new(global_id, op, children);
254        let fp = self.fingerprint(&op, &children);
255        let lid = self.nodes.len();
256        self.nodes.try_push(node).expect("push: within index word");
257        self.index.insert(StoredKey { fp, local_id: lid }, ());
258        lid
259    }
260
261    pub fn probe_or_insert(&mut self, global_id: G, op: O, children: [G; K]) -> InsertResult<G, L> {
262        if let Some(gid) = self.probe(&op, &children) {
263            return InsertResult::Hit { global_id: gid };
264        }
265        let lid = self.insert(global_id, op, children);
266        InsertResult::Inserted { local_id: lid }
267    }
268
269    pub fn node_get(&self, id: L) -> FixedArityNode<G, O, K> {
270        self.nodes.get(id)
271    }
272
273    pub fn node_set(&mut self, id: L, node: FixedArityNode<G, O, K>) {
274        self.nodes.set(id, node);
275    }
276
277    /// Recanonize a single node's children. Pushes collision pair into
278    /// `collisions` if the new canonical form matches an existing node.
279    /// When `PROOFS=true`, saves the original node to history on first recanonize.
280    pub fn recanonize_node<F: FixedCanon<G, K>>(
281        &mut self,
282        local_id: L,
283        find: impl Fn(G) -> G,
284        collisions: &mut Vec<(G, G)>,
285        touched: &mut Vec<G>,
286    ) {
287        let mut node = self.nodes.get(local_id);
288        let old_fp = self.fingerprint(&node.op(), &node.children);
289
290        F::canonize(&mut node.children, &find);
291
292        let new_fp = self.fingerprint(&node.op(), &node.children);
293        if new_fp == old_fp {
294            let old = self.nodes.get(local_id);
295            if old.children == node.children {
296                return;
297            }
298        }
299
300        // Node's canonical form genuinely changed this round — record it for
301        // the semi-naive delta (after the no-change early-return above).
302        touched.push(node.global_id());
303        self.note_dirty(local_id);
304
305        // save to history on first recanonize
306        if let Some(hist) = &mut self.history
307            && !node.has_history()
308        {
309            hist.try_push(self.nodes.get(local_id))
310                .expect("push: within index word");
311        }
312
313        self.index.remove(&StoredKey {
314            fp: old_fp,
315            local_id,
316        });
317
318        let gid = node.global_id();
319        let mut new_node = FixedArityNode::new(gid, node.op(), node.children);
320        if PROOFS {
321            new_node.set_history();
322        }
323        self.nodes.set(local_id, new_node);
324
325        if let Some(existing_gid) = self.probe(&node.op(), &node.children) {
326            collisions.push((gid, existing_gid));
327        }
328
329        self.index.insert(
330            StoredKey {
331                fp: new_fp,
332                local_id,
333            },
334            (),
335        );
336    }
337
338    /// Retrieve the original (pre-recanonize) children for a node by global id.
339    /// Linear scan of the history store. Returns `None` if no history or not found.
340    pub fn original_children(&self, global_id: G) -> Option<[G; K]> {
341        let hist = self.history.as_ref()?;
342        let len = hist.len();
343        for i in 0..len {
344            let node = hist.get(i);
345            if node.global_id() == global_id {
346                return Some(node.children);
347            }
348        }
349        None
350    }
351
352    /// Record a pre-mark node whose content just changed, so restore can put
353    /// its index entry back under the mark's key. Nodes at or above the
354    /// enclosing mark's `saved_len` need no entry: they are in the suffix
355    /// restore deletes outright, and every enclosing mark's `saved_len` is no
356    /// larger, so they are in its suffix too.
357    #[inline]
358    fn note_dirty(&mut self, local_id: L) {
359        if !TRACK {
360            return;
361        }
362        let Some(frame) = self.frames.last_mut() else {
363            return;
364        };
365        if local_id.as_usize() >= frame.saved_len {
366            return;
367        }
368        if self.dirty.len() - frame.dirty_start > dirty_budget(frame.saved_len) {
369            frame.dirty_overflow = true;
370            return;
371        }
372        self.dirty.push(local_id);
373    }
374
375    pub fn mark(&mut self, shrink: ShrinkPolicy) -> CacheToken {
376        let token = CacheToken {
377            nodes: self
378                .nodes
379                .try_mark(shrink)
380                .expect("mark: frame depth is bounded by the saturation driver"),
381            history: self.history.as_mut().map(|h| {
382                h.try_mark(shrink)
383                    .expect("mark: frame depth is bounded by the saturation driver")
384            }),
385            frame_index: self.frames.len(),
386        };
387        self.frames.push(CacheFrame {
388            saved_len: self.nodes.len().as_usize(),
389            dirty_start: self.dirty.len(),
390            dirty_overflow: false,
391        });
392        token
393    }
394
395    pub fn restore(&mut self, token: CacheToken) {
396        let frame = *self
397            .frames
398            .get(token.frame_index)
399            .expect("restore: token minted by this cache's own mark, and not already spent");
400        // Validate every inner token BEFORE touching the index: the deletions
401        // below are not undoable, so an invalid token must refuse while the
402        // cache is still consistent.
403        assert!(
404            self.nodes.is_valid_token(&token.nodes),
405            "restore: node-arena token is not restorable"
406        );
407        if let (Some(h), Some(tok)) = (&self.history, token.history.as_ref()) {
408            assert!(
409                h.is_valid_token(tok),
410                "restore: history token is not restorable"
411            );
412        }
413        let live_len = self.nodes.len().as_usize();
414        let incremental = !frame.dirty_overflow
415            && restore_incrementally(
416                live_len - frame.saved_len,
417                self.dirty.len() - frame.dirty_start,
418                frame.saved_len,
419            );
420
421        // The arena is append-only, so the nodes added since the mark are the
422        // contiguous suffix at or above `saved_len` and theirs are the entries
423        // to delete. The only other entries the scope moved are those of the
424        // pre-mark nodes `recanonize_node` re-keyed, which `dirty` names, so
425        // the correction is O(added + recanonized) rather than O(live).
426        //
427        // Delete under the CURRENT keys, before the arena rolls the content
428        // back: an entry is filed under the fingerprint of the content it had
429        // when it was last written.
430        if incremental {
431            for i in frame.saved_len..live_len {
432                self.remove_entry(L::from_usize(i));
433            }
434            for k in frame.dirty_start..self.dirty.len() {
435                self.remove_entry(self.dirty[k]);
436            }
437        }
438
439        self.nodes
440            .try_restore(token.nodes)
441            .expect("restore: token minted by this container's own mark");
442        if let (Some(h), Some(tok)) = (&mut self.history, token.history) {
443            h.try_restore(tok)
444                .expect("restore: token minted by this container's own mark");
445        }
446
447        if incremental {
448            for k in frame.dirty_start..self.dirty.len() {
449                self.insert_entry(self.dirty[k]);
450            }
451        } else {
452            self.rebuild_index();
453        }
454        self.dirty.truncate(frame.dirty_start);
455        self.frames.truncate(token.frame_index);
456        #[cfg(debug_assertions)]
457        debug_assert!(
458            self.index_matches_rebuild(),
459            "restore left the hashcons index out of step with the node arena"
460        );
461    }
462
463    /// Drop `local_id`'s entry, keyed by the content it holds right now. A
464    /// repeat call is a no-op: the entry is already gone.
465    #[inline]
466    fn remove_entry(&mut self, local_id: L) {
467        let fp = fold32(self.nodes.get(local_id).content_hash());
468        self.index.remove(&StoredKey { fp, local_id });
469    }
470
471    #[inline]
472    fn insert_entry(&mut self, local_id: L) {
473        let fp = fold32(self.nodes.get(local_id).content_hash());
474        self.index.insert(StoredKey { fp, local_id }, ());
475    }
476
477    /// The index holds exactly one entry per live node, keyed by that node's
478    /// current content, which is what [`rebuild_index`](Self::rebuild_index)
479    /// produces from scratch.
480    #[cfg(debug_assertions)]
481    fn index_matches_rebuild(&self) -> bool {
482        let count = self.nodes.len().as_usize();
483        if self.index.len() != count {
484            return false;
485        }
486        let mut seen = vec![false; count];
487        for (sk, ()) in self.index.iter() {
488            let i = sk.local_id.as_usize();
489            if i >= count || seen[i] || sk.fp != fold32(self.nodes.get(sk.local_id).content_hash())
490            {
491                return false;
492            }
493            seen[i] = true;
494        }
495        true
496    }
497
498    fn rebuild_index(&mut self) {
499        self.index.clear();
500        // `from_usize` needs no bound check here: `nodes` is indexed *by* `L`, so its own
501        // capacity guard is the id bound (`IndexLike::max_nat()` of a dense id is its
502        // `id_bound()`). Every position the arena can hold therefore has a local id. The
503        // scans that DO need a check are the ones over a container indexed by an id's
504        // *word* rather than the id — see `EGraph::node_ids`.
505        let count = self.nodes.len().as_usize();
506        for i in 0..count {
507            let lid = L::from_usize(i);
508            let n = self.nodes.get(lid);
509            self.index.insert(
510                StoredKey {
511                    fp: fold32(n.content_hash()),
512                    local_id: lid,
513                },
514                (),
515            );
516        }
517    }
518
519    fn fingerprint(&self, op: &O, children: &[G; K]) -> Fingerprint {
520        let mut h = rapidhash::fast::RapidHasher::default();
521        op.hash(&mut h);
522        children.hash(&mut h);
523        fold32(h.finish())
524    }
525}
526
527// ---------------------------------------------------------------------------
528// VariableArityCache<G, O, C, L, TRACK, PROOFS>
529// ---------------------------------------------------------------------------
530
531pub struct VariableArityCache<
532    G: DenseId,
533    O: DenseId,
534    C: Tagged + Clone + Copy + Hash + Eq,
535    L: DenseId,
536    const TRACK: bool = true,
537    const PROOFS: bool = false,
538> {
539    /// One entry per node, so `L` (a local node id) is the index width.
540    nodes: VecI<VariableArityNode<G, O>, L, TRACK>,
541    /// The shared child pool the nodes' spans address. Indexed at `usize`, matching the
542    /// `start`/`end` words in [`VariableArityNode`]: its population is `Σ arity` over the
543    /// nodes, which neither `L`'s nor `G`'s capacity bounds, so an id-width index here would
544    /// be a new cap rather than a narrowing. See [`VariableArityNode::start`].
545    children: VecI<C, usize, TRACK>,
546    index: hashbrown::HashMap<StoredKey<L>, (), PassthroughBuildHasher>,
547    /// Recanonicalization history. `usize` for a different reason than `children`: the
548    /// population here is the number of *rewrites* the run has performed, which is unbounded
549    /// by any id capacity — a single node can be recanonicalized arbitrarily many times.
550    history_nodes: Option<VecI<VariableArityNode<G, O>, usize, TRACK>>,
551    /// Children of the history entries; `Σ arity` over `history_nodes`, so `usize` for both
552    /// of the reasons above at once.
553    history_children: Option<VecI<C, usize, TRACK>>,
554    /// Local ids below the enclosing mark's `saved_len` whose content
555    /// `recanonize_node` changed, through the node's own span or through the
556    /// child pool it addresses. See [`FixedArityCache::dirty`].
557    dirty: Vec<L>,
558    frames: Vec<CacheFrame>,
559}
560
561impl<
562    G: DenseId + Hash,
563    O: DenseId + Hash,
564    C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
565    L: DenseId,
566    const TRACK: bool,
567    const PROOFS: bool,
568> Default for VariableArityCache<G, O, C, L, TRACK, PROOFS>
569{
570    fn default() -> Self {
571        Self::new()
572    }
573}
574
575impl<
576    G: DenseId + Hash,
577    O: DenseId + Hash,
578    C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
579    L: DenseId,
580    const TRACK: bool,
581    const PROOFS: bool,
582> VariableArityCache<G, O, C, L, TRACK, PROOFS>
583{
584    pub fn new() -> Self {
585        Self {
586            nodes: VecI::new(),
587            children: VecI::new(),
588            index: hashbrown::HashMap::with_hasher(PassthroughBuildHasher),
589            history_nodes: if PROOFS { Some(VecI::new()) } else { None },
590            history_children: if PROOFS { Some(VecI::new()) } else { None },
591            dirty: Vec::new(),
592            frames: Vec::new(),
593        }
594    }
595
596    pub fn len(&self) -> L {
597        self.nodes.len()
598    }
599
600    pub fn is_empty(&self) -> bool {
601        self.nodes.len() == <L as IndexLike>::min()
602    }
603
604    pub fn get(&self, id: L) -> VariableArityNode<G, O> {
605        self.nodes.get(id)
606    }
607
608    pub fn set(&mut self, id: L, node: VariableArityNode<G, O>) {
609        self.nodes.set(id, node);
610    }
611
612    pub fn children_vec(&self, node: &VariableArityNode<G, O>) -> Vec<C> {
613        let (start, end) = node.span();
614        (start..end).map(|i| self.children.get(i)).collect()
615    }
616
617    pub fn pool_get(&self, i: usize) -> C {
618        self.children.get(i)
619    }
620
621    pub fn pool_set(&mut self, i: usize, value: C) {
622        self.children.set(i, value);
623    }
624
625    pub fn probe(&self, op: O, elems: &[C]) -> Option<G> {
626        let fp = self.fingerprint(&op, elems);
627        self.index
628            .raw_entry()
629            .from_hash(spread(fp), |sk| {
630                sk.fp == fp && {
631                    let n = self.nodes.get(sk.local_id);
632                    n.op() == op && self.children_eq(&n, elems)
633                }
634            })
635            .map(|(sk, _)| self.nodes.get(sk.local_id).global_id())
636    }
637
638    pub fn insert(&mut self, global_id: G, op: O, elems: &[C]) -> L {
639        let start = self.children.len();
640        for &e in elems {
641            self.children.try_push(e).expect("push: within index word");
642        }
643        let end = self.children.len();
644        let node = VariableArityNode::make(global_id, op, start, end);
645        let fp = self.fingerprint(&op, elems);
646        let lid = self.nodes.len();
647        self.nodes.try_push(node).expect("push: within index word");
648        self.index.insert(StoredKey { fp, local_id: lid }, ());
649        lid
650    }
651
652    pub fn probe_or_insert(&mut self, global_id: G, op: O, elems: &[C]) -> InsertResult<G, L> {
653        if let Some(gid) = self.probe(op, elems) {
654            return InsertResult::Hit { global_id: gid };
655        }
656        let lid = self.insert(global_id, op, elems);
657        InsertResult::Inserted { local_id: lid }
658    }
659
660    pub fn node_get(&self, id: L) -> VariableArityNode<G, O> {
661        self.nodes.get(id)
662    }
663
664    pub fn node_set(&mut self, id: L, node: VariableArityNode<G, O>) {
665        self.nodes.set(id, node);
666    }
667
668    /// Recanonize a single node's children. `buf` is a caller-owned scratch
669    /// buffer, cleared internally. Pushes collision pair into `collisions`
670    /// if the new canonical form matches an existing node.
671    /// When `PROOFS=true`, saves the original node+children to history on first recanonize.
672    pub fn recanonize_node<V: VarCanon<G, C>>(
673        &mut self,
674        local_id: L,
675        find: impl Fn(G) -> G,
676        buf: &mut Vec<C>,
677        collisions: &mut Vec<(G, G)>,
678        touched: &mut Vec<G>,
679        mode: crate::canon::CanonMode<G>,
680    ) {
681        let node = self.nodes.get(local_id);
682        let (start, end) = node.span();
683        let old_fp = self.children_fingerprint(&node);
684
685        buf.clear();
686        V::canonize(buf, start, end, |i| self.children.get(i), &find, mode);
687
688        let new_len = buf.len();
689
690        if new_len == end - start {
691            let mut same = true;
692            for i in 0..new_len {
693                if buf[i] != self.children.get(start + i) {
694                    same = false;
695                    break;
696                }
697            }
698            if same {
699                return;
700            }
701        }
702
703        // Node's canonical form genuinely changed this round — record it for
704        // the semi-naive delta (after the no-change early-return above).
705        touched.push(node.global_id());
706        self.note_dirty(local_id);
707
708        // save to history on first recanonize
709        if let (Some(hn), Some(hc)) = (&mut self.history_nodes, &mut self.history_children)
710            && !node.has_history()
711        {
712            let hist_start = hc.len();
713            for i in start..end {
714                hc.try_push(self.children.get(i))
715                    .expect("push: within index word");
716            }
717            let hist_end = hc.len();
718            hn.try_push(VariableArityNode::make(
719                node.global_id(),
720                node.op(),
721                hist_start,
722                hist_end,
723            ))
724            .expect("push: within index word");
725        }
726
727        self.index.remove(&StoredKey {
728            fp: old_fp,
729            local_id,
730        });
731
732        for i in 0..new_len {
733            self.children.set(start + i, buf[i]);
734        }
735
736        let new_end = start + new_len;
737        let gid = node.global_id();
738        let mut updated = VariableArityNode::make(gid, node.op(), start, new_end);
739        if PROOFS {
740            updated.set_history();
741        }
742        if new_end != end || PROOFS {
743            self.nodes.set(local_id, updated);
744        }
745
746        let new_fp = self.fingerprint(&node.op(), &buf[..new_len]);
747
748        if let Some(existing_gid) = self.probe(node.op(), &buf[..new_len]) {
749            collisions.push((gid, existing_gid));
750        }
751
752        self.index.insert(
753            StoredKey {
754                fp: new_fp,
755                local_id,
756            },
757            (),
758        );
759    }
760
761    /// Retrieve the original (pre-recanonize) children for a node by global id.
762    /// Linear scan of the history store. Appends children to `out`.
763    /// Returns `true` if found.
764    pub fn original_children(&self, global_id: G, out: &mut Vec<C>) -> bool {
765        let (hn, hc) = match (&self.history_nodes, &self.history_children) {
766            (Some(hn), Some(hc)) => (hn, hc),
767            _ => return false,
768        };
769        let len = hn.len();
770        for i in 0..len {
771            let node = hn.get(i);
772            if node.global_id() == global_id {
773                let (s, e) = node.span();
774                for j in s..e {
775                    out.push(hc.get(j));
776                }
777                return true;
778            }
779        }
780        false
781    }
782
783    /// See [`FixedArityCache::note_dirty`].
784    #[inline]
785    fn note_dirty(&mut self, local_id: L) {
786        if !TRACK {
787            return;
788        }
789        let Some(frame) = self.frames.last_mut() else {
790            return;
791        };
792        if local_id.as_usize() >= frame.saved_len {
793            return;
794        }
795        if self.dirty.len() - frame.dirty_start > dirty_budget(frame.saved_len) {
796            frame.dirty_overflow = true;
797            return;
798        }
799        self.dirty.push(local_id);
800    }
801
802    pub fn mark(&mut self, shrink: ShrinkPolicy) -> PoolCacheToken {
803        let token = PoolCacheToken {
804            nodes: self
805                .nodes
806                .try_mark(shrink)
807                .expect("mark: frame depth is bounded by the saturation driver"),
808            children: self
809                .children
810                .try_mark(shrink)
811                .expect("mark: frame depth is bounded by the saturation driver"),
812            history_nodes: self.history_nodes.as_mut().map(|h| {
813                h.try_mark(shrink)
814                    .expect("mark: frame depth is bounded by the saturation driver")
815            }),
816            history_children: self.history_children.as_mut().map(|h| {
817                h.try_mark(shrink)
818                    .expect("mark: frame depth is bounded by the saturation driver")
819            }),
820            frame_index: self.frames.len(),
821        };
822        self.frames.push(CacheFrame {
823            saved_len: self.nodes.len().as_usize(),
824            dirty_start: self.dirty.len(),
825            dirty_overflow: false,
826        });
827        token
828    }
829
830    pub fn restore(&mut self, token: PoolCacheToken) {
831        let frame = *self
832            .frames
833            .get(token.frame_index)
834            .expect("restore: token minted by this cache's own mark, and not already spent");
835        // Validate every inner token BEFORE touching the index (as in the
836        // fixed-arity restore above).
837        assert!(
838            self.nodes.is_valid_token(&token.nodes),
839            "restore: node-arena token is not restorable"
840        );
841        assert!(
842            self.children.is_valid_token(&token.children),
843            "restore: child-pool token is not restorable"
844        );
845        if let (Some(h), Some(tok)) = (&self.history_nodes, token.history_nodes.as_ref()) {
846            assert!(
847                h.is_valid_token(tok),
848                "restore: history token is not restorable"
849            );
850        }
851        if let (Some(h), Some(tok)) = (&self.history_children, token.history_children.as_ref()) {
852            assert!(
853                h.is_valid_token(tok),
854                "restore: history token is not restorable"
855            );
856        }
857        let live_len = self.nodes.len().as_usize();
858        let incremental = !frame.dirty_overflow
859            && restore_incrementally(
860                live_len - frame.saved_len,
861                self.dirty.len() - frame.dirty_start,
862                frame.saved_len,
863            );
864
865        // Delete under the CURRENT keys, before the arena and the child pool
866        // roll back: an entry is filed under the fingerprint of the content it
867        // had when it was last written.
868        if incremental {
869            for i in frame.saved_len..live_len {
870                self.remove_entry(L::from_usize(i));
871            }
872            for k in frame.dirty_start..self.dirty.len() {
873                self.remove_entry(self.dirty[k]);
874            }
875        }
876
877        self.nodes
878            .try_restore(token.nodes)
879            .expect("restore: token minted by this container's own mark");
880        self.children
881            .try_restore(token.children)
882            .expect("restore: token minted by this container's own mark");
883        if let (Some(h), Some(tok)) = (&mut self.history_nodes, token.history_nodes) {
884            h.try_restore(tok)
885                .expect("restore: token minted by this container's own mark");
886        }
887        if let (Some(h), Some(tok)) = (&mut self.history_children, token.history_children) {
888            h.try_restore(tok)
889                .expect("restore: token minted by this container's own mark");
890        }
891
892        if incremental {
893            for k in frame.dirty_start..self.dirty.len() {
894                self.insert_entry(self.dirty[k]);
895            }
896        } else {
897            self.rebuild_index();
898        }
899        self.dirty.truncate(frame.dirty_start);
900        self.frames.truncate(token.frame_index);
901        #[cfg(debug_assertions)]
902        debug_assert!(
903            self.index_matches_rebuild(),
904            "restore left the hashcons index out of step with the node arena"
905        );
906    }
907
908    /// Drop `local_id`'s entry, keyed by the content it holds right now. A
909    /// repeat call is a no-op: the entry is already gone.
910    #[inline]
911    fn remove_entry(&mut self, local_id: L) {
912        let fp = self.children_fingerprint(&self.nodes.get(local_id));
913        self.index.remove(&StoredKey { fp, local_id });
914    }
915
916    #[inline]
917    fn insert_entry(&mut self, local_id: L) {
918        let fp = self.children_fingerprint(&self.nodes.get(local_id));
919        self.index.insert(StoredKey { fp, local_id }, ());
920    }
921
922    /// See [`FixedArityCache::index_matches_rebuild`].
923    #[cfg(debug_assertions)]
924    fn index_matches_rebuild(&self) -> bool {
925        let count = self.nodes.len().as_usize();
926        if self.index.len() != count {
927            return false;
928        }
929        let mut seen = vec![false; count];
930        for (sk, ()) in self.index.iter() {
931            let i = sk.local_id.as_usize();
932            if i >= count
933                || seen[i]
934                || sk.fp != self.children_fingerprint(&self.nodes.get(sk.local_id))
935            {
936                return false;
937            }
938            seen[i] = true;
939        }
940        true
941    }
942
943    fn children_eq(&self, node: &VariableArityNode<G, O>, elems: &[C]) -> bool {
944        let (start, end) = node.span();
945        if end - start != elems.len() {
946            return false;
947        }
948        (0..elems.len()).all(|i| self.children.get(start + i) == elems[i])
949    }
950
951    fn rebuild_index(&mut self) {
952        self.index.clear();
953        // `from_usize` needs no bound check here: `nodes` is indexed *by* `L`, so its own
954        // capacity guard is the id bound (`IndexLike::max_nat()` of a dense id is its
955        // `id_bound()`). Every position the arena can hold therefore has a local id. The
956        // scans that DO need a check are the ones over a container indexed by an id's
957        // *word* rather than the id — see `EGraph::node_ids`.
958        let count = self.nodes.len().as_usize();
959        for i in 0..count {
960            let lid = L::from_usize(i);
961            let n = self.nodes.get(lid);
962            let fp = self.children_fingerprint(&n);
963            self.index.insert(StoredKey { fp, local_id: lid }, ());
964        }
965    }
966
967    fn fingerprint(&self, op: &O, elems: &[C]) -> Fingerprint {
968        let mut h = rapidhash::fast::RapidHasher::default();
969        op.hash(&mut h);
970        elems.hash(&mut h);
971        fold32(h.finish())
972    }
973
974    fn children_fingerprint(&self, node: &VariableArityNode<G, O>) -> Fingerprint {
975        let mut h = rapidhash::fast::RapidHasher::default();
976        node.op().hash(&mut h);
977        let (start, end) = node.span();
978        (end - start).hash(&mut h);
979        for i in start..end {
980            self.children.get(i).hash(&mut h);
981        }
982        fold32(h.finish())
983    }
984}
985
986// ---------------------------------------------------------------------------
987// LitCache<G, O, V, L, TRACK>
988// ---------------------------------------------------------------------------
989
990pub struct LitCache<G: DenseId, O: DenseId, V: DenseId, L: DenseId, const TRACK: bool = true> {
991    nodes: VecI<LitNode<G, O, V>, L, TRACK>,
992    index: hashbrown::HashMap<StoredKey<L>, (), PassthroughBuildHasher>,
993    /// No `dirty` counterpart to the other two caches: a literal's content is
994    /// its operator and its value, and nothing recanonizes either, so the only
995    /// entries a restore has to drop are the suffix's.
996    frames: Vec<CacheFrame>,
997}
998
999impl<G: DenseId + Hash, O: DenseId + Hash, V: DenseId + Hash, L: DenseId, const TRACK: bool> Default
1000    for LitCache<G, O, V, L, TRACK>
1001{
1002    fn default() -> Self {
1003        Self::new()
1004    }
1005}
1006
1007impl<G: DenseId + Hash, O: DenseId + Hash, V: DenseId + Hash, L: DenseId, const TRACK: bool>
1008    LitCache<G, O, V, L, TRACK>
1009{
1010    pub fn new() -> Self {
1011        Self {
1012            nodes: VecI::new(),
1013            index: hashbrown::HashMap::with_hasher(PassthroughBuildHasher),
1014            frames: Vec::new(),
1015        }
1016    }
1017
1018    pub fn len(&self) -> L {
1019        self.nodes.len()
1020    }
1021
1022    pub fn is_empty(&self) -> bool {
1023        self.nodes.len() == <L as IndexLike>::min()
1024    }
1025
1026    pub fn get(&self, id: L) -> LitNode<G, O, V> {
1027        self.nodes.get(id)
1028    }
1029
1030    pub fn set(&mut self, id: L, node: LitNode<G, O, V>) {
1031        self.nodes.set(id, node);
1032    }
1033
1034    pub fn probe(&self, op: O, lit: V) -> Option<G> {
1035        let fp = self.fingerprint(&op, &lit);
1036        self.index
1037            .raw_entry()
1038            .from_hash(spread(fp), |sk| {
1039                sk.fp == fp && {
1040                    let n = self.nodes.get(sk.local_id);
1041                    n.op() == op && n.lit == lit
1042                }
1043            })
1044            .map(|(sk, _)| self.nodes.get(sk.local_id).global_id())
1045    }
1046
1047    pub fn insert(&mut self, global_id: G, op: O, lit: V) -> L {
1048        let node = LitNode::new(global_id, op, lit);
1049        let fp = self.fingerprint(&op, &lit);
1050        let lid = self.nodes.len();
1051        self.nodes.try_push(node).expect("push: within index word");
1052        self.index.insert(StoredKey { fp, local_id: lid }, ());
1053        lid
1054    }
1055
1056    pub fn probe_or_insert(&mut self, global_id: G, op: O, lit: V) -> InsertResult<G, L> {
1057        if let Some(gid) = self.probe(op, lit) {
1058            return InsertResult::Hit { global_id: gid };
1059        }
1060        let lid = self.insert(global_id, op, lit);
1061        InsertResult::Inserted { local_id: lid }
1062    }
1063
1064    pub fn mark(&mut self, shrink: ShrinkPolicy) -> CacheToken {
1065        let token = CacheToken {
1066            nodes: self
1067                .nodes
1068                .try_mark(shrink)
1069                .expect("mark: frame depth is bounded by the saturation driver"),
1070            history: None,
1071            frame_index: self.frames.len(),
1072        };
1073        self.frames.push(CacheFrame {
1074            saved_len: self.nodes.len().as_usize(),
1075            dirty_start: 0,
1076            dirty_overflow: false,
1077        });
1078        token
1079    }
1080
1081    pub fn restore(&mut self, token: CacheToken) {
1082        let frame = *self
1083            .frames
1084            .get(token.frame_index)
1085            .expect("restore: token minted by this cache's own mark, and not already spent");
1086        let live_len = self.nodes.len().as_usize();
1087        let incremental = restore_incrementally(live_len - frame.saved_len, 0, frame.saved_len);
1088
1089        if incremental {
1090            for i in frame.saved_len..live_len {
1091                let local_id = L::from_usize(i);
1092                let fp = fold32(self.nodes.get(local_id).content_hash());
1093                self.index.remove(&StoredKey { fp, local_id });
1094            }
1095        }
1096
1097        self.nodes
1098            .try_restore(token.nodes)
1099            .expect("restore: token minted by this container's own mark");
1100
1101        if !incremental {
1102            self.rebuild_index();
1103        }
1104        self.frames.truncate(token.frame_index);
1105        #[cfg(debug_assertions)]
1106        debug_assert!(
1107            self.index_matches_rebuild(),
1108            "restore left the hashcons index out of step with the node arena"
1109        );
1110    }
1111
1112    /// See [`FixedArityCache::index_matches_rebuild`].
1113    #[cfg(debug_assertions)]
1114    fn index_matches_rebuild(&self) -> bool {
1115        let count = self.nodes.len().as_usize();
1116        if self.index.len() != count {
1117            return false;
1118        }
1119        let mut seen = vec![false; count];
1120        for (sk, ()) in self.index.iter() {
1121            let i = sk.local_id.as_usize();
1122            if i >= count || seen[i] || sk.fp != fold32(self.nodes.get(sk.local_id).content_hash())
1123            {
1124                return false;
1125            }
1126            seen[i] = true;
1127        }
1128        true
1129    }
1130
1131    fn rebuild_index(&mut self) {
1132        self.index.clear();
1133        // `from_usize` needs no bound check here: `nodes` is indexed *by* `L`, so its own
1134        // capacity guard is the id bound (`IndexLike::max_nat()` of a dense id is its
1135        // `id_bound()`). Every position the arena can hold therefore has a local id. The
1136        // scans that DO need a check are the ones over a container indexed by an id's
1137        // *word* rather than the id — see `EGraph::node_ids`.
1138        let count = self.nodes.len().as_usize();
1139        for i in 0..count {
1140            let lid = L::from_usize(i);
1141            let n = self.nodes.get(lid);
1142            self.index.insert(
1143                StoredKey {
1144                    fp: fold32(n.content_hash()),
1145                    local_id: lid,
1146                },
1147                (),
1148            );
1149        }
1150    }
1151
1152    fn fingerprint(&self, op: &O, lit: &V) -> Fingerprint {
1153        let mut h = rapidhash::fast::RapidHasher::default();
1154        op.hash(&mut h);
1155        lit.hash(&mut h);
1156        fold32(h.finish())
1157    }
1158}
1159
1160// ---------------------------------------------------------------------------
1161// Tests
1162// ---------------------------------------------------------------------------
1163
1164#[cfg(test)]
1165mod tests {
1166    use super::*;
1167    use crate::canon::{CCanon, MSetCanon, OrderedCanon, PlainCanon, SetCanon};
1168    use crate::id::{ENodeId, OpId};
1169    use crate::multiplicity::Multiplicity;
1170    use crate::nodes::{
1171        LitNodeId, LitValId, MSetNodeId, Plain0Id, Plain2Id, PlainNId, SPairNodeId, SetNodeId,
1172    };
1173
1174    #[test]
1175    fn fixed_arity_probe_insert() {
1176        let mut c = FixedArityCache::<ENodeId, OpId, Plain0Id, 0, false>::new();
1177        let op = OpId::new(0);
1178        let r = c.probe_or_insert(ENodeId::new(0), op, []);
1179        assert!(matches!(r, InsertResult::Inserted { .. }));
1180        let r2 = c.probe_or_insert(ENodeId::new(99), op, []);
1181        assert!(matches!(r2, InsertResult::Hit { .. }));
1182    }
1183
1184    #[test]
1185    fn fixed_arity_binary() {
1186        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
1187        let op = OpId::new(0);
1188        let ch = [ENodeId::new(1), ENodeId::new(2)];
1189        let r = c.probe_or_insert(ENodeId::new(0), op, ch);
1190        assert!(matches!(r, InsertResult::Inserted { .. }));
1191        assert!(c.probe(&op, &ch).is_some());
1192        assert!(c.probe(&op, &[ENodeId::new(2), ENodeId::new(1)]).is_none());
1193    }
1194
1195    /// A 32-bit fingerprint collision does not produce a wrong hash-cons hit.
1196    ///
1197    /// `probe` uses the fingerprint only to reach a candidate; the hit is
1198    /// declared by `n.op() == *op && n.children == *children` (fixed arity) and
1199    /// `n.op() == op && self.children_eq(&n, elems)` (variable arity). Without
1200    /// that confirmation a collision would return some *other* node's class,
1201    /// which `EGraph::add` would then treat as the term's class — an unsound
1202    /// merge of two structurally different terms. The test brute-forces a real
1203    /// collision (birthday: ~2^16 candidates expected) and checks both probes
1204    /// still answer with their own node.
1205    #[test]
1206    fn fingerprint_collision_is_disambiguated_by_content() {
1207        const LIMIT: u32 = 4_000_000;
1208
1209        // -- fixed arity: `[G; 2]`, hashed element-wise --
1210        let mut fixed = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
1211        let op = OpId::new(0);
1212        let mut seen: std::collections::HashMap<Fingerprint, u32> =
1213            std::collections::HashMap::new();
1214        let (a, b) = (0..LIMIT)
1215            .find_map(|n| {
1216                let fp = fixed.fingerprint(&op, &[ENodeId::new(n), ENodeId::new(0)]);
1217                seen.insert(fp, n).map(|prev| (prev, n))
1218            })
1219            .expect("no 32-bit fingerprint collision within the search bound");
1220        assert_ne!(a, b);
1221        let (ca, cb) = (
1222            [ENodeId::new(a), ENodeId::new(0)],
1223            [ENodeId::new(b), ENodeId::new(0)],
1224        );
1225        // A genuine collision: same fingerprint, different children.
1226        assert_eq!(fixed.fingerprint(&op, &ca), fixed.fingerprint(&op, &cb));
1227        assert_ne!(ca, cb);
1228
1229        let ga = ENodeId::new(LIMIT + 1);
1230        let gb = ENodeId::new(LIMIT + 2);
1231        assert!(matches!(
1232            fixed.probe_or_insert(ga, op, ca),
1233            InsertResult::Inserted { .. }
1234        ));
1235        // The colliding node must NOT be reported as already present.
1236        assert!(matches!(
1237            fixed.probe_or_insert(gb, op, cb),
1238            InsertResult::Inserted { .. }
1239        ));
1240        assert_eq!(fixed.probe(&op, &ca), Some(ga));
1241        assert_eq!(fixed.probe(&op, &cb), Some(gb));
1242
1243        // -- variable arity: `&[C]`, hashed with a length prefix --
1244        let mut var = VariableArityCache::<ENodeId, OpId, ENodeId, PlainNId, false>::new();
1245        let mut seen: std::collections::HashMap<Fingerprint, u32> =
1246            std::collections::HashMap::new();
1247        let (a, b) = (0..LIMIT)
1248            .find_map(|n| {
1249                let fp = var.fingerprint(&op, &[ENodeId::new(n), ENodeId::new(0)]);
1250                seen.insert(fp, n).map(|prev| (prev, n))
1251            })
1252            .expect("no 32-bit fingerprint collision within the search bound");
1253        let (va, vb) = (
1254            [ENodeId::new(a), ENodeId::new(0)],
1255            [ENodeId::new(b), ENodeId::new(0)],
1256        );
1257        assert_eq!(var.fingerprint(&op, &va), var.fingerprint(&op, &vb));
1258        assert_ne!(va, vb);
1259
1260        assert!(matches!(
1261            var.probe_or_insert(ga, op, &va),
1262            InsertResult::Inserted { .. }
1263        ));
1264        assert!(matches!(
1265            var.probe_or_insert(gb, op, &vb),
1266            InsertResult::Inserted { .. }
1267        ));
1268        assert_eq!(var.probe(op, &va), Some(ga));
1269        assert_eq!(var.probe(op, &vb), Some(gb));
1270    }
1271
1272    #[test]
1273    fn variable_arity_probe_insert() {
1274        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, PlainNId, false>::new();
1275        let op = OpId::new(0);
1276        let ch = &[ENodeId::new(1), ENodeId::new(2), ENodeId::new(3)];
1277        let r = c.probe_or_insert(ENodeId::new(0), op, ch);
1278        assert!(matches!(r, InsertResult::Inserted { .. }));
1279        assert!(c.probe(op, ch).is_some());
1280    }
1281
1282    #[test]
1283    fn lit_cache_probe_insert() {
1284        let mut c = LitCache::<ENodeId, OpId, LitValId, LitNodeId, false>::new();
1285        let op = OpId::new(0);
1286        let lit = LitValId::new(42);
1287        let r = c.probe_or_insert(ENodeId::new(0), op, lit);
1288        assert!(matches!(r, InsertResult::Inserted { .. }));
1289        assert!(c.probe(op, lit).is_some());
1290        assert!(c.probe(op, LitValId::new(99)).is_none());
1291    }
1292
1293    // -- recanonize_node tests --
1294
1295    fn id(n: u32) -> ENodeId {
1296        ENodeId::new(n)
1297    }
1298
1299    #[test]
1300    fn recanonize_fixed_no_change() {
1301        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
1302        let op = OpId::new(0);
1303        c.probe_or_insert(id(0), op, [id(1), id(2)]);
1304        let mut collisions = Vec::new();
1305        c.recanonize_node::<PlainCanon>(Plain2Id::new(0), |g| g, &mut collisions, &mut Vec::new());
1306        assert!(collisions.is_empty());
1307        // node unchanged
1308        assert!(c.probe(&op, &[id(1), id(2)]).is_some());
1309    }
1310
1311    #[test]
1312    fn recanonize_fixed_plain_updates_children() {
1313        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
1314        let op = OpId::new(0);
1315        c.probe_or_insert(id(0), op, [id(1), id(2)]);
1316        let mut collisions = Vec::new();
1317        // find: 2 → 1
1318        c.recanonize_node::<PlainCanon>(
1319            Plain2Id::new(0),
1320            |g| {
1321                if g == id(2) { id(1) } else { g }
1322            },
1323            &mut collisions,
1324            &mut Vec::new(),
1325        );
1326        assert!(collisions.is_empty());
1327        // old key gone, new key present
1328        assert!(c.probe(&op, &[id(1), id(2)]).is_none());
1329        assert!(c.probe(&op, &[id(1), id(1)]).is_some());
1330    }
1331
1332    #[test]
1333    fn recanonize_fixed_collision() {
1334        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
1335        let op = OpId::new(0);
1336        c.probe_or_insert(id(10), op, [id(1), id(1)]); // node A: (op, [1,1]) → gid 10
1337        c.probe_or_insert(id(20), op, [id(1), id(2)]); // node B: (op, [1,2]) → gid 20
1338        let mut collisions = Vec::new();
1339        // find: 2 → 1, so node B becomes (op, [1,1]) → collision with A
1340        c.recanonize_node::<PlainCanon>(
1341            Plain2Id::new(1),
1342            |g| {
1343                if g == id(2) { id(1) } else { g }
1344            },
1345            &mut collisions,
1346            &mut Vec::new(),
1347        );
1348        assert_eq!(collisions.len(), 1);
1349        assert_eq!(collisions[0], (id(20), id(10)));
1350    }
1351
1352    #[test]
1353    fn recanonize_c_sorts_pair() {
1354        let mut c = FixedArityCache::<ENodeId, OpId, SPairNodeId, 2, false>::new();
1355        let op = OpId::new(0);
1356        c.probe_or_insert(id(10), op, [id(1), id(5)]); // sorted: [1, 5]
1357        let mut collisions = Vec::new();
1358        // find: 1 → 9, so children become [9, 5], CCanon sorts to [5, 9]
1359        c.recanonize_node::<CCanon>(
1360            SPairNodeId::new(0),
1361            |g| {
1362                if g == id(1) { id(9) } else { g }
1363            },
1364            &mut collisions,
1365            &mut Vec::new(),
1366        );
1367        assert!(collisions.is_empty());
1368        assert!(c.probe(&op, &[id(5), id(9)]).is_some());
1369    }
1370
1371    #[test]
1372    fn recanonize_var_ordered_no_change() {
1373        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, PlainNId, false>::new();
1374        let op = OpId::new(0);
1375        c.probe_or_insert(id(0), op, &[id(1), id(2), id(3)]);
1376        let mut buf = Vec::new();
1377        let mut collisions = Vec::new();
1378        c.recanonize_node::<OrderedCanon>(
1379            PlainNId::new(0),
1380            |g| g,
1381            &mut buf,
1382            &mut collisions,
1383            &mut Vec::new(),
1384            crate::canon::CanonMode::PLAIN,
1385        );
1386        assert!(collisions.is_empty());
1387    }
1388
1389    #[test]
1390    fn recanonize_var_ordered_collision() {
1391        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, PlainNId, false>::new();
1392        let op = OpId::new(0);
1393        c.probe_or_insert(id(10), op, &[id(1), id(1)]);
1394        c.probe_or_insert(id(20), op, &[id(1), id(2)]);
1395        let mut buf = Vec::new();
1396        let mut collisions = Vec::new();
1397        c.recanonize_node::<OrderedCanon>(
1398            PlainNId::new(1),
1399            |g| {
1400                if g == id(2) { id(1) } else { g }
1401            },
1402            &mut buf,
1403            &mut collisions,
1404            &mut Vec::new(),
1405            crate::canon::CanonMode::PLAIN,
1406        );
1407        assert_eq!(collisions, vec![(id(20), id(10))]);
1408    }
1409
1410    #[test]
1411    fn recanonize_aci_shrinks() {
1412        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, SetNodeId, false>::new();
1413        let op = OpId::new(0);
1414        // {1, 2, 3} sorted
1415        c.probe_or_insert(id(10), op, &[id(1), id(2), id(3)]);
1416        let mut buf = Vec::new();
1417        let mut collisions = Vec::new();
1418        // find: 2 → 1, 3 → 3 → after ACI canon: {1, 3} (deduped, sorted)
1419        c.recanonize_node::<SetCanon>(
1420            SetNodeId::new(0),
1421            |g| {
1422                if g == id(2) { id(1) } else { g }
1423            },
1424            &mut buf,
1425            &mut collisions,
1426            &mut Vec::new(),
1427            crate::canon::CanonMode::PLAIN,
1428        );
1429        assert!(collisions.is_empty());
1430        assert!(c.probe(op, &[id(1), id(3)]).is_some());
1431        // old 3-element key gone
1432        assert!(c.probe(op, &[id(1), id(2), id(3)]).is_none());
1433    }
1434
1435    // -- mark / restore --
1436
1437    const SHRINK: ShrinkPolicy = ShrinkPolicy::Never;
1438
1439    /// Restore drops the entries of the nodes the scope added and keeps the
1440    /// rest, which is what makes a later `probe` answer for the restored graph.
1441    #[test]
1442    fn restore_drops_the_post_mark_suffix() {
1443        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
1444        let op = OpId::new(0);
1445        c.probe_or_insert(id(10), op, [id(1), id(2)]);
1446        let token = c.mark(SHRINK);
1447        c.probe_or_insert(id(20), op, [id(3), id(4)]);
1448        assert!(c.probe(&op, &[id(3), id(4)]).is_some());
1449
1450        c.restore(token);
1451        assert_eq!(c.len(), Plain2Id::new(1));
1452        assert_eq!(c.probe(&op, &[id(1), id(2)]), Some(id(10)));
1453        assert!(c.probe(&op, &[id(3), id(4)]).is_none());
1454        // The freed local id is reusable and does not collide with the entry
1455        // the discarded node left behind, because there is none.
1456        c.probe_or_insert(id(30), op, [id(5), id(6)]);
1457        assert_eq!(c.probe(&op, &[id(5), id(6)]), Some(id(30)));
1458    }
1459
1460    /// A pre-mark node recanonized inside the scope is filed under its new key
1461    /// while the scope runs and back under the mark's key after restore.
1462    #[test]
1463    fn restore_rekeys_a_recanonized_pre_mark_node() {
1464        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
1465        let op = OpId::new(0);
1466        c.probe_or_insert(id(10), op, [id(1), id(2)]);
1467        let token = c.mark(SHRINK);
1468        c.recanonize_node::<PlainCanon>(
1469            Plain2Id::new(0),
1470            |g| if g == id(2) { id(1) } else { g },
1471            &mut Vec::new(),
1472            &mut Vec::new(),
1473        );
1474        assert!(c.probe(&op, &[id(1), id(1)]).is_some());
1475        assert!(c.probe(&op, &[id(1), id(2)]).is_none());
1476
1477        c.restore(token);
1478        assert_eq!(c.probe(&op, &[id(1), id(2)]), Some(id(10)));
1479        assert!(c.probe(&op, &[id(1), id(1)]).is_none());
1480    }
1481
1482    /// Same for a variable-arity node, whose content lives in the shared child
1483    /// pool: the pool rolls back with the arena and the key follows it.
1484    #[test]
1485    fn restore_rekeys_a_recanonized_variable_arity_node() {
1486        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, SetNodeId>::new();
1487        let op = OpId::new(0);
1488        c.probe_or_insert(id(10), op, &[id(1), id(2), id(3)]);
1489        let token = c.mark(SHRINK);
1490        c.recanonize_node::<SetCanon>(
1491            SetNodeId::new(0),
1492            |g| if g == id(2) { id(1) } else { g },
1493            &mut Vec::new(),
1494            &mut Vec::new(),
1495            &mut Vec::new(),
1496            crate::canon::CanonMode::PLAIN,
1497        );
1498        assert!(c.probe(op, &[id(1), id(3)]).is_some());
1499
1500        c.restore(token);
1501        assert_eq!(c.probe(op, &[id(1), id(2), id(3)]), Some(id(10)));
1502        assert!(c.probe(op, &[id(1), id(3)]).is_none());
1503    }
1504
1505    /// Nested marks: restoring the outer token past an unrestored inner mark
1506    /// has to undo both the inner suffix and a pre-outer-mark node the inner
1507    /// scope re-keyed.
1508    #[test]
1509    fn restore_past_an_open_inner_mark() {
1510        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
1511        let op = OpId::new(0);
1512        c.probe_or_insert(id(10), op, [id(1), id(2)]);
1513        let outer = c.mark(SHRINK);
1514        c.probe_or_insert(id(20), op, [id(3), id(4)]);
1515        let _inner = c.mark(SHRINK);
1516        c.probe_or_insert(id(30), op, [id(5), id(6)]);
1517        c.recanonize_node::<PlainCanon>(
1518            Plain2Id::new(0),
1519            |g| if g == id(2) { id(7) } else { g },
1520            &mut Vec::new(),
1521            &mut Vec::new(),
1522        );
1523
1524        c.restore(outer);
1525        assert_eq!(c.len(), Plain2Id::new(1));
1526        assert_eq!(c.probe(&op, &[id(1), id(2)]), Some(id(10)));
1527        assert!(c.probe(&op, &[id(1), id(7)]).is_none());
1528        assert!(c.probe(&op, &[id(3), id(4)]).is_none());
1529        assert!(c.probe(&op, &[id(5), id(6)]).is_none());
1530    }
1531
1532    /// A scope that adds more than a quarter of the arena takes the rebuild
1533    /// fallback, and lands on the same index the incremental path would build.
1534    #[test]
1535    fn restore_falls_back_to_rebuild_on_a_large_suffix() {
1536        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
1537        let op = OpId::new(0);
1538        c.probe_or_insert(id(10), op, [id(1), id(2)]);
1539        let token = c.mark(SHRINK);
1540        for k in 0..10 {
1541            c.probe_or_insert(id(100 + k), op, [id(200 + k), id(0)]);
1542        }
1543        assert!(!restore_incrementally(10, 0, 1));
1544
1545        c.restore(token);
1546        assert_eq!(c.len(), Plain2Id::new(1));
1547        assert_eq!(c.probe(&op, &[id(1), id(2)]), Some(id(10)));
1548        assert!(c.probe(&op, &[id(200), id(0)]).is_none());
1549    }
1550
1551    /// The check `restore` asserts on rejects a stale key. Without this, an
1552    /// index that never diverges and a check that never looks are the same
1553    /// test result.
1554    #[cfg(debug_assertions)]
1555    #[test]
1556    fn index_check_rejects_a_stale_key() {
1557        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
1558        let op = OpId::new(0);
1559        c.probe_or_insert(id(10), op, [id(1), id(2)]);
1560        assert!(c.index_matches_rebuild());
1561
1562        let local_id = Plain2Id::new(0);
1563        let fp = c.fingerprint(&op, &[id(1), id(2)]);
1564        c.index.remove(&StoredKey { fp, local_id });
1565        assert!(!c.index_matches_rebuild(), "a missing entry is a mismatch");
1566        c.index.insert(
1567            StoredKey {
1568                fp: fp ^ 1,
1569                local_id,
1570            },
1571            (),
1572        );
1573        assert!(!c.index_matches_rebuild(), "a stale key is a mismatch");
1574    }
1575
1576    #[test]
1577    fn recanonize_ac_merges_mult() {
1578        type MSetChild = crate::containers::Pair<ENodeId, Multiplicity>;
1579        let pair = |g, m| crate::containers::Pair {
1580            a: g,
1581            b: Multiplicity(m),
1582        };
1583        let mut c = VariableArityCache::<ENodeId, OpId, MSetChild, MSetNodeId, false>::new();
1584        let op = OpId::new(0);
1585        let elems: &[MSetChild] = &[pair(id(1), 1), pair(id(2), 1), pair(id(3), 1)];
1586        c.probe_or_insert(id(10), op, elems);
1587        let mut buf = Vec::new();
1588        let mut collisions = Vec::new();
1589        c.recanonize_node::<MSetCanon>(
1590            MSetNodeId::new(0),
1591            |g| {
1592                if g == id(2) { id(1) } else { g }
1593            },
1594            &mut buf,
1595            &mut collisions,
1596            &mut Vec::new(),
1597            crate::canon::CanonMode::PLAIN,
1598        );
1599        assert!(collisions.is_empty());
1600        let expected: &[MSetChild] = &[pair(id(1), 2), pair(id(3), 1)];
1601        assert!(c.probe(op, expected).is_some());
1602    }
1603}