drmkit-scene 0.1.2

Scene composition for drmkit: buffer sources, layer lowering, and atomic commit orchestration.
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
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! Tests for the scene's contract surface.
//!
//! The release *timing* contracts (invariants 1 and 2) need a real page flip
//! and land with the commit path, in the vkms lane. What is testable here is
//! the shape those contracts are built on: that a source's flow-control return
//! is distinguishable from a failure, that the defaults are the safe ones, and
//! that the commit report's accounting is checkable rather than merely
//! documented.

use super::*;
use drmkit_planes::LayerId;

/// A source that can be told what to do, standing in for a live producer.
#[derive(Debug, Default)]
struct FakeSource {
    format: SourceFormat,
    /// Returned by the next `acquire`.
    next: Option<Result<AcquiredBuffer, SourceError>>,
    released: Vec<u32>,
    released_with_fence: usize,
    fresh: bool,
}

impl LayerBufferSource for FakeSource {
    fn acquire(&mut self) -> Result<AcquiredBuffer, SourceError> {
        self.next.take().unwrap_or(Err(SourceError::WouldBlock))
    }

    fn release(&mut self, acquired: AcquiredBuffer) {
        self.released.push(acquired.fb_id);
    }

    fn release_with_fence(
        &mut self,
        acquired: AcquiredBuffer,
        _release_fence: Option<drmkit_sync::SyncFence>,
    ) {
        self.released_with_fence += 1;
        self.release(acquired);
    }

    fn has_fresh_content(&self) -> bool {
        self.fresh
    }

    fn format(&self) -> SourceFormat {
        self.format
    }
}

/// A source that overrides nothing, to exercise the trait's defaults.
#[derive(Debug, Default)]
struct MinimalSource;

impl LayerBufferSource for MinimalSource {
    fn acquire(&mut self) -> Result<AcquiredBuffer, SourceError> {
        Ok(AcquiredBuffer {
            fb_id: 7,
            ..AcquiredBuffer::default()
        })
    }

    fn release(&mut self, _acquired: AcquiredBuffer) {}

    fn format(&self) -> SourceFormat {
        SourceFormat::default()
    }
}

// --- DR-6: EAGAIN is a variant, not an I/O error -----------------------------

/// Flow control must be distinguishable from failure at the type level.
///
/// A source with nothing to contribute this vblank is skipped and retried; a
/// source that actually failed aborts the commit. Recovering that distinction
/// by squinting at an I/O error kind is how the contract gets lost in a
/// refactor — and losing it turns a stalled producer into an aborted commit.
#[test]
fn would_block_is_distinct_from_failure() {
    let mut source = FakeSource::default();

    // Nothing queued: the fake reports flow control.
    assert!(matches!(source.acquire(), Err(SourceError::WouldBlock)));

    source.next = Some(Err(SourceError::Failed(rustix::io::Errno::INVAL)));
    assert!(matches!(source.acquire(), Err(SourceError::Failed(_))));

    source.next = Some(Err(SourceError::Unsupported));
    assert!(matches!(source.acquire(), Err(SourceError::Unsupported)));
}

/// The variants must not be collapsible by accident: a caller matching on
/// `WouldBlock` must not also catch a real failure.
#[test]
fn a_real_failure_is_not_mistaken_for_flow_control() {
    let failure = SourceError::Failed(rustix::io::Errno::AGAIN);
    assert!(
        !matches!(failure, SourceError::WouldBlock),
        "an errno that happens to be EAGAIN is still a failure if the source \
         reported it as one -- the variant carries the intent, not the number"
    );
}

// --- trait defaults: the conservative answers --------------------------------

/// `has_fresh_content` defaults to true, so a source that cannot tell whether
/// its buffer changed never causes a real update to be skipped.
#[test]
fn fresh_content_defaults_to_the_safe_answer() {
    assert!(
        MinimalSource.has_fresh_content(),
        "a source that cannot introspect its buffer must report changed, or a \
         real update is silently skipped"
    );

    // A source that *knows* it is idle opts out, which is what enables the
    // whole-commit skip.
    let idle = FakeSource::default();
    assert!(!idle.has_fresh_content());
}

#[test]
fn binding_model_defaults_to_scene_submits_fb_id() {
    assert_eq!(
        MinimalSource.binding_model(),
        BindingModel::SceneSubmitsFbId
    );
    assert_eq!(BindingModel::default(), BindingModel::SceneSubmitsFbId);
}

#[test]
fn release_fence_is_opt_in() {
    assert!(
        !MinimalSource.wants_release_fence(),
        "the scene only requests an OUT_FENCE when a source asks, so this must \
         cost nothing by default"
    );
}

/// The default `release_with_fence` forwards to `release`, so a source that
/// does not care about the fence still sees every buffer come back.
#[test]
fn release_with_fence_forwards_by_default() {
    let mut source = MinimalSource;
    // Compiles and does not panic: the default drops the fence and forwards.
    source.release_with_fence(
        AcquiredBuffer {
            fb_id: 3,
            ..AcquiredBuffer::default()
        },
        None,
    );
}

/// A source that overrides it sees the fence path instead.
#[test]
fn release_with_fence_is_overridable() {
    let mut source = FakeSource::default();
    source.release_with_fence(
        AcquiredBuffer {
            fb_id: 5,
            ..AcquiredBuffer::default()
        },
        None,
    );
    assert_eq!(source.released_with_fence, 1);
    assert_eq!(source.released, vec![5]);
}

/// Both composition escapes default to unsupported, which is what makes a
/// source uncompositable rather than silently producing garbage.
#[test]
fn composition_escapes_default_to_unsupported() {
    let mut source = MinimalSource;
    assert!(matches!(
        source.map(drmkit_dumb::MapAccess::Read),
        Err(SourceError::Unsupported)
    ));
    assert!(matches!(
        source.export_dma_buf(),
        Err(SourceError::Unsupported)
    ));
}

/// The driver-binding hooks are no-ops by default (DR-4 dormant surface), so a
/// source that submits its own `FB_ID` needs to know nothing about them.
#[test]
fn driver_binding_hooks_are_inert_by_default() {
    let mut source = MinimalSource;
    assert!(source.bind_to_plane(31).is_ok());
    source.unbind_from_plane(31);
    source.on_session_paused();
}

// --- AcquiredBuffer ----------------------------------------------------------

/// Moving transfers the buffer intact.
///
/// The *non-copyability* this depends on is pinned by a `compile_fail` doctest
/// on [`AcquiredBuffer`] itself, not here: no stable Rust assertion can express
/// "this type must not be `Copy`", and a test function that silently asserts
/// nothing is worse than no test.
#[test]
fn moving_an_acquired_buffer_transfers_it_intact() {
    let buffer = AcquiredBuffer {
        fb_id: 42,
        token: 3,
        ..AcquiredBuffer::default()
    };
    let moved = buffer;
    assert_eq!(moved.fb_id, 42);
    assert_eq!(moved.token, 3);
}

#[test]
fn an_acquired_buffer_defaults_to_full_frame_damage() {
    let buffer = AcquiredBuffer::default();
    assert!(
        buffer.damage.is_empty(),
        "empty means full-frame: correct, just not power-optimal"
    );
    assert!(buffer.acquire_fence.is_none());
}

// --- CommitReport ------------------------------------------------------------

/// The accounting invariant the C++ states as a comment, made checkable.
#[test]
fn commit_report_accounting_balances() {
    let report = CommitReport {
        layers_total: 5,
        layers_assigned: 2,
        layers_composited: 1,
        layers_unassigned: 1,
        layers_skipped_no_frame: 1,
        ..CommitReport::default()
    };
    assert!(report.accounting_balances());

    let unbalanced = CommitReport {
        layers_total: 5,
        layers_assigned: 2,
        ..CommitReport::default()
    };
    assert!(
        !unbalanced.accounting_balances(),
        "a layer counted nowhere must show up as an imbalance"
    );
}

/// A pin that could not be honored does not disturb the accounting: the layer
/// falls back to normal allocation and is still counted once.
#[test]
fn unhonored_pins_do_not_affect_the_accounting() {
    let report = CommitReport {
        layers_total: 1,
        layers_assigned: 1,
        pin_requests_unhonored: 1,
        ..CommitReport::default()
    };
    assert!(report.accounting_balances());
}

/// **Invariant 4's observable signal.** Taking the fast path means issuing no
/// test commits; a report claiming both is self-contradictory.
#[test]
fn fast_path_implies_no_test_commits() {
    let good = CommitReport {
        fb_delta_fast_path: true,
        test_commits_issued: 0,
        ..CommitReport::default()
    };
    assert!(good.fast_path_consistent());

    let contradictory = CommitReport {
        fb_delta_fast_path: true,
        test_commits_issued: 1,
        ..CommitReport::default()
    };
    assert!(!contradictory.fast_path_consistent());

    // Not taking the fast path says nothing about the count.
    let warm = CommitReport {
        fb_delta_fast_path: false,
        test_commits_issued: 1,
        ..CommitReport::default()
    };
    assert!(warm.fast_path_consistent());
}

#[test]
fn an_empty_report_is_balanced_and_consistent() {
    let report = CommitReport::default();
    assert!(report.accounting_balances());
    assert!(report.fast_path_consistent());
    assert!(report.placements.is_empty());
    assert!(!report.fb_delta_fast_path);
}

#[test]
fn placements_describe_each_layer_outcome() {
    let report = CommitReport {
        layers_total: 2,
        layers_assigned: 1,
        layers_unassigned: 1,
        placements: vec![
            LayerPlacement {
                layer: LayerId(1),
                placement: Placement::AssignedToPlane,
                plane_id: Some(31),
                plane_rotation_bits: 0b0001,
            },
            LayerPlacement {
                layer: LayerId(2),
                placement: Placement::Unassigned,
                plane_id: None,
                plane_rotation_bits: 0,
            },
        ],
        ..CommitReport::default()
    };

    assert!(report.accounting_balances());
    assert_eq!(report.placements.len(), 2);
    assert_eq!(
        report.placements[1].plane_id, None,
        "unassigned has no plane"
    );
    assert_eq!(
        report.placements[1].plane_rotation_bits, 0,
        "and no rotation mask to report"
    );
}

// --- the deferred-release ring: invariants 1, 2 and 5 ------------------------

fn acquisition(layer: u64, fb_id: u32) -> Acquisition {
    Acquisition::new(
        LayerId(layer),
        AcquiredBuffer {
            fb_id,
            ..AcquiredBuffer::default()
        },
    )
}

/// The framebuffer ids returned, in order.
fn released_fbs(released: &Released) -> Vec<u32> {
    released
        .acquisitions
        .iter()
        .map(|a| a.buffer.fb_id)
        .collect()
}

/// **Invariant 1.** A buffer is released only after the flip that stops
/// scanning it out completes — two commits deep, never at ioctl return.
///
/// Frame 1 and frame 2 must return nothing: frame 1's buffer is still on
/// screen when frame 2 commits. Only frame 3 retires it.
#[test]
fn release_is_deferred_two_commits_deep() {
    let mut queue = ReleaseQueue::new();

    let first = queue.commit_succeeded(vec![acquisition(1, 100)], None, |_| false);
    assert!(
        first.is_empty(),
        "frame 1's buffer is being scanned out; releasing it here is the tear"
    );

    let second = queue.commit_succeeded(vec![acquisition(1, 200)], None, |_| false);
    assert!(
        second.is_empty(),
        "frame 1's buffer only leaves the screen when frame 2's flip completes, \
         which the *next* commit observes"
    );

    let third = queue.commit_succeeded(vec![acquisition(1, 300)], None, |_| false);
    assert_eq!(
        released_fbs(&third),
        vec![100],
        "two commits deep: frame 1 retires now"
    );
    assert_eq!(third.reason, ReleaseReason::Retired);

    let fourth = queue.commit_succeeded(vec![acquisition(1, 400)], None, |_| false);
    assert_eq!(released_fbs(&fourth), vec![200], "then frame 2, in order");
}

/// The ring holds exactly two generations, however long it runs.
#[test]
fn the_ring_holds_exactly_two_generations() {
    let mut queue = ReleaseQueue::new();
    assert!(queue.is_empty());

    for frame in 0..20u32 {
        queue.commit_succeeded(vec![acquisition(1, frame)], None, |_| false);
        assert!(
            queue.in_flight() <= 2,
            "frame {frame}: {} buffers in flight, expected at most 2",
            queue.in_flight()
        );
    }
    assert_eq!(queue.in_flight(), 2, "steady state holds N-1 and N-2");
}

/// **Invariant 2.** A failed commit releases that frame's acquisitions
/// immediately — no flip is in flight to gate them on, and a self-healing
/// producer ring depends on reusing them at once.
#[test]
fn a_failed_commit_releases_its_own_acquisitions_at_once() {
    let mut queue = ReleaseQueue::new();
    queue.commit_succeeded(vec![acquisition(1, 100)], None, |_| false);

    let failed = queue.commit_failed(vec![acquisition(1, 200)]);

    assert_eq!(
        released_fbs(&failed),
        vec![200],
        "this frame's buffer comes straight back"
    );
    assert_eq!(failed.reason, ReleaseReason::CommitFailed);
}

/// A failed commit must **not** disturb what is on screen. The previous
/// commit's buffers are still being scanned out — a rejection displaced
/// nothing.
#[test]
fn a_failed_commit_leaves_the_in_flight_generations_alone() {
    let mut queue = ReleaseQueue::new();
    queue.commit_succeeded(vec![acquisition(1, 100)], None, |_| false);
    queue.commit_succeeded(vec![acquisition(1, 200)], None, |_| false);
    let before = queue.in_flight();

    queue.commit_failed(vec![acquisition(1, 300)]);
    assert_eq!(queue.in_flight(), before, "nothing on screen changed");

    // And the ring is unbroken: the next success still retires frame 1.
    let next = queue.commit_succeeded(vec![acquisition(1, 400)], None, |_| false);
    assert_eq!(
        released_fbs(&next),
        vec![100],
        "a rejected commit must not skip a generation"
    );
}

/// A test commit applies nothing to hardware, so its buffers come back at once
/// too — reported distinctly, because the caller counts them differently.
#[test]
fn a_test_commit_releases_immediately_and_is_distinguishable() {
    let mut queue = ReleaseQueue::new();
    let released = queue.test_committed(vec![acquisition(1, 100)]);

    assert_eq!(released_fbs(&released), vec![100]);
    assert_eq!(released.reason, ReleaseReason::TestOnly);
    assert!(queue.is_empty(), "a test commit holds nothing in flight");
}

/// **Invariant 5's counterpart.** Draining returns everything held, oldest
/// first, for teardown and session pause — paths with no flip in flight, where
/// holding buffers back would simply leak them.
#[test]
fn draining_returns_every_held_buffer_oldest_first() {
    let mut queue = ReleaseQueue::new();
    queue.commit_succeeded(vec![acquisition(1, 100)], None, |_| false);
    queue.commit_succeeded(vec![acquisition(1, 200)], None, |_| false);
    assert_eq!(queue.in_flight(), 2);

    let drained = queue.drain();

    assert_eq!(
        released_fbs(&drained),
        vec![100, 200],
        "oldest first, matching the order a running scene would have used"
    );
    assert_eq!(drained.reason, ReleaseReason::Drained);
    assert!(queue.is_empty(), "draining leaves nothing behind");
}

#[test]
fn draining_an_empty_queue_is_harmless() {
    let mut queue = ReleaseQueue::new();
    let drained = queue.drain();
    assert!(drained.is_empty());
    assert_eq!(drained.len(), 0);
}

/// Multiple layers rotate together: a frame's buffers retire as a set.
#[test]
fn every_layers_buffer_retires_together() {
    let mut queue = ReleaseQueue::new();

    queue.commit_succeeded(vec![acquisition(1, 100), acquisition(2, 101)], None, |_| {
        false
    });
    queue.commit_succeeded(vec![acquisition(1, 200), acquisition(2, 201)], None, |_| {
        false
    });
    let third =
        queue.commit_succeeded(vec![acquisition(1, 300), acquisition(2, 301)], None, |_| {
            false
        });

    let mut fbs = released_fbs(&third);
    fbs.sort_unstable();
    assert_eq!(
        fbs,
        vec![100, 101],
        "both layers' frame-1 buffers retire together"
    );
}

/// A layer that skipped a frame — its source returned `WouldBlock` — simply
/// contributes nothing to that generation, and the ring stays consistent.
#[test]
fn a_skipped_layer_does_not_break_the_rotation() {
    let mut queue = ReleaseQueue::new();

    queue.commit_succeeded(vec![acquisition(1, 100), acquisition(2, 101)], None, |_| {
        false
    });
    // Layer 2 had no frame this vblank.
    queue.commit_succeeded(vec![acquisition(1, 200)], None, |_| false);
    let third = queue.commit_succeeded(vec![acquisition(1, 300)], None, |_| false);

    let mut fbs = released_fbs(&third);
    fbs.sort_unstable();
    assert_eq!(fbs, vec![100, 101]);

    let fourth = queue.commit_succeeded(vec![acquisition(1, 400)], None, |_| false);
    assert_eq!(
        released_fbs(&fourth),
        vec![200],
        "only layer 1 contributed to frame 2"
    );
}

/// The release fence is stamped only onto sources that asked for it, so a scene
/// with no interested source pays nothing.
#[test]
fn the_release_fence_is_stamped_only_where_wanted() {
    use std::os::fd::AsFd as _;

    let mut queue = ReleaseQueue::new();
    queue.commit_succeeded(vec![acquisition(1, 100), acquisition(2, 101)], None, |_| {
        false
    });

    // An eventfd stands in for the commit's OUT_FENCE.
    let raw = rustix::event::eventfd(0, rustix::event::EventfdFlags::CLOEXEC).expect("eventfd");
    let fence = drmkit_sync::SyncFence::import(raw.as_fd()).expect("import");

    // Only layer 1 wants it.
    queue.commit_succeeded(vec![acquisition(1, 200)], Some(&fence), |layer| {
        layer == LayerId(1)
    });

    // Frame 1's buffers retire next commit; check what came back stamped.
    let retired = queue.commit_succeeded(vec![acquisition(1, 300)], None, |_| false);
    let stamped: Vec<(u32, bool)> = retired
        .acquisitions
        .iter()
        .map(|a| (a.buffer.fb_id, a.release_fence.is_some()))
        .collect();

    assert_eq!(stamped.len(), 2);
    assert!(
        stamped.contains(&(100, true)),
        "layer 1 opted in and must get the fence: {stamped:?}"
    );
    assert!(
        stamped.contains(&(101, false)),
        "layer 2 did not opt in and must not: {stamped:?}"
    );
}

/// No fence offered means nothing stamped, whatever the sources want.
#[test]
fn no_out_fence_means_nothing_is_stamped() {
    let mut queue = ReleaseQueue::new();
    queue.commit_succeeded(vec![acquisition(1, 100)], None, |_| true);
    queue.commit_succeeded(vec![acquisition(1, 200)], None, |_| true);

    let retired = queue.commit_succeeded(vec![acquisition(1, 300)], None, |_| true);
    assert!(
        retired
            .acquisitions
            .iter()
            .all(|a| a.release_fence.is_none()),
        "a CRTC without OUT_FENCE_PTR stamps nothing"
    );
}

// --- invariant 5: the armed-flip tripwire ------------------------------------

/// Dropping a scene with a flip still armed is the RmFB-on-in-flight-FB hazard.
/// Tracking it is what lets the scene's drop say so out loud.
#[test]
fn pending_flip_tracks_whether_teardown_is_safe() {
    let mut pending = ScenePendingFlip::new();
    assert!(!pending.is_armed(), "nothing committed yet");

    pending.arm();
    assert!(
        pending.is_armed(),
        "a commit that armed PAGE_FLIP_EVENT still references its framebuffer"
    );

    pending.landed();
    assert!(!pending.is_armed(), "once dispatched, teardown is safe");
}

// --- lowering ----------------------------------------------------------------

use drmkit_planes::{Layer as PlaneLayer, PropTag};

fn lowering_input() -> LoweringInput {
    LoweringInput {
        display: DisplayParams {
            dst_rect: Rect {
                x: 10,
                y: 20,
                w: 640,
                h: 480,
            },
            ..DisplayParams::default()
        },
        format: SourceFormat {
            fourcc: 0x3234_5258, // XR24
            modifier: 0,
            width: 1920,
            height: 1080,
        },
        binding: BindingModel::SceneSubmitsFbId,
        fb_id: 42,
        crtc_id: 7,
        default_zpos: None,
    }
}

#[test]
fn lowering_writes_the_destination_rectangle_in_whole_pixels() {
    let mut plane_layer = PlaneLayer::new();
    lower_layer(&lowering_input(), &mut plane_layer);

    assert_eq!(plane_layer.property(PropTag::CrtcX), Some(10));
    assert_eq!(plane_layer.property(PropTag::CrtcY), Some(20));
    assert_eq!(plane_layer.property(PropTag::CrtcW), Some(640));
    assert_eq!(plane_layer.property(PropTag::CrtcH), Some(480));
}

/// A zero-sized source rectangle means "the buffer's full extent".
///
/// Callers commonly set only `dst_rect` — the scene cannot guess a screen
/// position but can read the source extent from the format. Without this
/// resolution `SRC_W`/`SRC_H` go out as 0, which the kernel rejects with
/// `EINVAL`; the C++ records that as the root cause of direct scanout failing
/// on every controller it was tried on, sending every frame through
/// composition.
#[test]
fn an_unset_source_rectangle_resolves_to_the_buffer_extent() {
    let mut plane_layer = PlaneLayer::new();
    lower_layer(&lowering_input(), &mut plane_layer);

    assert_eq!(
        plane_layer.property(PropTag::SrcW),
        Some(to_16_16(1920)),
        "an unset source width must become the buffer width, never 0"
    );
    assert_eq!(plane_layer.property(PropTag::SrcH), Some(to_16_16(1080)));
    assert_ne!(plane_layer.property(PropTag::SrcW), Some(0));
}

#[test]
fn an_explicit_source_rectangle_is_kept_and_converted_to_fixed_point() {
    let mut input = lowering_input();
    input.display.src_rect = Rect {
        x: 8,
        y: 16,
        w: 320,
        h: 240,
    };

    let mut plane_layer = PlaneLayer::new();
    lower_layer(&input, &mut plane_layer);

    assert_eq!(plane_layer.property(PropTag::SrcX), Some(to_16_16(8)));
    assert_eq!(plane_layer.property(PropTag::SrcY), Some(to_16_16(16)));
    assert_eq!(plane_layer.property(PropTag::SrcW), Some(320 << 16));
    assert_eq!(plane_layer.property(PropTag::SrcH), Some(240 << 16));
}

/// `CRTC_ID` must always be written. Without it the kernel rejects the plane
/// commit — the framebuffer is armed but the plane is still bound to whatever
/// the previous commit left — so every allocator test fails and the scene
/// reports zero layers assigned.
#[test]
fn crtc_id_is_always_written() {
    let mut plane_layer = PlaneLayer::new();
    lower_layer(&lowering_input(), &mut plane_layer);
    assert_eq!(plane_layer.property(PropTag::CrtcId), Some(7));

    // Even for a driver-owned binding, which skips only FB_ID.
    let mut input = lowering_input();
    input.binding = BindingModel::DriverOwnsBinding;
    let mut driver_owned = PlaneLayer::new();
    lower_layer(&input, &mut driver_owned);
    assert_eq!(driver_owned.property(PropTag::CrtcId), Some(7));
}

/// A driver-owned binding gets its `FB_ID` from the producer's extension stack,
/// so writing it here would race the consumer's internal state. The layer is
/// also flagged externally bound so the allocator skips it.
#[test]
fn a_driver_owned_binding_skips_fb_id_and_is_marked_external() {
    let mut input = lowering_input();
    input.binding = BindingModel::DriverOwnsBinding;

    let mut plane_layer = PlaneLayer::new();
    lower_layer(&input, &mut plane_layer);

    assert_eq!(
        plane_layer.property(PropTag::FbId),
        None,
        "the scene must not write FB_ID for a driver-owned binding"
    );
    assert!(plane_layer.is_externally_bound());
}

#[test]
fn a_scene_owned_binding_writes_fb_id_and_is_not_external() {
    let mut plane_layer = PlaneLayer::new();
    lower_layer(&lowering_input(), &mut plane_layer);

    assert_eq!(plane_layer.property(PropTag::FbId), Some(42));
    assert!(!plane_layer.is_externally_bound());
}

/// Format and modifier reach the bag so the allocator can screen planes before
/// issuing any test commit.
#[test]
fn format_and_modifier_reach_the_property_bag() {
    let mut input = lowering_input();
    input.format.modifier = 0x0800_0000_0000_0001; // AFBC(16x16)

    let mut plane_layer = PlaneLayer::new();
    lower_layer(&input, &mut plane_layer);

    assert_eq!(plane_layer.format(), Some(0x3234_5258));
    assert_eq!(plane_layer.modifier(), 0x0800_0000_0000_0001);
}

/// **`zpos` is written only when asked for.** Emitting 0 unconditionally would
/// statically disqualify any primary plane with an immutable non-zero `zpos` —
/// amdgpu pins primary at 2 — leaving a single-layer scene with nowhere to go.
#[test]
fn zpos_is_left_unwritten_unless_requested() {
    let mut plane_layer = PlaneLayer::new();
    lower_layer(&lowering_input(), &mut plane_layer);
    assert_eq!(
        plane_layer.property(PropTag::Zpos),
        None,
        "an unrequested zpos must not be written as 0"
    );

    let mut explicit = lowering_input();
    explicit.display.zpos = Some(3);
    let mut with_zpos = PlaneLayer::new();
    lower_layer(&explicit, &mut with_zpos);
    assert_eq!(with_zpos.property(PropTag::Zpos), Some(3));
}

/// The scene's hint fills in only when the caller expressed no preference.
#[test]
fn the_default_zpos_hint_only_applies_when_unset() {
    let mut hinted = lowering_input();
    hinted.default_zpos = Some(1);
    let mut plane_layer = PlaneLayer::new();
    lower_layer(&hinted, &mut plane_layer);
    assert_eq!(plane_layer.property(PropTag::Zpos), Some(1));

    // An explicit request wins over the hint.
    hinted.display.zpos = Some(4);
    let mut explicit = PlaneLayer::new();
    lower_layer(&hinted, &mut explicit);
    assert_eq!(explicit.property(PropTag::Zpos), Some(4));
}

/// Rotation is likewise conditional: zero means "no rotation", and writing it
/// would claim a capability the plane may not have.
#[test]
fn rotation_is_written_only_when_non_zero() {
    let mut plane_layer = PlaneLayer::new();
    lower_layer(&lowering_input(), &mut plane_layer);
    assert_eq!(plane_layer.property(PropTag::Rotation), None);

    let mut rotated = lowering_input();
    rotated.display.rotation = 0b0010;
    let mut with_rotation = PlaneLayer::new();
    lower_layer(&rotated, &mut with_rotation);
    assert_eq!(with_rotation.property(PropTag::Rotation), Some(0b0010));
}

#[test]
fn alpha_is_written_only_when_requested() {
    let mut plane_layer = PlaneLayer::new();
    lower_layer(&lowering_input(), &mut plane_layer);
    assert_eq!(plane_layer.property(PropTag::Alpha), None);

    let mut translucent = lowering_input();
    translucent.display.alpha = Some(0x8000);
    let mut with_alpha = PlaneLayer::new();
    lower_layer(&translucent, &mut with_alpha);
    assert_eq!(with_alpha.property(PropTag::Alpha), Some(0x8000));
}

/// A negative destination position round-trips: a plane may extend off-screen,
/// and KMS carries `CRTC_X`/`CRTC_Y` as signed values in unsigned slots.
#[test]
fn a_negative_destination_position_round_trips() {
    let mut input = lowering_input();
    input.display.dst_rect.x = -64;
    input.display.dst_rect.y = -32;

    let mut plane_layer = PlaneLayer::new();
    lower_layer(&input, &mut plane_layer);

    let rect = plane_layer.crtc_rect();
    assert_eq!(rect.x, -64, "a plane may extend off the left edge");
    assert_eq!(rect.y, -32);
}

/// A lowered layer must be scale-detectable: the allocator screens planes on
/// it, and getting the fixed-point conversion wrong would make every layer look
/// scaled.
#[test]
fn a_one_to_one_layer_does_not_read_as_scaled() {
    let mut input = lowering_input();
    input.display.dst_rect = Rect {
        x: 0,
        y: 0,
        w: 1920,
        h: 1080,
    };

    let mut plane_layer = PlaneLayer::new();
    lower_layer(&input, &mut plane_layer);
    assert!(
        !plane_layer.requires_scaling(),
        "a full-extent source into a matching destination is 1:1"
    );

    // And a genuine downscale does.
    input.display.dst_rect.w = 1280;
    let mut scaled = PlaneLayer::new();
    lower_layer(&input, &mut scaled);
    assert!(scaled.requires_scaling());
}

/// `SceneDisplayParams.FixedSrcRectScalesOnItsExactSize`: a 16.16 source
/// rectangle scales exactly when its size, not rounded to whole pixels,
/// differs from the destination's. Here through the lowered properties, which
/// are what the allocator reads; there is no `needs_scaling` on the params.
#[test]
fn a_fixed_source_rectangle_scales_on_its_exact_size() {
    let scaled = |fixed: Option<FixedRect>| {
        let mut input = lowering_input();
        input.display.src_rect = Rect {
            x: 0,
            y: 0,
            w: 10,
            h: 10,
        }; // ignored once the fixed rect is set
        input.display.dst_rect = Rect {
            x: 0,
            y: 0,
            w: 800,
            h: 600,
        };
        input.display.src_rect_fixed = fixed;
        let mut plane_layer = PlaneLayer::new();
        lower_layer(&input, &mut plane_layer);
        plane_layer.requires_scaling()
    };
    let rect = |x, w| {
        Some(FixedRect {
            x,
            y: 0,
            w,
            h: 600 << 16,
        })
    };
    assert!(
        !scaled(rect(0x8000, 800 << 16)),
        "a half-pixel offset alone is no scale"
    );
    assert!(scaled(rect(0, (800 << 16) - 0x8000)), "799.5 px onto 800");
    assert!(scaled(None), "back to the whole-pixel rect, 10 onto 800");
    // Beyond upstream: a fraction *above* the destination size scales too.
    // drm-cxx truncates SRC_W to whole pixels there and reads 800.25 as 1:1.
    assert!(scaled(rect(0, (800 << 16) + 0x4000)), "800.25 px onto 800");
}

/// A fixed source rectangle goes to `SRC_*` as given, and a zero size still
/// means the buffer's full extent.
#[test]
fn a_fixed_source_rectangle_is_written_as_given() {
    let mut input = lowering_input();
    input.display.src_rect_fixed = Some(FixedRect {
        x: 0x8000,
        y: 0x0040,
        w: (320 << 16) + 0x100,
        h: 0,
    });
    let mut plane_layer = PlaneLayer::new();
    lower_layer(&input, &mut plane_layer);

    assert_eq!(plane_layer.property(PropTag::SrcX), Some(0x8000));
    assert_eq!(plane_layer.property(PropTag::SrcY), Some(0x0040));
    assert_eq!(
        plane_layer.property(PropTag::SrcW),
        Some((320 << 16) + 0x100)
    );
    assert_eq!(plane_layer.property(PropTag::SrcH), Some(to_16_16(1080)));
}

/// The canvas samples whole pixels, so it rounds a fixed rectangle to the
/// nearest one, half up.
#[test]
fn the_canvas_rounds_a_fixed_rectangle_to_whole_pixels() {
    use crate::scene::round_16_16;
    assert_eq!(round_16_16(0), 0);
    assert_eq!(round_16_16(0x7fff), 0);
    assert_eq!(round_16_16(0x8000), 1);
    assert_eq!(round_16_16((799 << 16) + 0x8000), 800);
    assert_eq!(round_16_16(u32::MAX), 0x1_0000);
}

// --- frame lifecycle: what a commit does to scene state ----------------------

fn real_commit() -> CommitKind {
    CommitKind::Real { arms_flip: true }
}

/// A successful real commit rotates the ring — invariant 1 end to end through
/// the lifecycle rather than the queue alone.
#[test]
fn a_successful_commit_rotates_and_arms_the_flip() {
    let mut lifecycle = FrameLifecycle::new();

    let first = lifecycle.finalize(
        real_commit(),
        KernelResult::Ok,
        vec![acquisition(1, 100)],
        CommitReport::default(),
        None,
        |_| false,
    );
    assert!(first.released.is_empty(), "nothing has left the screen yet");
    assert!(lifecycle.has_pending_flip(), "a real commit armed a flip");
    assert!(!first.suspended);

    lifecycle.finalize(
        real_commit(),
        KernelResult::Ok,
        vec![acquisition(1, 200)],
        CommitReport::default(),
        None,
        |_| false,
    );
    let third = lifecycle.finalize(
        real_commit(),
        KernelResult::Ok,
        vec![acquisition(1, 300)],
        CommitReport::default(),
        None,
        |_| false,
    );
    assert_eq!(released_fbs(&third.released), vec![100]);
}

/// A commit that does not arm a flip leaves teardown safe.
#[test]
fn a_commit_without_a_flip_event_leaves_no_pending_flip() {
    let mut lifecycle = FrameLifecycle::new();
    lifecycle.finalize(
        CommitKind::Real { arms_flip: false },
        KernelResult::Ok,
        vec![acquisition(1, 100)],
        CommitReport::default(),
        None,
        |_| false,
    );
    assert!(!lifecycle.has_pending_flip());
}

/// **Invariant 2, both clauses.** A non-`EACCES` rejection releases this
/// frame's buffers at once and does **not** suspend the scene. Suspending on a
/// recoverable stumble would stop a scene that should have healed next frame.
#[test]
fn an_ordinary_rejection_releases_but_does_not_suspend() {
    let mut lifecycle = FrameLifecycle::new();
    lifecycle.finalize(
        real_commit(),
        KernelResult::Ok,
        vec![acquisition(1, 100)],
        CommitReport::default(),
        None,
        |_| false,
    );

    let rejected = lifecycle.finalize(
        real_commit(),
        KernelResult::Rejected,
        vec![acquisition(1, 200)],
        CommitReport::default(),
        None,
        |_| false,
    );

    assert_eq!(released_fbs(&rejected.released), vec![200]);
    assert_eq!(rejected.released.reason, ReleaseReason::CommitFailed);
    assert!(
        !rejected.suspended,
        "a non-EACCES failure must not suspend the scene -- the frame heals"
    );
    assert!(!lifecycle.is_suspended());
}

/// Lost DRM master is the one failure that suspends.
#[test]
fn lost_master_suspends_the_scene() {
    let mut lifecycle = FrameLifecycle::new();

    let outcome = lifecycle.finalize(
        real_commit(),
        KernelResult::NotMaster,
        vec![acquisition(1, 100)],
        CommitReport::default(),
        None,
        |_| false,
    );

    assert!(outcome.suspended);
    assert!(lifecycle.is_suspended());
    assert_eq!(
        released_fbs(&outcome.released),
        vec![100],
        "the buffers still come straight back"
    );

    lifecycle.resume();
    assert!(!lifecycle.is_suspended(), "a session resume lifts it");
}

/// **Invariant 4's safety net.** The kernel rejected a frame whose `TEST_ONLY`
/// was skipped, so the cached allocation is no longer trustworthy: drop it and
/// re-search next frame. The frame is dropped but heals — never corruption.
#[test]
fn a_rejected_fast_path_frame_invalidates_the_cached_allocation() {
    let mut lifecycle = FrameLifecycle::new();
    let report = CommitReport {
        fb_delta_fast_path: true,
        test_commits_issued: 0,
        ..CommitReport::default()
    };

    let outcome = lifecycle.finalize(
        real_commit(),
        KernelResult::Rejected,
        vec![acquisition(1, 100)],
        report,
        None,
        |_| false,
    );

    assert!(
        outcome.invalidate_allocation,
        "a fast-path frame the kernel refused must drop the cache"
    );
    assert!(
        !outcome.report.fb_delta_fast_path,
        "and the report must stop claiming a fast path that did not hold"
    );
    assert!(lifecycle.has_warned_fast_path_reject());
    assert!(!outcome.suspended, "it is still a recoverable rejection");
}

/// A rejection *after* a real test says nothing new about the cache, so it must
/// not invalidate it — that would throw away a good assignment every time the
/// kernel refused for an unrelated reason.
#[test]
fn an_ordinary_rejection_does_not_invalidate_the_cache() {
    let mut lifecycle = FrameLifecycle::new();
    let report = CommitReport {
        fb_delta_fast_path: false,
        test_commits_issued: 1,
        ..CommitReport::default()
    };

    let outcome = lifecycle.finalize(
        real_commit(),
        KernelResult::Rejected,
        vec![acquisition(1, 100)],
        report,
        None,
        |_| false,
    );

    assert!(!outcome.invalidate_allocation);
    assert!(!lifecycle.has_warned_fast_path_reject());
}

/// A test commit changes nothing: no rotation, no flip, no suspension.
#[test]
fn a_test_commit_leaves_scene_state_untouched() {
    let mut lifecycle = FrameLifecycle::new();
    lifecycle.finalize(
        real_commit(),
        KernelResult::Ok,
        vec![acquisition(1, 100)],
        CommitReport::default(),
        None,
        |_| false,
    );
    let in_flight = lifecycle.buffers_in_flight();
    lifecycle.flip_landed();

    let outcome = lifecycle.finalize(
        CommitKind::Test,
        KernelResult::Ok,
        vec![acquisition(1, 200)],
        CommitReport::default(),
        None,
        |_| false,
    );

    assert_eq!(released_fbs(&outcome.released), vec![200]);
    assert_eq!(outcome.released.reason, ReleaseReason::TestOnly);
    assert_eq!(
        lifecycle.buffers_in_flight(),
        in_flight,
        "a test applied nothing, so nothing rotated"
    );
    assert!(!lifecycle.has_pending_flip(), "and armed no flip");
}

/// Even a *failed* test releases immediately and does not suspend — the kind
/// decides the handling, not the result.
#[test]
fn a_failed_test_commit_is_still_just_a_test() {
    let mut lifecycle = FrameLifecycle::new();
    let outcome = lifecycle.finalize(
        CommitKind::Test,
        KernelResult::NotMaster,
        vec![acquisition(1, 100)],
        CommitReport::default(),
        None,
        |_| false,
    );

    assert_eq!(outcome.released.reason, ReleaseReason::TestOnly);
    assert!(
        !outcome.suspended,
        "a probe that could not run is not a reason to stop the scene"
    );
}

/// **Invariant 5.** The tripwire tracks whether teardown is safe, and draining
/// does not clear it — landing the flip is the caller's job.
#[test]
fn draining_does_not_land_the_flip() {
    let mut lifecycle = FrameLifecycle::new();
    lifecycle.finalize(
        real_commit(),
        KernelResult::Ok,
        vec![acquisition(1, 100)],
        CommitReport::default(),
        None,
        |_| false,
    );
    assert!(lifecycle.has_pending_flip());

    let drained = lifecycle.drain();
    assert_eq!(drained.reason, ReleaseReason::Drained);
    assert_eq!(lifecycle.buffers_in_flight(), 0);
    assert!(
        lifecycle.has_pending_flip(),
        "draining returns buffers; it does not wait on the kernel, so the flip \
         is still outstanding and teardown is still unsafe"
    );

    lifecycle.flip_landed();
    assert!(!lifecycle.has_pending_flip());
}

// --- EAGAIN accounting -------------------------------------------------------

/// A source with nothing to contribute is skipped and counted, never treated as
/// a failure — the flow-control half of DR-6, at the accounting level.
#[test]
fn the_acquire_tally_separates_skips_from_acquisitions() {
    let mut tally = AcquireTally::default();

    assert!(tally.record(true));
    assert!(!tally.record(false));
    assert!(tally.record(true));

    assert_eq!(tally.acquired, 2);
    assert_eq!(tally.skipped_no_frame, 1);
    assert_eq!(
        tally.considered(),
        3,
        "every layer is accounted for exactly once"
    );
}

/// The tally is what keeps the commit report's accounting balanced: a skipped
/// layer belongs in `layers_skipped_no_frame`, not in the failure tallies.
#[test]
fn skipped_layers_keep_the_report_balanced() {
    let mut tally = AcquireTally::default();
    tally.record(true);
    tally.record(false);
    tally.record(false);

    let report = CommitReport {
        layers_total: tally.considered(),
        layers_assigned: tally.acquired,
        layers_skipped_no_frame: tally.skipped_no_frame,
        ..CommitReport::default()
    };
    assert!(
        report.accounting_balances(),
        "a skipped layer must be counted somewhere, or the invariant breaks"
    );
}

// --- acquire fences ----------------------------------------------------------

/// A plane that takes `IN_FENCE_FD` gets the fence.
///
/// `AcquiredBuffer::acquire_fence` means the pixels are not valid yet. Giving
/// the descriptor to KMS is what makes the kernel hold scanout until the
/// producer signals; without it a half-rendered frame reaches the screen with
/// nothing having waited.
#[test]
fn a_plane_that_takes_a_fence_is_armed_with_it() {
    assert_eq!(
        crate::fence_action(Some(77)),
        crate::FenceAction::Arm { property_id: 77 },
    );
}

/// A plane that does not falls back to waiting on the CPU.
///
/// There is nowhere to put the fence, so the wait has to happen before the
/// commit instead. Slower, and the whole point: the alternative is not "no
/// wait", it is scanning out a buffer the producer has not finished.
///
/// This branch is why the decision is a function rather than an `if` inside
/// the arming loop. vkms advertises `IN_FENCE_FD` on all ten of its planes, so
/// no test against it can ever reach the fallback.
#[test]
fn a_plane_without_the_property_falls_back_to_a_cpu_wait() {
    assert_eq!(crate::fence_action(None), crate::FenceAction::CpuWait);
}

/// A derived zpos is bent to fit the plane, not sent to be refused.
///
/// Found on a Raspberry Pi 5: vc4's overlays advertise `zpos [1, 17]`, the
/// composition canvas asked for 19 -- one above the 18 layers in the scene --
/// and the kernel refused the entire frame with `EINVAL`, all sixteen
/// correctly programmed layers along with it. vkms exposes no zpos property at
/// all, so nothing there ever writes one and no lane could have caught it.
#[test]
fn a_canvas_zpos_above_the_plane_range_is_clamped_not_sent() {
    let mut map = PlanePropertyMap::new();
    map.zpos_range.insert(7, (1, 17));

    assert_eq!(
        map.clamp_zpos(7, 19),
        17,
        "above the range clamps to the top"
    );
    assert_eq!(
        map.clamp_zpos(7, 0),
        1,
        "below the range clamps to the bottom"
    );
    assert_eq!(map.clamp_zpos(7, 9), 9, "inside the range is left alone");
    assert_eq!(
        map.clamp_zpos(7, 17),
        17,
        "the top of the range is inside it"
    );

    // A plane that advertises no range is not second-guessed: the value goes
    // as-is and the kernel decides, which is what happens on vkms.
    assert_eq!(
        map.clamp_zpos(8, 19),
        19,
        "no known range means no clamping"
    );
}

/// A zpos fixed at one value, which the kernel does not flag immutable.
///
/// This is P-6, and the hardware is real: two Allwinner boards in the drmdb
/// corpus advertise `zpos` with `min == max == 0` and leave it mutable, so
/// `PlanePropertyMap` keeps it in the writable set. Writing anything but 0 to
/// such a plane is `EINVAL`, which refuses the whole frame.
///
/// The reference guards it separately, with `zpos_is_fixed`, because it sends
/// the requested value through unchanged. Here the clamp added for P-15
/// already covers it: a degenerate range admits exactly one value, so the
/// derived zpos becomes a write the kernel takes.
///
/// If the clamp is ever narrowed to skip degenerate ranges as a no-op, this
/// is what says those two boards stop scanning out.
#[test]
fn a_degenerate_zpos_clamps_to_the_only_value_it_will_take() {
    let mut map = PlanePropertyMap::new();
    map.zpos_range.insert(42, (0, 0));

    assert_eq!(
        map.clamp_zpos(42, 3),
        0,
        "the only legal value, not the one that would be refused"
    );
    assert_eq!(map.clamp_zpos(42, 0), 0, "and asking for it is unchanged");
}

// --- the primary anchor (P-26) ----------------------------------------------

/// A plane for the reservation cases, with a zpos range if it has one.
fn reservation_plane(
    id: u32,
    plane_type: drmkit_planes::PlaneType,
    zpos: Option<(u64, u64)>,
) -> drmkit_planes::PlaneCapabilities {
    drmkit_planes::PlaneCapabilities {
        id,
        possible_crtcs: 0b1,
        plane_type,
        formats: vec![drmkit_fmt::fourcc::ARGB8888, drmkit_fmt::fourcc::XRGB8888],
        zpos_min: zpos.map(|(min, _)| min),
        zpos_max: zpos.map(|(_, max)| max),
        ..drmkit_planes::PlaneCapabilities::default()
    }
}

/// A layer carrying an explicit zpos, or none.
fn reservation_layer(zpos: Option<u64>) -> drmkit_planes::Layer {
    let mut layer = drmkit_planes::Layer::default();
    if let Some(zpos) = zpos {
        layer.set_property(drmkit_planes::PropTag::Zpos, zpos);
    }
    layer
}

/// **P-26.** A pinned primary nothing can land on is reserved, not left to the
/// disable pass.
///
/// amdgpu pins its primary at zpos 2 and refuses a commit that disables the
/// primary of an active CRTC. With nothing eligible for the primary, nothing
/// assigns it, so the disable pass clears it in every test and the kernel
/// refuses every one. The allocator places nothing and the entire scene falls
/// through to software composition, still correct, still arriving, silently
/// not using the hardware.
///
/// Every layer above the pin is no longer enough to get here: the unique
/// lowest one can take the slot (see the next case). Two layers tied at the
/// bottom, both above it, still can't.
#[test]
fn a_pinned_primary_with_no_eligible_layer_is_reserved() {
    let registry = drmkit_planes::PlaneRegistry::from_capabilities(vec![
        reservation_plane(31, drmkit_planes::PlaneType::Primary, Some((2, 2))),
        reservation_plane(32, drmkit_planes::PlaneType::Overlay, Some((3, 9))),
        reservation_plane(33, drmkit_planes::PlaneType::Overlay, Some((3, 9))),
    ]);
    let layers = [reservation_layer(Some(3)), reservation_layer(Some(3))];
    let refs: Vec<drmkit_planes::LayerRef<'_>> = layers
        .iter()
        .enumerate()
        .map(|(i, layer)| drmkit_planes::LayerRef {
            id: drmkit_planes::LayerId(i as u64 + 1),
            layer,
        })
        .collect();

    assert_eq!(
        crate::scene::canvas_reservation(true, &refs, &registry, 0, None),
        vec![31],
        "the primary is held out of the disable pass"
    );
}

/// A layer that can take the pinned slot needs no anchor: it will be assigned
/// there, and an assigned plane is not disabled.
#[test]
fn a_layer_matching_the_pin_makes_the_anchor_unnecessary() {
    let registry = drmkit_planes::PlaneRegistry::from_capabilities(vec![
        reservation_plane(31, drmkit_planes::PlaneType::Primary, Some((2, 2))),
        reservation_plane(32, drmkit_planes::PlaneType::Overlay, Some((3, 9))),
    ]);
    let layers = [reservation_layer(Some(2)), reservation_layer(Some(3))];
    let refs: Vec<drmkit_planes::LayerRef<'_>> = layers
        .iter()
        .enumerate()
        .map(|(i, layer)| drmkit_planes::LayerRef {
            id: drmkit_planes::LayerId(i as u64 + 1),
            layer,
        })
        .collect();

    assert!(crate::scene::canvas_reservation(true, &refs, &registry, 0, None).is_empty());
}

/// So does a layer with no zpos at all: it is free to land on the pin, and
/// `plane_score`'s primary bonus is what puts it there.
#[test]
fn a_layer_with_no_zpos_makes_the_anchor_unnecessary() {
    let registry = drmkit_planes::PlaneRegistry::from_capabilities(vec![
        reservation_plane(31, drmkit_planes::PlaneType::Primary, Some((2, 2))),
        reservation_plane(32, drmkit_planes::PlaneType::Overlay, Some((3, 9))),
    ]);
    let layers = [reservation_layer(None)];
    let refs: Vec<drmkit_planes::LayerRef<'_>> = layers
        .iter()
        .enumerate()
        .map(|(i, layer)| drmkit_planes::LayerRef {
            id: drmkit_planes::LayerId(i as u64 + 1),
            layer,
        })
        .collect();

    assert!(crate::scene::canvas_reservation(true, &refs, &registry, 0, None).is_empty());
}

/// A primary with no zpos property is not pinned, so there is nothing to
/// anchor. This is vkms, which is why no lane can reach the case above.
#[test]
fn an_unpinned_primary_is_not_anchored() {
    let registry = drmkit_planes::PlaneRegistry::from_capabilities(vec![
        reservation_plane(31, drmkit_planes::PlaneType::Primary, None),
        reservation_plane(32, drmkit_planes::PlaneType::Overlay, None),
    ]);
    let layers = [reservation_layer(Some(3))];
    let refs: Vec<drmkit_planes::LayerRef<'_>> = layers
        .iter()
        .enumerate()
        .map(|(i, layer)| drmkit_planes::LayerRef {
            id: drmkit_planes::LayerId(i as u64 + 1),
            layer,
        })
        .collect();

    assert!(crate::scene::canvas_reservation(true, &refs, &registry, 0, None).is_empty());
}

/// The overflow trigger still works, and takes an overlay so the primary stays
/// free for the bottom layer.
#[test]
fn overflow_reserves_an_overlay_for_the_canvas() {
    let registry = drmkit_planes::PlaneRegistry::from_capabilities(vec![
        reservation_plane(31, drmkit_planes::PlaneType::Primary, Some((0, 0))),
        reservation_plane(32, drmkit_planes::PlaneType::Overlay, Some((1, 4))),
    ]);
    let layers: Vec<drmkit_planes::Layer> = (0..3).map(|_| reservation_layer(None)).collect();
    let refs: Vec<drmkit_planes::LayerRef<'_>> = layers
        .iter()
        .enumerate()
        .map(|(i, layer)| drmkit_planes::LayerRef {
            id: drmkit_planes::LayerId(i as u64 + 1),
            layer,
        })
        .collect();

    assert_eq!(
        crate::scene::canvas_reservation(true, &refs, &registry, 0, None),
        vec![32]
    );
}

fn refs_of(layers: &[drmkit_planes::Layer]) -> Vec<drmkit_planes::LayerRef<'_>> {
    layers
        .iter()
        .enumerate()
        .map(|(i, layer)| drmkit_planes::LayerRef {
            id: drmkit_planes::LayerId(i as u64 + 1),
            layer,
        })
        .collect()
}

/// Two primaries, the shape of P-24 (57 CRTCs across six drivers in the
/// drmdb corpus): the canvas takes the first overlay, not the second primary
/// and not the last plane listed (drm-cxx `6d787f9`).
fn two_primaries() -> drmkit_planes::PlaneRegistry {
    drmkit_planes::PlaneRegistry::from_capabilities(vec![
        reservation_plane(31, drmkit_planes::PlaneType::Primary, Some((0, 0))),
        reservation_plane(32, drmkit_planes::PlaneType::Primary, Some((0, 0))),
        reservation_plane(33, drmkit_planes::PlaneType::Overlay, Some((1, 8))),
        reservation_plane(34, drmkit_planes::PlaneType::Overlay, Some((1, 8))),
    ])
}

#[test]
fn with_two_primaries_overflow_reserves_the_first_overlay() {
    let layers: Vec<drmkit_planes::Layer> = (0..5).map(|_| reservation_layer(None)).collect();
    assert_eq!(
        crate::scene::canvas_reservation(true, &refs_of(&layers), &two_primaries(), 0, None),
        vec![33]
    );
}

/// The canvas keeps last frame's plane, so it does not move between frames.
#[test]
fn overflow_reserves_last_frames_canvas_plane() {
    let layers: Vec<drmkit_planes::Layer> = (0..5).map(|_| reservation_layer(None)).collect();
    assert_eq!(
        crate::scene::canvas_reservation(true, &refs_of(&layers), &two_primaries(), 0, Some(34)),
        vec![34]
    );
}

/// Overflow never reserves a multirect virtual plane, last frame's or the
/// first overlay: held, it is armed in every test the allocator runs, which
/// fail whenever the search gives its parent away (drm-cxx `4b366b5`).
#[test]
fn overflow_never_reserves_a_virtual_plane() {
    let registry = drmkit_planes::PlaneRegistry::from_capabilities(vec![
        reservation_plane(31, drmkit_planes::PlaneType::Primary, Some((0, 0))),
        drmkit_planes::PlaneCapabilities {
            multirect_parent: Some(34),
            ..reservation_plane(33, drmkit_planes::PlaneType::Overlay, Some((1, 8)))
        },
        reservation_plane(34, drmkit_planes::PlaneType::Overlay, Some((1, 8))),
    ]);
    let layers: Vec<drmkit_planes::Layer> = (0..5).map(|_| reservation_layer(None)).collect();
    let reserve = |previous| {
        crate::scene::canvas_reservation(true, &refs_of(&layers), &registry, 0, previous)
    };
    assert_eq!(reserve(None), vec![34]);
    assert_eq!(reserve(Some(33)), vec![34]);
}

/// The order itself: last frame's plane, then overlays, then primaries, and
/// only planes that can carry the canvas -- a previous plane that cannot is
/// skipped rather than tried.
#[test]
fn the_canvas_prefers_its_last_plane_then_overlays_then_primaries() {
    let registry = two_primaries();
    let order = |hosts: &[u32], previous| {
        crate::scene::canvas_plane_order(hosts, &registry, 0, previous).collect::<Vec<_>>()
    };
    assert_eq!(order(&[31, 32, 33, 34], None), [33, 34, 31, 32]);
    assert_eq!(order(&[31, 32, 33, 34], Some(32)), [32, 33, 34, 31]);
    assert_eq!(order(&[31, 33], Some(34)), [33, 31]);
}

/// Where planes have no zpos, overflow reserves nothing: the last candidate
/// stacks above every layer whatever the canvas carries, and the allocator
/// picks the plane between the composited run's neighbors instead
/// (drm-cxx#240).
#[test]
fn overflow_reserves_nothing_where_planes_stack_by_id() {
    let registry = drmkit_planes::PlaneRegistry::from_capabilities(vec![
        reservation_plane(31, drmkit_planes::PlaneType::Primary, None),
        reservation_plane(32, drmkit_planes::PlaneType::Overlay, None),
    ]);
    let layers: Vec<drmkit_planes::Layer> = (0..3).map(|_| reservation_layer(None)).collect();
    let refs: Vec<drmkit_planes::LayerRef<'_>> = layers
        .iter()
        .enumerate()
        .map(|(i, layer)| drmkit_planes::LayerRef {
            id: drmkit_planes::LayerId(i as u64 + 1),
            layer,
        })
        .collect();

    assert!(crate::scene::canvas_reservation(true, &refs, &registry, 0, None).is_empty());
}

/// The acquire-fence close discipline, at the level the scene works at.
///
/// `drmkit-sync` covers the fence itself -- that `import` dups, that a move
/// carries the descriptor, that repeated import and drop leaks nothing. What
/// is left is the composition: an `AcquiredBuffer` carrying one, moved into a
/// release ring and dropped, once per layer per frame.
mod acquire_fence {
    use std::os::fd::{AsFd as _, OwnedFd};

    use drmkit_sync::SyncFence;

    use crate::AcquiredBuffer;

    /// An eventfd with a count already written: readable, so `poll` reports it
    /// immediately. The same stand-in for a signaled `sync_file` that
    /// `drmkit-sync` uses, and cheaper than a pipe -- one descriptor rather
    /// than two.
    fn signaled() -> OwnedFd {
        rustix::event::eventfd(1, rustix::event::EventfdFlags::CLOEXEC).expect("eventfd")
    }

    fn open_fd_count() -> usize {
        std::fs::read_dir("/proc/self/fd")
            .expect("/proc/self/fd")
            .count()
    }

    #[test]
    fn a_buffer_with_no_fence_says_so() {
        // The common case: a source that produces ready buffers synchronously
        // leaves this unset, and the scene must not wait on nothing.
        let acquired = AcquiredBuffer::default();
        assert!(acquired.acquire_fence.is_none());
    }

    #[test]
    fn churning_fenced_buffers_does_not_leak_descriptors() {
        // Once per layer per frame, so a leak of one descriptor per acquire
        // reaches EMFILE in seconds at 60 Hz. `OwnedFd` makes the double-close
        // half of this unrepresentable; the leak half is still reachable
        // through a `forget` or a descriptor stashed somewhere and never
        // dropped, which is what this measures.
        let source = signaled();

        let churn = |times: usize| {
            for _ in 0..times {
                let fence = SyncFence::import(source.as_fd()).expect("import");
                let acquired = AcquiredBuffer {
                    fb_id: 1,
                    acquire_fence: Some(fence),
                    ..AcquiredBuffer::default()
                };
                // Moved as the scene moves it into its release ring, then
                // dropped at the end of the frame.
                let moved = acquired;
                assert!(moved.acquire_fence.is_some());
                drop(moved);
            }
        };

        churn(16);
        let after_few = open_fd_count();
        churn(240);
        let growth = open_fd_count().saturating_sub(after_few);

        assert!(
            growth < 16,
            "240 further acquire/drop cycles grew the fd table by {growth}; \
             a per-acquire leak would grow it by 240"
        );
    }

    #[test]
    fn a_fence_carried_through_a_move_is_still_waitable() {
        // The move must carry the descriptor rather than a copy of a number
        // that something else has since closed.
        let source = signaled();
        let acquired = AcquiredBuffer {
            fb_id: 1,
            acquire_fence: Some(SyncFence::import(source.as_fd()).expect("import")),
            ..AcquiredBuffer::default()
        };
        let moved = acquired;

        let fence = moved.acquire_fence.expect("the move kept it");
        fence
            .wait(std::time::Duration::from_millis(200))
            .expect("an already-signaled fence waits successfully");
    }
}

/// The scene's small surfaces, ported from `test_scene.cpp`.
///
/// The file is forty-one cases against an API that differs in shape here --
/// upstream has per-field `set_*_if_changed` setters where this has one
/// `set_display`, and constructors that take a device where this takes a CRTC
/// id. What follows is the behavior that exists on both sides; the parity row
/// names what does not and why.
mod scene_surfaces {
    use std::collections::HashMap;

    use drmkit_planes::{ContentType, Rect};

    use crate::{DisplayParams, LayerHandle, LayerScene, Placement};

    #[test]
    fn a_default_handle_is_the_invalid_sentinel() {
        // Slot 0 is reserved for exactly this, so a handle nobody assigned
        // cannot address the first layer.
        assert!(!LayerHandle::default().is_valid());
    }

    #[test]
    fn a_handle_distinguishes_slot_from_generation() {
        // Both halves have to participate in equality and in the hash. A
        // handle comparing on slot alone would let a stale one match the
        // layer that took its place, which is the whole hazard the generation
        // exists to close.
        let mut scene = LayerScene::new(1);
        let first = scene.add_layer(Box::new(super::MinimalSource));
        scene.remove_layer(first);
        let second = scene.add_layer(Box::new(super::MinimalSource));

        assert_ne!(first, second, "the recycled slot is a different handle");
        assert_ne!(
            first.layer_id(),
            second.layer_id(),
            "and a different identity"
        );

        // Usable as a map key, and the two do not collide there either.
        let mut by_handle: HashMap<LayerHandle, &str> = HashMap::new();
        by_handle.insert(first, "gone");
        by_handle.insert(second, "live");
        assert_eq!(by_handle.len(), 2);
        assert_eq!(by_handle.get(&second), Some(&"live"));
    }

    #[test]
    fn a_stale_handle_resolves_to_nothing() {
        let mut scene = LayerScene::new(1);
        let first = scene.add_layer(Box::new(super::MinimalSource));
        scene.remove_layer(first);
        let second = scene.add_layer(Box::new(super::MinimalSource));

        assert!(scene.layer(first).is_none(), "the removed layer is gone");
        assert!(scene.layer(second).is_some());
    }

    #[test]
    fn geometry_does_not_flag_a_layer_for_reallocation() {
        // Moving or resizing a layer changes what is written to the plane it
        // already has. Dropping the warm start for it would cost a search
        // every frame something moves, which is every frame.
        let mut scene = LayerScene::new(1);
        let handle = scene.add_layer(Box::new(super::MinimalSource));
        let layer = scene.layer_mut(handle).expect("live");
        assert!(!layer.hints_dirty());

        layer.set_display(DisplayParams {
            dst_rect: Rect {
                x: 10,
                y: 20,
                w: 64,
                h: 64,
            },
            ..DisplayParams::default()
        });
        assert!(
            !layer.hints_dirty(),
            "geometry must not drop the warm start"
        );
    }

    #[test]
    fn a_hint_that_changes_scoring_does_flag_it() {
        // Content type, refresh hint and app priority all feed plane scoring,
        // so the layer has to be free to move to a plane its new hint
        // prefers -- which it cannot do from a warm start.
        let mut scene = LayerScene::new(1);
        let handle = scene.add_layer(Box::new(super::MinimalSource));

        // A fresh layer per case: the flag is cleared by a commit, and there
        // is deliberately no public way to clear it otherwise.
        for set in [
            &(|l: &mut crate::SceneLayer| l.set_content_type(ContentType::Video))
                as &dyn Fn(&mut crate::SceneLayer),
            &|l: &mut crate::SceneLayer| l.set_update_hint(24),
            &|l: &mut crate::SceneLayer| l.set_app_priority(3),
        ] {
            let fresh = scene.add_layer(Box::new(super::MinimalSource));
            let layer = scene.layer_mut(fresh).expect("live");
            assert!(!layer.hints_dirty(), "starts clean");
            set(layer);
            assert!(layer.hints_dirty());
        }
        let _ = handle;
    }

    #[test]
    fn the_hint_accessors_read_back_what_was_set() {
        let mut scene = LayerScene::new(1);
        let handle = scene.add_layer(Box::new(super::MinimalSource));
        let layer = scene.layer_mut(handle).expect("live");

        assert_eq!(layer.app_priority(), 0, "defaults to none");
        assert_eq!(layer.update_hint_hz(), 0);
        assert_eq!(layer.content_type(), ContentType::default());

        layer.set_app_priority(7);
        layer.set_update_hint(48);
        layer.set_content_type(ContentType::Video);

        assert_eq!(layer.app_priority(), 7);
        assert_eq!(layer.update_hint_hz(), 48);
        assert_eq!(layer.content_type(), ContentType::Video);
    }

    #[test]
    fn a_placement_defaults_to_unassigned_with_no_plane() {
        // The safe default: a layer nothing recorded an outcome for has not
        // reached the screen, and claiming a plane it does not have would be
        // worse than claiming none.
        let placement = crate::LayerPlacement {
            layer: drmkit_planes::LayerId(1),
            ..crate::LayerPlacement::default()
        };
        assert_eq!(placement.placement, Placement::Unassigned);
        assert_eq!(placement.plane_id, None);
        assert_eq!(placement.plane_rotation_bits, 0);
    }

    #[test]
    fn a_fresh_report_counts_nothing() {
        let report = crate::CommitReport::default();
        assert_eq!(report.layers_total, 0);
        assert_eq!(report.layers_assigned, 0);
        assert_eq!(report.layers_composited, 0);
        assert_eq!(report.test_commits_issued, 0);
        assert!(report.placements.is_empty());
        assert!(
            report.accounting_balances(),
            "zero of everything still has to add up"
        );
    }

    #[test]
    fn the_scene_remembers_which_crtc_it_drives() {
        assert_eq!(LayerScene::new(42).crtc_id(), 42);
    }
}

// --- FB_DAMAGE_CLIPS rectangles ----------------------------------------------

/// Damage is converted to corners, not to origin-and-size.
///
/// `struct drm_mode_rect` is `x1, y1, x2, y2`. A `DamageRect` is `x, y, w, h`.
/// The two have the same shape and different meanings, which is exactly the
/// kind of mismatch that produces a plausible-looking blob describing the
/// wrong region — and the symptom is a stale area on screen, indistinguishable
/// from a producer that did not draw.
#[test]
fn damage_becomes_corner_pairs_not_widths() {
    let rects = crate::commit::damage_rects(&[DamageRect {
        x: 10,
        y: 20,
        w: 30,
        h: 40,
    }]);

    assert_eq!(
        rects,
        vec![[10, 20, 40, 60]],
        "x2 is x + w and y2 is y + h; [10, 20, 30, 40] would be the width \
         written where the far corner belongs"
    );
}

/// Every rectangle is converted, in the order given.
///
/// The kernel takes the union, so order does not change what is repainted --
/// but dropping one does, and a conversion that returned only the first would
/// leave the rest of the damage unreported.
#[test]
fn every_damage_rectangle_is_converted_in_order() {
    let rects = crate::commit::damage_rects(&[
        DamageRect {
            x: 0,
            y: 0,
            w: 8,
            h: 8,
        },
        DamageRect {
            x: 100,
            y: 200,
            w: 1,
            h: 1,
        },
    ]);

    assert_eq!(rects, vec![[0, 0, 8, 8], [100, 200, 101, 201]]);
}

/// A negative origin converts unchanged.
///
/// Clipping is [`clip_damage`](crate::commit::clip_damage)'s job, which runs
/// first and moves both corners. Coercing the origin to zero here, with the
/// far corner computed from it, would move the damage rather than clip it,
/// repainting a region the producer did not touch and leaving the one it did.
#[test]
fn a_negative_origin_is_carried_through_rather_than_clamped() {
    let rects = crate::commit::damage_rects(&[DamageRect {
        x: -4,
        y: -8,
        w: 16,
        h: 16,
    }]);

    assert_eq!(rects, vec![[-4, -8, 12, 8]]);
}

/// A far corner that cannot fit an `i32` saturates rather than wrapping.
///
/// Nothing real reaches this. What matters is which way it fails: wrapping
/// produces a rectangle whose corners are the wrong way round, which is a
/// malformed blob the driver may reject or read as an enormous region.
/// Saturating over-reports, which is at worst a wasted repaint.
#[test]
fn a_far_corner_past_i32_saturates_rather_than_wrapping() {
    let rects = crate::commit::damage_rects(&[DamageRect {
        x: i32::MAX - 1,
        y: 0,
        w: 64,
        h: 8,
    }]);

    assert_eq!(rects[0][2], i32::MAX, "clamped, not wrapped to a negative");
    assert!(
        rects[0][2] >= rects[0][0],
        "the far corner must never end up behind the near one"
    );
}

/// Nothing to report converts to nothing.
///
/// The caller is expected to write no property at all in this case — an empty
/// blob says *nothing changed*, which is the opposite of what empty damage
/// means. This pins that the conversion itself does not invent a rectangle.
#[test]
fn no_damage_converts_to_no_rectangles() {
    assert!(crate::commit::damage_rects(&[]).is_empty());
}

fn rect(x: i32, y: i32, w: u32, h: u32) -> DamageRect {
    DamageRect { x, y, w, h }
}

/// Damage inside the buffer passes through untouched.
#[test]
fn damage_inside_the_buffer_is_unchanged() {
    let damage = [rect(0, 0, 8, 8), rect(100, 50, 20, 10)];
    assert_eq!(crate::commit::clip_damage(&damage, 640, 480), damage);
}

/// A rectangle straying off the buffer is cut back to it, at both corners.
///
/// Upstream clamps every clip to the buffer extent before building the blob: a
/// clip outside the framebuffer is the producer's mistake, and the kernel is
/// entitled to refuse the commit over it -- every layer with it.
#[test]
fn damage_past_the_buffer_is_clipped_to_it() {
    let clipped =
        crate::commit::clip_damage(&[rect(-4, -8, 16, 16), rect(630, 470, 20, 20)], 640, 480);
    assert_eq!(clipped, [rect(0, 0, 12, 8), rect(630, 470, 10, 10)]);
}

/// A rectangle with nothing left inside the buffer is dropped, and so is one
/// with no area to begin with.
#[test]
fn damage_with_nothing_inside_the_buffer_is_dropped() {
    let clipped = crate::commit::clip_damage(
        &[
            rect(700, 0, 8, 8),
            rect(-20, 0, 10, 8),
            rect(10, 10, 0, 8),
            rect(4, 4, 2, 2),
        ],
        640,
        480,
    );
    assert_eq!(clipped, [rect(4, 4, 2, 2)]);
}

/// When every rectangle is dropped the frame is whole, which an empty list
/// already says -- not an empty blob, which says nothing changed.
#[test]
fn damage_entirely_off_the_buffer_becomes_whole_frame() {
    assert!(crate::commit::clip_damage(&[rect(640, 0, 8, 8)], 640, 480).is_empty());
}

/// Sixteen rectangles is the bound; seventeen is a whole-frame repaint.
#[test]
fn more_than_sixteen_damage_rectangles_is_whole_frame() {
    let sixteen: Vec<DamageRect> = (0..16).map(|i| rect(i * 10, 0, 4, 4)).collect();
    assert_eq!(crate::commit::clip_damage(&sixteen, 640, 480).len(), 16);

    let seventeen: Vec<DamageRect> = (0..17).map(|i| rect(i * 10, 0, 4, 4)).collect();
    assert!(
        crate::commit::clip_damage(&seventeen, 640, 480).is_empty(),
        "over upstream's bound the frame repaints whole"
    );
}

/// A plane with an 8-bit alpha range, as `emit_layer` sees it.
fn eight_bit_alpha_plane() -> PlanePropertyMap {
    let mut map = PlanePropertyMap::new();
    map.planes.insert(
        7,
        [(PropTag::FbId, 101), (PropTag::Alpha, 102)]
            .into_iter()
            .collect(),
    );
    map.alpha_max.insert(7, 255);
    map
}

fn alpha_layer(alpha: u64) -> drmkit_planes::Layer {
    let mut layer = drmkit_planes::Layer::new();
    layer
        .set_property(PropTag::FbId, 5)
        .set_property(PropTag::Alpha, alpha);
    layer
}

/// Alpha reaches the wire on the plane's own scale (drm-cxx#265).
///
/// Measured upstream on a vendor driver advertising `alpha [0, 255]`: the
/// layer's `0xFFFF` failed every commit with `EINVAL`, and the frame surfaced
/// as a dropped layer. Half alpha must stay half, not clamp to opaque.
#[test]
fn alpha_is_written_on_the_planes_scale() {
    let map = eight_bit_alpha_plane();
    for (asked, sent) in [(0xFFFF, 255), (0x8000, 128), (0, 0)] {
        let mut request = drmkit_core::AtomicRequest::with_capacity(4);
        emit_layer(&mut request, &map, 7, &alpha_layer(asked), None).expect("emit");
        let alpha = request
            .writes()
            .iter()
            .find(|write| write.property_id == 102)
            .map(|write| write.value);
        assert_eq!(alpha, Some(sent), "alpha {asked:#x} on an 8-bit plane");
    }
}

/// A steady frame on an 8-bit plane does not rewrite alpha.
///
/// The baseline records what the layer asked for, not what was sent, so the
/// diff has to compare like with like. Comparing the rescaled 255 against a
/// recorded 0xFFFF would find a change on every frame.
#[test]
fn a_steady_frame_does_not_rewrite_rescaled_alpha() {
    let map = eight_bit_alpha_plane();
    let layer = alpha_layer(0xFFFF);
    let baseline = layer.snapshot();
    let mut request = drmkit_core::AtomicRequest::with_capacity(4);
    let written = emit_layer(&mut request, &map, 7, &layer, Some(&baseline)).expect("emit");
    assert_eq!(
        written.properties, 1,
        "only FB_ID, which is written every frame by contract"
    );
}

/// A plane advertising no alpha range gets the layer's value as it stands.
#[test]
fn alpha_on_a_plane_without_a_range_is_left_alone() {
    let mut map = eight_bit_alpha_plane();
    map.alpha_max.clear();
    assert_eq!(map.rescale_alpha(7, 0x8000), 0x8000);
}

/// The unique lowest layer can take a fixed primary slot when every other layer
/// sits above it, so the anchor is not reserved (drm-cxx `8bf20e6`). Layers at
/// 3 and 4 over amdgpu's slot at 2: the 3 takes the primary, and the stack is
/// still what was asked for.
#[test]
fn the_lowest_layer_above_a_fixed_slot_makes_the_anchor_unnecessary() {
    let registry = drmkit_planes::PlaneRegistry::from_capabilities(vec![
        reservation_plane(31, drmkit_planes::PlaneType::Primary, Some((2, 2))),
        reservation_plane(32, drmkit_planes::PlaneType::Overlay, Some((3, 9))),
        reservation_plane(33, drmkit_planes::PlaneType::Overlay, Some((3, 9))),
    ]);
    let layers = [reservation_layer(Some(3)), reservation_layer(Some(4))];
    let refs: Vec<drmkit_planes::LayerRef<'_>> = layers
        .iter()
        .enumerate()
        .map(|(i, layer)| drmkit_planes::LayerRef {
            id: drmkit_planes::LayerId(i as u64 + 1),
            layer,
        })
        .collect();

    assert!(crate::scene::canvas_reservation(true, &refs, &registry, 0, None).is_empty());
}

/// Which layer can take a fixed slot below everything else.
#[test]
fn the_bottom_slot_layer_is_the_unique_lowest_above_the_pin() {
    use crate::scene::bottom_slot_layer;
    // i.MX LCDIF / tilcdc: a lone layer above slot 0.
    assert_eq!(bottom_slot_layer(&[Some(1)], 0), Some(0));
    // The unique lowest, wherever it is listed.
    assert_eq!(bottom_slot_layer(&[Some(5), Some(3), Some(4)], 2), Some(1));
    // Tied at the bottom: neither can claim the slot.
    assert_eq!(bottom_slot_layer(&[Some(3), Some(3)], 2), None);
    // Another layer at or below the slot keeps the existing behavior.
    assert_eq!(bottom_slot_layer(&[Some(1), Some(2)], 2), None);
    // A layer with no zpos is the existing hint's business.
    assert_eq!(bottom_slot_layer(&[Some(3), None], 2), None);
    assert_eq!(bottom_slot_layer(&[], 2), None);
}

// --- colorimetry fallback ----------------------------------------------------

mod ycbcr_fallback {
    use crate::commit::{encoding_value, range_value};
    use drmkit_planes::{ColorEncoding, ColorEncodingValues, ColorRange, ColorRangeValues};

    /// The values a plane listing all three encodings would hand back. The
    /// integers are deliberately not 0, 1, 2: a resolver that returned the
    /// enum's position rather than the driver's value would pass otherwise.
    const ALL: ColorEncodingValues = ColorEncodingValues {
        bt601: Some(10),
        bt709: Some(11),
        bt2020: Some(12),
    };

    #[test]
    fn an_encoding_the_plane_lists_is_written_as_asked() {
        assert_eq!(encoding_value(&ALL, ColorEncoding::Bt601), Some(10));
        assert_eq!(encoding_value(&ALL, ColorEncoding::Bt709), Some(11));
        assert_eq!(encoding_value(&ALL, ColorEncoding::Bt2020), Some(12));
    }

    /// Older drivers list no BT.2020. Upstream falls back to BT.709, then
    /// BT.601, rather than write nothing and leave the previous client's.
    #[test]
    fn a_missing_encoding_falls_back_to_bt709_then_bt601() {
        let no_2020 = ColorEncodingValues {
            bt2020: None,
            ..ALL
        };
        assert_eq!(encoding_value(&no_2020, ColorEncoding::Bt2020), Some(11));
        let only_601 = ColorEncodingValues {
            bt601: Some(10),
            ..ColorEncodingValues::default()
        };
        assert_eq!(encoding_value(&only_601, ColorEncoding::Bt709), Some(10));
        assert_eq!(
            encoding_value(&ColorEncodingValues::default(), ColorEncoding::Bt709),
            None,
            "a plane listing nothing known gets nothing written"
        );
    }

    #[test]
    fn a_missing_range_falls_back_to_limited_then_full() {
        let both = ColorRangeValues {
            limited: Some(20),
            full: Some(21),
        };
        assert_eq!(range_value(&both, ColorRange::Full), Some(21));
        assert_eq!(range_value(&both, ColorRange::Limited), Some(20));
        let only_limited = ColorRangeValues { full: None, ..both };
        assert_eq!(range_value(&only_limited, ColorRange::Full), Some(20));
        let only_full = ColorRangeValues {
            limited: None,
            ..both
        };
        assert_eq!(range_value(&only_full, ColorRange::Limited), Some(21));
    }
}