frust-shell-common 0.5.2

Platform-agnostic shell plumbing shared by the Frust platform shells: app-tree erasure, FFI guards, window metrics and insets.
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
//! Render-thread-split plumbing shared by every shell.
//!
//! # What lives here
//!
//! The split moves `encode→acquire→blit→present` off the UI thread onto a
//! dedicated render thread: the UI thread keeps
//! `rebuild→layout→paint`, then hands the finished [`Scene`] across. This
//! module is the *vocabulary* for that handoff — the shells
//! own the threads and the `wgpu`/`vello` resources, this crate owns the
//! platform-free channel types and the pure lifecycle/kill-switch logic they
//! coordinate through.
//!
//! - [`render_channel`] — the single UI→render link: a **depth-1, latest-wins**
//!   scene-handoff slot (a newer [`SceneFrame`] replaces an un-taken one; the
//!   render thread always takes the freshest, dropping stale frames) fused with
//!   a FIFO lifecycle-command queue behind **one** [`std::sync::Condvar`], so
//!   the render thread has a single wait point ([`RenderReceiver::wait_next`]).
//!   Depth 1 is deliberate — Flutter's merged-mode precedent shows pipeline
//!   depth drops to 1 when threads merge; deeper queues add latency
//!   for no mobile win.
//! - [`scene_return_channel`] — the reverse, render→UI give-back link: a
//!   **non-blocking, depth-1** [`Mutex`]-only slot (no
//!   [`Condvar`] — the UI thread only ever polls it, never parks) the render
//!   thread pushes a drained scene back through once it is done reading it, so
//!   a shell's split `submit_frame` can `Scene::reset()` and reuse the buffer
//!   next frame instead of reallocating one via `Scene::new()` every frame —
//!   restoring frust-scene's documented reuse contract (`scene.rs`'s
//!   `Scene::reset` docs) in split mode.
//! - [`RenderCommand`] / [`RenderEvent`] / [`RenderPhase`] — the surface
//!   lifecycle vocabulary (created/changed/destroyed/pause/resume) as **owned
//!   commands**, modelled on `frust-render`'s `SurfacePhase` machine: a pure,
//!   host-testable [`next_render_phase`] transition table gates whether the
//!   render thread [`may render`](RenderPhase::can_render).
//! - [`Ack`] / [`AckWaiter`] — the cross-thread acknowledgment barrier that
//!   makes [`RenderCommand::Pause`] and [`RenderCommand::SurfaceDestroyed`]
//!   *synchronous*: the UI thread blocks until the render thread has honored
//!   the command. This is the correctness anchor for two platform hazards:
//!   Android can destroy the `ANativeWindow` while the render
//!   thread still holds the surface, and iOS can kill a process that submits
//!   Metal work after the app backgrounds. Both are barriers, not shared
//!   mutable flags.
//! - [`SceneFrame`] / [`FrameMeta`] / [`SurfaceSize`] — the per-frame payload
//!   crossing the handoff: the scene plus the frame clock, the surface
//!   dimensions, and (for the single-emitter perf recording)
//!   the UI thread's [`UiSpans`] half of the frame timing, which the render
//!   thread folds together with its own [`RenderSpans`] via
//!   [`FramePasses::from_split`](crate::perf::FramePasses::from_split).
//! - [`render_thread_enabled`] / [`NO_RENDER_THREAD_VAR`] — the single kill
//!   switch the shells consult, parsed exactly like [`crate::frame_gate`]'s
//!   `FRUST_NO_FRAME_GATE` (compile-time define *or* runtime env, any non-`"0"`
//!   value). When engaged, a shell keeps the pre-split single-thread path (kept
//!   as an escape hatch until the split's on-device throughput is fully
//!   validated).
//!
//! # Benchmark scenario markers
//!
//! The channel carries one thing beside the scene: the benchmark
//! scenario-window edges [`crate::perf::mark_scenario_start`] raises, so
//! each is logged stamped with the frame that actually carried it. Three
//! properties of that route are load-bearing here.
//!
//! - **`perf-trace`-only.** Every marker field, call and queue in this
//!   module is behind the feature; a release-lean build has no marker code
//!   in the channel at all, and a `perf-trace` build with `FRUST_TRACE` off
//!   pays one cached bool read per [`RenderSender::send_scene`].
//! - **Per-thread, not process-wide.** [`RenderSender::send_scene`] moves
//!   the **calling** thread's raised markers into the inbox, and [`drain`]
//!   stages the taken frame's markers onto the **calling** (render) thread,
//!   which is the thread about to record that frame. No shared queue and no
//!   flag decide who owns a marker; the thread that raised it does, until it
//!   hands a frame off.
//! - **A marker from a thread that hands no frame off is never emitted.**
//!   Only the UI thread's own queue crosses this channel, so a marker raised
//!   on, say, a blocking-pool thread stays there and dies with it — see
//!   [`crate::perf::mark_scenario_start`], which documents the rule and why
//!   the alternative (attaching it to some other thread's frame) is the
//!   cross-thread guess this route exists to remove.
//!
//! # Layering choice
//!
//! Like [`crate::perf`] and [`crate::frame_gate`], this is shell-owned and
//! platform-free: it takes **no** `frust-render`/`wgpu`/`vello` dependency, no
//! `unsafe`, and no `frust-reactive`, preserving this crate's
//! compiles-everywhere, reactive-free charter (see `docs/ARCHITECTURE.md`'s
//! Layer Dependencies). The scene payload ([`SceneFrame`]) and the surface
//! handle a [`RenderCommand::SurfaceCreated`] carries are therefore *generic*
//! parameters (`S`/`W`): a shell instantiates `S = frust_scene::Scene` and `W`
//! = its own raw-window wrapper, while these host tests instantiate cheap
//! stand-ins, so the whole channel is exercised without a GPU or a platform.
//!
//! # Wiring
//!
//! This module ships the channel types + pure logic; the desktop, Android,
//! and iOS shells each spawn their own render thread on top of it, gated by
//! [`render_thread_enabled`].
//!
//! [`Scene`]: https://docs.rs/frust-scene
//! [`UiSpans`]: crate::perf::UiSpans
//! [`RenderSpans`]: crate::perf::RenderSpans

use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;

use frust_core::anim::FrameTime;

#[cfg(feature = "perf-trace")]
use crate::perf::MarkerQueue;
use crate::perf::UiSpans;

// ---------------------------------------------------------------------
// Kill switch
// ---------------------------------------------------------------------

/// The render-thread-split kill-switch environment/compile-time variable: when
/// set to any non-`"0"` value, [`render_thread_enabled`] is `false` and a shell
/// keeps the pre-split single-thread frame path.
///
/// Parsed exactly like [`crate::frame_gate::NO_FRAME_GATE_VAR`] — either the
/// compile-time `--define` or the runtime process env engages it.
pub const NO_RENDER_THREAD_VAR: &str = "FRUST_NO_RENDER_THREAD";

/// Whether a shell should run the render-thread split — the **single switch**
/// every shell consults. `true` unless the
/// [`NO_RENDER_THREAD_VAR`] kill switch is engaged (compile-time define or
/// runtime env, any non-`"0"` value), mirroring [`crate::perf::enabled`]'s and
/// [`crate::frame_gate`]'s `option_env!` + runtime-env parsing precedent.
///
/// Read once at shell startup: a shell that takes the split path spawns the
/// render thread, a shell where this is `false` keeps the single-thread path
/// verbatim.
pub fn render_thread_enabled() -> bool {
    !render_thread_kill_switch(
        option_env!("FRUST_NO_RENDER_THREAD"),
        std::env::var(NO_RENDER_THREAD_VAR).ok().as_deref(),
    )
}

/// The pure decision [`render_thread_enabled`] negates: a non-empty, non-`"0"`
/// value from either the compile-time or runtime source engages the kill
/// switch. Split out so it is directly unit-testable without touching the
/// process environment (see [`crate::frame_gate`]'s `kill_switch`).
fn render_thread_kill_switch(compile_time: Option<&str>, runtime: Option<&str>) -> bool {
    fn is_set_non_zero(value: Option<&str>) -> bool {
        matches!(value, Some(v) if v != "0")
    }
    is_set_non_zero(compile_time) || is_set_non_zero(runtime)
}

// ---------------------------------------------------------------------
// Frame payload
// ---------------------------------------------------------------------

/// The surface dimensions a [`SceneFrame`] / [`RenderCommand`] carries — the
/// physical (device-pixel) swapchain size plus the HiDPI scale factor, so the
/// render thread can (re)configure the surface without consulting the UI
/// thread. Physical-at-the-boundary matches the render thread's swapchain
/// needs (`docs/CODE_STANDARDS.md`'s physical-at-FFI, logical-inside rule).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SurfaceSize {
    /// Physical (device-pixel) width of the surface.
    pub width: u32,
    /// Physical (device-pixel) height of the surface.
    pub height: u32,
    /// HiDPI scale factor (physical / logical), already sanitized by the
    /// shell's [`sanitize_scale`](crate::sanitize_scale) at the FFI boundary.
    pub scale: f64,
}

/// Per-frame metadata riding the scene-handoff channel alongside the scene
/// itself.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FrameMeta {
    /// The shell's frame clock for this frame (`Choreographer`/`CADisplayLink`/
    /// desktop epoch), threaded through to `PaintCtx::frame_time` so the render
    /// thread advances animations against the same clock the UI thread painted
    /// with. Only *differences* of two [`FrameTime`]s carry meaning (see its
    /// docs).
    pub frame_time: FrameTime,
    /// The surface size this scene was laid out for — the render thread checks
    /// it against the live swapchain configuration before encoding.
    pub size: SurfaceSize,
    /// Monotonically increasing per-frame id the UI thread stamps, so a dropped
    /// (latest-wins-replaced) frame is observable in diagnostics and so a
    /// render-side report can be paired back to the frame that produced it.
    pub frame_id: u64,
}

/// One frame handed from the UI thread to the render thread across
/// [`render_channel`]: the finished scene, its
/// [`FrameMeta`], and the UI thread's [`UiSpans`] half of the frame timing
/// (the render thread is the single perf emitter).
///
/// Generic over the scene type `S` so this crate stays render-free: a shell
/// instantiates `SceneFrame<frust_scene::Scene>`, host tests use a cheap
/// stand-in.
#[derive(Debug, Clone)]
pub struct SceneFrame<S> {
    /// The finished scene the render thread encodes (`frust_scene::Scene` in a
    /// real shell — `Scene` is `Send`, verified by its compile-time tripwire).
    pub scene: S,
    /// This frame's metadata (clock, surface size, id).
    pub meta: FrameMeta,
    /// The UI thread's `rebuild`/`layout`/`paint` timing, folded with the
    /// render thread's [`RenderSpans`](crate::perf::RenderSpans) via
    /// [`FramePasses::from_split`](crate::perf::FramePasses::from_split) into
    /// the one recorded frame.
    pub ui_spans: UiSpans,
}

// ---------------------------------------------------------------------
// Lifecycle: phase machine (modelled on frust-render's SurfacePhase)
// ---------------------------------------------------------------------

/// A surface-lifecycle event that drives a render-thread [`RenderPhase`]
/// transition — the pure, `Copy` counterpart of a [`RenderCommand`] (mirroring
/// `frust-render`'s `SurfaceEvent`/callback split, keeping the transition table
/// host-testable without the owned `Ack`/window payloads).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderEvent {
    /// A surface became available (`surfaceCreated`/`resumed`/`set_surface`).
    SurfaceCreated,
    /// The existing surface was resized/reconfigured (rotation, inset change).
    SurfaceChanged,
    /// The surface is being torn down (`surfaceDestroyed`/`suspended`).
    SurfaceDestroyed,
    /// The app is backgrounding: stop submitting until [`Self::Resume`].
    Pause,
    /// The app returned to the foreground with its surface intact.
    Resume,
}

/// The render thread's view of surface lifecycle state,
/// modelled on `frust-render`'s `SurfacePhase`: the render loop renders a
/// handed-off [`SceneFrame`] only while [`can_render`](Self::can_render) — i.e.
/// only in [`RenderPhase::Active`]. [`RenderPhase::Paused`] is the cross-thread
/// backgrounding barrier (a leftover scene must NOT be submitted after a
/// `Pause`, per the iOS process-kill hazard).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderPhase {
    /// No usable surface: nothing to render into (initial state, or after a
    /// [`RenderEvent::SurfaceDestroyed`]).
    NoSurface,
    /// A configured surface is available and frames may be submitted.
    Active,
    /// The app backgrounded ([`RenderEvent::Pause`]); the surface may still
    /// exist but the render thread must not submit until [`RenderEvent::Resume`].
    Paused,
}

impl RenderPhase {
    /// Whether the render thread may submit a frame in this phase — only
    /// [`RenderPhase::Active`], mirroring `SurfacePhase::can_render`. A render
    /// loop checks this before encoding a handed-off [`SceneFrame`], so a scene
    /// left in the latest-wins slot when a `Pause`/`Destroy` is processed is
    /// dropped rather than submitted.
    pub fn can_render(self) -> bool {
        matches!(self, RenderPhase::Active)
    }
}

/// Pure render-phase transition table, the analogue of
/// `frust-render`'s `next_phase`. Total by design:
///
/// - `SurfaceCreated` → [`Active`](RenderPhase::Active) (create or recreate),
/// - `SurfaceDestroyed` → [`NoSurface`](RenderPhase::NoSurface),
/// - `SurfaceChanged` → the current phase unchanged (a resize never changes
///   *whether* we can render — mirrors "resize stays Ready"),
/// - `Pause` → [`Paused`](RenderPhase::Paused) unless there is no surface (you
///   cannot pause what was never created),
/// - `Resume` → [`Active`](RenderPhase::Active) unless there is no surface (you
///   cannot resume onto a surface that is gone; the shell must recreate it
///   first via `SurfaceCreated`).
pub fn next_render_phase(current: RenderPhase, event: RenderEvent) -> RenderPhase {
    match event {
        RenderEvent::SurfaceCreated => RenderPhase::Active,
        RenderEvent::SurfaceDestroyed => RenderPhase::NoSurface,
        RenderEvent::SurfaceChanged => current,
        RenderEvent::Pause => match current {
            RenderPhase::NoSurface => RenderPhase::NoSurface,
            _ => RenderPhase::Paused,
        },
        RenderEvent::Resume => match current {
            RenderPhase::NoSurface => RenderPhase::NoSurface,
            _ => RenderPhase::Active,
        },
    }
}

// ---------------------------------------------------------------------
// Lifecycle: acknowledgment barrier
// ---------------------------------------------------------------------

/// The render-thread side of an acknowledgment barrier: the render thread holds
/// this (moved out of a [`RenderCommand::Pause`]/[`RenderCommand::SurfaceDestroyed`])
/// while honoring the command, then [`acknowledge`](Self::acknowledge)s it —
/// unblocking the UI thread's paired [`AckWaiter`].
///
/// Dropping an `Ack` without an explicit [`acknowledge`](Self::acknowledge)
/// still signals (a safety net so a render thread that returns early — or
/// panics past the command — can never deadlock the UI thread), but a render
/// loop should acknowledge explicitly *after* the pause/destroy work is done,
/// which is exactly the barrier the two platform hazards need (Android window
/// release, iOS backgrounding).
#[derive(Debug)]
pub struct Ack {
    shared: Arc<AckShared>,
}

/// The UI-thread side of an acknowledgment barrier: the UI thread
/// [`wait`](Self::wait)s on this after sending a [`RenderCommand::Pause`]/
/// [`RenderCommand::SurfaceDestroyed`], blocking until the render thread has
/// [`acknowledge`](Ack::acknowledge)d (or dropped) the paired [`Ack`].
#[derive(Debug)]
pub struct AckWaiter {
    shared: Arc<AckShared>,
}

#[derive(Debug)]
struct AckShared {
    done: Mutex<bool>,
    signal: Condvar,
}

/// Create a linked [`AckWaiter`] / [`Ack`] barrier pair: the UI thread keeps
/// the waiter, the render thread receives the ack (inside the command). Used by
/// [`RenderSender::pause`]/[`RenderSender::destroy_surface`]; exposed directly
/// for shells building lifecycle commands by hand.
pub fn ack_pair() -> (AckWaiter, Ack) {
    let shared = Arc::new(AckShared {
        done: Mutex::new(false),
        signal: Condvar::new(),
    });
    (
        AckWaiter {
            shared: shared.clone(),
        },
        Ack { shared },
    )
}

impl Ack {
    /// Signal the paired [`AckWaiter`] that the command has been honored,
    /// consuming the ack. Equivalent to dropping it (the signal fires in
    /// [`Drop`]), but reads as the deliberate end-of-command acknowledgment the
    /// barrier contract expects.
    pub fn acknowledge(self) {
        // The Drop impl performs the signal; consuming `self` here runs it.
    }
}

impl Drop for Ack {
    fn drop(&mut self) {
        let mut done = self.shared.done.lock().unwrap();
        *done = true;
        drop(done);
        self.shared.signal.notify_all();
    }
}

impl AckWaiter {
    /// Block the UI thread until the render thread has acknowledged (or dropped)
    /// the paired [`Ack`]. Returns immediately if already acknowledged. This is
    /// the barrier: after it returns, the caller may safely proceed to release
    /// the window (Android) or let the app background (iOS).
    pub fn wait(self) {
        let mut done = self.shared.done.lock().unwrap();
        while !*done {
            done = self.shared.signal.wait(done).unwrap();
        }
    }

    /// Block the UI thread until the render thread acknowledges the paired
    /// [`Ack`] **or** `timeout` elapses, whichever comes first. Returns `true` if
    /// the ack fired (the barrier was honored), `false` on timeout.
    ///
    /// This is the **bounded** counterpart of [`Self::wait`]: the correctness fix
    /// (receiver-liveness — see [`RenderReceiver`]'s [`Drop`]) means a live render
    /// thread's ack always fires, but a render thread wedged mid-command (a GPU
    /// driver hang, not a clean exit) would still block [`Self::wait`] forever.
    /// A timeout lets the caller **degrade instead of hang** — proceed to release
    /// the window / let the app background after logging — so a stuck render
    /// thread never trips a platform watchdog (iOS backgrounding kill, Android
    /// ANR). Each call site picks a named, doc-commented per-platform deadline
    /// safely under its watchdog budget.
    #[must_use = "the caller must handle a timeout (proceed degraded) rather than assume the barrier was honored"]
    pub fn wait_timeout(self, timeout: Duration) -> bool {
        let done = self.shared.done.lock().unwrap();
        let (done, _timeout_result) = self
            .shared
            .signal
            .wait_timeout_while(done, timeout, |done| !*done)
            .unwrap();
        *done
    }

    /// Whether the paired [`Ack`] has been acknowledged yet, without blocking —
    /// a non-consuming diagnostic peek (the barrier proper is [`Self::wait`]).
    pub fn completed(&self) -> bool {
        *self.shared.done.lock().unwrap()
    }
}

// ---------------------------------------------------------------------
// Lifecycle: command vocabulary
// ---------------------------------------------------------------------

/// A lifecycle command the UI thread sends to the render thread across
/// [`render_channel`], as an **owned** value — not a shared
/// mutable flag. Generic over the surface-handle type `W` a
/// [`Self::SurfaceCreated`] carries (`frust-render`'s raw-window wrapper in a
/// real shell; a stand-in in host tests), keeping this crate render-free.
///
/// [`Self::Pause`] and [`Self::SurfaceDestroyed`] carry an [`Ack`]: the UI
/// thread blocks on the paired [`AckWaiter`] until the render thread honors
/// them (the window-release / backgrounding barrier). The others are
/// fire-and-forget. The command's effect on the render thread's [`RenderPhase`]
/// is given by [`Self::event`] → [`next_render_phase`].
#[derive(Debug)]
pub enum RenderCommand<W> {
    /// A surface became available: the render thread takes ownership of `window`
    /// and (re)configures its swapchain to `size`. Fire-and-forget.
    SurfaceCreated {
        /// The raw surface handle the render thread takes ownership of.
        window: W,
        /// The initial physical surface size.
        size: SurfaceSize,
    },
    /// The existing surface was resized/reconfigured (rotation, inset change).
    /// Fire-and-forget.
    SurfaceChanged {
        /// The new physical surface size.
        size: SurfaceSize,
    },
    /// The surface is being torn down: the render thread must drop every
    /// surface-derived `wgpu` resource **before acknowledging**, so the UI
    /// thread can safely release the underlying window (the Android
    /// `ANativeWindow`-release hazard). Blocks the UI thread via [`Ack`].
    SurfaceDestroyed {
        /// Acknowledged once surface resources are dropped.
        ack: Ack,
    },
    /// The app is backgrounding: the render thread must stop submitting frames
    /// **before acknowledging**, so the app never submits Metal/Vulkan work
    /// after it backgrounds (the iOS process-kill hazard). Blocks the UI thread
    /// via [`Ack`].
    Pause {
        /// Acknowledged once the render thread has quiesced.
        ack: Ack,
    },
    /// The app returned to the foreground with its surface intact: resume
    /// submitting. Fire-and-forget.
    Resume,
}

impl<W> RenderCommand<W> {
    /// The pure [`RenderEvent`] this command drives on the render thread's
    /// [`RenderPhase`] — the `Copy` projection that feeds [`next_render_phase`]
    /// (borrowing `self`, leaving the owned `Ack`/`window` in place).
    pub fn event(&self) -> RenderEvent {
        match self {
            RenderCommand::SurfaceCreated { .. } => RenderEvent::SurfaceCreated,
            RenderCommand::SurfaceChanged { .. } => RenderEvent::SurfaceChanged,
            RenderCommand::SurfaceDestroyed { .. } => RenderEvent::SurfaceDestroyed,
            RenderCommand::Pause { .. } => RenderEvent::Pause,
            RenderCommand::Resume => RenderEvent::Resume,
        }
    }

    /// Whether this command carries an [`Ack`] the UI thread blocks on — `true`
    /// for [`Self::Pause`]/[`Self::SurfaceDestroyed`], `false` for the
    /// fire-and-forget variants.
    pub fn requires_ack(&self) -> bool {
        matches!(
            self,
            RenderCommand::SurfaceDestroyed { .. } | RenderCommand::Pause { .. }
        )
    }
}

// ---------------------------------------------------------------------
// The UI→render channel: latest-wins scene slot + FIFO command queue
// ---------------------------------------------------------------------

/// The shared state behind [`render_channel`]: a depth-1 latest-wins scene slot
/// and a FIFO command queue, both under one mutex + condvar so the render
/// thread has a single wait point.
#[derive(Debug)]
struct Inbox<S, W> {
    /// The freshest un-taken scene (depth-1 latest-wins): a newer send replaces
    /// it, incrementing [`Self::dropped`].
    latest: Option<SceneFrame<S>>,
    /// Count of scenes replaced (dropped) before the render thread took them —
    /// the latest-wins drop counter, observable via
    /// [`RenderReceiver::dropped_frames`].
    dropped: u64,
    /// Pending lifecycle commands in FIFO order.
    commands: Vec<RenderCommand<W>>,
    /// Benchmark scenario markers moved out of the UI thread's own queue
    /// since the render thread last took a scene, waiting to travel with the
    /// next one ([`crate::perf::mark_scenario_start`]).
    ///
    /// They live here rather than on [`SceneFrame`] deliberately: the shells
    /// build that struct by literal and destructure [`RenderBatch`], so a new
    /// field there would be a breaking edit to three shell crates for a
    /// benchmark-only concern. Keeping them beside the slot also gives the
    /// right latest-wins behaviour for free — when a newer scene replaces an
    /// un-taken one, the replaced build's markers stay queued and ride the
    /// frame that supersedes it, which is the frame that actually drew that
    /// build's result.
    ///
    /// Private, `perf-trace`-only, and bounded like every other leg of the
    /// route (see [`crate::perf::MarkerQueue`]): a channel whose render
    /// thread stopped taking scenes must stop accumulating markers rather
    /// than grow one un-drained queue for the life of the process.
    #[cfg(feature = "perf-trace")]
    pending_markers: MarkerQueue,
    /// Cleared when the [`RenderSender`] is dropped, so a blocked
    /// [`RenderReceiver::wait_next`] wakes and reports disconnection (the render
    /// loop's clean-exit signal).
    sender_alive: bool,
    /// Cleared when the [`RenderReceiver`] is dropped (the render thread exited —
    /// panic-unwind, a clean early `return`, or a hung thread's drop). Once
    /// `false`, [`RenderSender::send_command`]/[`RenderSender::send_scene`] drop
    /// (rather than queue) new work: an ack-carrying command dropped here fires
    /// its [`Ack`]'s [`Drop`] safety net, so a UI thread blocked on the paired
    /// [`AckWaiter`] can never wedge on a command the departed render thread will
    /// never drain. Symmetric with [`Self::sender_alive`].
    receiver_alive: bool,
}

#[derive(Debug)]
struct Channel<S, W> {
    inbox: Mutex<Inbox<S, W>>,
    signal: Condvar,
}

/// The UI-thread handle to the render channel: sends scenes
/// (latest-wins) and lifecycle commands (FIFO). Single-producer by design (the
/// UI thread), so it is deliberately not [`Clone`].
#[derive(Debug)]
pub struct RenderSender<S, W> {
    channel: Arc<Channel<S, W>>,
}

/// The render-thread handle to the render channel: the
/// single wait point ([`Self::wait_next`]) draining pending commands plus the
/// freshest scene each wakeup.
#[derive(Debug)]
pub struct RenderReceiver<S, W> {
    channel: Arc<Channel<S, W>>,
}

/// One wakeup's worth of work handed to the render thread by
/// [`RenderReceiver::wait_next`]/[`RenderReceiver::try_next`]: the lifecycle
/// commands to process (FIFO), then the freshest scene to render (if any). A
/// render loop processes `commands` first (updating its [`RenderPhase`]), then
/// renders `scene` only if the resulting phase [`can_render`](RenderPhase::can_render).
#[derive(Debug)]
pub struct RenderBatch<S, W> {
    /// Pending lifecycle commands in FIFO order.
    pub commands: Vec<RenderCommand<W>>,
    /// The freshest scene handed off since the last drain (latest-wins), or
    /// `None` if no new scene arrived.
    pub scene: Option<SceneFrame<S>>,
    /// `true` once the [`RenderSender`] has been dropped and no work remains —
    /// the render loop's signal to exit cleanly.
    pub disconnected: bool,
}

/// Create the UI→render channel: a depth-1 latest-wins
/// scene slot fused with a FIFO lifecycle-command queue behind one condvar.
///
/// `S` is the scene payload type (`frust_scene::Scene` in a real shell), `W`
/// the surface-handle type a [`RenderCommand::SurfaceCreated`] carries — both
/// generic so this crate stays render-free (see the module docs' Layering
/// choice).
pub fn render_channel<S, W>() -> (RenderSender<S, W>, RenderReceiver<S, W>) {
    let channel = Arc::new(Channel {
        inbox: Mutex::new(Inbox {
            latest: None,
            dropped: 0,
            commands: Vec::new(),
            #[cfg(feature = "perf-trace")]
            pending_markers: MarkerQueue::new(),
            sender_alive: true,
            receiver_alive: true,
        }),
        signal: Condvar::new(),
    });
    (
        RenderSender {
            channel: channel.clone(),
        },
        RenderReceiver { channel },
    )
}

impl<S, W> RenderSender<S, W> {
    /// Hand a finished frame to the render thread (**depth-1 latest-wins**): if
    /// an un-taken scene is still in the slot it is replaced (the drop counter
    /// still increments — see [`Inbox::dropped`]) and **returned** to the
    /// caller instead of being silently dropped in the lock — a shell can
    /// reclaim the stale frame's scene buffer the same way
    /// it reclaims one off [`scene_return_channel`]. `None` if the slot was
    /// empty. A pure widening of the original fire-and-forget signature — a
    /// caller that doesn't care may still ignore the return value. Wakes the
    /// render thread's [`RenderReceiver::wait_next`].
    ///
    /// Also picks up any benchmark scenario markers **this** thread raised
    /// since the last send ([`Inbox::pending_markers`]), so they cross with
    /// this handoff instead of being stamped with a frame number guessed on
    /// this side of the split (`perf-trace` builds only; see the module
    /// docs' scenario-marker section).
    pub fn send_scene(&self, frame: SceneFrame<S>) -> Option<SceneFrame<S>> {
        let mut inbox = self.channel.inbox.lock().unwrap();
        if !inbox.receiver_alive {
            // The render thread is gone (see `Inbox::receiver_alive`): don't
            // queue `frame` into a slot no one will ever take — hand it straight
            // back so the caller can still reclaim its buffer. `frame` carries no
            // `Ack`, so nothing else needs firing either way.
            //
            // The markers raised for it are drained and discarded rather than
            // left queued: no frame will ever be recorded for them now, and a
            // queue this send stopped draining is a queue that grows for the
            // rest of the process.
            #[cfg(feature = "perf-trace")]
            drop(crate::perf::take_pending_markers());
            return Some(frame);
        }
        // Before the slot is written: every marker this thread raised up to
        // this moment belongs to the build being handed off now (or to an
        // earlier one whose scene this send replaces — same frame, once it is
        // recorded). Moving them out of the calling thread's queue is what
        // makes them this handoff's, so `FrameStats::record` over on the
        // render thread can never see a marker that is still being built here.
        #[cfg(feature = "perf-trace")]
        inbox
            .pending_markers
            .absorb(crate::perf::take_pending_markers());
        let stale = inbox.latest.replace(frame);
        if stale.is_some() {
            inbox.dropped += 1;
        }
        drop(inbox);
        self.channel.signal.notify_one();
        stale
    }

    /// Queue a lifecycle command (FIFO) and wake the render thread. For the
    /// ack-carrying [`RenderCommand::Pause`]/[`RenderCommand::SurfaceDestroyed`]
    /// prefer [`Self::pause`]/[`Self::destroy_surface`], which build the barrier
    /// pair and return the [`AckWaiter`] to block on.
    pub fn send_command(&self, command: RenderCommand<W>) {
        let mut inbox = self.channel.inbox.lock().unwrap();
        if !inbox.receiver_alive {
            // The render thread is gone (see `Inbox::receiver_alive`): drop the
            // command rather than queue it forever. Releasing the inbox lock first,
            // then dropping `command`, fires any embedded `Ack`'s `Drop` safety net
            // (Pause/SurfaceDestroyed), so a UI thread blocked on the paired
            // `AckWaiter` unblocks instead of deadlocking.
            drop(inbox);
            drop(command);
            return;
        }
        inbox.commands.push(command);
        drop(inbox);
        self.channel.signal.notify_one();
    }

    /// Send a [`RenderCommand::Pause`] and return the [`AckWaiter`] the UI
    /// thread must [`wait`](AckWaiter::wait) on **before letting the app
    /// background** — the iOS process-kill barrier.
    #[must_use = "the caller must wait() on the returned AckWaiter before backgrounding"]
    pub fn pause(&self) -> AckWaiter {
        let (waiter, ack) = ack_pair();
        self.send_command(RenderCommand::Pause { ack });
        waiter
    }

    /// Send a [`RenderCommand::SurfaceDestroyed`] and return the [`AckWaiter`]
    /// the UI thread must [`wait`](AckWaiter::wait) on **before releasing the
    /// window** — the Android `ANativeWindow`-release barrier.
    #[must_use = "the caller must wait() on the returned AckWaiter before releasing the window"]
    pub fn destroy_surface(&self) -> AckWaiter {
        let (waiter, ack) = ack_pair();
        self.send_command(RenderCommand::SurfaceDestroyed { ack });
        waiter
    }
}

impl<S, W> Drop for RenderSender<S, W> {
    fn drop(&mut self) {
        let mut inbox = self.channel.inbox.lock().unwrap();
        inbox.sender_alive = false;
        drop(inbox);
        // notify_all: a receiver blocked in wait_next must wake to observe the
        // disconnection and exit its loop.
        self.channel.signal.notify_all();
    }
}

impl<S, W> Drop for RenderReceiver<S, W> {
    fn drop(&mut self) {
        // The render thread is exiting (panic-unwind, a clean early `return`, or a
        // hung thread being torn down). Symmetric with `Drop for RenderSender`:
        // mark the receiver gone and drain any undrained work so an ack-carrying
        // command the render loop never reached (a `Pause`/`SurfaceDestroyed`
        // still in `commands`, or embedded in `latest` — the latter carries none
        // today, drained for completeness) fires its `Ack`'s `Drop` safety net.
        // Without this, that command would sit in the inbox forever (kept alive by
        // the `Arc<Channel>` the still-blocked UI side holds), the safety net would
        // never fire, and `AckWaiter::wait()` would deadlock the UI/main thread —
        // the load-bearing correctness fix this drop impl provides.
        let mut inbox = self.channel.inbox.lock().unwrap();
        inbox.receiver_alive = false;
        let commands = std::mem::take(&mut inbox.commands);
        let latest = inbox.latest.take();
        // No thread will ever record a frame for these, so they are dropped
        // rather than staged — a marker with no frame to name is nothing.
        #[cfg(feature = "perf-trace")]
        inbox.pending_markers.clear();
        drop(inbox);
        // Drop the drained work *after* releasing the inbox lock — dropping an
        // `Ack` locks its own (separate) mutex to signal, so ordering here avoids
        // holding the inbox lock across that notify.
        drop(commands);
        drop(latest);
        // notify_all for symmetry with the sender's drop (no thread blocks on the
        // channel condvar once the receiver is gone, but a stray waiter must never
        // be left parked).
        self.channel.signal.notify_all();
    }
}

impl<S, W> RenderReceiver<S, W> {
    /// Block until there is work — a pending command, a fresh scene, or a
    /// [`RenderSender`] disconnection — then drain it into one [`RenderBatch`].
    /// The render thread's single wait point.
    pub fn wait_next(&self) -> RenderBatch<S, W> {
        let mut inbox = self.channel.inbox.lock().unwrap();
        inbox = self
            .channel
            .signal
            .wait_while(inbox, |i| {
                i.commands.is_empty() && i.latest.is_none() && i.sender_alive
            })
            .unwrap();
        drain(&mut inbox)
    }

    /// Drain any pending commands + the freshest scene without blocking — for a
    /// render loop that also polls its own timers/vsync. Returns an empty,
    /// non-disconnected batch when nothing is pending and the sender is alive.
    pub fn try_next(&self) -> RenderBatch<S, W> {
        let mut inbox = self.channel.inbox.lock().unwrap();
        drain(&mut inbox)
    }

    /// The running count of scenes dropped by the latest-wins slot (replaced
    /// before the render thread took them) — a diagnostic for how far the
    /// render thread is falling behind the UI thread.
    pub fn dropped_frames(&self) -> u64 {
        self.channel.inbox.lock().unwrap().dropped
    }
}

/// Drain the inbox into a [`RenderBatch`]: all pending commands (FIFO), the
/// freshest scene (latest-wins), and the disconnection flag. Shared by
/// [`RenderReceiver::wait_next`]/[`RenderReceiver::try_next`].
///
/// When a scene comes out, the markers queued alongside it
/// ([`Inbox::pending_markers`]) are staged on the **calling** thread — the
/// render thread, which is about to render this scene and record the frame
/// that [`crate::perf::FrameStats::record`] will stamp them with. Staging
/// them on the caller is what keeps the attribution a thread property: the
/// only thread that can emit them is the one that took them. They are
/// staged rather than returned on the batch so [`RenderBatch`] keeps the
/// exact shape the shells destructure. When no scene comes out they stay
/// queued for the next one.
fn drain<S, W>(inbox: &mut Inbox<S, W>) -> RenderBatch<S, W> {
    #[cfg(feature = "perf-trace")]
    if inbox.latest.is_some() && !inbox.pending_markers.is_empty() {
        crate::perf::stage_markers(inbox.pending_markers.take());
    }
    RenderBatch {
        commands: std::mem::take(&mut inbox.commands),
        scene: inbox.latest.take(),
        disconnected: !inbox.sender_alive,
    }
}

// ---------------------------------------------------------------------
// Scene give-back: a non-blocking depth-1 return slot
// ---------------------------------------------------------------------

/// The render-thread handle to [`scene_return_channel`]: pushes a drained
/// scene back for the UI thread to reclaim (`Scene::reset` + reuse) instead
/// of a shell allocating a fresh one every frame — closing the buffer-reuse
/// gap a scene crossing [`render_channel`] would otherwise leave (a scene
/// with no way back, so every split `submit_frame` replaced it with
/// `Scene::new()`).
#[derive(Debug)]
pub struct SceneReturnSender<S> {
    slot: Arc<Mutex<Option<S>>>,
}

/// The UI-thread handle to [`scene_return_channel`]: polls (never blocks)
/// for a scene the render thread has finished with.
#[derive(Debug)]
pub struct SceneReturnReceiver<S> {
    slot: Arc<Mutex<Option<S>>>,
}

/// Create the render→UI scene give-back channel: a
/// non-blocking, depth-1 return slot — the reverse-direction, pull-based
/// counterpart to [`render_channel`]'s UI→render handoff. `Mutex<Option<S>>`
/// only, no [`Condvar`] and no new dependency: nothing should ever park
/// waiting on this slot, so there is no wait point to back — preserving this
/// module's no-`unsafe`, no-new-deps, generic-over-`S` charter (see the
/// module docs' Layering choice).
pub fn scene_return_channel<S>() -> (SceneReturnSender<S>, SceneReturnReceiver<S>) {
    let slot = Arc::new(Mutex::new(None));
    (
        SceneReturnSender { slot: slot.clone() },
        SceneReturnReceiver { slot },
    )
}

impl<S> SceneReturnSender<S> {
    /// Push a drained scene back for the UI thread to reclaim. Depth-1
    /// latest-wins, mirroring [`RenderSender::send_scene`]: an unpolled scene
    /// already in the slot is replaced (dropped) rather than queued — the UI
    /// thread only ever needs one spare, and an unbounded backlog here would
    /// just be a leak-shaped wait for a UI thread that has stopped polling.
    ///
    /// The render thread must call this for **every** [`SceneFrame`] it takes
    /// off a [`RenderReceiver`] — whether the scene is actually rendered or
    /// the frame is phase-gated out ([`RenderPhase::Paused`]/[`RenderPhase::NoSurface`]
    /// after a `Pause`/`SurfaceDestroyed`) — so a scene is never silently
    /// dropped instead of given back.
    pub fn give_back(&self, scene: S) {
        let mut slot = self.slot.lock().unwrap();
        *slot = Some(scene);
    }
}

impl<S> SceneReturnReceiver<S> {
    /// Non-blocking poll for a returned scene — `None` if the render thread
    /// hasn't given one back yet (cold start, or it is still busy on the
    /// current frame). Never blocks: a caller that finds nothing falls back
    /// to allocating a fresh scene (`Scene::new()`).
    pub fn try_recv(&self) -> Option<S> {
        self.slot.lock().unwrap().take()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};
    #[cfg(feature = "perf-trace")]
    use std::sync::mpsc;
    use std::thread;
    use std::time::{Duration, Instant};

    // -----------------------------------------------------------------
    // Kill switch (pure — the env-reading wrapper's cache-free counterpart,
    // mirroring frame_gate's kill_switch tests)
    // -----------------------------------------------------------------

    #[test]
    fn render_thread_kill_switch_off_when_neither_set() {
        assert!(!render_thread_kill_switch(None, None));
    }

    #[test]
    fn render_thread_kill_switch_on_when_compile_time_set_non_zero() {
        assert!(render_thread_kill_switch(Some("1"), None));
    }

    #[test]
    fn render_thread_kill_switch_on_when_runtime_set_non_zero() {
        assert!(render_thread_kill_switch(None, Some("1")));
    }

    #[test]
    fn render_thread_kill_switch_off_when_either_is_literal_zero_and_other_unset() {
        assert!(!render_thread_kill_switch(Some("0"), None));
        assert!(!render_thread_kill_switch(None, Some("0")));
    }

    #[test]
    fn render_thread_kill_switch_on_when_either_source_wins() {
        assert!(render_thread_kill_switch(Some("0"), Some("1")));
        assert!(render_thread_kill_switch(Some("1"), Some("0")));
    }

    #[test]
    fn render_thread_enabled_default_process_env_is_on() {
        // A normal test run sets neither the compile-time define nor the runtime
        // env, so the split is enabled by default (the kill switch is the
        // opt-out, mirroring frame_gate). This is the "kill-switch off path".
        assert!(render_thread_enabled());
    }

    // -----------------------------------------------------------------
    // RenderPhase transition table (modelled on frust-render's SurfacePhase)
    // -----------------------------------------------------------------

    const ALL_PHASES: [RenderPhase; 3] = [
        RenderPhase::NoSurface,
        RenderPhase::Active,
        RenderPhase::Paused,
    ];

    #[test]
    fn created_always_lands_in_active() {
        for phase in ALL_PHASES {
            assert_eq!(
                next_render_phase(phase, RenderEvent::SurfaceCreated),
                RenderPhase::Active,
                "creating (or recreating) a surface must reach Active from {phase:?}"
            );
        }
    }

    #[test]
    fn destroyed_always_lands_in_no_surface() {
        for phase in ALL_PHASES {
            assert_eq!(
                next_render_phase(phase, RenderEvent::SurfaceDestroyed),
                RenderPhase::NoSurface,
                "destroying a surface must reach NoSurface from {phase:?}"
            );
        }
    }

    #[test]
    fn changed_keeps_the_current_phase() {
        for phase in ALL_PHASES {
            assert_eq!(
                next_render_phase(phase, RenderEvent::SurfaceChanged),
                phase,
                "a resize must not change whether we can render, from {phase:?}"
            );
        }
    }

    #[test]
    fn pause_barriers_from_active_but_not_from_no_surface() {
        assert_eq!(
            next_render_phase(RenderPhase::Active, RenderEvent::Pause),
            RenderPhase::Paused
        );
        assert_eq!(
            next_render_phase(RenderPhase::Paused, RenderEvent::Pause),
            RenderPhase::Paused
        );
        // You cannot pause what was never created.
        assert_eq!(
            next_render_phase(RenderPhase::NoSurface, RenderEvent::Pause),
            RenderPhase::NoSurface
        );
    }

    #[test]
    fn resume_reactivates_unless_the_surface_is_gone() {
        assert_eq!(
            next_render_phase(RenderPhase::Paused, RenderEvent::Resume),
            RenderPhase::Active
        );
        assert_eq!(
            next_render_phase(RenderPhase::Active, RenderEvent::Resume),
            RenderPhase::Active
        );
        // Cannot resume onto a surface that is gone — must be recreated first.
        assert_eq!(
            next_render_phase(RenderPhase::NoSurface, RenderEvent::Resume),
            RenderPhase::NoSurface
        );
    }

    #[test]
    fn only_active_can_render() {
        assert!(RenderPhase::Active.can_render());
        assert!(!RenderPhase::NoSurface.can_render());
        assert!(!RenderPhase::Paused.can_render());
    }

    // -----------------------------------------------------------------
    // RenderCommand event/ack projections
    // -----------------------------------------------------------------

    #[test]
    fn command_event_projection_matches_each_variant() {
        // `()` for both the scene and window type params — a cheap host stand-in.
        let created: RenderCommand<()> = RenderCommand::SurfaceCreated {
            window: (),
            size: test_size(),
        };
        assert_eq!(created.event(), RenderEvent::SurfaceCreated);
        assert!(!created.requires_ack());

        let changed: RenderCommand<()> = RenderCommand::SurfaceChanged { size: test_size() };
        assert_eq!(changed.event(), RenderEvent::SurfaceChanged);
        assert!(!changed.requires_ack());

        let resume: RenderCommand<()> = RenderCommand::Resume;
        assert_eq!(resume.event(), RenderEvent::Resume);
        assert!(!resume.requires_ack());

        let (_w, ack) = ack_pair();
        let paused: RenderCommand<()> = RenderCommand::Pause { ack };
        assert_eq!(paused.event(), RenderEvent::Pause);
        assert!(paused.requires_ack());

        let (_w, ack) = ack_pair();
        let destroyed: RenderCommand<()> = RenderCommand::SurfaceDestroyed { ack };
        assert_eq!(destroyed.event(), RenderEvent::SurfaceDestroyed);
        assert!(destroyed.requires_ack());
    }

    // -----------------------------------------------------------------
    // Scene handoff: depth-1 latest-wins semantics
    // -----------------------------------------------------------------

    fn test_size() -> SurfaceSize {
        SurfaceSize {
            width: 1080,
            height: 1920,
            scale: 2.0,
        }
    }

    /// A scene frame carrying a `u32` scene id — a cheap host stand-in for a
    /// real `frust_scene::Scene`.
    fn frame(id: u32) -> SceneFrame<u32> {
        SceneFrame {
            scene: id,
            meta: FrameMeta {
                frame_time: FrameTime::from_nanos(u64::from(id)),
                size: test_size(),
                frame_id: u64::from(id),
            },
            ui_spans: UiSpans::default(),
        }
    }

    #[test]
    fn latest_wins_replaces_an_untaken_scene() {
        let (tx, rx) = render_channel::<u32, ()>();
        tx.send_scene(frame(1));
        tx.send_scene(frame(2));
        tx.send_scene(frame(3));

        // Only the freshest survives; the two older frames were dropped.
        let batch = rx.try_next();
        assert_eq!(batch.scene.expect("a scene is pending").scene, 3);
        assert_eq!(rx.dropped_frames(), 2, "two stale frames were replaced");

        // The slot is now empty.
        let batch = rx.try_next();
        assert!(batch.scene.is_none(), "the slot is drained after a take");
    }

    #[test]
    fn taking_between_sends_drops_nothing() {
        let (tx, rx) = render_channel::<u32, ()>();
        tx.send_scene(frame(1));
        assert_eq!(rx.try_next().scene.unwrap().scene, 1);
        tx.send_scene(frame(2));
        assert_eq!(rx.try_next().scene.unwrap().scene, 2);
        assert_eq!(
            rx.dropped_frames(),
            0,
            "each scene was taken before the next"
        );
    }

    #[test]
    fn send_scene_returns_none_when_the_slot_was_empty() {
        let (tx, _rx) = render_channel::<u32, ()>();
        assert!(
            tx.send_scene(frame(1)).is_none(),
            "the first send has nothing stale to hand back"
        );
    }

    #[test]
    fn send_scene_returns_the_overwritten_stale_frame() {
        // An untaken scene replaced by a newer send must be
        // handed back to the caller (to reclaim its buffer), not silently
        // dropped in the lock.
        let (tx, rx) = render_channel::<u32, ()>();
        assert!(tx.send_scene(frame(1)).is_none());
        let stale = tx
            .send_scene(frame(2))
            .expect("the untaken frame(1) must be returned");
        assert_eq!(stale.scene, 1, "the returned frame is the one replaced");

        // Latest-wins semantics are unchanged by the give-back: the freshest
        // scene is still what the render thread takes, and the drop counter
        // still increments exactly as before.
        let batch = rx.try_next();
        assert_eq!(batch.scene.expect("a scene is pending").scene, 2);
        assert_eq!(rx.dropped_frames(), 1);
    }

    #[test]
    fn send_scene_after_receiver_death_hands_the_frame_back() {
        // The dead-receiver path (see `Inbox::receiver_alive`) must not queue
        // the frame, but should still let the caller reclaim its buffer rather
        // than drop it on the floor.
        let (tx, rx) = render_channel::<u32, ()>();
        drop(rx);
        let returned = tx
            .send_scene(frame(1))
            .expect("a scene sent after receiver death must still be handed back");
        assert_eq!(returned.scene, 1);
    }

    // -----------------------------------------------------------------
    // Scene give-back channel: non-blocking depth-1
    // return slot, render thread -> UI thread.
    // -----------------------------------------------------------------

    #[test]
    fn scene_return_try_recv_is_none_before_any_give_back() {
        let (_tx, rx) = scene_return_channel::<u32>();
        assert!(rx.try_recv().is_none());
    }

    #[test]
    fn scene_return_round_trips_a_single_scene() {
        let (tx, rx) = scene_return_channel::<u32>();
        tx.give_back(7);
        assert_eq!(rx.try_recv(), Some(7), "the given-back scene is polled out");
        assert!(
            rx.try_recv().is_none(),
            "the slot is drained after a take, like the forward channel"
        );
    }

    #[test]
    fn scene_return_is_depth_1_latest_wins() {
        // Mirrors `render_channel`'s forward-slot semantics: a second give-back
        // before the UI thread polls replaces (not queues) the first.
        let (tx, rx) = scene_return_channel::<u32>();
        tx.give_back(1);
        tx.give_back(2);
        assert_eq!(
            rx.try_recv(),
            Some(2),
            "only the most recently given-back scene survives"
        );
    }

    #[test]
    fn scene_return_never_blocks_the_ui_thread() {
        // The whole point of the non-blocking design: polling an empty slot
        // returns immediately rather than parking, even with no render-thread
        // counterpart ever constructed to give one back.
        let (_tx, rx) = scene_return_channel::<u32>();
        let start = Instant::now();
        assert!(rx.try_recv().is_none());
        assert!(
            start.elapsed() < Duration::from_millis(50),
            "try_recv must return immediately, never park"
        );
    }

    #[test]
    fn wait_next_blocks_until_a_scene_arrives() {
        let (tx, rx) = render_channel::<u32, ()>();
        let handle = thread::spawn(move || rx.wait_next().scene.map(|f| f.scene));
        // Give the render thread a moment to park in wait_next, then hand it a
        // scene; the join proves it woke and took it.
        thread::sleep(Duration::from_millis(20));
        tx.send_scene(frame(7));
        assert_eq!(handle.join().unwrap(), Some(7));
    }

    // -----------------------------------------------------------------
    // Command ordering + disconnection
    // -----------------------------------------------------------------

    #[test]
    fn commands_drain_in_fifo_order_with_the_latest_scene() {
        let (tx, rx) = render_channel::<u32, ()>();
        tx.send_command(RenderCommand::SurfaceCreated {
            window: (),
            size: test_size(),
        });
        tx.send_scene(frame(1));
        tx.send_command(RenderCommand::SurfaceChanged { size: test_size() });
        tx.send_scene(frame(2)); // replaces frame(1)

        let batch = rx.try_next();
        let events: Vec<RenderEvent> = batch.commands.iter().map(RenderCommand::event).collect();
        assert_eq!(
            events,
            vec![RenderEvent::SurfaceCreated, RenderEvent::SurfaceChanged],
            "commands preserve FIFO order"
        );
        assert_eq!(
            batch.scene.unwrap().scene,
            2,
            "only the freshest scene rides along"
        );
        assert!(!batch.disconnected);
    }

    #[test]
    fn wait_next_wakes_and_reports_disconnection_when_sender_dropped() {
        let (tx, rx) = render_channel::<u32, ()>();
        let handle = thread::spawn(move || rx.wait_next().disconnected);
        thread::sleep(Duration::from_millis(20));
        drop(tx); // must wake the parked receiver
        assert!(
            handle.join().unwrap(),
            "dropping the sender wakes wait_next with a disconnection"
        );
    }

    #[test]
    fn pending_work_drains_before_disconnection_is_reported() {
        let (tx, rx) = render_channel::<u32, ()>();
        tx.send_scene(frame(5));
        drop(tx);
        // The buffered scene is still delivered; disconnected is also set so the
        // loop exits after handling it.
        let batch = rx.try_next();
        assert_eq!(batch.scene.unwrap().scene, 5);
        assert!(batch.disconnected);
    }

    // -----------------------------------------------------------------
    // Acknowledgment barrier (pause / destroy)
    // -----------------------------------------------------------------

    #[test]
    fn ack_unblocks_the_waiter_on_acknowledge() {
        let (waiter, ack) = ack_pair();
        assert!(!waiter.completed());
        ack.acknowledge();
        assert!(waiter.completed());
        waiter.wait(); // returns immediately
    }

    #[test]
    fn ack_unblocks_the_waiter_on_drop_as_a_safety_net() {
        let (waiter, ack) = ack_pair();
        drop(ack); // a render thread that returns early must not deadlock the UI
        assert!(waiter.completed());
    }

    #[test]
    fn pause_barrier_blocks_the_ui_thread_until_the_render_thread_quiesces() {
        // The plan's iOS backgrounding contract: the UI thread must not proceed
        // (let the app background) until the render thread has honored Pause.
        let (tx, rx) = render_channel::<u32, ()>();
        let quiesced = Arc::new(AtomicBool::new(false));
        let quiesced_render = quiesced.clone();

        let render = thread::spawn(move || {
            loop {
                let batch = rx.wait_next();
                for command in batch.commands {
                    if let RenderCommand::Pause { ack } = command {
                        // Simulate stopping submission *before* acknowledging.
                        thread::sleep(Duration::from_millis(30));
                        quiesced_render.store(true, Ordering::SeqCst);
                        ack.acknowledge();
                        return;
                    }
                }
                if batch.disconnected {
                    return;
                }
            }
        });

        let waiter = tx.pause();
        waiter.wait();
        // The barrier guarantees the render thread quiesced before wait returned.
        assert!(
            quiesced.load(Ordering::SeqCst),
            "the render thread must have quiesced before the UI thread proceeded"
        );
        render.join().unwrap();
    }

    #[test]
    fn destroy_surface_barrier_orders_resource_teardown_before_window_release() {
        // The plan's Android ANativeWindow-release contract: the UI thread must
        // not release the window until the render thread has dropped its
        // surface resources.
        let (tx, rx) = render_channel::<u32, ()>();
        let resources_dropped = Arc::new(AtomicBool::new(false));
        let resources_dropped_render = resources_dropped.clone();

        let render = thread::spawn(move || {
            loop {
                let batch = rx.wait_next();
                for command in batch.commands {
                    if let RenderCommand::SurfaceDestroyed { ack } = command {
                        thread::sleep(Duration::from_millis(30));
                        resources_dropped_render.store(true, Ordering::SeqCst);
                        ack.acknowledge();
                        return;
                    }
                }
                if batch.disconnected {
                    return;
                }
            }
        });

        let waiter = tx.destroy_surface();
        waiter.wait();
        assert!(
            resources_dropped.load(Ordering::SeqCst),
            "surface resources must be dropped before the UI thread releases the window"
        );
        render.join().unwrap();
    }

    #[test]
    fn a_leftover_scene_is_not_rendered_after_a_pause() {
        // The render loop gates on RenderPhase: a scene left in the slot when a
        // Pause is processed must be dropped, not submitted (the iOS
        // submit-after-background hazard). This exercises the phase-gating
        // composition the shells rely on.
        let (tx, rx) = render_channel::<u32, ()>();
        tx.send_scene(frame(1)); // a frame still in the slot...
        let _waiter = tx.pause(); // ...when a Pause arrives

        let mut phase = RenderPhase::Active;
        let mut submitted: Option<u32> = None;
        let batch = rx.try_next();
        for command in batch.commands {
            phase = next_render_phase(phase, command.event());
            if let RenderCommand::Pause { ack } = command {
                ack.acknowledge();
            }
        }
        if phase.can_render() {
            submitted = batch.scene.map(|f| f.scene);
        }
        assert_eq!(phase, RenderPhase::Paused);
        assert!(
            submitted.is_none(),
            "a leftover scene must not be submitted after a Pause"
        );
    }

    // -----------------------------------------------------------------
    // Receiver-liveness: a render thread that exits
    // before draining an ack-carrying command must never deadlock the UI
    // thread. Every assertion here is timeout-bounded so a *regression* FAILS
    // (the timeout expires, returning `false`) rather than hanging the suite.
    // -----------------------------------------------------------------

    /// A deadline generous enough that the correct path (the ack fires the
    /// instant the receiver drops) always beats it, yet finite so a regression
    /// fails the test instead of wedging the whole `cargo test` run.
    const REGRESSION_DEADLINE: Duration = Duration::from_secs(5);

    #[test]
    fn receiver_drop_drains_a_queued_orphaned_ack() {
        // The barrier command is queued while the receiver is still alive...
        let (tx, rx) = render_channel::<u32, ()>();
        let waiter = tx.pause();
        // ...then the render thread exits before draining it (drops its receiver).
        drop(rx);
        // The orphaned `Ack` must have fired via `RenderReceiver::drop`, so the
        // UI-side waiter unblocks rather than deadlocking.
        assert!(
            waiter.wait_timeout(REGRESSION_DEADLINE),
            "dropping the receiver must drain the queued Pause's Ack so the UI waiter unblocks"
        );
    }

    #[test]
    fn command_sent_after_receiver_death_fires_its_ack() {
        // The receiver is already gone before the barrier command is sent: the
        // sender must drop (not queue) it, still firing the embedded Ack.
        let (tx, rx) = render_channel::<u32, ()>();
        drop(rx);
        let waiter = tx.destroy_surface();
        assert!(
            waiter.wait_timeout(REGRESSION_DEADLINE),
            "an ack-carrying command sent after receiver death must fire its Ack safety net"
        );
    }

    #[test]
    fn receiver_death_mid_flight_unblocks_a_waiting_ui_thread() {
        // The closest reproduction of the live hazard: the UI thread is *already*
        // blocked on the barrier when the render thread dies. A background thread
        // sends the barrier and blocks on it (bounded); the main thread drops the
        // receiver a moment later, standing in for the render thread's exit.
        let (tx, rx) = render_channel::<u32, ()>();
        let (report_tx, report_rx) = std::sync::mpsc::channel();
        let ui = thread::spawn(move || {
            let honored = tx.destroy_surface().wait_timeout(REGRESSION_DEADLINE);
            report_tx.send(honored).unwrap();
        });
        thread::sleep(Duration::from_millis(20));
        drop(rx); // render thread exits without draining the command

        // The UI thread must have unblocked; a regression would leave it parked
        // until its own wait_timeout expired `false`.
        let honored = report_rx
            .recv_timeout(Duration::from_secs(10))
            .expect("the UI thread must report back, not stay deadlocked");
        assert!(
            honored,
            "receiver drop must unblock a UI thread already waiting on the barrier"
        );
        ui.join().unwrap();
    }

    #[test]
    fn a_scene_sent_after_receiver_death_is_dropped_not_queued() {
        // The scene half of the same contract: sending after the receiver is gone
        // must not stash a frame in a slot no one will take.
        let (tx, rx) = render_channel::<u32, ()>();
        drop(rx);
        tx.send_scene(frame(1)); // must be a no-op, not a panic or a leak
    }

    // -----------------------------------------------------------------
    // Bounded barrier waits (wait_timeout)
    // -----------------------------------------------------------------

    #[test]
    fn wait_timeout_returns_true_when_acknowledged() {
        let (waiter, ack) = ack_pair();
        ack.acknowledge();
        assert!(
            waiter.wait_timeout(REGRESSION_DEADLINE),
            "an acknowledged barrier must report honored"
        );
    }

    #[test]
    fn wait_timeout_expires_false_when_never_acknowledged() {
        // Hold the `Ack` for the whole call so it can never fire: the wait must
        // expire and report the timeout (the degrade-not-hang signal).
        let (waiter, _ack) = ack_pair();
        assert!(
            !waiter.wait_timeout(Duration::from_millis(20)),
            "wait_timeout must return false when the ack never fires"
        );
    }

    // ---------------------------------------------------------------
    // Scenario markers riding the handoff
    //
    // The channel is generic, so these drive `render_channel::<u32, ()>()`
    // with the same cheap stand-in payload every other test here uses — no
    // GPU, no platform, no real scene.
    //
    // Every test that asserts an attribution runs the UI leg on a REAL
    // second thread: the queues are per-thread now, so a single-threaded
    // simulation could not tell the split apart from the inline executor —
    // it would drain on the raising thread and pass no matter what the
    // channel did. Each thread that raises markers takes `perf`'s marker
    // test guard of its own (the force switch is per-thread too), and the
    // two threads step through a fixed interleaving with `lockstep_pair`
    // rather than racing.
    // ---------------------------------------------------------------

    /// A `FrameStats` in the shape a benchmark process runs: enabled, raw
    /// export on, small ring.
    #[cfg(feature = "perf-trace")]
    fn bench_stats() -> crate::perf::FrameStats {
        crate::perf::FrameStats::with_capacity_enabled_and_raw(8, true, true)
    }

    /// One recorded frame's worth of pass durations — the values are
    /// irrelevant here, only the recording is.
    #[cfg(feature = "perf-trace")]
    fn record_one(stats: &mut crate::perf::FrameStats) {
        stats.record(crate::perf::FramePasses::from_split(
            UiSpans::default(),
            crate::perf::RenderSpans::default(),
        ));
    }

    /// One end of the two-thread choreography these tests step through:
    /// [`Self::signal`] releases the peer's next [`Self::wait`].
    #[cfg(feature = "perf-trace")]
    struct Lockstep {
        to_peer: mpsc::Sender<()>,
        from_peer: mpsc::Receiver<()>,
    }

    #[cfg(feature = "perf-trace")]
    impl Lockstep {
        /// Let the peer proceed to its next step.
        fn signal(&self) {
            self.to_peer
                .send(())
                .expect("the peer thread must still be running");
        }

        /// Block until the peer reaches its matching `signal`. Deadlined so a
        /// broken interleaving fails this one test instead of hanging the
        /// whole run.
        fn wait(&self) {
            self.from_peer
                .recv_timeout(Duration::from_secs(5))
                .expect("the peer thread must reach its next step");
        }
    }

    /// The two ends of one choreography — hand one to each thread.
    #[cfg(feature = "perf-trace")]
    fn lockstep_pair() -> (Lockstep, Lockstep) {
        let (ui_tx, ui_rx) = mpsc::channel();
        let (render_tx, render_rx) = mpsc::channel();
        (
            Lockstep {
                to_peer: ui_tx,
                from_peer: render_rx,
            },
            Lockstep {
                to_peer: render_tx,
                from_peer: ui_rx,
            },
        )
    }

    #[cfg(feature = "perf-trace")]
    #[test]
    fn markers_land_on_the_frames_that_carried_them_across_the_split() {
        // The interleaving that motivated this whole route: the UI thread
        // raises BOTH edges of an S3 window before the render thread has
        // emitted a single line, so no frame number the UI side could have
        // guessed would have been right. `start` is raised in the build that
        // applies the op (frame 1), `end` in the build after it (frame 2) —
        // the harness window is the half-open [1, 2), i.e. exactly frame 1.
        let _guard = crate::perf::marker_test_guard(true);
        let (tx, rx) = render_channel::<u32, ()>();
        let mut stats = bench_stats();
        let (ui_step, render_step) = lockstep_pair();

        thread::scope(|scope| {
            scope.spawn(move || {
                let _ui_guard = crate::perf::marker_test_guard(true);
                // Build k: open the window and hand its scene off.
                crate::perf::mark_scenario_start("s3-create1k");
                tx.send_scene(frame(1));
                ui_step.signal();
                // The render thread has taken build k but has not recorded it
                // yet — the window where the UI thread runs ahead.
                ui_step.wait();
                // Build k+1: close the window and hand its scene off, still
                // before any raw line exists.
                crate::perf::mark_scenario_end("s3-create1k");
                tx.send_scene(frame(2));
                ui_step.signal();
            });

            render_step.wait();
            let batch1 = rx.try_next();
            assert!(batch1.scene.is_some(), "the render thread took build k");
            render_step.signal();
            render_step.wait();

            // Now the render thread catches up: frame 1, then frame 2.
            record_one(&mut stats);
            let batch2 = rx.try_next();
            assert!(batch2.scene.is_some(), "the render thread took build k+1");
            record_one(&mut stats);
        });

        assert_eq!(
            stats.marker_log(),
            [
                "bench-scenario-start n=1 s3-create1k",
                "bench-scenario-end n=2 s3-create1k",
            ],
            "each edge names the recorded frame that actually carried it"
        );
    }

    #[cfg(feature = "perf-trace")]
    #[test]
    fn a_window_whose_scene_is_replaced_collapses_onto_the_first_recorded_frame() {
        // Latest-wins: build k's scene is superseded before the render thread
        // takes it, so build k never becomes a frame of its own. Both edges
        // ride the frame that did draw that build's result — frame 1 — and
        // the half-open window [1, 1) is empty, which is the honest answer:
        // the op's own frame was dropped.
        let _guard = crate::perf::marker_test_guard(true);
        let (tx, rx) = render_channel::<u32, ()>();
        let mut stats = bench_stats();
        let (ui_step, render_step) = lockstep_pair();

        thread::scope(|scope| {
            scope.spawn(move || {
                let _ui_guard = crate::perf::marker_test_guard(true);
                crate::perf::mark_scenario_start("s3-update");
                tx.send_scene(frame(1));
                crate::perf::mark_scenario_end("s3-update");
                let stale = tx.send_scene(frame(2));
                assert!(stale.is_some(), "build k's scene was replaced, not taken");
                ui_step.signal();
            });

            render_step.wait();
            let batch = rx.try_next();
            assert_eq!(batch.scene.map(|f| f.scene), Some(2));
            record_one(&mut stats);
        });

        assert_eq!(
            stats.marker_log(),
            [
                "bench-scenario-start n=1 s3-update",
                "bench-scenario-end n=1 s3-update",
            ]
        );
        assert_eq!(rx.dropped_frames(), 1);
    }

    #[cfg(feature = "perf-trace")]
    #[test]
    fn a_marker_raised_after_the_handoff_never_lands_on_the_frame_in_flight() {
        // The former "record must not steal the queue" property, now a
        // property of the threads themselves: the marker is raised on the UI
        // thread AFTER build k crossed the channel and BEFORE the render
        // thread records frame 1, so it is sitting in the UI thread's own
        // queue while frame 1 is emitted. The render thread cannot reach that
        // queue at all, so frame 1 carries nothing and the marker rides
        // frame 2 — no flag, no ordering rule, just ownership.
        let _guard = crate::perf::marker_test_guard(true);
        let (tx, rx) = render_channel::<u32, ()>();
        let mut stats = bench_stats();
        let (ui_step, render_step) = lockstep_pair();

        thread::scope(|scope| {
            scope.spawn(move || {
                let _ui_guard = crate::perf::marker_test_guard(true);
                tx.send_scene(frame(1));
                ui_step.signal();

                ui_step.wait();
                crate::perf::mark_scenario_start("s3-update");
                ui_step.signal();

                ui_step.wait();
                tx.send_scene(frame(2));
                ui_step.signal();
            });

            render_step.wait();
            assert!(rx.try_next().scene.is_some(), "build k crossed");
            render_step.signal();

            render_step.wait();
            record_one(&mut stats);
            assert!(
                stats.marker_log().is_empty(),
                "a marker still queued on the UI thread cannot reach frame 1"
            );
            render_step.signal();

            render_step.wait();
            assert!(rx.try_next().scene.is_some(), "build k+1 crossed");
            record_one(&mut stats);
        });

        assert_eq!(stats.marker_log(), ["bench-scenario-start n=2 s3-update"]);
    }

    #[cfg(feature = "perf-trace")]
    #[test]
    fn markers_wait_in_the_inbox_until_a_scene_is_actually_taken() {
        // A drain that yields no scene must leave the inbox queue alone:
        // there is no frame for those markers to name yet. (A command-only
        // wakeup is exactly this case.)
        let _guard = crate::perf::marker_test_guard(true);
        let (tx, rx) = render_channel::<u32, ()>();
        let mut stats = bench_stats();
        let (ui_step, render_step) = lockstep_pair();

        thread::scope(|scope| {
            scope.spawn(move || {
                let _ui_guard = crate::perf::marker_test_guard(true);
                tx.send_scene(frame(1));
                ui_step.signal();

                ui_step.wait();
                crate::perf::mark_scenario_start("s3-swap");
                tx.send_command(RenderCommand::SurfaceChanged { size: test_size() });
                ui_step.signal();

                ui_step.wait();
                tx.send_scene(frame(2));
                ui_step.signal();
            });

            render_step.wait();
            assert!(rx.try_next().scene.is_some());
            record_one(&mut stats);
            assert!(stats.marker_log().is_empty(), "frame 1 carried no marker");
            render_step.signal();

            render_step.wait();
            let batch = rx.try_next();
            assert!(
                batch.scene.is_none(),
                "a command-only wakeup takes no scene"
            );
            record_one(&mut stats);
            assert!(
                stats.marker_log().is_empty(),
                "no scene was taken, so nothing may be attributed to frame 2"
            );
            render_step.signal();

            // The next real handoff carries it, onto frame 3.
            render_step.wait();
            assert!(rx.try_next().scene.is_some());
            record_one(&mut stats);
        });

        assert_eq!(stats.marker_log(), ["bench-scenario-start n=3 s3-swap"]);
    }

    #[cfg(feature = "perf-trace")]
    #[test]
    fn a_frame_carrying_no_marker_emits_no_marker_line() {
        let _guard = crate::perf::marker_test_guard(true);
        let (tx, rx) = render_channel::<u32, ()>();
        let mut stats = bench_stats();

        tx.send_scene(frame(1));
        assert!(rx.try_next().scene.is_some());
        record_one(&mut stats);

        assert!(stats.marker_log().is_empty());
        assert_eq!(
            stats.total_frames(),
            1,
            "the frame itself is still recorded"
        );
    }

    #[cfg(feature = "perf-trace")]
    #[test]
    fn receiver_death_discards_markers_no_frame_will_ever_name() {
        // Symmetric with the orphaned-ack drain in `Drop for RenderReceiver`:
        // the render thread is gone, so no frame will ever be recorded for
        // the markers riding its inbox. They are discarded there — and the
        // dead-receiver send drains the raising thread's own queue too, so a
        // marker raised post-mortem is neither attributed to a later channel
        // nor left accumulating on the UI thread forever.
        let _guard = crate::perf::marker_test_guard(true);
        let (tx, rx) = render_channel::<u32, ()>();
        let (next_tx, next_rx) = render_channel::<u32, ()>();
        let mut stats = bench_stats();
        let (ui_step, render_step) = lockstep_pair();

        thread::scope(|scope| {
            scope.spawn(move || {
                let _ui_guard = crate::perf::marker_test_guard(true);
                crate::perf::mark_scenario_start("s3-clear");
                tx.send_scene(frame(1));
                assert!(
                    crate::perf::take_pending_markers().is_empty(),
                    "send_scene moved the marker out of this thread's queue"
                );
                ui_step.signal();

                // The render thread has died; its inbox (marker included) is
                // gone with it.
                ui_step.wait();
                crate::perf::mark_scenario_end("s3-clear");
                assert!(
                    tx.send_scene(frame(2)).is_some(),
                    "a send to a dead receiver hands the frame straight back"
                );
                assert!(
                    crate::perf::take_pending_markers().is_empty(),
                    "the post-mortem marker was discarded, not left queued"
                );

                // A later channel in the same process must inherit nothing.
                next_tx.send_scene(frame(3));
                ui_step.signal();
            });

            render_step.wait();
            drop(rx);
            render_step.signal();

            render_step.wait();
            assert!(next_rx.try_next().scene.is_some());
            record_one(&mut stats);
        });

        assert!(
            stats.marker_log().is_empty(),
            "nothing leaked from the dead channel into the next one"
        );
    }

    #[cfg(feature = "perf-trace")]
    #[test]
    fn a_marker_raised_on_a_thread_that_hands_no_frame_off_is_never_emitted() {
        // The documented best-effort limit, asserted rather than assumed: a
        // worker thread that neither hands a frame across the channel nor
        // records one (the `spawn_blocking` shape) raises into its own queue,
        // which dies with it. Attaching it to a frame some other thread
        // produced would be exactly the cross-thread guess this route exists
        // to remove.
        let _guard = crate::perf::marker_test_guard(true);
        let (tx, rx) = render_channel::<u32, ()>();
        let mut stats = bench_stats();
        let (ui_step, render_step) = lockstep_pair();

        thread::scope(|scope| {
            scope.spawn(move || {
                let _ui_guard = crate::perf::marker_test_guard(true);
                // A third thread raises a window's opening edge and exits.
                thread::scope(|inner| {
                    inner.spawn(|| {
                        let _worker_guard = crate::perf::marker_test_guard(true);
                        crate::perf::mark_scenario_start("s4-parse");
                    });
                });
                // The frame-producing thread then hands off as usual.
                tx.send_scene(frame(1));
                ui_step.signal();
            });

            render_step.wait();
            assert!(rx.try_next().scene.is_some());
            record_one(&mut stats);
        });

        assert!(
            stats.marker_log().is_empty(),
            "the worker thread's marker belongs to no handed-off frame"
        );
    }

    #[cfg(feature = "perf-trace")]
    #[test]
    fn an_undrained_inbox_stops_growing_at_the_queue_cap() {
        // The inbox leg's bound: a render thread that has stopped taking
        // scenes must not let the UI thread's markers pile up without limit.
        // Two handoffs' worth arrive with no drain between them, so the
        // second pushes the inbox past its cap — the OLDEST edges go, and the
        // count comes out on its own line beside the frame that finally
        // carried the survivors.
        let _guard = crate::perf::marker_test_guard(true);
        let (tx, rx) = render_channel::<u32, ()>();
        let mut stats = bench_stats();
        let (ui_step, render_step) = lockstep_pair();

        let per_send = crate::perf::MARKER_QUEUE_CAP * 3 / 4;
        thread::scope(|scope| {
            scope.spawn(move || {
                let _ui_guard = crate::perf::marker_test_guard(true);
                for send in 0..2u32 {
                    for i in 0..per_send {
                        crate::perf::mark_scenario_start(&format!("s3-op{send}-{i}"));
                    }
                    tx.send_scene(frame(send + 1));
                }
                ui_step.signal();
            });

            render_step.wait();
            assert!(rx.try_next().scene.is_some());
            record_one(&mut stats);
        });

        let dropped = per_send * 2 - crate::perf::MARKER_QUEUE_CAP;
        let log = stats.marker_log();
        assert_eq!(
            log.len(),
            crate::perf::MARKER_QUEUE_CAP + 1,
            "a capped inbox's worth of markers, plus one overflow notice"
        );
        assert_eq!(
            log[0],
            format!("bench-scenario-start n=1 s3-op0-{dropped}"),
            "the oldest edges were the ones dropped"
        );
        assert_eq!(
            log[crate::perf::MARKER_QUEUE_CAP],
            format!("frust-perf marker-overflow n=1 dropped={dropped}")
        );
    }
}