auslander 0.6.0

Computational representation theory of finite-dimensional bound quiver algebras
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
//! Left mutation of a support tau-tilting pair at a module summand slot.
//!
//! A vertex is a pair `(M, P)` with module summands `X_1, ..., X_m`. Slot `j`
//! addresses `X_j`. Only module summands have slots. Mutation at a summand of
//! the projective part is always a right mutation, so a walk that descends
//! from `(A, 0)` never performs one. `docs/v0.5-design.md` section 8 records
//! that as a deviation from the earlier signed-slot design.
//!
//! Exactly one of two branches holds at a slot, and [`mutate_at`] decides
//! which by computation.
//!
//! 1. `X_j` lies in `Fac(M/X_j)`. The mutation at slot `j` is then a right
//!    mutation and there is no left mutation. [`FacWitness`] proves the
//!    membership by one rank comparison per vertex.
//! 2. Otherwise the left mutation exists. [`Mutation`] carries the target pair
//!    and a [`MutationWitness`].
//!
//! # Proof of adjacency
//!
//! The construction does not prove that the built pair is the mutation. The
//! proof runs through the almost complete pair:
//!
//! 1. `(U, Q) = (M/X_j, P)` is an almost complete support tau-tilting pair,
//!    certified by [`AlmostCompletePair`].
//! 2. `(M, P)` extends `(U, Q)`.
//! 3. `(M', P')` extends `(U, Q)`.
//! 4. The two completions are not isomorphic.
//! 5. `(M', P')` is a support tau-tilting pair, certified by
//!    [`SupportTauTiltingPair`].
//!
//! An almost complete support tau-tilting pair is a direct summand of exactly
//! two basic support tau-tilting pairs (Adachi, Iyama, and Reiten,
//! "tau-tilting theory", Compositio Math. 150 (2014), 415-452, Theorem 2.18,
//! two complements). With the five checks above, that theorem identifies
//! `(M', P')` as the mutation at slot `j`, and the `Fac` test of branch 1
//! identifies the direction (same paper, Definition-Proposition 2.28, and
//! Proposition 2.22: exactly one of `X in Fac U` and the containment
//! `perp(tau U) is inside perp(tau X)` holds).
//!
//! The theorem holds over an arbitrary field. Its hypothesis reads "let
//! `Lambda` be a finite dimensional `k`-algebra", and the algebraically closed
//! hypothesis of the paper's introduction is re-imposed at the head of section
//! 5, which would be pointless if it were already in force. Demonet, Iyama,
//! and Jasso, "tau-tilting finite algebras, bricks and g-vectors"
//! (arXiv:1503.00285), restate the same result over an arbitrary field for
//! right modules, which is this crate's setting. See
//! `docs/v0.5-design.md` section 8.
//!
//! The exchange sequence `X_j -> B -> Y -> 0` is stored as a construction
//! witness. It records how the target was built. It is not the proof of
//! adjacency.
//!
//! # Shapes
//!
//! The two shapes of a left mutation are [`ExchangeShape`]. The construction
//! decides between them by comparing supports, as in AIR Theorem 2.30(a) and
//! (b):
//!
//! - `supp(U)` is smaller than `supp(M)`: the cokernel is zero, `X_j` leaves
//!   the module part, and the one vertex of `supp(M) \ supp(U)` joins the
//!   projective support.
//! - `supp(U)` equals `supp(M)`: the cokernel is a sum of copies of one
//!   indecomposable `Y_1`, and `M' = U + Y_1` with the projective support
//!   unchanged.

use std::sync::Arc;

use crate::approx::{ApproxError, MinimalLeftApproximation, left_approximation};
use crate::basic::{
    AddClosureWitness, BasicDecomposition, BasicError, ProjectiveSupport, SupportPairIsoOutcome,
    SupportPairObstruction, pair_iso,
};
use crate::context::VerificationContext;
use crate::decompose::{Certificate, decompose, direct_sum_or_zero};
use crate::field::Fp;
use crate::hom::{HomError, Morphism, cokernel, hom};
use crate::indec::{IndecError, IndecomposableModule};
use crate::iso::indecomposable_iso;
use crate::linalg::DenseMat;
use crate::module::{Module, same_representation};
use crate::profile::{Site, hit};
use crate::supporttau::{
    AlmostCompleteClassification, AlmostCompletePair, PairRejection, SupportTauError,
    SupportTauTiltingClassification, SupportTauTiltingPair,
};
use crate::taurigid::TauCache;

/// Which end of a mutation edge a report is about.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Endpoint {
    /// The pair the mutation starts from.
    Source,
    /// The pair the mutation lands on.
    Target,
}

display_error! { Endpoint {
    Self::Source => "source";
    Self::Target => "target";
} }

/// A failed internal cross-check of the mutation layer.
///
/// Every variant signals a crate defect: the hypotheses of AIR Theorem 2.18 or
/// Theorem 2.30 hold on the input, and a consequence the code checked did not.
/// None of these is a statement about the input pair.
#[derive(Clone, Debug)]
pub enum MutationDefect {
    /// Dropping the slot summand left a pair that is not almost complete. A
    /// direct summand of a tau-rigid pair is tau-rigid, and the summand count
    /// drops by exactly one, so this cannot happen.
    AlmostCompleteRejected(PairRejection),
    /// The built pair failed a support tau-tilting condition. AIR Theorem 2.30
    /// says it is one.
    TargetRejected(PairRejection),
    /// `supp(M) \ supp(U)` has a size other than one. AIR's proof of Theorem
    /// 2.30(a) forces a singleton.
    DroppedVertexCount {
        /// The vertices of `supp(M)` that `supp(U)` misses.
        dropped: Vec<u32>,
    },
    /// `supp(U)` is smaller than `supp(M)` and the cokernel of the
    /// approximation is not zero, against AIR Theorem 2.30(a).
    CokernelNonzero {
        /// The dimension vector of the cokernel.
        dim_vector: Vec<usize>,
    },
    /// `supp(U)` equals `supp(M)` and the cokernel is zero, against AIR
    /// Theorem 2.30(b).
    CokernelZero,
    /// The cokernel summand at this position is not isomorphic to the first
    /// one. AIR Theorem 2.30(b) makes the cokernel a sum of copies of one
    /// indecomposable.
    CokernelSummandsDiffer {
        /// Position of the summand in decomposition order.
        summand: usize,
    },
    /// The cokernel summand is isomorphic to summand `summand` of `M`, against
    /// AIR Theorem 2.30(b), which puts `Y` outside `add(T)`.
    ReplacementRepeatsSummand {
        /// Position of the summand in the module part of the source pair.
        summand: usize,
    },
    /// `U` is not a direct summand of the named endpoint's module part.
    AddClosureMissing {
        /// Which endpoint failed.
        endpoint: Endpoint,
    },
    /// The named endpoint's projective support does not contain `Q`.
    ProjectiveSupportNotExtended {
        /// Which endpoint failed.
        endpoint: Endpoint,
    },
    /// The two completions of the almost complete pair are isomorphic, against
    /// AIR Theorem 2.18.
    EndpointsIsomorphic,
}

display_error! { error MutationDefect {
    Self::AlmostCompleteRejected(rejection) => "dropping the slot summand left condition {} unmet: {rejection}; crate defect", rejection.condition();
    Self::TargetRejected(rejection) => "the built pair left condition {} unmet: {rejection}; crate defect", rejection.condition();
    Self::DroppedVertexCount { dropped } => "dropping the slot summand lost {} vertices, not one; crate defect", dropped.len();
    Self::CokernelNonzero { dim_vector } => "the approximation has cokernel of dimension vector {dim_vector:?} where the \
                                             support test says zero; crate defect";
    Self::CokernelZero => "the approximation has zero cokernel where the support test says nonzero; \
                          crate defect";
    Self::CokernelSummandsDiffer { summand } => "cokernel summand {summand} is not isomorphic to the first one; crate defect";
    Self::ReplacementRepeatsSummand { summand } => "the cokernel summand repeats summand {summand} of the module part; crate defect";
    Self::AddClosureMissing { endpoint } => "the {endpoint} pair does not contain U; crate defect";
    Self::ProjectiveSupportNotExtended { endpoint } => "the {endpoint} projective support does not contain Q; crate defect";
    Self::EndpointsIsomorphic => "the two completions are isomorphic; crate defect";
} }

/// Rejected input, a blocked certification, or a failed internal cross-check
/// of the mutation layer.
///
/// A slot with no left mutation is no error. It comes back as
/// [`SlotOutcome::NoLeftMutation`] with its witness.
#[derive(Clone, Debug)]
pub enum MutationError {
    /// The slot index is not a module summand of the pair.
    SlotOutOfRange {
        /// The requested slot.
        slot: usize,
        /// `|M|`, the number of module summands.
        summands: usize,
    },
    /// The caller's index list and the module summands have different lengths.
    SummandIndexCount {
        /// Number of indices supplied.
        indices: usize,
        /// `|M|`, the number of module summands.
        summands: usize,
    },
    /// The basic layer rejected an input or could not certify a summand.
    Basic(BasicError),
    /// The support tau-tilting layer rejected an input or could not run a
    /// check.
    SupportTau(SupportTauError),
    /// The approximation layer rejected the add-generators of `U`.
    Approx(ApproxError),
    /// A Hom computation rejected its input.
    Hom(HomError),
    /// A cokernel summand failed the indecomposability gate.
    /// [`IndecError::Undetermined`] is a blocked certification, not budget
    /// exhaustion, and it must poison any completeness claim built on it.
    Indec(IndecError),
    /// An internal cross-check failed.
    Defect(MutationDefect),
}

display_error! { MutationError {
    Self::SlotOutOfRange { slot, summands } => "slot {slot} is out of range, the module part has {summands} summands";
    Self::SummandIndexCount { indices, summands } => "{indices} summand indices for {summands} summands";
    Self::Basic(error) => "basic layer: {error}";
    Self::SupportTau(error) => "support tau-tilting layer: {error}";
    Self::Approx(error) => "approximation layer: {error}";
    Self::Hom(error) => "hom: {error}";
    Self::Indec(error) => "cokernel summand: {error}";
    Self::Defect(defect) => "{defect}";
} }

error_source!(MutationError {
    Self::Basic(error) => Some(error),
    Self::SupportTau(error) => Some(error),
    Self::Approx(error) => Some(error),
    Self::Hom(error) => Some(error),
    Self::Indec(error) => Some(error),
    Self::Defect(defect) => Some(defect),
    Self::SlotOutOfRange { .. } | Self::SummandIndexCount { .. } => None,
});

from_variants!(MutationError {
    BasicError => Basic,
    SupportTauError => SupportTau,
    HomError => Hom,
});

fn defect(defect: MutationDefect) -> MutationError {
    MutationError::Defect(defect)
}

/// The vertices where `m` has positive dimension, ascending.
fn support(m: &Module) -> Vec<u32> {
    m.dim_vector()
        .iter()
        .enumerate()
        .filter_map(|(v, &d)| (d > 0).then_some(v as u32))
        .collect()
}

/// Whether `m` is the direct sum of `parts`, in that order, entry for entry.
///
/// Reassembles the sum and compares every arrow matrix. Dimension vectors
/// would not decide it: they are isomorphism invariants and not identifiers.
fn is_direct_sum(m: &Module, parts: &[Module]) -> bool {
    same_representation(&direct_sum_or_zero(m.algebra(), parts).0, m)
}

/// The dimension of the sum of the images of `maps` at each vertex.
///
/// The images of a spanning set of `Hom(U, X)` sum to the trace submodule
/// `tr_U(X)`, and at one vertex that sum is the row span of the stacked vertex
/// matrices. So a rank per vertex decides `X in Fac U`.
fn trace_dims(maps: &[Morphism], x: &Module) -> Vec<usize> {
    let field = x.field();
    (0..x.algebra().quiver().num_vertices())
        .map(|v| {
            if x.dim_at(v) == 0 {
                return 0;
            }
            let rows: Vec<Vec<Fp>> = maps
                .iter()
                .flat_map(|f| {
                    let block = f.map_at(v);
                    (0..block.rows()).map(move |r| block.row(r).to_vec())
                })
                .collect();
            DenseMat::from_rows(&rows).rank(&field)
        })
        .collect()
}

/// Whether `g` is a cokernel of `f`.
///
/// The checks are `f.then(g) = 0`, `g` onto at every vertex, and
/// `dim Y_v + rank f_v = dim B_v` at every vertex. Together those say
/// `im f = ker g` and `g` epi, which is the cokernel property.
fn is_cokernel(f: &Morphism, g: &Morphism) -> bool {
    verify_guard!(g.source().ptr_eq(f.target()));
    let_or_false!(Ok(composite) = f.then(g));
    verify_guard!(composite.is_zero());
    let field = f.source().field();
    (0..f.source().algebra().quiver().num_vertices()).all(|v| {
        let dim_y = g.target().dim_at(v);
        g.map_at(v).rank(&field) == dim_y
            && dim_y + f.map_at(v).rank(&field) == f.target().dim_at(v)
    })
}

/// A proof that `X_j` lies in `Fac(M/X_j)`, so slot `j` admits no left
/// mutation.
///
/// `X in Fac U` exactly when finitely many maps `f_i : U -> X` have images
/// summing to all of `X`, which is to say the induced `U^r -> X` is onto. The
/// witness is that family. It does not claim the family spans `Hom(U, X)`:
/// spanning is stronger than the definition of `Fac` and nothing here needs
/// it. The only constructor is [`mutate_at`].
///
/// By AIR Definition-Proposition 2.28 the mutation at this slot is then a
/// right mutation. This is a statement about the slot, not a failure.
#[derive(Clone, Debug)]
pub struct FacWitness {
    module: Module,
    // The summands of U, shared with the decomposition of the source pair.
    summands: Vec<Module>,
    summand: Module,
    maps: Vec<Morphism>,
}

impl FacWitness {
    accessor_methods! {
        /// `U = M/X_j`, the module part with the slot summand dropped.
        pub module() -> &Module = |this| &this.module;
        /// The summands of `U`, in the order they hold in the source pair.
        ///
        /// These are the module values of the source decomposition, not copies,
        /// so a caller binds the witness to its pair by [`Module::ptr_eq`] on each
        /// one. A dimension vector does not bind: two non-isomorphic modules can
        /// share one, as three of the `kronecker(2)` indecomposables do.
        pub summands() -> &[Module] = |this| &this.summands;
        /// `X_j`, the summand the slot addresses.
        pub summand() -> &Module = |this| &this.summand;
        /// The maps `U -> X_j` whose images were summed.
        pub maps() -> &[Morphism] = |this| &this.maps;
        /// The dimension of the sum of the images at each vertex, recomputed from
        /// the stored maps. On a witness that verifies it is the dimension vector
        /// of `X_j`.
        pub image_dims() -> Vec<usize> = |this| trace_dims(&this.maps, &this.summand);
    }

    /// Recomputes the rank equality from the stored maps.
    ///
    /// `U` must be the direct sum of the stored summands in order, entry for
    /// entry. Every stored map must run from `U` to `X_j`. The images must
    /// sum to the dimension vector of `X_j` at every vertex. A dropped map
    /// fails the rank check as soon as the remaining images stop covering
    /// `X_j`. No [`crate::homspace::HomSpace`] is rebuilt.
    ///
    /// The first check binds `U` to the summands. A caller that also compares
    /// [`FacWitness::summands`] against its own pair by [`Module::ptr_eq`]
    /// knows which module the rank equality was proved over.
    pub fn verify(&self) -> bool {
        hit(Site::FacWitnessVerify);
        is_direct_sum(&self.module, &self.summands)
            && self
                .maps
                .iter()
                .all(|f| f.source().ptr_eq(&self.module) && f.target().ptr_eq(&self.summand))
            && trace_dims(&self.maps, &self.summand) == self.summand.dim_vector()
    }
}

/// The shape of a left mutation at a module summand slot.
///
/// The two shapes are AIR Theorem 2.30(a) and (b). There is no third: a
/// projective summand is never exchanged for a projective, and a module summand
/// is never exchanged for two summands.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExchangeShape {
    /// `supp(U)` is smaller than `supp(M)`. The approximation has zero
    /// cokernel, the module part loses `X_j`, and `vertex` joins the projective
    /// support.
    MovesToProjective {
        /// The one vertex of `supp(M) \ supp(U)`.
        vertex: u32,
    },
    /// `supp(U)` equals `supp(M)`. The cokernel is `multiplicity` copies of one
    /// indecomposable, which enters the module part.
    ReplacedByModule {
        /// The number of summands of the cokernel.
        multiplicity: usize,
    },
}

/// The five checks that identify the target as the mutation, plus the exchange
/// sequence that built it.
///
/// The only constructor is [`mutate_at`], so a value of this type carries a
/// certified almost complete pair, an `add` closure witness per endpoint, a
/// proof that the endpoints differ, and a certified target pair.
/// [`MutationWitness::verify`] recomputes all of it.
///
/// The approximation and the cokernel map are construction data. They record
/// how the target was built. AIR Theorem 2.18 is what proves the target is
/// the mutation. See the module documentation.
#[derive(Debug)]
pub struct MutationWitness {
    slot: usize,
    exchanged: Module,
    almost_complete: AlmostCompletePair,
    source_module: Module,
    source_projective: Vec<u32>,
    source_extension: AddClosureWitness,
    target_module: Module,
    target_projective: Vec<u32>,
    target_extension: AddClosureWitness,
    distinct: SupportPairObstruction,
    approximation: MinimalLeftApproximation,
    // g: B -> Y, the cokernel of the approximation.
    exchange: Morphism,
    shape: ExchangeShape,
    // Y_1, present exactly for ExchangeShape::ReplacedByModule.
    replacement: Option<Module>,
}

impl MutationWitness {
    accessor_methods! {
        /// The slot the mutation was taken at.
        pub slot() -> usize = |this| this.slot;
        /// `X_j`, the summand the slot addresses.
        pub exchanged() -> &Module = |this| &this.exchanged;
        /// The almost complete pair `(U, Q) = (M/X_j, P)` both endpoints extend.
        pub almost_complete() -> &AlmostCompletePair = |this| &this.almost_complete;
        /// The proof that `U` is a direct summand of the source module part.
        pub source_extension() -> &AddClosureWitness = |this| &this.source_extension;
        /// The proof that `U` is a direct summand of the target module part.
        pub target_extension() -> &AddClosureWitness = |this| &this.target_extension;
        /// The proof that the two completions are not isomorphic.
        pub distinct() -> &SupportPairObstruction = |this| &this.distinct;
        /// The minimal left `add(U)`-approximation `f: X_j -> B`.
        pub approximation() -> &MinimalLeftApproximation = |this| &this.approximation;
        /// The cokernel map `g: B -> Y` of the approximation.
        ///
        /// With [`MutationWitness::approximation`] this is the exchange sequence
        /// `X_j -> B -> Y -> 0`.
        pub exchange() -> &Morphism = |this| &this.exchange;
        /// Which of the two shapes the mutation took.
        pub shape() -> &ExchangeShape = |this| &this.shape;
        /// `Y_1`, the indecomposable that enters the module part, or `None` when
        /// the slot moved to the projective part.
        pub replacement() -> Option<&Module> = |this| this.replacement.as_ref();
        /// The module part of the source pair.
        pub source_module() -> &Module = |this| &this.source_module;
        /// The projective support of the source pair.
        pub source_projective() -> &[u32] = |this| &this.source_projective;
        /// The module part of the target pair.
        pub target_module() -> &Module = |this| &this.target_module;
        /// The projective support of the target pair.
        pub target_projective() -> &[u32] = |this| &this.target_projective;
    }

    verify_methods!(pub(crate), { hit(Site::MutationWitnessVerify); },
        /// Recomputes every claim from the stored modules and maps.
        ///
        /// Both endpoints are decomposed again. The almost complete pair
        /// reruns all four of its conditions. The `add` closures are rebuilt
        /// as well as rechecked. The endpoints are compared again. The target
        /// is classified again from its parts. The exchange sequence is
        /// recomputed from the approximation. A witness borrowed from another
        /// slot fails, because its approximation does not start at the stored
        /// `X_j`.
        |self, context| {
        verify_guard!(self.almost_complete.verify_with_context(context));
        let u = self.almost_complete.module();
        let algebra = u.module().algebra();
        verify_guard!(Arc::ptr_eq(algebra, self.source_module.algebra())
            && Arc::ptr_eq(algebra, self.target_module.algebra()));
        let_or_false!((Ok(source_dec), Ok(target_dec)) = (
            BasicDecomposition::new_with_context(&self.source_module, context),
            BasicDecomposition::new_with_context(&self.target_module, context),
        ));
        let_or_false!((Ok(source_proj), Ok(target_proj)) = (
            ProjectiveSupport::new(algebra, &self.source_projective),
            ProjectiveSupport::new(algebra, &self.target_projective),
        ));
        // Check 2. The source keeps the projective part of the almost complete
        // pair, since a left mutation at a module slot leaves it alone.
        verify_guard!(self.almost_complete.projective().vertices() == source_proj.vertices()
            && extends(u, &source_dec, &self.source_extension));
        // Check 3.
        verify_guard!(self
            .almost_complete
            .projective()
            .vertices()
            .iter()
            .all(|&v| target_proj.contains(v))
            && extends(u, &target_dec, &self.target_extension));
        // Check 4.
        verify_guard!(matches!(
            context.pair_iso_for(&source_dec, &source_proj, &target_dec, &target_proj),
            Ok(outcome)
                if matches!(outcome.as_ref(), SupportPairIsoOutcome::NotIsomorphic(found) if found == &self.distinct)
        ));
        // Check 5. The decomposition and the support are rebuilt once more,
        // because classification takes them by value.
        let_or_false!((Ok(fresh_dec), Ok(fresh_proj)) = (
            BasicDecomposition::new_with_context(&self.target_module, context),
            ProjectiveSupport::new(algebra, &self.target_projective),
        ));
        matches!(
            SupportTauTiltingPair::classify_with_context(fresh_dec, fresh_proj, context),
            Ok(classification) if classification.is_pair()
        ) && self.exchange_holds(
                u,
                &source_dec,
                &target_dec,
                &source_proj,
                &target_proj,
                context,
            )
    });

    /// Rechecks the construction data: the approximation, the exchange
    /// sequence, and the shape.
    fn exchange_holds(
        &self,
        u: &BasicDecomposition,
        source_dec: &BasicDecomposition,
        target_dec: &BasicDecomposition,
        source_proj: &ProjectiveSupport,
        target_proj: &ProjectiveSupport,
        context: &VerificationContext,
    ) -> bool {
        let f = self.approximation.map();
        verify_guard!(f.source().ptr_eq(&self.exchanged));
        verify_guard!(
            self.approximation.summands().len() == u.len()
                && self
                    .approximation
                    .summands()
                    .iter()
                    .zip(u.summands())
                    .all(|(a, b)| a.module().ptr_eq(b.module()))
        );
        verify_guard!(
            self.approximation.verify_with_context(context) && is_cokernel(f, &self.exchange)
        );
        // The slot summand is a summand of the source module part, and the
        // slot is its position there.
        let_or_false!(Some(slot_summand) = source_dec.summands().get(self.slot));
        verify_guard!(
            indecomposable_iso(slot_summand.module(), &self.exchanged, slot_summand.endo())
                .is_some()
        );
        let y = self.exchange.target();
        match &self.shape {
            ExchangeShape::MovesToProjective { vertex } => {
                let mut expected = source_proj.vertices().to_vec();
                expected.push(*vertex);
                expected.sort_unstable();
                y.is_zero()
                    && self.replacement.is_none()
                    && !source_proj.contains(*vertex)
                    && target_proj.contains(*vertex)
                    && expected == target_proj.vertices()
                    && target_dec.len() == u.len()
            }
            ExchangeShape::ReplacedByModule { multiplicity } => {
                let_or_false!(Some(replacement) = &self.replacement);
                verify_guard!(!y.is_zero() && source_proj.vertices() == target_proj.vertices());
                verify_guard!(target_dec.len() == u.len() + 1);
                let split = context.decompose_for(y);
                verify_guard!(
                    split.summands().len() == *multiplicity
                        && !split
                            .certificates()
                            .iter()
                            .any(|c| *c != Certificate::Indecomposable)
                );
                let_or_false!(
                    Ok(y1) = IndecomposableModule::new_with_context(replacement, context)
                );
                verify_guard!(
                    split
                        .summands()
                        .iter()
                        .all(|s| indecomposable_iso(y1.module(), s, y1.endo()).is_some())
                );
                // AIR Theorem 2.30(b): Y_1 is outside add(T), so in particular
                // it repeats no summand of the source.
                verify_guard!(
                    !source_dec.summands().iter().any(|s| indecomposable_iso(
                        y1.module(),
                        s.module(),
                        y1.endo()
                    )
                    .is_some())
                );
                target_dec
                    .summands()
                    .iter()
                    .any(|s| indecomposable_iso(y1.module(), s.module(), y1.endo()).is_some())
            }
        }
    }
}

/// Whether `whole` contains `u` as a direct summand, both by a rebuilt match
/// and by the stored witness.
fn extends(u: &BasicDecomposition, whole: &BasicDecomposition, stored: &AddClosureWitness) -> bool {
    let_or_false!(Ok(Some(live)) = AddClosureWitness::new(u, whole));
    verify_guard!(
        live.matches().len() == stored.matches().len()
            && stored.module().ptr_eq(u.module())
            && stored.target().ptr_eq(whole.module())
    );
    let mut seen: Vec<usize> = stored.matches().iter().map(|m| m.target_index()).collect();
    seen.sort_unstable();
    let distinct = seen.windows(2).all(|w| w[0] != w[1]);
    distinct && stored.verify()
}

/// A left mutation at one slot, with the pair it lands on.
#[derive(Debug)]
pub struct Mutation {
    slot: usize,
    target: SupportTauTiltingPair,
    witness: MutationWitness,
}

impl Mutation {
    accessor_methods! {
        /// The slot the mutation was taken at.
        pub slot() -> usize = |this| this.slot;
        /// The pair the mutation lands on.
        pub target() -> &SupportTauTiltingPair = |this| &this.target;
    }

    /// The pair the mutation lands on, by value.
    #[inline]
    pub fn into_target(self) -> SupportTauTiltingPair {
        self.target
    }

    accessor_methods! {
        /// The five checks and the exchange sequence.
        pub witness() -> &MutationWitness = |this| &this.witness;
        /// Which of the two shapes the mutation took.
        pub shape() -> &ExchangeShape = |this| this.witness.shape();
    }

    verify_methods!(pub(crate), { hit(Site::MutationVerify); },
        /// Recomputes the witness and the target pair, and binds the two.
        ///
        /// The binding is [`Module::ptr_eq`] between the module part of the
        /// target pair and the target module the witness proves things about,
        /// plus equality of the two projective supports. Without it a witness
        /// for one target would pass next to a target pair for another.
        ///
        /// The slot is bound as well. The witness proves a statement about one
        /// slot, so a mutation carrying its own slot label could otherwise
        /// present a witness for a different one and still verify.
        |self, context| {
        self.slot == self.witness.slot()
            && self
                .target
                .module()
                .module()
                .ptr_eq(self.witness.target_module())
            && self.target.projective().vertices() == self.witness.target_projective()
            && self.witness.verify_with_context(context)
            && self.target.verify_with_context(context)
    });
}

/// What slot `j` of a pair admits.
#[derive(Debug)]
pub enum SlotOutcome {
    /// `X_j` lies in `Fac(M/X_j)`, so the mutation at this slot is a right
    /// mutation and there is no left mutation.
    NoLeftMutation(FacWitness),
    /// The left mutation at this slot, with its target.
    ///
    /// The mutation is boxed because it carries the whole target pair and
    /// every witness, which is much larger than a [`FacWitness`].
    LeftMutation(Box<Mutation>),
}

impl SlotOutcome {
    binary_outcome_accessors!(
        LeftMutation,
        NoLeftMutation,
        mutation -> Mutation = |value| value.as_ref(),
        fac_witness -> FacWitness = |value| value,
        is_left_mutation,
        into_mutation -> Mutation = |value| *value;
        flag = "Whether the slot admits a left mutation.";
        positive = "The mutation, or `None` when the slot admits no left mutation.";
        negative = "The `Fac` witness, or `None` when the slot admits a left mutation.";
        into = "The mutation by value, or `None` when the slot admits no left mutation.";
    );
}

/// The parts of the target pair the shape decision produces.
struct BuiltTarget {
    decomposition: BasicDecomposition,
    vertices: Vec<u32>,
    shape: ExchangeShape,
    // Y_1, present exactly for ExchangeShape::ReplacedByModule.
    replacement: Option<Module>,
}

/// The target parts, picked by the shape and cross-checked against AIR Theorem
/// 2.30.
///
/// `dropped` is `supp(M) \ supp(U)` and `y` is the cokernel of the
/// approximation. An empty `dropped` is the sincere case, where the cokernel
/// carries the exchange.
///
/// The target decomposition is built from `u_dec`, never decomposed again:
/// the module part is `U` itself, or `U` plus the one certified cokernel
/// summand `Y_1`.
fn build_target(
    pair: &SupportTauTiltingPair,
    u_dec: &BasicDecomposition,
    y: &Module,
    dropped: &[u32],
) -> Result<BuiltTarget, MutationError> {
    if let Some((&vertex, rest)) = dropped.split_first() {
        if !rest.is_empty() {
            return Err(defect(MutationDefect::DroppedVertexCount {
                dropped: dropped.to_vec(),
            }));
        }
        if !y.is_zero() {
            return Err(defect(MutationDefect::CokernelNonzero {
                dim_vector: y.dim_vector().to_vec(),
            }));
        }
        let mut vertices = pair.projective().vertices().to_vec();
        vertices.push(vertex);
        vertices.sort_unstable();
        return Ok(BuiltTarget {
            decomposition: u_dec.clone(),
            vertices,
            shape: ExchangeShape::MovesToProjective { vertex },
            replacement: None,
        });
    }
    if y.is_zero() {
        return Err(defect(MutationDefect::CokernelZero));
    }
    let split = decompose(y);
    for certificate in split.certificates() {
        if let Certificate::Undetermined { attempts } = certificate {
            return Err(MutationError::Basic(BasicError::CertificationBlocked {
                reason: format!(
                    "a cokernel summand stayed undetermined after {attempts} split attempts"
                ),
            }));
        }
    }
    let y1 =
        IndecomposableModule::from_endo(split.endos()[0].clone()).map_err(MutationError::Indec)?;
    for (position, other) in split.summands().iter().enumerate().skip(1) {
        if indecomposable_iso(y1.module(), other, y1.endo()).is_none() {
            return Err(defect(MutationDefect::CokernelSummandsDiffer {
                summand: position,
            }));
        }
    }
    // AIR Theorem 2.30(b) puts Y outside add(T). That covers the weaker
    // statement that Y_1 and X_j differ, since X_j is a summand of T.
    for (position, other) in pair.module().summands().iter().enumerate() {
        if indecomposable_iso(y1.module(), other.module(), y1.endo()).is_some() {
            return Err(defect(MutationDefect::ReplacementRepeatsSummand {
                summand: position,
            }));
        }
    }
    let replacement = y1.module().clone();
    Ok(BuiltTarget {
        decomposition: u_dec.with_new_summand(&y1).map_err(MutationError::Basic)?,
        vertices: pair.projective().vertices().to_vec(),
        shape: ExchangeShape::ReplacedByModule {
            multiplicity: split.summands().len(),
        },
        replacement: Some(replacement),
    })
}

/// The left mutation of `pair` at slot `slot`, over a cache of its own.
///
/// Summands are indexed by position and the cokernel summand gets the next
/// index, which is stable within this one call. Use
/// [`mutate_at_with_cache`] to share AR translates across several mutations.
///
/// # Errors
/// [`MutationError::SlotOutOfRange`] when the slot is not a module summand,
/// the wrapped errors of the layers a check runs through, and
/// [`MutationError::Defect`] on a failed internal cross-check.
pub fn mutate_at(pair: &SupportTauTiltingPair, slot: usize) -> Result<SlotOutcome, MutationError> {
    let count = pair.module().len();
    let indices: Vec<usize> = (0..count).collect();
    mutate_at_with_cache(pair, slot, &indices, count, None)
}

/// The left mutation of `pair` at slot `slot`, taking AR translates from
/// `cache`.
///
/// `summand_indices[i]` is the caller's stable label for summand `i` of the
/// module part, and `fresh_index` labels the cokernel summand of a
/// [`ExchangeShape::ReplacedByModule`] mutation. The labels travel to the
/// witnesses of the target pair and to
/// [`crate::taurigid::NonTauRigidWitness`]. They are not cache keys, so a
/// repeated label costs nothing but a confusing report. [`TauCache`] keys on
/// the identity of the module value.
///
/// The plain [`mutate_at`] labels summands by position because it builds and
/// drops its own cache. A caller that shares one cache usually has its own
/// numbering, which is why this entry point takes it.
///
/// With `cache` as `None` the call builds a cache, uses it, and drops it.
///
/// # Errors
/// As [`mutate_at`], plus [`MutationError::SummandIndexCount`] when the index
/// list and the summand list have different lengths.
pub fn mutate_at_with_cache(
    pair: &SupportTauTiltingPair,
    slot: usize,
    summand_indices: &[usize],
    fresh_index: usize,
    cache: Option<&mut TauCache>,
) -> Result<SlotOutcome, MutationError> {
    let m = pair.module();
    if slot >= m.len() {
        return Err(MutationError::SlotOutOfRange {
            slot,
            summands: m.len(),
        });
    }
    if summand_indices.len() != m.len() {
        return Err(MutationError::SummandIndexCount {
            indices: summand_indices.len(),
            summands: m.len(),
        });
    }
    let algebra = m.module().algebra().clone();
    let x = m.summands()[slot].module().clone();

    // Dropping one summand of a basic module leaves a basic module, so U comes
    // with its decomposition and no Krull-Schmidt runs here.
    let u_dec = m.without(slot).expect("the slot is a summand position");
    let u = u_dec.module().clone();

    // Step 2a of the case analysis: the Fac test decides the direction.
    let maps = hom(&u, &x)?;
    if trace_dims(&maps, &x) == x.dim_vector() {
        return Ok(SlotOutcome::NoLeftMutation(FacWitness {
            module: u,
            summands: u_dec
                .summands()
                .iter()
                .map(|s| s.module().clone())
                .collect(),
            summand: x,
            maps,
        }));
    }

    let u_indices: Vec<usize> = summand_indices
        .iter()
        .enumerate()
        .filter(|(i, _)| *i != slot)
        .map(|(_, &index)| index)
        .collect();
    let u_summands: Vec<Module> = u_dec
        .summands()
        .iter()
        .map(|s| s.module().clone())
        .collect();

    let mut owned = TauCache::new();
    let cache = cache.unwrap_or(&mut owned);
    let q = ProjectiveSupport::new(&algebra, pair.projective().vertices())?;
    let almost_complete = match AlmostCompletePair::classify_with_cache(
        u_dec.clone(),
        q,
        &u_indices,
        Some(&mut *cache),
    )? {
        AlmostCompleteClassification::Pair(almost) => almost,
        AlmostCompleteClassification::Rejected(rejection) => {
            return Err(defect(MutationDefect::AlmostCompleteRejected(rejection)));
        }
    };

    let approximation = left_approximation(&x, &u_summands).map_err(MutationError::Approx)?;
    let (y, exchange) = cokernel(approximation.map());

    // Step 2b: the sincerity test picks the shape. AIR Theorem 2.30 states it
    // as "U is sincere over Lambda/<e>", which is supp(U) = supp(M) here.
    let dropped: Vec<u32> = support(m.module())
        .into_iter()
        .filter(|&v| u.dim_at(v) == 0)
        .collect();

    let built = build_target(pair, &u_dec, &y, &dropped)?;

    let mut target_indices = u_indices.clone();
    target_indices.extend(built.replacement.is_some().then_some(fresh_index));
    let target_proj = ProjectiveSupport::new(&algebra, &built.vertices)?;
    let target = match SupportTauTiltingPair::classify_with_cache(
        built.decomposition,
        target_proj,
        &target_indices,
        Some(&mut *cache),
    )? {
        SupportTauTiltingClassification::Pair(target) => target,
        SupportTauTiltingClassification::Rejected(rejection) => {
            return Err(defect(MutationDefect::TargetRejected(rejection)));
        }
    };

    let Some(source_extension) = AddClosureWitness::new(almost_complete.module(), m)? else {
        return Err(defect(MutationDefect::AddClosureMissing {
            endpoint: Endpoint::Source,
        }));
    };
    let Some(target_extension) = AddClosureWitness::new(almost_complete.module(), target.module())?
    else {
        return Err(defect(MutationDefect::AddClosureMissing {
            endpoint: Endpoint::Target,
        }));
    };
    if almost_complete.projective().vertices() != pair.projective().vertices() {
        return Err(defect(MutationDefect::ProjectiveSupportNotExtended {
            endpoint: Endpoint::Source,
        }));
    }
    if !almost_complete
        .projective()
        .vertices()
        .iter()
        .all(|&v| target.projective().contains(v))
    {
        return Err(defect(MutationDefect::ProjectiveSupportNotExtended {
            endpoint: Endpoint::Target,
        }));
    }
    let distinct = match pair_iso(m, &pair.projective(), target.module(), &target.projective())? {
        SupportPairIsoOutcome::NotIsomorphic(obstruction) => obstruction,
        SupportPairIsoOutcome::Isomorphic(_) => {
            return Err(defect(MutationDefect::EndpointsIsomorphic));
        }
    };

    let witness = MutationWitness {
        slot,
        exchanged: x,
        almost_complete,
        source_module: m.module().clone(),
        source_projective: pair.projective().vertices().to_vec(),
        source_extension,
        target_module: target.module().module().clone(),
        target_projective: target.projective().vertices().to_vec(),
        target_extension,
        distinct,
        approximation,
        exchange,
        shape: built.shape,
        replacement: built.replacement,
    };
    Ok(SlotOutcome::LeftMutation(Box::new(Mutation {
        slot,
        target,
        witness,
    })))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::algebra::{Algebra, linear_an, truncated_poly};
    use crate::dynkin::{DynkinType, dynkin_quiver};
    use crate::field::PrimeField;
    use crate::quiver::Quiver;

    /// The direct sum of `parts`, and the zero module when `parts` is empty.
    fn assemble(algebra: &Arc<Algebra>, parts: &[&Module]) -> Module {
        direct_sum_or_zero(algebra, parts.iter().copied()).0
    }

    fn f2() -> PrimeField {
        PrimeField::new(2).unwrap()
    }

    fn f5() -> PrimeField {
        PrimeField::new(5).unwrap()
    }

    fn fields() -> [PrimeField; 2] {
        [f2(), f5()]
    }

    fn path_algebra(quiver: Quiver, field: PrimeField) -> Arc<Algebra> {
        crate::algebra::path_algebra(quiver, field)
            .expect("the zero ideal over an acyclic quiver completes")
    }

    fn semisimple(n: u32, field: PrimeField) -> Arc<Algebra> {
        path_algebra(
            Quiver::new(n, &[]).expect("no arrow is out of range"),
            field,
        )
    }

    // D_4 as dynkin_quiver builds it: vertex 0 is the center, arrows 0 -> 1,
    // 0 -> 2, 0 -> 3.
    fn d4(field: PrimeField) -> Arc<Algebra> {
        path_algebra(
            dynkin_quiver(DynkinType::D(4)).expect("D_4 has a quiver"),
            field,
        )
    }

    fn pair_of(
        algebra: &Arc<Algebra>,
        parts: &[&Module],
        projective: &[u32],
    ) -> SupportTauTiltingPair {
        let module = assemble(algebra, parts);
        let decomposition =
            BasicDecomposition::new(&module).expect("the fixture module part is basic");
        let support =
            ProjectiveSupport::new(algebra, projective).expect("the fixture vertices are in range");
        match SupportTauTiltingPair::classify(decomposition, support)
            .expect("the fixture parts share one algebra")
        {
            SupportTauTiltingClassification::Pair(pair) => pair,
            SupportTauTiltingClassification::Rejected(rejection) => panic!(
                "the fixture is a pair, condition {} says otherwise: {rejection}",
                rejection.condition()
            ),
        }
    }

    /// The regular module `A = P_0 + ... + P_{n-1}`.
    fn regular_pair(algebra: &Arc<Algebra>) -> SupportTauTiltingPair {
        let parts: Vec<Module> = (0..algebra.quiver().num_vertices())
            .map(|v| Module::projective(algebra, v))
            .collect();
        let refs: Vec<&Module> = parts.iter().collect();
        pair_of(algebra, &refs, &[])
    }

    /// The slot addressing the summand with dimension vector `dim`.
    ///
    /// Every fixture below has module summands of pairwise distinct dimension
    /// vectors, so the lookup is unambiguous. Over the Dynkin fixtures the
    /// dimension vector also determines the indecomposable, since the
    /// indecomposables are the positive roots.
    fn slot_of(pair: &SupportTauTiltingPair, dim: &[usize]) -> usize {
        let hits: Vec<usize> = pair
            .module()
            .summands()
            .iter()
            .enumerate()
            .filter(|(_, s)| s.module().dim_vector() == dim)
            .map(|(i, _)| i)
            .collect();
        assert_eq!(hits.len(), 1, "one summand of dimension vector {dim:?}");
        hits[0]
    }

    fn sorted_dims(pair: &SupportTauTiltingPair) -> Vec<Vec<usize>> {
        let mut dims = pair.module().dim_vectors();
        dims.sort();
        dims
    }

    /// The mutation at the slot addressing `dim`, with both verifications run.
    fn left(pair: &SupportTauTiltingPair, dim: &[usize]) -> Mutation {
        let slot = slot_of(pair, dim);
        let outcome = mutate_at(pair, slot).expect("the fixture slot mutates");
        let mutation = match outcome {
            SlotOutcome::LeftMutation(mutation) => *mutation,
            SlotOutcome::NoLeftMutation(_) => {
                panic!("slot {slot} of dimension vector {dim:?} has a left mutation")
            }
        };
        assert!(mutation.witness().verify(), "the witness recomputes");
        assert!(mutation.verify(), "the mutation recomputes");
        mutation
    }

    #[test]
    fn mutation_witness_reuses_context_for_nested_approximation() {
        let _reset_guard = crate::profile::tests::reset_lock();
        let algebra = linear_an(2, f5());
        let p0 = Module::projective(&algebra, 0);
        let p1 = Module::projective(&algebra, 1);
        let pair = pair_of(&algebra, &[&p0, &p1], &[]);
        let mutation = left(&pair, &[1, 1]);
        let context = VerificationContext::new();

        crate::profile::reset();
        assert!(mutation.witness().verify_with_context(&context));
        let first_counts = crate::profile::snapshot();
        let first_memo = context.memo_stats();
        assert!(first_memo.1 > 0, "the first verification has memo misses");

        assert!(mutation.witness().verify_with_context(&context));
        let second_counts = crate::profile::snapshot();
        let second_memo = context.memo_stats();
        assert_eq!(second_memo.1, first_memo.1);
        assert!(
            second_memo.0 > first_memo.0,
            "the second verification has memo hits"
        );
        assert_eq!(
            second_counts[Site::EndoNew as usize],
            first_counts[Site::EndoNew as usize],
            "the nested approximation reuses its cached endomorphism"
        );
    }

    fn no_left(pair: &SupportTauTiltingPair, dim: &[usize]) -> FacWitness {
        let slot = slot_of(pair, dim);
        match mutate_at(pair, slot).expect("the fixture slot classifies") {
            SlotOutcome::NoLeftMutation(witness) => {
                assert!(witness.verify(), "the Fac witness recomputes");
                witness
            }
            SlotOutcome::LeftMutation(_) => {
                panic!("slot {slot} of dimension vector {dim:?} has no left mutation")
            }
        }
    }

    fn assert_target(mutation: &Mutation, dims: &[&[usize]], projective: &[u32]) {
        let mut expected: Vec<Vec<usize>> = dims.iter().map(|d| d.to_vec()).collect();
        expected.sort();
        assert_eq!(sorted_dims(mutation.target()), expected);
        assert_eq!(mutation.target().projective().vertices(), projective);
    }

    // The pentagon of A_2, worked out by hand in the v0.5 mathematics spike,
    // section 3.2. Vertices in crate indexing (0-based, arrow 0 -> 1):
    //
    //   v1 = (P_0 + P_1, 0)      P_0 = (1,1), P_1 = (0,1) = S_1
    //   v2 = (P_0 + S_0, 0)      S_0 = (1,0)
    //   v3 = (S_0, P_1)
    //   v4 = (P_1, P_0)
    //   v5 = (0, P_0 + P_1)
    //
    // Left mutations, one line per slot:
    //
    //   v1 at P_0: U = P_1, Fac U = add P_1, so P_0 is outside it. supp U =
    //     {1} is smaller than supp M = {0,1}, so the slot moves to the
    //     projective part at vertex 0 and the target is v4. Hom(P_0, P_1) = 0,
    //     so the approximation is the zero map into the zero module.
    //   v1 at P_1: U = P_0. Every quotient of a sum of copies of P_0 has top a
    //     sum of S_0, and top P_1 = S_1, so P_1 is outside Fac U. supp U =
    //     {0,1} = supp M, so the cokernel carries the exchange: the minimal
    //     left add(P_0)-approximation is the socle inclusion P_1 -> P_0 and
    //     coker is S_0. Target v2.
    //   v2 at P_0: U = S_0, and P_0 is outside add S_0 = Fac S_0. supp U = {0}
    //     is smaller than {0,1}, so vertex 1 joins the projective part and the
    //     target is v3. The approximation P_0 -> S_0 is onto with kernel P_1,
    //     which the construction never touches.
    //   v2 at S_0: S_0 = top P_0 lies in Fac P_0, so there is no left mutation.
    //   v3 at S_0: U = 0 and Fac 0 = {0}, so S_0 is outside it. supp U = {} is
    //     smaller than {0}, so vertex 0 joins the projective part: target v5.
    //   v4 at P_1: as v3, with vertex 1: target v5.
    //   v5 has no module summand, so it has no slot.
    #[test]
    fn a2_pentagon_slot_by_slot() {
        for field in fields() {
            let algebra = linear_an(2, field);
            let p0 = Module::projective(&algebra, 0);
            let p1 = Module::projective(&algebra, 1);
            let s0 = Module::simple(&algebra, 0);

            let v1 = pair_of(&algebra, &[&p0, &p1], &[]);
            let v2 = pair_of(&algebra, &[&p0, &s0], &[]);
            let v3 = pair_of(&algebra, &[&s0], &[1]);
            let v4 = pair_of(&algebra, &[&p1], &[0]);
            let v5 = pair_of(&algebra, &[], &[0, 1]);

            let at_p0 = left(&v1, &[1, 1]);
            assert_target(&at_p0, &[&[0, 1]], &[0]);
            assert_eq!(
                *at_p0.shape(),
                ExchangeShape::MovesToProjective { vertex: 0 }
            );
            assert!(at_p0.witness().approximation().map().target().is_zero());

            let at_p1 = left(&v1, &[0, 1]);
            assert_target(&at_p1, &[&[1, 1], &[1, 0]], &[]);
            assert_eq!(
                *at_p1.shape(),
                ExchangeShape::ReplacedByModule { multiplicity: 1 }
            );
            assert_eq!(
                at_p1.witness().replacement().map(|y| y.dim_vector()),
                Some([1, 0].as_slice())
            );

            let v2_at_p0 = left(&v2, &[1, 1]);
            assert_target(&v2_at_p0, &[&[1, 0]], &[1]);
            assert_eq!(
                *v2_at_p0.shape(),
                ExchangeShape::MovesToProjective { vertex: 1 }
            );

            let fac = no_left(&v2, &[1, 0]);
            assert_eq!(fac.image_dims(), [1, 0]);
            assert_eq!(fac.maps().len(), 1);

            let v3_at_s0 = left(&v3, &[1, 0]);
            assert_target(&v3_at_s0, &[], &[0, 1]);
            assert_eq!(
                *v3_at_s0.shape(),
                ExchangeShape::MovesToProjective { vertex: 0 }
            );

            let v4_at_p1 = left(&v4, &[0, 1]);
            assert_target(&v4_at_p1, &[], &[0, 1]);
            assert_eq!(
                *v4_at_p1.shape(),
                ExchangeShape::MovesToProjective { vertex: 1 }
            );

            assert_eq!(v5.module().len(), 0);
            assert!(matches!(
                mutate_at(&v5, 0),
                Err(MutationError::SlotOutOfRange {
                    slot: 0,
                    summands: 0
                })
            ));
        }
    }

    // The semisimple algebra on two vertices, spike section 3.1. Every module
    // is projective, so tau is zero and a pair is any assignment of P_0 and
    // P_1 to the module part or the projective part: four vertices. Fac U is
    // add U here, so no module summand ever lies in Fac of the rest and every
    // slot mutates. Each mutation moves its summand to the projective part,
    // which makes the graph the 2-cube.
    #[test]
    fn semisimple_two_vertex_cube() {
        for field in fields() {
            let algebra = semisimple(2, field);
            let p0 = Module::projective(&algebra, 0);
            let p1 = Module::projective(&algebra, 1);

            let top = pair_of(&algebra, &[&p0, &p1], &[]);
            let left_side = pair_of(&algebra, &[&p1], &[0]);
            let right_side = pair_of(&algebra, &[&p0], &[1]);
            let bottom = pair_of(&algebra, &[], &[0, 1]);

            let drop_p0 = left(&top, &[1, 0]);
            assert_target(&drop_p0, &[&[0, 1]], &[0]);
            assert_eq!(
                *drop_p0.shape(),
                ExchangeShape::MovesToProjective { vertex: 0 }
            );

            let drop_p1 = left(&top, &[0, 1]);
            assert_target(&drop_p1, &[&[1, 0]], &[1]);

            let down_left = left(&left_side, &[0, 1]);
            assert_target(&down_left, &[], &[0, 1]);

            let down_right = left(&right_side, &[1, 0]);
            assert_target(&down_right, &[], &[0, 1]);

            assert_eq!(bottom.module().len(), 0);
        }
    }

    // Ten of the 21 edges of linear_an(3), spike section 3.3, with the
    // vertices named as in its table. Crate indexing is 0-based, so the
    // interval [i,j] of the spike is [i-1,j-1] here:
    //
    //   P_0 = (1,1,1)   P_1 = (0,1,1)   P_2 = (0,0,1)
    //   S_0 = (1,0,0)   S_1 = (0,1,0)   I_1 = (1,1,0)
    //
    //   A = (P_0 + S_0 + P_2, 0)   B = (A, 0)          C = (P_0 + P_1 + S_1, 0)
    //   E = (P_0 + I_1 + S_0, 0)   G = (P_1 + P_2, P_0)
    //   H = (S_0 + P_2, P_1)       K = (P_2, P_0 + P_1)
    //   M = (S_0, P_1 + P_2)       N = (0, A)
    //
    // Quotients of an interval module [a,b] are the intervals [a,c], so Fac
    // membership is a finite check by hand. Hom([a,b],[c,d]) is nonzero
    // exactly when c <= a <= d <= b, which fixes the approximations.
    //
    //   B at P_2: U = P_0 + P_1, whose quotients are [0,0], [0,1], [0,2],
    //     [1,1], [1,2]; P_2 = [2,2] is not among them. supp U = {0,1,2} is all
    //     of supp M, so the exchange runs through the cokernel. Hom(P_2, P_0)
    //     factors through Hom(P_2, P_1) . Hom(P_1, P_0), so the only generator
    //     is P_2 -> P_1 and coker is S_1. Target C.
    //   B at P_1: U = P_0 + P_2. Hom(P_0, P_1) = 0 and the image of
    //     Hom(P_2, P_1) is P_2, so the trace is P_2 and P_1 is outside Fac U.
    //     supp U is everything, the generator is P_1 -> P_0, and coker is S_0.
    //     Target A.
    //   B at P_0: U = P_1 + P_2 has support {1,2}, so P_0 is outside Fac U and
    //     vertex 0 moves to the projective part. Target G.
    //   A at P_2: U = P_0 + S_0. Hom(P_2, S_0) = 0 and Hom(P_2, P_0) is the
    //     socle inclusion, which is the one generator; coker is I_1. Target E.
    //   A at S_0: S_0 = top P_0 lies in Fac U, so no left mutation.
    //   A at P_0: U = S_0 + P_2 has support {0,2}, so vertex 1 moves to the
    //     projective part. Target H.
    //   H at P_2: U = S_0 has support {0}, so vertex 2 moves across. Target M.
    //   H at S_0: U = P_2 has support {2}, so vertex 0 moves across. Target K.
    //   K at P_2 and M at S_0: U = 0 in both, so the one support vertex moves
    //     across. Both land on N.
    #[test]
    fn linear_an_3_pinned_edges() {
        for field in fields() {
            let algebra = linear_an(3, field);
            let p0 = Module::projective(&algebra, 0);
            let p1 = Module::projective(&algebra, 1);
            let p2 = Module::projective(&algebra, 2);
            let s0 = Module::simple(&algebra, 0);
            // I_1 is the interval module (1,1,0), which the targets below
            // reach as a cokernel rather than as a fixture.
            assert_eq!(Module::injective(&algebra, 1).dim_vector(), [1, 1, 0]);

            let vertex_a = pair_of(&algebra, &[&p0, &s0, &p2], &[]);
            let vertex_b = pair_of(&algebra, &[&p0, &p1, &p2], &[]);
            let vertex_h = pair_of(&algebra, &[&s0, &p2], &[1]);
            let vertex_k = pair_of(&algebra, &[&p2], &[0, 1]);
            let vertex_m = pair_of(&algebra, &[&s0], &[1, 2]);

            let b_at_p2 = left(&vertex_b, &[0, 0, 1]);
            assert_target(&b_at_p2, &[&[1, 1, 1], &[0, 1, 1], &[0, 1, 0]], &[]);
            assert_eq!(
                *b_at_p2.shape(),
                ExchangeShape::ReplacedByModule { multiplicity: 1 }
            );

            let b_at_p1 = left(&vertex_b, &[0, 1, 1]);
            assert_target(&b_at_p1, &[&[1, 1, 1], &[0, 0, 1], &[1, 0, 0]], &[]);

            let b_at_p0 = left(&vertex_b, &[1, 1, 1]);
            assert_target(&b_at_p0, &[&[0, 1, 1], &[0, 0, 1]], &[0]);
            assert_eq!(
                *b_at_p0.shape(),
                ExchangeShape::MovesToProjective { vertex: 0 }
            );

            let a_at_p2 = left(&vertex_a, &[0, 0, 1]);
            assert_target(&a_at_p2, &[&[1, 1, 1], &[1, 0, 0], &[1, 1, 0]], &[]);

            let fac = no_left(&vertex_a, &[1, 0, 0]);
            assert_eq!(fac.image_dims(), [1, 0, 0]);

            let a_at_p0 = left(&vertex_a, &[1, 1, 1]);
            assert_target(&a_at_p0, &[&[1, 0, 0], &[0, 0, 1]], &[1]);
            assert_eq!(
                *a_at_p0.shape(),
                ExchangeShape::MovesToProjective { vertex: 1 }
            );

            let h_at_p2 = left(&vertex_h, &[0, 0, 1]);
            assert_target(&h_at_p2, &[&[1, 0, 0]], &[1, 2]);

            let h_at_s0 = left(&vertex_h, &[1, 0, 0]);
            assert_target(&h_at_s0, &[&[0, 0, 1]], &[0, 1]);

            let k_at_p2 = left(&vertex_k, &[0, 0, 1]);
            assert_target(&k_at_p2, &[], &[0, 1, 2]);

            let m_at_s0 = left(&vertex_m, &[1, 0, 0]);
            assert_target(&m_at_s0, &[], &[0, 1, 2]);
        }
    }

    // `(A, 0)` is the maximum of the order, so no slot of it can be a right
    // mutation. Concretely: dropping P_j leaves U = sum of the other
    // projectives, every quotient of a sum of copies of U has top a sum of the
    // simples S_v with v not j, and top P_j = S_j, so P_j is outside Fac U.
    // The argument uses no property of the algebra, so it holds on both
    // fixtures.
    #[test]
    fn every_slot_of_the_regular_pair_mutates() {
        for field in fields() {
            for algebra in [linear_an(3, field), d4(field)] {
                let pair = regular_pair(&algebra);
                assert_eq!(pair.module().len(), pair.summand_count());
                for slot in 0..pair.module().len() {
                    let outcome = mutate_at(&pair, slot).expect("the regular pair mutates");
                    let mutation = match outcome {
                        SlotOutcome::LeftMutation(mutation) => *mutation,
                        SlotOutcome::NoLeftMutation(_) => {
                            panic!("slot {slot} of the regular pair has a left mutation")
                        }
                    };
                    assert!(mutation.witness().verify());
                    assert!(mutation.target().verify());
                }
            }
        }
    }

    // k[x]/(x^3) has one vertex and two pairs, `(A, 0)` and `(0, A)`. The one
    // slot drops the only summand, leaving U = 0 with empty support, so vertex
    // 0 moves to the projective part.
    #[test]
    fn truncated_poly_3_has_one_slot_to_the_zero_pair() {
        for field in fields() {
            let algebra = truncated_poly(3, field).expect("x^3 is admissible");
            let pair = regular_pair(&algebra);
            assert_eq!(pair.module().len(), 1);
            let mutation = left(&pair, &[3]);
            assert_target(&mutation, &[], &[0]);
            assert_eq!(
                *mutation.shape(),
                ExchangeShape::MovesToProjective { vertex: 0 }
            );
            assert!(mutation.target().module().is_empty());
        }
    }

    // One cache across several mutations answers repeated translates from the
    // store. The hit count rising is what shows the cache is shared rather
    // than rebuilt per call.
    #[test]
    fn one_cache_serves_several_mutations() {
        let algebra = linear_an(3, f5());
        let pair = regular_pair(&algebra);
        let indices: Vec<usize> = (0..pair.module().len()).collect();
        let mut cache = TauCache::new();
        let mut hits = Vec::new();
        for slot in 0..pair.module().len() {
            let outcome = mutate_at_with_cache(
                &pair,
                slot,
                &indices,
                indices.len() + slot,
                Some(&mut cache),
            )
            .expect("the regular pair mutates");
            assert!(outcome.is_left_mutation());
            hits.push(cache.hits());
        }
        assert!(hits[0] > 0, "the first call already reuses a translate");
        assert!(
            hits[2] > hits[0],
            "later calls keep hitting the shared store, got {hits:?}"
        );
        assert!(cache.misses() > 0);
    }

    // A witness whose target is another slot's target, which is a valid pair
    // in its own right. The stored almost complete pair no longer sits inside
    // it, so the extension check fails.
    #[test]
    fn a_swapped_target_fails_verification() {
        let algebra = linear_an(2, f2());
        let p0 = Module::projective(&algebra, 0);
        let p1 = Module::projective(&algebra, 1);
        let pair = pair_of(&algebra, &[&p0, &p1], &[]);

        let at_p0 = left(&pair, &[1, 1]);
        let at_p1 = left(&pair, &[0, 1]);
        let mut tampered = at_p0.witness;
        tampered.target_module = at_p1.witness.target_module.clone();
        tampered.target_projective = at_p1.witness.target_projective.clone();
        assert!(!tampered.verify());
    }

    // An approximation borrowed from the other slot of the same pair. It
    // starts at the wrong summand, which the witness catches before it
    // recomputes the exchange sequence.
    #[test]
    fn a_borrowed_approximation_fails_verification() {
        let algebra = linear_an(2, f2());
        let p0 = Module::projective(&algebra, 0);
        let p1 = Module::projective(&algebra, 1);
        let pair = pair_of(&algebra, &[&p0, &p1], &[]);

        let at_p0 = left(&pair, &[1, 1]);
        let at_p1 = left(&pair, &[0, 1]);
        let mut tampered = at_p1.witness;
        tampered.approximation = at_p0.witness.approximation;
        assert!(!tampered.verify());
    }

    // A witness whose target is the source pair, with the matching extension
    // witness moved over so that the add-closure checks pass. What is left is
    // the check that the two completions differ, and it fails: AIR Theorem
    // 2.18 gives two completions, not one taken twice.
    #[test]
    fn a_target_equal_to_the_source_fails_verification() {
        let algebra = linear_an(2, f2());
        let p0 = Module::projective(&algebra, 0);
        let p1 = Module::projective(&algebra, 1);
        let pair = pair_of(&algebra, &[&p0, &p1], &[]);

        let mut tampered = left(&pair, &[0, 1]).witness;
        tampered.target_module = tampered.source_module.clone();
        tampered.target_projective = tampered.source_projective.clone();
        tampered.target_extension = tampered.source_extension.clone();
        assert!(!tampered.verify());
    }

    // A Fac witness that lost a map. The remaining images no longer cover
    // X_j, which is the rank equality the witness exists to prove.
    #[test]
    fn a_truncated_fac_witness_fails_verification() {
        let algebra = linear_an(2, f2());
        let p0 = Module::projective(&algebra, 0);
        let s0 = Module::simple(&algebra, 0);
        let pair = pair_of(&algebra, &[&p0, &s0], &[]);

        let mut witness = no_left(&pair, &[1, 0]);
        assert!(witness.verify());
        witness.maps.pop();
        assert!(!witness.verify());
    }

    // A Fac witness whose summand list is not a decomposition of its stored
    // U. The rank equality is proved over U, so a caller reading the summand
    // list has to know it belongs to that U, and only the direct-sum check
    // says so.
    #[test]
    fn a_fac_witness_whose_summands_miss_u_fails_verification() {
        // Vertex A of the linear_an(3) table above. S_0 is the top of P_0, so
        // it lies in Fac(P_0 + P_2) and slot S_0 has no left mutation.
        let algebra = linear_an(3, f2());
        let p0 = Module::projective(&algebra, 0);
        let p2 = Module::projective(&algebra, 2);
        let s0 = Module::simple(&algebra, 0);
        let pair = pair_of(&algebra, &[&p0, &s0, &p2], &[]);

        let mut witness = no_left(&pair, &[1, 0, 0]);
        assert_eq!(witness.summands().len(), 2);
        witness.summands.pop();
        assert!(!witness.verify());
    }

    // A mutation carrying another slot's target pair. Both halves still pass
    // on their own, so only the binding between them catches the swap.
    #[test]
    fn a_mutation_with_another_slot_target_fails_verification() {
        let algebra = linear_an(2, f2());
        let p0 = Module::projective(&algebra, 0);
        let p1 = Module::projective(&algebra, 1);
        let pair = pair_of(&algebra, &[&p0, &p1], &[]);

        let mut at_p0 = left(&pair, &[1, 1]);
        let at_p1 = left(&pair, &[0, 1]);
        at_p0.target = at_p1.target;
        assert!(at_p0.witness.verify());
        assert!(at_p0.target.verify());
        assert!(!at_p0.verify());
    }

    // A witness proves a statement about one slot, so relabelling the
    // mutation must not survive verification. Both halves still pass alone.
    #[test]
    fn a_mutation_relabelled_to_another_slot_fails_verification() {
        let algebra = linear_an(2, f2());
        let p0 = Module::projective(&algebra, 0);
        let p1 = Module::projective(&algebra, 1);
        let pair = pair_of(&algebra, &[&p0, &p1], &[]);

        let mut at_p0 = left(&pair, &[1, 1]);
        let other = left(&pair, &[0, 1]);
        assert_ne!(at_p0.slot, other.slot, "the two slots must differ");
        at_p0.slot = other.slot;
        assert!(at_p0.witness.verify());
        assert!(at_p0.target.verify());
        assert!(!at_p0.verify());
    }

    // Every mutation of the A_2 pentagon leaves the source pair usable, since
    // mutate_at takes it by reference and builds fresh modules for the target.
    #[test]
    fn the_source_pair_survives_a_mutation() {
        let algebra = linear_an(2, f5());
        let p0 = Module::projective(&algebra, 0);
        let p1 = Module::projective(&algebra, 1);
        let pair = pair_of(&algebra, &[&p0, &p1], &[]);
        let _ = left(&pair, &[1, 1]);
        assert!(pair.verify());
    }
}