many_cpus 2.4.0

Efficiently schedule work and inspect the hardware environment on many-processor systems
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
use std::hint::black_box;
use std::mem::offset_of;
use std::num::NonZero;
use std::ptr::NonNull;
use std::sync::OnceLock;

use folo_ffi::NativeBuffer;
use itertools::Itertools;
use nonempty::NonEmpty;
use smallvec::SmallVec;
use windows::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
use windows::Win32::System::JobObjects::{
    JOB_OBJECT_CPU_RATE_CONTROL_ENABLE, JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP,
    JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE, JOBOBJECT_CPU_RATE_CONTROL_INFORMATION,
};
use windows::Win32::System::SystemInformation::{
    GROUP_AFFINITY, LOGICAL_PROCESSOR_RELATIONSHIP, RelationNumaNode, RelationNumaNodeEx,
    RelationProcessorCore, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX,
};
use windows::core::HRESULT;

use crate::pal::windows::{Bindings, BindingsFacade, ProcessorGroupIndex, ProcessorIndexInGroup};
use crate::pal::{GroupMask, Platform, ProcessorFacade, ProcessorImpl};
use crate::{EfficiencyClass, MemoryRegionId, ProcessorId};

/// Singleton instance of `BuildTargetPlatform`, used by public API types
/// to hook up to the correct PAL implementation.
pub static BUILD_TARGET_PLATFORM: BuildTargetPlatform =
    BuildTargetPlatform::new(BindingsFacade::target());

const PROCESSOR_GROUP_MAX_SIZE: usize = 64;

// Some of our logic will operate without heap allocations as long as the group count is not higher.
const ALLOC_FREE_GROUPS_MAX: usize = 8;

/// The platform that matches the crate's build target.
///
/// You would only use a different platform in unit tests that need to mock the platform.
/// Even then, whenever possible, unit tests should use the real platform for maximum realism.
#[derive(Debug)]
pub struct BuildTargetPlatform {
    bindings: BindingsFacade,

    max_processor_id: OnceLock<ProcessorId>,

    active_processor_count: OnceLock<NonZero<usize>>,

    // We cache these as we expect them to never change. This data is in non-local memory in
    // systems with multiple memory regions, which is not ideal but the bookkeeping to make it
    // local is also not really better. `#[thread_local]` might help but is currently unstable.
    // All these group arrays are indexed by group index.
    group_max_count: OnceLock<ProcessorGroupIndex>,
    group_max_sizes: OnceLock<Box<[ProcessorIndexInGroup]>>,
    group_active_sizes: OnceLock<Box<[ProcessorIndexInGroup]>>,
    group_start_offsets: OnceLock<Box<[ProcessorId]>>,

    // Combines some of the above information to make it easier to work with.
    group_metas: OnceLock<Box<[ProcessorGroupMeta]>>,
}

#[derive(Debug)]
struct ProcessorGroupMeta {
    max_processors: ProcessorIndexInGroup,
    active_processors: ProcessorIndexInGroup,

    start_offset: ProcessorId,

    // All the theoretical processor IDs, including processors that are offline.
    // Sorted by value, ascending.
    all_processor_ids: Vec<ProcessorId>,

    // All the processor IDs of active processors, without those that are not offline.
    // This is not the same as "available" processors because the operating system
    // resource constraint mechanisms may limit the set we can actually use further.
    // Sorted by value, ascending.
    active_processor_ids: Vec<ProcessorId>,
}

impl Platform for BuildTargetPlatform {
    fn get_all_processors(&self) -> NonEmpty<ProcessorFacade> {
        let group_metas = self.get_processor_group_metas();

        let efficiency_classes = self.get_processor_efficiency_classes();
        let memory_regions = self.get_processor_memory_regions();
        let allowed_processors = self.processors_allowed_by_job_constraints();

        // We are required to return all the processors ordered by the processor ID.
        // As we know that Windows assigns processor IDs sequentially, we can just
        // iterate in order through the groups and each processor in each group.
        NonEmpty::collect(group_metas.iter().enumerate()
            .flat_map(move |(group_index, meta)| {
                meta.active_processor_ids.iter().map(move |&processor_id| {
                    let index_in_group = processor_id
                        .checked_sub(meta.start_offset)
                        .and_then(|x| u8::try_from(x).ok())
                        .expect(
                        "processor ID calculation overflowed - platform must have given us bad inputs",
                    );

                    (group_index, index_in_group, processor_id)
                })
            })
            .filter_map(|(group_index, index_in_group, processor_id)| {
                if !allowed_processors.contains(&processor_id) {
                    return None;
                }

                let memory_region_index = *memory_regions
                    .get(processor_id as usize)
                    .expect("we expect to have the memory region for every processor ID unless the platform lied to us at some point");

                let efficiency_class = *efficiency_classes.get(processor_id as usize).expect("we expect to have the efficiency class for every processor ID unless the platform lied to us at some point");

                Some(ProcessorImpl::new(
                    group_index
                        .try_into()
                        .expect("group index can only overflow if our algorithm has a logic error"),
                    index_in_group,
                    processor_id,
                    memory_region_index,
                    efficiency_class
                ))
            })
        ).expect(
            "we are returning all processors on the system - obviously there must be at least one",
        ).map(ProcessorFacade::Target)
    }

    fn pin_current_thread_to<P>(&self, processors: &NonEmpty<P>)
    where
        P: AsRef<ProcessorFacade>,
    {
        let group_count = self.get_processor_group_max_count();

        // We define one mask per processor group, even if that mask is all clear,
        // to ensure that we overwrite any previous state that may have existed.
        let mut affinity_masks = SmallVec::<[GROUP_AFFINITY; ALLOC_FREE_GROUPS_MAX]>::new();

        for group_index in 0..group_count {
            let mut mask = GroupMask::none();

            // We started with all bits clear and now set any that we do want to allow.
            for processor in processors
                .iter()
                .filter(|p| p.as_ref().as_target().group_index == group_index)
            {
                mask.add(processor.as_ref().as_target());
            }

            affinity_masks.push(GROUP_AFFINITY {
                Group: group_index,
                Mask: mask.value(),
                ..Default::default()
            });
        }

        self.bindings
            .set_current_thread_cpu_set_masks(&affinity_masks);
    }

    fn current_processor_id(&self) -> ProcessorId {
        let current_processor = self.bindings.get_current_processor_number_ex();

        let group_start_offsets = self.get_processor_group_start_offsets();

        let group_start_offset = *group_start_offsets
            .get(current_processor.Group as usize)
            .expect("the platform told us how many groups exist, so if it now tells us an out of bounds group, nothing we can do");

        group_start_offset
            .checked_add(ProcessorId::from(current_processor.Number))
            .expect("processor ID calculation overflowed - only possible if platform gives us bad IDs as inputs")
    }

    fn max_processor_id(&self) -> ProcessorId {
        *self.max_processor_id.get_or_init(|| {
            let group_max_sizes = self.get_processor_group_max_sizes();

            // Windows assigns processor IDs sequentially from 0, so we just calculate.
            // The max processor ID is the sum of all processors in all groups minus 1.
            group_max_sizes
                .iter()
                .map(|&s| ProcessorId::from(s))
                .sum::<ProcessorId>()
                .checked_sub(1)
                .expect("there must be at least 1 theoretical processor in each group")
        })
    }

    fn max_memory_region_id(&self) -> MemoryRegionId {
        self.bindings.get_numa_highest_node_number()
    }

    fn current_thread_processors(&self) -> NonEmpty<ProcessorId> {
        let mut current_thread_affinities = self.bindings.get_current_thread_cpu_set_masks();

        // A thread may have no masks defined, in which case it will inherit from the process.
        // Note that the process mask is ignored if a thread mask is set.
        if current_thread_affinities.is_empty() {
            current_thread_affinities = self.bindings.get_current_process_default_cpu_set_masks();
        }

        // A process may also have no mask defined! In this case, we check the legacy mechanisms
        // used before Windows was many-processor aware. While this crate never uses this mechanism
        // to **set** limits, we may still inherit such limits from e.g. "start /affinity".
        if current_thread_affinities.is_empty() {
            let legacy_affinities = self.bindings.get_current_thread_legacy_group_affinity();

            // The challenge here is that this always returns some data - the legacy affinity is
            // always *something*, unlike the CPU sets feature which is only present when customized
            // which means that even if the platform wants to apply no limits, there is a value and
            // we must detect the default value to ignore it here. This is important because the
            // legacy mechanism is only capable of affinitizing to a single processor group, so if
            // we obey its default value, we would inadvertently follow that limitation.
            //
            // Therefore, we apply the following heuristic: if the mask is set to a value that
            // allows all processors in this processor group, we consider it a default value and
            // pretend it does not exist, allowing the thread to run on all processors in all
            // processor groups.
            let group_max_sizes = self.get_processor_group_max_sizes();

            // TODO: Does the default mask contain all bits for max or active processors?
            let default_mask_processor_count = *group_max_sizes
                .get(legacy_affinities.Group as usize)
                .expect("platform referenced a processor group that was out of bounds");

            let is_default_mask =
                legacy_affinities.Mask.count_ones() == u32::from(default_mask_processor_count);

            if !is_default_mask {
                // Found a non-default legacy affinity mask, so we use it.
                current_thread_affinities = vec![legacy_affinities];
            }
        }

        // If the legacy mechanism also says nothing (== was at its default value)
        // then the current thread may use all processors in all memory regions.
        if current_thread_affinities.is_empty() {
            // Note that we also include offline processors here because this function
            // does not know or need to know which ones are active and which are not, as
            // this list is only used as input for further processing upstream.
            // Any inactive processors will be filtered out by the caller later.
            return NonEmpty::collect(0..=self.max_processor_id())
                .expect("range over non-empty set cannot result in empty result");
        }

        let group_metas = self.get_processor_group_metas();

        NonEmpty::collect(group_metas.iter().enumerate()
            .filter_map(move |(group_index, meta)| {
                let Some(affinity_mask) = current_thread_affinities.iter().find_map(|a| {
                    if usize::from(a.Group) == group_index {
                        Some(a.Mask)
                    } else {
                        None
                    }
                }) else {
                    // Depending on how we obtained the per-group affinity masks, it may in theory
                    // be possible that we do not have an affinity mask for some group. In that
                    // case we consider the group off-limits and skip it.
                    return None;
                };

                let mask = GroupMask::from_components(
                    affinity_mask,
                    ProcessorGroupIndex::try_from(group_index)
                        .expect("platform gave us processor group index that was out of bounds"),
                );

                Some((0..meta.max_processors).filter_map(move |index_in_group| {
                    if mask.contains_by_index_in_group(index_in_group) {
                        Some(
                            *meta
                                .all_processor_ids
                                .get(index_in_group as usize)
                                .expect("we validated the bounds above"),
                        )
                    } else {
                        None
                    }
                }))
            }).flatten()
        ).expect("we are returning the set of processors assigned to the current thread - obviously there must be at least one because the thread is executing")
    }

    fn max_processor_time(&self) -> f64 {
        // The job object processor time limits are relative to the total number of
        // active processors on the system and do not consider any per-process limitations.
        #[expect(clippy::cast_precision_loss, reason = "value is always in safe range")]
        let system_processor_count = self.active_processor_count() as f64;

        // This API, however, speaks in terms of processor time available to the current process,
        // so we do need to care about per-process limitations. Whatever value we return, it
        // cannot be greater than this because this is the upper limit available to the process.
        #[expect(
            clippy::cast_precision_loss,
            reason = "precision loss will never happen because all realistic values are in safe f64 range"
        )]
        let current_process_processor_count = self.get_all_processors().len() as f64;

        let Some(rate_control) = self.bindings.get_current_job_cpu_rate_control() else {
            // No rate control, so we can use all processors available to the current process.
            return current_process_processor_count;
        };

        // There are different rate control modes. We care about the following:
        // 1. Hard cap, which just gives us a single number.
        // 2. Soft cap (guaranteed + ceiling), in which case we use the ceiling.
        // Other modes (e.g. weighted) we ignore because they cannot be expressed in absolutes.
        if is_hard_capped(rate_control) {
            // SAFETY: Guarded by the flags we validated.
            let windows_cpu_rate = unsafe { rate_control.Anonymous.CpuRate };

            Self::windows_processor_rate_to_processor_time(windows_cpu_rate, system_processor_count)
                .min(current_process_processor_count)
        } else if is_soft_capped(rate_control) {
            // SAFETY: Guarded by the flags we validated.
            let windows_cpu_rate = unsafe { rate_control.Anonymous.Anonymous.MaxRate };

            Self::windows_processor_rate_to_processor_time(
                windows_cpu_rate.into(),
                system_processor_count,
            )
            .min(current_process_processor_count)
        } else {
            // Found no limits, fall back to our internally detected ceiling.
            current_process_processor_count
        }
    }

    fn active_processor_count(&self) -> usize {
        self.active_processor_count
            .get_or_init(|| {
                let group_active_sizes = self.get_processor_group_active_sizes();

                NonZero::new(
                    group_active_sizes
                        .iter()
                        .map(|&s| usize::from(s))
                        .sum::<usize>(),
                )
                .expect("a system with 0 active processors is impossible")
            })
            .get()
    }
}

impl BuildTargetPlatform {
    pub(crate) const fn new(bindings: BindingsFacade) -> Self {
        Self {
            bindings,
            group_max_count: OnceLock::new(),
            group_max_sizes: OnceLock::new(),
            group_active_sizes: OnceLock::new(),
            group_start_offsets: OnceLock::new(),
            max_processor_id: OnceLock::new(),
            group_metas: OnceLock::new(),
            active_processor_count: OnceLock::new(),
        }
    }

    #[must_use]
    fn get_processor_group_max_count(&self) -> ProcessorGroupIndex {
        *self
            .group_max_count
            .get_or_init(|| self.bindings.get_maximum_processor_group_count())
    }

    #[must_use]
    fn max_processor_count(&self) -> usize {
        (self.max_processor_id() as usize).checked_add(1)
            .expect("this could only overflow if the platform has usize::MAX processors, which is unrealistic")
    }

    /// Returns the max number of processors in each processor group, ordered ascending
    /// by group index. This is used to calculate the global index of a processor and/or
    /// the start offset of each processor group.
    #[must_use]
    fn get_processor_group_max_sizes(&self) -> &[u8] {
        self.group_max_sizes.get_or_init(|| {
            let group_count = self.get_processor_group_max_count();

            let mut group_sizes = Vec::with_capacity(group_count as usize);

            for group_index in 0..group_count {
                let processor_count = self.bindings.get_maximum_processor_count(group_index);

                let processor_count = u8::try_from(processor_count)
                    .expect("somehow encountered processor group with more than 256 processors, which is impossible as per Windows API - the max is 64");

                group_sizes.push(processor_count);
            }

            group_sizes.into_boxed_slice()
        })
    }

    /// Returns the max number of active in each processor group, ordered ascending
    /// by group index.
    #[must_use]
    fn get_processor_group_active_sizes(&self) -> &[u8] {
        self.group_active_sizes.get_or_init(|| {
            let group_count = self.get_processor_group_max_count();

            let mut group_sizes = Vec::with_capacity(group_count as usize);

            for group_index in 0..group_count {
                let processor_count = self.bindings.get_active_processor_count(group_index);

                let processor_count = u8::try_from(processor_count)
                    .expect("somehow encountered processor group with more than 256 processors, which is impossible as per Windows API - the max is 64");

                group_sizes.push(processor_count);
            }

            group_sizes.into_boxed_slice()
        })
    }

    #[must_use]
    fn get_processor_group_start_offsets(&self) -> &[ProcessorId] {
        self.group_start_offsets.get_or_init(|| {
            let group_sizes = self.get_processor_group_max_sizes();

            let mut group_offsets = Vec::with_capacity(group_sizes.len());

            let mut group_start_offset: ProcessorId = 0;
            for &size in group_sizes {
                group_offsets.push(group_start_offset);
                group_start_offset = group_start_offset.checked_add(ProcessorId::from(size))
                    .expect("processor group start offset overflowed - this is only possible if the platform have us bad inputs");
            }

            group_offsets.into_boxed_slice()
        })
    }

    #[must_use]
    fn get_processor_group_metas(&self) -> &[ProcessorGroupMeta] {
        self.group_metas.get_or_init(|| {
            let max_sizes = self.get_processor_group_max_sizes();
            let active_sizes = self.get_processor_group_active_sizes();
            let start_offsets = self.get_processor_group_start_offsets();

            assert_eq!(
                max_sizes.len(),
                start_offsets.len(),
                "platform must provide group sizes and offsets in equal amounts",
            );

            assert_eq!(
                max_sizes.len(),
                active_sizes.len(),
                "platform must provide group sizes and active sizes in equal amounts",
            );

            let mut group_metas = Vec::with_capacity(max_sizes.len());

            for ((group_index, &max_size), &start_offset) in max_sizes.iter().enumerate().zip(start_offsets.iter()) {
                let active_size = *active_sizes
                    .get(group_index)
                    .expect("we validated bounds above");

                let active_id_end = start_offset
                    .checked_add(ProcessorId::from(active_size))
                    .expect("processor ID calculation overflowed - platform must have given us invalid inputs");

                let all_id_end = start_offset
                    .checked_add(ProcessorId::from(max_size))
                    .expect("processor ID calculation overflowed - platform must have given us invalid inputs");

                group_metas.push(ProcessorGroupMeta {
                    max_processors: max_size,
                    active_processors: active_size,
                    start_offset,
                    active_processor_ids: (start_offset..active_id_end).collect_vec(),
                    all_processor_ids: (start_offset..all_id_end).collect_vec(),
                });
            }

            group_metas.into_boxed_slice()
        })
    }

    #[must_use]
    fn get_logical_processor_information_raw(
        &self,
        relationship: LOGICAL_PROCESSOR_RELATIONSHIP,
    ) -> NativeBuffer<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX> {
        loop {
            let mut required_length: u32 = 0;

            // SAFETY: Pointers must outlive the call (true - local variable lives beyond call).
            let probe_result = unsafe {
                self.bindings.get_logical_processor_information_ex(
                    relationship,
                    None,
                    &raw mut required_length,
                )
            };
            let e = probe_result.expect_err("GetLogicalProcessorInformationEx with null buffer must always fail and return required buffer size");
            assert_eq!(
                e.code(),
                HRESULT::from_win32(ERROR_INSUFFICIENT_BUFFER.0),
                "GetLogicalProcessorInformationEx size probe failed with unexpected error code {e}",
            );

            let required_length_usize = NonZero::<usize>::new(required_length as usize).expect(
                "GetLogicalProcessorInformationEx size probe said 0 bytes are needed - impossible",
            );
            let mut buffer =
                NativeBuffer::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>::new(required_length_usize);
            let mut final_length = required_length;

            // SAFETY: Pointers must outlive the call (true - local variables live beyond call).
            let real_result = unsafe {
                self.bindings.get_logical_processor_information_ex(
                    relationship,
                    Some(buffer.as_ptr().as_ptr()),
                    &raw mut final_length,
                )
            };

            // In theory, it could still have failed with "insufficient buffer" because the set of
            // processors available to us can change at any time. Super unlikely but let us be safe.
            match check_logical_processor_info_result(&real_result) {
                LogicalProcessorInfoResult::Retry => continue,
                LogicalProcessorInfoResult::Proceed => {}
            }

            // Signal the buffer that we wrote into it.
            // SAFETY: We must be sure that the specified number of bytes have actually been written.
            // We are sure, obviously, because the operating system just told us it did that.
            unsafe {
                buffer.set_len_bytes(final_length as usize);
            }

            return buffer;
        }
    }

    /// Gets the efficiency classes of all processors on the system, ordered by processor ID.
    /// This also returns data for offline processors but the value for those is unspecified.
    fn get_processor_efficiency_classes(&self) -> Box<[EfficiencyClass]> {
        let mut native_efficiency_classes: Vec<u8> = vec![0; self.max_processor_count()];

        let core_relationships_raw =
            self.get_logical_processor_information_raw(RelationProcessorCore);

        // We create a map of processor index to efficiency class. Then we simply take all
        // processors with the max efficiency class (whatever the numeric value) - those are the
        // performance processors.

        // The structures returned by the OS are dynamically sized so we only have various
        // disgusting options for parsing/processing them. Pointer wrangling is the most readable.
        let raw_range = core_relationships_raw.as_data_ptr_range();
        let mut next: NonNull<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX> = raw_range.start.cast();
        let end = raw_range.end.cast();

        while next < end {
            // SAFETY: We just process the data in the form the OS promises to give it to us.
            let info = unsafe { next.as_ref() };

            // SAFETY: We just process the data in the form the OS promises to give it to us.
            next = unsafe { next.byte_add(info.Size as usize) };

            assert_eq!(info.Relationship, RelationProcessorCore);

            // SAFETY: Guarded via info.Relationship, asserted above.
            let details = unsafe { &info.Anonymous.Processor };

            // API docs: If the PROCESSOR_RELATIONSHIP structure represents a processor core,
            // the GroupCount member is always 1.
            assert_eq!(details.GroupCount, 1);

            // There may be 1 or more bits set in the mask because one core might have multiple
            // logical processors via SMT (hyper-threading). We just iterate over all the bits
            // to check them individually without worrying about SMT logic.
            for processor_id in self.affinity_mask_to_processor_ids(&details.GroupMask[0]) {
                *native_efficiency_classes.get_mut(processor_id as usize)
                    .expect("the platform gave us a processor ID that was out of the range of valid processor IDs - it lied about the max ID!") = details.EfficiencyClass;
            }
        }

        let max_native_efficiency_class = native_efficiency_classes.iter().max().copied().expect(
            "there must be at least one processor - this code is running on one, after all",
        );

        native_efficiency_classes
            .into_iter()
            .map(|native| {
                if native == max_native_efficiency_class {
                    EfficiencyClass::Performance
                } else {
                    EfficiencyClass::Efficiency
                }
            })
            .collect_vec()
            .into_boxed_slice()
    }

    /// Gets the efficiency classes of all processors on the system, ordered by processor ID.
    /// This also returns data for offline processors.
    #[must_use]
    #[cfg_attr(test, mutants::skip)] // Mutating this can lead to non-deterministic looping as mutations can violate memory safety. We could define a safer iterator abstraction but it hardly seems worth it.
    fn get_processor_memory_regions(&self) -> Box<[MemoryRegionId]> {
        // TODO: Verify that this returns correct data for offline processors.
        let memory_region_relationships_raw =
            self.get_logical_processor_information_raw(RelationNumaNodeEx);

        let mut result = vec![0; self.max_processor_count()];

        // The structures returned by the OS are dynamically sized so we only have various
        // disgusting options for parsing/processing them. Pointer wrangling is the most readable.
        let raw_range = memory_region_relationships_raw.as_data_ptr_range();
        let mut next: NonNull<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX> = raw_range.start.cast();
        let end = raw_range.end.cast();

        while next < end {
            let current = next;

            // SAFETY: We just process the data in the form the OS promises to give it to us.
            let info = unsafe { current.as_ref() };

            // SAFETY: We just process the data in the form the OS promises to give it to us.
            next = unsafe { next.byte_add(info.Size as usize) };

            // Even though we request NumaNodeEx, it returns entries with NumaNode. It just does.
            // It always does, asking for Ex simply allows it to return multiple processor groups
            // for the same NUMA node (instead of just the primary group as with plain NumaNode).
            assert_eq!(info.Relationship, RelationNumaNode);

            // SAFETY: Guarded via info.Relationship, asserted above.
            let details = unsafe { &info.Anonymous.NumaNode };

            let numa_node_number = details.NodeNumber;

            // In the struct definition, this is a 1-element array because Rust has no notion
            // of dynamic-size arrays. We use pointer arithmetic to access the real array elements.
            //
            // NOTE: that we need to start from scratch with the original pointer here!
            // Pointer -> shared ref -> pointer conversions are not guaranteed to return the
            // original pointer, so if we get rid of a pointer once, we cannot get it back!
            //
            // SAFETY: RelationNumaNodeEx guarantees that this union member is present.
            let mut group_mask_array = unsafe {
                current
                    .byte_add(offset_of!(
                        SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX,
                        Anonymous.NumaNode.Anonymous.GroupMask
                    ))
                    .cast::<GROUP_AFFINITY>()
            };

            for _ in 0..details.GroupCount {
                // SAFETY: The OS promises us that this array contains `GroupCount` elements.
                let affinity = unsafe { *group_mask_array.as_ref() };

                for processor_id in self.affinity_mask_to_processor_ids(&affinity) {
                    *result.get_mut(processor_id as usize)
                        .expect("the platform gave us a processor ID that was out of the range of valid processor IDs - it lied about the max ID!") = numa_node_number;
                }

                // SAFETY: The OS promises us that this array contains `GroupCount` elements.
                // It is fine to move past the end if we never access it (because the loop ends).
                group_mask_array = unsafe { group_mask_array.add(1) };
            }
        }

        result.into_boxed_slice()
    }

    #[must_use]
    fn affinity_mask_to_processor_ids(
        &self,
        affinity: &GROUP_AFFINITY,
    ) -> heapless::Vec<ProcessorId, PROCESSOR_GROUP_MAX_SIZE> {
        let mut result = heapless::Vec::new();

        let group_index: ProcessorGroupIndex = affinity.Group;

        let meta = self.get_processor_group_metas().get(group_index as usize).expect(
            "platform indicated a processor group that was out of range of known processor groups",
        );

        // Minimum effort approach for WOW64 support - we only see the first 32 in a group.
        let processors_in_group = meta
            .active_processors
            .min(u8::try_from(usize::BITS).expect("constant that always fits into u8"));

        let mask = GroupMask::from_components(affinity.Mask, affinity.Group);

        for index_in_group in 0..processors_in_group {
            if !mask.contains_by_index_in_group(index_in_group) {
                continue;
            }

            result.push(*meta.all_processor_ids.get(index_in_group as usize).expect(
                "internal conflict between processor group metadata - expected ID not found",
            )).expect("result could only be full if we somehow processed more than PROCESSOR_GROUP_MAX_SIZE processors, which is nonsense");
        }

        result
    }

    /// The job object (if it exists) defines hard limits for what processors we are allowed to use.
    /// If there is no limit defined, we allow all processors and return all processor IDs.
    #[must_use]
    fn processors_allowed_by_job_constraints(&self) -> NonEmpty<ProcessorId> {
        let job_affinity_masks = self.bindings.get_current_job_cpu_set_masks();

        if job_affinity_masks.is_empty() {
            return NonEmpty::collect(0..=self.max_processor_id())
                .expect("range over non-empty set cannot result in empty result");
        }

        let group_metas = self.get_processor_group_metas();

        NonEmpty::collect(group_metas
            .iter()
            .enumerate()
            .filter_map(|(group_index, meta)| {
                job_affinity_masks.iter().find_map(|a| {
                    if usize::from(a.Group) == group_index {
                        Some((a.Mask, group_index, meta))
                    } else {
                        // This group was not a member of the defined affinity mask, so we
                        // do not care about this group and do not consider it allowed.
                        None
                    }
                })
            })
            .flat_map(|(mask, group_index, meta)| {
                let mask = GroupMask::from_components(
                    mask,
                    ProcessorGroupIndex::try_from(group_index)
                        .expect("platform gave us processor group index that was out of bounds"),
                );

                (0..meta.max_processors).filter_map(move |index_in_group| {
                    if mask.contains_by_index_in_group(index_in_group) {
                        Some(meta.start_offset
                            .checked_add(ProcessorId::from(index_in_group))
                            .expect("processor ID calculation overflowed - platform must have given us bad inputs"))
                    } else {
                        None
                    }
                })
            }))
            .expect("we are returning the set of processors assigned to the current thread - obviously there must be at least one because the thread is executing")
    }

    /// Windows measures processor time in 1/100 of a percent (10000 = 100%) of the total available
    /// processor time available on the system, ignoring any per-process maximums and not counting
    /// offline processors.
    ///
    /// We measure time in seconds of processor time per second of real time.
    ///
    /// This converts from Windows to our internal representation.
    fn windows_processor_rate_to_processor_time(
        windows_rate: u32,
        system_processor_count: f64,
    ) -> f64 {
        // Get the ratio of processor time on all processors on the system.
        // 1 means the process can use all processor time on the system (if not otherwise limited).
        let cpu_ratio = f64::from(windows_rate) / 10_000.0;

        cpu_ratio * system_processor_count
    }

    // Exposed for benchmarking only, not part of public API surface.
    #[must_use]
    #[cfg_attr(test, mutants::skip)] // Just for benchmarking, not real code.
    pub fn __private_current_thread_processors(&self) -> NonEmpty<ProcessorId> {
        self.current_thread_processors()
    }

    // Exposed for benchmarking only, not part of public API surface.
    #[must_use]
    #[cfg_attr(test, mutants::skip)] // Just for benchmarking, not real code.
    pub fn __private_affinity_mask_to_processor_id(
        &self,
        mask: &GROUP_AFFINITY,
    ) -> heapless::Vec<ProcessorId, PROCESSOR_GROUP_MAX_SIZE> {
        self.affinity_mask_to_processor_ids(mask)
    }

    // Exposed for benchmarking only, not part of public API surface.
    #[cfg_attr(test, mutants::skip)] // Just for benchmarking, not real code.
    pub fn __private_get_all_processors(&self) {
        black_box(self.get_all_processors());
    }
}

#[cfg_attr(test, mutants::skip)] // No-op mutates the constant, not helpful.
fn is_hard_capped(rate_control: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION) -> bool {
    const HARD_CAP_FLAGS: u32 =
        JOB_OBJECT_CPU_RATE_CONTROL_ENABLE.0 | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP.0;

    rate_control.ControlFlags.0 & HARD_CAP_FLAGS == HARD_CAP_FLAGS
}

#[cfg_attr(test, mutants::skip)] // No-op mutates the constant, not helpful.
fn is_soft_capped(rate_control: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION) -> bool {
    const SOFT_CAP_FLAGS: u32 =
        JOB_OBJECT_CPU_RATE_CONTROL_ENABLE.0 | JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE.0;

    rate_control.ControlFlags.0 & SOFT_CAP_FLAGS == SOFT_CAP_FLAGS
}

/// Result of checking the outcome of `GetLogicalProcessorInformationEx`.
enum LogicalProcessorInfoResult {
    /// The caller should retry the call because the buffer size changed.
    Retry,
    /// The call succeeded and the caller should proceed with processing the data.
    Proceed,
}

/// Checks the result of `GetLogicalProcessorInformationEx` and returns the action to take.
///
/// Panics if the call failed with an unexpected error.
// Excluded from coverage because:
// 1. The retry path requires the processor set to change between size probe and actual call,
//    which is extremely rare and impractical to test.
// 2. The panic path requires an OS-level failure that is unrealistic to trigger.
#[cfg_attr(coverage_nightly, coverage(off))]
fn check_logical_processor_info_result(
    result: &windows::core::Result<()>,
) -> LogicalProcessorInfoResult {
    if let Err(e) = result {
        if e.code() == HRESULT::from_win32(ERROR_INSUFFICIENT_BUFFER.0) {
            // Buffer size changed between probe and actual call. Retry.
            return LogicalProcessorInfoResult::Retry;
        }

        panic!("GetLogicalProcessorInformationEx failed with unexpected error code: {e}");
    }

    LogicalProcessorInfoResult::Proceed
}

#[allow(
    clippy::arithmetic_side_effects,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::indexing_slicing,
    reason = "we need not worry in tests"
)]
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use std::mem::offset_of;
    use std::sync::Arc;

    use itertools::Itertools;
    use mockall::Sequence;
    use static_assertions::assert_eq_size;
    use testing::f64_diff_abs;
    use windows::Win32::System::JobObjects::{
        JOB_OBJECT_CPU_RATE_CONTROL, JOBOBJECT_CPU_RATE_CONTROL_INFORMATION,
        JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0, JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0,
    };
    use windows::Win32::System::Kernel::PROCESSOR_NUMBER;

    use super::*;
    use crate::MemoryRegionId;
    use crate::pal::windows::{MockBindings, ProcessorIndexInGroup};

    const PROCESSOR_TIME_CLOSE_ENOUGH: f64 = 0.01;

    #[test]
    fn get_all_processors_smoke_test() {
        // We imagine a simple system with 2 physical cores, 4 logical processors, all in a
        // single processor group and a single memory region. Welcome to 2010!
        let mut bindings = MockBindings::new();
        simulate_processor_layout(
            &mut bindings,
            [4],
            [4],
            [vec![0, 0, 0, 0]],
            [vec![0, 0, 0, 0]],
            None, // All processors are allowed by job constraints.
        );

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        let processors = platform.get_all_processors();

        // We expect to see 4 logical processors. This API does not care about the physical cores.
        assert_eq!(processors.len(), 4);

        // All processors must be in the same group and memory region.
        assert_eq!(
            1,
            processors
                .iter()
                .map(|p| p.as_target().group_index)
                .dedup()
                .count()
        );
        assert_eq!(
            1,
            processors
                .iter()
                .map(|p| p.as_target().memory_region_id)
                .dedup()
                .count()
        );

        let p0 = &processors[0];
        assert_eq!(p0.as_target().group_index, 0);
        assert_eq!(p0.as_target().index_in_group, 0);
        assert_eq!(p0.as_target().memory_region_id, 0);

        let p1 = &processors[1];
        assert_eq!(p1.as_target().group_index, 0);
        assert_eq!(p1.as_target().index_in_group, 1);
        assert_eq!(p1.as_target().memory_region_id, 0);

        let p2 = &processors[2];
        assert_eq!(p2.as_target().group_index, 0);
        assert_eq!(p2.as_target().index_in_group, 2);
        assert_eq!(p2.as_target().memory_region_id, 0);

        let p3 = &processors[3];
        assert_eq!(p3.as_target().group_index, 0);
        assert_eq!(p3.as_target().index_in_group, 3);
        assert_eq!(p3.as_target().memory_region_id, 0);
    }

    #[test]
    fn two_numa_nodes_efficiency_performance() {
        let mut bindings = MockBindings::new();
        // Two groups, each with 2 active processors:
        // Group 0 -> [Performance, Efficiency], Group 1 -> [Efficiency, Performance].
        simulate_processor_layout(
            &mut bindings,
            [2, 2],
            [2, 2],
            [vec![1, 0], vec![0, 1]],
            [vec![0, 0], vec![1, 1]],
            None, // All processors are allowed by job constraints.
        );

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        assert_eq!(processors.len(), 4);

        // Group 0
        let p0 = &processors[0];
        assert_eq!(p0.as_target().group_index, 0);
        assert_eq!(p0.as_target().index_in_group, 0);
        assert_eq!(p0.as_target().memory_region_id, 0);
        assert_eq!(
            p0.as_target().efficiency_class,
            EfficiencyClass::Performance
        );

        let p1 = &processors[1];
        assert_eq!(p1.as_target().group_index, 0);
        assert_eq!(p1.as_target().index_in_group, 1);
        assert_eq!(p1.as_target().memory_region_id, 0);
        assert_eq!(p1.as_target().efficiency_class, EfficiencyClass::Efficiency);

        // Group 1
        let p2 = &processors[2];
        assert_eq!(p2.as_target().group_index, 1);
        assert_eq!(p2.as_target().index_in_group, 0);
        assert_eq!(p2.as_target().memory_region_id, 1);
        assert_eq!(p2.as_target().efficiency_class, EfficiencyClass::Efficiency);

        let p3 = &processors[3];
        assert_eq!(p3.as_target().group_index, 1);
        assert_eq!(p3.as_target().index_in_group, 1);
        assert_eq!(p3.as_target().memory_region_id, 1);
        assert_eq!(
            p3.as_target().efficiency_class,
            EfficiencyClass::Performance
        );
    }

    #[test]
    fn one_big_numa_two_small_nodes() {
        let mut bindings = MockBindings::new();
        // Three groups: group 0 -> 4 Performance, group 1 -> 2 Efficiency, group 2 -> 2 Efficiency
        simulate_processor_layout(
            &mut bindings,
            [4, 2, 2],
            [4, 2, 2],
            [vec![1, 1, 1, 1], vec![0, 0], vec![0, 0]],
            [vec![0, 0, 0, 0], vec![1, 1], vec![2, 2]],
            None, // All processors are allowed by job constraints.
        );

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        assert_eq!(processors.len(), 8);

        // First 4 in group 0 => Performance
        for i in 0..4 {
            let p = &processors[i];
            assert_eq!(p.as_target().group_index, 0);
            assert_eq!(p.as_target().index_in_group, i as ProcessorIndexInGroup);
            assert_eq!(p.as_target().memory_region_id, 0);
            assert_eq!(p.as_target().efficiency_class, EfficiencyClass::Performance);
        }
        // Next 2 in group 1 => Efficiency
        for i in 4..6 {
            let p = &processors[i];
            assert_eq!(p.as_target().group_index, 1);
            assert_eq!(
                p.as_target().index_in_group,
                (i - 4) as ProcessorIndexInGroup
            );
            assert_eq!(p.as_target().memory_region_id, 1);
            assert_eq!(p.as_target().efficiency_class, EfficiencyClass::Efficiency);
        }
        // Last 2 in group 2 => Efficiency
        for i in 6..8 {
            let p = &processors[i];
            assert_eq!(p.as_target().group_index, 2);
            assert_eq!(
                p.as_target().index_in_group,
                (i - 6) as ProcessorIndexInGroup
            );
            assert_eq!(p.as_target().memory_region_id, 2);
            assert_eq!(p.as_target().efficiency_class, EfficiencyClass::Efficiency);
        }
    }

    #[test]
    fn one_active_one_inactive_numa_node() {
        let mut bindings = MockBindings::new();
        // Group 0 -> inactive, Group 1 -> [Performance, Efficiency, Performance]
        simulate_processor_layout(
            &mut bindings,
            [0, 3],
            [2, 3],
            [vec![], vec![1, 0, 1]],
            [vec![], vec![1, 1, 1]],
            None, // All processors are allowed by job constraints.
        );

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        assert_eq!(processors.len(), 3);

        // Group 1 => [Perf, Eff, Perf]
        let p0 = &processors[0];
        assert_eq!(p0.as_target().group_index, 1);
        assert_eq!(p0.as_target().index_in_group, 0);
        assert_eq!(p0.as_target().memory_region_id, 1);
        assert_eq!(
            p0.as_target().efficiency_class,
            EfficiencyClass::Performance
        );

        let p1 = &processors[1];
        assert_eq!(p1.as_target().group_index, 1);
        assert_eq!(p1.as_target().index_in_group, 1);
        assert_eq!(p1.as_target().memory_region_id, 1);
        assert_eq!(p1.as_target().efficiency_class, EfficiencyClass::Efficiency);

        let p2 = &processors[2];
        assert_eq!(p2.as_target().group_index, 1);
        assert_eq!(p2.as_target().index_in_group, 2);
        assert_eq!(p2.as_target().memory_region_id, 1);
        assert_eq!(
            p2.as_target().efficiency_class,
            EfficiencyClass::Performance
        );
    }

    #[test]
    fn two_numa_nodes_some_inactive_processors() {
        let mut bindings = MockBindings::new();
        // Group 0 -> Efficiency, Group 1 -> Performance
        simulate_processor_layout(
            &mut bindings,
            [2, 2],
            [4, 4],
            [vec![0, 0], vec![1, 1]],
            [vec![0, 0], vec![1, 1]],
            None, // All processors are allowed by job constraints.
        );

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        assert_eq!(processors.len(), 4);

        // Group 0 => [Eff, Eff]
        let p0 = &processors[0];
        assert_eq!(p0.as_target().group_index, 0);
        assert_eq!(p0.as_target().index_in_group, 0);
        assert_eq!(p0.as_target().memory_region_id, 0);
        assert_eq!(p0.as_target().efficiency_class, EfficiencyClass::Efficiency);

        let p1 = &processors[1];
        assert_eq!(p1.as_target().group_index, 0);
        assert_eq!(p1.as_target().index_in_group, 1);
        assert_eq!(p1.as_target().memory_region_id, 0);
        assert_eq!(p1.as_target().efficiency_class, EfficiencyClass::Efficiency);

        // Group 1 => [Perf, Perf]
        let p2 = &processors[2];
        assert_eq!(p2.as_target().group_index, 1);
        assert_eq!(p2.as_target().index_in_group, 0);
        assert_eq!(p2.as_target().memory_region_id, 1);
        assert_eq!(
            p2.as_target().efficiency_class,
            EfficiencyClass::Performance
        );

        let p3 = &processors[3];
        assert_eq!(p3.as_target().group_index, 1);
        assert_eq!(p3.as_target().index_in_group, 1);
        assert_eq!(p3.as_target().memory_region_id, 1);
        assert_eq!(
            p3.as_target().efficiency_class,
            EfficiencyClass::Performance
        );
    }

    #[test]
    fn one_multi_group_numa_node_one_small() {
        let mut bindings = MockBindings::new();
        // Group 0 -> [Perf, Perf], Group 1 -> [Eff, Eff], Group 2 -> [Perf]
        simulate_processor_layout(
            &mut bindings,
            [2, 2, 1],
            [2, 2, 1],
            [vec![1, 1], vec![0, 0], vec![1]],
            [vec![0, 0], vec![0, 0], vec![1]],
            None, // All processors are allowed by job constraints.
        );

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        assert_eq!(processors.len(), 5);

        // Group 0 => [Performance, Performance]
        for (i, p) in processors.iter().enumerate() {
            let p = p.as_target();

            if i < 2 {
                assert_eq!(p.group_index, 0);
                assert_eq!(p.memory_region_id, 0);
            } else if i < 4 {
                assert_eq!(p.group_index, 1);
                assert_eq!(p.memory_region_id, 0);
            } else {
                assert_eq!(p.group_index, 2);
                assert_eq!(p.memory_region_id, 1);
            }
            assert_eq!(p.index_in_group, i as ProcessorIndexInGroup % 2); // Groups of max 2.

            if i < 2 {
                assert_eq!(p.efficiency_class, EfficiencyClass::Performance);
            } else if i < 4 {
                assert_eq!(p.efficiency_class, EfficiencyClass::Efficiency);
            } else {
                assert_eq!(p.efficiency_class, EfficiencyClass::Performance);
            }
        }
    }

    #[test]
    fn job_affinity_limits_applied() {
        let mut bindings = MockBindings::new();
        // Three groups, 3x2 processors. Job constraints limit us to 2+1+0.
        simulate_processor_layout(
            &mut bindings,
            [2, 2, 2],
            [2, 2, 2],
            [vec![1, 1], vec![1, 1], vec![1, 1]],
            [vec![0, 0], vec![0, 0], vec![0, 0]],
            Some([vec![true, true], vec![true, false], vec![false, false]]),
        );

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        assert_eq!(processors.len(), 3);

        // Group 0
        let p0 = &processors[0];
        assert_eq!(p0.as_target().group_index, 0);
        assert_eq!(p0.as_target().index_in_group, 0);
        assert_eq!(p0.as_target().memory_region_id, 0);

        let p1 = &processors[1];
        assert_eq!(p1.as_target().group_index, 0);
        assert_eq!(p1.as_target().index_in_group, 1);
        assert_eq!(p1.as_target().memory_region_id, 0);

        // Group 1
        let p2 = &processors[2];
        assert_eq!(p2.as_target().group_index, 1);
        assert_eq!(p2.as_target().index_in_group, 0);
        assert_eq!(p2.as_target().memory_region_id, 0);
    }

    #[test]
    fn insufficient_buffer_retry() {
        use mockall::Sequence;

        let mut bindings = MockBindings::new();
        let mut seq = Sequence::new();

        // First iteration, probe (None) => size=64 => insufficient buffer
        bindings
            .expect_get_logical_processor_information_ex()
            .times(1)
            .in_sequence(&mut seq)
            .withf(|rel, buf, _| rel == &RelationProcessorCore && buf.is_none())
            .returning(|_, _, returned_length| {
                // SAFETY: No safety requirements.
                unsafe {
                    *returned_length = 64;
                }
                Err(windows::core::Error::from_hresult(
                    ERROR_INSUFFICIENT_BUFFER.to_hresult(),
                ))
            });

        // First iteration, real call (Some(64)) => still insufficient => size=96
        bindings
            .expect_get_logical_processor_information_ex()
            .times(1)
            .in_sequence(&mut seq)
            .withf(|rel, buf, _| rel == &RelationProcessorCore && buf.is_some())
            .returning(|_, _, returned_length| {
                // SAFETY: No safety requirements.
                unsafe {
                    *returned_length = 96;
                }
                Err(windows::core::Error::from_hresult(
                    ERROR_INSUFFICIENT_BUFFER.to_hresult(),
                ))
            });

        // Second iteration, probe (None) => size=128 => insufficient
        bindings
            .expect_get_logical_processor_information_ex()
            .times(1)
            .in_sequence(&mut seq)
            .withf(|rel, buf, _| rel == &RelationProcessorCore && buf.is_none())
            .returning(|_, _, returned_length| {
                // SAFETY: No safety requirements.
                unsafe {
                    *returned_length = 128;
                }

                Err(windows::core::Error::from_hresult(
                    ERROR_INSUFFICIENT_BUFFER.to_hresult(),
                ))
            });

        // Second iteration, real call (Some(128)) => success
        bindings
            .expect_get_logical_processor_information_ex()
            .times(1)
            .in_sequence(&mut seq)
            .withf(|rel, buf, _| rel == &RelationProcessorCore && buf.is_some())
            .returning(|_, _, returned_length| {
                // SAFETY: No safety requirements.
                unsafe {
                    *returned_length = 128;
                }

                Ok(())
            });

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let buffer = platform.get_logical_processor_information_raw(RelationProcessorCore);
        assert!(!buffer.is_empty(), "Expected final buffer to be filled");
    }

    /// Configures mock bindings to simulate a particular type of processor layout.
    ///
    /// The simulation is valid for one call to `get_all_processors()` only.
    fn simulate_processor_layout<const GROUP_COUNT: usize>(
        bindings: &mut MockBindings,
        // If entry is 0 the group is not considered active. Such groups have to be at the end.
        // Presumably. Lack of machine to actually test this on limits our ability to be sure.
        group_active_counts: [ProcessorIndexInGroup; GROUP_COUNT],
        group_max_counts: [ProcessorIndexInGroup; GROUP_COUNT],
        // Only for the active processors in each group.
        efficiency_ratings_per_group: [Vec<u8>; GROUP_COUNT],
        // Only for the active processors in each group.
        memory_regions_per_group: [Vec<MemoryRegionId>; GROUP_COUNT],
        // Only for the active processors in each group. If None, all are allowed.
        job_affinitized_processors_per_group: Option<[Vec<bool>; GROUP_COUNT]>,
    ) {
        assert_eq!(group_active_counts.len(), group_max_counts.len());
        assert_eq!(group_active_counts.len(), memory_regions_per_group.len());
        assert_eq!(
            group_active_counts.len(),
            efficiency_ratings_per_group.len()
        );

        for (group_index, group_active_processors) in group_active_counts.iter().enumerate() {
            assert!(*group_active_processors <= group_max_counts[group_index]);

            assert_eq!(
                efficiency_ratings_per_group[group_index].len(),
                *group_active_processors as usize
            );
        }

        // Move into Arc because we need to keep referencing it in the mock.
        let group_active_counts = Arc::from(group_active_counts);
        let group_max_counts = Arc::from(group_max_counts);
        let efficiency_ratings_per_group = Arc::from(efficiency_ratings_per_group);
        let memory_regions_per_group = Arc::from(memory_regions_per_group);

        simulate_get_counts(bindings, &group_active_counts, &group_max_counts);
        simulate_get_numa_relations(bindings, &memory_regions_per_group);
        simulate_get_core_info(
            bindings,
            &group_active_counts,
            &efficiency_ratings_per_group,
        );

        // Transform the booleans to IDs.
        let job_affinitized_processors_per_group =
            job_affinitized_processors_per_group.map(|groups| {
                groups
                    .into_iter()
                    .map(|processor_bools| {
                        processor_bools
                            .into_iter()
                            .enumerate()
                            .filter_map(|(index_in_group, is_allowed)| {
                                if is_allowed {
                                    Some(index_in_group as ProcessorIndexInGroup)
                                } else {
                                    None
                                }
                            })
                            .collect_vec()
                    })
                    .collect_vec()
            });

        simulate_job_constraints(bindings, job_affinitized_processors_per_group);
    }

    fn simulate_get_counts(
        bindings: &mut MockBindings,
        group_active_counts: &Arc<[ProcessorIndexInGroup]>,
        group_max_counts: &Arc<[ProcessorIndexInGroup]>,
    ) {
        let max_group_count = group_active_counts.len() as u16;

        // The "get maximum" we expect the platform to always report the same numbers for, so we
        // do not care how many times they are called. The "get active" we only want to call once
        // per processor group to avoid multiple calls into the platform getting different results.

        // Note that "get active group count" is not actually used - the code probes all groups
        // and just checks number of processors in group to identify if the group is active.
        bindings
            .expect_get_maximum_processor_group_count()
            .return_const(max_group_count);

        bindings
            .expect_get_active_processor_count()
            .times(group_max_counts.len())
            .returning({
                let group_active_counts = Arc::clone(group_active_counts);

                move |group_number| u32::from(group_active_counts[group_number as usize])
            });

        bindings.expect_get_maximum_processor_count().returning({
            let group_max_counts = Arc::clone(group_max_counts);

            move |group_number| u32::from(group_max_counts[group_number as usize])
        });
    }

    fn simulate_get_numa_relations(
        bindings: &mut MockBindings,
        // Active processors only.
        active_processor_memory_regions_per_group: &Arc<[Vec<MemoryRegionId>]>,
    ) {
        // The mask logic is weird on 32-bit, so we have not bothered to implement/test it.
        // We do not today care about correctly operating in 32-bit builds.
        assert_eq_size!(u64, usize);

        // NB! WARNING! size_of<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>() is not correct! This is
        // because there is a dynamically-sized array in there that in the Rust bindings is just
        // hardcoded to size 1. The real size in memory may be greater than size_of()!
        //
        // We define here some additional buffer to add on top of the "known" memory.
        const MAX_ADDITIONAL_PROCESSOR_GROUPS: usize = 32;

        #[repr(C)]
        struct ExpandedLogicalProcessorInformation {
            root: SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX,
            // We do not necessarily use it in-place, this is a fake member
            // just to make room in the sizeof calculation.
            extra_buffer: [GROUP_AFFINITY; MAX_ADDITIONAL_PROCESSOR_GROUPS],
        }

        // There will be a call to get the groups that are members of each NUMA node.
        // The NUMA response is structured by memory region, not by processor group.
        // Therefore we need to also structure our data this way.
        let memory_regions_to_group_indexes = active_processor_memory_regions_per_group
            .iter()
            .enumerate()
            .flat_map(|(group_index, active_processor_memory_regions)| {
                active_processor_memory_regions
                    .iter()
                    .map(move |memory_region_index| {
                        (*memory_region_index, group_index as ProcessorGroupIndex)
                    })
                    .unique()
            })
            .into_group_map();

        let memory_region_count = memory_regions_to_group_indexes.len();

        let memory_region_responses = memory_regions_to_group_indexes
            .into_iter()
            .map(|(memory_region_index, group_indexes)| {
                // We made some additional space in the struct to allow for more groups
                // but there is still an upper limit to what we can fit, so be careful.
                assert!(group_indexes.len() <= MAX_ADDITIONAL_PROCESSOR_GROUPS);

                let mut response = ExpandedLogicalProcessorInformation {
                    root: SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX {
                        // This is always RelationNumaNode, even if RelationNumaNodeEx is requested.
                        // RelationNumaNodeEx simply allows the group count to be more than 1.
                        Relationship: RelationNumaNode,
                        Size: size_of::<ExpandedLogicalProcessorInformation>() as u32,
                        ..Default::default()
                    },
                    extra_buffer: [GROUP_AFFINITY::default(); MAX_ADDITIONAL_PROCESSOR_GROUPS],
                };

                // SAFETY: We define RelationNumaNode above so this dereference is valid.
                let response_numa = unsafe { &mut response.root.Anonymous.NumaNode };

                response_numa.NodeNumber = memory_region_index;
                response_numa.GroupCount = group_indexes.len() as u16;

                // The type definition just has an array of 1 here (not correct), so we write
                // through pointers to fill each array element. We have to do this dance of starting
                // out borrow from the root of the document we are returning to prove to the
                // compiler and Miri that we have the rights to write beyond the 1-element array.
                let document = &raw mut response;

                // SAFETY: We define GroupCount above so this dereference is valid.
                let mut group_mask = unsafe {
                    document
                        .byte_add(offset_of!(
                            ExpandedLogicalProcessorInformation,
                            root.Anonymous.NumaNode.Anonymous.GroupMask
                        ))
                        .cast::<GROUP_AFFINITY>()
                };

                for group_index in group_indexes {
                    let mut mask: u64 = 0;

                    for (index_in_group, memory_region_id) in
                        active_processor_memory_regions_per_group[group_index as usize]
                            .iter()
                            .enumerate()
                    {
                        if *memory_region_id != memory_region_index {
                            continue;
                        }

                        mask |= 1 << index_in_group;
                    }

                    let group_data = GROUP_AFFINITY {
                        Group: group_index,
                        Mask: mask as usize,
                        ..Default::default()
                    };

                    // SAFETY: We define GroupCount above and ensured that we have enough space
                    // via MAX_ADDITIONAL_PROCESSOR_GROUPS so this is valid.
                    unsafe {
                        group_mask.write(group_data);
                    }

                    // SAFETY: We define GroupCount above and ensured that we have enough space
                    // via MAX_ADDITIONAL_PROCESSOR_GROUPS so this is valid.
                    group_mask = unsafe { group_mask.add(1) };
                }

                response
            })
            .collect_vec();

        let memory_region_response_buffer = NativeBuffer::from_items(memory_region_responses);
        let memory_region_response_len = memory_region_response_buffer.len_bytes();

        let mut seq = Sequence::new();

        // This will actually be two calls, one for the size probe and one for the real data.
        bindings
            .expect_get_logical_processor_information_ex()
            .times(1)
            .in_sequence(&mut seq)
            .withf(|relationship_type, buffer, _| {
                *relationship_type == RelationNumaNodeEx && buffer.is_none()
            })
            .returning(move |_, _, returned_length| {
                // SAFETY: Caller must guarantee that the pointer is valid for use.
                unsafe {
                    *returned_length = memory_region_response_len as u32;
                }

                Err(windows::core::Error::from_hresult(HRESULT::from_win32(
                    ERROR_INSUFFICIENT_BUFFER.0,
                )))
            });

        bindings
            .expect_get_logical_processor_information_ex()
            .times(1)
            .in_sequence(&mut seq)
            .withf(|relationship_type, buffer, _| {
                *relationship_type == RelationNumaNodeEx && buffer.is_some()
            })
            .returning_st(move |_, buffer, returned_length| {
                // SAFETY: Caller must guarantee that the pointer is valid for use.
                unsafe {
                    *returned_length = memory_region_response_len as u32;
                }

                // SAFETY: Caller must guarantee that the pointer is valid for use.
                unsafe {
                    buffer
                        .unwrap()
                        .cast::<ExpandedLogicalProcessorInformation>()
                        .copy_from_nonoverlapping(
                            memory_region_response_buffer.as_ptr().as_ptr(),
                            memory_region_count,
                        );
                }

                Ok(())
            });
    }

    fn simulate_get_core_info(
        bindings: &mut MockBindings,
        group_active_counts: &Arc<[ProcessorIndexInGroup]>,
        // Active processors only.
        active_processor_efficiency_ratings_per_group: &Arc<[Vec<u8>]>,
    ) {
        // Next we define the "get core info" simulation, used to access metadata of each processor.
        // Specifically, this provides the efficiency class. The other info is currently unused.

        // In case of RelationProcessorCore, we do not use any dynamically sized arrays, which
        // keeps the size logic a bit simpler than with the NUMA nodes response. We have one entry
        // in the response for each processor. For the sake of simplicity (the code does not care)
        // we pretend that each core is 1 logical processor (no SMT).
        let response_entries = group_active_counts
            .iter()
            .enumerate()
            .flat_map(|(group_index, group_active_count)| {
                (0..*group_active_count).map({
                    let efficiency_ratings_per_group =
                        Arc::clone(active_processor_efficiency_ratings_per_group);

                    move |index_in_group| {
                        let mut entry = SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX {
                            Relationship: RelationProcessorCore,
                            Size: size_of::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>() as u32,
                            ..Default::default()
                        };

                        // SAFETY: We define RelationProcessorCore above so this dereference is valid.
                        let entry_processor = unsafe { &mut entry.Anonymous.Processor };

                        entry_processor.EfficiencyClass =
                            efficiency_ratings_per_group[group_index][index_in_group as usize];

                        entry_processor.GroupCount = 1;
                        entry_processor.GroupMask[0].Group = group_index as u16;
                        entry_processor.GroupMask[0].Mask = 1 << index_in_group;

                        entry
                    }
                })
            })
            .collect_vec();

        let core_info_response_entry_count = response_entries.len();
        let core_info_response_buffer = NativeBuffer::from_items(response_entries);
        let core_info_response_len = core_info_response_buffer.len_bytes();

        let mut seq = Sequence::new();

        // This will actually be two calls, one for the size probe and one for the real data.
        bindings
            .expect_get_logical_processor_information_ex()
            .times(1)
            .in_sequence(&mut seq)
            .withf(|relationship_type, buffer, _| {
                *relationship_type == RelationProcessorCore && buffer.is_none()
            })
            .returning(move |_, _, returned_length| {
                // SAFETY: Caller must guarantee that the pointer is valid for use.
                unsafe {
                    *returned_length = core_info_response_len as u32;
                }

                Err(windows::core::Error::from_hresult(HRESULT::from_win32(
                    ERROR_INSUFFICIENT_BUFFER.0,
                )))
            });

        bindings
            .expect_get_logical_processor_information_ex()
            .times(1)
            .in_sequence(&mut seq)
            .withf(|relationship_type, buffer, _| {
                *relationship_type == RelationProcessorCore && buffer.is_some()
            })
            .returning_st(move |_, buffer, returned_length| {
                // SAFETY: Caller must guarantee that the pointer is valid for use.
                unsafe {
                    *returned_length = core_info_response_len as u32;
                }

                // SAFETY: Caller must guarantee that the pointer is valid for use.
                unsafe {
                    buffer.unwrap().copy_from_nonoverlapping(
                        core_info_response_buffer.as_ptr().as_ptr(),
                        core_info_response_entry_count,
                    );
                }

                Ok(())
            });
    }

    fn simulate_job_constraints(
        bindings: &mut MockBindings,
        affinities_per_group: Option<Vec<Vec<ProcessorIndexInGroup>>>,
    ) {
        match affinities_per_group {
            Some(groups) => {
                let group_affinities = groups
                    .into_iter()
                    .enumerate()
                    .filter_map(|(group_index, group_processors)| {
                        if group_processors.is_empty() {
                            None
                        } else {
                            let mut affinity = GROUP_AFFINITY {
                                Group: group_index as ProcessorGroupIndex,
                                Mask: 0,
                                ..Default::default()
                            };

                            for processor_index in group_processors {
                                affinity.Mask |= 1 << processor_index;
                            }

                            Some(affinity)
                        }
                    })
                    .collect_vec();

                bindings
                    .expect_get_current_job_cpu_set_masks()
                    .return_once(|| group_affinities);
            }
            None => {
                bindings
                    .expect_get_current_job_cpu_set_masks()
                    .return_once(Vec::new);
            }
        }
    }

    #[test]
    fn pin_current_thread_to_single_processor() {
        let mut bindings = MockBindings::new();
        simulate_processor_layout(
            &mut bindings,
            [1],
            [1],
            [vec![0]],
            [vec![0]],
            None, // All processors are allowed by job constraints.
        );
        bindings
            .expect_set_current_thread_cpu_set_masks()
            .withf(|affinities| {
                affinities.len() == 1 && affinities[0].Group == 0 && affinities[0].Mask == 1
            })
            .return_const(());

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        platform.pin_current_thread_to(&processors);
    }

    #[test]
    fn pin_current_thread_to_multiple_processors() {
        let mut bindings = MockBindings::new();
        simulate_processor_layout(
            &mut bindings,
            [2],
            [2],
            [vec![0, 0]],
            [vec![0, 0]],
            None, // All processors are allowed by job constraints.
        );
        bindings
            .expect_set_current_thread_cpu_set_masks()
            .withf(|affinities| {
                affinities.len() == 1 && affinities[0].Group == 0 && affinities[0].Mask == 3
            })
            .return_const(());

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        platform.pin_current_thread_to(&processors);
    }

    #[test]
    fn pin_current_thread_to_multiple_groups() {
        let mut bindings = MockBindings::new();
        simulate_processor_layout(
            &mut bindings,
            [1, 1],
            [1, 1],
            [vec![0], vec![0]],
            [vec![0], vec![1]],
            None, // All processors are allowed by job constraints.
        );
        bindings
            .expect_set_current_thread_cpu_set_masks()
            .withf(|affinities| {
                affinities.len() == 2
                    && affinities[0].Group == 0
                    && affinities[0].Mask == 1
                    && affinities[1].Group == 1
                    && affinities[1].Mask == 1
            })
            .return_const(());

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        platform.pin_current_thread_to(&processors);
    }

    #[test]
    fn pin_current_thread_to_efficiency_processors() {
        let mut bindings = MockBindings::new();
        // Group 0 -> [Performance, Efficiency], Group 1 -> [Efficiency, Performance]
        simulate_processor_layout(
            &mut bindings,
            [2, 2],
            [2, 2],
            [vec![1, 0], vec![0, 1]],
            [vec![0, 0], vec![1, 1]],
            None, // All processors are allowed by job constraints.
        );
        bindings
            .expect_set_current_thread_cpu_set_masks()
            .withf(|affinities| {
                affinities.len() == 2
                    && affinities[0].Group == 0
                    && affinities[0].Mask == 2
                    && affinities[1].Group == 1
                    && affinities[1].Mask == 1
            })
            .return_const(());

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        let efficiency_processors = NonEmpty::from_vec(
            processors
                .iter()
                .filter(|p| p.as_target().efficiency_class == EfficiencyClass::Efficiency)
                .collect_vec(),
        )
        .unwrap();
        platform.pin_current_thread_to(&efficiency_processors);
    }

    #[test]
    fn single_group_multiple_memory_regions() {
        let mut bindings = MockBindings::new();
        // Group 0 -> [MemoryRegion 0, MemoryRegion 1, MemoryRegion 0, MemoryRegion 1]
        simulate_processor_layout(
            &mut bindings,
            [4],
            [4],
            [vec![0, 0, 0, 0]],
            [vec![0, 1, 0, 1]],
            None, // All processors are allowed by job constraints.
        );

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));
        let processors = platform.get_all_processors();
        assert_eq!(processors.len(), 4);

        // Check memory regions
        assert_eq!(processors[0].as_target().memory_region_id, 0);
        assert_eq!(processors[1].as_target().memory_region_id, 1);
        assert_eq!(processors[2].as_target().memory_region_id, 0);
        assert_eq!(processors[3].as_target().memory_region_id, 1);
    }

    #[test]
    fn current_thread_processors_if_no_affinity_set() {
        let mut bindings = MockBindings::new();

        // We are only obtaining processor IDs here, so we never actually perform a "get processors"
        // call, therefore we cannot use our "simulate_processor_layout" helper because that exists
        // specifically to facilitate the "get processors" API call.
        bindings
            .expect_get_maximum_processor_group_count()
            .times(1)
            .return_const(2 as ProcessorGroupIndex);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 0)
            .return_const(2 as ProcessorId);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 1)
            .return_const(1 as ProcessorId);

        bindings
            .expect_get_current_thread_cpu_set_masks()
            .return_once(Vec::new);
        bindings
            .expect_get_current_process_default_cpu_set_masks()
            .return_once(Vec::new);
        bindings
            .expect_get_current_thread_legacy_group_affinity()
            .return_once(|| GROUP_AFFINITY {
                Group: 0,
                Mask: 3, // Processors 0 and 1 - the default mask for this group.
                ..Default::default()
            });

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        let processor_ids = platform.current_thread_processors();
        assert_eq!(processor_ids.len(), 3);

        assert!(processor_ids.contains(&0));
        assert!(processor_ids.contains(&1));
        assert!(processor_ids.contains(&2));
    }

    #[test]
    fn current_thread_processors_if_no_affinity_set_default_group1() {
        let mut bindings = MockBindings::new();

        // We are only obtaining processor IDs here, so we never actually perform a "get processors"
        // call, therefore we cannot use our "simulate_processor_layout" helper because that exists
        // specifically to facilitate the "get processors" API call.
        bindings
            .expect_get_maximum_processor_group_count()
            .times(1)
            .return_const(2 as ProcessorGroupIndex);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 0)
            .return_const(2 as ProcessorId);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 1)
            .return_const(1 as ProcessorId);

        bindings
            .expect_get_current_thread_cpu_set_masks()
            .return_once(Vec::new);
        bindings
            .expect_get_current_process_default_cpu_set_masks()
            .return_once(Vec::new);
        bindings
            .expect_get_current_thread_legacy_group_affinity()
            .return_once(|| GROUP_AFFINITY {
                // We default to group 1. This is still a default value and should be ignored as
                // there is no requirement that the default affinitization be in group 0.
                Group: 1,
                Mask: 1, // Processor 0 - the default mask for this group.
                ..Default::default()
            });

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        let processor_ids = platform.current_thread_processors();
        assert_eq!(processor_ids.len(), 3);

        assert!(processor_ids.contains(&0));
        assert!(processor_ids.contains(&1));
        assert!(processor_ids.contains(&2));
    }

    #[test]
    fn current_thread_processors_if_legacy_affinity_set() {
        let mut bindings = MockBindings::new();

        // We are only obtaining processor IDs here, so we never actually perform a "get processors"
        // call, therefore we cannot use our "simulate_processor_layout" helper because that exists
        // specifically to facilitate the "get processors" API call.
        bindings
            .expect_get_maximum_processor_group_count()
            .times(1)
            .return_const(2 as ProcessorGroupIndex);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 0)
            .return_const(2 as ProcessorId);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 1)
            .return_const(1 as ProcessorId);
        bindings
            .expect_get_active_processor_count()
            .times(1)
            .withf(|group| *group == 0)
            .return_const(2 as ProcessorId);
        bindings
            .expect_get_active_processor_count()
            .times(1)
            .withf(|group| *group == 1)
            .return_const(1 as ProcessorId);

        bindings
            .expect_get_current_thread_cpu_set_masks()
            .return_once(Vec::new);
        bindings
            .expect_get_current_process_default_cpu_set_masks()
            .return_once(Vec::new);
        bindings
            .expect_get_current_thread_legacy_group_affinity()
            .return_once(|| GROUP_AFFINITY {
                Group: 0,
                Mask: 1, // Processor 0 allowed, processor 1 forbidden - not the default value!
                ..Default::default()
            });

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        let processor_ids = platform.current_thread_processors();
        assert_eq!(processor_ids.len(), 1);

        assert!(processor_ids.contains(&0));
    }

    #[test]
    fn current_thread_processors_if_process_affinity_set() {
        let mut bindings = MockBindings::new();

        // We are only obtaining processor IDs here, so we never actually perform a "get processors"
        // call, therefore we cannot use our "simulate_processor_layout" helper because that exists
        // specifically to facilitate the "get processors" API call.
        bindings
            .expect_get_maximum_processor_group_count()
            .times(1)
            .return_const(2 as ProcessorGroupIndex);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 0)
            .return_const(2 as ProcessorId);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 1)
            .return_const(1 as ProcessorId);
        bindings
            .expect_get_active_processor_count()
            .times(1)
            .withf(|group| *group == 0)
            .return_const(2 as ProcessorId);
        bindings
            .expect_get_active_processor_count()
            .times(1)
            .withf(|group| *group == 1)
            .return_const(1 as ProcessorId);

        // Process affinity is only queried if thread affinity contains nothing.
        bindings
            .expect_get_current_thread_cpu_set_masks()
            .return_once(Vec::new);
        bindings
            .expect_get_current_process_default_cpu_set_masks()
            .return_once(|| {
                vec![
                    GROUP_AFFINITY {
                        Group: 0,
                        Mask: 1,
                        ..Default::default()
                    },
                    GROUP_AFFINITY {
                        Group: 1,
                        Mask: 1,
                        ..Default::default()
                    },
                ]
            });

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        let processor_ids = platform.current_thread_processors();
        assert_eq!(processor_ids.len(), 2);

        assert!(processor_ids.contains(&0));
        assert!(processor_ids.contains(&2));
    }

    #[test]
    fn current_thread_processors_if_thread_affinity_set() {
        let mut bindings = MockBindings::new();

        // We are only obtaining processor IDs here, so we never actually perform a "get processors"
        // call, therefore we cannot use our "simulate_processor_layout" helper because that exists
        // specifically to facilitate the "get processors" API call.
        bindings
            .expect_get_maximum_processor_group_count()
            .times(1)
            .return_const(2 as ProcessorGroupIndex);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 0)
            .return_const(2 as ProcessorId);
        bindings
            .expect_get_maximum_processor_count()
            .times(1)
            .withf(|group| *group == 1)
            .return_const(1 as ProcessorId);
        bindings
            .expect_get_active_processor_count()
            .times(1)
            .withf(|group| *group == 0)
            .return_const(2 as ProcessorId);
        bindings
            .expect_get_active_processor_count()
            .times(1)
            .withf(|group| *group == 1)
            .return_const(1 as ProcessorId);

        // Note that we do not define any expectation that process affinity is queried - if a thread
        // affinity is set, process affinity is ignored and should not even be queried.
        bindings
            .expect_get_current_thread_cpu_set_masks()
            .return_once(|| {
                vec![
                    GROUP_AFFINITY {
                        Group: 0,
                        Mask: 1,
                        ..Default::default()
                    },
                    GROUP_AFFINITY {
                        Group: 1,
                        Mask: 1,
                        ..Default::default()
                    },
                ]
            });

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        let processor_ids = platform.current_thread_processors();
        assert_eq!(processor_ids.len(), 2);

        assert!(processor_ids.contains(&0));
        assert!(processor_ids.contains(&2));
    }

    #[test]
    fn basic_facts_are_represented() {
        let mut bindings = MockBindings::new();
        // 3 groups, 3 processors each group, 3 different memory regions.
        simulate_processor_layout(
            &mut bindings,
            [3, 3, 3],
            [3, 3, 3],
            [vec![0, 0, 0], vec![0, 0, 0], vec![0, 0, 0]],
            [vec![0, 0, 0], vec![1, 1, 1], vec![2, 2, 2]],
            None, // All processors are allowed by job constraints.
        );

        bindings
            .expect_get_numa_highest_node_number()
            .times(1)
            .return_once(|| 2);

        bindings
            .expect_get_current_processor_number_ex()
            .times(1)
            .return_once(|| PROCESSOR_NUMBER {
                Group: 1,
                Number: 2,
                ..Default::default()
            });

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        let current_processor_id = platform.current_processor_id();
        assert_eq!(current_processor_id, 5);

        let max_processor_id = platform.max_processor_id();
        assert_eq!(max_processor_id, 8);

        let max_memory_region_id = platform.max_memory_region_id();
        assert_eq!(max_memory_region_id, 2);

        // We do this just to ensure we meet all the expectations declared by the simulation.
        drop(platform.get_all_processors());
    }

    #[test]
    fn max_processor_time_without_job() {
        // If there is no job, max_processor_time is the same as the number of available processors.
        let mut bindings = MockBindings::new();

        // 4 processors in a single group, 2 more offline processors.
        simulate_processor_layout(&mut bindings, [4], [6], [vec![0; 4]], [vec![0; 4]], None);

        bindings
            .expect_get_current_job_cpu_rate_control()
            .times(1)
            .return_const(None);

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        // This will internally call "get all processors" to identify the total count,
        // so our simulation will correctly exercise the mocked simulation calls.
        let max_processor_time = platform.max_processor_time();

        #[expect(
            clippy::float_cmp,
            reason = "we use absolute error, which is the right way to compare"
        )]
        {
            assert_eq!(
                f64_diff_abs(max_processor_time, 4.0, PROCESSOR_TIME_CLOSE_ENOUGH),
                0.0
            );
        }
    }

    #[test]
    fn max_processor_time_without_limits_on_job() {
        // If there is a job but it has no limits, max_processor_time is
        // the same as the number of available processors.
        let mut bindings = MockBindings::new();

        // 4 processors in a single group, 2 more offline processors.
        simulate_processor_layout(&mut bindings, [4], [6], [vec![0; 4]], [vec![0; 4]], None);

        bindings
            .expect_get_current_job_cpu_rate_control()
            .times(1)
            .return_const(Some(JOBOBJECT_CPU_RATE_CONTROL_INFORMATION::default()));

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        // This will internally call "get all processors" to identify the total count,
        // so our simulation will correctly exercise the mocked simulation calls.
        let max_processor_time = platform.max_processor_time();

        #[expect(
            clippy::float_cmp,
            reason = "we use absolute error, which is the right way to compare"
        )]
        {
            assert_eq!(
                f64_diff_abs(max_processor_time, 4.0, PROCESSOR_TIME_CLOSE_ENOUGH),
                0.0
            );
        }
    }

    #[test]
    fn max_processor_time_below_available_hard_cap() {
        // If the job limit is less than the number of available processors,
        // we should use the job limit as the processor time limit.
        let mut bindings = MockBindings::new();

        // 4 processors in a single group, 2 more offline processors.
        simulate_processor_layout(&mut bindings, [4], [6], [vec![0; 4]], [vec![0; 4]], None);

        bindings
            .expect_get_current_job_cpu_rate_control()
            .times(1)
            .return_const(Some(JOBOBJECT_CPU_RATE_CONTROL_INFORMATION {
                ControlFlags: JOB_OBJECT_CPU_RATE_CONTROL(
                    JOB_OBJECT_CPU_RATE_CONTROL_ENABLE.0 | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP.0,
                ),
                Anonymous: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0 {
                    CpuRate: 5000, // 50% of the available processors (2 out of 4).
                },
            }));

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        // This will internally call "get all processors" to identify the total count,
        // so our simulation will correctly exercise the mocked simulation calls.
        let max_processor_time = platform.max_processor_time();

        #[expect(
            clippy::float_cmp,
            reason = "we use absolute error, which is the right way to compare"
        )]
        {
            assert_eq!(
                f64_diff_abs(max_processor_time, 2.0, PROCESSOR_TIME_CLOSE_ENOUGH),
                0.0
            );
        }
    }

    #[test]
    fn max_processor_time_below_available_soft_cap() {
        // If the job limit is less than the number of available processors,
        // we should use the job limit as the processor time limit.
        let mut bindings = MockBindings::new();

        // 4 processors in a single group, 2 more offline processors.
        simulate_processor_layout(&mut bindings, [4], [6], [vec![0; 4]], [vec![0; 4]], None);

        bindings
            .expect_get_current_job_cpu_rate_control()
            .times(1)
            .return_const(Some(JOBOBJECT_CPU_RATE_CONTROL_INFORMATION {
                ControlFlags: JOB_OBJECT_CPU_RATE_CONTROL(
                    JOB_OBJECT_CPU_RATE_CONTROL_ENABLE.0
                        | JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE.0,
                ),
                Anonymous: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0 {
                    Anonymous: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0 {
                        MinRate: 3000, // 30% - we ignore this.
                        MaxRate: 7500, // 75% - this is the cap.
                    },
                },
            }));

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        // This will internally call "get all processors" to identify the total count,
        // so our simulation will correctly exercise the mocked simulation calls.
        let max_processor_time = platform.max_processor_time();

        #[expect(
            clippy::float_cmp,
            reason = "we use absolute error, which is the right way to compare"
        )]
        {
            assert_eq!(
                f64_diff_abs(max_processor_time, 3.0, PROCESSOR_TIME_CLOSE_ENOUGH),
                0.0
            );
        }
    }

    #[test]
    fn max_processor_time_above_available() {
        // If the job limit is greater than the number of available processors due to affinity,
        // we should use the number of available processors as the processor time limit.
        let mut bindings = MockBindings::new();

        // 4 processors in a single group, 2 more offline processors.
        simulate_processor_layout(
            &mut bindings,
            [4],
            [6],
            [vec![0; 4]],
            [vec![0; 4]],
            // However! We are limited to only 2 processors by affinity!
            Some([vec![true, true, false, false]]),
        );

        bindings
            .expect_get_current_job_cpu_rate_control()
            .times(1)
            .return_const(Some(JOBOBJECT_CPU_RATE_CONTROL_INFORMATION {
                ControlFlags: JOB_OBJECT_CPU_RATE_CONTROL(
                    JOB_OBJECT_CPU_RATE_CONTROL_ENABLE.0
                        | JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE.0,
                ),
                Anonymous: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0 {
                    Anonymous: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION_0_0 {
                        MinRate: 3000, // 30% - we ignore this.
                        MaxRate: 7500, // 75% - this is the cap.
                    },
                },
            }));

        let platform = BuildTargetPlatform::new(BindingsFacade::from_mock(bindings));

        // This will internally call "get all processors" to identify the total count,
        // so our simulation will correctly exercise the mocked simulation calls.
        let max_processor_time = platform.max_processor_time();

        #[expect(
            clippy::float_cmp,
            reason = "we use absolute error, which is the right way to compare"
        )]
        {
            assert_eq!(
                f64_diff_abs(max_processor_time, 2.0, PROCESSOR_TIME_CLOSE_ENOUGH),
                0.0
            );
        }
    }
}