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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#[cfg(test)]
mod test {
    use crate::egraph::EGraph31;
    use crate::id::ENodeId;
    use crate::literal::NiraLitVal;
    use crate::union_find::{Justification, ProofBuf};

    #[test]
    fn long_proof_chain() {
        let mut eg = EGraph31::<NiraLitVal, false, true>::new();
        let int = eg.intern_sort("Int");

        let mut ops = Vec::new();
        for i in 0..20 {
            ops.push(eg.register_op0(&format!("c{i}"), int));
        }
        let nodes: Vec<ENodeId> = ops.iter().map(|&op| eg.add(op, &[])).collect();

        for i in 0..19 {
            eg.merge_justified(
                nodes[i],
                nodes[i + 1],
                Justification::Axiom {
                    axiom_id: crate::id::AxiomId::new(i as u16),
                },
            );
        }

        let mut buf = ProofBuf::new();
        eg.explain(nodes[0], nodes[19], &mut buf);
        eprintln!("\nc0 ≡ c19 ({} steps):", buf.steps.len());
        for (from, to, just) in &buf.steps {
            eprintln!("  {:?} ≡ {:?}  by {:?}", from, to, just);
        }
        assert_eq!(buf.steps.len(), 19);
    }

    #[test]
    fn layered_congruence_proof() {
        let mut eg = EGraph31::<NiraLitVal, false, true>::new();
        let int = eg.intern_sort("Int");
        let f = eg.register_op1("f", int, int);
        let g = eg.register_op2("g", int, int, int);

        // Layer 0: 8 constants
        let mut c = Vec::new();
        for i in 0..8 {
            let op = eg.register_op0(&format!("c{i}"), int);
            c.push(eg.add(op, &[]));
        }

        // Layer 1: f(ci)
        let fc: Vec<_> = c.iter().map(|&x| eg.add(f, &[x])).collect();

        // Layer 2: g(f(c2i), f(c2i+1))
        let gfc: Vec<_> = (0..4)
            .map(|i| eg.add(g, &[fc[2 * i], fc[2 * i + 1]]))
            .collect();

        // Merge pairs at layer 0: c0≡c2, c1≡c3, c4≡c6, c5≡c7
        eg.merge_justified(
            c[0],
            c[2],
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(0),
            },
        );
        eg.merge_justified(
            c[1],
            c[3],
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(1),
            },
        );
        eg.merge_justified(
            c[4],
            c[6],
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(2),
            },
        );
        eg.merge_justified(
            c[5],
            c[7],
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(3),
            },
        );
        eg.rebuild();

        // Layer 1 congruences
        assert_eq!(eg.find(fc[0]), eg.find(fc[2]));
        assert_eq!(eg.find(fc[1]), eg.find(fc[3]));
        // Layer 2 congruences
        assert_eq!(eg.find(gfc[0]), eg.find(gfc[1]));
        assert_eq!(eg.find(gfc[2]), eg.find(gfc[3]));
        // But left half ≢ right half yet
        assert_ne!(eg.find(gfc[0]), eg.find(gfc[2]));

        // Bridge: c0≡c4, c1≡c5 — cascades all the way up
        eg.merge_justified(
            c[0],
            c[4],
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(4),
            },
        );
        eg.merge_justified(
            c[1],
            c[5],
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(5),
            },
        );
        eg.rebuild();

        // Now everything collapses
        assert_eq!(eg.find(gfc[0]), eg.find(gfc[2]));

        // Print proofs at each layer
        let mut buf = ProofBuf::new();
        let proofs = [
            ("c0 ≡ c6 (layer 0, chain)", c[0], c[6]),
            ("f(c0) ≡ f(c2) (layer 1, congruence)", fc[0], fc[2]),
            ("f(c1) ≡ f(c7) (layer 1, cross)", fc[1], fc[7]),
            ("g(f(c0),f(c1)) ≡ g(f(c2),f(c3)) (layer 2)", gfc[0], gfc[1]),
            (
                "g(f(c0),f(c1)) ≡ g(f(c4),f(c5)) (layer 2, cross)",
                gfc[0],
                gfc[2],
            ),
            (
                "g(f(c0),f(c1)) ≡ g(f(c6),f(c7)) (layer 2, far)",
                gfc[0],
                gfc[3],
            ),
        ];
        for (label, a, b) in proofs {
            buf.clear();
            eg.explain(a, b, &mut buf);
            eprintln!("\n{label} ({} steps):", buf.steps.len());
            for (from, to, just) in &buf.steps {
                eprintln!("  {:?} ≡ {:?}  by {:?}", from, to, just);
            }
            assert!(!buf.steps.is_empty());
        }
    }
}

#[cfg(test)]
mod deep_proof_test {
    use crate::egraph::EGraph31;
    use crate::id::ENodeId;
    use crate::literal::NiraLitVal;
    use crate::union_find::{Justification, ProofBuf};

    /// Build a 3-layer e-graph, merge leaves, rebuild, extract deep proof.
    ///
    /// Layer 0: constants a, b, c, d
    /// Layer 1: f(a), f(b), f(c), f(d)
    /// Layer 2: g(f(a), f(b)), g(f(c), f(d))
    ///
    /// Merge a≡c (axiom 1), b≡d (axiom 2), rebuild.
    /// This cascades: f(a)≡f(c), f(b)≡f(d), then g(f(a),f(b))≡g(f(c),f(d)).
    /// Extract deep proof of g(f(a),f(b)) ≡ g(f(c),f(d)).
    #[test]
    fn deep_proof_layered() {
        let mut eg = EGraph31::<NiraLitVal, false, true>::new();
        let int = eg.intern_sort("Int");
        let f = eg.register_op1("f", int, int);
        let g = eg.register_op2("g", int, int, int);

        // Layer 0
        let op_a = eg.register_op0("a", int);
        let op_b = eg.register_op0("b", int);
        let op_c = eg.register_op0("c", int);
        let op_d = eg.register_op0("d", int);
        let a = eg.add(op_a, &[]);
        let b = eg.add(op_b, &[]);
        let c = eg.add(op_c, &[]);
        let d = eg.add(op_d, &[]);

        // Layer 1
        let fa = eg.add(f, &[a]);
        let fb = eg.add(f, &[b]);
        let fc = eg.add(f, &[c]);
        let fd = eg.add(f, &[d]);

        // Layer 2
        let gab = eg.add(g, &[fa, fb]);
        let gcd = eg.add(g, &[fc, fd]);

        assert_ne!(eg.find(gab), eg.find(gcd));

        // Merge leaves
        eg.merge_justified(
            a,
            c,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(1),
            },
        );
        eg.merge_justified(
            b,
            d,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(2),
            },
        );
        eg.rebuild();

        // Verify cascading congruence
        assert_eq!(eg.find(fa), eg.find(fc));
        assert_eq!(eg.find(fb), eg.find(fd));
        assert_eq!(eg.find(gab), eg.find(gcd));

        // Extract deep proof
        let mut buf = ProofBuf::new();
        assert!(eg.explain_deep(gab, gcd, &mut buf));

        // Print proof
        let name = |id: ENodeId| -> String { eg.node_op_name(id).to_string() };
        eprintln!("\n=== Deep proof: g(f(a),f(b)) ≡ g(f(c),f(d)) ===");
        eprintln!("{} steps:", buf.steps.len());
        for (i, (from, to, just)) in buf.steps.iter().enumerate() {
            let reason = match just {
                Justification::Axiom { axiom_id } => format!("axiom #{axiom_id}"),
                Justification::Congruence { node_a, node_b } => {
                    let na = *node_a;
                    let nb = *node_b;
                    format!("congruence({}, {})", name(na), name(nb))
                }
                Justification::Rewrite { rule_id, .. } => format!("rewrite #{rule_id}"),
                Justification::ACSuperposition { .. }
                | Justification::ACInterReduction { .. }
                | Justification::ACAxiomCP { .. }
                | Justification::Cancellative { .. }
                | Justification::InverseCancel { .. } => "ac-algebraic".to_string(),
                Justification::Filler => unreachable!("filler is never a real proof step"),
            };
            eprintln!("  [{i}] {} ≡ {}  by {reason}", name(*from), name(*to));
        }

        // Must contain at least one Congruence step (the g-level merge)
        assert!(
            buf.steps
                .iter()
                .any(|(_, _, j)| matches!(j, Justification::Congruence { .. }))
        );
        // Must contain axiom steps (the leaf merges, expanded from congruence children)
        assert!(
            buf.steps
                .iter()
                .any(|(_, _, j)| matches!(j, Justification::Axiom { .. }))
        );

        eprintln!("\n✓ Deep proof extracted successfully");
    }
}

#[cfg(test)]
mod kind_proof_tests {
    use crate::egraph::EGraph31;
    use crate::id::{ENodeId, OpId};
    use crate::literal::NiraLitVal;
    use crate::union_find::{Justification, ProofBuf};

    struct Th {
        x: OpId,
        y: OpId,
        z: OpId,
        w: OpId,
        f: OpId,
        g: OpId,
        eq: OpId,   // C
        sub: OpId,  // A
        plus: OpId, // AC
        and: OpId,  // ACI
    }

    fn setup() -> (EGraph31<NiraLitVal, false, true>, Th) {
        let mut eg = EGraph31::new();
        let int = eg.intern_sort("Int");
        let th = Th {
            x: eg.register_op0("x", int),
            y: eg.register_op0("y", int),
            z: eg.register_op0("z", int),
            w: eg.register_op0("w", int),
            f: eg.register_op1("f", int, int),
            g: eg.register_op2("g", int, int, int),
            eq: eg.register_c("eq", [int, int], int),
            sub: eg.register_a("sub", int, int, crate::registry::AssocDir::Left),
            plus: eg.register_mset("plus", int, int),
            and: eg.register_set("and", int, int),
        };
        (eg, th)
    }

    fn has_congruence(buf: &ProofBuf<ENodeId>) -> bool {
        buf.steps
            .iter()
            .any(|(_, _, j)| matches!(j, Justification::Congruence { .. }))
    }

    fn has_axiom(buf: &ProofBuf<ENodeId>, id: u32) -> bool {
        buf.steps.iter().any(|(_, _, j)| {
            *j == Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(id as u16),
            }
        })
    }

    fn print_proof(label: &str, buf: &ProofBuf<ENodeId>, eg: &EGraph31<NiraLitVal, false, true>) {
        eprintln!("\n--- {label} ({} steps) ---", buf.steps.len());
        for (i, (from, to, just)) in buf.steps.iter().enumerate() {
            let reason = match just {
                Justification::Axiom { axiom_id } => format!("axiom #{axiom_id}"),
                Justification::Congruence { node_a, node_b } => format!(
                    "congruence({}, {})",
                    eg.node_op_name(*node_a),
                    eg.node_op_name(*node_b)
                ),
                Justification::Rewrite { rule_id, .. } => format!("rewrite #{rule_id}"),
                Justification::ACSuperposition { .. }
                | Justification::ACInterReduction { .. }
                | Justification::ACAxiomCP { .. }
                | Justification::Cancellative { .. }
                | Justification::InverseCancel { .. } => "ac-algebraic".to_string(),
                Justification::Filler => unreachable!("filler is never a real proof step"),
            };
            eprintln!(
                "  [{i}] {} ≡ {}  by {reason}",
                eg.node_op_name(*from),
                eg.node_op_name(*to)
            );
        }
    }

    // -- Plain1: f(x) ≡ f(y) after merge(x,y) --

    #[test]
    fn proof_plain1() {
        let (ref mut eg, th) = setup();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let fx = eg.add(th.f, &[x]);
        let fy = eg.add(th.f, &[y]);
        eg.merge_justified(
            x,
            y,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(10),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(fx), eg.find(fy));

        let mut buf = ProofBuf::new();
        eg.explain_deep(fx, fy, &mut buf);
        print_proof("Plain1: f(x)≡f(y)", &buf, eg);
        assert!(has_congruence(&buf));
        assert!(has_axiom(&buf, 10));
    }

    // -- Plain2: g(x,y) ≡ g(z,w) after merge(x,z), merge(y,w) --

    #[test]
    fn proof_plain2() {
        let (ref mut eg, th) = setup();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        let w = eg.add(th.w, &[]);
        let gxy = eg.add(th.g, &[x, y]);
        let gzw = eg.add(th.g, &[z, w]);
        eg.merge_justified(
            x,
            z,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(20),
            },
        );
        eg.merge_justified(
            y,
            w,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(21),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(gxy), eg.find(gzw));

        let mut buf = ProofBuf::new();
        eg.explain_deep(gxy, gzw, &mut buf);
        print_proof("Plain2: g(x,y)≡g(z,w)", &buf, eg);
        assert!(has_congruence(&buf));
        assert!(has_axiom(&buf, 20));
        assert!(has_axiom(&buf, 21));
    }

    // -- C: eq(x,y) ≡ eq(z,w) after merge(x,z), merge(y,w) --
    // Children are sorted, so proof must match by repr not position.

    #[test]
    fn proof_commutative() {
        let (ref mut eg, th) = setup();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        let w = eg.add(th.w, &[]);
        let eq_xy = eg.add(th.eq, &[x, y]);
        let eq_zw = eg.add(th.eq, &[z, w]);
        eg.merge_justified(
            x,
            z,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(30),
            },
        );
        eg.merge_justified(
            y,
            w,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(31),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(eq_xy), eg.find(eq_zw));

        let mut buf = ProofBuf::new();
        eg.explain_deep(eq_xy, eq_zw, &mut buf);
        print_proof("C: eq(x,y)≡eq(z,w)", &buf, eg);
        assert!(has_congruence(&buf));
        assert!(has_axiom(&buf, 30));
        assert!(has_axiom(&buf, 31));
    }

    // -- A: sub(x,y) ≡ sub(z,w) after merge(x,z), merge(y,w) --

    #[test]
    fn proof_associative() {
        let (ref mut eg, th) = setup();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        let w = eg.add(th.w, &[]);
        let sxy = eg.add(th.sub, &[x, y]);
        let szw = eg.add(th.sub, &[z, w]);
        eg.merge_justified(
            x,
            z,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(40),
            },
        );
        eg.merge_justified(
            y,
            w,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(41),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(sxy), eg.find(szw));

        let mut buf = ProofBuf::new();
        eg.explain_deep(sxy, szw, &mut buf);
        print_proof("A: sub(x,y)≡sub(z,w)", &buf, eg);
        assert!(has_congruence(&buf));
        assert!(has_axiom(&buf, 40));
        assert!(has_axiom(&buf, 41));
    }

    // -- AC: plus(x,y) ≡ plus(z,w) after merge(x,z), merge(y,w) --

    #[test]
    fn proof_ac() {
        let (ref mut eg, th) = setup();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        let w = eg.add(th.w, &[]);
        let pxy = eg.add(th.plus, &[x, y]);
        let pzw = eg.add(th.plus, &[z, w]);
        eg.merge_justified(
            x,
            z,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(50),
            },
        );
        eg.merge_justified(
            y,
            w,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(51),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(pxy), eg.find(pzw));

        let mut buf = ProofBuf::new();
        eg.explain_deep(pxy, pzw, &mut buf);
        print_proof("AC: plus(x,y)≡plus(z,w)", &buf, eg);
        assert!(has_congruence(&buf));
        assert!(has_axiom(&buf, 50));
        assert!(has_axiom(&buf, 51));
    }

    // -- ACI: and(x,y) ≡ and(z,w) after merge(x,z), merge(y,w) --

    #[test]
    fn proof_aci() {
        let (ref mut eg, th) = setup();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        let w = eg.add(th.w, &[]);
        let axy = eg.add(th.and, &[x, y]);
        let azw = eg.add(th.and, &[z, w]);
        eg.merge_justified(
            x,
            z,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(60),
            },
        );
        eg.merge_justified(
            y,
            w,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(61),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(axy), eg.find(azw));

        let mut buf = ProofBuf::new();
        eg.explain_deep(axy, azw, &mut buf);
        print_proof("ACI: and(x,y)≡and(z,w)", &buf, eg);
        assert!(has_congruence(&buf));
        assert!(has_axiom(&buf, 60));
        assert!(has_axiom(&buf, 61));
    }

    // -- End-to-end: all kinds in one graph --

    #[test]
    fn proof_all_kinds() {
        let (ref mut eg, th) = setup();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        let w = eg.add(th.w, &[]);

        // Build nodes of every kind using x,y
        let fx = eg.add(th.f, &[x]); // Plain1
        let gxy = eg.add(th.g, &[x, y]); // Plain2
        let eq_xy = eg.add(th.eq, &[x, y]); // C
        let sxy = eg.add(th.sub, &[x, y]); // A
        let pxy = eg.add(th.plus, &[x, y]); // AC
        let axy = eg.add(th.and, &[x, y]); // ACI

        // Build matching nodes using z,w
        let fz = eg.add(th.f, &[z]);
        let gzw = eg.add(th.g, &[z, w]);
        let eq_zw = eg.add(th.eq, &[z, w]);
        let szw = eg.add(th.sub, &[z, w]);
        let pzw = eg.add(th.plus, &[z, w]);
        let azw = eg.add(th.and, &[z, w]);

        // Merge leaves
        eg.merge_justified(
            x,
            z,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(100),
            },
        );
        eg.merge_justified(
            y,
            w,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(101),
            },
        );
        eg.rebuild();

        // Verify all congruences
        assert_eq!(eg.find(fx), eg.find(fz));
        assert_eq!(eg.find(gxy), eg.find(gzw));
        assert_eq!(eg.find(eq_xy), eg.find(eq_zw));
        assert_eq!(eg.find(sxy), eg.find(szw));
        assert_eq!(eg.find(pxy), eg.find(pzw));
        assert_eq!(eg.find(axy), eg.find(azw));

        // Extract and print deep proofs for each
        let mut buf = ProofBuf::new();
        let cases: &[(&str, ENodeId, ENodeId)] = &[
            ("Plain1 f", fx, fz),
            ("Plain2 g", gxy, gzw),
            ("C eq", eq_xy, eq_zw),
            ("A sub", sxy, szw),
            ("AC plus", pxy, pzw),
            ("ACI and", axy, azw),
        ];
        for &(label, a, b) in cases {
            buf.clear();
            eg.explain_deep(a, b, &mut buf);
            print_proof(label, &buf, eg);
            assert!(has_congruence(&buf), "{label}: missing congruence step");
            assert!(
                has_axiom(&buf, 100) || has_axiom(&buf, 101),
                "{label}: missing axiom step"
            );
        }
        eprintln!("\n✓ All kinds proof extraction passed");
    }
}

#[cfg(test)]
mod stress_proof_test {
    use crate::egraph::EGraph31;
    use crate::id::{ENodeId, OpId};
    use crate::literal::NiraLitVal;
    use crate::union_find::{Justification, ProofBuf};
    use std::collections::HashSet;

    struct Ops {
        f: OpId,   // Plain1
        g: OpId,   // Plain2
        eq: OpId,  // C
        sub: OpId, // A
        add: OpId, // AC
        and: OpId, // ACI
    }

    fn build_stress(seed: u64, n_leaves: usize, n_layers: usize, n_merges: usize) {
        let mut eg = EGraph31::<NiraLitVal, false, true>::new();
        let int = eg.intern_sort("Int");
        let ops = Ops {
            f: eg.register_op1("f", int, int),
            g: eg.register_op2("g", int, int, int),
            eq: eg.register_c("eq", [int, int], int),
            sub: eg.register_a("sub", int, int, crate::registry::AssocDir::Left),
            add: eg.register_mset("add", int, int),
            and: eg.register_set("and", int, int),
        };

        // Simple LCG for deterministic pseudo-random
        let mut rng = seed;
        let mut next = || -> usize {
            rng = rng
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (rng >> 33) as usize
        };

        // Layer 0: leaves
        let mut prev_layer: Vec<ENodeId> = Vec::new();
        for i in 0..n_leaves {
            let op = eg.register_op0(&format!("c{i}"), int);
            prev_layer.push(eg.add(op, &[]));
        }

        // Build layers — create pairs of nodes with same op, different children
        // to maximize congruence opportunities after leaf merges
        for _layer in 0..n_layers {
            let n = prev_layer.len();
            let mut new_layer: Vec<ENodeId> = Vec::new();
            // For each op kind, build multiple nodes over different children
            let ops_list: &[(
                &dyn Fn(&mut EGraph31<NiraLitVal, false, true>, ENodeId, ENodeId) -> ENodeId,
                usize,
            )] = &[
                (
                    &|eg: &mut EGraph31<NiraLitVal, false, true>, a, _| eg.add(ops.f, &[a]),
                    1,
                ),
                (&|eg, a, b| eg.add(ops.g, &[a, b]), 2),
                (&|eg, a, b| eg.add(ops.eq, &[a, b]), 2),
                (&|eg, a, b| eg.add(ops.sub, &[a, b]), 2),
                (&|eg, a, b| eg.add(ops.add, &[a, b]), 2),
                (&|eg, a, b| eg.add(ops.and, &[a, b]), 2),
            ];
            for &(builder, _arity) in ops_list {
                for _ in 0..(n / 3).max(2) {
                    let a = prev_layer[next() % n];
                    let b = prev_layer[next() % n];
                    new_layer.push(builder(&mut eg, a, b));
                }
            }
            prev_layer = new_layer;
        }

        let all_nodes: usize = eg.node_count();

        // Random merges on leaves with axiom justifications
        let mut axioms_issued: HashSet<crate::id::AxiomId> = HashSet::new();
        for i in 0..n_merges {
            let a_idx = next() % n_leaves;
            let b_idx = next() % n_leaves;
            if a_idx == b_idx {
                continue;
            }
            let a = ENodeId::new(a_idx as u32);
            let b = ENodeId::new(b_idx as u32);
            let axiom_id = crate::id::AxiomId::new(i as u16);
            if eg
                .merge_justified(a, b, Justification::Axiom { axiom_id })
                .is_some()
            {
                axioms_issued.insert(axiom_id);
            }
        }
        eg.rebuild();

        // Find pairs that became equivalent and extract deep proofs
        let mut buf = ProofBuf::new();
        let mut proofs_extracted = 0;
        let top = &prev_layer;
        for i in 0..top.len().min(50) {
            for j in (i + 1)..top.len().min(50) {
                if eg.find(top[i]) == eg.find(top[j]) && top[i] != top[j] {
                    buf.clear();
                    let ok = eg.explain_deep(top[i], top[j], &mut buf);
                    assert!(ok, "explain_deep failed for equivalent nodes");
                    assert!(!buf.steps.is_empty(), "empty proof for equivalent nodes");

                    // Validate: every axiom step must be one we issued
                    for (_, _, just) in &buf.steps {
                        if let Justification::Axiom { axiom_id } = just {
                            assert!(
                                axioms_issued.contains(axiom_id),
                                "proof references axiom #{axiom_id} which was never issued"
                            );
                        }
                    }

                    // Validate: every congruence step references valid node ids
                    for (_, _, just) in &buf.steps {
                        if let Justification::Congruence { node_a, node_b } = just {
                            assert!(
                                node_a.raw() < all_nodes as u32,
                                "congruence references invalid node_a"
                            );
                            assert!(
                                node_b.raw() < all_nodes as u32,
                                "congruence references invalid node_b"
                            );
                        }
                    }

                    proofs_extracted += 1;
                }
            }
        }

        eprintln!(
            "  seed={seed} leaves={n_leaves} layers={n_layers} merges={n_merges} \
             nodes={all_nodes} axioms={} proofs_extracted={proofs_extracted}",
            axioms_issued.len()
        );
    }

    /// Rebuild a stress structure with AC completion and reduced-basis reports enabled.
    /// This supports the ignored divergence reproducer below.
    fn build_completion_stress_with_reports(
        seed: u64,
        n_leaves: usize,
        n_layers: usize,
        n_merges: usize,
    ) {
        let mut eg = EGraph31::<NiraLitVal, false, true>::new();
        eg.set_cc(true);
        // Always run reduced-basis checks so each completion round is validated.
        eg.set_basis_checks(true);
        let int = eg.intern_sort("Int");
        let ops = Ops {
            f: eg.register_op1("f", int, int),
            g: eg.register_op2("g", int, int, int),
            eq: eg.register_c("eq", [int, int], int),
            sub: eg.register_a("sub", int, int, crate::registry::AssocDir::Left),
            add: eg.register_mset("add", int, int),
            and: eg.register_set("and", int, int),
        };

        let mut rng = seed;
        let mut next = || -> usize {
            rng = rng
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (rng >> 33) as usize
        };

        let mut prev_layer: Vec<ENodeId> = Vec::new();
        for i in 0..n_leaves {
            let op = eg.register_op0(&format!("c{i}"), int);
            prev_layer.push(eg.add(op, &[]));
        }

        for _layer in 0..n_layers {
            let n = prev_layer.len();
            let mut new_layer: Vec<ENodeId> = Vec::new();
            let ops_list: &[(
                &dyn Fn(&mut EGraph31<NiraLitVal, false, true>, ENodeId, ENodeId) -> ENodeId,
                usize,
            )] = &[
                (
                    &|eg: &mut EGraph31<NiraLitVal, false, true>, a, _| eg.add(ops.f, &[a]),
                    1,
                ),
                (&|eg, a, b| eg.add(ops.g, &[a, b]), 2),
                (&|eg, a, b| eg.add(ops.eq, &[a, b]), 2),
                (&|eg, a, b| eg.add(ops.sub, &[a, b]), 2),
                (&|eg, a, b| eg.add(ops.add, &[a, b]), 2),
                (&|eg, a, b| eg.add(ops.and, &[a, b]), 2),
            ];
            for &(builder, _arity) in ops_list {
                for _ in 0..(n / 3).max(2) {
                    let a = prev_layer[next() % n];
                    let b = prev_layer[next() % n];
                    new_layer.push(builder(&mut eg, a, b));
                }
            }
            prev_layer = new_layer;
        }

        for i in 0..n_merges {
            let a_idx = next() % n_leaves;
            let b_idx = next() % n_leaves;
            if a_idx == b_idx {
                continue;
            }
            let a = ENodeId::new(a_idx as u32);
            let b = ENodeId::new(b_idx as u32);
            let axiom_id = crate::id::AxiomId::new(i as u16);
            eg.merge_justified(a, b, Justification::Axiom { axiom_id });
        }
        eprintln!("[completion] seed={seed} starting rebuild");
        eg.rebuild();
        eg.cc_basis_dump("final");
        eprintln!(
            "[completion] seed={seed} final node_count={}",
            eg.node_count()
        );
    }

    /// Run the same completion stress case without reports and return its node count.
    /// On divergence, the rebuild backstop panics.
    fn build_completion_stress(
        seed: u64,
        n_leaves: usize,
        n_layers: usize,
        n_merges: usize,
    ) -> usize {
        let mut eg = EGraph31::<NiraLitVal, false, true>::new();
        eg.set_cc(true);
        let int = eg.intern_sort("Int");
        let ops = Ops {
            f: eg.register_op1("f", int, int),
            g: eg.register_op2("g", int, int, int),
            eq: eg.register_c("eq", [int, int], int),
            sub: eg.register_a("sub", int, int, crate::registry::AssocDir::Left),
            add: eg.register_mset("add", int, int),
            and: eg.register_set("and", int, int),
        };
        let mut rng = seed;
        let mut next = || -> usize {
            rng = rng
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (rng >> 33) as usize
        };
        let mut prev_layer: Vec<ENodeId> = Vec::new();
        for i in 0..n_leaves {
            let op = eg.register_op0(&format!("c{i}"), int);
            prev_layer.push(eg.add(op, &[]));
        }
        for _layer in 0..n_layers {
            let n = prev_layer.len();
            let mut new_layer: Vec<ENodeId> = Vec::new();
            let ops_list: &[&dyn Fn(
                &mut EGraph31<NiraLitVal, false, true>,
                ENodeId,
                ENodeId,
            ) -> ENodeId] = &[
                &|eg, a, _| eg.add(ops.f, &[a]),
                &|eg, a, b| eg.add(ops.g, &[a, b]),
                &|eg, a, b| eg.add(ops.eq, &[a, b]),
                &|eg, a, b| eg.add(ops.sub, &[a, b]),
                &|eg, a, b| eg.add(ops.add, &[a, b]),
                &|eg, a, b| eg.add(ops.and, &[a, b]),
            ];
            for builder in ops_list {
                for _ in 0..(n / 3).max(2) {
                    let a = prev_layer[next() % n];
                    let b = prev_layer[next() % n];
                    new_layer.push(builder(&mut eg, a, b));
                }
            }
            prev_layer = new_layer;
        }
        for i in 0..n_merges {
            let a_idx = next() % n_leaves;
            let b_idx = next() % n_leaves;
            if a_idx == b_idx {
                continue;
            }
            let a = ENodeId::new(a_idx as u32);
            let b = ENodeId::new(b_idx as u32);
            let axiom_id = crate::id::AxiomId::new(i as u16);
            eg.merge_justified(a, b, Justification::Axiom { axiom_id });
        }
        eg.rebuild();
        eg.node_count()
    }

    #[test]
    #[ignore = "known completion-divergence reproducer; slow"]
    fn completion_divergence_reproducer() {
        build_completion_stress_with_reports(42, 30, 4, 20);
    }

    /// Check a grid of completion stress cases and report convergence versus the
    /// rebuild backstop. Basis reports stay off so only the verdict is collected.
    #[test]
    #[ignore = "completion convergence matrix; slow"]
    fn completion_convergence_matrix() {
        // (seed, leaves, layers, merges)
        let grid: &[(u64, usize, usize, usize)] = &[
            (1, 6, 2, 4),
            (2, 8, 2, 6),
            (7, 12, 2, 5),
            (3, 12, 3, 8),
            (4, 16, 3, 10),
            (5, 20, 3, 12),
            (8, 24, 3, 14),
            (6, 30, 4, 20),
            (123, 30, 4, 20),
            (999, 40, 3, 30),
        ];
        // Seed 42 at (30, 4, 20) is the known diverging input. It is covered by
        // `completion_divergence_reproducer` because reaching the node backstop
        // is slow. Divergence is input-specific, not size-specific; see the
        // completion specification section 3.3.
        for &(seed, leaves, layers, merges) in grid {
            let res =
                std::panic::catch_unwind(|| build_completion_stress(seed, leaves, layers, merges));
            match res {
                Ok(nodes) => eprintln!(
                    "[matrix] seed={seed} leaves={leaves} layers={layers} merges={merges}: CONVERGED, {nodes} nodes"
                ),
                Err(_) => eprintln!(
                    "[matrix] seed={seed} leaves={leaves} layers={layers} merges={merges}: DIVERGED (hit backstop)"
                ),
            }
        }
    }

    #[test]
    #[ignore = "slow reduced-basis report on a converging completion case"]
    fn completion_reduced_basis_smoke() {
        build_completion_stress_with_reports(7, 12, 2, 5);
    }

    #[test]
    fn stress_small() {
        for seed in 0..20 {
            build_stress(seed, 8, 2, 6);
        }
        eprintln!("✓ stress_small passed");
    }

    #[test]
    fn stress_medium() {
        for seed in 0..10 {
            build_stress(seed, 16, 3, 12);
        }
        eprintln!("✓ stress_medium passed");
    }

    #[test]
    fn stress_large() {
        build_stress(42, 30, 4, 20);
        build_stress(123, 30, 4, 20);
        build_stress(999, 40, 3, 30);
        eprintln!("✓ stress_large passed");
    }
}

#[cfg(test)]
mod aci_deep_proof_test {
    use crate::egraph::EGraph31;
    use crate::id::ENodeId;
    use crate::literal::NiraLitVal;
    use crate::union_find::{Justification, ProofBuf};

    /// Two ACI (and) nodes with n children each:
    /// - k children shared
    /// - n-k children distinct per side
    ///
    /// Merge the n-k distinct pairs, rebuild, verify equivalence, extract deep proof.
    fn aci_overlap(n: usize, k: usize) {
        assert!(k <= n);
        let mut eg = EGraph31::<NiraLitVal, false, true>::new();
        let int = eg.intern_sort("Int");
        let and = eg.register_set("and", int, int);

        // Shared children: s0..s(k-1)
        let mut shared = Vec::new();
        for i in 0..k {
            let op = eg.register_op0(&format!("s{i}"), int);
            shared.push(eg.add(op, &[]));
        }

        // Distinct children for left: a0..a(n-k-1)
        let mut left_only = Vec::new();
        for i in 0..(n - k) {
            let op = eg.register_op0(&format!("a{i}"), int);
            left_only.push(eg.add(op, &[]));
        }

        // Distinct children for right: b0..b(n-k-1)
        let mut right_only = Vec::new();
        for i in 0..(n - k) {
            let op = eg.register_op0(&format!("b{i}"), int);
            right_only.push(eg.add(op, &[]));
        }

        // Build and(shared..., left_only...)
        let mut left_children: Vec<ENodeId> = Vec::new();
        left_children.extend_from_slice(&shared);
        left_children.extend_from_slice(&left_only);
        let left = eg.add(and, &left_children);

        // Build and(shared..., right_only...)
        let mut right_children: Vec<ENodeId> = Vec::new();
        right_children.extend_from_slice(&shared);
        right_children.extend_from_slice(&right_only);
        let right = eg.add(and, &right_children);

        assert_ne!(eg.find(left), eg.find(right));

        // Merge each distinct pair: a_i ≡ b_i
        for i in 0..(n - k) {
            eg.merge_justified(
                left_only[i],
                right_only[i],
                Justification::Axiom {
                    axiom_id: crate::id::AxiomId::new(i as u16),
                },
            );
        }
        eg.rebuild();

        assert_eq!(
            eg.find(left),
            eg.find(right),
            "and-nodes should be equivalent after merging distinct children (n={n}, k={k})"
        );

        // Extract deep proof
        let mut buf = ProofBuf::new();
        assert!(eg.explain_deep(left, right, &mut buf));

        eprintln!(
            "\n--- ACI overlap n={n} k={k} ({} steps) ---",
            buf.steps.len()
        );
        for (i, (from, to, just)) in buf.steps.iter().enumerate() {
            let reason = match just {
                Justification::Axiom { axiom_id } => format!("axiom #{axiom_id}"),
                Justification::Congruence { node_a, node_b } => format!(
                    "congruence({}, {})",
                    eg.node_op_name(*node_a),
                    eg.node_op_name(*node_b)
                ),
                Justification::Rewrite { rule_id, .. } => format!("rewrite #{rule_id}"),
                Justification::ACSuperposition { .. }
                | Justification::ACInterReduction { .. }
                | Justification::ACAxiomCP { .. }
                | Justification::Cancellative { .. }
                | Justification::InverseCancel { .. } => "ac-algebraic".to_string(),
                Justification::Filler => unreachable!("filler is never a real proof step"),
            };
            eprintln!(
                "  [{i}] {} ≡ {}  by {reason}",
                eg.node_op_name(*from),
                eg.node_op_name(*to)
            );
        }

        // Validate: must have congruence + all axioms we issued
        assert!(
            buf.steps
                .iter()
                .any(|(_, _, j)| matches!(j, Justification::Congruence { .. })),
            "missing congruence step"
        );
        for i in 0..(n - k) {
            assert!(
                buf.steps.iter().any(|(_, _, j)| *j
                    == Justification::Axiom {
                        axiom_id: crate::id::AxiomId::new(i as u16)
                    }),
                "missing axiom #{i}"
            );
        }
    }

    #[test]
    fn aci_no_overlap() {
        aci_overlap(4, 0);
    }

    #[test]
    fn aci_half_overlap() {
        aci_overlap(6, 3);
    }

    #[test]
    fn aci_mostly_shared() {
        aci_overlap(8, 6);
    }

    #[test]
    fn aci_deep() {
        aci_overlap(20, 10);
    }

    #[test]
    fn aci_wide() {
        aci_overlap(50, 25);
    }
}

#[cfg(test)]
mod bench_overhead {
    use crate::egraph::EGraph31;
    use crate::id::{ENodeId, OpId};
    use crate::literal::NiraLitVal;
    use crate::union_find::Justification;
    use std::time::Instant;

    fn build_and_rebuild<const TRACK: bool, const PROOFS: bool>(
        n_leaves: usize,
        n_layers: usize,
        n_merges: usize,
    ) -> std::time::Duration {
        let mut eg = EGraph31::<NiraLitVal, TRACK, PROOFS>::new();
        let int = eg.intern_sort("Int");
        let f = eg.register_op1("f", int, int);
        let g = eg.register_op2("g", int, int, int);
        let eq = eg.register_c("eq", [int, int], int);
        let add = eg.register_mset("add", int, int);
        let and = eg.register_set("and", int, int);

        let mut rng: u64 = 12345;
        let mut next = || -> usize {
            rng = rng
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (rng >> 33) as usize
        };

        // Leaves
        let mut prev: Vec<ENodeId> = Vec::new();
        for i in 0..n_leaves {
            let op = eg.register_op0(&format!("c{i}"), int);
            prev.push(eg.add(op, &[]));
        }

        // Layers
        for _ in 0..n_layers {
            let n = prev.len();
            let mut layer = Vec::new();
            let ops: [OpId; 5] = [f, g, eq, add, and];
            for _ in 0..n {
                let a = prev[next() % n];
                let b = prev[next() % n];
                let op = ops[next() % 5];
                if op == f {
                    layer.push(eg.add(op, &[a]));
                } else {
                    layer.push(eg.add(op, &[a, b]));
                }
            }
            prev = layer;
        }

        // Merges
        let start = Instant::now();
        for i in 0..n_merges {
            let a = ENodeId::new((next() % n_leaves) as u32);
            let b = ENodeId::new((next() % n_leaves) as u32);
            if PROOFS {
                eg.merge_justified(
                    a,
                    b,
                    Justification::Axiom {
                        axiom_id: crate::id::AxiomId::new(i as u16),
                    },
                );
            } else {
                eg.merge(a, b);
            }
        }
        eg.rebuild();
        start.elapsed()
    }

    #[test]
    fn overhead_comparison() {
        let params = [
            (50, 3, 20, "small"),
            (100, 3, 40, "medium"),
            (200, 4, 80, "large"),
        ];

        // Warmup
        build_and_rebuild::<false, false>(20, 2, 10);
        build_and_rebuild::<false, true>(20, 2, 10);
        build_and_rebuild::<true, true>(20, 2, 10);

        eprintln!("\n=== PROOFS overhead comparison (merge+rebuild) ===");
        eprintln!(
            "{:<10} {:>12} {:>12} {:>12} {:>8} {:>8}",
            "size", "T=f,P=f", "T=f,P=t", "T=t,P=t", "P ratio", "TP ratio"
        );
        eprintln!("{}", "-".repeat(72));

        for &(leaves, layers, merges, label) in &params {
            let mut t_ff = Vec::new();
            let mut t_ft = Vec::new();
            let mut t_tt = Vec::new();
            let iters = 20;
            for _ in 0..iters {
                t_ff.push(build_and_rebuild::<false, false>(leaves, layers, merges));
                t_ft.push(build_and_rebuild::<false, true>(leaves, layers, merges));
                t_tt.push(build_and_rebuild::<true, true>(leaves, layers, merges));
            }
            t_ff.sort();
            t_ft.sort();
            t_tt.sort();
            let m_ff = t_ff[iters / 2];
            let m_ft = t_ft[iters / 2];
            let m_tt = t_tt[iters / 2];
            let r_p = m_ft.as_nanos() as f64 / m_ff.as_nanos().max(1) as f64;
            let r_tp = m_tt.as_nanos() as f64 / m_ff.as_nanos().max(1) as f64;
            eprintln!(
                "{:<10} {:>10.1}µs {:>10.1}µs {:>10.1}µs {:>7.2}x {:>7.2}x",
                label,
                m_ff.as_nanos() as f64 / 1000.0,
                m_ft.as_nanos() as f64 / 1000.0,
                m_tt.as_nanos() as f64 / 1000.0,
                r_p,
                r_tp,
            );
        }
    }
}

#[cfg(test)]
mod proof_restore_test {
    use crate::containers::ShrinkPolicy;
    use crate::egraph::EGraph31;
    use crate::literal::NiraLitVal;
    use crate::union_find::{Justification, ProofBuf};

    /// Merge + rebuild + mark/restore: verify that proof state is fully rolled back.
    /// After restore, congruence should be undone and explain_deep should fail.
    /// Then re-merge different leaves and verify new proofs work correctly.
    #[test]
    fn proof_state_restored() {
        let mut eg = EGraph31::<NiraLitVal, true, true>::new();
        let int = eg.intern_sort("Int");
        let f = eg.register_op1("f", int, int);
        let x_op = eg.register_op0("x", int);
        let y_op = eg.register_op0("y", int);
        let z_op = eg.register_op0("z", int);

        let x = eg.add(x_op, &[]);
        let y = eg.add(y_op, &[]);
        let z = eg.add(z_op, &[]);
        let fx = eg.add(f, &[x]);
        let fy = eg.add(f, &[y]);
        let fz = eg.add(f, &[z]);

        // Mark before any merges
        let token = eg.mark(ShrinkPolicy::Never);

        // Merge x≡y, rebuild → f(x)≡f(y) by congruence
        eg.merge_justified(
            x,
            y,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(1),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(fx), eg.find(fy));
        assert_ne!(eg.find(fx), eg.find(fz));

        // Deep proof should work
        let mut buf = ProofBuf::new();
        assert!(eg.explain_deep(fx, fy, &mut buf));
        assert!(
            buf.steps
                .iter()
                .any(|(_, _, j)| matches!(j, Justification::Congruence { .. }))
        );
        assert!(buf.steps.iter().any(|(_, _, j)| *j
            == Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(1)
            }));

        // Restore
        eg.restore(token);

        // Congruence should be undone
        assert_ne!(eg.find(fx), eg.find(fy));
        assert_ne!(eg.find(fx), eg.find(fz));

        // Proof should fail
        buf.clear();
        assert!(!eg.explain_deep(fx, fy, &mut buf));

        // Now merge x≡z instead, rebuild → f(x)≡f(z)
        eg.merge_justified(
            x,
            z,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(2),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(fx), eg.find(fz));
        assert_ne!(eg.find(fx), eg.find(fy));

        // New proof should reference axiom #2, not axiom #1
        buf.clear();
        assert!(eg.explain_deep(fx, fz, &mut buf));
        assert!(buf.steps.iter().any(|(_, _, j)| *j
            == Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(2)
            }));
        assert!(!buf.steps.iter().any(|(_, _, j)| *j
            == Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(1)
            }));

        eprintln!("✓ proof_state_restored passed");
    }

    /// Multiple mark/restore cycles with proofs.
    #[test]
    fn proof_nested_restore() {
        let mut eg = EGraph31::<NiraLitVal, true, true>::new();
        let int = eg.intern_sort("Int");
        let f = eg.register_op1("f", int, int);
        let a_op = eg.register_op0("a", int);
        let b_op = eg.register_op0("b", int);
        let c_op = eg.register_op0("c", int);

        let a = eg.add(a_op, &[]);
        let b = eg.add(b_op, &[]);
        let c = eg.add(c_op, &[]);
        let fa = eg.add(f, &[a]);
        let fb = eg.add(f, &[b]);
        let fc = eg.add(f, &[c]);

        let tok1 = eg.mark(ShrinkPolicy::Never);

        // Merge a≡b
        eg.merge_justified(
            a,
            b,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(10),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(fa), eg.find(fb));

        let tok2 = eg.mark(ShrinkPolicy::Never);

        // Merge a≡c on top
        eg.merge_justified(
            a,
            c,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(20),
            },
        );
        eg.rebuild();
        assert_eq!(eg.find(fa), eg.find(fc));

        // Restore to tok2: a≡c undone, a≡b still holds
        eg.restore(tok2);
        assert_eq!(eg.find(fa), eg.find(fb));
        assert_ne!(eg.find(fa), eg.find(fc));

        let mut buf = ProofBuf::new();
        assert!(eg.explain_deep(fa, fb, &mut buf));
        assert!(!eg.explain_deep(fa, fc, &mut buf));

        // Restore to tok1: everything undone
        eg.restore(tok1);
        assert_ne!(eg.find(fa), eg.find(fb));
        assert_ne!(eg.find(fa), eg.find(fc));

        buf.clear();
        assert!(!eg.explain_deep(fa, fb, &mut buf));

        eprintln!("✓ proof_nested_restore passed");
    }
}