re_dataframe 0.32.0-rc.1

High-level query APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
use std::collections::BTreeSet;
use std::sync::OnceLock;

use arrow::array::{
    Array as _, ArrayData, ArrayRef as ArrowArrayRef, BooleanArray as ArrowBooleanArray,
    MutableArrayData, PrimitiveArray as ArrowPrimitiveArray, RecordBatch as ArrowRecordBatch,
    RecordBatchOptions, make_array,
};
use arrow::buffer::{NullBuffer, ScalarBuffer as ArrowScalarBuffer};
use arrow::datatypes::{
    DataType as ArrowDataType, Fields as ArrowFields, Schema as ArrowSchema,
    SchemaRef as ArrowSchemaRef,
};
use itertools::{Either, Itertools as _};
use nohash_hasher::{IntMap, IntSet};
use re_arrow_util::{ArrowArrayDowncastRef as _, into_arrow_ref};
use re_chunk::external::arrow::array::ArrayRef;
use re_chunk::{
    Chunk, ComponentIdentifier, EntityPath, RangeQuery, RowId, TimeInt, TimelineName,
    UnitChunkShared,
};
use re_chunk_store::{
    ChunkStore, ColumnDescriptor, ComponentColumnDescriptor, Index, IndexColumnDescriptor,
    IndexValue, QueryExpression, SparseFillStrategy,
};
use re_log::{debug_assert, debug_assert_eq, debug_panic};
use re_log_types::AbsoluteTimeRange;
use re_query::{QueryCache, StorageEngineLike};
use re_sorbet::{
    ChunkColumnDescriptors, ColumnSelector, RowIdColumnDescriptor, TimeColumnSelector,
};
use re_span::Span;
use re_types_core::arrow_helpers::as_array_ref;
use re_types_core::{Loggable as _, SerializedComponentColumn, archetypes};

// ---

/// Streaming-join state for a single component column on a single row.
#[derive(Debug)]
struct StreamingJoinStateEntry<'a> {
    /// Which `Chunk` is this?
    chunk: &'a Chunk,

    /// How far are we into this `Chunk`?
    cursor: u64,

    /// What's the `RowId` at the current cursor?
    row_id: RowId,
}

/// Streaming-join state for a single component column on a single row.
///
/// Possibly retrofilled, see [`QueryExpression::sparse_fill_strategy`].
#[derive(Debug)]
enum StreamingJoinState<'a> {
    /// Incoming data for the current iteration.
    StreamingJoinState(StreamingJoinStateEntry<'a>),

    /// Data retrofilled through an extra query.
    ///
    /// See [`QueryExpression::sparse_fill_strategy`].
    Retrofilled(UnitChunkShared),
}

/// Per-row index data resolved by [`QueryHandle::_resolve_one_row`]: the max value
/// seen on each timeline for this row.
type ResolvedRow = IntMap<TimelineName, (TimeInt, ArrowScalarBuffer<i64>)>;

/// Output of [`QueryHandle::next_n_rows`] / [`QueryHandle::next_n_rows_async`].
///
/// `columns` always has length equal to `schema().fields().len()`. `num_rows` is the number
/// of rows actually appended (≤ requested `max_rows`; 0 means the query is exhausted).
#[derive(Debug)]
pub struct NextNRowsOutput {
    pub columns: Vec<ArrowArrayRef>,
    pub num_rows: usize,
}

/// One step in the deferred-replay finalizer inside `_next_n_rows`.
///
/// Each output column accumulates a list of [`ColumnExtend`] entries during the
/// row-resolution loop and replays them via `MutableArrayData` once the batch is
/// fully sized, allowing single-row pushes to coalesce into long abutting runs.
#[derive(Debug, Clone, Copy)]
enum ColumnExtend {
    /// Append a contiguous row run by copying `rows` from one of the column's
    /// distinct source arrays (`SelectedEmitter::Source::sources[source_idx]`).
    Range {
        /// Index into `SelectedEmitter::Source::sources` — picks which previously
        /// registered source array this run reads from. Source arrays are
        /// deduplicated by their underlying chunk pointer at registration time
        /// (see `SelectedEmitter::ensure_source`), so multiple runs from the
        /// same chunk share a single `source_idx`.
        source_idx: usize,

        /// Row range to copy out of `sources[source_idx]` (start row, inclusive,
        /// for `len` rows).
        rows: Span<usize>,
    },

    /// Append `len` null rows.
    Nulls { len: usize },
}

/// Per-output-column emission state used by [`QueryHandle::_next_n_rows`].
///
/// `Source` columns accumulate [`ColumnExtend`] entries that reference shared
/// source arrays (deduplicated by chunk pointer), then replay them through
/// `MutableArrayData` once the batch is fully sized. `Time` columns push i64
/// values + a validity mask directly.
enum SelectedEmitter {
    Source {
        sources: Vec<ArrayData>,

        source_ids: Vec<*const Chunk>, // Used over `ChunkId` for speed.

        /// `source_bytes_per_row[i]` is the estimated bytes-per-row for `sources[i]`, computed
        /// as `get_array_memory_size() / len()` at registration time. Cheap (one
        /// division per distinct source per batch) and lets the walk amortize the byte
        /// budget without inspecting `MutableArrayData` until freeze.
        source_bytes_per_row: Vec<usize>,

        extends: Vec<ColumnExtend>,
    },
    Time {
        values: Vec<i64>,
        valid: Vec<bool>,
    },
}

impl SelectedEmitter {
    fn ensure_source(
        sources: &mut Vec<ArrayData>,
        source_ids: &mut Vec<*const Chunk>,
        source_bytes_per_row: &mut Vec<usize>,
        id: *const Chunk,
        data: impl FnOnce() -> ArrayData,
    ) -> usize {
        if let Some(idx) = source_ids.iter().position(|x| *x == id) {
            idx
        } else {
            let idx = sources.len();
            let d = data();
            let bpr = d.get_array_memory_size().checked_div(d.len()).unwrap_or(0);
            sources.push(d);
            source_ids.push(id);
            source_bytes_per_row.push(bpr);
            idx
        }
    }

    /// Append a contiguous row run drawn from `sources[source_idx]`,
    /// merging with a trailing abutting `Range` from the same source.
    /// Coalescing turns long runs of single-row extends into a handful
    /// of multi-row extends, shrinking the replay loop in the finalizer.
    fn push_run(extends: &mut Vec<ColumnExtend>, source_idx: usize, rows: Span<usize>) {
        if rows.len == 0 {
            return;
        }
        if let Some(ColumnExtend::Range {
            source_idx: prev_src,
            rows: prev_rows,
        }) = extends.last_mut()
            && *prev_src == source_idx
            && prev_rows.end() == rows.start
        {
            prev_rows.len += rows.len;
            return;
        }
        extends.push(ColumnExtend::Range { source_idx, rows });
    }

    /// Append `len` null rows, merging with a trailing `Nulls` entry.
    fn push_nulls(extends: &mut Vec<ColumnExtend>, len: usize) {
        if len == 0 {
            return;
        }
        if let Some(ColumnExtend::Nulls { len: prev_len }) = extends.last_mut() {
            *prev_len += len;
            return;
        }
        extends.push(ColumnExtend::Nulls { len });
    }
}

// TODO(cmc): (no specific order) (should we make issues for these?)
// * [x] basic thing working
// * [x] custom selection
// * [x] support for overlaps (slow)
// * [x] pagination (any solution, even a slow one)
// * [x] pov support
// * [x] latestat sparse-filling
// * [x] sampling support
// * [x] clears
// * [x] pagination (fast)
// * [x] take kernel duplicates all memory
// * [x] dedupe-latest without allocs/copies
// * [ ] allocate null arrays once
// * [ ] overlaps (less dumb)
// * [ ] selector-based `filtered_index`
// * [ ] configurable cache bypass

/// A handle to a dataframe query, ready to be executed.
///
/// Cheaply created via `QueryEngine::query`.
///
/// See [`QueryHandle::next_row`] or [`QueryHandle::into_iter`].
pub struct QueryHandle<E: StorageEngineLike> {
    /// Handle to the `QueryEngine`.
    pub(crate) engine: E,

    /// The original query expression used to instantiate this handle.
    pub(crate) query: QueryExpression,

    /// Immutable view metadata. Lazily computed on first use.
    ///
    /// It is important that handles stay cheap to create.
    state: OnceLock<QueryHandleState>,

    /// Mutable iteration state. Lazily initialized on the first `&mut self` call.
    ///
    /// Layout mirrors [`QueryHandleState::view_chunks`].
    iter_state: Option<IterState>,
}

/// Immutable per-chunk metadata used by the streaming-join walk.
///
/// `time_min`/`time_max` are cached at init from the chunk's time column for the query's
/// `filtered_index`, used for range-based pruning and as the sort key for early-break iteration.
struct ChunkBundle {
    chunk: Chunk,
    time_min: i64,
    time_max: i64,
}

impl ChunkBundle {
    fn new(chunk: Chunk, filtered_index: Option<&Index>) -> Self {
        let (time_min, time_max) = filtered_index
            .and_then(|idx| chunk.timelines().get(idx))
            .map_or((i64::MIN, i64::MAX), |tc| {
                let r = tc.time_range();
                (r.min().as_i64(), r.max().as_i64())
            });
        Self {
            chunk,
            time_min,
            time_max,
        }
    }
}

/// Mutable per-chunk iteration state for the streaming-join walk.
///
/// `cursor` tracks the current row inside the corresponding [`ChunkBundle::chunk`].
/// `exhausted` is set once the cursor moves past `chunk.num_rows()` or once
/// `cur_index_value` exceeds `time_max`, allowing later rows to skip the chunk entirely.
#[derive(Debug, Default, Clone, Copy)]
struct ChunkIterCursor {
    cursor: u64,
    exhausted: bool,
}

/// Mutable iteration state. Lazily initialized on the first `&mut self` iteration call,
/// after the immutable [`QueryHandleState`] has been built.
///
/// Lives outside `OnceLock` so that the public iteration API can take `&mut self` and
/// mutate it through plain Rust references (no `Cell`/atomics needed).
struct IterState {
    /// Current row index: the position of the iterator. For [`QueryHandle::next_row`].
    ///
    /// This represents the number of rows that the caller has iterated on; unrelated to
    /// the per-chunk cursors. The corresponding index value is
    /// [`QueryHandleState::unique_index_values`]`[cur_row]`.
    cur_row: u64,

    /// Per-view, per-chunk cursors. Layout mirrors [`QueryHandleState::view_chunks`]
    /// exactly: `view_chunks[view_idx][chunk_idx]` corresponds to
    /// `state.view_chunks[view_idx][chunk_idx]`.
    view_chunks: Vec<Vec<ChunkIterCursor>>,
}

impl IterState {
    fn new(state: &QueryHandleState) -> Self {
        Self {
            cur_row: 0,
            view_chunks: state
                .view_chunks
                .iter()
                .map(|chunks| vec![ChunkIterCursor::default(); chunks.len()])
                .collect(),
        }
    }
}

/// Internal private state. Lazily computed.
struct QueryHandleState {
    /// Describes the columns that make up this view.
    ///
    /// See [`QueryExpression::view_contents`].
    view_contents: ChunkColumnDescriptors,

    /// Describes the columns specifically selected to be returned from this view.
    ///
    /// All returned rows will have an Arrow schema that matches this selection.
    ///
    /// Columns that do not yield any data will still be present in the results, filled with null values.
    ///
    /// The extra `usize` is the index in [`QueryHandleState::view_contents`] that this selection
    /// points to.
    ///
    /// See also [`QueryHandleState::arrow_schema`].
    selected_contents: Vec<(usize, ColumnDescriptor)>,

    /// This keeps track of the static data associated with each entry in `selected_contents`, if any.
    ///
    /// This is queried only once during init, and will override all cells that follow.
    ///
    /// `selected_contents`: [`QueryHandleState::selected_contents`]
    selected_static_values: Vec<Option<UnitChunkShared>>,

    /// The actual index filter in use, since the user-specified one is optional.
    ///
    /// This just defaults to `Index::default()` if the user hasn't specified any: the actual
    /// value is irrelevant since this means we are only concerned with static data anyway.
    filtered_index: Index,

    /// The Arrow schema that corresponds to the `selected_contents`.
    ///
    /// All returned rows will have this schema.
    arrow_schema: ArrowSchemaRef,

    /// All the [`Chunk`]s included in the view contents, with their cached time ranges.
    ///
    /// These are already sorted, densified, vertically sliced, and [latest-deduped] according
    /// to the query. Per-chunk iteration cursors live in [`IterState::view_chunks`] with
    /// matching layout (chunks are allowed to overlap, so iteration may rebound between two
    /// or more chunks).
    ///
    /// This vector's entries correspond to those in [`QueryHandleState::view_contents`].
    /// Note: time and column entries don't have chunks -- inner vectors will be empty.
    ///
    /// [latest-deduped]: [`Chunk::deduped_latest_on_index`]
    //
    // NOTE: Reminder: we have to query everything in the _view_, irrelevant of the current selection.
    view_chunks: Vec<Vec<ChunkBundle>>,

    /// All unique index values that can possibly be returned by this query.
    ///
    /// Guaranteed ascendingly sorted and deduped.
    ///
    /// See also [`IterState::cur_row`].
    unique_index_values: Vec<IndexValue>,
}

impl<E: StorageEngineLike> QueryHandle<E> {
    pub(crate) fn new(engine: E, query: QueryExpression) -> Self {
        Self {
            engine,
            query,
            state: Default::default(),
            iter_state: None,
        }
    }
}

impl<E: StorageEngineLike> QueryHandle<E> {
    /// Lazily initialize internal private state.
    ///
    /// It is important that query handles stay cheap to create.
    fn init(&self) -> &QueryHandleState {
        self.engine.with(|store, cache| {
            self.state
                .get_or_init(|| Self::init_(&self.query, store, cache))
        })
    }

    /// Trigger lazy initialization of both `state` and `iter_state`, then return split
    /// borrows into the immutable view metadata and the mutable iteration state.
    ///
    /// All `&mut self` iteration entry points funnel through this helper so the rest of
    /// the implementation can work against `(&QueryHandleState, &mut IterState)` directly,
    /// without further interior mutability.
    fn init_iter(&mut self) -> (&QueryHandleState, &mut IterState) {
        // First trigger immutable lazy init so the OnceLock is populated.
        let _ = self.init();
        // Now split-borrow `state` (immut, via OnceLock::get) from `iter_state` (mut).
        let Self {
            state, iter_state, ..
        } = self;
        let state = state.get().expect("state was just initialized by init()");
        let iter_state = iter_state.get_or_insert_with(|| IterState::new(state));
        (state, iter_state)
    }

    // NOTE: This is split in its own method otherwise it completely breaks `rustfmt`.
    #[tracing::instrument(level = "trace", skip_all)]
    fn init_(query: &QueryExpression, store: &ChunkStore, cache: &QueryCache) -> QueryHandleState {
        re_tracing::profile_scope!("init");

        // The timeline doesn't matter if we're running in static-only mode.
        let filtered_index = query
            .filtered_index
            .unwrap_or_else(|| TimelineName::new(""));

        // 1. Compute the schema for the query.
        let view_contents_schema = store.schema_for_query(query);
        let view_contents = view_contents_schema.indices_and_components();

        // 2. Compute the schema of the selected contents.
        //
        // The caller might have selected columns that do not exist in the view: they should
        // still appear in the results.
        let selected_contents: Vec<(_, _)> = if let Some(selection) = query.selection.as_ref() {
            Self::compute_user_selection(&view_contents, selection)
        } else {
            view_contents.clone().into_iter().enumerate().collect()
        };

        // 3. Compute the Arrow schema of the selected components.
        //
        // Every result returned using this `QueryHandle` will match this schema exactly.
        let arrow_schema = ArrowSchemaRef::from(ArrowSchema::new_with_metadata(
            selected_contents
                .iter()
                .map(|(_, descr)| descr.to_arrow_field(re_sorbet::BatchType::Dataframe))
                .collect::<ArrowFields>(),
            Default::default(),
        ));

        // 4. Perform the query and keep track of all the relevant chunks.
        let range_query = {
            let index_range = if query.filtered_index.is_none() {
                AbsoluteTimeRange::EMPTY // static-only
            } else if let Some(using_index_values) = query.using_index_values.as_ref() {
                using_index_values
                    .first()
                    .and_then(|start| using_index_values.last().map(|end| (start, end)))
                    .map_or(AbsoluteTimeRange::EMPTY, |(start, end)| {
                        AbsoluteTimeRange::new(*start, *end)
                    })
            } else {
                query
                    .filtered_index_range
                    .unwrap_or(AbsoluteTimeRange::EVERYTHING)
            };

            RangeQuery::new(filtered_index, index_range)
                .keep_extra_timelines(true) // we want all the timelines we can get!
                .keep_extra_components(false)
        };
        let (view_pov_chunks_idx, mut view_chunks) =
            Self::fetch_view_chunks(query, store, cache, &range_query, &view_contents);

        // 5. Collect all relevant clear chunks and update the view accordingly.
        //
        // We'll turn the clears into actual empty arrays of the expected component type.
        {
            re_tracing::profile_scope!("clear_chunks");

            let clear_chunks =
                Self::fetch_clear_chunks(query, store, cache, &range_query, &view_contents);
            for (view_idx, chunks) in view_chunks.iter_mut().enumerate() {
                let Some(ColumnDescriptor::Component(descr)) = view_contents.get(view_idx) else {
                    continue;
                };

                descr.sanity_check();

                // NOTE: It would be tempting to concatenate all these individual clear chunks into one
                // single big chunk, but that'd be a mistake: 1) it's costly to do so but more
                // importantly 2) that would lead to likely very large chunk overlap, which is very bad
                // for business.
                if let Some(clear_chunks) = clear_chunks.get(&descr.entity_path) {
                    chunks.extend(clear_chunks.iter().map(|chunk| {
                        let child_datatype = match &descr.store_datatype {
                            ArrowDataType::List(field) | ArrowDataType::LargeList(field) => {
                                field.data_type().clone()
                            }
                            ArrowDataType::Dictionary(_, datatype) => (**datatype).clone(),
                            datatype => datatype.clone(),
                        };

                        let mut chunk = chunk.clone();
                        // Only way this could fail is if the number of rows did not match.
                        #[expect(clippy::unwrap_used)]
                        chunk
                            .add_component(SerializedComponentColumn::new(
                                re_arrow_util::new_list_array_of_empties(
                                    &child_datatype,
                                    chunk.num_rows(),
                                ),
                                re_types_core::ComponentDescriptor {
                                    component_type: descr.component_type,
                                    archetype: descr.archetype,
                                    component: descr.component,
                                },
                            ))
                            .unwrap();

                        ChunkBundle::new(chunk, Some(&filtered_index))
                    }));
                }
            }
        }

        // 5b. Sort each view's chunks by `time_min` ascending.
        //
        // The streaming-join walk relies on this ordering to break out of the per-row inner
        // loop as soon as it sees a chunk whose `time_min > cur_index_value`. Order doesn't
        // affect row output because the streaming-join already takes max-RowId across
        // overlapping chunks for any given index value.
        for chunks in &mut view_chunks {
            chunks.sort_by_key(|cc| cc.time_min);
        }

        // 6. Collect all unique index values.
        //
        // Used to achieve ~O(log(n)) pagination.
        let unique_index_values = if query.filtered_index.is_none() {
            vec![TimeInt::STATIC]
        } else if let Some(using_index_values) = query.using_index_values.as_ref() {
            using_index_values
                .iter()
                .filter(|index_value| !index_value.is_static())
                .copied()
                .collect_vec()
        } else {
            re_tracing::profile_scope!("index_values");

            let mut view_chunks = view_chunks.iter();
            let view_chunks = if let Some(view_pov_chunks_idx) = view_pov_chunks_idx {
                Either::Left(view_chunks.nth(view_pov_chunks_idx).into_iter())
            } else {
                Either::Right(view_chunks)
            };

            let mut all_unique_index_values: BTreeSet<TimeInt> = view_chunks
                .flat_map(|chunks| {
                    chunks.iter().filter_map(|cc| {
                        cc.chunk
                            .timelines()
                            .get(&filtered_index)
                            .map(|time_column| time_column.times())
                    })
                })
                .flatten()
                .collect();

            if let Some(filtered_index_values) = query.filtered_index_values.as_ref() {
                all_unique_index_values.retain(|time| filtered_index_values.contains(time));
            }

            all_unique_index_values
                .into_iter()
                .filter(|index_value| !index_value.is_static())
                .collect_vec()
        };

        let selected_static_values = {
            re_tracing::profile_scope!("static_values");

            selected_contents
                .iter()
                .map(|(_view_idx, descr)| match descr {
                    ColumnDescriptor::RowId(_) | ColumnDescriptor::Time(_) => None,
                    ColumnDescriptor::Component(descr) => {
                        descr.sanity_check();

                        let query =
                            re_chunk::LatestAtQuery::new(TimelineName::new(""), TimeInt::STATIC);

                        let results =
                            cache.latest_at(&query, &descr.entity_path, [descr.component]);

                        results.components.into_values().next()
                    }
                })
                .collect_vec()
        };

        for (_, descr) in &selected_contents {
            descr.sanity_check();
        }

        QueryHandleState {
            view_contents: view_contents_schema,
            selected_contents,
            selected_static_values,
            filtered_index,
            arrow_schema,
            view_chunks,
            unique_index_values,
        }
    }

    #[tracing::instrument(level = "trace", skip_all)]
    fn compute_user_selection(
        view_contents: &[ColumnDescriptor],
        selection: &[ColumnSelector],
    ) -> Vec<(usize, ColumnDescriptor)> {
        selection
            .iter()
            .map(|column| match column {
                ColumnSelector::RowId => view_contents
                    .iter()
                    .enumerate()
                    .find_map(|(idx, view_column)| {
                        if let ColumnDescriptor::RowId(descr) = view_column {
                            Some((idx, ColumnDescriptor::RowId(descr.clone())))
                        } else {
                            None
                        }
                    })
                    .unwrap_or_else(|| {
                        (
                            usize::MAX,
                            ColumnDescriptor::RowId(RowIdColumnDescriptor::from_sorted(false)),
                        )
                    }),

                ColumnSelector::Time(selected_column) => {
                    let TimeColumnSelector {
                        timeline: selected_timeline,
                    } = selected_column;

                    view_contents
                        .iter()
                        .enumerate()
                        .filter_map(|(idx, view_column)| {
                            if let ColumnDescriptor::Time(view_descr) = view_column {
                                Some((idx, view_descr))
                            } else {
                                None
                            }
                        })
                        .find(|(_idx, view_descr)| {
                            *view_descr.timeline().name() == *selected_timeline
                        })
                        .map_or_else(
                            || {
                                (
                                    usize::MAX,
                                    ColumnDescriptor::Time(IndexColumnDescriptor::new_null(
                                        *selected_timeline,
                                    )),
                                )
                            },
                            |(idx, view_descr)| (idx, ColumnDescriptor::Time(view_descr.clone())),
                        )
                }

                ColumnSelector::Component(selected_column) => view_contents
                    .iter()
                    .enumerate()
                    .filter_map(|(idx, view_column)| {
                        if let ColumnDescriptor::Component(view_descr) = view_column {
                            Some((idx, view_descr))
                        } else {
                            None
                        }
                    })
                    .find(|(_idx, view_descr)| view_descr.matches(selected_column))
                    .map_or_else(
                        || {
                            (
                                usize::MAX,
                                ColumnDescriptor::Component(ComponentColumnDescriptor {
                                    entity_path: selected_column.entity_path.clone(),
                                    archetype: None,
                                    component: selected_column.component.as_str().into(),
                                    component_type: None,
                                    store_datatype: ArrowDataType::Null,
                                    is_static: false,
                                    is_tombstone: false,
                                    is_semantically_empty: false,
                                }),
                            )
                        },
                        |(idx, view_descr)| (idx, ColumnDescriptor::Component(view_descr.clone())),
                    ),
            })
            .collect_vec()
    }

    fn fetch_view_chunks(
        query: &QueryExpression,
        store: &ChunkStore,
        cache: &QueryCache,
        range_query: &RangeQuery,
        view_contents: &[ColumnDescriptor],
    ) -> (Option<usize>, Vec<Vec<ChunkBundle>>) {
        let mut view_pov_chunks_idx = query.filtered_is_not_null.as_ref().map(|_| usize::MAX);

        let view_chunks = view_contents
            .iter()
            .enumerate()
            .map(|(idx, selected_column)| match selected_column {
                ColumnDescriptor::RowId(_) | ColumnDescriptor::Time(_) => Vec::new(),

                ColumnDescriptor::Component(column) => {
                    let chunks = Self::fetch_chunks(
                        query,
                        store,
                        cache,
                        range_query,
                        &column.entity_path,
                        [column.component],
                    )
                    .unwrap_or_default();

                    if let Some(pov) = query.filtered_is_not_null.as_ref()
                        && column.matches(pov)
                    {
                        view_pov_chunks_idx = Some(idx);
                    }

                    chunks
                }
            })
            .collect();

        (view_pov_chunks_idx, view_chunks)
    }

    /// Returns all potentially relevant clear [`Chunk`]s for each unique entity path in the view contents.
    ///
    /// These chunks take recursive clear semantics into account and are guaranteed to be properly densified.
    /// The component data is stripped out, only the indices are left.
    fn fetch_clear_chunks(
        query: &QueryExpression,
        store: &ChunkStore,
        cache: &QueryCache,
        range_query: &RangeQuery,
        view_contents: &[ColumnDescriptor],
    ) -> IntMap<EntityPath, Vec<Chunk>> {
        /// Returns all the ancestors of an [`EntityPath`].
        ///
        /// Doesn't return `entity_path` itself.
        fn entity_path_ancestors(
            entity_path: &EntityPath,
        ) -> impl Iterator<Item = EntityPath> + use<> {
            std::iter::from_fn({
                let mut entity_path = entity_path.parent();
                move || {
                    let yielded = entity_path.clone()?;
                    entity_path = yielded.parent();
                    Some(yielded)
                }
            })
        }

        /// Given a [`Chunk`] containing a [`ClearIsRecursive`] column, returns a filtered version
        /// of that chunk where only rows with `ClearIsRecursive=true` are left.
        ///
        /// Returns `None` if the chunk either doesn't contain a `ClearIsRecursive` column or if
        /// the end result is an empty chunk.
        fn chunk_filter_recursive_only(chunk: &Chunk) -> Option<Chunk> {
            let list_array = chunk
                .components()
                .get_array(archetypes::Clear::descriptor_is_recursive().component)?;

            let values = list_array
                .values()
                .downcast_array_ref::<ArrowBooleanArray>()?;

            let indices = ArrowPrimitiveArray::from(
                values
                    .iter()
                    .enumerate()
                    .filter_map(|(index, is_recursive)| {
                        // can't fail - we're iterating over a 32-bit container
                        #[expect(clippy::cast_possible_wrap)]
                        (is_recursive == Some(true)).then_some(index as i32)
                    })
                    .collect_vec(),
            );

            let chunk = chunk.taken(&indices);

            (!chunk.is_empty()).then_some(chunk)
        }

        let components = [archetypes::Clear::descriptor_is_recursive().component];

        // All unique entity paths present in the view contents.
        let entity_paths: IntSet<EntityPath> = view_contents
            .iter()
            .filter_map(|col| col.entity_path().cloned())
            .collect();

        entity_paths
            .iter()
            .filter_map(|entity_path| {
                // For the entity itself, any chunk that contains clear data is relevant, recursive or not.
                // Just fetch everything we find.
                let flat_chunks =
                    Self::fetch_chunks(query, store, cache, range_query, entity_path, components)
                        .map(|chunks| chunks.into_iter().map(|cc| cc.chunk).collect_vec())
                        .unwrap_or_default();

                let recursive_chunks =
                    entity_path_ancestors(entity_path).flat_map(|ancestor_path| {
                        Self::fetch_chunks(
                            query,
                            store,
                            cache,
                            range_query,
                            &ancestor_path,
                            components,
                        )
                        .into_iter() // option
                        .flat_map(|chunks| chunks.into_iter().map(|cc| cc.chunk))
                        // NOTE: Ancestors' chunks are only relevant for the rows where `ClearIsRecursive=true`.
                        .filter_map(|chunk| chunk_filter_recursive_only(&chunk))
                    });

                let chunks = flat_chunks
                    .into_iter()
                    .chain(recursive_chunks)
                    // The component data is irrelevant.
                    // We do not expose the actual tombstones to end-users, only their _effect_.
                    .map(|chunk| chunk.components_removed())
                    .collect_vec();

                (!chunks.is_empty()).then(|| (entity_path.clone(), chunks))
            })
            .collect()
    }

    fn fetch_chunks(
        query: &QueryExpression,
        _store: &ChunkStore,
        cache: &QueryCache,
        range_query: &RangeQuery,
        entity_path: &EntityPath,
        components: impl IntoIterator<Item = ComponentIdentifier>,
    ) -> Option<Vec<ChunkBundle>> {
        // NOTE: Keep in mind that the range APIs natively make sure that we will
        // either get a bunch of relevant _static_ chunks, or a bunch of relevant
        // _temporal_ chunks, but never both.
        //
        // TODO(cmc): Going through the cache is very useful in a Viewer context, but
        // not so much in an SDK context. Make it configurable.
        let results = cache.range(range_query, entity_path, components);

        debug_assert!(
            results.components.len() <= 1,
            "cannot possibly get more than one component with this query"
        );

        results
            .components
            .into_iter()
            .next()
            .map(|(_component_descr, chunks)| {
                let filtered_index = query.filtered_index.as_ref();
                chunks
                    .into_iter()
                    .map(|chunk| {
                        // NOTE: Keep in mind that the range APIs would have already taken care
                        // of A) sorting the chunk on the `filtered_index` (and row-id) and
                        // B) densifying it according to the current `component_type`.
                        // Both of these are mandatory requirements for the deduplication logic to
                        // do what we want: keep the latest known value for `component_type` at all
                        // remaining unique index values all while taking row-id ordering semantics
                        // into account.
                        debug_assert!(
                            if let Some(index) = filtered_index {
                                chunk.is_timeline_sorted(index)
                            } else {
                                chunk.is_sorted()
                            },
                            "the query cache should have already taken care of sorting (and densifying!) the chunk",
                        );

                        // TODO(cmc): That'd be more elegant, but right now there is no way to
                        // avoid allocations and copies when using Arrow's `ListArray`.
                        //
                        // let chunk = chunk.deduped_latest_on_index(&query.timeline);

                        ChunkBundle::new(chunk, filtered_index)
                    })
                    .collect_vec()
            })
    }

    /// The query used to instantiate this handle.
    #[inline]
    pub fn query(&self) -> &QueryExpression {
        &self.query
    }

    /// Describes the columns that make up this view.
    ///
    /// See [`QueryExpression::view_contents`].
    #[inline]
    pub fn view_contents(&self) -> &ChunkColumnDescriptors {
        &self.init().view_contents
    }

    /// Describes the columns that make up this selection.
    ///
    /// The extra `usize` is the index in [`Self::view_contents`] that this selection points to.
    ///
    /// See [`QueryExpression::selection`].
    #[inline]
    pub fn selected_contents(&self) -> &[(usize, ColumnDescriptor)] {
        &self.init().selected_contents
    }

    /// All results returned by this handle will strictly follow this Arrow schema.
    ///
    /// Columns that do not yield any data will still be present in the results, filled with null values.
    #[inline]
    pub fn schema(&self) -> &ArrowSchemaRef {
        &self.init().arrow_schema
    }

    /// Advance all internal cursors so that the next row yielded will correspond to `row_idx`.
    ///
    /// Does nothing if `row_idx` is out of bounds.
    ///
    /// ## Performance
    ///
    /// This requires going through every chunk once, and for each chunk running a binary search if
    /// the chunk's time range contains the `index_value`.
    ///
    /// I.e.: it's pretty cheap already.
    #[inline]
    pub fn seek_to_row(&mut self, row_idx: usize) {
        let (state, iter_state) = self.init_iter();

        let Some(index_value) = state.unique_index_values.get(row_idx).copied() else {
            return;
        };

        iter_state.cur_row = row_idx as _;
        Self::seek_to_index_value_impl(state, iter_state, index_value);
    }

    /// Advance all internal cursors so that the next row yielded will correspond to `index_value`.
    ///
    /// If `index_value` isn't present in the dataset, this seeks to the first index value
    /// available past that point, if any.
    ///
    /// ## Performance
    ///
    /// This requires going through every chunk once, and for each chunk running a binary search if
    /// the chunk's time range contains the `index_value`.
    ///
    /// I.e.: it's pretty cheap already.
    #[tracing::instrument(level = "debug", skip_all)]
    fn seek_to_index_value_impl(
        state: &QueryHandleState,
        iter_state: &mut IterState,
        index_value: IndexValue,
    ) {
        re_tracing::profile_function!();

        if index_value.is_static() {
            for chunks in &mut iter_state.view_chunks {
                for cc in chunks {
                    cc.cursor = 0;
                    cc.exhausted = false;
                }
            }
            return;
        }

        for (state_chunks, iter_chunks) in state
            .view_chunks
            .iter()
            .zip(iter_state.view_chunks.iter_mut())
        {
            for (bundle, cc) in state_chunks.iter().zip(iter_chunks.iter_mut()) {
                // NOTE: The chunk has been densified already: its global time range is the same as
                // the time range for the specific component of interest.
                let Some(time_column) = bundle.chunk.timelines().get(&state.filtered_index) else {
                    continue;
                };

                let time_range = time_column.time_range();

                let new_cursor = if index_value < time_range.min() {
                    0
                } else if index_value > time_range.max() {
                    bundle.chunk.num_rows() as u64 /* yes, one past the end -- not a mistake */
                } else {
                    time_column
                        .times_raw()
                        .partition_point(|&time| time < index_value.as_i64())
                        as u64
                };

                cc.cursor = new_cursor;
                cc.exhausted = false;
            }
        }
    }

    /// How many rows of data will be returned?
    ///
    /// The number of rows depends and only depends on the _view contents_.
    /// The _selected contents_ has no influence on this value.
    pub fn num_rows(&self) -> u64 {
        self.init().unique_index_values.len() as _
    }

    /// Returns the row index of the last row whose index value is <= the given time,
    /// or `None` if no such row exists.
    pub fn row_index_at_or_before_time(&self, time: TimeInt) -> Option<u64> {
        let state = self.init();
        let idx = state.unique_index_values.partition_point(|t| *t <= time);
        if idx == 0 {
            None
        } else {
            Some((idx - 1) as u64)
        }
    }

    /// Returns the next row's worth of data.
    ///
    /// The returned vector of Arrow arrays strictly follows the schema specified by [`Self::schema`].
    /// Columns that do not yield any data will still be present in the results, filled with null values.
    ///
    /// Each cell in the result corresponds to the latest _locally_ known value at that particular point in
    /// the index, for each respective `ColumnDescriptor`.
    /// See [`QueryExpression::sparse_fill_strategy`] to go beyond local resolution.
    ///
    /// Example:
    /// ```ignore
    /// while let Some(row) = query_handle.next_row() {
    ///     // …
    /// }
    /// ```
    ///
    /// ## Pagination
    ///
    /// Use [`Self::seek_to_row`]:
    /// ```ignore
    /// query_handle.seek_to_row(42);
    /// for row in query_handle.into_iter().take(len) {
    ///     // …
    /// }
    /// ```
    #[inline]
    pub fn next_row(&mut self) -> Option<Vec<ArrayRef>> {
        // Trigger lazy state init through the immutable `&self` path before split-borrowing.
        let _ = self.init();
        let Self {
            engine,
            query,
            state,
            iter_state,
        } = self;
        let state = state.get().expect("state was just initialized by init()");
        let iter_state = iter_state.get_or_insert_with(|| IterState::new(state));
        engine.with(|store, cache| Self::_next_row(query, state, iter_state, store, cache))
    }

    /// Asynchronously returns the next row's worth of data.
    ///
    /// The returned vector of Arrow arrays strictly follows the schema specified by [`Self::schema`].
    /// Columns that do not yield any data will still be present in the results, filled with null values.
    ///
    /// Each cell in the result corresponds to the latest _locally_ known value at that particular point in
    /// the index, for each respective `ColumnDescriptor`.
    /// See [`QueryExpression::sparse_fill_strategy`] to go beyond local resolution.
    ///
    /// Example:
    /// ```ignore
    /// while let Some(row) = query_handle.next_row_async().await {
    ///     // …
    /// }
    /// ```
    #[cfg(not(target_arch = "wasm32"))]
    pub fn next_row_async(
        &mut self,
    ) -> impl std::future::Future<Output = Option<Vec<ArrayRef>>> + use<E>
    where
        E: 'static + Send + Clone,
    {
        let Self {
            engine,
            query,
            state,
            iter_state,
        } = self;
        let res: Option<Option<_>> = engine.try_with(|store, cache| {
            let st = state.get_or_init(|| Self::init_(query, store, cache));
            let it = iter_state.get_or_insert_with(|| IterState::new(st));
            Self::_next_row(query, st, it, store, cache)
        });

        let engine = engine.clone();
        std::future::poll_fn(move |cx| {
            if let Some(row) = &res {
                std::task::Poll::Ready(row.clone())
            } else {
                // The lock is already held by a writer, we have to yield control back to the async
                // runtime, for now.
                // Before we do so, we need to schedule a callback that will be in charge of waking up
                // the async task once we can possibly make progress once again.

                // Commenting out this code should make the `async_barebones` test deadlock.
                rayon::spawn({
                    let engine = engine.clone();
                    let waker = cx.waker().clone();
                    move || {
                        engine.with(|_store, _cache| {
                            // This is of course optimistic -- we might end up right back here on
                            // next tick. That's fine.
                            waker.wake();
                        });
                    }
                });

                std::task::Poll::Pending
            }
        })
    }

    fn _next_row<'state>(
        query: &QueryExpression,
        state: &'state QueryHandleState,
        iter_state: &mut IterState,
        _store: &ChunkStore,
        cache: &QueryCache,
    ) -> Option<Vec<ArrowArrayRef>> {
        // re_tracing::profile_function!(); // too many and short-lived

        let mut scratch: Vec<Option<StreamingJoinState<'state>>> =
            Vec::with_capacity(state.view_chunks.len());
        let resolved = Self::_resolve_one_row(query, state, iter_state, cache, &mut scratch)?;

        // NOTE: Non-component entries have no data to slice, hence the optional layer.
        //
        // TODO(cmc): no point in slicing arrays that are not selected.
        let view_sliced_arrays: Vec<Option<_>> = scratch
            .iter()
            .enumerate()
            .map(|(view_idx, streaming_state)| {
                // NOTE: Reminder: the only reason the streaming state could be `None` here is
                // because this column does not have data for the current index value (i.e. `null`).
                let streaming_state = streaming_state.as_ref()?;
                let list_array = match streaming_state {
                    StreamingJoinState::StreamingJoinState(s) => {
                        debug_assert!(
                            s.chunk.components().iter().count() <= 1,
                            "cannot possibly get more than one component with this query"
                        );

                        s.chunk
                            .components()
                            .list_arrays()
                            .next()
                            .map(|list_array| list_array.slice(s.cursor as usize, 1))
                    }

                    StreamingJoinState::Retrofilled(unit) => {
                        let component = state
                            .view_contents
                            .get_index_or_component(view_idx)
                            .and_then(|col| {
                                if let ColumnDescriptor::Component(descr) = col {
                                    if let Some(component_type) = descr.component_type {
                                        component_type.sanity_check();
                                    }
                                    Some(descr.component)
                                } else {
                                    None
                                }
                            })?;
                        unit.components().get_array(component).cloned()
                    }
                };

                debug_assert!(
                    list_array.is_some(),
                    "This must exist or the chunk wouldn't have been sliced/retrofilled to start with."
                );

                // NOTE: This cannot possibly return None, see assert above.
                list_array
            })
            .collect();

        // TODO(cmc): It would likely be worth it to allocate all these possible
        // null-arrays ahead of time, and just return a pointer to those in the failure
        // case here.
        let selected_arrays = state
            .selected_contents
            .iter()
            .map(|(view_idx, column)| match column {
                ColumnDescriptor::RowId(_) => state
                    .view_chunks
                    .first()
                    .and_then(|vec| vec.first()) // TODO(#9922): verify that using the row:ids from the first chunk always makes sense
                    .zip(iter_state.view_chunks.first().and_then(|vec| vec.first()))
                    .map(|(cc, cs)| as_array_ref(cc.chunk.row_ids_array().slice(cs.cursor as _, 1)))
                    .unwrap_or_else(|| arrow::array::new_null_array(&RowId::arrow_datatype(), 1)),

                ColumnDescriptor::Time(descr) => resolved.get(descr.timeline().name()).map_or_else(
                    || arrow::array::new_null_array(&column.arrow_datatype(), 1),
                    |(_time, time_sliced)| {
                        descr.timeline().typ().make_arrow_array(time_sliced.clone())
                    },
                ),

                ColumnDescriptor::Component(_descr) => view_sliced_arrays
                    .get(*view_idx)
                    .cloned()
                    .flatten()
                    .map(into_arrow_ref)
                    .unwrap_or_else(|| arrow::array::new_null_array(&column.arrow_datatype(), 1)),
            })
            .collect_vec();

        debug_assert_eq!(state.arrow_schema.fields.len(), selected_arrays.len());

        Some(selected_arrays)
    }

    /// Resolve the streaming-join state for a single row.
    ///
    /// Returns `None` once the query is exhausted. On success, `view_streaming_state` holds the
    /// per-view-column resolved state for this row (component chunks, retrofills, statics) and
    /// the returned [`ResolvedRow`] holds the max value seen on each timeline.
    fn _resolve_one_row<'state>(
        query: &QueryExpression,
        state: &'state QueryHandleState,
        iter_state: &mut IterState,
        cache: &QueryCache,
        view_streaming_state: &mut Vec<Option<StreamingJoinState<'state>>>,
    ) -> Option<ResolvedRow> {
        let row_idx = iter_state.cur_row;
        iter_state.cur_row = row_idx + 1;
        let cur_index_value = state.unique_index_values.get(row_idx as usize)?;

        // First, we need to find, among all the chunks available for the current view contents,
        // what is their index value for the current row?
        //
        // NOTE: Non-component columns don't have a streaming state, hence the optional layer.
        view_streaming_state.clear();
        view_streaming_state.resize_with(state.view_chunks.len(), || None);
        let cur_index_value_i64 = cur_index_value.as_i64();
        for (view_column_idx, (view_chunks, iter_chunks)) in state
            .view_chunks
            .iter()
            .zip(iter_state.view_chunks.iter_mut())
            .enumerate()
        {
            let mut entry: Option<StreamingJoinStateEntry<'state>> = None;

            'overlaps: for (cc, cs) in view_chunks.iter().zip(iter_chunks.iter_mut()) {
                // H1: skip chunks that already finished a prior row.
                if cs.exhausted {
                    continue 'overlaps;
                }

                // H3: chunks are sorted by `time_min` ascending — once we see a chunk
                // whose `time_min` is past `cur_index_value`, no later chunk can match
                // either.
                if cur_index_value_i64 < cc.time_min {
                    break 'overlaps;
                }

                // H2: chunks whose `time_max` is below `cur_index_value` are exhausted
                // for the rest of the iteration. Mark and skip.
                if cur_index_value_i64 > cc.time_max {
                    cs.exhausted = true;
                    continue 'overlaps;
                }

                // NOTE: Too soon to increment the cursor, we cannot know yet which chunks will or
                // will not be part of the current row.
                let mut cur_cursor_value = cs.cursor;

                let cur_index_times_empty: &[i64] = &[];
                let cur_index_times = cc
                    .chunk
                    .timelines()
                    .get(&state.filtered_index)
                    .map_or(cur_index_times_empty, |time_column| time_column.times_raw());
                let cur_index_row_ids = cc.chunk.row_ids_slice();

                let (index_value, cur_row_id) = 'walk: loop {
                    let (Some(mut index_value), Some(mut cur_row_id)) = (
                        cur_index_times
                            .get(cur_cursor_value as usize)
                            .copied()
                            .map(TimeInt::new_temporal),
                        cur_index_row_ids.get(cur_cursor_value as usize).copied(),
                    ) else {
                        // Cursor is past the last row of this chunk — exhausted forever.
                        cs.exhausted = true;
                        continue 'overlaps;
                    };

                    if index_value == *cur_index_value {
                        // TODO(cmc): Because of Arrow's `ListArray` limitations, we inline the
                        // "deduped_latest_on_index" logic here directly, which prevents a lot of
                        // unnecessary allocations and copies.
                        while let (Some(next_index_value), Some(next_row_id)) = (
                            cur_index_times
                                .get(cur_cursor_value as usize + 1)
                                .copied()
                                .map(TimeInt::new_temporal),
                            cur_index_row_ids
                                .get(cur_cursor_value as usize + 1)
                                .copied(),
                        ) {
                            if next_index_value == *cur_index_value {
                                index_value = next_index_value;
                                cur_row_id = next_row_id;
                                cur_cursor_value = cs.cursor + 1;
                                cs.cursor = cur_cursor_value;
                            } else {
                                break;
                            }
                        }

                        break 'walk (index_value, cur_row_id);
                    }

                    if index_value > *cur_index_value {
                        continue 'overlaps;
                    }

                    cur_cursor_value = cs.cursor + 1;
                    cs.cursor = cur_cursor_value;
                };

                debug_assert_eq!(index_value, *cur_index_value);

                if let Some(existing) = entry.as_mut() {
                    if cur_row_id > existing.row_id {
                        existing.chunk = &cc.chunk;
                        existing.cursor = cur_cursor_value;
                        existing.row_id = cur_row_id;
                    }
                } else {
                    entry = Some(StreamingJoinStateEntry {
                        chunk: &cc.chunk,
                        cursor: cur_cursor_value,
                        row_id: cur_row_id,
                    });
                }
            }

            view_streaming_state[view_column_idx] =
                entry.map(StreamingJoinState::StreamingJoinState);
        }

        // Static always wins, no matter what.
        for (selected_idx, static_state) in state.selected_static_values.iter().enumerate() {
            if let Some(unit) = static_state.clone() {
                let Some(view_idx) = state
                    .selected_contents
                    .get(selected_idx)
                    .map(|(view_idx, _)| *view_idx)
                else {
                    debug_panic!("selected_idx out of bounds");
                    continue;
                };

                let Some(streaming_state) = view_streaming_state.get_mut(view_idx) else {
                    debug_panic!("view_idx out of bounds");
                    continue;
                };

                *streaming_state = Some(StreamingJoinState::Retrofilled(unit));
            }
        }

        match query.sparse_fill_strategy {
            SparseFillStrategy::None => {}

            SparseFillStrategy::LatestAtGlobal => {
                // Everything that yielded `null` for the current iteration.
                let null_streaming_states = view_streaming_state
                    .iter_mut()
                    .enumerate()
                    .filter(|(_view_idx, streaming_state)| streaming_state.is_none());

                for (view_idx, streaming_state) in null_streaming_states {
                    let Some(ColumnDescriptor::Component(descr)) =
                        state.view_contents.get_index_or_component(view_idx)
                    else {
                        continue;
                    };

                    // NOTE: While it would be very tempting to resolve the latest-at state
                    // of the entire view contents at `filtered_index_range.start - 1` once
                    // during `QueryHandle` initialization, and then bootstrap off of that, that
                    // would effectively close the door to efficient pagination forever, since
                    // we'd have to iterate over all the pages to compute the right latest-at
                    // value at t+n (i.e. no more random access).
                    // Therefore, it is better to simply do this the "dumb" way.
                    //
                    // TODO(cmc): Still, as always, this can be made faster and smarter at
                    // the cost of some extra complexity (e.g. caching the result across
                    // consecutive nulls etc). Later.

                    let query =
                        re_chunk::LatestAtQuery::new(state.filtered_index, *cur_index_value);

                    let results =
                        cache.latest_at(&query, &descr.entity_path.clone(), [descr.component]);

                    *streaming_state = results
                        .components
                        .into_values()
                        .next()
                        .map(|unit| StreamingJoinState::Retrofilled(unit.clone()));
                }
            }
        }

        // We are stitching a bunch of unrelated cells together in order to create the final row
        // that is being returned.
        //
        // For this reason, we can only guarantee that the index being explicitly queried for
        // (`QueryExpression::filtered_index`) will match for all these cells.
        //
        // When it comes to other indices that the caller might have asked for, it is possible that
        // these different cells won't share the same values (e.g. two cells were found at
        // `log_time=100`, but one of them has `frame=3` and the other `frame=5`, for whatever
        // reason).
        // In order to deal with this, we keep track of the maximum value for every possible index
        // within the returned set of cells, and return that.
        //
        // TODO(cmc): In the future, it would be nice to make that either configurable, e.g.:
        // * return the minimum value instead of the max
        // * return the exact value for each component (that would be a _lot_ of columns!)
        // * etc
        let mut max_value_per_index: IntMap<TimelineName, (TimeInt, ArrowScalarBuffer<i64>)> =
            IntMap::default();
        view_streaming_state
            .iter()
            .flatten()
            .flat_map(|streaming_state| {
                match streaming_state {
                    StreamingJoinState::StreamingJoinState(s) => s.chunk.timelines(),
                    StreamingJoinState::Retrofilled(unit) => unit.timelines(),
                }
                .values()
                // NOTE: Cannot fail, just want to stay away from unwraps.
                .filter_map(move |time_column| {
                    let cursor = match streaming_state {
                        StreamingJoinState::StreamingJoinState(s) => s.cursor as usize,
                        StreamingJoinState::Retrofilled(_) => 0,
                    };
                    time_column
                        .times_raw()
                        .get(cursor)
                        .copied()
                        .map(TimeInt::new_temporal)
                        .map(|time| {
                            (
                                *time_column.timeline(),
                                (time, time_column.times_buffer().slice(cursor, 1)),
                            )
                        })
                })
            })
            .for_each(|(timeline, (time, time_sliced))| {
                max_value_per_index
                    .entry(*timeline.name())
                    .and_modify(|(max_time, max_time_sliced)| {
                        if time > *max_time {
                            *max_time = time;
                            *max_time_sliced = time_sliced.clone();
                        }
                    })
                    .or_insert((time, time_sliced));
            });

        if !cur_index_value.is_static() {
            // The current index value (if temporal) should be the one returned for the
            // queried index, no matter what.
            max_value_per_index.insert(
                state.filtered_index,
                (
                    *cur_index_value,
                    ArrowScalarBuffer::from(vec![cur_index_value.as_i64()]),
                ),
            );
        }

        Some(max_value_per_index)
    }

    /// Append up to `max_rows` rows of data into freshly allocated per-column arrays.
    ///
    /// Throughput-oriented sibling of [`Self::next_row`]: shares the streaming-join machinery but
    /// amortizes per-row allocation by batching `MutableArrayData` extends and only finalizing
    /// to `ArrayRef` once per call.
    ///
    /// The returned [`NextNRowsOutput::columns`] strictly follows the schema specified by
    /// [`Self::schema`], with `num_rows == 0` signalling exhaustion.
    ///
    /// `max_bytes` caps the estimated output-buffer footprint of the batch (sum of
    /// per-row source-array bytes, computed from `ArrayData::get_array_memory_size /
    /// len`). Pass `usize::MAX` to disable the byte cap. The first row is always
    /// admitted regardless of the cap, so a single wide row can exceed `max_bytes`.
    #[inline]
    pub fn next_n_rows(&mut self, max_rows: usize, max_bytes: usize) -> NextNRowsOutput {
        let _ = self.init();
        let Self {
            engine,
            query,
            state,
            iter_state,
        } = self;
        let state = state.get().expect("state was just initialized by init()");
        let iter_state = iter_state.get_or_insert_with(|| IterState::new(state));
        engine.with(|store, cache| {
            Self::_next_n_rows(query, state, iter_state, store, cache, max_rows, max_bytes)
        })
    }

    /// Asynchronous sibling of [`Self::next_n_rows`].
    #[cfg(not(target_arch = "wasm32"))]
    pub fn next_n_rows_async(
        &mut self,
        max_rows: usize,
        max_bytes: usize,
    ) -> impl std::future::Future<Output = NextNRowsOutput> + use<'_, E>
    where
        E: 'static + Send + Clone,
    {
        let Self {
            engine,
            query,
            state,
            iter_state,
        } = self;

        // Retry on every poll: if `try_with` initially fails because a writer
        // holds the lock, the rayon-spawned `engine.with(..)` re-acquires the
        // lock and wakes us, but only a fresh `try_with` call here can actually
        // make progress. Capturing the result once at function entry would let
        // the future spin forever on a permanent `None`.
        //
        // State and iter-state are lazily initialized inside the `try_with` closure
        // so we never block on the engine lock — the future simply yields and is
        // re-polled when the writer releases the lock.
        std::future::poll_fn(move |cx| {
            let res = engine.try_with(|store, cache| {
                let st = state.get_or_init(|| Self::init_(query, store, cache));
                let it = iter_state.get_or_insert_with(|| IterState::new(st));
                Self::_next_n_rows(query, st, it, store, cache, max_rows, max_bytes)
            });

            if let Some(out) = res {
                std::task::Poll::Ready(out)
            } else {
                rayon::spawn({
                    let engine = engine.clone();
                    let waker = cx.waker().clone();
                    move || {
                        engine.with(|_store, _cache| {
                            waker.wake();
                        });
                    }
                });

                std::task::Poll::Pending
            }
        })
    }

    #[tracing::instrument(level = "debug", skip_all, fields(max_rows, max_bytes))]
    fn _next_n_rows(
        query: &QueryExpression,
        state: &QueryHandleState,
        iter_state: &mut IterState,
        _store: &ChunkStore,
        cache: &QueryCache,
        max_rows: usize,
        max_bytes: usize,
    ) -> NextNRowsOutput {
        re_tracing::profile_function!();

        let n_selected = state.selected_contents.len();

        if max_rows == 0 {
            return NextNRowsOutput {
                columns: Vec::new(),
                num_rows: 0,
            };
        }

        // Clamp the up-front capacity hint: callers can legitimately pass a very
        // large `max_rows` (e.g. `usize::MAX` when only `max_bytes` is meant to
        // cap the batch) and `Vec::with_capacity(usize::MAX)` aborts with
        // "capacity overflow". 8192 covers every realistic batch size while
        // keeping the pre-allocation small; the vectors grow as needed.
        let cap_hint = max_rows.min(8192);

        let mut emitters: Vec<SelectedEmitter> = state
            .selected_contents
            .iter()
            .map(|(_view_idx, col)| match col {
                ColumnDescriptor::Component(_) | ColumnDescriptor::RowId(_) => {
                    SelectedEmitter::Source {
                        sources: Vec::new(),
                        source_ids: Vec::new(),
                        source_bytes_per_row: Vec::new(),
                        extends: Vec::with_capacity(cap_hint),
                    }
                }
                ColumnDescriptor::Time(_) => SelectedEmitter::Time {
                    values: Vec::with_capacity(cap_hint),
                    valid: Vec::with_capacity(cap_hint),
                },
            })
            .collect();

        let mut scratch: Vec<Option<StreamingJoinState<'_>>> =
            Vec::with_capacity(state.view_chunks.len());

        let mut num_rows = 0usize;
        let mut total_bytes = 0usize;
        loop {
            if num_rows >= max_rows {
                break;
            }
            // Always admit the first row so an empty batch is impossible while the
            // query has data (callers rely on `num_rows == 0` meaning exhausted).
            if num_rows > 0 && total_bytes >= max_bytes {
                break;
            }

            let Some(resolved) =
                Self::_resolve_one_row(query, state, iter_state, cache, &mut scratch)
            else {
                break;
            };

            for (selected_idx, (view_idx, column)) in state.selected_contents.iter().enumerate() {
                match column {
                    ColumnDescriptor::RowId(_) => {
                        let SelectedEmitter::Source {
                            sources,
                            source_ids,
                            source_bytes_per_row,
                            extends,
                        } = &mut emitters[selected_idx]
                        else {
                            debug_panic!("Source emitter expected for RowId column");
                            continue;
                        };

                        if let Some((cc, cs)) = state
                            .view_chunks
                            .first()
                            .and_then(|v| v.first())
                            .zip(iter_state.view_chunks.first().and_then(|v| v.first()))
                        {
                            // TODO(#9922): verify that using the row:ids from the first chunk
                            // always makes sense.
                            let id = std::ptr::from_ref::<Chunk>(&cc.chunk);
                            let pos = cs.cursor as usize;
                            let source_idx = SelectedEmitter::ensure_source(
                                sources,
                                source_ids,
                                source_bytes_per_row,
                                id,
                                || cc.chunk.row_ids_array().to_data(),
                            );
                            SelectedEmitter::push_run(
                                extends,
                                source_idx,
                                Span::from_start_len(pos, 1),
                            );
                            total_bytes =
                                total_bytes.saturating_add(source_bytes_per_row[source_idx]);
                        } else {
                            SelectedEmitter::push_nulls(extends, 1);
                        }
                    }

                    ColumnDescriptor::Time(descr) => {
                        let SelectedEmitter::Time { values, valid } = &mut emitters[selected_idx]
                        else {
                            debug_panic!("Time emitter expected for Time column");
                            continue;
                        };

                        if let Some((time, _)) = resolved.get(descr.timeline().name()) {
                            values.push(time.as_i64());
                            valid.push(true);
                        } else {
                            values.push(0);
                            valid.push(false);
                        }
                        total_bytes = total_bytes.saturating_add(std::mem::size_of::<i64>());
                    }

                    ColumnDescriptor::Component(_) => {
                        let SelectedEmitter::Source {
                            sources,
                            source_ids,
                            source_bytes_per_row,
                            extends,
                        } = &mut emitters[selected_idx]
                        else {
                            debug_panic!("Source emitter expected for Component column");
                            continue;
                        };

                        let streaming_state = scratch.get(*view_idx).and_then(|s| s.as_ref());
                        match streaming_state {
                            Some(StreamingJoinState::StreamingJoinState(s)) => {
                                let list_array_data = s
                                    .chunk
                                    .components()
                                    .list_arrays()
                                    .next()
                                    .map(|la| la.to_data());
                                if let Some(data) = list_array_data {
                                    let id = std::ptr::from_ref::<Chunk>(s.chunk);
                                    let source_idx = SelectedEmitter::ensure_source(
                                        sources,
                                        source_ids,
                                        source_bytes_per_row,
                                        id,
                                        || data,
                                    );
                                    SelectedEmitter::push_run(
                                        extends,
                                        source_idx,
                                        Span::from_start_len(s.cursor as usize, 1),
                                    );
                                    total_bytes = total_bytes
                                        .saturating_add(source_bytes_per_row[source_idx]);
                                } else {
                                    SelectedEmitter::push_nulls(extends, 1);
                                }
                            }
                            Some(StreamingJoinState::Retrofilled(unit)) => {
                                let component = state
                                    .view_contents
                                    .get_index_or_component(*view_idx)
                                    .and_then(|col| {
                                        if let ColumnDescriptor::Component(descr) = col {
                                            if let Some(component_type) = descr.component_type {
                                                component_type.sanity_check();
                                            }
                                            Some(descr.component)
                                        } else {
                                            None
                                        }
                                    });
                                let component_data = component.and_then(|c| {
                                    unit.components()
                                        .get_array(c)
                                        .cloned()
                                        .map(|arr| arr.to_data())
                                });
                                if let Some(data) = component_data {
                                    // UnitChunkShared derefs to Chunk; underlying address is
                                    // Arc-stable.
                                    let id = std::ptr::from_ref::<Chunk>(&**unit);
                                    let source_idx = SelectedEmitter::ensure_source(
                                        sources,
                                        source_ids,
                                        source_bytes_per_row,
                                        id,
                                        || data,
                                    );
                                    SelectedEmitter::push_run(
                                        extends,
                                        source_idx,
                                        Span::from_start_len(0, 1),
                                    );
                                    total_bytes = total_bytes
                                        .saturating_add(source_bytes_per_row[source_idx]);
                                } else {
                                    SelectedEmitter::push_nulls(extends, 1);
                                }
                            }
                            None => SelectedEmitter::push_nulls(extends, 1),
                        }
                    }
                }
            }

            num_rows += 1;
        }

        if num_rows == 0 {
            return NextNRowsOutput {
                columns: Vec::new(),
                num_rows: 0,
            };
        }

        // Finalize each output column.
        let mut columns: Vec<ArrowArrayRef> = Vec::with_capacity(n_selected);
        for (selected_idx, emitter) in emitters.into_iter().enumerate() {
            let (_, column) = &state.selected_contents[selected_idx];
            let datatype = state.arrow_schema.field(selected_idx).data_type();
            match emitter {
                SelectedEmitter::Source {
                    sources,
                    extends,
                    source_ids: _,
                    source_bytes_per_row: _,
                } => {
                    if sources.is_empty() {
                        columns.push(arrow::array::new_null_array(datatype, num_rows));
                        continue;
                    }
                    let src_refs: Vec<&ArrayData> = sources.iter().collect();
                    let mut mutable = MutableArrayData::new(src_refs, true, num_rows);
                    for ext in &extends {
                        match ext {
                            ColumnExtend::Range { source_idx, rows } => {
                                mutable.extend(*source_idx, rows.start, rows.end());
                            }
                            ColumnExtend::Nulls { len } => mutable.extend_nulls(*len),
                        }
                    }
                    columns.push(make_array(mutable.freeze()));
                }
                SelectedEmitter::Time { values, valid } => {
                    // The schema field's datatype is the source of truth. An
                    // `IndexColumnDescriptor::new_null` produces `datatype = Null`
                    // even though `descr.timeline().typ()` returns the placeholder
                    // `Sequence` (Int64); mirror `_next_row`, which falls back to
                    // `new_null_array(&column.arrow_datatype(), 1)` and therefore
                    // emits a `Null` array whenever the schema says so.
                    if matches!(datatype, ArrowDataType::Null) {
                        columns.push(arrow::array::new_null_array(datatype, num_rows));
                        continue;
                    }
                    let ColumnDescriptor::Time(descr) = column else {
                        debug_panic!("Time emitter on non-Time column");
                        columns.push(arrow::array::new_null_array(datatype, num_rows));
                        continue;
                    };
                    let nulls = if valid.iter().all(|v| *v) {
                        None
                    } else {
                        Some(valid.iter().copied().collect::<NullBuffer>())
                    };
                    columns.push(
                        descr
                            .timeline()
                            .typ()
                            .make_arrow_array_with_nulls(ArrowScalarBuffer::from(values), nulls),
                    );
                }
            }
        }

        debug_assert_eq!(columns.len(), state.arrow_schema.fields.len());

        NextNRowsOutput { columns, num_rows }
    }

    /// Calls [`Self::next_row`] and wraps the result in a [`ArrowRecordBatch`].
    ///
    /// Only use this if you absolutely need a [`ArrowRecordBatch`] as this adds a
    /// some overhead for schema validation.
    ///
    /// See [`Self::next_row`] for more information.
    #[inline]
    pub fn next_row_batch(&mut self) -> Option<ArrowRecordBatch> {
        let row = self.next_row()?;
        match ArrowRecordBatch::try_new_with_options(
            self.schema().clone(),
            row,
            // Explicitly setting row-count to one means it works even when there are no columns (e.g. due to heavy filtering)
            &RecordBatchOptions::new().with_row_count(Some(1)),
        ) {
            Ok(batch) => Some(batch),
            Err(err) => {
                if cfg!(debug_assertions) {
                    panic!("Failed to create record batch: {err}");
                } else {
                    re_log::error_once!("Failed to create record batch: {err}");
                    None
                }
            }
        }
    }

    #[inline]
    #[cfg(not(target_arch = "wasm32"))]
    pub async fn next_row_batch_async(&mut self) -> Option<ArrowRecordBatch>
    where
        E: 'static + Send + Clone,
    {
        let row = self.next_row_async().await?;
        let row_count = row.first().map(|a| a.len()).unwrap_or(0);

        // If we managed to get a row, then the state must be initialized already.
        #[expect(clippy::unwrap_used)]
        let schema = self.state.get().unwrap().arrow_schema.clone();

        ArrowRecordBatch::try_new_with_options(
            schema,
            row,
            &RecordBatchOptions::default().with_row_count(Some(row_count)),
        )
        .ok()
    }
}

impl<E: StorageEngineLike> QueryHandle<E> {
    /// Returns an iterator backed by [`Self::next_row`].
    pub fn iter(&mut self) -> impl Iterator<Item = Vec<ArrowArrayRef>> + '_ {
        std::iter::from_fn(move || self.next_row())
    }

    /// Returns an iterator backed by [`Self::next_row`].
    #[expect(clippy::should_implement_trait)] // we need an anonymous closure, this won't work
    pub fn into_iter(mut self) -> impl Iterator<Item = Vec<ArrowArrayRef>> {
        std::iter::from_fn(move || self.next_row())
    }

    /// Returns an iterator backed by [`Self::next_row_batch`].
    pub fn batch_iter(&mut self) -> impl Iterator<Item = ArrowRecordBatch> + '_ {
        std::iter::from_fn(move || self.next_row_batch())
    }

    /// Returns an iterator backed by [`Self::next_row_batch`].
    pub fn into_batch_iter(mut self) -> impl Iterator<Item = ArrowRecordBatch> {
        std::iter::from_fn(move || self.next_row_batch())
    }
}

// ---

#[cfg(test)]
#[expect(clippy::iter_on_single_items)]
mod tests {
    use std::sync::Arc;

    use arrow::array::{StringArray, UInt32Array};
    use arrow::compute::concat_batches;
    use insta::assert_snapshot;
    use re_arrow_util::format_record_batch;
    use re_chunk::{Chunk, ChunkId, ComponentIdentifier, RowId, TimePoint};
    use re_chunk_store::{
        AbsoluteTimeRange, ChunkStore, ChunkStoreConfig, ChunkStoreHandle, QueryExpression, TimeInt,
    };
    use re_log_types::example_components::{MyColor, MyLabel, MyPoint, MyPoints};
    use re_log_types::{EntityPath, Timeline, build_frame_nr, build_log_time};
    use re_query::StorageEngine;
    use re_sdk_types::{AnyValues, AsComponents as _, ComponentDescriptor};
    use re_sorbet::ComponentColumnSelector;
    use re_types_core::components;

    use super::*;
    use crate::{QueryCache, QueryEngine};

    /// Implement `Display` for `ArrowRecordBatch`
    struct DisplayRB(ArrowRecordBatch);

    impl std::fmt::Display for DisplayRB {
        #[inline]
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let width = 200;
            re_arrow_util::format_record_batch_with_width(&self.0, Some(width), f.sign_minus())
                .fmt(f)
        }
    }

    // NOTE: The best way to understand what these tests are doing is to run them in verbose mode,
    // e.g. `cargo t -p re_dataframe -- --show-output barebones`.
    // Each test will print the state of the store, the query being run, and the results that were
    // returned in the usual human-friendly format.
    // From there it is generally straightforward to infer what's going on.

    // TODO(cmc): at least one basic test for every feature in `QueryExpression`.
    // In no particular order:
    // * [x] filtered_index
    // * [x] filtered_index_range
    // * [x] filtered_index_values
    // * [x] view_contents
    // * [x] selection
    // * [x] filtered_is_not_null
    // * [x] sparse_fill_strategy
    // * [x] using_index_values
    //
    // In addition to those, some much needed extras:
    // * [x] num_rows
    // * [x] clears
    // * [ ] timelines returned with selection=none
    // * [x] pagination

    // TODO(cmc): At some point I'd like to stress multi-entity queries too, but that feels less
    // urgent considering how things are implemented (each entity lives in its own index, so it's
    // really just more of the same).

    /// All features disabled.
    #[test]
    fn barebones() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let filtered_index = Some(TimelineName::new("frame_nr"));

        // static
        {
            let query = QueryExpression::default();
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        // temporal
        {
            let query = QueryExpression {
                filtered_index,
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        Ok(())
    }

    #[test]
    fn sparse_fill_strategy_latestatglobal() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let filtered_index = Some(TimelineName::new("frame_nr"));
        let query = QueryExpression {
            filtered_index,
            sparse_fill_strategy: SparseFillStrategy::LatestAtGlobal,
            ..Default::default()
        };
        eprintln!("{query:#?}:");

        let mut query_handle = query_engine.query(query.clone());
        assert_eq!(
            query_engine.query(query.clone()).into_iter().count() as u64,
            query_handle.num_rows()
        );
        let schema = query_handle.schema().clone();
        let batches = query_handle.batch_iter().collect_vec();
        let dataframe = concat_batches(&schema, &batches)?;
        eprintln!("{}", format_record_batch(&dataframe.clone()));

        assert_snapshot!(DisplayRB(dataframe));

        Ok(())
    }

    #[test]
    fn filtered_index_range() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let filtered_index = Some(TimelineName::new("frame_nr"));
        let query = QueryExpression {
            filtered_index,
            filtered_index_range: Some(AbsoluteTimeRange::new(30, 60)),
            ..Default::default()
        };
        eprintln!("{query:#?}:");

        let mut query_handle = query_engine.query(query.clone());
        assert_eq!(
            query_engine.query(query.clone()).into_iter().count() as u64,
            query_handle.num_rows()
        );
        let schema = query_handle.schema().clone();
        let batches = query_handle.batch_iter().collect_vec();
        let dataframe = concat_batches(&schema, &batches)?;
        eprintln!("{}", format_record_batch(&dataframe.clone()));

        assert_snapshot!(DisplayRB(dataframe));

        Ok(())
    }

    #[test]
    fn filtered_index_values() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let filtered_index = Some(TimelineName::new("frame_nr"));
        let query = QueryExpression {
            filtered_index,
            filtered_index_values: Some(
                [0, 30, 60, 90]
                    .into_iter()
                    .map(TimeInt::new_temporal)
                    .chain(std::iter::once(TimeInt::STATIC))
                    .collect(),
            ),
            ..Default::default()
        };
        eprintln!("{query:#?}:");

        let mut query_handle = query_engine.query(query.clone());
        assert_eq!(
            query_engine.query(query.clone()).into_iter().count() as u64,
            query_handle.num_rows()
        );
        let schema = query_handle.schema().clone();
        let batches = query_handle.batch_iter().collect_vec();
        let dataframe = concat_batches(&schema, &batches)?;
        eprintln!("{}", format_record_batch(&dataframe.clone()));

        assert_snapshot!(DisplayRB(dataframe));

        Ok(())
    }

    #[test]
    fn using_index_values() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let filtered_index = Some(TimelineName::new("frame_nr"));

        // vanilla
        {
            let query = QueryExpression {
                filtered_index,
                using_index_values: Some(
                    [0, 15, 30, 30, 45, 60, 75, 90]
                        .into_iter()
                        .map(TimeInt::new_temporal)
                        .chain(std::iter::once(TimeInt::STATIC))
                        .collect(),
                ),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        // sparse-filled
        {
            let query = QueryExpression {
                filtered_index,
                using_index_values: Some(
                    [0, 15, 30, 30, 45, 60, 75, 90]
                        .into_iter()
                        .map(TimeInt::new_temporal)
                        .chain(std::iter::once(TimeInt::STATIC))
                        .collect(),
                ),
                sparse_fill_strategy: SparseFillStrategy::LatestAtGlobal,
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        Ok(())
    }

    #[test]
    fn filtered_is_not_null() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let filtered_index = Some(TimelineName::new("frame_nr"));
        let entity_path: EntityPath = "this/that".into();

        // non-existing entity
        {
            let ComponentDescriptor { component, .. } = MyPoints::descriptor_points();

            let query = QueryExpression {
                filtered_index,
                filtered_is_not_null: Some(ComponentColumnSelector {
                    entity_path: "no/such/entity".into(),
                    component: component.to_string(),
                }),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        // non-existing component
        {
            let query = QueryExpression {
                filtered_index,
                filtered_is_not_null: Some(ComponentColumnSelector {
                    entity_path: entity_path.clone(),
                    component: "AFieldThatDoesntExist".to_owned(),
                }),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        // MyPoint
        {
            let ComponentDescriptor { component, .. } = MyPoints::descriptor_points();

            let query = QueryExpression {
                filtered_index,
                filtered_is_not_null: Some(ComponentColumnSelector {
                    entity_path: entity_path.clone(),
                    component: component.to_string(),
                }),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        // MyColor
        {
            let ComponentDescriptor { component, .. } = MyPoints::descriptor_colors();

            let query = QueryExpression {
                filtered_index,
                filtered_is_not_null: Some(ComponentColumnSelector {
                    entity_path: entity_path.clone(),
                    component: component.to_string(),
                }),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        Ok(())
    }

    #[test]
    fn view_contents() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let entity_path: EntityPath = "this/that".into();
        let filtered_index = Some(TimelineName::new("frame_nr"));

        // empty view
        {
            let query = QueryExpression {
                filtered_index,
                view_contents: Some(
                    [(entity_path.clone(), Some(Default::default()))]
                        .into_iter()
                        .collect(),
                ),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        {
            let query = QueryExpression {
                filtered_index,
                view_contents: Some(
                    [(
                        entity_path.clone(),
                        Some(
                            [
                                MyPoints::descriptor_labels().component,
                                MyPoints::descriptor_colors().component,
                                ComponentIdentifier::new("AColumnThatDoesntEvenExist"),
                            ]
                            .into_iter()
                            .collect(),
                        ),
                    )]
                    .into_iter()
                    .collect(),
                ),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        Ok(())
    }

    #[test]
    fn selection() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let entity_path: EntityPath = "this/that".into();
        let filtered_index = TimelineName::new("frame_nr");

        // empty selection
        {
            let query = QueryExpression {
                filtered_index: Some(filtered_index),
                selection: Some(vec![]),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        // only indices (+ duplication)
        {
            let query = QueryExpression {
                filtered_index: Some(filtered_index),
                selection: Some(vec![
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from("ATimeColumnThatDoesntExist")),
                ]),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        // duplication and non-existing
        {
            let ComponentDescriptor { component, .. } = MyPoints::descriptor_points();

            let query = QueryExpression {
                filtered_index: Some(filtered_index),
                selection: Some(vec![
                    // Duplication
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: entity_path.clone(),
                        component: component.to_string(),
                    }),
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: entity_path.clone(),
                        component: component.to_string(),
                    }),
                    // Non-existing entity
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: "non_existing_entity".into(),
                        component: component.to_string(),
                    }),
                    // Non-existing components
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: entity_path.clone(),
                        component: "MyPoints:AFieldThatDoesntExist".into(),
                    }),
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: entity_path.clone(),
                        component: "AFieldThatDoesntExist".into(),
                    }),
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: entity_path.clone(),
                        component: "AArchetypeNameThatDoesNotExist:positions".into(),
                    }),
                ]),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        // static
        {
            let ComponentDescriptor { component, .. } = MyPoints::descriptor_labels();

            let query = QueryExpression {
                filtered_index: Some(filtered_index),
                selection: Some(vec![
                    // NOTE: This will force a crash if the selected indexes vs. view indexes are
                    // improperly handled.
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    //
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: entity_path.clone(),
                        component: component.to_string(),
                    }),
                ]),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        Ok(())
    }

    #[test]
    fn view_contents_and_selection() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let entity_path: EntityPath = "this/that".into();
        let filtered_index = TimelineName::new("frame_nr");

        // only components
        {
            let query = QueryExpression {
                filtered_index: Some(filtered_index),
                view_contents: Some(
                    [(
                        entity_path.clone(),
                        Some(
                            [
                                MyPoints::descriptor_colors().component,
                                MyPoints::descriptor_labels().component,
                            ]
                            .into_iter()
                            .collect(),
                        ),
                    )]
                    .into_iter()
                    .collect(),
                ),
                selection: Some(vec![
                    ColumnSelector::Time(TimeColumnSelector::from(filtered_index)),
                    ColumnSelector::Time(TimeColumnSelector::from(*Timeline::log_time().name())),
                    ColumnSelector::Time(TimeColumnSelector::from(*Timeline::log_tick().name())),
                    //
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: entity_path.clone(),
                        component: MyPoints::descriptor_points().component.to_string(),
                    }),
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: entity_path.clone(),
                        component: MyPoints::descriptor_colors().component.to_string(),
                    }),
                    ColumnSelector::Component(ComponentColumnSelector {
                        entity_path: entity_path.clone(),
                        component: MyPoints::descriptor_labels().component.to_string(),
                    }),
                ]),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        Ok(())
    }

    #[test]
    fn clears() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        extend_nasty_store_with_clears(&mut store.write())?;
        eprintln!("{store}");

        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let filtered_index = Some(TimelineName::new("frame_nr"));
        let entity_path = EntityPath::from("this/that");

        // barebones
        {
            let query = QueryExpression {
                filtered_index,
                view_contents: Some([(entity_path.clone(), None)].into_iter().collect()),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            assert_snapshot!(DisplayRB(dataframe));
        }

        // sparse-filled
        {
            let query = QueryExpression {
                filtered_index,
                view_contents: Some([(entity_path.clone(), None)].into_iter().collect()),
                sparse_fill_strategy: SparseFillStrategy::LatestAtGlobal,
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows()
            );
            let schema = query_handle.schema().clone();
            let batches = query_handle.batch_iter().collect_vec();
            let dataframe = concat_batches(&schema, &batches)?;
            eprintln!("{}", format_record_batch(&dataframe.clone()));

            // TODO(#7650): Those null values for `MyColor` on 10 and 20 look completely insane, but then again
            // static clear semantics in general are pretty unhinged right now, especially when
            // ranges are involved.

            assert_snapshot!(DisplayRB(dataframe));
        }

        Ok(())
    }

    #[test]
    fn pagination() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let filtered_index = Some(TimelineName::new("frame_nr"));
        let entity_path = EntityPath::from("this/that");

        // basic
        {
            let query = QueryExpression {
                filtered_index,
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows(),
            );

            let expected_rows = query_handle.batch_iter().collect_vec();

            for _ in 0..3 {
                for i in 0..expected_rows.len() {
                    query_handle.seek_to_row(i);

                    let expected = concat_batches(
                        query_handle.schema(),
                        &expected_rows.iter().skip(i).take(3).cloned().collect_vec(),
                    )?;
                    let schema = query_handle.schema().clone();
                    let batches = query_handle.batch_iter().take(3).collect_vec();
                    let got = concat_batches(&schema, &batches)?;

                    let expected = format!("{:#?}", expected.columns());
                    let got = format!("{:#?}", got.columns());

                    similar_asserts::assert_eq!(expected, got);
                }
            }
        }

        // with pov
        {
            let ComponentDescriptor { component, .. } = MyPoints::descriptor_points();
            let query = QueryExpression {
                filtered_index,
                filtered_is_not_null: Some(ComponentColumnSelector {
                    entity_path: entity_path.clone(),
                    component: component.to_string(),
                }),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows(),
            );

            let expected_rows = query_handle.batch_iter().collect_vec();

            for _ in 0..3 {
                for i in 0..expected_rows.len() {
                    query_handle.seek_to_row(i);

                    let expected = concat_batches(
                        query_handle.schema(),
                        &expected_rows.iter().skip(i).take(3).cloned().collect_vec(),
                    )?;
                    let schema = query_handle.schema().clone();
                    let batches = query_handle.batch_iter().take(3).collect_vec();
                    let got = concat_batches(&schema, &batches)?;

                    let expected = format!("{:#?}", expected.columns());
                    let got = format!("{:#?}", got.columns());

                    similar_asserts::assert_eq!(expected, got);
                }
            }
        }

        // with sampling
        {
            let query = QueryExpression {
                filtered_index,
                using_index_values: Some(
                    [0, 15, 30, 30, 45, 60, 75, 90]
                        .into_iter()
                        .map(TimeInt::new_temporal)
                        .chain(std::iter::once(TimeInt::STATIC))
                        .collect(),
                ),
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows(),
            );

            let expected_rows = query_handle.batch_iter().collect_vec();

            for _ in 0..3 {
                for i in 0..expected_rows.len() {
                    query_handle.seek_to_row(i);

                    let expected = concat_batches(
                        query_handle.schema(),
                        &expected_rows.iter().skip(i).take(3).cloned().collect_vec(),
                    )?;
                    let schema = query_handle.schema().clone();
                    let batches = query_handle.batch_iter().take(3).collect_vec();
                    let got = concat_batches(&schema, &batches)?;

                    let expected = format!("{:#?}", expected.columns());
                    let got = format!("{:#?}", got.columns());

                    similar_asserts::assert_eq!(expected, got);
                }
            }
        }

        // with sparse-fill
        {
            let query = QueryExpression {
                filtered_index,
                sparse_fill_strategy: SparseFillStrategy::LatestAtGlobal,
                ..Default::default()
            };
            eprintln!("{query:#?}:");

            let mut query_handle = query_engine.query(query.clone());
            assert_eq!(
                query_engine.query(query.clone()).into_iter().count() as u64,
                query_handle.num_rows(),
            );

            let expected_rows = query_handle.batch_iter().collect_vec();

            for _ in 0..3 {
                for i in 0..expected_rows.len() {
                    query_handle.seek_to_row(i);

                    let expected = concat_batches(
                        query_handle.schema(),
                        &expected_rows.iter().skip(i).take(3).cloned().collect_vec(),
                    )?;
                    let schema = query_handle.schema().clone();
                    let batches = query_handle.batch_iter().take(3).collect_vec();
                    let got = concat_batches(&schema, &batches)?;

                    let expected = format!("{:#?}", expected.columns());
                    let got = format!("{:#?}", got.columns());

                    similar_asserts::assert_eq!(expected, got);
                }
            }
        }

        Ok(())
    }

    #[test]
    fn query_static_any_values() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStore::new_handle(
            re_log_types::StoreId::random(re_log_types::StoreKind::Recording, "test_app"),
            ChunkStoreConfig::COMPACTION_DISABLED,
        );

        let any_values = AnyValues::default()
            .with_component_from_data("yak", Arc::new(StringArray::from(vec!["yuk"])))
            .with_component_from_data("foo", Arc::new(StringArray::from(vec!["bar"])))
            .with_component_from_data("baz", Arc::new(UInt32Array::from(vec![42u32])));

        let entity_path = EntityPath::from("test");

        let chunk0 = Chunk::builder(entity_path.clone())
            .with_serialized_batches(
                RowId::new(),
                TimePoint::default(),
                any_values.as_serialized_batches(),
            )
            .build()?;

        store.write().insert_chunk(&Arc::new(chunk0))?;

        let engine = QueryEngine::from_store(store);

        let query_expr = QueryExpression {
            view_contents: None,
            include_semantically_empty_columns: false,
            include_tombstone_columns: false,
            include_static_columns: re_chunk_store::StaticColumnSelection::Both,
            filtered_index: None,
            filtered_index_range: None,
            filtered_index_values: None,
            using_index_values: None,
            filtered_is_not_null: None,
            sparse_fill_strategy: re_chunk_store::SparseFillStrategy::None,
            selection: None,
        };

        let mut query_handle = engine.query(query_expr);

        let schema = query_handle.schema().clone();
        let batches = query_handle.batch_iter().collect_vec();
        let dataframe = concat_batches(&schema, &batches)?;
        eprintln!("{}", format_record_batch(&dataframe.clone()));

        assert_snapshot!(DisplayRB(dataframe));

        Ok(())
    }

    #[tokio::test]
    async fn async_barebones() -> anyhow::Result<()> {
        use tokio_stream::StreamExt as _;

        re_log::setup_logging();

        /// Wraps a [`QueryHandle`] in a [`Stream`].
        pub struct QueryHandleStream(pub QueryHandle<StorageEngine>);

        impl tokio_stream::Stream for QueryHandleStream {
            type Item = ArrowRecordBatch;

            #[inline]
            fn poll_next(
                mut self: std::pin::Pin<&mut Self>,
                cx: &mut std::task::Context<'_>,
            ) -> std::task::Poll<Option<Self::Item>> {
                let fut = self.0.next_row_batch_async();
                let fut = std::pin::pin!(fut);

                use std::future::Future as _;
                fut.poll(cx)
            }
        }

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        eprintln!("{store}");
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let engine_guard = query_engine.engine.write_arc();

        let filtered_index = Some(TimelineName::new("frame_nr"));

        // static
        let handle_static = tokio::spawn({
            let query_engine = query_engine.clone();
            async move {
                let query = QueryExpression::default();
                eprintln!("{query:#?}:");

                let query_handle = query_engine.query(query.clone());
                assert_eq!(
                    QueryHandleStream(query_engine.query(query.clone()))
                        .collect::<Vec<_>>()
                        .await
                        .len() as u64,
                    query_handle.num_rows()
                );
                let dataframe = concat_batches(
                    query_handle.schema(),
                    &QueryHandleStream(query_engine.query(query.clone()))
                        .collect::<Vec<_>>()
                        .await,
                )?;
                eprintln!("{}", format_record_batch(&dataframe.clone()));

                assert_snapshot!("async_barebones_static", DisplayRB(dataframe));

                Ok::<_, anyhow::Error>(())
            }
        });

        // temporal
        let handle_temporal = tokio::spawn({
            async move {
                let query = QueryExpression {
                    filtered_index,
                    ..Default::default()
                };
                eprintln!("{query:#?}:");

                let query_handle = query_engine.query(query.clone());
                assert_eq!(
                    QueryHandleStream(query_engine.query(query.clone()))
                        .collect::<Vec<_>>()
                        .await
                        .len() as u64,
                    query_handle.num_rows()
                );
                let dataframe = concat_batches(
                    query_handle.schema(),
                    &QueryHandleStream(query_engine.query(query.clone()))
                        .collect::<Vec<_>>()
                        .await,
                )?;
                eprintln!("{}", format_record_batch(&dataframe.clone()));

                assert_snapshot!("async_barebones_temporal", DisplayRB(dataframe));

                Ok::<_, anyhow::Error>(())
            }
        });

        let (tx, rx) = tokio::sync::oneshot::channel::<()>();

        let handle_queries = tokio::spawn(async move {
            let mut handle_static = std::pin::pin!(handle_static);
            let mut handle_temporal = std::pin::pin!(handle_temporal);

            // Poll the query handles, just once.
            //
            // Because the storage engine is already held by a writer, this will put them in a pending state,
            // waiting to be woken up. If nothing wakes them up, then this will simply deadlock.
            {
                // Although it might look scary, all we're doing is crafting a noop waker manually,
                // because `std::task::Waker::noop` is unstable.
                //
                // We'll use this to build a noop async context, so that we can poll our promises
                // manually.
                const RAW_WAKER_NOOP: std::task::RawWaker = {
                    const VTABLE: std::task::RawWakerVTable = std::task::RawWakerVTable::new(
                        |_| RAW_WAKER_NOOP, // Cloning just returns a new no-op raw waker
                        |_| {},             // `wake` does nothing
                        |_| {},             // `wake_by_ref` does nothing
                        |_| {},             // Dropping does nothing as we don't allocate anything
                    );
                    std::task::RawWaker::new(std::ptr::null(), &VTABLE)
                };

                #[expect(unsafe_code)]
                let mut cx = std::task::Context::from_waker(
                    // Safety: a Waker is just a privacy-preserving wrapper around a RawWaker.
                    unsafe {
                        &*std::ptr::from_ref::<std::task::RawWaker>(&RAW_WAKER_NOOP)
                            .cast::<std::task::Waker>()
                    },
                );

                use std::future::Future as _;
                assert!(handle_static.as_mut().poll(&mut cx).is_pending());
                assert!(handle_temporal.as_mut().poll(&mut cx).is_pending());
            }

            tx.send(()).unwrap();

            handle_static.await??;
            handle_temporal.await??;

            Ok::<_, anyhow::Error>(())
        });

        rx.await?;

        // Release the writer: the queries should now be able to stream to completion, provided
        // that _something_ wakes them up appropriately.
        drop(engine_guard);

        handle_queries.await??;

        Ok(())
    }

    /// Verifies that `next_n_rows` produces the same data as repeated `next_row` calls,
    /// across all sparse-fill strategies and a representative selection of queries.
    #[test]
    fn next_n_rows_matches_next_row() -> anyhow::Result<()> {
        re_log::setup_logging();

        let store = ChunkStoreHandle::new(create_nasty_store()?);
        let query_cache = QueryCache::new_handle(store.clone());
        let query_engine = QueryEngine::new(store.clone(), query_cache.clone());

        let filtered_index = Some(TimelineName::new("frame_nr"));

        // Cover: static, temporal, range-filtered, and LatestAtGlobal sparse fill.
        let queries = [
            QueryExpression::default(),
            QueryExpression {
                filtered_index,
                ..Default::default()
            },
            QueryExpression {
                filtered_index,
                filtered_index_range: Some(AbsoluteTimeRange::new(30, 60)),
                ..Default::default()
            },
            QueryExpression {
                filtered_index,
                sparse_fill_strategy: SparseFillStrategy::LatestAtGlobal,
                ..Default::default()
            },
        ];

        for query in queries {
            // Reference path: row-by-row via existing `next_row`.
            let mut reference_handle = query_engine.query(query.clone());
            let reference_rows: Vec<_> = reference_handle.iter().collect();
            let total_rows = reference_rows.len();
            let n_fields = reference_handle.schema().fields.len();

            // Candidate path: many `next_n_rows` calls of size 64.
            let mut candidate_handle = query_engine.query(query.clone());
            let mut candidate_rows = 0usize;
            let mut candidate_columns: Vec<Vec<ArrowArrayRef>> =
                (0..n_fields).map(|_| Vec::new()).collect();
            loop {
                let out = candidate_handle.next_n_rows(64, usize::MAX);
                if out.num_rows == 0 {
                    break;
                }
                candidate_rows += out.num_rows;
                for (col_idx, arr) in out.columns.into_iter().enumerate() {
                    candidate_columns[col_idx].push(arr);
                }
            }

            assert_eq!(
                total_rows, candidate_rows,
                "row count mismatch for query {query:?}"
            );

            // Concatenate row-by-row reference into per-column arrays and compare.
            for (col_idx, candidate_parts) in candidate_columns.iter().enumerate() {
                let ref_parts: Vec<&dyn arrow::array::Array> = reference_rows
                    .iter()
                    .map(|row| row[col_idx].as_ref())
                    .collect();
                let cand_parts: Vec<&dyn arrow::array::Array> =
                    candidate_parts.iter().map(|a| a.as_ref()).collect();
                if ref_parts.is_empty() && cand_parts.is_empty() {
                    continue;
                }
                let reference =
                    re_arrow_util::concat_arrays(&ref_parts).expect("ref concat failed");
                let candidate =
                    re_arrow_util::concat_arrays(&cand_parts).expect("cand concat failed");
                assert_eq!(
                    reference.to_data(),
                    candidate.to_data(),
                    "column {col_idx} mismatch for query {query:?}",
                );
            }
        }

        Ok(())
    }

    /// Returns a very nasty [`ChunkStore`] with all kinds of partial updates, chunk overlaps,
    /// repeated timestamps, duplicated chunks, partial multi-timelines, flat and recursive clears, etc.
    fn create_nasty_store() -> anyhow::Result<ChunkStore> {
        let mut store = ChunkStore::new(
            re_log_types::StoreId::random(re_log_types::StoreKind::Recording, "test_app"),
            ChunkStoreConfig::COMPACTION_DISABLED,
        );

        let entity_path = EntityPath::from("/this/that");

        let frame1 = TimeInt::new_temporal(10);
        let frame2 = TimeInt::new_temporal(20);
        let frame3 = TimeInt::new_temporal(30);
        let frame4 = TimeInt::new_temporal(40);
        let frame5 = TimeInt::new_temporal(50);
        let frame6 = TimeInt::new_temporal(60);
        let frame7 = TimeInt::new_temporal(70);

        let points1 = MyPoint::from_iter(0..1);
        let points2 = MyPoint::from_iter(1..2);
        let points3 = MyPoint::from_iter(2..3);
        let points4 = MyPoint::from_iter(3..4);
        let points5 = MyPoint::from_iter(4..5);
        let points6 = MyPoint::from_iter(5..6);
        let points7_1 = MyPoint::from_iter(6..7);
        let points7_2 = MyPoint::from_iter(7..8);
        let points7_3 = MyPoint::from_iter(8..9);

        let colors3 = MyColor::from_iter(2..3);
        let colors4 = MyColor::from_iter(3..4);
        let colors5 = MyColor::from_iter(4..5);
        let colors7 = MyColor::from_iter(6..7);

        let labels1 = vec![MyLabel("a".to_owned())];
        let labels2 = vec![MyLabel("b".to_owned())];
        let labels3 = vec![MyLabel("c".to_owned())];

        let row_id1_1 = RowId::new();
        let row_id1_3 = RowId::new();
        let row_id1_5 = RowId::new();
        let row_id1_7_1 = RowId::new();
        let row_id1_7_2 = RowId::new();
        let row_id1_7_3 = RowId::new();
        let chunk1_1 = Chunk::builder(entity_path.clone())
            .with_sparse_component_batches(
                row_id1_1,
                [build_frame_nr(frame1), build_log_time(frame1.into())],
                [
                    (MyPoints::descriptor_points(), Some(&points1 as _)),
                    (MyPoints::descriptor_colors(), None),
                    (MyPoints::descriptor_labels(), Some(&labels1 as _)), // shadowed by static
                ],
            )
            .with_sparse_component_batches(
                row_id1_3,
                [build_frame_nr(frame3), build_log_time(frame3.into())],
                [
                    (MyPoints::descriptor_points(), Some(&points3 as _)),
                    (MyPoints::descriptor_colors(), Some(&colors3 as _)),
                ],
            )
            .with_sparse_component_batches(
                row_id1_5,
                [build_frame_nr(frame5), build_log_time(frame5.into())],
                [
                    (MyPoints::descriptor_points(), Some(&points5 as _)),
                    (MyPoints::descriptor_colors(), None),
                ],
            )
            .with_sparse_component_batches(
                row_id1_7_1,
                [build_frame_nr(frame7), build_log_time(frame7.into())],
                [(MyPoints::descriptor_points(), Some(&points7_1 as _))],
            )
            .with_sparse_component_batches(
                row_id1_7_2,
                [build_frame_nr(frame7), build_log_time(frame7.into())],
                [(MyPoints::descriptor_points(), Some(&points7_2 as _))],
            )
            .with_sparse_component_batches(
                row_id1_7_3,
                [build_frame_nr(frame7), build_log_time(frame7.into())],
                [(MyPoints::descriptor_points(), Some(&points7_3 as _))],
            )
            .build()?;

        let chunk1_1 = Arc::new(chunk1_1);
        store.insert_chunk(&chunk1_1)?;
        let chunk1_2 = Arc::new(chunk1_1.clone_as(ChunkId::new(), RowId::new()));
        store.insert_chunk(&chunk1_2)?; // x2 !
        let chunk1_3 = Arc::new(chunk1_1.clone_as(ChunkId::new(), RowId::new()));
        store.insert_chunk(&chunk1_3)?; // x3 !!

        let row_id2_2 = RowId::new();
        let row_id2_3 = RowId::new();
        let row_id2_4 = RowId::new();
        let chunk2 = Chunk::builder(entity_path.clone())
            .with_sparse_component_batches(
                row_id2_2,
                [build_frame_nr(frame2)],
                [(MyPoints::descriptor_points(), Some(&points2 as _))],
            )
            .with_sparse_component_batches(
                row_id2_3,
                [build_frame_nr(frame3)],
                [
                    (MyPoints::descriptor_points(), Some(&points3 as _)),
                    (MyPoints::descriptor_colors(), Some(&colors3 as _)),
                ],
            )
            .with_sparse_component_batches(
                row_id2_4,
                [build_frame_nr(frame4)],
                [(MyPoints::descriptor_points(), Some(&points4 as _))],
            )
            .build()?;

        let chunk2 = Arc::new(chunk2);
        store.insert_chunk(&chunk2)?;

        let row_id3_2 = RowId::new();
        let row_id3_4 = RowId::new();
        let row_id3_6 = RowId::new();
        let chunk3 = Chunk::builder(entity_path.clone())
            .with_sparse_component_batches(
                row_id3_2,
                [build_frame_nr(frame2)],
                [(MyPoints::descriptor_points(), Some(&points2 as _))],
            )
            .with_sparse_component_batches(
                row_id3_4,
                [build_frame_nr(frame4)],
                [(MyPoints::descriptor_points(), Some(&points4 as _))],
            )
            .with_sparse_component_batches(
                row_id3_6,
                [build_frame_nr(frame6)],
                [(MyPoints::descriptor_points(), Some(&points6 as _))],
            )
            .build()?;

        let chunk3 = Arc::new(chunk3);
        store.insert_chunk(&chunk3)?;

        let row_id4_4 = RowId::new();
        let row_id4_5 = RowId::new();
        let row_id4_7 = RowId::new();
        let chunk4 = Chunk::builder(entity_path.clone())
            .with_sparse_component_batches(
                row_id4_4,
                [build_frame_nr(frame4)],
                [(MyPoints::descriptor_colors(), Some(&colors4 as _))],
            )
            .with_sparse_component_batches(
                row_id4_5,
                [build_frame_nr(frame5)],
                [(MyPoints::descriptor_colors(), Some(&colors5 as _))],
            )
            .with_sparse_component_batches(
                row_id4_7,
                [build_frame_nr(frame7)],
                [(MyPoints::descriptor_colors(), Some(&colors7 as _))],
            )
            .build()?;

        let chunk4 = Arc::new(chunk4);
        store.insert_chunk(&chunk4)?;

        let row_id5_1 = RowId::new();
        let chunk5 = Chunk::builder(entity_path.clone())
            .with_sparse_component_batches(
                row_id5_1,
                TimePoint::default(),
                [(MyPoints::descriptor_labels(), Some(&labels2 as _))],
            )
            .build()?;

        let chunk5 = Arc::new(chunk5);
        store.insert_chunk(&chunk5)?;

        let row_id6_1 = RowId::new();
        let chunk6 = Chunk::builder(entity_path.clone())
            .with_sparse_component_batches(
                row_id6_1,
                TimePoint::default(),
                [(MyPoints::descriptor_labels(), Some(&labels3 as _))],
            )
            .build()?;

        let chunk6 = Arc::new(chunk6);
        store.insert_chunk(&chunk6)?;

        Ok(store)
    }

    fn extend_nasty_store_with_clears(store: &mut ChunkStore) -> anyhow::Result<()> {
        let entity_path = EntityPath::from("/this/that");
        let entity_path_parent = EntityPath::from("/this");
        let entity_path_root = EntityPath::from("/");

        let frame35 = TimeInt::new_temporal(35);
        let frame55 = TimeInt::new_temporal(55);
        let frame60 = TimeInt::new_temporal(60);
        let frame65 = TimeInt::new_temporal(65);

        let clear_flat = components::ClearIsRecursive(false.into());
        let clear_recursive = components::ClearIsRecursive(true.into());

        let row_id1_1 = RowId::new();
        let chunk1 = Chunk::builder(entity_path.clone())
            .with_sparse_component_batches(
                row_id1_1,
                TimePoint::default(),
                [(
                    archetypes::Clear::descriptor_is_recursive(),
                    Some(&clear_flat as _),
                )],
            )
            .build()?;

        let chunk1 = Arc::new(chunk1);
        store.insert_chunk(&chunk1)?;

        // NOTE: This tombstone will never have any visible effect.
        //
        // Tombstones still obey the same rules as other all other data, specifically: if a component
        // has been statically logged for an entity, it shadows any temporal data for that same
        // component on that same entity.
        //
        // In this specific case, `this/that` already has been logged a static clear, so further temporal
        // clears will be ignored.
        //
        // It's pretty weird, but then again static clear semantics in general are very weird.
        let row_id2_1 = RowId::new();
        let chunk2 = Chunk::builder(entity_path.clone())
            .with_sparse_component_batches(
                row_id2_1,
                [build_frame_nr(frame35), build_log_time(frame35.into())],
                [(
                    archetypes::Clear::descriptor_is_recursive(),
                    Some(&clear_recursive as _),
                )],
            )
            .build()?;

        let chunk2 = Arc::new(chunk2);
        store.insert_chunk(&chunk2)?;

        let row_id3_1 = RowId::new();
        let chunk3 = Chunk::builder(entity_path_root.clone())
            .with_sparse_component_batches(
                row_id3_1,
                [build_frame_nr(frame55), build_log_time(frame55.into())],
                [(
                    archetypes::Clear::descriptor_is_recursive(),
                    Some(&clear_flat as _),
                )],
            )
            .with_sparse_component_batches(
                row_id3_1,
                [build_frame_nr(frame60), build_log_time(frame60.into())],
                [(
                    archetypes::Clear::descriptor_is_recursive(),
                    Some(&clear_recursive as _),
                )],
            )
            .with_sparse_component_batches(
                row_id3_1,
                [build_frame_nr(frame65), build_log_time(frame65.into())],
                [(
                    archetypes::Clear::descriptor_is_recursive(),
                    Some(&clear_flat as _),
                )],
            )
            .build()?;

        let chunk3 = Arc::new(chunk3);
        store.insert_chunk(&chunk3)?;

        let row_id4_1 = RowId::new();
        let chunk4 = Chunk::builder(entity_path_parent.clone())
            .with_sparse_component_batches(
                row_id4_1,
                [build_frame_nr(frame60), build_log_time(frame60.into())],
                [(
                    archetypes::Clear::descriptor_is_recursive(),
                    Some(&clear_flat as _),
                )],
            )
            .build()?;

        let chunk4 = Arc::new(chunk4);
        store.insert_chunk(&chunk4)?;

        let row_id5_1 = RowId::new();
        let chunk5 = Chunk::builder(entity_path_parent.clone())
            .with_sparse_component_batches(
                row_id5_1,
                [build_frame_nr(frame65), build_log_time(frame65.into())],
                [(
                    archetypes::Clear::descriptor_is_recursive(),
                    Some(&clear_recursive as _),
                )],
            )
            .build()?;

        let chunk5 = Arc::new(chunk5);
        store.insert_chunk(&chunk5)?;

        Ok(())
    }

    /// Build a store containing `n_chunks` disjoint single-component chunks, each holding
    /// `rows_per_chunk` rows. Chunk `k` covers the time range
    /// `[k * rows_per_chunk, (k+1) * rows_per_chunk)`. Chunks are inserted in `order`.
    fn build_disjoint_chunk_store(
        n_chunks: usize,
        rows_per_chunk: usize,
        order: &[usize],
    ) -> anyhow::Result<ChunkStore> {
        assert_eq!(order.len(), n_chunks);
        let mut store = ChunkStore::new(
            re_log_types::StoreId::random(re_log_types::StoreKind::Recording, "test_app"),
            ChunkStoreConfig::COMPACTION_DISABLED,
        );

        let entity_path = EntityPath::from("/disjoint");

        let mut chunks: Vec<Arc<Chunk>> = Vec::with_capacity(n_chunks);
        for chunk_idx in 0..n_chunks {
            let mut builder = Chunk::builder(entity_path.clone());
            for local_row in 0..rows_per_chunk {
                let global_row = chunk_idx * rows_per_chunk + local_row;
                #[expect(clippy::cast_possible_wrap)]
                let frame = TimeInt::new_temporal(global_row as i64);
                let points = MyPoint::from_iter(global_row as u32..global_row as u32 + 1);
                builder = builder.with_sparse_component_batches(
                    RowId::new(),
                    [build_frame_nr(frame)],
                    [(MyPoints::descriptor_points(), Some(&points as _))],
                );
            }
            chunks.push(Arc::new(builder.build()?));
        }

        for &idx in order {
            store.insert_chunk(&chunks[idx])?;
        }

        Ok(store)
    }

    fn run_query_collect_rows(
        store: &ChunkStoreHandle,
        query: QueryExpression,
    ) -> anyhow::Result<ArrowRecordBatch> {
        let cache = QueryCache::new_handle(store.clone());
        let engine = QueryEngine::new(store.clone(), cache);
        let mut handle = engine.query(query);
        let schema = handle.schema().clone();
        let batches = handle.batch_iter().collect_vec();
        Ok(concat_batches(&schema, &batches)?)
    }

    /// Build `n_chunks` single-component chunks on the same entity whose time
    /// ranges overlap with their neighbors.
    ///
    /// Chunk `k` covers `frame_nr ∈ [k * step, k * step + chunk_width)`. With
    /// `step < chunk_width`, neighboring chunks share `chunk_width - step` frames.
    /// Each chunk uses a distinct payload offset so the streaming-join's
    /// max-`RowId` overlap resolution at `query.rs:1243` has a meaningful winner
    /// to pick.
    fn build_overlapping_chunks(
        n_chunks: usize,
        chunk_width: u32,
        step: u32,
    ) -> anyhow::Result<Vec<Arc<Chunk>>> {
        assert!(n_chunks >= 1);
        assert!(step < chunk_width, "chunks must actually overlap");

        let entity_path = EntityPath::from("/overlap");
        let mut chunks: Vec<Arc<Chunk>> = Vec::with_capacity(n_chunks);
        for k in 0..n_chunks {
            let mut builder = Chunk::builder(entity_path.clone());
            #[expect(clippy::cast_possible_truncation)]
            let base = (k as u32) * step;
            // Distinct payload so we can detect which chunk's data ended up in the row.
            #[expect(clippy::cast_possible_truncation)]
            let payload_offset = (k as u32) * 1_000;
            for f in base..base + chunk_width {
                let points = MyPoint::from_iter((f + payload_offset)..(f + payload_offset + 1));
                let frame = TimeInt::new_temporal(i64::from(f));
                builder = builder.with_sparse_component_batches(
                    RowId::new(),
                    [build_frame_nr(frame)],
                    [(MyPoints::descriptor_points(), Some(&points as _))],
                );
            }
            chunks.push(Arc::new(builder.build()?));
        }
        Ok(chunks)
    }

    fn build_overlapping_chunk_store(
        chunks: &[Arc<Chunk>],
        order: &[usize],
    ) -> anyhow::Result<ChunkStore> {
        assert_eq!(order.len(), chunks.len());
        let mut store = ChunkStore::new(
            re_log_types::StoreId::random(re_log_types::StoreKind::Recording, "test_app"),
            ChunkStoreConfig::COMPACTION_DISABLED,
        );
        for &idx in order {
            store.insert_chunk(&chunks[idx])?;
        }
        Ok(store)
    }

    /// Verifies that the H3 init-sort by `time_min` (which is now unconditional, vs. the
    /// previous "only after clear-chunk merge" policy) leaves emitted output unchanged
    /// when two chunks overlap on the same `filtered_index` value, exercised through both
    /// the batched (`next_n_rows` -> `next_row_batch`) and the per-row (`next_row` ->
    /// `_resolve_one_row`) paths.
    ///
    /// Why both paths matter: the streaming-join's overlap resolution at `query.rs:1243`
    /// picks max-`RowId` for value columns, which is order-independent by construction.
    /// The `RowId` column itself is sourced from `view_chunks.first()`
    /// (`query.rs:1101-1107`, `1635-1656`). Once `view_chunks` is sorted by `time_min`,
    /// the "first chunk" identity becomes a function of `time_min` rather than insert
    /// order — so insert-order invariance is the correct assertion either way.
    ///
    /// Note: the `RowId` column itself is intentionally not in the selection. Today,
    /// `indices_and_components()` (per its `TODO(#9922)` doc) excludes `RowId`, so the
    /// first view is always a `Time` column with empty `view_chunks[0]`, which makes the
    /// `view_chunks.first().and_then(|vec| vec.first())` lookup return `None` and emit
    /// a null array — incompatible with the non-nullable `RowId` schema field. When
    /// `#9922` is fixed and `RowId` emission picks a real chunk, the H3 sort makes that
    /// choice a pure function of `time_min`, so this test's insert-order-invariance
    /// assertion will continue to hold over the full record batch.
    #[test]
    fn pruning_walk_overlapping_chunks_rowid_invariance() -> anyhow::Result<()> {
        re_log::setup_logging();

        // 3 chunks: A=[0,5), B=[3,8), C=[6,11). Pairwise overlaps on frames
        // {3,4} (A∩B) and {6,7} (B∩C). Distinct payload offsets per chunk so
        // the max-RowId overlap winner at `query.rs:1243` has a real choice
        // to make.
        const N_CHUNKS: usize = 3;
        const CHUNK_WIDTH: u32 = 5;
        const STEP: u32 = 3;
        let chunks = build_overlapping_chunks(N_CHUNKS, CHUNK_WIDTH, STEP)?;

        let forward: Vec<usize> = (0..N_CHUNKS).collect();
        let reversed: Vec<usize> = (0..N_CHUNKS).rev().collect();
        let shuffled: Vec<usize> = vec![1, 2, 0];

        let store_fwd = ChunkStoreHandle::new(build_overlapping_chunk_store(&chunks, &forward)?);
        let store_rev = ChunkStoreHandle::new(build_overlapping_chunk_store(&chunks, &reversed)?);
        let store_shuf = ChunkStoreHandle::new(build_overlapping_chunk_store(&chunks, &shuffled)?);

        let filtered_index_name = TimelineName::new("frame_nr");
        let filtered_index = Some(filtered_index_name);

        let make_query = |range: Option<AbsoluteTimeRange>| QueryExpression {
            filtered_index,
            filtered_index_range: range,
            selection: Some(vec![
                ColumnSelector::Time(TimeColumnSelector::from(filtered_index_name)),
                ColumnSelector::Component(ComponentColumnSelector {
                    entity_path: EntityPath::from("/overlap"),
                    component: MyPoints::descriptor_points().component.to_string(),
                }),
            ]),
            ..Default::default()
        };

        let collect_per_row_arrays = |store: &ChunkStoreHandle,
                                      query: QueryExpression|
         -> anyhow::Result<Vec<Vec<ArrayRef>>> {
            let cache = QueryCache::new_handle(store.clone());
            let engine = QueryEngine::new(store.clone(), cache);
            let mut handle = engine.query(query);
            let mut out = Vec::new();
            while let Some(row) = handle.next_row() {
                out.push(row);
            }
            Ok(out)
        };

        // Full-range and mid-range queries. Mid-range crosses chunk boundaries
        // to exercise H1 (exhausted), H2 (time-range prune), and H3 (early
        // break) jointly under overlap.
        //
        // Total unique frames: union of [0,5), [3,8), [6,11) = [0,11) -> 11 rows.
        // Mid-range [4..=7] picks 4 rows, with frame 4 in A∩B and frames 6,7 in B∩C.
        let full_query = make_query(None);
        let mid_query = make_query(Some(AbsoluteTimeRange::new(4, 7)));

        for (label, query, expected_rows) in [
            ("full-range", full_query, 11usize),
            ("mid-range", mid_query, 4usize),
        ] {
            // Batched path: byte-identical record batches across all 3 orderings.
            let rb_fwd = run_query_collect_rows(&store_fwd, query.clone())?;
            let rb_rev = run_query_collect_rows(&store_rev, query.clone())?;
            let rb_shuf = run_query_collect_rows(&store_shuf, query.clone())?;
            assert_eq!(rb_fwd.num_rows(), expected_rows, "{label}: row count");
            assert_eq!(rb_fwd, rb_rev, "{label}: batched fwd vs reversed");
            assert_eq!(rb_fwd, rb_shuf, "{label}: batched fwd vs shuffled");

            // Per-row path drives `_resolve_one_row` directly.
            let rows_fwd = collect_per_row_arrays(&store_fwd, query.clone())?;
            let rows_rev = collect_per_row_arrays(&store_rev, query.clone())?;
            let rows_shuf = collect_per_row_arrays(&store_shuf, query)?;
            assert_eq!(rows_fwd.len(), expected_rows, "{label}: per-row count");
            for (other_label, other) in [("reversed", &rows_rev), ("shuffled", &rows_shuf)] {
                assert_eq!(
                    rows_fwd.len(),
                    other.len(),
                    "{label}: per-row count diverged vs {other_label}",
                );
                for (i, (a_row, b_row)) in rows_fwd.iter().zip(other).enumerate() {
                    assert_eq!(
                        a_row.len(),
                        b_row.len(),
                        "{label}: per-row column count diverged at row {i} vs {other_label}",
                    );
                    for (col_idx, (a, b)) in a_row.iter().zip(b_row).enumerate() {
                        assert_eq!(
                            a.to_data(),
                            b.to_data(),
                            "{label}: row {i} col {col_idx} changed vs {other_label}",
                        );
                    }
                }
            }
        }

        Ok(())
    }

    /// Verifies that the H1/H2/H3 pruning logic produces identical row output regardless
    /// of the insertion order of disjoint chunks. The view-init sort by `time_min` (H3)
    /// must normalize the walk so that:
    /// - forward, reversed, and shuffled chunk inserts yield byte-identical record batches
    /// - mid-range filtered queries (which exercise H1 exhaustion of earlier chunks and
    ///   H3 early-break for later chunks) match the unfiltered slice.
    #[test]
    fn pruning_walk_insert_order_invariance() -> anyhow::Result<()> {
        re_log::setup_logging();

        const N_CHUNKS: usize = 5;
        const ROWS_PER_CHUNK: usize = 4;
        const TOTAL_ROWS: usize = N_CHUNKS * ROWS_PER_CHUNK;

        let forward: Vec<usize> = (0..N_CHUNKS).collect();
        let reversed: Vec<usize> = (0..N_CHUNKS).rev().collect();
        let shuffled: Vec<usize> = vec![2, 0, 4, 1, 3];

        let store_fwd = ChunkStoreHandle::new(build_disjoint_chunk_store(
            N_CHUNKS,
            ROWS_PER_CHUNK,
            &forward,
        )?);
        let store_rev = ChunkStoreHandle::new(build_disjoint_chunk_store(
            N_CHUNKS,
            ROWS_PER_CHUNK,
            &reversed,
        )?);
        let store_shuf = ChunkStoreHandle::new(build_disjoint_chunk_store(
            N_CHUNKS,
            ROWS_PER_CHUNK,
            &shuffled,
        )?);

        let filtered_index = Some(TimelineName::new("frame_nr"));

        // Full-range query: all rows visible. Each row should match across orderings.
        let full_query = QueryExpression {
            filtered_index,
            ..Default::default()
        };

        let rb_fwd = run_query_collect_rows(&store_fwd, full_query.clone())?;
        let rb_rev = run_query_collect_rows(&store_rev, full_query.clone())?;
        let rb_shuf = run_query_collect_rows(&store_shuf, full_query.clone())?;

        assert_eq!(rb_fwd.num_rows(), TOTAL_ROWS);
        assert_eq!(rb_fwd, rb_rev, "forward vs reversed insert order differ");
        assert_eq!(rb_fwd, rb_shuf, "forward vs shuffled insert order differ");

        // Mid-range query: indices [8..16) skip the first two chunks entirely (H1/H2)
        // and break out before reaching the last chunk (H3).
        let mid_query = QueryExpression {
            filtered_index,
            filtered_index_range: Some(AbsoluteTimeRange::new(8, 15)),
            ..Default::default()
        };

        let mid_fwd = run_query_collect_rows(&store_fwd, mid_query.clone())?;
        let mid_rev = run_query_collect_rows(&store_rev, mid_query.clone())?;
        let mid_shuf = run_query_collect_rows(&store_shuf, mid_query)?;

        assert_eq!(mid_fwd.num_rows(), 8); // frames 8..=15 inclusive
        assert_eq!(mid_fwd, mid_rev, "mid-range fwd vs reversed differ");
        assert_eq!(mid_fwd, mid_shuf, "mid-range fwd vs shuffled differ");

        // Sanity: per-row `next_row` matches batch output.
        let cache = QueryCache::new_handle(store_shuf.clone());
        let engine = QueryEngine::new(store_shuf.clone(), cache);
        let mut handle = engine.query(QueryExpression {
            filtered_index,
            ..Default::default()
        });
        let mut row_count = 0usize;
        while handle.next_row().is_some() {
            row_count += 1;
        }
        assert_eq!(row_count, TOTAL_ROWS);

        Ok(())
    }
}