symfn 0.9.0

A modern, fast kernel for computing with symmetric functions.
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
//! Schubert polynomials `S_w`, indexed by [`Perm`].
//!
//! `{S_w : w ∈ S_∞}` is a ℤ-basis of the *whole* polynomial ring
//! `ℤ[x₁, x₂, …]`, not of Sym — which is why this type deliberately does not
//! implement [`SymFn`](crate::sym::SymFn): that trait is `Partition`-indexed
//! and everything generic over it assumes symmetric functions.
//! [`Forgotten`](crate::sym::Forgotten) is the precedent for declining a trait
//! rather than half-satisfying it. The handful of shared helpers are small
//! enough to reimplement here.
//!
//! Everything in this module is 1-based, per [`crate::permutation`].
//!
//! Sage's equivalent is `SchubertPolynomialRing(ZZ)`, and it is the source of
//! the committed structure-constant fixture (`scripts/gen_sage_oracle.sage`).
//! Buch's C `schubmult` is the second external implementation, and
//! `docs/record/schubert.md` measures where each stops.
//!
//! # What is implemented here
//!
//! The reference layer: the verified primitives and the E1 engine that exists
//! to be the in-house oracle — the role [`NaiveLr`](crate::lr::NaiveLr) plays for LR. E1 is
//! Symmetrica's own route: expand one factor to monomials, then push the other
//! through a Monk chain per monomial. Its cost is the number of **pipe
//! dreams**, which is why it walls at S₁₀–S₁₁ and why E3 exists. E1
//! is kept forever regardless of what wins.
//!
//! ## References
//!
//! - **\[LS82\]** A. Lascoux, M.-P. Schützenberger, *Polynômes de Schubert*,
//!   C. R. Acad. Sci. Paris Sér. I **294** (1982) — the definition by divided
//!   differences, \[MN\] (4.1), and the action `∂ᵢ S_w = S_{w sᵢ}` of
//!   \[MN\] (4.2) that [`Schubert::divided_difference`] implements. The
//!   braid relations are \[MN\] (2.4), and \[MN\] (2.5) is what makes `∂_w`
//!   ([`Schubert::divided_difference_perm`]) independent of the reduced word.
//! - **\[Mo\]** D. Monk, *The geometry of flag manifolds*, Proc. London Math.
//!   Soc. (3) **9** (1959) — Monk's formula, \[MN\] (4.15''), for
//!   `(x₁ + … + x_r)·S_w`. [`Schubert::mul_variable`] implements the signed
//!   form for a single `x_r`, \[MN\] (4.15'), which follows from it.
//! - **\[LS85\]** A. Lascoux, M.-P. Schützenberger, *Schubert polynomials and
//!   the Littlewood–Richardson rule*, Lett. Math. Phys. **10** (1985) — the
//!   transition formula. The form used here, at the last descent, is
//!   \[MN\] (4.16); [`Perm::transition`] computes it, [`Schubert::mul_e2`]
//!   memoizes the recursion, and [`Schubert::mul_e3`] runs it as operators
//!   over a state DAG.
//! - **\[LS82H\]** A. Lascoux, M.-P. Schützenberger, *Structure de Hopf de
//!   l'anneau de cohomologie et de l'anneau de Grothendieck d'une variété de
//!   drapeaux*, C. R. Acad. Sci. Paris Sér. I **295** (1982) — 1.15, that
//!   `S_{1ᵐ×w}` with the variables past the m-th set to zero is
//!   `Σ_I d_w(I) s_I` with non-negative integer `d_w(I)` independent of m:
//!   the stable limit `F_w`, which is the range in which [`stanley`] and
//!   `S_w` agree. \[MN\] Chapter VII develops this note.
//! - **\[BB\]** N. Bergeron, S. Billey, *RC-graphs and Schubert polynomials*,
//!   Experiment. Math. **2** (1993) — Corollary 3.3, `S_w = Σ_{D ∈ RC(w)} x^D`
//!   over rc-graphs (pipe dreams), so `S_w(1,…,1)` is the number of them: the
//!   count [`dimension`] returns and E1 pays. It restates their Theorem 2.1,
//!   which they credit to Billey–Jockusch–Stanley and Fomin–Stanley.
//! - **\[St\]** R. P. Stanley, *On the number of reduced decompositions of
//!   elements of Coxeter groups*, European J. Combin. **5** (1984) — the
//!   symmetric function `F_w`. Its Schur expansion, which [`stanley`]
//!   computes, is \[MN\] (7.19).
//! - **\[MN\]** I. G. Macdonald, *Notes on Schubert Polynomials*, LACIM,
//!   Université du Québec à Montréal, 1991 — the equation numbers above, and
//!   (4.5), the stability under `Sₙ ⊂ Sₘ` that makes `S_w` well defined for
//!   every `w ∈ S_∞`.

// Every `as` here is a variable index or a permutation position, bounded by the
// permutation's length. Coefficients are the generic `C` and are never cast.
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]

use crate::coeff::Ring;
use crate::partition::Partition;
use crate::permutation::Perm;
use crate::sym::{impl_linear_ops, impl_product_ops, InPlaceArith, Schur};
use std::collections::{BTreeMap, HashMap};

/// A monomial exponent vector: index `j-1` holds the exponent of `x_j`,
/// trailing zeros stripped so equal monomials compare equal.
pub type Expo = Vec<u32>;

/// A finite formal `C`-combination of permutations, i.e. an element of
/// `ℤ[x₁, x₂, …]` written in the Schubert basis.
///
/// `BTreeMap` for the same reason [`crate::sym`] uses one — deterministic
/// iteration — plus one this module actually depends on: [`Schubert::
/// from_polynomial`]'s greedy peel needs the lex-minimal monomial, and an
/// ordered map hands it over for free.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Schubert<C: Ring> {
    terms: BTreeMap<Perm, C>,
}

impl<C: Ring> Default for Schubert<C> {
    fn default() -> Self {
        Schubert::zero()
    }
}

fn strip(mut e: Expo) -> Expo {
    while e.last() == Some(&0) {
        e.pop();
    }
    e
}

impl<C: Ring> Schubert<C> {
    /// The zero element.
    pub fn zero() -> Self {
        Schubert {
            terms: BTreeMap::new(),
        }
    }

    /// `S_w` scaled by `c` (dropped if `c` is zero).
    pub fn monomial(w: Perm, c: C) -> Self {
        let mut t = BTreeMap::new();
        if !c.is_zero() {
            t.insert(w, c);
        }
        Schubert { terms: t }
    }

    /// `1 = S_id`.
    pub fn one() -> Self {
        Schubert::monomial(Perm::identity(), C::one())
    }

    /// The terms, keyed by permutation. Explicit zeros are never stored, so
    /// the map is empty exactly when the element is.
    pub fn terms(&self) -> &BTreeMap<Perm, C> {
        &self.terms
    }

    /// Whether this is 0.
    pub fn is_zero(&self) -> bool {
        self.terms.is_empty()
    }

    /// The coefficient of `S_w`, zero if `w` does not occur.
    pub fn coeff(&self, w: &Perm) -> C {
        self.terms.get(w).cloned().unwrap_or_else(C::zero)
    }

    /// `self += c·S_w`, removing the entry if it cancels to zero.
    pub fn add_term(&mut self, w: Perm, c: &C) {
        if c.is_zero() {
            return;
        }
        match self.terms.get_mut(&w) {
            Some(slot) => {
                slot.add_assign(c);
                if slot.is_zero() {
                    self.terms.remove(&w);
                }
            }
            None => {
                self.terms.insert(w, c.clone());
            }
        }
    }

    /// The sum, with terms that cancel dropped rather than stored as zero.
    pub fn add(&self, other: &Self) -> Self {
        let mut out = self.clone();
        out.add_assign(other);
        out
    }

    /// `self += other`, in place.
    ///
    /// The in-place form exists because E3's BRANCH step accumulates over
    /// covers, and `acc = acc.add(&part)` copies the whole accumulator once
    /// per cover.
    pub fn add_assign(&mut self, other: &Self) {
        for (w, c) in &other.terms {
            self.add_term(*w, c);
        }
    }

    /// The difference, with terms that cancel dropped rather than stored as
    /// zero.
    pub fn sub(&self, other: &Self) -> Self {
        let mut out = self.clone();
        for (w, c) in &other.terms {
            out.add_term(*w, &c.neg());
        }
        out
    }

    /// `self` scaled by `c`. A zero `c` gives the zero element rather than an
    /// element carrying zero coefficients.
    pub fn scale(&self, c: &C) -> Self {
        let mut out = Schubert::zero();
        for (w, a) in &self.terms {
            out.add_term(*w, &a.mul(c));
        }
        out
    }
}

impl<C: Ring> InPlaceArith<C> for Schubert<C> {
    fn add_from(&mut self, other: &Self) {
        self.add_assign(other);
    }

    fn add_owned(&mut self, mut other: Self) {
        // Addition commutes, so the side with more terms keeps its map.
        if self.terms.len() < other.terms.len() {
            std::mem::swap(self, &mut other);
        }
        for (w, c) in std::mem::take(&mut other.terms) {
            self.add_term(w, &c);
        }
    }

    fn sub_from(&mut self, other: &Self) {
        for (w, c) in &other.terms {
            self.add_term(*w, &c.neg());
        }
    }

    fn negate(&mut self) {
        // -c is zero only when c is, so no term can cancel here.
        for c in self.terms.values_mut() {
            *c = c.neg();
        }
    }

    fn scale_by(&mut self, c: &C) {
        if c.is_zero() {
            self.terms.clear();
            return;
        }
        for v in self.terms.values_mut() {
            *v = v.mul(c);
        }
        // A ring with zero divisors can send a nonzero product to zero.
        self.terms.retain(|_, v| !v.is_zero());
    }
}

impl_linear_ops!(Schubert);
impl_product_ops!(Schubert);

impl<C: Ring> Schubert<C> {
    /// `S_w = s_λ(x₁, …, x_k)` for the Grassmannian `w` of descent `k` and
    /// shape `λ`.
    ///
    /// The convention — `code(w) = (λ_k, …, λ_1)`, i.e. `w(i) = λ_{k+1−i} + i`
    /// for `i ≤ k` with the unused values following in increasing order — was
    /// pinned against Sage over 128 shapes on 2026-07-30, together with the
    /// flag-truncation identity that makes leaf dispatch legal.
    ///
    /// `λ` must have at most `k` parts; otherwise `s_λ(x₁..x_k) = 0` and there
    /// is no such permutation, so this returns `None` rather than inventing
    /// one.
    pub fn grassmannian(lambda: &Partition, k: u32) -> Option<Self> {
        if lambda.len() as u32 > k {
            return None;
        }
        Some(Schubert::monomial(grassmannian_perm(lambda, k)?, C::one()))
    }

    /// `xᵢ · f`, the **signed Monk rule** (1-based), verified against Sage
    /// exhaustively on `S₄ × i ∈ 1..4`:
    ///
    /// ```text
    ///     xᵢ · S_w = Σ_{j>i, cover} S_{w t_{ij}} − Σ_{j<i, cover} S_{w t_{ji}}
    /// ```
    ///
    /// Both sums run over Bruhat covers only. The left sum is why
    /// intermediates are signed even though structure constants are not, and
    /// therefore why `guard`'s checked arithmetic is doing real work here.
    ///
    /// # Panics
    ///
    /// Panics if `i == 0` — variable indices are 1-based — or if a cover scan
    /// reaches past [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT).
    pub fn mul_variable(&self, i: u32) -> Self {
        assert!(i >= 1, "variable indices are 1-based");
        let mut out = Schubert::zero();
        for (w, c) in &self.terms {
            for (_, u) in w.covers_right(i) {
                out.add_term(u, c);
            }
            let neg = c.neg();
            for (_, u) in w.covers_left(i) {
                out.add_term(u, &neg);
            }
        }
        out
    }

    /// `∂ᵢ f` on the Schubert basis: `∂ᵢ S_w = S_{w sᵢ}` when `w(i) > w(i+1)`,
    /// and `0` otherwise. 1-based.
    ///
    /// A second, entirely independent implementation exists on *expanded
    /// polynomials* — `(f − sᵢf)/(xᵢ − xᵢ₊₁)` by exact division — in the tests,
    /// so the two can disagree loudly. They share no machinery, which is the
    /// point.
    ///
    /// # Panics
    ///
    /// Panics if `i == 0` — variable indices are 1-based — or if `i + 1`
    /// reaches past [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT).
    pub fn divided_difference(&self, i: u32) -> Self {
        assert!(i >= 1, "variable indices are 1-based");
        let mut out = Schubert::zero();
        for (w, c) in &self.terms {
            if w.at(i) > w.at(i + 1) {
                out.add_term(w.transpose(i, i + 1), c);
            }
        }
        out
    }

    /// `∂_w`, composing one-letter steps along a reduced word of `w`, applied
    /// left to right.
    ///
    /// With that convention the basis action is `S_v ↦ S_{v·w}` when
    /// `ℓ(v·w) = ℓ(v) − ℓ(w)`, and `0` otherwise. Independent of *which*
    /// reduced word, since `∂` satisfies the braid relations — asserted in the
    /// tests rather than assumed.
    pub fn divided_difference_perm(&self, w: &Perm) -> Self {
        let mut out = self.clone();
        for i in w.reduced_word() {
            out = out.divided_difference(i);
            if out.is_zero() {
                break;
            }
        }
        out
    }

    /// Expand into monomials of `ℤ[x₁, x₂, …]`.
    ///
    /// This is Symmetrica's `algorithmus2` peel (sb.c:323) with the one thing
    /// it lacks: memoization. The recursion tree's leaf count is
    /// `S_w(1,…,1)` — the pipe-dream count, which is super-exponential — while
    /// its distinct states are far fewer (measured 2026-07-30: 2 097 152
    /// leaves against 3 052 states on `stair7`). Here the memo is keyed on
    /// `(perm, stufe)`, the granularity that needs **no** bookkeeping to be
    /// sound.
    ///
    /// The sharper key is `perm` alone — `stufe` is read only at the DESCEND
    /// branch, so it moves the subtree value by a power of a single variable —
    /// and it visits fewer states by a factor that grows with the permutation
    /// (`docs/record/schubert.md`, "The two memo keys, counted"). That
    /// refinement belongs with E3, not with the reference expansion, because
    /// it is exactly the kind of shift bookkeeping that is wrong in a way
    /// tests notice late.
    pub fn expand(&self) -> Vec<(Expo, C)> {
        let mut acc: BTreeMap<Expo, C> = BTreeMap::new();
        let mut memo = PeelMemo::default();
        for (w, c) in &self.terms {
            for (e, k) in memo.peel_perm(w) {
                let term = c.mul(&C::from_u128(k));
                match acc.get_mut(&e) {
                    Some(slot) => {
                        slot.add_assign(&term);
                        if slot.is_zero() {
                            acc.remove(&e);
                        }
                    }
                    None => {
                        if !term.is_zero() {
                            acc.insert(e, term);
                        }
                    }
                }
            }
        }
        acc.into_iter().collect()
    }

    /// Write a polynomial in the Schubert basis: the greedy peel of
    /// `t_POLYNOM_SCHUBERT` (sb.c:232), minus its recompute-everything defect.
    ///
    /// Correct because of **lex-triangularity**: `x^{code(w)}` is the
    /// lex-*minimal* monomial of `S_w` (verified against Sage on 40 random
    /// `S₇`). So the lex-minimal monomial of the remaining polynomial names
    /// its own permutation, and subtracting `c·S_w` strictly shrinks the
    /// problem. Symmetrica relies on this silently; here it is the documented
    /// reason the loop terminates.
    ///
    /// # Panics
    ///
    /// Panics if a monomial's exponent vector, read as a Lehmer code, needs a
    /// permutation past [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT).
    pub fn from_polynomial(terms: &[(Expo, C)]) -> Self {
        let mut rem: BTreeMap<Expo, C> = BTreeMap::new();
        for (e, c) in terms {
            if c.is_zero() {
                continue;
            }
            let e = strip(e.clone());
            match rem.get_mut(&e) {
                Some(slot) => {
                    slot.add_assign(c);
                    if slot.is_zero() {
                        rem.remove(&e);
                    }
                }
                None => {
                    rem.insert(e, c.clone());
                }
            }
        }

        let mut out = Schubert::zero();
        let mut memo = PeelMemo::default();
        while let Some((alpha, c)) = rem.iter().next().map(|(a, c)| (a.clone(), c.clone())) {
            let w = Perm::from_code(&alpha);
            out.add_term(w, &c);
            for (e, k) in memo.peel_perm(&w) {
                let sub = c.mul(&C::from_u128(k)).neg();
                match rem.get_mut(&e) {
                    Some(slot) => {
                        slot.add_assign(&sub);
                        if slot.is_zero() {
                            rem.remove(&e);
                        }
                    }
                    None => {
                        if !sub.is_zero() {
                            rem.insert(e, sub);
                        }
                    }
                }
            }
            debug_assert!(
                !rem.contains_key(&alpha),
                "peel failed to clear its own lex-minimal monomial — triangularity violated"
            );
        }
        out
    }

    /// **E1**, the reference product and permanent oracle: expand the factor
    /// with the smaller pipe-dream count, then run a Monk chain per monomial.
    ///
    /// This is Symmetrica's route, with its factor-choice heuristic fixed —
    /// `mult_schubert_schubert` compares only the *head term's* vector length,
    /// which is not even a proxy for the cost it is trying to avoid. Here the
    /// choice uses [`dimension`], the actual leaf count.
    ///
    /// Cost is `#pipe dreams × Monk chains`, the two compounding blowups
    /// behind the S₁₀ wall. That is intended: this engine's job is to be
    /// obviously correct.
    pub fn mul_naive(&self, other: &Self) -> Self {
        if self.is_zero() || other.is_zero() {
            return Schubert::zero();
        }
        let (expand_side, keep_side) = if total_dimension(self) <= total_dimension(other) {
            (self, other)
        } else {
            (other, self)
        };
        let mut out = Schubert::zero();
        for (alpha, c) in expand_side.expand() {
            let mut t = keep_side.clone();
            for (j, &e) in alpha.iter().enumerate() {
                for _ in 0..e {
                    t = t.mul_variable((j + 1) as u32);
                }
            }
            for (w, a) in &t.terms {
                out.add_term(*w, &a.mul(&c));
            }
        }
        out
    }

    /// The product `S_u · S_v`, by whichever engine is currently the best one.
    ///
    /// **That is [`mul_e2`](Self::mul_e2), the memoized transition** — ahead of
    /// the C `schubmult` where that finishes, and completing rows it does not.
    /// [`mul_e3`](Self::mul_e3) is kept as the comparison rather than as a
    /// route anyone should take. `docs/record/schubert.md`'s ladder ranks the
    /// engines and the C `schubmult`.
    ///
    /// Callers wanting a specific engine name it: [`mul_naive`](Self::mul_naive)
    /// is E1, the permanent oracle; `mul_e2` and `mul_e3` are the two engines.
    /// This function is free to change which one it delegates to.
    pub fn mul(&self, other: &Self) -> Self {
        self.mul_e2(other)
    }

    /// **E3**: evaluate the merged peel DAG of one factor once, carrying the
    /// partial product at every state.
    ///
    /// E1 walks a *tree* whose leaves are pipe dreams and re-runs a Monk chain
    /// per leaf. E3 walks the same recursion as a **DAG**, merging states, and
    /// stores `V(state)·S_u` at each. The transitions become operators:
    /// DESCEND is `stufe` applications of [`Schubert::mul_variable`], BRANCH
    /// is an addition, and the leaf is `S_u` or `x_level·S_u`.
    ///
    /// **Superseded by [`mul_e2`](Self::mul_e2), and the reason is the whole
    /// lesson of this module.** A pre-implementation measurement of *state
    /// compression* — `pipe dreams ÷ states`, 687× on `stair7` and 125 599× on
    /// an S₁₃ element — pointed hard at this engine, so it was built first. It
    /// duly beat E1, then lost to the C `schubmult`, then lost to E2.
    /// `docs/record/schubert.md`'s ladder carries the numbers. Both engines
    /// cost (nodes) × (size of the running element); **the metric counted only
    /// nodes**. On `S_11.1` E2 uses *more* nodes than E3 and still wins,
    /// because E1 and E3 expand a factor into monomials so the running element
    /// inflates to answer-size early, while the transition recursion never
    /// expands.
    ///
    /// Kept, and kept tested, so the comparison stays reproducible.
    ///
    /// Keyed on `(perm, level, stufe)` — the granularity that is sound with no
    /// bookkeeping. Merging on `perm` alone visits fewer states
    /// (`docs/record/schubert.md`, "The two memo keys, counted") and was never
    /// done: it needs a shift by a power of `x_level`, hence more Monk passes,
    /// and E2 overtook the engine before the trade was worth measuring.
    pub fn mul_e3(&self, other: &Self) -> Self {
        if self.is_zero() || other.is_zero() {
            return Schubert::zero();
        }
        // Choose by *state* count, not pipe dreams: states are what E3 pays.
        // (E1's choice by `dimension` is right for E1 and wrong here — the two
        // orders differ, since compression varies by permutation shape.)
        let (peel_side, keep_side) = if total_states(self) <= total_states(other) {
            (self, other)
        } else {
            (other, self)
        };
        let mut out = Schubert::zero();
        for (w, c) in peel_side.terms() {
            let part = E3 {
                keep: keep_side,
                memo: HashMap::new(),
            }
            .eval_perm(w);
            for (v, a) in &part.terms {
                out.add_term(*v, &a.mul(c));
            }
        }
        out
    }

    /// **E2**, the memoized transition recursion. Recurse on the *second*
    /// factor with Lascoux–Schützenberger:
    ///
    /// ```text
    ///     S_u · S_v = x_r · (S_u · S_v')  +  Σ (S_u · S_v'')
    /// ```
    ///
    /// where `(r, v', {v''}) = v.transition()`, `ℓ(v') = ℓ(v) − 1`, and each
    /// `ℓ(v'') = ℓ(v)`. Base case: `v` dominant, where `S_v` is the single
    /// monomial `x^{code(v)}` and the product is `ℓ(v)` Monk passes.
    ///
    /// **Why this exists even though E3 already works.** E1 and E3 both expand
    /// one factor into monomials, so both pay (number of nodes) × (size of the
    /// running element). On a large-output case that second factor is the size
    /// of the answer. E3's gap to the C `schubmult` therefore widens with the
    /// output size, far beyond what the staircases show
    /// (`docs/record/schubert.md`). E2 has the same *shape* of cost, so it is
    /// not automatically better; what differs is the node count, and whether
    /// the transition tree is smaller than the peel DAG is a measurement, not
    /// an argument. `examples/bench_e2.rs` makes it.
    ///
    /// ⚠️ Termination is not obvious and is not proved here: the `v''` have the
    /// *same* length as `v`, so the recursion does not descend on `ℓ`. It is
    /// the recursion `newtrans` (mss.c:44) has relied on for thirty years, and
    /// Macdonald's notes prove the tree finite. [`Schubert::mul_e2_depth`]
    /// carries an explicit depth cap so a counterexample is a clean panic
    /// rather than a hang.
    ///
    /// # Panics
    ///
    /// Panics if the transition recursion reaches depth 4096, the cap this
    /// function passes to [`mul_e2_depth`](Self::mul_e2_depth). Panics also if
    /// a Monk cover scan reaches past
    /// [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT).
    pub fn mul_e2(&self, other: &Self) -> Self {
        self.mul_e2_depth(other, 4096).0
    }

    /// [`Schubert::mul_e2`] with an explicit recursion cap, also returning the
    /// two cost counters — nodes visited and Monk passes performed — because
    /// those are what the E2-vs-E3 comparison actually turns on.
    ///
    /// # Panics
    ///
    /// Panics if the transition recursion reaches depth `cap`. Panics also if a
    /// Monk cover scan reaches past
    /// [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT).
    pub fn mul_e2_depth(&self, other: &Self, cap: u32) -> (Self, u64, u64) {
        if self.is_zero() || other.is_zero() {
            return (Schubert::zero(), 0, 0);
        }
        let mut out = Schubert::zero();
        let (mut nodes, mut passes) = (0u64, 0u64);
        for (w, c) in other.terms() {
            let mut refs = HashMap::new();
            count_transition_parents(w, &mut refs);
            let mut e2 = E2 {
                keep: self,
                target: None,
                memo: HashMap::new(),
                refs,
                cap,
                passes: 0,
                nodes: 0,
                peak_live: 0,
            };
            let part = e2.eval(w, 0);
            nodes += e2.nodes;
            passes += e2.passes;
            for (v, a) in &part.terms {
                out.add_term(*v, &a.mul(c));
            }
        }
        (out, nodes, passes)
    }

    /// The Poincaré pairing on `H*(Fl(n))`: `⟨S_u, S_v⟩ = δ_{v, w₀u}`, i.e.
    /// the coefficient of `S_{w₀⁽ⁿ⁾}` in the product.
    ///
    /// **`n` is an explicit argument**, unlike the incumbent.
    /// `scalarproduct_schubert` (sb.c:1840) reads `n` off however long the
    /// stored vectors happen to be, so the same mathematical inputs give
    /// different answers depending on prior padding — semantics a caller
    /// cannot predict. It also computes the full product and then runs
    /// `n(n−1)/2` divided-difference passes; reading one coefficient is the
    /// same number.
    ///
    /// # Panics
    ///
    /// Panics if `n` exceeds [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT),
    /// which is the only way `w₀⁽ⁿ⁾` fails to be representable — the reversal
    /// of `1..=n` is a permutation for every other `n`, including `n = 0`.
    pub fn pairing(&self, other: &Self, n: u32) -> C {
        let w0 = Perm::new((1..=n).rev())
            .expect("the reversal of 1..=n is a permutation unless n > MAX_SUPPORT");
        self.mul(other).coeff(&w0)
    }

    /// `∂_{w₀⁽ⁿ⁾}(f · g)` — Symmetrica's `scalarproduct_schubert` (sb.c:1840),
    /// which Sage exposes as `SchubertPolynomial.scalar_product`.
    ///
    /// **The value is a Schubert polynomial, not a scalar**, and it is a
    /// different map from [`pairing`](Self::pairing). The two meet in one
    /// place: `∂_{w₀⁽ⁿ⁾} S_w = S_{w·w₀⁽ⁿ⁾}` when `w(1) > … > w(n)` and `0`
    /// otherwise, so the coefficient of `S_id` here is exactly
    /// `⟨f, g⟩` — and everything of higher degree, which `pairing` cannot see,
    /// survives. Reading the name as the pairing is the error
    /// `docs/record/schubert.md` records.
    ///
    /// **`n` is an explicit argument**, as it is for [`pairing`](Self::pairing).
    /// The incumbent reads it off however long its stored vectors happen to be,
    /// so the same mathematical inputs answer differently after padding. What a
    /// Sage caller reaches is the special case `n` = the longest one-line form
    /// among the terms of both arguments, since Sage strips trailing fixed
    /// points before the call; choosing `n` that way is the adapter's job
    /// (`docs/policies/python.md`, P5), not the kernel's.
    ///
    /// Every surviving term drops `ℓ(w₀⁽ⁿ⁾) = n(n−1)/2` in degree, so the
    /// result is zero whenever `n(n−1)/2` exceeds the product's degree. At
    /// `n ≤ 1` the operator is the identity and the product comes back
    /// unchanged; either argument being zero gives zero.
    ///
    /// # Panics
    ///
    /// Panics if `n` exceeds [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT),
    /// which is the only way `w₀⁽ⁿ⁾` fails to be representable. Panics also
    /// wherever [`mul`](Self::mul) does.
    ///
    /// # Examples
    ///
    /// `S_{21}·S_{21} = x₁² = S_{312}`, and the single pass at `n = 2` leaves
    /// `S_{132}`. That value is what separates this map from the pairing, which
    /// answers `0` on the same input.
    ///
    /// ```
    /// use symfn::permutation::Perm;
    /// use symfn::schubert::Schubert;
    /// let u: Schubert<i64> = Schubert::monomial(Perm::new([2u32, 1]).unwrap(), 1);
    /// let want = Schubert::monomial(Perm::new([1u32, 3, 2]).unwrap(), 1);
    /// assert_eq!(u.scalar_product(&u, 2), want);
    /// assert_eq!(u.pairing(&u, 2), 0);
    /// ```
    ///
    /// The rank is not a formality — the same inputs at `n = 3` give zero,
    /// because `ℓ(w₀⁽³⁾) = 3` is past the product's degree of 2.
    ///
    /// ```
    /// # use symfn::permutation::Perm;
    /// # use symfn::schubert::Schubert;
    /// let u: Schubert<i64> = Schubert::monomial(Perm::new([2u32, 1]).unwrap(), 1);
    /// assert!(u.scalar_product(&u, 3).is_zero());
    /// ```
    pub fn scalar_product(&self, other: &Self, n: u32) -> Self {
        let w0 = Perm::new((1..=n).rev())
            .expect("the reversal of 1..=n is a permutation unless n > MAX_SUPPORT");
        self.mul(other).divided_difference_perm(&w0)
    }
}

/// The Grassmannian permutation of descent `k` and shape `λ` (at most `k`
/// parts): `w(i) = λ_{k+1−i} + i` for `i ≤ k`, unused values in order after.
///
/// Returns `None` when λ has more than `k` parts: then `s_λ(x₁..x_k) = 0` and
/// there is no such permutation. Returns `None` also when the permutation's
/// `λ₁ + k` points exceed [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT).
pub fn grassmannian_perm(lambda: &Partition, k: u32) -> Option<Perm> {
    if lambda.len() as u32 > k {
        return None;
    }
    let k = k as usize;
    let mut head: Vec<u32> = Vec::with_capacity(k);
    for i in 1..=k {
        head.push(lambda.part(k - i) + i as u32);
    }
    let n = head.iter().copied().max().unwrap_or(0);
    let used: std::collections::BTreeSet<u32> = head.iter().copied().collect();
    let mut v = head;
    v.extend((1..=n).filter(|x| !used.contains(x)));
    Perm::new(v).ok()
}

/// `1 × w`: the shift `w'(1) = 1`, `w'(i+1) = w(i) + 1`.
///
/// Stanley symmetric functions are invariant under it, which is what makes it
/// a legal move rather than a different question.
fn shift_up(w: &Perm) -> Perm {
    let m = w.support_len();
    let mut v = Vec::with_capacity(m as usize + 1);
    v.push(1);
    for i in 1..=m {
        v.push(w.at(i) + 1);
    }
    Perm::new(v).expect("the shift 1 x w is a permutation unless it exceeds MAX_SUPPORT")
}

/// The **Stanley symmetric function** `F_w`, expanded in Schur functions.
///
/// The transition recursion with the `x_r·S_v` term dropped:
/// `F_w = Σ F_{v t_{qr}}` over the same left covers, with the Grassmannian
/// base case `F_w = s_λ` and the `F_w = F_{1×w}` shift when the left sum is
/// empty. Iterative with an explicit stack, per the incumbent, minus its
/// static `char[1000]`.
///
/// ⚠️ **This is not "Schubert → Schur".** Symmetrica exports it as
/// `t_SCHUBERT_SCHUR` and Sage inherits that name, but `F_w = S_w` only in the
/// stable range: `newtrans([2,1,4,3]) = s₂ + s₁₁` while `S_{2143}` is not even
/// symmetric. The name here says what it computes.
///
/// This is the module's one bridge into `Sym`, and the only reason `Schur`
/// appears in this file.
///
/// # Panics
///
/// Panics if the transition tree takes more than `2²⁴` steps. The cap is a
/// backstop against a non-terminating recursion, which would otherwise hang
/// rather than fail; it is **not** a measured capacity wall, and where in `S_n`
/// a legitimate expansion first reaches it is unmeasured.
///
/// Also if the shift `1 × w` would exceed
/// [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT).
pub fn stanley<C: Ring>(w: &Perm) -> Schur<C> {
    use crate::sym::SymFn;
    let mut out: Schur<C> = Schur::zero();
    let mut stack = vec![*w];
    let mut steps = 0u64;
    while let Some(p) = stack.pop() {
        crate::interrupt::poll();
        steps += 1;
        assert!(
            steps < 1 << 24,
            "stanley: transition tree failed to terminate"
        );
        // last_descent() is the same test as is_grassmannian() for this
        // purpose and allocates nothing: no descent, or one, means vexillary
        // with a single Schur term.
        let Some(r) = p.last_descent() else {
            // identity: F = s_empty
            let lambda = Partition::default();
            let c = out.coeff(&lambda);
            let mut c = c;
            c.add_assign(&C::one());
            out.terms_mut().insert(lambda, c);
            continue;
        };
        if p.is_grassmannian().is_some() {
            // Grassmannian is vexillary with shape = its code sorted; for a
            // single descent the code is already weakly increasing.
            let lambda = Partition::new(p.code());
            let c = out.coeff(&lambda);
            let mut c = c;
            c.add_assign(&C::one());
            out.terms_mut().insert(lambda, c);
            continue;
        }
        // transition, inlined so nothing is allocated: the ups go straight
        // onto the work stack instead of through two intermediate `Vec`s.
        let wr = p.at(r);
        let s = (r + 1..=p.support_len())
            .rfind(|&s| p.at(s) < wr)
            .expect("a descent has something smaller to its right");
        let v = p.transpose(r, s);
        let before = stack.len();
        v.for_each_cover_left(r, |_, u| stack.push(u));
        if stack.len() == before {
            // no room to the left of r; shifting makes room and F is invariant
            stack.push(shift_up(&p));
        }
    }
    out
}

/// `S_u(1,…,1)·S_v(1,…,1)`: the product's total monomial mass. The one cheap
/// quantity that flags an out-of-family pair, and deliberately not enforced
/// anywhere.
///
/// # Range
///
/// **Saturates** at `u128::MAX` rather than overflowing, which is why R4
/// (`docs/policies/failure.md`) permits it here: this is a magnitude used to
/// decide "too big to attempt", and a pair whose true mass exceeds `u128` is
/// one the saturated value classifies identically. A caller reading it as the
/// exact mass rather than as a cost signal is reading it wrong — at that
/// magnitude the product is unattemptable regardless. A factor whose own
/// count [`dimension`] declines to give saturates the same way.
pub fn schubert_monomial_mass_of(u: &Perm, v: &Perm) -> u128 {
    let count = |w: &Perm| dimension(w).unwrap_or(u128::MAX);
    count(u).saturating_mul(count(v))
}

/// A single structure constant `c^w_{uv}`, without building the whole product.
///
/// The motivating case is the one no engine can complete: `S_13 ℓ=25,36` has a
/// monomial mass of 4.3×10¹⁶, so its full expansion cannot be materialized on
/// any machine. One coefficient of it is still a perfectly reasonable
/// question, and asking it is what positivity searches and rule-hunting
/// actually do.
///
/// Runs E2 with every term not `≤ w` in Bruhat order discarded at each node.
/// The pruning is sound because signed Monk moves strictly up the Bruhat order
/// (`monk_covers_move_up_the_bruhat_order`), so nothing below the cut can
/// reach `w`. It is also *cheap* to check — the tableau criterion on an inline
/// `Perm` — which matters because it runs on every surviving term.
///
/// Returns zero immediately unless `ℓ(w) = ℓ(u) + ℓ(v)` and `u ≤ w`, `v ≤ w`;
/// those are necessary conditions
/// (`product_support_lies_above_both_factors`), and they alone answer most
/// queries with no work at all.
///
/// # Panics
///
/// Panics if the transition recursion reaches depth 4096, the cap this function
/// gives E2. Panics also if a Monk cover scan reaches past
/// [`MAX_SUPPORT`](crate::permutation::MAX_SUPPORT).
pub fn schubert_coeff<C: Ring>(u: &Perm, v: &Perm, w: &Perm) -> C {
    if w.length() != u.length() + v.length() || !u.bruhat_le(w) || !v.bruhat_le(w) {
        return C::zero();
    }
    // c^w_{uv} = c^w_{vu}, so recurse on whichever side has the smaller
    // transition tree. `transition_tree` builds no elements, so asking is
    // microseconds. This is the `lr_coeff` lesson applied before the fact
    // rather than after: peeling the wrong side cost 21x there.
    let (recurse, keep_perm) = if transition_tree(v).0 <= transition_tree(u).0 {
        (v, u)
    } else {
        (u, v)
    };
    let keep: Schubert<C> = Schubert::monomial(*keep_perm, C::one());
    let mut refs = HashMap::new();
    count_transition_parents(recurse, &mut refs);
    let mut e2 = E2 {
        keep: &keep,
        target: Some(*w),
        memo: HashMap::new(),
        refs,
        cap: 4096,
        passes: 0,
        nodes: 0,
        peak_live: 0,
    };
    let out = e2.eval(recurse, 0);
    out.coeff(w)
}

/// `S_w(1,…,1)` — the number of pipe dreams of `w`, and exactly the leaf count
/// of the peel recursion. `None` if the count does not fit `u128`, and that is
/// the only `None`; the identity gives `Some(1)`.
///
/// Not re-exported at the crate root: [`crate::eval::dimension`] is a
/// different function on partitions, and two `dimension`s in one namespace is
/// how a caller gets a plausible wrong answer. The two share their shape: both
/// decline past `u128` rather than panicking, since the count is the whole
/// answer and a caller asking for it can only want it or not.
pub fn dimension(w: &Perm) -> Option<u128> {
    PeelMemo::default().count(w)
}

/// Number of distinct `(perm, level, stufe)` states in the peel DAG of `w` —
/// E3's cost, the way [`dimension`] is E1's.
///
/// Cheap: it walks the DAG the product would walk anyway, without building any
/// element at the states.
pub fn peel_states(w: &Perm) -> u64 {
    let m = w.support_len();
    if m == 0 {
        return 1;
    }
    let n = m;
    let mut seen = std::collections::HashSet::new();
    let mut stack = vec![(w.padded(m), m.saturating_sub(1))];
    while let Some((p, stufe)) = stack.pop() {
        crate::interrupt::poll();
        let len = p.len() as u32;
        if !seen.insert((p.clone(), n - len + 1, stufe)) {
            continue;
        }
        if len <= 2 {
            continue;
        }
        if p[0] == len {
            stack.push((p[1..].to_vec(), len.saturating_sub(2)));
        } else {
            for q in covers_at_1(&p) {
                stack.push((q, stufe.saturating_sub(1)));
            }
        }
    }
    seen.len() as u64
}

/// Saturating by R4's estimate clause: the sum is only ever compared against
/// another `total_states` to pick which side to expand, so saturation changes
/// the answer only when both sides saturate — where the two are equally
/// hopeless and either choice is as good. An exact width here would buy a
/// panic on a quantity that is not part of any result.
fn total_states<C: Ring>(f: &Schubert<C>) -> u64 {
    f.terms()
        .keys()
        .map(peel_states)
        .fold(0u64, |a, b| a.saturating_add(b))
}

/// E2's evaluator: the transition tree with `S_u·S_v` cached at each node
/// **only until its last parent has consumed it**.
///
/// The memo has to be evicted, not merely populated. A node's cached value is
/// a whole product — on `S_13.2` the answer alone is 3.2M terms — so retaining
/// every node for the length of the run is gigabytes. Before this existed,
/// `S_13 ℓ=25,36` died out of memory (`docs/record/schubert.md`): the failure
/// predicted for E3 in as many words, which E2 then shipped anyway.
///
/// So a pre-pass counts how many parents each node has, and `eval` drops a
/// child's value the moment the last of them is done with it. The pre-pass is
/// cheap in the way that matters: it walks the same tree using only `Perm`
/// operations, computing no products.
struct E2<'a, C: Ring> {
    keep: &'a Schubert<C>,
    /// When set, drop every term not `≤ target` in Bruhat order. Sound
    /// because Monk only moves up (both facts are tested), so a dropped term
    /// can reach the target neither directly nor by canceling against
    /// something that does.
    target: Option<Perm>,
    memo: HashMap<Perm, std::rc::Rc<Schubert<C>>>,
    /// Parents not yet served, per node. At zero the memo entry is dropped.
    refs: HashMap<Perm, u32>,
    cap: u32,
    passes: u64,
    /// Distinct nodes evaluated. Not `memo.len()` any more — that is now the
    /// *live* set, and an entry leaves it as its last parent is served.
    nodes: u64,
    /// High-water mark of the live set.
    peak_live: usize,
}

/// Size of E2's transition tree for `w`: `(distinct nodes, total edges)`.
///
/// **Computes no products.** It walks exactly the tree `mul_e2` walks using
/// only `Perm` operations, so it finishes on inputs whose actual product does
/// not — which makes it the probe for asking *why* a case is hard before paying
/// to find out. `edges − nodes + 1` is the amount of sharing the memo captures.
pub fn transition_tree(w: &Perm) -> (u64, u64) {
    let mut refs = HashMap::new();
    count_transition_parents(w, &mut refs);
    let nodes = refs.len() as u64;
    let edges: u64 = refs.values().map(|&n| n as u64).sum();
    (nodes, edges)
}

/// Count parent references over the transition tree, expanding each distinct
/// node once. The root gets one reference, from the caller.
fn count_transition_parents(root: &Perm, refs: &mut HashMap<Perm, u32>) {
    let mut stack = vec![*root];
    let mut expanded = std::collections::HashSet::new();
    while let Some(p) = stack.pop() {
        crate::interrupt::poll();
        *refs.entry(p).or_insert(0) += 1;
        if !expanded.insert(p) || p.is_dominant() {
            continue;
        }
        let (_, vp, ups) = p.transition().expect("non-dominant implies a descent");
        stack.push(vp);
        stack.extend(ups);
    }
}

impl<C: Ring> E2<'_, C> {
    /// Note the child's value has been consumed; drop it if no parent remains.
    fn release(&mut self, child: &Perm) {
        if let Some(n) = self.refs.get_mut(child) {
            *n = n.saturating_sub(1);
            if *n == 0 {
                self.memo.remove(child);
            }
        }
    }

    fn eval(&mut self, v: &Perm, depth: u32) -> std::rc::Rc<Schubert<C>> {
        if let Some(r) = self.memo.get(v) {
            return std::rc::Rc::clone(r);
        }
        assert!(
            depth < self.cap,
            "E2 recursion exceeded depth {} at {v} — the transition tree was \
             supposed to be finite",
            self.cap
        );
        let out = if v.is_dominant() {
            // S_v is the single monomial x^code(v); the identity lands here
            // too, with an empty code and no work.
            let mut acc = self.keep.clone();
            for (i, &e) in v.code().iter().enumerate() {
                for _ in 0..e {
                    acc = acc.mul_variable(i as u32 + 1);
                    self.passes += 1;
                }
            }
            acc
        } else {
            let (r, vp, ups) = v.transition().expect("non-dominant implies a descent");
            let child = self.eval(&vp, depth + 1);
            let mut acc = child.mul_variable(r);
            self.passes += 1;
            drop(child);
            self.release(&vp);
            for u in &ups {
                let part = self.eval(u, depth + 1);
                acc.add_assign(&part);
                drop(part);
                self.release(u);
            }
            acc
        };
        self.nodes += 1;
        let mut out = out;
        if let Some(t) = &self.target {
            out.terms.retain(|z, _| z.bruhat_le(t));
        }
        let out = std::rc::Rc::new(out);
        self.memo.insert(*v, std::rc::Rc::clone(&out));
        self.peak_live = self.peak_live.max(self.memo.len());
        out
    }
}

/// E3's evaluator: the peel DAG with `V(state)·S_u` cached at every state.
struct E3<'a, C: Ring> {
    keep: &'a Schubert<C>,
    /// `Rc`, not the element itself: a state's value is read once per parent
    /// and the DAG is what makes parents plural, so a by-value memo copies
    /// whole elements for no reason.
    memo: HashMap<(Vec<u32>, u32, u32), std::rc::Rc<Schubert<C>>>,
}

impl<C: Ring> E3<'_, C> {
    fn eval_perm(mut self, w: &Perm) -> Schubert<C> {
        let m = w.support_len();
        if m == 0 {
            return self.keep.clone();
        }
        let v = w.padded(m);
        let r = self.eval(&v, m, m.saturating_sub(1));
        std::rc::Rc::try_unwrap(r).unwrap_or_else(|rc| (*rc).clone())
    }

    fn eval(&mut self, p: &[u32], n: u32, stufe: u32) -> std::rc::Rc<Schubert<C>> {
        let m = p.len() as u32;
        let level = n - m + 1;
        let key = (p.to_vec(), level, stufe);
        if let Some(v) = self.memo.get(&key) {
            return std::rc::Rc::clone(v);
        }
        let out = if m <= 2 {
            // LEAF: V = x_level for the transposition, 1 for the identity.
            if m == 2 && p[0] == 2 {
                self.keep.mul_variable(level)
            } else {
                self.keep.clone()
            }
        } else if p[0] == m {
            // DESCEND: V = x_level^stufe · (the subtree one alphabet along)
            let child = self.eval(&p[1..], n, m.saturating_sub(2));
            if stufe == 0 {
                (*child).clone()
            } else {
                let mut acc = child.mul_variable(level);
                for _ in 1..stufe {
                    acc = acc.mul_variable(level);
                }
                acc
            }
        } else {
            // BRANCH: sum over the covers raising p[0]
            let mut acc = Schubert::zero();
            for q in covers_at_1(p) {
                let part = self.eval(&q, n, stufe.saturating_sub(1));
                acc.add_assign(&part);
            }
            acc
        };
        let out = std::rc::Rc::new(out);
        self.memo.insert(key, std::rc::Rc::clone(&out));
        out
    }
}

/// Saturating for the same reason as [`total_states`]: a dispatch magnitude
/// compared only against its own counterpart, never returned as a result.
fn total_dimension<C: Ring>(f: &Schubert<C>) -> u128 {
    f.terms()
        .keys()
        .map(|w| dimension(w).unwrap_or(u128::MAX))
        .fold(0u128, |a, b| a.saturating_add(b))
}

// ---------------------------------------------------------------------------
// the peel recursion (Symmetrica `algorithmus2`, sb.c:323)
// ---------------------------------------------------------------------------

/// Memo for the peel, keyed on `(one-line prefix, level, stufe)`.
///
/// The C carries `(vorfaktor, alphabetindex, stufe, perm)` and merges nothing.
/// One of those is genuinely derivable — the accumulated prefix `vorfaktor`
/// belongs outside the subtree, so the subtree value is a function of the
/// rest.
///
/// **`level` must stay in the key even though `len(perm)` pins it.** It pins
/// it only *within one top-level call*: `level = n − len(p) + 1`, and `n`
/// differs between permutations. A memo shared across `S_{132}` (n = 3) and
/// `S_{1423}` (n = 4) would hand a length-3 state computed in `x₁, x₂` back to
/// a caller expecting `x₂, x₃`. [`Schubert::from_polynomial`] shares one memo
/// across permutations of different sizes, so that is where the collision would
/// occur.
#[derive(Default)]
struct PeelMemo {
    poly: HashMap<(Vec<u32>, u32, u32), Vec<(Expo, u128)>>,
    /// Leaf counts need no `level` or `stufe`: neither can change how many
    /// leaves a subtree has, only which monomials they carry. This is the
    /// `states_p` granularity of the compression table.
    count: HashMap<Vec<u32>, u128>,
}

impl PeelMemo {
    fn peel_perm(&mut self, w: &Perm) -> Vec<(Expo, u128)> {
        let m = w.support_len();
        if m == 0 {
            return vec![(Vec::new(), 1)];
        }
        let v = w.padded(m);
        let n = v.len() as u32;
        self.peel(&v, n, m.saturating_sub(1))
    }

    /// `V(p, level, stufe)` in absolute variable indices, where
    /// `level = n − len(p) + 1`.
    fn peel(&mut self, p: &[u32], n: u32, stufe: u32) -> Vec<(Expo, u128)> {
        let m = p.len() as u32;
        let level = n - m + 1;
        let key = (p.to_vec(), level, stufe);
        if let Some(v) = self.poly.get(&key) {
            return v.clone();
        }
        let out: Vec<(Expo, u128)> = if m <= 2 {
            // LEAF: the identity contributes 1, the transposition x_level.
            let mut e = Vec::new();
            if m == 2 && p[0] == 2 {
                e = vec![0; level as usize];
                e[(level - 1) as usize] = 1;
            }
            vec![(strip(e), 1)]
        } else if p[0] == m {
            // DESCEND: x_level^stufe · (the rest, one alphabet along)
            let sub = self.peel(&p[1..], n, m.saturating_sub(2));
            let mut acc: BTreeMap<Expo, u128> = BTreeMap::new();
            for (e, k) in sub {
                let mut e2 = e;
                if stufe > 0 {
                    if e2.len() < level as usize {
                        e2.resize(level as usize, 0);
                    }
                    e2[(level - 1) as usize] += stufe;
                }
                *acc.entry(strip(e2)).or_insert(0) += k;
            }
            acc.into_iter().collect()
        } else {
            // BRANCH: the covers raising p[0], stufe one lower
            let mut acc: BTreeMap<Expo, u128> = BTreeMap::new();
            for q in covers_at_1(p) {
                for (e, k) in self.peel(&q, n, stufe.saturating_sub(1)) {
                    *acc.entry(e).or_insert(0) += k;
                }
            }
            acc.into_iter().collect()
        };
        self.poly.insert(key, out.clone());
        out
    }

    /// Leaf count only — the same DAG without building polynomials. `None`
    /// once a count leaves `u128`, and nothing past that point is memoized.
    fn count(&mut self, w: &Perm) -> Option<u128> {
        let m = w.support_len();
        if m == 0 {
            return Some(1);
        }
        let v = w.padded(m);
        self.count_rec(&v)
    }

    fn count_rec(&mut self, p: &[u32]) -> Option<u128> {
        if let Some(&v) = self.count.get(p) {
            return Some(v);
        }
        let m = p.len() as u32;
        let out = if m <= 2 {
            1
        } else if p[0] == m {
            self.count_rec(&p[1..])?
        } else {
            covers_at_1(p)
                .into_iter()
                .try_fold(0u128, |a, q| a.checked_add(self.count_rec(&q)?))?
        };
        self.count.insert(p.to_vec(), out);
        Some(out)
    }
}

/// The Bruhat covers `p ⋖ p·t_{1,i}` raising `p[0]`, in Symmetrica's
/// running-minimum scan order.
///
/// This is [`Perm::covers_right`] at `i = 1` specialized to a raw padded
/// vector: the peel works on fixed-length vectors of a known `n`, and routing
/// through `Perm` would strip fixed points and lose the level bookkeeping.
fn covers_at_1(p: &[u32]) -> Vec<Vec<u32>> {
    let mut out = Vec::new();
    let mut running_min = u32::MAX;
    for i in 1..p.len() {
        if p[i] > p[0] && p[i] < running_min {
            running_min = p[i];
            let mut q = p.to_vec();
            q.swap(0, i);
            out.push(q);
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn p(v: &[u32]) -> Perm {
        Perm::new(v.iter().copied()).unwrap()
    }

    fn sch(v: &[u32]) -> Schubert<i64> {
        Schubert::monomial(p(v), 1)
    }

    fn expo(e: &[u32]) -> Expo {
        strip(e.to_vec())
    }

    // --- layer 1: hand values ----------------------------------------------

    #[test]
    fn hand_values() {
        // S_132 = x1 + x2
        assert_eq!(
            sch(&[1, 3, 2]).expand(),
            vec![(expo(&[0, 1]), 1), (expo(&[1]), 1)]
        );
        // S_321 = x1^2 x2   (dominant, one monomial)
        assert_eq!(sch(&[3, 2, 1]).expand(), vec![(expo(&[2, 1]), 1)]);
        // S_1423 = x1^2 + x1x2 + x2^2   (Knutson p.6, the pipe-dream example)
        assert_eq!(
            sch(&[1, 4, 2, 3]).expand(),
            vec![(expo(&[0, 2]), 1), (expo(&[1, 1]), 1), (expo(&[2]), 1)]
        );
        // S_id = 1
        assert_eq!(Schubert::<i64>::one().expand(), vec![(expo(&[]), 1)]);
    }

    #[test]
    fn dominant_is_a_single_monomial() {
        for n in 0..=6u32 {
            for w in crate::permutation::tests::all_perms(n) {
                if w.is_dominant() {
                    let e = sch(&w.padded(n)).expand();
                    assert_eq!(e.len().max(1), 1, "{w} expanded to {e:?}");
                    assert_eq!(e[0].0, strip(w.code()), "{w}");
                    assert_eq!(dimension(&w), Some(1), "{w}");
                }
            }
        }
    }

    #[test]
    fn grassmannian_matches_schur_in_k_variables() {
        // S_w = s_lambda(x_1..x_k); check the two smallest by hand, plus the
        // shape/permutation convention.
        let w = grassmannian_perm(&Partition::new([1]), 2).unwrap();
        assert_eq!(w, p(&[1, 3, 2]));
        let w = grassmannian_perm(&Partition::new([2, 1]), 2).unwrap();
        assert_eq!(w, p(&[2, 4, 1, 3]));
        assert_eq!(w.is_grassmannian(), Some(2));
        // s_{2,1}(x1,x2) = x1^2 x2 + x1 x2^2
        assert_eq!(
            sch(&[2, 4, 1, 3]).expand(),
            vec![(expo(&[1, 2]), 1), (expo(&[2, 1]), 1)]
        );
        // more parts than variables has no Grassmannian permutation
        assert!(grassmannian_perm(&Partition::new([1, 1, 1]), 2).is_none());
    }

    // --- layer 2: structural laws ------------------------------------------

    #[test]
    fn degree_equals_length() {
        for n in 0..=6u32 {
            for w in crate::permutation::tests::all_perms(n) {
                for (e, _) in sch(&w.padded(n)).expand() {
                    assert_eq!(e.iter().sum::<u32>(), w.length(), "{w} term {e:?}");
                }
            }
        }
    }

    #[test]
    fn divided_difference_is_nilpotent_and_braided() {
        for n in 2..=5u32 {
            for w in crate::permutation::tests::all_perms(n) {
                let f = sch(&w.padded(n));
                for i in 1..n {
                    // d_i d_i = 0
                    assert!(
                        f.divided_difference(i).divided_difference(i).is_zero(),
                        "{w} {i}"
                    );
                    // commuting braid relation
                    for j in (i + 2)..n {
                        let a = f.divided_difference(i).divided_difference(j);
                        let b = f.divided_difference(j).divided_difference(i);
                        assert_eq!(a, b, "{w} commute {i},{j}");
                    }
                    // long braid relation
                    if i + 1 < n {
                        let j = i + 1;
                        let a = f
                            .divided_difference(i)
                            .divided_difference(j)
                            .divided_difference(i);
                        let b = f
                            .divided_difference(j)
                            .divided_difference(i)
                            .divided_difference(j);
                        assert_eq!(a, b, "{w} braid {i},{j}");
                    }
                }
            }
        }
    }

    /// `∂` computed on the basis, against `∂` computed by exact division on
    /// the expanded polynomial. The two share no machinery.
    #[test]
    fn divided_difference_agrees_with_exact_division() {
        for n in 2..=5u32 {
            for w in crate::permutation::tests::all_perms(n) {
                let f = sch(&w.padded(n));
                for i in 1..=(n + 1) {
                    let via_basis = f.divided_difference(i).expand();
                    let via_poly = poly_divided_difference(&f.expand(), i);
                    assert_eq!(via_basis, via_poly, "{w} at i={i}");
                }
            }
        }
    }

    /// `(f − s_i f)/(x_i − x_{i+1})`, by exact division, on exponent vectors.
    fn poly_divided_difference(terms: &[(Expo, i64)], i: u32) -> Vec<(Expo, i64)> {
        let i = (i - 1) as usize;
        let mut num: BTreeMap<Expo, i64> = BTreeMap::new();
        for (e, c) in terms {
            let mut a = e.clone();
            if a.len() <= i + 1 {
                a.resize(i + 2, 0);
            }
            *num.entry(strip(a.clone())).or_insert(0) += c;
            a.swap(i, i + 1);
            *num.entry(strip(a)).or_insert(0) -= c;
        }
        num.retain(|_, c| *c != 0);
        // divide by (x_i - x_{i+1}) with a monomial-order long division
        let mut quot: BTreeMap<Expo, i64> = BTreeMap::new();
        while let Some((lead, c)) = num.iter().next_back().map(|(e, c)| (e.clone(), *c)) {
            let mut q = lead.clone();
            if q.len() <= i {
                q.resize(i + 1, 0);
            }
            assert!(q[i] >= 1, "not divisible by (x_i - x_{{i+1}})");
            q[i] -= 1;
            let q = strip(q);
            *quot.entry(q.clone()).or_insert(0) += c;
            // subtract c·q·(x_i − x_{i+1})
            for (slot, sign) in [(i, 1i64), (i + 1, -1i64)] {
                let mut t = q.clone();
                if t.len() <= slot {
                    t.resize(slot + 1, 0);
                }
                t[slot] += 1;
                let t = strip(t);
                *num.entry(t.clone()).or_insert(0) -= c * sign;
                if num[&t] == 0 {
                    num.remove(&t);
                }
            }
        }
        quot.retain(|_, c| *c != 0);
        quot.into_iter().collect()
    }

    #[test]
    fn divided_difference_perm_lands_where_it_should() {
        for n in 2..=5u32 {
            for w in crate::permutation::tests::all_perms(n) {
                for v in crate::permutation::tests::all_perms(n) {
                    let got = sch(&v.padded(n)).divided_difference_perm(&w);
                    // S_v |-> S_{v w} when the length drops by exactly l(w)
                    let mut vw = v.padded(n);
                    let wp = w.padded(n);
                    let composed: Vec<u32> =
                        (0..n as usize).map(|i| vw[(wp[i] - 1) as usize]).collect();
                    vw = composed;
                    let vw = Perm::new(vw).unwrap();
                    let want = if vw.length() + w.length() == v.length() {
                        sch(&vw.padded(n))
                    } else {
                        Schubert::zero()
                    };
                    assert_eq!(got, want, "d_{w} on S_{v}");
                }
            }
        }
    }

    // --- layer 3: the defining recursion ------------------------------------

    /// `S_{w₀⁽ⁿ⁾} = x^δ`, and the downward `∂` recursion reproduces `expand()`
    /// for all of S₅.
    #[test]
    fn defining_recursion_reproduces_expand() {
        for n in 2..=5u32 {
            let w0: Vec<u32> = (1..=n).rev().collect();
            let top = sch(&w0);
            let delta: Expo = strip((1..=n).rev().map(|x| x - 1).collect::<Vec<u32>>());
            assert_eq!(top.expand(), vec![(delta, 1)], "w0 in S_{n}");

            for w in crate::permutation::tests::all_perms(n) {
                // w0 * w^{-1}-ish: reach S_w from S_{w0} by divided differences
                let u = compose(&Perm::new(w0.iter().copied()).unwrap(), &w, n);
                let got = top.divided_difference_perm(&u);
                assert_eq!(got, sch(&w.padded(n)), "reaching {w} in S_{n}");
            }
        }
    }

    /// `u` with `w₀ · u = w`, i.e. `u = w₀⁻¹ w`.
    fn compose(w0: &Perm, w: &Perm, n: u32) -> Perm {
        let a = w0.inverse().padded(n);
        let b = w.padded(n);
        // (a then b): position i -> a[b[i]-1]? we want w0 * u = w  =>  u = w0^{-1} w
        let v: Vec<u32> = (0..n as usize).map(|i| a[(b[i] - 1) as usize]).collect();
        // that is w composed with w0^{-1} in the one-line convention used by
        // transpose(); verify by the length identity the caller asserts.
        Perm::new(v).unwrap()
    }

    // --- layer 4: engines and round trips ----------------------------------

    #[test]
    fn from_polynomial_inverts_expand() {
        for n in 0..=6u32 {
            for w in crate::permutation::tests::all_perms(n) {
                let f = sch(&w.padded(n));
                assert_eq!(Schubert::from_polynomial(&f.expand()), f, "{w}");
            }
        }
    }

    #[test]
    fn from_polynomial_on_sums() {
        let f = sch(&[1, 3, 2])
            .add(&sch(&[3, 2, 1]))
            .add(&sch(&[1, 4, 2, 3]).scale(&3));
        assert_eq!(Schubert::from_polynomial(&f.expand()), f);
    }

    #[test]
    fn dimension_is_the_expansion_size() {
        for n in 0..=6u32 {
            for w in crate::permutation::tests::all_perms(n) {
                let total: i64 = sch(&w.padded(n)).expand().iter().map(|(_, c)| c).sum();
                assert_eq!(dimension(&w).map(|d| d as i64), Some(total), "{w}");
            }
        }
    }

    #[test]
    fn monk_matches_expanded_multiplication() {
        for n in 0..=5u32 {
            for w in crate::permutation::tests::all_perms(n) {
                let f = sch(&w.padded(n));
                for i in 1..=(n + 1) {
                    let via_monk = f.mul_variable(i).expand();
                    let mut want: BTreeMap<Expo, i64> = BTreeMap::new();
                    for (e, c) in f.expand() {
                        let mut e2 = e;
                        if e2.len() < i as usize {
                            e2.resize(i as usize, 0);
                        }
                        e2[(i - 1) as usize] += 1;
                        *want.entry(strip(e2)).or_insert(0) += c;
                    }
                    let want: Vec<(Expo, i64)> = want.into_iter().collect();
                    assert_eq!(via_monk, want, "x_{i} · S_{w}");
                }
            }
        }
    }

    #[test]
    fn product_is_multiplication_of_polynomials() {
        for n in 0..=4u32 {
            for u in crate::permutation::tests::all_perms(n) {
                for v in crate::permutation::tests::all_perms(n) {
                    let a = sch(&u.padded(n));
                    let b = sch(&v.padded(n));
                    let got = a.mul(&b).expand();
                    let want = poly_mul(&a.expand(), &b.expand());
                    assert_eq!(got, want, "S_{u} · S_{v}");
                }
            }
        }
    }

    fn poly_mul(a: &[(Expo, i64)], b: &[(Expo, i64)]) -> Vec<(Expo, i64)> {
        let mut acc: BTreeMap<Expo, i64> = BTreeMap::new();
        for (e, c) in a {
            for (f, d) in b {
                let n = e.len().max(f.len());
                let mut g = vec![0u32; n];
                for (i, slot) in g.iter_mut().enumerate() {
                    *slot = e.get(i).copied().unwrap_or(0) + f.get(i).copied().unwrap_or(0);
                }
                *acc.entry(strip(g)).or_insert(0) += c * d;
            }
        }
        acc.retain(|_, c| *c != 0);
        acc.into_iter().collect()
    }

    /// The engines agree. E3 merges states that E1 visits separately, so
    /// a merge that is subtly wrong shows up here and nowhere else.
    #[test]
    fn e1_and_e3_agree_exhaustively() {
        for n in 0..=5u32 {
            for u in crate::permutation::tests::all_perms(n) {
                for v in crate::permutation::tests::all_perms(n) {
                    let a = sch(&u.padded(n));
                    let b = sch(&v.padded(n));
                    assert_eq!(a.mul_e3(&b), a.mul_naive(&b), "S_{u} · S_{v}");
                }
            }
        }
    }

    /// The verified example, and the point of the name: `F_w` is the
    /// *Stanley* symmetric function, not `S_w` rewritten.
    #[test]
    fn stanley_hand_values() {
        use crate::sym::SymFn;
        let f: Schur<i64> = stanley(&p(&[2, 1, 4, 3]));
        assert_eq!(f.coeff(&Partition::new([2])), 1);
        assert_eq!(f.coeff(&Partition::new([1, 1])), 1);
        assert_eq!(f.terms().len(), 2);
        // ...and S_2143 is not even symmetric, so F_w != S_w here
        assert_ne!(sch(&[2, 1, 4, 3]).expand().len(), 1);
        // identity
        let e: Schur<i64> = stanley(&Perm::identity());
        assert_eq!(e.coeff(&Partition::new([] as [u32; 0])), 1);
    }

    /// Grassmannian `w` is vexillary: a single Schur term, the shape being the
    /// same one `grassmannian_perm` was built from. Ties the bridge into `Sym`
    /// back to the convention pinned against Sage.
    #[test]
    fn stanley_of_grassmannian_is_one_schur() {
        use crate::sym::SymFn;
        for k in 1..=4u32 {
            for size in 0..=7u32 {
                for lam in crate::partition::partitions_of(size) {
                    if lam.len() as u32 > k {
                        continue;
                    }
                    let w = grassmannian_perm(&lam, k).unwrap();
                    let f: Schur<i64> = stanley(&w);
                    assert_eq!(f.terms().len().max(1), 1, "{w} -> {f:?}");
                    assert_eq!(f.coeff(&lam), 1, "{w} shape {lam:?}");
                }
            }
        }
    }

    /// `F_w` is Schur-positive, and invariant under the `1×w` shift the
    /// recursion relies on — a law test for the one move that is not a
    /// transition step.
    #[test]
    fn stanley_is_positive_and_shift_invariant() {
        use crate::sym::SymFn;
        for n in 0..=6u32 {
            for w in crate::permutation::tests::all_perms(n) {
                let f: Schur<i64> = stanley(&w);
                for (lam, c) in f.terms() {
                    assert!(*c > 0, "{w}: negative coefficient at {lam:?}");
                    assert_eq!(lam.size(), w.length(), "{w}: wrong degree");
                }
                let g: Schur<i64> = stanley(&shift_up(&w));
                assert_eq!(f, g, "shift invariance at {w}");
            }
        }
    }

    /// The pruned query must agree with reading the coefficient off the whole
    /// product — exhaustively, including all the zero answers, since pruning
    /// bugs show up as spurious zeros.
    #[test]
    fn schubert_coeff_agrees_with_the_full_product() {
        for n in 0..=4u32 {
            for u in crate::permutation::tests::all_perms(n) {
                for v in crate::permutation::tests::all_perms(n) {
                    let full = sch(&u.padded(n)).mul_naive(&sch(&v.padded(n)));
                    for w in crate::permutation::tests::all_perms(n + 2) {
                        let got: i64 = schubert_coeff(&u, &v, &w);
                        assert_eq!(got, full.coeff(&w), "c^{w}_{{{u},{v}}}");
                    }
                }
            }
        }
    }

    /// The pruning rule behind a single-coefficient query: every `w` in the
    /// support of `S_u · S_v` satisfies `u ≤ w` and `v ≤ w` in Bruhat order,
    /// and every Monk cover moves strictly up. Both are checked here because
    /// the query's soundness rests on them and neither is verified elsewhere.
    #[test]
    fn product_support_lies_above_both_factors() {
        for n in 0..=5u32 {
            for u in crate::permutation::tests::all_perms(n) {
                for v in crate::permutation::tests::all_perms(n) {
                    for w in sch(&u.padded(n))
                        .mul_naive(&sch(&v.padded(n)))
                        .terms()
                        .keys()
                    {
                        assert!(u.bruhat_le(w), "{u} !<= {w} in S_{u}·S_{v}");
                        assert!(v.bruhat_le(w), "{v} !<= {w} in S_{u}·S_{v}");
                    }
                }
            }
        }
    }

    #[test]
    fn monk_covers_move_up_the_bruhat_order() {
        for n in 0..=5u32 {
            for w in crate::permutation::tests::all_perms(n) {
                for i in 1..=(n + 1) {
                    for (_, u) in w.covers_right(i) {
                        assert!(w.bruhat_le(&u), "{w} !<= {u}");
                    }
                    for (_, u) in w.covers_left(i) {
                        assert!(w.bruhat_le(&u), "{w} !<= {u} (left)");
                    }
                }
            }
        }
    }

    #[test]
    fn bruhat_is_a_partial_order_with_known_bounds() {
        for n in 0..=5u32 {
            let w0 = p(&(1..=n).rev().collect::<Vec<u32>>());
            for a in crate::permutation::tests::all_perms(n) {
                assert!(a.bruhat_le(&a), "reflexive {a}");
                assert!(Perm::identity().bruhat_le(&a), "id <= {a}");
                assert!(a.bruhat_le(&w0), "{a} <= w0");
                for b in crate::permutation::tests::all_perms(n) {
                    if a.bruhat_le(&b) && b.bruhat_le(&a) {
                        assert_eq!(a, b, "antisymmetry {a} {b}");
                    }
                    if a.bruhat_le(&b) {
                        assert!(a.length() <= b.length(), "{a} <= {b} but longer");
                    }
                }
            }
        }
    }

    /// Engine agreement again, for the third. E2 recurses on a completely different
    /// decomposition (transition, not the peel), so agreement here is a real
    /// cross-check rather than a restatement.
    #[test]
    fn e2_agrees_with_e1_exhaustively() {
        for n in 0..=5u32 {
            for u in crate::permutation::tests::all_perms(n) {
                for v in crate::permutation::tests::all_perms(n) {
                    let a = sch(&u.padded(n));
                    let b = sch(&v.padded(n));
                    assert_eq!(a.mul_e2(&b), a.mul_naive(&b), "S_{u} · S_{v}");
                }
            }
        }
    }

    /// E2 recurses on the *second* factor while E1/E3 pick a side, so the two
    /// argument orders exercise different trees and must still agree.
    #[test]
    fn e2_is_order_independent() {
        for n in 2..=5u32 {
            for u in crate::permutation::tests::all_perms(n) {
                for v in crate::permutation::tests::all_perms(n) {
                    let a = sch(&u.padded(n));
                    let b = sch(&v.padded(n));
                    assert_eq!(a.mul_e2(&b), b.mul_e2(&a), "S_{u} · S_{v}");
                }
            }
        }
    }

    #[test]
    fn e2_agrees_on_staircases() {
        for k in 2..=4u32 {
            let w: Vec<u32> = (1..=k)
                .map(|i| 2 * i)
                .chain((1..=k).map(|i| 2 * i - 1))
                .collect();
            let a = sch(&w);
            assert_eq!(a.mul_e2(&a), a.mul_naive(&a), "stair{k}^2");
        }
    }

    /// E1 and E3 agree on *sums*, and on mixed sizes — the shape that caught
    /// the peel memo's missing level key.
    #[test]
    fn e1_and_e3_agree_on_sums() {
        let f = sch(&[1, 3, 2])
            .add(&sch(&[3, 2, 1]))
            .add(&sch(&[1, 4, 2, 3]).scale(&3));
        let g = sch(&[2, 4, 1, 3]).add(&sch(&[2, 1]).scale(&2));
        assert_eq!(f.mul_e3(&g), f.mul_naive(&g));
        assert_eq!(g.mul_e3(&f), f.mul_naive(&g));
    }

    /// Bigger than the exhaustive sweep reaches, where the DAG actually
    /// compresses (`stair4` has 64 pipe dreams against 114 states).
    #[test]
    fn e1_and_e3_agree_on_staircases() {
        for k in 2..=4u32 {
            let w: Vec<u32> = (1..=k)
                .map(|i| 2 * i)
                .chain((1..=k).map(|i| 2 * i - 1))
                .collect();
            let a = sch(&w);
            assert_eq!(a.mul_e3(&a), a.mul_naive(&a), "stair{k}^2");
        }
    }

    #[test]
    fn peel_states_counts_the_dag() {
        // matches scripts/spec_schubert_peel.py's states_ps column (the corrected
        // one -- the first version of that script undercounted it at 114/33)
        let stair4: Vec<u32> = vec![2, 4, 6, 8, 1, 3, 5, 7];
        assert_eq!(peel_states(&p(&stair4)), 158);
        let stair3: Vec<u32> = vec![2, 4, 6, 1, 3, 5];
        assert_eq!(peel_states(&p(&stair3)), 38);
        assert_eq!(dimension(&p(&stair4)), Some(64));
        assert_eq!(dimension(&p(&stair3)), Some(8));
    }

    #[test]
    fn product_is_commutative_and_unital() {
        for n in 0..=4u32 {
            for u in crate::permutation::tests::all_perms(n) {
                let a = sch(&u.padded(n));
                assert_eq!(a.mul(&Schubert::one()), a, "{u} · 1");
                for v in crate::permutation::tests::all_perms(n) {
                    let b = sch(&v.padded(n));
                    assert_eq!(a.mul(&b), b.mul(&a), "{u} · {v}");
                }
            }
        }
    }

    /// Structure constants are non-negative — the geometric fact, and the
    /// cheapest possible smoke test that the signed Monk intermediates cancel
    /// the way they must.
    #[test]
    fn structure_constants_are_non_negative() {
        for n in 0..=5u32 {
            for u in crate::permutation::tests::all_perms(n) {
                for v in crate::permutation::tests::all_perms(n) {
                    for (w, c) in sch(&u.padded(n)).mul(&sch(&v.padded(n))).terms() {
                        assert!(*c > 0, "c^{w}_{{{u},{v}}} = {c}");
                    }
                }
            }
        }
    }

    #[test]
    fn pairing_is_the_top_coefficient() {
        // <S_u, S_v> = 1 iff v = w0 u, on Fl(3)
        let n = 3u32;
        let w0 = p(&[3, 2, 1]);
        for u in crate::permutation::tests::all_perms(n) {
            for v in crate::permutation::tests::all_perms(n) {
                let got = sch(&u.padded(n)).pairing(&sch(&v.padded(n)), n);
                let w0u: Vec<u32> = (0..n as usize)
                    .map(|i| w0.padded(n)[(u.padded(n)[i] - 1) as usize])
                    .collect();
                let want = i64::from(v == Perm::new(w0u).unwrap());
                assert_eq!(got, want, "<S_{u}, S_{v}>");
            }
        }
    }

    /// `w` with its first `n` values reversed, when those values descend —
    /// the closed form of `∂_{w₀⁽ⁿ⁾}` on a basis element, `None` where the
    /// operator kills it.
    fn reverse_descending_prefix(w: &Perm, n: u32) -> Option<Perm> {
        let m = w.support_len().max(n);
        let mut v = w.padded(m);
        let n = n as usize;
        if v[..n].windows(2).any(|pair| pair[0] < pair[1]) {
            return None;
        }
        v[..n].reverse();
        Some(Perm::new(v).unwrap())
    }

    /// The shipped route — `n(n−1)/2` divided-difference passes along a reduced
    /// word, over the E2 product — against the closed form of `∂_{w₀⁽ⁿ⁾}` read
    /// off each term, over the E1 product. Neither the engine nor the way the
    /// operator is applied is shared, so agreement is evidence rather than
    /// consistency (`docs/policies/validation.md`, V3).
    #[test]
    fn scalar_product_agrees_with_the_prefix_reversal_rule() {
        for m in 0..=4u32 {
            for u in crate::permutation::tests::all_perms(m) {
                for v in crate::permutation::tests::all_perms(m) {
                    let (a, b) = (sch(&u.padded(m)), sch(&v.padded(m)));
                    let naive = a.mul_naive(&b);
                    for n in 0..=4u32 {
                        let mut want = Schubert::zero();
                        for (w, c) in naive.terms() {
                            if let Some(z) = reverse_descending_prefix(w, n) {
                                want.add_term(z, c);
                            }
                        }
                        assert_eq!(
                            a.scalar_product(&b, n),
                            want,
                            "scalar product of S_{u} and S_{v} at n={n}"
                        );
                    }
                }
            }
        }
    }

    /// The Poincaré pairing is this map's constant term, which is the whole
    /// relationship between the two operations and the one the audit had
    /// wrong.
    #[test]
    fn scalar_product_recovers_the_pairing_at_the_identity() {
        for n in 0..=4u32 {
            for u in crate::permutation::tests::all_perms(n) {
                for v in crate::permutation::tests::all_perms(n) {
                    let (a, b) = (sch(&u.padded(n)), sch(&v.padded(n)));
                    assert_eq!(
                        a.scalar_product(&b, n).coeff(&Perm::identity()),
                        a.pairing(&b, n),
                        "constant term at n={n} for S_{u}, S_{v}"
                    );
                }
            }
        }
    }

    /// The values Sage's own `SchubertPolynomial.scalar_product` doctests
    /// assert (`combinat/schubert_polynomial.py`), which are what a drop-in has
    /// to reproduce. Both arguments have one-line length 4, so the rank a Sage
    /// caller reaches is 4.
    #[test]
    fn scalar_product_matches_sages_doctest_values() {
        let a = sch(&[3, 2, 4, 1]);
        let b = sch(&[4, 3, 2, 1]);
        assert!(a.scalar_product(&a, 4).is_zero());
        assert_eq!(b.scalar_product(&a, 4), sch(&[1, 3, 4, 6, 2, 5]));
    }

    /// The bottom of the range, per `docs/policies/validation.md` V6: below
    /// rank 2 the operator is empty, so the map is the bare product — a
    /// convention, and one a caller sweeping `n` from 0 will meet.
    #[test]
    fn scalar_product_below_rank_two_is_the_product() {
        for m in 0..=3u32 {
            for u in crate::permutation::tests::all_perms(m) {
                for v in crate::permutation::tests::all_perms(m) {
                    let (a, b) = (sch(&u.padded(m)), sch(&v.padded(m)));
                    for n in 0..=1u32 {
                        assert_eq!(
                            a.scalar_product(&b, n),
                            a.mul(&b),
                            "S_{u} times S_{v} at n={n}"
                        );
                    }
                }
            }
        }
    }

    /// Stability: padding the input permutation changes nothing.
    #[test]
    fn stability_under_padding() {
        let a = sch(&[3, 1, 4, 2]);
        let b = sch(&[3, 1, 4, 2, 5, 6]);
        assert_eq!(a, b);
        assert_eq!(a.expand(), b.expand());
        assert_eq!(a.mul(&a), b.mul(&b));
    }
}