semi-persistent-egraph 0.3.0

Semi-persistent equality saturation engine with e-matching, rewrite scheduling, and proof logging
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Generic node caches — hash-consing tables parameterized by id types.
//!
//! - `FixedArityCache<G, O, L, K, TRACK>` — for Plain0..3 and Commutative
//! - `VariableArityCache<G, O, C, L, TRACK>` — for PlainN, A, AC, ACI
//! - `LitCache<G, O, V, L, TRACK>` — for literal leaves

use std::hash::{BuildHasher, Hash, Hasher};

use crate::canon::{FixedCanon, VarCanon};
use crate::containers::DenseId;
use crate::containers::IndexLike; // prod-parity: L::min() (was L::MIN)
use crate::containers::Tagged;
use crate::containers::{ShrinkPolicy, VecI, VecToken};
use crate::node_types::{FixedArityNode, LitNode, VariableArityNode};

// ---------------------------------------------------------------------------
// Shared infrastructure
// ---------------------------------------------------------------------------

#[derive(Default, Clone)]
struct PassthroughHasher(u64);

impl Hasher for PassthroughHasher {
    fn write(&mut self, _bytes: &[u8]) {}
    fn write_u64(&mut self, i: u64) {
        self.0 = i;
    }
    fn finish(&self) -> u64 {
        self.0
    }
}

#[derive(Default, Clone)]
struct PassthroughBuildHasher;

impl BuildHasher for PassthroughBuildHasher {
    type Hasher = PassthroughHasher;
    fn build_hasher(&self) -> PassthroughHasher {
        PassthroughHasher(0)
    }
}

/// A node's content hash, folded to 32 bits.
///
/// The index stores the fingerprint rather than the whole 64-bit hash. It is
/// not a filter that has to be exact — every candidate the table returns is
/// still confirmed against the node's operator and children — so its only job
/// is to keep the table from reading the node arena on a near-miss, and 32
/// bits do that: at a million nodes the expected number of colliding pairs in
/// the whole table is under two hundred.
///
/// What the width buys is the entry: `(StoredKey<u32>, ())` is eight bytes
/// where `(StoredKey<u64>, G)` was sixteen, so a probe of a million-node table
/// touches half as many cache lines and a growth rehashes half as much memory.
type Fingerprint = u32;

/// Fold a 64-bit content hash into a fingerprint, mixing the high half in so
/// every input bit reaches the result.
#[inline]
fn fold32(h: u64) -> Fingerprint {
    (h ^ (h >> 32)) as Fingerprint
}

/// Spread a fingerprint over the 64 bits hashbrown reads.
///
/// hashbrown takes the bucket index from the low bits and the control byte
/// from the top seven, so a fingerprint zero-extended into a `u64` would file
/// every entry under the same control byte and turn each probe into a scan.
/// Multiplying by an odd constant is a bijection on `u64`, so distinct
/// fingerprints keep distinct hashes and equal ones keep equal hashes — which
/// is what lets `remove` find an entry from its stored fingerprint.
#[inline]
fn spread(fp: Fingerprint) -> u64 {
    (fp as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
}

#[derive(Clone, Copy, Debug)]
struct StoredKey<L> {
    fp: Fingerprint,
    local_id: L,
}

impl<L> Hash for StoredKey<L> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_u64(spread(self.fp));
    }
}
impl<L: PartialEq> PartialEq for StoredKey<L> {
    fn eq(&self, other: &Self) -> bool {
        self.local_id == other.local_id
    }
}
impl<L: Eq> Eq for StoredKey<L> {}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InsertResult<G, L> {
    Hit { global_id: G },
    Inserted { local_id: L },
}

/// One open mark, mirroring the frame the node arena pushed for the same mark.
///
/// `saved_len` splits the arena at restore time: local ids below it existed at
/// the mark and keep their index entries, ids at or above it are the suffix the
/// restore deletes. `dirty_start` cuts [`dirty`](FixedArityCache::dirty) into
/// per-frame segments the same way the arena's `diff_start` cuts its diff log.
#[derive(Clone, Copy, Debug)]
struct CacheFrame {
    saved_len: usize,
    dirty_start: usize,
    /// Set when the budget dropped a pre-mark write from `dirty`. Restore must
    /// then rebuild: the dirty segment is incomplete. The ratio test reaches
    /// the same verdict arithmetically (an overflowing segment already fails
    /// it), and this flag states the requirement instead of relying on that
    /// coupling.
    dirty_overflow: bool,
}

/// Restore rebuilds the whole index once the incremental work would exceed
/// `1 / REBUILD_RATIO` of it.
///
/// Deleting one index entry costs a fingerprint and a probe, about what
/// inserting one during a rebuild costs, and the incremental path also
/// re-inserts every recanonized pre-mark node, so the two paths break even
/// near `suffix + 2 * dirty == live`. A quarter keeps the incremental path
/// below that break-even point and bounds the cost of a restore that takes the
/// rebuild it did not need to a quarter of one.
pub(crate) const REBUILD_RATIO: usize = 4;

/// Per-frame cap on recorded pre-mark writes: past it, restore is going to
/// rebuild anyway (the fallback test below is already false), so recording
/// more would only cost memory.
#[inline]
fn dirty_budget(saved_len: usize) -> usize {
    saved_len / REBUILD_RATIO
}

/// Whether restore can fix the index in place rather than rebuilding it.
#[inline]
pub(crate) fn restore_incrementally(suffix_len: usize, dirty_len: usize, saved_len: usize) -> bool {
    REBUILD_RATIO * (suffix_len + dirty_len) <= saved_len
}

#[derive(Clone, Copy, Debug)]
pub struct CacheToken {
    nodes: VecToken,
    history: Option<VecToken>,
    frame_index: usize,
}

#[derive(Clone, Copy, Debug)]
pub struct PoolCacheToken {
    nodes: VecToken,
    children: VecToken,
    history_nodes: Option<VecToken>,
    history_children: Option<VecToken>,
    frame_index: usize,
}

// ---------------------------------------------------------------------------
// FixedArityCache<G, O, L, K, TRACK, PROOFS>
// ---------------------------------------------------------------------------

pub struct FixedArityCache<
    G: DenseId,
    O: DenseId,
    L: DenseId,
    const K: usize,
    const TRACK: bool = true,
    const PROOFS: bool = false,
> {
    /// One entry per node, so `L` (a local node id) is the index width.
    nodes: VecI<FixedArityNode<G, O, K>, L, TRACK>,
    index: hashbrown::HashMap<StoredKey<L>, (), PassthroughBuildHasher>,
    /// Recanonicalization history, indexed at `usize`: its population is the number of
    /// rewrites performed, not the number of nodes, and a single node can be recanonicalized
    /// arbitrarily many times — so no id capacity bounds it and `L` here would be a cap.
    history: Option<VecI<FixedArityNode<G, O, K>, usize, TRACK>>,
    /// Local ids below the enclosing mark's `saved_len` whose content
    /// `recanonize_node` changed. Their index entries were re-keyed at
    /// recanonize time and the arena rolls their content back on restore, so
    /// restore has to re-key them a second time, back to the mark's content.
    /// Duplicates are allowed: re-keying a node twice is idempotent.
    dirty: Vec<L>,
    frames: Vec<CacheFrame>,
}

impl<
    G: DenseId + Hash,
    O: DenseId + Hash,
    L: DenseId,
    const K: usize,
    const TRACK: bool,
    const PROOFS: bool,
> Default for FixedArityCache<G, O, L, K, TRACK, PROOFS>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<
    G: DenseId + Hash,
    O: DenseId + Hash,
    L: DenseId,
    const K: usize,
    const TRACK: bool,
    const PROOFS: bool,
> FixedArityCache<G, O, L, K, TRACK, PROOFS>
{
    pub fn new() -> Self {
        Self {
            nodes: VecI::new(),
            index: hashbrown::HashMap::with_hasher(PassthroughBuildHasher),
            history: if PROOFS { Some(VecI::new()) } else { None },
            dirty: Vec::new(),
            frames: Vec::new(),
        }
    }

    pub fn len(&self) -> L {
        self.nodes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.nodes.len() == <L as IndexLike>::min()
    }

    pub fn get(&self, id: L) -> FixedArityNode<G, O, K> {
        self.nodes.get(id)
    }

    pub fn set(&mut self, id: L, node: FixedArityNode<G, O, K>) {
        self.nodes.set(id, node);
    }

    pub fn probe(&self, op: &O, children: &[G; K]) -> Option<G> {
        let fp = self.fingerprint(op, children);
        self.index
            .raw_entry()
            .from_hash(spread(fp), |sk| {
                sk.fp == fp && {
                    let n = self.nodes.get(sk.local_id);
                    n.op() == *op && n.children == *children
                }
            })
            .map(|(sk, _)| self.nodes.get(sk.local_id).global_id())
    }

    pub fn insert(&mut self, global_id: G, op: O, children: [G; K]) -> L {
        let node = FixedArityNode::new(global_id, op, children);
        let fp = self.fingerprint(&op, &children);
        let lid = self.nodes.len();
        self.nodes.try_push(node).expect("push: within index word");
        self.index.insert(StoredKey { fp, local_id: lid }, ());
        lid
    }

    pub fn probe_or_insert(&mut self, global_id: G, op: O, children: [G; K]) -> InsertResult<G, L> {
        if let Some(gid) = self.probe(&op, &children) {
            return InsertResult::Hit { global_id: gid };
        }
        let lid = self.insert(global_id, op, children);
        InsertResult::Inserted { local_id: lid }
    }

    pub fn node_get(&self, id: L) -> FixedArityNode<G, O, K> {
        self.nodes.get(id)
    }

    pub fn node_set(&mut self, id: L, node: FixedArityNode<G, O, K>) {
        self.nodes.set(id, node);
    }

    /// Recanonize a single node's children. Pushes collision pair into
    /// `collisions` if the new canonical form matches an existing node.
    /// When `PROOFS=true`, saves the original node to history on first recanonize.
    pub fn recanonize_node<F: FixedCanon<G, K>>(
        &mut self,
        local_id: L,
        find: impl Fn(G) -> G,
        collisions: &mut Vec<(G, G)>,
        touched: &mut Vec<G>,
    ) {
        let mut node = self.nodes.get(local_id);
        let old_fp = self.fingerprint(&node.op(), &node.children);

        F::canonize(&mut node.children, &find);

        let new_fp = self.fingerprint(&node.op(), &node.children);
        if new_fp == old_fp {
            let old = self.nodes.get(local_id);
            if old.children == node.children {
                return;
            }
        }

        // Node's canonical form genuinely changed this round — record it for
        // the semi-naive delta (after the no-change early-return above).
        touched.push(node.global_id());
        self.note_dirty(local_id);

        // save to history on first recanonize
        if let Some(hist) = &mut self.history
            && !node.has_history()
        {
            hist.try_push(self.nodes.get(local_id))
                .expect("push: within index word");
        }

        self.index.remove(&StoredKey {
            fp: old_fp,
            local_id,
        });

        let gid = node.global_id();
        let mut new_node = FixedArityNode::new(gid, node.op(), node.children);
        if PROOFS {
            new_node.set_history();
        }
        self.nodes.set(local_id, new_node);

        if let Some(existing_gid) = self.probe(&node.op(), &node.children) {
            collisions.push((gid, existing_gid));
        }

        self.index.insert(
            StoredKey {
                fp: new_fp,
                local_id,
            },
            (),
        );
    }

    /// Retrieve the original (pre-recanonize) children for a node by global id.
    /// Linear scan of the history store. Returns `None` if no history or not found.
    pub fn original_children(&self, global_id: G) -> Option<[G; K]> {
        let hist = self.history.as_ref()?;
        let len = hist.len();
        for i in 0..len {
            let node = hist.get(i);
            if node.global_id() == global_id {
                return Some(node.children);
            }
        }
        None
    }

    /// Record a pre-mark node whose content just changed, so restore can put
    /// its index entry back under the mark's key. Nodes at or above the
    /// enclosing mark's `saved_len` need no entry: they are in the suffix
    /// restore deletes outright, and every enclosing mark's `saved_len` is no
    /// larger, so they are in its suffix too.
    #[inline]
    fn note_dirty(&mut self, local_id: L) {
        if !TRACK {
            return;
        }
        let Some(frame) = self.frames.last_mut() else {
            return;
        };
        if local_id.as_usize() >= frame.saved_len {
            return;
        }
        if self.dirty.len() - frame.dirty_start > dirty_budget(frame.saved_len) {
            frame.dirty_overflow = true;
            return;
        }
        self.dirty.push(local_id);
    }

    pub fn mark(&mut self, shrink: ShrinkPolicy) -> CacheToken {
        let token = CacheToken {
            nodes: self
                .nodes
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
            history: self.history.as_mut().map(|h| {
                h.try_mark(shrink)
                    .expect("mark: frame depth is bounded by the saturation driver")
            }),
            frame_index: self.frames.len(),
        };
        self.frames.push(CacheFrame {
            saved_len: self.nodes.len().as_usize(),
            dirty_start: self.dirty.len(),
            dirty_overflow: false,
        });
        token
    }

    pub fn restore(&mut self, token: CacheToken) {
        let frame = *self
            .frames
            .get(token.frame_index)
            .expect("restore: token minted by this cache's own mark, and not already spent");
        // Validate every inner token BEFORE touching the index: the deletions
        // below are not undoable, so an invalid token must refuse while the
        // cache is still consistent.
        assert!(
            self.nodes.is_valid_token(&token.nodes),
            "restore: node-arena token is not restorable"
        );
        if let (Some(h), Some(tok)) = (&self.history, token.history.as_ref()) {
            assert!(
                h.is_valid_token(tok),
                "restore: history token is not restorable"
            );
        }
        let live_len = self.nodes.len().as_usize();
        let incremental = !frame.dirty_overflow
            && restore_incrementally(
                live_len - frame.saved_len,
                self.dirty.len() - frame.dirty_start,
                frame.saved_len,
            );

        // The arena is append-only, so the nodes added since the mark are the
        // contiguous suffix at or above `saved_len` and theirs are the entries
        // to delete. The only other entries the scope moved are those of the
        // pre-mark nodes `recanonize_node` re-keyed, which `dirty` names, so
        // the correction is O(added + recanonized) rather than O(live).
        //
        // Delete under the CURRENT keys, before the arena rolls the content
        // back: an entry is filed under the fingerprint of the content it had
        // when it was last written.
        if incremental {
            for i in frame.saved_len..live_len {
                self.remove_entry(L::from_usize(i));
            }
            for k in frame.dirty_start..self.dirty.len() {
                self.remove_entry(self.dirty[k]);
            }
        }

        self.nodes
            .try_restore(token.nodes)
            .expect("restore: token minted by this container's own mark");
        if let (Some(h), Some(tok)) = (&mut self.history, token.history) {
            h.try_restore(tok)
                .expect("restore: token minted by this container's own mark");
        }

        if incremental {
            for k in frame.dirty_start..self.dirty.len() {
                self.insert_entry(self.dirty[k]);
            }
        } else {
            self.rebuild_index();
        }
        self.dirty.truncate(frame.dirty_start);
        self.frames.truncate(token.frame_index);
        #[cfg(debug_assertions)]
        debug_assert!(
            self.index_matches_rebuild(),
            "restore left the hashcons index out of step with the node arena"
        );
    }

    /// Drop `local_id`'s entry, keyed by the content it holds right now. A
    /// repeat call is a no-op: the entry is already gone.
    #[inline]
    fn remove_entry(&mut self, local_id: L) {
        let fp = fold32(self.nodes.get(local_id).content_hash());
        self.index.remove(&StoredKey { fp, local_id });
    }

    #[inline]
    fn insert_entry(&mut self, local_id: L) {
        let fp = fold32(self.nodes.get(local_id).content_hash());
        self.index.insert(StoredKey { fp, local_id }, ());
    }

    /// The index holds exactly one entry per live node, keyed by that node's
    /// current content, which is what [`rebuild_index`](Self::rebuild_index)
    /// produces from scratch.
    #[cfg(debug_assertions)]
    fn index_matches_rebuild(&self) -> bool {
        let count = self.nodes.len().as_usize();
        if self.index.len() != count {
            return false;
        }
        let mut seen = vec![false; count];
        for (sk, ()) in self.index.iter() {
            let i = sk.local_id.as_usize();
            if i >= count || seen[i] || sk.fp != fold32(self.nodes.get(sk.local_id).content_hash())
            {
                return false;
            }
            seen[i] = true;
        }
        true
    }

    fn rebuild_index(&mut self) {
        self.index.clear();
        // `from_usize` needs no bound check here: `nodes` is indexed *by* `L`, so its own
        // capacity guard is the id bound (`IndexLike::max_nat()` of a dense id is its
        // `id_bound()`). Every position the arena can hold therefore has a local id. The
        // scans that DO need a check are the ones over a container indexed by an id's
        // *word* rather than the id — see `EGraph::node_ids`.
        let count = self.nodes.len().as_usize();
        for i in 0..count {
            let lid = L::from_usize(i);
            let n = self.nodes.get(lid);
            self.index.insert(
                StoredKey {
                    fp: fold32(n.content_hash()),
                    local_id: lid,
                },
                (),
            );
        }
    }

    fn fingerprint(&self, op: &O, children: &[G; K]) -> Fingerprint {
        let mut h = rapidhash::fast::RapidHasher::default();
        op.hash(&mut h);
        children.hash(&mut h);
        fold32(h.finish())
    }
}

// ---------------------------------------------------------------------------
// VariableArityCache<G, O, C, L, TRACK, PROOFS>
// ---------------------------------------------------------------------------

pub struct VariableArityCache<
    G: DenseId,
    O: DenseId,
    C: Tagged + Clone + Copy + Hash + Eq,
    L: DenseId,
    const TRACK: bool = true,
    const PROOFS: bool = false,
> {
    /// One entry per node, so `L` (a local node id) is the index width.
    nodes: VecI<VariableArityNode<G, O>, L, TRACK>,
    /// The shared child pool the nodes' spans address. Indexed at `usize`, matching the
    /// `start`/`end` words in [`VariableArityNode`]: its population is `Σ arity` over the
    /// nodes, which neither `L`'s nor `G`'s capacity bounds, so an id-width index here would
    /// be a new cap rather than a narrowing. See [`VariableArityNode::start`].
    children: VecI<C, usize, TRACK>,
    index: hashbrown::HashMap<StoredKey<L>, (), PassthroughBuildHasher>,
    /// Recanonicalization history. `usize` for a different reason than `children`: the
    /// population here is the number of *rewrites* the run has performed, which is unbounded
    /// by any id capacity — a single node can be recanonicalized arbitrarily many times.
    history_nodes: Option<VecI<VariableArityNode<G, O>, usize, TRACK>>,
    /// Children of the history entries; `Σ arity` over `history_nodes`, so `usize` for both
    /// of the reasons above at once.
    history_children: Option<VecI<C, usize, TRACK>>,
    /// Local ids below the enclosing mark's `saved_len` whose content
    /// `recanonize_node` changed, through the node's own span or through the
    /// child pool it addresses. See [`FixedArityCache::dirty`].
    dirty: Vec<L>,
    frames: Vec<CacheFrame>,
}

impl<
    G: DenseId + Hash,
    O: DenseId + Hash,
    C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
    L: DenseId,
    const TRACK: bool,
    const PROOFS: bool,
> Default for VariableArityCache<G, O, C, L, TRACK, PROOFS>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<
    G: DenseId + Hash,
    O: DenseId + Hash,
    C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
    L: DenseId,
    const TRACK: bool,
    const PROOFS: bool,
> VariableArityCache<G, O, C, L, TRACK, PROOFS>
{
    pub fn new() -> Self {
        Self {
            nodes: VecI::new(),
            children: VecI::new(),
            index: hashbrown::HashMap::with_hasher(PassthroughBuildHasher),
            history_nodes: if PROOFS { Some(VecI::new()) } else { None },
            history_children: if PROOFS { Some(VecI::new()) } else { None },
            dirty: Vec::new(),
            frames: Vec::new(),
        }
    }

    pub fn len(&self) -> L {
        self.nodes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.nodes.len() == <L as IndexLike>::min()
    }

    pub fn get(&self, id: L) -> VariableArityNode<G, O> {
        self.nodes.get(id)
    }

    pub fn set(&mut self, id: L, node: VariableArityNode<G, O>) {
        self.nodes.set(id, node);
    }

    pub fn children_vec(&self, node: &VariableArityNode<G, O>) -> Vec<C> {
        let (start, end) = node.span();
        (start..end).map(|i| self.children.get(i)).collect()
    }

    pub fn pool_get(&self, i: usize) -> C {
        self.children.get(i)
    }

    pub fn pool_set(&mut self, i: usize, value: C) {
        self.children.set(i, value);
    }

    pub fn probe(&self, op: O, elems: &[C]) -> Option<G> {
        let fp = self.fingerprint(&op, elems);
        self.index
            .raw_entry()
            .from_hash(spread(fp), |sk| {
                sk.fp == fp && {
                    let n = self.nodes.get(sk.local_id);
                    n.op() == op && self.children_eq(&n, elems)
                }
            })
            .map(|(sk, _)| self.nodes.get(sk.local_id).global_id())
    }

    pub fn insert(&mut self, global_id: G, op: O, elems: &[C]) -> L {
        let start = self.children.len();
        for &e in elems {
            self.children.try_push(e).expect("push: within index word");
        }
        let end = self.children.len();
        let node = VariableArityNode::make(global_id, op, start, end);
        let fp = self.fingerprint(&op, elems);
        let lid = self.nodes.len();
        self.nodes.try_push(node).expect("push: within index word");
        self.index.insert(StoredKey { fp, local_id: lid }, ());
        lid
    }

    pub fn probe_or_insert(&mut self, global_id: G, op: O, elems: &[C]) -> InsertResult<G, L> {
        if let Some(gid) = self.probe(op, elems) {
            return InsertResult::Hit { global_id: gid };
        }
        let lid = self.insert(global_id, op, elems);
        InsertResult::Inserted { local_id: lid }
    }

    pub fn node_get(&self, id: L) -> VariableArityNode<G, O> {
        self.nodes.get(id)
    }

    pub fn node_set(&mut self, id: L, node: VariableArityNode<G, O>) {
        self.nodes.set(id, node);
    }

    /// Recanonize a single node's children. `buf` is a caller-owned scratch
    /// buffer, cleared internally. Pushes collision pair into `collisions`
    /// if the new canonical form matches an existing node.
    /// When `PROOFS=true`, saves the original node+children to history on first recanonize.
    pub fn recanonize_node<V: VarCanon<G, C>>(
        &mut self,
        local_id: L,
        find: impl Fn(G) -> G,
        buf: &mut Vec<C>,
        collisions: &mut Vec<(G, G)>,
        touched: &mut Vec<G>,
        mode: crate::canon::CanonMode<G>,
    ) {
        let node = self.nodes.get(local_id);
        let (start, end) = node.span();
        let old_fp = self.children_fingerprint(&node);

        buf.clear();
        V::canonize(buf, start, end, |i| self.children.get(i), &find, mode);

        let new_len = buf.len();

        if new_len == end - start {
            let mut same = true;
            for i in 0..new_len {
                if buf[i] != self.children.get(start + i) {
                    same = false;
                    break;
                }
            }
            if same {
                return;
            }
        }

        // Node's canonical form genuinely changed this round — record it for
        // the semi-naive delta (after the no-change early-return above).
        touched.push(node.global_id());
        self.note_dirty(local_id);

        // save to history on first recanonize
        if let (Some(hn), Some(hc)) = (&mut self.history_nodes, &mut self.history_children)
            && !node.has_history()
        {
            let hist_start = hc.len();
            for i in start..end {
                hc.try_push(self.children.get(i))
                    .expect("push: within index word");
            }
            let hist_end = hc.len();
            hn.try_push(VariableArityNode::make(
                node.global_id(),
                node.op(),
                hist_start,
                hist_end,
            ))
            .expect("push: within index word");
        }

        self.index.remove(&StoredKey {
            fp: old_fp,
            local_id,
        });

        for i in 0..new_len {
            self.children.set(start + i, buf[i]);
        }

        let new_end = start + new_len;
        let gid = node.global_id();
        let mut updated = VariableArityNode::make(gid, node.op(), start, new_end);
        if PROOFS {
            updated.set_history();
        }
        if new_end != end || PROOFS {
            self.nodes.set(local_id, updated);
        }

        let new_fp = self.fingerprint(&node.op(), &buf[..new_len]);

        if let Some(existing_gid) = self.probe(node.op(), &buf[..new_len]) {
            collisions.push((gid, existing_gid));
        }

        self.index.insert(
            StoredKey {
                fp: new_fp,
                local_id,
            },
            (),
        );
    }

    /// Retrieve the original (pre-recanonize) children for a node by global id.
    /// Linear scan of the history store. Appends children to `out`.
    /// Returns `true` if found.
    pub fn original_children(&self, global_id: G, out: &mut Vec<C>) -> bool {
        let (hn, hc) = match (&self.history_nodes, &self.history_children) {
            (Some(hn), Some(hc)) => (hn, hc),
            _ => return false,
        };
        let len = hn.len();
        for i in 0..len {
            let node = hn.get(i);
            if node.global_id() == global_id {
                let (s, e) = node.span();
                for j in s..e {
                    out.push(hc.get(j));
                }
                return true;
            }
        }
        false
    }

    /// See [`FixedArityCache::note_dirty`].
    #[inline]
    fn note_dirty(&mut self, local_id: L) {
        if !TRACK {
            return;
        }
        let Some(frame) = self.frames.last_mut() else {
            return;
        };
        if local_id.as_usize() >= frame.saved_len {
            return;
        }
        if self.dirty.len() - frame.dirty_start > dirty_budget(frame.saved_len) {
            frame.dirty_overflow = true;
            return;
        }
        self.dirty.push(local_id);
    }

    pub fn mark(&mut self, shrink: ShrinkPolicy) -> PoolCacheToken {
        let token = PoolCacheToken {
            nodes: self
                .nodes
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
            children: self
                .children
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
            history_nodes: self.history_nodes.as_mut().map(|h| {
                h.try_mark(shrink)
                    .expect("mark: frame depth is bounded by the saturation driver")
            }),
            history_children: self.history_children.as_mut().map(|h| {
                h.try_mark(shrink)
                    .expect("mark: frame depth is bounded by the saturation driver")
            }),
            frame_index: self.frames.len(),
        };
        self.frames.push(CacheFrame {
            saved_len: self.nodes.len().as_usize(),
            dirty_start: self.dirty.len(),
            dirty_overflow: false,
        });
        token
    }

    pub fn restore(&mut self, token: PoolCacheToken) {
        let frame = *self
            .frames
            .get(token.frame_index)
            .expect("restore: token minted by this cache's own mark, and not already spent");
        // Validate every inner token BEFORE touching the index (as in the
        // fixed-arity restore above).
        assert!(
            self.nodes.is_valid_token(&token.nodes),
            "restore: node-arena token is not restorable"
        );
        assert!(
            self.children.is_valid_token(&token.children),
            "restore: child-pool token is not restorable"
        );
        if let (Some(h), Some(tok)) = (&self.history_nodes, token.history_nodes.as_ref()) {
            assert!(
                h.is_valid_token(tok),
                "restore: history token is not restorable"
            );
        }
        if let (Some(h), Some(tok)) = (&self.history_children, token.history_children.as_ref()) {
            assert!(
                h.is_valid_token(tok),
                "restore: history token is not restorable"
            );
        }
        let live_len = self.nodes.len().as_usize();
        let incremental = !frame.dirty_overflow
            && restore_incrementally(
                live_len - frame.saved_len,
                self.dirty.len() - frame.dirty_start,
                frame.saved_len,
            );

        // Delete under the CURRENT keys, before the arena and the child pool
        // roll back: an entry is filed under the fingerprint of the content it
        // had when it was last written.
        if incremental {
            for i in frame.saved_len..live_len {
                self.remove_entry(L::from_usize(i));
            }
            for k in frame.dirty_start..self.dirty.len() {
                self.remove_entry(self.dirty[k]);
            }
        }

        self.nodes
            .try_restore(token.nodes)
            .expect("restore: token minted by this container's own mark");
        self.children
            .try_restore(token.children)
            .expect("restore: token minted by this container's own mark");
        if let (Some(h), Some(tok)) = (&mut self.history_nodes, token.history_nodes) {
            h.try_restore(tok)
                .expect("restore: token minted by this container's own mark");
        }
        if let (Some(h), Some(tok)) = (&mut self.history_children, token.history_children) {
            h.try_restore(tok)
                .expect("restore: token minted by this container's own mark");
        }

        if incremental {
            for k in frame.dirty_start..self.dirty.len() {
                self.insert_entry(self.dirty[k]);
            }
        } else {
            self.rebuild_index();
        }
        self.dirty.truncate(frame.dirty_start);
        self.frames.truncate(token.frame_index);
        #[cfg(debug_assertions)]
        debug_assert!(
            self.index_matches_rebuild(),
            "restore left the hashcons index out of step with the node arena"
        );
    }

    /// Drop `local_id`'s entry, keyed by the content it holds right now. A
    /// repeat call is a no-op: the entry is already gone.
    #[inline]
    fn remove_entry(&mut self, local_id: L) {
        let fp = self.children_fingerprint(&self.nodes.get(local_id));
        self.index.remove(&StoredKey { fp, local_id });
    }

    #[inline]
    fn insert_entry(&mut self, local_id: L) {
        let fp = self.children_fingerprint(&self.nodes.get(local_id));
        self.index.insert(StoredKey { fp, local_id }, ());
    }

    /// See [`FixedArityCache::index_matches_rebuild`].
    #[cfg(debug_assertions)]
    fn index_matches_rebuild(&self) -> bool {
        let count = self.nodes.len().as_usize();
        if self.index.len() != count {
            return false;
        }
        let mut seen = vec![false; count];
        for (sk, ()) in self.index.iter() {
            let i = sk.local_id.as_usize();
            if i >= count
                || seen[i]
                || sk.fp != self.children_fingerprint(&self.nodes.get(sk.local_id))
            {
                return false;
            }
            seen[i] = true;
        }
        true
    }

    fn children_eq(&self, node: &VariableArityNode<G, O>, elems: &[C]) -> bool {
        let (start, end) = node.span();
        if end - start != elems.len() {
            return false;
        }
        (0..elems.len()).all(|i| self.children.get(start + i) == elems[i])
    }

    fn rebuild_index(&mut self) {
        self.index.clear();
        // `from_usize` needs no bound check here: `nodes` is indexed *by* `L`, so its own
        // capacity guard is the id bound (`IndexLike::max_nat()` of a dense id is its
        // `id_bound()`). Every position the arena can hold therefore has a local id. The
        // scans that DO need a check are the ones over a container indexed by an id's
        // *word* rather than the id — see `EGraph::node_ids`.
        let count = self.nodes.len().as_usize();
        for i in 0..count {
            let lid = L::from_usize(i);
            let n = self.nodes.get(lid);
            let fp = self.children_fingerprint(&n);
            self.index.insert(StoredKey { fp, local_id: lid }, ());
        }
    }

    fn fingerprint(&self, op: &O, elems: &[C]) -> Fingerprint {
        let mut h = rapidhash::fast::RapidHasher::default();
        op.hash(&mut h);
        elems.hash(&mut h);
        fold32(h.finish())
    }

    fn children_fingerprint(&self, node: &VariableArityNode<G, O>) -> Fingerprint {
        let mut h = rapidhash::fast::RapidHasher::default();
        node.op().hash(&mut h);
        let (start, end) = node.span();
        (end - start).hash(&mut h);
        for i in start..end {
            self.children.get(i).hash(&mut h);
        }
        fold32(h.finish())
    }
}

// ---------------------------------------------------------------------------
// LitCache<G, O, V, L, TRACK>
// ---------------------------------------------------------------------------

pub struct LitCache<G: DenseId, O: DenseId, V: DenseId, L: DenseId, const TRACK: bool = true> {
    nodes: VecI<LitNode<G, O, V>, L, TRACK>,
    index: hashbrown::HashMap<StoredKey<L>, (), PassthroughBuildHasher>,
    /// No `dirty` counterpart to the other two caches: a literal's content is
    /// its operator and its value, and nothing recanonizes either, so the only
    /// entries a restore has to drop are the suffix's.
    frames: Vec<CacheFrame>,
}

impl<G: DenseId + Hash, O: DenseId + Hash, V: DenseId + Hash, L: DenseId, const TRACK: bool> Default
    for LitCache<G, O, V, L, TRACK>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<G: DenseId + Hash, O: DenseId + Hash, V: DenseId + Hash, L: DenseId, const TRACK: bool>
    LitCache<G, O, V, L, TRACK>
{
    pub fn new() -> Self {
        Self {
            nodes: VecI::new(),
            index: hashbrown::HashMap::with_hasher(PassthroughBuildHasher),
            frames: Vec::new(),
        }
    }

    pub fn len(&self) -> L {
        self.nodes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.nodes.len() == <L as IndexLike>::min()
    }

    pub fn get(&self, id: L) -> LitNode<G, O, V> {
        self.nodes.get(id)
    }

    pub fn set(&mut self, id: L, node: LitNode<G, O, V>) {
        self.nodes.set(id, node);
    }

    pub fn probe(&self, op: O, lit: V) -> Option<G> {
        let fp = self.fingerprint(&op, &lit);
        self.index
            .raw_entry()
            .from_hash(spread(fp), |sk| {
                sk.fp == fp && {
                    let n = self.nodes.get(sk.local_id);
                    n.op() == op && n.lit == lit
                }
            })
            .map(|(sk, _)| self.nodes.get(sk.local_id).global_id())
    }

    pub fn insert(&mut self, global_id: G, op: O, lit: V) -> L {
        let node = LitNode::new(global_id, op, lit);
        let fp = self.fingerprint(&op, &lit);
        let lid = self.nodes.len();
        self.nodes.try_push(node).expect("push: within index word");
        self.index.insert(StoredKey { fp, local_id: lid }, ());
        lid
    }

    pub fn probe_or_insert(&mut self, global_id: G, op: O, lit: V) -> InsertResult<G, L> {
        if let Some(gid) = self.probe(op, lit) {
            return InsertResult::Hit { global_id: gid };
        }
        let lid = self.insert(global_id, op, lit);
        InsertResult::Inserted { local_id: lid }
    }

    pub fn mark(&mut self, shrink: ShrinkPolicy) -> CacheToken {
        let token = CacheToken {
            nodes: self
                .nodes
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
            history: None,
            frame_index: self.frames.len(),
        };
        self.frames.push(CacheFrame {
            saved_len: self.nodes.len().as_usize(),
            dirty_start: 0,
            dirty_overflow: false,
        });
        token
    }

    pub fn restore(&mut self, token: CacheToken) {
        let frame = *self
            .frames
            .get(token.frame_index)
            .expect("restore: token minted by this cache's own mark, and not already spent");
        let live_len = self.nodes.len().as_usize();
        let incremental = restore_incrementally(live_len - frame.saved_len, 0, frame.saved_len);

        if incremental {
            for i in frame.saved_len..live_len {
                let local_id = L::from_usize(i);
                let fp = fold32(self.nodes.get(local_id).content_hash());
                self.index.remove(&StoredKey { fp, local_id });
            }
        }

        self.nodes
            .try_restore(token.nodes)
            .expect("restore: token minted by this container's own mark");

        if !incremental {
            self.rebuild_index();
        }
        self.frames.truncate(token.frame_index);
        #[cfg(debug_assertions)]
        debug_assert!(
            self.index_matches_rebuild(),
            "restore left the hashcons index out of step with the node arena"
        );
    }

    /// See [`FixedArityCache::index_matches_rebuild`].
    #[cfg(debug_assertions)]
    fn index_matches_rebuild(&self) -> bool {
        let count = self.nodes.len().as_usize();
        if self.index.len() != count {
            return false;
        }
        let mut seen = vec![false; count];
        for (sk, ()) in self.index.iter() {
            let i = sk.local_id.as_usize();
            if i >= count || seen[i] || sk.fp != fold32(self.nodes.get(sk.local_id).content_hash())
            {
                return false;
            }
            seen[i] = true;
        }
        true
    }

    fn rebuild_index(&mut self) {
        self.index.clear();
        // `from_usize` needs no bound check here: `nodes` is indexed *by* `L`, so its own
        // capacity guard is the id bound (`IndexLike::max_nat()` of a dense id is its
        // `id_bound()`). Every position the arena can hold therefore has a local id. The
        // scans that DO need a check are the ones over a container indexed by an id's
        // *word* rather than the id — see `EGraph::node_ids`.
        let count = self.nodes.len().as_usize();
        for i in 0..count {
            let lid = L::from_usize(i);
            let n = self.nodes.get(lid);
            self.index.insert(
                StoredKey {
                    fp: fold32(n.content_hash()),
                    local_id: lid,
                },
                (),
            );
        }
    }

    fn fingerprint(&self, op: &O, lit: &V) -> Fingerprint {
        let mut h = rapidhash::fast::RapidHasher::default();
        op.hash(&mut h);
        lit.hash(&mut h);
        fold32(h.finish())
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::canon::{CCanon, MSetCanon, OrderedCanon, PlainCanon, SetCanon};
    use crate::id::{ENodeId, OpId};
    use crate::multiplicity::Multiplicity;
    use crate::nodes::{
        LitNodeId, LitValId, MSetNodeId, Plain0Id, Plain2Id, PlainNId, SPairNodeId, SetNodeId,
    };

    #[test]
    fn fixed_arity_probe_insert() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain0Id, 0, false>::new();
        let op = OpId::new(0);
        let r = c.probe_or_insert(ENodeId::new(0), op, []);
        assert!(matches!(r, InsertResult::Inserted { .. }));
        let r2 = c.probe_or_insert(ENodeId::new(99), op, []);
        assert!(matches!(r2, InsertResult::Hit { .. }));
    }

    #[test]
    fn fixed_arity_binary() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
        let op = OpId::new(0);
        let ch = [ENodeId::new(1), ENodeId::new(2)];
        let r = c.probe_or_insert(ENodeId::new(0), op, ch);
        assert!(matches!(r, InsertResult::Inserted { .. }));
        assert!(c.probe(&op, &ch).is_some());
        assert!(c.probe(&op, &[ENodeId::new(2), ENodeId::new(1)]).is_none());
    }

    /// A 32-bit fingerprint collision does not produce a wrong hash-cons hit.
    ///
    /// `probe` uses the fingerprint only to reach a candidate; the hit is
    /// declared by `n.op() == *op && n.children == *children` (fixed arity) and
    /// `n.op() == op && self.children_eq(&n, elems)` (variable arity). Without
    /// that confirmation a collision would return some *other* node's class,
    /// which `EGraph::add` would then treat as the term's class — an unsound
    /// merge of two structurally different terms. The test brute-forces a real
    /// collision (birthday: ~2^16 candidates expected) and checks both probes
    /// still answer with their own node.
    #[test]
    fn fingerprint_collision_is_disambiguated_by_content() {
        const LIMIT: u32 = 4_000_000;

        // -- fixed arity: `[G; 2]`, hashed element-wise --
        let mut fixed = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
        let op = OpId::new(0);
        let mut seen: std::collections::HashMap<Fingerprint, u32> =
            std::collections::HashMap::new();
        let (a, b) = (0..LIMIT)
            .find_map(|n| {
                let fp = fixed.fingerprint(&op, &[ENodeId::new(n), ENodeId::new(0)]);
                seen.insert(fp, n).map(|prev| (prev, n))
            })
            .expect("no 32-bit fingerprint collision within the search bound");
        assert_ne!(a, b);
        let (ca, cb) = (
            [ENodeId::new(a), ENodeId::new(0)],
            [ENodeId::new(b), ENodeId::new(0)],
        );
        // A genuine collision: same fingerprint, different children.
        assert_eq!(fixed.fingerprint(&op, &ca), fixed.fingerprint(&op, &cb));
        assert_ne!(ca, cb);

        let ga = ENodeId::new(LIMIT + 1);
        let gb = ENodeId::new(LIMIT + 2);
        assert!(matches!(
            fixed.probe_or_insert(ga, op, ca),
            InsertResult::Inserted { .. }
        ));
        // The colliding node must NOT be reported as already present.
        assert!(matches!(
            fixed.probe_or_insert(gb, op, cb),
            InsertResult::Inserted { .. }
        ));
        assert_eq!(fixed.probe(&op, &ca), Some(ga));
        assert_eq!(fixed.probe(&op, &cb), Some(gb));

        // -- variable arity: `&[C]`, hashed with a length prefix --
        let mut var = VariableArityCache::<ENodeId, OpId, ENodeId, PlainNId, false>::new();
        let mut seen: std::collections::HashMap<Fingerprint, u32> =
            std::collections::HashMap::new();
        let (a, b) = (0..LIMIT)
            .find_map(|n| {
                let fp = var.fingerprint(&op, &[ENodeId::new(n), ENodeId::new(0)]);
                seen.insert(fp, n).map(|prev| (prev, n))
            })
            .expect("no 32-bit fingerprint collision within the search bound");
        let (va, vb) = (
            [ENodeId::new(a), ENodeId::new(0)],
            [ENodeId::new(b), ENodeId::new(0)],
        );
        assert_eq!(var.fingerprint(&op, &va), var.fingerprint(&op, &vb));
        assert_ne!(va, vb);

        assert!(matches!(
            var.probe_or_insert(ga, op, &va),
            InsertResult::Inserted { .. }
        ));
        assert!(matches!(
            var.probe_or_insert(gb, op, &vb),
            InsertResult::Inserted { .. }
        ));
        assert_eq!(var.probe(op, &va), Some(ga));
        assert_eq!(var.probe(op, &vb), Some(gb));
    }

    #[test]
    fn variable_arity_probe_insert() {
        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, PlainNId, false>::new();
        let op = OpId::new(0);
        let ch = &[ENodeId::new(1), ENodeId::new(2), ENodeId::new(3)];
        let r = c.probe_or_insert(ENodeId::new(0), op, ch);
        assert!(matches!(r, InsertResult::Inserted { .. }));
        assert!(c.probe(op, ch).is_some());
    }

    #[test]
    fn lit_cache_probe_insert() {
        let mut c = LitCache::<ENodeId, OpId, LitValId, LitNodeId, false>::new();
        let op = OpId::new(0);
        let lit = LitValId::new(42);
        let r = c.probe_or_insert(ENodeId::new(0), op, lit);
        assert!(matches!(r, InsertResult::Inserted { .. }));
        assert!(c.probe(op, lit).is_some());
        assert!(c.probe(op, LitValId::new(99)).is_none());
    }

    // -- recanonize_node tests --

    fn id(n: u32) -> ENodeId {
        ENodeId::new(n)
    }

    #[test]
    fn recanonize_fixed_no_change() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(0), op, [id(1), id(2)]);
        let mut collisions = Vec::new();
        c.recanonize_node::<PlainCanon>(Plain2Id::new(0), |g| g, &mut collisions, &mut Vec::new());
        assert!(collisions.is_empty());
        // node unchanged
        assert!(c.probe(&op, &[id(1), id(2)]).is_some());
    }

    #[test]
    fn recanonize_fixed_plain_updates_children() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(0), op, [id(1), id(2)]);
        let mut collisions = Vec::new();
        // find: 2 → 1
        c.recanonize_node::<PlainCanon>(
            Plain2Id::new(0),
            |g| {
                if g == id(2) { id(1) } else { g }
            },
            &mut collisions,
            &mut Vec::new(),
        );
        assert!(collisions.is_empty());
        // old key gone, new key present
        assert!(c.probe(&op, &[id(1), id(2)]).is_none());
        assert!(c.probe(&op, &[id(1), id(1)]).is_some());
    }

    #[test]
    fn recanonize_fixed_collision() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2, false>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(10), op, [id(1), id(1)]); // node A: (op, [1,1]) → gid 10
        c.probe_or_insert(id(20), op, [id(1), id(2)]); // node B: (op, [1,2]) → gid 20
        let mut collisions = Vec::new();
        // find: 2 → 1, so node B becomes (op, [1,1]) → collision with A
        c.recanonize_node::<PlainCanon>(
            Plain2Id::new(1),
            |g| {
                if g == id(2) { id(1) } else { g }
            },
            &mut collisions,
            &mut Vec::new(),
        );
        assert_eq!(collisions.len(), 1);
        assert_eq!(collisions[0], (id(20), id(10)));
    }

    #[test]
    fn recanonize_c_sorts_pair() {
        let mut c = FixedArityCache::<ENodeId, OpId, SPairNodeId, 2, false>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(10), op, [id(1), id(5)]); // sorted: [1, 5]
        let mut collisions = Vec::new();
        // find: 1 → 9, so children become [9, 5], CCanon sorts to [5, 9]
        c.recanonize_node::<CCanon>(
            SPairNodeId::new(0),
            |g| {
                if g == id(1) { id(9) } else { g }
            },
            &mut collisions,
            &mut Vec::new(),
        );
        assert!(collisions.is_empty());
        assert!(c.probe(&op, &[id(5), id(9)]).is_some());
    }

    #[test]
    fn recanonize_var_ordered_no_change() {
        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, PlainNId, false>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(0), op, &[id(1), id(2), id(3)]);
        let mut buf = Vec::new();
        let mut collisions = Vec::new();
        c.recanonize_node::<OrderedCanon>(
            PlainNId::new(0),
            |g| g,
            &mut buf,
            &mut collisions,
            &mut Vec::new(),
            crate::canon::CanonMode::PLAIN,
        );
        assert!(collisions.is_empty());
    }

    #[test]
    fn recanonize_var_ordered_collision() {
        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, PlainNId, false>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(10), op, &[id(1), id(1)]);
        c.probe_or_insert(id(20), op, &[id(1), id(2)]);
        let mut buf = Vec::new();
        let mut collisions = Vec::new();
        c.recanonize_node::<OrderedCanon>(
            PlainNId::new(1),
            |g| {
                if g == id(2) { id(1) } else { g }
            },
            &mut buf,
            &mut collisions,
            &mut Vec::new(),
            crate::canon::CanonMode::PLAIN,
        );
        assert_eq!(collisions, vec![(id(20), id(10))]);
    }

    #[test]
    fn recanonize_aci_shrinks() {
        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, SetNodeId, false>::new();
        let op = OpId::new(0);
        // {1, 2, 3} sorted
        c.probe_or_insert(id(10), op, &[id(1), id(2), id(3)]);
        let mut buf = Vec::new();
        let mut collisions = Vec::new();
        // find: 2 → 1, 3 → 3 → after ACI canon: {1, 3} (deduped, sorted)
        c.recanonize_node::<SetCanon>(
            SetNodeId::new(0),
            |g| {
                if g == id(2) { id(1) } else { g }
            },
            &mut buf,
            &mut collisions,
            &mut Vec::new(),
            crate::canon::CanonMode::PLAIN,
        );
        assert!(collisions.is_empty());
        assert!(c.probe(op, &[id(1), id(3)]).is_some());
        // old 3-element key gone
        assert!(c.probe(op, &[id(1), id(2), id(3)]).is_none());
    }

    // -- mark / restore --

    const SHRINK: ShrinkPolicy = ShrinkPolicy::Never;

    /// Restore drops the entries of the nodes the scope added and keeps the
    /// rest, which is what makes a later `probe` answer for the restored graph.
    #[test]
    fn restore_drops_the_post_mark_suffix() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(10), op, [id(1), id(2)]);
        let token = c.mark(SHRINK);
        c.probe_or_insert(id(20), op, [id(3), id(4)]);
        assert!(c.probe(&op, &[id(3), id(4)]).is_some());

        c.restore(token);
        assert_eq!(c.len(), Plain2Id::new(1));
        assert_eq!(c.probe(&op, &[id(1), id(2)]), Some(id(10)));
        assert!(c.probe(&op, &[id(3), id(4)]).is_none());
        // The freed local id is reusable and does not collide with the entry
        // the discarded node left behind, because there is none.
        c.probe_or_insert(id(30), op, [id(5), id(6)]);
        assert_eq!(c.probe(&op, &[id(5), id(6)]), Some(id(30)));
    }

    /// A pre-mark node recanonized inside the scope is filed under its new key
    /// while the scope runs and back under the mark's key after restore.
    #[test]
    fn restore_rekeys_a_recanonized_pre_mark_node() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(10), op, [id(1), id(2)]);
        let token = c.mark(SHRINK);
        c.recanonize_node::<PlainCanon>(
            Plain2Id::new(0),
            |g| if g == id(2) { id(1) } else { g },
            &mut Vec::new(),
            &mut Vec::new(),
        );
        assert!(c.probe(&op, &[id(1), id(1)]).is_some());
        assert!(c.probe(&op, &[id(1), id(2)]).is_none());

        c.restore(token);
        assert_eq!(c.probe(&op, &[id(1), id(2)]), Some(id(10)));
        assert!(c.probe(&op, &[id(1), id(1)]).is_none());
    }

    /// Same for a variable-arity node, whose content lives in the shared child
    /// pool: the pool rolls back with the arena and the key follows it.
    #[test]
    fn restore_rekeys_a_recanonized_variable_arity_node() {
        let mut c = VariableArityCache::<ENodeId, OpId, ENodeId, SetNodeId>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(10), op, &[id(1), id(2), id(3)]);
        let token = c.mark(SHRINK);
        c.recanonize_node::<SetCanon>(
            SetNodeId::new(0),
            |g| if g == id(2) { id(1) } else { g },
            &mut Vec::new(),
            &mut Vec::new(),
            &mut Vec::new(),
            crate::canon::CanonMode::PLAIN,
        );
        assert!(c.probe(op, &[id(1), id(3)]).is_some());

        c.restore(token);
        assert_eq!(c.probe(op, &[id(1), id(2), id(3)]), Some(id(10)));
        assert!(c.probe(op, &[id(1), id(3)]).is_none());
    }

    /// Nested marks: restoring the outer token past an unrestored inner mark
    /// has to undo both the inner suffix and a pre-outer-mark node the inner
    /// scope re-keyed.
    #[test]
    fn restore_past_an_open_inner_mark() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(10), op, [id(1), id(2)]);
        let outer = c.mark(SHRINK);
        c.probe_or_insert(id(20), op, [id(3), id(4)]);
        let _inner = c.mark(SHRINK);
        c.probe_or_insert(id(30), op, [id(5), id(6)]);
        c.recanonize_node::<PlainCanon>(
            Plain2Id::new(0),
            |g| if g == id(2) { id(7) } else { g },
            &mut Vec::new(),
            &mut Vec::new(),
        );

        c.restore(outer);
        assert_eq!(c.len(), Plain2Id::new(1));
        assert_eq!(c.probe(&op, &[id(1), id(2)]), Some(id(10)));
        assert!(c.probe(&op, &[id(1), id(7)]).is_none());
        assert!(c.probe(&op, &[id(3), id(4)]).is_none());
        assert!(c.probe(&op, &[id(5), id(6)]).is_none());
    }

    /// A scope that adds more than a quarter of the arena takes the rebuild
    /// fallback, and lands on the same index the incremental path would build.
    #[test]
    fn restore_falls_back_to_rebuild_on_a_large_suffix() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(10), op, [id(1), id(2)]);
        let token = c.mark(SHRINK);
        for k in 0..10 {
            c.probe_or_insert(id(100 + k), op, [id(200 + k), id(0)]);
        }
        assert!(!restore_incrementally(10, 0, 1));

        c.restore(token);
        assert_eq!(c.len(), Plain2Id::new(1));
        assert_eq!(c.probe(&op, &[id(1), id(2)]), Some(id(10)));
        assert!(c.probe(&op, &[id(200), id(0)]).is_none());
    }

    /// The check `restore` asserts on rejects a stale key. Without this, an
    /// index that never diverges and a check that never looks are the same
    /// test result.
    #[cfg(debug_assertions)]
    #[test]
    fn index_check_rejects_a_stale_key() {
        let mut c = FixedArityCache::<ENodeId, OpId, Plain2Id, 2>::new();
        let op = OpId::new(0);
        c.probe_or_insert(id(10), op, [id(1), id(2)]);
        assert!(c.index_matches_rebuild());

        let local_id = Plain2Id::new(0);
        let fp = c.fingerprint(&op, &[id(1), id(2)]);
        c.index.remove(&StoredKey { fp, local_id });
        assert!(!c.index_matches_rebuild(), "a missing entry is a mismatch");
        c.index.insert(
            StoredKey {
                fp: fp ^ 1,
                local_id,
            },
            (),
        );
        assert!(!c.index_matches_rebuild(), "a stale key is a mismatch");
    }

    #[test]
    fn recanonize_ac_merges_mult() {
        type MSetChild = crate::containers::Pair<ENodeId, Multiplicity>;
        let pair = |g, m| crate::containers::Pair {
            a: g,
            b: Multiplicity(m),
        };
        let mut c = VariableArityCache::<ENodeId, OpId, MSetChild, MSetNodeId, false>::new();
        let op = OpId::new(0);
        let elems: &[MSetChild] = &[pair(id(1), 1), pair(id(2), 1), pair(id(3), 1)];
        c.probe_or_insert(id(10), op, elems);
        let mut buf = Vec::new();
        let mut collisions = Vec::new();
        c.recanonize_node::<MSetCanon>(
            MSetNodeId::new(0),
            |g| {
                if g == id(2) { id(1) } else { g }
            },
            &mut buf,
            &mut collisions,
            &mut Vec::new(),
            crate::canon::CanonMode::PLAIN,
        );
        assert!(collisions.is_empty());
        let expected: &[MSetChild] = &[pair(id(1), 2), pair(id(3), 1)];
        assert!(c.probe(op, expected).is_some());
    }
}