edgefirst-tensor 0.33.0

Zero-copy tensor memory management with DMA, shared memory, and heap backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
// SPDX-FileCopyrightText: Copyright 2026 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0

//! The dynamic backend: a thin newtype over the opaque C handle that calls
//! into `libedgefirst_tensor.so` instead of embedding this crate's own
//! implementation.
//!
//! Every method here is a caller of an already-`#[no_mangle]`-exported
//! `ef_tensor_*` function declared in `edgefirst-tensor-ffi` -- none of the
//! logic that produces a tensor's bytes, geometry, or metadata lives in this
//! file; it lives in `libedgefirst_tensor.so` (the `static`-backend build of
//! `edgefirst-tensor-capi`). See `docs/superpowers/plans/
//! PRIMITIVE-INVENTORY.md` for which methods are primitive (a direct
//! `ef_tensor_*` call, here) versus derived (expressible over the primitives,
//! in `derived.rs`, identical on both backends).
//!
//! Not `#[repr(transparent)]`: unlike the brief's original stub, this struct
//! also caches the shape as `Vec<usize>` (because `shape()` must return a
//! borrowed `&[usize]`, but `ef_tensor_shape` returns a borrowed `*const
//! u64` -- a different element width) and a locally-derived
//! [`crate::BufferIdentity`] (because there is no `ef_tensor_*` primitive
//! that exposes one). Neither extra field changes `into_raw`/`from_raw`'s
//! contract: they only ever read/write the handle field explicitly, never
//! `transmute` the whole struct.

use std::fmt;
use std::ptr::NonNull;

use edgefirst_tensor_ffi::EfTensor;

use crate::{
    BufferIdentity, Colorimetry, CpuAccess, DType, Error, IdentityKind, PixelFormat, PixelLayout,
    Region, Result, TensorMemory, ViewOrigin,
};

/// The tensor handle, plus the facts this backend cannot re-derive from the
/// handle alone on every call (see the module docs).
pub struct TensorDyn {
    handle: NonNull<EfTensor>,
    shape_cache: Vec<usize>,
    identity: BufferIdentity,
    /// Lazily-fetched quantization, read back through the two-call
    /// `ef_tensor_quantization_{info,get}` idiom the first time
    /// [`Self::quantization`] is called on *this* Rust value, then served
    /// from cache. Exists because `quantization(&self) -> Option<&Quantization>`
    /// must hand back a borrow with a stable address for as long as `self`
    /// lives, and `Quantization` is variable-length -- there is nowhere
    /// else on `Tensor<T>` to put owned storage for it without adding a
    /// field there, which would break its `#[repr(transparent)]` layout
    /// over `TensorDyn` (see `dynamic_tensor.rs`'s module docs). `OnceLock`
    /// specifically (not a raw `&mut` cast, the F12 colorimetry race's
    /// shape) is what makes concurrent reads from multiple threads sharing
    /// one `&TensorDyn` sound: `get_or_init` serializes concurrent
    /// initializers itself, so no `&mut TensorDyn` is ever materialized
    /// while a `&TensorDyn` could be alive elsewhere. [`Self::set_quantization`]/
    /// [`Self::clear_quantization`] take `&mut self`, so Rust's own
    /// aliasing rules already guarantee no `&TensorDyn` (hence no
    /// in-flight `get_or_init`) can coexist with the write that replaces
    /// this field wholesale -- unlike colorimetry's cross-thread
    /// read/write race, this write path is Rust-borrow-checked, not
    /// merely documented. What this does **not** cover: a *different*
    /// `TensorDyn` Rust value wrapping the same underlying C handle (via a
    /// separate `retain` + `from_raw`) has its own, independent cache, so
    /// a `set_quantization` through one wrapper does not invalidate an
    /// already-cached read through another -- a documented staleness
    /// limitation, not a memory-safety one (each wrapper's cache is its
    /// own allocation).
    quantization_cache: std::sync::OnceLock<Option<crate::Quantization>>,
    /// Lazily-derived retained lens over the library-owned chroma plane.
    ///
    /// This is a cache, not a second source of truth: the first
    /// [`Self::chroma`] call obtains it from `ef_tensor_chroma`, and wrappers
    /// reconstructed with [`Self::from_raw`] derive their own cache from the
    /// handle again. Keeping the retained lens for this parent's lifetime
    /// lets the typed API return the same borrowed `Option<&Tensor<T>>` as
    /// the static backend and keeps native handles borrowed from that chroma
    /// lens valid through downstream imports.
    chroma_cache: std::sync::OnceLock<Option<Box<TensorDyn>>>,
    /// The texture NT handle [`Self::descriptor_pinned`] puts in a
    /// [`crate::protocol::kind::D3D11_TEXTURE`] descriptor, kept here for as
    /// long as this value lives.
    ///
    /// The static backend borrows the tensor's own handle
    /// (`d3d11_shared_handle_value`); across the C ABI there is no such
    /// accessor -- `ef_tensor_d3d11_shared_handle` transfers ownership of a
    /// *duplicate*, which a descriptor cannot own (it is `Copy` and has no
    /// drop). Writing the duplicate's value into the descriptor and dropping
    /// it leaves the descriptor naming a closed handle; leaking it leaks one
    /// handle per descriptor, and a per-frame producer builds one every
    /// frame. Holding it here gives it the same lifetime the static
    /// backend's borrowed handle has -- the producing tensor's, which the
    /// capsule keepalive already holds for the descriptor's whole life --
    /// and closes it exactly once, when this tensor drops.
    ///
    /// `OnceLock` for the reason [`Self::quantization_cache`] documents:
    /// `descriptor_pinned` takes `&self`, and `get_or_init` serializes
    /// concurrent initializers without ever materializing a `&mut`.
    #[cfg(target_os = "windows")]
    descriptor_texture_handle: std::sync::OnceLock<Option<std::os::windows::io::OwnedHandle>>,
}

// SAFETY: `TensorTrait<T>: Send + Sync` is a supertrait bound every consumer
// (e.g. `edgefirst-image`'s `gl/threaded.rs`, which wraps a `TensorDyn` for
// cross-thread GL work) relies on, and `NonNull<EfTensor>` is neither by
// default. The C ABI's handles are designed to cross threads: ownership is
// tracked by refcount (`ef_tensor_retain`/`ef_tensor_free`), not by Rust's
// aliasing rules, and every mutating entry point this backend calls
// (`ef_tensor_map`/`unmap`, `ef_tensor_set_colorimetry`, ...) is documented
// as safe to call from any thread holding a valid reference. `shape_cache`
// and `identity` are ordinary owned `Send + Sync` data;
// `quantization_cache` and `chroma_cache` are `OnceLock`s, `Sync` by
// construction whenever their contents are -- see those fields' own doc
// comments for why concurrent access through them specifically is sound,
// not just asserted here.
unsafe impl Send for TensorDyn {}
unsafe impl Sync for TensorDyn {}

impl Drop for TensorDyn {
    fn drop(&mut self) {
        // SAFETY: we hold one reference, taken at construction.
        unsafe { edgefirst_tensor_ffi::ef_tensor_free(self.handle.as_ptr()) }
    }
}

/// Same name, same meaning as the static backend's -- here it is the real
/// handle rather than a boxed Rust value.
pub type Raw = *mut EfTensor;

impl TensorDyn {
    /// Wrap an already-live handle, deriving the cached facts fresh.
    fn from_handle(handle: NonNull<EfTensor>) -> Self {
        let shape_cache = Self::query_shape(handle);
        let identity = Self::derive_identity(handle);
        TensorDyn {
            handle,
            shape_cache,
            identity,
            quantization_cache: std::sync::OnceLock::new(),
            chroma_cache: std::sync::OnceLock::new(),
            #[cfg(target_os = "windows")]
            descriptor_texture_handle: std::sync::OnceLock::new(),
        }
    }

    /// Derive this handle's [`BufferIdentity`].
    ///
    /// On Windows, a texture-backed handle uses the `ID3D11Texture2D*` behind
    /// `ef_tensor_d3d11_texture`, the same key the static backend's
    /// `d3d11::texture::tex_key` derives, so one texture has one identity
    /// whichever backend names it.
    ///
    /// For a DMA-BUF-backed handle, uses the native fd's `(st_dev, st_ino)`
    /// -- survives `dup`, and is the same value for every independent
    /// import of the same underlying buffer, matching the static backend's
    /// own `IdentityKind::DmaBuf` strategy exactly (`dma.rs::
    /// identity_from_stat`) rather than the handle's own process-local
    /// address. Observable from the Rust side today via an `fstat` on the
    /// native fd [`Self::plane0`] already exposes, so it needs no new
    /// `ef_tensor_*` primitive (proposed by task 15's report, implemented
    /// here by task 17).
    ///
    /// **Why this matters beyond `aliases()` returning the right bool.**
    /// `edgefirst-image`'s GL import cache (`gl/cache.rs`) keys a cached
    /// EGLImage on `buffer_identity().id()` and is documented as safe to
    /// outlive the tensor that produced it *specifically because* a
    /// DMA-BUF/IOSurface-kind identity is an OS-level key: the kernel
    /// cannot recycle an inode onto a different buffer while any reference
    /// (including the cache's own retained import) is alive. The
    /// `HostPtr` fallback this replaces has no such guarantee -- it is a
    /// process address, and this library's own C-side allocator can (and,
    /// under allocation churn, will) reuse a just-freed `EfTensorImpl`'s
    /// address for the next handle it mints. A cache entry keyed on that
    /// reused address, for a request with matching geometry, would serve a
    /// *different* buffer's stale imported texture: wrong pixels, no
    /// error, no crash -- an ABA hazard the design a `IdentityKind` doc
    /// comment (`lib.rs`) explicitly says a process-local kind must not be
    /// exposed to a cache like this without exactly this kind of stable,
    /// unrecyclable-while-live key. The D3D11 branch is the same argument on
    /// Windows: an `ID3D11Texture2D*` is process-local like a handle address,
    /// but ANGLE's EGLImage holds a reference to the texture, so the address
    /// cannot be recycled while a cache entry keyed on it can be found --
    /// which a handle address, held by nothing, can. Falls back to `HostPtr`
    /// (this handle's own address) for every other storage kind, or if the fd
    /// cannot be `fstat`-ed -- no `ef_tensor_*` primitive exposes a
    /// system-level identity key for those, so a process-local one is the best
    /// answer available, same as the static backend's own `Mem`/`Pbo` tensors,
    /// neither of which any GPU import path accepts.
    fn derive_identity(handle: NonNull<EfTensor>) -> BufferIdentity {
        // Gated on the storage kind first, as the Unix branch is, so a `Mem`
        // or PBO handle does not pay an `ENOTSUP` that overwrites the ABI's
        // last-error slot on every construction.
        #[cfg(target_os = "windows")]
        {
            // SAFETY: `handle` is live for the duration of this call.
            let code = unsafe { edgefirst_tensor_ffi::ef_tensor_storage_kind(handle.as_ptr()) };
            if TensorMemory::from_code(code) == Some(TensorMemory::DmaBuf) {
                // SAFETY: `handle` is live for the duration of this call; the
                // pointer is borrowed and carries no reference of its own.
                let tex = unsafe { edgefirst_tensor_ffi::ef_tensor_d3d11_texture(handle.as_ptr()) };
                if !tex.is_null() {
                    return BufferIdentity::derived(
                        IdentityKind::D3d11Texture,
                        tex as usize as u64,
                    );
                }
            }
        }
        #[cfg(unix)]
        {
            // SAFETY: `handle` is live for the duration of this call.
            let code = unsafe { edgefirst_tensor_ffi::ef_tensor_storage_kind(handle.as_ptr()) };
            if TensorMemory::from_code(code) == Some(TensorMemory::DmaBuf) {
                let mut plane = edgefirst_tensor_ffi::EfTensorPlane::default();
                // SAFETY: `handle` is live; `plane` is a valid local out-param.
                let rc = unsafe {
                    edgefirst_tensor_ffi::ef_tensor_plane_at(handle.as_ptr(), 0, &mut plane)
                };
                if rc == 0 && plane.handle >= 0 {
                    // SAFETY: `plane.handle` is a valid fd owned by this
                    // handle for at least the duration of this borrow.
                    let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(plane.handle as i32) };
                    if let Ok(stat) = nix::sys::stat::fstat(fd) {
                        return identity_from_stat(&stat);
                    }
                }
            }
        }
        BufferIdentity::derived(IdentityKind::HostPtr, handle.as_ptr() as u64)
    }

    /// Whether this handle is a two-allocation semi-planar tensor.
    pub fn is_multiplane(&self) -> bool {
        // SAFETY: `self.handle` is live.
        unsafe { edgefirst_tensor_ffi::ef_tensor_is_multiplane(self.handle.as_ptr()) != 0 }
    }

    /// Borrowed lens over the chroma plane, or `None` if this is not
    /// multiplane.
    pub fn chroma(&self) -> Option<&TensorDyn> {
        self.chroma_cache
            .get_or_init(|| {
                // SAFETY: `self.handle` is live. A non-NULL result carries
                // one retained reference that the cached lens owns.
                let p = unsafe { edgefirst_tensor_ffi::ef_tensor_chroma(self.handle.as_ptr()) };
                std::ptr::NonNull::new(p).map(|h| Box::new(unsafe { Self::from_raw(h.as_ptr()) }))
            })
            .as_deref()
    }

    /// Read the handle's current shape via `ef_tensor_ndim`/`ef_tensor_shape`.
    fn query_shape(handle: NonNull<EfTensor>) -> Vec<usize> {
        // SAFETY: `handle` is a live handle for the duration of this call.
        unsafe {
            let ndim = edgefirst_tensor_ffi::ef_tensor_ndim(handle.as_ptr());
            let ptr = edgefirst_tensor_ffi::ef_tensor_shape(handle.as_ptr());
            if ptr.is_null() || ndim == 0 {
                return Vec::new();
            }
            std::slice::from_raw_parts(ptr, ndim as usize)
                .iter()
                .map(|&d| d as usize)
                .collect()
        }
    }

    /// Give up ownership, yielding the handle itself. No allocation beyond
    /// the cache this instance already carried, which is simply dropped: it
    /// is derived state, not something `from_raw` needs handed back to it.
    pub fn into_raw(self) -> Raw {
        let p = self.handle.as_ptr();
        std::mem::forget(self); // the caller owns the reference now
        p
    }

    /// # Safety
    /// `p` must be a live handle carrying a reference the caller owns.
    pub unsafe fn from_raw(p: Raw) -> TensorDyn {
        Self::from_handle(unsafe { NonNull::new_unchecked(p) })
    }

    /// # Safety
    /// `p` must be a live handle from an EdgeFirst library.
    pub unsafe fn with_raw<R>(p: Raw, f: impl FnOnce(&mut TensorDyn) -> R) -> R {
        let mut t =
            std::mem::ManuallyDrop::new(Self::from_handle(unsafe { NonNull::new_unchecked(p) }));
        f(&mut t)
    }

    // --- The 9 primitives `TensorTrait<T>`'s method set requires a
    // per-backend implementation for (`lib.rs`'s trait definition; see
    // `docs/superpowers/plans/PRIMITIVE-INVENTORY.md`). Each is a direct
    // `ef_tensor_*` call, same as the static backend's own inherent methods
    // of the same names dispatch to `Tensor<T>`'s.

    /// Create a type-erased tensor with the given shape and element type.
    ///
    /// Drives the builder (`ef_tensor_builder_{new,dtype,shape,storage,
    /// alloc}`) rather than the shortcut `ef_tensor_new`, because that
    /// shortcut only ever allocates host memory -- the builder is what lets
    /// `memory` name a specific backing, matching the static backend's own
    /// contract. `name` is accepted for signature parity but has no effect:
    /// no `ef_tensor_*` primitive carries a tensor's name across the ABI.
    pub fn new(
        shape: &[usize],
        dtype: DType,
        memory: Option<TensorMemory>,
        _name: Option<&str>,
    ) -> Result<Self> {
        // SAFETY: every call below either takes a value or a pointer to data
        // this function owns for the call's duration.
        unsafe {
            let b = edgefirst_tensor_ffi::ef_tensor_builder_new();
            if b.is_null() {
                return Err(Error::NotImplemented(
                    "ef_tensor_builder_new: allocation failed".into(),
                ));
            }
            let dims: Vec<u64> = shape.iter().map(|&d| d as u64).collect();
            edgefirst_tensor_ffi::ef_tensor_builder_dtype(b, dtype.code());
            edgefirst_tensor_ffi::ef_tensor_builder_shape(b, dims.as_ptr(), dims.len() as u32);
            if let Some(mem) = memory {
                edgefirst_tensor_ffi::ef_tensor_builder_storage(b, mem.code());
            }
            let handle = edgefirst_tensor_ffi::ef_tensor_builder_alloc(b);
            let result = match NonNull::new(handle) {
                Some(h) => Ok(Self::from_handle(h)),
                None => Err(builder_error(
                    edgefirst_tensor_ffi::ef_tensor_builder_error(b),
                )),
            };
            edgefirst_tensor_ffi::ef_tensor_builder_free(b);
            result
        }
    }

    /// Import an existing buffer as a type-erased tensor, taking ownership
    /// of its file descriptor. No bytes are copied.
    ///
    /// Drives the builder's adopt path (`ef_tensor_builder_{new,dtype,shape,
    /// add_plane,wrap}`) -- `ef_tensor_builder_wrap` is exactly this
    /// primitive: it adopts the first plane's handle and dispatches to the
    /// static backend's own `TensorDyn::from_fd` internally (backend
    /// detection from the fd's filesystem magic included), inside
    /// `libedgefirst_tensor.so`.
    #[cfg(unix)]
    pub fn from_fd(
        fd: std::os::fd::OwnedFd,
        shape: &[usize],
        dtype: DType,
        _name: Option<&str>,
    ) -> Result<Self> {
        use std::os::fd::{FromRawFd, IntoRawFd};
        // SAFETY: every call below either takes a value or a pointer to data
        // this function owns for the call's duration; `raw_fd` is reclaimed
        // into an `OwnedFd` (and so closed) on every path that does not hand
        // it to `wrap`.
        unsafe {
            let b = edgefirst_tensor_ffi::ef_tensor_builder_new();
            if b.is_null() {
                return Err(Error::NotImplemented(
                    "ef_tensor_builder_new: allocation failed".into(),
                ));
            }
            let dims: Vec<u64> = shape.iter().map(|&d| d as u64).collect();
            edgefirst_tensor_ffi::ef_tensor_builder_dtype(b, dtype.code());
            edgefirst_tensor_ffi::ef_tensor_builder_shape(b, dims.as_ptr(), dims.len() as u32);
            let raw_fd = fd.into_raw_fd();
            edgefirst_tensor_ffi::ef_tensor_builder_add_plane(b, raw_fd as i64, 0, 0, 0, 0, 0);
            let handle = edgefirst_tensor_ffi::ef_tensor_builder_wrap(b);
            let result = match NonNull::new(handle) {
                Some(h) => Ok(Self::from_handle(h)),
                None => {
                    // `wrap` adopts the fd only on success, so it is still
                    // ours -- reclaim it so it is closed instead of leaked.
                    drop(std::os::fd::OwnedFd::from_raw_fd(raw_fd));
                    let errno = edgefirst_tensor_ffi::ef_tensor_builder_error(b);
                    Err(Error::NotImplemented(format!(
                        "ef_tensor_builder_wrap failed: errno {errno}"
                    )))
                }
            };
            edgefirst_tensor_ffi::ef_tensor_builder_free(b);
            result
        }
    }

    /// Return the tensor shape.
    pub fn shape(&self) -> &[usize] {
        &self.shape_cache
    }

    /// Reshape this tensor. Total element count must remain the same.
    ///
    /// No `ef_tensor_reshape` primitive exists yet -- `PRIMITIVE-INVENTORY.md`
    /// found no call site across any of the four `-capi` siblings that
    /// reaches this on `TensorDyn` under the dynamic backend, so adding one
    /// was out of this task's scope. Rather than silently updating only the
    /// local `shape_cache` (which `ef_tensor_shape` itself would then
    /// contradict for any other consumer of the same handle), this refuses
    /// with a clear error until a real primitive lands.
    pub fn reshape(&mut self, shape: &[usize]) -> Result<()> {
        self.reshape_impl(shape, false)
    }

    /// Set the logical shape to any shape whose bytes fit the allocation,
    /// without [`reshape`](Self::reshape)'s equal-count constraint --
    /// the pool-reuse primitive. Drives `ef_tensor_set_logical_shape`.
    ///
    /// Not a convenience over `reshape`: `TensorTrait::set_logical_shape`'s
    /// *default* body is `self.reshape(shape)`, which is precisely the bug
    /// task P2e fixed. Without a real implementation here the dynamic
    /// backend would inherit that default and apply the strict rule to a
    /// pool tensor, silently refusing the reconfigure the method exists for.
    pub fn set_logical_shape(&mut self, shape: &[usize]) -> Result<()> {
        self.reshape_impl(shape, true)
    }

    /// The shared body of [`reshape`](Self::reshape) and
    /// [`set_logical_shape`](Self::set_logical_shape) -- one place to
    /// marshal the dims and refresh the cache, so the two cannot drift into
    /// leaving different state behind.
    fn reshape_impl(&mut self, shape: &[usize], by_capacity: bool) -> Result<()> {
        let dims: Vec<u64> = shape.iter().map(|&d| d as u64).collect();
        // SAFETY: `self.handle` is live; `dims` is a live local for the call.
        let rc = unsafe {
            if by_capacity {
                edgefirst_tensor_ffi::ef_tensor_set_logical_shape(
                    self.handle.as_ptr(),
                    dims.as_ptr(),
                    dims.len() as u32,
                )
            } else {
                edgefirst_tensor_ffi::ef_tensor_reshape(
                    self.handle.as_ptr(),
                    dims.as_ptr(),
                    dims.len() as u32,
                )
            }
        };
        if rc != 0 {
            // The C side already prefixes its message with the operation
            // name, so this does not add a second one.
            let msg = ffi_last_error();
            // ERANGE is "this shape does not fit"; anything else is a
            // malformed argument. The static backend distinguishes further
            // and the ABI has no room for it, so several of its variants
            // collapse into these two. The message survives every one of
            // them, which is what a caller actually sees (`python-common`
            // renders `Display` into a `PyErr`), and nothing in this
            // workspace matches on the variants. Enumerated so the next
            // reader does not have to re-derive it:
            //
            //   static                              dynamic
            //   ShapeMismatch (count mismatch)      ShapeMismatch
            //   InsufficientCapacity {needed, cap}  ShapeMismatch (numbers
            //                                       do not cross the ABI)
            //   InvalidOperation ("cannot reshape   InvalidShape
            //     a multiplane tensor")
            //   InvalidSize(0) (empty shape)        InvalidShape -- the C
            //                                       entry rejects ndim == 0
            //                                       before the backend sees it
            return Err(if rc == libc::ERANGE {
                Error::ShapeMismatch(msg)
            } else {
                Error::InvalidShape(msg)
            });
        }
        // `shape()` serves the cached vector, not the handle, so it would
        // keep reporting the OLD geometry the moment after this succeeded.
        self.shape_cache = Self::query_shape(self.handle);
        // A PBO-backed handle keeps its geometry in ONE place now -- the
        // library's own `TensorStorage::Pbo` -- so there is no second copy
        // to sync. Before Stage B this had to mirror every shape change onto
        // a `PboTensor` stashed beside the handle.
        Ok(())
    }

    /// Return the tensor name.
    ///
    /// Always empty: no `ef_tensor_*` primitive carries a tensor's name
    /// across the ABI (confirmed in `PRIMITIVE-INVENTORY.md` and by task 7's
    /// investigation of this same gap).
    pub fn name(&self) -> String {
        String::new()
    }

    /// Return the memory allocation type, as the library reports it.
    ///
    /// No PBO special case: since Stage B a PBO-backed handle *is*
    /// `TensorStorage::Pbo` inside `libedgefirst_tensor.so`, so
    /// `ef_tensor_storage_kind` returns `TensorMemory::Pbo` on its own. The
    /// override this replaces existed because the handle underneath was
    /// ordinary host memory.
    pub fn memory(&self) -> TensorMemory {
        // SAFETY: `self.handle` is a live handle for as long as `self` exists.
        let code = unsafe { edgefirst_tensor_ffi::ef_tensor_storage_kind(self.handle.as_ptr()) };
        TensorMemory::from_code(code).unwrap_or(TensorMemory::Mem)
    }

    /// Clone the file descriptor backing this tensor, for any storage kind
    /// that has one.
    ///
    /// Drives `ef_tensor_clone_fd`. This used to read plane 0's native
    /// handle (`ef_tensor_plane_at`) and `dup` it directly, which needed no
    /// new primitive -- and was wrong for SHM. A plane's native handle is a
    /// dma-buf fd on Linux and an IOSurface id on Apple, and `-1` for every
    /// other backing, so deriving "clone this tensor's fd" from it refused
    /// SHM-backed tensors, which do have a real fd and which the static
    /// backend clones without complaint (`TensorStorage::Shm(t) =>
    /// t.clone_fd()`). Asking the library, which owns the storage and knows
    /// which kinds have an fd, is what the split is for -- the same rule
    /// every other method here follows.
    #[cfg(unix)]
    pub fn clone_fd(&self) -> Result<std::os::fd::OwnedFd> {
        use std::os::fd::FromRawFd;
        // SAFETY: `self.handle` is live for as long as `self` exists.
        let rc = unsafe { edgefirst_tensor_ffi::ef_tensor_clone_fd(self.handle.as_ptr()) };
        if rc < 0 {
            let msg = ffi_last_error();
            return Err(if -rc == libc::ENOTSUP {
                Error::NotImplemented(msg)
            } else {
                // `Error::other`, not `from_raw_os_error`: the latter
                // discarded `msg` on exactly the path where it is most
                // useful -- a `dup` that failed for a reason worth reading,
                // reduced to a bare errno. The errno is kept in the text.
                //
                // Variant note: the static backend returns `NixError` here
                // (it calls `nix::unistd::dup` directly), and this returns
                // `IoError`. The ABI carries an errno, not a Rust variant,
                // and no caller in this workspace matches on either -- both
                // render the same way through `Display`. Stated rather than
                // left for the next reader to re-derive.
                Error::IoError(std::io::Error::other(format!(
                    "clone_fd: {msg} (errno {})",
                    -rc
                )))
            });
        }
        // SAFETY: `ef_tensor_clone_fd` returned a freshly-`dup`'d fd whose
        // ownership it handed to this caller.
        Ok(unsafe { std::os::fd::OwnedFd::from_raw_fd(rc) })
    }

    /// Return the [`BufferIdentity`] of the underlying allocation.
    ///
    /// See [`from_handle`](Self::from_handle): derived once at construction
    /// from the handle's own address, because no `ef_tensor_*` primitive
    /// exposes a system-level identity key (a dma-buf `(st_dev, st_ino)`,
    /// say) to derive one from instead.
    pub fn buffer_identity(&self) -> &BufferIdentity {
        &self.identity
    }

    /// The shared core of [`map_bytes`](Self::map_bytes) and
    /// [`pin_host`](Self::pin_host): `ef_tensor_map` plus an
    /// `ef_tensor_retain`'d [`MapKeepalive`] so the resulting pin is
    /// genuinely `'static` (shares ownership through the keepalive, never a
    /// borrow of `self` -- same contract the static backend's `map_bytes`
    /// documents).
    ///
    /// `pub(crate)`, not `pub`: `dynamic_tensor.rs`'s `Tensor<T>::map_with`
    /// also calls this directly (to build a typed `HostView<T>` instead of
    /// the byte-level one [`map_bytes`](Self::map_bytes) returns), which is
    /// why this is not `pub(self)` -- it is shared plumbing within the
    /// crate, not a second public byte-mapping entry point.
    pub(crate) fn map_pin(&self, access: CpuAccess) -> Result<crate::pin::HostPin<'static>> {
        self.map_pin_with(access, false)
    }

    /// [`map_pin`](Self::map_pin), with the choice of `ef_tensor_map` or
    /// `ef_tensor_try_map`.
    ///
    /// One body rather than two: the retain that makes the pin `'static`
    /// and the unmap-on-retain-failure unwind are identical for both, and
    /// the ABI call is the only line that differs.
    pub(crate) fn map_pin_with(
        &self,
        access: CpuAccess,
        non_blocking: bool,
    ) -> Result<crate::pin::HostPin<'static>> {
        let code = match access {
            CpuAccess::None => {
                return Err(Error::InvalidArgument(
                    "map: CpuAccess::None is not a mappable direction".into(),
                ))
            }
            CpuAccess::Read => 1,
            CpuAccess::Write => 2,
            CpuAccess::ReadWrite => 3,
        };
        let mut view = edgefirst_tensor_ffi::EfTensorView {
            ptr: std::ptr::null_mut(),
            len: 0,
        };
        // SAFETY: `self.handle` is live; `view` is a valid local out-param.
        let rc = unsafe {
            if non_blocking {
                edgefirst_tensor_ffi::ef_tensor_try_map(self.handle.as_ptr(), code, &mut view)
            } else {
                edgefirst_tensor_ffi::ef_tensor_map(self.handle.as_ptr(), code, &mut view)
            }
        };
        if rc == libc::EAGAIN && non_blocking {
            // Not a failure: the GPU copy this map depends on is still in
            // flight and a retry makes progress. Rebuilt as the exact error
            // the static backend raises, so `try_map_with` means one thing
            // on both backends.
            return Err(Error::IoError(std::io::Error::new(
                std::io::ErrorKind::WouldBlock,
                ffi_last_error(),
            )));
        }
        if rc != 0 {
            let what = if non_blocking {
                "ef_tensor_try_map"
            } else {
                "ef_tensor_map"
            };
            return Err(Error::InvalidOperation(format!(
                "{what} failed: errno {rc}"
            )));
        }
        // Retain so the pin can genuinely outlive `self` -- released by
        // `MapKeepalive::drop`.
        // SAFETY: `self.handle` is live.
        let retain_rc = unsafe { edgefirst_tensor_ffi::ef_tensor_retain(self.handle.as_ptr()) };
        if retain_rc != 0 {
            // SAFETY: undoes the successful map above.
            unsafe { edgefirst_tensor_ffi::ef_tensor_unmap(self.handle.as_ptr()) };
            return Err(Error::NotImplemented(format!(
                "ef_tensor_retain failed: errno {retain_rc}"
            )));
        }
        let keepalive: std::sync::Arc<dyn Send + Sync> =
            std::sync::Arc::new(MapKeepalive(self.handle.as_ptr()));
        Ok(crate::pin::HostPin::new(keepalive, view.ptr, view.len))
    }

    /// Map this tensor's whole extent for CPU access, type-erased to raw
    /// bytes. Returns a `'static` view, same contract as the static
    /// backend's own `map_bytes`.
    pub fn map_bytes(&self, access: CpuAccess) -> Result<crate::view::HostView<'static, u8>> {
        let pin = self.map_pin(access)?;
        let len = pin.len();
        Ok(crate::view::HostView::new(pin, vec![len], None, access))
    }

    /// Non-blocking [`map_bytes`](Self::map_bytes), same contract as the
    /// static backend's own `try_map_bytes`.
    ///
    /// Drives `ef_tensor_try_map`, whose `EAGAIN` becomes
    /// `Error::IoError(WouldBlock)` -- the same error the static backend
    /// raises for the same reason, so a caller sees one contract on both.
    /// Only the Windows D3D11 texture can actually answer it; every other
    /// backing reaches the identical code `ef_tensor_map` does.
    pub fn try_map_bytes(&self, access: CpuAccess) -> Result<crate::view::HostView<'static, u8>> {
        let pin = self.map_pin_with(access, true)?;
        let len = pin.len();
        Ok(crate::view::HostView::new(pin, vec![len], None, access))
    }

    /// Pin a stable host address for this tensor's data. Returns a
    /// `'static` pin, same contract as the static backend's own `pin_host`.
    ///
    /// No dedicated `ef_tensor_pin_host` primitive exists; `ef_tensor_map`
    /// plus a retained reference (the same primitive `map_bytes` uses) is
    /// the only mapping operation the ABI exposes, so this shares
    /// [`map_pin`](Self::map_pin) rather than duplicating it.
    ///
    /// Which is why the PBO refusal has to be **repeated** here rather than
    /// forwarded. `Tensor::pin_host` (`lib.rs`) refuses `TensorStorage::Pbo`
    /// -- `glMapBufferRange`'s address is valid only until `glUnmapBuffer`,
    /// so a pin would have to hold the buffer mapped across GL work -- but
    /// `ef_tensor_map` is `map`, not `pin_host`, and the library cannot tell
    /// the two callers apart. Without this guard a PBO pinned on this
    /// backend and refused on the other, from the same call. The message is
    /// [`crate::pbo::PIN_HOST_PBO_REFUSAL`], the one both arms read, so they
    /// cannot drift. A real `ef_tensor_pin_host` entry point (Stage E) is
    /// what removes the duplication.
    ///
    /// The AHardwareBuffer arm, which the static backend refuses for the
    /// same reason, is deliberately **not** mirrored: Android reports it as
    /// `TensorMemory::DmaBuf`, indistinguishable here from a Linux DMA-BUF
    /// or an IOSurface, both of which pin. Guessing from the storage kind
    /// would refuse two backings that work.
    pub fn pin_host(&self, access: CpuAccess) -> Result<crate::pin::HostPin<'static>> {
        if self.memory() == TensorMemory::Pbo {
            return Err(Error::NotImplemented(
                crate::pbo::PIN_HOST_PBO_REFUSAL.to_owned(),
            ));
        }
        self.map_pin(access)
    }

    /// This tensor's plane-0 geometry (`ef_tensor_plane_at`, already
    /// exported), or `None` for an invalid handle or one with no planes.
    /// Shared by [`clone_fd`](Self::clone_fd), [`aliases`](Self::aliases),
    /// and [`effective_row_stride`](Self::effective_row_stride).
    ///
    /// `pub`, not `pub(crate)`: each `-capi` leaf's own transition vtable
    /// (`vtable.rs`, scheduled for removal once G4 closes -- see the
    /// single-tensor-home plan's task 10) mints tensors under its own
    /// private `EfTensorImpl` wrapper and needs exactly this to answer its
    /// own `ef_tensor_plane_at`-equivalent dispatch (the formatless-tensor
    /// fallback geometry, and the shareable native handle for any plane
    /// index -- every plane of one tensor shares plane 0's handle). Before
    /// task 9 switched the leaves onto this backend, those call sites used
    /// `TensorDyn::capacity_bytes()`/`dmabuf()`/`iosurface_id()`, which
    /// only exist on the `static` backend this crate no longer embeds in
    /// those libraries; delegating to the already-correct primitive here
    /// (rather than re-deriving capacity/native-handle logic on the
    /// consumer side) is the same rule task 15's report states for every
    /// other dynamic-backend method.
    pub fn plane0(&self) -> Option<edgefirst_tensor_ffi::EfTensorPlane> {
        let mut plane = edgefirst_tensor_ffi::EfTensorPlane::default();
        // SAFETY: `self.handle` is live; `plane` is a valid local out-param.
        let rc = unsafe {
            edgefirst_tensor_ffi::ef_tensor_plane_at(self.handle.as_ptr(), 0, &mut plane)
        };
        (rc == 0).then_some(plane)
    }

    /// Effective row stride: the padded byte pitch a stride-aware CPU
    /// reader must honor, sourced from plane 0's stride -- which is exactly
    /// what the static backend's own `effective_row_stride()` computes
    /// (`vtable.rs`'s `ef_tensor_plane_at` implementation reads that same
    /// value on the producing side).
    pub fn effective_row_stride(&self) -> Option<usize> {
        self.plane0().map(|p| p.stride as usize)
    }

    /// Image width in pixels (`None` if not an image tensor). Pure function
    /// of `shape()` + `format()`, mirroring `Tensor::width`.
    pub fn width(&self) -> Option<usize> {
        let (fmt, dims) = self.image_dims()?;
        match fmt.layout() {
            PixelLayout::Packed => dims.get(1).copied(),
            PixelLayout::Planar => dims.get(2).copied(),
            PixelLayout::SemiPlanar => dims.get(1).copied(),
        }
    }

    /// The format and the trailing shape dims that describe one image,
    /// allowing one leading batch `N`; `None` when unformatted or when the
    /// shape has any other rank. Mirrors `Tensor::image_dims`.
    fn image_dims(&self) -> Option<(PixelFormat, &[usize])> {
        let fmt = self.format()?;
        let shape = self.shape();
        let rank = match fmt.layout() {
            PixelLayout::SemiPlanar => 2,
            PixelLayout::Packed | PixelLayout::Planar => 3,
        };
        let batch_dims = shape.len().checked_sub(rank).filter(|&n| n <= 1)?;
        Some((fmt, &shape[batch_dims..]))
    }

    /// Image height in pixels (`None` if not an image tensor). Pure
    /// function of `shape()` + `format()`, mirroring `Tensor::height`.
    ///
    pub fn height(&self) -> Option<usize> {
        let (fmt, dims) = self.image_dims()?;
        match fmt.layout() {
            PixelLayout::Packed => dims.first().copied(),
            PixelLayout::Planar => dims.get(1).copied(),
            PixelLayout::SemiPlanar => {
                if self.is_multiplane() {
                    dims.first().copied()
                } else {
                    match fmt {
                        PixelFormat::Nv12 => dims.first().map(|h| h * 2 / 3),
                        PixelFormat::Nv16 => dims.first().map(|h| h / 2),
                        PixelFormat::Nv24 => dims.first().map(|h| h / 3),
                        _ => None,
                    }
                }
            }
        }
    }

    /// True if `self` and `other` reference the same underlying buffer.
    /// Same matching rules as the static backend's `aliases`: identity
    /// equality, then (Linux DMA tensors only) a same-fd-number compare
    /// via plane 0's native handle.
    pub fn aliases(&self, other: &Self) -> bool {
        if self.buffer_identity().id() == other.buffer_identity().id() {
            return true;
        }
        if self.memory() != other.memory() {
            return false;
        }
        if self.memory() == TensorMemory::DmaBuf {
            if let (Some(a), Some(b)) = (self.plane0(), other.plane0()) {
                if a.handle >= 0 && a.handle == b.handle {
                    return true;
                }
            }
        }
        false
    }

    // --- The three primitives `PRIMITIVE-INVENTORY.md` found genuinely new:
    // `colorimetry`, `set_colorimetry`, `view_origin`.

    /// Colorimetry metadata (`None` = undefined; never auto-filled).
    pub fn colorimetry(&self) -> Option<Colorimetry> {
        // SAFETY: `self.handle` is live.
        let packed = unsafe { edgefirst_tensor_ffi::ef_tensor_colorimetry(self.handle.as_ptr()) };
        if packed == 0 {
            None
        } else {
            Some(Colorimetry::unpack(packed))
        }
    }

    /// Attach/clear colorimetry metadata.
    pub fn set_colorimetry(&mut self, c: Option<Colorimetry>) {
        let packed = c.map(|c| c.pack()).unwrap_or(0);
        // SAFETY: `self.handle` is live and own-mint (every dynamic-backend
        // handle is minted by this same `libedgefirst_tensor.so`).
        unsafe { edgefirst_tensor_ffi::ef_tensor_set_colorimetry(self.handle.as_ptr(), packed) };
    }

    /// Builder-style [`Self::set_colorimetry`]. Same signature as the
    /// static backend's, so a shared call site needs no backend branch.
    pub fn with_colorimetry(mut self, c: Colorimetry) -> Self {
        self.set_colorimetry(Some(c));
        self
    }

    /// The parent-image snapshot if this tensor is a `view`/`batch`
    /// sub-region; `None` for a whole tensor. See [`ViewOrigin`].
    pub fn view_origin(&self) -> Option<ViewOrigin> {
        let mut out = edgefirst_tensor_ffi::EfViewOrigin::default();
        // SAFETY: `self.handle` is live; `out` is a valid local out-param.
        let rc =
            unsafe { edgefirst_tensor_ffi::ef_tensor_view_origin(self.handle.as_ptr(), &mut out) };
        if rc != 0 || out.has_origin == 0 {
            return None;
        }
        Some(ViewOrigin {
            parent_width: out.parent_width as usize,
            parent_height: out.parent_height as usize,
            parent_row_stride: out.parent_row_stride as usize,
            x: out.x as usize,
            y: out.y as usize,
        })
    }

    /// Return the runtime element type discriminant. Already-exported
    /// (`ef_tensor_dtype`); needed by `derived.rs`'s pure functions of
    /// `dtype()`/`shape()`/`format()`.
    pub fn dtype(&self) -> DType {
        // SAFETY: `self.handle` is live.
        let code = unsafe { edgefirst_tensor_ffi::ef_tensor_dtype(self.handle.as_ptr()) };
        DType::from_code(code).unwrap_or(DType::U8)
    }

    /// Return the pixel format (`None` if not an image tensor).
    /// Already-exported (`ef_tensor_format`).
    pub fn format(&self) -> Option<PixelFormat> {
        // SAFETY: `self.handle` is live; the returned pointer is borrowed
        // for as long as the handle lives, which outlives this call.
        let ptr = unsafe { edgefirst_tensor_ffi::ef_tensor_format(self.handle.as_ptr()) };
        if ptr.is_null() {
            return None;
        }
        // SAFETY: `ef_tensor_format` returns a NUL-terminated C string.
        let s = unsafe { std::ffi::CStr::from_ptr(ptr) }.to_str().ok()?;
        if s.is_empty() {
            None
        } else {
            PixelFormat::from_str_code(s)
        }
    }

    /// Allocate an image tensor with the given geometry, memory backing,
    /// and CPU access declaration -- dispatching on `dtype`, same as
    /// `static`'s `TensorDyn::image` (`static_backend.rs`). Drives
    /// `ef_tensor_image_alloc`, a thin wrapper the producer side
    /// (`tensor-capi`, always the `static` backend) resolves by calling the
    /// real `static::TensorDyn::image` -- the platform image geometry lives
    /// there, not here. Real callers under `dynamic`: `edgefirst-image`'s
    /// `cpu/mod.rs`.
    pub fn image(
        width: usize,
        height: usize,
        format: PixelFormat,
        dtype: DType,
        memory: Option<TensorMemory>,
        access: CpuAccess,
    ) -> Result<Self> {
        let c_format = format_cstring(format)?;
        let (has_memory, memory_code) = memory_code(memory);
        // SAFETY: `c_format` is a valid NUL-terminated string for the
        // call's duration.
        let handle = unsafe {
            edgefirst_tensor_ffi::ef_tensor_image_alloc(
                width,
                height,
                c_format.as_ptr(),
                dtype.code(),
                has_memory,
                memory_code,
                access_code(access),
            )
        };
        match NonNull::new(handle) {
            Some(h) => Ok(Self::from_handle(h)),
            // `NotImplemented` was a guess: an allocation that failed for
            // want of memory, or a format the platform declined, is not
            // "not implemented". `ffi_error` takes the producing side's own
            // class, and falls back to the old variant only when the
            // library recorded none.
            None => Err(ffi_error(Error::NotImplemented)),
        }
    }

    /// See [`Self::image`]: same primitive family, full-featured request
    /// form. Drives `ef_tensor_image_desc_alloc`, which resolves the
    /// request (including any compression negotiation) through the
    /// producer side's real `static::TensorDyn::image_desc`.
    pub fn image_desc(desc: &crate::ImageDesc) -> Result<Self> {
        let c_format = format_cstring(desc.format())?;
        // SAFETY: every call below either takes a value or a pointer to
        // data this function owns for the call's duration.
        unsafe {
            let d = edgefirst_tensor_ffi::ef_tensor_image_desc_new(
                desc.width(),
                desc.height(),
                c_format.as_ptr(),
                desc.dtype().code(),
            );
            if d.is_null() {
                return Err(Error::NotImplemented(
                    "ef_tensor_image_desc_new: allocation failed".into(),
                ));
            }
            if let Some(m) = desc.memory() {
                edgefirst_tensor_ffi::ef_tensor_image_desc_set_memory(d, m.code());
            }
            edgefirst_tensor_ffi::ef_tensor_image_desc_set_access(d, access_code(desc.access()));
            if let Some(c) = desc.compression() {
                let code = match c {
                    crate::Compression::Any => 1,
                    // `Compression::Scheme(_)` has no C setter (see
                    // `ef_tensor_image_desc_set_compression`'s own doc) --
                    // request the closest expressible thing, "any scheme",
                    // rather than silently dropping the request. A caller
                    // that specifically needs a named scheme has no ABI
                    // path to it today.
                    crate::Compression::Scheme(_) => 1,
                };
                edgefirst_tensor_ffi::ef_tensor_image_desc_set_compression(d, code);
            }
            let handle = edgefirst_tensor_ffi::ef_tensor_image_desc_alloc(d);
            let result = match NonNull::new(handle) {
                Some(h) => Ok(Self::from_handle(h)),
                None => Err(ffi_error(Error::NotImplemented)),
            };
            edgefirst_tensor_ffi::ef_tensor_image_desc_free(d);
            result
        }
    }

    /// See [`Self::image`]: same primitive family, externally-strided form.
    /// Drives `ef_tensor_image_with_stride_alloc`.
    pub fn image_with_stride(
        width: usize,
        height: usize,
        format: PixelFormat,
        dtype: DType,
        row_stride_bytes: usize,
        memory: Option<TensorMemory>,
        access: CpuAccess,
    ) -> Result<Self> {
        let c_format = format_cstring(format)?;
        let (has_memory, memory_code) = memory_code(memory);
        // SAFETY: `c_format` is a valid NUL-terminated string for the
        // call's duration.
        let handle = unsafe {
            edgefirst_tensor_ffi::ef_tensor_image_with_stride_alloc(
                width,
                height,
                c_format.as_ptr(),
                dtype.code(),
                row_stride_bytes,
                has_memory,
                memory_code,
                access_code(access),
            )
        };
        match NonNull::new(handle) {
            Some(h) => Ok(Self::from_handle(h)),
            None => Err(ffi_error(Error::NotImplemented)),
        }
    }

    /// Borrow a rectangular spatial sub-region as a zero-copy view sharing
    /// this tensor's allocation. Same signature as `static`'s
    /// `TensorDyn::view` (`static_backend.rs`), which dispatches to
    /// `Tensor<T>::view` (`lib.rs`) -- real production code calls it
    /// (`edgefirst-image`'s tiled multi-slot convert path,
    /// `tiling.rs::render_tile`, views a row-band out of a tall parent
    /// destination tensor).
    ///
    /// Drives `ef_tensor_view_region`, which is *not* a composition over
    /// `ef_tensor_builder_wrap`/`add_plane` (that path would mint a fresh
    /// identity by duplicating a plane's fd, breaking
    /// [`TensorTrait::view`]'s "must never mint a fresh identity" contract)
    /// -- it calls the producer side's real `static::TensorDyn::view`
    /// directly, which shares the parent's allocation and
    /// [`BufferIdentity`] the same way the static backend's own callers get.
    pub fn view(&self, region: Region) -> Result<TensorDyn> {
        // SAFETY: `self.handle` is a live handle for the call's duration.
        let handle = unsafe {
            edgefirst_tensor_ffi::ef_tensor_view_region(
                self.handle.as_ptr(),
                region.x as u64,
                region.y as u64,
                region.width as u64,
                region.height as u64,
            )
        };
        match NonNull::new(handle) {
            Some(h) => Ok(Self::from_handle(h)),
            None => {
                // Only claim "out of bounds" when the producing side says
                // that is what happened. This used to assert it for *every*
                // NULL -- including an unresolvable handle and a region a
                // format rejected for reasons other than fit -- and to
                // fabricate the `bounds` from `width()`/`height()`, which
                // for a non-image tensor are `None` and rendered as `(0,
                // 0)`. Same shape of confident falsehood `batch` had, found
                // by the P2c sweep rather than by a failing test.
                if ffi_last_error_class() == edgefirst_tensor_ffi::EfErrorClass::RegionOutOfBounds {
                    // Rebuilt with real numbers rather than through
                    // `ffi_error`: this caller has them (`region` is its own
                    // argument, and the frame comes from the tensor).
                    Err(Error::RegionOutOfBounds {
                        region,
                        bounds: (self.width().unwrap_or(0), self.height().unwrap_or(0)),
                    })
                } else {
                    Err(ffi_error(Error::InvalidShape))
                }
            }
        }
    }

    /// Attach pixel format metadata to this tensor, validating shape
    /// compatibility. Same contract as `static`'s `TensorDyn::set_format`
    /// (`static_backend.rs`). Drives `ef_tensor_set_format`, the live-handle
    /// mutator (as opposed to the pre-alloc `ef_tensor_builder_format`
    /// setter). Real caller: `edgefirst-image`'s `import_image` (`lib.rs`),
    /// which tags an already-imported DMA-BUF fd with its pixel format
    /// immediately after `TensorDyn::from_fd`.
    ///
    /// **Concurrency**: `ef_tensor_set_format` is narrower than
    /// `ef_tensor_set_colorimetry` -- not safe to call while any other
    /// `tensor-capi` call is in flight on the same underlying handle from
    /// another thread (see `mutate.rs`'s module docs in `tensor-capi`).
    /// `&mut self` here already gives this call exclusive access to *this*
    /// Rust value, which is what every real caller (`import_image`, once,
    /// right after construction) relies on.
    pub fn set_format(&mut self, format: PixelFormat) -> Result<()> {
        let c_format = format_cstring(format)?;
        // SAFETY: `self.handle` is a live handle; `c_format` is valid for
        // the call's duration.
        let rc = unsafe {
            edgefirst_tensor_ffi::ef_tensor_set_format(self.handle.as_ptr(), c_format.as_ptr())
        };
        if rc != 0 {
            return Err(Error::InvalidArgument(format!(
                "ef_tensor_set_format failed: {}",
                ffi_last_error()
            )));
        }
        Ok(())
    }

    /// Builder-style variant of [`Self::set_format`].
    pub fn with_format(mut self, format: PixelFormat) -> Result<Self> {
        self.set_format(format)?;
        Ok(self)
    }

    /// Set the row stride without format validation. Same contract as
    /// `static`'s `TensorDyn::set_row_stride`. Drives
    /// `ef_tensor_set_row_stride`. Real caller: `edgefirst-image`'s
    /// `import_image` (`lib.rs`), immediately after [`Self::with_format`].
    /// Same concurrency note as [`Self::set_format`].
    pub fn set_row_stride(&mut self, stride: usize) -> Result<()> {
        // SAFETY: `self.handle` is a live handle.
        let rc =
            unsafe { edgefirst_tensor_ffi::ef_tensor_set_row_stride(self.handle.as_ptr(), stride) };
        if rc != 0 {
            return Err(Error::InvalidArgument(format!(
                "ef_tensor_set_row_stride failed: {}",
                ffi_last_error()
            )));
        }
        Ok(())
    }

    /// Set the row stride in bytes without format validation. Same contract
    /// as `static`'s `TensorDyn::set_row_stride_unchecked`
    /// (`static_backend.rs`). Drives `ef_tensor_set_row_stride_unchecked`
    /// (task 17) -- unlike [`Self::set_row_stride`], needs no format on this
    /// tensor first, which is what makes it usable on a raw multiplane
    /// chroma plane (`from_planes` requires that plane to carry no format;
    /// see [`crate::Tensor::from_planes`]'s doc comment). Same concurrency
    /// note as [`Self::set_format`].
    pub fn set_row_stride_unchecked(&mut self, stride: usize) {
        // SAFETY: `self.handle` is a live handle.
        unsafe {
            edgefirst_tensor_ffi::ef_tensor_set_row_stride_unchecked(self.handle.as_ptr(), stride)
        };
    }

    /// Retag this tensor's element type, keeping its bytes untouched.
    ///
    /// Drives `ef_tensor_set_dtype`. Needed here and not on the static
    /// backend because of where the element type lives: `static`'s
    /// `TensorDyn` is an enum over eleven `Tensor<T>`, so the dtype **is**
    /// the Rust type and a layout-identical `transmute` changes it for free.
    /// This backend's `Tensor<T>` is `#[repr(transparent)]` over a handle
    /// that records its own dtype, so the same transmute changes a
    /// `PhantomData` and nothing else -- the handle keeps saying `U8`. See
    /// [`crate::TensorDyn::set_dtype`]'s static counterpart for the contract
    /// and why a width change is refused.
    pub fn set_dtype(&mut self, dtype: DType) -> Result<()> {
        if self.dtype() == dtype {
            return Ok(());
        }
        // SAFETY: `self.handle` is live and own-mint.
        let rc = unsafe {
            edgefirst_tensor_ffi::ef_tensor_set_dtype(self.handle.as_ptr(), dtype.code())
        };
        if rc == 0 {
            return Ok(());
        }
        Err(Error::InvalidArgument(format!(
            "ef_tensor_set_dtype failed: {} (errno {rc})",
            ffi_last_error()
        )))
    }

    /// Set the byte offset within the DMA-BUF where image data starts.
    /// Drives `ef_tensor_set_plane_offset`. Same caller as
    /// [`Self::set_row_stride`] (`import_image`'s `image_offset`
    /// parameter), same concurrency note as [`Self::set_format`].
    ///
    /// `static`'s signature returns `()`, not `Result` -- there is no
    /// channel to report a failure through, but with the real primitive in
    /// place there is also nothing left that can fail here short of a
    /// process-level handle corruption `ef_tensor_set_plane_offset` itself
    /// would only hit for a null/foreign handle, neither reachable through
    /// `&mut self` on an owned, already-validated `TensorDyn`.
    pub fn set_plane_offset(&mut self, offset: usize) {
        // SAFETY: `self.handle` is a live handle.
        unsafe { edgefirst_tensor_ffi::ef_tensor_set_plane_offset(self.handle.as_ptr(), offset) };
    }

    /// Byte offset within the DMA-BUF where image data starts (`None` = 0).
    /// Drives `ef_tensor_plane_offset` -- found missing while proving
    /// `set_plane_offset` above (task 15): the only other candidate,
    /// `plane0().offset` (`ef_tensor_plane_at`), is `plane_table`'s
    /// intra-buffer layout offset, always 0 for plane 0 by construction, a
    /// different quantity entirely from what this setter writes. Same
    /// contract as `static`'s `TensorDyn::plane_offset` (`static_backend.rs`).
    pub fn plane_offset(&self) -> Option<usize> {
        // SAFETY: `self.handle` is live.
        let raw = unsafe { edgefirst_tensor_ffi::ef_tensor_plane_offset(self.handle.as_ptr()) };
        (raw >= 0).then_some(raw as usize)
    }

    /// Set this tensor's logical dimensions and pixel format to a decoded
    /// image, reusing the existing allocation -- the pool-reuse primitive a
    /// JPEG decode-into-pool destination tensor needs before each decode.
    /// Same contract as `static`'s `TensorDyn::configure_image`
    /// (`static_backend.rs`). Drives `ef_tensor_configure_image`, whose
    /// producer-side implementation is the real `static::Tensor::configure_image`
    /// -- the pool-reuse stride-preservation and alignment rules live there,
    /// not here. Real caller: `edgefirst-codec`'s JPEG decode-into-pool path,
    /// via [`dynamic_tensor::Tensor::configure_image`](crate::Tensor::configure_image),
    /// which forwards straight to this. Same concurrency note as
    /// [`Self::set_format`].
    pub fn configure_image(
        &mut self,
        width: usize,
        height: usize,
        format: PixelFormat,
    ) -> Result<()> {
        let c_format = format_cstring(format)?;
        // SAFETY: `self.handle` is a live handle; `c_format` is valid for
        // the call's duration.
        let rc = unsafe {
            edgefirst_tensor_ffi::ef_tensor_configure_image(
                self.handle.as_ptr(),
                width,
                height,
                c_format.as_ptr(),
            )
        };
        if rc != 0 {
            return Err(Error::InvalidArgument(format!(
                "ef_tensor_configure_image failed: {}",
                ffi_last_error()
            )));
        }
        // `shape_cache` was captured once at construction and does not
        // track `inner`'s live shape the way the C side's own
        // `EfTensorImpl` caches do -- `configure_image` just changed it, so
        // it must be re-derived the same way `from_handle` derives it the
        // first time, or `Self::shape()`/`Self::width()`/`Self::height()`
        // would report the pre-reconfigure geometry forever after.
        self.shape_cache = Self::query_shape(self.handle);
        Ok(())
    }

    // --- Quantization: family 2's primitives. `Tensor<T>` (integer-gated
    // via `IntegerType`, `dynamic_tensor.rs`) forwards straight to these;
    // the type gating lives entirely at that layer, matching how
    // `static`'s own `TensorDyn::quantization`/etc. (`static_backend.rs`)
    // already fold every float variant to `None`/an error without a
    // separate type-erased gate of their own.

    /// Quantization metadata for this tensor (`None` for a tensor that
    /// carries none, *or* a float-dtype tensor). Drives the two-call
    /// `ef_tensor_quantization_info`/`ef_tensor_quantization_get` idiom,
    /// caching the result in [`Self::quantization_cache`] the first time
    /// this particular `TensorDyn` value reads it -- see that field's doc
    /// comment for why the cache is sound under concurrent access.
    pub fn quantization(&self) -> Option<&crate::Quantization> {
        self.quantization_cache
            .get_or_init(|| self.fetch_quantization())
            .as_ref()
    }

    /// The actual `ef_tensor_quantization_{info,get}` two-call fetch,
    /// isolated from [`Self::quantization`] so the `OnceLock::get_or_init`
    /// closure stays a one-line call. Reconstructs the exact `Quantization`
    /// mode (symmetric vs. not, per-tensor vs. per-channel) the producer
    /// attached, not merely a numerically-equivalent one -- the wire
    /// encoding always returns a full `zero_point` array (zero-filled for
    /// symmetric, see `ef_tensor_quantization_get`'s own doc comment), so
    /// this re-derives symmetry from an all-zero check rather than losing
    /// it.
    fn fetch_quantization(&self) -> Option<crate::Quantization> {
        let mut info = edgefirst_tensor_ffi::EfQuantizationInfo::default();
        // SAFETY: `self.handle` is live; `info` is a valid local out-param.
        let rc = unsafe {
            edgefirst_tensor_ffi::ef_tensor_quantization_info(self.handle.as_ptr(), &mut info)
        };
        if rc != 0 || info.has_quantization == 0 {
            return None;
        }
        let n = info.count as usize;
        let mut scales = vec![0f32; n];
        let mut zps = vec![0i32; n];
        // SAFETY: `self.handle` is live; `scales`/`zps` are sized to `n`,
        // the count `ef_tensor_quantization_info` just reported.
        let rc = unsafe {
            edgefirst_tensor_ffi::ef_tensor_quantization_get(
                self.handle.as_ptr(),
                scales.as_mut_ptr(),
                zps.as_mut_ptr(),
                n as u32,
            )
        };
        if rc != 0 {
            return None;
        }
        let symmetric = zps.iter().all(|&z| z == 0);
        if info.axis == -1 {
            Some(if symmetric {
                crate::Quantization::per_tensor_symmetric(scales[0])
            } else {
                crate::Quantization::per_tensor(scales[0], zps[0])
            })
        } else {
            let axis = info.axis as usize;
            let q = if symmetric {
                crate::Quantization::per_channel_symmetric(scales, axis)
            } else {
                crate::Quantization::per_channel(scales, zps, axis)
            };
            q.ok()
        }
    }

    /// Attach quantization metadata to this tensor. Drives
    /// `ef_tensor_quantization_set`, then refreshes
    /// [`Self::quantization_cache`] so a subsequent [`Self::quantization`]
    /// call on this same `TensorDyn` value observes it immediately rather
    /// than the value cached before this call (see that field's doc
    /// comment: `&mut self` here means no concurrent reader on *this*
    /// value can be mid-`get_or_init` while the field is replaced).
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if the underlying call fails -- including
    /// a float-dtype tensor, matching `static`'s own
    /// `QuantizationInvalid { field: "dtype_is_integer", .. }` refusal
    /// (folded here into the same generic errno-derived message every
    /// other setter in this file uses, not the structured variant).
    pub fn set_quantization(&mut self, q: crate::Quantization) -> Result<()> {
        let axis = q.axis().map(|a| a as i32).unwrap_or(-1);
        let scales = q.scale();
        let n = scales.len() as u32;
        let zps_owned = q.zero_point().map(|z| z.to_vec());
        let zps_ptr = zps_owned
            .as_ref()
            .map(|z| z.as_ptr())
            .unwrap_or(std::ptr::null());
        // SAFETY: `self.handle` is live; `scales` points to `n` elements;
        // `zps_ptr` is either null or points to `n` elements from the same
        // `Quantization`.
        let rc = unsafe {
            edgefirst_tensor_ffi::ef_tensor_quantization_set(
                self.handle.as_ptr(),
                axis,
                scales.as_ptr(),
                zps_ptr,
                n,
            )
        };
        if rc != 0 {
            return Err(Error::InvalidArgument(format!(
                "ef_tensor_quantization_set failed: {}",
                ffi_last_error()
            )));
        }
        self.quantization_cache = std::sync::OnceLock::new();
        let _ = self.quantization_cache.set(Some(q));
        Ok(())
    }

    /// Builder-style variant of [`Self::set_quantization`].
    pub fn with_quantization(mut self, q: crate::Quantization) -> Result<Self> {
        self.set_quantization(q)?;
        Ok(self)
    }

    /// Clear any quantization metadata on this tensor. Drives
    /// `ef_tensor_quantization_clear`, then resets
    /// [`Self::quantization_cache`] the same way [`Self::set_quantization`]
    /// does.
    pub fn clear_quantization(&mut self) {
        // SAFETY: `self.handle` is live.
        unsafe { edgefirst_tensor_ffi::ef_tensor_quantization_clear(self.handle.as_ptr()) };
        self.quantization_cache = std::sync::OnceLock::new();
        let _ = self.quantization_cache.set(None);
    }

    // --- The `edgefirst-python-common` surface.
    //
    // `crates/python-common/src/tensor.rs` is the first consumer to call
    // `TensorDyn` at the Rust level under `dynamic` -- every earlier one
    // reached it through the `ef_tensor_*` C ABI instead -- so this block
    // is the set of methods it needs that the `-capi` leaves never did.
    // Some are pure derivations over primitives that already existed; the
    // ones that are not name the `ef_tensor_*` entry they drive and why no
    // existing primitive could answer. See `.superpowers/sdd/
    // 2026-08-25-python-single-tensor-home/task-P2a-report.md`.

    /// Total logical size of this tensor in bytes.
    ///
    /// Derived, with no `ef_tensor_*` entry of its own:
    /// [`crate::TensorTrait::size`] is defined as `len() * size_of::<T>()`
    /// and `len()` as `shape().iter().product()`, both of which this
    /// backend can already answer exactly -- `DType::size()` is
    /// `size_of::<T>()` for every one of the eleven element types.
    ///
    /// Logical, **not** the allocation: a pitch-aligned or pool-sized
    /// tensor's allocation is larger. [`Self::capacity_bytes`] is that one.
    pub fn size(&self) -> usize {
        self.shape().iter().product::<usize>() * self.dtype().size()
    }

    /// Bytes of the underlying allocation, which is `>=` [`Self::size`].
    ///
    /// Drives `ef_tensor_capacity_bytes`. Not derivable from
    /// `ef_tensor_plane_at`: for a *formatted* tensor that reports per-plane
    /// geometry computed from the format's plane table, whose sum is the
    /// logical image size rather than the allocation's -- the two differ for
    /// exactly the pool-sized and pitch-padded tensors that make the
    /// distinction matter.
    pub fn capacity_bytes(&self) -> usize {
        // SAFETY: `self.handle` is live for as long as `self` exists.
        let n = unsafe { edgefirst_tensor_ffi::ef_tensor_capacity_bytes(self.handle.as_ptr()) };
        // `-1` is the entry point's invalid-handle sentinel. Falling back to
        // the logical size matches `TensorTrait::capacity_bytes`'s own
        // default ("the logical size for storages without spare capacity")
        // rather than inventing a zero.
        usize::try_from(n).unwrap_or_else(|_| self.size())
    }

    /// The *recorded* row stride in bytes; `None` when the tensor is
    /// tightly packed.
    ///
    /// Drives `ef_tensor_row_stride`, and is deliberately **not**
    /// [`Self::effective_row_stride`]: that one reports plane 0's pitch,
    /// which falls back to a pitch computed from the format and width when
    /// nothing is recorded. The difference is load-bearing for
    /// [`Self::descriptor_pinned`] -- the cross-package protocol carries
    /// `None` for a tight tensor and lets the consumer recompute, and
    /// baking a computed pitch in instead would turn "no stride recorded"
    /// into "this exact stride is required" across a package boundary.
    pub fn row_stride(&self) -> Option<usize> {
        // SAFETY: `self.handle` is live for as long as `self` exists.
        let n = unsafe { edgefirst_tensor_ffi::ef_tensor_row_stride(self.handle.as_ptr()) };
        usize::try_from(n).ok()
    }

    /// The vendor tile-compression scheme recorded at allocation; `None`
    /// for a linear layout.
    ///
    /// Drives `ef_tensor_compression`. The scheme is chosen by the
    /// allocator inside `libedgefirst_tensor.so` (today only an Android
    /// AHardwareBuffer allocation ever resolves to one), so it is a fact
    /// only that library holds -- `ef_tensor_image_desc_get`'s own
    /// `compression` field is the *request* a caller made, which is a
    /// different question and routinely disagrees with the answer.
    /// An unrecognised code is reported as `None` and **logged**, not
    /// silently passed off as a linear layout. `Option<CompressionScheme>`
    /// has no variant for "some scheme this build cannot name", so `None`
    /// is the only value available -- but a consumer acting on it will
    /// treat a tile-compressed buffer as linear, and a compressed tensor
    /// has no meaningful linear row stride (see [`crate::Tensor::
    /// compression`]). The one way a code lands here unrecognised is a
    /// `libedgefirst_tensor.so` newer than this build; the loader's own
    /// undefined-symbol failure catches deployment skew that *adds a
    /// symbol*, and says nothing about skew that adds a *value* returned
    /// through an existing one. The log line is what makes that case
    /// visible instead of silent -- there is no ABI-version negotiation to
    /// refuse it first (`ef_tensor_abi_version` is defined and declared but
    /// nothing in the tree compares it to anything).
    pub fn compression(&self) -> Option<crate::CompressionScheme> {
        // SAFETY: `self.handle` is live for as long as `self` exists.
        let code = unsafe { edgefirst_tensor_ffi::ef_tensor_compression(self.handle.as_ptr()) };
        // 0 is the wire code for "linear", a real answer rather than an
        // unrecognised one, so it must not warn -- it is what almost every
        // allocation on almost every platform reports.
        let scheme = crate::CompressionScheme::from_code(code);
        if scheme.is_none() && code != 0 {
            log::warn!(
                "ef_tensor_compression returned scheme code {code}, which this build of \
                 edgefirst-tensor does not recognise; reporting a linear layout. The \
                 loaded libedgefirst_tensor.so is newer than this consumer."
            );
        }
        scheme
    }

    /// Acquire the buffer for CPU access -- the standalone cache-maintenance
    /// bracket. See [`crate::Tensor::sync_for_cpu`].
    ///
    /// Drives `ef_tensor_sync_for_cpu`. Not derivable here: the maintenance
    /// is per-backing (a dma-buf ioctl, an IOSurface lock, a no-op for
    /// coherent host memory, an honest refusal for a PBO), and this backend
    /// holds none of that state -- it holds a handle. Re-deriving the
    /// dma-buf arm locally from [`Self::clone_fd`] would work on Linux and
    /// be silently wrong everywhere else, which is exactly the shape of
    /// answer this backend must not invent.
    pub fn sync_for_cpu(&self, access: CpuAccess) -> Result<()> {
        self.sync(access, true)
    }

    /// Release the buffer back to the device. See
    /// [`crate::Tensor::sync_for_device`].
    ///
    /// Drives `ef_tensor_sync_for_device`; `access` must match the one that
    /// opened the bracket. See [`Self::sync_for_cpu`].
    pub fn sync_for_device(&self, access: CpuAccess) -> Result<()> {
        self.sync(access, false)
    }

    /// Shared body of the two sync brackets -- one place to translate the
    /// access code and the errno, so the two ends cannot drift into
    /// accepting or reporting different things.
    fn sync(&self, access: CpuAccess, to_cpu: bool) -> Result<()> {
        let what = if to_cpu {
            "sync_for_cpu"
        } else {
            "sync_for_device"
        };
        // No PBO guard: the library refuses a PBO's sync bracket itself
        // (`TensorStorage::Pbo` in `Tensor::sync_for_cpu`/`_for_device`),
        // and its message -- which names "PBO" -- travels back through
        // `ffi_last_error` as a `NotImplemented`, the same error kind the
        // static backend raises.
        let code = match access {
            CpuAccess::None => {
                return Err(Error::InvalidArgument(format!(
                    "{what}: CpuAccess::None is not a sync direction"
                )))
            }
            CpuAccess::Read => 1,
            CpuAccess::Write => 2,
            CpuAccess::ReadWrite => 3,
        };
        // SAFETY: `self.handle` is live for as long as `self` exists.
        let rc = unsafe {
            if to_cpu {
                edgefirst_tensor_ffi::ef_tensor_sync_for_cpu(self.handle.as_ptr(), code)
            } else {
                edgefirst_tensor_ffi::ef_tensor_sync_for_device(self.handle.as_ptr(), code)
            }
        };
        if rc == 0 {
            return Ok(());
        }
        // `ENOTSUP` is the C surface's translation of the
        // backing-has-no-independent-coherency-window refusal
        // (AHardwareBuffer on Android). Preserving it as `NotImplemented`
        // keeps the static backend's own error *kind* for the same
        // condition, so a caller matching on it behaves identically on both
        // backends.
        let msg = ffi_last_error();
        if rc == libc::ENOTSUP {
            return Err(Error::NotImplemented(msg));
        }
        Err(Error::InvalidOperation(format!(
            "{what}: {msg} (errno {rc})"
        )))
    }

    /// Borrow batch element `n` of a batched tensor (leading `N` dimension)
    /// as a zero-copy view sharing this tensor's allocation. See
    /// [`crate::Tensor::batch`].
    ///
    /// Drives `ef_tensor_batch`, which is a genuinely distinct primitive
    /// from `ef_tensor_view_region`: that one crops a spatial rectangle
    /// *within* one image and cannot express dropping the leading
    /// dimension. Like `view`, it calls the producer side's real
    /// `static::TensorDyn::batch`, so the result shares the parent's
    /// allocation instead of minting a fresh one.
    pub fn batch(&self, n: usize) -> Result<TensorDyn> {
        // SAFETY: `self.handle` is a live handle for the call's duration.
        let handle =
            unsafe { edgefirst_tensor_ffi::ef_tensor_batch(self.handle.as_ptr(), n as u64) };
        match NonNull::new(handle) {
            Some(h) => Ok(Self::from_handle(h)),
            None => {
                // Read the class before anything else on this thread can
                // overwrite it -- same lifetime rule as the message.
                let is_index = ffi_last_error_class()
                    == edgefirst_tensor_ffi::EfErrorClass::BatchIndexOutOfBounds;
                Err(batch_error(n, self.shape().first().copied(), is_index))
            }
        }
    }

    /// Clone the DMA-BUF file descriptor backing this tensor (Linux only).
    ///
    /// Derived, with no `ef_tensor_*` entry of its own: the same
    /// memory-kind check the static backend performs, then
    /// [`Self::clone_fd`], which already `dup`s plane 0's native fd.
    ///
    /// # Errors
    ///
    /// * [`Error::NotImplemented`] if the tensor is not DMA-backed
    /// * [`Error::IoError`] if the `dup` syscall fails
    #[cfg(target_os = "linux")]
    pub fn dmabuf_clone(&self) -> Result<std::os::fd::OwnedFd> {
        if self.memory() != TensorMemory::DmaBuf {
            return Err(Error::NotImplemented(format!(
                "dmabuf_clone requires DMA-backed tensor, got {:?}",
                self.memory()
            )));
        }
        self.clone_fd()
    }

    /// Borrow the raw `IOSurfaceRef` backing this handle (macOS/iOS).
    ///
    /// Drives `ef_tensor_iosurface_ref`. `None` when the producing library
    /// has no IOSurface (wrong backing, or not Apple).
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    pub fn iosurface_ref(&self) -> Option<*mut std::ffi::c_void> {
        // SAFETY: `self.handle` is live for as long as `self` exists.
        let p = unsafe { edgefirst_tensor_ffi::ef_tensor_iosurface_ref(self.handle.as_ptr()) };
        if p.is_null() {
            None
        } else {
            Some(p)
        }
    }

    /// Physical IOSurface dimensions in texels, independent of logical shape.
    ///
    /// There is no `ef_tensor_iosurface_physical_dims` primitive (unlike the
    /// AHardwareBuffer counterpart), so this reads `IOSurfaceGetWidth` /
    /// `IOSurfaceGetHeight` on the borrowed ref. `None` when
    /// [`Self::iosurface_ref`] is `None`.
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    pub fn iosurface_physical_dims(&self) -> Option<(usize, usize)> {
        let surface = self.iosurface_ref()?;
        // SAFETY: `surface` is a live IOSurfaceRef owned by the producing
        // library for at least as long as `self` (the handle) exists.
        unsafe { Some((IOSurfaceGetWidth(surface), IOSurfaceGetHeight(surface))) }
    }

    /// The borrowed `ID3D11Texture2D*` backing this tensor (Windows only).
    /// `None` when the tensor is not texture-backed.
    ///
    /// Drives `ef_tensor_d3d11_texture`. Same contract as the static
    /// backend's own `TensorDyn::d3d11_texture`: the pointer is valid while
    /// the tensor lives and carries no reference of its own.
    #[cfg(target_os = "windows")]
    pub fn d3d11_texture(&self) -> Option<*mut std::ffi::c_void> {
        // SAFETY: `self.handle` is live for as long as `self` exists.
        let p = unsafe { edgefirst_tensor_ffi::ef_tensor_d3d11_texture(self.handle.as_ptr()) };
        (!p.is_null()).then_some(p)
    }

    /// The texture geometry the HAL chose for this image (Windows only).
    /// `None` when the tensor is not texture-backed.
    ///
    /// Drives `ef_tensor_d3d11_layout`, whose `ef_d3d11_layout` is the wire
    /// form of the same five fields `D3d11ImageLayout` carries -- widened
    /// back to `usize` here, since the ABI struct pins them at `uint32_t`.
    #[cfg(target_os = "windows")]
    pub fn d3d11_layout(&self) -> Option<crate::d3d11_layout::D3d11ImageLayout> {
        let mut out = edgefirst_tensor_ffi::EfD3d11Layout::default();
        // SAFETY: `self.handle` is live; `out` is a valid local out-param.
        let rc =
            unsafe { edgefirst_tensor_ffi::ef_tensor_d3d11_layout(self.handle.as_ptr(), &mut out) };
        (rc == 0).then_some(crate::d3d11_layout::D3d11ImageLayout {
            dxgi_format: out.dxgi_format,
            texture_width: out.texture_width as usize,
            texture_height: out.texture_height as usize,
            bytes_per_texel: out.bytes_per_texel as usize,
            gl_internal_format: out.gl_internal_format,
        })
    }

    /// A duplicated NT handle the caller owns (Windows only).
    ///
    /// Drives `ef_tensor_d3d11_shared_handle`, which is documented to
    /// transfer ownership of the duplicate -- so wrapping it in an
    /// `OwnedHandle` is what closes it, exactly once, when this value is
    /// dropped.
    #[cfg(target_os = "windows")]
    pub fn d3d11_shared_handle(&self) -> Result<std::os::windows::io::OwnedHandle> {
        use std::os::windows::io::FromRawHandle;
        // SAFETY: `self.handle` is live for as long as `self` exists.
        let h =
            unsafe { edgefirst_tensor_ffi::ef_tensor_d3d11_shared_handle(self.handle.as_ptr()) };
        if h.is_null() {
            return Err(ffi_error(Error::NotImplemented));
        }
        // SAFETY: the export transferred ownership of a live NT handle.
        Ok(unsafe { std::os::windows::io::OwnedHandle::from_raw_handle(h) })
    }

    /// The fence handle plus value a GPU consumer waits on before reading
    /// this texture (Windows only), or `None` when no GPU write has been
    /// recorded.
    ///
    /// Drives `ef_tensor_gpu_completion`, which writes `NULL`/0 before doing
    /// anything else -- so a returned `NULL` fence with rc 0 is genuinely
    /// "nothing recorded", not a stale local. The fence handle it hands back
    /// is an owned duplicate, wrapped here for the same reason
    /// [`d3d11_shared_handle`](Self::d3d11_shared_handle) wraps its own.
    #[cfg(target_os = "windows")]
    pub fn gpu_completion(&self) -> Result<Option<crate::d3d11::GpuCompletion>> {
        use std::os::windows::io::FromRawHandle;
        let mut fence = std::ptr::null_mut();
        let mut value = 0u64;
        // SAFETY: `self.handle` is live; both out-params are valid locals.
        let rc = unsafe {
            edgefirst_tensor_ffi::ef_tensor_gpu_completion(
                self.handle.as_ptr(),
                &mut fence,
                &mut value,
            )
        };
        if rc != 0 {
            return Err(ffi_error(Error::NotImplemented));
        }
        if fence.is_null() {
            return Ok(None);
        }
        // SAFETY: the export transferred ownership of a live NT handle.
        let fence = unsafe { std::os::windows::io::OwnedHandle::from_raw_handle(fence) };
        Ok(Some(crate::d3d11::GpuCompletion { fence, value }))
    }

    /// The fence value of the newest GPU write recorded on this tensor, or 0
    /// when there is none; every platform, 0 off Windows. See
    /// [`Tensor::gpu_write_value`](crate::Tensor::gpu_write_value).
    ///
    /// Drives `ef_tensor_gpu_write_value`, declared on every platform. Only a
    /// texture can carry a recorded write, so any other backing is answered
    /// here: the export would cost an FFI round trip and leave a refusal in
    /// the thread-local last error that no caller of this reads.
    pub fn gpu_write_value(&self) -> u64 {
        if self.memory() != TensorMemory::DmaBuf {
            return 0;
        }
        // SAFETY: `self.handle` is live for as long as `self` exists.
        unsafe { edgefirst_tensor_ffi::ef_tensor_gpu_write_value(self.handle.as_ptr()) }
    }

    /// Record that GPU work writing this texture completes at `value` of the
    /// process device's fence (Windows only).
    ///
    /// Drives `ef_tensor_set_gpu_write`. Takes `&self`, matching the static
    /// backend: the export records a monotonic maximum into an atomic and
    /// needs no exclusive access, so a producer can record a write on a
    /// tensor its consumers are reading.
    #[cfg(target_os = "windows")]
    pub fn set_gpu_write(&self, value: u64) -> Result<()> {
        // SAFETY: `self.handle` is live; the export records a monotonic
        // maximum into an atomic, so a shared borrow is all it needs.
        let rc =
            unsafe { edgefirst_tensor_ffi::ef_tensor_set_gpu_write(self.handle.as_ptr(), value) };
        if rc != 0 {
            return Err(ffi_error(Error::NotImplemented));
        }
        Ok(())
    }

    /// The registration lives in the library after Stage C. This lens cannot
    /// borrow that `CudaHandle`, so the getter is always `None` even after
    /// [`Self::set_cuda_handle`]; use [`Self::is_cuda_attached`] or
    /// [`Self::cuda_map`].
    #[deprecated(
        since = "0.32.0",
        note = "On the dynamic backend use is_cuda_attached() or cuda_map() — the CudaHandle is not borrowable through this lens."
    )]
    pub fn cuda(&self) -> Option<&crate::cuda::CudaHandle> {
        None
    }

    /// Whether the library tensor carries a CUDA registration.
    pub fn is_cuda_attached(&self) -> bool {
        // SAFETY: `self.handle` is live.
        unsafe { edgefirst_tensor_ffi::ef_tensor_cuda_attached(self.handle.as_ptr()) != 0 }
    }

    /// Attach a GL-buffer CUDA registration on the library tensor.
    pub fn set_cuda_handle(&mut self, h: crate::cuda::CudaHandle) {
        match h.into_client_parts() {
            Ok(parts) => {
                // SAFETY: `parts` keeps the channel alive for the retain
                // `ef_tensor_cuda_attach` takes; the function pointers match
                // `CudaHandle::into_client_parts`.
                let rc = unsafe {
                    edgefirst_tensor_ffi::ef_tensor_cuda_attach(
                        self.handle.as_ptr(),
                        parts.state,
                        parts.resource,
                        parts.size,
                        Some(parts.map_fn),
                        Some(parts.unmap_fn),
                        Some(parts.unregister_fn),
                    )
                };
                if rc != 0 {
                    log::debug!("ef_tensor_cuda_attach failed: {rc}");
                }
            }
            Err(e) => log::debug!("set_cuda_handle: {e}"),
        }
    }

    /// The C library's mapping of this tensor. `mk` is `ef_tensor_cuda_map`
    /// or `ef_tensor_cuda_map_mut`; both return an opaque map that retains
    /// the tensor and is released by `ef_tensor_cuda_unmap`.
    fn ffi_cuda_map(
        &self,
        mk: unsafe extern "C" fn(*const EfTensor) -> *mut std::ffi::c_void,
    ) -> Option<crate::cuda::CudaMap<'_>> {
        // SAFETY: `self.handle` is this tensor's live C handle.
        let map = unsafe { mk(self.handle.as_ptr()) };
        if map.is_null() {
            return None;
        }
        // SAFETY: `map` is the live, non-NULL map `mk` just returned, with no
        // other owner, so the guard may release it exactly once.
        unsafe { crate::cuda::CudaMap::from_ffi(map) }
    }

    /// Fast-fail CUDA map through the library (`ef_tensor_cuda_map`).
    pub fn cuda_map(&self) -> Option<crate::cuda::CudaMap<'_>> {
        self.ffi_cuda_map(edgefirst_tensor_ffi::ef_tensor_cuda_map)
    }

    /// Writable counterpart of [`cuda_map`](Self::cuda_map).
    pub fn cuda_map_mut(&self) -> Option<crate::cuda::CudaMap<'_>> {
        self.ffi_cuda_map(edgefirst_tensor_ffi::ef_tensor_cuda_map_mut)
    }

    /// GL buffer ID for this PBO; `None` when the tensor is not PBO-backed.
    ///
    /// Drives `ef_tensor_pbo_id`. Before Stage B this read a `PboTensor`
    /// stashed on this struct; the buffer now lives in the library, which is
    /// the only place that can answer.
    pub fn pbo_id(&self) -> Option<u32> {
        let mut id: u32 = 0;
        // SAFETY: `self.handle` is live; `id` is a valid out-param.
        let rc = unsafe { edgefirst_tensor_ffi::ef_tensor_pbo_id(self.handle.as_ptr(), &mut id) };
        (rc == 0).then_some(id)
    }

    /// Whether this PBO holds (or is establishing) a CPU mapping; `None`
    /// when the tensor is not PBO-backed.
    ///
    /// Drives `ef_tensor_pbo_is_mapped`, whose answer is three-valued: `1`
    /// mapped, `0` not, negative "not a PBO".
    pub fn pbo_is_mapped(&self) -> Option<bool> {
        // SAFETY: `self.handle` is live for the call.
        let rc = unsafe { edgefirst_tensor_ffi::ef_tensor_pbo_is_mapped(self.handle.as_ptr()) };
        match rc {
            0 => Some(false),
            1 => Some(true),
            _ => None,
        }
    }

    /// The C-ABI `PboOpsVtable` address for this PBO, for cross-cdylib
    /// export via [`crate::TensorDesc::ptr`]; `None` when not PBO-backed.
    ///
    /// Drives `ef_tensor_pbo_vtable`. The address is the library's, borrowed
    /// for as long as this handle lives -- which is exactly what
    /// [`Self::pbo_keepalive`] holds.
    pub fn pbo_vtable_ptr(&self) -> Option<*const std::ffi::c_void> {
        // SAFETY: `self.handle` is live for the call.
        let p = unsafe { edgefirst_tensor_ffi::ef_tensor_pbo_vtable(self.handle.as_ptr()) };
        (!p.is_null()).then_some(p)
    }

    /// A keepalive holding [`Self::pbo_vtable_ptr`]'s address valid: a
    /// retained reference on this tensor's own handle, which owns the
    /// library-side `PboTensor` the vtable belongs to.
    ///
    /// `None` when the tensor is not PBO-backed, or when the retain fails.
    /// Under `static` this is an `Arc<PboHandle>`; here it is a handle
    /// reference, which is the same guarantee expressed in this backend's
    /// own currency.
    pub fn pbo_keepalive(&self) -> Option<std::sync::Arc<dyn Send + Sync>> {
        self.pbo_id()?;
        // SAFETY: `self.handle` is live for the call.
        let rc = unsafe { edgefirst_tensor_ffi::ef_tensor_retain(self.handle.as_ptr()) };
        if rc != 0 {
            return None;
        }
        Some(std::sync::Arc::new(HandleKeepalive(self.handle.as_ptr())))
    }

    /// Wrap a producer's host pointer as a type-erased tensor without
    /// copying, aliasing rather than owning it -- the consumer half of the
    /// capsule protocol's [`crate::protocol::kind::HOST`].
    ///
    /// Drives `ef_tensor_wrap_host`. Not expressible over the builder the
    /// way [`Self::from_fd`] is: `ef_tensor_builder_add_plane` takes a
    /// *native handle* (an fd or surface id), and a host address is neither
    /// -- there was no primitive that could hand `libedgefirst_tensor.so` a
    /// raw pointer to alias.
    ///
    /// # Safety
    ///
    /// Same as the static backend's `from_raw_host_with_capacity`: `ptr`
    /// must be non-null, aligned to `dtype`, and valid for
    /// `max(capacity_bytes, shape.product() * dtype.size())` bytes for as
    /// long as the returned tensor -- and every view/map sharing its
    /// backing -- is used. Nothing here extends that lifetime.
    pub unsafe fn from_raw_host_with_capacity(
        ptr: *mut u8,
        shape: &[usize],
        capacity_bytes: usize,
        dtype: DType,
        _name: Option<&str>,
    ) -> Result<Self> {
        let dims: Vec<u64> = shape.iter().map(|&d| d as u64).collect();
        // SAFETY: the caller upholds `ptr`'s validity (this function's own
        // contract); `dims` is a live local for the call's duration.
        let handle = unsafe {
            edgefirst_tensor_ffi::ef_tensor_wrap_host(
                ptr,
                capacity_bytes,
                dtype.code(),
                dims.as_ptr(),
                dims.len() as u32,
            )
        };
        match NonNull::new(handle) {
            Some(h) => Ok(Self::from_handle(h)),
            None => Err(Error::InvalidArgument(format!(
                "ef_tensor_wrap_host failed: {}",
                ffi_last_error()
            ))),
        }
    }

    /// Wrap a live `IOSurfaceRef` (macOS/iOS). Looks up the surface's
    /// `IOSurfaceID` and drives [`Self::from_iosurface_id`]: the C ABI
    /// does not take a raw ref, so the id is the portable handle.
    ///
    /// # Safety
    ///
    /// `surface_ref` must be a valid live `IOSurfaceRef`. `shape` must
    /// match the IOSurface's pixel dimensions and chosen element type.
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    pub unsafe fn from_iosurface(
        surface_ref: *mut std::ffi::c_void,
        shape: &[usize],
        dtype: DType,
        name: Option<&str>,
    ) -> Result<Self> {
        if surface_ref.is_null() {
            return Err(Error::InvalidArgument(
                "from_iosurface: surface_ref is null".into(),
            ));
        }
        // SAFETY: caller guarantees `surface_ref` is a live IOSurfaceRef.
        let id = unsafe { IOSurfaceGetID(surface_ref) };
        Self::from_iosurface_id(id, shape, dtype, name)
    }

    /// IOSurfaceID for cross-process sharing. `None` when this handle has
    /// no IOSurface (wrong backing, or `IOSurfaceGetID` returned 0).
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    pub fn iosurface_id(&self) -> Option<u32> {
        let surface = self.iosurface_ref()?;
        let id = unsafe { IOSurfaceGetID(surface) };
        if id == 0 {
            None
        } else {
            Some(id)
        }
    }

    /// Wrap a live IOSurface named by its cross-process `IOSurfaceID`
    /// (macOS/iOS only) -- the consumer half of the capsule protocol's
    /// [`crate::protocol::kind::IOSURFACE`].
    ///
    /// Drives `ef_tensor_from_iosurface_id`. The lookup, the liveness
    /// check, and the retain all happen inside `libedgefirst_tensor.so`:
    /// `IOSurfaceRef` is a CoreFoundation object with its own refcount
    /// discipline, and splitting "look it up" from "retain it" across an
    /// ABI boundary would put a window between them in which the surface
    /// can be freed. Passing the *id* rather than the ref is what closes
    /// that window.
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    pub fn from_iosurface_id(
        id: u32,
        shape: &[usize],
        dtype: DType,
        _name: Option<&str>,
    ) -> Result<Self> {
        let dims: Vec<u64> = shape.iter().map(|&d| d as u64).collect();
        // SAFETY: `dims` is a live local for the call's duration.
        let handle = unsafe {
            edgefirst_tensor_ffi::ef_tensor_from_iosurface_id(
                id,
                dtype.code(),
                dims.as_ptr(),
                dims.len() as u32,
            )
        };
        match NonNull::new(handle) {
            Some(h) => Ok(Self::from_handle(h)),
            None => Err(Error::InvalidArgument(format!(
                "ef_tensor_from_iosurface_id failed: {}",
                ffi_last_error()
            ))),
        }
    }

    /// Wrap an existing `ID3D11Texture2D` as a type-erased tensor (Windows
    /// only). See
    /// [`Tensor::from_d3d11_texture`](crate::Tensor::from_d3d11_texture).
    ///
    /// Drives `ef_tensor_from_d3d11_texture`. Same signature as the static
    /// backend's, so a caller compiles against either; the C constructor
    /// takes the tensor's *shape* rather than `width`/`height`, so those are
    /// turned into the allocation shape here and validated back against the
    /// texture description on the far side.
    ///
    /// # Safety
    ///
    /// `texture` must be null or a live `ID3D11Texture2D` created on the HAL
    /// device ([`crate::d3d11::device()`]).
    #[cfg(target_os = "windows")]
    #[allow(clippy::too_many_arguments)] // one image description, spelled out
    pub unsafe fn from_d3d11_texture(
        texture: *mut std::ffi::c_void,
        width: usize,
        height: usize,
        format: PixelFormat,
        dtype: DType,
        access: CpuAccess,
        name: Option<&str>,
    ) -> Result<Self> {
        let dims = allocation_dims(format, width, height, "from_d3d11_texture")?;
        let format = format_cstring(format)?;
        let name = name_cstring(name)?;
        // SAFETY: the caller guarantees `texture`; `dims`, `format` and
        // `name` are live locals for the call's duration.
        let handle = unsafe {
            edgefirst_tensor_ffi::ef_tensor_from_d3d11_texture(
                texture,
                dtype.code(),
                dims.as_ptr(),
                dims.len() as u32,
                format.as_ptr(),
                access_code(access),
                name.as_ref().map_or(std::ptr::null(), |n| n.as_ptr()),
            )
        };
        match NonNull::new(handle) {
            Some(h) => Ok(Self::from_handle(h)),
            None => Err(ffi_error(Error::InvalidArgument)),
        }
    }

    /// Open a shared texture by its NT handle as a type-erased tensor
    /// (Windows only). See
    /// [`Tensor::from_d3d11_shared_handle`](crate::Tensor::from_d3d11_shared_handle).
    ///
    /// Drives `ef_tensor_from_d3d11_shared_handle`, with the same
    /// dimensions-to-shape conversion
    /// [`from_d3d11_texture`](Self::from_d3d11_texture) documents. Both
    /// handles stay the caller's: the export duplicates what it keeps.
    ///
    /// # Safety
    ///
    /// `handle` must be an NT shared handle of a D3D11 texture, valid in
    /// this process, and `completion`'s handle a shared fence handle.
    #[cfg(target_os = "windows")]
    #[allow(clippy::too_many_arguments)] // one image description, spelled out
    pub unsafe fn from_d3d11_shared_handle(
        handle: std::os::windows::io::RawHandle,
        width: usize,
        height: usize,
        format: PixelFormat,
        dtype: DType,
        access: CpuAccess,
        completion: Option<(std::os::windows::io::RawHandle, u64)>,
        name: Option<&str>,
    ) -> Result<Self> {
        let dims = allocation_dims(format, width, height, "from_d3d11_shared_handle")?;
        let format = format_cstring(format)?;
        let name = name_cstring(name)?;
        let (fence, fence_value) = completion.unwrap_or((std::ptr::null_mut(), 0));
        // SAFETY: the caller guarantees both handles; `dims`, `format` and
        // `name` are live locals for the call's duration.
        let tensor = unsafe {
            edgefirst_tensor_ffi::ef_tensor_from_d3d11_shared_handle(
                handle,
                dtype.code(),
                dims.as_ptr(),
                dims.len() as u32,
                format.as_ptr(),
                access_code(access),
                fence,
                fence_value,
                name.as_ref().map_or(std::ptr::null(), |n| n.as_ptr()),
            )
        };
        match NonNull::new(tensor) {
            Some(h) => Ok(Self::from_handle(h)),
            None => Err(ffi_error(Error::InvalidArgument)),
        }
    }

    /// See the static backend's `TensorDyn::from_client_pbo`.
    ///
    /// Drives `ef_tensor_wrap_pbo`: the library owns the `PboTensor`, this
    /// side owns only the handle.
    ///
    /// # Safety
    /// `state`, `map_fn` and `unmap_fn` must satisfy
    /// [`crate::client_state_pbo_ops`]'s contract.
    pub unsafe fn from_client_pbo(
        state: crate::EfClientState,
        map_fn: crate::EfPboMapFn,
        unmap_fn: crate::EfPboUnmapFn,
        buffer_id: u32,
        size: usize,
        shape: &[usize],
        dtype: DType,
    ) -> Result<TensorDyn> {
        let dims: Vec<u64> = shape.iter().map(|d| *d as u64).collect();
        // SAFETY: `dims` is a live local for the call; the state and op
        // pointers carry this function's own contract into the library.
        let handle = unsafe {
            edgefirst_tensor_ffi::ef_tensor_wrap_pbo(
                state,
                buffer_id,
                size,
                dtype.code(),
                dims.as_ptr(),
                dims.len() as u32,
                Some(map_fn),
                Some(unmap_fn),
            )
        };
        match NonNull::new(handle) {
            Some(h) => Ok(Self::from_handle(h)),
            // `ffi_error`, not a hand-rolled variant: the library just
            // recorded a class through `set_last_error_classified`, and
            // throwing it away would make `dynamic` report
            // `InvalidOperation` where `static` reports `InvalidArgument`
            // for the very same malformed channel. `InvalidArgument` is the
            // fallback the neighbouring `from_d3d11_*` constructors use, and
            // it is only reached for an `Unspecified` class -- every
            // classified failure keeps the class the library recorded.
            None => Err(ffi_error(Error::InvalidArgument)),
        }
    }

    /// The per-kind construction switch [`TensorDyn::import_descriptor`]
    /// (`derived.rs`) drives, once the descriptor has been validated and
    /// its `dtype`/`shape` decoded.
    ///
    /// Backend-specific because it is the one part of the import that names
    /// *constructors*; everything around it (validation, and the
    /// format/stride/colorimetry restore afterward) is shared. See
    /// `derived.rs` for the whole function's contract.
    pub(crate) fn import_storage(
        desc: &crate::TensorDesc,
        shape: &[usize],
        dtype: DType,
    ) -> Result<Self> {
        match desc.kind {
            #[cfg(target_os = "linux")]
            crate::protocol::kind::DMABUF => {
                let fd = crate::protocol::dup_descriptor_fd(desc)?;
                Self::from_fd(fd, shape, dtype, None)
            }
            #[cfg(not(target_os = "linux"))]
            crate::protocol::kind::DMABUF => {
                Err(Error::NotImplemented("dma-buf import off Linux".into()))
            }
            #[cfg(any(target_os = "macos", target_os = "ios"))]
            crate::protocol::kind::IOSURFACE => {
                let id = crate::protocol::descriptor_surface_id(desc)?;
                Self::from_iosurface_id(id, shape, dtype, None)
            }
            #[cfg(not(any(target_os = "macos", target_os = "ios")))]
            crate::protocol::kind::IOSURFACE => Err(Error::NotImplemented(
                "IOSurface import off Apple platforms".into(),
            )),
            crate::protocol::kind::HOST => {
                crate::protocol::check_descriptor_host_ptr(desc)?;
                // SAFETY: the caller guarantees the producer's keepalive
                // outlives the returned tensor -- that is the capsule
                // contract `import_descriptor` documents. `desc.capacity`
                // comes from the same trusted producer as `ptr`/`shape`.
                unsafe {
                    Self::from_raw_host_with_capacity(
                        desc.ptr.0,
                        shape,
                        desc.capacity as usize,
                        dtype,
                        None,
                    )
                }
            }
            crate::protocol::kind::PBO => {
                let buffer_id = crate::protocol::descriptor_pbo_buffer_id(desc)?;
                // SAFETY: `desc.ptr` carries a `PboOpsVtable` address under
                // `kind::PBO`, held live for this call by the producer's
                // capsule keepalive.
                let parts = unsafe { crate::read_pbo_vtable_parts(desc.ptr.0 as *const _) }?;
                // SAFETY: the parts came from a table this crate built.
                unsafe {
                    Self::from_client_pbo(
                        parts.state,
                        parts.map_fn,
                        parts.unmap_fn,
                        buffer_id,
                        desc.capacity as usize,
                        shape,
                        dtype,
                    )
                }
            }
            #[cfg(target_os = "windows")]
            crate::protocol::kind::D3D11_TEXTURE => {
                let (tex, completion) = crate::protocol::descriptor_d3d11_handles(desc)?;
                // SAFETY: the caller guarantees the producer's keepalive
                // outlives the returned tensor -- the capsule contract
                // `import_descriptor` documents -- so both handles are the
                // producer's own and live for this call. `ReadWrite` is the
                // widest access an import can ask for; the descriptor
                // carries no access of its own.
                unsafe {
                    let (format, width, height) =
                        crate::protocol::descriptor_d3d11_geometry(desc, tex, shape)?;
                    Self::from_d3d11_shared_handle(
                        tex,
                        width,
                        height,
                        format,
                        dtype,
                        CpuAccess::ReadWrite,
                        completion,
                        None,
                    )
                }
            }
            #[cfg(not(target_os = "windows"))]
            crate::protocol::kind::D3D11_TEXTURE => Err(Error::NotImplemented(
                "D3D11 texture import off Windows".into(),
            )),
            k => Err(Error::NotImplemented(format!(
                "tensor interop kind {k} cannot be imported by this build"
            ))),
        }
    }

    /// Descriptor for the cross-package tensor protocol; see
    /// [`crate::protocol`]'s module docs.
    pub fn descriptor(&self) -> crate::TensorDesc {
        self.descriptor_pinned(None)
    }

    /// Descriptor carrying a pinned host address. See the static backend's
    /// `TensorDyn::descriptor_pinned` for the contract -- this is the same
    /// function over the same [`crate::protocol::from_parts`], which is
    /// compiled into both backends precisely so the two cannot describe the
    /// same tensor differently.
    ///
    /// The one input fetched differently here is `handle`: the static
    /// backend branches on the platform to pick `dmabuf()`'s fd or
    /// `iosurface_id()`, whereas this reads plane 0's `handle` --
    /// `ef_tensor_plane_at`'s own `native_handle` (`tensor-capi`'s
    /// `vtable.rs`) already makes exactly that platform choice on the
    /// producing side, so re-deriving it here would be a second copy of the
    /// same decision, free to drift.
    pub fn descriptor_pinned(&self, pin: Option<&crate::HostPin<'_>>) -> crate::TensorDesc {
        let memory = self.memory();
        let handle: i64 = match memory {
            // A PBO's "native handle" is its GL buffer id, which only
            // `ef_tensor_pbo_id` can answer -- plane 0 would report `-1`
            // here, since a GL buffer name is not a value
            // `ef_tensor_plane_at`'s `native_handle` carries.
            TensorMemory::Pbo => self.pbo_id().map(|id| id as i64).unwrap_or(-1),
            // A D3D11 texture's plane 0 reports `-1`: an NT handle is not a
            // value `ef_tensor_plane_at` carries. The handle comes from
            // `ef_tensor_d3d11_shared_handle`, and this tensor keeps it --
            // see `descriptor_texture_handle`.
            #[cfg(target_os = "windows")]
            TensorMemory::DmaBuf => self.descriptor_texture_handle_value(),
            _ => self.plane0().map(|p| p.handle).unwrap_or(-1),
        };
        // The fence is the process device's, shared with the library that
        // owns this handle through the rendezvous, so its handle value is
        // borrowed rather than duplicated -- the device outlives the
        // descriptor, and a copy whose own fence is private exports no handle
        // at all rather than pairing two timelines. Only the value comes from
        // the library, through `ef_tensor_gpu_write_value`, which duplicates
        // no fence handle for a number the descriptor only forwards.
        #[cfg(target_os = "windows")]
        let (fence_handle, sync) = match memory {
            TensorMemory::DmaBuf => (
                crate::d3d11::device()
                    .map(|d| d.exported_fence_handle_value())
                    .unwrap_or(0),
                Some(self.gpu_write_value()).filter(|v| *v != 0),
            ),
            _ => (0, None),
        };
        #[cfg(not(target_os = "windows"))]
        let (fence_handle, sync) = (0, None);
        crate::protocol::from_parts(crate::protocol::DescParts {
            dims: self.shape(),
            memory,
            dtype: self.dtype(),
            fourcc: self.format().map(|f| f.to_fourcc()).unwrap_or(0),
            format: self.format(),
            row_stride: self.row_stride(),
            handle,
            colorimetry: self.colorimetry().map(|c| c.pack()).unwrap_or(0),
            capacity: self.capacity_bytes() as u64,
            pin,
            pbo_vtable_ptr: self.pbo_vtable_ptr(),
            fence_handle,
            sync,
        })
    }

    /// The value of the texture handle this tensor keeps for its
    /// descriptors, duplicating it on first use; `-1` when this tensor has
    /// no D3D11 texture behind it.
    #[cfg(target_os = "windows")]
    fn descriptor_texture_handle_value(&self) -> i64 {
        use std::os::windows::io::AsRawHandle;
        self.descriptor_texture_handle
            .get_or_init(|| self.d3d11_shared_handle().ok())
            .as_ref()
            .map(|h| h.as_raw_handle() as usize as i64)
            .unwrap_or(-1)
    }
}

/// Turn `ef_tensor_batch`'s `NULL` into the error [`crate::Tensor::batch`]
/// would have returned.
///
/// `ef_tensor_batch` returns `NULL` for four distinct conditions -- an
/// unresolvable handle, an `n` not representable as `usize` on the
/// producing side, an out-of-range index, and `Tensor::batch`'s "this
/// tensor is not batched" shape refusal. Collapsing them into
/// [`Error::BatchIndexOutOfBounds`] produced a statement that was not
/// merely unhelpful but **false**: `.batch(0)` on an ordinary NV12 image
/// reported "batch index 0 out of bounds for batch size 720", pointing the
/// reader at the one argument they got right.
///
/// The first fix for that reconstructed the variant by matching a fragment
/// of `BatchIndexOutOfBounds`'s own `Display` in the message -- an ABI
/// programmed against a `Display` string, tolerable only because it
/// degraded to a truth. `ef_tensor_last_error_class` (task P2c) is the
/// structured signal it wanted, and the string matching is gone.
///
/// The out-of-bounds case is rebuilt with its real numbers rather than
/// taking `ffi_error`'s generic mapping, because this caller has them: `n`
/// is its own argument and the leading dimension is on the cached shape.
/// Every other class falls through to [`ffi_error`], carrying the
/// producing side's own message.
fn batch_error(n: usize, leading: Option<usize>, class_is_index: bool) -> Error {
    match leading {
        Some(batch) if class_is_index => Error::BatchIndexOutOfBounds { index: n, batch },
        // `InvalidShape` is the fallback because it is what `Tensor::batch`
        // (`lib.rs`) itself returns for both of its shape refusals, which
        // are the failures an older library would report unclassified.
        _ => ffi_error(Error::InvalidShape),
    }
}

/// Turn a builder's sticky errno into the typed [`Error`] the static
/// backend would have returned.
///
/// Driven by the **builder's own errno**, not by the thread-local error
/// class P2c added. That is deliberate: `ef_tensor_builder_error(b)` is set
/// by this call on this builder, so it cannot be stale, whereas the
/// thread-local is only as fresh as the last path that wrote it -- and
/// `terminal`'s early returns (a null builder, a sticky error from an
/// earlier call) write no message at all. The errno is the sound channel
/// here; [`ffi_last_error`] supplies advisory text on top of it.
///
/// Before this, every refusal came back as
/// `NotImplemented("ef_tensor_builder_alloc failed: errno 12")` -- ENOMEM
/// for everything, with the real reason discarded on the producing side.
/// A caller could not tell "try a smaller allocation" from "this build has
/// no such backing", and `tests/vocabulary.rs`'s
/// `a_defined_but_unbacked_code_errors_instead_of_panicking` failed under
/// `dynamic` for exactly that reason -- which is why that file was excluded
/// by name from the dynamic test lane.
fn builder_error(errno: std::ffi::c_int) -> Error {
    let msg = ffi_last_error();
    // Mirrors `errno_for` (`tensor-capi/src/map.rs`) in reverse; that
    // function is the single place the forward mapping lives, so the two
    // are read together rather than each inventing a table.
    match errno {
        libc::ENOTSUP => Error::NotImplemented(msg),
        libc::ENOMEM => Error::IoError(std::io::Error::from_raw_os_error(libc::ENOMEM)),
        libc::ERANGE => Error::ShapeMismatch(msg),
        libc::EACCES => Error::InvalidOperation(msg),
        libc::EIO => Error::IoError(std::io::Error::other(msg)),
        libc::EINVAL => Error::InvalidArgument(msg),
        other => Error::InvalidArgument(format!("{msg} (errno {other})")),
    }
}

/// Derive a [`BufferIdentity`] from an fd's `(st_dev, st_ino)`. See
/// [`TensorDyn::derive_identity`]'s doc comment for why this is the correct
/// key for a DMA-BUF handle. Mirrors `dma.rs::identity_from_stat` exactly
/// (that one is `static`-backend-private and `target_os = "linux"`-gated;
/// this one only needs `unix`, since it works from a bare fd via `nix`
/// rather than any Linux-specific DMA-BUF API).
// See `dma.rs::identity_from_stat`'s own `#[allow]` for why this cast is
// needed on exactly one platform per field and both are needed to compile
// on both.
#[cfg(unix)]
#[allow(clippy::unnecessary_cast)]
fn identity_from_stat(stat: &nix::sys::stat::FileStat) -> BufferIdentity {
    let key = ((stat.st_dev as u64) << 32) ^ (stat.st_ino as u64);
    BufferIdentity::derived(IdentityKind::DmaBuf, key)
}

/// `NUL`-terminate a [`PixelFormat`]'s wire string for a C call.
///
/// # Errors
///
/// [`Error::InvalidArgument`] in the (unreachable in practice) case that a
/// format's wire string somehow contains a NUL byte -- `PixelFormat::as_str`
/// always returns a static ASCII string, but the fallible `CString::new`
/// path is kept explicit rather than `.unwrap()`-ed, matching this crate's
/// standing rule against silently swallowing an error class just because
/// it looks unreachable today.
fn format_cstring(format: PixelFormat) -> Result<std::ffi::CString> {
    std::ffi::CString::new(format.as_str())
        .map_err(|e| Error::InvalidArgument(format!("pixel format string contains a NUL: {e}")))
}

/// `NUL`-terminate an optional debug name for a C call.
///
/// Unlike [`format_cstring`]'s input, this string comes from the caller and
/// really can contain a NUL, so the refusal is a reachable path rather than
/// a defensive one. `None` stays `None`, which is the ABI's own "no name"
/// spelling.
#[cfg(target_os = "windows")]
fn name_cstring(name: Option<&str>) -> Result<Option<std::ffi::CString>> {
    name.map(std::ffi::CString::new)
        .transpose()
        .map_err(|e| Error::InvalidArgument(format!("name contains a NUL: {e}")))
}

/// `width`x`height` as the `uint64_t[]` shape a D3D11 constructor takes.
///
/// The C constructors are given the tensor's shape, not its pixel
/// dimensions, so that `ef_tensor_shape` reports back exactly what was
/// passed in and the far side can check it against the texture. The static
/// backend's constructors take `width`/`height` and derive the same shape
/// internally, so converting here is what keeps the two signatures
/// identical.
///
/// # Errors
///
/// [`Error::InvalidArgument`] for a `width`/`height` the format has no
/// allocation shape for (a zero dimension, or an odd one for a subsampled
/// format).
#[cfg(target_os = "windows")]
fn allocation_dims(
    format: PixelFormat,
    width: usize,
    height: usize,
    what: &str,
) -> Result<Vec<u64>> {
    format
        .allocation_shape(width, height)
        .map(|s| s.iter().map(|&d| d as u64).collect())
        .ok_or_else(|| {
            Error::InvalidArgument(format!(
                "{what}: invalid dimensions {width}x{height} for format {format:?}"
            ))
        })
}

/// Encode `Option<TensorMemory>` as the `(has_memory, memory)` pair every
/// `ef_tensor_image_*` constructor takes -- 0/0 for "auto-select", matching
/// `ef_tensor_image_desc_view`'s own `has_memory` convention rather than a
/// sentinel code (every `ef_storage_kind` value 0..=5 is real).
fn memory_code(memory: Option<TensorMemory>) -> (std::ffi::c_int, u32) {
    match memory {
        Some(m) => (1, m.code()),
        None => (0, 0),
    }
}

/// Encode [`CpuAccess`] as the `ef_cpu_access` wire code, `None` included
/// (0) -- unlike [`TensorDyn::map_pin`]'s access decode, which rejects 0 as
/// "not a mappable direction", image allocation legitimately wants
/// `CpuAccess::None` (e.g. a GPU-only render target).
fn access_code(access: CpuAccess) -> u32 {
    match access {
        CpuAccess::None => 0,
        CpuAccess::Read => 1,
        CpuAccess::Write => 2,
        CpuAccess::ReadWrite => 3,
    }
}

/// Read the calling thread's most recent `tensor-capi` failure detail, for
/// enriching the `Error` this backend returns on a constructor/mutator
/// failure -- see `ef_tensor_last_error_message`'s own doc comment for the
/// "advisory, `dlerror`-style, valid until this thread's next call"
/// contract. Never `""`-checked by the caller: an empty string is a
/// perfectly fine (if uninformative) suffix to a message.
pub(crate) fn ffi_last_error() -> String {
    // SAFETY: `ef_tensor_last_error_message` always returns a valid,
    // NUL-terminated string (possibly empty), read immediately and copied
    // out before any further `tensor-capi` call on this thread.
    unsafe {
        let ptr = edgefirst_tensor_ffi::ef_tensor_last_error_message();
        if ptr.is_null() {
            return String::new();
        }
        std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned()
    }
}

/// Read the calling thread's most recent `tensor-capi` failure **class**,
/// beside [`ffi_last_error`]'s message.
///
/// The entry points that report failure by returning `NULL` carry no errno,
/// so this is the only structured signal available for them. Unlike the
/// message -- whose contract is "never parse this" -- this is meant to be
/// programmed against.
fn ffi_last_error_class() -> edgefirst_tensor_ffi::EfErrorClass {
    use edgefirst_tensor_ffi::EfErrorClass as C;
    // SAFETY: a plain thread-local read on the producing side; no pointers.
    let code = unsafe { edgefirst_tensor_ffi::ef_tensor_last_error_class() };
    match code {
        1 => C::InvalidArgument,
        2 => C::InvalidShape,
        3 => C::InsufficientCapacity,
        4 => C::BatchIndexOutOfBounds,
        5 => C::RegionOutOfBounds,
        6 => C::NotSupported,
        7 => C::InvalidOperation,
        8 => C::AllocationFailed,
        9 => C::QuantizationInvalid,
        // 0, and anything a newer library added that this build does not
        // know: "no class recorded", which is exactly how an unclassified
        // failure already reads. Never a guess at the nearest neighbour.
        _ => C::Unspecified,
    }
}

/// Rebuild a typed [`Error`] from the class and message the last failing
/// `ef_tensor_*` call recorded.
///
/// This replaces the string matching `TensorDyn::batch` used to do. That
/// coupling was tolerable only because it degraded to a truth rather than a
/// falsehood, but it was still an ABI programmed against a `Display`
/// fragment; `ef_tensor_last_error_class` is the structured signal it
/// wanted and did not have.
///
/// The message is always the producing side's own, whatever the class. An
/// `Unspecified` class -- an older library, or a failure path that recorded
/// only a message -- yields `fallback`, so this degrades exactly the way
/// the string match did: to a less specific truth, never to a confident
/// wrong answer.
///
/// Variants carrying structured fields (`RegionOutOfBounds`,
/// `BatchIndexOutOfBounds`, `InsufficientCapacity`) are not rebuilt here:
/// their numbers do not cross the boundary. The two callers that can supply
/// them from their own arguments do so themselves; everyone else gets a
/// message-carrying variant of the right *kind*, which is what a consumer
/// reads.
pub(crate) fn ffi_error(fallback: fn(String) -> Error) -> Error {
    use edgefirst_tensor_ffi::EfErrorClass as C;
    let msg = ffi_last_error();
    match ffi_last_error_class() {
        C::InvalidArgument => Error::InvalidArgument(msg),
        C::InvalidShape => Error::InvalidShape(msg),
        C::InsufficientCapacity | C::BatchIndexOutOfBounds | C::RegionOutOfBounds => {
            Error::ShapeMismatch(msg)
        }
        C::NotSupported => Error::NotImplemented(msg),
        C::InvalidOperation => Error::InvalidOperation(msg),
        C::AllocationFailed => Error::IoError(std::io::Error::other(msg)),
        C::QuantizationInvalid => Error::InvalidArgument(msg),
        C::Unspecified => fallback(msg),
    }
}

/// Holds one `ef_tensor_retain` on a handle for a keepalive's lifetime, so
/// an address borrowed out of that handle (a `PboOpsVtable`, today) stays
/// valid independently of the `TensorDyn` it came from.
struct HandleKeepalive(*mut EfTensor);

// SAFETY: an `ef_tensor` handle is refcounted and documented as safe to
// cross threads (`ef_tensor_retain`); this holds one reference and does
// nothing else with the pointer.
unsafe impl Send for HandleKeepalive {}
unsafe impl Sync for HandleKeepalive {}

impl Drop for HandleKeepalive {
    fn drop(&mut self) {
        // SAFETY: releases exactly the reference `pbo_keepalive` took.
        unsafe { edgefirst_tensor_ffi::ef_tensor_free(self.0) }
    }
}

/// The keepalive behind [`TensorDyn::map_bytes`]'s pin. Holds its own
/// `ef_tensor_retain`'d reference (independent of the `TensorDyn` that
/// created it, matching the static backend's "genuinely `'static`" pin
/// contract) and releases it on `Drop`, after unmapping.
struct MapKeepalive(*mut EfTensor);

// SAFETY: the referenced handle is `libedgefirst_tensor`'s own C ABI object,
// designed to cross threads; ownership is tracked by refcount
// (`ef_tensor_retain`/`ef_tensor_free`), not by Rust's aliasing rules.
unsafe impl Send for MapKeepalive {}
unsafe impl Sync for MapKeepalive {}

impl Drop for MapKeepalive {
    fn drop(&mut self) {
        // SAFETY: `self.0` was retained in `map_bytes` and is released here,
        // symmetrically -- unmap first (the sync bracket), then the retained
        // reference.
        unsafe {
            edgefirst_tensor_ffi::ef_tensor_unmap(self.0);
            edgefirst_tensor_ffi::ef_tensor_free(self.0);
        }
    }
}

/// Lighter than the static backend's. `static_backend.rs`'s `Debug` prints
/// every field of the boxed `Tensor<T>` (`storage`, `format`, `chroma`,
/// `row_stride`, `quantization`, `colorimetry`, the CUDA handle, ...); this
/// one prints only `dtype` and `shape`, because those are the only two facts
/// `libedgefirst_tensor.so` exposes a *reader* for today (`ef_tensor_dtype`,
/// `ef_tensor_shape`/`ef_tensor_ndim`). Byte parity with the static backend
/// is not reachable without a new `ef_tensor_*` getter -- `quantization` in
/// particular has only a pre-alloc builder setter, no runtime reader -- so
/// matching it is a future primitive, not an impl choice made here. Safe to
/// reduce fidelity like this because nothing in the codebase parses or
/// compares `TensorDyn`'s `Debug` output; it exists only so
/// `detect::ProtoData`'s `#[derive(Debug)]` (unconditionally compiled, real
/// cross-backend surface `decoder` constructs) has something to call.
impl fmt::Debug for TensorDyn {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TensorDyn")
            .field("dtype", &self.dtype())
            .field("shape", &self.shape())
            .finish()
    }
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "IOSurface", kind = "framework")]
extern "C" {
    fn IOSurfaceGetWidth(surface: *mut std::ffi::c_void) -> usize;
    fn IOSurfaceGetHeight(surface: *mut std::ffi::c_void) -> usize;
    fn IOSurfaceGetID(surface: *mut std::ffi::c_void) -> u32;
}