fret-ui 0.1.0

Mechanism-layer UI engine for Fret with tree, layout, focus, routing, and interaction contracts.
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
use super::super::ElementHostWidget;
use crate::declarative::layout_helpers::clamp_to_constraints;
use crate::declarative::prelude::*;

use crate::cache_key::CacheKeyBuilder;
use crate::layout_constraints::{AvailableSpace, LayoutConstraints, LayoutSize};
use crate::tree::{
    UiDebugInvalidationDetail, UiDebugInvalidationSource, UiDebugScrollAxis,
    UiDebugScrollNodeTelemetry, UiDebugScrollOverflowObservationTelemetry,
};
use fret_core::FrameId;
use fret_core::time::{Duration, Instant};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::OnceLock;

#[derive(Debug, Clone)]
struct ScrollLayoutProfileConfig {
    min_elapsed: Duration,
    min_self_measure: Duration,
}

impl ScrollLayoutProfileConfig {
    fn from_env() -> Option<Self> {
        let cfg = crate::runtime_config::ui_runtime_config().scroll_layout_profile?;
        Some(Self {
            min_elapsed: cfg.min_elapsed,
            min_self_measure: cfg.min_self_measure,
        })
    }
}

fn scroll_layout_profile_config() -> Option<&'static ScrollLayoutProfileConfig> {
    static CONFIG: OnceLock<Option<ScrollLayoutProfileConfig>> = OnceLock::new();
    CONFIG
        .get_or_init(ScrollLayoutProfileConfig::from_env)
        .as_ref()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ScrollLayoutProbeKey {
    avail_w: u64,
    avail_h: u64,
}

#[derive(Debug, Default, Clone)]
struct ScrollLayoutProbeCacheState {
    frame_id: FrameId,
    entries: Vec<(ScrollLayoutProbeKey, Size)>,
    last_max_child: Size,
}

fn available_space_cache_key(space: AvailableSpace) -> u64 {
    match space {
        AvailableSpace::Definite(px) => px.0.to_bits() as u64,
        AvailableSpace::MinContent => 1 << 62,
        AvailableSpace::MaxContent => 2 << 62,
    }
}

fn scroll_defer_unbounded_probe_on_resize_enabled() -> bool {
    crate::runtime_config::ui_runtime_config().scroll_defer_unbounded_probe_on_resize
}

fn scroll_defer_unbounded_probe_on_invalidation_enabled() -> bool {
    crate::runtime_config::ui_runtime_config().scroll_defer_unbounded_probe_on_invalidation
}

fn scroll_defer_unbounded_probe_stable_frames() -> u8 {
    crate::runtime_config::ui_runtime_config().scroll_defer_unbounded_probe_stable_frames
}

fn scroll_overflow_observation_is_authoritative(
    observation: UiDebugScrollOverflowObservationTelemetry,
) -> bool {
    !observation.deep_scan_budget_hit
        && (!observation.wrapper_peel_budget_hit || observation.deep_scan_enabled)
}

fn scroll_overflow_observation_needs_follow_up_probe(
    observation: UiDebugScrollOverflowObservationTelemetry,
) -> bool {
    (observation.wrapper_peel_budget_hit || observation.deep_scan_budget_hit)
        && !scroll_overflow_observation_is_authoritative(observation)
}

fn maybe_schedule_extent_probe_after_observation_budget_hit<H: UiHost>(
    app: &mut H,
    tree: &mut UiTree<H>,
    window: AppWindowId,
    node: NodeId,
    element: GlobalElementId,
    observation: UiDebugScrollOverflowObservationTelemetry,
) -> bool {
    // If we cannot confidently observe overflow in post-layout geometry (budget hit), schedule a
    // measured unbounded probe on the next frame. A wrapper-peel budget hit alone is not fatal if
    // the subsequent deep scan completed and reconstructed an authoritative descendant frontier.
    if !scroll_overflow_observation_needs_follow_up_probe(observation) {
        return false;
    }

    let first_set = crate::elements::with_element_state(
        app,
        window,
        element,
        crate::element::ScrollState::default,
        |state| {
            let prev = state.pending_extent_probe;
            state.pending_extent_probe = true;
            !prev
        },
    );
    if !first_set {
        return false;
    }

    tree.schedule_barrier_relayout_with_source_and_detail(
        node,
        UiDebugInvalidationSource::Other,
        UiDebugInvalidationDetail::ScrollExtentsObservationBudgetHit,
    );
    true
}

trait ScrollOverflowTree {
    fn children_ref(&self, node: NodeId) -> &[NodeId];
    fn node_bounds(&self, node: NodeId) -> Option<Rect>;
    fn node_is_absolute(&mut self, node: NodeId) -> bool;
    fn node_clips_descendant_scroll_overflow(&mut self, node: NodeId) -> bool;
}

struct UiTreeScrollOverflowTree<'a, 'b, H: UiHost> {
    tree: &'a crate::tree::UiTree<H>,
    app: &'b mut H,
    window: AppWindowId,
}

impl<H: UiHost> ScrollOverflowTree for UiTreeScrollOverflowTree<'_, '_, H> {
    fn children_ref(&self, node: NodeId) -> &[NodeId] {
        self.tree.children_ref(node)
    }

    fn node_bounds(&self, node: NodeId) -> Option<Rect> {
        self.tree.node_bounds(node)
    }

    fn node_is_absolute(&mut self, node: NodeId) -> bool {
        crate::declarative::frame::layout_style_for_node(self.app, self.window, node).position
            == crate::element::PositionStyle::Absolute
    }

    fn node_clips_descendant_scroll_overflow(&mut self, node: NodeId) -> bool {
        let layout_clips = matches!(
            crate::declarative::frame::layout_style_for_node(self.app, self.window, node).overflow,
            crate::element::Overflow::Clip
        );
        layout_clips
            || crate::declarative::frame::element_record_for_node(self.app, self.window, node)
                .is_some_and(|record| {
                    matches!(
                        record.instance,
                        crate::declarative::frame::ElementInstance::Scroll(_)
                            | crate::declarative::frame::ElementInstance::ViewportSurface(_)
                            | crate::declarative::frame::ElementInstance::VirtualList(_)
                    )
                })
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct ScrollOverflowObservedExtents {
    loose: Size,
    trusted: Size,
}

#[derive(Debug, Clone)]
struct ScrollOverflowObservedNode {
    extent: Size,
    children: Vec<NodeId>,
    pinned_to_content_extent_x: bool,
    pinned_to_content_extent_y: bool,
}

const SCROLL_OVERFLOW_NONLEAF_OVERSHOOT_TOLERANCE: f32 = 32.0;

fn record_scroll_overflow_candidate<T: ScrollOverflowTree>(
    tree: &T,
    axis: crate::element::ScrollAxis,
    extent_may_be_stale: bool,
    content_size: Size,
    node: NodeId,
    right: f32,
    bottom: f32,
    root_loose: &mut Size,
    root_trusted: &mut Size,
    root_suspicious_nonleaf_x: &mut bool,
    root_suspicious_nonleaf_y: &mut bool,
) {
    root_loose.width = Px(root_loose.width.0.max(right));
    root_loose.height = Px(root_loose.height.0.max(bottom));

    let node_has_children = !tree.children_ref(node).is_empty();
    let suspicious_x = axis.scroll_x()
        && extent_may_be_stale
        && node_has_children
        && right + 0.5 >= content_size.width.0;
    let suspicious_y = axis.scroll_y()
        && extent_may_be_stale
        && node_has_children
        && bottom + 0.5 >= content_size.height.0;

    if suspicious_x {
        *root_suspicious_nonleaf_x = true;
    } else {
        root_trusted.width = Px(root_trusted.width.0.max(right));
    }
    if suspicious_y {
        *root_suspicious_nonleaf_y = true;
    } else {
        root_trusted.height = Px(root_trusted.height.0.max(bottom));
    }
}

fn trust_scroll_overflow_nonleaf_axis(
    own: f32,
    child_frontier: f32,
    child_count: usize,
    pinned_to_content_extent: bool,
) -> Px {
    let own = own.max(0.0);
    let child_frontier = child_frontier.max(0.0);
    if child_frontier <= 0.0 {
        return Px(own);
    }
    if own + 0.5 < child_frontier {
        return Px(child_frontier);
    }
    if child_count != 1 {
        return Px(own.max(child_frontier));
    }
    if pinned_to_content_extent && child_frontier + 0.5 < own {
        return Px(child_frontier);
    }
    if own <= child_frontier + SCROLL_OVERFLOW_NONLEAF_OVERSHOOT_TOLERANCE {
        return Px(own.max(child_frontier));
    }
    Px(child_frontier)
}

fn validate_scroll_overflow_observed_subtree(
    nodes: &HashMap<NodeId, ScrollOverflowObservedNode>,
    node: NodeId,
    memo: &mut HashMap<NodeId, Size>,
) -> Size {
    if let Some(size) = memo.get(&node).copied() {
        return size;
    }

    let Some(info) = nodes.get(&node) else {
        return Size::new(Px(0.0), Px(0.0));
    };

    let mut child_frontier = Size::new(Px(0.0), Px(0.0));
    let mut has_child = false;
    for &child in &info.children {
        let Some(_) = nodes.get(&child) else {
            continue;
        };
        has_child = true;
        let validated = validate_scroll_overflow_observed_subtree(nodes, child, memo);
        child_frontier.width = Px(child_frontier.width.0.max(validated.width.0));
        child_frontier.height = Px(child_frontier.height.0.max(validated.height.0));
    }

    let trusted = if has_child {
        Size::new(
            trust_scroll_overflow_nonleaf_axis(
                info.extent.width.0,
                child_frontier.width.0,
                info.children.len(),
                info.pinned_to_content_extent_x,
            ),
            trust_scroll_overflow_nonleaf_axis(
                info.extent.height.0,
                child_frontier.height.0,
                info.children.len(),
                info.pinned_to_content_extent_y,
            ),
        )
    } else {
        info.extent
    };
    memo.insert(node, trusted);
    trusted
}

fn observe_scroll_overflow_extents<T: ScrollOverflowTree>(
    tree: &mut T,
    barrier_roots: &[NodeId],
    content_bounds: Rect,
    axis: crate::element::ScrollAxis,
    content_size: Size,
    extent_may_be_stale: bool,
    deep_scan_allowed: bool,
) -> (
    ScrollOverflowObservedExtents,
    UiDebugScrollOverflowObservationTelemetry,
) {
    let mut observed_loose = Size::new(Px(0.0), Px(0.0));
    let mut observed_trusted = Size::new(Px(0.0), Px(0.0));
    const MAX_BARRIER_WRAPPER_CHAIN: usize = 8;
    const OVERFLOW_SCAN_BUDGET_NODES: usize = 4096;

    let mut wrapper_peeled_max: u8 = 0;
    let mut wrapper_peel_budget_hit: bool = false;
    let mut immediate_children_visited: u16 = 0;
    let mut immediate_children_skipped_absolute: u16 = 0;
    let mut deep_scan_enabled: bool = false;
    let mut deep_scan_visited: u16 = 0;
    let mut deep_scan_budget_hit: bool = false;
    let mut deep_scan_skipped_absolute: u16 = 0;

    for &barrier_root in barrier_roots {
        let mut root_loose = Size::new(Px(0.0), Px(0.0));
        let mut root_trusted = Size::new(Px(0.0), Px(0.0));
        let mut root_suspicious_nonleaf_x = false;
        let mut root_suspicious_nonleaf_y = false;

        // Peel common "same-bounds wrapper" chains (e.g. interactivity gates / test-id wrappers)
        // so we can observe extents from the first node whose children may actually overflow the
        // forced `content_bounds` rect.
        let mut observe_root = barrier_root;
        let mut peeled: u8 = 0;
        for _ in 0..MAX_BARRIER_WRAPPER_CHAIN {
            let children = tree.children_ref(observe_root);
            if children.len() != 1 {
                break;
            }
            let child = children[0];
            if tree.node_is_absolute(child) || tree.node_clips_descendant_scroll_overflow(child) {
                break;
            }
            let Some(parent_bounds) = tree.node_bounds(observe_root) else {
                break;
            };
            let Some(child_bounds) = tree.node_bounds(child) else {
                break;
            };
            let same_origin = (parent_bounds.origin.x.0 - child_bounds.origin.x.0).abs() <= 0.5
                && (parent_bounds.origin.y.0 - child_bounds.origin.y.0).abs() <= 0.5;
            let same_size = (parent_bounds.size.width.0 - child_bounds.size.width.0).abs() <= 0.5
                && (parent_bounds.size.height.0 - child_bounds.size.height.0).abs() <= 0.5;
            if same_origin && same_size {
                observe_root = child;
                peeled = peeled.saturating_add(1);
                continue;
            }
            break;
        }
        wrapper_peeled_max = wrapper_peeled_max.max(peeled);
        if (peeled as usize) >= MAX_BARRIER_WRAPPER_CHAIN {
            wrapper_peel_budget_hit = true;
        }

        // Scroll content is commonly implemented as a layout barrier root whose bounds are forced
        // to `content_bounds`. When descendants overflow that forced rect, `node_bounds` at the
        // barrier root can under-report the true content extent.
        //
        // Prefer observing immediate children of the barrier root, but keep the peeled root's own
        // bounds as a baseline when they differ from the forced `content_bounds` rect. That
        // preserves shell/padding contribution for real content roots while still ignoring the
        // synthetic wrapper case where the root is just the forced scroll content box.
        let mut any = false;
        if let Some(bounds) = tree.node_bounds(observe_root) {
            let same_origin = (bounds.origin.x.0 - content_bounds.origin.x.0).abs() <= 0.5
                && (bounds.origin.y.0 - content_bounds.origin.y.0).abs() <= 0.5;
            let same_size = (bounds.size.width.0 - content_bounds.size.width.0).abs() <= 0.5
                && (bounds.size.height.0 - content_bounds.size.height.0).abs() <= 0.5;
            if !(same_origin && same_size) {
                let right =
                    (bounds.origin.x.0 + bounds.size.width.0 - content_bounds.origin.x.0).max(0.0);
                let bottom =
                    (bounds.origin.y.0 + bounds.size.height.0 - content_bounds.origin.y.0).max(0.0);
                // The scroll barrier root's own laid-out bounds are authoritative for the current
                // frame. The stale-wrapper guard applies to descendants under that root, not to
                // the barrier root itself; otherwise explicit-size content roots (for example a
                // 100.2px tall container inside a 50px viewport) would never be allowed to grow
                // on the initial clean frame.
                root_loose.width = Px(root_loose.width.0.max(right));
                root_loose.height = Px(root_loose.height.0.max(bottom));
                root_trusted.width = Px(root_trusted.width.0.max(right));
                root_trusted.height = Px(root_trusted.height.0.max(bottom));
            }
        }
        let observe_children: Vec<NodeId> = tree.children_ref(observe_root).to_vec();
        for child in observe_children {
            immediate_children_visited = immediate_children_visited.saturating_add(1);
            if tree.node_is_absolute(child) {
                immediate_children_skipped_absolute =
                    immediate_children_skipped_absolute.saturating_add(1);
                continue;
            }
            let Some(bounds) = tree.node_bounds(child) else {
                continue;
            };
            any = true;
            // `node_bounds` are expressed in layout-space (pre-transform) coordinates. For scroll
            // containers, descendants remain in content space while hit-testing/painting apply
            // `children_render_transform()` separately. Compute content-space extents directly
            // from the layout bounds without incorporating the current scroll offset.
            let right =
                (bounds.origin.x.0 + bounds.size.width.0 - content_bounds.origin.x.0).max(0.0);
            let bottom =
                (bounds.origin.y.0 + bounds.size.height.0 - content_bounds.origin.y.0).max(0.0);
            record_scroll_overflow_candidate(
                &*tree,
                axis,
                extent_may_be_stale,
                content_size,
                child,
                right,
                bottom,
                &mut root_loose,
                &mut root_trusted,
                &mut root_suspicious_nonleaf_x,
                &mut root_suspicious_nonleaf_y,
            );
        }
        if !any {
            let Some(bounds) = tree.node_bounds(observe_root) else {
                continue;
            };
            let right =
                (bounds.origin.x.0 + bounds.size.width.0 - content_bounds.origin.x.0).max(0.0);
            let bottom =
                (bounds.origin.y.0 + bounds.size.height.0 - content_bounds.origin.y.0).max(0.0);
            record_scroll_overflow_candidate(
                &*tree,
                axis,
                extent_may_be_stale,
                content_size,
                observe_root,
                right,
                bottom,
                &mut root_loose,
                &mut root_trusted,
                &mut root_suspicious_nonleaf_x,
                &mut root_suspicious_nonleaf_y,
            );
        }

        let deep_scan_needed = deep_scan_allowed
            && extent_may_be_stale
            && ((axis.scroll_x()
                && (root_trusted.width.0 <= content_size.width.0 + 0.5
                    || root_suspicious_nonleaf_x))
                || (axis.scroll_y()
                    && (root_trusted.height.0 <= content_size.height.0 + 0.5
                        || root_suspicious_nonleaf_y)));
        if deep_scan_needed {
            deep_scan_enabled = true;
            // When extents may be stale, a bounded descendant scan needs a second validation step:
            // wrapper shells can be shorter or taller than the real content subtree. GPUI/Zed only
            // clamps scroll ranges from authoritative content bounds in the same pass; here we
            // reconstruct that authority conservatively by trusting descendant-supported frontiers
            // and rejecting large non-leaf overshoots.
            let mut visited: usize = 0;
            let mut stack: Vec<NodeId> = vec![observe_root];
            let mut observed_nodes: HashMap<NodeId, ScrollOverflowObservedNode> = HashMap::new();
            while let Some(id) = stack.pop() {
                visited = visited.saturating_add(1);
                if visited > OVERFLOW_SCAN_BUDGET_NODES {
                    deep_scan_budget_hit = true;
                    break;
                }
                deep_scan_visited = deep_scan_visited.max(visited as u16);
                if id != observe_root && tree.node_is_absolute(id) {
                    deep_scan_skipped_absolute = deep_scan_skipped_absolute.saturating_add(1);
                    continue;
                }
                let Some(bounds) = tree.node_bounds(id) else {
                    continue;
                };
                let right =
                    (bounds.origin.x.0 + bounds.size.width.0 - content_bounds.origin.x.0).max(0.0);
                let bottom =
                    (bounds.origin.y.0 + bounds.size.height.0 - content_bounds.origin.y.0).max(0.0);
                root_loose.width = Px(root_loose.width.0.max(right));
                root_loose.height = Px(root_loose.height.0.max(bottom));

                let mut children: Vec<NodeId> = Vec::new();
                // Nested scroll/viewport roots clip their own content frontier, so an ancestor
                // overflow scan must trust the nested viewport bounds and stop before its
                // descendants reintroduce the inner scroll content extent.
                let stop_at_nested_scroll_boundary =
                    id != observe_root && tree.node_clips_descendant_scroll_overflow(id);
                if !stop_at_nested_scroll_boundary {
                    let child_ids: Vec<NodeId> = tree.children_ref(id).to_vec();
                    for child in child_ids {
                        if tree.node_is_absolute(child) {
                            deep_scan_skipped_absolute =
                                deep_scan_skipped_absolute.saturating_add(1);
                            continue;
                        }
                        children.push(child);
                    }
                }
                for &child in children.iter().rev() {
                    stack.push(child);
                }
                observed_nodes.insert(
                    id,
                    ScrollOverflowObservedNode {
                        extent: Size::new(Px(right), Px(bottom)),
                        children,
                        pinned_to_content_extent_x: axis.scroll_x()
                            && extent_may_be_stale
                            && right + 0.5 >= content_size.width.0,
                        pinned_to_content_extent_y: axis.scroll_y()
                            && extent_may_be_stale
                            && bottom + 0.5 >= content_size.height.0,
                    },
                );
            }

            if observed_nodes.get(&observe_root).is_some() {
                let mut memo: HashMap<NodeId, Size> = HashMap::new();
                root_trusted = validate_scroll_overflow_observed_subtree(
                    &observed_nodes,
                    observe_root,
                    &mut memo,
                );
            }
        }

        observed_loose.width = Px(observed_loose.width.0.max(root_loose.width.0));
        observed_loose.height = Px(observed_loose.height.0.max(root_loose.height.0));
        observed_trusted.width = Px(observed_trusted.width.0.max(root_trusted.width.0));
        observed_trusted.height = Px(observed_trusted.height.0.max(root_trusted.height.0));
    }

    (
        ScrollOverflowObservedExtents {
            loose: observed_loose,
            trusted: observed_trusted,
        },
        UiDebugScrollOverflowObservationTelemetry {
            extent_may_be_stale,
            barrier_roots: barrier_roots.len().min(u8::MAX as usize) as u8,
            wrapper_peel_budget: MAX_BARRIER_WRAPPER_CHAIN.min(u8::MAX as usize) as u8,
            wrapper_peeled_max,
            wrapper_peel_budget_hit,
            immediate_children_visited,
            immediate_children_skipped_absolute,
            deep_scan_enabled,
            deep_scan_budget_nodes: OVERFLOW_SCAN_BUDGET_NODES.min(u16::MAX as usize) as u16,
            deep_scan_visited,
            deep_scan_budget_hit,
            deep_scan_skipped_absolute,
        },
    )
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum ScrollDeferredUnboundedProbeKind {
    #[default]
    None,
    Invalidation,
    Resize,
}

#[derive(Debug, Default, Clone, Copy)]
struct ScrollDeferredUnboundedProbeState {
    kind: ScrollDeferredUnboundedProbeKind,
    stable_frames: u8,
    pending_invalidation_probe: bool,
}

fn non_default_size(size: Size) -> Option<Size> {
    (size != Size::default()).then_some(size)
}

fn scroll_measure_child_constraints(
    axis: crate::element::ScrollAxis,
    probe_unbounded_for_measure: bool,
    available: Size,
) -> LayoutConstraints {
    LayoutConstraints::new(
        LayoutSize::new(None, None),
        LayoutSize::new(
            if axis.scroll_x() && probe_unbounded_for_measure {
                AvailableSpace::MaxContent
            } else if probe_unbounded_for_measure && available.width.0 <= 0.0 {
                // Intrinsic sizing flows may pass `available.width = 0` as a placeholder for
                // "unknown" even when the scroll axis is vertical. Treat it as unbounded so the
                // child can contribute its intrinsic cross size.
                AvailableSpace::MaxContent
            } else {
                AvailableSpace::Definite(available.width)
            },
            if axis.scroll_y() && probe_unbounded_for_measure {
                AvailableSpace::MaxContent
            } else if probe_unbounded_for_measure && available.height.0 <= 0.0 {
                // Same as above, but for the vertical cross axis.
                AvailableSpace::MaxContent
            } else {
                AvailableSpace::Definite(available.height)
            },
        ),
    )
}

fn scroll_intrinsic_measure_cache_key(
    axis: crate::element::ScrollAxis,
    child_constraints: LayoutConstraints,
    scale_factor: f32,
) -> crate::element::ScrollIntrinsicMeasureCacheKey {
    crate::element::ScrollIntrinsicMeasureCacheKey {
        avail_w: available_space_cache_key(child_constraints.available.width),
        avail_h: available_space_cache_key(child_constraints.available.height),
        axis: match axis {
            crate::element::ScrollAxis::X => 0,
            crate::element::ScrollAxis::Y => 1,
            crate::element::ScrollAxis::Both => 2,
        },
        probe_unbounded: matches!(
            child_constraints.available.width,
            AvailableSpace::MaxContent
        ) || matches!(
            child_constraints.available.height,
            AvailableSpace::MaxContent
        ),
        scale_bits: scale_factor.to_bits(),
    }
}

#[derive(Debug, Default, Clone, Copy)]
struct ScrollProbeSeed {
    intrinsic_cached_max_child: Option<Size>,
    cached_max_child: Option<Size>,
    retained_measured_max_child: Option<Size>,
    last_max_child: Option<Size>,
}

impl ScrollProbeSeed {
    fn can_defer_with_seed(self) -> bool {
        self.deferred_max_child().is_some()
    }

    fn deferred_max_child(self) -> Option<Size> {
        self.cached_max_child
            .or(self.intrinsic_cached_max_child)
            .or(self.last_max_child)
            .or(self.retained_measured_max_child)
    }
}

fn resolve_retained_measured_max_child<H: UiHost>(cx: &LayoutCx<'_, H>) -> Option<Size> {
    let mut max_child = Size::new(Px(0.0), Px(0.0));
    let mut found = false;

    for &child in cx.children {
        if let Some(size) = cx.tree.node_measured_size(child).and_then(non_default_size) {
            found = true;
            max_child.width = Px(max_child.width.0.max(size.width.0));
            max_child.height = Px(max_child.height.0.max(size.height.0));
        }
    }

    found.then_some(max_child)
}

fn resolve_scroll_probe_seed<H: UiHost>(
    cx: &LayoutCx<'_, H>,
    intrinsic_measure_cache: Option<crate::element::ScrollIntrinsicMeasureCache>,
    intrinsic_cache_key: Option<crate::element::ScrollIntrinsicMeasureCacheKey>,
    retained_measured_max_child: Option<Size>,
    last_max_child: Option<Size>,
    at_end_with_invalidated_child: bool,
) -> ScrollProbeSeed {
    let mut seed = ScrollProbeSeed {
        retained_measured_max_child,
        last_max_child,
        ..Default::default()
    };

    if let Some(cache_key) = intrinsic_cache_key
        && cx.children.len() == 1
    {
        let child = cx.children[0];
        seed.intrinsic_cached_max_child = intrinsic_measure_cache
            .and_then(|cache| (cache.key == cache_key).then_some(cache.max_child))
            .and_then(non_default_size);
        if !at_end_with_invalidated_child && !cx.tree.node_needs_layout(child) {
            seed.cached_max_child = seed.intrinsic_cached_max_child;
        }
    }

    seed
}

#[derive(Debug, Clone, Copy)]
struct ScrollDeferredProbeInputs {
    force_probe_now: bool,
    wants_unbounded_probe: bool,
    can_defer_with_seed: bool,
    defer_probe_on_invalidation: bool,
    should_defer_on_resize: bool,
    should_defer_on_invalidation: bool,
    children_layout_invalidated: bool,
    at_scroll_extent_edge: bool,
    stable_frames_required: u8,
}

fn clear_scroll_deferred_probe_state(state: &mut ScrollDeferredUnboundedProbeState) {
    state.kind = ScrollDeferredUnboundedProbeKind::None;
    state.stable_frames = 0;
    state.pending_invalidation_probe = false;
}

fn update_scroll_deferred_probe_state(
    state: &mut ScrollDeferredUnboundedProbeState,
    inputs: ScrollDeferredProbeInputs,
) -> bool {
    let mut defer_this_frame = false;

    if inputs.force_probe_now || !inputs.wants_unbounded_probe || !inputs.can_defer_with_seed {
        clear_scroll_deferred_probe_state(state);
        return false;
    }

    if inputs.should_defer_on_resize {
        defer_this_frame = true;
        state.kind = ScrollDeferredUnboundedProbeKind::Resize;
        state.stable_frames = 0;
        return defer_this_frame;
    }

    match state.kind {
        ScrollDeferredUnboundedProbeKind::Resize => {
            if inputs.stable_frames_required == 0 {
                clear_scroll_deferred_probe_state(state);
            } else {
                state.stable_frames = state.stable_frames.saturating_add(1);
                if state.stable_frames < inputs.stable_frames_required {
                    defer_this_frame = true;
                } else {
                    clear_scroll_deferred_probe_state(state);
                }
            }
        }
        ScrollDeferredUnboundedProbeKind::Invalidation => {
            // Under view-cache reconciliation, descendants can remain layout-invalidated for
            // multiple frames. Keep deferring while invalidated, and only allow the expensive
            // unbounded probe once the subtree stabilizes for a few frames.
            if inputs.at_scroll_extent_edge || !inputs.defer_probe_on_invalidation {
                clear_scroll_deferred_probe_state(state);
            } else if inputs.children_layout_invalidated {
                defer_this_frame = true;
                state.pending_invalidation_probe = true;
                state.stable_frames = 0;
            } else if inputs.stable_frames_required == 0 {
                clear_scroll_deferred_probe_state(state);
            } else {
                state.stable_frames = state.stable_frames.saturating_add(1);
                if state.stable_frames < inputs.stable_frames_required {
                    defer_this_frame = true;
                } else {
                    clear_scroll_deferred_probe_state(state);
                }
            }
        }
        ScrollDeferredUnboundedProbeKind::None => {
            if inputs.should_defer_on_invalidation {
                defer_this_frame = true;
                state.kind = ScrollDeferredUnboundedProbeKind::Invalidation;
                state.pending_invalidation_probe = true;
                state.stable_frames = 0;
            }
        }
    }

    defer_this_frame
}

#[derive(Debug, Clone, Copy)]
struct ScrollAuthoritativeExtentCommit {
    max_child: Size,
    intrinsic_cache_key: Option<crate::element::ScrollIntrinsicMeasureCacheKey>,
    probe_cache_key: Option<(FrameId, ScrollLayoutProbeKey)>,
    clear_pending_invalidation_probe: bool,
    clear_pending_extent_probe: bool,
}

fn commit_scroll_authoritative_extent<H: UiHost>(
    app: &mut H,
    window: AppWindowId,
    element: GlobalElementId,
    commit: ScrollAuthoritativeExtentCommit,
) {
    crate::elements::with_element_state(
        app,
        window,
        element,
        ScrollLayoutProbeCacheState::default,
        |state| {
            if let Some((frame_id, key)) = commit.probe_cache_key {
                if state.frame_id != frame_id {
                    state.frame_id = frame_id;
                    state.entries.clear();
                }
                state.entries.push((key, commit.max_child));
            }
            state.last_max_child = commit.max_child;
        },
    );

    if commit.clear_pending_invalidation_probe {
        crate::elements::with_element_state(
            app,
            window,
            element,
            ScrollDeferredUnboundedProbeState::default,
            clear_scroll_deferred_probe_state,
        );
    }

    crate::elements::with_element_state(
        app,
        window,
        element,
        crate::element::ScrollState::default,
        |state| {
            if commit.clear_pending_extent_probe {
                state.pending_extent_probe = false;
            }
            state.intrinsic_measure_cache =
                commit
                    .intrinsic_cache_key
                    .map(|key| crate::element::ScrollIntrinsicMeasureCache {
                        key,
                        max_child: commit.max_child,
                    });
        },
    );
}

impl ElementHostWidget {
    pub(super) fn layout_virtual_list_impl<H: UiHost>(
        &mut self,
        cx: &mut LayoutCx<'_, H>,
        window: AppWindowId,
        props: crate::element::VirtualListProps,
    ) -> Size {
        let axis = props.axis;
        let (
            mut metrics,
            prev_items_revision,
            render_window_range,
            prev_window_range,
            prev_offset_x,
            prev_offset_y,
            prev_viewport_w,
            prev_viewport_h,
            mut layout_scratch,
        ) = crate::elements::with_element_state(
            &mut *cx.app,
            window,
            self.element,
            crate::element::VirtualListState::default,
            |state| {
                state.metrics.ensure_with_mode(
                    props.measure_mode,
                    props.len,
                    props.estimate_row_height,
                    props.gap,
                    props.scroll_margin,
                );
                (
                    std::mem::take(&mut state.metrics),
                    state.items_revision,
                    state.render_window_range,
                    state.window_range,
                    state.offset_x,
                    state.offset_y,
                    state.viewport_w,
                    state.viewport_h,
                    std::mem::take(&mut state.layout_scratch),
                )
            },
        );
        let content_extent = metrics.total_height();
        let should_remeasure_visible_items = props.items_revision != prev_items_revision;

        let desired_w = match props.layout.size.width {
            Length::Px(px) => Px(px.0.max(0.0)),
            Length::Fill => cx.available.width,
            Length::Fraction(f) => {
                let f = if f.is_finite() { f.max(0.0) } else { 0.0 };
                Px((cx.available.width.0 * f).max(0.0))
            }
            Length::Auto => match axis {
                fret_core::Axis::Vertical => cx.available.width,
                fret_core::Axis::Horizontal => {
                    Px(content_extent.0.min(cx.available.width.0.max(0.0)))
                }
            },
        };
        let desired_h = match props.layout.size.height {
            Length::Px(px) => Px(px.0.max(0.0)),
            Length::Fill => cx.available.height,
            Length::Fraction(f) => {
                let f = if f.is_finite() { f.max(0.0) } else { 0.0 };
                Px((cx.available.height.0 * f).max(0.0))
            }
            Length::Auto => match axis {
                fret_core::Axis::Vertical => {
                    Px(content_extent.0.min(cx.available.height.0.max(0.0)))
                }
                fret_core::Axis::Horizontal => cx.available.height,
            },
        };

        let size =
            clamp_to_constraints(Size::new(desired_w, desired_h), props.layout, cx.available);
        let viewport = match axis {
            fret_core::Axis::Vertical => Px(size.height.0.max(0.0)),
            fret_core::Axis::Horizontal => Px(size.width.0.max(0.0)),
        };
        let mut needs_redraw = false;

        let cross_extent = match axis {
            fret_core::Axis::Vertical => size.width,
            fret_core::Axis::Horizontal => size.height,
        };
        if metrics.reset_measured_cache_if_cross_extent_changed(cross_extent) {
            needs_redraw = true;
        }

        props.scroll_handle.set_items_count(props.len);
        self.scroll_child_transform = Some(super::super::ScrollChildTransform {
            handle: props.scroll_handle.base_handle().clone(),
            axis: match axis {
                fret_core::Axis::Vertical => crate::element::ScrollAxis::Y,
                fret_core::Axis::Horizontal => crate::element::ScrollAxis::X,
            },
        });

        let handle_offset = props.scroll_handle.offset();
        let handle_offset_axis = match axis {
            fret_core::Axis::Vertical => handle_offset.y,
            fret_core::Axis::Horizontal => handle_offset.x,
        };
        let mut offset = metrics.clamp_offset(handle_offset_axis, viewport);
        let deferred_scroll_to_item = props.scroll_handle.deferred_scroll_to_item().is_some();
        let mut deferred_scroll_consumed = false;

        // Avoid consuming deferred scroll requests during "probe" layout passes that use an
        // effectively-unbounded available space. Those passes are not the final viewport
        // constraints and would
        // otherwise clear the request before the real layout happens.
        let is_probe_layout = cx.pass_kind == crate::layout_pass::LayoutPassKind::Probe;

        if !is_probe_layout
            && viewport.0 > 0.0
            && props.len > 0
            && let Some((index, strategy)) = props.scroll_handle.deferred_scroll_to_item()
        {
            deferred_scroll_consumed = true;
            offset = metrics.scroll_offset_for_item(index, viewport, offset, strategy);
            props
                .scroll_handle
                .clear_deferred_scroll_to_item(cx.app.frame_id());
        }

        offset = metrics.clamp_offset(offset, viewport);

        if (handle_offset_axis.0 - offset.0).abs() > 0.01 {
            needs_redraw = true;
        }

        let visible_range = metrics.visible_range(offset, viewport, 0);
        let anchor = visible_range.map(|r| r.start_index);
        let anchor_offset_in_viewport = anchor.map(|anchor| {
            let start = metrics.offset_for_index(anchor);
            Px((offset.0 - start.0).max(0.0))
        });

        layout_scratch.measured_updates.clear();
        layout_scratch.measured_updates.reserve(cx.children.len());

        match props.measure_mode {
            crate::element::VirtualListMeasureMode::Measured => {
                let item_constraints = LayoutConstraints::new(
                    LayoutSize::new(
                        match axis {
                            fret_core::Axis::Vertical => Some(size.width),
                            fret_core::Axis::Horizontal => None,
                        },
                        match axis {
                            fret_core::Axis::Vertical => None,
                            fret_core::Axis::Horizontal => Some(size.height),
                        },
                    ),
                    LayoutSize::new(
                        match axis {
                            fret_core::Axis::Vertical => AvailableSpace::Definite(size.width),
                            fret_core::Axis::Horizontal => AvailableSpace::MaxContent,
                        },
                        match axis {
                            fret_core::Axis::Vertical => AvailableSpace::MaxContent,
                            fret_core::Axis::Horizontal => AvailableSpace::Definite(size.height),
                        },
                    ),
                );

                for (&child, item) in cx.children.iter().zip(props.visible_items.iter()) {
                    let idx = item.index;
                    // Treat `items_revision` as the mechanism-level contract for "size-affecting
                    // content changed". Avoid forcing re-measure just because the widget subtree
                    // was (re)mounted or otherwise marked layout-invalidated: the virtualizer can
                    // legitimately reuse a cached extent for a previously measured index.
                    let should_measure =
                        should_remeasure_visible_items || !metrics.is_measured(idx);
                    let measured_extent = if should_measure {
                        #[cfg(test)]
                        crate::virtual_list::debug_record_virtual_list_item_measure();
                        let measured = cx.measure_in(child, item_constraints);
                        match axis {
                            fret_core::Axis::Vertical => Px(measured.height.0.max(0.0)),
                            fret_core::Axis::Horizontal => Px(measured.width.0.max(0.0)),
                        }
                    } else {
                        metrics.height_at(idx)
                    };

                    layout_scratch
                        .measured_updates
                        .push((child, idx, measured_extent));
                }

                let mut any_measured_change = false;
                for (_, idx, measured_extent) in &layout_scratch.measured_updates {
                    if metrics.set_measured_height(*idx, *measured_extent) {
                        any_measured_change = true;
                    }
                }

                if any_measured_change || should_remeasure_visible_items {
                    needs_redraw = true;

                    if !is_probe_layout
                        && let (Some(anchor), Some(anchor_offset_in_viewport)) =
                            (anchor, anchor_offset_in_viewport)
                    {
                        let prev_offset = offset;
                        let desired =
                            Px(metrics.offset_for_index(anchor).0 + anchor_offset_in_viewport.0);
                        offset = metrics.clamp_offset(desired, viewport);
                        if (prev_offset.0 - offset.0).abs() > 0.01 {
                            needs_redraw = true;
                        }
                    }
                }
            }
            crate::element::VirtualListMeasureMode::Fixed => {
                for (&child, item) in cx.children.iter().zip(props.visible_items.iter()) {
                    let idx = item.index;
                    let estimated_extent = metrics.height_at(idx);
                    layout_scratch
                        .measured_updates
                        .push((child, idx, estimated_extent));
                }
            }
            crate::element::VirtualListMeasureMode::Known => {
                for (&child, item) in cx.children.iter().zip(props.visible_items.iter()) {
                    let idx = item.index;
                    let known_extent = metrics.height_at(idx);
                    layout_scratch
                        .measured_updates
                        .push((child, idx, known_extent));
                }
            }
        }

        let content_extent = metrics.total_height();
        props
            .scroll_handle
            .set_viewport_size_internal(Size::new(size.width, size.height));
        let content_size = match axis {
            fret_core::Axis::Vertical => Size::new(size.width, content_extent),
            fret_core::Axis::Horizontal => Size::new(content_extent, size.height),
        };
        props.scroll_handle.set_content_size_internal(content_size);

        let prev_offset = props.scroll_handle.offset();
        let clamped = metrics.clamp_offset(offset, viewport);
        if (clamped.0 - offset.0).abs() > 0.01 {
            needs_redraw = true;
        }
        match axis {
            fret_core::Axis::Vertical => {
                props
                    .scroll_handle
                    .set_offset_internal(fret_core::Point::new(prev_offset.x, clamped));
            }
            fret_core::Axis::Horizontal => {
                props
                    .scroll_handle
                    .set_offset_internal(fret_core::Point::new(clamped, prev_offset.y));
            }
        }
        offset = clamped;

        // Layout children in stable "content space" and apply the scroll offset via
        // `children_render_transform` (same pattern as `Scroll`).
        //
        // This avoids the "translation-only layout" O(N) subtree bound updates that happen when
        // we bake the scroll offset into each child's layout rect.
        self.scroll_child_transform = Some(super::super::ScrollChildTransform {
            handle: props.scroll_handle.base_handle().clone(),
            axis: match axis {
                fret_core::Axis::Vertical => crate::element::ScrollAxis::Y,
                fret_core::Axis::Horizontal => crate::element::ScrollAxis::X,
            },
        });

        layout_scratch.barrier_roots.clear();
        layout_scratch
            .barrier_roots
            .reserve(layout_scratch.measured_updates.len());
        let mut should_defer_overscan_layout = false;
        if !is_probe_layout && props.overscan > 0 && viewport.0 > 0.0 {
            if deferred_scroll_consumed {
                // On large scroll-to-item jumps, laying out the full overscan window in a single
                // frame can create tail spikes. Prioritize the true visible window and let
                // overscanned rows catch up on subsequent frames.
                should_defer_overscan_layout = true;
            } else {
                // `scroll_to_bottom()` / `scroll_to_item()` may update the handle immediately
                // (without a deferred-scroll marker). Detect large jumps by comparing against the
                // last committed offset from the element state.
                let prev_state_viewport_axis = match axis {
                    fret_core::Axis::Vertical => prev_viewport_h,
                    fret_core::Axis::Horizontal => prev_viewport_w,
                };
                let prev_state_offset_axis = match axis {
                    fret_core::Axis::Vertical => prev_offset_y,
                    fret_core::Axis::Horizontal => prev_offset_x,
                };

                let viewport_unchanged = (prev_state_viewport_axis.0 - viewport.0).abs() <= 0.01
                    && prev_state_viewport_axis.0 > 0.0;

                if viewport_unchanged {
                    let prev_clamped = metrics.clamp_offset(prev_state_offset_axis, viewport);
                    let prev_visible = metrics.visible_range(prev_clamped, viewport, 0);

                    let large_index_jump = match (prev_visible, visible_range) {
                        (Some(prev), Some(now)) => {
                            let prev_len = prev
                                .end_index
                                .saturating_sub(prev.start_index)
                                .saturating_add(1);
                            let threshold = prev_len
                                .saturating_mul(4)
                                .max(props.overscan.saturating_mul(8));
                            now.start_index.abs_diff(prev.start_index) > threshold
                        }
                        _ => {
                            let delta_px = (offset.0 - prev_clamped.0).abs();
                            delta_px > (viewport.0 * 3.0)
                        }
                    };

                    if large_index_jump {
                        should_defer_overscan_layout = true;
                    }
                }
            }
        }

        let bounds_for_start_and_extent = |start: Px, extent: Px| -> Rect {
            let origin = match axis {
                fret_core::Axis::Vertical => {
                    let y = cx.bounds.origin.y.0 + start.0;
                    fret_core::Point::new(cx.bounds.origin.x, Px(y))
                }
                fret_core::Axis::Horizontal => {
                    let x = cx.bounds.origin.x.0 + start.0;
                    fret_core::Point::new(Px(x), cx.bounds.origin.y)
                }
            };
            match axis {
                fret_core::Axis::Vertical => Rect::new(origin, Size::new(size.width, extent)),
                fret_core::Axis::Horizontal => Rect::new(origin, Size::new(extent, size.height)),
            }
        };

        let use_visible_item_starts = props.measure_mode
            != crate::element::VirtualListMeasureMode::Measured
            && layout_scratch.measured_updates.len() == props.visible_items.len();

        let mut prev_idx: Option<usize> = None;
        let mut prev_start: Px = Px(0.0);
        let mut prev_extent: Px = Px(0.0);
        let gap = metrics.gap();

        for (pos, (child, idx, measured_extent)) in
            layout_scratch.measured_updates.iter().enumerate()
        {
            let start = if use_visible_item_starts {
                props
                    .visible_items
                    .get(pos)
                    .map(|item| item.start)
                    .unwrap_or_else(|| metrics.offset_for_index(*idx))
            } else {
                let start = if let Some(prev) = prev_idx
                    && *idx == prev.saturating_add(1)
                {
                    Px(prev_start.0 + prev_extent.0 + gap.0)
                } else {
                    metrics.offset_for_index(*idx)
                };
                prev_idx = Some(*idx);
                prev_start = start;
                prev_extent = *measured_extent;
                start
            };

            if should_defer_overscan_layout {
                let Some(visible) = visible_range else {
                    continue;
                };
                if *idx < visible.start_index || *idx > visible.end_index {
                    continue;
                }
            }

            let child_bounds = bounds_for_start_and_extent(start, *measured_extent);
            layout_scratch.barrier_roots.push((*child, child_bounds));
        }

        if !is_probe_layout {
            cx.solve_barrier_child_roots_if_needed(&layout_scratch.barrier_roots);
        }

        for (child, child_bounds) in &layout_scratch.barrier_roots {
            let _ = cx.layout_in(*child, *child_bounds);
        }

        let window_range = if !is_probe_layout {
            metrics.visible_range(offset, viewport, props.overscan)
        } else {
            None
        };

        crate::elements::with_element_state(
            &mut *cx.app,
            window,
            self.element,
            crate::element::VirtualListState::default,
            |state| {
                if !is_probe_layout {
                    match axis {
                        fret_core::Axis::Vertical => {
                            state.offset_y = offset;
                            if state.viewport_h != viewport {
                                state.viewport_h = viewport;
                                needs_redraw = true;
                            }
                        }
                        fret_core::Axis::Horizontal => {
                            state.offset_x = offset;
                            if state.viewport_w != viewport {
                                state.viewport_w = viewport;
                                needs_redraw = true;
                            }
                        }
                    }
                    if viewport.0 > 0.0 {
                        state.has_final_viewport = true;
                    }

                    state.window_range = window_range;
                    state.deferred_scroll_offset_hint = None;
                }
                state.items_revision = props.items_revision;
                state.metrics = metrics;
                state.layout_scratch = layout_scratch;
            },
        );

        let window_mismatch = {
            // `render_window_range` is the window that was used during declarative render to build
            // `props.visible_items` (typically an overscanned window).
            //
            // `visible_range` is the true visible window (no overscan).
            //
            // We only need to force a cache-root rerender when the current visible window falls
            // outside the previously rendered window. A mere mismatch between the “ideal” window
            // for the current scroll offset and the rendered window is expected and should not
            // trigger rerender while we're still within overscan.
            if is_probe_layout || viewport.0 <= 0.0 {
                false
            } else if let Some(visible) = visible_range {
                match render_window_range {
                    None => visible.count > 0,
                    Some(rendered) => {
                        if rendered.count == 0 {
                            // If declarative render couldn't produce a window (typically because
                            // the viewport size was unknown), the next non-probe layout pass will
                            // compute a real visible range. Ensure we schedule a rerender so the
                            // view-cache root can build the initial visible items.
                            visible.count > 0
                        } else {
                            let rendered_start =
                                rendered.start_index.saturating_sub(rendered.overscan);
                            let rendered_end = (rendered.end_index + rendered.overscan)
                                .min(rendered.count.saturating_sub(1));
                            visible.start_index < rendered_start || visible.end_index > rendered_end
                        }
                    }
                }
            } else {
                false
            }
        };

        if cx.tree.debug_enabled() {
            let scroll_to_item_consumed_in_frame = props
                .scroll_handle
                .scroll_to_item_consumed_in_frame(cx.app.frame_id());
            let scroll_to_item_in_frame =
                deferred_scroll_to_item || scroll_to_item_consumed_in_frame;
            let policy_key = {
                let mut b = CacheKeyBuilder::new();
                b.write_u32(axis as u32);
                b.write_u32(props.measure_mode as u32);
                b.write_u64(props.overscan as u64);
                b.write_px(props.estimate_row_height);
                b.write_px(props.gap);
                b.write_px(props.scroll_margin);
                b.finish()
            };
            let inputs_key = {
                let mut b = CacheKeyBuilder::new();
                b.write_u64(policy_key);
                b.write_u64(props.len as u64);
                b.write_u64(props.items_revision);
                b.write_px(viewport);
                b.write_px(offset);
                b.write_px(content_extent);
                b.finish()
            };
            let prev_offset_state = match axis {
                fret_core::Axis::Vertical => prev_offset_y,
                fret_core::Axis::Horizontal => prev_offset_x,
            };
            let prev_viewport_state = match axis {
                fret_core::Axis::Vertical => prev_viewport_h,
                fret_core::Axis::Horizontal => prev_viewport_w,
            };
            let (window_shift_reason, window_shift_apply_mode, window_shift_invalidation_detail) =
                if window_mismatch {
                    let reason = if scroll_to_item_in_frame {
                        crate::tree::UiDebugVirtualListWindowShiftReason::ScrollToItem
                    } else if props.items_revision != prev_items_revision {
                        crate::tree::UiDebugVirtualListWindowShiftReason::ItemsRevision
                    } else if (viewport.0 - prev_viewport_state.0).abs() > 0.01 {
                        crate::tree::UiDebugVirtualListWindowShiftReason::ViewportResize
                    } else if (offset.0 - prev_offset_state.0).abs() > 0.01 {
                        crate::tree::UiDebugVirtualListWindowShiftReason::ScrollOffset
                    } else if prev_window_range.map(|r| (r.count, r.overscan))
                        != window_range.map(|r| (r.count, r.overscan))
                    {
                        crate::tree::UiDebugVirtualListWindowShiftReason::InputsChange
                    } else {
                        crate::tree::UiDebugVirtualListWindowShiftReason::Unknown
                    };
                    let retained_host = crate::elements::with_window_state(
                        &mut *cx.app,
                        window,
                        |window_state| {
                            window_state.has_state::<crate::windowed_surface_host::RetainedVirtualListHostMarker>(self.element)
                        },
                    );
                    let mode = if retained_host {
                        crate::tree::UiDebugVirtualListWindowShiftApplyMode::RetainedReconcile
                    } else {
                        crate::tree::UiDebugVirtualListWindowShiftApplyMode::NonRetainedRerender
                    };
                    let invalidation_detail = if cx.tree.view_cache_enabled() && !retained_host {
                        Some(match reason {
                            crate::tree::UiDebugVirtualListWindowShiftReason::ScrollToItem => {
                                crate::tree::UiDebugInvalidationDetail::ScrollHandleScrollToItemWindowUpdate
                            }
                            crate::tree::UiDebugVirtualListWindowShiftReason::ViewportResize => {
                                crate::tree::UiDebugInvalidationDetail::ScrollHandleViewportResizeWindowUpdate
                            }
                            crate::tree::UiDebugVirtualListWindowShiftReason::ItemsRevision => {
                                crate::tree::UiDebugInvalidationDetail::ScrollHandleItemsRevisionWindowUpdate
                            }
                            _ => crate::tree::UiDebugInvalidationDetail::ScrollHandleWindowUpdate,
                        })
                    } else {
                        None
                    };
                    (Some(reason), Some(mode), invalidation_detail)
                } else {
                    (None, None, None)
                };

            cx.tree
                .debug_record_virtual_list_window(crate::tree::UiDebugVirtualListWindow {
                    source: crate::tree::UiDebugVirtualListWindowSource::Layout,
                    node: cx.node,
                    element: self.element,
                    axis,
                    is_probe_layout,
                    items_len: props.len,
                    items_revision: props.items_revision,
                    prev_items_revision,
                    measure_mode: props.measure_mode,
                    overscan: props.overscan,
                    estimate_row_height: props.estimate_row_height,
                    gap: props.gap,
                    scroll_margin: props.scroll_margin,
                    viewport,
                    prev_viewport: prev_viewport_state,
                    offset,
                    prev_offset: prev_offset_state,
                    content_extent,
                    policy_key,
                    inputs_key,
                    window_range,
                    prev_window_range,
                    render_window_range,
                    deferred_scroll_to_item: scroll_to_item_in_frame,
                    deferred_scroll_consumed: deferred_scroll_consumed
                        || scroll_to_item_consumed_in_frame,
                    window_mismatch,
                    window_shift_kind: if window_mismatch {
                        crate::tree::UiDebugVirtualListWindowShiftKind::Escape
                    } else {
                        crate::tree::UiDebugVirtualListWindowShiftKind::None
                    },
                    window_shift_reason,
                    window_shift_apply_mode,
                    window_shift_invalidation_detail,
                });
        }

        // Window-boundary invalidation under view-cache is prepaint-driven (ADR 0175):
        // - retained hosts reconcile during prepaint,
        // - non-retained lists schedule a one-shot rerender during prepaint.
        //
        // Layout still records window telemetry and updates `VirtualListState`, but should not
        // duplicate the scheduling side effects.
        if !is_probe_layout && cx.tree.view_cache_enabled() && window_mismatch {
            needs_redraw = true;
        }

        if needs_redraw && let Some(window) = cx.window {
            cx.app.request_redraw(window);
        }

        size
    }

    pub(super) fn layout_scroll_impl<H: UiHost>(
        &mut self,
        cx: &mut LayoutCx<'_, H>,
        window: AppWindowId,
        props: crate::element::ScrollProps,
    ) -> Size {
        let profile_cfg = scroll_layout_profile_config();
        let profile_started = profile_cfg.is_some().then(Instant::now);
        let mut t_measure_children: Duration = Duration::default();
        let mut t_solve_barrier: Duration = Duration::default();
        let mut t_layout_children: Duration = Duration::default();

        let is_probe_layout = cx.pass_kind == crate::layout_pass::LayoutPassKind::Probe;

        // The post-layout extents path is the authoritative scroll-range update strategy.
        // Keep it scoped to vertical scroll surfaces under definite viewport constraints where
        // post-layout geometry is trustworthy and GPUI/DOM parity is required.
        let post_layout_extents_mode = !is_probe_layout
            && props.probe_unbounded
            && matches!(props.axis, crate::element::ScrollAxis::Y)
            && cx.available.width.0 > 0.0
            && cx.available.height.0 > 0.0
            && !matches!(props.layout.size.height, Length::Auto);

        // Acquire the imperative handle early so probe layout passes can use the last known
        // viewport size instead of the probe pass' effectively-unbounded available size.
        //
        // This keeps scroll probing stable across probe/final passes and avoids accidental
        // "infinite window" layouts (e.g. text reflowing as a single long line) during probes.
        let external_handle = props.scroll_handle.clone();
        let (handle, intrinsic_measure_cache, pending_extent_probe) =
            crate::elements::with_element_state(
                &mut *cx.app,
                window,
                self.element,
                crate::element::ScrollState::default,
                |state| {
                    (
                        external_handle
                            .as_ref()
                            .unwrap_or(&state.scroll_handle)
                            .clone(),
                        state.intrinsic_measure_cache,
                        state.pending_extent_probe,
                    )
                },
            );

        let available = if is_probe_layout {
            let last = handle.viewport_size();
            if last.width.0 > 0.0 && last.height.0 > 0.0 {
                last
            } else {
                cx.available
            }
        } else {
            cx.available
        };

        // If the user is already at the current scroll extent edge, avoid relying on prior-frame
        // caches for the content extent. Otherwise the scroll container can temporarily "pin" its
        // content size to the previous frame, making it impossible to scroll further when content
        // grows (e.g. expanding a collapsible near the bottom of a scroll view).
        let prev_offset = handle.offset();
        let prev_max_offset = handle.max_offset();
        let at_scroll_extent_edge = match props.axis {
            crate::element::ScrollAxis::X => prev_offset.x.0 + 0.5 >= prev_max_offset.x.0,
            crate::element::ScrollAxis::Y => prev_offset.y.0 + 0.5 >= prev_max_offset.y.0,
            crate::element::ScrollAxis::Both => {
                prev_offset.x.0 + 0.5 >= prev_max_offset.x.0
                    || prev_offset.y.0 + 0.5 >= prev_max_offset.y.0
            }
        };

        let direct_children_layout_invalidated = cx
            .children
            .iter()
            .copied()
            .any(|child| cx.tree.node_layout_invalidated(child));
        // When the user is at the current scroll extent edge, we must be conservative about
        // reusing cached content extents: if a descendant layout invalidation did not bubble up to
        // the scroll's direct child root, relying on cached measurement fast paths can "pin" the
        // scroll range to the previous frame (e.g. toggling a tabs panel at the bottom of a docs
        // page and being unable to scroll further).
        //
        // The subtree dirty aggregation makes it cheap to detect this condition without scanning.
        let descendant_subtree_layout_dirty = (at_scroll_extent_edge || post_layout_extents_mode)
            && cx
                .children
                .iter()
                .copied()
                .any(|child| cx.tree.node_subtree_layout_dirty(child));

        let children_layout_invalidated =
            direct_children_layout_invalidated || descendant_subtree_layout_dirty;
        let forced_barrier_child_roots: Vec<NodeId> = if post_layout_extents_mode {
            cx.children
                .iter()
                .copied()
                .filter(|&child| {
                    cx.tree.node_subtree_layout_dirty(child)
                        && !cx.tree.node_layout_invalidated(child)
                })
                .collect()
        } else {
            Vec::new()
        };
        let force_barrier_child_root_relayout = !forced_barrier_child_roots.is_empty();
        let at_end_with_invalidated_child = at_scroll_extent_edge && children_layout_invalidated;

        let frame_id = cx.app.frame_id();
        let retained_measured_max_child = resolve_retained_measured_max_child(cx);
        let last_max_child = crate::elements::with_element_state(
            &mut *cx.app,
            window,
            self.element,
            ScrollLayoutProbeCacheState::default,
            |state| {
                if state.frame_id != frame_id {
                    state.frame_id = frame_id;
                    state.entries.clear();
                }
                non_default_size(state.last_max_child)
            },
        );
        let wants_unbounded_probe = props.probe_unbounded
            && (props.axis.scroll_x() || props.axis.scroll_y())
            && !post_layout_extents_mode
            && !is_probe_layout;
        let defer_probe_on_resize = scroll_defer_unbounded_probe_on_resize_enabled();
        let defer_probe_on_invalidation = scroll_defer_unbounded_probe_on_invalidation_enabled();
        let prev_viewport = handle.viewport_size();
        let viewport_known = prev_viewport.width.0 > 0.0 && prev_viewport.height.0 > 0.0;
        let viewport_changed = viewport_known
            && (prev_viewport.width.0.to_bits() != available.width.0.to_bits()
                || prev_viewport.height.0.to_bits() != available.height.0.to_bits());

        let deferred_child_constraints =
            scroll_measure_child_constraints(props.axis, true, available);
        let deferred_seed_cache_key =
            (!is_probe_layout && cx.children.len() == 1 && wants_unbounded_probe).then(|| {
                scroll_intrinsic_measure_cache_key(
                    props.axis,
                    deferred_child_constraints,
                    cx.scale_factor,
                )
            });
        let deferred_probe_seed = resolve_scroll_probe_seed(
            cx,
            intrinsic_measure_cache,
            deferred_seed_cache_key,
            retained_measured_max_child,
            last_max_child,
            at_end_with_invalidated_child,
        );
        let can_defer_probe_with_cached_children = deferred_probe_seed.can_defer_with_seed();
        let viewport_became_known_during_resize = !viewport_known
            && cx.tree.interactive_resize_active()
            && available.width.0 > 0.0
            && available.height.0 > 0.0
            && can_defer_probe_with_cached_children;

        let should_defer_unbounded_probe_on_resize = wants_unbounded_probe
            && defer_probe_on_resize
            && can_defer_probe_with_cached_children
            && !pending_extent_probe
            && (viewport_changed || viewport_became_known_during_resize);
        let should_defer_unbounded_probe_on_invalidation = wants_unbounded_probe
            && defer_probe_on_invalidation
            && can_defer_probe_with_cached_children
            && !pending_extent_probe
            && children_layout_invalidated
            && !at_scroll_extent_edge;

        let stable_frames_required = scroll_defer_unbounded_probe_stable_frames();
        let (defer_state, defer_this_frame) = crate::elements::with_element_state(
            &mut *cx.app,
            window,
            self.element,
            ScrollDeferredUnboundedProbeState::default,
            |state| {
                let defer_this_frame = update_scroll_deferred_probe_state(
                    state,
                    ScrollDeferredProbeInputs {
                        force_probe_now: pending_extent_probe,
                        wants_unbounded_probe,
                        can_defer_with_seed: can_defer_probe_with_cached_children,
                        defer_probe_on_invalidation,
                        should_defer_on_resize: should_defer_unbounded_probe_on_resize,
                        should_defer_on_invalidation: should_defer_unbounded_probe_on_invalidation,
                        children_layout_invalidated,
                        at_scroll_extent_edge,
                        stable_frames_required,
                    },
                );
                (*state, defer_this_frame)
            },
        );

        if defer_this_frame {
            let schedule_follow_up = match defer_state.kind {
                ScrollDeferredUnboundedProbeKind::Invalidation => true,
                ScrollDeferredUnboundedProbeKind::Resize => !viewport_changed,
                ScrollDeferredUnboundedProbeKind::None => false,
            };
            if schedule_follow_up {
                cx.tree.schedule_barrier_relayout_with_source_and_detail(
                    cx.node,
                    UiDebugInvalidationSource::Other,
                    UiDebugInvalidationDetail::ScrollDeferredProbe,
                );
                cx.request_redraw();
            }
        }

        let must_probe_for_growing_extent = pending_extent_probe
            || (at_scroll_extent_edge
                && (children_layout_invalidated || defer_state.pending_invalidation_probe));
        // On the authoritative post-layout extents path, avoid measuring children under MaxContent constraints by
        // default; rely on post-layout observed overflow to grow extents. When correctness is at
        // risk (e.g. the user is already at the scroll edge), we still fall back to an unbounded
        // probe for that frame.
        let probe_unbounded_for_measure =
            props.probe_unbounded && (!post_layout_extents_mode || must_probe_for_growing_extent);

        let child_constraints =
            scroll_measure_child_constraints(props.axis, probe_unbounded_for_measure, available);
        let intrinsic_cache_key = (!is_probe_layout && cx.children.len() == 1).then(|| {
            scroll_intrinsic_measure_cache_key(props.axis, child_constraints, cx.scale_factor)
        });
        let probe_seed = resolve_scroll_probe_seed(
            cx,
            intrinsic_measure_cache,
            intrinsic_cache_key,
            retained_measured_max_child,
            last_max_child,
            at_end_with_invalidated_child,
        );
        let intrinsic_cached_max_child = probe_seed.intrinsic_cached_max_child;
        let mut cached_max_child = probe_seed.cached_max_child;

        if must_probe_for_growing_extent {
            cached_max_child = None;
        }

        // Avoid recomputing the unbounded scroll probe twice in a single frame when the runtime
        // performs probe+final layout passes (e.g. view-cache reconciliation).
        let key = ScrollLayoutProbeKey {
            avail_w: available_space_cache_key(child_constraints.available.width),
            avail_h: available_space_cache_key(child_constraints.available.height),
        };
        let cached = crate::elements::with_element_state(
            &mut *cx.app,
            window,
            self.element,
            ScrollLayoutProbeCacheState::default,
            |state| {
                if state.frame_id != frame_id {
                    state.frame_id = frame_id;
                    state.entries.clear();
                }
                let cached = state
                    .entries
                    .iter()
                    .find_map(|(k, v)| (*k == key).then_some(*v));
                if let Some(cached) = cached {
                    state.last_max_child = cached;
                }
                cached
            },
        );

        // Some fast paths intentionally reuse cached extents to avoid deep unbounded probe walks
        // during transient invalidation. Those cached extents can temporarily overestimate the true
        // content size after shrink (e.g. filtering a nav list), so we later apply an observed
        // post-layout shrink clamp when possible.
        let mut needs_authoritative_cache_commit_from_same_frame_probe = false;
        let max_child = if must_probe_for_growing_extent {
            let measure_started = profile_cfg.is_some().then(Instant::now);
            let mut max_child = Size::new(Px(0.0), Px(0.0));
            for &child in cx.children {
                let child_size = cx.measure_in(child, child_constraints);
                max_child.width = Px(max_child.width.0.max(child_size.width.0));
                max_child.height = Px(max_child.height.0.max(child_size.height.0));
            }
            if let Some(started) = measure_started {
                t_measure_children = started.elapsed();
            }

            commit_scroll_authoritative_extent(
                &mut *cx.app,
                window,
                self.element,
                ScrollAuthoritativeExtentCommit {
                    max_child,
                    intrinsic_cache_key,
                    probe_cache_key: Some((frame_id, key)),
                    clear_pending_invalidation_probe: true,
                    clear_pending_extent_probe: true,
                },
            );

            max_child
        } else if let Some(cached) = cached_max_child {
            cached
        } else if let Some(cached) = cached {
            needs_authoritative_cache_commit_from_same_frame_probe = true;
            cached
        } else if defer_this_frame {
            if let Some(max_child) = deferred_probe_seed.deferred_max_child() {
                // Best-effort: reuse the last measured max-child size while deferring the expensive
                // unbounded probe during interactive resize/unstable frames.
                //
                // Correctness note:
                //
                // When content shrinks (e.g. filtering a nav list) we must avoid pinning the scroll
                // extent to the previous frame's larger probe result, otherwise users can scroll
                // into blank space until the unbounded probe runs again.
                //
                // The layout pass below opportunistically observes the post-layout child bounds
                // and clamps the cached extent downward (when it can be proven smaller) without
                // performing an additional deep measure walk.
                max_child
            } else {
                debug_assert!(
                    false,
                    "deferred scroll probe frame must have a retained seed before skipping measure"
                );

                let measure_started = profile_cfg.is_some().then(Instant::now);
                let mut max_child = Size::new(Px(0.0), Px(0.0));
                for &child in cx.children {
                    let child_size = cx.measure_in(child, child_constraints);
                    max_child.width = Px(max_child.width.0.max(child_size.width.0));
                    max_child.height = Px(max_child.height.0.max(child_size.height.0));
                }
                if let Some(started) = measure_started {
                    t_measure_children = started.elapsed();
                }

                commit_scroll_authoritative_extent(
                    &mut *cx.app,
                    window,
                    self.element,
                    ScrollAuthoritativeExtentCommit {
                        max_child,
                        intrinsic_cache_key,
                        probe_cache_key: Some((frame_id, key)),
                        clear_pending_invalidation_probe: true,
                        clear_pending_extent_probe: false,
                    },
                );

                max_child
            }
        } else {
            let measure_started = profile_cfg.is_some().then(Instant::now);
            let mut max_child = Size::new(Px(0.0), Px(0.0));
            for &child in cx.children {
                let child_size = cx.measure_in(child, child_constraints);
                max_child.width = Px(max_child.width.0.max(child_size.width.0));
                max_child.height = Px(max_child.height.0.max(child_size.height.0));
            }
            if let Some(started) = measure_started {
                t_measure_children = started.elapsed();
            }

            commit_scroll_authoritative_extent(
                &mut *cx.app,
                window,
                self.element,
                ScrollAuthoritativeExtentCommit {
                    max_child,
                    intrinsic_cache_key,
                    probe_cache_key: Some((frame_id, key)),
                    clear_pending_invalidation_probe: true,
                    clear_pending_extent_probe: false,
                },
            );

            max_child
        };

        // In unbounded probe flows, scroll surfaces frequently sit under auto-sized containers
        // (e.g. `max-height` shells). During intrinsic sizing, parents may pass
        // `available.{width,height} = 0` as a placeholder for "unknown".
        //
        // `clamp_to_constraints()` treats `available` as a hard upper bound even for `Auto`, so we
        // must avoid feeding a zero "unknown" available size into it. Use the measured content
        // size as an upper bound in that case so the scroll node can participate in intrinsic
        // sizing (similar to how percentage heights behave under `auto` in CSS).
        let mut clamp_available = available;
        if probe_unbounded_for_measure {
            if clamp_available.width.0 <= 0.0 {
                clamp_available.width = Px(max_child.width.0.max(0.0));
            }
            if clamp_available.height.0 <= 0.0 {
                clamp_available.height = Px(max_child.height.0.max(0.0));
            }
        }
        let desired = clamp_to_constraints(max_child, props.layout, clamp_available);
        // Scroll containers should not under-report their scrollable extent due to fractional
        // layout rounding. Match DOM behavior by rounding the scrollable axis up to the next
        // whole pixel (tolerating tiny floating point noise).
        const ROUND_EPSILON: f32 = 0.001;
        let previous_content = handle.content_size();
        let trust_live_edge_probe_shrink =
            pending_extent_probe || (cx.children.len() == 1 && direct_children_layout_invalidated);
        let content_w = if props.axis.scroll_x() && probe_unbounded_for_measure {
            let measured = Px((max_child.width.0.max(0.0) - ROUND_EPSILON).ceil().max(0.0));
            if post_layout_extents_mode {
                if trust_live_edge_probe_shrink {
                    // Trust explicit probe shrink when we are in a deliberate follow-up probe, or
                    // when the scroll hosts a single directly-invalidated child root. In that
                    // single-child case the unbounded measure already reflects the authoritative
                    // subtree frontier, while re-seeding layout from `previous_content` would pin
                    // wrapper-heavy collapse flows to stale bounds for the whole frame.
                    Px(measured.0.max(desired.width.0.max(0.0)))
                } else {
                    // Otherwise keep the previously observed extent as a floor. Edge probes can
                    // temporarily under-report wrapper-heavy descendant-only invalidations while
                    // contained/cache relayout catches up; shrinking from the probe result here
                    // would reintroduce the "bottom jumps upward" regression.
                    Px(previous_content
                        .width
                        .0
                        .max(measured.0.max(desired.width.0.max(0.0))))
                }
            } else {
                measured
            }
        } else if post_layout_extents_mode && props.axis.scroll_x() {
            // On the authoritative post-layout extents path, keep the previous observed content extent as the
            // baseline for the next frame. Re-seeding from the viewport each frame can make the
            // overflow observer rediscover deep content incrementally at the scroll edge, which
            // shows up as a "bottom keeps moving away" loop on wrapper-heavy docs/gallery pages.
            Px(previous_content.width.0.max(desired.width.0.max(0.0)))
        } else {
            desired.width
        };
        let content_h = if props.axis.scroll_y() && probe_unbounded_for_measure {
            let measured = Px((max_child.height.0.max(0.0) - ROUND_EPSILON)
                .ceil()
                .max(0.0));
            if post_layout_extents_mode {
                if trust_live_edge_probe_shrink {
                    // Same as above for the vertical axis: deliberate follow-up probes and
                    // single-child direct invalidations can trust the freshly measured frontier for
                    // shrink immediately.
                    Px(measured.0.max(desired.height.0.max(0.0)))
                } else {
                    // Same guard as above for the vertical axis: descendant-only edge probes may
                    // still observe an outdated outer shell during relayout catch-up, so keep the
                    // previous content extent as the temporary floor.
                    Px(previous_content
                        .height
                        .0
                        .max(measured.0.max(desired.height.0.max(0.0))))
                }
            } else {
                measured
            }
        } else if post_layout_extents_mode && props.axis.scroll_y() {
            // Same rationale as above for the vertical axis: preserve the last observed extent so
            // edge revalidation can compare against a stable floor instead of collapsing back to
            // the viewport before the observer runs.
            Px(previous_content.height.0.max(desired.height.0.max(0.0)))
        } else {
            desired.height
        };
        // Ensure the scroll content bounds never underflow the viewport bounds.
        //
        // This matches DOM behavior (the scrollable content box is at least the viewport size),
        // and prevents `Length::Fill` descendants from collapsing when we probe with
        // `AvailableSpace::MaxContent` on the scroll axis.
        let mut content_w = Px(content_w.0.max(desired.width.0.max(0.0)));
        let mut content_h = Px(content_h.0.max(desired.height.0.max(0.0)));

        if crate::runtime_config::ui_runtime_config().debug_scroll_extent_probe
            && !is_probe_layout
            && probe_unbounded_for_measure
            && ((props.axis.scroll_x() && content_w.0 + 0.5 < previous_content.width.0)
                || (props.axis.scroll_y() && content_h.0 + 0.5 < previous_content.height.0))
        {
            eprintln!(
                "scroll extent measured smaller element={:?} node={:?} axis={:?} previous=({:.1},{:.1}) measured=({:.1},{:.1}) max_child=({:.1},{:.1}) desired=({:.1},{:.1}) cached_probe={} cached_intrinsic={} cached_max_child={} direct_invalidated={} descendant_dirty={} at_edge={} defer_this_frame={} pending_probe={}",
                self.element,
                cx.node,
                props.axis,
                previous_content.width.0,
                previous_content.height.0,
                content_w.0,
                content_h.0,
                max_child.width.0,
                max_child.height.0,
                desired.width.0,
                desired.height.0,
                cached.is_some(),
                intrinsic_cached_max_child.is_some(),
                cached_max_child.is_some(),
                direct_children_layout_invalidated,
                descendant_subtree_layout_dirty,
                at_scroll_extent_edge,
                defer_this_frame,
                pending_extent_probe,
            );
        }

        let debug_test_id: Option<Arc<str>> = if cx.tree.debug_enabled() {
            let mut current = Some(cx.node);
            let mut steps: u8 = 0;
            let mut found: Option<Arc<str>> = None;
            while let Some(node) = current {
                if let Some(record) =
                    crate::declarative::element_record_for_node(cx.app, window, node)
                    && let Some(decoration) = record.semantics_decoration.as_ref()
                    && let Some(test_id) = decoration.test_id.as_ref()
                {
                    found = Some(test_id.clone());
                    break;
                }
                current = cx.tree.node_parent(node);
                steps = steps.saturating_add(1);
                if steps >= 48 {
                    break;
                }
            }
            found
        } else {
            None
        };

        // Avoid mutating the imperative handle during "probe" layout passes that use an
        // effectively-unbounded available space, otherwise scroll position can be clamped to zero
        // prematurely.
        if !is_probe_layout {
            handle.set_viewport_size_internal(desired);
            handle.set_content_size_internal(Size::new(content_w, content_h));
            let prev = handle.offset();
            handle.set_offset_internal(prev);

            cx.tree
                .debug_record_scroll_node_telemetry(UiDebugScrollNodeTelemetry {
                    node: cx.node,
                    element: Some(self.element),
                    test_id: debug_test_id.clone(),
                    axis: match props.axis {
                        crate::element::ScrollAxis::X => UiDebugScrollAxis::X,
                        crate::element::ScrollAxis::Y => UiDebugScrollAxis::Y,
                        crate::element::ScrollAxis::Both => UiDebugScrollAxis::Both,
                    },
                    offset: handle.offset(),
                    viewport: handle.viewport_size(),
                    content: handle.content_size(),
                    observed_extent: None,
                    overflow_observation: None,
                });

            if needs_authoritative_cache_commit_from_same_frame_probe {
                commit_scroll_authoritative_extent(
                    &mut *cx.app,
                    window,
                    self.element,
                    ScrollAuthoritativeExtentCommit {
                        max_child,
                        intrinsic_cache_key,
                        probe_cache_key: None,
                        clear_pending_invalidation_probe: false,
                        clear_pending_extent_probe: false,
                    },
                );
            }
        }

        self.scroll_child_transform = Some(super::super::ScrollChildTransform {
            handle: handle.clone(),
            axis: props.axis,
        });

        let mut content_bounds = Rect::new(cx.bounds.origin, Size::new(content_w, content_h));

        // Install an overflow context so wrapper
        // widgets can probe their descendants with `MaxContent` on the scroll axis. This is a
        // prerequisite for making overflow observable in post-layout geometry without relying on
        // deep unbounded pre-measure passes.
        let overflow_ctx = if post_layout_extents_mode {
            let mut ctx = cx.overflow_ctx;
            if props.axis.scroll_x() {
                ctx.probe_available_override.width = Some(AvailableSpace::MaxContent);
                ctx.allow_overflow_on_auto.width = true;
            }
            if props.axis.scroll_y() {
                ctx.probe_available_override.height = Some(AvailableSpace::MaxContent);
                ctx.allow_overflow_on_auto.height = true;
            }
            ctx
        } else {
            cx.overflow_ctx
        };

        cx.with_overflow_context(overflow_ctx, |cx| {
            if !is_probe_layout {
                if force_barrier_child_root_relayout {
                    for &child in &forced_barrier_child_roots {
                        cx.tree.invalidate(child, Invalidation::Layout);
                    }
                }
                let solve_started = profile_cfg.is_some().then(Instant::now);
                match cx.children {
                    [child] => {
                        cx.solve_barrier_child_root_if_needed(*child, content_bounds);
                    }
                    children => {
                        let roots: Vec<(NodeId, Rect)> =
                            children.iter().map(|&c| (c, content_bounds)).collect();
                        cx.solve_barrier_child_roots_if_needed(&roots);
                    }
                }
                if let Some(started) = solve_started {
                    t_solve_barrier = started.elapsed();
                }
            }

            let layout_started = profile_cfg.is_some().then(Instant::now);
            for &child in cx.children {
                let _ = cx.layout_in(child, content_bounds);
            }
            if let Some(started) = layout_started {
                t_layout_children = started.elapsed();
            }
        });

        if !is_probe_layout {
            let mut relayout_with_updated_content_bounds = false;
            let mut authoritative_observation_cleared_pending = false;
            let mut authoritative_observation_committed_this_pass = false;
            // If we didn't do a deep unbounded probe for `max_child` this frame, scroll extents can
            // be temporarily pinned to cached values even if descendants overflow the forced
            // `content_bounds` rect (common with wrapper-heavy trees like docs pages and tab
            // panels). In that mode we allow a small, bounded subtree scan to discover overflow
            // and grow the scroll handle immediately.
            // Under the authoritative post-layout path, descendant wrapper bounds may be stale
            // even on the initial clean frame. Keep the stale-wrapper guard enabled for the whole
            // mode, and let the observer trust the direct barrier root's own bounds separately.
            let extent_may_be_stale = post_layout_extents_mode
                || defer_this_frame
                || cached_max_child.is_some()
                || cached.is_some();
            let mut tree = UiTreeScrollOverflowTree {
                tree: cx.tree,
                app: cx.app,
                window,
            };
            let post_layout_shrink_revalidation = post_layout_extents_mode
                && ((props.axis.scroll_x() && content_w.0 > desired.width.0 + 0.5)
                    || (props.axis.scroll_y() && content_h.0 > desired.height.0 + 0.5))
                && children_layout_invalidated;
            let shrink_validation_enabled = defer_this_frame
                || post_layout_shrink_revalidation
                || (cx.children.len() == 1
                    && probe_unbounded_for_measure
                    && (direct_children_layout_invalidated || cached.is_some())
                    && ((props.axis.scroll_x() && content_w.0 > desired.width.0 + 0.5)
                        || (props.axis.scroll_y() && content_h.0 > desired.height.0 + 0.5)));
            let post_layout_authoritative_scan = post_layout_extents_mode
                && children_layout_invalidated
                && !must_probe_for_growing_extent;
            let deep_scan_allowed =
                (at_scroll_extent_edge && extent_may_be_stale && !must_probe_for_growing_extent)
                    || shrink_validation_enabled
                    || post_layout_authoritative_scan;
            let (observed, observation) = observe_scroll_overflow_extents(
                &mut tree,
                cx.children,
                content_bounds,
                props.axis,
                Size::new(content_w, content_h),
                extent_may_be_stale,
                deep_scan_allowed,
            );

            if crate::runtime_config::ui_runtime_config().debug_scroll_extent_probe
                && scroll_overflow_observation_needs_follow_up_probe(observation)
            {
                eprintln!(
                    "scroll extent observation budget hit element={:?} node={:?} axis={:?} peel={}/{} deep_scan={} visited={}/{} stale_hint={}",
                    self.element,
                    cx.node,
                    props.axis,
                    observation.wrapper_peeled_max,
                    observation.wrapper_peel_budget,
                    observation.deep_scan_enabled,
                    observation.deep_scan_visited,
                    observation.deep_scan_budget_nodes,
                    observation.extent_may_be_stale,
                );
            }

            // If we cannot confidently observe overflow in post-layout geometry (budget hit), schedule a
            // measured unbounded probe on the next frame. This keeps the authoritative path robust
            // when bounded observation runs out of budget on wrapper-heavy trees.
            //
            // Nuance for shrink-at-edge:
            //
            // A live edge probe keeps `previous_content` as a floor to avoid transient "bottom jumps
            // upward" when wrappers under-report mid-interaction. If that frame also hits the
            // observation budget, we still need one follow-up explicit probe so shrink can converge
            // on the next frame. By contrast, once we're already in that follow-up
            // `pending_extent_probe` frame, don't schedule another one or we'll loop forever.
            let budget_hit_needs_follow_up_probe = probe_unbounded_for_measure
                && !pending_extent_probe
                && post_layout_extents_mode
                && ((props.axis.scroll_x() && max_child.width.0 + 0.5 < previous_content.width.0)
                    || (props.axis.scroll_y()
                        && max_child.height.0 + 0.5 < previous_content.height.0));
            if (!probe_unbounded_for_measure || budget_hit_needs_follow_up_probe)
                && maybe_schedule_extent_probe_after_observation_budget_hit(
                    &mut *cx.app,
                    cx.tree,
                    window,
                    cx.node,
                    self.element,
                    observation,
                )
            {
                cx.request_redraw();
            }

            let authoritative_post_layout_observation = post_layout_authoritative_scan
                && scroll_overflow_observation_is_authoritative(observation);
            if authoritative_post_layout_observation {
                // Move the post-layout path closer to GPUI's authoritative child-bounds union:
                // when descendants changed and the bounded observation completed within budget,
                // trust the freshly observed extent for the current frame instead of carrying a
                // cached/probed baseline forward and then patching it via separate grow/shrink
                // branches.
                let next_content_w = if props.axis.scroll_x() && observed.trusted.width.0 > 0.0 {
                    Px(observed.trusted.width.0.max(desired.width.0.max(0.0)))
                } else {
                    content_w
                };
                let next_content_h = if props.axis.scroll_y() && observed.trusted.height.0 > 0.0 {
                    Px(observed.trusted.height.0.max(desired.height.0.max(0.0)))
                } else {
                    content_h
                };
                let changed = (next_content_w.0 - content_w.0).abs() > 0.5
                    || (next_content_h.0 - content_h.0).abs() > 0.5;
                if changed {
                    if crate::runtime_config::ui_runtime_config().debug_scroll_extent_probe {
                        eprintln!(
                            "scroll extent authoritative sync element={:?} node={:?} axis={:?} previous=({:.1},{:.1}) observed_trusted=({:.1},{:.1}) desired=({:.1},{:.1}) stale_hint={} deep_scan={} invalidated={}",
                            self.element,
                            cx.node,
                            props.axis,
                            content_w.0,
                            content_h.0,
                            observed.trusted.width.0,
                            observed.trusted.height.0,
                            desired.width.0,
                            desired.height.0,
                            extent_may_be_stale,
                            observation.deep_scan_enabled,
                            children_layout_invalidated,
                        );
                    }
                    content_w = next_content_w;
                    content_h = next_content_h;
                    relayout_with_updated_content_bounds = true;
                    handle.set_content_size_internal(Size::new(content_w, content_h));
                    let prev = handle.offset();
                    handle.set_offset_internal(prev);

                    cx.tree
                        .debug_record_scroll_node_telemetry(UiDebugScrollNodeTelemetry {
                            node: cx.node,
                            element: Some(self.element),
                            test_id: debug_test_id.clone(),
                            axis: match props.axis {
                                crate::element::ScrollAxis::X => UiDebugScrollAxis::X,
                                crate::element::ScrollAxis::Y => UiDebugScrollAxis::Y,
                                crate::element::ScrollAxis::Both => UiDebugScrollAxis::Both,
                            },
                            offset: handle.offset(),
                            viewport: handle.viewport_size(),
                            content: handle.content_size(),
                            observed_extent: None,
                            overflow_observation: None,
                        });

                    commit_scroll_authoritative_extent(
                        &mut *cx.app,
                        window,
                        self.element,
                        ScrollAuthoritativeExtentCommit {
                            max_child: Size::new(content_w, content_h),
                            intrinsic_cache_key,
                            probe_cache_key: None,
                            clear_pending_invalidation_probe: true,
                            clear_pending_extent_probe: pending_extent_probe,
                        },
                    );
                    authoritative_observation_cleared_pending = true;
                }
            } else {
                // If post-layout child bounds exceed the currently inferred extent (cached/deferral
                // cases), expand the scroll handle immediately so users can reach the new content.
                let mut changed_grow = false;
                if props.axis.scroll_x()
                    && observed.trusted.width.0 > 0.0
                    && observed.trusted.width.0 > content_w.0 + 0.5
                {
                    content_w = Px(observed.trusted.width.0.max(desired.width.0.max(0.0)));
                    changed_grow = true;
                }
                if props.axis.scroll_y()
                    && observed.trusted.height.0 > 0.0
                    && observed.trusted.height.0 > content_h.0 + 0.5
                {
                    content_h = Px(observed.trusted.height.0.max(desired.height.0.max(0.0)));
                    changed_grow = true;
                }
                if changed_grow {
                    relayout_with_updated_content_bounds = true;
                    if crate::runtime_config::ui_runtime_config().debug_scroll_extent_probe {
                        eprintln!(
                            "scroll extent grew element={:?} node={:?} axis={:?} content=({:.1},{:.1}) observed=({:.1},{:.1}) viewport=({:.1},{:.1}) pending_probe={} must_probe={}",
                            self.element,
                            cx.node,
                            props.axis,
                            handle.content_size().width.0,
                            handle.content_size().height.0,
                            observed.loose.width.0,
                            observed.loose.height.0,
                            handle.viewport_size().width.0,
                            handle.viewport_size().height.0,
                            pending_extent_probe,
                            must_probe_for_growing_extent,
                        );
                    }
                    handle.set_content_size_internal(Size::new(content_w, content_h));
                    let prev = handle.offset();
                    handle.set_offset_internal(prev);

                    cx.tree
                        .debug_record_scroll_node_telemetry(UiDebugScrollNodeTelemetry {
                            node: cx.node,
                            element: Some(self.element),
                            test_id: debug_test_id.clone(),
                            axis: match props.axis {
                                crate::element::ScrollAxis::X => UiDebugScrollAxis::X,
                                crate::element::ScrollAxis::Y => UiDebugScrollAxis::Y,
                                crate::element::ScrollAxis::Both => UiDebugScrollAxis::Both,
                            },
                            offset: handle.offset(),
                            viewport: handle.viewport_size(),
                            content: handle.content_size(),
                            observed_extent: None,
                            overflow_observation: None,
                        });

                    commit_scroll_authoritative_extent(
                        &mut *cx.app,
                        window,
                        self.element,
                        ScrollAuthoritativeExtentCommit {
                            max_child: Size::new(content_w, content_h),
                            intrinsic_cache_key,
                            probe_cache_key: None,
                            clear_pending_invalidation_probe:
                                scroll_overflow_observation_is_authoritative(observation),
                            clear_pending_extent_probe: scroll_overflow_observation_is_authoritative(
                                observation,
                            )
                                && pending_extent_probe,
                        },
                    );
                    authoritative_observation_committed_this_pass =
                        scroll_overflow_observation_is_authoritative(observation);
                    authoritative_observation_cleared_pending =
                        scroll_overflow_observation_is_authoritative(observation);
                }

                if shrink_validation_enabled
                    && !authoritative_observation_committed_this_pass
                    && scroll_overflow_observation_is_authoritative(observation)
                {
                    // Single-child scroll subtrees can over-measure under unbounded probe passes
                    // (including deferred/cached paths and clean probe/final flows). When a bounded
                    // post-layout observation proves the laid-out content is smaller, clamp the
                    // scroll extent down without scheduling another deep measure walk.
                    //
                    // Important nuance:
                    //
                    // In fresh unbounded-probe flows, bounded layout commonly clamps the child subtree
                    // back to the viewport on the scroll axis. An observed extent equal to the viewport
                    // is therefore ambiguous: it does not prove the probed content extent was too
                    // large, only that the final layout phase constrained it. Only treat fresh-probe
                    // observations as shrink proof when the laid-out subtree still exceeds the viewport
                    // (i.e. the observation contains real post-layout overflow beyond `desired`).
                    let post_layout_shrink_has_layout_evidence_x = post_layout_shrink_revalidation
                        && observed.loose.width.0 > 0.0
                        && observed.loose.width.0 + 0.5 < content_w.0;
                    let post_layout_shrink_has_layout_evidence_y = post_layout_shrink_revalidation
                        && observed.loose.height.0 > 0.0
                        && observed.loose.height.0 + 0.5 < content_h.0;
                    let multi_child_post_layout_shrink_revalidation =
                        post_layout_shrink_revalidation && cx.children.len() > 1;
                    let can_shrink_x = defer_this_frame
                        || post_layout_shrink_has_layout_evidence_x
                        || multi_child_post_layout_shrink_revalidation
                        || observed.trusted.width.0 > desired.width.0 + 0.5;
                    let can_shrink_y = defer_this_frame
                        || post_layout_shrink_has_layout_evidence_y
                        || multi_child_post_layout_shrink_revalidation
                        || observed.trusted.height.0 > desired.height.0 + 0.5;
                    let mut changed = false;
                    if props.axis.scroll_x()
                        && can_shrink_x
                        && observed.trusted.width.0 > 0.0
                        && observed.trusted.width.0 + 0.5 < content_w.0
                    {
                        content_w = Px(observed.trusted.width.0.max(desired.width.0.max(0.0)));
                        changed = true;
                    }
                    if props.axis.scroll_y()
                        && can_shrink_y
                        && observed.trusted.height.0 > 0.0
                        && observed.trusted.height.0 + 0.5 < content_h.0
                    {
                        content_h = Px(observed.trusted.height.0.max(desired.height.0.max(0.0)));
                        changed = true;
                    }

                    if changed {
                        if crate::runtime_config::ui_runtime_config().debug_scroll_extent_probe {
                            eprintln!(
                                "scroll extent shrank element={:?} node={:?} axis={:?} content=({:.1},{:.1}) observed_trusted=({:.1},{:.1}) observed_loose=({:.1},{:.1}) desired=({:.1},{:.1}) post_layout_shrink={} defer_this_frame={}",
                                self.element,
                                cx.node,
                                props.axis,
                                handle.content_size().width.0,
                                handle.content_size().height.0,
                                observed.trusted.width.0,
                                observed.trusted.height.0,
                                observed.loose.width.0,
                                observed.loose.height.0,
                                desired.width.0,
                                desired.height.0,
                                post_layout_shrink_revalidation,
                                defer_this_frame,
                            );
                        }
                        relayout_with_updated_content_bounds = true;
                        handle.set_content_size_internal(Size::new(content_w, content_h));
                        let prev = handle.offset();
                        handle.set_offset_internal(prev);

                        cx.tree
                            .debug_record_scroll_node_telemetry(UiDebugScrollNodeTelemetry {
                                node: cx.node,
                                element: Some(self.element),
                                test_id: debug_test_id.clone(),
                                axis: match props.axis {
                                    crate::element::ScrollAxis::X => UiDebugScrollAxis::X,
                                    crate::element::ScrollAxis::Y => UiDebugScrollAxis::Y,
                                    crate::element::ScrollAxis::Both => UiDebugScrollAxis::Both,
                                },
                                offset: handle.offset(),
                                viewport: handle.viewport_size(),
                                content: handle.content_size(),
                                observed_extent: None,
                                overflow_observation: None,
                            });

                        commit_scroll_authoritative_extent(
                            &mut *cx.app,
                            window,
                            self.element,
                            ScrollAuthoritativeExtentCommit {
                                max_child: Size::new(content_w, content_h),
                                intrinsic_cache_key,
                                probe_cache_key: None,
                                clear_pending_invalidation_probe: true,
                                clear_pending_extent_probe: pending_extent_probe,
                            },
                        );
                        authoritative_observation_cleared_pending = true;
                    }
                }
            }

            let deferred_probe_state_still_armed =
                defer_state.kind != ScrollDeferredUnboundedProbeKind::None || pending_extent_probe;
            let authoritative_observation_completed_without_extent_change =
                !authoritative_observation_cleared_pending
                    && scroll_overflow_observation_is_authoritative(observation)
                    && deferred_probe_state_still_armed;
            if authoritative_observation_completed_without_extent_change {
                commit_scroll_authoritative_extent(
                    &mut *cx.app,
                    window,
                    self.element,
                    ScrollAuthoritativeExtentCommit {
                        max_child: Size::new(content_w, content_h),
                        intrinsic_cache_key,
                        probe_cache_key: None,
                        clear_pending_invalidation_probe: defer_state.kind
                            != ScrollDeferredUnboundedProbeKind::None,
                        clear_pending_extent_probe: pending_extent_probe,
                    },
                );
            }

            if relayout_with_updated_content_bounds {
                // Keep wrapper/layout-barrier geometry in sync with the corrected scroll content
                // extent in the same frame. Without this pass, the scroll handle can expose the
                // new range while outer shells (cards, panels, etc.) still retain stale bounds.
                content_bounds = Rect::new(cx.bounds.origin, Size::new(content_w, content_h));
                cx.with_overflow_context(overflow_ctx, |cx| {
                    if !is_probe_layout {
                        if force_barrier_child_root_relayout {
                            for &child in &forced_barrier_child_roots {
                                cx.tree.invalidate(child, Invalidation::Layout);
                            }
                        }
                        let solve_started = profile_cfg.is_some().then(Instant::now);
                        match cx.children {
                            [child] => {
                                cx.solve_barrier_child_root_if_needed(*child, content_bounds);
                            }
                            children => {
                                let roots: Vec<(NodeId, Rect)> =
                                    children.iter().map(|&c| (c, content_bounds)).collect();
                                cx.solve_barrier_child_roots_if_needed(&roots);
                            }
                        }
                        if let Some(started) = solve_started {
                            t_solve_barrier += started.elapsed();
                        }
                    }

                    let layout_started = profile_cfg.is_some().then(Instant::now);
                    for &child in cx.children {
                        let _ = cx.layout_in(child, content_bounds);
                    }
                    if let Some(started) = layout_started {
                        t_layout_children += started.elapsed();
                    }
                });
            }

            if observation.wrapper_peel_budget_hit || observation.deep_scan_budget_hit {
                cx.tree
                    .debug_record_scroll_node_telemetry(UiDebugScrollNodeTelemetry {
                        node: cx.node,
                        element: Some(self.element),
                        test_id: debug_test_id.clone(),
                        axis: match props.axis {
                            crate::element::ScrollAxis::X => UiDebugScrollAxis::X,
                            crate::element::ScrollAxis::Y => UiDebugScrollAxis::Y,
                            crate::element::ScrollAxis::Both => UiDebugScrollAxis::Both,
                        },
                        offset: handle.offset(),
                        viewport: handle.viewport_size(),
                        content: handle.content_size(),
                        observed_extent: Some(observed.trusted),
                        overflow_observation: Some(observation),
                    });
            }
        }

        if let Some(cfg) = profile_cfg
            && let Some(started) = profile_started
        {
            let total = started.elapsed();
            if total >= cfg.min_elapsed && t_measure_children >= cfg.min_self_measure {
                let element_path: Option<String> = {
                    #[cfg(feature = "diagnostics")]
                    {
                        Some(crate::elements::with_window_state(
                            &mut *cx.app,
                            window,
                            |st| {
                                st.debug_path_for_element(self.element)
                                    .unwrap_or_else(|| "<unknown>".to_string())
                            },
                        ))
                    }
                    #[cfg(not(feature = "diagnostics"))]
                    {
                        None
                    }
                };

                tracing::info!(
                    window = ?cx.window,
                    node = ?cx.node,
                    element = self.element.0,
                    pass = ?cx.pass_kind,
                    axis = ?props.axis,
                    probe_unbounded = props.probe_unbounded,
                    children = cx.children.len(),
                    available_w = cx.available.width.0,
                    available_h = cx.available.height.0,
                    desired_w = desired.width.0,
                    desired_h = desired.height.0,
                    content_w = content_w.0,
                    content_h = content_h.0,
                    measure_children_us = t_measure_children.as_micros() as u64,
                    solve_barrier_us = t_solve_barrier.as_micros() as u64,
                    layout_children_us = t_layout_children.as_micros() as u64,
                    total_us = total.as_micros() as u64,
                    element_path = element_path.as_deref().unwrap_or("<unknown>"),
                    "scroll layout profile"
                );
            }
        }

        desired
    }

    pub(super) fn layout_scrollbar_impl<H: UiHost>(
        &mut self,
        cx: &mut LayoutCx<'_, H>,
        props: crate::element::ScrollbarProps,
    ) -> Size {
        clamp_to_constraints(cx.available, props.layout, cx.available)
    }
}

#[cfg(test)]
mod budget_probe_tests {
    use super::*;

    #[derive(Default)]
    struct TestWidget;

    impl<H: UiHost> Widget<H> for TestWidget {
        fn layout(&mut self, _cx: &mut LayoutCx<'_, H>) -> Size {
            Size::new(Px(0.0), Px(0.0))
        }

        fn paint(&mut self, _cx: &mut PaintCx<'_, H>) {}
    }

    fn make_observation(
        wrapper_budget_hit: bool,
        deep_scan_enabled: bool,
        deep_scan_budget_hit: bool,
    ) -> UiDebugScrollOverflowObservationTelemetry {
        UiDebugScrollOverflowObservationTelemetry {
            extent_may_be_stale: true,
            barrier_roots: 1,
            wrapper_peel_budget: 8,
            wrapper_peeled_max: if wrapper_budget_hit { 8 } else { 0 },
            wrapper_peel_budget_hit: wrapper_budget_hit,
            immediate_children_visited: 0,
            immediate_children_skipped_absolute: 0,
            deep_scan_enabled,
            deep_scan_budget_nodes: 4096,
            deep_scan_visited: if deep_scan_enabled {
                if deep_scan_budget_hit { 4096 } else { 128 }
            } else {
                0
            },
            deep_scan_budget_hit,
            deep_scan_skipped_absolute: 0,
        }
    }

    #[test]
    fn scroll_post_layout_observation_budget_hit_schedules_probe_next_frame() {
        let mut app = crate::test_host::TestHost::new();
        let mut ui: UiTree<crate::test_host::TestHost> = UiTree::new();
        let window = AppWindowId::default();
        ui.set_window(window);
        ui.set_debug_enabled(true);

        let root = ui.create_node(TestWidget);
        ui.set_root(root);

        let element_peel = GlobalElementId(101);
        let element_deep = GlobalElementId(202);
        let node_peel = ui.create_node_for_element(element_peel, TestWidget);
        let node_deep = ui.create_node_for_element(element_deep, TestWidget);
        ui.set_children(root, vec![node_peel, node_deep]);

        assert!(
            maybe_schedule_extent_probe_after_observation_budget_hit(
                &mut app,
                &mut ui,
                window,
                node_peel,
                element_peel,
                make_observation(true, false, false),
            ),
            "expected wrapper-peel budget hit to schedule a probe"
        );
        assert!(
            maybe_schedule_extent_probe_after_observation_budget_hit(
                &mut app,
                &mut ui,
                window,
                node_deep,
                element_deep,
                make_observation(false, true, true),
            ),
            "expected deep-scan budget hit to schedule a probe"
        );

        let pending = ui.take_pending_barrier_relayouts();
        assert!(
            pending.contains(&node_peel) && pending.contains(&node_deep),
            "expected both scroll nodes to be scheduled for barrier relayout, got={pending:?}"
        );

        let pending_probe_peel = crate::elements::with_element_state(
            &mut app,
            window,
            element_peel,
            crate::element::ScrollState::default,
            |state| state.pending_extent_probe,
        );
        let pending_probe_deep = crate::elements::with_element_state(
            &mut app,
            window,
            element_deep,
            crate::element::ScrollState::default,
            |state| state.pending_extent_probe,
        );
        assert!(
            pending_probe_peel && pending_probe_deep,
            "expected budget-hit scheduling to set pending_extent_probe"
        );

        assert!(
            !maybe_schedule_extent_probe_after_observation_budget_hit(
                &mut app,
                &mut ui,
                window,
                node_peel,
                element_peel,
                make_observation(true, false, false),
            ),
            "expected repeated scheduling to be a no-op once pending"
        );
        assert!(
            ui.take_pending_barrier_relayouts().is_empty(),
            "expected no additional pending barrier relayouts after a no-op schedule"
        );
    }

    #[test]
    fn scroll_post_layout_observation_deep_scan_can_resolve_wrapper_budget_hit() {
        let mut app = crate::test_host::TestHost::new();
        let mut ui: UiTree<crate::test_host::TestHost> = UiTree::new();
        let window = AppWindowId::default();
        ui.set_window(window);

        let root = ui.create_node(TestWidget);
        ui.set_root(root);

        let element = GlobalElementId(404);
        let node = ui.create_node_for_element(element, TestWidget);
        ui.set_children(root, vec![node]);

        assert!(
            !maybe_schedule_extent_probe_after_observation_budget_hit(
                &mut app,
                &mut ui,
                window,
                node,
                element,
                make_observation(true, true, false),
            ),
            "expected completed deep scan to resolve wrapper-peel budget hit without scheduling another probe"
        );
        assert!(
            ui.take_pending_barrier_relayouts().is_empty(),
            "expected resolved wrapper budget hit to avoid scheduling a barrier relayout"
        );

        let pending_probe = crate::elements::with_element_state(
            &mut app,
            window,
            element,
            crate::element::ScrollState::default,
            |state| state.pending_extent_probe,
        );
        assert!(
            !pending_probe,
            "expected resolved wrapper budget hit to leave pending_extent_probe cleared"
        );
    }

    #[test]
    fn scroll_post_layout_observation_budget_hit_schedules_probe_without_edge_requirement() {
        let mut app = crate::test_host::TestHost::new();
        let mut ui: UiTree<crate::test_host::TestHost> = UiTree::new();
        let window = AppWindowId::default();
        ui.set_window(window);

        let root = ui.create_node(TestWidget);
        ui.set_root(root);

        let element = GlobalElementId(303);
        let node = ui.create_node_for_element(element, TestWidget);
        ui.set_children(root, vec![node]);

        assert!(maybe_schedule_extent_probe_after_observation_budget_hit(
            &mut app,
            &mut ui,
            window,
            node,
            element,
            make_observation(false, true, true),
        ));

        let pending = ui.take_pending_barrier_relayouts();
        assert!(
            pending.contains(&node),
            "expected non-edge budget hit to still schedule a barrier relayout, got={pending:?}"
        );

        let pending_probe = crate::elements::with_element_state(
            &mut app,
            window,
            element,
            crate::element::ScrollState::default,
            |state| state.pending_extent_probe,
        );
        assert!(
            pending_probe,
            "expected budget hit to set pending_extent_probe before edge"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fret_core::{Point, Rect};
    use slotmap::SlotMap;
    use std::collections::{HashMap, HashSet};

    #[derive(Default)]
    struct TestOverflowTree {
        children: HashMap<NodeId, Vec<NodeId>>,
        bounds: HashMap<NodeId, Rect>,
        absolute: HashSet<NodeId>,
        clip_overflow: HashSet<NodeId>,
    }

    impl ScrollOverflowTree for TestOverflowTree {
        fn children_ref(&self, node: NodeId) -> &[NodeId] {
            self.children.get(&node).map(Vec::as_slice).unwrap_or(&[])
        }

        fn node_bounds(&self, node: NodeId) -> Option<Rect> {
            self.bounds.get(&node).copied()
        }

        fn node_is_absolute(&mut self, node: NodeId) -> bool {
            self.absolute.contains(&node)
        }

        fn node_clips_descendant_scroll_overflow(&mut self, node: NodeId) -> bool {
            self.clip_overflow.contains(&node)
        }
    }

    fn rect_xywh(x: f32, y: f32, w: f32, h: f32) -> Rect {
        Rect::new(
            Point::new(Px(x), Px(y)),
            Size::new(Px(w.max(0.0)), Px(h.max(0.0))),
        )
    }

    #[test]
    fn scroll_observed_overflow_peels_same_bounds_wrapper_chain() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let wrapper = ids.insert(());
        let content_root = ids.insert(());
        let leaf_overflow = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![wrapper]);
        tree.children.insert(wrapper, vec![content_root]);
        tree.children.insert(content_root, vec![leaf_overflow]);

        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(wrapper, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(content_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(leaf_overflow, rect_xywh(0.0, 0.0, 100.0, 300.0));

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, _telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(100.0)),
            false,
            false,
        );

        assert_eq!(observed.trusted.height, Px(300.0));
    }

    #[test]
    fn scroll_observed_overflow_bounded_scan_discovers_deeper_overflow() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let observe_root = ids.insert(());
        let wrapper_a = ids.insert(());
        let wrapper_b = ids.insert(());
        let deep_overflow = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![observe_root]);
        tree.children
            .insert(observe_root, vec![wrapper_a, wrapper_b]);
        tree.children.insert(wrapper_a, vec![deep_overflow]);

        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(observe_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(wrapper_a, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(wrapper_b, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(deep_overflow, rect_xywh(0.0, 0.0, 100.0, 300.0));

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, _telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(100.0)),
            true,
            true,
        );

        assert_eq!(observed.trusted.height, Px(300.0));
    }

    #[test]
    fn scroll_observed_overflow_ignores_stale_nonleaf_extent_until_descendants_confirm_it() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let stale_wrapper = ids.insert(());
        let leaf = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![stale_wrapper]);
        tree.children.insert(stale_wrapper, vec![leaf]);

        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(stale_wrapper, rect_xywh(0.0, 0.0, 100.0, 300.0));
        tree.bounds.insert(leaf, rect_xywh(0.0, 0.0, 100.0, 200.0));

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(300.0)),
            true,
            true,
        );

        assert_eq!(observed.loose.height, Px(300.0));
        assert_eq!(observed.trusted.height, Px(200.0));
        assert!(telemetry.deep_scan_enabled);
    }

    #[test]
    fn scroll_observed_overflow_preserves_multi_child_container_padding() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let container = ids.insert(());
        let child_a = ids.insert(());
        let child_b = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![container]);
        tree.children.insert(container, vec![child_a, child_b]);

        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(container, rect_xywh(0.0, 0.0, 100.0, 300.0));
        tree.bounds
            .insert(child_a, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(child_b, rect_xywh(0.0, 150.0, 100.0, 80.0));

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(350.0)),
            true,
            true,
        );

        assert_eq!(observed.loose.height, Px(300.0));
        assert_eq!(observed.trusted.height, Px(300.0));
        assert!(telemetry.deep_scan_enabled);
    }

    #[test]
    fn scroll_observed_overflow_prefers_descendant_frontier_over_shorter_outer_shell() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let outer_shell = ids.insert(());
        let inner_shell = ids.insert(());
        let leaf = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![outer_shell]);
        tree.children.insert(outer_shell, vec![inner_shell]);
        tree.children.insert(inner_shell, vec![leaf]);

        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(outer_shell, rect_xywh(0.0, 0.0, 100.0, 280.0));
        tree.bounds
            .insert(inner_shell, rect_xywh(0.0, 0.0, 100.0, 416.0));
        tree.bounds.insert(leaf, rect_xywh(0.0, 0.0, 100.0, 400.0));

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(500.0)),
            true,
            true,
        );

        assert_eq!(observed.loose.height, Px(416.0));
        assert_eq!(observed.trusted.height, Px(416.0));
        assert!(telemetry.deep_scan_enabled);
    }

    #[test]
    fn scroll_observed_overflow_does_not_deep_scan_when_not_stale() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let observe_root = ids.insert(());
        let wrapper = ids.insert(());
        let sibling = ids.insert(());
        let deep_overflow = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![observe_root]);
        tree.children.insert(observe_root, vec![wrapper, sibling]);
        tree.children.insert(wrapper, vec![deep_overflow]);

        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(observe_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        // Wrapper bounds mask deeper overflow.
        tree.bounds
            .insert(wrapper, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(sibling, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(deep_overflow, rect_xywh(0.0, 0.0, 100.0, 300.0));

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, _telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(100.0)),
            false,
            true,
        );

        assert_eq!(observed.trusted.height, Px(100.0));
    }

    #[test]
    fn scroll_observed_overflow_wrapper_peel_stops_before_nested_viewport_boundary() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let nested_viewport = ids.insert(());
        let deep_overflow = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![nested_viewport]);
        tree.children.insert(nested_viewport, vec![deep_overflow]);
        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(nested_viewport, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(deep_overflow, rect_xywh(0.0, 0.0, 100.0, 320.0));
        tree.clip_overflow.insert(nested_viewport);

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(100.0)),
            true,
            true,
        );

        assert!(telemetry.deep_scan_enabled);
        assert_eq!(observed.trusted.height, Px(100.0));
    }

    #[test]
    fn scroll_observed_overflow_wrapper_peel_stops_before_absolute_child() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let absolute_child = ids.insert(());
        let deep_overflow = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![absolute_child]);
        tree.children.insert(absolute_child, vec![deep_overflow]);
        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(absolute_child, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(deep_overflow, rect_xywh(0.0, 0.0, 100.0, 320.0));
        tree.absolute.insert(absolute_child);

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, _telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(100.0)),
            true,
            true,
        );

        assert_eq!(observed.trusted.height, Px(100.0));
    }

    #[test]
    fn scroll_observed_overflow_excludes_absolute_nodes() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let abs_child = ids.insert(());
        let normal_child = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children
            .insert(barrier_root, vec![abs_child, normal_child]);
        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(abs_child, rect_xywh(0.0, 0.0, 100.0, 800.0));
        tree.bounds
            .insert(normal_child, rect_xywh(0.0, 0.0, 100.0, 300.0));
        tree.absolute.insert(abs_child);

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, _telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(100.0)),
            true,
            true,
        );

        assert_eq!(observed.trusted.height, Px(300.0));
    }

    #[test]
    fn scroll_observed_overflow_telemetry_reports_budget_hits() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());

        let mut chain: Vec<NodeId> = Vec::new();
        for _ in 0..(8 + 4096 + 16) {
            chain.push(ids.insert(()));
        }

        let mut tree = TestOverflowTree::default();
        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.children.insert(barrier_root, vec![chain[0]]);

        for (ix, &id) in chain.iter().enumerate() {
            tree.bounds.insert(id, rect_xywh(0.0, 0.0, 100.0, 100.0));
            if let Some(&next) = chain.get(ix + 1) {
                tree.children.insert(id, vec![next]);
            }
        }

        // Put overflow beyond the deep-scan node budget so the scan must hit its budget before it
        // can observe the true extent.
        let last = *chain.last().expect("non-empty chain");
        tree.bounds.insert(last, rect_xywh(0.0, 0.0, 100.0, 1000.0));

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (_observed, telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(100.0)),
            true,
            true,
        );

        assert!(telemetry.wrapper_peel_budget_hit);
        assert!(telemetry.deep_scan_enabled);
        assert!(telemetry.deep_scan_budget_hit);
        assert_eq!(telemetry.deep_scan_budget_nodes, 4096);
        assert_eq!(telemetry.deep_scan_visited, 4096);
    }

    #[test]
    fn scroll_observed_overflow_deep_scan_resolves_wrapper_chain_beyond_peel_budget() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());

        let mut chain: Vec<NodeId> = (0..10).map(|_| ids.insert(())).collect();
        let leaf = ids.insert(());
        chain.push(leaf);

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![chain[0]]);
        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));

        for window in chain.windows(2) {
            let parent = window[0];
            let child = window[1];
            tree.children.insert(parent, vec![child]);
            tree.bounds
                .insert(parent, rect_xywh(0.0, 0.0, 100.0, 100.0));
        }
        tree.bounds.insert(leaf, rect_xywh(0.0, 0.0, 100.0, 320.0));

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(100.0)),
            true,
            true,
        );

        assert!(telemetry.wrapper_peel_budget_hit);
        assert!(telemetry.deep_scan_enabled);
        assert!(!telemetry.deep_scan_budget_hit);
        assert_eq!(observed.trusted.height, Px(320.0));
    }

    #[test]
    fn scroll_observed_overflow_respects_deep_scan_allowed_flag() {
        let mut ids: SlotMap<NodeId, ()> = SlotMap::with_key();
        let barrier_root = ids.insert(());
        let observe_root = ids.insert(());
        let wrapper_a = ids.insert(());
        let wrapper_b = ids.insert(());
        let deep_overflow = ids.insert(());

        let mut tree = TestOverflowTree::default();
        tree.children.insert(barrier_root, vec![observe_root]);
        tree.children
            .insert(observe_root, vec![wrapper_a, wrapper_b]);
        tree.children.insert(wrapper_a, vec![deep_overflow]);

        tree.bounds
            .insert(barrier_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(observe_root, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(wrapper_a, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(wrapper_b, rect_xywh(0.0, 0.0, 100.0, 100.0));
        tree.bounds
            .insert(deep_overflow, rect_xywh(0.0, 0.0, 100.0, 300.0));

        let content_bounds = rect_xywh(0.0, 0.0, 100.0, 100.0);
        let (observed, telemetry) = observe_scroll_overflow_extents(
            &mut tree,
            &[barrier_root],
            content_bounds,
            crate::element::ScrollAxis::Y,
            Size::new(Px(100.0), Px(100.0)),
            true,
            false,
        );

        assert_eq!(observed.trusted.height, Px(100.0));
        assert!(!telemetry.deep_scan_enabled);
        assert_eq!(telemetry.deep_scan_visited, 0);
        assert!(!telemetry.deep_scan_budget_hit);
    }

    #[test]
    fn authoritative_extent_commit_clears_deferred_probe_state() {
        let mut app = crate::test_host::TestHost::new();
        let window = AppWindowId::default();
        let element = GlobalElementId(9001);

        crate::elements::with_element_state(
            &mut app,
            window,
            element,
            ScrollDeferredUnboundedProbeState::default,
            |state| {
                state.kind = ScrollDeferredUnboundedProbeKind::Invalidation;
                state.stable_frames = 2;
                state.pending_invalidation_probe = true;
            },
        );

        commit_scroll_authoritative_extent(
            &mut app,
            window,
            element,
            ScrollAuthoritativeExtentCommit {
                max_child: Size::new(Px(120.0), Px(160.0)),
                intrinsic_cache_key: None,
                probe_cache_key: None,
                clear_pending_invalidation_probe: true,
                clear_pending_extent_probe: false,
            },
        );

        let state = crate::elements::with_element_state(
            &mut app,
            window,
            element,
            ScrollDeferredUnboundedProbeState::default,
            |state| *state,
        );
        assert_eq!(
            state.kind,
            ScrollDeferredUnboundedProbeKind::None,
            "authoritative extent commit should end deferred probe mode instead of leaving the state machine armed"
        );
        assert_eq!(
            state.stable_frames, 0,
            "authoritative extent commit should clear deferred probe stability bookkeeping"
        );
        assert!(
            !state.pending_invalidation_probe,
            "authoritative extent commit should clear the pending invalidation probe flag"
        );
    }
}