ftui-render 0.3.1

Render kernel: cells, buffers, diffs, and ANSI presentation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
#![forbid(unsafe_code)]

//! Diff computation between buffers.
//!
//! The `BufferDiff` computes the minimal set of changed cells between two
//! buffers using a row-major scan for optimal cache efficiency.
//!
//! # Algorithm
//!
//! Row-major scan for cache efficiency:
//! 1. Iterate y from 0 to height
//! 2. Fast-path skip rows where the full slice is equal
//! 3. For changed rows, scan in coarse blocks and skip unchanged blocks
//! 4. Within dirty blocks, compare cells using `bits_eq`
//!
//! This ensures sequential memory access since cells are stored row-by-row.
//! With 4 cells per cache line, the prefetcher can anticipate next access.
//!
//! # Usage
//!
//! ```
//! use ftui_render::buffer::Buffer;
//! use ftui_render::cell::Cell;
//! use ftui_render::diff::BufferDiff;
//!
//! let mut old = Buffer::new(80, 24);
//! let mut new = Buffer::new(80, 24);
//!
//! // Make some changes
//! new.set_raw(5, 5, Cell::from_char('X'));
//! new.set_raw(6, 5, Cell::from_char('Y'));
//!
//! let diff = BufferDiff::compute(&old, &new);
//! assert_eq!(diff.len(), 2);
//!
//! // Coalesce into runs for efficient emission
//! let runs = diff.runs();
//! assert_eq!(runs.len(), 1); // Adjacent cells form one run
//! ```

use crate::buffer::{Buffer, DirtySpan};
use crate::cell::Cell;

// =============================================================================
// Certificate-Based Skip Hints
// =============================================================================

/// Hint from a render certificate evaluator about what diff work can be skipped.
///
/// The runtime evaluates a certificate (e.g., from `render_certificate::CertificateEvaluator`)
/// and translates the result into a `DiffSkipHint` that `BufferDiff::compute_certified_into`
/// can act on.
///
/// # Safety contract
///
/// The hint must be correct: `SkipDiff` must only be issued when the caller
/// can guarantee that old and new buffers are byte-identical. `NarrowToRows`
/// must include all rows that actually changed. Incorrect hints produce stale
/// frames — the diff engine trusts the hint without verification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffSkipHint {
    /// No skip — perform standard dirty-diff computation.
    FullDiff,
    /// Skip diff entirely — buffers are guaranteed identical.
    SkipDiff,
    /// Only diff the specified rows — all other rows are guaranteed clean.
    NarrowToRows(Vec<u16>),
}

impl DiffSkipHint {
    /// Whether this hint skips any work.
    #[must_use]
    pub fn skips_work(&self) -> bool {
        !matches!(self, Self::FullDiff)
    }

    /// Human-readable label for evidence logging.
    #[must_use]
    pub fn label(&self) -> &'static str {
        match self {
            Self::FullDiff => "full-diff",
            Self::SkipDiff => "skip-diff",
            Self::NarrowToRows(_) => "narrow-to-rows",
        }
    }
}

// =============================================================================
// Block-based Row Scanning (autovec-friendly)
// =============================================================================

/// Block size for vectorized comparison (4 cells = 64 bytes).
/// Chosen to match common SIMD register width (256-bit / 512-bit)
/// and a single 64-byte cache line.
const BLOCK_SIZE: usize = 4;

// Compile-time: 4 cells must equal exactly one 64-byte cache line.
const _: () = assert!(
    core::mem::size_of::<Cell>() * BLOCK_SIZE == 64,
    "BLOCK_SIZE * Cell must equal 64-byte cache line"
);

// Compile-time: Cell alignment must be at least 16 bytes so that
// Vec<Cell> allocations are 16-byte aligned (SSE-friendly).
const _: () = assert!(
    core::mem::align_of::<Cell>() >= 16,
    "Cell alignment must be >= 16 for SIMD access"
);

/// Row block size for coarse blockwise skip (32 cells = 512 bytes).
/// This lets us skip large unchanged regions in sparse rows while
/// preserving row-major iteration order.
const ROW_BLOCK_SIZE: usize = 32;

/// Cache-line-aligned block of 4 cells (64 bytes).
///
/// This type documents the alignment contract: each `BLOCK_SIZE` group
/// of cells should ideally start on a 64-byte boundary for optimal
/// SIMD and cache performance.
#[repr(C, align(64))]
#[allow(dead_code)]
struct CacheLineBlock {
    cells: [Cell; BLOCK_SIZE],
}

// Compile-time: CacheLineBlock must be exactly 64 bytes.
const _: () = assert!(
    core::mem::size_of::<CacheLineBlock>() == 64,
    "CacheLineBlock must be exactly 64 bytes"
);

#[cfg(test)]
fn span_diagnostics(buf: &Buffer) -> String {
    let stats = buf.dirty_span_stats();
    if !buf.dirty_span_config().enabled {
        return format!("dirty spans disabled; stats={stats:?}");
    }
    let mut rows = Vec::new();
    for y in 0..buf.height() {
        let Some(row) = buf.dirty_span_row(y) else {
            continue;
        };
        if row.is_full() {
            rows.push(format!("{y}:full"));
            continue;
        }
        if row.spans().is_empty() {
            continue;
        }
        let spans = row
            .spans()
            .iter()
            .map(|span| format!("[{}, {})", span.x0, span.x1))
            .collect::<Vec<_>>()
            .join(",");
        rows.push(format!("{y}:{spans}"));
    }
    format!("stats={stats:?} rows=[{}]", rows.join(" | "))
}

/// Scan a row slice for changed cells, appending positions to `changes`.
///
/// `x_offset` is added to each recorded x coordinate.
///
/// `#[inline(always)]` forces inlining into the blockwise caller so LLVM can
/// see the full loop and apply auto-vectorization across the 4-cell block.
#[inline(always)]
fn scan_row_changes_range(
    old_row: &[Cell],
    new_row: &[Cell],
    y: u16,
    x_offset: u16,
    changes: &mut Vec<(u16, u16)>,
) {
    debug_assert_eq!(old_row.len(), new_row.len());
    let len = old_row.len();
    let blocks = len / BLOCK_SIZE;
    let remainder = len % BLOCK_SIZE;

    // Process full blocks
    for block_idx in 0..blocks {
        let base = block_idx * BLOCK_SIZE;
        let base_x = x_offset + base as u16;
        if cell_quad_bits_eq(old_row, new_row, base) {
            continue;
        }

        // Compare each cell and push changes directly.
        // We use a constant loop which the compiler will unroll.
        for i in 0..BLOCK_SIZE {
            if !old_row[base + i].bits_eq(&new_row[base + i]) {
                changes.push((base_x + i as u16, y));
            }
        }
    }

    // Process remainder cells
    let rem_base = blocks * BLOCK_SIZE;
    let rem_base_x = x_offset + rem_base as u16;
    for i in 0..remainder {
        if !old_row[rem_base + i].bits_eq(&new_row[rem_base + i]) {
            changes.push((rem_base_x + i as u16, y));
        }
    }
}

#[inline(always)]
fn cell_quad_bits_eq(old_row: &[Cell], new_row: &[Cell], base: usize) -> bool {
    old_row[base].bits_eq(&new_row[base])
        & old_row[base + 1].bits_eq(&new_row[base + 1])
        & old_row[base + 2].bits_eq(&new_row[base + 2])
        & old_row[base + 3].bits_eq(&new_row[base + 3])
}

/// Scan a row pair for changed cells, appending positions to `changes`.
///
/// Uses coarse block skipping to avoid full per-cell scans in sparse rows,
/// then falls back to fine-grained scanning inside dirty blocks.
#[inline]
fn scan_row_changes(old_row: &[Cell], new_row: &[Cell], y: u16, changes: &mut Vec<(u16, u16)>) {
    scan_row_changes_blockwise(old_row, new_row, y, changes);
}

/// Scan a row in coarse blocks, skipping unchanged blocks, and falling back
/// to fine-grained scan for blocks that differ.
#[inline]
fn scan_row_changes_blockwise(
    old_row: &[Cell],
    new_row: &[Cell],
    y: u16,
    changes: &mut Vec<(u16, u16)>,
) {
    debug_assert_eq!(old_row.len(), new_row.len());
    let len = old_row.len();
    let blocks = len / ROW_BLOCK_SIZE;
    let remainder = len % ROW_BLOCK_SIZE;

    for block_idx in 0..blocks {
        let base = block_idx * ROW_BLOCK_SIZE;
        let old_block = &old_row[base..base + ROW_BLOCK_SIZE];
        let new_block = &new_row[base..base + ROW_BLOCK_SIZE];
        scan_row_changes_range(old_block, new_block, y, base as u16, changes);
    }

    if remainder > 0 {
        let base = blocks * ROW_BLOCK_SIZE;
        let old_block = &old_row[base..base + remainder];
        let new_block = &new_row[base..base + remainder];
        scan_row_changes_range(old_block, new_block, y, base as u16, changes);
    }
}

/// Scan only dirty spans within a row, preserving row-major ordering.
#[inline]
fn scan_row_changes_spans(
    old_row: &[Cell],
    new_row: &[Cell],
    y: u16,
    spans: &[DirtySpan],
    changes: &mut Vec<(u16, u16)>,
) {
    for span in spans {
        let start = span.x0 as usize;
        let end = span.x1 as usize;
        if start >= end || start >= old_row.len() {
            continue;
        }
        let end = end.min(old_row.len());
        let old_slice = &old_row[start..end];
        let new_slice = &new_row[start..end];
        if old_slice == new_slice {
            continue;
        }
        scan_row_changes_range(old_slice, new_slice, y, span.x0, changes);
    }
}

#[inline]
fn scan_row_changes_range_if_needed(
    old_row: &[Cell],
    new_row: &[Cell],
    y: u16,
    start: usize,
    end: usize,
    changes: &mut Vec<(u16, u16)>,
) {
    if start >= end || start >= old_row.len() {
        return;
    }
    let end = end.min(old_row.len());
    let old_slice = &old_row[start..end];
    let new_slice = &new_row[start..end];
    if old_slice == new_slice {
        return;
    }
    scan_row_changes_range(old_slice, new_slice, y, start as u16, changes);
}

#[inline]
#[allow(clippy::too_many_arguments)]
fn scan_row_tiles(
    old_row: &[Cell],
    new_row: &[Cell],
    y: u16,
    width: usize,
    tile_w: usize,
    tiles_x: usize,
    tile_row_base: usize,
    dirty_tiles: &[bool],
    changes: &mut Vec<(u16, u16)>,
) {
    for tile_x in 0..tiles_x {
        let tile_idx = tile_row_base + tile_x;
        if !dirty_tiles[tile_idx] {
            continue;
        }
        let start = tile_x * tile_w;
        let end = ((tile_x + 1) * tile_w).min(width);
        scan_row_changes_range_if_needed(old_row, new_row, y, start, end, changes);
    }
}

#[inline]
#[allow(clippy::too_many_arguments)]
fn scan_row_tiles_spans(
    old_row: &[Cell],
    new_row: &[Cell],
    y: u16,
    width: usize,
    tile_w: usize,
    tiles_x: usize,
    tile_row_base: usize,
    dirty_tiles: &[bool],
    spans: &[DirtySpan],
    changes: &mut Vec<(u16, u16)>,
) {
    if spans.is_empty() {
        return;
    }
    let max_x = width.saturating_sub(1);
    for span in spans {
        let span_start = span.x0 as usize;
        let span_end_exclusive = span.x1 as usize;
        if span_start >= span_end_exclusive || span_start > max_x {
            continue;
        }
        let span_end = span_end_exclusive.saturating_sub(1).min(max_x);
        let tile_x_start = span_start / tile_w;
        let tile_x_end = span_end / tile_w;
        for tile_x in tile_x_start..=tile_x_end {
            if tile_x >= tiles_x {
                break;
            }
            let tile_idx = tile_row_base + tile_x;
            if !dirty_tiles[tile_idx] {
                continue;
            }
            let tile_start = tile_x * tile_w;
            let tile_end = ((tile_x + 1) * tile_w).min(width);
            let seg_start = span_start.max(tile_start);
            let seg_end = span_end.min(tile_end.saturating_sub(1));
            if seg_start > seg_end {
                continue;
            }
            scan_row_changes_range_if_needed(old_row, new_row, y, seg_start, seg_end + 1, changes);
        }
    }
}

// =============================================================================
// Tile-based Skip (Summed-Area Table)
// =============================================================================

const TILE_SIZE_MIN: u16 = 8;
const TILE_SIZE_MAX: u16 = 64;

#[inline]
fn clamp_tile_size(value: u16) -> u16 {
    value.clamp(TILE_SIZE_MIN, TILE_SIZE_MAX)
}

#[inline]
fn div_ceil_usize(n: usize, d: usize) -> usize {
    debug_assert!(d > 0);
    n.div_ceil(d)
}

#[inline]
fn accumulate_tile_counts_range(
    tile_counts: &mut [u32],
    dirty_row_bits: &[u8],
    tile_row_base: usize,
    tiles_x: usize,
    tile_w: usize,
    range: core::ops::Range<usize>,
    scanned_cells: &mut usize,
) -> Result<(), ()> {
    let start = range.start;
    let end = range.end;
    if start >= end || start >= dirty_row_bits.len() {
        return Ok(());
    }

    let end = end.min(dirty_row_bits.len());
    *scanned_cells = scanned_cells.saturating_add(end.saturating_sub(start));

    let tile_x_start = start / tile_w;
    let tile_x_end = (end - 1) / tile_w;
    for tile_x in tile_x_start..=tile_x_end {
        if tile_x >= tiles_x {
            break;
        }

        let seg_start = start.max(tile_x * tile_w);
        let seg_end = end.min((tile_x + 1) * tile_w);
        let count = dirty_row_bits[seg_start..seg_end]
            .iter()
            .filter(|&&bit| bit != 0)
            .count();
        if count == 0 {
            continue;
        }

        let tile_idx = tile_row_base + tile_x;
        match tile_counts[tile_idx].checked_add(count as u32) {
            Some(value) => tile_counts[tile_idx] = value,
            None => return Err(()),
        }
    }

    Ok(())
}

/// Configuration for tile-based diff skipping.
#[derive(Debug, Clone)]
pub struct TileDiffConfig {
    /// Whether tile-based skipping is enabled.
    pub enabled: bool,
    /// Tile width in cells (clamped to [8, 64]).
    pub tile_w: u16,
    /// Tile height in cells (clamped to [8, 64]).
    pub tile_h: u16,
    /// Skip scanning clean rows when building tile counts.
    ///
    /// When true, the tile build only scans rows marked dirty, reducing
    /// build cost for sparse updates. Disable to force full-row scans.
    pub skip_clean_rows: bool,
    /// Minimum total cells required before enabling tiles.
    pub min_cells_for_tiles: usize,
    /// Dense cell ratio threshold for falling back to non-tile diff.
    pub dense_cell_ratio: f64,
    /// Dense tile ratio threshold for falling back to non-tile diff.
    pub dense_tile_ratio: f64,
    /// Maximum number of tiles allowed (SAT build budget; fallback if exceeded).
    pub max_tiles: usize,
}

impl Default for TileDiffConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            tile_w: 16,
            tile_h: 8,
            skip_clean_rows: true,
            min_cells_for_tiles: 12_000,
            dense_cell_ratio: 0.25,
            dense_tile_ratio: 0.60,
            max_tiles: 4096,
        }
    }
}

impl TileDiffConfig {
    /// Toggle tile-based skipping.
    #[must_use]
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Set tile size in cells (clamped during build).
    #[must_use]
    pub fn with_tile_size(mut self, tile_w: u16, tile_h: u16) -> Self {
        self.tile_w = tile_w;
        self.tile_h = tile_h;
        self
    }

    /// Set minimum cell count required before tiles are considered.
    #[must_use]
    pub fn with_min_cells_for_tiles(mut self, min_cells: usize) -> Self {
        self.min_cells_for_tiles = min_cells;
        self
    }

    /// Toggle skipping clean rows during tile build.
    #[must_use]
    pub fn with_skip_clean_rows(mut self, skip: bool) -> Self {
        self.skip_clean_rows = skip;
        self
    }

    /// Set dense cell ratio threshold for falling back to non-tile diff.
    #[must_use]
    pub fn with_dense_cell_ratio(mut self, ratio: f64) -> Self {
        self.dense_cell_ratio = ratio;
        self
    }

    /// Set dense tile ratio threshold for falling back to non-tile diff.
    #[must_use]
    pub fn with_dense_tile_ratio(mut self, ratio: f64) -> Self {
        self.dense_tile_ratio = ratio;
        self
    }

    /// Set SAT build budget via maximum tiles allowed.
    #[must_use]
    pub fn with_max_tiles(mut self, max_tiles: usize) -> Self {
        self.max_tiles = max_tiles;
        self
    }
}

/// Reason the tile path fell back to a non-tile diff.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TileDiffFallback {
    Disabled,
    SmallScreen,
    DirtyAll,
    DenseCells,
    DenseTiles,
    TooManyTiles,
    Overflow,
}

impl TileDiffFallback {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Disabled => "disabled",
            Self::SmallScreen => "small_screen",
            Self::DirtyAll => "dirty_all",
            Self::DenseCells => "dense_cells",
            Self::DenseTiles => "dense_tiles",
            Self::TooManyTiles => "too_many_tiles",
            Self::Overflow => "overflow",
        }
    }
}

/// Tile parameters derived from the current buffer dimensions.
#[derive(Debug, Clone, Copy)]
pub struct TileParams {
    pub width: u16,
    pub height: u16,
    pub tile_w: u16,
    pub tile_h: u16,
    pub tiles_x: usize,
    pub tiles_y: usize,
}

impl TileParams {
    #[inline]
    pub fn total_tiles(self) -> usize {
        self.tiles_x * self.tiles_y
    }

    #[inline]
    pub fn total_cells(self) -> usize {
        self.width as usize * self.height as usize
    }
}

/// Summary statistics from building a tile SAT.
#[derive(Debug, Clone, Copy)]
pub struct TileDiffStats {
    pub width: u16,
    pub height: u16,
    pub tile_w: u16,
    pub tile_h: u16,
    pub tiles_x: usize,
    pub tiles_y: usize,
    pub total_tiles: usize,
    pub dirty_cells: usize,
    pub dirty_tiles: usize,
    pub dirty_cell_ratio: f64,
    pub dirty_tile_ratio: f64,
    pub scanned_tiles: usize,
    pub skipped_tiles: usize,
    pub sat_build_cells: usize,
    pub scan_cells_estimate: usize,
    pub fallback: Option<TileDiffFallback>,
}

/// Reusable builder for tile counts and SAT.
#[derive(Debug, Default, Clone)]
#[must_use]
pub struct TileDiffBuilder {
    tile_counts: Vec<u32>,
    sat: Vec<u32>,
    dirty_tiles: Vec<bool>,
}

/// Inputs required to build a tile diff plan.
#[derive(Debug, Clone, Copy)]
pub struct TileDiffInput<'a> {
    pub width: u16,
    pub height: u16,
    pub dirty_rows: &'a [bool],
    pub dirty_bits: &'a [u8],
    pub dirty_cells: usize,
    pub dirty_all: bool,
}

/// Successful tile build with reusable buffers.
#[derive(Debug, Clone)]
pub struct TileDiffPlan<'a> {
    pub params: TileParams,
    pub stats: TileDiffStats,
    pub dirty_tiles: &'a [bool],
    pub tile_counts: &'a [u32],
    pub sat: &'a [u32],
}

/// Result of a tile build attempt.
#[derive(Debug, Clone)]
pub enum TileDiffBuild<'a> {
    UseTiles(TileDiffPlan<'a>),
    Fallback(TileDiffStats),
}

impl TileDiffBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn build<'a, 'b>(
        &'a mut self,
        config: &TileDiffConfig,
        input: TileDiffInput<'b>,
    ) -> TileDiffBuild<'a> {
        let TileDiffInput {
            width,
            height,
            dirty_rows,
            dirty_bits,
            dirty_cells,
            dirty_all,
        } = input;
        let tile_w = clamp_tile_size(config.tile_w);
        let tile_h = clamp_tile_size(config.tile_h);
        let width_usize = width as usize;
        let height_usize = height as usize;
        let tiles_x = div_ceil_usize(width_usize, tile_w as usize);
        let tiles_y = div_ceil_usize(height_usize, tile_h as usize);
        let total_tiles = tiles_x * tiles_y;
        let total_cells = width_usize * height_usize;
        let dirty_cell_ratio = if total_cells == 0 {
            0.0
        } else {
            dirty_cells as f64 / total_cells as f64
        };

        let mut stats = TileDiffStats {
            width,
            height,
            tile_w,
            tile_h,
            tiles_x,
            tiles_y,
            total_tiles,
            dirty_cells,
            dirty_tiles: 0,
            dirty_cell_ratio,
            dirty_tile_ratio: 0.0,
            scanned_tiles: 0,
            skipped_tiles: total_tiles,
            sat_build_cells: 0,
            scan_cells_estimate: 0,
            fallback: None,
        };

        if !config.enabled {
            stats.fallback = Some(TileDiffFallback::Disabled);
            return TileDiffBuild::Fallback(stats);
        }

        if total_cells < config.min_cells_for_tiles {
            stats.fallback = Some(TileDiffFallback::SmallScreen);
            return TileDiffBuild::Fallback(stats);
        }

        if dirty_all {
            stats.fallback = Some(TileDiffFallback::DirtyAll);
            return TileDiffBuild::Fallback(stats);
        }

        if dirty_cell_ratio >= config.dense_cell_ratio {
            stats.fallback = Some(TileDiffFallback::DenseCells);
            return TileDiffBuild::Fallback(stats);
        }

        if total_tiles > config.max_tiles {
            stats.fallback = Some(TileDiffFallback::TooManyTiles);
            return TileDiffBuild::Fallback(stats);
        }

        debug_assert_eq!(dirty_bits.len(), total_cells);
        if dirty_bits.len() < total_cells {
            stats.fallback = Some(TileDiffFallback::Overflow);
            return TileDiffBuild::Fallback(stats);
        }

        self.tile_counts.resize(total_tiles, 0);
        self.tile_counts.fill(0);
        self.dirty_tiles.resize(total_tiles, false);
        self.dirty_tiles.fill(false);

        let tile_w_usize = tile_w as usize;
        let tile_h_usize = tile_h as usize;
        let mut overflow = false;
        let mut scanned_cells = 0usize;

        debug_assert_eq!(dirty_rows.len(), height_usize);
        for y in 0..height_usize {
            let row_dirty = if config.skip_clean_rows {
                dirty_rows.get(y).copied().unwrap_or(true)
            } else {
                true
            };
            if !row_dirty {
                continue;
            }
            scanned_cells = scanned_cells.saturating_add(width_usize);
            let row_start = y * width_usize;
            let tile_y = y / tile_h_usize;
            for x in 0..width_usize {
                let idx = row_start + x;
                if dirty_bits[idx] == 0 {
                    continue;
                }
                let tile_x = x / tile_w_usize;
                let tile_idx = tile_y * tiles_x + tile_x;
                match self.tile_counts[tile_idx].checked_add(1) {
                    Some(value) => self.tile_counts[tile_idx] = value,
                    None => {
                        overflow = true;
                        break;
                    }
                }
            }
            if overflow {
                break;
            }
        }

        if overflow {
            stats.fallback = Some(TileDiffFallback::Overflow);
            return TileDiffBuild::Fallback(stats);
        }

        let mut dirty_tiles = 0usize;
        for (idx, count) in self.tile_counts.iter().enumerate() {
            if *count > 0 {
                self.dirty_tiles[idx] = true;
                dirty_tiles += 1;
            }
        }

        stats.dirty_tiles = dirty_tiles;
        stats.dirty_tile_ratio = if total_tiles == 0 {
            0.0
        } else {
            dirty_tiles as f64 / total_tiles as f64
        };
        stats.scanned_tiles = dirty_tiles;
        stats.skipped_tiles = total_tiles.saturating_sub(dirty_tiles);
        stats.sat_build_cells = scanned_cells;
        stats.scan_cells_estimate = dirty_tiles * tile_w_usize * tile_h_usize;

        if stats.dirty_tile_ratio >= config.dense_tile_ratio {
            stats.fallback = Some(TileDiffFallback::DenseTiles);
            return TileDiffBuild::Fallback(stats);
        }

        let sat_w = tiles_x + 1;
        let sat_h = tiles_y + 1;
        let sat_len = sat_w * sat_h;
        self.sat.resize(sat_len, 0);
        self.sat.fill(0);

        for ty in 0..tiles_y {
            let row_base = (ty + 1) * sat_w;
            let prev_base = ty * sat_w;
            for tx in 0..tiles_x {
                let count = self.tile_counts[ty * tiles_x + tx] as u64;
                let above = self.sat[prev_base + tx + 1] as u64;
                let left = self.sat[row_base + tx] as u64;
                let diag = self.sat[prev_base + tx] as u64;
                let value = count + above + left - diag;
                if value > u32::MAX as u64 {
                    stats.fallback = Some(TileDiffFallback::Overflow);
                    return TileDiffBuild::Fallback(stats);
                }
                self.sat[row_base + tx + 1] = value as u32;
            }
        }

        let params = TileParams {
            width,
            height,
            tile_w,
            tile_h,
            tiles_x,
            tiles_y,
        };

        TileDiffBuild::UseTiles(TileDiffPlan {
            params,
            stats,
            dirty_tiles: &self.dirty_tiles,
            tile_counts: &self.tile_counts,
            sat: &self.sat,
        })
    }

    fn build_from_buffer<'a>(
        &'a mut self,
        config: &TileDiffConfig,
        buffer: &Buffer,
    ) -> TileDiffBuild<'a> {
        let width = buffer.width();
        let height = buffer.height();
        let dirty_rows = buffer.dirty_rows();
        let dirty_bits = buffer.dirty_bits();
        let dirty_cells = buffer.dirty_cell_count();
        let dirty_all = buffer.dirty_all();

        let tile_w = clamp_tile_size(config.tile_w);
        let tile_h = clamp_tile_size(config.tile_h);
        let width_usize = width as usize;
        let height_usize = height as usize;
        let tiles_x = div_ceil_usize(width_usize, tile_w as usize);
        let tiles_y = div_ceil_usize(height_usize, tile_h as usize);
        let total_tiles = tiles_x * tiles_y;
        let total_cells = width_usize * height_usize;
        let dirty_cell_ratio = if total_cells == 0 {
            0.0
        } else {
            dirty_cells as f64 / total_cells as f64
        };

        let mut stats = TileDiffStats {
            width,
            height,
            tile_w,
            tile_h,
            tiles_x,
            tiles_y,
            total_tiles,
            dirty_cells,
            dirty_tiles: 0,
            dirty_cell_ratio,
            dirty_tile_ratio: 0.0,
            scanned_tiles: 0,
            skipped_tiles: total_tiles,
            sat_build_cells: 0,
            scan_cells_estimate: 0,
            fallback: None,
        };

        if !config.enabled {
            stats.fallback = Some(TileDiffFallback::Disabled);
            return TileDiffBuild::Fallback(stats);
        }

        if total_cells < config.min_cells_for_tiles {
            stats.fallback = Some(TileDiffFallback::SmallScreen);
            return TileDiffBuild::Fallback(stats);
        }

        if dirty_all {
            stats.fallback = Some(TileDiffFallback::DirtyAll);
            return TileDiffBuild::Fallback(stats);
        }

        if dirty_cell_ratio >= config.dense_cell_ratio {
            stats.fallback = Some(TileDiffFallback::DenseCells);
            return TileDiffBuild::Fallback(stats);
        }

        if total_tiles > config.max_tiles {
            stats.fallback = Some(TileDiffFallback::TooManyTiles);
            return TileDiffBuild::Fallback(stats);
        }

        debug_assert_eq!(dirty_bits.len(), total_cells);
        if dirty_bits.len() < total_cells {
            stats.fallback = Some(TileDiffFallback::Overflow);
            return TileDiffBuild::Fallback(stats);
        }

        self.tile_counts.resize(total_tiles, 0);
        self.tile_counts.fill(0);
        self.dirty_tiles.resize(total_tiles, false);
        self.dirty_tiles.fill(false);

        let tile_w_usize = tile_w as usize;
        let tile_h_usize = tile_h as usize;
        let mut overflow = false;
        let mut scanned_cells = 0usize;

        debug_assert_eq!(dirty_rows.len(), height_usize);
        for y in 0..height_usize {
            let row_dirty = if config.skip_clean_rows {
                dirty_rows.get(y).copied().unwrap_or(true)
            } else {
                true
            };
            if !row_dirty {
                continue;
            }

            let row_start = y * width_usize;
            let row_bits = &dirty_bits[row_start..row_start + width_usize];
            let tile_y = y / tile_h_usize;
            let tile_row_base = tile_y * tiles_x;

            let row_result = match buffer.dirty_span_row(y as u16) {
                Some(span_row) if !span_row.is_full() => {
                    let spans = span_row.spans();
                    if spans.is_empty() {
                        accumulate_tile_counts_range(
                            &mut self.tile_counts,
                            row_bits,
                            tile_row_base,
                            tiles_x,
                            tile_w_usize,
                            0..width_usize,
                            &mut scanned_cells,
                        )
                    } else {
                        let mut result = Ok(());
                        for span in spans {
                            result = accumulate_tile_counts_range(
                                &mut self.tile_counts,
                                row_bits,
                                tile_row_base,
                                tiles_x,
                                tile_w_usize,
                                span.x0 as usize..span.x1 as usize,
                                &mut scanned_cells,
                            );
                            if result.is_err() {
                                break;
                            }
                        }
                        result
                    }
                }
                _ => accumulate_tile_counts_range(
                    &mut self.tile_counts,
                    row_bits,
                    tile_row_base,
                    tiles_x,
                    tile_w_usize,
                    0..width_usize,
                    &mut scanned_cells,
                ),
            };

            if row_result.is_err() {
                overflow = true;
                break;
            }
        }

        if overflow {
            stats.fallback = Some(TileDiffFallback::Overflow);
            return TileDiffBuild::Fallback(stats);
        }

        let mut dirty_tiles = 0usize;
        for (idx, count) in self.tile_counts.iter().enumerate() {
            if *count > 0 {
                self.dirty_tiles[idx] = true;
                dirty_tiles += 1;
            }
        }

        stats.dirty_tiles = dirty_tiles;
        stats.dirty_tile_ratio = if total_tiles == 0 {
            0.0
        } else {
            dirty_tiles as f64 / total_tiles as f64
        };
        stats.scanned_tiles = dirty_tiles;
        stats.skipped_tiles = total_tiles.saturating_sub(dirty_tiles);
        stats.sat_build_cells = scanned_cells;
        stats.scan_cells_estimate = dirty_tiles * tile_w_usize * tile_h_usize;

        if stats.dirty_tile_ratio >= config.dense_tile_ratio {
            stats.fallback = Some(TileDiffFallback::DenseTiles);
            return TileDiffBuild::Fallback(stats);
        }

        let sat_w = tiles_x + 1;
        let sat_h = tiles_y + 1;
        let sat_len = sat_w * sat_h;
        self.sat.resize(sat_len, 0);
        self.sat.fill(0);

        for ty in 0..tiles_y {
            let row_base = (ty + 1) * sat_w;
            let prev_base = ty * sat_w;
            for tx in 0..tiles_x {
                let count = self.tile_counts[ty * tiles_x + tx] as u64;
                let above = self.sat[prev_base + tx + 1] as u64;
                let left = self.sat[row_base + tx] as u64;
                let diag = self.sat[prev_base + tx] as u64;
                let value = count + above + left - diag;
                if value > u32::MAX as u64 {
                    stats.fallback = Some(TileDiffFallback::Overflow);
                    return TileDiffBuild::Fallback(stats);
                }
                self.sat[row_base + tx + 1] = value as u32;
            }
        }

        let params = TileParams {
            width,
            height,
            tile_w,
            tile_h,
            tiles_x,
            tiles_y,
        };

        TileDiffBuild::UseTiles(TileDiffPlan {
            params,
            stats,
            dirty_tiles: &self.dirty_tiles,
            tile_counts: &self.tile_counts,
            sat: &self.sat,
        })
    }
}

#[inline]
fn reserve_changes_capacity(width: u16, height: u16, changes: &mut Vec<(u16, u16)>) {
    // Estimate capacity: assume ~5% of cells change on average.
    let estimated_changes = (width as usize * height as usize) / 20;
    let additional = estimated_changes.saturating_sub(changes.len());
    if additional > 0 {
        changes.reserve(additional);
    }
}

fn compute_changes(old: &Buffer, new: &Buffer, changes: &mut Vec<(u16, u16)>) {
    #[cfg(feature = "tracing")]
    let _span = tracing::debug_span!("diff_compute", width = old.width(), height = old.height());
    #[cfg(feature = "tracing")]
    let _guard = _span.enter();

    assert_eq!(old.width(), new.width(), "buffer widths must match");
    assert_eq!(old.height(), new.height(), "buffer heights must match");

    let width = old.width();
    let height = old.height();
    let w = width as usize;

    changes.clear();
    reserve_changes_capacity(width, height, changes);

    let old_cells = old.cells();
    let new_cells = new.cells();

    // Row-major scan with row-skip fast path
    for y in 0..height {
        let row_start = y as usize * w;
        let old_row = &old_cells[row_start..row_start + w];
        let new_row = &new_cells[row_start..row_start + w];

        // Scan for changed cells using blockwise row scan.
        // This avoids a full-row equality pre-scan and prevents
        // double-scanning rows that contain changes.
        scan_row_changes(old_row, new_row, y, changes);
    }

    #[cfg(feature = "tracing")]
    tracing::trace!(changes = changes.len(), "diff computed");
}

fn compute_dirty_changes(
    old: &Buffer,
    new: &Buffer,
    changes: &mut Vec<(u16, u16)>,
    tile_builder: &mut TileDiffBuilder,
    tile_config: &TileDiffConfig,
    tile_stats_out: &mut Option<TileDiffStats>,
) {
    assert_eq!(old.width(), new.width(), "buffer widths must match");
    assert_eq!(old.height(), new.height(), "buffer heights must match");

    let width = old.width();
    let height = old.height();
    let w = width as usize;

    changes.clear();
    reserve_changes_capacity(width, height, changes);

    let old_cells = old.cells();
    let new_cells = new.cells();
    let dirty = new.dirty_rows();

    *tile_stats_out = None;
    let tile_build = tile_builder.build_from_buffer(tile_config, new);

    if let TileDiffBuild::UseTiles(plan) = tile_build {
        *tile_stats_out = Some(plan.stats);
        let tile_w = plan.params.tile_w as usize;
        let tile_h = plan.params.tile_h as usize;
        let tiles_x = plan.params.tiles_x;
        let dirty_tiles = plan.dirty_tiles;

        for y in 0..height {
            if !dirty[y as usize] {
                continue;
            }

            let row_start = y as usize * w;
            let old_row = &old_cells[row_start..row_start + w];
            let new_row = &new_cells[row_start..row_start + w];

            if old_row == new_row {
                continue;
            }

            let tile_y = y as usize / tile_h;
            let tile_row_base = tile_y * tiles_x;
            debug_assert!(tile_row_base + tiles_x <= dirty_tiles.len());

            let span_row = new.dirty_span_row(y);
            if let Some(span_row) = span_row {
                if span_row.is_full() {
                    scan_row_tiles(
                        old_row,
                        new_row,
                        y,
                        w,
                        tile_w,
                        tiles_x,
                        tile_row_base,
                        dirty_tiles,
                        changes,
                    );
                    continue;
                }
                let spans = span_row.spans();
                if spans.is_empty() {
                    scan_row_tiles(
                        old_row,
                        new_row,
                        y,
                        w,
                        tile_w,
                        tiles_x,
                        tile_row_base,
                        dirty_tiles,
                        changes,
                    );
                    continue;
                }
                scan_row_tiles_spans(
                    old_row,
                    new_row,
                    y,
                    w,
                    tile_w,
                    tiles_x,
                    tile_row_base,
                    dirty_tiles,
                    spans,
                    changes,
                );
            } else {
                scan_row_tiles(
                    old_row,
                    new_row,
                    y,
                    w,
                    tile_w,
                    tiles_x,
                    tile_row_base,
                    dirty_tiles,
                    changes,
                );
            }
        }
        return;
    }

    if let TileDiffBuild::Fallback(stats) = tile_build {
        *tile_stats_out = Some(stats);
    }

    for y in 0..height {
        // Skip clean rows (the key optimization).
        if !dirty[y as usize] {
            continue;
        }

        let row_start = y as usize * w;
        let old_row = &old_cells[row_start..row_start + w];
        let new_row = &new_cells[row_start..row_start + w];

        // Even for dirty rows, row-skip fast path applies:
        // a row may be marked dirty but end up identical after compositing.
        if old_row == new_row {
            continue;
        }

        let span_row = new.dirty_span_row(y);
        if let Some(span_row) = span_row {
            if span_row.is_full() {
                scan_row_changes(old_row, new_row, y, changes);
                continue;
            }
            let spans = span_row.spans();
            if spans.is_empty() {
                scan_row_changes(old_row, new_row, y, changes);
                continue;
            }
            scan_row_changes_spans(old_row, new_row, y, spans, changes);
        } else {
            scan_row_changes(old_row, new_row, y, changes);
        }
    }
}

/// A contiguous run of changed cells on a single row.
///
/// Used by the presenter to emit efficient cursor positioning.
/// Instead of positioning for each cell, position once and emit the run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChangeRun {
    /// Row index.
    pub y: u16,
    /// Start column (inclusive).
    pub x0: u16,
    /// End column (inclusive).
    pub x1: u16,
}

impl ChangeRun {
    /// Create a new change run.
    #[inline]
    pub const fn new(y: u16, x0: u16, x1: u16) -> Self {
        debug_assert!(x0 <= x1);
        Self { y, x0, x1 }
    }

    /// Number of cells in this run.
    #[inline]
    pub const fn len(&self) -> usize {
        self.x1.saturating_sub(self.x0) as usize + 1
    }

    /// Check if this run is empty (should never happen in practice).
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.x1 < self.x0
    }
}

/// The diff between two buffers.
///
/// Contains the list of (x, y) positions where cells differ.
#[derive(Debug, Clone, Default)]
pub struct BufferDiff {
    /// List of changed cell positions (x, y).
    changes: Vec<(u16, u16)>,
    /// Reusable tile builder for SAT-based diff skipping.
    tile_builder: TileDiffBuilder,
    /// Tile diff configuration (thresholds + sizes).
    tile_config: TileDiffConfig,
    /// Last tile diagnostics from a dirty diff pass.
    last_tile_stats: Option<TileDiffStats>,
}

impl BufferDiff {
    /// Create an empty diff.
    pub fn new() -> Self {
        Self {
            changes: Vec::new(),
            tile_builder: TileDiffBuilder::default(),
            tile_config: TileDiffConfig::default(),
            last_tile_stats: None,
        }
    }

    /// Create a diff with pre-allocated capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        let mut diff = Self::new();
        diff.changes = Vec::with_capacity(capacity);
        diff
    }

    /// Create a diff that marks every cell as changed.
    ///
    /// Useful for full-screen redraws where the previous buffer is unknown
    /// (e.g., after resize or initial present).
    pub fn full(width: u16, height: u16) -> Self {
        if width == 0 || height == 0 {
            return Self::new();
        }

        let total = width as usize * height as usize;
        let mut changes = Vec::with_capacity(total);
        for y in 0..height {
            for x in 0..width {
                changes.push((x, y));
            }
        }
        let mut diff = Self::new();
        diff.changes = changes;
        diff
    }

    /// Compute the diff between two buffers.
    ///
    /// Uses row-major scan for cache efficiency. Both buffers must have
    /// the same dimensions.
    ///
    /// # Optimizations
    ///
    /// - **Row-skip fast path**: unchanged rows are detected via slice
    ///   equality and skipped entirely. For typical UI updates where most
    ///   rows are static, this eliminates the majority of per-cell work.
    /// - **Blockwise row scan**: rows with sparse edits are scanned in
    ///   coarse blocks, skipping unchanged blocks and only diving into
    ///   the blocks that differ.
    /// - **Direct slice iteration**: row slices are computed once per row
    ///   instead of calling `get_unchecked(x, y)` per cell, eliminating
    ///   repeated `y * width + x` index arithmetic.
    /// - **Branchless cell comparison**: `bits_eq` uses bitwise AND to
    ///   avoid branch mispredictions in the inner loop.
    ///
    /// # Panics
    ///
    /// Debug-asserts that both buffers have identical dimensions.
    pub fn compute(old: &Buffer, new: &Buffer) -> Self {
        let mut diff = Self::new();
        diff.compute_into(old, new);
        diff
    }

    /// Compute the diff into an existing buffer to reuse allocation.
    pub fn compute_into(&mut self, old: &Buffer, new: &Buffer) {
        self.last_tile_stats = None;
        compute_changes(old, new, &mut self.changes);
    }

    /// Compute the diff between two buffers using dirty-row hints.
    ///
    /// Only rows marked dirty in `new` are compared cell-by-cell.
    /// Clean rows are skipped entirely (O(1) per clean row).
    ///
    /// This is sound provided the dirty tracking invariant holds:
    /// for all y, if any cell in row y changed, then `new.is_row_dirty(y)`.
    ///
    /// Falls back to full comparison for rows marked dirty, so false positives
    /// (marking a row dirty when it didn't actually change) are safe — they
    /// only cost the per-cell scan for that row.
    pub fn compute_dirty(old: &Buffer, new: &Buffer) -> Self {
        let mut diff = Self::new();
        diff.compute_dirty_into(old, new);
        diff
    }

    /// Compute the dirty-row diff into an existing buffer to reuse allocation.
    pub fn compute_dirty_into(&mut self, old: &Buffer, new: &Buffer) {
        compute_dirty_changes(
            old,
            new,
            &mut self.changes,
            &mut self.tile_builder,
            &self.tile_config,
            &mut self.last_tile_stats,
        );
    }

    /// Compute the diff with a certificate-based skip hint.
    ///
    /// The caller (typically the runtime loop) evaluates a render certificate
    /// and passes the result as a `DiffSkipHint`. This method shortcuts the
    /// diff computation when the certificate allows it:
    ///
    /// - `FullDiff`: performs the standard dirty-diff computation.
    /// - `SkipDiff`: clears changes (no work to present). The caller must
    ///   ensure that old and new buffers are identical when issuing this hint.
    /// - `NarrowToRows(rows)`: only diffs the specified rows, skipping all
    ///   others even if marked dirty. Useful when the certificate identifies
    ///   exactly which rows changed.
    ///
    /// # Safety invariant
    ///
    /// Issuing `SkipDiff` when buffers differ produces stale frames.
    /// The certificate evaluator must guarantee correctness — this method
    /// trusts the hint without verification.
    ///
    /// # Tracing
    ///
    /// Emits a tracing event when a skip or narrow is applied, including
    /// the hint type and resulting change count for evidence logging.
    pub fn compute_certified_into(&mut self, old: &Buffer, new: &Buffer, hint: DiffSkipHint) {
        match hint {
            DiffSkipHint::FullDiff => {
                // Standard path — no certificate benefit
                self.compute_dirty_into(old, new);
            }
            DiffSkipHint::SkipDiff => {
                // Certificate guarantees buffers are identical — skip all work
                self.changes.clear();
                self.last_tile_stats = None;
                #[cfg(feature = "tracing")]
                tracing::debug!(
                    event = "diff_skip_certified",
                    hint = "skip_diff",
                    changes = 0,
                );
            }
            DiffSkipHint::NarrowToRows(ref rows) => {
                // Only diff the specified rows
                self.changes.clear();
                self.last_tile_stats = None;

                let w = old.width();
                let h = old.height();
                debug_assert_eq!(w, new.width());
                debug_assert_eq!(h, new.height());

                let old_cells = old.cells();
                let new_cells = new.cells();
                let stride = w as usize;

                for &row in rows {
                    if row >= h {
                        continue;
                    }
                    let start = row as usize * stride;
                    let end = start + stride;
                    if end > old_cells.len() || end > new_cells.len() {
                        continue;
                    }
                    let old_row = &old_cells[start..end];
                    let new_row = &new_cells[start..end];
                    if old_row == new_row {
                        continue;
                    }
                    for (x, (o, n)) in old_row.iter().zip(new_row.iter()).enumerate() {
                        if !o.bits_eq(n) {
                            self.changes.push((x as u16, row));
                        }
                    }
                }

                #[cfg(feature = "tracing")]
                tracing::debug!(
                    event = "diff_narrow_certified",
                    hint = "narrow_to_rows",
                    rows_checked = rows.len(),
                    changes = self.changes.len(),
                );
            }
        }
    }

    /// Populate the diff with all cells (full redraw) reusing existing capacity.
    pub fn fill_full(&mut self, width: u16, height: u16) {
        self.changes.clear();
        let total = width as usize * height as usize;
        if self.changes.capacity() < total {
            self.changes.reserve(total - self.changes.len());
        }
        for y in 0..height {
            for x in 0..width {
                self.changes.push((x, y));
            }
        }
    }

    /// Number of changed cells.
    #[inline]
    pub fn len(&self) -> usize {
        self.changes.len()
    }

    /// Check if no cells changed.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.changes.is_empty()
    }

    /// Get the list of changed positions.
    #[inline]
    pub fn changes(&self) -> &[(u16, u16)] {
        &self.changes
    }

    /// Access the last tile diagnostics from a dirty diff pass.
    #[inline]
    pub fn last_tile_stats(&self) -> Option<TileDiffStats> {
        self.last_tile_stats
    }

    /// Mutably access tile diff configuration.
    #[inline]
    pub fn tile_config_mut(&mut self) -> &mut TileDiffConfig {
        &mut self.tile_config
    }

    /// Convert point changes into contiguous runs.
    ///
    /// Consecutive x positions on the same row are coalesced into a single run.
    /// This enables efficient cursor positioning in the presenter.
    pub fn runs(&self) -> Vec<ChangeRun> {
        #[cfg(feature = "tracing")]
        let _span = tracing::debug_span!("diff_runs", changes = self.changes.len());
        #[cfg(feature = "tracing")]
        let _guard = _span.enter();

        if self.changes.is_empty() {
            return Vec::new();
        }

        // Changes are already sorted by (y, x) from row-major scan
        // so we don't need to sort again.
        let sorted = &self.changes;
        let len = sorted.len();

        // Worst case: every change is isolated, so runs == changes.
        // Pre-alloc to avoid repeated growth in hot paths.
        let mut runs = Vec::with_capacity(len);

        let mut i = 0;

        while i < len {
            let (x0, y) = sorted[i];
            let mut x1 = x0;
            i += 1;

            // Coalesce consecutive x positions on the same row
            while i < len {
                let (x, yy) = sorted[i];
                if yy != y || x != x1.saturating_add(1) {
                    break;
                }
                x1 = x;
                i += 1;
            }

            runs.push(ChangeRun::new(y, x0, x1));
        }

        #[cfg(feature = "tracing")]
        tracing::trace!(run_count = runs.len(), "runs coalesced");

        runs
    }

    /// Like `runs()` but writes into a caller-provided buffer, avoiding
    /// per-frame allocation when the buffer is reused across frames.
    pub fn runs_into(&self, out: &mut Vec<ChangeRun>) {
        out.clear();

        #[cfg(feature = "tracing")]
        let _span = tracing::debug_span!("diff_runs_into", changes = self.changes.len());
        #[cfg(feature = "tracing")]
        let _guard = _span.enter();

        if self.changes.is_empty() {
            return;
        }

        let sorted = &self.changes;
        let len = sorted.len();
        let mut i = 0;

        while i < len {
            let (x0, y) = sorted[i];
            let mut x1 = x0;
            i += 1;

            while i < len {
                let (x, yy) = sorted[i];
                if yy != y || x != x1.saturating_add(1) {
                    break;
                }
                x1 = x;
                i += 1;
            }

            out.push(ChangeRun::new(y, x0, x1));
        }

        #[cfg(feature = "tracing")]
        tracing::trace!(run_count = out.len(), "runs coalesced (reuse)");
    }

    /// Iterate over changed positions.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = (u16, u16)> + '_ {
        self.changes.iter().copied()
    }

    /// Clear the diff, removing all recorded changes.
    pub fn clear(&mut self) {
        self.changes.clear();
    }
}

#[cfg(test)]
mod tests {
    fn is_coverage_run() -> bool {
        if let Ok(value) = std::env::var("FTUI_COVERAGE") {
            let value = value.to_ascii_lowercase();
            if matches!(value.as_str(), "1" | "true" | "yes") {
                return true;
            }
            if matches!(value.as_str(), "0" | "false" | "no") {
                return false;
            }
        }
        std::env::var("LLVM_PROFILE_FILE").is_ok() || std::env::var("CARGO_LLVM_COV").is_ok()
    }
    use super::*;
    use crate::cell::{Cell, PackedRgba};

    #[test]
    fn scan_row_changes_range_reports_late_change_after_equal_quad() {
        let old = vec![Cell::default(); 8];
        let mut new = old.clone();
        let mut changes = Vec::new();

        new[7] = Cell::from_char('X');
        scan_row_changes_range(&old, &new, 4, 10, &mut changes);

        assert_eq!(changes, vec![(17, 4)]);
    }

    #[test]
    fn empty_diff_when_buffers_identical() {
        let buf1 = Buffer::new(10, 10);
        let buf2 = Buffer::new(10, 10);
        let diff = BufferDiff::compute(&buf1, &buf2);

        assert!(diff.is_empty());
        assert_eq!(diff.len(), 0);
    }

    #[test]
    fn full_diff_marks_all_cells() {
        let diff = BufferDiff::full(3, 2);
        assert_eq!(diff.len(), 6);
        assert_eq!(diff.changes()[0], (0, 0));
        assert_eq!(diff.changes()[5], (2, 1));
    }

    #[test]
    fn single_cell_change_detected() {
        let old = Buffer::new(10, 10);
        let mut new = Buffer::new(10, 10);

        new.set_raw(5, 5, Cell::from_char('X'));
        let diff = BufferDiff::compute(&old, &new);

        assert_eq!(diff.len(), 1);
        assert_eq!(diff.changes(), &[(5, 5)]);
    }

    #[test]
    fn dirty_row_false_positive_skipped() {
        let old = Buffer::new(8, 2);
        let mut new = old.clone();

        // Clear initial dirty state to isolate this row.
        new.clear_dirty();
        // Mark row 0 dirty without changing content.
        new.set_raw(2, 0, Cell::default());

        let diff = BufferDiff::compute_dirty(&old, &new);
        assert!(
            diff.is_empty(),
            "dirty row with no changes should be skipped"
        );
    }

    #[test]
    fn multiple_scattered_changes_detected() {
        let old = Buffer::new(10, 10);
        let mut new = Buffer::new(10, 10);

        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(9, 9, Cell::from_char('B'));
        new.set_raw(5, 3, Cell::from_char('C'));

        let diff = BufferDiff::compute(&old, &new);

        assert_eq!(diff.len(), 3);
        // Sorted by row-major order: (0,0), (5,3), (9,9)
        let changes = diff.changes();
        assert!(changes.contains(&(0, 0)));
        assert!(changes.contains(&(9, 9)));
        assert!(changes.contains(&(5, 3)));
    }

    #[test]
    fn runs_coalesces_adjacent_cells() {
        let old = Buffer::new(10, 10);
        let mut new = Buffer::new(10, 10);

        // Three adjacent cells on row 5
        new.set_raw(3, 5, Cell::from_char('A'));
        new.set_raw(4, 5, Cell::from_char('B'));
        new.set_raw(5, 5, Cell::from_char('C'));

        let diff = BufferDiff::compute(&old, &new);
        let runs = diff.runs();

        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].y, 5);
        assert_eq!(runs[0].x0, 3);
        assert_eq!(runs[0].x1, 5);
        assert_eq!(runs[0].len(), 3);
    }

    #[test]
    fn runs_handles_gaps_correctly() {
        let old = Buffer::new(10, 10);
        let mut new = Buffer::new(10, 10);

        // Two groups with a gap
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(1, 0, Cell::from_char('B'));
        // gap at x=2
        new.set_raw(3, 0, Cell::from_char('C'));
        new.set_raw(4, 0, Cell::from_char('D'));

        let diff = BufferDiff::compute(&old, &new);
        let runs = diff.runs();

        assert_eq!(runs.len(), 2);

        assert_eq!(runs[0].y, 0);
        assert_eq!(runs[0].x0, 0);
        assert_eq!(runs[0].x1, 1);

        assert_eq!(runs[1].y, 0);
        assert_eq!(runs[1].x0, 3);
        assert_eq!(runs[1].x1, 4);
    }

    #[test]
    fn runs_handles_max_column_without_overflow() {
        let mut diff = BufferDiff::new();
        diff.changes = vec![(u16::MAX, 0)];

        let runs = diff.runs();

        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0], ChangeRun::new(0, u16::MAX, u16::MAX));
    }

    #[test]
    fn runs_handles_multiple_rows() {
        let old = Buffer::new(10, 10);
        let mut new = Buffer::new(10, 10);

        // Changes on multiple rows
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(1, 0, Cell::from_char('B'));
        new.set_raw(5, 2, Cell::from_char('C'));
        new.set_raw(0, 5, Cell::from_char('D'));

        let diff = BufferDiff::compute(&old, &new);
        let runs = diff.runs();

        assert_eq!(runs.len(), 3);

        // Row 0: (0-1)
        assert_eq!(runs[0].y, 0);
        assert_eq!(runs[0].x0, 0);
        assert_eq!(runs[0].x1, 1);

        // Row 2: (5)
        assert_eq!(runs[1].y, 2);
        assert_eq!(runs[1].x0, 5);
        assert_eq!(runs[1].x1, 5);

        // Row 5: (0)
        assert_eq!(runs[2].y, 5);
        assert_eq!(runs[2].x0, 0);
        assert_eq!(runs[2].x1, 0);
    }

    #[test]
    fn empty_runs_from_empty_diff() {
        let diff = BufferDiff::new();
        let runs = diff.runs();
        assert!(runs.is_empty());
    }

    #[test]
    fn change_run_len() {
        let run = ChangeRun::new(0, 5, 10);
        assert_eq!(run.len(), 6);

        let single = ChangeRun::new(0, 5, 5);
        assert_eq!(single.len(), 1);
    }

    #[test]
    fn color_changes_detected() {
        let old = Buffer::new(10, 10);
        let mut new = Buffer::new(10, 10);

        // Same empty content but different color
        new.set_raw(5, 5, Cell::default().with_fg(PackedRgba::rgb(255, 0, 0)));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 1);
    }

    #[test]
    fn diff_iter() {
        let old = Buffer::new(5, 5);
        let mut new = Buffer::new(5, 5);
        new.set_raw(1, 1, Cell::from_char('X'));
        new.set_raw(2, 2, Cell::from_char('Y'));

        let diff = BufferDiff::compute(&old, &new);
        let positions: Vec<_> = diff.iter().collect();

        assert_eq!(positions.len(), 2);
        assert!(positions.contains(&(1, 1)));
        assert!(positions.contains(&(2, 2)));
    }

    #[test]
    fn diff_clear() {
        let old = Buffer::new(5, 5);
        let mut new = Buffer::new(5, 5);
        new.set_raw(1, 1, Cell::from_char('X'));

        let mut diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 1);

        diff.clear();
        assert!(diff.is_empty());
    }

    #[test]
    fn with_capacity() {
        let diff = BufferDiff::with_capacity(100);
        assert!(diff.is_empty());
    }

    #[test]
    fn full_buffer_change() {
        let old = Buffer::new(5, 5);
        let mut new = Buffer::new(5, 5);

        // Change every cell
        for y in 0..5 {
            for x in 0..5 {
                new.set_raw(x, y, Cell::from_char('#'));
            }
        }

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 25);

        // Should coalesce into 5 runs (one per row)
        let runs = diff.runs();
        assert_eq!(runs.len(), 5);

        for (i, run) in runs.iter().enumerate() {
            assert_eq!(run.y, i as u16);
            assert_eq!(run.x0, 0);
            assert_eq!(run.x1, 4);
            assert_eq!(run.len(), 5);
        }
    }

    #[test]
    fn row_major_order_preserved() {
        let old = Buffer::new(3, 3);
        let mut new = Buffer::new(3, 3);

        // Set cells in non-row-major order
        new.set_raw(2, 2, Cell::from_char('C'));
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(1, 1, Cell::from_char('B'));

        let diff = BufferDiff::compute(&old, &new);

        // Row-major scan should produce (0,0), (1,1), (2,2)
        let changes = diff.changes();
        assert_eq!(changes[0], (0, 0));
        assert_eq!(changes[1], (1, 1));
        assert_eq!(changes[2], (2, 2));
    }

    #[test]
    fn blockwise_scan_preserves_sparse_row_changes() {
        let old = Buffer::new(64, 2);
        let mut new = old.clone();

        new.set_raw(1, 0, Cell::from_char('A'));
        new.set_raw(33, 0, Cell::from_char('B'));
        new.set_raw(62, 1, Cell::from_char('C'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.changes(), &[(1, 0), (33, 0), (62, 1)]);
    }

    #[test]
    fn rows_with_no_changes_are_skipped() {
        let old = Buffer::new(4, 3);
        let mut new = old.clone();

        new.set_raw(1, 1, Cell::from_char('X'));
        new.set_raw(3, 1, Cell::from_char('Y'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 2);
        assert!(diff.changes().iter().all(|&(_, y)| y == 1));
    }

    #[test]
    fn clear_retains_capacity_for_reuse() {
        let mut diff = BufferDiff::with_capacity(16);
        diff.changes.extend_from_slice(&[(0, 0), (1, 0), (2, 0)]);
        let capacity = diff.changes.capacity();

        diff.clear();

        assert!(diff.is_empty());
        assert!(diff.changes.capacity() >= capacity);
    }

    #[test]
    #[should_panic(expected = "buffer widths must match")]
    fn compute_panics_on_width_mismatch() {
        let old = Buffer::new(5, 5);
        let new = Buffer::new(4, 5);
        let _ = BufferDiff::compute(&old, &new);
    }

    // =========================================================================
    // Block-based Row Scan Tests (bd-4kq0.1.2)
    // =========================================================================

    #[test]
    fn block_scan_alignment_exact_block() {
        // Width = 4 (exactly one block, no remainder)
        let old = Buffer::new(4, 1);
        let mut new = Buffer::new(4, 1);
        new.set_raw(2, 0, Cell::from_char('X'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 1);
        assert_eq!(diff.changes(), &[(2, 0)]);
    }

    #[test]
    fn block_scan_alignment_remainder() {
        // Width = 7 (one full block + 3 remainder)
        let old = Buffer::new(7, 1);
        let mut new = Buffer::new(7, 1);
        // Change in full block part
        new.set_raw(1, 0, Cell::from_char('A'));
        // Change in remainder part
        new.set_raw(5, 0, Cell::from_char('B'));
        new.set_raw(6, 0, Cell::from_char('C'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 3);
        assert_eq!(diff.changes(), &[(1, 0), (5, 0), (6, 0)]);
    }

    #[test]
    fn block_scan_single_cell_row() {
        // Width = 1 (pure remainder, no full blocks)
        let old = Buffer::new(1, 1);
        let mut new = Buffer::new(1, 1);
        new.set_raw(0, 0, Cell::from_char('X'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 1);
        assert_eq!(diff.changes(), &[(0, 0)]);
    }

    #[test]
    fn block_scan_two_cell_row() {
        // Width = 2 (pure remainder)
        let old = Buffer::new(2, 1);
        let mut new = Buffer::new(2, 1);
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(1, 0, Cell::from_char('B'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 2);
        assert_eq!(diff.changes(), &[(0, 0), (1, 0)]);
    }

    #[test]
    fn block_scan_three_cell_row() {
        // Width = 3 (pure remainder)
        let old = Buffer::new(3, 1);
        let mut new = Buffer::new(3, 1);
        new.set_raw(2, 0, Cell::from_char('X'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 1);
        assert_eq!(diff.changes(), &[(2, 0)]);
    }

    #[test]
    fn block_scan_multiple_blocks_sparse() {
        // Width = 80 (20 full blocks), changes scattered across blocks
        let old = Buffer::new(80, 1);
        let mut new = Buffer::new(80, 1);

        // One change per block in every other block
        for block in (0..20).step_by(2) {
            let x = (block * 4 + 1) as u16;
            new.set_raw(x, 0, Cell::from_char('X'));
        }

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 10);
        assert_eq!(
            diff.changes(),
            &[
                (1, 0),
                (9, 0),
                (17, 0),
                (25, 0),
                (33, 0),
                (41, 0),
                (49, 0),
                (57, 0),
                (65, 0),
                (73, 0)
            ]
        );
    }

    #[test]
    fn block_scan_full_block_unchanged_skip() {
        // Verify blocks with no changes are skipped efficiently
        let old = Buffer::new(20, 1);
        let mut new = Buffer::new(20, 1);

        // Only change one cell in the last block
        new.set_raw(19, 0, Cell::from_char('Z'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 1);
        assert_eq!(diff.changes(), &[(19, 0)]);
    }

    #[test]
    fn block_scan_wide_row_all_changed() {
        // All cells changed in a wide row
        let old = Buffer::new(120, 1);
        let mut new = Buffer::new(120, 1);
        for x in 0..120 {
            new.set_raw(x, 0, Cell::from_char('#'));
        }

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 120);
    }

    #[test]
    fn perf_block_scan_vs_scalar_baseline() {
        // Verify that block scan works correctly on large buffers
        // and measure relative performance with structured diagnostics.
        use std::time::Instant;

        let width = 200u16;
        let height = 50u16;
        let old = Buffer::new(width, height);
        let mut new = Buffer::new(width, height);

        // ~10% cells changed
        for i in 0..1000 {
            let x = (i * 7 + 3) as u16 % width;
            let y = (i * 11 + 5) as u16 % height;
            let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
            new.set_raw(x, y, Cell::from_char(ch));
        }

        let iterations = 1000u32;
        let samples = std::env::var("FTUI_DIFF_BLOCK_SAMPLES")
            .ok()
            .and_then(|value| value.parse::<usize>().ok())
            .unwrap_or(50)
            .clamp(1, iterations as usize);
        let iters_per_sample = (iterations / samples as u32).max(1) as u64;

        let mut times_us = Vec::with_capacity(samples);
        let mut last_checksum = 0u64;

        for _ in 0..samples {
            let start = Instant::now();
            for _ in 0..iters_per_sample {
                let diff = BufferDiff::compute(&old, &new);
                assert!(!diff.is_empty());
                last_checksum = fnv1a_hash(diff.changes());
            }
            let elapsed = start.elapsed();
            let per_iter = (elapsed.as_micros() as u64) / iters_per_sample;
            times_us.push(per_iter);
        }

        times_us.sort_unstable();
        let len = times_us.len();
        let p50 = times_us[len / 2];
        let p95 = times_us[((len as f64 * 0.95) as usize).min(len.saturating_sub(1))];
        let p99 = times_us[((len as f64 * 0.99) as usize).min(len.saturating_sub(1))];
        let mean = times_us
            .iter()
            .copied()
            .map(|value| value as f64)
            .sum::<f64>()
            / len as f64;
        let variance = times_us
            .iter()
            .map(|value| {
                let delta = *value as f64 - mean;
                delta * delta
            })
            .sum::<f64>()
            / len as f64;

        // JSONL log line for perf diagnostics (captured by --nocapture/CI artifacts).
        eprintln!(
            "{{\"ts\":\"2026-02-04T00:00:00Z\",\"event\":\"block_scan_baseline\",\"width\":{},\"height\":{},\"samples\":{},\"iters_per_sample\":{},\"p50_us\":{},\"p95_us\":{},\"p99_us\":{},\"mean_us\":{:.2},\"variance_us\":{:.2},\"checksum\":\"0x{:016x}\"}}",
            width, height, samples, iters_per_sample, p50, p95, p99, mean, variance, last_checksum
        );

        // Perf tests are inherently noisy on shared runners (OS scheduling, IO, contention).
        // We enforce a strict median budget (typical performance) and a looser tail budget
        // to avoid flaking on incidental pauses.
        #[allow(unexpected_cfgs)]
        let p50_budget_us = if is_coverage_run() { 3_000u64 } else { 500u64 };
        #[allow(unexpected_cfgs)]
        let p95_budget_us = if is_coverage_run() {
            10_000u64
        } else {
            2_500u64
        };

        assert!(
            p50 <= p50_budget_us,
            "Diff too slow: p50={p50}µs (budget {p50_budget_us}µs) for {width}x{height}"
        );
        assert!(
            p95 <= p95_budget_us,
            "Diff tail too slow: p95={p95}µs (budget {p95_budget_us}µs) for {width}x{height}"
        );
    }
    // =========================================================================
    // Run Coalescing Invariants (bd-4kq0.1.3)
    // =========================================================================

    #[test]
    fn unit_run_coalescing_invariants() {
        // Verify runs preserve order, coverage, and contiguity for a
        // complex multi-row change pattern.
        let old = Buffer::new(80, 24);
        let mut new = Buffer::new(80, 24);

        // Row 0: two separate runs (0-2) and (10-12)
        for x in 0..=2 {
            new.set_raw(x, 0, Cell::from_char('A'));
        }
        for x in 10..=12 {
            new.set_raw(x, 0, Cell::from_char('B'));
        }
        // Row 5: single run (40-45)
        for x in 40..=45 {
            new.set_raw(x, 5, Cell::from_char('C'));
        }
        // Row 23: single cell at end
        new.set_raw(79, 23, Cell::from_char('Z'));

        let diff = BufferDiff::compute(&old, &new);
        let runs = diff.runs();

        // Invariant 1: runs are sorted by (y, x0)
        for w in runs.windows(2) {
            assert!(
                (w[0].y, w[0].x0) < (w[1].y, w[1].x0),
                "runs must be sorted: {:?} should precede {:?}",
                w[0],
                w[1]
            );
        }

        // Invariant 2: total cells in runs == diff.len()
        let total_cells: usize = runs.iter().map(|r| r.len()).sum();
        assert_eq!(
            total_cells,
            diff.len(),
            "runs must cover all changes exactly"
        );

        // Invariant 3: no two runs on the same row are adjacent (should have merged)
        for w in runs.windows(2) {
            if w[0].y == w[1].y {
                assert!(
                    w[1].x0 > w[0].x1.saturating_add(1),
                    "adjacent runs on same row should be merged: {:?} and {:?}",
                    w[0],
                    w[1]
                );
            }
        }

        // Invariant 4: expected structure
        assert_eq!(runs.len(), 4);
        assert_eq!(runs[0], ChangeRun::new(0, 0, 2));
        assert_eq!(runs[1], ChangeRun::new(0, 10, 12));
        assert_eq!(runs[2], ChangeRun::new(5, 40, 45));
        assert_eq!(runs[3], ChangeRun::new(23, 79, 79));
    }

    // =========================================================================
    // Golden Output Fixtures (bd-4kq0.1.3)
    // =========================================================================

    /// FNV-1a hash for deterministic checksums (no external dependency).
    fn fnv1a_hash(data: &[(u16, u16)]) -> u64 {
        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
        for &(x, y) in data {
            for byte in x.to_le_bytes().iter().chain(y.to_le_bytes().iter()) {
                hash ^= *byte as u64;
                hash = hash.wrapping_mul(0x0100_0000_01b3);
            }
        }
        hash
    }

    /// Build a canonical "dashboard-like" scene: header row, status bar,
    /// scattered content cells.
    fn build_golden_scene(width: u16, height: u16, seed: u64) -> Buffer {
        let mut buf = Buffer::new(width, height);
        let mut rng = seed;

        // Header row: all cells set
        for x in 0..width {
            buf.set_raw(x, 0, Cell::from_char('='));
        }

        // Status bar (last row)
        for x in 0..width {
            buf.set_raw(x, height - 1, Cell::from_char('-'));
        }

        // Scattered content using simple LCG
        let count = (width as u64 * height as u64 / 10).max(5);
        for _ in 0..count {
            rng = rng.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
            let x = ((rng >> 16) as u16) % width;
            rng = rng.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
            let y = ((rng >> 16) as u16) % height;
            rng = rng.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
            let ch = char::from_u32('A' as u32 + (rng % 26) as u32).unwrap();
            buf.set_raw(x, y, Cell::from_char(ch));
        }

        buf
    }

    #[test]
    fn golden_diff_80x24() {
        let old = Buffer::new(80, 24);
        let new = build_golden_scene(80, 24, 0x000D_01DE_5EED_0001);

        let diff = BufferDiff::compute(&old, &new);
        let checksum = fnv1a_hash(diff.changes());

        // Verify determinism: same inputs → same output
        let diff2 = BufferDiff::compute(&old, &new);
        assert_eq!(
            fnv1a_hash(diff2.changes()),
            checksum,
            "diff must be deterministic"
        );

        // Sanity: scene has header + status + scattered content
        assert!(
            diff.len() >= 160,
            "80x24 golden scene should have at least 160 changes (header+status), got {}",
            diff.len()
        );

        let runs = diff.runs();
        // Header and status rows should each be one run
        assert_eq!(runs[0].y, 0, "first run should be header row");
        assert_eq!(runs[0].x0, 0);
        assert_eq!(runs[0].x1, 79);
        assert!(
            runs.last().unwrap().y == 23,
            "last row should contain status bar"
        );
    }

    #[test]
    fn golden_diff_120x40() {
        let old = Buffer::new(120, 40);
        let new = build_golden_scene(120, 40, 0x000D_01DE_5EED_0002);

        let diff = BufferDiff::compute(&old, &new);
        let checksum = fnv1a_hash(diff.changes());

        // Determinism
        let diff2 = BufferDiff::compute(&old, &new);
        assert_eq!(fnv1a_hash(diff2.changes()), checksum);

        // Sanity
        assert!(
            diff.len() >= 240,
            "120x40 golden scene should have >=240 changes, got {}",
            diff.len()
        );

        // Dirty diff must match
        let dirty = BufferDiff::compute_dirty(&old, &new);
        assert_eq!(
            fnv1a_hash(dirty.changes()),
            checksum,
            "dirty diff must produce identical changes"
        );
    }

    #[test]
    fn golden_sparse_update() {
        // Start from a populated scene, apply a small update
        let old = build_golden_scene(80, 24, 0x000D_01DE_5EED_0003);
        let mut new = old.clone();

        // Apply 5 deterministic changes
        new.set_raw(10, 5, Cell::from_char('!'));
        new.set_raw(11, 5, Cell::from_char('@'));
        new.set_raw(40, 12, Cell::from_char('#'));
        new.set_raw(70, 20, Cell::from_char('$'));
        new.set_raw(0, 23, Cell::from_char('%'));

        let diff = BufferDiff::compute(&old, &new);
        let checksum = fnv1a_hash(diff.changes());

        // Determinism
        let diff2 = BufferDiff::compute(&old, &new);
        assert_eq!(fnv1a_hash(diff2.changes()), checksum);

        // Exactly 5 changes (or fewer if some cells happened to already have that value)
        assert!(
            diff.len() <= 5,
            "sparse update should have <=5 changes, got {}",
            diff.len()
        );
        assert!(
            diff.len() >= 3,
            "sparse update should have >=3 changes, got {}",
            diff.len()
        );
    }

    // =========================================================================
    // E2E Random Scene Replay (bd-4kq0.1.3)
    // =========================================================================

    #[test]
    fn e2e_random_scene_replay() {
        // 10 frames of seeded scene evolution, verify checksums are
        // deterministic across replays and dirty/full paths agree.
        let width = 80u16;
        let height = 24u16;
        let base_seed: u64 = 0x5C3E_E3E1_A442u64;

        let mut checksums = Vec::new();

        for frame in 0..10u64 {
            let seed = base_seed.wrapping_add(frame.wrapping_mul(0x9E37_79B9_7F4A_7C15));
            let old = build_golden_scene(width, height, seed);
            let new = build_golden_scene(width, height, seed.wrapping_add(1));

            let diff = BufferDiff::compute(&old, &new);
            let dirty_diff = BufferDiff::compute_dirty(&old, &new);

            // Full and dirty must agree
            assert_eq!(
                diff.changes(),
                dirty_diff.changes(),
                "frame {frame}: dirty diff must match full diff"
            );

            checksums.push(fnv1a_hash(diff.changes()));
        }

        // Replay: same seeds must produce identical checksums
        for frame in 0..10u64 {
            let seed = base_seed.wrapping_add(frame.wrapping_mul(0x9E37_79B9_7F4A_7C15));
            let old = build_golden_scene(width, height, seed);
            let new = build_golden_scene(width, height, seed.wrapping_add(1));

            let diff = BufferDiff::compute(&old, &new);
            assert_eq!(
                fnv1a_hash(diff.changes()),
                checksums[frame as usize],
                "frame {frame}: checksum mismatch on replay"
            );
        }
    }

    // =========================================================================
    // Perf Microbench with JSONL (bd-4kq0.1.3)
    // =========================================================================

    #[test]
    fn perf_diff_microbench() {
        use std::time::Instant;

        let scenarios: &[(u16, u16, &str, u64)] = &[
            (80, 24, "full_frame", 0xBE4C_0001u64),
            (80, 24, "sparse_update", 0xBE4C_0002u64),
            (120, 40, "full_frame", 0xBE4C_0003u64),
            (120, 40, "sparse_update", 0xBE4C_0004u64),
        ];

        let iterations = std::env::var("FTUI_DIFF_BENCH_ITERS")
            .ok()
            .and_then(|value| value.parse::<u32>().ok())
            .unwrap_or(50u32);

        for &(width, height, scene_type, seed) in scenarios {
            let old = Buffer::new(width, height);
            let new = match scene_type {
                "full_frame" => build_golden_scene(width, height, seed),
                "sparse_update" => {
                    let mut buf = old.clone();
                    buf.set_raw(10, 5, Cell::from_char('!'));
                    buf.set_raw(40, 12, Cell::from_char('#'));
                    buf.set_raw(70 % width, 20 % height, Cell::from_char('$'));
                    buf
                }
                _ => unreachable!(),
            };

            let mut times_us = Vec::with_capacity(iterations as usize);
            let mut last_changes = 0usize;
            let mut last_runs = 0usize;
            let mut last_checksum = 0u64;

            for _ in 0..iterations {
                let start = Instant::now();
                let diff = BufferDiff::compute(&old, &new);
                let runs = diff.runs();
                let elapsed = start.elapsed();

                last_changes = diff.len();
                last_runs = runs.len();
                last_checksum = fnv1a_hash(diff.changes());
                times_us.push(elapsed.as_micros() as u64);
            }

            times_us.sort();
            let len = times_us.len();
            let p50 = times_us[len / 2];
            let p95 = times_us[((len as f64 * 0.95) as usize).min(len.saturating_sub(1))];
            let p99 = times_us[((len as f64 * 0.99) as usize).min(len.saturating_sub(1))];

            // JSONL log line (captured by --nocapture or CI artifact)
            eprintln!(
                "{{\"ts\":\"2026-02-03T00:00:00Z\",\"seed\":{},\"width\":{},\"height\":{},\"scene\":\"{}\",\"changes\":{},\"runs\":{},\"p50_us\":{},\"p95_us\":{},\"p99_us\":{},\"checksum\":\"0x{:016x}\"}}",
                seed,
                width,
                height,
                scene_type,
                last_changes,
                last_runs,
                p50,
                p95,
                p99,
                last_checksum
            );

            // Budget: full 80x24 diff should be < 100µs at p95
            // Budget: full 120x40 diff should be < 200µs at p95
            let budget_us = match (width, height) {
                (80, 24) => 500,   // generous for CI variance
                (120, 40) => 1000, // generous for CI variance
                _ => 2000,
            };

            // Checksum must be identical across all iterations (determinism)
            for _ in 0..3 {
                let diff = BufferDiff::compute(&old, &new);
                assert_eq!(
                    fnv1a_hash(diff.changes()),
                    last_checksum,
                    "diff must be deterministic"
                );
            }

            // Soft budget assertion (warn but don't fail on slow CI)
            if p95 > budget_us {
                eprintln!(
                    "WARN: {scene_type} {width}x{height} p95={p95}µs exceeds budget {budget_us}µs"
                );
            }
        }
    }

    // =========================================================================
    // Dirty vs Full Diff Regression Gate (bd-3e1t.1.6)
    // =========================================================================

    #[test]
    fn perf_dirty_diff_large_screen_regression() {
        use std::time::Instant;

        let iterations = std::env::var("FTUI_DIFF_BENCH_ITERS")
            .ok()
            .and_then(|value| value.parse::<u32>().ok())
            .unwrap_or(50u32);

        let max_slowdown = std::env::var("FTUI_DIRTY_DIFF_MAX_SLOWDOWN")
            .ok()
            .and_then(|value| value.parse::<f64>().ok())
            .unwrap_or(2.0);

        let cases: &[(u16, u16, &str, f64)] = &[
            (200, 60, "sparse_5pct", 5.0),
            (240, 80, "sparse_5pct", 5.0),
            (200, 60, "single_row", 0.0),
            (240, 80, "single_row", 0.0),
        ];

        for &(width, height, pattern, pct) in cases {
            let old = Buffer::new(width, height);
            let mut new = old.clone();

            if pattern == "single_row" {
                for x in 0..width {
                    new.set_raw(x, 0, Cell::from_char('X'));
                }
            } else {
                let total = width as usize * height as usize;
                let to_change = ((total as f64) * pct / 100.0) as usize;
                for i in 0..to_change {
                    let x = (i * 7 + 3) as u16 % width;
                    let y = (i * 11 + 5) as u16 % height;
                    let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
                    new.set_raw(x, y, Cell::from_char(ch));
                }
            }

            // Sanity: dirty and full diffs must agree.
            let full = BufferDiff::compute(&old, &new);
            let dirty = BufferDiff::compute_dirty(&old, &new);
            let change_count = full.len();
            let dirty_rows = new.dirty_row_count();
            assert_eq!(
                full.changes(),
                dirty.changes(),
                "dirty diff must match full diff for {width}x{height} {pattern}"
            );

            let mut full_times = Vec::with_capacity(iterations as usize);
            let mut dirty_times = Vec::with_capacity(iterations as usize);

            for _ in 0..iterations {
                let start = Instant::now();
                let diff = BufferDiff::compute(&old, &new);
                std::hint::black_box(diff.len());
                full_times.push(start.elapsed().as_micros() as u64);

                let start = Instant::now();
                let diff = BufferDiff::compute_dirty(&old, &new);
                std::hint::black_box(diff.len());
                dirty_times.push(start.elapsed().as_micros() as u64);
            }

            full_times.sort();
            dirty_times.sort();

            let len = full_times.len();
            let p50_idx = len / 2;
            let p95_idx = ((len as f64 * 0.95) as usize).min(len.saturating_sub(1));

            let full_p50 = full_times[p50_idx];
            let full_p95 = full_times[p95_idx];
            let dirty_p50 = dirty_times[p50_idx];
            let dirty_p95 = dirty_times[p95_idx];

            let denom = full_p50.max(1) as f64;
            let ratio = dirty_p50 as f64 / denom;

            eprintln!(
                "{{\"ts\":\"2026-02-03T00:00:00Z\",\"event\":\"diff_regression\",\"width\":{},\"height\":{},\"pattern\":\"{}\",\"iterations\":{},\"changes\":{},\"dirty_rows\":{},\"full_p50_us\":{},\"full_p95_us\":{},\"dirty_p50_us\":{},\"dirty_p95_us\":{},\"slowdown_ratio\":{:.3},\"max_slowdown\":{}}}",
                width,
                height,
                pattern,
                iterations,
                change_count,
                dirty_rows,
                full_p50,
                full_p95,
                dirty_p50,
                dirty_p95,
                ratio,
                max_slowdown
            );

            assert!(
                ratio <= max_slowdown,
                "dirty diff regression: {width}x{height} {pattern} ratio {ratio:.2} exceeds {max_slowdown}"
            );
        }
    }

    #[test]
    fn tile_diff_matches_compute_for_sparse_tiles() {
        let width = 200;
        let height = 60;
        let old = Buffer::new(width, height);
        let mut new = old.clone();

        new.clear_dirty();
        for x in 0..10u16 {
            new.set_raw(x, 0, Cell::from_char('X'));
        }

        let full = BufferDiff::compute(&old, &new);
        let dirty = BufferDiff::compute_dirty(&old, &new);

        assert_eq!(full.changes(), dirty.changes());
        let stats = dirty
            .last_tile_stats()
            .expect("tile stats should be recorded");
        assert!(
            stats.fallback.is_none(),
            "tile path should be used for sparse tiles"
        );
    }

    fn make_dirty_buffer(width: u16, height: u16, changes: &[(u16, u16, char)]) -> Buffer {
        let mut buffer = Buffer::new(width, height);
        buffer.clear_dirty();
        for &(x, y, ch) in changes {
            buffer.set_raw(x, y, Cell::from_char(ch));
        }
        buffer
    }

    fn tile_stats_for_config(old: &Buffer, new: &Buffer, config: TileDiffConfig) -> TileDiffStats {
        let mut diff = BufferDiff::new();
        *diff.tile_config_mut() = config;
        diff.compute_dirty_into(old, new);
        diff.last_tile_stats()
            .expect("tile stats should be recorded")
    }

    #[test]
    fn tile_fallback_disabled_when_config_off() {
        let width = 64;
        let height = 32;
        let old = Buffer::new(width, height);
        let new = make_dirty_buffer(width, height, &[(0, 0, 'X')]);

        let config = TileDiffConfig {
            enabled: false,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 1.1,
            dense_tile_ratio: 1.1,
            max_tiles: usize::MAX,
            ..Default::default()
        };

        let stats = tile_stats_for_config(&old, &new, config);
        assert_eq!(stats.fallback, Some(TileDiffFallback::Disabled));
    }

    #[test]
    fn tile_fallback_small_screen_when_below_threshold() {
        let width = 64;
        let height = 32;
        let old = Buffer::new(width, height);
        let new = make_dirty_buffer(width, height, &[(1, 2, 'Y')]);

        let config = TileDiffConfig {
            enabled: true,
            min_cells_for_tiles: width as usize * height as usize + 1,
            dense_cell_ratio: 1.1,
            dense_tile_ratio: 1.1,
            max_tiles: usize::MAX,
            ..Default::default()
        };

        let stats = tile_stats_for_config(&old, &new, config);
        assert_eq!(stats.fallback, Some(TileDiffFallback::SmallScreen));
    }

    #[test]
    fn tile_fallback_too_many_tiles_when_budget_exceeded() {
        let width = 64;
        let height = 64;
        let old = Buffer::new(width, height);
        let new = make_dirty_buffer(width, height, &[(2, 3, 'Z')]);

        let config = TileDiffConfig {
            enabled: true,
            tile_w: 8,
            tile_h: 8,
            skip_clean_rows: true,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 1.1,
            dense_tile_ratio: 1.1,
            max_tiles: 4,
        };

        let stats = tile_stats_for_config(&old, &new, config);
        assert_eq!(stats.fallback, Some(TileDiffFallback::TooManyTiles));
    }

    #[test]
    fn tile_fallback_dense_tiles_when_ratio_exceeded() {
        let width = 64;
        let height = 32;
        let old = Buffer::new(width, height);
        let new = make_dirty_buffer(width, height, &[(0, 0, 'A'), (24, 0, 'B')]);

        let config = TileDiffConfig {
            enabled: true,
            tile_w: 8,
            tile_h: 8,
            skip_clean_rows: true,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 1.1,
            dense_tile_ratio: 0.05,
            max_tiles: usize::MAX / 4,
        };

        let stats = tile_stats_for_config(&old, &new, config);
        assert_eq!(stats.fallback, Some(TileDiffFallback::DenseTiles));
    }

    #[test]
    fn tile_builder_skips_clean_rows_when_enabled() {
        let width = 200;
        let height = 60;
        let old = Buffer::new(width, height);
        let mut new = old.clone();
        new.clear_dirty();
        new.set_raw(3, 0, Cell::from_char('X'));
        new.set_raw(4, 10, Cell::from_char('Y'));

        let base = TileDiffConfig {
            enabled: true,
            tile_w: 16,
            tile_h: 8,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 1.1,
            dense_tile_ratio: 1.1,
            max_tiles: usize::MAX,
            ..Default::default()
        };
        let config_full = TileDiffConfig {
            skip_clean_rows: false,
            ..base.clone()
        };
        let config_skip = TileDiffConfig {
            skip_clean_rows: true,
            ..base
        };

        let stats_full = tile_stats_for_config(&old, &new, config_full);
        let stats_skip = tile_stats_for_config(&old, &new, config_skip);

        // Invariant: full scan processes some cells
        assert!(
            stats_full.sat_build_cells > 0,
            "full scan should process cells, got 0"
        );
        // Invariant: skip optimization actually reduces work
        assert!(
            stats_skip.sat_build_cells < stats_full.sat_build_cells,
            "skip_clean_rows should process fewer cells than full scan: skip={} full={}",
            stats_skip.sat_build_cells,
            stats_full.sat_build_cells
        );
        // Invariant: the savings are meaningful (at least 50% reduction)
        // With only 2 dirty rows out of 60, skipping should save substantially
        assert!(
            stats_skip.sat_build_cells <= stats_full.sat_build_cells / 2,
            "skip_clean_rows should save at least 50%: skip={} full={}",
            stats_skip.sat_build_cells,
            stats_full.sat_build_cells
        );
    }

    fn lcg_next(state: &mut u64) -> u64 {
        *state = state
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        *state
    }

    fn apply_random_changes(buf: &mut Buffer, seed: u64, count: usize) {
        let width = buf.width().max(1) as u64;
        let height = buf.height().max(1) as u64;
        let mut state = seed;
        for i in 0..count {
            let v = lcg_next(&mut state);
            let x = (v % width) as u16;
            let y = ((v >> 32) % height) as u16;
            let ch = char::from_u32(('A' as u32) + ((i as u32) % 26)).unwrap();
            buf.set_raw(x, y, Cell::from_char(ch));
        }
    }

    fn tile_diag(stats: &TileDiffStats) -> String {
        let tile_size = stats.tile_w as usize * stats.tile_h as usize;
        format!(
            "tile_size={tile_size}, dirty_tiles={}, skipped_tiles={}, dirty_cells={}, dirty_tile_ratio={:.3}, dirty_cell_ratio={:.3}, scanned_tiles={}, fallback={:?}",
            stats.dirty_tiles,
            stats.skipped_tiles,
            stats.dirty_cells,
            stats.dirty_tile_ratio,
            stats.dirty_cell_ratio,
            stats.scanned_tiles,
            stats.fallback
        )
    }

    fn diff_with_forced_tiles(old: &Buffer, new: &Buffer) -> (BufferDiff, TileDiffStats) {
        let mut diff = BufferDiff::new();
        {
            let config = diff.tile_config_mut();
            config.enabled = true;
            config.tile_w = 8;
            config.tile_h = 8;
            config.min_cells_for_tiles = 0;
            config.dense_cell_ratio = 1.1;
            config.dense_tile_ratio = 1.1;
            config.max_tiles = usize::MAX / 4;
        }
        diff.compute_dirty_into(old, new);
        let stats = diff
            .last_tile_stats()
            .expect("tile stats should be recorded");
        (diff, stats)
    }

    fn assert_tile_diff_equivalence(old: &Buffer, new: &Buffer, label: &str) {
        let full = BufferDiff::compute(old, new);
        let (dirty, stats) = diff_with_forced_tiles(old, new);
        let diag = tile_diag(&stats);
        assert!(
            stats.fallback.is_none(),
            "tile diff fallback ({label}) {w}x{h}: {diag}",
            w = old.width(),
            h = old.height()
        );
        assert!(
            full.changes() == dirty.changes(),
            "tile diff mismatch ({label}) {w}x{h}: {diag}",
            w = old.width(),
            h = old.height()
        );
    }

    #[test]
    fn tile_diff_equivalence_small_and_odd_sizes() {
        let cases: &[(u16, u16, usize)] = &[
            (1, 1, 1),
            (2, 1, 1),
            (1, 2, 1),
            (5, 3, 4),
            (7, 13, 12),
            (15, 9, 20),
            (31, 5, 12),
        ];

        for (idx, &(width, height, changes)) in cases.iter().enumerate() {
            let old = Buffer::new(width, height);
            let mut new = old.clone();
            new.clear_dirty();
            apply_random_changes(&mut new, 0xC0FFEE_u64 + idx as u64, changes);
            assert_tile_diff_equivalence(&old, &new, "small_odd");
        }
    }

    #[test]
    fn tile_diff_equivalence_large_sparse_random() {
        let cases: &[(u16, u16)] = &[(200, 60), (240, 80)];
        for (idx, &(width, height)) in cases.iter().enumerate() {
            let old = Buffer::new(width, height);
            let mut new = old.clone();
            new.clear_dirty();
            let total = width as usize * height as usize;
            let changes = (total / 100).max(1);
            apply_random_changes(&mut new, 0xDEADBEEF_u64 + idx as u64, changes);
            assert_tile_diff_equivalence(&old, &new, "large_sparse");
        }
    }

    #[test]
    fn tile_diff_equivalence_row_and_full_buffer() {
        let width = 200u16;
        let height = 60u16;
        let old = Buffer::new(width, height);

        let mut row = old.clone();
        row.clear_dirty();
        for x in 0..width {
            row.set_raw(x, 0, Cell::from_char('R'));
        }
        assert_tile_diff_equivalence(&old, &row, "single_row");

        let mut full = old.clone();
        full.clear_dirty();
        for y in 0..height {
            for x in 0..width {
                full.set_raw(x, y, Cell::from_char('F'));
            }
        }
        assert_tile_diff_equivalence(&old, &full, "full_buffer");
    }

    // =========================================================================
    // Edge-Case Tests (bd-27b0k)
    // =========================================================================

    // --- BufferDiff::full zero/edge dimensions ---

    #[test]
    fn full_zero_width_returns_empty() {
        let diff = BufferDiff::full(0, 10);
        assert!(diff.is_empty());
    }

    #[test]
    fn full_zero_height_returns_empty() {
        let diff = BufferDiff::full(10, 0);
        assert!(diff.is_empty());
    }

    #[test]
    fn full_zero_both_returns_empty() {
        let diff = BufferDiff::full(0, 0);
        assert!(diff.is_empty());
    }

    #[test]
    fn full_single_cell_has_one_change() {
        let diff = BufferDiff::full(1, 1);
        assert_eq!(diff.len(), 1);
        assert_eq!(diff.changes(), &[(0, 0)]);
    }

    #[test]
    fn full_row_major_order() {
        let diff = BufferDiff::full(2, 3);
        assert_eq!(
            diff.changes(),
            &[(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)]
        );
    }

    // --- runs_into ---

    #[test]
    fn runs_into_matches_runs_output() {
        let old = Buffer::new(20, 5);
        let mut new = Buffer::new(20, 5);
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(1, 0, Cell::from_char('B'));
        new.set_raw(5, 2, Cell::from_char('C'));
        new.set_raw(10, 4, Cell::from_char('D'));
        new.set_raw(11, 4, Cell::from_char('E'));

        let diff = BufferDiff::compute(&old, &new);
        let runs = diff.runs();
        let mut runs_buf = Vec::new();
        diff.runs_into(&mut runs_buf);

        assert_eq!(runs, runs_buf);
    }

    #[test]
    fn runs_into_clears_previous_content() {
        let diff = BufferDiff::new();
        let mut out = vec![ChangeRun::new(0, 0, 0)];
        diff.runs_into(&mut out);
        assert!(out.is_empty());
    }

    #[test]
    fn runs_into_preserves_capacity() {
        let old = Buffer::new(10, 2);
        let mut new = Buffer::new(10, 2);
        new.set_raw(0, 0, Cell::from_char('A'));
        let diff = BufferDiff::compute(&old, &new);

        let mut out = Vec::with_capacity(64);
        diff.runs_into(&mut out);
        assert_eq!(out.len(), 1);
        assert!(out.capacity() >= 64);
    }

    // --- ChangeRun ---

    #[test]
    fn change_run_fields_accessible() {
        let run = ChangeRun::new(7, 3, 10);
        assert_eq!(run.y, 7);
        assert_eq!(run.x0, 3);
        assert_eq!(run.x1, 10);
        assert_eq!(run.len(), 8);
        assert!(!run.is_empty());
    }

    #[test]
    fn change_run_single_cell_not_empty() {
        let run = ChangeRun::new(0, 5, 5);
        assert_eq!(run.len(), 1);
        assert!(!run.is_empty());
    }

    #[test]
    fn change_run_debug_format() {
        let run = ChangeRun::new(1, 2, 3);
        let dbg = format!("{:?}", run);
        assert!(dbg.contains("ChangeRun"), "Debug output: {dbg}");
    }

    #[test]
    fn change_run_clone_copy_eq() {
        let run = ChangeRun::new(5, 10, 20);
        let copied = run; // Copy
        assert_eq!(run, copied);
        let cloned: ChangeRun = run; // Copy
        assert_eq!(run, cloned);
    }

    #[test]
    fn change_run_ne() {
        let a = ChangeRun::new(0, 0, 5);
        let b = ChangeRun::new(0, 0, 6);
        assert_ne!(a, b);
    }

    // --- TileDiffConfig ---

    #[test]
    fn tile_diff_config_default_values() {
        let config = TileDiffConfig::default();
        assert!(config.enabled);
        assert_eq!(config.tile_w, 16);
        assert_eq!(config.tile_h, 8);
        assert!(config.skip_clean_rows);
        assert_eq!(config.min_cells_for_tiles, 12_000);
        assert!((config.dense_cell_ratio - 0.25).abs() < f64::EPSILON);
        assert!((config.dense_tile_ratio - 0.60).abs() < f64::EPSILON);
        assert_eq!(config.max_tiles, 4096);
    }

    #[test]
    fn tile_diff_config_builder_methods() {
        let config = TileDiffConfig::default()
            .with_enabled(false)
            .with_tile_size(32, 32)
            .with_min_cells_for_tiles(500)
            .with_skip_clean_rows(false)
            .with_dense_cell_ratio(0.5)
            .with_dense_tile_ratio(0.8)
            .with_max_tiles(100);

        assert!(!config.enabled);
        assert_eq!(config.tile_w, 32);
        assert_eq!(config.tile_h, 32);
        assert!(!config.skip_clean_rows);
        assert_eq!(config.min_cells_for_tiles, 500);
        assert!((config.dense_cell_ratio - 0.5).abs() < f64::EPSILON);
        assert!((config.dense_tile_ratio - 0.8).abs() < f64::EPSILON);
        assert_eq!(config.max_tiles, 100);
    }

    #[test]
    fn tile_diff_config_debug_clone() {
        let config = TileDiffConfig::default();
        let dbg = format!("{:?}", config);
        assert!(dbg.contains("TileDiffConfig"), "Debug: {dbg}");
        let cloned = config.clone();
        assert_eq!(cloned.tile_w, 16);
    }

    // --- TileDiffFallback ---

    #[test]
    fn tile_diff_fallback_as_str_all_variants() {
        assert_eq!(TileDiffFallback::Disabled.as_str(), "disabled");
        assert_eq!(TileDiffFallback::SmallScreen.as_str(), "small_screen");
        assert_eq!(TileDiffFallback::DirtyAll.as_str(), "dirty_all");
        assert_eq!(TileDiffFallback::DenseCells.as_str(), "dense_cells");
        assert_eq!(TileDiffFallback::DenseTiles.as_str(), "dense_tiles");
        assert_eq!(TileDiffFallback::TooManyTiles.as_str(), "too_many_tiles");
        assert_eq!(TileDiffFallback::Overflow.as_str(), "overflow");
    }

    #[test]
    fn tile_diff_fallback_traits() {
        let a = TileDiffFallback::Disabled;
        let b = a; // Copy
        assert_eq!(a, b);
        let c: TileDiffFallback = a; // Copy
        assert_eq!(a, c);
        assert_ne!(a, TileDiffFallback::Overflow);
        let dbg = format!("{:?}", a);
        assert!(dbg.contains("Disabled"), "Debug: {dbg}");
    }

    // --- TileDiffBuilder direct ---

    #[test]
    fn tile_builder_dirty_all_fallback() {
        let mut builder = TileDiffBuilder::new();
        let config = TileDiffConfig::default().with_min_cells_for_tiles(0);
        let dirty_rows = vec![true; 10];
        let dirty_bits = vec![1u8; 200]; // 20x10

        let input = TileDiffInput {
            width: 20,
            height: 10,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 200,
            dirty_all: true,
        };

        let result = builder.build(&config, input);
        assert!(matches!(
            result,
            TileDiffBuild::Fallback(stats) if stats.fallback == Some(TileDiffFallback::DirtyAll)
        ));
    }

    #[test]
    fn tile_builder_dense_cells_fallback() {
        // DenseCells triggers when dirty_cell_ratio >= dense_cell_ratio
        let mut builder = TileDiffBuilder::new();
        let config = TileDiffConfig::default()
            .with_min_cells_for_tiles(0)
            .with_dense_cell_ratio(0.10); // 10% threshold

        let w = 20u16;
        let h = 10u16;
        let total = (w as usize) * (h as usize);
        let dirty_count = total / 10; // exactly 10%

        let dirty_rows = vec![true; h as usize];
        let dirty_bits = vec![0u8; total];

        let input = TileDiffInput {
            width: w,
            height: h,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: dirty_count,
            dirty_all: false,
        };

        let result = builder.build(&config, input);
        assert!(matches!(
            result,
            TileDiffBuild::Fallback(stats) if stats.fallback == Some(TileDiffFallback::DenseCells)
        ));
    }

    #[test]
    fn tile_builder_reuse_across_builds() {
        let mut builder = TileDiffBuilder::new();
        let config = TileDiffConfig::default()
            .with_min_cells_for_tiles(0)
            .with_dense_tile_ratio(1.1)
            .with_dense_cell_ratio(1.1)
            .with_max_tiles(usize::MAX / 4);

        // First build: 20x10 with one dirty cell
        let dirty_rows_1 = vec![true; 10];
        let mut dirty_bits_1 = vec![0u8; 200];
        dirty_bits_1[0] = 1;
        let input_1 = TileDiffInput {
            width: 20,
            height: 10,
            dirty_rows: &dirty_rows_1,
            dirty_bits: &dirty_bits_1,
            dirty_cells: 1,
            dirty_all: false,
        };
        let result_1 = builder.build(&config, input_1);
        assert!(matches!(result_1, TileDiffBuild::UseTiles(_)));

        // Second build: 30x15 with one dirty cell — reuses internal allocations
        let dirty_rows_2 = vec![true; 15];
        let mut dirty_bits_2 = vec![0u8; 450];
        dirty_bits_2[200] = 1;
        let input_2 = TileDiffInput {
            width: 30,
            height: 15,
            dirty_rows: &dirty_rows_2,
            dirty_bits: &dirty_bits_2,
            dirty_cells: 1,
            dirty_all: false,
        };
        let result_2 = builder.build(&config, input_2);
        assert!(matches!(result_2, TileDiffBuild::UseTiles(_)));
    }

    #[test]
    fn tile_builder_default_matches_new() {
        let from_new = TileDiffBuilder::new();
        let from_default = TileDiffBuilder::default();
        assert_eq!(format!("{:?}", from_new), format!("{:?}", from_default));
    }

    // --- TileParams ---

    #[test]
    fn tile_params_total_tiles_and_cells() {
        let params = TileParams {
            width: 100,
            height: 50,
            tile_w: 16,
            tile_h: 8,
            tiles_x: 7, // ceil(100/16)
            tiles_y: 7, // ceil(50/8)
        };
        assert_eq!(params.total_tiles(), 49);
        assert_eq!(params.total_cells(), 5000);
    }

    // --- TileDiffStats ---

    #[test]
    fn tile_diff_stats_from_builder() {
        let mut builder = TileDiffBuilder::new();
        let config = TileDiffConfig::default()
            .with_min_cells_for_tiles(0)
            .with_dense_tile_ratio(1.1)
            .with_dense_cell_ratio(1.1)
            .with_max_tiles(usize::MAX / 4);

        let w = 32u16;
        let h = 16u16;
        let dirty_rows = vec![true; h as usize];
        let mut dirty_bits = vec![0u8; (w as usize) * (h as usize)];
        dirty_bits[0] = 1; // one cell dirty in first tile

        let input = TileDiffInput {
            width: w,
            height: h,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 1,
            dirty_all: false,
        };

        let result = builder.build(&config, input);
        match result {
            TileDiffBuild::UseTiles(plan) => {
                let stats = plan.stats;
                assert_eq!(stats.width, w);
                assert_eq!(stats.height, h);
                // tile_w clamped from 16 → 16 (within [8,64])
                assert_eq!(stats.tile_w, 16);
                assert_eq!(stats.tile_h, 8);
                // tiles_x = ceil(32/16) = 2, tiles_y = ceil(16/8) = 2
                assert_eq!(stats.tiles_x, 2);
                assert_eq!(stats.tiles_y, 2);
                assert_eq!(stats.total_tiles, 4);
                assert_eq!(stats.dirty_cells, 1);
                assert_eq!(stats.dirty_tiles, 1);
                assert_eq!(stats.skipped_tiles, 3);
                assert!(stats.fallback.is_none());
                // Copy trait works
                let copy = stats;
                assert_eq!(copy.width, stats.width);
            }
            _ => unreachable!("expected UseTiles"),
        }
    }

    // --- clamp_tile_size via builder ---

    #[test]
    fn tile_size_clamped_to_min_8() {
        let mut builder = TileDiffBuilder::new();
        let config = TileDiffConfig {
            enabled: true,
            tile_w: 1, // below min 8
            tile_h: 0, // below min 8
            skip_clean_rows: false,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 1.1,
            dense_tile_ratio: 1.1,
            max_tiles: usize::MAX / 4,
        };

        let dirty_rows = vec![true; 16];
        let mut dirty_bits = vec![0u8; 256]; // 16x16
        dirty_bits[0] = 1;

        let input = TileDiffInput {
            width: 16,
            height: 16,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 1,
            dirty_all: false,
        };

        let result = builder.build(&config, input);
        match result {
            TileDiffBuild::UseTiles(plan) => {
                assert_eq!(plan.stats.tile_w, 8);
                assert_eq!(plan.stats.tile_h, 8);
            }
            _ => unreachable!("expected UseTiles"),
        }
    }

    #[test]
    fn tile_size_clamped_to_max_64() {
        let mut builder = TileDiffBuilder::new();
        let config = TileDiffConfig {
            enabled: true,
            tile_w: 255, // above max 64
            tile_h: 100, // above max 64
            skip_clean_rows: false,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 1.1,
            dense_tile_ratio: 1.1,
            max_tiles: usize::MAX / 4,
        };

        let dirty_rows = vec![true; 128];
        let mut dirty_bits = vec![0u8; 128 * 128];
        dirty_bits[0] = 1;

        let input = TileDiffInput {
            width: 128,
            height: 128,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 1,
            dirty_all: false,
        };

        let result = builder.build(&config, input);
        match result {
            TileDiffBuild::UseTiles(plan) => {
                assert_eq!(plan.stats.tile_w, 64);
                assert_eq!(plan.stats.tile_h, 64);
            }
            _ => unreachable!("expected UseTiles"),
        }
    }

    // --- BufferDiff trait coverage ---

    #[test]
    fn buffer_diff_default_is_empty() {
        let diff: BufferDiff = Default::default();
        assert!(diff.is_empty());
        assert_eq!(diff.len(), 0);
        assert!(diff.last_tile_stats().is_none());
    }

    #[test]
    fn buffer_diff_debug_format() {
        let diff = BufferDiff::new();
        let dbg = format!("{:?}", diff);
        assert!(dbg.contains("BufferDiff"), "Debug: {dbg}");
    }

    #[test]
    fn buffer_diff_clone_preserves_changes() {
        let old = Buffer::new(5, 5);
        let mut new = Buffer::new(5, 5);
        new.set_raw(2, 3, Cell::from_char('X'));
        let diff = BufferDiff::compute(&old, &new);
        let cloned = diff.clone();
        assert_eq!(diff.changes(), cloned.changes());
    }

    // --- compute_into reuse ---

    #[test]
    fn compute_into_replaces_previous_changes() {
        let mut diff = BufferDiff::new();

        let old1 = Buffer::new(5, 5);
        let mut new1 = Buffer::new(5, 5);
        new1.set_raw(0, 0, Cell::from_char('A'));
        diff.compute_into(&old1, &new1);
        assert_eq!(diff.len(), 1);

        let old2 = Buffer::new(3, 3);
        let mut new2 = Buffer::new(3, 3);
        new2.set_raw(1, 1, Cell::from_char('B'));
        new2.set_raw(2, 2, Cell::from_char('C'));
        diff.compute_into(&old2, &new2);
        assert_eq!(diff.len(), 2);
        assert_eq!(diff.changes(), &[(1, 1), (2, 2)]);
    }

    #[test]
    fn compute_into_identical_clears() {
        let mut diff = BufferDiff::new();
        let old = Buffer::new(5, 5);
        let mut new = Buffer::new(5, 5);
        new.set_raw(0, 0, Cell::from_char('X'));
        diff.compute_into(&old, &new);
        assert_eq!(diff.len(), 1);

        diff.compute_into(&old, &old);
        assert!(diff.is_empty());
    }

    // --- compute_dirty_into ---

    #[test]
    fn compute_dirty_into_no_dirty_rows() {
        let old = Buffer::new(10, 10);
        let mut new = old.clone();
        new.clear_dirty();

        let mut diff = BufferDiff::new();
        diff.compute_dirty_into(&old, &new);
        assert!(diff.is_empty());
    }

    #[test]
    fn compute_dirty_into_reuse() {
        let mut diff = BufferDiff::new();

        let old = Buffer::new(10, 10);
        let mut new1 = old.clone();
        new1.clear_dirty();
        new1.set_raw(5, 5, Cell::from_char('X'));
        diff.compute_dirty_into(&old, &new1);
        assert_eq!(diff.len(), 1);

        let mut new2 = old.clone();
        new2.clear_dirty();
        new2.set_raw(3, 3, Cell::from_char('Y'));
        new2.set_raw(7, 7, Cell::from_char('Z'));
        diff.compute_dirty_into(&old, &new2);
        assert_eq!(diff.len(), 2);
        assert_eq!(diff.changes(), &[(3, 3), (7, 7)]);
    }

    // --- last_tile_stats ---

    #[test]
    fn last_tile_stats_none_after_compute_into() {
        let mut diff = BufferDiff::new();
        let old = Buffer::new(5, 5);
        let new = Buffer::new(5, 5);
        diff.compute_into(&old, &new);
        assert!(diff.last_tile_stats().is_none());
    }

    #[test]
    fn last_tile_stats_some_after_compute_dirty_into() {
        let mut diff = BufferDiff::new();
        let old = Buffer::new(10, 10);
        let mut new = old.clone();
        new.set_raw(0, 0, Cell::from_char('A'));
        diff.compute_dirty_into(&old, &new);
        // 10x10=100 < 12000 min threshold → SmallScreen fallback
        let stats = diff.last_tile_stats().expect("should have tile stats");
        assert_eq!(stats.fallback, Some(TileDiffFallback::SmallScreen));
    }

    // --- tile_config_mut ---

    #[test]
    fn tile_config_mut_modifies_behavior() {
        let old = Buffer::new(200, 60);
        let mut new = old.clone();
        new.clear_dirty();
        new.set_raw(0, 0, Cell::from_char('X'));

        // Default config: tiles enabled for 200x60=12000 cells
        let mut diff = BufferDiff::new();
        diff.compute_dirty_into(&old, &new);
        let stats = diff.last_tile_stats().expect("stats");
        assert!(
            stats.fallback.is_none(),
            "tiles should be active for 200x60"
        );

        // Disable via config_mut
        diff.tile_config_mut().enabled = false;
        diff.compute_dirty_into(&old, &new);
        let stats = diff.last_tile_stats().expect("stats");
        assert_eq!(stats.fallback, Some(TileDiffFallback::Disabled));
    }

    // --- Row scan boundary ---

    #[test]
    fn row_scan_width_31_below_row_block_size() {
        let old = Buffer::new(31, 1);
        let mut new = Buffer::new(31, 1);
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(15, 0, Cell::from_char('B'));
        new.set_raw(30, 0, Cell::from_char('C'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 3);
        assert_eq!(diff.changes(), &[(0, 0), (15, 0), (30, 0)]);
    }

    #[test]
    fn row_scan_width_32_exact_row_block_size() {
        let old = Buffer::new(32, 1);
        let mut new = Buffer::new(32, 1);
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(15, 0, Cell::from_char('B'));
        new.set_raw(31, 0, Cell::from_char('C'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 3);
        assert_eq!(diff.changes(), &[(0, 0), (15, 0), (31, 0)]);
    }

    #[test]
    fn row_scan_width_33_one_past_row_block_size() {
        let old = Buffer::new(33, 1);
        let mut new = Buffer::new(33, 1);
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(31, 0, Cell::from_char('B'));
        new.set_raw(32, 0, Cell::from_char('C'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 3);
        assert_eq!(diff.changes(), &[(0, 0), (31, 0), (32, 0)]);
    }

    // --- DenseCells threshold boundary ---

    #[test]
    fn dense_cells_exact_threshold_triggers_fallback() {
        let mut builder = TileDiffBuilder::new();
        let w = 20u16;
        let h = 20u16;
        let total = (w as usize) * (h as usize); // 400
        let dirty_count = total / 4; // 100 = exactly 25%

        let config = TileDiffConfig {
            enabled: true,
            tile_w: 8,
            tile_h: 8,
            skip_clean_rows: false,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 0.25,
            dense_tile_ratio: 1.1,
            max_tiles: usize::MAX / 4,
        };

        let dirty_rows = vec![true; h as usize];
        let dirty_bits = vec![1u8; total];

        let input = TileDiffInput {
            width: w,
            height: h,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: dirty_count,
            dirty_all: false,
        };

        let result = builder.build(&config, input);
        assert!(matches!(
            result,
            TileDiffBuild::Fallback(stats) if stats.fallback == Some(TileDiffFallback::DenseCells)
        ));
    }

    #[test]
    fn dense_cells_just_below_threshold_passes() {
        let mut builder = TileDiffBuilder::new();
        let w = 20u16;
        let h = 20u16;
        let total = (w as usize) * (h as usize); // 400
        let dirty_count = total / 4 - 1; // 99 = 24.75% < 25%

        let config = TileDiffConfig {
            enabled: true,
            tile_w: 8,
            tile_h: 8,
            skip_clean_rows: false,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 0.25,
            dense_tile_ratio: 1.1,
            max_tiles: usize::MAX / 4,
        };

        let dirty_rows = vec![true; h as usize];
        let mut dirty_bits = vec![0u8; total];
        for bit in dirty_bits.iter_mut().take(dirty_count) {
            *bit = 1;
        }

        let input = TileDiffInput {
            width: w,
            height: h,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: dirty_count,
            dirty_all: false,
        };

        let result = builder.build(&config, input);
        match &result {
            TileDiffBuild::Fallback(stats) => {
                assert_ne!(
                    stats.fallback,
                    Some(TileDiffFallback::DenseCells),
                    "should not trigger DenseCells below 25%: {:?}",
                    stats.fallback
                );
            }
            TileDiffBuild::UseTiles(_) => { /* expected */ }
        }
    }

    // --- Switching between compute paths ---

    #[test]
    fn switch_between_compute_and_dirty() {
        let mut diff = BufferDiff::new();
        let old = Buffer::new(10, 10);
        let mut new = Buffer::new(10, 10);
        new.set_raw(3, 3, Cell::from_char('X'));

        diff.compute_into(&old, &new);
        assert_eq!(diff.len(), 1);
        assert!(diff.last_tile_stats().is_none());

        diff.compute_dirty_into(&old, &new);
        assert_eq!(diff.len(), 1);
        assert!(diff.last_tile_stats().is_some());

        diff.compute_into(&old, &new);
        assert_eq!(diff.len(), 1);
        assert!(diff.last_tile_stats().is_none());
    }

    // --- Dimension mismatch panics ---

    #[test]
    #[should_panic(expected = "buffer heights must match")]
    fn compute_panics_on_height_mismatch() {
        let old = Buffer::new(5, 5);
        let new = Buffer::new(5, 4);
        let _ = BufferDiff::compute(&old, &new);
    }

    #[test]
    #[should_panic(expected = "buffer widths must match")]
    fn compute_dirty_panics_on_width_mismatch() {
        let old = Buffer::new(5, 5);
        let new = Buffer::new(4, 5);
        let _ = BufferDiff::compute_dirty(&old, &new);
    }

    #[test]
    #[should_panic(expected = "buffer heights must match")]
    fn compute_dirty_panics_on_height_mismatch() {
        let old = Buffer::new(5, 5);
        let new = Buffer::new(5, 4);
        let _ = BufferDiff::compute_dirty(&old, &new);
    }

    // --- TileDiffInput/TileDiffBuild trait coverage ---

    #[test]
    fn tile_diff_input_debug_copy() {
        let dirty_rows = vec![true; 2];
        let dirty_bits = vec![0u8; 4];
        let input = TileDiffInput {
            width: 2,
            height: 2,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 0,
            dirty_all: false,
        };
        let dbg = format!("{:?}", input);
        assert!(dbg.contains("TileDiffInput"), "Debug: {dbg}");
        let copy = input; // Copy
        assert_eq!(copy.width, input.width);
    }

    #[test]
    fn tile_diff_build_debug() {
        let mut builder = TileDiffBuilder::new();
        let config = TileDiffConfig::default();
        let dirty_rows = vec![true; 1];
        let dirty_bits = vec![0u8; 4];
        let input = TileDiffInput {
            width: 4,
            height: 1,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 0,
            dirty_all: false,
        };
        let result = builder.build(&config, input);
        let dbg = format!("{:?}", result);
        assert!(dbg.contains("Fallback"), "Debug: {dbg}");
    }

    // --- BufferDiff::full runs ---

    #[test]
    fn full_diff_runs_one_per_row() {
        let diff = BufferDiff::full(10, 3);
        let runs = diff.runs();
        assert_eq!(runs.len(), 3);
        for (i, run) in runs.iter().enumerate() {
            assert_eq!(run.y, i as u16);
            assert_eq!(run.x0, 0);
            assert_eq!(run.x1, 9);
            assert_eq!(run.len(), 10);
        }
    }

    // --- dirty diff false positive rows ---

    #[test]
    fn dirty_diff_skips_false_positive_rows() {
        let old = Buffer::new(10, 5);
        let mut new = old.clone();
        new.clear_dirty();

        // set_raw marks rows dirty, but Cell::default() matches old content
        for y in 0..5u16 {
            new.set_raw(0, y, Cell::default());
        }
        // Real changes on rows 1 and 3
        new.set_raw(5, 1, Cell::from_char('A'));
        new.set_raw(7, 3, Cell::from_char('B'));

        let diff = BufferDiff::compute_dirty(&old, &new);
        assert_eq!(diff.len(), 2);
        assert!(diff.changes().contains(&(5, 1)));
        assert!(diff.changes().contains(&(7, 3)));
    }

    // --- Attribute-only change ---

    #[test]
    fn bg_only_change_detected() {
        let old = Buffer::new(5, 1);
        let mut new = Buffer::new(5, 1);
        new.set_raw(2, 0, Cell::default().with_bg(PackedRgba::rgb(0, 0, 255)));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 1);
        assert_eq!(diff.changes(), &[(2, 0)]);
    }

    // --- Changes at buffer boundaries ---

    #[test]
    fn changes_at_buffer_corners() {
        let w = 100u16;
        let h = 50u16;
        let old = Buffer::new(w, h);
        let mut new = Buffer::new(w, h);
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(w - 1, h - 1, Cell::from_char('Z'));

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.len(), 2);
        assert_eq!(diff.changes()[0], (0, 0));
        assert_eq!(diff.changes()[1], (w - 1, h - 1));

        let runs = diff.runs();
        assert_eq!(runs.len(), 2);
        assert_eq!(runs[0], ChangeRun::new(0, 0, 0));
        assert_eq!(runs[1], ChangeRun::new(h - 1, w - 1, w - 1));
    }

    // --- TileParams Debug/Copy ---

    #[test]
    fn tile_params_debug_copy() {
        let params = TileParams {
            width: 80,
            height: 24,
            tile_w: 16,
            tile_h: 8,
            tiles_x: 5,
            tiles_y: 3,
        };
        let dbg = format!("{:?}", params);
        assert!(dbg.contains("TileParams"), "Debug: {dbg}");
        let copy = params; // Copy
        assert_eq!(copy.width, params.width);
        let cloned: TileParams = params; // Copy
        assert_eq!(cloned.tiles_x, params.tiles_x);
    }

    // --- TileDiffStats Debug/Copy ---

    #[test]
    fn tile_diff_stats_debug_copy() {
        let mut builder = TileDiffBuilder::new();
        let config = TileDiffConfig::default();
        let dirty_rows = vec![true; 1];
        let dirty_bits = vec![0u8; 1];
        let input = TileDiffInput {
            width: 1,
            height: 1,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 0,
            dirty_all: false,
        };
        let result = builder.build(&config, input);
        match result {
            TileDiffBuild::Fallback(stats) => {
                let dbg = format!("{:?}", stats);
                assert!(dbg.contains("TileDiffStats"), "Debug: {dbg}");
                let copy = stats;
                assert_eq!(copy.width, stats.width);
                let cloned: TileDiffStats = stats; // Copy
                assert_eq!(cloned.height, stats.height);
            }
            _ => unreachable!("expected Fallback for 1x1"),
        }
    }

    // =========================================================================
    // Dirty Span-Based Scanning (bd-khkj4)
    // =========================================================================

    #[test]
    fn compute_dirty_with_targeted_spans() {
        // Verify that compute_dirty correctly uses span information
        // to limit scanning to only the dirty span regions.
        let width = 100u16;
        let height = 10u16;
        let old = Buffer::new(width, height);
        let mut new = old.clone();
        new.clear_dirty();

        // Set a few cells in specific positions to create narrow spans
        new.set_raw(10, 3, Cell::from_char('A'));
        new.set_raw(11, 3, Cell::from_char('B'));
        new.set_raw(50, 7, Cell::from_char('C'));

        let full = BufferDiff::compute(&old, &new);
        let dirty = BufferDiff::compute_dirty(&old, &new);

        assert_eq!(full.changes(), dirty.changes());
        assert_eq!(dirty.len(), 3);
        assert!(dirty.changes().contains(&(10, 3)));
        assert!(dirty.changes().contains(&(11, 3)));
        assert!(dirty.changes().contains(&(50, 7)));
    }

    #[test]
    fn compute_dirty_spans_on_multiple_rows() {
        // Multiple rows with spans at different positions
        let width = 80u16;
        let height = 5u16;
        let old = Buffer::new(width, height);
        let mut new = old.clone();
        new.clear_dirty();

        // Row 0: changes at start
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(1, 0, Cell::from_char('B'));
        // Row 2: changes in middle
        new.set_raw(40, 2, Cell::from_char('C'));
        // Row 4: changes at end
        new.set_raw(79, 4, Cell::from_char('D'));

        let full = BufferDiff::compute(&old, &new);
        let dirty = BufferDiff::compute_dirty(&old, &new);

        assert_eq!(full.changes(), dirty.changes());
        assert_eq!(dirty.len(), 4);
    }

    #[test]
    fn compute_dirty_span_with_false_positive_row() {
        // Row is dirty but actual cell content hasn't changed
        let old = Buffer::new(20, 3);
        let mut new = old.clone();
        new.clear_dirty();

        // Mark row 1 dirty via set_raw with default cell (matches old)
        new.set_raw(5, 1, Cell::default());
        // Real change on row 2
        new.set_raw(10, 2, Cell::from_char('X'));

        let dirty = BufferDiff::compute_dirty(&old, &new);
        assert_eq!(dirty.len(), 1);
        assert_eq!(dirty.changes(), &[(10, 2)]);
    }

    #[test]
    fn compute_dirty_many_spans_per_row() {
        // Create many separate spans on a single row (below overflow threshold)
        let width = 200u16;
        let height = 1u16;
        let old = Buffer::new(width, height);
        let mut new = old.clone();
        new.clear_dirty();

        // Create 10 isolated changes (each creates a separate span)
        let positions: Vec<u16> = vec![5, 20, 35, 50, 65, 80, 95, 110, 125, 140];
        for &x in &positions {
            new.set_raw(x, 0, Cell::from_char('X'));
        }

        let full = BufferDiff::compute(&old, &new);
        let dirty = BufferDiff::compute_dirty(&old, &new);

        assert_eq!(full.changes(), dirty.changes());
        assert_eq!(dirty.len(), positions.len());
    }

    // =========================================================================
    // Tile + Span Combination Path (bd-khkj4)
    // =========================================================================

    #[test]
    fn tile_diff_with_dirty_spans_matches_full() {
        // Force tile path and verify it works correctly with dirty spans
        let width = 200u16;
        let height = 60u16;
        let old = Buffer::new(width, height);
        let mut new = old.clone();
        new.clear_dirty();

        // Create sparse changes across multiple tiles
        new.set_raw(5, 2, Cell::from_char('A'));
        new.set_raw(100, 30, Cell::from_char('B'));
        new.set_raw(195, 55, Cell::from_char('C'));

        let (dirty_diff, stats) = diff_with_forced_tiles(&old, &new);
        let full = BufferDiff::compute(&old, &new);

        assert!(stats.fallback.is_none(), "tile path should be used");
        assert_eq!(
            stats.sat_build_cells, 3,
            "span-aware tile build should only scan covered span cells"
        );
        assert_eq!(full.changes(), dirty_diff.changes());
        assert_eq!(dirty_diff.len(), 3);
    }

    #[test]
    fn tile_diff_with_spans_straddling_tile_boundary() {
        // Create a span that crosses a tile boundary
        let width = 200u16;
        let height = 60u16;
        let old = Buffer::new(width, height);
        let mut new = old.clone();
        new.clear_dirty();

        // With tile_w=8, create adjacent changes around position 8 (tile boundary)
        new.set_raw(6, 0, Cell::from_char('A'));
        new.set_raw(7, 0, Cell::from_char('B'));
        new.set_raw(8, 0, Cell::from_char('C'));
        new.set_raw(9, 0, Cell::from_char('D'));

        let (dirty_diff, stats) = diff_with_forced_tiles(&old, &new);
        let full = BufferDiff::compute(&old, &new);

        assert!(stats.fallback.is_none());
        assert_eq!(full.changes(), dirty_diff.changes());
        assert_eq!(dirty_diff.len(), 4);
    }

    #[test]
    fn tile_diff_single_dirty_tile_skips_others() {
        // Verify that clean tiles are skipped
        let width = 200u16;
        let height = 60u16;
        let old = Buffer::new(width, height);
        let mut new = old.clone();
        new.clear_dirty();

        // Only one change in one tile
        new.set_raw(3, 3, Cell::from_char('X'));

        let (dirty_diff, stats) = diff_with_forced_tiles(&old, &new);

        assert!(stats.fallback.is_none());
        assert_eq!(dirty_diff.len(), 1);
        assert!(stats.skipped_tiles > 0, "should skip clean tiles");
        assert_eq!(stats.dirty_tiles, 1, "only one tile should be dirty");
    }

    #[test]
    fn accumulate_tile_counts_range_single_cell_range() {
        let mut tile_counts = vec![0u32; 4];
        let dirty_bits = vec![0, 0, 1, 0, 0, 0, 0, 0];
        let mut scanned_cells = 0usize;

        accumulate_tile_counts_range(
            &mut tile_counts,
            &dirty_bits,
            0,
            4,
            2,
            2..3,
            &mut scanned_cells,
        )
        .unwrap();

        assert_eq!(scanned_cells, 1);
        assert_eq!(tile_counts, vec![0, 1, 0, 0]);
    }

    #[test]
    fn accumulate_tile_counts_range_single_tile_multi_cell_range() {
        let mut tile_counts = vec![0u32; 4];
        let dirty_bits = vec![0, 1, 0, 1, 1, 0, 0, 0];
        let mut scanned_cells = 0usize;

        accumulate_tile_counts_range(
            &mut tile_counts,
            &dirty_bits,
            0,
            4,
            2,
            4..6,
            &mut scanned_cells,
        )
        .unwrap();

        assert_eq!(scanned_cells, 2);
        assert_eq!(tile_counts, vec![0, 0, 1, 0]);
    }

    // =========================================================================
    // TileDiffPlan Field Access (bd-khkj4)
    // =========================================================================

    #[test]
    fn tile_diff_plan_fields_accessible() {
        let mut builder = TileDiffBuilder::new();
        let config = TileDiffConfig::default()
            .with_min_cells_for_tiles(0)
            .with_dense_tile_ratio(1.1)
            .with_dense_cell_ratio(1.1)
            .with_max_tiles(usize::MAX / 4);

        let w = 32u16;
        let h = 16u16;
        let dirty_rows = vec![true; h as usize];
        let mut dirty_bits = vec![0u8; (w as usize) * (h as usize)];
        // Mark two cells dirty in different tiles
        dirty_bits[0] = 1; // tile (0,0)
        dirty_bits[8 + 8 * w as usize] = 1; // tile (1,1) roughly

        let input = TileDiffInput {
            width: w,
            height: h,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 2,
            dirty_all: false,
        };

        let result = builder.build(&config, input);
        match result {
            TileDiffBuild::UseTiles(plan) => {
                // Verify params are accessible
                assert_eq!(plan.params.width, w);
                assert_eq!(plan.params.height, h);
                assert!(plan.params.tile_w >= 8);
                assert!(plan.params.tile_h >= 8);
                assert!(plan.params.tiles_x > 0);
                assert!(plan.params.tiles_y > 0);

                // Verify dirty_tiles slice
                assert_eq!(plan.dirty_tiles.len(), plan.params.total_tiles());
                let dirty_count: usize = plan.dirty_tiles.iter().filter(|&&d| d).count();
                assert_eq!(dirty_count, plan.stats.dirty_tiles);

                // Verify tile_counts slice
                assert_eq!(plan.tile_counts.len(), plan.params.total_tiles());

                // Verify SAT slice (tiles_x+1 * tiles_y+1)
                let expected_sat_len = (plan.params.tiles_x + 1) * (plan.params.tiles_y + 1);
                assert_eq!(plan.sat.len(), expected_sat_len);

                // SAT[0][*] and SAT[*][0] should be 0 (prefix sum boundary)
                let sat_w = plan.params.tiles_x + 1;
                for tx in 0..sat_w {
                    assert_eq!(plan.sat[tx], 0, "SAT top border should be 0");
                }
                for ty in 0..plan.params.tiles_y + 1 {
                    assert_eq!(plan.sat[ty * sat_w], 0, "SAT left border should be 0");
                }
            }
            _ => unreachable!("expected UseTiles"),
        }
    }

    // =========================================================================
    // DenseTiles Threshold Boundary (bd-khkj4)
    // =========================================================================

    #[test]
    fn dense_tiles_exact_threshold_triggers_fallback() {
        let mut builder = TileDiffBuilder::new();
        let w = 32u16;
        let h = 32u16;
        // With tile_w=8, tile_h=8: tiles_x=4, tiles_y=4, total=16
        // Dense tile ratio = 0.5 means >=8 dirty tiles trigger fallback

        let total_cells = (w as usize) * (h as usize);
        let config = TileDiffConfig {
            enabled: true,
            tile_w: 8,
            tile_h: 8,
            skip_clean_rows: false,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 1.1,
            dense_tile_ratio: 0.5,
            max_tiles: usize::MAX / 4,
        };

        let dirty_rows = vec![true; h as usize];
        let mut dirty_bits = vec![0u8; total_cells];
        // Mark one cell dirty in each of 8 tiles (50% of 16 tiles)
        // Tiles are 8x8 on a 32x32 grid: (0,0), (1,0), (2,0), (3,0), (0,1)...
        for tile_y in 0..2 {
            for tile_x in 0..4 {
                let x = tile_x * 8;
                let y = tile_y * 8;
                dirty_bits[y * w as usize + x] = 1;
            }
        }

        let input = TileDiffInput {
            width: w,
            height: h,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 8,
            dirty_all: false,
        };

        let result = builder.build(&config, input);
        assert!(
            matches!(
                result,
                TileDiffBuild::Fallback(stats) if stats.fallback == Some(TileDiffFallback::DenseTiles)
            ),
            "8 of 16 tiles dirty (50%) should trigger DenseTiles with threshold 0.5"
        );
    }

    #[test]
    fn dense_tiles_just_below_threshold_passes() {
        let mut builder = TileDiffBuilder::new();
        let w = 32u16;
        let h = 32u16;
        // tiles: 4x4=16. Dense tile ratio = 0.5 means <8 dirty tiles pass

        let total_cells = (w as usize) * (h as usize);
        let config = TileDiffConfig {
            enabled: true,
            tile_w: 8,
            tile_h: 8,
            skip_clean_rows: false,
            min_cells_for_tiles: 0,
            dense_cell_ratio: 1.1,
            dense_tile_ratio: 0.5,
            max_tiles: usize::MAX / 4,
        };

        let dirty_rows = vec![true; h as usize];
        let mut dirty_bits = vec![0u8; total_cells];
        // Mark one cell dirty in 7 tiles (43.75% < 50%)
        for tile_idx in 0..7 {
            let tile_x = tile_idx % 4;
            let tile_y = tile_idx / 4;
            let x = tile_x * 8;
            let y = tile_y * 8;
            dirty_bits[y * w as usize + x] = 1;
        }

        let input = TileDiffInput {
            width: w,
            height: h,
            dirty_rows: &dirty_rows,
            dirty_bits: &dirty_bits,
            dirty_cells: 7,
            dirty_all: false,
        };

        let result = builder.build(&config, input);
        assert!(
            matches!(result, TileDiffBuild::UseTiles(_)),
            "7 of 16 tiles dirty (43.75%) should use tiles with threshold 0.5"
        );
    }

    // =========================================================================
    // span_diagnostics Helper (bd-khkj4)
    // =========================================================================

    #[test]
    fn span_diagnostics_with_no_dirty_spans() {
        let mut buf = Buffer::new(20, 3);
        buf.clear_dirty();
        let diag = span_diagnostics(&buf);
        // Should report stats with no dirty rows
        assert!(
            diag.contains("stats="),
            "diagnostics should include stats: {diag}"
        );
    }

    #[test]
    fn span_diagnostics_with_dirty_cells() {
        let mut buf = Buffer::new(20, 3);
        buf.clear_dirty();
        buf.set_raw(5, 1, Cell::from_char('X'));
        let diag = span_diagnostics(&buf);
        assert!(
            diag.contains("stats="),
            "diagnostics should include stats: {diag}"
        );
    }

    #[test]
    fn span_diagnostics_with_full_row() {
        let mut buf = Buffer::new(20, 2);
        buf.clear_dirty();
        // Fill entire row to trigger full-row dirty
        for x in 0..20u16 {
            buf.set_raw(x, 0, Cell::from_char('X'));
        }
        let diag = span_diagnostics(&buf);
        // Should mention "full" for the full-row dirty case
        assert!(
            diag.contains("stats="),
            "diagnostics should include stats: {diag}"
        );
    }

    // =========================================================================
    // Misc Edge Cases (bd-khkj4)
    // =========================================================================

    #[test]
    fn compute_dirty_matches_full_for_single_row_buffer() {
        let old = Buffer::new(50, 1);
        let mut new = old.clone();
        new.set_raw(25, 0, Cell::from_char('M'));

        let full = BufferDiff::compute(&old, &new);
        let dirty = BufferDiff::compute_dirty(&old, &new);

        assert_eq!(full.changes(), dirty.changes());
    }

    #[test]
    fn compute_dirty_matches_full_for_single_column_buffer() {
        let old = Buffer::new(1, 50);
        let mut new = old.clone();
        new.set_raw(0, 25, Cell::from_char('M'));

        let full = BufferDiff::compute(&old, &new);
        let dirty = BufferDiff::compute_dirty(&old, &new);

        assert_eq!(full.changes(), dirty.changes());
    }

    #[test]
    fn tile_config_chain_returns_same_type() {
        // Verify builder pattern chaining works and returns Self
        let config = TileDiffConfig::default()
            .with_enabled(true)
            .with_tile_size(16, 16)
            .with_min_cells_for_tiles(1000)
            .with_skip_clean_rows(true)
            .with_dense_cell_ratio(0.3)
            .with_dense_tile_ratio(0.7)
            .with_max_tiles(2048);

        assert!(config.enabled);
        assert_eq!(config.tile_w, 16);
        assert_eq!(config.tile_h, 16);
        assert_eq!(config.min_cells_for_tiles, 1000);
        assert!(config.skip_clean_rows);
        assert!((config.dense_cell_ratio - 0.3).abs() < f64::EPSILON);
        assert!((config.dense_tile_ratio - 0.7).abs() < f64::EPSILON);
        assert_eq!(config.max_tiles, 2048);
    }

    #[test]
    fn runs_into_reuse_across_multiple_diffs() {
        // Verify runs_into correctly reuses buffer across multiple diff operations
        let mut runs_buf: Vec<ChangeRun> = Vec::new();

        // First diff
        let old1 = Buffer::new(10, 2);
        let mut new1 = Buffer::new(10, 2);
        new1.set_raw(0, 0, Cell::from_char('A'));
        new1.set_raw(1, 0, Cell::from_char('B'));
        let diff1 = BufferDiff::compute(&old1, &new1);
        diff1.runs_into(&mut runs_buf);
        assert_eq!(runs_buf.len(), 1);
        assert_eq!(runs_buf[0], ChangeRun::new(0, 0, 1));

        // Second diff - should clear previous and fill with new
        let old2 = Buffer::new(5, 3);
        let mut new2 = Buffer::new(5, 3);
        new2.set_raw(2, 1, Cell::from_char('X'));
        new2.set_raw(4, 2, Cell::from_char('Y'));
        let diff2 = BufferDiff::compute(&old2, &new2);
        diff2.runs_into(&mut runs_buf);
        assert_eq!(runs_buf.len(), 2);
        assert_eq!(runs_buf[0], ChangeRun::new(1, 2, 2));
        assert_eq!(runs_buf[1], ChangeRun::new(2, 4, 4));
    }

    #[test]
    fn full_diff_zero_dimensions_runs_empty() {
        let diff_w0 = BufferDiff::full(0, 5);
        assert!(diff_w0.runs().is_empty());

        let diff_h0 = BufferDiff::full(5, 0);
        assert!(diff_h0.runs().is_empty());

        let diff_both = BufferDiff::full(0, 0);
        assert!(diff_both.runs().is_empty());
    }

    #[test]
    fn change_run_max_u16_values() {
        // Test near-max values that don't overflow len()
        let run = ChangeRun::new(u16::MAX, 1, u16::MAX);
        assert_eq!(run.y, u16::MAX);
        assert_eq!(run.x0, 1);
        assert_eq!(run.x1, u16::MAX);
        assert_eq!(run.len(), usize::from(u16::MAX)); // 65535 - 1 + 1 = 65535

        // Single-cell run at max position
        let run2 = ChangeRun::new(u16::MAX, u16::MAX, u16::MAX);
        assert_eq!(run2.len(), 1);
    }

    #[test]
    fn tile_diff_equivalence_adjacent_tiles() {
        // Changes at tile boundaries (tiles are 8 cells wide)
        let width = 200u16;
        let height = 60u16;
        let old = Buffer::new(width, height);
        let mut new = old.clone();
        new.clear_dirty();

        // Place changes at boundaries of adjacent tiles
        // tile_w=8, so tile boundaries at 0, 8, 16, 24...
        new.set_raw(7, 0, Cell::from_char('A')); // end of tile 0
        new.set_raw(8, 0, Cell::from_char('B')); // start of tile 1
        new.set_raw(15, 0, Cell::from_char('C')); // end of tile 1
        new.set_raw(16, 0, Cell::from_char('D')); // start of tile 2

        assert_tile_diff_equivalence(&old, &new, "adjacent_tile_boundaries");
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use crate::cell::Cell;
    use ftui_core::geometry::Rect;
    use proptest::prelude::*;

    // Property: Applying diff changes to old buffer produces new buffer.
    #[test]
    fn diff_apply_produces_target() {
        proptest::proptest!(|(
            width in 5u16..50,
            height in 5u16..30,
            num_changes in 0usize..200,
        )| {
            // Create old buffer (all spaces)
            let old = Buffer::new(width, height);

            // Create new buffer by making random changes
            let mut new = old.clone();
            for i in 0..num_changes {
                let x = (i * 7 + 3) as u16 % width;
                let y = (i * 11 + 5) as u16 % height;
                let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
                new.set_raw(x, y, Cell::from_char(ch));
            }

            // Compute diff
            let diff = BufferDiff::compute(&old, &new);

            // Apply diff to old should produce new
            let mut result = old.clone();
            for (x, y) in diff.iter() {
                let cell = *new.get_unchecked(x, y);
                result.set_raw(x, y, cell);
            }

            // Verify buffers match
            for y in 0..height {
                for x in 0..width {
                    let result_cell = result.get_unchecked(x, y);
                    let new_cell = new.get_unchecked(x, y);
                    prop_assert!(
                        result_cell.bits_eq(new_cell),
                        "Mismatch at ({}, {})",
                        x,
                        y
                    );
                }
            }
        });
    }

    // Property: Diff is empty when buffers are identical.
    #[test]
    fn identical_buffers_empty_diff() {
        proptest::proptest!(|(width in 1u16..100, height in 1u16..50)| {
            let buf = Buffer::new(width, height);
            let diff = BufferDiff::compute(&buf, &buf);
            prop_assert!(diff.is_empty(), "Identical buffers should have empty diff");
        });
    }

    // Property: Every change in diff corresponds to an actual difference.
    #[test]
    fn diff_contains_only_real_changes() {
        proptest::proptest!(|(
            width in 5u16..50,
            height in 5u16..30,
            num_changes in 0usize..100,
        )| {
            let old = Buffer::new(width, height);
            let mut new = old.clone();

            for i in 0..num_changes {
                let x = (i * 7 + 3) as u16 % width;
                let y = (i * 11 + 5) as u16 % height;
                new.set_raw(x, y, Cell::from_char('X'));
            }

            let diff = BufferDiff::compute(&old, &new);

            // Every change position should actually differ
            for (x, y) in diff.iter() {
                let old_cell = old.get_unchecked(x, y);
                let new_cell = new.get_unchecked(x, y);
                prop_assert!(
                    !old_cell.bits_eq(new_cell),
                    "Diff includes unchanged cell at ({}, {})",
                    x,
                    y
                );
            }
        });
    }

    // Property: Runs correctly coalesce adjacent changes.
    #[test]
    fn runs_are_contiguous() {
        proptest::proptest!(|(width in 10u16..80, height in 5u16..30)| {
            let old = Buffer::new(width, height);
            let mut new = old.clone();

            // Create some horizontal runs
            for y in 0..height.min(5) {
                for x in 0..width.min(10) {
                    new.set_raw(x, y, Cell::from_char('#'));
                }
            }

            let diff = BufferDiff::compute(&old, &new);
            let runs = diff.runs();

            // Verify each run is contiguous
            for run in runs {
                prop_assert!(run.x1 >= run.x0, "Run has invalid range");
                prop_assert!(!run.is_empty(), "Run should not be empty");

                // Verify all cells in run are actually changed
                for x in run.x0..=run.x1 {
                    let old_cell = old.get_unchecked(x, run.y);
                    let new_cell = new.get_unchecked(x, run.y);
                    prop_assert!(
                        !old_cell.bits_eq(new_cell),
                        "Run includes unchanged cell at ({}, {})",
                        x,
                        run.y
                    );
                }
            }
        });
    }

    // Property: Runs cover all changes exactly once.
    #[test]
    fn runs_cover_all_changes() {
        proptest::proptest!(|(
            width in 10u16..60,
            height in 5u16..30,
            num_changes in 1usize..100,
        )| {
            let old = Buffer::new(width, height);
            let mut new = old.clone();

            for i in 0..num_changes {
                let x = (i * 13 + 7) as u16 % width;
                let y = (i * 17 + 3) as u16 % height;
                new.set_raw(x, y, Cell::from_char('X'));
            }

            let diff = BufferDiff::compute(&old, &new);
            let runs = diff.runs();

            // Count cells covered by runs
            let mut run_cells: std::collections::HashSet<(u16, u16)> =
                std::collections::HashSet::new();
            for run in &runs {
                for x in run.x0..=run.x1 {
                    let was_new = run_cells.insert((x, run.y));
                    prop_assert!(was_new, "Duplicate cell ({}, {}) in runs", x, run.y);
                }
            }

            // Verify runs cover exactly the changes
            for (x, y) in diff.iter() {
                prop_assert!(
                    run_cells.contains(&(x, y)),
                    "Change at ({}, {}) not covered by runs",
                    x,
                    y
                );
            }

            prop_assert_eq!(
                run_cells.len(),
                diff.len(),
                "Run cell count should match diff change count"
            );
        });
    }

    // Property (bd-4kq0.1.2): Block-based scan matches scalar scan
    // for random row widths and change patterns. This verifies the
    // block/remainder handling is correct for all alignment cases.
    #[test]
    fn block_scan_matches_scalar() {
        proptest::proptest!(|(
            width in 1u16..200,
            height in 1u16..20,
            num_changes in 0usize..200,
        )| {
            use crate::cell::PackedRgba;

            let old = Buffer::new(width, height);
            let mut new = Buffer::new(width, height);

            for i in 0..num_changes {
                let x = (i * 13 + 7) as u16 % width;
                let y = (i * 17 + 3) as u16 % height;
                let fg = PackedRgba::rgb(
                    ((i * 31) % 256) as u8,
                    ((i * 47) % 256) as u8,
                    ((i * 71) % 256) as u8,
                );
                new.set_raw(x, y, Cell::from_char('X').with_fg(fg));
            }

            let diff = BufferDiff::compute(&old, &new);

            // Verify against manual scalar scan
            let mut scalar_changes = Vec::new();
            for y in 0..height {
                for x in 0..width {
                    let old_cell = old.get_unchecked(x, y);
                    let new_cell = new.get_unchecked(x, y);
                    if !old_cell.bits_eq(new_cell) {
                        scalar_changes.push((x, y));
                    }
                }
            }

            prop_assert_eq!(
                diff.changes(),
                &scalar_changes[..],
                "Block scan should match scalar scan"
            );
        });
    }

    // ========== Diff Equivalence: dirty+block vs full scan (bd-4kq0.1.3) ==========

    // Property: compute_dirty with all rows dirty matches compute exactly.
    // This verifies the block-scan + dirty-row path is semantically
    // equivalent to the full scan for random buffers.
    #[test]
    fn property_diff_equivalence() {
        proptest::proptest!(|(
            width in 1u16..120,
            height in 1u16..40,
            num_changes in 0usize..300,
        )| {
            let old = Buffer::new(width, height);
            let mut new = Buffer::new(width, height);

            // Apply deterministic pseudo-random changes
            for i in 0..num_changes {
                let x = (i * 13 + 7) as u16 % width;
                let y = (i * 17 + 3) as u16 % height;
                let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
                let fg = crate::cell::PackedRgba::rgb(
                    ((i * 31) % 256) as u8,
                    ((i * 47) % 256) as u8,
                    ((i * 71) % 256) as u8,
                );
                new.set_raw(x, y, Cell::from_char(ch).with_fg(fg));
            }

            let full = BufferDiff::compute(&old, &new);
            let dirty = BufferDiff::compute_dirty(&old, &new);

            prop_assert_eq!(
                full.changes(),
                dirty.changes(),
                "dirty diff must match full diff (width={}, height={}, changes={})",
                width,
                height,
                num_changes
            );

            // Also verify run coalescing is identical
            let full_runs = full.runs();
            let dirty_runs = dirty.runs();
            prop_assert_eq!(full_runs.len(), dirty_runs.len(), "run count must match");
            for (fr, dr) in full_runs.iter().zip(dirty_runs.iter()) {
                prop_assert_eq!(fr, dr, "run mismatch");
            }
        });
    }

    // Property: compute_dirty matches compute for random fill/set operations.
    // This exercises span merging and complex dirty patterns (bd-3e1t.6.4).
    #[test]
    fn property_diff_equivalence_complex_spans() {
        proptest::proptest!(|(
            width in 10u16..100,
            height in 10u16..50,
            ops in proptest::collection::vec(
                prop_oneof![
                    // Single cell set
                    (Just(0u8), any::<u16>(), any::<u16>(), any::<char>()),
                    // Region fill (small rects)
                    (Just(1u8), any::<u16>(), any::<u16>(), any::<char>()),
                ],
                1..50
            )
        )| {
            let old = Buffer::new(width, height);
            let mut new = Buffer::new(width, height);

            // Clear dirty state on new so we start fresh tracking
            new.clear_dirty();

            for (op_type, x, y, ch) in ops {
                let x = x % width;
                let y = y % height;
                let cell = Cell::from_char(ch);

                match op_type {
                    0 => new.set(x, y, cell),
                    1 => {
                        // Random small rect
                        let w = ((x + 10).min(width) - x).max(1);
                        let h = ((y + 5).min(height) - y).max(1);
                        new.fill(Rect::new(x, y, w, h), cell);
                    }
                    _ => unreachable!(),
                }
            }

            let full = BufferDiff::compute(&old, &new);
            let dirty = BufferDiff::compute_dirty(&old, &new);

            prop_assert_eq!(
                full.changes(),
                dirty.changes(),
                "dirty diff (spans) must match full diff; {}",
                super::span_diagnostics(&new)
            );
        });
    }

    // ========== Idempotence Property (bd-1rz0.6) ==========

    // Property: Diff is idempotent - computing diff between identical buffers
    // produces empty diff, and applying diff twice has no additional effect.
    //
    // Invariant: For any buffers A and B:
    //   apply(apply(A, diff(A,B)), diff(A,B)) == apply(A, diff(A,B))
    #[test]
    fn diff_is_idempotent() {
        proptest::proptest!(|(
            width in 5u16..60,
            height in 5u16..30,
            num_changes in 0usize..100,
        )| {
            let mut buf_a = Buffer::new(width, height);
            let mut buf_b = Buffer::new(width, height);

            // Make buf_b different from buf_a
            for i in 0..num_changes {
                let x = (i * 13 + 7) as u16 % width;
                let y = (i * 17 + 3) as u16 % height;
                buf_b.set_raw(x, y, Cell::from_char('X'));
            }

            // Compute diff from A to B
            let diff = BufferDiff::compute(&buf_a, &buf_b);

            // Apply diff to A once
            for (x, y) in diff.iter() {
                let cell = *buf_b.get_unchecked(x, y);
                buf_a.set_raw(x, y, cell);
            }

            // Now buf_a should equal buf_b
            let diff_after_first = BufferDiff::compute(&buf_a, &buf_b);
            prop_assert!(
                diff_after_first.is_empty(),
                "After applying diff once, buffers should be identical (diff was {} changes)",
                diff_after_first.len()
            );

            // Apply diff again (should be no-op since buffers are now equal)
            let before_second = buf_a.clone();
            for (x, y) in diff.iter() {
                let cell = *buf_b.get_unchecked(x, y);
                buf_a.set_raw(x, y, cell);
            }

            // Verify no change from second application
            let diff_after_second = BufferDiff::compute(&before_second, &buf_a);
            prop_assert!(
                diff_after_second.is_empty(),
                "Second diff application should be a no-op"
            );
        });
    }

    // ========== No-Ghosting After Clear Property (bd-1rz0.6) ==========

    // Property: After a full buffer clear (simulating resize), diffing
    // against a blank old buffer captures all content cells.
    //
    // This simulates the no-ghosting invariant: when terminal shrinks,
    // we present against a fresh blank buffer, ensuring no old content
    // persists. The key is that all non-blank cells in the new buffer
    // appear in the diff.
    //
    // Failure mode: If we diff against stale buffer state after resize,
    // some cells might be incorrectly marked as unchanged.
    #[test]
    fn no_ghosting_after_clear() {
        proptest::proptest!(|(
            width in 10u16..80,
            height in 5u16..30,
            num_content_cells in 1usize..200,
        )| {
            // Old buffer is blank (simulating post-resize cleared state)
            let old = Buffer::new(width, height);

            // New buffer has content (the UI to render)
            let mut new = Buffer::new(width, height);
            let mut expected_changes = std::collections::HashSet::new();

            for i in 0..num_content_cells {
                let x = (i * 13 + 7) as u16 % width;
                let y = (i * 17 + 3) as u16 % height;
                new.set_raw(x, y, Cell::from_char('#'));
                expected_changes.insert((x, y));
            }

            let diff = BufferDiff::compute(&old, &new);

            // Every non-blank cell should be in the diff
            // This ensures no "ghosting" - all visible content is explicitly rendered
            for (x, y) in expected_changes {
                let in_diff = diff.iter().any(|(dx, dy)| dx == x && dy == y);
                prop_assert!(
                    in_diff,
                    "Content cell at ({}, {}) missing from diff - would ghost",
                    x,
                    y
                );
            }

            // Also verify the diff doesn't include any extra cells
            for (x, y) in diff.iter() {
                let old_cell = old.get_unchecked(x, y);
                let new_cell = new.get_unchecked(x, y);
                prop_assert!(
                    !old_cell.bits_eq(new_cell),
                    "Diff includes unchanged cell at ({}, {})",
                    x,
                    y
                );
            }
        });
    }

    // ========== Monotonicity Property (bd-1rz0.6) ==========

    // Property: Diff changes are monotonically ordered (row-major).
    // This ensures deterministic iteration order for presentation.
    //
    // Invariant: For consecutive changes (x1,y1) and (x2,y2):
    //   y1 < y2 OR (y1 == y2 AND x1 < x2)
    #[test]
    fn diff_changes_are_monotonic() {
        proptest::proptest!(|(
            width in 10u16..80,
            height in 5u16..30,
            num_changes in 1usize..200,
        )| {
            let old = Buffer::new(width, height);
            let mut new = old.clone();

            // Apply changes in random positions
            for i in 0..num_changes {
                let x = (i * 37 + 11) as u16 % width;
                let y = (i * 53 + 7) as u16 % height;
                new.set_raw(x, y, Cell::from_char('M'));
            }

            let diff = BufferDiff::compute(&old, &new);
            let changes: Vec<_> = diff.iter().collect();

            // Verify monotonic ordering
            for window in changes.windows(2) {
                let (x1, y1) = window[0];
                let (x2, y2) = window[1];

                let is_monotonic = y1 < y2 || (y1 == y2 && x1 < x2);
                prop_assert!(
                    is_monotonic,
                    "Changes not monotonic: ({}, {}) should come before ({}, {})",
                    x1,
                    y1,
                    x2,
                    y2
                );
            }
        });
    }
}

#[cfg(test)]
mod span_edge_cases {
    use super::*;
    use crate::cell::Cell;
    use proptest::prelude::*;

    #[test]
    fn test_span_diff_u16_max_width() {
        // Test near u16::MAX limit (65535)
        let width = 65000;
        let height = 1;
        let old = Buffer::new(width, height);
        let mut new = Buffer::new(width, height);

        // We must clear dirty because Buffer::new starts with all rows dirty
        new.clear_dirty();

        // Set changes at start, middle, end
        new.set_raw(0, 0, Cell::from_char('A'));
        new.set_raw(32500, 0, Cell::from_char('B'));
        new.set_raw(64999, 0, Cell::from_char('C'));

        let full = BufferDiff::compute(&old, &new);
        let dirty = BufferDiff::compute_dirty(&old, &new);

        assert_eq!(full.changes(), dirty.changes());
        assert_eq!(full.len(), 3);

        // Verify changes are what we expect
        let changes = full.changes();
        assert!(changes.contains(&(0, 0)));
        assert!(changes.contains(&(32500, 0)));
        assert!(changes.contains(&(64999, 0)));
    }

    #[test]
    fn test_span_full_row_dirty_overflow() {
        let width = 1000;
        let height = 1;
        let old = Buffer::new(width, height);
        let mut new = Buffer::new(width, height);
        new.clear_dirty(); // All clean

        // Create > 64 spans to force overflow
        // DIRTY_SPAN_MAX_SPANS_PER_ROW is 64
        for i in 0..70 {
            let x = (i * 10) as u16;
            new.set_raw(x, 0, Cell::from_char('X'));
        }

        // Verify it overflowed
        let stats = new.dirty_span_stats();
        assert!(
            stats.rows_full_dirty > 0,
            "Should have overflowed to full row"
        );
        assert_eq!(
            stats.rows_with_spans, 0,
            "Should have cleared spans on overflow"
        );

        let full = BufferDiff::compute(&old, &new);
        let dirty = BufferDiff::compute_dirty(&old, &new);

        assert_eq!(full.changes(), dirty.changes());
        assert_eq!(full.len(), 70);
    }

    #[test]
    fn test_span_diff_empty_rows() {
        let width = 100;
        let height = 10;
        let old = Buffer::new(width, height);
        let mut new = Buffer::new(width, height);
        new.clear_dirty(); // All clean

        // No changes
        let dirty = BufferDiff::compute_dirty(&old, &new);
        assert!(dirty.is_empty());
    }

    proptest! {
        #[test]
        fn property_span_diff_equivalence_large(
            width in 1000u16..5000,
            height in 10u16..50,
            changes in proptest::collection::vec((0u16..5000, 0u16..50), 0..100)
        ) {
            // Cap width/height to avoid OOM in test runner
            let w = width.min(2000);
            let h = height.min(50);

            let old = Buffer::new(w, h);
            let mut new = Buffer::new(w, h);
            new.clear_dirty();

            // Apply changes
            for (raw_x, raw_y) in changes {
                let x = raw_x % w;
                let y = raw_y % h;
                new.set_raw(x, y, Cell::from_char('Z'));
            }

            let full = BufferDiff::compute(&old, &new);
            let dirty = BufferDiff::compute_dirty(&old, &new);

            prop_assert_eq!(
                full.changes(),
                dirty.changes(),
                "Large buffer mismatch: w={}, h={}, {}",
                w,
                h,
                super::span_diagnostics(&new)
            );
        }
    }

    // =========================================================================
    // Certificate-based skip hint tests (bd-i71od)
    // =========================================================================

    #[test]
    fn certified_skip_produces_empty_diff() {
        let old = Buffer::new(10, 5);
        let new = Buffer::new(10, 5);
        let mut diff = BufferDiff::new();

        diff.compute_certified_into(&old, &new, DiffSkipHint::SkipDiff);
        assert!(diff.is_empty(), "SkipDiff should produce zero changes");
    }

    #[test]
    fn certified_full_diff_matches_standard() {
        let old = Buffer::new(10, 5);
        let mut new = Buffer::new(10, 5);
        new.set(3, 2, Cell::from_char('X'));

        let mut standard = BufferDiff::new();
        standard.compute_dirty_into(&old, &new);

        let mut certified = BufferDiff::new();
        certified.compute_certified_into(&old, &new, DiffSkipHint::FullDiff);

        assert_eq!(
            standard.changes(),
            certified.changes(),
            "FullDiff hint should produce identical results to standard dirty diff"
        );
    }

    #[test]
    fn certified_narrow_to_rows_only_diffs_specified_rows() {
        let old = Buffer::new(10, 5);
        let mut new = Buffer::new(10, 5);
        // Change cells in rows 1 and 3
        new.set(2, 1, Cell::from_char('A'));
        new.set(5, 3, Cell::from_char('B'));
        // Also change row 4 (but we won't include it in the hint)
        new.set(7, 4, Cell::from_char('C'));

        let mut diff = BufferDiff::new();
        diff.compute_certified_into(&old, &new, DiffSkipHint::NarrowToRows(vec![1, 3]));

        // Should find changes in rows 1 and 3, but NOT row 4
        let changes = diff.changes();
        assert!(
            changes.iter().any(|&(x, y)| x == 2 && y == 1),
            "should find change at (2, 1)"
        );
        assert!(
            changes.iter().any(|&(x, y)| x == 5 && y == 3),
            "should find change at (5, 3)"
        );
        assert!(
            !changes.iter().any(|&(_, y)| y == 4),
            "should NOT find changes in row 4 (not in hint)"
        );
    }

    #[test]
    fn certified_narrow_skips_clean_rows() {
        let old = Buffer::new(10, 5);
        let new = Buffer::new(10, 5);

        let mut diff = BufferDiff::new();
        diff.compute_certified_into(&old, &new, DiffSkipHint::NarrowToRows(vec![0, 2, 4]));

        assert!(
            diff.is_empty(),
            "narrowing to clean rows should produce zero changes"
        );
    }

    #[test]
    fn certified_narrow_out_of_bounds_rows_ignored() {
        let old = Buffer::new(10, 5);
        let mut new = Buffer::new(10, 5);
        new.set(0, 0, Cell::from_char('X'));

        let mut diff = BufferDiff::new();
        diff.compute_certified_into(
            &old,
            &new,
            DiffSkipHint::NarrowToRows(vec![0, 100, 200]), // 100, 200 are out of bounds
        );

        assert_eq!(diff.len(), 1, "should find the one change in row 0");
        assert_eq!(diff.changes()[0], (0, 0));
    }

    #[test]
    fn diff_skip_hint_labels() {
        assert_eq!(DiffSkipHint::FullDiff.label(), "full-diff");
        assert_eq!(DiffSkipHint::SkipDiff.label(), "skip-diff");
        assert_eq!(DiffSkipHint::NarrowToRows(vec![]).label(), "narrow-to-rows");
    }

    #[test]
    fn diff_skip_hint_skips_work() {
        assert!(!DiffSkipHint::FullDiff.skips_work());
        assert!(DiffSkipHint::SkipDiff.skips_work());
        assert!(DiffSkipHint::NarrowToRows(vec![1]).skips_work());
    }
}