cranpose-ui-graphics 0.1.84

Pure math/data for drawing & units in Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
//! Similarity verification over typed draw records.
//!
//! This is the record-level home of the math the wgpu flat-list replay
//! detector applies to materialized primitives: deriving a per-segment
//! similarity transform (uniform scale + rotation about a fixed center) from
//! an anchor pair, and verifying that a freshly recorded entry is the
//! retained entry moved by exactly that transform. Operating on
//! [`SolidArcRecord`]/[`SolidRoundRectRecord`] means the comparison sees the
//! RAW values the app drew with, before arc bands, tight bounds, or
//! `DrawPrimitive` construction — all of which a confirmed match makes
//! unnecessary.
//!
//! Records are solid-brush by construction, so the brush half of
//! verification collapses to a color comparison: geometry match + equal
//! color is [`RecordMatch::Exact`], geometry match + different color is
//! [`RecordMatch::Recolor`] (a retained buffer patch), anything else is
//! [`RecordMatch::Mismatch`] and must take the ordinary path in the same
//! frame. Tolerances are identical to the flat-list detector's; they cover
//! the game's own per-frame float noise, and a real content change is orders
//! of magnitude larger.

use crate::geometry::{
    CommandRecording, Point, RecordKind, Rect, SolidArcRecord, SolidRoundRectRecord, TapeRef,
};
use crate::{Color, CornerRadii};

/// Relative tolerance for similarity verification.
const REL_EPS: f32 = 2e-3;
/// Absolute tolerance for positions/angles near zero, logical px/radians.
const ABS_EPS: f32 = 2e-2;
/// How far apart two entries' implied per-frame transforms may sit while
/// still being grouped into one segment. Much tighter than verification:
/// entries of one ring share literally the same baked rotation step, while
/// neighboring rings differ by a speed delta that accumulates every frame.
const GROUP_SCALE_EPS: f32 = 1e-4;
const GROUP_ANGLE_EPS: f32 = 2e-4;

fn close_rel(a: f32, b: f32) -> bool {
    (a - b).abs() <= ABS_EPS + REL_EPS * a.abs().max(b.abs())
}

fn close_angle(a: f32, b: f32) -> bool {
    use std::f32::consts::TAU;
    let mut d = (a - b) % TAU;
    if d > TAU * 0.5 {
        d -= TAU;
    }
    if d < -TAU * 0.5 {
        d += TAU;
    }
    d.abs() <= ABS_EPS
}

fn close_point(a: Point, b: Point) -> bool {
    close_rel(a.x, b.x) && close_rel(a.y, b.y)
}

/// One segment's frame-over-frame motion: uniform scale and rotation about
/// a shared external center.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RecordTransform {
    pub scale: f32,
    pub angle: f32,
}

impl RecordTransform {
    pub const IDENTITY: Self = Self {
        scale: 1.0,
        angle: 0.0,
    };

    pub fn apply(&self, center: Point, p: Point) -> Point {
        let (sin, cos) = self.angle.sin_cos();
        let dx = p.x - center.x;
        let dy = p.y - center.y;
        Point::new(
            center.x + (dx * cos - dy * sin) * self.scale,
            center.y + (dx * sin + dy * cos) * self.scale,
        )
    }

    /// Axis-aligned bounds of `bounds` after the transform: the four
    /// transformed corners' box. This is the once-per-group bound transform
    /// that replaces per-entry tight-bounds recomputation for retained
    /// content.
    pub fn apply_to_bounds(&self, center: Point, bounds: Rect) -> Rect {
        let corners = [
            Point::new(bounds.x, bounds.y),
            Point::new(bounds.x + bounds.width, bounds.y),
            Point::new(bounds.x, bounds.y + bounds.height),
            Point::new(bounds.x + bounds.width, bounds.y + bounds.height),
        ];
        let mut min_x = f32::INFINITY;
        let mut min_y = f32::INFINITY;
        let mut max_x = f32::NEG_INFINITY;
        let mut max_y = f32::NEG_INFINITY;
        for corner in corners {
            let p = self.apply(center, corner);
            min_x = min_x.min(p.x);
            min_y = min_y.min(p.y);
            max_x = max_x.max(p.x);
            max_y = max_y.max(p.y);
        }
        Rect {
            x: min_x,
            y: min_y,
            width: max_x - min_x,
            height: max_y - min_y,
        }
    }
}

/// Whether an entry's own implied transform is tightly consistent with a
/// chain's anchor transform. `pinned` marks transforms whose angle is
/// meaningful — an on-pivot circle pins no rotation and joins any chain.
pub fn transforms_group(
    entry: RecordTransform,
    entry_pinned: bool,
    anchor: RecordTransform,
) -> bool {
    use std::f32::consts::TAU;
    if (entry.scale - anchor.scale).abs() > GROUP_SCALE_EPS * anchor.scale.abs().max(1.0) {
        return false;
    }
    if !entry_pinned {
        return true;
    }
    let mut d = (entry.angle - anchor.angle) % TAU;
    if d > TAU * 0.5 {
        d -= TAU;
    }
    if d < -TAU * 0.5 {
        d += TAU;
    }
    d.abs() <= GROUP_ANGLE_EPS
}

/// The result of verifying one incoming record against its retained
/// counterpart under a segment transform.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecordMatch {
    Exact,
    /// Geometry matched; only the solid color moved. Replayable with a
    /// 16-byte patch into the retained buffer.
    Recolor,
    Mismatch,
}

/// A circular round-rect (corner radius == half extent on every corner):
/// the one rect family that stays itself under rotation about an external
/// pivot. Returns `(center, diameter)`.
pub fn circle_view(record: &SolidRoundRectRecord) -> Option<(Point, f32)> {
    if !is_circle(record.rect, record.radii) {
        return None;
    }
    Some((
        Point::new(
            record.rect.x + record.rect.width * 0.5,
            record.rect.y + record.rect.height * 0.5,
        ),
        record.rect.width,
    ))
}

/// Whether corner radii + extents describe a circle.
pub fn is_circle(rect: Rect, radii: CornerRadii) -> bool {
    let half = rect.width * 0.5;
    close_rel(rect.width, rect.height)
        && close_rel(radii.top_left, half)
        && close_rel(radii.top_right, half)
        && close_rel(radii.bottom_right, half)
        && close_rel(radii.bottom_left, half)
}

fn stroke_width(record_stroke: Option<crate::Stroke>) -> Option<f32> {
    record_stroke.map(|stroke| stroke.width)
}

/// Similarity-invariant compatibility of a fresh arc with a retained one,
/// for re-locating a segment when dynamic spans change length. Colors are
/// deliberately excluded — a twinkling anchor must still re-anchor its
/// segment. A false positive costs a failed probe, never a wrong pixel.
pub fn arcs_anchor_compatible(current: &SolidArcRecord, anchor: &SolidArcRecord) -> bool {
    close_rel(current.sweep_angle, anchor.sweep_angle)
        && current.stroke.is_some() == anchor.stroke.is_some()
}

/// Derives the segment transform from an arc anchor pair. Arcs pin both
/// scale and rotation exactly.
pub fn arc_anchor_transform(
    current: &SolidArcRecord,
    retained: &SolidArcRecord,
) -> Option<RecordTransform> {
    if retained.radius <= f32::EPSILON {
        return None;
    }
    Some(RecordTransform {
        scale: current.radius / retained.radius,
        angle: current.start_angle - retained.start_angle,
    })
}

/// Derives the segment transform from a circle anchor pair, with its
/// pinnedness (an on-pivot circle pins no rotation).
pub fn circle_anchor_transform_pinned(
    current: (Point, f32),
    retained: (Point, f32),
    center: Point,
) -> Option<(RecordTransform, bool)> {
    let (c_now, d_now) = current;
    let (c_then, d_then) = retained;
    if d_then <= f32::EPSILON {
        return None;
    }
    let scale = d_now / d_then;
    let dx_then = c_then.x - center.x;
    let dy_then = c_then.y - center.y;
    let pinned = dx_then * dx_then + dy_then * dy_then > 1.0;
    let angle = if pinned {
        let dx_now = c_now.x - center.x;
        let dy_now = c_now.y - center.y;
        dy_now.atan2(dx_now) - dy_then.atan2(dx_then)
    } else {
        0.0
    };
    Some((RecordTransform { scale, angle }, pinned))
}

/// Verifies a fresh arc record against the retained one under `t`. Arc
/// centers must sit on the shared pivot — that is what makes rotation a
/// value change instead of a position change.
pub fn match_arc(
    current: &SolidArcRecord,
    retained: &SolidArcRecord,
    center: Point,
    t: RecordTransform,
) -> RecordMatch {
    let geometry_ok = close_point(current.center, retained.center)
        && close_point(current.center, center)
        && close_rel(current.radius, retained.radius * t.scale)
        && close_rel(current.inner_radius, retained.inner_radius * t.scale)
        && close_angle(current.start_angle, retained.start_angle + t.angle)
        && close_rel(current.sweep_angle, retained.sweep_angle)
        && match (stroke_width(current.stroke), stroke_width(retained.stroke)) {
            (None, None) => true,
            (Some(now), Some(then)) => close_rel(now, then * t.scale),
            _ => false,
        };
    if !geometry_ok {
        return RecordMatch::Mismatch;
    }
    if current.color == retained.color {
        RecordMatch::Exact
    } else {
        RecordMatch::Recolor
    }
}

/// Verifies a fresh circular round-rect against the retained one under `t`.
/// Non-circular round rects never match — they do not survive rotation
/// about an external pivot.
pub fn match_round_rect(
    current: &SolidRoundRectRecord,
    retained: &SolidRoundRectRecord,
    center: Point,
    t: RecordTransform,
) -> RecordMatch {
    let (Some((c_now, d_now)), Some((c_then, d_then))) =
        (circle_view(current), circle_view(retained))
    else {
        return RecordMatch::Mismatch;
    };
    let geometry_ok = close_point(c_now, t.apply(center, c_then))
        && close_rel(d_now, d_then * t.scale)
        && match (stroke_width(current.stroke), stroke_width(retained.stroke)) {
            (None, None) => true,
            (Some(now), Some(then)) => close_rel(now, then * t.scale),
            _ => false,
        };
    if !geometry_ok {
        return RecordMatch::Mismatch;
    }
    if current.color == retained.color {
        RecordMatch::Exact
    } else {
        RecordMatch::Recolor
    }
}

/// Below this many entries a stable stretch is not worth a retained group.
/// Mirrors the flat-list detector.
pub const MIN_SEGMENT_RECORDS: usize = 128;
/// Chains longer than this split into multiple groups, bounding the blast
/// radius of any one entry going dynamic later.
pub const MAX_SEGMENT_RECORDS: usize = 2048;
/// Below this many records a command is not worth watching at all.
pub const MIN_REPLAY_COMMAND_RECORDS: usize = 512;
/// Structural-resync search span when entity churn inserts/removes entries
/// between frames. Mirrors the flat-list detector's bounded resync.
const RESYNC_SPAN: usize = 48;
const MAX_RESYNC_EVENTS: usize = 512;
/// How far past its expected position a segment anchor may drift when the
/// dynamic spans between segments change length.
const RESYNC_WINDOW: usize = 1024;
/// Entries probed under a candidate anchor transform before committing to a
/// full-segment verification.
const ANCHOR_PROBE_RECORDS: usize = 4;
/// Full-span verifications a segment may commit to per frame. Self-similar
/// rings can pass the probe from a wrong anchor (every entry shares the
/// candidate's radius and angle step), so one failed commitment must not
/// abandon the search — but unbounded re-verification of 2048-entry spans
/// must not either.
const MAX_COMMIT_ATTEMPTS: usize = 4;
/// When live coverage sinks below this fraction of the retained records,
/// re-partition from scratch.
const MIN_COVERAGE_FRACTION: f32 = 0.5;
/// Coverage eroding this far below what the capture achieved re-partitions
/// to win dead ranges back — deaths are permanent otherwise, while the
/// content they covered usually stabilizes again a moment later.
const RECAPTURE_EROSION: f32 = 0.05;
/// Frames a capture must survive before erosion alone may retire it. Keeps
/// an inherently churning scene from recapturing in a loop — at worst one
/// two-frame recapture per cooldown.
const RECAPTURE_COOLDOWN_FRAMES: u32 = 180;

/// The similarity-checkable view of one tape entry: which typed store it
/// lives in and its index there. `None` marks entries replay cannot carry
/// (plain rects, ordinary primitives) — they break segments wherever they
/// sit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReplayView {
    Arc(usize),
    RoundRect(usize),
}

/// The replay-checkable view of tape entry `i`, decoded on the fly from the
/// tagged tape: `None` for entries replay cannot carry (plain rects,
/// ordinary primitives, non-circular round rects). This is THE eligibility
/// rule — both the `&CommandRecording` form and the [`TypedRecords`] form
/// delegate here, so they cannot drift.
fn view_at_slices(
    tape: &[TapeRef],
    round_rects: &[SolidRoundRectRecord],
    i: usize,
) -> Option<ReplayView> {
    let entry = tape[i];
    match entry.kind() {
        RecordKind::SolidArc => Some(ReplayView::Arc(entry.index())),
        // Non-circular round rects cannot survive rotation about an
        // external pivot; they stay dynamic.
        RecordKind::SolidRoundRect => circle_view(&round_rects[entry.index()])
            .is_some()
            .then_some(ReplayView::RoundRect(entry.index())),
        RecordKind::SolidRect | RecordKind::Other => None,
    }
}

/// [`view_at_slices`] over a whole recording.
fn view_at(recording: &CommandRecording, i: usize) -> Option<ReplayView> {
    view_at_slices(&recording.tape, &recording.round_rects, i)
}

/// The shared rotation/scale pivot of a recording: the first arc's center.
fn detect_center(recording: &CommandRecording) -> Option<Point> {
    recording.arcs.first().map(|arc| arc.center)
}

/// Similarity-invariant compatibility of a current entry with a retained
/// one, for structural pairing under churn. Colors excluded by design.
fn views_compatible(
    current: &CommandRecording,
    current_view: Option<ReplayView>,
    retained: &CommandRecording,
    retained_view: Option<ReplayView>,
) -> bool {
    match (current_view, retained_view) {
        (Some(ReplayView::Arc(i)), Some(ReplayView::Arc(j))) => {
            arcs_anchor_compatible(&current.arcs[i], &retained.arcs[j])
        }
        (Some(ReplayView::RoundRect(i)), Some(ReplayView::RoundRect(j))) => {
            let now = current.round_rects[i].stroke.is_some();
            let then = retained.round_rects[j].stroke.is_some();
            now == then
        }
        (None, None) => true,
        _ => false,
    }
}

/// Pairs current tape entries with retained tape entries, tolerating bounded
/// insertions and deletions (entity churn between frames). Pairing is
/// structural only; transform-consistency during verification decides
/// whether a pair actually moved together, so a wrong pairing costs a
/// segment, never a wrong capture.
fn align_recordings(current: &CommandRecording, retained: &CommandRecording) -> Vec<Option<usize>> {
    let pair = |i: usize, j: usize| -> bool {
        views_compatible(current, view_at(current, i), retained, view_at(retained, j))
    };
    let current_len = current.tape.len();
    let retained_len = retained.tape.len();
    let mut aligned = vec![None; current_len];
    let (mut i, mut j) = (0usize, 0usize);
    let mut events = 0usize;
    while i < current_len && j < retained_len {
        if pair(i, j) {
            aligned[i] = Some(j);
            i += 1;
            j += 1;
            continue;
        }
        events += 1;
        if events > MAX_RESYNC_EVENTS {
            // Not churn — the structure is gone. An empty alignment makes
            // the caller restart from a fresh snapshot.
            return vec![None; current_len];
        }
        let mut resynced = false;
        'search: for total in 1..=RESYNC_SPAN {
            for di in 0..=total {
                let dj = total - di;
                if i + di < current_len && j + dj < retained_len && pair(i + di, j + dj) {
                    i += di;
                    j += dj;
                    resynced = true;
                    break 'search;
                }
            }
        }
        if !resynced {
            i += 1;
            j += 1;
        }
    }
    aligned
}

/// Derives the pair's implied transform, with pinnedness.
fn pair_transform(
    current: &CommandRecording,
    current_view: ReplayView,
    retained: &CommandRecording,
    retained_view: ReplayView,
    center: Point,
) -> Option<(RecordTransform, bool)> {
    match (current_view, retained_view) {
        (ReplayView::Arc(i), ReplayView::Arc(j)) => {
            arc_anchor_transform(&current.arcs[i], &retained.arcs[j]).map(|t| (t, true))
        }
        (ReplayView::RoundRect(i), ReplayView::RoundRect(j)) => {
            let now = circle_view(&current.round_rects[i])?;
            let then = circle_view(&retained.round_rects[j])?;
            circle_anchor_transform_pinned(now, then, center)
        }
        _ => None,
    }
}

/// Verifies one aligned pair under a segment transform.
fn match_pair(
    current: &CommandRecording,
    current_view: ReplayView,
    retained: &CommandRecording,
    retained_view: ReplayView,
    center: Point,
    t: RecordTransform,
) -> RecordMatch {
    match (current_view, retained_view) {
        (ReplayView::Arc(i), ReplayView::Arc(j)) => {
            match_arc(&current.arcs[i], &retained.arcs[j], center, t)
        }
        (ReplayView::RoundRect(i), ReplayView::RoundRect(j)) => {
            match_round_rect(&current.round_rects[i], &retained.round_rects[j], center, t)
        }
        _ => RecordMatch::Mismatch,
    }
}

/// Loose logical bounds of a retained tape range: shapes bound by their full
/// outer circle. Visibility culling only needs containment.
fn range_bounds(recording: &CommandRecording, range: (usize, usize)) -> Rect {
    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;
    for view in (range.0..range.1).filter_map(|i| view_at(recording, i)) {
        let (center, reach) = match view {
            ReplayView::Arc(i) => {
                let arc = &recording.arcs[i];
                (
                    arc.center,
                    arc.radius + arc.stroke.map(|stroke| stroke.width).unwrap_or(0.0),
                )
            }
            ReplayView::RoundRect(i) => {
                let record = &recording.round_rects[i];
                let Some((center, diameter)) = circle_view(record) else {
                    continue;
                };
                (
                    center,
                    diameter * 0.5 + record.stroke.map(|stroke| stroke.width).unwrap_or(0.0),
                )
            }
        };
        let reach = reach + 2.0;
        min_x = min_x.min(center.x - reach);
        min_y = min_y.min(center.y - reach);
        max_x = max_x.max(center.x + reach);
        max_y = max_y.max(center.y + reach);
    }
    if min_x > max_x {
        return Rect {
            x: 0.0,
            y: 0.0,
            width: 0.0,
            height: 0.0,
        };
    }
    Rect {
        x: min_x,
        y: min_y,
        width: max_x - min_x,
        height: max_y - min_y,
    }
}

/// One retained stretch of a command's recording, addressed by the retained
/// snapshot's tape range. The `id` is stable for the segment's lifetime —
/// renderer-side retained slots key on it, and it survives other segments
/// dying.
#[derive(Clone, Debug, PartialEq)]
pub struct CommandSegment {
    /// The capture identity this segment's content lives under: renderer
    /// retained slots key on the (command, slot) pair. Slot ids are
    /// allocated at partition, whose emission carries the capture content;
    /// split pieces inherit the parent's slot and address into it, so a
    /// split never needs a recapture.
    pub slot: u32,
    /// This segment's first record within the slot's captured content.
    pub slot_offset: usize,
    pub tape_start: usize,
    pub tape_end: usize,
    /// Loose logical bounds at capture.
    pub bounds: Rect,
}

/// One span of this frame's recording, in tape order.
#[derive(Clone, Debug, PartialEq)]
pub enum ReplaySpan {
    /// The retained segment moved by `transform`; `recolors` are
    /// (span-relative record offset, new color) patches.
    Retained {
        /// The capture identity ([`CommandSegment::slot`]).
        slot: u32,
        /// True only on partition frames, where the snapshot IS the current
        /// frame: this span's records are the slot's capture content and
        /// `transform` is identity. Every later frame's transform is motion
        /// since exactly that content — never double-applied.
        capture: bool,
        /// The span's first record within the slot's captured content.
        slot_offset: usize,
        /// Where the span sits in the CURRENT frame's tape.
        tape_start: usize,
        tape_end: usize,
        transform: RecordTransform,
        recolors: Vec<(u32, Color)>,
        /// Segment capture bounds under this frame's transform.
        bounds: Rect,
    },
    /// Materialize these current-tape entries through the ordinary path.
    Dynamic { tape_start: usize, tape_end: usize },
}

/// What one frame of verification decided for a command.
#[derive(Debug, PartialEq)]
pub enum ReplayOutcome {
    /// No retention this frame: materialize the whole recording.
    AllDynamic,
    /// The interleaved retained/dynamic structure of this frame, in exact
    /// tape order.
    Spans(Vec<ReplaySpan>),
}

/// Fans independent verification bodies across worker threads. `run(i)` is
/// called exactly once for every `i in 0..jobs`, from any thread; the call
/// returns only after every job finished (jobs borrow the caller's stack).
/// The renderer wires its frame worker pool in through this seam so the
/// recorder crate stays free of threading machinery.
pub trait VerifyExecutor: Sync {
    fn for_each(&self, jobs: usize, run: &(dyn Fn(usize) + Sync));
}

/// A command's replay verdict translated into the space its consumers see:
/// spans address the run's materialized primitive vector, not the record
/// tape. This is what rides the render graph next to the primitives.
#[derive(Clone, Debug)]
pub struct CommandReplayFrame {
    /// The similarity pivot every span transform rotates and scales about.
    pub center: Point,
    /// Interleaved retained/dynamic structure in exact z order.
    pub spans: Vec<FrameSpan>,
    /// The frame-owned rematerialization source: the exact recording this
    /// frame's spans address, pinned for the frame's lifetime. A bypassed
    /// span (empty primitive range) that cannot draw retained materializes
    /// its `tape_range` from HERE — never from a sweepable ambient registry,
    /// whose contents may have moved on by render time. `None` only before
    /// the recording is published (the builder attaches the published
    /// handle) or on hand-built frames with nothing bypassed. Shared, not
    /// cloned: the handle pins the recording buffers; the depth-one frame
    /// packet will carry this same handle as an `Arc` when the graph goes
    /// `Send`.
    pub fallback: Option<std::rc::Rc<crate::geometry::CommandRecording>>,
}

impl PartialEq for CommandReplayFrame {
    fn eq(&self, other: &Self) -> bool {
        self.center == other.center
            && self.spans == other.spans
            && match (&self.fallback, &other.fallback) {
                (None, None) => true,
                (Some(a), Some(b)) => std::rc::Rc::ptr_eq(a, b),
                _ => false,
            }
    }
}

/// One primitive-space span of a [`CommandReplayFrame`].
#[derive(Clone, Debug, PartialEq)]
pub enum FrameSpan {
    Retained {
        /// The capture identity; renderer retained slots key on the
        /// (command, slot) pair.
        slot: u32,
        /// True only when `range` holds the slot's full capture content
        /// (partition frames, transform identity): retain it under the
        /// slot's identity.
        capture: bool,
        /// The span's first primitive within the slot's captured content.
        slot_offset: u32,
        /// The span's primitives in the run's primitive vector. EMPTY when
        /// the span was bypassed — its records were never materialized and
        /// the renderer draws it from the retained slot, or asks the
        /// recorder to materialize `tape_range` on demand when it cannot.
        range: (u32, u32),
        /// The span's records in the command's recording tape, for
        /// emergency rematerialization of a bypassed span.
        tape_range: (u32, u32),
        transform: RecordTransform,
        /// (span-relative primitive offset, new solid color) patches.
        recolors: Vec<(u32, Color)>,
        /// Capture bounds under this frame's transform.
        bounds: Rect,
    },
    Dynamic {
        /// Ordinary primitives in the run's primitive vector.
        range: (u32, u32),
    },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CommandReplayPhase {
    Idle,
    Snapshotted,
    Captured,
}

/// A pooled span job's result: the cleanly matched prefix length and the
/// recolors within it. One slot per segment, reused across frames — see
/// [`CommandReplayState::verify_results`].
#[derive(Debug, Default)]
struct SpanResultSlot {
    matched: usize,
    recolors: Vec<(u32, Color)>,
}

/// Per-command replay state: the retained snapshot (previous stable form of
/// the recording) and the segments carved out of it. This is the double
/// buffer sol's plan sanctions — previous and current forms coexist only
/// for comparison.
#[derive(Debug)]
pub struct CommandReplayState {
    phase: CommandReplayPhase,
    center: Point,
    snapshot: CommandRecording,
    segments: Vec<CommandSegment>,
    next_slot_id: u32,
    lifetime_deaths: u64,
    lifetime_splits: u64,
    /// Fraction of the tape the capture covered when it was taken. Dead
    /// segments never come back on their own, so coverage eroding well
    /// below this watermark means stable content sits unwatched — worth
    /// paying a recapture for.
    capture_coverage: f32,
    frames_since_capture: u32,
    /// Frames the pooled fast path fully committed — diagnostics for
    /// judging how often verification actually parallelizes.
    optimistic_commits: u64,
    /// Reusable per-job result slots for the pooled fast path — one slot
    /// per segment, grown once, recolor capacity retained across frames.
    /// The Mutex is uncontended (each job writes only its own slot once);
    /// what this kills is the per-frame allocation of the results vector,
    /// its mutexes, and every job's recolors vector. When the pass commits,
    /// each emitted span `mem::take`s its slot's recolors — the buffer
    /// walks into the graph and the slot re-grows next frame (accepted:
    /// emitting spans do real work); on a bail the buffers stay warm in
    /// their slots.
    verify_results: Vec<std::sync::Mutex<SpanResultSlot>>,
    /// The serial walk's recolor buffer, refilled by every `match_span`
    /// commit attempt. An emitted span `mem::take`s the contents and the
    /// scratch re-grows on the next attempt — same accepted emit-cost as
    /// the pooled slots.
    recolor_scratch: Vec<(u32, Color)>,
    /// The best-prefix recolors during the serial walk's candidate scan,
    /// swapped with `recolor_scratch` whenever a longer prefix turns up.
    best_recolor_scratch: Vec<(u32, Color)>,
    /// Serial-walk segment queues, persistent so their buffers keep their
    /// high-water capacity; refilled per verified frame.
    verify_pending: std::collections::VecDeque<CommandSegment>,
    verify_survivors: Vec<CommandSegment>,
}

impl Default for CommandReplayState {
    fn default() -> Self {
        Self {
            phase: CommandReplayPhase::Idle,
            center: Point::new(0.0, 0.0),
            snapshot: CommandRecording::default(),
            segments: Vec::new(),
            next_slot_id: 0,
            lifetime_deaths: 0,
            lifetime_splits: 0,
            capture_coverage: 0.0,
            frames_since_capture: 0,
            optimistic_commits: 0,
            verify_results: Vec::new(),
            recolor_scratch: Vec::new(),
            best_recolor_scratch: Vec::new(),
            verify_pending: std::collections::VecDeque::new(),
            verify_survivors: Vec::new(),
        }
    }
}

impl CommandReplayState {
    pub fn segments(&self) -> &[CommandSegment] {
        &self.segments
    }

    /// Lifetime (deaths, splits) across every verified frame — diagnostics
    /// for judging how churn interacts with retention.
    pub fn stats(&self) -> (u64, u64) {
        (self.lifetime_deaths, self.lifetime_splits)
    }

    /// Frames the pooled fast path fully committed (0 without an executor).
    pub fn optimistic_commits(&self) -> u64 {
        self.optimistic_commits
    }

    /// The similarity pivot all span transforms rotate and scale about.
    pub fn center(&self) -> Point {
        self.center
    }

    /// Advances the state machine with this frame's recording and returns
    /// what the frame can retain. Phases mirror the flat-list detector:
    /// snapshot on the first sighting, partition into
    /// transform-consistent chains on the second, verify per entry from the
    /// third on. A structural collapse or coverage erosion re-snapshots;
    /// correctness never depends on the detector being right about
    /// stability — a wrong guess costs a frame of ordinary rendering.
    pub fn advance(&mut self, current: &CommandRecording) -> ReplayOutcome {
        self.advance_pooled(current, None)
    }

    /// [`Self::advance`] with an optional executor that verification fans
    /// its per-segment span matching across. The pooled path is exercised
    /// only on frames where every segment commits cleanly at its first
    /// probe-passing anchor — any other frame falls back to the serial
    /// walk, so the outcome is identical with and without an executor.
    pub fn advance_pooled(
        &mut self,
        current: &CommandRecording,
        pool: Option<&dyn VerifyExecutor>,
    ) -> ReplayOutcome {
        if current.tape.len() < MIN_REPLAY_COMMAND_RECORDS {
            self.retire();
            return ReplayOutcome::AllDynamic;
        }
        let Some(center) = detect_center(current) else {
            self.retire();
            return ReplayOutcome::AllDynamic;
        };
        match self.phase {
            CommandReplayPhase::Idle => {
                self.take_snapshot(current, center);
                ReplayOutcome::AllDynamic
            }
            CommandReplayPhase::Snapshotted => self.partition(current, center),
            CommandReplayPhase::Captured => self.verify(current, pool),
        }
    }

    fn retire(&mut self) {
        self.phase = CommandReplayPhase::Idle;
        self.snapshot = CommandRecording::default();
        self.segments.clear();
    }

    fn take_snapshot(&mut self, current: &CommandRecording, center: Point) {
        self.snapshot = current.clone();
        self.center = center;
        self.segments.clear();
        self.phase = CommandReplayPhase::Snapshotted;
    }

    /// Splits the recording into maximal chains of consecutive entries that
    /// moved from the snapshot by one shared similarity transform, then
    /// re-snapshots at the current values so verification always compares
    /// against the capture frame. The returned spans carry the capture
    /// content itself (`capture: true`, identity transform): the snapshot
    /// IS this frame, so what the renderer retains equals what later
    /// transforms move.
    fn partition(&mut self, current: &CommandRecording, center: Point) -> ReplayOutcome {
        let aligned = align_recordings(current, &self.snapshot);
        let mut chains: Vec<(usize, usize)> = Vec::new();
        let mut i = 0;
        while i < current.tape.len() {
            let (Some(view), Some(snapshot_view)) = (
                view_at(current, i),
                aligned[i].and_then(|j| view_at(&self.snapshot, j)),
            ) else {
                i += 1;
                continue;
            };
            // A chain anchor must pin rotation itself.
            let Some((t, true)) =
                pair_transform(current, view, &self.snapshot, snapshot_view, self.center)
            else {
                i += 1;
                continue;
            };
            if match_pair(current, view, &self.snapshot, snapshot_view, self.center, t)
                == RecordMatch::Mismatch
            {
                i += 1;
                continue;
            }
            let start = i;
            let mut end = i + 1;
            while end < current.tape.len() {
                let (Some(view), Some(snapshot_view)) = (
                    view_at(current, end),
                    aligned[end].and_then(|j| view_at(&self.snapshot, j)),
                ) else {
                    break;
                };
                let Some((entry_t, pinned)) =
                    pair_transform(current, view, &self.snapshot, snapshot_view, self.center)
                else {
                    break;
                };
                if !transforms_group(entry_t, pinned, t) {
                    break;
                }
                if match_pair(current, view, &self.snapshot, snapshot_view, self.center, t)
                    == RecordMatch::Mismatch
                {
                    break;
                }
                end += 1;
            }
            if end - start >= MIN_SEGMENT_RECORDS {
                let mut piece_start = start;
                while piece_start < end {
                    let piece_end = (piece_start + MAX_SEGMENT_RECORDS).min(end);
                    if piece_end - piece_start >= MIN_SEGMENT_RECORDS {
                        chains.push((piece_start, piece_end));
                    }
                    piece_start = piece_end;
                }
            }
            i = end.max(i + 1);
        }

        if chains.is_empty() {
            self.take_snapshot(current, center);
            return ReplayOutcome::AllDynamic;
        }
        // Re-snapshot at current values: chain ranges are current-tape
        // ranges, which the fresh snapshot preserves verbatim.
        self.take_snapshot(current, center);
        self.segments = chains
            .into_iter()
            .map(|range| {
                let slot = self.next_slot_id;
                self.next_slot_id += 1;
                CommandSegment {
                    slot,
                    slot_offset: 0,
                    tape_start: range.0,
                    tape_end: range.1,
                    bounds: range_bounds(&self.snapshot, range),
                }
            })
            .collect();
        let covered: usize = self
            .segments
            .iter()
            .map(|segment| segment.tape_end - segment.tape_start)
            .sum();
        self.capture_coverage = covered as f32 / current.tape.len().max(1) as f32;
        self.frames_since_capture = 0;
        self.phase = CommandReplayPhase::Captured;

        let mut spans: Vec<ReplaySpan> = Vec::with_capacity(self.segments.len() * 2 + 1);
        let mut cursor = 0usize;
        for segment in &self.segments {
            if segment.tape_start > cursor {
                spans.push(ReplaySpan::Dynamic {
                    tape_start: cursor,
                    tape_end: segment.tape_start,
                });
            }
            spans.push(ReplaySpan::Retained {
                slot: segment.slot,
                capture: true,
                slot_offset: 0,
                tape_start: segment.tape_start,
                tape_end: segment.tape_end,
                transform: RecordTransform::IDENTITY,
                recolors: Vec::new(),
                bounds: segment.bounds,
            });
            cursor = segment.tape_end;
        }
        if cursor < current.tape.len() {
            spans.push(ReplaySpan::Dynamic {
                tape_start: cursor,
                tape_end: current.tape.len(),
            });
        }
        ReplayOutcome::Spans(spans)
    }

    /// Verifies this frame's recording against the capture. Each segment
    /// re-locates its anchor by searching forward from the cursor within
    /// [`RESYNC_WINDOW`] — dynamic spans between segments change length
    /// freely — probing a few entries under each candidate transform before
    /// committing to a full-span verification (a wrong candidate from a
    /// different ring fails the probe on its radii). A mismatch mid-span
    /// splits the segment: the matched prefix stays retained, the record
    /// that changed goes dynamic, and the suffix re-enters the location
    /// queue as its own segment — churn costs the records it touched, not
    /// the whole capture. Eroded coverage re-snapshots for the next frame.
    fn verify(
        &mut self,
        current: &CommandRecording,
        pool: Option<&dyn VerifyExecutor>,
    ) -> ReplayOutcome {
        if let Some(pool) = pool {
            if self.segments.len() >= 2 {
                if let Some((spans, retained_records)) = self.verify_optimistic(current, pool) {
                    self.optimistic_commits += 1;
                    return self.finish_verify(current, spans, retained_records);
                }
            }
        }
        let mut spans: Vec<ReplaySpan> = Vec::new();
        let mut retained_records = 0usize;
        // Current-tape position covered so far.
        let mut cursor = 0usize;
        // Segments awaiting location this frame, tape order. A split pushes
        // the suffix back onto the front so it is located before the next
        // original segment. Both queues are persistent fields refilled per
        // frame, so their buffers keep their high-water capacity.
        self.verify_pending.clear();
        self.verify_pending.extend(self.segments.drain(..));
        self.verify_survivors.clear();
        while let Some(segment) = self.verify_pending.pop_front() {
            let len = segment.tape_end - segment.tape_start;
            let search_end = (cursor + RESYNC_WINDOW)
                .min(current.tape.len().saturating_sub(len - 1))
                .max(cursor);
            // Candidates run LEFT TO RIGHT from the cursor, never by
            // proximity to an expected position: within a self-similar
            // ring, every pairing shifted right of the true anchor passes
            // probes (recolor-tolerant matching even repaints the color
            // pattern) with a sub-tolerance angle residual — the one
            // pairing a distance heuristic must never be allowed to reach
            // first. The true anchor is always the LEFTMOST compatible
            // candidate, exactly the order the flat detector proved out.
            let candidates = cursor..search_end;
            let mut located: Option<(usize, RecordTransform)> = None;
            // The longest cleanly matched prefix among failed commits:
            // (start, transform); its length and the recolors within it
            // live in `best_prefix_len` / `best_recolor_scratch`. A genuine
            // mid-span change surfaces here — the right anchor matches far
            // more than any mislocated one.
            let mut best_prefix: Option<(usize, RecordTransform)> = None;
            let mut best_prefix_len = 0usize;
            let mut attempts = 0usize;
            'search: for start in candidates {
                let Some(t) = probe_anchor(
                    current,
                    &self.snapshot,
                    self.center,
                    segment.tape_start,
                    len,
                    start,
                ) else {
                    continue;
                };
                // Committed: verify the whole span. A failure may still be a
                // mislocated anchor (self-similar rings), so the search
                // resumes — a bounded number of times.
                let matched = match_span(
                    TypedRecords::from(current),
                    TypedRecords::from(&self.snapshot),
                    self.center,
                    start,
                    segment.tape_start,
                    len,
                    t,
                    &mut self.recolor_scratch,
                );
                if matched < len {
                    if matched > best_prefix_len {
                        best_prefix_len = matched;
                        best_prefix = Some((start, t));
                        // Keep the best prefix's recolors without an
                        // allocation: the two scratches trade places.
                        std::mem::swap(&mut self.recolor_scratch, &mut self.best_recolor_scratch);
                    }
                    // Only failures with a substantial matched prefix
                    // consume the commit budget: those are genuine split
                    // candidates, and re-verifying long spans is the cost
                    // being bounded. A short-prefix failure is just a wrong
                    // anchor (a dead predecessor's entries, a cross-ring
                    // pairing) that the scan must be free to step past —
                    // charging those burned the budget before the true
                    // anchor and killed healthy segments.
                    if matched >= MIN_SEGMENT_RECORDS {
                        attempts += 1;
                        if attempts >= MAX_COMMIT_ATTEMPTS {
                            break 'search;
                        }
                    }
                    continue;
                }
                located = Some((start, t));
                break;
            }
            // A failed segment splits around the record that changed: the
            // matched prefix is retained now, the suffix re-enters the
            // queue to locate itself past whatever churn displaced it. Only
            // a prefix long enough to prove the anchor was right earns a
            // split — a segment with no solid prefix dies whole, or a weak
            // wrong-anchor prefix would shed one record and re-fail across
            // the whole span. The emitted span `mem::take`s its recolors
            // out of the owning scratch — the buffer walks into the graph
            // and the scratch re-grows on the next attempt (accepted:
            // emitting spans do real work).
            let (span_start, t, recolors, span_len) = match located {
                Some((start, t)) => (start, t, std::mem::take(&mut self.recolor_scratch), len),
                None => {
                    let split = best_prefix_len >= MIN_SEGMENT_RECORDS;
                    let Some((start, t)) = best_prefix.filter(|_| split) else {
                        self.lifetime_deaths += 1;
                        continue;
                    };
                    let suffix_start = segment.tape_start + best_prefix_len + 1;
                    if segment.tape_end > suffix_start
                        && segment.tape_end - suffix_start >= MIN_SEGMENT_RECORDS
                    {
                        // The suffix addresses the SAME captured content,
                        // just deeper in: no recapture, only an offset.
                        self.verify_pending.push_front(CommandSegment {
                            slot: segment.slot,
                            slot_offset: segment.slot_offset + (suffix_start - segment.tape_start),
                            tape_start: suffix_start,
                            tape_end: segment.tape_end,
                            bounds: range_bounds(&self.snapshot, (suffix_start, segment.tape_end)),
                        });
                    }
                    self.lifetime_splits += 1;
                    (
                        start,
                        t,
                        std::mem::take(&mut self.best_recolor_scratch),
                        best_prefix_len,
                    )
                }
            };
            let survivor = if span_len == len {
                segment
            } else {
                // The prefix keeps its capture identity — it addresses the
                // same slot content from the same offset, just shorter.
                CommandSegment {
                    slot: segment.slot,
                    slot_offset: segment.slot_offset,
                    tape_start: segment.tape_start,
                    tape_end: segment.tape_start + span_len,
                    bounds: range_bounds(
                        &self.snapshot,
                        (segment.tape_start, segment.tape_start + span_len),
                    ),
                }
            };
            if span_start > cursor {
                spans.push(ReplaySpan::Dynamic {
                    tape_start: cursor,
                    tape_end: span_start,
                });
            }
            retained_records += span_len;
            spans.push(ReplaySpan::Retained {
                slot: survivor.slot,
                capture: false,
                slot_offset: survivor.slot_offset,
                tape_start: span_start,
                tape_end: span_start + span_len,
                transform: t,
                recolors,
                bounds: t.apply_to_bounds(self.center, survivor.bounds),
            });
            cursor = span_start + span_len;
            self.verify_survivors.push(survivor);
        }
        if cursor < current.tape.len() {
            spans.push(ReplaySpan::Dynamic {
                tape_start: cursor,
                tape_end: current.tape.len(),
            });
        }

        // Survivors become the live table; swapping (the table was drained
        // above) lets the two buffers ping-pong, both keeping capacity.
        std::mem::swap(&mut self.segments, &mut self.verify_survivors);
        self.finish_verify(current, spans, retained_records)
    }

    /// The verification epilogue shared by the serial and pooled paths:
    /// coverage bookkeeping and the collapse/erosion re-snapshot decision.
    fn finish_verify(
        &mut self,
        current: &CommandRecording,
        spans: Vec<ReplaySpan>,
        retained_records: usize,
    ) -> ReplayOutcome {
        self.frames_since_capture += 1;
        let retained_total: usize = self
            .segments
            .iter()
            .map(|segment| segment.tape_end - segment.tape_start)
            .sum();
        let coverage = retained_total as f32 / current.tape.len().max(1) as f32;
        let collapsed = retained_records == 0 || coverage < MIN_COVERAGE_FRACTION;
        let eroded = coverage + RECAPTURE_EROSION < self.capture_coverage
            && self.frames_since_capture >= RECAPTURE_COOLDOWN_FRAMES;
        if collapsed || eroded {
            // Re-snapshot so the next two frames re-partition. Collapse pays
            // immediately; mere erosion waits out the capture cooldown.
            let center = self.center;
            self.take_snapshot(current, center);
            if retained_records == 0 {
                return ReplayOutcome::AllDynamic;
            }
        }
        ReplayOutcome::Spans(spans)
    }

    /// The clean-frame fast path: locates every segment serially with cheap
    /// probes only (identical candidate order to the serial walk), then fans
    /// the expensive full-span matching across `pool`. Returns `None` — and
    /// changes nothing but its private result scratch — the moment any
    /// segment lacks a probe-passing candidate
    /// or any span fails to match whole, leaving the serial walk
    /// to redo the frame with its split/death/attempt machinery. When it
    /// does return spans, they are exactly what the serial walk would have
    /// produced: a fully matching first probe-passing candidate is the
    /// leftmost committing candidate.
    fn verify_optimistic(
        &mut self,
        current: &CommandRecording,
        pool: &dyn VerifyExecutor,
    ) -> Option<(Vec<ReplaySpan>, usize)> {
        struct SpanJob {
            start: usize,
            seg_start: usize,
            len: usize,
            t: RecordTransform,
        }
        let mut jobs: Vec<SpanJob> = Vec::with_capacity(self.segments.len());
        let mut cursor = 0usize;
        for segment in &self.segments {
            let len = segment.tape_end - segment.tape_start;
            let search_end = (cursor + RESYNC_WINDOW)
                .min(current.tape.len().saturating_sub(len - 1))
                .max(cursor);
            let mut found = None;
            for start in cursor..search_end {
                if let Some(t) = probe_anchor(
                    current,
                    &self.snapshot,
                    self.center,
                    segment.tape_start,
                    len,
                    start,
                ) {
                    found = Some((start, t));
                    break;
                }
            }
            let (start, t) = found?;
            jobs.push(SpanJob {
                start,
                seg_start: segment.tape_start,
                len,
                t,
            });
            cursor = start + len;
        }
        // One reusable result slot per job, grown once and kept across
        // frames; every job writes only its own slot, filling the slot's
        // own recolor buffer in place via the out-param.
        if self.verify_results.len() < jobs.len() {
            self.verify_results
                .resize_with(jobs.len(), Default::default);
        }
        {
            let current = TypedRecords::from(current);
            let snapshot = TypedRecords::from(&self.snapshot);
            let center = self.center;
            let jobs = &jobs;
            let results = &self.verify_results;
            pool.for_each(jobs.len(), &|i| {
                let job = &jobs[i];
                let mut guard = results[i].lock().expect("verify span job lock");
                let slot = &mut *guard;
                slot.matched = match_span(
                    current,
                    snapshot,
                    center,
                    job.start,
                    job.seg_start,
                    job.len,
                    job.t,
                    &mut slot.recolors,
                );
            });
        }
        // Bail before taking anything: a single short match leaves every
        // slot's recolor buffer warm for the serial rerun and later frames.
        for (job, result) in jobs.iter().zip(&self.verify_results) {
            if result.lock().expect("verify span job lock").matched < job.len {
                return None;
            }
        }
        let mut spans: Vec<ReplaySpan> = Vec::with_capacity(jobs.len() * 2 + 1);
        let mut retained_records = 0usize;
        let mut cursor = 0usize;
        for (segment, (job, result)) in self
            .segments
            .iter()
            .zip(jobs.iter().zip(&self.verify_results))
        {
            // Committing: each emitted span takes its slot's buffer — the
            // capacity walks into the graph and the slot re-grows next
            // frame (accepted: emitting spans do real work).
            let recolors =
                std::mem::take(&mut result.lock().expect("verify span job lock").recolors);
            if job.start > cursor {
                spans.push(ReplaySpan::Dynamic {
                    tape_start: cursor,
                    tape_end: job.start,
                });
            }
            retained_records += job.len;
            spans.push(ReplaySpan::Retained {
                slot: segment.slot,
                capture: false,
                slot_offset: segment.slot_offset,
                tape_start: job.start,
                tape_end: job.start + job.len,
                transform: job.t,
                recolors,
                bounds: job.t.apply_to_bounds(self.center, segment.bounds),
            });
            cursor = job.start + job.len;
        }
        if cursor < current.tape.len() {
            spans.push(ReplaySpan::Dynamic {
                tape_start: cursor,
                tape_end: current.tape.len(),
            });
        }
        Some((spans, retained_records))
    }
}

/// The cheap anchor test shared by the serial walk and the pooled fast
/// path: view compatibility, transform derivation from the anchor pair, and
/// [`ANCHOR_PROBE_RECORDS`] probe matches. `None` means this candidate
/// cannot be the segment's anchor.
fn probe_anchor(
    current: &CommandRecording,
    snapshot: &CommandRecording,
    center: Point,
    seg_start: usize,
    len: usize,
    start: usize,
) -> Option<RecordTransform> {
    let (Some(view), Some(snapshot_view)) = (view_at(current, start), view_at(snapshot, seg_start))
    else {
        return None;
    };
    if !views_compatible(current, Some(view), snapshot, Some(snapshot_view)) {
        return None;
    }
    let (t, _) = pair_transform(current, view, snapshot, snapshot_view, center)?;
    for probe in 0..ANCHOR_PROBE_RECORDS.min(len) {
        let (Some(view), Some(snapshot_view)) = (
            view_at(current, start + probe),
            view_at(snapshot, seg_start + probe),
        ) else {
            return None;
        };
        if match_pair(current, view, snapshot, snapshot_view, center, t) == RecordMatch::Mismatch {
            return None;
        }
    }
    Some(t)
}

/// The typed-record arrays a span match reads — the POD slice view of a
/// [`CommandRecording`] that is `Sync` (the recording itself is not: its
/// `others` vector may hold `Rc`-carrying primitives), which is what lets
/// [`match_span`] calls cross worker threads.
#[derive(Clone, Copy)]
struct TypedRecords<'a> {
    tape: &'a [TapeRef],
    arcs: &'a [SolidArcRecord],
    round_rects: &'a [SolidRoundRectRecord],
}

impl<'a> From<&'a CommandRecording> for TypedRecords<'a> {
    fn from(recording: &'a CommandRecording) -> Self {
        Self {
            tape: &recording.tape,
            arcs: &recording.arcs,
            round_rects: &recording.round_rects,
        }
    }
}

impl TypedRecords<'_> {
    /// [`view_at`] over the POD slices, for worker-thread span matching —
    /// the same [`view_at_slices`] implementation, so eligibility cannot
    /// drift between the two forms.
    fn view_at(&self, i: usize) -> Option<ReplayView> {
        view_at_slices(self.tape, self.round_rects, i)
    }
}

/// The full-span commit body: matches `len` records of `current` from
/// `start` against the snapshot span at `seg_start` under `t`. Fills
/// `recolors` (cleared at entry) with the recolors inside the cleanly
/// matched prefix and returns that prefix's length — the out-param lets
/// callers own reusable buffers instead of allocating per call. The
/// record dispatch mirrors [`match_pair`] exactly; it operates on the typed
/// slices so one call per segment can run on a worker thread.
#[allow(clippy::too_many_arguments)]
fn match_span(
    current: TypedRecords<'_>,
    snapshot: TypedRecords<'_>,
    center: Point,
    start: usize,
    seg_start: usize,
    len: usize,
    t: RecordTransform,
    recolors: &mut Vec<(u32, Color)>,
) -> usize {
    recolors.clear();
    for offset in 0..len {
        let entry_match = match (
            current.view_at(start + offset),
            snapshot.view_at(seg_start + offset),
        ) {
            (Some(ReplayView::Arc(i)), Some(ReplayView::Arc(j))) => {
                match_arc(&current.arcs[i], &snapshot.arcs[j], center, t)
            }
            (Some(ReplayView::RoundRect(i)), Some(ReplayView::RoundRect(j))) => {
                match_round_rect(&current.round_rects[i], &snapshot.round_rects[j], center, t)
            }
            _ => RecordMatch::Mismatch,
        };
        match entry_match {
            RecordMatch::Exact => {}
            RecordMatch::Recolor => {
                let color = match current.view_at(start + offset) {
                    Some(ReplayView::Arc(a)) => current.arcs[a].color,
                    Some(ReplayView::RoundRect(r)) => current.round_rects[r].color,
                    None => unreachable!("recolor requires a view"),
                };
                recolors.push((offset as u32, color));
            }
            RecordMatch::Mismatch => return offset,
        }
    }
    len
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Color, Stroke};

    const CENTER: Point = Point { x: 204.0, y: 204.0 };

    fn arc(radius: f32, start: f32, color: Color) -> SolidArcRecord {
        SolidArcRecord {
            center: CENTER,
            radius,
            start_angle: start,
            sweep_angle: 0.4,
            inner_radius: radius * 0.8,
            color,
            stroke: None,
        }
    }

    fn moved_arc(base: &SolidArcRecord, t: RecordTransform) -> SolidArcRecord {
        SolidArcRecord {
            center: base.center,
            radius: base.radius * t.scale,
            start_angle: base.start_angle + t.angle,
            sweep_angle: base.sweep_angle,
            inner_radius: base.inner_radius * t.scale,
            color: base.color,
            stroke: base.stroke.map(|stroke| Stroke {
                width: stroke.width * t.scale,
                ..stroke
            }),
        }
    }

    fn circle(cx: f32, cy: f32, diameter: f32, color: Color) -> SolidRoundRectRecord {
        SolidRoundRectRecord {
            rect: Rect {
                x: cx - diameter * 0.5,
                y: cy - diameter * 0.5,
                width: diameter,
                height: diameter,
            },
            radii: CornerRadii::uniform(diameter * 0.5),
            color,
            stroke: None,
        }
    }

    #[test]
    fn arc_anchor_recovers_the_baked_transform() {
        let t = RecordTransform {
            scale: 0.9994,
            angle: 0.0123,
        };
        let retained = arc(120.0, 1.0, Color::WHITE);
        let current = moved_arc(&retained, t);
        let derived = arc_anchor_transform(&current, &retained).expect("derivable");
        assert!((derived.scale - t.scale).abs() < 1e-6);
        assert!((derived.angle - t.angle).abs() < 1e-6);
        assert_eq!(
            match_arc(&current, &retained, CENTER, derived),
            RecordMatch::Exact
        );
    }

    #[test]
    fn recolored_arc_matches_as_recolor() {
        let t = RecordTransform {
            scale: 1.0,
            angle: 0.05,
        };
        let retained = arc(80.0, 0.2, Color::WHITE);
        let mut current = moved_arc(&retained, t);
        current.color = Color::rgb(0.5, 0.1, 0.9);
        assert_eq!(
            match_arc(&current, &retained, CENTER, t),
            RecordMatch::Recolor
        );
    }

    #[test]
    fn changed_sweep_is_a_mismatch() {
        let t = RecordTransform::IDENTITY;
        let retained = arc(80.0, 0.2, Color::WHITE);
        let mut current = retained;
        current.sweep_angle += 0.1;
        assert_eq!(
            match_arc(&current, &retained, CENTER, t),
            RecordMatch::Mismatch
        );
    }

    #[test]
    fn stroked_arc_scales_its_width_with_the_segment() {
        let t = RecordTransform {
            scale: 0.98,
            angle: 0.0,
        };
        let mut retained = arc(60.0, 0.0, Color::WHITE);
        retained.stroke = Some(Stroke::new(5.0));
        let current = moved_arc(&retained, t);
        assert_eq!(
            match_arc(&current, &retained, CENTER, t),
            RecordMatch::Exact
        );

        // An unscaled stroke under a scaling segment is a real change: 2%
        // of 5px is well past the noise tolerance.
        let mut stale = current;
        stale.stroke = Some(Stroke::new(5.0));
        assert_eq!(
            match_arc(&stale, &retained, CENTER, t),
            RecordMatch::Mismatch
        );
    }

    #[test]
    fn orbiting_circle_matches_under_rotation() {
        let t = RecordTransform {
            scale: 1.0,
            angle: 0.3,
        };
        let retained = circle(304.0, 204.0, 10.0, Color::WHITE);
        let (c_then, d_then) = circle_view(&retained).expect("circle");
        let c_now = t.apply(CENTER, c_then);
        let current = circle(c_now.x, c_now.y, d_then * t.scale, Color::WHITE);
        let (derived, pinned) = circle_anchor_transform_pinned(
            circle_view(&current).unwrap(),
            (c_then, d_then),
            CENTER,
        )
        .expect("derivable");
        assert!(pinned, "an off-pivot circle pins rotation");
        assert!((derived.angle - t.angle).abs() < 1e-4);
        assert_eq!(
            match_round_rect(&current, &retained, CENTER, derived),
            RecordMatch::Exact
        );
    }

    #[test]
    fn non_circular_round_rect_never_matches() {
        let mut retained = circle(304.0, 204.0, 10.0, Color::WHITE);
        retained.rect.width = 14.0; // no longer a circle
        assert_eq!(
            match_round_rect(&retained, &retained, CENTER, RecordTransform::IDENTITY),
            RecordMatch::Mismatch
        );
    }

    #[test]
    fn grouping_is_tighter_than_verification() {
        let anchor = RecordTransform {
            scale: 1.0,
            angle: 0.010,
        };
        let same_ring = RecordTransform {
            scale: 1.0,
            angle: 0.0100001,
        };
        let next_ring = RecordTransform {
            scale: 1.0,
            angle: 0.011,
        };
        assert!(transforms_group(same_ring, true, anchor));
        assert!(
            !transforms_group(next_ring, true, anchor),
            "a 1e-3 rotation-step difference is another ring, not float noise"
        );
        let unpinned = RecordTransform {
            scale: 1.0,
            angle: 0.0,
        };
        assert!(transforms_group(unpinned, false, anchor));
    }

    use crate::geometry::{DrawScopeDefault, Size};
    use crate::{Brush, DrawScope as _};

    /// Records one MEGA-shaped frame: `rings` rings of `per_ring` arcs, each
    /// ring rotated by its own step × `frame`, breathing scale applied to
    /// every radius, plus `tail` dynamic circles whose count varies.
    fn ring_frame(rings: usize, per_ring: usize, frame: usize, tail: usize) -> CommandRecording {
        let mut scope = DrawScopeDefault::new(Size::new(408.0, 408.0));
        let scale = 0.9994f32.powi(frame as i32);
        for ring in 0..rings {
            let step = 0.01 + ring as f32 * 0.005;
            let rotation = step * frame as f32;
            let radius = (60.0 + ring as f32 * 30.0) * scale;
            for slot in 0..per_ring {
                let start = slot as f32 * (std::f32::consts::TAU / per_ring as f32) + rotation;
                scope.draw_annular_sector(
                    Brush::solid(Color::WHITE),
                    CENTER,
                    radius * 0.8,
                    radius,
                    start,
                    0.02,
                );
            }
        }
        for i in 0..tail {
            // Dynamic entities: different positions every frame.
            let x = 40.0 + (frame * 17 + i * 31) as f32 % 300.0;
            scope.draw_circle(Brush::solid(Color::RED), Point::new(x, 50.0), 3.0);
        }
        scope.recorded().clone()
    }

    #[test]
    fn ring_scene_reaches_retention_by_the_third_frame() {
        let mut state = CommandReplayState::default();
        assert!(matches!(
            state.advance(&ring_frame(3, 300, 0, 10)),
            ReplayOutcome::AllDynamic
        ));
        // The partition frame itself emits the capture: snapshot == current,
        // so every span is capture:true under an identity transform.
        let ReplayOutcome::Spans(capture_spans) = state.advance(&ring_frame(3, 300, 1, 10)) else {
            panic!("partition frame should emit the capture");
        };
        assert!(capture_spans.iter().all(|span| match span {
            ReplaySpan::Retained {
                capture, transform, ..
            } => *capture && *transform == RecordTransform::IDENTITY,
            ReplaySpan::Dynamic { .. } => true,
        }));
        assert!(!state.segments().is_empty(), "partition found the rings");

        let ReplayOutcome::Spans(spans) = state.advance(&ring_frame(3, 300, 2, 10)) else {
            panic!("third frame should retain");
        };
        let retained: usize = spans
            .iter()
            .filter(|span| matches!(span, ReplaySpan::Retained { .. }))
            .count();
        assert!(retained >= 3, "each ring retains, got {spans:?}");
        // The tail circles are dynamic.
        assert!(spans
            .iter()
            .any(|span| matches!(span, ReplaySpan::Dynamic { .. })));
        // Retained spans carry the per-ring rotations, not a shared one.
        let transforms: Vec<RecordTransform> = spans
            .iter()
            .filter_map(|span| match span {
                ReplaySpan::Retained { transform, .. } => Some(*transform),
                _ => None,
            })
            .collect();
        assert!(transforms.windows(2).any(|w| w[0].angle != w[1].angle));
    }

    #[test]
    fn entity_churn_between_frames_still_retains_rings() {
        let mut state = CommandReplayState::default();
        state.advance(&ring_frame(2, 400, 0, 8));
        state.advance(&ring_frame(2, 400, 1, 13)); // tail length changed
        let ReplayOutcome::Spans(spans) = state.advance(&ring_frame(2, 400, 2, 5)) else {
            panic!("churned tail must not break ring retention");
        };
        let retained_records: usize = spans
            .iter()
            .filter_map(|span| match span {
                ReplaySpan::Retained { .. } => Some(1),
                _ => None,
            })
            .sum();
        assert!(retained_records >= 2);
    }

    #[test]
    fn recolors_are_patches_not_mismatches() {
        let recolored_frame = |frame: usize| {
            let mut recording = ring_frame(1, 600, frame, 0);
            // Twinkle: 40 dots change color every frame, geometry untouched.
            for i in (0..recording.arcs.len()).step_by(15) {
                recording.arcs[i].color = if frame.is_multiple_of(2) {
                    Color::rgb(1.0, 0.5, 0.1)
                } else {
                    Color::rgb(0.1, 0.5, 1.0)
                };
            }
            recording
        };
        let mut state = CommandReplayState::default();
        state.advance(&recolored_frame(0));
        state.advance(&recolored_frame(1));
        let ReplayOutcome::Spans(spans) = state.advance(&recolored_frame(2)) else {
            panic!("twinkles must not break retention");
        };
        let recolor_count: usize = spans
            .iter()
            .filter_map(|span| match span {
                ReplaySpan::Retained { recolors, .. } => Some(recolors.len()),
                _ => None,
            })
            .sum();
        assert!(recolor_count >= 30, "twinkles surface as patches");
    }

    #[test]
    fn geometry_change_kills_only_its_segment() {
        let mut state = CommandReplayState::default();
        state.advance(&ring_frame(3, 300, 0, 0));
        state.advance(&ring_frame(3, 300, 1, 0));
        let mut broken = ring_frame(3, 300, 2, 0);
        // A brick hit: one entry in the middle ring changes sweep.
        broken.arcs[450].sweep_angle *= 3.0;
        let ReplayOutcome::Spans(spans) = state.advance(&broken) else {
            panic!("one changed entry must not drop the whole command");
        };
        let retained: usize = spans
            .iter()
            .filter(|span| matches!(span, ReplaySpan::Retained { .. }))
            .count();
        assert!(
            retained >= 2,
            "the untouched rings keep retaining, got {spans:?}"
        );
    }

    #[test]
    fn mid_segment_change_splits_and_retains_both_halves() {
        let mut state = CommandReplayState::default();
        state.advance(&ring_frame(1, 900, 0, 0));
        state.advance(&ring_frame(1, 900, 1, 0));
        assert_eq!(state.segments().len(), 1, "one ring is one segment");
        let mut broken = ring_frame(1, 900, 2, 0);
        broken.arcs[450].sweep_angle *= 3.0;
        let ReplayOutcome::Spans(spans) = state.advance(&broken) else {
            panic!("a single changed record must not drop retention");
        };
        let dynamic: usize = spans
            .iter()
            .filter_map(|span| match span {
                ReplaySpan::Dynamic {
                    tape_start,
                    tape_end,
                } => Some(tape_end - tape_start),
                _ => None,
            })
            .sum();
        let retained: Vec<(u32, usize, bool)> = spans
            .iter()
            .filter_map(|span| match span {
                ReplaySpan::Retained {
                    slot,
                    slot_offset,
                    capture,
                    ..
                } => Some((*slot, *slot_offset, *capture)),
                _ => None,
            })
            .collect();
        assert_eq!(
            retained.len(),
            2,
            "prefix and suffix both retain: {spans:?}"
        );
        // Both pieces address the SAME captured slot — a split never
        // recaptures, it re-addresses: the suffix starts one record past
        // the prefix within the capture.
        assert_eq!(retained[0].0, retained[1].0);
        assert_eq!(retained[0].1, 0);
        assert_eq!(retained[1].1, 451);
        assert!(retained.iter().all(|(_, _, capture)| !capture));
        assert_eq!(dynamic, 1, "only the changed record goes dynamic");
        assert_eq!(state.stats(), (0, 1), "one split, no deaths");

        // The pieces keep retaining on later frames, the changed record's
        // slot staying dynamic between them.
        let ReplayOutcome::Spans(spans) = state.advance(&ring_frame(1, 900, 3, 0)) else {
            panic!("split pieces must keep retaining");
        };
        let retained = spans
            .iter()
            .filter(|span| matches!(span, ReplaySpan::Retained { .. }))
            .count();
        assert_eq!(retained, 2, "both pieces relocate next frame: {spans:?}");
    }

    #[test]
    fn erosion_recaptures_dead_ranges_after_the_cooldown() {
        let mut state = CommandReplayState::default();
        state.advance(&ring_frame(3, 300, 0, 0));
        state.advance(&ring_frame(3, 300, 1, 0));
        // The middle ring changes shape permanently: its segment dies, and
        // only a recapture can watch the new shape.
        let mutated = |frame: usize| {
            let mut recording = ring_frame(3, 300, frame, 0);
            for arc in &mut recording.arcs[300..600] {
                arc.sweep_angle *= 3.0;
            }
            recording
        };
        let dynamic_records = |outcome: &ReplayOutcome| -> usize {
            match outcome {
                ReplayOutcome::AllDynamic => usize::MAX,
                ReplayOutcome::Spans(spans) => spans
                    .iter()
                    .filter_map(|span| match span {
                        ReplaySpan::Dynamic {
                            tape_start,
                            tape_end,
                        } => Some(tape_end - tape_start),
                        _ => None,
                    })
                    .sum(),
            }
        };
        let after_death = state.advance(&mutated(2));
        let lost = dynamic_records(&after_death);
        assert!(
            (250..=400).contains(&lost),
            "the changed ring goes dynamic, got {lost}"
        );
        for frame in 3..(3 + RECAPTURE_COOLDOWN_FRAMES as usize + 4) {
            state.advance(&mutated(frame));
        }
        let recovered = state.advance(&mutated(200));
        let residue = dynamic_records(&recovered);
        assert!(
            residue < 50,
            "the recapture watches the ring's new shape, got {residue} dynamic"
        );
    }

    #[test]
    fn small_commands_are_not_watched() {
        let mut state = CommandReplayState::default();
        for frame in 0..4 {
            assert!(matches!(
                state.advance(&ring_frame(1, 40, frame, 0)),
                ReplayOutcome::AllDynamic
            ));
        }
        assert!(state.segments().is_empty());
    }

    /// A real multi-threaded executor for the equivalence test: lane 0 is
    /// the caller, the rest are scoped threads, jobs stride across lanes —
    /// the same distribution the renderer's frame pool uses.
    struct ThreadedExec {
        lanes: usize,
    }

    impl VerifyExecutor for ThreadedExec {
        fn for_each(&self, jobs: usize, run: &(dyn Fn(usize) + Sync)) {
            std::thread::scope(|s| {
                for lane in 1..self.lanes {
                    s.spawn(move || {
                        let mut i = lane;
                        while i < jobs {
                            run(i);
                            i += self.lanes;
                        }
                    });
                }
                let mut i = 0;
                while i < jobs {
                    run(i);
                    i += self.lanes;
                }
            });
        }
    }

    #[test]
    fn pooled_verification_matches_serial_exactly() {
        let exec = ThreadedExec { lanes: 3 };
        // Every verification path in one churning sequence: multi-ring
        // retention under rotation, tail churn, twinkle recolors, and a
        // mid-run sweep change that forces the optimistic pass to bail and
        // the serial rerun to split.
        let frame = |f: usize| -> CommandRecording {
            let tail = [10usize, 13, 5, 8, 11, 6, 9, 12][f % 8];
            let mut recording = ring_frame(3, 300, f, tail);
            if f >= 3 {
                for i in (0..recording.arcs.len()).step_by(17) {
                    recording.arcs[i].color = if f.is_multiple_of(2) {
                        Color::rgb(1.0, 0.5, 0.1)
                    } else {
                        Color::rgb(0.1, 0.5, 1.0)
                    };
                }
            }
            if f == 5 {
                // Geometry change inside the middle ring: a genuine
                // mismatch mid-segment.
                recording.arcs[450].sweep_angle = 0.15;
            }
            recording
        };
        let mut serial = CommandReplayState::default();
        let mut pooled = CommandReplayState::default();
        for f in 0..10 {
            let recording = frame(f);
            let serial_outcome = serial.advance(&recording);
            let pooled_outcome = pooled.advance_pooled(&recording, Some(&exec));
            assert_eq!(
                serial_outcome, pooled_outcome,
                "outcome diverged at frame {f}"
            );
            assert_eq!(
                serial.segments(),
                pooled.segments(),
                "segments diverged at frame {f}"
            );
            assert_eq!(
                serial.stats(),
                pooled.stats(),
                "stats diverged at frame {f}"
            );
        }
        let (deaths, splits) = serial.stats();
        assert!(
            !serial.segments().is_empty() && deaths + splits > 0,
            "sequence must exercise both retention and the mismatch path, \
             got {deaths} deaths {splits} splits {} segments",
            serial.segments().len()
        );
        assert_eq!(serial.optimistic_commits(), 0);
        assert!(
            pooled.optimistic_commits() >= 3,
            "the pooled fast path must actually commit steady frames, got {}",
            pooled.optimistic_commits()
        );
    }

    #[test]
    fn transformed_bounds_contain_the_moved_content() {
        let t = RecordTransform {
            scale: 1.1,
            angle: 0.5,
        };
        let bounds = Rect {
            x: 150.0,
            y: 150.0,
            width: 100.0,
            height: 30.0,
        };
        let moved = t.apply_to_bounds(CENTER, bounds);
        for corner in [
            Point::new(bounds.x, bounds.y),
            Point::new(bounds.x + bounds.width, bounds.y + bounds.height),
        ] {
            let p = t.apply(CENTER, corner);
            assert!(p.x >= moved.x - 1e-3 && p.x <= moved.x + moved.width + 1e-3);
            assert!(p.y >= moved.y - 1e-3 && p.y <= moved.y + moved.height + 1e-3);
        }
    }
}