drmkit-scene 0.1.3

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
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! End-to-end scene flow, with no device.
//!
//! The pieces built separately — the source contract, the release ring, the
//! frame lifecycle, lowering, and the allocator — run together here for the
//! first time. Everything is host-side: the allocator's test commits go to a
//! fake, and the kernel's answer to a real commit is a parameter.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use drmkit_fmt::fourcc;
use drmkit_planes::{
    LayerRef, PlaneCapabilities, PlaneRegistry, PlaneType, TestCommitter, TestFailure,
};
use drmkit_scene::{
    AcquiredBuffer, ColorEncoding, ColorRange, CommitKind, DamageRect, DisplayParams, KernelResult,
    LayerBufferSource, LayerScene, Rect, SceneError, SourceError, SourceFormat, Ycbcr,
};

// --- fixtures ----------------------------------------------------------------

fn registry() -> PlaneRegistry {
    PlaneRegistry::from_capabilities(vec![
        PlaneCapabilities {
            id: 31,
            possible_crtcs: 0b1,
            plane_type: PlaneType::Primary,
            formats: vec![fourcc::XRGB8888],
            supports_scaling: true,
            ..PlaneCapabilities::default()
        },
        PlaneCapabilities {
            id: 32,
            possible_crtcs: 0b1,
            plane_type: PlaneType::Overlay,
            formats: vec![fourcc::XRGB8888],
            supports_scaling: true,
            ..PlaneCapabilities::default()
        },
    ])
}

/// What a source did, observable from the test.
#[derive(Debug, Default)]
struct SourceLog {
    acquired: usize,
    released: Vec<u32>,
}

/// A source whose behavior the test controls.
struct TestSource {
    log: Rc<RefCell<SourceLog>>,
    /// Framebuffer id handed out next.
    next_fb: u32,
    /// Return `WouldBlock` instead of a buffer.
    starved: bool,
    /// Fail for a real reason.
    fails: bool,
    /// Starve on demand, after the source has been handed to the scene.
    ///
    /// `starved` is fixed at construction, which suits a source that never
    /// produces. A layer that starves *after* putting a frame up is a
    /// different case, and the interesting one: it has something to hold.
    toggle: Rc<Cell<bool>>,
    /// Damage reported with every buffer.
    damage: Vec<DamageRect>,
}

impl TestSource {
    fn new(log: &Rc<RefCell<SourceLog>>) -> Self {
        Self {
            log: Rc::clone(log),
            next_fb: 100,
            starved: false,
            fails: false,
            toggle: Rc::new(Cell::new(false)),
            damage: Vec::new(),
        }
    }

    /// A handle to this source's starve switch, to keep before boxing it.
    fn starve_switch(&self) -> Rc<Cell<bool>> {
        Rc::clone(&self.toggle)
    }
}

impl LayerBufferSource for TestSource {
    fn acquire(&mut self) -> Result<AcquiredBuffer, SourceError> {
        if self.fails {
            return Err(SourceError::Failed(rustix::io::Errno::IO));
        }
        if self.starved || self.toggle.get() {
            return Err(SourceError::WouldBlock);
        }
        self.log.borrow_mut().acquired += 1;
        let fb_id = self.next_fb;
        self.next_fb += 1;
        Ok(AcquiredBuffer {
            fb_id,
            damage: self.damage.clone(),
            ..AcquiredBuffer::default()
        })
    }

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

    fn format(&self) -> SourceFormat {
        SourceFormat {
            fourcc: fourcc::XRGB8888,
            modifier: 0,
            width: 1920,
            height: 1080,
        }
    }
}

/// Accepts every test commit.
#[derive(Debug, Default)]
struct Accepting {
    calls: usize,
}

impl TestCommitter for Accepting {
    fn test_assignment(&mut self, _assignment: &[(u32, LayerRef<'_>)]) -> Result<(), TestFailure> {
        self.calls += 1;
        Ok(())
    }
}

fn full_screen() -> DisplayParams {
    DisplayParams {
        dst_rect: Rect {
            x: 0,
            y: 0,
            w: 1920,
            h: 1080,
        },
        ..DisplayParams::default()
    }
}

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

// --- the flow ----------------------------------------------------------------

#[test]
fn a_layer_is_acquired_lowered_placed_and_released() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());

    let registry = registry();
    let mut committer = Accepting::default();

    // Frame 1.
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    assert_eq!(build.held(), 1, "the source contributed a buffer");
    let report = scene.finalize_frame(build, KernelResult::Ok);

    assert_eq!(report.layers_total, 1);
    assert_eq!(report.layers_assigned, 1, "one plane, one layer");
    assert_eq!(report.layers_skipped_no_frame, 0);
    assert!(report.accounting_balances());
    assert_eq!(log.borrow().acquired, 1);
    assert!(
        log.borrow().released.is_empty(),
        "invariant 1: the buffer is on screen, not back yet"
    );
    assert!(scene.has_pending_flip());

    // Frames 2 and 3: frame 1's buffer comes back on the third.
    scene.flip_landed();
    for _ in 0..2 {
        let build = scene
            .build_frame(&registry, 0, real(), &mut committer)
            .expect("build");
        scene.finalize_frame(build, KernelResult::Ok);
        scene.flip_landed();
    }
    assert_eq!(
        log.borrow().released,
        vec![100],
        "invariant 1: released two commits deep, in order"
    );

    scene.drain();
}

/// What a source says changed reaches the plan bounded to its buffer.
///
/// The emission builds its `FB_DAMAGE_CLIPS` blob from the plan, so the plan
/// is where a rectangle off the 1920x1080 buffer must already be cut back --
/// and where seventeen rectangles must already have become a whole frame.
#[test]
fn a_sources_damage_reaches_the_plan_clipped_to_its_buffer() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let registry = registry();
    let mut committer = Accepting::default();

    let mut source = TestSource::new(&log);
    source.damage = vec![
        DamageRect {
            x: 1900,
            y: -10,
            w: 40,
            h: 30,
        },
        DamageRect {
            x: 2000,
            y: 0,
            w: 8,
            h: 8,
        },
    ];
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(source));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    assert_eq!(
        build.plan()[0].damage,
        [DamageRect {
            x: 1900,
            y: 0,
            w: 20,
            h: 20
        }],
        "clipped to the buffer, and the rectangle wholly off it dropped"
    );
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    scene.drain();

    let mut source = TestSource::new(&log);
    source.damage = (0..17)
        .map(|i| DamageRect {
            x: i * 10,
            y: 0,
            w: 4,
            h: 4,
        })
        .collect();
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(source));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    assert!(
        build.plan()[0].damage.is_empty(),
        "seventeen rectangles is a whole-frame repaint"
    );
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    scene.drain();
}

/// A starved source is skipped and counted — never a failure, and the frame
/// still commits.
#[test]
fn a_starved_source_is_skipped_not_failed() {
    let live_log = Rc::new(RefCell::new(SourceLog::default()));
    let starved_log = Rc::new(RefCell::new(SourceLog::default()));

    let mut scene = LayerScene::new(1);
    let live = scene.add_layer(Box::new(TestSource::new(&live_log)));
    let mut starved_source = TestSource::new(&starved_log);
    starved_source.starved = true;
    scene.add_layer(Box::new(starved_source));

    scene
        .layer_mut(live)
        .expect("layer")
        .set_display(full_screen());

    let mut committer = Accepting::default();
    let build = scene
        .build_frame(&registry(), 0, real(), &mut committer)
        .expect("a starved source must not abort the build");
    let report = scene.finalize_frame(build, KernelResult::Ok);

    assert_eq!(report.layers_total, 2);
    assert_eq!(report.layers_skipped_no_frame, 1);
    assert_eq!(report.layers_assigned, 1);
    assert!(report.accounting_balances());
    assert_eq!(starved_log.borrow().acquired, 0);

    scene.flip_landed();
    scene.drain();
}

/// A source that fails for a real reason aborts the build — and the buffers
/// already taken this pass go straight back, so those rings do not stall.
#[test]
fn a_failing_source_aborts_the_build_and_returns_what_was_taken() {
    let good_log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    scene.add_layer(Box::new(TestSource::new(&good_log)));
    let mut failing = TestSource::new(&Rc::new(RefCell::new(SourceLog::default())));
    failing.fails = true;
    scene.add_layer(Box::new(failing));

    let mut committer = Accepting::default();
    let result = scene.build_frame(&registry(), 0, real(), &mut committer);

    assert!(
        matches!(result, Err(SceneError::Source(SourceError::Failed(_)))),
        "a real source failure must surface as such, not as a skip: {result:?}"
    );
    assert_eq!(
        good_log.borrow().released,
        vec![100],
        "the buffer taken before the failure must not be stranded"
    );
}

/// **Invariant 2**, end to end: a rejected commit returns that frame's buffers
/// at once and leaves the scene running.
#[test]
fn a_rejected_commit_returns_buffers_and_keeps_the_scene_running() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());

    let registry = registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    scene.finalize_frame(build, KernelResult::Rejected);

    assert_eq!(
        log.borrow().released,
        vec![100],
        "the rejected frame's buffer comes straight back"
    );
    assert!(!scene.is_suspended(), "a rejection is recoverable");

    // And the scene still commits next frame.
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("the scene kept running");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    scene.drain();
}

/// Lost DRM master suspends the scene, and further builds short-circuit until
/// the session resumes.
#[test]
fn lost_master_suspends_until_resumed() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());

    let registry = registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    scene.finalize_frame(build, KernelResult::NotMaster);
    assert!(scene.is_suspended());

    assert!(
        matches!(
            scene.build_frame(&registry, 0, real(), &mut committer),
            Err(SceneError::Suspended)
        ),
        "a suspended scene short-circuits with Suspended, not some other error"
    );

    scene.resume();
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("resumed");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    scene.drain();
}

// --- handles -----------------------------------------------------------------

/// A handle to a removed layer must never address whatever takes its slot.
#[test]
fn a_stale_handle_does_not_address_the_slots_new_occupant() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);

    let first = scene.add_layer(Box::new(TestSource::new(&log)));
    assert!(scene.layer(first).is_some());

    assert!(scene.remove_layer(first));
    assert!(scene.layer(first).is_none(), "removed");

    // The slot is recycled by the next add.
    let second = scene.add_layer(Box::new(TestSource::new(&log)));
    assert!(scene.layer(second).is_some());
    assert!(
        scene.layer(first).is_none(),
        "the stale handle must not resolve to the new occupant"
    );
    assert_ne!(
        first.layer_id(),
        second.layer_id(),
        "and their allocator identities must differ, or warm-start state would \
         carry across two unrelated layers"
    );

    assert!(!scene.remove_layer(first), "removing twice is a no-op");
}

/// Removing a layer whose buffers are still in flight keeps its source alive
/// until they come back — releasing to a dropped source would strand them.
#[test]
fn a_removed_layers_source_survives_until_its_buffers_return() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());

    let registry = registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    assert!(log.borrow().released.is_empty());

    // Remove it while its buffer is still on screen.
    assert!(scene.remove_layer(handle));
    assert!(scene.is_empty());

    // Draining must still reach the retired source.
    scene.drain();
    assert_eq!(
        log.borrow().released,
        vec![100],
        "the buffer must reach the source that produced it, not vanish"
    );
}

#[test]
fn an_empty_scene_builds_an_empty_frame() {
    let mut scene = LayerScene::new(1);
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry(), 0, real(), &mut committer)
        .expect("build");
    let report = scene.finalize_frame(build, KernelResult::Ok);

    assert_eq!(report.layers_total, 0);
    assert!(report.accounting_balances());

    scene.flip_landed();
}

/// A changed hint drops the warm start so the layer can move to the plane it
/// now prefers.
#[test]
fn changing_a_hint_forces_reallocation() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());

    let registry = registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    scene
        .layer_mut(handle)
        .expect("layer")
        .set_content_type(drmkit_planes::ContentType::Video);
    assert!(scene.layer(handle).expect("layer").hints_dirty());

    let calls_before = committer.calls;
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    assert!(
        committer.calls > calls_before,
        "a changed hint must force a re-search, not reuse the cached assignment"
    );
    assert!(
        !scene.layer(handle).expect("layer").hints_dirty(),
        "and the flag clears once the allocation has seen it"
    );
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    scene.drain();
}

/// The invariant 5 tripwire is real: dropping a scene with a flip still armed
/// is the RmFB-on-in-flight-FB hazard, and the scene says so.
///
/// This caught two cases in this very file while they were being written —
/// both drained but never landed the flip, which is precisely the mistake a
/// caller makes.
#[test]
#[should_panic(expected = "page-flip event still armed")]
fn dropping_a_scene_with_an_armed_flip_is_caught() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());

    let mut committer = Accepting::default();
    let build = scene
        .build_frame(&registry(), 0, real(), &mut committer)
        .expect("build");
    scene.finalize_frame(build, KernelResult::Ok);
    assert!(scene.has_pending_flip());

    // Dropped here without landing the flip. In a release build this is silent
    // and shows up as a rare tear; in development it is loud, which is the
    // whole point of the tripwire.
    drop(scene);
}

/// A commit that armed no flip leaves teardown safe, so no tripwire fires.
#[test]
fn a_scene_without_an_armed_flip_drops_cleanly() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());

    let mut committer = Accepting::default();
    let build = scene
        .build_frame(
            &registry(),
            0,
            CommitKind::Real { arms_flip: false },
            &mut committer,
        )
        .expect("build");
    scene.finalize_frame(build, KernelResult::Ok);

    assert!(!scene.has_pending_flip());
    scene.drain();
}

// --- invariant 4: the fast path has to be reachable from the scene -----------

/// A steady frame issues no test commit at all.
///
/// **Invariant 4.** The allocator's FB-only fast path is gated on a baseline of
/// what the kernel last accepted, and only a successful *real* commit may set
/// it. Nothing in the scene recorded that baseline until the parity harness
/// counted the test commits the reference did not issue: the allocator's own
/// unit tests populate the baseline by calling `record_committed` themselves,
/// so they passed while the path was unreachable in production.
///
/// Counting commits from outside the allocator is the point. A test that sets
/// up the baseline by hand proves the predicate works and says nothing about
/// whether anyone ever satisfies it.
#[test]
fn a_steady_frame_issues_no_test_commit() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());

    let registry = registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("first frame");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    let after_first = committer.calls;
    assert!(
        after_first > 0,
        "the first frame has no baseline and must search"
    );

    // Nothing changed but the buffer, which is what a compositor does every
    // frame it is not reconfiguring anything.
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("second frame");
    // Read the fact out before finalizing, and assert only once the scene is
    // quiescent. Asserting with a flip still armed makes the failure unwind
    // through `LayerScene::drop`, whose invariant-5 tripwire then fires during
    // cleanup -- and a panic in a destructor while panicking aborts the
    // process, so the message that mattered never gets printed.
    let took_fast_path = build.report().fb_delta_fast_path;
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    assert!(
        took_fast_path,
        "an unchanged layer set must take the FB-only fast path"
    );
    assert_eq!(
        committer.calls,
        after_first,
        "a steady frame must not issue a test commit; it issued {}",
        committer.calls - after_first
    );
}

/// Removing a layer does not cost a test commit.
///
/// Dropping a layer only frees resources, so the assignment the kernel already
/// accepted stays valid without it. The scene used to invalidate the whole
/// warm-start cache here, which forced a full search -- several test commits --
/// for a configuration that could not have become invalid.
#[test]
fn removing_a_layer_does_not_force_a_search() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let keep = scene.add_layer(Box::new(TestSource::new(&log)));
    let drop_me = scene.add_layer(Box::new(TestSource::new(&log)));
    for handle in [keep, drop_me] {
        scene
            .layer_mut(handle)
            .expect("layer")
            .set_display(full_screen());
    }

    let registry = registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("first frame");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    let after_first = committer.calls;

    scene.remove_layer(drop_me);

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("frame after removal");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    assert_eq!(
        committer.calls, after_first,
        "removing a layer must not re-test the survivors"
    );
}

// --- invariant 4: the steady-state property-write census ---------------------

/// A steady frame re-disables nothing and diffs everything.
///
/// **Invariant 4.** Once the kernel has taken a configuration, the next frame's
/// job is to hand it new buffers, not to restate the configuration. Two things
/// have to hold for that: every assigned plane must carry a baseline to diff
/// against, and no plane the kernel already has off may be disabled again.
///
/// Re-disabling costs two property writes per idle plane per frame, which on a
/// card with ten planes is most of the frame's property traffic and none of its
/// meaning.
#[test]
fn a_steady_frame_disables_nothing_and_diffs_everything() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());

    let registry = registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("first frame");
    assert!(
        build.plan().iter().all(|entry| entry.baseline.is_none()),
        "the first frame has no baseline and must write every property"
    );
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("second frame");
    let all_have_baselines = build.plan().iter().all(|entry| entry.baseline.is_some());
    let disables = build.disables().to_vec();
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    assert!(
        all_have_baselines,
        "a plane the kernel already accepted must be diffed, not re-stated"
    );
    assert!(
        disables.is_empty(),
        "no plane changed hands, so nothing needs disabling; got {disables:?}"
    );
}

/// The plane a removed layer was using still gets switched off.
///
/// Dropping the layer removes the scene's reason to program that plane, but the
/// kernel is still scanning out whatever was on it. The frame after a removal
/// has to disable it explicitly or it keeps displaying the departed layer's
/// last framebuffer.
///
/// This is the hazard in pruning the allocator's committed baseline on removal:
/// the baseline entry is the only record that the plane is still lit, so
/// erasing it makes the plane look already-off and nothing disables it. The
/// entry is kept and its layer identity cleared instead.
#[test]
fn the_plane_a_removed_layer_held_is_disabled() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let keep = scene.add_layer(Box::new(TestSource::new(&log)));
    let drop_me = scene.add_layer(Box::new(TestSource::new(&log)));
    for handle in [keep, drop_me] {
        scene
            .layer_mut(handle)
            .expect("layer")
            .set_display(full_screen());
    }

    let registry = registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("first frame");
    let vacated = build
        .plan()
        .iter()
        .find(|entry| entry.layer_id == drop_me.layer_id())
        .map(|entry| entry.plane_id)
        .expect("the layer being dropped must have been placed");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    scene.remove_layer(drop_me);

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("frame after removal");
    let disables = build.disables().to_vec();
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    assert!(
        disables.contains(&vacated),
        "plane {vacated} still holds the removed layer's framebuffer and was \
         not disabled; disables were {disables:?}"
    );
}

/// Until a real commit lands, every plane the frame does not use is turned
/// off, whatever the allocator's baseline says.
///
/// The baseline knows only what this scene lit. Another client -- the session
/// it took over from, a compositor that held the CRTC while it was suspended
/// -- can leave a plane armed, and every `TEST_ONLY` disables that plane, so
/// the frame the kernel accepted is one without it. Leaving it out of the real
/// commit puts it on screen and, on a controller that lights fewer planes than
/// it offers, over the limit the tests were held to. Once the scene's own
/// commit has landed it is the authority again, and a resume makes it not.
#[test]
fn until_a_commit_lands_every_unused_plane_is_turned_off() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let registry = registry();
    let mut committer = Accepting::default();

    // An empty frame keeps whatever is there: an active CRTC's only primary
    // cannot be disabled on some controllers.
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("empty frame");
    assert!(build.disables().is_empty(), "{:?}", build.disables());
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());
    let unused = |build: &drmkit_scene::FrameBuild| -> Vec<u32> {
        let mut planes: Vec<u32> = registry
            .force_disable_candidates(0)
            .map(|plane| plane.id)
            .filter(|id| !build.plan().iter().any(|entry| entry.plane_id == *id))
            .collect();
        planes.sort_unstable();
        planes
    };
    let sorted = |build: &drmkit_scene::FrameBuild| -> Vec<u32> {
        let mut planes = build.disables().to_vec();
        planes.sort_unstable();
        planes
    };

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("first frame with a layer");
    assert!(!unused(&build).is_empty(), "the case needs a spare plane");
    assert_eq!(
        sorted(&build),
        unused(&build),
        "the first commit clears the CRTC"
    );
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("settled frame");
    assert!(build.disables().is_empty(), "{:?}", build.disables());
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    scene.resume();
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("frame after a resume");
    assert_eq!(sorted(&build), unused(&build), "a resume clears it again");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
}

// --- EAGAIN flow control -----------------------------------------------------

/// A starved layer keeps its plane, and the report still balances.
///
/// `WouldBlock` from a source is flow control, not failure: the layer has no
/// new frame this vblank and goes on showing the one it already put up. It
/// must not be dropped from the commit, because a layer dropped from the
/// commit has its plane disabled — a source that hiccups for one frame would
/// blink the layer off screen.
///
/// Holding the plane is what makes the accounting delicate. The layer is in
/// the assignment *and* counted as skipped, so a report that took
/// `layers_assigned` straight from the assignment counts it twice and the
/// identity
///
/// ```text
/// total = assigned + composited + unassigned + skipped
/// ```
///
/// stops holding. A compositor watching those counters for dropped frames then
/// sees phantom ones.
#[test]
fn a_starved_layer_holds_its_plane_and_the_report_still_balances() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let steady = scene.add_layer(Box::new(TestSource::new(&log)));
    let hiccup_source = TestSource::new(&log);
    let switch = hiccup_source.starve_switch();
    let hiccup = scene.add_layer(Box::new(hiccup_source));
    for handle in [steady, hiccup] {
        scene
            .layer_mut(handle)
            .expect("layer")
            .set_display(full_screen());
    }

    let registry = registry();
    let mut committer = Accepting::default();

    // One good frame, so the layer has something to hold.
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("first frame");
    let plane_of_hiccup = build
        .plan()
        .iter()
        .find(|entry| entry.layer_id == hiccup.layer_id())
        .map(|entry| entry.plane_id)
        .expect("both layers must be placed");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    switch.set(true);

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("starved frame");
    let still_programmed = build
        .plan()
        .iter()
        .any(|entry| entry.plane_id == plane_of_hiccup);
    let disabled = build.disables().contains(&plane_of_hiccup);
    let report = scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    assert!(
        still_programmed,
        "a starved layer must keep its plane and re-attach the frame it \
         already had"
    );
    assert!(
        !disabled,
        "plane {plane_of_hiccup} was switched off; the layer would blink"
    );
    assert_eq!(
        report.layers_skipped_no_frame, 1,
        "the starved layer must be counted as skipped"
    );
    assert!(
        report.accounting_balances(),
        "report double-counts the starved layer: total {} != assigned {} + \
         composited {} + unassigned {} + skipped {}",
        report.layers_total,
        report.layers_assigned,
        report.layers_composited,
        report.layers_unassigned,
        report.layers_skipped_no_frame
    );

    scene.drain();
}

/// Planes with an SA8155P-like zpos range: every one mutable over `[0, 10]`,
/// which that controller advertises and then refuses at 9 and 10.
fn ranged_registry() -> PlaneRegistry {
    let plane = |id, plane_type| PlaneCapabilities {
        id,
        possible_crtcs: 0b1,
        plane_type,
        formats: vec![fourcc::XRGB8888],
        supports_scaling: true,
        zpos_min: Some(0),
        zpos_max: Some(10),
        ..PlaneCapabilities::default()
    };
    PlaneRegistry::from_capabilities(vec![
        plane(31, PlaneType::Primary),
        plane(32, PlaneType::Overlay),
        plane(33, PlaneType::Overlay),
    ])
}

/// The frame writes zpos densely over the planes it arms, and the next frame
/// diffs against what was written while still taking the fast path.
///
/// Two layers asking 8 and 20 go out as 0 and 1 (drm-cxx `1384526`): 20 is past
/// the range, and even 8 sits near a top the SA8155P rejects. The baseline has
/// to record the written values, or the next frame would compare 0 against 8
/// and rewrite zpos forever; its hash has to stay the layer's own, or the fast
/// path would never match the layer as the caller presents it again.
#[test]
fn zpos_is_written_densely_and_the_baseline_keeps_what_was_written() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let mut handles = Vec::new();
    for (x, zpos) in [(0, 8), (960, 20)] {
        let handle = scene.add_layer(Box::new(TestSource::new(&log)));
        scene
            .layer_mut(handle)
            .expect("layer")
            .set_display(DisplayParams {
                dst_rect: Rect {
                    x,
                    y: 0,
                    w: 960,
                    h: 1080,
                },
                zpos: Some(zpos),
                ..DisplayParams::default()
            });
        handles.push(handle);
    }
    let registry = ranged_registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    let mut written: Vec<(u64, Option<u64>)> = build
        .plan()
        .iter()
        .map(|entry| {
            (
                entry
                    .layer
                    .property(drmkit_planes::PropTag::Zpos)
                    .expect("asked"),
                entry.zpos,
            )
        })
        .collect();
    written.sort_unstable();
    assert_eq!(written, vec![(8, Some(0)), (20, Some(1))]);
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    for entry in build.plan() {
        assert_eq!(
            entry
                .baseline
                .and_then(|b| b.get(drmkit_planes::PropTag::Zpos)),
            entry.zpos,
            "the baseline holds the zpos that went out, not the one asked for"
        );
    }
    let report = scene.finalize_frame(build, KernelResult::Ok);
    assert!(
        report.fb_delta_fast_path,
        "an unchanged frame still takes the fast path"
    );
    scene.flip_landed();
    scene.drain();
}

/// Commit one frame with a layer per display in `displays`, and return their
/// handles.
fn commit_layers(
    scene: &mut LayerScene,
    log: &Rc<RefCell<SourceLog>>,
    displays: &[DisplayParams],
) -> Vec<drmkit_scene::LayerHandle> {
    let handles: Vec<_> = displays
        .iter()
        .map(|display| {
            let handle = scene.add_layer(Box::new(TestSource::new(log)));
            scene
                .layer_mut(handle)
                .expect("layer")
                .set_display(*display);
            handle
        })
        .collect();
    let build = scene
        .build_frame(&registry(), 0, real(), &mut Accepting::default())
        .expect("frame");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    handles
}

/// A plane a replaced layer left armed is turned off, not left on screen
/// under or over the new stack (drm-cxx `d895c8d`). Upstream skipped the
/// disable pass whenever the warm start was gone, which a replaced layer set
/// always makes it.
#[test]
fn a_plane_left_by_replaced_layers_is_turned_off() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let mut top = full_screen();
    top.zpos = Some(1);
    let old = commit_layers(&mut scene, &log, &[full_screen(), top]);

    for handle in old {
        scene.remove_layer(handle);
    }
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());
    let build = scene
        .build_frame(&registry(), 0, real(), &mut Accepting::default())
        .expect("frame with the replacement");

    let used: Vec<u32> = build.plan().iter().map(|entry| entry.plane_id).collect();
    assert_eq!(used.len(), 1, "{used:?}");
    let left = if used[0] == 31 { 32 } else { 31 };
    assert_eq!(build.disables(), [left], "the old layer's plane goes off");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
}

/// A scene emptied of layers keeps its planes: the last frame stays up, and an
/// active CRTC's only primary cannot be disabled on some controllers (i.MX
/// LCDIF), so turning it off would get the commit refused (drm-cxx
/// `d895c8d`).
#[test]
fn an_emptied_scene_keeps_its_planes() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let old = commit_layers(&mut scene, &log, &[full_screen()]);

    for handle in old {
        scene.remove_layer(handle);
    }
    let build = scene
        .build_frame(&registry(), 0, real(), &mut Accepting::default())
        .expect("empty frame");
    assert!(build.disables().is_empty(), "{:?}", build.disables());
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
}

/// Refuses any test that arms `plane`, the way a driver refuses a plane it
/// will not drive on this CRTC.
#[derive(Debug, Default)]
struct RefusingPlane {
    plane: u32,
    calls: usize,
}

impl TestCommitter for RefusingPlane {
    fn test_assignment(&mut self, assignment: &[(u32, LayerRef<'_>)]) -> Result<(), TestFailure> {
        self.calls += 1;
        if assignment
            .iter()
            .any(|(plane_id, _)| *plane_id == self.plane)
        {
            Err(TestFailure::Rejected)
        } else {
            Ok(())
        }
    }
}

/// A pin the driver refuses is tested before it is committed, not committed
/// untested to fail the frame whole (drm-cxx `c766e97`). The refused layer is
/// left off its plane and counted, and from the next frame takes normal
/// allocation, without asking the kernel about that pin again.
#[test]
fn a_pin_the_driver_refuses_is_caught_before_the_commit() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    let layer = scene.layer_mut(handle).expect("layer");
    layer.set_display(full_screen());
    layer.set_pinned_plane(Some(32));
    let mut committer = RefusingPlane {
        plane: 32,
        ..RefusingPlane::default()
    };

    let build = scene
        .build_frame(&registry(), 0, real(), &mut committer)
        .expect("the frame with the refused pin");
    assert!(
        build.plan().iter().all(|entry| entry.plane_id != 32),
        "the refused plane is not programmed: {:?}",
        build.plan()
    );
    let report = scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    assert_eq!(report.pin_requests_unhonored, 1, "{report:?}");
    assert!(report.accounting_balances(), "{report:?}");

    // From the next frame the layer is unpinned: every test is the
    // allocator's own search for it, and none is the pin asked again.
    let tests_before = committer.calls;
    let build = scene
        .build_frame(&registry(), 0, real(), &mut committer)
        .expect("the next frame");
    let report = scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    assert_eq!(
        report.pin_requests_unhonored, 1,
        "still counted: {report:?}"
    );
    assert!(report.accounting_balances(), "{report:?}");
    assert_eq!(
        committer.calls - tests_before,
        report.test_commits_issued,
        "the refused pin is not tested again"
    );
}

/// A pin the driver takes is tested once; a steady frame does not ask again.
#[test]
fn an_accepted_pin_is_tested_once() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    let layer = scene.layer_mut(handle).expect("layer");
    layer.set_display(full_screen());
    layer.set_pinned_plane(Some(32));
    let mut committer = Accepting::default();

    for frame in 0..3 {
        let build = scene
            .build_frame(&registry(), 0, real(), &mut committer)
            .expect("frame");
        let placed: Vec<u32> = build.plan().iter().map(|entry| entry.plane_id).collect();
        assert_eq!(placed, [32], "frame {frame}");
        let report = scene.finalize_frame(build, KernelResult::Ok);
        scene.flip_landed();
        assert_eq!(report.pin_requests_unhonored, 0, "{report:?}");
    }
    assert_eq!(committer.calls, 1, "one test, for the pin");
}

// --- colorimetry -------------------------------------------------------------

/// A layer's `COLOR_ENCODING` and `COLOR_RANGE` ride its plan entry, with the
/// defaults filled in where it asked for nothing.
///
/// The emitter reads them off the entry; a layer whose request did not reach
/// it would be shown through BT.709 limited whatever it set, which is P-52.
#[test]
fn a_layers_ycbcr_rides_its_plan_entry() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let video = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(video)
        .expect("layer")
        .set_display(DisplayParams {
            color_encoding: Some(ColorEncoding::Bt601),
            color_range: Some(ColorRange::Full),
            zpos: Some(0),
            ..full_screen()
        });
    let plain = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(plain)
        .expect("layer")
        .set_display(DisplayParams {
            zpos: Some(1),
            ..full_screen()
        });

    let registry = registry();
    let mut committer = Accepting::default();
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    let color_of = |handle: drmkit_scene::LayerHandle| {
        build
            .plan()
            .iter()
            .find(|entry| entry.layer_id == handle.layer_id())
            .map(|entry| entry.color)
    };
    assert_eq!(
        color_of(video),
        Some(Some(Ycbcr {
            encoding: ColorEncoding::Bt601,
            range: ColorRange::Full,
        })),
        "the override reaches the plan"
    );
    assert_eq!(
        color_of(plain),
        Some(Some(Ycbcr {
            encoding: ColorEncoding::Bt709,
            range: ColorRange::Limited,
        })),
        "no override is BT.709 limited, upstream's default"
    );
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    scene.drain();
}

/// Sticky properties are restated until the scene knows what the kernel
/// holds: on the first frame, and on the first after a resume.
///
/// In between they are diffed against what the last real commit carried.
/// Upstream clears its cache of them on resume and rebind for the same
/// reason: whoever held the planes meanwhile may have left their own.
#[test]
fn sticky_properties_are_restated_until_the_kernel_is_known() {
    let log = Rc::new(RefCell::new(SourceLog::default()));
    let mut scene = LayerScene::new(1);
    let handle = scene.add_layer(Box::new(TestSource::new(&log)));
    scene
        .layer_mut(handle)
        .expect("layer")
        .set_display(full_screen());
    let registry = registry();
    let mut committer = Accepting::default();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    assert!(build.restates_sticky(), "the first frame restates");
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();

    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("build");
    assert!(
        !build.restates_sticky(),
        "once a frame has landed, what the kernel holds is known"
    );
    scene.finalize_frame(build, KernelResult::NotMaster);
    assert!(scene.is_suspended());

    scene.resume();
    let build = scene
        .build_frame(&registry, 0, real(), &mut committer)
        .expect("resumed");
    assert!(
        build.restates_sticky(),
        "after a resume another client may have changed them"
    );
    scene.finalize_frame(build, KernelResult::Ok);
    scene.flip_landed();
    scene.drain();
}