kryst 4.0.4

Krylov subspace and preconditioned iterative solvers for dense and sparse linear systems, with shared and distributed memory parallelism.
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
use std::sync::Arc;

use crate::algebra::scalar::KrystScalar;
use crate::error::KError;
use crate::matrix::convert::csr_from_linop;
use crate::matrix::dist::LocalSquareCsr;
use crate::matrix::format::OpFormat;
use crate::matrix::op::{LinOp, StructureId, ValuesId};
use crate::matrix::sparse::CsrMatrix;
use crate::preconditioner::{
    LocalPreconditioner, Op, PcCaps, PcDistributedSupport, PcSide, Preconditioner,
};
use crate::utils::conditioning::ConditioningOptions;
use crate::utils::permutation::Permutation;
#[cfg(feature = "complex")]
use crate::utils::permutation::{
    amd_csr, permute_csr_nonsymmetric, permute_csr_symmetric, rcm_csr,
};
use crate::utils::preconditioning_pipeline::{
    PreconditioningMetadata, apply_preconditioning_pipeline,
};

#[cfg(feature = "complex")]
use crate::algebra::bridge::BridgeScratch;
#[cfg(feature = "complex")]
use crate::algebra::scalar::S;
#[cfg(feature = "complex")]
use crate::ops::kpc::KPreconditioner;

use once_cell::sync::OnceCell;

// ILU_CSR is restricted to real scalars for now.
type Real = f64;

mod csr_builder;
mod ilut_params;
mod pivot;
mod pos_map;
mod row_work;
mod tri_solve;

pub use ilut_params::{IlutParams, PivotPolicy, Pivoting};
pub use pivot::PivotStrategy;

use csr_builder::CsrBuilder;
use row_work::RowWork;

// Workspace for fast lookups of U(i, j) positions within a row during
// numeric factorization. Uses the marker/epoch trick to provide O(1)
// amortized access without clearing the entire array each iteration.
#[derive(Clone, Debug)]
struct URowMap {
    epoch: usize,
    mark: Vec<usize>,
    pos: Vec<usize>,
}

impl URowMap {
    fn new() -> Self {
        Self {
            epoch: 0,
            mark: Vec::new(),
            pos: Vec::new(),
        }
    }

    fn ensure_size(&mut self, n: usize) {
        if self.mark.len() < n {
            self.mark.resize(n, 0);
            self.pos.resize(n, 0);
        }
    }

    fn prime(&mut self, u_row: &[usize], u_col: &[usize], i: usize) {
        self.epoch = self.epoch.wrapping_add(1);
        let rs = u_row[i];
        let re = u_row[i + 1];
        for (offset, &col) in u_col[rs..re].iter().enumerate() {
            self.mark[col] = self.epoch;
            self.pos[col] = rs + offset;
        }
    }

    #[inline]
    fn get(&self, j: usize) -> Option<usize> {
        if self.mark.get(j).copied().unwrap_or(0) == self.epoch {
            Some(self.pos[j])
        } else {
            None
        }
    }
}

mod symbolic;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum IluKind {
    Ilu0,
    Milu0,
    Iluk { k: usize },
    Ilut { params: IlutParams },
}

#[derive(Clone, Debug)]
pub struct IluCsrConfig {
    pub kind: IluKind,
    pub pivot: PivotStrategy,
    pub pivot_threshold: f64,
    pub diag_perturb_factor: f64,
    pub level_sched: bool,
    pub numeric_update_fixed: bool,
    pub logging: usize,
    pub reordering: ReorderingOptions,
    pub conditioning: ConditioningOptions,
}

impl Default for IluCsrConfig {
    fn default() -> Self {
        Self {
            kind: IluKind::Ilu0,
            pivot: PivotStrategy::DiagonalPerturbation,
            pivot_threshold: 1e-12,
            diag_perturb_factor: 1e-10,
            level_sched: cfg!(feature = "rayon"),
            numeric_update_fixed: true,
            logging: 0,
            reordering: ReorderingOptions::default(),
            conditioning: ConditioningOptions::default(),
        }
    }
}

#[cfg(feature = "complex")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IluComplexKernelMode {
    Native,
    DegradedRealProjection,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ReorderingKind {
    None,
    Rcm,
    Amd,
}

#[derive(Clone, Debug)]
pub struct ReorderingOptions {
    pub kind: ReorderingKind,
    pub symmetric: bool,
    pub deterministic: bool,
}

impl Default for ReorderingOptions {
    fn default() -> Self {
        Self {
            kind: ReorderingKind::None,
            symmetric: true,
            deterministic: true,
        }
    }
}

pub struct IluCsr {
    pub(crate) cfg: IluCsrConfig,

    // reuse policy: last operator IDs
    last_sid: Option<StructureId>,
    last_vid: Option<ValuesId>,

    // factors (CSR by rows)
    n: usize,
    // L strictly lower (unit diagonal implied)
    l_row: Vec<usize>,
    l_col: Vec<usize>,
    l_val: Vec<Real>,
    // U upper including diagonal
    u_row: Vec<usize>,
    u_col: Vec<usize>,
    u_val: Vec<Real>,
    u_diag_ix: Vec<usize>,
    // Optional per-entry levels for ILUK
    l_lev: Vec<usize>,
    u_lev: Vec<usize>,

    // cached transposes, built lazily
    lt: OnceCell<(Vec<usize>, Vec<usize>, Vec<Real>)>,
    ut: OnceCell<(Vec<usize>, Vec<usize>, Vec<Real>)>,

    // optional level scheduling
    levels_fwd: Vec<usize>,
    levels_bwd: Vec<usize>,
    buckets_fwd: Vec<Vec<usize>>,
    buckets_bwd: Vec<Vec<usize>>,

    // scratch for mutable apply paths. Immutable trait apply cannot borrow these,
    // but GMRES/FGMRES and other mutable callers can reuse them without per-apply
    // heap traffic.
    tmp: Vec<Real>,
    tmp2: Vec<Real>,
    tmp3: Vec<Real>,
    perm: Permutation,
    pipeline_meta: PreconditioningMetadata,
    #[cfg(feature = "complex")]
    c_l_val: Vec<S>,
    #[cfg(feature = "complex")]
    c_u_val: Vec<S>,
    #[cfg(feature = "complex")]
    c_tmp: Vec<S>,
    #[cfg(feature = "complex")]
    c_y_tmp: Vec<S>,
    #[cfg(feature = "complex")]
    c_xr: Vec<Real>,
    #[cfg(feature = "complex")]
    c_xi: Vec<Real>,
    #[cfg(feature = "complex")]
    c_yr: Vec<Real>,
    #[cfg(feature = "complex")]
    c_yi: Vec<Real>,
    #[cfg(feature = "complex")]
    native_complex_active: bool,
    #[cfg(feature = "complex")]
    complex_kernel_mode: IluComplexKernelMode,
    #[cfg(feature = "complex")]
    complex_force_degraded: bool,
}

impl IluCsr {
    pub(crate) fn empty() -> Self {
        Self {
            cfg: IluCsrConfig::default(),
            last_sid: None,
            last_vid: None,
            n: 0,
            l_row: Vec::new(),
            l_col: Vec::new(),
            l_val: Vec::new(),
            u_row: Vec::new(),
            u_col: Vec::new(),
            u_val: Vec::new(),
            u_diag_ix: Vec::new(),
            l_lev: Vec::new(),
            u_lev: Vec::new(),
            lt: OnceCell::new(),
            ut: OnceCell::new(),
            levels_fwd: Vec::new(),
            levels_bwd: Vec::new(),
            buckets_fwd: Vec::new(),
            buckets_bwd: Vec::new(),
            tmp: Vec::new(),
            tmp2: Vec::new(),
            tmp3: Vec::new(),
            perm: Permutation::identity(0),
            pipeline_meta: PreconditioningMetadata::identity(0),
            #[cfg(feature = "complex")]
            c_l_val: Vec::new(),
            #[cfg(feature = "complex")]
            c_u_val: Vec::new(),
            #[cfg(feature = "complex")]
            c_tmp: Vec::new(),
            #[cfg(feature = "complex")]
            c_y_tmp: Vec::new(),
            #[cfg(feature = "complex")]
            c_xr: Vec::new(),
            #[cfg(feature = "complex")]
            c_xi: Vec::new(),
            #[cfg(feature = "complex")]
            c_yr: Vec::new(),
            #[cfg(feature = "complex")]
            c_yi: Vec::new(),
            #[cfg(feature = "complex")]
            native_complex_active: false,
            #[cfg(feature = "complex")]
            complex_kernel_mode: IluComplexKernelMode::DegradedRealProjection,
            #[cfg(feature = "complex")]
            complex_force_degraded: false,
        }
    }

    pub fn new_with_config(cfg: IluCsrConfig) -> Self {
        let mut me = Self::empty();
        me.cfg = cfg;
        me
    }

    fn clear_levels(&mut self) {
        self.levels_fwd.clear();
        self.levels_bwd.clear();
        self.buckets_fwd.clear();
        self.buckets_bwd.clear();
    }

    fn build_levels_if_enabled(&mut self) {
        if !self.cfg.level_sched {
            self.clear_levels();
            return;
        }
        // Forward levels from L dependency graph (i <- j if L(i,j) != 0)
        let n = self.n;
        self.levels_fwd.resize(n, 0);
        for i in 0..n {
            let mut lv = 0usize;
            let rs = self.l_row[i];
            let re = self.l_row[i + 1];
            for p in rs..re {
                let j = self.l_col[p];
                lv = lv.max(self.levels_fwd[j] + 1);
            }
            self.levels_fwd[i] = lv;
        }
        let max_lv_fwd = self.levels_fwd.iter().copied().max().unwrap_or(0);
        self.buckets_fwd.clear();
        self.buckets_fwd.resize(max_lv_fwd + 1, Vec::new());
        for i in 0..n {
            let lv = self.levels_fwd[i];
            self.buckets_fwd[lv].push(i);
        }

        // Backward levels from U dependency graph (i <- j if U(i,j) != 0 and j>i)
        self.levels_bwd.resize(n, 0);
        for i in (0..n).rev() {
            let mut lv = 0usize;
            let rs = self.u_row[i];
            let re = self.u_row[i + 1];
            for p in rs..re {
                let j = self.u_col[p];
                if j > i {
                    lv = lv.max(self.levels_bwd[j] + 1);
                }
            }
            self.levels_bwd[i] = lv;
        }
        let max_lv_bwd = self.levels_bwd.iter().copied().max().unwrap_or(0);
        self.buckets_bwd.clear();
        self.buckets_bwd.resize(max_lv_bwd + 1, Vec::new());
        // For backward we want to visit decreasing rows within each bucket for numerical dependencies.
        for i in (0..n).rev() {
            let lv = self.levels_bwd[i];
            self.buckets_bwd[lv].push(i);
        }
    }

    fn factor_symbolic_and_numeric(&mut self, a: &CsrMatrix<f64>) -> Result<(), KError> {
        match self.cfg.kind {
            IluKind::Ilu0 | IluKind::Milu0 => self.factor_ilu0(a),
            IluKind::Iluk { k } => self.factor_iluk(a, k),
            IluKind::Ilut { params } => self.factor_ilut(a, &params),
        }
    }

    fn factor_numeric_only(&mut self, a: &CsrMatrix<f64>) -> Result<(), KError> {
        match self.cfg.kind {
            IluKind::Ilu0 | IluKind::Milu0 => self.factor_ilu0_numeric_only(a),
            IluKind::Iluk { k } => self.factor_iluk_numeric_only(a, k),
            IluKind::Ilut { .. } => self.factor_ilut_numeric_only(a),
        }
    }

    #[cfg(feature = "complex")]
    fn factor_ilu0_complex(&mut self, a: &CsrMatrix<S>) -> Result<(), KError> {
        let a_zero = CsrMatrix::from_csr(
            a.nrows(),
            a.ncols(),
            a.row_ptr().to_vec(),
            a.col_idx().to_vec(),
            vec![0.0; a.values().len()],
        );
        self.factor_ilu0(&a_zero)?;
        self.c_l_val.resize(self.l_val.len(), S::zero());
        self.c_u_val.resize(self.u_val.len(), S::zero());

        let n = a.nrows();
        let rp = a.row_ptr();
        let cj = a.col_idx();
        let vv = a.values();
        let mut map = URowMap::new();
        map.ensure_size(n);
        let milu = matches!(self.cfg.kind, IluKind::Milu0);
        let mut max_diag_abs = 0.0f64;
        for i in 0..n {
            let mut di = S::zero();
            for p in rp[i]..rp[i + 1] {
                if cj[p] == i {
                    di = vv[p];
                    break;
                }
            }
            max_diag_abs = max_diag_abs.max(di.abs());
        }

        for i in 0..n {
            map.prime(&self.u_row, &self.u_col, i);
            for p in rp[i]..rp[i + 1] {
                let j = cj[p];
                let val = vv[p];
                if j < i {
                    let ls = self.l_row[i];
                    if let Ok(off) = self.l_col[ls..self.l_row[i + 1]].binary_search(&j) {
                        self.c_l_val[ls + off] = val;
                    }
                } else if let Some(pos) = map.get(j) {
                    self.c_u_val[pos] = val;
                }
            }

            for p in self.l_row[i]..self.l_row[i + 1] {
                let j = self.l_col[p];
                let wij = self.c_l_val[p];
                if wij == S::zero() {
                    continue;
                }
                let djj = self.c_u_val[self.u_diag_ix[j]];
                let mult = wij / djj;
                self.c_l_val[p] = mult;
                for q in self.u_row[j]..self.u_row[j + 1] {
                    let k = self.u_col[q];
                    if k <= j {
                        continue;
                    }
                    let ujk = self.c_u_val[q];
                    if let Some(pos_ik) = map.get(k) {
                        self.c_u_val[pos_ik] -= mult * ujk;
                    } else if milu {
                        self.c_u_val[self.u_diag_ix[i]] -= mult * ujk;
                    }
                }
            }

            let di_pos = self.u_diag_ix[i];
            let fixed = pivot::handle_pivot_scalar(
                self.c_u_val[di_pos],
                self.cfg.pivot,
                self.cfg.pivot_threshold,
                self.cfg.diag_perturb_factor,
                max_diag_abs,
            )
            .map_err(|_| KError::ZeroPivot(i))?;
            self.c_u_val[di_pos] = fixed;
        }

        self.native_complex_active = true;
        self.complex_kernel_mode = IluComplexKernelMode::Native;
        Ok(())
    }

    #[cfg(feature = "complex")]
    fn factor_iluk_complex(&mut self, a: &CsrMatrix<S>, k: usize) -> Result<(), KError> {
        let a_zero = CsrMatrix::from_csr(
            a.nrows(),
            a.ncols(),
            a.row_ptr().to_vec(),
            a.col_idx().to_vec(),
            vec![0.0; a.values().len()],
        );
        self.factor_iluk(&a_zero, k)?;
        self.c_l_val.resize(self.l_val.len(), S::zero());
        self.c_u_val.resize(self.u_val.len(), S::zero());

        let n = a.nrows();
        let rp = a.row_ptr();
        let cj = a.col_idx();
        let vv = a.values();
        let mut map = URowMap::new();
        map.ensure_size(n);
        let mut max_diag_abs = 0.0f64;
        for i in 0..n {
            let mut di = S::zero();
            for p in rp[i]..rp[i + 1] {
                if cj[p] == i {
                    di = vv[p];
                    break;
                }
            }
            max_diag_abs = max_diag_abs.max(di.abs());
        }

        for i in 0..n {
            map.prime(&self.u_row, &self.u_col, i);
            for p in rp[i]..rp[i + 1] {
                let j = cj[p];
                let val = vv[p];
                if j < i {
                    let ls = self.l_row[i];
                    if let Ok(off) = self.l_col[ls..self.l_row[i + 1]].binary_search(&j) {
                        self.c_l_val[ls + off] = val;
                    }
                } else if let Some(pos) = map.get(j) {
                    self.c_u_val[pos] = val;
                }
            }

            for p in self.l_row[i]..self.l_row[i + 1] {
                let j = self.l_col[p];
                let wij = self.c_l_val[p];
                if wij == S::zero() {
                    continue;
                }
                let djj = self.c_u_val[self.u_diag_ix[j]];
                let mult = wij / djj;
                self.c_l_val[p] = mult;
                for q in self.u_row[j]..self.u_row[j + 1] {
                    let kcol = self.u_col[q];
                    if kcol <= j {
                        continue;
                    }
                    let ujk = self.c_u_val[q];
                    if let Some(pos_ik) = map.get(kcol) {
                        self.c_u_val[pos_ik] -= mult * ujk;
                    }
                }
            }

            let di_pos = self.u_diag_ix[i];
            let fixed = pivot::handle_pivot_scalar(
                self.c_u_val[di_pos],
                self.cfg.pivot,
                self.cfg.pivot_threshold,
                self.cfg.diag_perturb_factor,
                max_diag_abs,
            )
            .map_err(|_| KError::ZeroPivot(i))?;
            self.c_u_val[di_pos] = fixed;
        }

        self.native_complex_active = true;
        self.complex_kernel_mode = IluComplexKernelMode::Native;
        Ok(())
    }

    #[cfg(feature = "complex")]
    fn factor_ilut_complex(&mut self, a: &CsrMatrix<S>, params: &IlutParams) -> Result<(), KError> {
        // NOTE: ILUT currently reuses the real-valued kernel by projecting A to Re(A).
        // This is a degraded/provisional complex path and is intentionally *not* suitable
        // for complex-robustness benchmarking. It exists for functional continuity only.
        let a_real = CsrMatrix::from_csr(
            a.nrows(),
            a.ncols(),
            a.row_ptr().to_vec(),
            a.col_idx().to_vec(),
            a.values().iter().map(|v| v.real()).collect(),
        );
        self.factor_ilut(&a_real, params)?;
        self.native_complex_active = false;
        self.complex_kernel_mode = if self.complex_force_degraded {
            IluComplexKernelMode::DegradedRealProjection
        } else {
            IluComplexKernelMode::Native
        };
        Ok(())
    }

    // === ILU(0) implementation over CSR ===
    fn factor_ilu0(&mut self, a: &CsrMatrix<f64>) -> Result<(), KError> {
        let n = a.nrows();
        if n != a.ncols() {
            return Err(KError::InvalidInput("ILU requires square matrix".into()));
        }
        self.n = n;

        // Build L/U symbolic pattern by splitting A and ensuring a diagonal slot exists in U.
        self.l_row.clear();
        self.l_col.clear();
        self.u_row.clear();
        self.u_col.clear();
        self.u_diag_ix.clear();
        self.l_row.resize(n + 1, 0);
        self.u_row.resize(n + 1, 0);
        self.u_diag_ix.resize(n, 0);

        let rp = a.row_ptr();
        let cj = a.col_idx();

        // First pass: collect columns per row, split at diagonal, and sort.
        let mut lcols_row: Vec<usize> = Vec::new();
        let mut ucols_row: Vec<usize> = Vec::new();
        for i in 0..n {
            lcols_row.clear();
            ucols_row.clear();
            let mut have_diag = false;
            for p in rp[i]..rp[i + 1] {
                let j = cj[p];
                if j < i {
                    lcols_row.push(j);
                } else if j == i {
                    ucols_row.push(j);
                    have_diag = true;
                } else {
                    ucols_row.push(j);
                }
            }
            if !have_diag {
                ucols_row.push(i);
            }
            lcols_row.sort_unstable();
            ucols_row.sort_unstable();

            // Append to global structures and record diag index
            self.l_row[i + 1] = self.l_row[i] + lcols_row.len();
            self.u_row[i + 1] = self.u_row[i] + ucols_row.len();
            self.l_col.extend_from_slice(&lcols_row);
            let u_start = self.u_col.len();
            self.u_col.extend_from_slice(&ucols_row);
            // Find diag position in this appended segment
            let d_rel = ucols_row
                .iter()
                .position(|&c| c == i)
                .expect("diagonal present");
            self.u_diag_ix[i] = u_start + d_rel;
        }

        // Allocate values
        self.l_val.clear();
        self.u_val.clear();
        self.l_lev.clear();
        self.u_lev.clear();
        self.l_val.resize(self.l_col.len(), Real::zero());
        self.u_val.resize(self.u_col.len(), Real::zero());
        // not used in ILU0
        self.l_lev.resize(self.l_col.len(), 0);
        self.u_lev.resize(self.u_col.len(), 0);
        // Numeric factorization using work row over A's pattern only (no fill added).
        let milu = matches!(self.cfg.kind, IluKind::Milu0);
        self.ilu0_numeric(a, milu)
    }

    fn factor_ilu0_numeric_only(&mut self, a: &CsrMatrix<f64>) -> Result<(), KError> {
        if self.n == 0 {
            return self.factor_ilu0(a);
        }
        if self.n != a.nrows() || a.nrows() != a.ncols() {
            return Err(KError::InvalidInput(
                "ILU0 numeric update: size/shape mismatch".into(),
            ));
        }
        // Keep pattern intact; just recompute numeric values.
        let milu = matches!(self.cfg.kind, IluKind::Milu0);
        self.ilu0_numeric(a, milu)
    }

    fn ilu0_numeric(&mut self, a: &CsrMatrix<f64>, milu: bool) -> Result<(), KError> {
        let n = self.n;
        let rp = a.row_ptr();
        let cj = a.col_idx();
        let vv = a.values();

        // Workspace for locating U(i, j) quickly
        let mut map = URowMap::new();
        map.ensure_size(n);

        // Precompute max |A_ii| for pivot handling
        let mut max_diag_abs = 0.0f64;
        for i in 0..n {
            let mut di = 0.0;
            for p in rp[i]..rp[i + 1] {
                if cj[p] == i {
                    di = vv[p];
                    break;
                }
            }
            max_diag_abs = max_diag_abs.max(di.abs());
        }

        for i in 0..n {
            map.prime(&self.u_row, &self.u_col, i);

            // Initialize L and U values from A for this row
            let mut p = rp[i];
            while p < rp[i + 1] {
                let j = cj[p];
                let val = vv[p];
                if j < i {
                    // L part
                    let ls = self.l_row[i];
                    if let Ok(off) = self.l_col[ls..self.l_row[i + 1]].binary_search(&j) {
                        self.l_val[ls + off] = Real::from_real(val);
                    }
                } else {
                    // U part (including diagonal)
                    if let Some(pos) = map.get(j) {
                        self.u_val[pos] = Real::from_real(val);
                    }
                }
                p += 1;
            }

            // Eliminate using previous rows
            let ls = self.l_row[i];
            let le = self.l_row[i + 1];
            for pos in ls..le {
                let k = self.l_col[pos];
                let ukk = self.u_val[self.u_diag_ix[k]];
                if ukk == Real::zero() {
                    return Err(KError::FactorError(format!(
                        "zero U(j,j) encountered at row {k}"
                    )));
                }
                let mult = self.l_val[pos] / ukk;
                self.l_val[pos] = mult;

                // Update U(i, j)
                let urs = self.u_row[k];
                let ure = self.u_row[k + 1];
                for q in urs..ure {
                    let j = self.u_col[q];
                    if j <= k {
                        continue;
                    }
                    let val_q = self.u_val[q];
                    if let Some(pos_ij) = map.get(j) {
                        self.u_val[pos_ij] -= mult * val_q;
                    } else if milu {
                        let di_pos = self.u_diag_ix[i];
                        self.u_val[di_pos] -= mult * val_q;
                    }
                }
            }

            // Handle pivot on U(i,i)
            let di_pos = self.u_diag_ix[i];
            let fixed = pivot::handle_pivot(
                self.u_val[di_pos],
                self.cfg.pivot,
                self.cfg.pivot_threshold,
                self.cfg.diag_perturb_factor,
                max_diag_abs,
            )
            .map_err(|_| KError::ZeroPivot(i))?;
            self.u_val[di_pos] = fixed;
        }

        Ok(())
    }

    // === ILUK(k) implementation ===
    fn factor_iluk(&mut self, a: &CsrMatrix<f64>, k_limit: usize) -> Result<(), KError> {
        let n = a.nrows();
        if n != a.ncols() {
            return Err(KError::InvalidInput("ILUK requires square matrix".into()));
        }
        self.n = n;

        // Initialize CSR row pointers to 0; we’ll build per-row then append.
        self.l_row.clear();
        self.u_row.clear();
        self.l_col.clear();
        self.u_col.clear();
        self.l_val.clear();
        self.u_val.clear();
        self.l_lev.clear();
        self.u_lev.clear();
        self.u_diag_ix.clear();
        self.l_row.resize(n + 1, 0);
        self.u_row.resize(n + 1, 0);
        self.u_diag_ix.resize(n, 0);

        use symbolic::RowWork;
        let rp = a.row_ptr();
        let cj = a.col_idx();
        let vv = a.values();
        let mut w = RowWork {
            mark: Vec::new(),
            idx: Vec::new(),
            val: Vec::new(),
        };
        let mut wlev: Vec<usize> = Vec::new();
        symbolic::ensure_rowwork(&mut w, n);

        // Precompute max |A_ii| for pivot handling
        let mut max_diag_abs = 0.0f64;
        for i in 0..n {
            let mut di = 0.0;
            for p in rp[i]..rp[i + 1] {
                if cj[p] == i {
                    di = vv[p];
                    break;
                }
            }
            max_diag_abs = max_diag_abs.max(di.abs());
        }

        for i in 0..n {
            // Load A row with level 0
            symbolic::ensure_rowwork(&mut w, n);
            wlev.clear();
            for p in rp[i]..rp[i + 1] {
                let j = cj[p];
                let pos = symbolic::find_or_insert(&mut w, j);
                if pos == wlev.len() {
                    wlev.push(0);
                } else {
                    wlev[pos] = 0;
                }
                w.val[pos] = Real::from_real(vv[p]);
            }

            // Create sorted list of lower columns present
            let mut lowers: Vec<(usize, usize)> = w
                .idx
                .iter()
                .enumerate()
                .filter_map(|(pos, &col)| if col < i { Some((col, pos)) } else { None })
                .collect();
            lowers.sort_by_key(|x| x.0);

            // Eliminate against j < i that are kept (level <= k)
            for &(j, pos) in &lowers {
                let lij_level = wlev[pos];
                // If level exceeds k, skip elimination for this j
                if lij_level > k_limit {
                    continue;
                }
                let wij = w.val[pos];
                if wij == Real::zero() {
                    continue;
                }
                let djj = {
                    let dix = self.u_diag_ix.get(j).copied().unwrap_or(0);
                    if j < i && self.u_val.get(dix).copied().unwrap_or(Real::zero()) == Real::zero()
                    {
                        // Not yet built; for row 0 there is none — but we will handle when j<i holds
                    }
                    if j < i {
                        self.u_val[self.u_diag_ix[j]]
                    } else {
                        Real::one()
                    }
                };
                let lij = wij / djj;

                // AXPY to k > j using U(j,*)
                let urs = self.u_row.get(j).copied().unwrap_or(0);
                let ure = self.u_row.get(j + 1).copied().unwrap_or(0);
                for q in urs..ure {
                    let kcol = self.u_col[q];
                    if kcol <= j {
                        continue;
                    }
                    let new_level = lij_level + self.u_lev[q] + 1;
                    if new_level > k_limit {
                        continue;
                    }
                    let kpos = symbolic::find_or_insert(&mut w, kcol);
                    if kpos == wlev.len() {
                        wlev.push(new_level);
                    } else if new_level < wlev[kpos] {
                        wlev[kpos] = new_level;
                    }
                    w.val[kpos] -= lij * self.u_val[q];
                }
                // store L(i,j) entry (value+level) later when we finalize L row
            }

            // Finalize L and U rows from work row with level <= k
            // Gather L (j<i)
            let mut l_pairs: Vec<(usize, Real, usize)> = w
                .idx
                .iter()
                .enumerate()
                .filter_map(|(pos, &col)| {
                    if col < i && wlev[pos] <= k_limit {
                        Some((col, w.val[pos], wlev[pos]))
                    } else {
                        None
                    }
                })
                .collect();
            l_pairs.sort_by_key(|x| x.0);

            // Gather U (k>=i); ensure diagonal exists with some level (0)
            let mut u_pairs: Vec<(usize, Real, usize)> = w
                .idx
                .iter()
                .enumerate()
                .filter_map(|(pos, &col)| {
                    if col >= i && wlev[pos] <= k_limit {
                        Some((col, w.val[pos], wlev[pos]))
                    } else {
                        None
                    }
                })
                .collect();
            if !u_pairs.iter().any(|(c, _, _)| *c == i) {
                u_pairs.push((i, Real::zero(), 0));
            }
            u_pairs.sort_by_key(|x| x.0);

            // Write L row
            self.l_row[i + 1] = self.l_row[i] + l_pairs.len();
            for (c, v, lev) in l_pairs {
                self.l_col.push(c);
                self.l_val.push(v);
                self.l_lev.push(lev);
            }

            // Write U row and remember diag ix; pivot later after elimination loop
            let u_start = self.u_col.len();
            self.u_row[i + 1] = self.u_row[i] + u_pairs.len();
            for (c, v, lev) in &u_pairs {
                self.u_col.push(*c);
                self.u_val.push(*v);
                self.u_lev.push(*lev);
            }
            let d_rel = u_pairs.iter().position(|(c, _, _)| *c == i).unwrap();
            self.u_diag_ix[i] = u_start + d_rel;

            // Clear work row
            symbolic::clear_rowwork(&mut w);
        }

        // Numeric refinement: run numeric-only to enforce pivot strategy and compute final values.
        self.iluk_numeric_only(a, k_limit, max_diag_abs)
    }

    fn iluk_numeric_only(
        &mut self,
        a: &CsrMatrix<f64>,
        _k_limit: usize,
        max_diag_abs: f64,
    ) -> Result<(), KError> {
        use symbolic::RowWork;
        let n = self.n;
        let rp = a.row_ptr();
        let cj = a.col_idx();
        let vv = a.values();
        let mut w = RowWork {
            mark: Vec::new(),
            idx: Vec::new(),
            val: Vec::new(),
        };
        symbolic::ensure_rowwork(&mut w, n);

        for i in 0..n {
            // load A row into work
            symbolic::ensure_rowwork(&mut w, n);
            for p in rp[i]..rp[i + 1] {
                let j = cj[p];
                let pos = symbolic::find_or_insert(&mut w, j);
                w.val[pos] = Real::from_real(vv[p]);
            }

            // eliminate for j in L pattern (already filtered by <=k)
            let ls = self.l_row[i];
            let le = self.l_row[i + 1];
            for pos in ls..le {
                let j = self.l_col[pos];
                let wij = if w.mark[j] >= 0 {
                    w.val[w.mark[j] as usize]
                } else {
                    Real::zero()
                };
                let djj = self.u_val[self.u_diag_ix[j]];
                let lij = if djj == Real::zero() {
                    Real::zero()
                } else {
                    wij / djj
                };
                self.l_val[pos] = lij;
                // AXPY into k>j but only if k exists in this row's U pattern
                let urs = self.u_row[j];
                let ure = self.u_row[j + 1];
                for q in urs..ure {
                    let kcol = self.u_col[q];
                    if kcol <= j {
                        continue;
                    }
                    let mk = w.mark.get(kcol).copied().unwrap_or(-1);
                    if mk >= 0 {
                        w.val[mk as usize] -= lij * self.u_val[q];
                    }
                }
            }

            // finalize U row values from work restricted to U pattern
            let us = self.u_row[i];
            let ue = self.u_row[i + 1];
            let mut diag = Real::zero();
            for q in us..ue {
                let k = self.u_col[q];
                let v = if w.mark.get(k).copied().unwrap_or(-1) >= 0 {
                    w.val[w.mark[k] as usize]
                } else {
                    Real::zero()
                };
                if k == i {
                    diag = v;
                }
                self.u_val[q] = v;
            }
            // pivot
            let fixed = pivot::handle_pivot(
                diag,
                self.cfg.pivot,
                self.cfg.pivot_threshold,
                self.cfg.diag_perturb_factor,
                max_diag_abs,
            )
            .map_err(|_| KError::ZeroPivot(i))?;
            let dix = self.u_diag_ix[i];
            self.u_val[dix] = fixed;

            symbolic::clear_rowwork(&mut w);
        }
        Ok(())
    }

    fn factor_iluk_numeric_only(
        &mut self,
        a: &CsrMatrix<f64>,
        k_limit: usize,
    ) -> Result<(), KError> {
        // Recompute max diag
        let mut max_diag_abs = 0.0f64;
        let rp = a.row_ptr();
        let cj = a.col_idx();
        let vv = a.values();
        for i in 0..self.n {
            let mut di = 0.0;
            for p in rp[i]..rp[i + 1] {
                if cj[p] == i {
                    di = vv[p];
                    break;
                }
            }
            max_diag_abs = max_diag_abs.max(di.abs());
        }
        self.iluk_numeric_only(a, k_limit, max_diag_abs)
    }

    // === ILUT(p, tau) implementation with separate L/U caps ===
    fn factor_ilut(&mut self, a: &CsrMatrix<f64>, params: &IlutParams) -> Result<(), KError> {
        let n = a.nrows();
        if n != a.ncols() {
            return Err(KError::InvalidInput("ILUT requires square matrix".into()));
        }
        self.n = n;

        // Builders for L and U
        let mut l_build = CsrBuilder::new(n);
        let mut u_build = CsrBuilder::new(n);
        let mut inv_diag_u = vec![Real::zero(); n];

        // Row workspace
        let mut w = RowWork::new();
        w.ensure_size(n);
        let mut l_tmp: Vec<(usize, Real)> = Vec::new();
        let mut u_tmp: Vec<(usize, Real)> = Vec::new();

        let mut max_diag_abs = 0.0f64;

        for i in 0..n {
            w.clear_row();
            l_tmp.clear();
            u_tmp.clear();

            // Seed w from row i of A
            let (a_cols, a_vals) = a.row(i);
            let mut row_inf: f64 = 0.0;
            for (&j, &v) in a_cols.iter().zip(a_vals.iter()) {
                if v != 0.0 {
                    w.set(j, Real::from_real(v));
                    row_inf = row_inf.max(v.abs());
                }
            }
            let tau = params.droptol_abs + params.droptol_rel * row_inf;

            // Eliminate lower entries
            let mut lowers: Vec<usize> = w.iter().filter(|&(j, _)| j < i).map(|(j, _)| j).collect();
            lowers.sort_unstable();
            for &k in &lowers {
                let wk = w.get(k);
                if wk == Real::zero() {
                    continue;
                }
                let lik = wk * inv_diag_u[k];
                if params.early_drop && lik.abs() < tau {
                    w.set(k, Real::zero());
                    continue;
                }
                l_tmp.push((k, lik));
                w.set(k, Real::zero());

                let (u_cols_k, u_vals_k) = u_build.row(k);
                for (&j, &ukj) in u_cols_k.iter().zip(u_vals_k.iter()) {
                    if j <= k {
                        continue;
                    }
                    let newv: Real = w.get(j) - lik * ukj;
                    if params.early_drop && newv.abs() < tau {
                        w.set(j, Real::zero());
                    } else {
                        w.set(j, newv);
                    }
                }
            }

            // Split remaining w into U-part
            for (j, v) in w.iter() {
                if j >= i && (j == i || v.abs() >= tau) {
                    u_tmp.push((j, v));
                }
            }
            if !u_tmp.iter().any(|(j, _)| *j == i) {
                u_tmp.push((i, Real::zero()));
            }

            // Cap L entries
            if params.p_l > 0 && l_tmp.len() > params.p_l {
                l_tmp.sort_by(|a, b| b.1.abs().partial_cmp(&a.1.abs()).unwrap());
                l_tmp.truncate(params.p_l);
            }

            // Cap U entries (excluding diagonal)
            let mut diag = Real::zero();
            if let Some(pos) = u_tmp.iter().position(|(j, _)| *j == i) {
                diag = u_tmp[pos].1;
                u_tmp.remove(pos);
            }
            if params.p_u > 0 && u_tmp.len() > params.p_u {
                u_tmp.sort_by(|a, b| b.1.abs().partial_cmp(&a.1.abs()).unwrap());
                u_tmp.truncate(params.p_u);
            }
            u_tmp.push((i, diag));

            // Sort by column for determinism
            if params.reproducible_order {
                l_tmp.sort_by(|a, b| a.0.cmp(&b.0));
                u_tmp.sort_by(|a, b| a.0.cmp(&b.0));
            } else {
                l_tmp.sort_unstable_by(|a, b| a.0.cmp(&b.0));
                u_tmp.sort_unstable_by(|a, b| a.0.cmp(&b.0));
            }

            // Pivot handling
            let diag_pos = u_tmp.iter().position(|(j, _)| *j == i).unwrap();
            let mut uii = u_tmp[diag_pos].1;
            max_diag_abs = max_diag_abs.max(uii.abs());
            let tau = params.pivot_tau;
            match params.pivot {
                PivotPolicy::Strict => {
                    if uii.abs() < tau {
                        return Err(KError::ZeroPivot(i));
                    }
                }
                PivotPolicy::Threshold => {
                    if uii.abs() < tau {
                        if uii == Real::zero() {
                            uii = Real::from_real(tau);
                        } else {
                            uii = uii * Real::from_real(tau / uii.abs());
                        }
                    }
                }
                PivotPolicy::DiagonalPerturbation => {
                    if uii.abs() < tau {
                        let direction = if uii == Real::zero() {
                            Real::one()
                        } else {
                            uii / Real::from_real(uii.abs())
                        };
                        uii += direction * Real::from_real(tau);
                    }
                }
            }
            u_tmp[diag_pos].1 = uii;
            inv_diag_u[i] = uii.inv();

            // Store rows into builders
            for &(k, v) in &l_tmp {
                l_build.push(i, k, v);
            }
            l_build.push(i, i, Real::one());
            for &(j, v) in &u_tmp {
                u_build.push(i, j, v);
            }
        }

        // Finalize builders into CSR arrays
        let (l_row, l_col, l_val) = l_build.finalize_sorted_unique(params.reproducible_order);
        let (u_row, u_col, u_val) = u_build.finalize_sorted_unique(params.reproducible_order);

        self.l_row = l_row;
        self.l_col = l_col;
        self.l_val = l_val;
        self.u_row = u_row;
        self.u_col = u_col;
        self.u_val = u_val;

        self.u_diag_ix.clear();
        self.u_diag_ix.resize(n, 0);
        for i in 0..n {
            let rs = self.u_row[i];
            let re = self.u_row[i + 1];
            if let Some(pos) = self.u_col[rs..re].iter().position(|&c| c == i) {
                self.u_diag_ix[i] = rs + pos;
            } else {
                return Err(KError::InvalidInput("missing diagonal".into()));
            }
        }

        self.resize_apply_workspace(n);

        // Optional numeric refine
        self.ilut_numeric_only(a, max_diag_abs)
    }

    fn ilut_numeric_only(&mut self, a: &CsrMatrix<f64>, max_diag_abs: f64) -> Result<(), KError> {
        // Re-run elimination using fixed L/U patterns (no drop/cap)
        use symbolic::RowWork;
        let n = self.n;
        let rp = a.row_ptr();
        let cj = a.col_idx();
        let vv = a.values();
        let mut w = RowWork {
            mark: Vec::new(),
            idx: Vec::new(),
            val: Vec::new(),
        };
        symbolic::ensure_rowwork(&mut w, n);
        for i in 0..n {
            symbolic::ensure_rowwork(&mut w, n);
            for p in rp[i]..rp[i + 1] {
                let j = cj[p];
                let pos = symbolic::find_or_insert(&mut w, j);
                w.val[pos] = Real::from_real(vv[p]);
            }
            // eliminate across L pattern
            let ls = self.l_row[i];
            let le = self.l_row[i + 1];
            for pos in ls..le {
                let j = self.l_col[pos];
                let wij = if w.mark[j] >= 0 {
                    w.val[w.mark[j] as usize]
                } else {
                    Real::zero()
                };
                let djj = self.u_val[self.u_diag_ix[j]];
                let lij = if djj == Real::zero() {
                    Real::zero()
                } else {
                    wij / djj
                };
                self.l_val[pos] = lij;
                let urs = self.u_row[j];
                let ure = self.u_row[j + 1];
                for q in urs..ure {
                    let kcol = self.u_col[q];
                    if kcol <= j {
                        continue;
                    }
                    let mk = w.mark.get(kcol).copied().unwrap_or(-1);
                    if mk >= 0 {
                        w.val[mk as usize] -= lij * self.u_val[q];
                    }
                }
            }
            // finalize U row
            let us = self.u_row[i];
            let ue = self.u_row[i + 1];
            let mut diag = Real::zero();
            for q in us..ue {
                let k = self.u_col[q];
                let v = if w.mark.get(k).copied().unwrap_or(-1) >= 0 {
                    w.val[w.mark[k] as usize]
                } else {
                    Real::zero()
                };
                if k == i {
                    diag = v;
                }
                self.u_val[q] = v;
            }
            let fixed = pivot::handle_pivot(
                diag,
                self.cfg.pivot,
                self.cfg.pivot_threshold,
                self.cfg.diag_perturb_factor,
                max_diag_abs,
            )
            .map_err(|_| KError::ZeroPivot(i))?;
            self.u_val[self.u_diag_ix[i]] = fixed;
            symbolic::clear_rowwork(&mut w);
        }
        Ok(())
    }

    fn factor_ilut_numeric_only(&mut self, a: &CsrMatrix<f64>) -> Result<(), KError> {
        // recompute max_diag_abs
        let rp = a.row_ptr();
        let cj = a.col_idx();
        let vv = a.values();
        let mut max_diag_abs = 0.0f64;
        for i in 0..self.n {
            let mut di = 0.0;
            for p in rp[i]..rp[i + 1] {
                if cj[p] == i {
                    di = vv[p];
                    break;
                }
            }
            max_diag_abs = max_diag_abs.max(di.abs());
        }
        self.ilut_numeric_only(a, max_diag_abs)
    }

    fn setup_from_local_square_ids(
        &mut self,
        a: &CsrMatrix<f64>,
        sid: StructureId,
        vid: ValuesId,
    ) -> Result<(), KError> {
        let pipeline =
            apply_preconditioning_pipeline(a, &self.cfg.conditioning, &self.cfg.reordering)?;
        let a = &pipeline.matrix;

        let structure_changed = self.last_sid != Some(sid);
        let values_changed = self.last_vid != Some(vid);

        if structure_changed || !self.cfg.numeric_update_fixed {
            self.perm = pipeline.metadata.left_perm.clone();
            self.pipeline_meta = pipeline.metadata.clone();
            self.factor_symbolic_and_numeric(a)?;
            self.build_levels_if_enabled();
            self.last_sid = Some(sid);
            self.last_vid = Some(vid);
            self.resize_apply_workspace(a.nrows());
            Ok(())
        } else if values_changed {
            self.pipeline_meta = pipeline.metadata.clone();
            self.factor_numeric_only(a)?;
            self.last_vid = Some(vid);
            Ok(())
        } else {
            Ok(())
        }
    }

    pub fn setup_local_square(&mut self, local: &LocalSquareCsr<f64>) -> Result<(), KError> {
        let op = local.as_csr();
        self.setup_from_local_square_ids(op, op.structure_id(), op.values_id())
    }

    fn resize_apply_workspace(&mut self, n: usize) {
        self.tmp.resize(n, Real::zero());
        self.tmp2.resize(n, Real::zero());
        self.tmp3.resize(n, Real::zero());
        #[cfg(feature = "complex")]
        {
            self.c_tmp.resize(n, S::zero());
            self.c_y_tmp.resize(n, S::zero());
            self.c_xr.resize(n, Real::zero());
            self.c_xi.resize(n, Real::zero());
            self.c_yr.resize(n, Real::zero());
            self.c_yi.resize(n, Real::zero());
        }
    }
}

#[cfg(not(feature = "complex"))]
impl Preconditioner for IluCsr {
    fn dims(&self) -> (usize, usize) {
        (self.n, self.n)
    }

    fn setup(&mut self, op: &dyn LinOp<S = f64>) -> Result<(), KError> {
        let drop = 0.0; // use full numerical content by default
        let a: Arc<CsrMatrix<f64>> = csr_from_linop(op, drop)?;
        let local = LocalSquareCsr::try_from(a.as_ref().clone())?;
        self.setup_from_local_square_ids(local.as_csr(), op.structure_id(), op.values_id())
    }

    fn apply(&self, _side: PcSide, x: &[f64], y: &mut [f64]) -> Result<(), KError> {
        self.apply_op_scalar(Op::NoTrans, x, y)
    }

    fn distributed_support(&self) -> PcDistributedSupport {
        PcDistributedSupport::LocalOnly
    }

    fn apply_op(&self, op: Op, x: &[f64], y: &mut [f64]) -> Result<(), KError> {
        if x.len() != self.n || y.len() != self.n {
            return Err(KError::InvalidInput(format!(
                "IluCsr::apply dimension mismatch: n={}, x.len()={}, y.len()={}",
                self.n,
                x.len(),
                y.len()
            )));
        }
        self.apply_op_scalar(op, x, y)
    }

    fn apply_mut(&mut self, _side: PcSide, x: &[f64], y: &mut [f64]) -> Result<(), KError> {
        self.apply_op_scalar_mut(Op::NoTrans, x, y)
    }

    fn supports_numeric_update(&self) -> bool {
        self.cfg.numeric_update_fixed
    }

    fn update_numeric(&mut self, op: &dyn LinOp<S = f64>) -> Result<(), KError> {
        if !self.cfg.numeric_update_fixed {
            return Err(KError::Unsupported("numeric update requires fixed pattern"));
        }
        if Some(op.structure_id()) != self.last_sid {
            return Err(KError::Unsupported("pattern changed; call update_symbolic"));
        }
        let a = csr_from_linop(op, 0.0)?;
        self.factor_numeric_only(&a)?;
        self.last_vid = Some(op.values_id());
        Ok(())
    }

    fn update_symbolic(&mut self, op: &dyn LinOp<S = f64>) -> Result<(), KError> {
        let a = csr_from_linop(op, 0.0)?;
        self.factor_symbolic_and_numeric(&a)?;
        self.build_levels_if_enabled();
        self.last_sid = Some(op.structure_id());
        self.last_vid = Some(op.values_id());
        Ok(())
    }

    fn required_format(&self) -> OpFormat {
        OpFormat::Csr
    }

    fn capabilities(&self) -> PcCaps {
        PcCaps {
            supports_transpose: true,
            supports_conj_trans: false,
            is_spd: false,
            side_restriction: Some(PcSide::Left),
        }
    }
}

#[cfg(feature = "complex")]
impl Preconditioner for IluCsr {
    fn dims(&self) -> (usize, usize) {
        (self.n, self.n)
    }

    fn setup(&mut self, op: &dyn LinOp<S = S>) -> Result<(), KError> {
        let csr = op
            .as_any()
            .downcast_ref::<CsrMatrix<S>>()
            .ok_or_else(|| {
                KError::Unsupported(
                    "IluCsr complex setup currently requires a CSR operator; non-CSR LinOp paths have no lossless complex ILU fallback".into(),
                )
            })?;
        let local = LocalSquareCsr::try_from(csr.clone())?;
        let csr = local.as_csr();

        let sid = op.structure_id();
        let vid = op.values_id();
        let structure_changed = self.last_sid != Some(sid);
        let values_changed = self.last_vid != Some(vid);

        if structure_changed || !self.cfg.numeric_update_fixed {
            let perm = match self.cfg.reordering.kind {
                ReorderingKind::None => Permutation::identity(csr.nrows()),
                ReorderingKind::Rcm => {
                    let a_real = CsrMatrix::from_csr(
                        csr.nrows(),
                        csr.ncols(),
                        csr.row_ptr().to_vec(),
                        csr.col_idx().to_vec(),
                        csr.values().iter().map(|v| v.real()).collect(),
                    );
                    rcm_csr(&a_real)
                }
                ReorderingKind::Amd => {
                    let a_real = CsrMatrix::from_csr(
                        csr.nrows(),
                        csr.ncols(),
                        csr.row_ptr().to_vec(),
                        csr.col_idx().to_vec(),
                        csr.values().iter().map(|v| v.real()).collect(),
                    );
                    amd_csr(&a_real)
                }
            };
            let a_perm = if self.cfg.reordering.symmetric {
                self.perm = perm.clone();
                self.pipeline_meta = PreconditioningMetadata::identity(csr.nrows());
                self.pipeline_meta.left_perm = perm.clone();
                self.pipeline_meta.right_perm = perm;
                permute_csr_symmetric(csr, &self.pipeline_meta.left_perm)
            } else {
                let a_real = CsrMatrix::from_csr(
                    csr.nrows(),
                    csr.ncols(),
                    csr.row_ptr().to_vec(),
                    csr.col_idx().to_vec(),
                    csr.values().iter().map(|v| v.real()).collect(),
                );
                let pipeline = apply_preconditioning_pipeline(
                    &a_real,
                    &ConditioningOptions::default(),
                    &self.cfg.reordering,
                )?;
                self.perm = pipeline.metadata.left_perm.clone();
                self.pipeline_meta = PreconditioningMetadata::identity(csr.nrows());
                self.pipeline_meta.left_perm = pipeline.metadata.left_perm.clone();
                self.pipeline_meta.right_perm = pipeline.metadata.right_perm;
                permute_csr_nonsymmetric(
                    csr,
                    &self.pipeline_meta.left_perm,
                    &self.pipeline_meta.right_perm,
                )
            };

            match self.cfg.kind {
                IluKind::Ilu0 | IluKind::Milu0 => {
                    if self.complex_force_degraded {
                        let a_real = CsrMatrix::from_csr(
                            a_perm.nrows(),
                            a_perm.ncols(),
                            a_perm.row_ptr().to_vec(),
                            a_perm.col_idx().to_vec(),
                            a_perm.values().iter().map(|v| v.real()).collect(),
                        );
                        self.factor_ilu0(&a_real)?;
                        self.native_complex_active = false;
                        self.complex_kernel_mode = IluComplexKernelMode::DegradedRealProjection;
                    } else {
                        self.factor_ilu0_complex(&a_perm)?;
                    }
                }
                IluKind::Iluk { k } => {
                    if self.complex_force_degraded {
                        let a_real = CsrMatrix::from_csr(
                            a_perm.nrows(),
                            a_perm.ncols(),
                            a_perm.row_ptr().to_vec(),
                            a_perm.col_idx().to_vec(),
                            a_perm.values().iter().map(|v| v.real()).collect(),
                        );
                        self.factor_iluk(&a_real, k)?;
                        self.native_complex_active = false;
                        self.complex_kernel_mode = IluComplexKernelMode::DegradedRealProjection;
                    } else {
                        self.factor_iluk_complex(&a_perm, k)?;
                    }
                }
                IluKind::Ilut { params } => self.factor_ilut_complex(&a_perm, &params)?,
            }

            self.build_levels_if_enabled();
            self.last_sid = Some(sid);
            self.last_vid = Some(vid);
            self.resize_apply_workspace(csr.nrows());
            Ok(())
        } else if values_changed {
            self.update_numeric(op)
        } else {
            Ok(())
        }
    }

    fn apply(&self, _side: PcSide, x: &[S], y: &mut [S]) -> Result<(), KError> {
        let n = self.n;
        if x.len() != n || y.len() != n {
            return Err(KError::InvalidInput(format!(
                "IluCsr::apply dimension mismatch: n={}, x.len()={}, y.len()={}",
                self.n,
                x.len(),
                y.len()
            )));
        }

        if self.native_complex_active {
            let mut w = vec![S::zero(); n];
            let mut y_perm = vec![S::zero(); n];
            self.pipeline_meta.left_perm.apply_vec(x, &mut w);
            for i in 0..n {
                let mut s = w[i];
                for p in self.l_row[i]..self.l_row[i + 1] {
                    s -= self.c_l_val[p] * w[self.l_col[p]];
                }
                w[i] = s;
            }
            for i in (0..n).rev() {
                let mut s = w[i];
                for p in self.u_row[i]..self.u_row[i + 1] {
                    let j = self.u_col[p];
                    if j > i {
                        s -= self.c_u_val[p] * w[j];
                    }
                }
                w[i] = s / self.c_u_val[self.u_diag_ix[i]];
            }
            self.pipeline_meta.right_perm.apply_vec_t(&w, &mut y_perm);
            y.copy_from_slice(&y_perm);
            Ok(())
        } else {
            let mut xr = vec![Real::zero(); n];
            let mut xi = vec![Real::zero(); n];
            let mut yr = vec![Real::zero(); n];
            let mut yi = vec![Real::zero(); n];
            for i in 0..n {
                xr[i] = x[i].real();
                xi[i] = x[i].imag();
            }
            self.apply_op_scalar(Op::NoTrans, &xr, &mut yr)?;
            self.apply_op_scalar(Op::NoTrans, &xi, &mut yi)?;
            for i in 0..n {
                y[i] = S::from_parts(yr[i], yi[i]);
            }
            Ok(())
        }
    }

    fn apply_mut(&mut self, _side: PcSide, x: &[S], y: &mut [S]) -> Result<(), KError> {
        self.apply_complex_mut(x, y)
    }

    fn supports_numeric_update(&self) -> bool {
        self.cfg.numeric_update_fixed
    }

    fn update_numeric(&mut self, op: &dyn LinOp<S = S>) -> Result<(), KError> {
        if !self.cfg.numeric_update_fixed {
            return Err(KError::Unsupported("numeric update requires fixed pattern"));
        }
        if Some(op.structure_id()) != self.last_sid {
            return Err(KError::Unsupported("pattern changed; call update_symbolic"));
        }

        let csr = op.as_any().downcast_ref::<CsrMatrix<S>>().ok_or_else(|| {
            KError::Unsupported("IluCsr complex numeric update requires CSR".into())
        })?;
        let a_perm = if self.cfg.reordering.symmetric {
            permute_csr_symmetric(csr, &self.pipeline_meta.left_perm)
        } else {
            permute_csr_nonsymmetric(
                csr,
                &self.pipeline_meta.left_perm,
                &self.pipeline_meta.right_perm,
            )
        };
        match self.cfg.kind {
            IluKind::Ilu0 | IluKind::Milu0 => {
                if self.complex_force_degraded {
                    let a_real = CsrMatrix::from_csr(
                        a_perm.nrows(),
                        a_perm.ncols(),
                        a_perm.row_ptr().to_vec(),
                        a_perm.col_idx().to_vec(),
                        a_perm.values().iter().map(|v| v.real()).collect(),
                    );
                    self.factor_ilu0(&a_real)?;
                    self.native_complex_active = false;
                    self.complex_kernel_mode = IluComplexKernelMode::DegradedRealProjection;
                } else {
                    self.factor_ilu0_complex(&a_perm)?;
                }
            }
            IluKind::Iluk { k } => {
                if self.complex_force_degraded {
                    let a_real = CsrMatrix::from_csr(
                        a_perm.nrows(),
                        a_perm.ncols(),
                        a_perm.row_ptr().to_vec(),
                        a_perm.col_idx().to_vec(),
                        a_perm.values().iter().map(|v| v.real()).collect(),
                    );
                    self.factor_iluk(&a_real, k)?;
                    self.native_complex_active = false;
                    self.complex_kernel_mode = IluComplexKernelMode::DegradedRealProjection;
                } else {
                    self.factor_iluk_complex(&a_perm, k)?;
                }
            }
            IluKind::Ilut { params } => self.factor_ilut_complex(&a_perm, &params)?,
        }
        self.last_vid = Some(op.values_id());
        Ok(())
    }

    fn update_symbolic(&mut self, op: &dyn LinOp<S = S>) -> Result<(), KError> {
        self.last_sid = None;
        self.last_vid = None;
        self.setup(op)
    }

    fn required_format(&self) -> OpFormat {
        OpFormat::Csr
    }

    fn capabilities(&self) -> PcCaps {
        PcCaps {
            supports_transpose: false,
            supports_conj_trans: false,
            is_spd: false,
            side_restriction: Some(PcSide::Left),
        }
    }

    fn apply_op(&self, op: Op, x: &[S], y: &mut [S]) -> Result<(), KError> {
        if op == Op::NoTrans {
            return self.apply(PcSide::Left, x, y);
        }
        Err(KError::Unsupported(
            "IluCsr complex transpose kernels are not yet implemented".into(),
        ))
    }
}

impl LocalPreconditioner<f64> for IluCsr {
    fn dims(&self) -> (usize, usize) {
        (self.n, self.n)
    }

    fn apply_local(&self, x: &[f64], y: &mut [f64]) -> Result<(), KError> {
        if x.len() != self.n || y.len() != self.n {
            return Err(KError::InvalidInput(format!(
                "IluCsr::apply_local dimension mismatch: n={}, x.len()={}, y.len()={}",
                self.n,
                x.len(),
                y.len()
            )));
        }

        self.apply_op_scalar(Op::NoTrans, x, y)
    }
}

#[cfg(feature = "complex")]
impl KPreconditioner for IluCsr {
    // Use the *complex* scalar type from the algebra prelude, not the local f64 alias.
    type Scalar = crate::algebra::prelude::S;

    #[inline]
    fn dims(&self) -> (usize, usize) {
        // IluCsr already implements the real Preconditioner
        crate::preconditioner::Preconditioner::dims(self)
    }

    fn apply_s(
        &self,
        side: PcSide,
        x: &[Self::Scalar],
        y: &mut [Self::Scalar],
        scratch: &mut BridgeScratch,
    ) -> Result<(), KError> {
        let _ = scratch;
        self.apply(side, x, y)
    }

    fn apply_mut_s(
        &mut self,
        side: PcSide,
        x: &[Self::Scalar],
        y: &mut [Self::Scalar],
        scratch: &mut BridgeScratch,
    ) -> Result<(), KError> {
        let _ = scratch;
        crate::preconditioner::Preconditioner::apply_mut(self, side, x, y)
    }
}

impl IluCsr {
    #[cfg(feature = "complex")]
    /// Reports which kernel family backed the most recent complex factorization.
    ///
    /// `DegradedRealProjection` means the factorization path projected the complex system
    /// to a real surrogate (typically Re(A)); treat this mode as provisional and do not use
    /// it for complex robustness/performance claims.
    pub fn complex_kernel_mode(&self) -> IluComplexKernelMode {
        self.complex_kernel_mode
    }

    #[cfg(feature = "complex")]
    pub fn set_complex_force_degraded(&mut self, on: bool) {
        self.complex_force_degraded = on;
    }

    #[cfg(feature = "complex")]
    fn apply_complex_mut(&mut self, x: &[S], y: &mut [S]) -> Result<(), KError> {
        let n = self.n;
        if x.len() != n || y.len() != n {
            return Err(KError::InvalidInput(format!(
                "IluCsr::apply dimension mismatch: n={}, x.len()={}, y.len()={}",
                self.n,
                x.len(),
                y.len()
            )));
        }
        if self.c_tmp.len() != n
            || self.c_y_tmp.len() != n
            || self.c_xr.len() != n
            || self.c_xi.len() != n
            || self.c_yr.len() != n
            || self.c_yi.len() != n
            || self.tmp.len() != n
            || self.tmp2.len() != n
            || self.tmp3.len() != n
        {
            self.resize_apply_workspace(n);
        }

        if self.native_complex_active {
            let mut w = std::mem::take(&mut self.c_tmp);
            let mut y_perm = std::mem::take(&mut self.c_y_tmp);
            let result = (|| {
                let w = &mut w[..n];
                let y_perm = &mut y_perm[..n];
                self.pipeline_meta.left_perm.apply_vec(x, w);
                for i in 0..n {
                    let mut s = w[i];
                    for p in self.l_row[i]..self.l_row[i + 1] {
                        s -= self.c_l_val[p] * w[self.l_col[p]];
                    }
                    w[i] = s;
                }
                for i in (0..n).rev() {
                    let mut s = w[i];
                    for p in self.u_row[i]..self.u_row[i + 1] {
                        let j = self.u_col[p];
                        if j > i {
                            s -= self.c_u_val[p] * w[j];
                        }
                    }
                    w[i] = s / self.c_u_val[self.u_diag_ix[i]];
                }
                self.pipeline_meta.right_perm.apply_vec_t(w, y_perm);
                y.copy_from_slice(y_perm);
                Ok(())
            })();
            self.c_tmp = w;
            self.c_y_tmp = y_perm;
            result
        } else {
            let mut xr = std::mem::take(&mut self.c_xr);
            let mut xi = std::mem::take(&mut self.c_xi);
            let mut yr = std::mem::take(&mut self.c_yr);
            let mut yi = std::mem::take(&mut self.c_yi);
            let result = (|| {
                for i in 0..n {
                    xr[i] = x[i].real();
                    xi[i] = x[i].imag();
                }
                self.apply_op_scalar_mut(Op::NoTrans, &xr[..n], &mut yr[..n])?;
                self.apply_op_scalar_mut(Op::NoTrans, &xi[..n], &mut yi[..n])?;
                for i in 0..n {
                    y[i] = S::from_parts(yr[i], yi[i]);
                }
                Ok(())
            })();
            self.c_xr = xr;
            self.c_xi = xi;
            self.c_yr = yr;
            self.c_yi = yi;
            result
        }
    }

    #[inline]
    pub(crate) fn n(&self) -> usize {
        self.n
    }
    #[inline]
    pub(crate) fn l_row(&self) -> &[usize] {
        &self.l_row
    }
    #[inline]
    pub(crate) fn l_col(&self) -> &[usize] {
        &self.l_col
    }
    #[inline]
    pub(crate) fn l_val(&self) -> &[Real] {
        &self.l_val
    }
    #[inline]
    pub(crate) fn u_row(&self) -> &[usize] {
        &self.u_row
    }
    #[inline]
    pub(crate) fn u_col(&self) -> &[usize] {
        &self.u_col
    }
    #[inline]
    pub(crate) fn u_val(&self) -> &[Real] {
        &self.u_val
    }
    #[inline]
    pub(crate) fn u_diag_ix(&self) -> &[usize] {
        &self.u_diag_ix
    }
    #[allow(dead_code)]
    #[inline]
    pub(crate) fn tmp(&self) -> &[Real] {
        &self.tmp
    }
    #[allow(dead_code)]
    #[inline]
    pub(crate) fn tmp_mut(&mut self) -> &mut [Real] {
        &mut self.tmp
    }

    #[inline]
    pub(crate) fn buckets_fwd(&self) -> &[Vec<usize>] {
        &self.buckets_fwd
    }
    #[inline]
    pub(crate) fn buckets_bwd(&self) -> &[Vec<usize>] {
        &self.buckets_bwd
    }

    fn pipeline_apply_left(&self, x: &[Real], y: &mut [Real]) {
        self.pipeline_meta.left_perm.apply_vec(x, y);
        if let Some(scale) = &self.pipeline_meta.row_scaling {
            for i in 0..y.len() {
                y[i] /= scale[i];
            }
        }
    }

    fn pipeline_apply_right_inverse_with_tmp(&self, x: &[Real], tmp: &mut [Real], y: &mut [Real]) {
        self.pipeline_meta.right_perm.apply_vec_t(x, tmp);
        if let Some(scale) = &self.pipeline_meta.col_scaling {
            for i in 0..y.len() {
                y[i] = tmp[i] / scale[i];
            }
        } else {
            y.copy_from_slice(tmp);
        }
    }

    fn apply_op_scalar(&self, op: Op, x: &[Real], y: &mut [Real]) -> Result<(), KError> {
        if x.len() != self.n || y.len() != self.n {
            return Err(KError::InvalidInput(format!(
                "IluCsr::apply dimension mismatch: n={}, x.len()={}, y.len()={}",
                self.n,
                x.len(),
                y.len()
            )));
        }
        let mut x_perm = vec![Real::zero(); self.n];
        let mut y_perm = vec![Real::zero(); self.n];
        let mut right_tmp = vec![Real::zero(); self.n];
        self.apply_op_scalar_with_workspace(op, x, y, &mut x_perm, &mut y_perm, &mut right_tmp)
    }

    fn apply_op_scalar_mut(&mut self, op: Op, x: &[Real], y: &mut [Real]) -> Result<(), KError> {
        if self.tmp.len() != self.n || self.tmp2.len() != self.n || self.tmp3.len() != self.n {
            self.resize_apply_workspace(self.n);
        }
        let mut x_perm = std::mem::take(&mut self.tmp);
        let mut y_perm = std::mem::take(&mut self.tmp2);
        let mut right_tmp = std::mem::take(&mut self.tmp3);
        let result = self.apply_op_scalar_with_workspace(
            op,
            x,
            y,
            &mut x_perm[..self.n],
            &mut y_perm[..self.n],
            &mut right_tmp[..self.n],
        );
        self.tmp = x_perm;
        self.tmp2 = y_perm;
        self.tmp3 = right_tmp;
        result
    }

    fn apply_op_scalar_with_workspace(
        &self,
        op: Op,
        x: &[Real],
        y: &mut [Real],
        x_perm: &mut [Real],
        y_perm: &mut [Real],
        right_tmp: &mut [Real],
    ) -> Result<(), KError> {
        if x.len() != self.n || y.len() != self.n {
            return Err(KError::InvalidInput(format!(
                "IluCsr::apply dimension mismatch: n={}, x.len()={}, y.len()={}",
                self.n,
                x.len(),
                y.len()
            )));
        }
        self.pipeline_apply_left(x, x_perm);
        match op {
            Op::NoTrans => {
                if self.cfg.level_sched {
                    tri_solve::tri_solve_level_scheduled(self, x_perm, y_perm)
                } else {
                    tri_solve::tri_solve_serial(self, x_perm, y_perm)
                }
            }
            Op::Trans | Op::ConjTrans => {
                let ut = self
                    .ut
                    .get_or_init(|| transpose_csr(self.n, &self.u_row, &self.u_col, &self.u_val));
                let lt = self
                    .lt
                    .get_or_init(|| transpose_csr(self.n, &self.l_row, &self.l_col, &self.l_val));
                tri_solve::tri_solve_transpose_serial(
                    self, &ut.0, &ut.1, &ut.2, &lt.0, &lt.1, &lt.2, x_perm, y_perm,
                )
            }
        }?;
        self.pipeline_apply_right_inverse_with_tmp(y_perm, right_tmp, y);
        Ok(())
    }
}

fn transpose_csr(
    n: usize,
    row: &[usize],
    col: &[usize],
    val: &[Real],
) -> (Vec<usize>, Vec<usize>, Vec<Real>) {
    let nnz = col.len();
    let mut t_row = vec![0usize; n + 1];
    for &j in col {
        t_row[j + 1] += 1;
    }
    for i in 0..n {
        t_row[i + 1] += t_row[i];
    }
    let mut t_col = vec![0usize; nnz];
    let mut t_val = vec![Real::zero(); nnz];
    let mut offset = t_row.clone();
    for i in 0..n {
        for p in row[i]..row[i + 1] {
            let j = col[p];
            let dest = offset[j];
            t_col[dest] = i;
            t_val[dest] = val[p];
            offset[j] += 1;
        }
    }
    (t_row, t_col, t_val)
}

#[cfg(all(test, feature = "complex"))]
mod complex_pivot_tests {
    use super::*;

    fn checkerboard_zero_diag() -> CsrMatrix<S> {
        CsrMatrix::from_csr(
            2,
            2,
            vec![0, 1, 2],
            vec![1, 0],
            vec![S::from_real(1.0), S::from_real(1.0)],
        )
    }

    #[test]
    fn ilu0_complex_zero_pivot_obeys_strategy() {
        let a = checkerboard_zero_diag();

        let mut strict = IluCsr::new_with_config(IluCsrConfig {
            kind: IluKind::Ilu0,
            pivot: PivotStrategy::Strict,
            pivot_threshold: 1e-12,
            diag_perturb_factor: 1e-10,
            level_sched: false,
            numeric_update_fixed: true,
            logging: 0,
            reordering: ReorderingOptions::default(),
            conditioning: ConditioningOptions::default(),
        });
        assert!(strict.factor_ilu0_complex(&a).is_err());

        let mut threshold = IluCsr::new_with_config(IluCsrConfig {
            kind: IluKind::Ilu0,
            pivot: PivotStrategy::Threshold,
            pivot_threshold: 1e-12,
            diag_perturb_factor: 1e-10,
            level_sched: false,
            numeric_update_fixed: true,
            logging: 0,
            reordering: ReorderingOptions::default(),
            conditioning: ConditioningOptions::default(),
        });
        threshold
            .factor_ilu0_complex(&a)
            .expect("threshold pivot policy should floor tiny complex pivots");
        for i in 0..threshold.n {
            let d = threshold.c_u_val[threshold.u_diag_ix[i]];
            assert!(d.abs() >= 1e-12, "row {i} pivot should be floored");
        }

        let mut perturb = IluCsr::new_with_config(IluCsrConfig {
            kind: IluKind::Ilu0,
            pivot: PivotStrategy::DiagonalPerturbation,
            pivot_threshold: 1e-12,
            diag_perturb_factor: 1e-10,
            level_sched: false,
            numeric_update_fixed: true,
            logging: 0,
            reordering: ReorderingOptions::default(),
            conditioning: ConditioningOptions::default(),
        });
        perturb
            .factor_ilu0_complex(&a)
            .expect("diag perturbation should repair tiny complex pivots");
        for i in 0..perturb.n {
            let d = perturb.c_u_val[perturb.u_diag_ix[i]];
            assert!(d.abs() > 0.0, "row {i} pivot should be nonzero");
        }
    }
}