cubecl-runtime 0.11.0

The runtime API of CubeCL: clients, devices, handles and everything a kernel launch needs.
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
use super::{CaptureStatus, DeviceCaptures, Handle};
use crate::kernel::BufferIOAttr;
use crate::{
    client::Client,
    compiler::CompilationError,
    config::{CubeClRuntimeConfig, RuntimeConfig, compilation::BoundsCheckMode},
    dry_run::LaunchMode,
    id::GraphId,
    kernel::CubeKernel,
    logging::ServerLogger,
    memory_management::{
        ManagedMemoryHandle, ManagedMemoryId, MemoryAllocationMode, StreamMemoryReport,
    },
    poison::DevicePoison,
    server::{BufferBinding, KernelResource},
    storage::{ComputeStorage, ManagedResource},
    tma::{OobFill, TensorMapFormat, TensorMapInterleave, TensorMapPrefetch, TensorMapSwizzle},
};
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::{
    fmt::{Debug, Display},
    hash::{BuildHasher, Hash},
};
use cubecl_common::{
    bytes::Bytes,
    device::{self, DeviceId, ServiceId},
    profile::ProfileDuration,
};
use cubecl_environment::backtrace::BackTrace;
use cubecl_environment::collections::HashSet;
use cubecl_environment::future::DynFut;
use cubecl_environment::stream::StreamId;
use cubecl_environment::sync::RwLock;
use cubecl_ir::{DeviceProperties, ElemType, TargetProperties, settings::Dim3};
use cubecl_zspace::{Shape, Strides, metadata::Metadata};
use derive_more::{Deref, DerefMut, From};
use foldhash::fast::FixedState;
use itertools::Itertools;
use thiserror::Error;

#[derive(Error, Clone)]
#[cfg_attr(serializable, derive(serde::Serialize, serde::Deserialize))]
/// An error during profiling.
pub enum ProfileError {
    /// An unknown error happened during profiling
    #[error(
        "An unknown error happened during profiling\nCaused by:\n  {reason}\nBacktrace:\n{backtrace}"
    )]
    Unknown {
        /// The caused of the error
        reason: String,
        /// The captured backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// No profiling was registered
    #[error("No profiling registered\nBacktrace:\n{backtrace}")]
    NotRegistered {
        /// The captured backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// The profiled window resolved no device timing.
    ///
    /// Distinct from a zero duration, which is a measurement that came back
    /// instant. This is the absence of one: nothing the window enqueued was
    /// timestamped, so the backend has nothing to report. A caller that only
    /// wants a number can treat it as zero; a caller comparing candidates must
    /// not, because an absence that reads as zero is the fastest result there
    /// is and wins every comparison it enters.
    #[error("The profiled window resolved no device timing\nBacktrace:\n{backtrace}")]
    NotMeasured {
        /// The captured backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// A launch error happened during profiling
    #[error("A launch error happened during profiling\nCaused by:\n  {0}")]
    Launch(#[from] LaunchError),

    /// An execution error happened during profiling
    #[error("An execution error happened during profiling\nCaused by:\n  {0}")]
    Server(#[from] Box<ServerError>),
}

/// A failure during a profiling window invalidates the measurement, whatever
/// the failure was. Every backend answers a launch, write or replay failure
/// this way, so the conversion lives here rather than five times over.
impl From<&ServerError> for ProfileError {
    fn from(error: &ServerError) -> Self {
        ProfileError::Server(Box::new(error.clone()))
    }
}

impl core::fmt::Debug for ProfileError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_fmt(format_args!("{self}"))
    }
}

/// Contains many different types that are useful for server implementations and compute clients.
pub struct ServerUtilities {
    /// The time when `profile-tracy` is activated.
    #[cfg(feature = "profile-tracy")]
    pub epoch_time: cubecl_environment::time::Instant,
    /// The GPU client when `profile-tracy` is activated.
    #[cfg(feature = "profile-tracy")]
    pub gpu_client: tracy_client::GpuContext,
    /// The service these utilities belong to: what the handles it allocates
    /// are stamped with, and what a client compares them against.
    pub service: ServiceId,
    /// The runtime name on this device, as logs and cache keys show it:
    /// `cuda`, `wgpu<spirv>`.
    pub name: &'static str,
    /// Information shared between all servers.
    pub properties: Arc<DeviceProperties>,
    /// Stable hash of the device properties
    pub properties_hash: u64,
    /// What the target the server compiles for guarantees about its own
    /// instructions — [`Runtime::target_properties`](crate::runtime::Runtime::target_properties)
    /// resolved once, when the device came up, rather than on every launch.
    ///
    /// A kernel keeps a clone of this `Arc` so it can expand itself on the
    /// device thread without naming a runtime, so building it per launch
    /// would put a `TargetProperties` construction — and the allocations
    /// inside it — on the hot path of every already-compiled kernel.
    pub target_properties: Arc<TargetProperties>,
    /// The logger based on global cubecl configs.
    pub logger: Arc<ServerLogger>,
    /// How to create the allocation.
    pub layout_policy: Box<dyn MemoryLayoutPolicy>,
    /// Whether the server can move data to a peer server of the same runtime
    /// directly, without a round trip through the host: the device transport
    /// `Client::has_device_transport` reports. Off unless the backend turns it
    /// on at init.
    pub server_comm_enabled: bool,
    /// How to enforce bounds checking on kernels.
    pub check_mode: BoundsCheckMode,
    /// A set containing the ids for which the inter-device communication has already been initialized.
    pub initialized_comms: RwLock<HashSet<CommunicationId>>,
    /// The graph captures under way on the device, read-only: the streams update them through
    /// the [`DeviceCaptures`] [`init`](Self::init) returns alongside.
    pub captures: CaptureStatus,
}

/// Defines how the memory layout is determined.
pub trait MemoryLayoutPolicy: Send + Sync + 'static {
    /// Applies the memory layout policy to a list of descriptors.
    ///
    /// Returns a vector of `MemoryLayout`, one per descriptor, with layouts that share a
    /// single `Binding`.
    fn apply(
        &self,
        service: ServiceId,
        stream_id: StreamId,
        descriptors: &[MemoryLayoutDescriptor],
    ) -> (Handle, Vec<MemoryLayout>);
}

impl core::fmt::Debug for ServerUtilities {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_struct("ServerUtilities")
            .field("properties", &self.properties)
            .field("name", &self.name)
            .field("logger", &self.logger)
            .finish()
    }
}

impl ServerUtilities {
    /// Creates the utilities of a device, with the [captures](DeviceCaptures) its streams
    /// update.
    ///
    /// The utilities are shared with every client and only read the captures; the server hands
    /// the returned writer to the streams it creates, and to nothing else.
    pub fn init(
        service: ServiceId,
        name: &'static str,
        properties: DeviceProperties,
        target_properties: TargetProperties,
        logger: Arc<ServerLogger>,
        allocator: impl MemoryLayoutPolicy,
    ) -> (Self, DeviceCaptures) {
        let captures = DeviceCaptures::default();
        // Start a tracy client if needed.
        #[cfg(feature = "profile-tracy")]
        let client = tracy_client::Client::start();

        let utilities = Self {
            service,
            name,
            properties_hash: properties.checksum(),
            properties: Arc::new(properties),
            target_properties: Arc::new(target_properties),
            logger,
            // Create the GPU client if needed.
            #[cfg(feature = "profile-tracy")]
            gpu_client: client
                .clone()
                .new_gpu_context(
                    Some(name),
                    // In the future should ask the server what makes sense here. 'Invalid' atm is a generic stand-in (Tracy doesn't have CUDA/RocM atm anyway).
                    tracy_client::GpuContextType::Invalid,
                    0,   // Timestamps are manually aligned to this epoch so start at 0.
                    1.0, // Timestamps are manually converted to be nanoseconds so period is 1.
                )
                .unwrap(),
            #[cfg(feature = "profile-tracy")]
            epoch_time: cubecl_environment::time::Instant::now(),
            layout_policy: Box::new(allocator),
            server_comm_enabled: false,
            check_mode: CubeClRuntimeConfig::get().compilation.check_mode,
            initialized_comms: RwLock::new(HashSet::default()),
            captures: captures.status(),
        };

        (utilities, captures)
    }
}

/// Kernel Launch Errors.
#[derive(Error, Clone)]
#[cfg_attr(serializable, derive(serde::Serialize, serde::Deserialize))]
pub enum LaunchError {
    /// The given kernel can't be compiled.
    #[error("A compilation error happened during launch\nCaused by:\n  {0}")]
    CompilationError(#[from] CompilationError),

    /// The server is out of memory.
    #[error(
        "An out-of-memory error happened during launch\nCaused by:\n  {reason}\nBacktrace\n{backtrace}"
    )]
    OutOfMemory {
        /// The caused of the memory error.
        reason: String,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// Too many resources were requested
    #[error("Too many resources were requested during launch\n{0}")]
    TooManyResources(#[from] ResourceLimitError),

    /// The device is poisoned: a kernel faulted in a way the driver makes
    /// sticky (an illegal address, a trap, a hardware fault, etc.)
    #[error("The device was poisoned during launch\nCaused by:\n  {0}")]
    DevicePoisoned(#[from] DevicePoison),

    /// Unknown launch error.
    #[error(
        "An unknown error happened during launch\nCaused by:\n  {reason}\nBacktrace\n{backtrace}"
    )]
    Unknown {
        /// The caused of the unknown error.
        reason: String,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },
}

/// Resource limit errors.
#[derive(Error, Clone)]
#[cfg_attr(serializable, derive(serde::Serialize, serde::Deserialize))]
pub enum ResourceLimitError {
    /// Shared memory exceeds maximum
    #[error(
        "Too much shared memory requested.\nRequested {requested} bytes, maximum {max} bytes available.\nBacktrace\n{backtrace}"
    )]
    SharedMemory {
        /// Value requested
        requested: usize,
        /// Maximum value
        max: usize,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },
    /// Total units exceeds maximum
    #[error(
        "Total unit count exceeds maximum.\nRequested {requested} units, max units is {max}.\nBacktrace\n{backtrace}"
    )]
    Units {
        /// Requested value
        requested: u32,
        /// Maximum value
        max: u32,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },
    /// `CubeDim` exceeds maximum
    #[error(
        "Cube dim exceeds maximum bounds.\nRequested {requested:?}, max is {max:?}.\nBacktrace\n{backtrace}"
    )]
    CubeDim {
        /// Requested value
        requested: (u32, u32, u32),
        /// Maximum value
        max: (u32, u32, u32),
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },
}

impl LaunchError {
    /// Whether the device that emitted the error is poisoned.
    pub fn is_device_poisoned(&self) -> bool {
        match self {
            Self::DevicePoisoned(_) => true,
            Self::CompilationError(error) => error.is_device_poisoned(),
            _ => false,
        }
    }

    /// Whether this is the kernel being refused before it ran.
    pub fn is_refusal(&self) -> bool {
        match self {
            Self::CompilationError(error) => error.is_refusal(),
            Self::TooManyResources(_) => true,
            _ => false,
        }
    }
}

impl core::fmt::Debug for LaunchError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_fmt(format_args!("{self}"))
    }
}

impl core::fmt::Debug for ResourceLimitError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_fmt(format_args!("{self}"))
    }
}

/// A collective operation between the devices of one runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(serializable, derive(serde::Serialize, serde::Deserialize))]
pub enum Collective {
    /// Setting up the communication between a group of devices.
    CommInit,
    /// Reducing a buffer across a group of devices.
    AllReduce,
    /// Sending a buffer to a peer device.
    Send,
    /// Receiving a buffer from a peer device.
    Recv,
    /// Waiting for queued collectives to finish.
    SyncCollective,
}

impl Display for Collective {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(match self {
            Self::CommInit => "comm_init",
            Self::AllReduce => "all_reduce",
            Self::Send => "send",
            Self::Recv => "recv",
            Self::SyncCollective => "sync_collective",
        })
    }
}

/// Error that can happen asynchronously while executing registered kernels.
#[derive(Error, Clone)]
#[cfg_attr(serializable, derive(serde::Serialize, serde::Deserialize))]
pub enum ServerError {
    /// A runtime validation error
    #[error(
        "A validation error happened during execution\nCaused by:\n  {message}\nBacktrace:\n{backtrace}"
    )]
    Validation {
        /// The details of the validation error.
        message: String,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// A generic runtime error.
    #[error("An error happened during execution\nCaused by:\n  {reason}\nBacktrace:\n{backtrace}")]
    Generic {
        /// The details of the generic error.
        reason: String,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// The runtime has no transport between its devices, so the collective was
    /// not run. Its own variant rather than a `Generic` reason, so a caller can
    /// tell a runtime that cannot do this apart from a collective that failed.
    #[error(
        "{operation} needs a transport between devices, and this runtime has none\nBacktrace:\n{backtrace}"
    )]
    NoDeviceTransport {
        /// The collective that was asked for.
        operation: Collective,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// A handle from one service was handed to a client of another: memory
    /// coordinates mean nothing there, so nothing was run.
    #[error("A handle of {handle} was used on {client}\nBacktrace:\n{backtrace}")]
    ForeignHandle {
        /// The service whose memory the handle addresses.
        handle: String,
        /// The service the client reaches.
        client: String,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// A caller named a server type the client does not reach. The client is
    /// erased over its server, so the type it is asked for is checked against
    /// the one it was built from, and nothing was run.
    #[error("The client reaches {client}, not a {requested}\nBacktrace:\n{backtrace}")]
    ServiceMismatch {
        /// The service the client reaches.
        client: String,
        /// The server type the caller asked for.
        requested: String,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// The device is poisoned: a kernel faulted in a way the driver makes
    /// sticky (an illegal address, a trap, a hardware fault, etc.)
    #[error("The device is poisoned\nCaused by:\n  {0}")]
    DevicePoisoned(#[from] DevicePoison),

    /// A launch error happened
    #[error("A launch error happened\nCaused by:\n  {0}")]
    Launch(#[from] LaunchError),

    /// An IO error happened
    #[error("An IO error happened\nCaused by:\n  {0}")]
    Io(#[from] IoError),

    /// The work writing this buffer was torn down before it could say what
    /// went wrong: its write scope never reached the exit that names the real
    /// failure, which a panic mid-launch explains.
    ///
    /// This is the provisional error every write scope enters with, so it
    /// carries no payload and captures no backtrace — a launch that succeeds
    /// mints one and drops it again, and paying a `String` and a stack walk
    /// per launch for the message nobody normally reads is the whole reason
    /// it is a variant rather than a [`Generic`](Self::Generic).
    #[error(
        "The work writing this buffer was torn down before it could say what went wrong: its \
         write scope never reached the exit that names the real failure, which a panic \
         mid-launch explains"
    )]
    TornDown,

    /// The bytes asked about were never written: the work that was going to
    /// write them failed, or was skipped downstream of a failure. `chain`
    /// walks from the buffer asked about back toward the root, newest skip
    /// first, and `root` is the failure that started it.
    #[error(
        "The bytes were never written (failure #{failure}, still claiming {claimed} buffer(s))\n{}Caused by:\n  {root}\nAsked at:\n{backtrace}",
        chain.iter().map(|hop| alloc::format!("  {hop}\n")).collect::<String>()
    )]
    Unwritten {
        /// The failure's id in the device's error store, as printed by every
        /// other read that trips over the same failure.
        failure: u64,
        /// How many buffers the failure still claims.
        claimed: u32,
        /// The skip chain from the buffer asked about back toward the root.
        chain: Vec<String>,
        /// The failure that started it, backtrace included.
        root: Box<ServerError>,
        /// Where the question was asked, so the lazy report and the read that
        /// tripped over it can be tied together.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// The work did not run, because an input it needed carried a failure.
    ///
    /// The report is on the buffers: the work's outputs claim the failure its
    /// inputs did, so a read of one of them names the root cause and the path
    /// back to it. This variant says only *that* the caller's work was
    /// skipped, which is why it carries no payload — the failure the inputs
    /// held is not the caller's to receive here, and minting a formatted
    /// message per skip would cost the loop that skips on every iteration.
    #[error(
        "The work was skipped: an input carried a failure, and the work's outputs claim it now \
         — a read of one of them names the root cause"
    )]
    Skipped,

    /// More than one thing went wrong at once, and the caller is owed all of
    /// them: a read naming buffers that several distinct failures claim, or a
    /// capture that was both doomed and abandoned.
    #[error("Several failures at once\nCaused by:\n  {}", errors.iter().join("\n"))]
    Several {
        /// The failures, in the order they were found.
        errors: Vec<Self>,
        /// The backtrace for this error.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },
}

impl Debug for ServerError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{self}")
    }
}

impl ServerError {
    /// The error every collective returns on a runtime with no transport between devices.
    pub fn no_device_transport(operation: Collective) -> Self {
        Self::NoDeviceTransport {
            operation,
            backtrace: BackTrace::capture(),
        }
    }

    /// Whether this is the kernel being refused before it ran, rather than
    /// something going wrong while running it.
    ///
    /// The distinction a test harness or an autotuner needs: a kernel a
    /// backend cannot build at this configuration is a candidate to drop or a
    /// case to skip, while a fault, an out-of-memory, an IO failure or a
    /// kernel that panicked while expanding is a defect that has to be
    /// reported. Answering it by reading the message is
    /// how a harness ends up accepting the second as the first.
    ///
    /// Walks [`Several`](Self::Several) and [`Unwritten`](Self::Unwritten) to
    /// the roots, because a read of an unwritten buffer reports the failure
    /// that stopped its writer and that is where the distinction lives. A
    /// group answers yes only when every root does: one real failure among
    /// refusals is still a real failure, and an empty group refuses nothing.
    pub fn is_refusal(&self) -> bool {
        match self {
            Self::Launch(error) => error.is_refusal(),
            Self::Unwritten { root, .. } => root.is_refusal(),
            Self::Several { errors, .. } => {
                !errors.is_empty() && errors.iter().all(Self::is_refusal)
            }
            _ => false,
        }
    }

    /// Whether the device that emitted the error is poisoned.
    ///
    /// The other half of [`is_refusal`](Self::is_refusal): a refusal says
    /// "drop this candidate", a poisoned device says "drop the device". Anything
    /// else — an out-of-memory, a failed copy, a skipped launch — leaves the
    /// device usable, and redoing the work may well succeed.
    ///
    /// Walks [`Several`](Self::Several) and [`Unwritten`](Self::Unwritten) to
    /// the roots, and answers yes when *any* root poisoned the device: one poisoned
    /// device among other failures still means nothing on it can be trusted.
    pub fn is_device_poisoned(&self) -> bool {
        match self {
            Self::DevicePoisoned(_) => true,
            Self::Launch(error) => error.is_device_poisoned(),
            Self::Io(error) => error.is_device_poisoned(),
            Self::Unwritten { root, .. } => root.is_device_poisoned(),
            Self::Several { errors, .. } => errors.iter().any(Self::is_device_poisoned),
            _ => false,
        }
    }

    /// A graph-capture call the stream's lifecycle does not allow — a
    /// `begin_capture` without `graph_prepare`, a second overlapping capture, a
    /// replay of an unknown graph, or an operation a capture window cannot
    /// record. `reason` names the call and what was wrong with it.
    pub fn graph_state(reason: impl Into<String>) -> Self {
        Self::Generic {
            reason: reason.into(),
            backtrace: BackTrace::capture(),
        }
    }

    /// The error the default (unsupported) graph-capture methods return, for a
    /// backend that has no graph support at all.
    pub fn graph_capture_unsupported() -> Self {
        Self::graph_state("graph capture is not supported by this backend")
    }
}

/// The compute server is responsible for handling resources and computations over resources.
///
/// Everything in the server is mutable, therefore it should be solely accessed through the
/// [`Client`] for thread safety.
pub trait Server:
    core::any::Any + Send + core::fmt::Debug + ServerCommunication + device::DeviceService + 'static
{
    /// Initializes [memory](ManagedMemoryHandle) on the given [stream](StreamId) with the given size.
    ///
    /// # Errors
    ///
    /// Returns a [`ServerError`] when the memory could not be initialized, e.g. because the stream
    /// cannot be created on a poisoned device. The memory then carries the error: the next
    /// sync point reading that memory reports it.
    fn initialize_memory(
        &mut self,
        memory: ManagedMemoryHandle,
        size: u64,
        stream_id: StreamId,
    ) -> Result<(), ServerError>;

    /// Reserves N [Bytes] of the provided sizes to be used as staging to load data.
    fn staging(
        &mut self,
        _sizes: &[usize],
        _stream_id: StreamId,
    ) -> Result<Vec<Bytes>, ServerError> {
        Err(IoError::UnsupportedIoOperation {
            backtrace: BackTrace::capture(),
        }
        .into())
    }

    /// Retrieve the server logger.
    fn logger(&self) -> Arc<ServerLogger>;

    /// Retrieve the server utilities.
    fn utilities(&self) -> Arc<ServerUtilities>;

    /// Given bindings, returns the owned resources as bytes.
    ///
    /// # Errors
    ///
    /// [`ServerError::Several`] when the work that was supposed to
    /// write one of these buffers failed, whichever stream it ran on — copying
    /// bytes out would hand back whatever was in memory before. Every
    /// implementation asks
    /// `FailureStore::ensure_written` (in `cubecl-server`) before it copies
    /// anything.
    fn read(
        &mut self,
        descriptors: Vec<CopyDescriptor>,
        stream_id: StreamId,
    ) -> DynFut<Result<Vec<Bytes>, ServerError>>;

    /// Writes the specified bytes into the buffers given
    fn write(&mut self, descriptors: Vec<(CopyDescriptor, Bytes)>, stream_id: StreamId);

    /// Wait for the completion of every task in the server, then answer for
    /// `handles`: the barrier first, so device faults count, and then the
    /// claim check a read would have made — a read without the read.
    ///
    /// An empty `handles` is the plain barrier plus the device fault, which
    /// is the only failure left that no buffer can report.
    fn sync(
        &mut self,
        handles: Vec<BufferBinding>,
        stream_id: StreamId,
    ) -> DynFut<Result<(), ServerError>>;

    /// Whether the bytes the handles name can be trusted, right now and with
    /// no barrier: the claim check a read makes, without the read. Instant —
    /// enqueue-time failures only. A device fault needs [`sync`](Self::sync),
    /// which drains first.
    fn check(
        &mut self,
        handles: Vec<BufferBinding>,
        stream_id: StreamId,
    ) -> Result<(), ServerError>;

    /// Executes the `kernel` over the given memory `handles`.
    ///
    /// Kernels have mutable access to every resource they are given
    /// and are responsible of determining which should be read or written.
    ///
    /// `launch_mode` says whether the kernel actually runs. On
    /// [`LaunchMode::Skip`] the server must still do everything a first launch
    /// does short of dispatching — expand, compile, validate, fill its caches —
    /// and then drop the launch; skipping the compilation instead would defeat
    /// the whole point of a [dry run](crate::dry_run).
    ///
    /// # Safety
    ///
    /// When executing with mode [`ExecutionMode::Unchecked`], out-of-bound reads and writes can happen.
    unsafe fn launch(
        &mut self,
        kernel: Box<dyn CubeKernel>,
        count: CubeCount,
        bindings: KernelArguments,
        stream_id: StreamId,
        launch_mode: LaunchMode,
    );

    /// Flush all outstanding tasks in the server.
    ///
    /// # Errors
    ///
    /// The device fault, when the context itself is broken — a launch failure
    /// is not the flush's to report: it lives on the buffers the launch left
    /// unwritten, and surfaces on any read, sync or check of them.
    fn flush(&mut self, stream_id: StreamId) -> Result<(), ServerError>;

    /// Prepare `stream_id` for an upcoming graph capture. Call this
    /// **before** the warmup run: the capture window allocates nothing, so it
    /// reuses what the warmup run left in the pools, and every page the
    /// recording touches is guarded for the graph's lifetime.
    ///
    /// Prefer having kernels already **autotuned before** this call, so the
    /// warmup run allocates what the recorded run asks for and nothing else.
    ///
    /// A no-op by default (harmless on backends without graph support).
    fn graph_prepare(&mut self, stream_id: StreamId) -> Result<(), ServerError> {
        let _ = stream_id;
        Ok(())
    }

    /// Begin recording the launches issued on `stream_id` into a graph instead
    /// of executing them, so the sequence can later be
    /// [replayed](Server::replay) without paying the launch path again.
    /// Call [`graph_prepare`](Server::graph_prepare) and warm up first.
    ///
    /// Between this call and [`end_capture`](Server::end_capture) the
    /// stream must not synchronize — a read, a sync or a profile either aborts
    /// the capture or is refused — and should not allocate fresh device memory,
    /// which `graph_prepare` plus a warmup run is what avoids. Whether an
    /// operation the window cannot record fails the call or fails
    /// `end_capture`, and whether a mid-window allocation is fatal, is the
    /// backend's to say; see `StreamCapture` in `cubecl-server`.
    ///
    /// The default is unsupported. Two shapes of backend override it: a
    /// **hardware graph** (CUDA, HIP), where the driver records a replayable
    /// graph object, and a **software graph** (wgpu), where the runtime records
    /// fully-resolved dispatches and re-encodes them on replay.
    fn begin_capture(&mut self, stream_id: StreamId) -> Result<(), ServerError> {
        let _ = stream_id;
        Err(ServerError::graph_capture_unsupported())
    }

    /// Stop recording (see [`begin_capture`](Server::begin_capture)),
    /// store the captured graph in the backend's registry, and return its
    /// [`GraphId`], ready to [replay](Server::replay).
    fn end_capture(&mut self, stream_id: StreamId) -> Result<GraphId, ServerError> {
        let _ = stream_id;
        Err(ServerError::graph_capture_unsupported())
    }

    /// Replay the graph identified by `graph` on `stream_id`, re-running the
    /// whole recorded launch sequence against its original buffers. A hardware
    /// graph replays as a single dispatch; a software graph re-encodes the
    /// recorded dispatches, which is still far cheaper than the launch path but
    /// stays O(n) in recorded launches.
    ///
    /// The call enqueues the dispatch and returns without waiting for the
    /// device; what it reports is the enqueue — an unknown or destroyed
    /// graph, a refusal — since a caller replaying a graph is standing right
    /// there. A failure also leaves the graph's write set carrying it, so a
    /// read of those buffers fails until a replay lands. Unsupported by
    /// default: a [`GraphId`] can only come from
    /// [`end_capture`](Server::end_capture).
    fn replay(&mut self, graph: GraphId, stream_id: StreamId) -> Result<(), ServerError> {
        let _ = (graph, stream_id);
        Err(ServerError::graph_capture_unsupported())
    }

    /// Release the graph identified by `graph`, destroying whatever it recorded
    /// and unpinning the buffers it retained. Replay returns at enqueue time,
    /// so the backend must guarantee no in-flight replay can still read those
    /// buffers once they return to the pool — by syncing `stream_id` where
    /// nothing weaker will do (CUDA, HIP), or by relying on the queue ordering
    /// that already places a submitted replay ahead of any later write (wgpu).
    /// A no-op by default and for an unknown id.
    fn graph_destroy(&mut self, graph: GraphId, stream_id: StreamId) {
        let _ = (graph, stream_id);
    }

    /// Structured per-pool report of the given stream's **main GPU** memory:
    /// each pool's shape, usage, and high-water marks, in allocation-routing
    /// order. The read side of a measured memory plan — see
    /// `MemoryManagement::memory_report` in `cubecl-server`.
    ///
    /// `None` when the stream was never created.
    fn memory_report(&mut self, stream_id: StreamId) -> Option<StreamMemoryReport>;

    /// Stream ids the client should iterate to aggregate across the device.
    ///
    /// Default is just the calling stream, which is correct for
    /// non-multi-stream backends; multi-stream backends override to
    /// return one id per initialized stream pool slot.
    fn stream_ids(&self) -> Vec<StreamId> {
        Vec::from([StreamId::current()])
    }

    /// Ask the server to release memory that it can release.
    ///
    /// # Errors
    ///
    /// Refused while a stream records a graph: releasing memory waits on the
    /// device, and a wait on a stream that records aborts its capture.
    fn memory_cleanup(&mut self, stream_id: StreamId) -> Result<(), ServerError>;

    /// Enable collecting timestamps.
    fn start_profile(&mut self, stream_id: StreamId) -> Result<ProfilingToken, ServerError>;

    /// Disable collecting timestamps.
    fn end_profile(
        &mut self,
        stream_id: StreamId,
        token: ProfilingToken,
    ) -> Result<ProfileDuration, ProfileError>;

    /// Drop the window `token` opened without measuring it, for a caller that
    /// will never close it with [`end_profile`](Self::end_profile).
    ///
    /// An open window is not free: depending on the backend it retains
    /// command buffers, keeps timestamp writes on, or holds a device event.
    ///
    /// Every backend overrides this, and should: the default closes the window
    /// and throws the measurement away, which is the most expensive way to be
    /// rid of it — [`end_profile`](Self::end_profile) is where the syncing and
    /// flushing live, and this is the one call that needs none of it.
    fn abandon_profile(&mut self, stream_id: StreamId, token: ProfilingToken) {
        let _ = self.end_profile(stream_id, token);
    }

    /// Update the memory mode of allocation in the server.
    fn allocation_mode(&mut self, mode: MemoryAllocationMode, stream_id: StreamId);
}

/// The storage a server allocates from, and the native resources it hands
/// out. Kept off [`Server`] so that trait is object-safe: a resource's
/// type is the backend's own, and only a caller that names the backend can
/// receive one.
pub trait ServerStorage: Server {
    /// The [storage](ComputeStorage) type defines how data is stored and accessed.
    type Storage: ComputeStorage;
    /// Given a resource handle, returns the storage resource.
    ///
    /// The same claim check a read makes guards this too: a buffer a failed
    /// launch never filled reports the failure rather than handing back a
    /// pointer to whatever was there before. It costs a field read on a slice
    /// the resolution walks anyway.
    fn get_resource(
        &mut self,
        binding: BufferBinding,
        stream_id: StreamId,
    ) -> Result<ManagedResource<<Self::Storage as ComputeStorage>::Resource>, ServerError>;
}

/// An ID unique to any unordered combination of devices.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct CommunicationId {
    /// The ID as a `String`.
    pub id: u64,
}

impl From<Vec<DeviceId>> for CommunicationId {
    fn from(mut value: Vec<DeviceId>) -> Self {
        // Make sure that device ids are sorted so that any combination of the same devices uses the same communicator.
        value.sort();
        CommunicationId {
            id: FixedState::default().hash_one(value),
        }
    }
}

/// Different reduce operations.
pub enum ReduceOperation {
    /// Sum.
    Sum,
    /// Mean.
    Mean,
}

/// Defines functions for optimized data transfer between servers, supporting custom communication
/// mechanisms such as peer-to-peer communication or specialized implementations.
///
/// # Inside the tainted-buffer rules
///
/// A collective reads a source buffer and produces a destination one, and owes
/// the same two answers the rest of the server gives: ask whether the source
/// carries a failure on the way in (as [`read`](Server::read) does
/// through
/// `FailureStore::ensure_written` in `cubecl-server`),
/// and taint the destination on the way out when the operation fails (as a
/// failed [`launch`](Server::launch) does). Skipping either lets a
/// collective reduce stale bytes across every device in the group, or leave a
/// destination that reads back clean when nothing wrote it.
///
/// The default methods are for a runtime with no transport between its devices:
/// each returns [`ServerError::NoDeviceTransport`] before touching any buffer, so
/// there is no destination to taint.
pub trait ServerCommunication {
    /// Ensure that all queued collective operations have been executed.
    ///
    /// # Arguments
    ///
    /// * `stream_id` - The [`StreamId`] of the stream waiting for the sync.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing an `ServerError` if the operation fails.
    ///
    /// # Errors
    ///
    /// The default returns [`ServerError::NoDeviceTransport`].
    #[allow(unused_variables)]
    fn sync_collective(&mut self, stream_id: StreamId) -> Result<(), ServerError> {
        Err(ServerError::no_device_transport(Collective::SyncCollective))
    }

    /// Initialize the communication between the devices in `device_ids`.
    ///
    /// # Arguments
    ///
    /// * `device_ids` - The IDs of the devices that need communication.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing an `ServerError` if the operation fails.
    ///
    /// # Errors
    ///
    /// The default returns [`ServerError::NoDeviceTransport`].
    #[allow(unused_variables)]
    fn comm_init(&mut self, device_ids: Vec<DeviceId>) -> Result<(), ServerError> {
        Err(ServerError::no_device_transport(Collective::CommInit))
    }

    /// Performs an `all_reduce` operation on the input data and writes it to the output buffer.
    /// see <https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/collectives.html#allreduce>
    ///
    /// # Arguments
    ///
    /// * `src` - The data to be reduced.
    /// * `dst` - Where to write the result.
    /// * `dtype` - The element type of the data being reduced
    /// * `stream_id` - The data's stream id.
    /// * `op` - The reduce's aggregation operation e.g. mean, sum, etc.
    /// * `device_ids` - The list of device ids from which to `all_reduce`.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing an `ServerError` if the operation fails.
    ///
    /// # Errors
    ///
    /// The default returns [`ServerError::NoDeviceTransport`].
    #[allow(unused_variables)]
    fn all_reduce(
        &mut self,
        src: BufferBinding,
        dst: BufferBinding,
        dtype: ElemType,
        stream_id: StreamId,
        op: ReduceOperation,
        device_ids: Vec<DeviceId>,
    ) -> Result<(), ServerError> {
        Err(ServerError::no_device_transport(Collective::AllReduce))
    }

    /// Sends data from this server to a destination server.
    ///
    /// # Arguments
    ///
    /// * `desc` - A descriptor specifying the data to be sent, including shape, strides, and binding.
    /// * `dtype` - The element type of the data being sent.
    /// * `stream_id` - The stream ID associated with the server's operation.
    /// * `device_id_dst` - ID of the device receiving the data.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing an `ServerError` if the operation fails.
    ///
    /// # Known limitation
    ///
    /// Send and recv are posted fire-and-forget on two devices and block for
    /// each other, so a send that refuses — a source whose writer failed,
    /// above all — leaves the peer's already-posted recv waiting on its
    /// communication stream with no way to recall it from here. The refusal
    /// is still right: completing the send would launder stale bytes onto a
    /// handle that carries no claim on the other device. Cross-device
    /// failure propagation needs a design pass of its own.
    ///
    /// # Errors
    ///
    /// The default returns [`ServerError::NoDeviceTransport`].
    #[allow(unused_variables)]
    fn send(
        &mut self,
        desc: CopyDescriptor,
        dtype: ElemType,
        stream_id: StreamId,
        device_id_dst: DeviceId,
    ) -> Result<(), ServerError> {
        Err(ServerError::no_device_transport(Collective::Send))
    }

    /// Receive data from another server.
    ///
    /// # Arguments
    ///
    /// * `handle` - The handle in which the received data is written.
    /// * `dtype` - The element type of the data being sent.
    /// * `stream_id` - The stream ID associated with the server's operation.
    /// * `device_id_src` - ID of the device sending the data.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing an `ServerError` if the operation fails.
    ///
    /// # Errors
    ///
    /// The default returns [`ServerError::NoDeviceTransport`].
    #[allow(unused_variables)]
    fn recv(
        &mut self,
        handle: Handle,
        dtype: ElemType,
        stream_id: StreamId,
        device_id_src: DeviceId,
    ) -> Result<(), ServerError> {
        Err(ServerError::no_device_transport(Collective::Recv))
    }
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
/// Profiling identification so that the server can support recursive and overlapping profilings.
pub struct ProfilingToken {
    /// The token value.
    pub id: u64,
}

/// Type of allocation, either contiguous or optimized (row-aligned when possible)
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum MemoryLayoutStrategy {
    /// Contiguous layout, with no padding
    Contiguous,
    /// Optimized for access speed. In practice this means row-aligned with padding for runtimes
    /// that support it.
    Optimized,
}

/// Descriptor for a new tensor allocation
#[derive(new, Debug, Clone)]
pub struct MemoryLayoutDescriptor {
    /// Strategy used to create the memory layout.
    pub strategy: MemoryLayoutStrategy,
    /// Shape of the tensor
    pub shape: Shape,
    /// Size of each element in the tensor (used for conversion of shape to bytes)
    pub elem_size: usize,
}

impl MemoryLayoutDescriptor {
    /// Create an optimized allocation descriptor
    pub fn optimized(shape: Shape, elem_size: usize) -> Self {
        MemoryLayoutDescriptor::new(MemoryLayoutStrategy::Optimized, shape, elem_size)
    }

    /// Create a contiguous allocation descriptor
    pub fn contiguous(shape: Shape, elem_size: usize) -> Self {
        MemoryLayoutDescriptor::new(MemoryLayoutStrategy::Contiguous, shape, elem_size)
    }
}

/// An allocation with associated strides. Strides depend on tensor layout.
#[derive(Debug, Clone)]
pub struct MemoryLayout {
    /// The handle for the memory resource
    pub memory: Handle,
    /// TODO: `Strides` should become `Layout`.
    ///
    /// The strides of the tensor
    pub strides: Strides,
}

impl MemoryLayout {
    /// Create a new memory layout.
    pub fn new(handle: Handle, strides: impl Into<Strides>) -> Self {
        MemoryLayout {
            memory: handle,
            strides: strides.into(),
        }
    }
}

/// A reason for an error.
#[derive(Default, Clone)]
pub struct Reason {
    inner: ReasonInner,
}

#[cfg(serializable)]
mod _reason_serde {
    use super::*;

    use alloc::string::ToString;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    impl Serialize for Reason {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            // Use the Display implementation (via to_string) to flatten the enum
            serializer.serialize_str(&self.to_string())
        }
    }

    impl<'de> Deserialize<'de> for Reason {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            // Deserialize into a standard String first
            let s = String::deserialize(deserializer)?;

            // Wrap it in the Dynamic variant since we can't safely
            // reconstruct a 'static str from a runtime string.
            Ok(Reason {
                inner: ReasonInner::Dynamic(Arc::new(s)),
            })
        }
    }
}

#[derive(Default, Clone)]
enum ReasonInner {
    Static(&'static str),
    Dynamic(Arc<String>),
    #[default]
    NotProvided,
}

impl core::fmt::Display for Reason {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match &self.inner {
            ReasonInner::Static(content) => f.write_str(content),
            ReasonInner::Dynamic(content) => f.write_str(content),
            ReasonInner::NotProvided => f.write_str("No reason provided for the error"),
        }
    }
}

impl core::fmt::Debug for Reason {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self, f)
    }
}

impl From<&'static str> for Reason {
    fn from(value: &'static str) -> Self {
        Self {
            inner: ReasonInner::Static(value),
        }
    }
}

impl From<String> for Reason {
    fn from(value: String) -> Self {
        Self {
            inner: ReasonInner::Dynamic(Arc::new(value)),
        }
    }
}

/// Error returned from `create`/`read`/`write` functions. Due to async execution not all errors
/// are able to be caught, so some IO errors will still panic.
#[derive(Error, Clone)]
#[cfg_attr(serializable, derive(serde::Serialize, serde::Deserialize))]
pub enum IoError {
    /// Buffer size exceeds the max available
    #[error("can't allocate buffer of size: {size}\n{backtrace}")]
    BufferTooBig {
        /// The size of the buffer in bytes.
        size: u64,
        /// The captured backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// The device had no memory left for this allocation.
    ///
    /// Unlike [`IoError::BufferTooBig`] (the allocation can *never* fit), this
    /// describes the device at one moment: pool pages whose slices have all
    /// been dropped are still resident, and the frees that would release them
    /// may not have reached the driver yet. Reclaiming and retrying is a
    /// reasonable response, which is why a storage backend must not report a
    /// driver out-of-memory as `BufferTooBig`: that tells every caller the
    /// allocation is hopeless when it is merely untimely.
    #[error("out of device memory allocating {size} bytes\n{backtrace}")]
    OutOfMemory {
        /// The size of the failed allocation in bytes.
        size: u64,
        /// The captured backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// No room for the allocation in the pages the memory holds, and the
    /// reservation was not allowed to add one.
    ///
    /// A stream recording a graph reserves this way: an allocation would
    /// become part of the recording, and a hardware graph holding one cannot
    /// be relaunched. The warmup before a capture is what leaves the pools
    /// holding what the recorded run asks for.
    #[error(
        "No room for {size} bytes in the memory held, and no page may be added (a graph capture is recording: warm up with the same workload first)\n{backtrace}"
    )]
    PageUpdateForbidden {
        /// The size of the allocation in bytes.
        size: u64,
        /// The captured backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// An allocation needs pages of a new size, and the memory already holds
    /// as many page sizes as it keeps track of.
    ///
    /// Every size a workload grew through keeps a pool until what lives on it
    /// is freed or relocated. A cleanup relocates what it can, so reclaiming
    /// and retrying is a reasonable response.
    #[error(
        "Can't allocate {size} bytes: every page size the memory tracks still holds live allocations\n{backtrace}"
    )]
    PageSizesExhausted {
        /// The size of the allocation in bytes.
        size: u64,
        /// The captured backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// Strides aren't supported for this copy operation on this runtime
    #[error("the provided strides are not supported for this operation\n{backtrace}")]
    UnsupportedStrides {
        /// The backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// Memory wasn't found in the memory pool
    #[error("couldn't find resource for that handle: {reason}\n{backtrace}")]
    NotFound {
        /// The backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
        /// The reason the handle is invalid.
        reason: Reason,
    },

    /// The storage backend holds no allocation for a handle's storage id.
    ///
    /// One layer below [`IoError::NotFound`]: there the memory manager could
    /// not route a binding to a slice, here the routing succeeded and the
    /// allocation the slice names is gone. A handle outliving its page, or a
    /// storage id a deallocation retired, reaches the storage this way.
    #[error("the storage holds no allocation for that handle: {reason}\n{backtrace}")]
    StorageHandleNotFound {
        /// Which id was looked up, and in which storage.
        reason: Reason,
        /// The backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// An allocation carved lazily under a [`DryRun`](crate::dry_run::DryRun)
    /// could not be given real device backing when it was finally resolved.
    ///
    /// Distinct from the same failure at reservation time, and the distinction
    /// is what a caller acts on: the memory was promised earlier, by a pass
    /// that measured a plan without paying for it, and is only now being
    /// charged for. A plan whose replay hits this was measured against more
    /// device memory than the replay has — warm the tune caches first, or
    /// measure a smaller one.
    #[error(
        "couldn't map storage for a deferred allocation of {size} bytes\nCaused by:\n  {source}"
    )]
    StorageMappingFailed {
        /// The size of the allocation that could not be backed, in bytes.
        size: u64,
        /// Why the device allocation failed.
        source: Box<IoError>,
        /// The backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// The device is poisoned: a kernel faulted in a way the driver makes
    /// sticky (an illegal address, a trap, a hardware fault, etc.)
    #[error("The device is poisoned: {0}")]
    DevicePoisoned(#[from] DevicePoison),

    /// Unknown error happened during execution
    #[error("Unknown error happened during execution: {description}\n{backtrace}")]
    Unknown {
        /// Details of the error
        description: String,
        /// The backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },

    /// The current IO operation is not supported
    #[error("The current IO operation is not supported\n{backtrace}")]
    UnsupportedIoOperation {
        /// The backtrace.
        #[cfg_attr(serializable, serde(skip))]
        backtrace: BackTrace,
    },
}

impl IoError {
    /// Whether the device that emitted the error is poisoned.
    pub fn is_device_poisoned(&self) -> bool {
        match self {
            Self::DevicePoisoned(_) => true,
            Self::StorageMappingFailed { source, .. } => source.is_device_poisoned(),
            _ => false,
        }
    }

    /// Whether reclaiming memory could still make this allocation succeed.
    ///
    /// Out of memory *right now* is not out of memory for good: pool pages
    /// whose slices have all been dropped are still resident, and the frees
    /// that would release them may sit in a deferred drop queue. A transient
    /// peak — a model build holding float weights while their quantized copies
    /// allocate, an autotune sample on a full device — is rescued by a reclaim
    /// and a second attempt.
    ///
    /// A buffer larger than any page the device can hold is the exception. It
    /// never fits, so reclaiming would only spend the time. So is an
    /// allocation while a graph records, where nothing may be released.
    pub fn may_succeed_after_reclaim(&self) -> bool {
        !matches!(
            self,
            IoError::BufferTooBig { .. } | IoError::PageUpdateForbidden { .. }
        )
    }
}

impl core::fmt::Debug for IoError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_fmt(format_args!("{self}"))
    }
}

/// Arguments to execute a kernel.
#[derive(Debug, Default)]
pub struct KernelArguments {
    /// Kernel bindings
    pub resources: Vec<KernelResource>,
    /// What the caller declared each resource is for, indexed like
    /// `resources`.
    ///
    /// The compiled kernel's own answer is better when it exists — the
    /// visibility analysis can prove a buffer write-only or dead, which a
    /// caller cannot — but it only exists once the kernel compiles. This one
    /// is stamped at the launch site from what the caller can see (a launch
    /// generated from `&Tensor` versus `&mut Tensor` knows it statically), so
    /// it survives the compile failing, which is exactly when it is needed: a
    /// launch that never ran must not taint the buffers it was only going to
    /// read. Missing entries read as [`ReadWrite`](BufferIOAttr::ReadWrite),
    /// so a caller that declares nothing keeps the loud fallback.
    pub declared_io: Vec<BufferIOAttr>,
    /// Packed scalars and metadata. First scalars sorted by type, then static metadata,
    /// then dynamic metadata.
    pub info: MetadataBindingInfo,
}

impl core::fmt::Display for KernelArguments {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("KernelArguments")?;
        for b in self.resources.iter() {
            f.write_fmt(format_args!("\n - buffer: {b:?}\n"))?;
        }

        Ok(())
    }
}

impl KernelArguments {
    /// Create a new bindings struct
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a buffer binding
    pub fn with_buffer(mut self, binding: BufferBinding) -> Self {
        self.resources.push(KernelResource::Buffer(binding));
        self
    }

    /// Add a buffer binding, declaring what the kernel does with it.
    ///
    /// The declaration is what a launch that fails before running — a kernel
    /// that does not compile above all — falls back on: only declared-writable
    /// buffers take the failure, so the ones the kernel was only going to read
    /// stay readable. Resources added without a declaration read as
    /// [`ReadWrite`](BufferIOAttr::ReadWrite), and mixing the two keeps every
    /// declaration on the resource it was made for.
    pub fn with_buffer_io(mut self, binding: BufferBinding, io: BufferIOAttr) -> Self {
        self.declared_io
            .resize(self.resources.len(), BufferIOAttr::ReadWrite);
        self.resources.push(KernelResource::Buffer(binding));
        self.declared_io.push(io);
        self
    }

    /// Extend the buffers with `bindings`
    pub fn with_buffers(mut self, bindings: Vec<BufferBinding>) -> Self {
        let bindings = bindings.into_iter().map(KernelResource::Buffer);
        self.resources.extend(bindings);
        self
    }

    /// Set the info to `info`
    pub fn with_info(mut self, info: MetadataBindingInfo) -> Self {
        self.info = info;
        self
    }

    /// Extend the tensor maps with `bindings`
    pub fn with_tensor_maps(mut self, bindings: Vec<TensorMapBinding>) -> Self {
        let bindings = bindings.into_iter().map(KernelResource::TensorMap);
        self.resources.extend(bindings);
        self
    }

    /// The buffers this launch was given.
    pub fn buffers(&self) -> impl Iterator<Item = &BufferBinding> {
        self.resources.iter().map(|resource| match resource {
            KernelResource::Buffer(binding) => binding,
            KernelResource::TensorMap(tensor_map) => &tensor_map.binding,
        })
    }

    /// The memory this launch was given.
    pub fn memory_ids(&self) -> impl Iterator<Item = ManagedMemoryId> + '_ {
        self.buffers().map(|binding| binding.memory.id())
    }

    /// The buffers this launch was given that the kernel writes, per the
    /// compiled kernel's own answer — the ones a launch that fails taints,
    /// and nothing else.
    ///
    /// `io` is what the compiler recorded from its visibility analysis,
    /// indexed like `resources` (see
    /// [`BufferIOAttr`](crate::kernel::BufferIOAttr)). An index it has no
    /// answer for falls back to the caller's declaration in `declared_io` —
    /// which is how a kernel that never compiled still taints only its
    /// outputs — and an index neither answers reads as written: naming a
    /// buffer the kernel only read fails a read that would have been fine,
    /// loudly; missing one it writes hands back the bytes that were there
    /// before, silently — so the last-resort fallback over-names.
    pub fn buffers_written<'a>(
        &'a self,
        io: Option<&'a [BufferIOAttr]>,
    ) -> impl Iterator<Item = &'a BufferBinding> {
        self.buffers()
            .enumerate()
            .filter_map(move |(index, binding)| {
                let written = self
                    .io_attr(io, index)
                    .map(|io| io.is_writable())
                    .unwrap_or(true);
                written.then_some(binding)
            })
    }

    /// The buffers this launch was given that the kernel reads — the ones
    /// whose contents have to be trustworthy before the launch runs, and the
    /// only ones checked: a pure output is not read, so a relaunch into a
    /// tainted buffer is exactly how the buffer gets repaired.
    ///
    /// The same fallback chain as [`buffers_written`](Self::buffers_written):
    /// compiled answer, then the caller's declaration, then read — so a
    /// kernel nobody kept an answer for is checked on everything rather than
    /// checked on nothing.
    pub fn buffers_read<'a>(
        &'a self,
        io: Option<&'a [BufferIOAttr]>,
    ) -> impl Iterator<Item = &'a BufferBinding> {
        self.buffers()
            .enumerate()
            .filter_map(move |(index, binding)| {
                let read = self
                    .io_attr(io, index)
                    .map(|io| io.is_readable())
                    .unwrap_or(true);
                read.then_some(binding)
            })
    }

    /// The answer for one resource: the compiled kernel's when it kept one,
    /// the caller's declaration otherwise, `None` when neither answered.
    fn io_attr(&self, compiled: Option<&[BufferIOAttr]>, index: usize) -> Option<BufferIOAttr> {
        compiled
            .and_then(|io| io.get(index))
            .or_else(|| self.declared_io.get(index))
            .copied()
    }
}

/// Binding of a set of scalars of the same type to execute a kernel.
///
/// The [`Server`] is responsible to convert those info into actual [`Binding`] when launching
/// kernels.
#[derive(new, Debug, Default)]
pub struct MetadataBindingInfo {
    /// Scalar and metadata values
    pub data: Vec<u64>,
    /// Start of the dynamically sized portion of the metadata, relative to the entire info buffer
    pub dynamic_metadata_offset: usize,
}

impl MetadataBindingInfo {
    /// Create a new binding info for custom data, for externally compiled kernels.
    pub fn custom(data: Vec<u64>) -> Self {
        Self::new(data, 0)
    }
}

/// A binding with shape and stride info for non-contiguous reading
#[derive(new, Debug)]
pub struct CopyDescriptor {
    /// Binding for the memory resource
    pub handle: BufferBinding,
    /// Shape of the resource
    pub shape: Shape,
    /// Strides of the resource
    pub strides: Strides,
    /// Size of each element in the resource
    pub elem_size: usize,
}

/// A tensor map used with TMA ops
#[derive(new, Clone, Debug)]
pub struct TensorMapBinding {
    /// The binding for the backing tensor
    pub binding: BufferBinding,
    /// The tensormap metadata
    pub map: TensorMapMeta,
}

/// `TensorMap` metadata for the opaque proxy used in TMA copies
#[derive(Debug, Clone)]
pub struct TensorMapMeta {
    /// Tensormap format (tiled or im2col)
    pub format: TensorMapFormat,
    /// Metadata of the backing tensor
    pub metadata: Metadata,
    /// Element stride, usually 1 but may be 2 for complex tensors
    /// For im2col, this is equivalent to the kernel stride
    pub elem_stride: Strides,
    /// Interleave mode
    pub interleave: TensorMapInterleave,
    /// Swizzle mode
    pub swizzle: TensorMapSwizzle,
    /// Prefetch settings
    pub prefetch: TensorMapPrefetch,
    /// OOB fill value
    pub oob_fill: OobFill,
    /// Element type
    pub elem_ty: ElemType,
}

/// Specifieds the number of cubes to be dispatched for a kernel.
///
/// This translates to eg. a grid for CUDA, or to `num_workgroups` for wgsl.
#[allow(clippy::large_enum_variant)]
pub enum CubeCount {
    /// Dispatch a known count of x, y, z cubes.
    Static(u32, u32, u32),
    /// Dispatch an amount based on the values in this buffer. The buffer should contain a u32 array [x, y, z].
    Dynamic(BufferBinding),
}

/// Defines how to select cube count based on the number of cubes required.
pub enum CubeCountSelection {
    /// If the number of cubes is the same as required.
    Exact(CubeCount),
    /// If the number of cubes isn't the same as required.
    ///
    /// This can happen based on the hardware limit, requiring the kernel to perform OOB checks.
    Approx(CubeCount, u32),
}

impl CubeCountSelection {
    /// Creates a [`CubeCount`] while respecting the hardware limits.
    pub fn new(client: &Client, num_cubes: u32) -> Self {
        let cube_count = cube_count_spread(&client.properties().hardware.max_cube_count, num_cubes);

        let num_cubes_actual = cube_count[0] * cube_count[1] * cube_count[2];
        let cube_count = CubeCount::Static(cube_count[0], cube_count[1], cube_count[2]);

        match num_cubes_actual == num_cubes {
            true => CubeCountSelection::Exact(cube_count),
            false => CubeCountSelection::Approx(cube_count, num_cubes_actual),
        }
    }

    /// If some cubes will be idle.
    pub fn has_idle(&self) -> bool {
        matches!(self, Self::Approx(..))
    }

    /// Converts into [`CubeCount`].
    pub fn cube_count(self) -> CubeCount {
        match self {
            CubeCountSelection::Exact(cube_count) => cube_count,
            CubeCountSelection::Approx(cube_count, _) => cube_count,
        }
    }
}

impl From<CubeCountSelection> for CubeCount {
    fn from(value: CubeCountSelection) -> Self {
        value.cube_count()
    }
}

impl CubeCount {
    /// Create a new static cube count with the given x = y = z = 1.
    pub fn new_single() -> Self {
        CubeCount::Static(1, 1, 1)
    }

    /// Create a new static cube count with the given x, and y = z = 1.
    pub fn new_1d(x: u32) -> Self {
        CubeCount::Static(x, 1, 1)
    }

    /// Create a new static cube count with the given x and y, and z = 1.
    pub fn new_2d(x: u32, y: u32) -> Self {
        CubeCount::Static(x, y, 1)
    }

    /// Create a new static cube count with the given x, y and z.
    pub fn new_3d(x: u32, y: u32, z: u32) -> Self {
        CubeCount::Static(x, y, z)
    }

    /// Checks whether the cube count is definitely empty, i.e. has 0 dispatches.
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Static(x, y, z) => *x == 0 || *y == 0 || *z == 0,
            Self::Dynamic(_) => false,
        }
    }
}

impl Debug for CubeCount {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            CubeCount::Static(x, y, z) => f.write_fmt(format_args!("({x}, {y}, {z})")),
            CubeCount::Dynamic(_) => f.write_str("binding"),
        }
    }
}

impl Clone for CubeCount {
    fn clone(&self) -> Self {
        match self {
            Self::Static(x, y, z) => Self::Static(*x, *y, *z),
            Self::Dynamic(binding) => Self::Dynamic(binding.clone()),
        }
    }
}

#[derive(Debug, From, PartialEq, Eq, Clone, Copy, Hash, Deref, DerefMut)]
#[cfg_attr(serializable, derive(serde::Serialize, serde::Deserialize))]
#[allow(missing_docs)]
/// The number of units across all 3 axis totalling to the number of working units in a cube.
pub struct CubeDim(pub Dim3);

impl CubeDim {
    /// Creates a new [`CubeDim`] based on the maximum number of tasks that can be parellalized by units, in other words,
    /// by the maximum number of working units.
    ///
    /// # Notes
    ///
    /// For complex problems, you probably want to have your own logic function to create the
    /// [`CubeDim`], but for simpler problems such as elemwise-operation, this is a great default.
    pub fn new(client: &Client, working_units: usize) -> Self {
        let properties = client.properties();
        let plane_size = properties.hardware.plane_size_max;
        let plane_count = Self::calculate_plane_count_per_cube(
            working_units as u32,
            plane_size,
            properties.hardware.num_cpu_cores,
        );

        // Make sure it respects the max units per cube (especially on wasm)
        let limit = properties.hardware.max_units_per_cube / plane_size;

        // Ensure at least 1 plane so CubeDim is always valid (num_elems() > 0).
        Self::new_2d(plane_size, u32::min(limit, plane_count).max(1))
    }

    fn calculate_plane_count_per_cube(
        working_units: u32,
        plane_dim: u32,
        num_cpu_cores: Option<u32>,
    ) -> u32 {
        match num_cpu_cores {
            Some(num_cores) => core::cmp::min(num_cores, working_units),
            None => {
                let plane_count_max = core::cmp::max(1, working_units / plane_dim);

                // Ensures `plane_count` is a power of 2.
                const NUM_PLANE_MAX: u32 = 8u32;
                const NUM_PLANE_MAX_LOG2: u32 = NUM_PLANE_MAX.ilog2();
                let plane_count_max_log2 =
                    core::cmp::min(NUM_PLANE_MAX_LOG2, u32::ilog2(plane_count_max));
                2u32.pow(plane_count_max_log2)
            }
        }
    }

    /// Create a new cube dim with x = y = z = 1.
    pub const fn new_single() -> Self {
        Self(Dim3::new_single())
    }

    /// Create a new cube dim with the given x, and y = z = 1.
    pub const fn new_1d(x: u32) -> Self {
        Self(Dim3::new_1d(x))
    }

    /// Create a new cube dim with the given x and y, and z = 1.
    pub const fn new_2d(x: u32, y: u32) -> Self {
        Self(Dim3::new_2d(x, y))
    }

    /// Create a new cube dim with the given x, y and z.
    /// This is equivalent to the [new](CubeDim::new) function.
    pub const fn new_3d(x: u32, y: u32, z: u32) -> Self {
        Self(Dim3::new_3d(x, y, z))
    }

    /// Total numbers of units per cube
    pub const fn num_elems(&self) -> u32 {
        self.0.num_elems()
    }

    /// Whether this `CubeDim` can fully contain `other`
    pub const fn can_contain(&self, other: CubeDim) -> bool {
        self.0.can_contain(other.0)
    }
}

impl From<(u32, u32, u32)> for CubeDim {
    fn from(value: (u32, u32, u32)) -> Self {
        CubeDim::new_3d(value.0, value.1, value.2)
    }
}

impl From<CubeDim> for (u32, u32, u32) {
    fn from(val: CubeDim) -> Self {
        (val.x, val.y, val.z)
    }
}

impl From<CubeDim> for Dim3 {
    fn from(value: CubeDim) -> Self {
        value.0
    }
}

fn cube_count_spread(max: &(u32, u32, u32), num_cubes: u32) -> [u32; 3] {
    let max_cube_counts = [max.0, max.1, max.2];
    let mut num_cubes = [num_cubes, 1, 1];
    let base = 2;

    let mut reduce_count = |i: usize| {
        if num_cubes[i] <= max_cube_counts[i] {
            return true;
        }

        loop {
            num_cubes[i] = num_cubes[i].div_ceil(base);
            num_cubes[i + 1] *= base;

            if num_cubes[i] <= max_cube_counts[i] {
                return false;
            }
        }
    };

    for i in 0..2 {
        if reduce_count(i) {
            break;
        }
    }

    num_cubes
}

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

    /// A service for handles that never reach a device.
    fn service() -> cubecl_common::device::ServiceId {
        cubecl_common::device::ServiceId::of::<()>(cubecl_common::device::DeviceId::new(0, 0))
    }

    #[test_log::test]
    fn safe_num_cubes_even() {
        let max = (32, 32, 32);
        let required = 2048;

        let actual = cube_count_spread(&max, required);
        let expected = [32, 32, 2];
        assert_eq!(actual, expected);
    }

    #[test_log::test]
    fn safe_num_cubes_odd() {
        let max = (48, 32, 16);
        let required = 3177;

        let actual = cube_count_spread(&max, required);
        let expected = [25, 32, 4];
        assert_eq!(actual, expected);
    }

    /// The compiled kernel's answer drives both sets exactly, in resource
    /// order.
    #[test_log::test]
    fn buffer_io_drives_the_read_and_write_sets() {
        use crate::kernel::BufferIOAttr;
        use cubecl_environment::stream::StreamId;

        let stream = StreamId { value: 0 };
        let args = KernelArguments::new().with_buffers(vec![
            Handle::new(service(), stream, 8).binding(),
            Handle::new(service(), stream, 8).binding(),
            Handle::new(service(), stream, 8).binding(),
            Handle::new(service(), stream, 8).binding(),
        ]);
        let io = [
            BufferIOAttr::ReadOnly,
            BufferIOAttr::WriteOnly,
            BufferIOAttr::ReadWrite,
            BufferIOAttr::Dead,
        ];

        let written: Vec<_> = args.buffers_written(Some(&io)).collect();
        assert_eq!(written.len(), 2, "WriteOnly and ReadWrite are written");
        assert!(core::ptr::eq(written[0], args.buffers().nth(1).unwrap()));
        assert!(core::ptr::eq(written[1], args.buffers().nth(2).unwrap()));

        let read: Vec<_> = args.buffers_read(Some(&io)).collect();
        assert_eq!(read.len(), 2, "ReadOnly and ReadWrite are read");
        assert!(core::ptr::eq(read[0], args.buffers().next().unwrap()));
        assert!(core::ptr::eq(read[1], args.buffers().nth(2).unwrap()));
    }

    /// A poisoned device is the one failure a caller must not retry.
    ///
    /// Loading the next kernel is the case that matters most: it arrives as a
    /// compilation error, and read as a refusal it would have an autotuner
    /// quietly drop the candidate and try the next one on a dead device.
    #[test_log::test]
    fn poisoned_device_read_through_every_path() {
        use crate::server::{IoError, LaunchError};

        let poison = || DevicePoison {
            reason: String::from("cuEventSynchronize failed with status 700"),
            backtrace: Default::default(),
        };
        let poisoned = [
            ServerError::DevicePoisoned(poison()),
            ServerError::Launch(LaunchError::DevicePoisoned(poison())),
            ServerError::Launch(LaunchError::CompilationError(
                CompilationError::DevicePoisoned(poison()),
            )),
            ServerError::Io(IoError::DevicePoisoned(poison())),
            ServerError::Io(IoError::StorageMappingFailed {
                size: 1 << 20,
                source: alloc::boxed::Box::new(IoError::DevicePoisoned(poison())),
                backtrace: Default::default(),
            }),
        ];
        let refused =
            ServerError::Launch(LaunchError::CompilationError(CompilationError::Generic {
                reason: "no such intrinsic on this target".into(),
                backtrace: Default::default(),
            }));
        let transient = ServerError::Generic {
            reason: "the copy failed".into(),
            backtrace: Default::default(),
        };

        for error in &poisoned {
            assert!(error.is_device_poisoned(), "{error}");
            assert!(
                !error.is_refusal(),
                "a poisoned device is not a refusal: {error}"
            );
        }
        assert!(!refused.is_device_poisoned());
        assert!(!transient.is_device_poisoned());

        let unwritten = ServerError::Unwritten {
            failure: 1,
            claimed: 1,
            chain: Vec::new(),
            root: alloc::boxed::Box::new(poisoned[1].clone()),
            backtrace: Default::default(),
        };
        assert!(unwritten.is_device_poisoned());
        let group = ServerError::Several {
            errors: vec![refused, unwritten],
            backtrace: Default::default(),
        };
        assert!(group.is_device_poisoned());
        assert!(!group.is_refusal());
    }

    /// A refusal is the kernel being turned down, and nothing else is.
    ///
    /// The direction that matters is the false positive: a harness that takes
    /// a device fault for a refusal reports a broken run as a skipped one, and
    /// the test goes green. So a group answers yes only when every root does.
    #[test_log::test]
    fn only_a_refused_kernel_reads_as_a_refusal() {
        use crate::server::{LaunchError, ResourceLimitError};

        let refused =
            ServerError::Launch(LaunchError::CompilationError(CompilationError::Generic {
                reason: "no such intrinsic on this target".into(),
                backtrace: Default::default(),
            }));
        let over_budget = ServerError::Launch(LaunchError::TooManyResources(
            ResourceLimitError::SharedMemory {
                requested: 1 << 20,
                max: 1 << 15,
                backtrace: Default::default(),
            },
        ));
        let fault = ServerError::Generic {
            reason: "the device faulted".into(),
            backtrace: Default::default(),
        };

        let panicked = ServerError::Launch(LaunchError::CompilationError(
            CompilationError::ExpansionPanicked {
                kernel: "kernel".into(),
                message: "an assertion failed".into(),
                backtrace: Default::default(),
            },
        ));

        assert!(refused.is_refusal());
        assert!(over_budget.is_refusal());
        assert!(!fault.is_refusal(), "a fault is not a refusal");
        assert!(
            !panicked.is_refusal(),
            "a kernel that panicked while expanding is a defect, not a refusal"
        );

        // A read reports the failure that stopped the buffer's writer, so the
        // question has to reach through the report to the root.
        let unwritten = |root: &ServerError| ServerError::Unwritten {
            failure: 1,
            claimed: 1,
            chain: Vec::new(),
            root: alloc::boxed::Box::new(root.clone()),
            backtrace: Default::default(),
        };
        assert!(unwritten(&refused).is_refusal());
        assert!(!unwritten(&fault).is_refusal());
        assert!(!unwritten(&panicked).is_refusal());

        let group = |errors: Vec<ServerError>| ServerError::Several {
            errors,
            backtrace: Default::default(),
        };
        assert!(group(vec![unwritten(&refused), unwritten(&over_budget)]).is_refusal());
        assert!(
            !group(vec![unwritten(&refused), unwritten(&fault)]).is_refusal(),
            "one real failure among refusals is still a real failure"
        );
        assert!(
            !group(Vec::new()).is_refusal(),
            "an empty group refuses nothing"
        );
    }

    /// Every fallback over-names: a kernel the compiler kept no answer for,
    /// and a resource past what the answer covers, read as both read and
    /// written. Naming a buffer the kernel only read fails a read that would
    /// have been fine, loudly; missing one it writes hands back the bytes
    /// that were there before, silently.
    #[test_log::test]
    fn missing_io_reads_as_everything_read_and_written() {
        use crate::kernel::BufferIOAttr;
        use cubecl_environment::stream::StreamId;

        let stream = StreamId { value: 0 };
        let args = KernelArguments::new().with_buffers(vec![
            Handle::new(service(), stream, 8).binding(),
            Handle::new(service(), stream, 8).binding(),
        ]);

        assert_eq!(args.buffers_written(None).count(), 2);
        assert_eq!(args.buffers_read(None).count(), 2);

        let short = [BufferIOAttr::Dead];
        assert_eq!(
            args.buffers_written(Some(&short)).count(),
            1,
            "the uncovered resource reads as written"
        );
        assert_eq!(args.buffers_read(Some(&short)).count(), 1);
    }

    /// The caller's declaration answers when the compiled kernel kept none —
    /// which is what a launch that fails to compile falls back on, so it
    /// taints only its declared outputs — and the compiled answer still wins
    /// where it exists, since only the visibility analysis can prove a buffer
    /// write-only or dead.
    #[test_log::test]
    fn declared_io_answers_when_the_compiled_kernel_kept_none() {
        use crate::kernel::BufferIOAttr;
        use cubecl_environment::stream::StreamId;

        let stream = StreamId { value: 0 };
        let args = KernelArguments::new()
            .with_buffer_io(
                Handle::new(service(), stream, 8).binding(),
                BufferIOAttr::ReadOnly,
            )
            .with_buffer_io(
                Handle::new(service(), stream, 8).binding(),
                BufferIOAttr::ReadOnly,
            )
            .with_buffer_io(
                Handle::new(service(), stream, 8).binding(),
                BufferIOAttr::WriteOnly,
            );

        // No compiled answer: the declaration decides. The inputs are not
        // written, so a failed compile leaves them readable.
        let written: Vec<_> = args.buffers_written(None).collect();
        assert_eq!(written.len(), 1, "only the declared output is written");
        assert!(core::ptr::eq(written[0], args.buffers().nth(2).unwrap()));
        assert_eq!(args.buffers_read(None).count(), 2);

        // A compiled answer overrides the declaration where it has one and
        // falls back to it where it does not.
        let compiled = [BufferIOAttr::ReadWrite];
        let written: Vec<_> = args.buffers_written(Some(&compiled)).collect();
        assert_eq!(written.len(), 2, "compiled ReadWrite plus declared output");
        assert!(core::ptr::eq(written[0], args.buffers().next().unwrap()));
        assert!(core::ptr::eq(written[1], args.buffers().nth(2).unwrap()));
    }

    /// Declarations stay on the resource they were made for when declared and
    /// undeclared resources mix, and the undeclared ones keep the loud
    /// fallback.
    #[test_log::test]
    fn an_undeclared_resource_among_declared_ones_over_names() {
        use crate::kernel::BufferIOAttr;
        use cubecl_environment::stream::StreamId;

        let stream = StreamId { value: 0 };
        let args = KernelArguments::new()
            .with_buffer(Handle::new(service(), stream, 8).binding())
            .with_buffer_io(
                Handle::new(service(), stream, 8).binding(),
                BufferIOAttr::ReadOnly,
            );

        let written: Vec<_> = args.buffers_written(None).collect();
        assert_eq!(written.len(), 1, "the undeclared resource reads as written");
        assert!(core::ptr::eq(written[0], args.buffers().next().unwrap()));
        assert_eq!(args.buffers_read(None).count(), 2);
    }
}