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
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
//! Ext groups over minimal resolutions: dimensions, global dimension,
//! [`ExtSpace`] and [`ExtClass`] as explicit vector space data, and Yoneda
//! products with their chain-lift witnesses.
//!
//! `Ext^k(M, N)` is the cohomology of `Hom_A(P_*, N)` for a projective
//! resolution `P_* -> M`. Every term built by
//! [`projective_cover`](crate::resolution::projective_cover) is a sum
//! `(+)_v P_v^{t_v}` in a canonical layout, and Yoneda identifies
//! `Hom_A(e_v A, N)` with `N_v`. So `Hom_A(P, N)` has an explicit basis indexed
//! by (generator, basis vector of `N` at the generator's vertex). The element
//! for generator `g` at `v` and index `j` sends the summand basis path
//! `p: v -> w` to row `j` of `N(p)`. Coordinates of a morphism in this basis are
//! its generator rows, read off directly. No linear system is solved.
//!
//! Sign convention: the induced cochain map is `delta^k(f) = d_{k+1}.then(f)`,
//! with no signs. Alternating signs exist to force `delta^2 = 0` under other
//! conventions for the differential; here it follows from `d^2 = 0`. A sign
//! choice rescales basis vectors and leaves every rank alone, so no dimension
//! depends on it.
//!
//! Exactness: [`ext_dim`]`(m, n, k)` resolves `m` for `k + 1` steps. The result
//! is either a complete finite resolution or a prefix with differentials
//! `d_1, ..., d_{k+1}`. Cohomology at position `k` needs only `d_k` and
//! `d_{k+1}`, so the answer is exact for every `k`, even when the projective
//! dimension is unknown.

use std::sync::Arc;

use crate::algebra::Algebra;
use crate::field::Fp;
use crate::hom::Morphism;
use crate::homspace::{
    deterministic_complement, row_times, rref_coords, rref_coords_many, stack_rows,
};
use crate::linalg::DenseMat;
use crate::module::{Module, same_morphism_data, same_representation, same_slice};
use crate::radical::top;
use crate::resolution::{Bounded, ProjectiveResolution, projective_dimension, resolve};

/// Rejected Ext input.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExtError {
    /// The modules live over different algebras (distinct [`Arc`]s).
    DifferentAlgebras,
}

display_error! { error ExtError {
    Self::DifferentAlgebras => "modules live over different algebras";
} }

/// Summand layout of a projective term `(+)_v P_v^{t_v}` built by
/// [`projective_cover`](crate::resolution::projective_cover): generators are
/// ordered by vertex, then by copy. At each vertex the term's basis is the
/// concatenation of the summands' path bases in generator order.
struct Layout {
    /// Vertex of each generator, in canonical order.
    gen_vertex: Vec<u32>,
    /// `offsets[w][g]`: first row of generator `g`'s block in the term at vertex `w`.
    offsets: Vec<Vec<usize>>,
}

/// Recovers the layout from the term alone: `t_v = dim (top P)_v`, because
/// `top P_v = S_v`. The block-total assertion holds for every resolution term
/// and for the zero module; a failure means the term is not a canonical
/// projective sum, which is a bug in auslander.
fn layout(term: &Module) -> Layout {
    let algebra = term.algebra();
    let n = algebra.quiver().num_vertices();
    let (t, _) = top(term);
    let mut gen_vertex = Vec::new();
    for v in 0..n {
        for _ in 0..t.dim_at(v) {
            gen_vertex.push(v);
        }
    }
    let mut offsets = vec![Vec::with_capacity(gen_vertex.len()); n as usize];
    for w in 0..n {
        let mut off = 0;
        for &v in &gen_vertex {
            offsets[w as usize].push(off);
            off += algebra.paths_between(v, w).len();
        }
        assert_eq!(
            off,
            term.dim_at(w),
            "resolution term is not a canonical projective sum at vertex {w}; \
             this is a bug in auslander"
        );
    }
    Layout {
        gen_vertex,
        offsets,
    }
}

/// `dim Hom_A(term, n)`, which by Yoneda is the sum of `dim N_{v_g}` over the
/// generators `g`.
fn hom_space_dim(lay: &Layout, n: &Module) -> usize {
    lay.gen_vertex.iter().map(|&v| n.dim_at(v)).sum()
}

/// The Yoneda basis of `Hom_A(term, n)`, in canonical (generator, index) order.
fn yoneda_basis(term: &Module, lay: &Layout, n: &Module) -> Vec<Morphism> {
    let algebra = term.algebra();
    let nv = algebra.quiver().num_vertices();
    let mut basis = Vec::new();
    for (g, &v) in lay.gen_vertex.iter().enumerate() {
        for j in 0..n.dim_at(v) {
            let mut maps: Vec<DenseMat> = (0..nv)
                .map(|w| DenseMat::zero(term.dim_at(w), n.dim_at(w)))
                .collect();
            for w in 0..nv {
                for (r, &b) in algebra.paths_between(v, w).iter().enumerate() {
                    let action = n
                        .word_action(&algebra.basis()[b])
                        .expect("algebra basis words are valid in their own quiver");
                    for c in 0..n.dim_at(w) {
                        maps[w as usize].set(lay.offsets[w as usize][g] + r, c, action.get(j, c));
                    }
                }
            }
            basis.push(Morphism::new(term, n, maps).expect("Yoneda basis element is A-linear"));
        }
    }
    basis
}

/// Coordinates of `f: term -> n` in the Yoneda basis: the trivial path `e_v` is
/// the first basis path of every `(v, v)` block, so the coordinate block of
/// generator `g` is row `offsets[v_g][g]` of `f` at `v_g`.
fn coordinates(f: &Morphism, lay: &Layout, n: &Module) -> Vec<Fp> {
    let mut coords = Vec::new();
    for (g, &v) in lay.gen_vertex.iter().enumerate() {
        let row = lay.offsets[v as usize][g];
        for j in 0..n.dim_at(v) {
            coords.push(f.map_at(v).get(row, j));
        }
    }
    coords
}

/// Rank of `delta^k: Hom(P_k, N) -> Hom(P_{k+1}, N)`, `f -> d.then(f)`, in the
/// Yoneda bases.
fn delta_rank(d: &Morphism, term: &Module, lay: &Layout, next_lay: &Layout, n: &Module) -> usize {
    let rows = delta_rows(d, term, lay, next_lay, n);
    if rows.is_empty() {
        return 0;
    }
    DenseMat::from_rows(&rows).into_rank(&term.field())
}

fn delta_rows(
    d: &Morphism,
    term: &Module,
    lay: &Layout,
    next_lay: &Layout,
    n: &Module,
) -> Vec<Vec<Fp>> {
    yoneda_basis(term, lay, n)
        .iter()
        .map(|f| {
            let composite = d
                .then(f)
                .expect("internal endpoint invariant: d targets the term f leaves");
            coordinates(&composite, next_lay, n)
        })
        .collect()
}

fn check_pair(m: &Module, n: &Module) -> Result<(), ExtError> {
    Arc::ptr_eq(m.algebra(), n.algebra())
        .then_some(())
        .ok_or(ExtError::DifferentAlgebras)
}

/// `[dim Ext^0(m, n), ..., dim Ext^max_k(m, n)]`, every entry exact because the
/// resolution prefix is always long enough (see the module docs). Errors when
/// the modules do not share one algebra.
pub fn ext_table(m: &Module, n: &Module, max_k: usize) -> Result<Vec<usize>, ExtError> {
    check_pair(m, n)?;
    let res = resolve(m, max_k + 1);
    let layouts: Vec<Layout> = res.terms.iter().map(layout).collect();
    // A finite resolution continues with zero terms: past its end, Hom is zero
    // and delta is zero.
    let h: Vec<usize> = (0..=max_k)
        .map(|i| layouts.get(i).map_or(0, |lay| hom_space_dim(lay, n)))
        .collect();
    let ranks: Vec<usize> = (0..=max_k)
        .map(|i| {
            if i + 1 < res.terms.len() {
                delta_rank(&res.maps[i], &res.terms[i], &layouts[i], &layouts[i + 1], n)
            } else {
                0
            }
        })
        .collect();
    Ok((0..=max_k)
        .map(|k| {
            let kernel_dim = h[k] - ranks[k];
            let boundary = if k == 0 { 0 } else { ranks[k - 1] };
            assert!(
                kernel_dim >= boundary,
                "im delta^{} is not contained in ker delta^{k}; this is a bug in auslander",
                k.wrapping_sub(1)
            );
            kernel_dim - boundary
        })
        .collect())
}

/// `dim Ext^k_A(m, n)`, exact for every `k`. `Ext^0` is `dim Hom_A(m, n)`.
/// Errors when the modules do not share one algebra.
pub fn ext_dim(m: &Module, n: &Module, k: usize) -> Result<usize, ExtError> {
    Ok(ext_table(m, n, k)?[k])
}

/// The global dimension of the algebra, resolved up to `bound` differentials.
///
/// For a finite-dimensional algebra `gldim A = pd (A/rad A) = max_v pd S_v`:
/// every module has a finite composition series with simple factors, so the
/// supremum of projective dimensions is attained on the simples. Returns
/// `Exact` when every simple resolves within `bound`, otherwise
/// `AtLeast(bound + 1)`, which says the minimal resolution of some simple still
/// has a nonzero syzygy past the bound.
///
/// The function does not fail: it builds the simples it resolves over the given
/// algebra itself, so no endpoint mismatch can arise.
pub fn global_dimension(algebra: &Arc<Algebra>, bound: usize) -> Bounded<usize> {
    let mut max = 0usize;
    let mut cut = false;
    for v in 0..algebra.quiver().num_vertices() {
        match projective_dimension(&Module::simple(algebra, v), bound) {
            Bounded::Exact(d) => max = max.max(d),
            Bounded::AtLeast(_) => cut = true,
        }
    }
    if cut {
        Bounded::AtLeast(bound + 1)
    } else {
        Bounded::Exact(max)
    }
}

/// The cochain morphism `term -> n` whose canonical coordinates are `coords`:
/// generator `g` at vertex `v` takes the coordinate block of length
/// `dim N_v`, and the basis path `p: v -> w` of its summand maps to that
/// block times `N(p)`.
///
/// # Panics
/// Panics unless `coords` has one entry per (generator, basis vector) pair.
fn cochain_from_coordinates(term: &Module, lay: &Layout, n: &Module, coords: &[Fp]) -> Morphism {
    let algebra = term.algebra();
    let field = term.field();
    let nv = algebra.quiver().num_vertices();
    let mut maps: Vec<DenseMat> = (0..nv)
        .map(|w| DenseMat::zero(term.dim_at(w), n.dim_at(w)))
        .collect();
    let mut offset = 0;
    for (g, &v) in lay.gen_vertex.iter().enumerate() {
        let block = &coords[offset..offset + n.dim_at(v)];
        offset += n.dim_at(v);
        for w in 0..nv {
            for (r, &b) in algebra.paths_between(v, w).iter().enumerate() {
                let action = n
                    .word_action(&algebra.basis()[b])
                    .expect("algebra basis words are valid in their own quiver");
                for c in 0..n.dim_at(w) {
                    let mut acc = Fp::ZERO;
                    for (j, &x) in block.iter().enumerate() {
                        acc = field.add(acc, field.mul(x, action.get(j, c)));
                    }
                    maps[w as usize].set(lay.offsets[w as usize][g] + r, c, acc);
                }
            }
        }
    }
    assert_eq!(
        offset,
        coords.len(),
        "coords needs one entry per (generator, basis vector) pair"
    );
    Morphism::new(term, n, maps).expect("generator images extend to an A-linear map")
}

/// The matrix of `delta: Hom(term, N) -> Hom(next, N)`, `f -> d.then(f)`, in
/// Yoneda bases: one row per basis element of the source cochain space.
fn delta_matrix(
    d: &Morphism,
    term: &Module,
    lay: &Layout,
    next_lay: &Layout,
    n: &Module,
) -> DenseMat {
    let rows = delta_rows(d, term, lay, next_lay, n);
    DenseMat::from_rows_with_cols(&rows, hom_space_dim(next_lay, n))
}

/// The lift `phi: term -> T` with `phi.then(through) = rhs`, for `through: T -> B`
/// and `rhs: term -> B` with `term` a canonical projective sum. Every generator
/// image solves with free variables zeroed, so the lift is deterministic.
///
/// All generators at one vertex solve against the same `through` matrix, so
/// they are grouped by vertex and one [`DenseMat::solve_many`] per vertex
/// replaces one `solve` per generator.
///
/// # Panics
/// Panics when a generator image of `rhs` lies outside the image of `through`;
/// callers only lift maps that land there.
pub(crate) fn lift_through(term: &Module, through: &Morphism, rhs: &Morphism) -> Morphism {
    debug_assert!(rhs.source().ptr_eq(term));
    debug_assert!(rhs.target().ptr_eq(through.target()));
    let field = term.field();
    let lay = layout(term);
    let vertices = term.algebra().quiver().num_vertices() as usize;
    let mut at_vertex: Vec<Vec<usize>> = vec![Vec::new(); vertices];
    for (g, &v) in lay.gen_vertex.iter().enumerate() {
        at_vertex[v as usize].push(g);
    }
    // Column `j` of `solved[v]` is the image of the `j`-th generator at `v`,
    // generators in index order.
    let solved: Vec<DenseMat> = (0..vertices)
        .map(|v| {
            let rows: Vec<Vec<Fp>> = at_vertex[v]
                .iter()
                .map(|&g| rhs.map_at(v as u32).row(lay.offsets[v][g]).to_vec())
                .collect();
            if rows.is_empty() {
                return DenseMat::zero(through.source().dim_at(v as u32), 0);
            }
            through
                .map_at(v as u32)
                .transpose()
                .solve_many(&DenseMat::from_rows(&rows).transpose(), &field)
                .expect("lift_through: the right side lands in the image of the lifted-through map")
        })
        .collect();
    let mut taken = vec![0usize; vertices];
    let mut coords = Vec::new();
    for &v in &lay.gen_vertex {
        let x = &solved[v as usize];
        let j = taken[v as usize];
        taken[v as usize] += 1;
        coords.extend((0..x.rows()).map(|i| x.get(i, j)));
    }
    cochain_from_coordinates(term, &lay, through.source(), &coords)
}

fn chain_terms(
    resolution: &ProjectiveResolution,
    start: usize,
    end: usize,
    terminal: &Module,
    algebra: &Arc<Algebra>,
) -> Vec<Module> {
    (start..=end)
        .map(|degree| {
            resolution
                .terms
                .get(degree)
                .cloned()
                .or_else(|| (degree == end).then(|| terminal.clone()))
                .unwrap_or_else(|| Module::zero(algebra))
        })
        .collect()
}

fn chain_maps(
    resolution: &ProjectiveResolution,
    start: usize,
    count: usize,
    terms: &[Module],
) -> Vec<Morphism> {
    (0..count)
        .map(|i| {
            resolution.maps.get(start + i).cloned().unwrap_or_else(|| {
                crate::hom::zero_morphism(&terms[i + 1], &terms[i])
                    .expect("chain terms share one algebra")
            })
        })
        .collect()
}

/// Rejected Ext class input.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExtClassError {
    /// The operands' spaces are not compatible: compatibility needs
    /// pointer-equal sources, pointer-equal targets, and equal degrees.
    IncompatibleSpaces,
    /// The left class's target module is not the right class's source module
    /// (by [`Module::ptr_eq`]), so the Yoneda product is undefined.
    MiddleMismatch,
    /// The cochain's source is not the space's cochain term (by
    /// [`Module::ptr_eq`]).
    SourceMismatch,
    /// The cochain's target is not the space's target module (by
    /// [`Module::ptr_eq`]).
    TargetMismatch,
    /// The cochain is not a cocycle: `d_{k+1}.then(f)` is nonzero. The field
    /// holds the composite's coordinates in the degree `k + 1` cochain basis.
    NotCocycle { composite: Vec<Fp> },
    /// The coordinate vector's length is not the space's dimension.
    CoordinateCountMismatch { expected: usize, got: usize },
    /// The coordinate at this index is not a canonical element of the
    /// modules' field.
    NonCanonicalCoordinate { index: usize },
    /// The identity class lives only in `Ext^0(M, M)`: degree 0 with
    /// pointer-equal endpoints.
    NotDegreeZeroEndo,
    /// The left class's resolution prefix and the product space's prefix
    /// disagree at this degree, in the term or in the differential into it.
    /// Both come from [`resolve`] on the same module, so a disagreement is a
    /// crate defect, not bad input.
    ResolutionDisagreement { degree: usize },
}

display_error! { error ExtClassError {
    Self::IncompatibleSpaces => "the classes live in incompatible Ext spaces";
    Self::MiddleMismatch => "the left class's target module is not the right class's source module";
    Self::SourceMismatch => "the cochain's source is not the space's cochain term";
    Self::TargetMismatch => "the cochain's target is not the space's target module";
    Self::NotCocycle { .. } => "the cochain is not a cocycle";
    Self::CoordinateCountMismatch { expected, got } => "coordinate vector has {got} entries, the space has dimension {expected}";
    Self::NonCanonicalCoordinate { index } => "coordinate {index} is not a canonical element of the modules' field";
    Self::NotDegreeZeroEndo => "the identity class lives only in Ext^0(M, M)";
    Self::ResolutionDisagreement { degree } => "two resolutions of one module disagree at degree {degree}; crate defect";
} }

struct ExtSpaceInner {
    source: Module,
    target: Module,
    degree: usize,
    // resolve(source, degree + 1); minimal, so recomputation gives the same
    // matrices.
    resolution: ProjectiveResolution,
    // P_k, or the zero module when the finite resolution ends before k.
    term: Module,
    // RREF basis of Z^k = ker delta^k in generator-block coordinates.
    cocycles: DenseMat,
    // RREF basis of B^k = im delta^{k-1}; zero rows at degree 0.
    coboundaries: DenseMat,
    // Deterministic complement of B^k in Z^k.
    complement: DenseMat,
    // One cocycle morphism P_k -> N per complement row.
    reps: Vec<Morphism>,
}

/// `Ext^k(M, N)` as an explicit vector space: the resolution prefix, RREF
/// cocycle and coboundary bases in generator-block coordinates, the
/// deterministic complement of the coboundaries inside the cocycles, and one
/// representative cocycle per complement row.
///
/// Two spaces are compatible when their sources are [`Module::ptr_eq`], their
/// targets are [`Module::ptr_eq`], and their degrees are equal. Every stored
/// matrix is deterministic, so recomputed compatible spaces carry identical
/// bases and class coordinates transport verbatim.
///
/// Cloning is cheap (a reference count bump).
#[derive(Clone)]
pub struct ExtSpace(Arc<ExtSpaceInner>);

debug_fields!(ExtSpace |this| {
    "source_dim" => this.0.source.dim_vector();
    "target_dim" => this.0.target.dim_vector();
    "degree" => this.0.degree;
    "dim" => this.dim();
});

impl ExtSpace {
    /// Builds `Ext^k(m, n)` from the minimal resolution prefix
    /// `resolve(m, k + 1)`. Zero modules give zero spaces. A finite resolution
    /// that ends before degree `k` gives the zero space with the zero module
    /// as cochain term. Errors when the modules do not share one algebra.
    pub fn new(m: &Module, n: &Module, k: usize) -> Result<ExtSpace, ExtError> {
        check_pair(m, n)?;
        let field = m.field();
        let resolution = resolve(m, k + 1);
        let (term, cocycles, coboundaries) = if k < resolution.terms.len() {
            let term = resolution.terms[k].clone();
            let lay = layout(&term);
            let width = hom_space_dim(&lay, n);
            let cocycles = if k + 1 < resolution.terms.len() {
                let next_lay = layout(&resolution.terms[k + 1]);
                let delta = delta_matrix(&resolution.maps[k], &term, &lay, &next_lay, n);
                delta.left_kernel_basis(&field).into_row_space_basis(&field)
            } else {
                DenseMat::identity(width)
            };
            let coboundaries = if k == 0 {
                DenseMat::zero(0, width)
            } else {
                let prev = &resolution.terms[k - 1];
                let prev_lay = layout(prev);
                delta_matrix(&resolution.maps[k - 1], prev, &prev_lay, &lay, n)
                    .into_row_space_basis(&field)
            };
            (term, cocycles, coboundaries)
        } else {
            (
                Module::zero(m.algebra()),
                DenseMat::zero(0, 0),
                DenseMat::zero(0, 0),
            )
        };
        assert!(
            rref_coords_many(&cocycles, &coboundaries, &field).is_some(),
            "im delta^{} is not contained in ker delta^{k}; this is a bug in auslander",
            k.wrapping_sub(1)
        );
        let complement = deterministic_complement(&cocycles, &coboundaries, &field);
        let lay = layout(&term);
        let reps = (0..complement.rows())
            .map(|r| cochain_from_coordinates(&term, &lay, n, complement.row(r)))
            .collect();
        Ok(ExtSpace(Arc::new(ExtSpaceInner {
            source: m.clone(),
            target: n.clone(),
            degree: k,
            resolution,
            term,
            cocycles,
            coboundaries,
            complement,
            reps,
        })))
    }

    accessor_methods! {
        /// `dim_Fp Ext^k(M, N)`: the number of complement rows. Equals
        /// [`ext_dim`]`(m, n, k)`.
        pub dim() -> usize = |this| this.0.complement.rows();
        /// The source module `M`.
        pub source() -> &Module = |this| &this.0.source;
        /// The target module `N`.
        pub target() -> &Module = |this| &this.0.target;
        /// The cohomological degree `k`.
        pub degree() -> usize = |this| this.0.degree;
        /// The source of degree-`k` cochains: `P_k` of the minimal resolution, or
        /// the zero module when the finite resolution ends before `k`.
        pub cochain_term() -> &Module = |this| &this.0.term;
        /// One representative cocycle `P_k -> N` per complement row, in row order.
        pub representatives() -> &[Morphism] = |this| &this.0.reps;
        /// The RREF basis of `Z^k = ker delta^k` in generator-block coordinates,
        /// one vector per row.
        pub cocycle_basis() -> &DenseMat = |this| &this.0.cocycles;
        /// The RREF basis of `B^k = im delta^{k-1}` in generator-block
        /// coordinates, one vector per row; no rows at degree 0.
        pub coboundary_basis() -> &DenseMat = |this| &this.0.coboundaries;
        /// The complement of `B^k` in `Z^k`, in scan order. Class coordinates
        /// index these rows.
        pub complement_basis() -> &DenseMat = |this| &this.0.complement;
        /// The stored resolution prefix `resolve(source, degree + 1)`.
        pub(crate) resolution() -> &ProjectiveResolution = |this| &this.0.resolution;
    }

    /// Whether class coordinates transport verbatim between the two spaces:
    /// sources pointer-equal, targets pointer-equal, degrees equal.
    pub fn is_compatible(&self, other: &ExtSpace) -> bool {
        self.0.source.ptr_eq(&other.0.source)
            && self.0.target.ptr_eq(&other.0.target)
            && self.0.degree == other.0.degree
    }

    /// Whether the two compatible spaces carry the same stored data: the
    /// resolution prefix term by term and differential by differential, the
    /// cochain term, the cocycle, coboundary and complement bases, and the
    /// representatives.
    ///
    /// Incompatible spaces are never equal. Terms and representatives are
    /// compared entry by entry, because a recomputed space owns fresh module
    /// values that no pointer test can match.
    pub fn matches(&self, other: &ExtSpace) -> bool {
        let (a, b) = (&*self.0, &*other.0);
        self.is_compatible(other)
            && a.resolution.agrees_with(&b.resolution)
            && same_representation(&a.term, &b.term)
            && a.cocycles == b.cocycles
            && a.coboundaries == b.coboundaries
            && a.complement == b.complement
            && same_slice(&a.reps, &b.reps, same_morphism_data)
    }

    /// Whether every stored matrix equals a fresh [`ExtSpace::new`] over the
    /// live endpoint modules, by [`ExtSpace::matches`].
    ///
    /// Rechecks that read this space (action matrices, socle, cocycle
    /// reduction) use the stored resolution and bases, so a tampered space
    /// would otherwise certify itself.
    pub fn matches_recomputation(&self) -> bool {
        let_or_false!(Ok(fresh) = ExtSpace::new(&self.0.source, &self.0.target, self.0.degree));
        self.matches(&fresh)
    }

    /// The zero class of this space.
    pub fn zero_class(&self) -> ExtClass {
        ExtClass {
            space: self.clone(),
            coords: vec![Fp::ZERO; self.dim()],
        }
    }

    /// The Yoneda unit: the class of the augmentation in `Ext^0(M, M)`.
    /// Errors unless the space has degree 0 and pointer-equal endpoints.
    pub fn identity_class(&self) -> Result<ExtClass, ExtClassError> {
        if self.0.degree != 0 || !self.0.source.ptr_eq(&self.0.target) {
            return Err(ExtClassError::NotDegreeZeroEndo);
        }
        self.class_from_cocycle(&self.0.resolution.augmentation)
    }

    /// The class of the cocycle `f: P_k -> N`: checks both endpoints by
    /// [`Module::ptr_eq`], checks `d_{k+1}.then(f) = 0`, then reduces modulo
    /// `B^k` by solving `f` against the complement rows stacked above the
    /// coboundary basis and keeping the complement part.
    pub fn class_from_cocycle(&self, f: &Morphism) -> Result<ExtClass, ExtClassError> {
        let inner = &self.0;
        if !f.source().ptr_eq(&inner.term) {
            return Err(ExtClassError::SourceMismatch);
        }
        if !f.target().ptr_eq(&inner.target) {
            return Err(ExtClassError::TargetMismatch);
        }
        let field = inner.source.field();
        if inner.degree + 1 < inner.resolution.terms.len() {
            let composite = inner.resolution.maps[inner.degree]
                .then(f)
                .expect("d_{k+1} targets the cochain term");
            if !composite.is_zero() {
                let next_lay = layout(&inner.resolution.terms[inner.degree + 1]);
                return Err(ExtClassError::NotCocycle {
                    composite: coordinates(&composite, &next_lay, &inner.target),
                });
            }
        }
        let lay = layout(&inner.term);
        let f_coords = coordinates(f, &lay, &inner.target);
        let stacked = stack_rows(
            &[&inner.complement, &inner.coboundaries],
            inner.complement.cols(),
        );
        let x = stacked
            .transpose()
            .solve(&f_coords, &field)
            .expect("a cocycle lies in the span of the complement plus the coboundaries; this is a bug in auslander");
        Ok(ExtClass {
            space: self.clone(),
            coords: x[..inner.complement.rows()].to_vec(),
        })
    }

    /// A copy of the space with the three stored bases replaced and the
    /// representatives rebuilt from the new complement.
    ///
    /// Test helper for the mutation corpus: the result is an `ExtSpace` value
    /// that no constructor would produce, so [`ExtSpace::matches_recomputation`]
    /// must reject it.
    #[cfg(test)]
    pub(crate) fn with_bases(
        &self,
        cocycles: DenseMat,
        coboundaries: DenseMat,
        complement: DenseMat,
    ) -> ExtSpace {
        let inner = &self.0;
        let lay = layout(&inner.term);
        let reps = (0..complement.rows())
            .map(|r| cochain_from_coordinates(&inner.term, &lay, &inner.target, complement.row(r)))
            .collect();
        self.with_parts(cocycles, coboundaries, complement, reps)
    }

    /// A copy of the space with the representatives replaced and every basis
    /// kept. Test helper for the mutation corpus, as [`ExtSpace::with_bases`].
    #[cfg(test)]
    pub(crate) fn with_representatives(&self, reps: Vec<Morphism>) -> ExtSpace {
        let inner = &self.0;
        self.with_parts(
            inner.cocycles.clone(),
            inner.coboundaries.clone(),
            inner.complement.clone(),
            reps,
        )
    }

    #[cfg(test)]
    fn with_parts(
        &self,
        cocycles: DenseMat,
        coboundaries: DenseMat,
        complement: DenseMat,
        reps: Vec<Morphism>,
    ) -> ExtSpace {
        let inner = &self.0;
        ExtSpace(Arc::new(ExtSpaceInner {
            source: inner.source.clone(),
            target: inner.target.clone(),
            degree: inner.degree,
            resolution: ProjectiveResolution {
                terms: inner.resolution.terms.clone(),
                maps: inner.resolution.maps.clone(),
                augmentation: inner.resolution.augmentation.clone(),
                end: inner.resolution.end,
            },
            term: inner.term.clone(),
            cocycles,
            coboundaries,
            complement,
            reps,
        }))
    }

    /// The class with the given coordinates over the complement basis.
    /// Errors on a wrong length and on entries that are not canonical
    /// elements of the modules' field.
    pub fn class_from_coordinates(&self, coords: &[Fp]) -> Result<ExtClass, ExtClassError> {
        if coords.len() != self.dim() {
            return Err(ExtClassError::CoordinateCountMismatch {
                expected: self.dim(),
                got: coords.len(),
            });
        }
        let modulus = self.0.source.field().modulus();
        if let Some(index) = coords.iter().position(|c| c.raw() >= modulus) {
            return Err(ExtClassError::NonCanonicalCoordinate { index });
        }
        Ok(ExtClass {
            space: self.clone(),
            coords: coords.to_vec(),
        })
    }
}

/// An element of an [`ExtSpace`]: coordinates over the complement basis.
///
/// Equality and arithmetic require compatible spaces (see
/// [`ExtSpace::is_compatible`]); incompatible operands are a typed
/// [`ExtClassError`], never `false`.
#[derive(Clone, Debug)]
pub struct ExtClass {
    space: ExtSpace,
    coords: Vec<Fp>,
}

impl ExtClass {
    accessor_methods! {
        /// The space the class lives in.
        pub space() -> &ExtSpace = |this| &this.space;
        /// The coordinates over the complement basis.
        pub coordinates() -> &[Fp] = |this| &this.coords;
    }

    /// Whether every coordinate is zero.
    pub fn is_zero(&self) -> bool {
        self.coords.iter().all(|c| c.is_zero())
    }

    fn with_coordinates(&self, coords: Vec<Fp>) -> ExtClass {
        ExtClass {
            space: self.space.clone(),
            coords,
        }
    }

    fn require_compatible(&self, other: &ExtClass) -> Result<(), ExtClassError> {
        self.space
            .is_compatible(&other.space)
            .then_some(())
            .ok_or(ExtClassError::IncompatibleSpaces)
    }

    /// The sum of two classes. Errors unless the spaces are compatible.
    pub fn add(&self, other: &ExtClass) -> Result<ExtClass, ExtClassError> {
        self.require_compatible(other)?;
        let field = self.space.0.source.field();
        let coords = self
            .coords
            .iter()
            .zip(&other.coords)
            .map(|(&a, &b)| field.add(a, b))
            .collect();
        Ok(self.with_coordinates(coords))
    }

    /// The additive inverse.
    pub fn neg(&self) -> ExtClass {
        let field = self.space.0.source.field();
        self.with_coordinates(self.coords.iter().map(|&c| field.neg(c)).collect())
    }

    /// The scalar multiple. The scalar must be a canonical element of the
    /// modules' field.
    pub fn scale(&self, c: Fp) -> ExtClass {
        let field = self.space.0.source.field();
        self.with_coordinates(self.coords.iter().map(|&x| field.mul(c, x)).collect())
    }

    /// Whether the classes are equal. Errors unless the spaces are
    /// compatible, so incompatible operands never read as unequal.
    pub fn equals(&self, other: &ExtClass) -> Result<bool, ExtClassError> {
        self.require_compatible(other)?;
        Ok(self.coords == other.coords)
    }

    /// The representative cocycle `P_k -> N`: the complement-row combination
    /// of the coordinates.
    pub fn representative(&self) -> Morphism {
        let inner = &self.space.0;
        let field = inner.source.field();
        let row = row_times(&self.coords, &inner.complement, &field);
        let lay = layout(&inner.term);
        cochain_from_coordinates(&inner.term, &lay, &inner.target, &row)
    }

    /// The Yoneda product `Ext^m(M, N) x Ext^n(N, L) -> Ext^{m+n}(M, L)`,
    /// matching the endpoint order of [`Morphism::then`]. Errors when the
    /// middle modules disagree (by [`Module::ptr_eq`]).
    ///
    /// Each call builds the product space. To multiply many classes into one
    /// space, build it once and use [`ExtClass::then_in`].
    pub fn then(&self, other: &ExtClass) -> Result<ExtClass, ExtClassError> {
        self.then_with_witness(other).map(|(class, _)| class)
    }

    /// The Yoneda product together with the chain lifts that computed it.
    /// Errors when the middle modules disagree (by [`Module::ptr_eq`]).
    pub fn then_with_witness(
        &self,
        other: &ExtClass,
    ) -> Result<(ExtClass, ProductWitness), ExtClassError> {
        let product_space = self.product_space(other)?;
        self.then_with_witness_in(other, &product_space)
    }

    /// The Yoneda product reduced in `product_space` instead of a fresh one.
    ///
    /// `product_space` must be `Ext^{m+n}(M, L)` for the endpoints of the two
    /// factors: source pointer-equal to this class's source, target
    /// pointer-equal to `other`'s target, degree the sum. A space that fails
    /// any of those is [`ExtClassError::IncompatibleSpaces`]. Recomputed
    /// compatible spaces carry identical bases, so the coordinates are the
    /// ones [`ExtClass::then`] returns.
    pub fn then_in(
        &self,
        other: &ExtClass,
        product_space: &ExtSpace,
    ) -> Result<ExtClass, ExtClassError> {
        self.then_with_witness_in(other, product_space)
            .map(|(class, _)| class)
    }

    /// [`ExtClass::then_in`] with the chain lifts that computed the product.
    pub fn then_with_witness_in(
        &self,
        other: &ExtClass,
        product_space: &ExtSpace,
    ) -> Result<(ExtClass, ProductWitness), ExtClassError> {
        if !self.space.0.target.ptr_eq(&other.space.0.source) {
            return Err(ExtClassError::MiddleMismatch);
        }
        let n = other.space.0.degree;
        if !product_space.0.source.ptr_eq(&self.space.0.source)
            || !product_space.0.target.ptr_eq(&other.space.0.target)
            || product_space.0.degree != self.space.0.degree + n
        {
            return Err(ExtClassError::IncompatibleSpaces);
        }
        let lifts = chain_lifts(self, other, product_space)?;
        let g = other.representative();
        let h = lifts[n]
            .then(&g)
            .expect("the last lift targets the right class's cochain term");
        let class = product_space
            .class_from_cocycle(&h)
            .expect("a Yoneda product of cocycles is a cocycle");
        Ok((class, ProductWitness { lifts }))
    }

    /// `Ext^{m+n}(M, L)` for the two factors. Errors when the middle modules
    /// disagree (by [`Module::ptr_eq`]).
    pub fn product_space(&self, other: &ExtClass) -> Result<ExtSpace, ExtClassError> {
        if !self.space.0.target.ptr_eq(&other.space.0.source) {
            return Err(ExtClassError::MiddleMismatch);
        }
        Ok(ExtSpace::new(
            &self.space.0.source,
            &other.space.0.target,
            self.space.0.degree + other.space.0.degree,
        )
        .expect("the product endpoints share one algebra through the middle module"))
    }
}

/// The chain lifts `phi_0, ..., phi_n` with `phi_i: P^M_{m+i} -> P^N_i`,
/// `phi_0.then(aug_N) = f` for `f` the representative of `alpha`, and
/// `d^M_{m+i+1}.then(phi_i) = phi_{i+1}.then(d^N_{i+1})` for `0 <= i < n`.
///
/// Both chains are extended by zero modules and zero maps past the end of a
/// finite resolution. Every lift solves per-generator systems with free
/// variables zeroed, so the family is deterministic.
fn chain_lifts(
    alpha: &ExtClass,
    beta: &ExtClass,
    product_space: &ExtSpace,
) -> Result<Vec<Morphism>, ExtClassError> {
    let m = alpha.space.0.degree;
    let n = beta.space.0.degree;
    let deep = &product_space.0.resolution;
    // Both prefixes come from `resolve` on the same module, so they must
    // agree term by term. The lifts below transport the representative onto
    // `deep.terms[m]` and would build a morphism over the wrong actions if
    // they did not, so the disagreement is reported, not asserted away.
    let own = &alpha.space.0.resolution;
    for (degree, (x, y)) in own.terms.iter().zip(&deep.terms).enumerate() {
        if !same_representation(x, y) {
            return Err(ExtClassError::ResolutionDisagreement { degree });
        }
    }
    for (k, (x, y)) in own.maps.iter().zip(&deep.maps).enumerate() {
        if !same_morphism_data(x, y) {
            return Err(ExtClassError::ResolutionDisagreement { degree: k + 1 });
        }
    }
    let algebra = alpha.space.0.source.algebra();
    let chain_m = chain_terms(deep, m, m + n, &product_space.0.term, algebra);
    let chain_dm = chain_maps(deep, m, n, &chain_m);
    let res_n = &beta.space.0.resolution;
    let chain_n = chain_terms(res_n, 0, n, &beta.space.0.term, algebra);
    let chain_dn = chain_maps(res_n, 0, n, &chain_n);
    let rep = alpha.representative();
    let nv = algebra.quiver().num_vertices();
    let rep_maps: Vec<DenseMat> = (0..nv).map(|v| rep.map_at(v).clone()).collect();
    let f = Morphism::new(&chain_m[0], &beta.space.0.source, rep_maps)
        .expect("the compared resolution prefix matches, so the representative transports");
    let mut lifts = vec![lift_through(&chain_m[0], &res_n.augmentation, &f)];
    for i in 1..=n {
        let rhs = chain_dm[i - 1]
            .then(&lifts[i - 1])
            .expect("chain endpoints line up by construction");
        lifts.push(lift_through(&chain_m[i], &chain_dn[i - 1], &rhs));
    }
    Ok(lifts)
}

/// The chain lifts behind one Yoneda product, `phi_i: P^M_{m+i} -> P^N_i` in
/// degree order.
#[derive(Clone, Debug)]
pub struct ProductWitness {
    lifts: Vec<Morphism>,
}

impl ProductWitness {
    accessor_methods! {
        /// The lifts in degree order, `phi_0` first.
        pub lifts() -> &[Morphism] = |this| &this.lifts;
    }

    /// Rechecks that the lifts tie `alpha` and `beta` to `product`.
    ///
    /// The product space is recomputed from the live endpoint modules and
    /// compared by [`ExtSpace::matches`]. The two factor spaces are
    /// not rechecked: their bases fix what `alpha.representative()` and
    /// `beta.representative()` mean. [`ExtSpace::matches_recomputation`] is
    /// the check for a factor.
    ///
    /// The remaining checks are the two lift identity families and the
    /// reduction of `phi_n.then(g)` to the product coordinates, by
    /// multiplication and coboundary membership. Membership alone is not
    /// enough: on the fixtures here the raw product cocycle already lies in
    /// the complement span, so a tampered coboundary basis still passes the
    /// membership solve and only the space comparison rejects it.
    pub fn verify(&self, alpha: &ExtClass, beta: &ExtClass, product: &ExtClass) -> bool {
        let inner = &product.space.0;
        let_or_false!(Ok(fresh) = ExtSpace::new(&inner.source, &inner.target, inner.degree));
        self.verify_against(alpha, beta, product, &fresh)
    }

    /// [`ProductWitness::verify`] with the product space's recomputation
    /// supplied by the caller.
    ///
    /// `recomputed` must be a fresh [`ExtSpace::new`] over the product
    /// endpoints. This method compares it against `product.space()` with
    /// [`ExtSpace::matches`]. Pass a space already built when verifying many
    /// products in one space.
    pub fn verify_against(
        &self,
        alpha: &ExtClass,
        beta: &ExtClass,
        product: &ExtClass,
        recomputed: &ExtSpace,
    ) -> bool {
        let m = alpha.space.0.degree;
        let n = beta.space.0.degree;
        verify_guard!(
            product.space.0.degree == m + n
                && beta.space.0.source.ptr_eq(&alpha.space.0.target)
                && product.space.0.source.ptr_eq(&alpha.space.0.source)
                && product.space.0.target.ptr_eq(&beta.space.0.target)
                && self.lifts.len() == n + 1
                && product.coords.len() == product.space.dim()
                && product.space.matches(recomputed)
        );
        let deep = &product.space.0.resolution;
        let res_n = &beta.space.0.resolution;
        let field = alpha.space.0.source.field();
        let algebra = alpha.space.0.source.algebra();
        let nv = algebra.quiver().num_vertices();
        let rep = alpha.representative();
        let rep_maps: Vec<DenseMat> = (0..nv).map(|v| rep.map_at(v).clone()).collect();
        let_or_false!(
            Ok(f) = Morphism::new(self.lifts[0].source(), &beta.space.0.source, rep_maps)
        );
        let_or_false!(Ok(lhs) = self.lifts[0].then(&res_n.augmentation));
        verify_guard!(lhs == f);
        let terms_m = chain_terms(deep, m, m + n, &product.space.0.term, algebra);
        let maps_m = chain_maps(deep, m, n, &terms_m);
        let terms_n = chain_terms(res_n, 0, n, &beta.space.0.term, algebra);
        let maps_n = chain_maps(res_n, 0, n, &terms_n);
        verify_guard!(
            maps_m
                .iter()
                .zip(&self.lifts)
                .zip(self.lifts.iter().skip(1).zip(&maps_n))
                .all(|((left, lift), (next_lift, right))| {
                    matches!(
                        (left.then(lift), next_lift.then(right)),
                        (Ok(left), Ok(right)) if left == right
                    )
                })
        );
        let g = beta.representative();
        let_or_false!(Ok(h) = self.lifts[n].then(&g));
        verify_guard!(h.source().ptr_eq(&product.space.0.term));
        let lay = layout(&product.space.0.term);
        let h_coords = coordinates(&h, &lay, &product.space.0.target);
        let expected = row_times(&product.coords, &product.space.0.complement, &field);
        let diff: Vec<Fp> = h_coords
            .iter()
            .zip(&expected)
            .map(|(&a, &b)| field.sub(a, b))
            .collect();
        // The space matched its recomputation above, so its coboundary basis
        // is RREF and the membership solve reads off its pivots.
        rref_coords(&product.space.0.coboundaries, &diff, &field).is_some()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::algebra::{
        an_with_relations, dual_numbers, kronecker, linear_an, radical_square_zero_cycle,
        truncated_poly,
    };
    use crate::field::PrimeField;
    use crate::hom::hom_dim;
    use crate::module::direct_sum;

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

    // Right modules over linearly oriented A_3 (arrows a: 0 -> 1, b: 1 -> 2).
    // The non-split extension realized by arrow a is 0 -> S_1 -> M -> S_0 -> 0
    // with M = P_0/rad^2 of dimension vector (1, 1, 0), top S_0 and socle S_1,
    // so the nonzero Ext group is Ext^1(S_0, S_1). In general
    // dim Ext^1(S_i, S_j) is the number of arrows i -> j (the same pairing as
    // for left modules over A^op read backwards; ASS III.2.12 states it for
    // right modules).
    #[test]
    fn a3_ext_1_between_simples_counts_arrows_source_to_target() {
        let field = f5();
        let algebra = linear_an(3, field);
        let simples: Vec<Module> = (0..3).map(|v| Module::simple(&algebra, v)).collect();
        for i in 0..3 {
            for j in 0..3 {
                let expected = usize::from(j == i + 1);
                assert_eq!(
                    ext_dim(&simples[i], &simples[j], 1).unwrap(),
                    expected,
                    "Ext^1(S_{i}, S_{j})"
                );
                for k in 2..=4 {
                    assert_eq!(
                        ext_dim(&simples[i], &simples[j], k).unwrap(),
                        0,
                        "Ext^{k}(S_{i}, S_{j}) over a gldim-1 algebra"
                    );
                }
            }
        }
        assert_eq!(ext_dim(&simples[1], &simples[0], 1).unwrap(), 0);
        assert_eq!(global_dimension(&algebra, 5), Bounded::Exact(1));
    }

    // kA_3/(ab), right modules: pd S_0 = 2 via 0 -> P_2 -> P_1 -> P_0 -> S_0 -> 0.
    // Counting arrows i -> j gives Ext^1(S_0, S_1) = Ext^1(S_1, S_2) = 1. The
    // relation detects Ext^2 on the ordered pair (source, target) of the
    // forbidden path: Hom(P_2, S_2) = k sits in degree 2 of the resolution of
    // S_0 with zero delta on both sides, so Ext^2(S_0, S_2) = 1. These values
    // match the QPA-verified facts (Ext^1(S_0, S_1) = 1, Ext^2(S_0, S_2) = 1)
    // on the same ordered pairs, with no right-versus-left discrepancy.
    #[test]
    fn a3_mod_ab_ext_1_and_2_among_simples() {
        let field = f5();
        let algebra = an_with_relations(3, &[(0, 2)], field).unwrap();
        let simples: Vec<Module> = (0..3).map(|v| Module::simple(&algebra, v)).collect();
        for i in 0..3 {
            for j in 0..3 {
                let ext1 = usize::from(j == i + 1);
                let ext2 = usize::from(i == 0 && j == 2);
                assert_eq!(
                    ext_dim(&simples[i], &simples[j], 1).unwrap(),
                    ext1,
                    "Ext^1(S_{i}, S_{j})"
                );
                assert_eq!(
                    ext_dim(&simples[i], &simples[j], 2).unwrap(),
                    ext2,
                    "Ext^2(S_{i}, S_{j})"
                );
                assert_eq!(ext_dim(&simples[i], &simples[j], 3).unwrap(), 0);
            }
        }
        assert_eq!(global_dimension(&algebra, 5), Bounded::Exact(2));
    }

    #[test]
    fn dual_numbers_ext_table_of_the_simple_is_all_ones() {
        let field = f5();
        let algebra = dual_numbers(field);
        let s = Module::simple(&algebra, 0);
        assert_eq!(ext_table(&s, &s, 4).unwrap(), vec![1, 1, 1, 1, 1]);
        assert_eq!(global_dimension(&algebra, 6), Bounded::AtLeast(7));
    }

    // k[x]/(x^3) over F_3: the minimal resolution of S has syzygy period 2
    // (Omega S = rad P has dimension 2, Omega^2 S = soc P is isomorphic to S),
    // every term is P, and Hom(P, S) = k with zero differentials throughout.
    #[test]
    fn truncated_poly_3_ext_table_of_the_simple_is_all_ones() {
        let field = PrimeField::new(3).unwrap();
        let algebra = truncated_poly(3, field).unwrap();
        let s = Module::simple(&algebra, 0);
        let res = resolve(&s, 5);
        for term in &res.terms {
            assert_eq!(term.dim_vector(), &[3]);
        }
        assert_eq!(ext_table(&s, &s, 4).unwrap(), vec![1, 1, 1, 1, 1]);
    }

    // Cycle 0 -> 1 -> 2 -> 0 with rad^2 = 0, right modules: rad P_i = S_{i+1},
    // so Omega S_i = S_{i+1} and the extension realized by the arrow i -> i+1
    // gives Ext^1(S_i, S_{i+1}) = 1 while Ext^1(S_i, S_{i-1}) = 0. The pairing
    // again runs from arrow source to arrow target.
    #[test]
    fn radical_square_zero_cycle_ext_1_follows_the_arrows() {
        let field = f5();
        let algebra = radical_square_zero_cycle(3, field);
        let simples: Vec<Module> = (0..3).map(|v| Module::simple(&algebra, v)).collect();
        for i in 0..3 {
            for j in 0..3 {
                let expected = usize::from(j == (i + 1) % 3);
                assert_eq!(
                    ext_dim(&simples[i], &simples[j], 1).unwrap(),
                    expected,
                    "Ext^1(S_{i}, S_{j})"
                );
            }
        }
        assert_eq!(global_dimension(&algebra, 4), Bounded::AtLeast(5));
    }

    // Regression against the old examples-db, which listed hereditary Kronecker
    // algebras as having infinite global dimension.
    #[test]
    fn kronecker_2_is_hereditary_with_global_dimension_1() {
        let algebra = kronecker(2, f5());
        assert_eq!(global_dimension(&algebra, 5), Bounded::Exact(1));
    }

    fn assorted_pairs() -> Vec<(Module, Module)> {
        let field = f5();
        let mut pairs = Vec::new();
        for algebra in [
            linear_an(3, field),
            an_with_relations(3, &[(0, 2)], field).unwrap(),
            dual_numbers(field),
            radical_square_zero_cycle(3, field),
        ] {
            let n = algebra.quiver().num_vertices();
            for v in 0..n {
                let s = Module::simple(&algebra, v);
                let p = Module::projective(&algebra, v);
                let i = Module::injective(&algebra, v);
                pairs.push((s.clone(), i.clone()));
                pairs.push((i, s.clone()));
                pairs.push((s.clone(), p.clone()));
                pairs.push((p, s));
            }
            let s0 = Module::simple(&algebra, 0);
            let i_last = Module::injective(&algebra, n - 1);
            let (sum, _, _) = direct_sum(&[&s0, &i_last]);
            pairs.push((sum.clone(), s0));
            pairs.push((sum.clone(), sum));
        }
        pairs
    }

    #[test]
    fn ext_0_equals_hom_dim() {
        for (m, n) in assorted_pairs() {
            assert_eq!(
                ext_dim(&m, &n, 0).unwrap(),
                hom_dim(&m, &n).unwrap(),
                "Ext^0 with dim m = {:?}, dim n = {:?}",
                m.dim_vector(),
                n.dim_vector()
            );
        }
    }

    // The Yoneda basis must agree with the generic commuting-square solver: same
    // dimension for Hom(P, N) on every resolution term, and the canonical
    // coordinates of the Yoneda basis form the identity matrix.
    #[test]
    fn yoneda_basis_agrees_with_generic_hom_on_resolution_terms() {
        let field = f5();
        for (m, n) in assorted_pairs() {
            let res = resolve(&m, 2);
            for term in &res.terms {
                let lay = layout(term);
                assert_eq!(hom_space_dim(&lay, &n), hom_dim(term, &n).unwrap());
                let basis = yoneda_basis(term, &lay, &n);
                for (i, f) in basis.iter().enumerate() {
                    let coords = coordinates(f, &lay, &n);
                    for (c, &val) in coords.iter().enumerate() {
                        let expected = if c == i { field.one() } else { field.zero() };
                        assert_eq!(val, expected, "coordinate {c} of basis element {i}");
                    }
                }
            }
        }
    }

    #[test]
    fn ext_beyond_a_finite_resolution_is_zero() {
        let field = f5();
        let algebra = an_with_relations(3, &[(0, 2)], field).unwrap();
        let s0 = Module::simple(&algebra, 0);
        let s2 = Module::simple(&algebra, 2);
        assert_eq!(ext_table(&s0, &s2, 6).unwrap(), vec![0, 0, 1, 0, 0, 0, 0]);
    }
}

#[cfg(test)]
mod ext_class_tests {
    use super::*;
    use crate::algebra::{
        an_with_relations, commutative_square, dual_numbers, linear_an, truncated_poly,
    };
    use crate::decompose::add_morphisms;
    use crate::field::PrimeField;
    use crate::hom::{hom_dim, zero_morphism};
    use crate::homspace::scale_morphism;
    use crate::module::direct_sum;

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

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

    fn unit(dim: usize, k: usize, field: &PrimeField) -> Vec<Fp> {
        let mut v = vec![field.zero(); dim];
        v[k] = field.one();
        v
    }

    fn basis_class(space: &ExtSpace, k: usize) -> ExtClass {
        let field = space.source().field();
        space
            .class_from_coordinates(&unit(space.dim(), k, &field))
            .unwrap()
    }

    #[test]
    fn ext_space_dim_matches_ext_dim_and_hom_dim_on_fixtures() {
        let field = f5();
        for algebra in [
            truncated_poly(3, field).unwrap(),
            commutative_square(field),
            linear_an(3, field),
            an_with_relations(3, &[(0, 2)], field).unwrap(),
            dual_numbers(field),
        ] {
            let nv = algebra.quiver().num_vertices();
            let mut modules: Vec<Module> = (0..nv).map(|v| Module::simple(&algebra, v)).collect();
            modules.push(Module::projective(&algebra, 0));
            modules.push(Module::injective(&algebra, nv - 1));
            let s0 = Module::simple(&algebra, 0);
            let i_last = Module::injective(&algebra, nv - 1);
            modules.push(direct_sum(&[&s0, &i_last]).0);
            for m in &modules {
                for n in &modules {
                    for k in 0..=3 {
                        let space = ExtSpace::new(m, n, k).unwrap();
                        assert_eq!(
                            space.dim(),
                            ext_dim(m, n, k).unwrap(),
                            "dim m = {:?}, dim n = {:?}, k = {k}",
                            m.dim_vector(),
                            n.dim_vector()
                        );
                        if k == 0 {
                            assert_eq!(space.dim(), hom_dim(m, n).unwrap());
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn truncated_poly_3_ext_spaces_are_one_dimensional_over_f5_and_f2() {
        for field in [f5(), f2()] {
            let algebra = truncated_poly(3, field).unwrap();
            let s = Module::simple(&algebra, 0);
            for k in 0..=4 {
                let space = ExtSpace::new(&s, &s, k).unwrap();
                assert_eq!(space.dim(), 1, "Ext^{k}(S, S) over F_{}", field.modulus());
                assert_eq!(space.dim(), ext_dim(&s, &s, k).unwrap());
            }
        }
    }

    #[test]
    fn identity_classes_are_yoneda_units() {
        let field = f5();
        let x3 = truncated_poly(3, field).unwrap();
        let s = Module::simple(&x3, 0);
        let a3 = an_with_relations(3, &[(0, 2)], field).unwrap();
        let s0 = Module::simple(&a3, 0);
        let s1 = Module::simple(&a3, 1);
        let s2 = Module::simple(&a3, 2);
        let cases: Vec<(Module, Module, usize)> = vec![
            (s.clone(), s.clone(), 0),
            (s.clone(), s.clone(), 1),
            (s.clone(), s.clone(), 2),
            (s0.clone(), s1.clone(), 1),
            (s0.clone(), s2.clone(), 2),
            (s1.clone(), s2.clone(), 1),
        ];
        for (m, n, k) in cases {
            let space = ExtSpace::new(&m, &n, k).unwrap();
            assert!(space.dim() > 0, "fixture case has a nonzero space");
            let alpha = basis_class(&space, 0);
            let id_m = ExtSpace::new(&m, &m, 0).unwrap().identity_class().unwrap();
            let id_n = ExtSpace::new(&n, &n, 0).unwrap().identity_class().unwrap();
            let left = id_m.then(&alpha).unwrap();
            let right = alpha.then(&id_n).unwrap();
            assert!(left.equals(&alpha).unwrap(), "left unit at degree {k}");
            assert!(right.equals(&alpha).unwrap(), "right unit at degree {k}");
        }
    }

    // Over k[x]/(x^3) the differentials of the minimal resolution of S
    // alternate right multiplication by x and by x^2. The degree-1 lift of
    // the Ext^1 generator sends the generator of P_2 into the radical, so
    // composing with a cocycle P_1 -> S kills it: the Yoneda square of the
    // degree-1 class is zero in every characteristic. The Ext algebra is
    // k[z] tensor the exterior algebra on y, so every product involving the
    // degree-2 generator z is nonzero.
    #[test]
    fn truncated_poly_3_yoneda_products_match_the_ext_algebra() {
        for field in [f5(), f2()] {
            let algebra = truncated_poly(3, field).unwrap();
            let s = Module::simple(&algebra, 0);
            let ext1 = ExtSpace::new(&s, &s, 1).unwrap();
            let ext2 = ExtSpace::new(&s, &s, 2).unwrap();
            let xi = basis_class(&ext1, 0);
            let chi = basis_class(&ext2, 0);
            assert!(
                xi.then(&xi).unwrap().is_zero(),
                "y^2 = 0 over F_{}",
                field.modulus()
            );
            assert!(!xi.then(&chi).unwrap().is_zero(), "y z is nonzero");
            assert!(!chi.then(&xi).unwrap().is_zero(), "z y is nonzero");
            assert!(!chi.then(&chi).unwrap().is_zero(), "z^2 is nonzero");
            let (product, witness) = xi.then_with_witness(&chi).unwrap();
            assert!(witness.verify(&xi, &chi, &product));
        }
    }

    // Over k[x]/(x^2) the Ext algebra of the simple is the polynomial ring
    // on the degree-1 class, so every Yoneda power is nonzero.
    #[test]
    fn dual_numbers_yoneda_powers_of_the_degree_one_class_are_nonzero() {
        let algebra = dual_numbers(f5());
        let s = Module::simple(&algebra, 0);
        let ext1 = ExtSpace::new(&s, &s, 1).unwrap();
        let xi = basis_class(&ext1, 0);
        let square = xi.then(&xi).unwrap();
        assert!(!square.is_zero(), "y^2 is nonzero over k[x]/(x^2)");
        assert!(!square.then(&xi).unwrap().is_zero(), "y^3 is nonzero");
    }

    // Ext^1(S_0, S_1) x Ext^1(S_1, S_2) -> Ext^2(S_0, S_2) over kA_3/(ab):
    // both lifts are identities on the shared projective terms, so the
    // product is the Ext^2 generator detected by the relation. On the
    // commutative square the product Ext^1(S_0, S_1) x Ext^1(S_1, S_3) ->
    // Ext^2(S_0, S_3) has rank 1 (QPA-verified).
    #[test]
    fn ext1_times_ext1_is_nonzero_on_relation_detected_pairs() {
        let field = f5();
        let a3 = an_with_relations(3, &[(0, 2)], field).unwrap();
        let s0 = Module::simple(&a3, 0);
        let s1 = Module::simple(&a3, 1);
        let s2 = Module::simple(&a3, 2);
        let alpha = basis_class(&ExtSpace::new(&s0, &s1, 1).unwrap(), 0);
        let beta = basis_class(&ExtSpace::new(&s1, &s2, 1).unwrap(), 0);
        let product = alpha.then(&beta).unwrap();
        assert_eq!(product.space().dim(), 1);
        assert!(!product.is_zero(), "Ext^1 . Ext^1 -> Ext^2 over kA_3/(ab)");
        let square = commutative_square(field);
        let t0 = Module::simple(&square, 0);
        let t1 = Module::simple(&square, 1);
        let t3 = Module::simple(&square, 3);
        let a = basis_class(&ExtSpace::new(&t0, &t1, 1).unwrap(), 0);
        let b = basis_class(&ExtSpace::new(&t1, &t3, 1).unwrap(), 0);
        let ab = a.then(&b).unwrap();
        assert_eq!(ab.space().dim(), 1);
        assert!(
            !ab.is_zero(),
            "the commutative square relation pairs 0 -> 3"
        );
    }

    #[test]
    fn yoneda_products_are_bilinear_on_small_cases() {
        let field = f5();
        let a3 = an_with_relations(3, &[(0, 2)], field).unwrap();
        let dn = dual_numbers(field);
        let cases: Vec<(ExtClass, ExtClass)> = {
            let s0 = Module::simple(&a3, 0);
            let s1 = Module::simple(&a3, 1);
            let s2 = Module::simple(&a3, 2);
            let s = Module::simple(&dn, 0);
            vec![
                (
                    basis_class(&ExtSpace::new(&s0, &s1, 1).unwrap(), 0),
                    basis_class(&ExtSpace::new(&s1, &s2, 1).unwrap(), 0),
                ),
                (
                    basis_class(&ExtSpace::new(&s, &s, 1).unwrap(), 0),
                    basis_class(&ExtSpace::new(&s, &s, 1).unwrap(), 0),
                ),
            ]
        };
        for (alpha, beta) in cases {
            let two = field.elem(2);
            let three = field.elem(3);
            let product = alpha.then(&beta).unwrap();
            let doubled = alpha.scale(two);
            let sum = alpha.add(&doubled).unwrap();
            let left = sum.then(&beta).unwrap();
            let right = product.add(&doubled.then(&beta).unwrap()).unwrap();
            assert!(left.equals(&right).unwrap(), "additivity on the left");
            let scaled_left = alpha.scale(three).then(&beta).unwrap();
            assert!(scaled_left.equals(&product.scale(three)).unwrap());
            let scaled_right = alpha.then(&beta.scale(three)).unwrap();
            assert!(scaled_right.equals(&product.scale(three)).unwrap());
            let negated = alpha.neg().then(&beta).unwrap();
            assert!(negated.equals(&product.neg()).unwrap());
            let zero = alpha.space().zero_class().then(&beta).unwrap();
            assert!(zero.is_zero(), "the zero class annihilates products");
        }
    }

    #[test]
    fn adding_a_coboundary_does_not_change_the_class() {
        let field = f5();
        let mut saw_nonzero_coboundary = false;
        for algebra in [
            truncated_poly(3, field).unwrap(),
            an_with_relations(3, &[(0, 2)], field).unwrap(),
            commutative_square(field),
        ] {
            let nv = algebra.quiver().num_vertices();
            for v in 0..nv {
                let s = Module::simple(&algebra, v);
                for w in 0..nv {
                    for n in [
                        Module::projective(&algebra, w),
                        Module::injective(&algebra, w),
                    ] {
                        for k in 1..=2 {
                            let space = ExtSpace::new(&s, &n, k).unwrap();
                            let cob = space.coboundary_basis();
                            if cob.rows() == 0 {
                                continue;
                            }
                            saw_nonzero_coboundary = true;
                            let lay = layout(space.cochain_term());
                            let mut classes = vec![space.zero_class()];
                            for i in 0..space.dim() {
                                classes.push(basis_class(&space, i));
                            }
                            for class in &classes {
                                let rep = class.representative();
                                for r in 0..cob.rows() {
                                    let boundary = cochain_from_coordinates(
                                        space.cochain_term(),
                                        &lay,
                                        space.target(),
                                        cob.row(r),
                                    );
                                    let shifted = add_morphisms(&rep, &boundary);
                                    let recovered = space.class_from_cocycle(&shifted).unwrap();
                                    assert!(recovered.equals(class).unwrap());
                                }
                            }
                        }
                    }
                }
            }
        }
        assert!(saw_nonzero_coboundary, "the fixtures exercise nonzero B^k");
    }

    #[test]
    fn class_from_cocycle_rejects_wrong_endpoints_and_non_cocycles() {
        let field = f5();
        let algebra = truncated_poly(3, field).unwrap();
        let s = Module::simple(&algebra, 0);
        let p = Module::projective(&algebra, 0);
        let space = ExtSpace::new(&s, &p, 1).unwrap();
        let other = ExtSpace::new(&s, &p, 1).unwrap();
        let wrong_source = zero_morphism(other.cochain_term(), &p).unwrap();
        assert_eq!(
            space.class_from_cocycle(&wrong_source).unwrap_err(),
            ExtClassError::SourceMismatch
        );
        let p_copy = Module::projective(&algebra, 0);
        let wrong_target = zero_morphism(space.cochain_term(), &p_copy).unwrap();
        assert_eq!(
            space.class_from_cocycle(&wrong_target).unwrap_err(),
            ExtClassError::TargetMismatch
        );
        let lay = layout(space.cochain_term());
        let non_cocycle = yoneda_basis(space.cochain_term(), &lay, &p).remove(0);
        match space.class_from_cocycle(&non_cocycle).unwrap_err() {
            ExtClassError::NotCocycle { composite } => {
                assert!(composite.iter().any(|c| !c.is_zero()));
            }
            other => panic!("expected NotCocycle, got {other:?}"),
        }
    }

    #[test]
    fn class_from_coordinates_rejects_wrong_length_and_non_canonical_entries() {
        let algebra = truncated_poly(3, f2()).unwrap();
        let s = Module::simple(&algebra, 0);
        let space = ExtSpace::new(&s, &s, 1).unwrap();
        assert_eq!(space.dim(), 1);
        assert_eq!(
            space.class_from_coordinates(&[]).unwrap_err(),
            ExtClassError::CoordinateCountMismatch {
                expected: 1,
                got: 0
            }
        );
        let one = f2().one();
        assert_eq!(
            space.class_from_coordinates(&[one, one]).unwrap_err(),
            ExtClassError::CoordinateCountMismatch {
                expected: 1,
                got: 2
            }
        );
        // The entry 3 comes from F_5; it is not a canonical F_2 representative.
        assert_eq!(
            space.class_from_coordinates(&[f5().elem(3)]).unwrap_err(),
            ExtClassError::NonCanonicalCoordinate { index: 0 }
        );
    }

    #[test]
    fn arithmetic_rejects_incompatible_spaces_and_products_reject_bad_middles() {
        let field = f5();
        let algebra = truncated_poly(3, field).unwrap();
        let s = Module::simple(&algebra, 0);
        let s_copy = Module::simple(&algebra, 0);
        let deg1 = ExtSpace::new(&s, &s, 1).unwrap();
        let deg2 = ExtSpace::new(&s, &s, 2).unwrap();
        let copied = ExtSpace::new(&s_copy, &s_copy, 1).unwrap();
        let a = basis_class(&deg1, 0);
        let b = basis_class(&deg2, 0);
        let c = basis_class(&copied, 0);
        assert_eq!(a.add(&b).unwrap_err(), ExtClassError::IncompatibleSpaces);
        assert_eq!(a.equals(&b).unwrap_err(), ExtClassError::IncompatibleSpaces);
        assert_eq!(a.add(&c).unwrap_err(), ExtClassError::IncompatibleSpaces);
        assert_eq!(a.equals(&c).unwrap_err(), ExtClassError::IncompatibleSpaces);
        assert_eq!(a.then(&c).unwrap_err(), ExtClassError::MiddleMismatch);
    }

    #[test]
    fn identity_class_needs_degree_zero_and_equal_endpoints() {
        let field = f5();
        let algebra = truncated_poly(3, field).unwrap();
        let s = Module::simple(&algebra, 0);
        let p = Module::projective(&algebra, 0);
        assert_eq!(
            ExtSpace::new(&s, &s, 1)
                .unwrap()
                .identity_class()
                .unwrap_err(),
            ExtClassError::NotDegreeZeroEndo
        );
        assert_eq!(
            ExtSpace::new(&s, &p, 0)
                .unwrap()
                .identity_class()
                .unwrap_err(),
            ExtClassError::NotDegreeZeroEndo
        );
    }

    #[test]
    fn zero_modules_give_zero_spaces() {
        let field = f5();
        let algebra = truncated_poly(3, field).unwrap();
        let s = Module::simple(&algebra, 0);
        let z = Module::zero(&algebra);
        for k in 0..=2 {
            let left = ExtSpace::new(&z, &s, k).unwrap();
            let right = ExtSpace::new(&s, &z, k).unwrap();
            assert_eq!(left.dim(), 0);
            assert_eq!(right.dim(), 0);
            assert!(left.zero_class().is_zero());
            assert!(right.zero_class().representative().is_zero());
        }
    }

    #[test]
    fn a_finite_resolution_ending_before_the_degree_gives_the_zero_space() {
        let field = f5();
        let algebra = linear_an(3, field);
        let s0 = Module::simple(&algebra, 0);
        let s1 = Module::simple(&algebra, 1);
        let space = ExtSpace::new(&s0, &s1, 3).unwrap();
        assert_eq!(space.dim(), 0);
        assert!(space.cochain_term().is_zero());
        assert!(space.zero_class().representative().is_zero());
        let empty = space.class_from_coordinates(&[]).unwrap();
        assert!(empty.is_zero());
        let zero = zero_morphism(space.cochain_term(), space.target()).unwrap();
        assert!(space.class_from_cocycle(&zero).unwrap().is_zero());
    }

    #[test]
    fn product_witness_accepts_the_genuine_triple_and_rejects_tampering() {
        let field = f5();
        let algebra = an_with_relations(3, &[(0, 2)], field).unwrap();
        let s0 = Module::simple(&algebra, 0);
        let s1 = Module::simple(&algebra, 1);
        let s2 = Module::simple(&algebra, 2);
        let alpha = basis_class(&ExtSpace::new(&s0, &s1, 1).unwrap(), 0);
        let beta = basis_class(&ExtSpace::new(&s1, &s2, 1).unwrap(), 0);
        let (product, witness) = alpha.then_with_witness(&beta).unwrap();
        assert!(witness.verify(&alpha, &beta, &product));
        // A Morphism is checked at construction, so the tamper scales one
        // lift: every nonzero entry changes and one lift identity breaks.
        assert!(!witness.lifts()[0].is_zero());
        let scaled = scale_morphism(&witness.lifts()[0], field.elem(2));
        let mut tampered_lifts = witness.lifts().to_vec();
        tampered_lifts[0] = scaled;
        let tampered = ProductWitness {
            lifts: tampered_lifts,
        };
        assert!(!tampered.verify(&alpha, &beta, &product));
        let wrong_product = ExtClass {
            space: product.space().clone(),
            coords: vec![field.elem(2)],
        };
        assert!(!witness.verify(&alpha, &beta, &wrong_product));
        assert!(!witness.verify(&alpha.scale(field.elem(2)), &beta, &product));
    }

    #[test]
    fn recomputed_spaces_carry_identical_bases_and_representatives() {
        let field = f5();
        let algebra = commutative_square(field);
        let s0 = Module::simple(&algebra, 0);
        let p0 = Module::projective(&algebra, 0);
        for (m, n, k) in [(&s0, &p0, 1), (&s0, &p0, 2), (&s0, &s0, 0)] {
            let first = ExtSpace::new(m, n, k).unwrap();
            let second = ExtSpace::new(m, n, k).unwrap();
            assert!(first.is_compatible(&second));
            assert_eq!(
                first.cocycle_basis().entries_u64(),
                second.cocycle_basis().entries_u64()
            );
            assert_eq!(
                first.coboundary_basis().entries_u64(),
                second.coboundary_basis().entries_u64()
            );
            assert_eq!(
                first.complement_basis().entries_u64(),
                second.complement_basis().entries_u64()
            );
            for (a, b) in first.representatives().iter().zip(second.representatives()) {
                for v in 0..algebra.quiver().num_vertices() {
                    assert_eq!(a.map_at(v), b.map_at(v));
                }
            }
        }
    }

    #[test]
    fn ext_space_new_rejects_modules_over_different_algebras() {
        let a = linear_an(3, f5());
        let b = linear_an(3, f5());
        let m = Module::simple(&a, 0);
        let n = Module::simple(&b, 0);
        assert_eq!(
            ExtSpace::new(&m, &n, 1).unwrap_err(),
            ExtError::DifferentAlgebras
        );
    }
}

/// Representative-level product tests. The acceptance suite pins the
/// class-level product laws. These tests drive the lift construction on
/// altered cocycle morphisms and on cocycles recovered from realized
/// extensions.
#[cfg(test)]
mod product_representative_tests {
    use super::*;
    use crate::algebra::{an_with_relations, dual_numbers, truncated_poly};
    use crate::decompose::add_morphisms;
    use crate::field::PrimeField;
    use crate::homspace::scale_morphism;
    use crate::radical::radical;
    use crate::sequence::ShortExactSequence;

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

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

    fn basis_class(space: &ExtSpace, k: usize) -> ExtClass {
        let field = space.source().field();
        let mut coords = vec![field.zero(); space.dim()];
        coords[k] = field.one();
        space.class_from_coordinates(&coords).unwrap()
    }

    /// The cochain morphism of `row` over the cochain term of `space`.
    fn cocycle_of_row(space: &ExtSpace, row: &[Fp]) -> Morphism {
        let inner = &space.0;
        let lay = layout(&inner.term);
        cochain_from_coordinates(&inner.term, &lay, &inner.target, row)
    }

    /// The degree 1 x degree 1 product class computed by the lift
    /// construction from an arbitrary left cocycle `P^M_1 -> N`, not from
    /// the canonical representative: transport the cocycle onto the product
    /// resolution, lift it through the augmentation of N's resolution, push
    /// one differential further, compose with the right cocycle, and
    /// reduce.
    fn product_from_cocycles(
        left_cocycle: &Morphism,
        beta: &ExtClass,
        right_cocycle: &Morphism,
        product_space: &ExtSpace,
    ) -> ExtClass {
        let deep = &product_space.0.resolution;
        let res_n = &beta.space().0.resolution;
        let nv = product_space.0.source.algebra().quiver().num_vertices();
        let maps: Vec<DenseMat> = (0..nv).map(|v| left_cocycle.map_at(v).clone()).collect();
        let f = Morphism::new(&deep.terms[1], &beta.space().0.source, maps)
            .expect("the recomputed resolution prefix matches, so the cocycle transports");
        let phi0 = lift_through(&deep.terms[1], &res_n.augmentation, &f);
        let rhs = deep.maps[1].then(&phi0).unwrap();
        let phi1 = lift_through(&deep.terms[2], &res_n.maps[0], &rhs);
        let h = phi1.then(right_cocycle).unwrap();
        product_space.class_from_cocycle(&h).unwrap()
    }

    /// Over A = k[x]/(x^3) with S the simple and R = rad P = A/(x^2): the
    /// resolution of S has d_1 = x and d_2 = x^2, so B^1(S, R) is the line
    /// spanned by 1 -> x while B^1 into any simple target vanishes. The
    /// products Ext^1(S, R) x Ext^1(R, S) -> Ext^2(S, S) and
    /// Ext^1(R, S) x Ext^1(S, R) -> Ext^2(R, R) are both nonzero: the
    /// spliced 2-extensions 0 -> S -> P -> P -> S -> 0 (middle map x) and
    /// 0 -> R -> P -> P -> R -> 0 (middle map x^2) have nonzero connecting
    /// cocycles against the minimal resolutions.
    fn x3_pairs(field: PrimeField) -> Vec<(ExtSpace, ExtSpace)> {
        let algebra = truncated_poly(3, field).unwrap();
        let s = Module::simple(&algebra, 0);
        let r = radical(&Module::projective(&algebra, 0)).0;
        vec![
            (
                ExtSpace::new(&s, &r, 1).unwrap(),
                ExtSpace::new(&r, &s, 1).unwrap(),
            ),
            (
                ExtSpace::new(&r, &s, 1).unwrap(),
                ExtSpace::new(&s, &r, 1).unwrap(),
            ),
        ]
    }

    #[test]
    fn a_left_cocycle_shifted_by_a_coboundary_lifts_to_the_same_product() {
        for field in [f5(), f2()] {
            let mut shifted_cases = 0usize;
            for (left, right) in x3_pairs(field) {
                let alpha = basis_class(&left, 0);
                let beta = basis_class(&right, 0);
                let canonical = alpha.then(&beta).unwrap();
                assert!(!canonical.is_zero(), "the fixture products are nonzero");
                let cob = left.coboundary_basis();
                if cob.rows() == 0 {
                    continue;
                }
                let rep = alpha.representative();
                let g = beta.representative();
                let product_space = canonical.space();
                for k in 0..cob.rows() {
                    let boundary = cocycle_of_row(&left, cob.row(k));
                    assert!(!boundary.is_zero());
                    let shifted = add_morphisms(&rep, &boundary);
                    assert!(shifted != rep, "the altered representative differs");
                    let from_shifted = product_from_cocycles(&shifted, &beta, &g, product_space);
                    assert!(from_shifted.equals(&canonical).unwrap());
                    shifted_cases += 1;
                }
            }
            assert!(
                shifted_cases > 0,
                "some left factor space has nonzero coboundaries"
            );
        }
    }

    #[test]
    fn a_right_cocycle_shifted_by_a_coboundary_composes_to_the_same_product() {
        for field in [f5(), f2()] {
            let mut shifted_cases = 0usize;
            for (left, right) in x3_pairs(field) {
                let alpha = basis_class(&left, 0);
                let beta = basis_class(&right, 0);
                let (canonical, witness) = alpha.then_with_witness(&beta).unwrap();
                assert!(!canonical.is_zero(), "the fixture products are nonzero");
                let cob = right.coboundary_basis();
                if cob.rows() == 0 {
                    continue;
                }
                let g = beta.representative();
                for k in 0..cob.rows() {
                    let boundary = cocycle_of_row(&right, cob.row(k));
                    assert!(!boundary.is_zero());
                    let shifted = add_morphisms(&g, &boundary);
                    assert!(shifted != g, "the altered representative differs");
                    let h = witness.lifts()[1].then(&shifted).unwrap();
                    let reduced = canonical.space().class_from_cocycle(&h).unwrap();
                    assert!(reduced.equals(&canonical).unwrap());
                    shifted_cases += 1;
                }
            }
            assert!(
                shifted_cases > 0,
                "some right factor space has nonzero coboundaries"
            );
        }
    }

    /// Re-solves the connecting cocycle of `alpha`'s realized extension,
    /// the pre-reduction morphism of the `ext1_class` recovery: lift the
    /// augmentation through the projection, push it one differential
    /// further, and pull the result back through the inclusion.
    fn recovered_cocycle(alpha: &ExtClass) -> Morphism {
        let ses = ShortExactSequence::from_ext1(alpha).unwrap();
        let res = &alpha.space().0.resolution;
        let h = lift_through(&res.terms[0], ses.projection(), &res.augmentation);
        let d1h = res.maps[0].then(&h).unwrap();
        lift_through(&res.terms[1], ses.inclusion(), &d1h)
    }

    #[test]
    fn the_cocycle_recovered_from_the_extension_splices_to_the_product() {
        let field = f5();
        let a3 = an_with_relations(3, &[(0, 2)], field).unwrap();
        let s0 = Module::simple(&a3, 0);
        let s1 = Module::simple(&a3, 1);
        let s2 = Module::simple(&a3, 2);
        let dn = dual_numbers(field);
        let ds = Module::simple(&dn, 0);
        let mut pairs = vec![
            (
                ExtSpace::new(&s0, &s1, 1).unwrap(),
                ExtSpace::new(&s1, &s2, 1).unwrap(),
            ),
            (
                ExtSpace::new(&ds, &ds, 1).unwrap(),
                ExtSpace::new(&ds, &ds, 1).unwrap(),
            ),
        ];
        pairs.extend(x3_pairs(field));
        let mut perturbed_cases = 0usize;
        for (left, right) in pairs {
            let alpha = basis_class(&left, 0);
            let beta = basis_class(&right, 0);
            let canonical = alpha.then(&beta).unwrap();
            assert!(!canonical.is_zero(), "the fixture products are nonzero");
            let recovered = recovered_cocycle(&alpha);
            assert!(
                left.class_from_cocycle(&recovered)
                    .unwrap()
                    .equals(&alpha)
                    .unwrap()
            );
            let rep = alpha.representative();
            let cocycle = if recovered == rep {
                // A route through the same morphism proves nothing, so
                // perturb by a coboundary. When B^1 is zero every class
                // has one cocycle and the coincidence is forced.
                let cob = left.coboundary_basis();
                if cob.rows() == 0 {
                    recovered
                } else {
                    let shifted = add_morphisms(&recovered, &cocycle_of_row(&left, cob.row(0)));
                    assert!(shifted != rep, "the perturbed cocycle differs");
                    perturbed_cases += 1;
                    shifted
                }
            } else {
                perturbed_cases += 1;
                recovered
            };
            let g = beta.representative();
            let spliced = product_from_cocycles(&cocycle, &beta, &g, canonical.space());
            assert!(spliced.equals(&canonical).unwrap());
        }
        assert!(
            perturbed_cases > 0,
            "some case runs the splice on a cocycle other than the canonical representative"
        );
    }

    fn rows_of(mat: &DenseMat) -> Vec<Vec<Fp>> {
        (0..mat.rows()).map(|r| mat.row(r).to_vec()).collect()
    }

    // Section 15 of the design: a complement row replaced by a coboundary.
    // The stored witness reduces the product cocycle against the tampered
    // complement, and the mismatch is not a coboundary, so verify rejects.
    #[test]
    fn a_complement_row_replaced_by_a_coboundary_fails_product_verification() {
        let field = f5();
        let mut pairs = x3_pairs(field);
        let (left, right) = pairs.remove(1);
        let alpha = basis_class(&left, 0);
        let beta = basis_class(&right, 0);
        let (product, witness) = alpha.then_with_witness(&beta).unwrap();
        assert!(!product.is_zero());
        assert!(witness.verify(&alpha, &beta, &product));
        let inner = &product.space().0;
        assert!(
            inner.coboundaries.rows() > 0,
            "Ext^2(R, R) has nonzero coboundaries"
        );
        let mut rows = rows_of(&inner.complement);
        rows[0] = inner.coboundaries.row(0).to_vec();
        let tampered = product.space().with_bases(
            inner.cocycles.clone(),
            inner.coboundaries.clone(),
            DenseMat::from_rows(&rows),
        );
        let bad = ExtClass {
            space: tampered,
            coords: product.coordinates().to_vec(),
        };
        assert!(!witness.verify(&alpha, &beta, &bad));
    }

    // Section 15 of the design: a product reduced against a tampered
    // coboundary basis. A basis grown by a cocycle outside B^2 would let
    // any class label pass the membership solve, so verify must compare
    // the stored basis against the recomputation and reject.
    #[test]
    fn a_tampered_coboundary_basis_fails_product_verification() {
        let field = f5();
        let mut pairs = x3_pairs(field);
        let (left, right) = pairs.remove(1);
        let alpha = basis_class(&left, 0);
        let beta = basis_class(&right, 0);
        let (product, witness) = alpha.then_with_witness(&beta).unwrap();
        assert!(witness.verify(&alpha, &beta, &product));
        let inner = &product.space().0;
        assert!(
            inner.coboundaries.rows() > 0,
            "Ext^2(R, R) has nonzero coboundaries"
        );
        let mut rows = rows_of(&inner.coboundaries);
        rows.push(inner.complement.row(0).to_vec());
        let grown = DenseMat::from_rows(&rows).into_row_space_basis(&field);
        assert_ne!(grown, inner.coboundaries);
        let tampered =
            product
                .space()
                .with_bases(inner.cocycles.clone(), grown, inner.complement.clone());
        let bad = ExtClass {
            space: tampered,
            coords: product.coordinates().to_vec(),
        };
        assert!(!witness.verify(&alpha, &beta, &bad));
        let wrong_label = ExtClass {
            space: bad.space.clone(),
            coords: vec![field.zero(); product.coordinates().len()],
        };
        assert!(!witness.verify(&alpha, &beta, &wrong_label));
    }

    // The space recheck of C1: an untampered space matches its recomputation,
    // a space with any one stored matrix replaced does not.
    #[test]
    fn a_space_matches_its_recomputation_and_no_tampered_copy_does() {
        let field = f5();
        let algebra = truncated_poly(3, field).unwrap();
        let s = Module::simple(&algebra, 0);
        let space = ExtSpace::new(&s, &s, 2).unwrap();
        assert!(space.matches_recomputation());
        assert!(space.matches(&ExtSpace::new(&s, &s, 2).unwrap()));
        assert!(!space.matches(&ExtSpace::new(&s, &s, 1).unwrap()));
        let width = space.cocycle_basis().cols();
        let tampered = [
            space.with_bases(
                DenseMat::zero(0, width),
                space.coboundary_basis().clone(),
                space.complement_basis().clone(),
            ),
            space.with_bases(
                space.cocycle_basis().clone(),
                space.complement_basis().clone(),
                space.complement_basis().clone(),
            ),
            space.with_bases(
                space.cocycle_basis().clone(),
                space.coboundary_basis().clone(),
                DenseMat::zero(0, width),
            ),
            space.with_representatives(
                space
                    .representatives()
                    .iter()
                    .map(|rep| scale_morphism(rep, field.elem(2)))
                    .collect(),
            ),
        ];
        for bad in &tampered {
            assert!(!bad.matches_recomputation());
            assert!(!space.matches(bad));
        }
    }

    // then_in reuses the caller's space; the coordinates are the ones then
    // returns, because recomputed compatible spaces carry identical bases.
    #[test]
    fn then_in_agrees_with_then_and_rejects_an_unrelated_space() {
        let field = f5();
        let algebra = truncated_poly(3, field).unwrap();
        let s = Module::simple(&algebra, 0);
        let alpha = basis_class(&ExtSpace::new(&s, &s, 1).unwrap(), 0);
        let beta = basis_class(&ExtSpace::new(&s, &s, 2).unwrap(), 0);
        let product_space = alpha.product_space(&beta).unwrap();
        assert_eq!(product_space.degree(), 3);
        let plain = alpha.then(&beta).unwrap();
        let reused = alpha.then_in(&beta, &product_space).unwrap();
        assert_eq!(reused.coordinates(), plain.coordinates());
        assert!(reused.space().matches(plain.space()));
        let (again, witness) = alpha.then_with_witness_in(&beta, &product_space).unwrap();
        assert!(witness.verify(&alpha, &beta, &again));
        assert!(witness.verify_against(&alpha, &beta, &again, &product_space));
        let wrong_degree = ExtSpace::new(&s, &s, 2).unwrap();
        assert_eq!(
            alpha.then_in(&beta, &wrong_degree).unwrap_err(),
            ExtClassError::IncompatibleSpaces
        );
        let other_target = Module::projective(&algebra, 0);
        let wrong_target = ExtSpace::new(&s, &other_target, 3).unwrap();
        assert_eq!(
            alpha.then_in(&beta, &wrong_target).unwrap_err(),
            ExtClassError::IncompatibleSpaces
        );
    }

    // verify_against takes the recomputation from the caller, so it must
    // reject one that is not a recomputation of the product space.
    #[test]
    fn verify_against_rejects_a_space_that_is_not_the_recomputation() {
        let field = f5();
        let algebra = truncated_poly(3, field).unwrap();
        let s = Module::simple(&algebra, 0);
        let alpha = basis_class(&ExtSpace::new(&s, &s, 1).unwrap(), 0);
        let beta = basis_class(&ExtSpace::new(&s, &s, 1).unwrap(), 0);
        let (product, witness) = alpha.then_with_witness(&beta).unwrap();
        assert!(witness.verify(&alpha, &beta, &product));
        let inner = product.space();
        let grown = stack_rows(
            &[inner.coboundary_basis(), inner.complement_basis()],
            inner.complement_basis().cols(),
        )
        .into_row_space_basis(&field);
        let forged = inner.with_bases(
            inner.cocycle_basis().clone(),
            grown,
            inner.complement_basis().clone(),
        );
        assert!(!witness.verify_against(&alpha, &beta, &product, &forged));
    }
}