zirql 0.1.0

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

/// A whole argument is admitted before its immutable name is installed.
#[derive(Debug, PartialEq)]
pub struct FunctionParameter<K> {
    pub name: Located<String>,
    pub declaration: DeclaredType<K>,
}
/// Ordered local bindings and one final pure value. Signatures register before
/// any body is inspected, permitting direct and mutual recursion.
#[derive(Debug, PartialEq)]
pub struct FunctionDeclaration<Q = (), K = ()> {
    pub name: Located<String>,
    pub parameters: Vec<Located<FunctionParameter<K>>>,
    pub result: Located<DeclaredType<K>>,
    pub bindings: Vec<(Located<String>, ValueExpression<Q>)>,
    pub value: ValueExpression<Q>,
}
/// A resolved header borrowing an immutable body. A host can resolve nominal
/// types for its current request without cloning or reparsing expression trees.
pub struct FunctionDeclarationRef<'a, Q = (), K = ()> {
    pub name: &'a Located<String>,
    pub parameters: &'a [Located<FunctionParameter<K>>],
    pub result: &'a Located<DeclaredType<K>>,
    pub bindings: &'a [(Located<String>, ValueExpression<Q>)],
    pub value: &'a ValueExpression<Q>,
}
impl<Q, K> Copy for FunctionDeclarationRef<'_, Q, K> {}
impl<Q, K> Clone for FunctionDeclarationRef<'_, Q, K> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<Q, K> FunctionDeclaration<Q, K> {
    pub fn as_borrowed(&self) -> FunctionDeclarationRef<'_, Q, K> {
        FunctionDeclarationRef {
            name: &self.name,
            parameters: &self.parameters,
            result: &self.result,
            bindings: &self.bindings,
            value: &self.value,
        }
    }
}
/// A whole typed argument destructured only after all argument admission.
#[derive(Debug, PartialEq)]
pub struct PatternParameter<K> {
    pub pattern: Pattern,
    pub declaration: DeclaredType<K>,
}

/// Pattern-capable declarations use lexical `Block` values for local lets.
/// Existing name-only declarations remain accepted by their original APIs.
#[derive(Debug, PartialEq)]
pub struct PatternFunctionDeclaration<Q = (), K = ()> {
    pub name: Located<String>,
    pub parameters: Vec<Located<PatternParameter<K>>>,
    pub result: Located<DeclaredType<K>>,
    pub value: ValueExpression<Q>,
}

/// A request-resolved declaration borrowing its original parameter pattern.
#[derive(Debug, PartialEq)]
pub struct PatternParameterRef<'a, K> {
    pub pattern: &'a Pattern,
    pub declaration: DeclaredType<K>,
}

/// Request-owned headers borrowing reusable patterns and a body tree.
pub struct PatternFunctionDeclarationRef<'a, Q = (), K = ()> {
    pub name: &'a Located<String>,
    pub parameters: &'a [Located<PatternParameterRef<'a, K>>],
    pub result: &'a Located<DeclaredType<K>>,
    pub value: &'a ValueExpression<Q>,
}

pub(crate) enum Parameters<'a, K> {
    Names(&'a [Located<FunctionParameter<K>>]),
    Patterns(&'a [Located<PatternParameter<K>>]),
    BorrowedPatterns(&'a [Located<PatternParameterRef<'a, K>>]),
}
impl<K> Copy for Parameters<'_, K> {}
impl<K> Clone for Parameters<'_, K> {
    fn clone(&self) -> Self {
        *self
    }
}
pub(crate) struct ParameterRef<'a, K> {
    pub pattern: PatternRef<'a>,
    pub declaration: &'a DeclaredType<K>,
    pub range: &'a Range<usize>,
}
impl<'a, K> Parameters<'a, K> {
    pub fn len(self) -> usize {
        match self {
            Self::Names(v) => v.len(),
            Self::Patterns(v) => v.len(),
            Self::BorrowedPatterns(v) => v.len(),
        }
    }
    pub fn iter(self) -> impl Iterator<Item = ParameterRef<'a, K>> {
        (0..self.len()).map(move |index| match self {
            Self::Names(v) => ParameterRef {
                pattern: PatternRef::Name(&v[index].value.name),
                declaration: &v[index].value.declaration,
                range: &v[index].range,
            },
            Self::Patterns(v) => ParameterRef {
                pattern: PatternRef::Pattern(&v[index].value.pattern),
                declaration: &v[index].value.declaration,
                range: &v[index].range,
            },
            Self::BorrowedPatterns(v) => ParameterRef {
                pattern: PatternRef::Pattern(v[index].value.pattern),
                declaration: &v[index].value.declaration,
                range: &v[index].range,
            },
        })
    }
}
pub(crate) struct DeclarationRef<'a, Q, K> {
    pub name: &'a Located<String>,
    pub parameters: Parameters<'a, K>,
    pub result: &'a Located<DeclaredType<K>>,
    pub bindings: &'a [(Located<String>, ValueExpression<Q>)],
    pub value: &'a ValueExpression<Q>,
}
impl<Q, K> Copy for DeclarationRef<'_, Q, K> {}
impl<Q, K> Clone for DeclarationRef<'_, Q, K> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<'a, Q, K> From<FunctionDeclarationRef<'a, Q, K>> for DeclarationRef<'a, Q, K> {
    fn from(d: FunctionDeclarationRef<'a, Q, K>) -> Self {
        Self {
            name: d.name,
            parameters: Parameters::Names(d.parameters),
            result: d.result,
            bindings: d.bindings,
            value: d.value,
        }
    }
}
impl<'a, Q, K> From<PatternFunctionDeclarationRef<'a, Q, K>> for DeclarationRef<'a, Q, K> {
    fn from(d: PatternFunctionDeclarationRef<'a, Q, K>) -> Self {
        Self {
            name: d.name,
            parameters: Parameters::BorrowedPatterns(d.parameters),
            result: d.result,
            bindings: &[],
            value: d.value,
        }
    }
}
impl<Q, K> PatternFunctionDeclaration<Q, K> {
    pub(crate) fn as_borrowed(&self) -> DeclarationRef<'_, Q, K> {
        DeclarationRef {
            name: &self.name,
            parameters: Parameters::Patterns(&self.parameters),
            result: &self.result,
            bindings: &[],
            value: &self.value,
        }
    }
}

/// The maximum simultaneously active user-function activations. Compatible
/// tail calls reuse one activation. Expression nesting and host reentry have
/// separate existing guards in [`Budget`]. Every call still spends work.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FunctionLimits {
    pub active_depth: usize,
}
/// A bounded active-call location; completed calls are never retained.
#[derive(Debug, PartialEq, Eq)]
pub struct FunctionCall {
    pub function: String,
    pub range: Range<usize>,
}
/// Original failure and at most sixteen active function locations (names are
/// capped at 64 characters), innermost
/// first. A tail activation records its current call rather than its history.
#[derive(Debug, PartialEq, Eq)]
pub struct FunctionError<E> {
    pub error: E,
    pub calls: Vec<FunctionCall>,
    pub omitted_calls: usize,
}
impl<E: fmt::Display> fmt::Display for FunctionError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.error.fmt(f)
    }
}
impl<E: std::error::Error + 'static> std::error::Error for FunctionError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.error)
    }
}
impl<E: From<QueryError>> From<QueryError> for FunctionError<E> {
    fn from(error: QueryError) -> Self {
        Self {
            error: error.into(),
            calls: Vec::new(),
            omitted_calls: 0,
        }
    }
}

#[derive(Default)]
pub(crate) struct CallTrace {
    pub frames: Vec<(usize, Range<usize>)>,
    pub omitted: usize,
}
impl CallTrace {
    pub fn append(&mut self, calls: &[(usize, Range<usize>)], omitted: usize) {
        let keep = calls.len().min(16 - self.frames.len());
        self.frames.extend_from_slice(&calls[..keep]);
        self.omitted = self
            .omitted
            .saturating_add(omitted)
            .saturating_add(calls.len() - keep);
    }
}

pub(crate) struct Resolver<'h, 'a, Q, K, H> {
    pub queries: &'h mut H,
    pub declarations: &'a [DeclarationRef<'a, Q, K>],
}
impl<Q, K: PartialEq, H: ValueQueryHost<Q>> ValueQueryHost<Q> for Resolver<'_, '_, Q, K, H> {
    type Error = H::Error;
    fn function(
        &mut self,
        name: &Located<String>,
        budget: &mut Budget,
    ) -> Result<(usize, usize), QueryError> {
        for (id, d) in self.declarations.iter().enumerate() {
            budget.charge(
                1 + name.value.len().min(d.name.value.len()),
                Location::Query(name.range.clone()),
            )?;
            if name.value == d.name.value {
                return Ok((id, d.parameters.len()));
            }
        }
        Err(QueryError::query(
            name.range.clone(),
            format!("undefined function: {}", name.value),
        ))
    }
    fn function_types(
        &mut self,
        name: &Located<String>,
        budget: &mut Budget,
    ) -> Result<Vec<ValueType>, QueryError> {
        let (id, _) = self.function(name, budget)?;
        crate::value::function_facts(
            &self.declarations[id].result.value,
            budget,
            &Location::Query(name.range.clone()),
        )
    }
    fn accumulator_function(
        &mut self,
        step: &Located<String>,
        budget: &mut Budget,
    ) -> Result<(usize, Vec<ValueType>), QueryError> {
        let (id, _) = self.function(step, budget)?;
        let state = accumulator_state(&self.declarations[id], step, budget)?;
        Ok((
            id,
            crate::value::function_facts(state, budget, &Location::Query(step.range.clone()))?,
        ))
    }
    fn query_types(
        &mut self,
        q: &Q,
        l: &[(&str, Vec<ValueType>)],
        b: &mut Budget,
        r: &Range<usize>,
    ) -> Result<Vec<ValueType>, QueryError> {
        self.queries.query_types(q, l, b, r)
    }
    fn native_value_types(
        &mut self,
        q: &Q,
        l: &[(&str, Vec<ValueType>)],
        b: &mut Budget,
        r: &Range<usize>,
    ) -> Result<Vec<ValueType>, QueryError> {
        self.queries.native_value_types(q, l, b, r)
    }
    fn query_arguments<'q>(
        &self,
        q: &'q Q,
        b: &mut Budget,
        r: &Range<usize>,
    ) -> Result<Vec<&'q ValueExpression<Q>>, QueryError> {
        self.queries.query_arguments(q, b, r)
    }
    fn evaluate_query(
        &mut self,
        q: &Q,
        l: &[(&str, ConstructedValue)],
        b: &mut Budget,
    ) -> Result<ConstructedValue, Self::Error> {
        self.queries.evaluate_query(q, l, b)
    }
    fn read_binding(
        &mut self,
        n: &str,
        r: &Range<usize>,
        b: &mut Budget,
    ) -> Result<ConstructedValue, Self::Error> {
        self.queries.read_binding(n, r, b)
    }
}
fn accumulator_state<'a, Q, K: PartialEq>(
    declaration: &DeclarationRef<'a, Q, K>,
    step: &Located<String>,
    budget: &mut Budget,
) -> Result<&'a DeclaredType<K>, QueryError> {
    let location = Location::Query(step.range.clone());
    if declaration.parameters.len() != 2 {
        return Err(QueryError::query(
            step.range.clone(),
            "accumulator step needs two parameters",
        ));
    }
    let state = declaration
        .parameters
        .iter()
        .next()
        .expect("two parameters")
        .declaration;
    if !crate::runtime_types::compatible_state(state, &declaration.result.value, budget, &location)?
    {
        return Err(QueryError::query(
            step.range.clone(),
            "accumulator result is incompatible with state",
        ));
    }
    Ok(state)
}

fn register<'a, Q: 'a, K: 'a>(
    declarations: impl Clone + Iterator<Item = DeclarationRef<'a, Q, K>>,
    budget: &mut Budget,
    mut conflict: impl FnMut(&str) -> bool,
) -> Result<(), QueryError> {
    for (index, d) in declarations.clone().enumerate() {
        let location = Location::Query(d.name.range.clone());
        budget.charge(d.name.value.len() + 1, location.clone())?;
        if d.name.value == "_" || builtin(&d.name.value) || conflict(&d.name.value) {
            return Err(QueryError::query(
                d.name.range.clone(),
                "function conflicts with a reserved operation name",
            ));
        }
        for previous in declarations.clone().take(index) {
            budget.charge(
                1 + d.name.value.len().min(previous.name.value.len()),
                location.clone(),
            )?;
            if d.name.value == previous.name.value {
                return Err(QueryError::query(
                    d.name.range.clone(),
                    "function is already defined",
                ));
            }
        }
        for p in d.parameters.iter() {
            crate::runtime_types::validate_declaration(
                p.declaration,
                budget,
                &Location::Query(p.range.clone()),
            )?;
        }
        crate::runtime_types::validate_declaration(
            &d.result.value,
            budget,
            &Location::Query(d.result.range.clone()),
        )?;
    }
    Ok(())
}
fn builtin(name: &str) -> bool {
    matches!(
        name,
        "queue"
            | "pop_front"
            | "push_back_all"
            | "identity_set"
            | "insert"
            | "fold"
            | "scan"
            | "one"
            | "occurs"
            | "absent"
            | "lookup"
            | "has_key"
            | "index_set"
            | "entries"
            | "zip_exact"
            | "contains"
            | "filter"
            | "fixpoint"
            | "where_exists"
            | "starts_with"
            | "ends_with"
            | "length"
            | "sum"
            | "forall"
            | "exists"
            | "sort"
            | "sort_by"
            | "min"
            | "max"
            | "min_by"
            | "max_by"
            | "group_by"
            | "require"
            | "project"
            | "match"
            | "paths"
            | "map_by"
            | "default"
            | "if"
    )
}

/// Execute constructed functions without a native host. The same runner powers
/// [`FunctionRequest`]; declarations do not capture surrounding bindings.
///
/// ```
/// use zirql::{Bindings, Budget, ConstructedValue as V, DeclaredType as D,
///     FunctionDeclaration, FunctionParameter, FunctionLimits, Located,
///     ProgramLimits, ValueExpression as E, ValueExpressionKind as K,
///     ValueBinaryOperator as B, evaluate_functions};
/// fn e(value: K) -> E { Located::new(value, 0..1) }
/// fn name(value: &str) -> E { e(K::Name(value.into())) }
/// fn int(value: i64) -> E { e(K::Literal(V::Integer(value))) }
/// fn op(operator: B, left: E, right: E) -> E {
///     e(K::Binary { operator, left: Box::new(left), right: Box::new(right) })
/// }
/// fn call(arguments: Vec<E>) -> E {
///     e(K::Call { function: Located::new("acc".into(), 0..1), arguments })
/// }
/// let parameters = ["n", "total"].map(|name| Located::new(
///     FunctionParameter { name: Located::new(name.into(), 0..1),
///                         declaration: D::Integer }, 0..1));
/// let functions = [FunctionDeclaration {
///     name: Located::new("acc".into(), 0..1),
///     parameters: Vec::from(parameters), result: Located::new(D::Integer, 0..1),
///     bindings: vec![],
///     value: e(K::Conditional {
///         branches: vec![(op(B::Equal, name("n"), int(0)), name("total"))],
///         otherwise: Box::new(call(vec![op(B::Subtract, name("n"), int(1)),
///                                      op(B::Add, name("total"), name("n"))])),
///     }),
/// }];
/// let mut budget = Budget::for_program(ProgramLimits {
///     work: 1_000_000, results: 100_000, nesting: 64, stream_items: 100,
/// });
/// let value = evaluate_functions(&functions, &call(vec![int(100), int(0)]),
///     &Bindings::default(), &mut budget, FunctionLimits { active_depth: 1 })?;
/// assert_eq!(value.data(), &V::Integer(5050));
/// # Ok::<(), zirql::FunctionError<zirql::QueryError>>(())
/// ```
///
/// # Errors
/// Preflight checks every body. Runtime contracts, active depth and request
/// allowances fail at the responsible expression and preserve spent work.
pub fn evaluate_functions(
    declarations: &[FunctionDeclaration],
    entry: &ValueExpression,
    bindings: &Bindings<ConstructedValue>,
    budget: &mut Budget,
    limits: FunctionLimits,
) -> Result<ConstructedValue, FunctionError<QueryError>> {
    register(
        declarations.iter().map(|d| d.as_borrowed().into()),
        budget,
        |_| false,
    )?;
    crate::value::run_functions(declarations, entry, bindings, budget, limits)
}

/// Execute pattern-capable constructed functions through the ordinary runner.
///
/// # Errors
/// Every declaration is preflighted. Whole argument admission precedes atomic
/// parameter matching; mismatches fail at the parameter pattern.
pub fn evaluate_pattern_functions(
    declarations: &[PatternFunctionDeclaration],
    entry: &ValueExpression,
    bindings: &Bindings<ConstructedValue>,
    budget: &mut Budget,
    limits: FunctionLimits,
) -> Result<ConstructedValue, FunctionError<QueryError>> {
    register(
        declarations
            .iter()
            .map(PatternFunctionDeclaration::as_borrowed),
        budget,
        |_| false,
    )?;
    let mut retained = Vec::new();
    for d in declarations {
        crate::projection::admit_slots::<DeclarationRef<'_, (), ()>>(1, budget, &d.name.range)?;
        retained.push(d.as_borrowed());
    }
    crate::value::run_function_refs(&retained, entry, bindings, budget, limits)
}

/// Missing concrete function hooks over the existing projection/admission APIs.
/// Existing hosts opt in only when they expose named functions.
pub trait FunctionHost<C>:
    ProjectionHost<C> + RuntimeTypeHost<C, Kind = <Self as ProjectionHost<C>>::Kind>
{
    /// Map an explicit signature to the host's existing preflight kinds.
    fn declaration_kind(
        &self,
        declaration: &DeclaredType<<Self as ProjectionHost<C>>::Kind>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<<Self as ProjectionHost<C>>::Kind, QueryError>;
    /// Recognize registered domain operation names, including effectful ones.
    fn is_operation_name(&self, name: &str) -> bool;

    /// Enumerate one eager positional native container in order, preserving
    /// native identity and coordinates. Reject keyed/non-positional storage and
    /// incompatible empty element metadata. Charge scans and output allocation.
    fn sequence_items(
        &self,
        _value: &Self::Value,
        _element: &DeclaredType<<Self as ProjectionHost<C>>::Kind>,
        _context: &mut C,
        _budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<Vec<Self::Value>, EvaluationError<Self::Error>> {
        Err(QueryError::query(range.clone(), "native positional sequences are unsupported").into())
    }

    /// Construct a positional sequence of immutable native scan snapshots.
    /// Preserve the supplied element contract even for empty output, retaining
    /// each value's identity/coordinates and charging host allocation.
    fn construct_sequence(
        &self,
        _values: Vec<Self::Value>,
        _element: &DeclaredType<<Self as ProjectionHost<C>>::Kind>,
        _context: &mut C,
        _budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<Self::Value, EvaluationError<Self::Error>> {
        Err(QueryError::query(range.clone(), "native scan construction is unsupported").into())
    }

    /// Opt into computational constructors during all-branch preparation.
    /// `None` defers element inference to selected actual input. A known
    /// declaration is checked before execution or public factory allocation.
    fn prepare_computational(
        &self,
        _declaration: Option<&DeclaredType<<Self as ProjectionHost<C>>::Kind>>,
        _budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<(), QueryError> {
        Err(QueryError::query(
            range.clone(),
            "computational values are unsupported",
        ))
    }
    /// Borrow an opt-in computational wrapper without exposing storage.
    fn computational_value<'v>(
        &self,
        _value: &'v Self::Value,
    ) -> Option<&'v crate::ComputationalValue<Self::Value, <Self as ProjectionHost<C>>::Kind>> {
        None
    }
    /// Wrap a computational result. Copying this wrapper must share roots.
    fn lift_computational(
        &self,
        _value: crate::ComputationalValue<Self::Value, <Self as ProjectionHost<C>>::Kind>,
        _context: &mut C,
        _budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<Self::Value, EvaluationError<Self::Error>> {
        Err(QueryError::query(range.clone(), "computational values are unsupported").into())
    }
    /// Construct an explicit native/mixed positional tuple, preserving owners.
    fn construct_tuple(
        &self,
        _values: Vec<Self::Value>,
        _context: &mut C,
        _budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<Self::Value, EvaluationError<Self::Error>> {
        Err(QueryError::query(range.clone(), "native tuple construction is unsupported").into())
    }
    /// Resolve a named constructor type in the current immutable request owner.
    fn resolve_type_name(
        &self,
        name: Located<&str>,
        _budget: &mut Budget,
    ) -> Result<DeclaredType<<Self as ProjectionHost<C>>::Kind>, QueryError> {
        Err(QueryError::query(
            name.range,
            "native type resolution is unsupported",
        ))
    }
    /// Identify the immutable owner/snapshot, including its validity stamp.
    /// Change this token whenever earlier native admission can become invalid.
    fn worklist_context(
        &self,
        _context: &mut C,
        _budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<crate::NativeContextId, EvaluationError<Self::Error>> {
        Err(QueryError::query(range.clone(), "computational values are unsupported").into())
    }
    /// Return an exact canonical identity agreeing with native semantic equality.
    /// Include owner, diff side and object; never substitute a hash or label.
    fn native_identity(
        &self,
        _value: &Self::Value,
        _expected: &<Self as ProjectionHost<C>>::Kind,
        _context: &mut C,
        _budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<crate::NativeIdentity, EvaluationError<Self::Error>> {
        Err(QueryError::query(range.clone(), "native identity is unsupported").into())
    }

    /// Successful native admission remains valid for an unchanged immutable
    /// value and equivalent contract throughout this request. Opt in only when
    /// ownership, coordinates, element contents and handle validity cannot
    /// change during execution. Fresh values still receive whole admission.
    /// Hosts with mutable native state retain admission at every boundary.
    fn retains_native_admission(&self) -> bool {
        false
    }
}
type Kind<C, H> = <H as ProjectionHost<C>>::Kind;
type Query<C, H> = NativeExpression<C, H>;
type HostValue<'a, C, H> = Value<'a, <H as ProgramHost<C>>::Value, Kind<C, H>>;
type Bodies<'a, C, H> = [Body<'a, Query<C, H>, Kind<C, H>>];
type Declaration<C, H> = FunctionDeclaration<Query<C, H>, Kind<C, H>>;
type PatternDeclaration<C, H> = PatternFunctionDeclaration<Query<C, H>, Kind<C, H>>;
struct LexicalKinds<K> {
    scope: BTreeMap<String, K>,
    generators: BTreeMap<String, K>,
    contracts: BTreeMap<String, DeclaredType<K>>,
}
struct Operand<K> {
    native: crate::projection::prepared::PreparedNative,
    names: Vec<String>,
    kind: K,
    argument_kinds: BTreeMap<usize, K>,
}
struct Preflight<'h, 'a, C, H: FunctionHost<C>> {
    host: &'h H,
    declarations: Vec<DeclarationRef<'a, Query<C, H>, Kind<C, H>>>,
    scope: BTreeMap<String, Kind<C, H>>,
    generator_kinds: BTreeMap<String, Kind<C, H>>,
    relative: Option<Kind<C, H>>,
    prepared: BTreeMap<usize, Operand<Kind<C, H>>>,
    scopes: Vec<LexicalKinds<Kind<C, H>>>,
    contracts: BTreeMap<String, DeclaredType<Kind<C, H>>>,
    worklists: BTreeMap<usize, Option<DeclaredType<Kind<C, H>>>>,
    worklist_contracts: Vec<Option<DeclaredType<Kind<C, H>>>>,
}
impl<'h, 'a, C, H: FunctionHost<C>> Preflight<'h, 'a, C, H> {
    fn new(
        declarations: impl IntoIterator<Item = DeclarationRef<'a, Query<C, H>, Kind<C, H>>>,
        host: &'h H,
        budget: &mut Budget,
    ) -> Result<Self, QueryError> {
        let mut retained = Vec::new();
        for declaration in declarations {
            crate::projection::admit_slots::<DeclarationRef<'_, Query<C, H>, Kind<C, H>>>(
                1,
                budget,
                &declaration.name.range,
            )?;
            retained.push(declaration);
        }
        register(retained.iter().copied(), budget, |name| {
            host.is_operation_name(name)
        })?;
        Ok(Self {
            host,
            declarations: retained,
            scope: BTreeMap::new(),
            generator_kinds: BTreeMap::new(),
            relative: None,
            prepared: BTreeMap::new(),
            scopes: Vec::new(),
            contracts: BTreeMap::new(),
            worklists: BTreeMap::new(),
            worklist_contracts: Vec::new(),
        })
    }
}

/// Discover one value's kind from pattern declarations and outer kinds.
/// This registers and checks signatures, then uses ordinary common preflight for
/// the value, including lexical patterns and native arguments. It does not prepare
/// declaration bodies, so hosts can call it from a kind callback while complete
/// function preparation is already active.
///
/// Before executing a request, separately call [`PreparedFunctions::prepare_patterns`]
/// (or its borrowed-header counterpart) to check every body, including unused ones.
/// This query alone does not establish body purity or authorize execution.
///
/// # Errors
/// Invalid signatures, value scope/effects, host operations and limits are located.
pub fn pattern_function_value_kind<'a, C, H: FunctionHost<C>>(
    declarations: impl IntoIterator<Item = &'a PatternFunctionDeclaration<Query<C, H>, Kind<C, H>>>,
    host: &H,
    value: &ValueExpression<Query<C, H>>,
    scope: &BTreeMap<String, Kind<C, H>>,
    relative: Option<Kind<C, H>>,
    budget: &mut Budget,
) -> Result<Kind<C, H>, QueryError>
where
    Query<C, H>: 'a,
    Kind<C, H>: 'a,
{
    Preflight::new(
        declarations
            .into_iter()
            .map(PatternFunctionDeclaration::as_borrowed),
        host,
        budget,
    )?
    .entry_kind(value, scope, relative, budget)
}

/// Discover one value's kind from request-resolved borrowed pattern headers.
///
/// Like [`pattern_function_value_kind`], this checks signatures and the selected
/// value without preparing declaration bodies. Hosts can call it from a native
/// kind callback using their existing resolved headers and borrowed body trees.
/// Before execution, separately check every body with
/// [`PreparedFunctions::prepare_patterns_borrowed`], including unused declarations.
///
/// # Errors
/// Invalid signatures, value scope/effects, host operations and limits are located.
pub fn pattern_function_value_kind_borrowed<'a, C, H: FunctionHost<C>>(
    declarations: impl IntoIterator<Item = PatternFunctionDeclarationRef<'a, Query<C, H>, Kind<C, H>>>,
    host: &H,
    value: &ValueExpression<Query<C, H>>,
    scope: &BTreeMap<String, Kind<C, H>>,
    relative: Option<Kind<C, H>>,
    budget: &mut Budget,
) -> Result<Kind<C, H>, QueryError>
where
    Query<C, H>: 'a,
    Kind<C, H>: 'a,
{
    Preflight::new(
        declarations.into_iter().map(DeclarationRef::from),
        host,
        budget,
    )?
    .entry_kind(value, scope, relative, budget)
}

impl<C, H: FunctionHost<C>> Preflight<'_, '_, C, H> {
    fn native(
        &mut self,
        query: &Query<C, H>,
        locals: &[(&str, Vec<ValueType>)],
        budget: &mut Budget,
        projected: bool,
    ) -> Result<Vec<ValueType>, QueryError> {
        let mut scope = crate::projection::copy_scope::<C, H>(&self.scope, budget, &query.range)?;
        for (name, types) in locals {
            if !scope.contains_key(*name) {
                budget.charge(name.len() + 1, Location::Query(query.range.clone()))?;
                scope.insert(
                    (*name).to_owned(),
                    match self.generator_kinds.get(*name) {
                        Some(kind) => kind.clone(),
                        None => self.host.constructed_kind(copy_value_types(
                            types,
                            budget,
                            Location::Query(query.range.clone()),
                        )?),
                    },
                );
            }
        }
        if self.relative.is_none() {
            no_ambient_input::<C, H>(query, self.host, budget)?;
        }
        let input = self
            .relative
            .clone()
            .unwrap_or_else(|| self.host.constructed_kind(vec![ValueType::Unestablished]));
        let kind = native_expression_kind(query, self.host, &input, &scope, budget)?;
        crate::projection::admit_slots::<String>(scope.len(), budget, &query.range)?;
        let names = scope.keys().map(String::as_str).collect::<Vec<_>>();
        let native = crate::projection::prepared::PreparedNative::resolve::<C, H>(
            query,
            self.host,
            &names,
            None,
            &[],
            budget,
        )?;
        let names = scope
            .keys()
            .map(|name| {
                budget.charge(name.len(), Location::Query(query.range.clone()))?;
                Ok(name.clone())
            })
            .collect::<Result<_, QueryError>>()?;
        budget.charge(1, Location::Query(query.range.clone()))?;
        self.prepared.insert(
            query as *const _ as usize,
            Operand {
                native,
                names,
                kind: kind.clone(),
                argument_kinds: BTreeMap::new(),
            },
        );
        let arguments =
            crate::projection::scoped_arguments::<C, H>(query, self.host, &input, &scope, budget)?;
        let mut argument_kinds = BTreeMap::new();
        for argument in arguments {
            let saved = std::mem::replace(
                &mut self.scope,
                crate::projection::copy_scope::<C, H>(&scope, budget, &query.range)?,
            );
            for (name, kind) in argument.locals {
                budget_name(&name.value, budget, &name.range)?;
                if self.scope.insert(name.value, kind).is_some() {
                    return Err(QueryError::query(name.range, "binding is already defined"));
                }
            }
            let old = std::mem::replace(&mut self.relative, argument.relative);
            let mut facts = BTreeMap::new();
            for (name, kind) in &self.scope {
                budget.charge(name.len() + 1, Location::Query(query.range.clone()))?;
                facts.insert(
                    name.clone(),
                    self.host
                        .scalar_types(kind, budget, &query.range)?
                        .unwrap_or_else(|| vec![ValueType::Unestablished]),
                );
            }
            let result = (|| {
                let types = query_value_types(argument.expression, &facts, self, budget)?;
                let kind = self
                    .local_kind(argument.expression, budget)?
                    .unwrap_or_else(|| self.host.constructed_kind(types));
                crate::projection::admit_slots::<(usize, Kind<C, H>)>(
                    1,
                    budget,
                    &argument.expression.range,
                )?;
                argument_kinds.insert(argument.expression as *const _ as usize, kind);
                Ok::<_, QueryError>(())
            })();
            self.scope = saved;
            self.relative = old;
            result?;
        }
        self.prepared
            .get_mut(&(query as *const _ as usize))
            .expect("prepared native operand")
            .argument_kinds = argument_kinds;
        match self.host.scalar_types(&kind, budget, &query.range)? {
            Some(types) => Ok(types),
            None if !projected => Ok(vec![ValueType::Unestablished]),
            None => Err(QueryError::query(
                query.range.clone(),
                "native handles require an explicit scalar projection",
            )),
        }
    }
}
impl<C, H: FunctionHost<C>> Preflight<'_, '_, C, H> {
    fn entry_kind(
        &mut self,
        entry: &ValueExpression<Query<C, H>>,
        scope: &BTreeMap<String, Kind<C, H>>,
        relative: Option<Kind<C, H>>,
        budget: &mut Budget,
    ) -> Result<Kind<C, H>, QueryError> {
        self.scope = crate::projection::copy_scope::<C, H>(scope, budget, &entry.range)?;
        self.relative = relative;
        self.generator_kinds.clear();
        self.contracts.clear();
        self.worklists.clear();
        let mut facts = BTreeMap::new();
        for (name, kind) in scope {
            budget_name(name, budget, &entry.range)?;
            facts.insert(
                name.clone(),
                self.host
                    .scalar_types(kind, budget, &entry.range)?
                    .unwrap_or_else(|| vec![ValueType::Unestablished]),
            );
        }
        let types = query_value_types(entry, &facts, self, budget)?;
        Ok(match self.local_kind(entry, budget)? {
            Some(kind) => kind,
            None => self.host.constructed_kind(types),
        })
    }

    fn expect(
        &mut self,
        value: &ValueExpression<Query<C, H>>,
        expected: &DeclaredType<Kind<C, H>>,
        budget: &mut Budget,
    ) -> Result<(), QueryError> {
        let location = Location::Query(value.range.clone());
        budget.within_evaluation(1, location.clone(), |budget| {
            budget.charge(1, location.clone())?;
            let mut d = expected;
            while let DeclaredType::Optional(c) = d {
                d = c;
            }
            match &value.value {
                ValueExpressionKind::Queue { .. } if matches!(d, DeclaredType::Queue(_)) => {
                    let id = value as *const _ as usize;
                    if let Some(Some(old)) = self.worklists.get(&id) {
                        if !crate::runtime_types::same_declaration(old, d, budget, &location)? {
                            return Err(QueryError::query(
                                value.range.clone(),
                                "incompatible queue contexts",
                            ));
                        }
                    } else {
                        self.worklists.insert(
                            id,
                            Some(crate::runtime_types::copy_declaration(
                                d, budget, &location,
                            )?),
                        );
                    }
                }
                ValueExpressionKind::Conditional {
                    branches,
                    otherwise,
                } => {
                    for (_, v) in branches {
                        self.expect(v, expected, budget)?;
                    }
                    self.expect(otherwise, expected, budget)?;
                }
                ValueExpressionKind::Block { value, .. }
                | ValueExpressionKind::Require { value, .. }
                | ValueExpressionKind::Break(value) => self.expect(value, expected, budget)?,
                ValueExpressionKind::ValueMatch { arms, .. } => {
                    for arm in arms {
                        self.expect(&arm.value, expected, budget)?;
                    }
                }
                ValueExpressionKind::Default { value, fallback } => {
                    self.expect(value, expected, budget)?;
                    self.expect(fallback, expected, budget)?;
                }
                ValueExpressionKind::Tuple(values) => {
                    if let DeclaredType::Tuple(types) = d {
                        for (v, d) in values.iter().zip(types) {
                            self.expect(v, d, budget)?;
                        }
                    }
                }
                ValueExpressionKind::Array(values) => {
                    if let DeclaredType::Array(d) | DeclaredType::Sequence(d) = d {
                        for v in values {
                            self.expect(v, d, budget)?;
                        }
                    }
                }
                ValueExpressionKind::Loop { body, .. } => self.expect(body, expected, budget)?,
                _ => {}
            }
            Ok(())
        })
    }
    fn expect_next(
        &mut self,
        value: &ValueExpression<Query<C, H>>,
        states: &[Option<DeclaredType<Kind<C, H>>>],
        budget: &mut Budget,
    ) -> Result<(), QueryError> {
        budget.within_evaluation(1, Location::Query(value.range.clone()), |budget| {
            budget.charge(1, Location::Query(value.range.clone()))?;
            match &value.value {
                ValueExpressionKind::Continue(values) => {
                    for (v, d) in values.iter().zip(states) {
                        if let Some(d) = d {
                            self.expect(v, d, budget)?;
                        }
                    }
                }
                ValueExpressionKind::Block { value, .. } => {
                    self.expect_next(value, states, budget)?
                }
                ValueExpressionKind::Conditional {
                    branches,
                    otherwise,
                } => {
                    for (_, v) in branches {
                        self.expect_next(v, states, budget)?;
                    }
                    self.expect_next(otherwise, states, budget)?;
                }
                ValueExpressionKind::ValueMatch { arms, .. } => {
                    for arm in arms {
                        self.expect_next(&arm.value, states, budget)?;
                    }
                }
                _ => {}
            }
            Ok(())
        })
    }
    fn value_declaration(
        &mut self,
        value: &ValueExpression<Query<C, H>>,
        budget: &mut Budget,
    ) -> Result<Option<DeclaredType<Kind<C, H>>>, QueryError> {
        let location = Location::Query(value.range.clone());
        budget.within_evaluation(1, location.clone(), |budget| {
            budget.charge(1, location.clone())?;
            Ok(match &value.value {
                ValueExpressionKind::Queue { .. } | ValueExpressionKind::IdentitySet { .. } => self
                    .worklists
                    .get(&(value as *const _ as usize))
                    .and_then(Option::as_ref)
                    .map(|d| crate::runtime_types::copy_declaration(d, budget, &location))
                    .transpose()?,
                ValueExpressionKind::PushBackAll { queue, .. } => {
                    self.value_declaration(queue, budget)?
                }
                ValueExpressionKind::Insert { set, .. } => self.value_declaration(set, budget)?,
                ValueExpressionKind::PopFront(queue) => match self
                    .value_declaration(queue, budget)?
                {
                    Some(DeclaredType::Queue(element)) => {
                        let queue = DeclaredType::Queue(Box::new(
                            crate::runtime_types::copy_declaration(&element, budget, &location)?,
                        ));
                        Some(DeclaredType::Optional(Box::new(DeclaredType::Tuple(vec![
                            *element, queue,
                        ]))))
                    }
                    _ => None,
                },
                ValueExpressionKind::Call { function, .. } => {
                    let (id, _) = self.function(function, budget)?;
                    Some(crate::runtime_types::copy_declaration(
                        &self.declarations[id].result.value,
                        budget,
                        &location,
                    )?)
                }
                ValueExpressionKind::PredicateSubject => self
                    .scope
                    .get(crate::value::PREDICATE_SUBJECT)
                    .or_else(|| self.generator_kinds.get(crate::value::PREDICATE_SUBJECT))
                    .cloned()
                    .map(DeclaredType::Native),
                ValueExpressionKind::Name(name) => match self.contracts.get(name) {
                    Some(d) => Some(crate::runtime_types::copy_declaration(
                        d, budget, &location,
                    )?),
                    None => self
                        .scope
                        .get(name)
                        .or_else(|| self.generator_kinds.get(name))
                        .cloned()
                        .map(DeclaredType::Native),
                },
                ValueExpressionKind::NativeValue(q) => self
                    .prepared
                    .get(&(q.as_ref() as *const _ as usize))
                    .map(|p| DeclaredType::Native(p.kind.clone())),
                ValueExpressionKind::Literal(v) => crate::worklists::scalar_contract(v),
                ValueExpressionKind::Array(values) => match values.first() {
                    Some(v) => self
                        .value_declaration(v, budget)?
                        .map(|d| DeclaredType::Sequence(Box::new(d))),
                    None => None,
                },
                ValueExpressionKind::Tuple(values) => {
                    let mut types = Vec::new();
                    for v in values {
                        if let Some(d) = self.value_declaration(v, budget)? {
                            crate::projection::admit_slots::<DeclaredType<Kind<C, H>>>(
                                1,
                                budget,
                                &value.range,
                            )?;
                            types.push(d);
                        } else {
                            return Ok(None);
                        }
                    }
                    Some(DeclaredType::Tuple(types))
                }
                _ => self.local_kind(value, budget)?.map(DeclaredType::Native),
            })
        })
    }

    // Retain already-known native kinds through the same selected-value forms.
    // Unknown scalar/collection facts continue through ordinary value analysis.
    fn pattern_kind(
        &mut self,
        pattern: PatternRef<'_>,
        kind: Option<Kind<C, H>>,
        declaration: Option<&DeclaredType<Kind<C, H>>>,
        budget: &mut Budget,
    ) -> Result<(), QueryError> {
        let range = pattern.range();
        budget.within_evaluation(1, Location::Query(range.clone()), |budget| {
            budget.charge(1, Location::Query(range.clone()))?;
            let node = match pattern {
                PatternRef::Name(name) => {
                    if let Some(kind) = kind {
                        budget_name(&name.value, budget, &name.range)?;
                        self.scope.insert(name.value.clone(), kind);
                        if let Some(d) = declaration {
                            self.contracts.insert(
                                name.value.clone(),
                                crate::runtime_types::copy_declaration(
                                    d,
                                    budget,
                                    &Location::Query(range.clone()),
                                )?,
                            );
                        }
                    }
                    return Ok(());
                }
                PatternRef::Pattern(p) => &p.value,
            };
            match node {
                crate::PatternKind::Name(name) => {
                    if let Some(kind) = kind {
                        budget_name(&name.value, budget, &name.range)?;
                        self.scope.insert(name.value.clone(), kind);
                        if let Some(d) = declaration {
                            self.contracts.insert(
                                name.value.clone(),
                                crate::runtime_types::copy_declaration(
                                    d,
                                    budget,
                                    &Location::Query(range.clone()),
                                )?,
                            );
                        }
                    }
                }
                crate::PatternKind::Present(child) => {
                    let declaration = match declaration {
                        Some(DeclaredType::Optional(child)) => Some(child.as_ref()),
                        other => other,
                    };
                    let kind = if let Some(declaration) = declaration {
                        Some(self.host.declaration_kind(declaration, budget, range)?)
                    } else if let Some(kind) = kind {
                        // Native callbacks must see the same presence facts as
                        // the lexical value walker. Opaque native kinds retain
                        // their identity without a scalar projection.
                        Some(match self.host.scalar_types(&kind, budget, range)? {
                            Some(types) => {
                                self.host
                                    .constructed_kind(crate::value::pattern::present_types(
                                        &types,
                                        budget,
                                        &Location::Query(range.clone()),
                                    )?)
                            }
                            None => kind,
                        })
                    } else {
                        None
                    };
                    self.pattern_kind(PatternRef::Pattern(child), kind, declaration, budget)?;
                }
                crate::PatternKind::Tuple(children) => {
                    let declaration = declaration.map(|mut d| {
                        while let DeclaredType::Optional(child) = d {
                            d = child;
                        }
                        d
                    });
                    for (index, child) in children.iter().enumerate() {
                        let d = match declaration {
                            Some(DeclaredType::Tuple(v)) => v.get(index),
                            _ => None,
                        };
                        let k = match d {
                            Some(d) => Some(self.host.declaration_kind(d, budget, range)?),
                            None => kind
                                .as_ref()
                                .and_then(|k| self.host.tuple_view_kind(k))
                                .and_then(|v| v.get(index))
                                .cloned(),
                        };
                        self.pattern_kind(PatternRef::Pattern(child), k, d, budget)?;
                    }
                }
                crate::PatternKind::List { elements, .. } => {
                    let declaration = declaration.map(|mut d| {
                        while let DeclaredType::Optional(child) = d {
                            d = child;
                        }
                        d
                    });
                    for child in elements {
                        let d = match declaration {
                            Some(DeclaredType::Array(d) | DeclaredType::Sequence(d)) => {
                                Some(d.as_ref())
                            }
                            _ => None,
                        };
                        let k = match d {
                            Some(d) => Some(self.host.declaration_kind(d, budget, range)?),
                            None => match kind.as_ref() {
                                Some(k) => self.host.positional_view_kind(k, budget, range)?,
                                None => None,
                            },
                        };
                        self.pattern_kind(PatternRef::Pattern(child), k, d, budget)?;
                    }
                }
                crate::PatternKind::Record { fields, .. } => {
                    let declaration = declaration.map(|mut d| {
                        while let DeclaredType::Optional(child) = d {
                            d = child;
                        }
                        d
                    });
                    for (label, child) in fields {
                        let d = match declaration {
                            Some(DeclaredType::Record(v)) => {
                                let mut found = None;
                                for (name, d) in v {
                                    budget.charge(
                                        1 + name.len().min(label.value.len()),
                                        Location::Query(label.range.clone()),
                                    )?;
                                    if name == &label.value {
                                        found = Some(d);
                                        break;
                                    }
                                }
                                found
                            }
                            _ => None,
                        };
                        let k = if let Some(d) = d {
                            Some(self.host.declaration_kind(d, budget, &label.range)?)
                        } else {
                            let mut found = None;
                            if let Some(fields) =
                                kind.as_ref().and_then(|k| self.host.capture_record_kind(k))
                            {
                                for (name, k) in &fields.fields {
                                    budget.charge(
                                        1 + name.len().min(label.value.len()),
                                        Location::Query(label.range.clone()),
                                    )?;
                                    if name == &label.value {
                                        found = Some(k.clone());
                                        break;
                                    }
                                }
                            }
                            found
                        };
                        self.pattern_kind(PatternRef::Pattern(child), k, d, budget)?;
                    }
                }
                crate::PatternKind::Wildcard
                | crate::PatternKind::Literal(_)
                | crate::PatternKind::Absent => {}
            }
            Ok(())
        })
    }

    // The outer Option distinguishes no break (continue) from a constructed
    // break result. Nested loops are ordinary values, never outer exits.
    fn loop_kind(
        &mut self,
        value: &ValueExpression<Query<C, H>>,
        budget: &mut Budget,
    ) -> Result<Option<Option<Kind<C, H>>>, QueryError> {
        budget.within_evaluation(1, Location::Query(value.range.clone()), |budget| {
            budget.charge(1, Location::Query(value.range.clone()))?;
            match &value.value {
                ValueExpressionKind::Break(value) => Ok(Some(self.local_kind(value, budget)?)),
                ValueExpressionKind::Continue(_) => Ok(None),
                ValueExpressionKind::Block { bindings, value } => {
                    self.enter_scope(budget, &value.range)?;
                    let result = (|| {
                        for (pattern, source) in bindings {
                            let kind = self.local_kind(source, budget)?;
                            self.pattern_kind(PatternRef::Pattern(pattern), kind, None, budget)?;
                        }
                        self.loop_kind(value, budget)
                    })();
                    self.leave_scope();
                    result
                }
                ValueExpressionKind::Conditional {
                    branches,
                    otherwise,
                } => {
                    let mut kind = self.loop_kind(otherwise, budget)?;
                    for (_, branch) in branches {
                        if let Some(next) = self.loop_kind(branch, budget)? {
                            if kind.as_ref().is_some_and(|previous| *previous != next) {
                                return Ok(Some(None));
                            }
                            kind = Some(next);
                        }
                    }
                    Ok(kind)
                }
                ValueExpressionKind::ValueMatch { subject, arms } => {
                    let subject = self.local_kind(subject, budget)?;
                    let mut kind = None;
                    for arm in arms {
                        self.enter_scope(budget, &arm.pattern.range)?;
                        let result = (|| {
                            self.pattern_kind(
                                PatternRef::Pattern(&arm.pattern),
                                subject.clone(),
                                None,
                                budget,
                            )?;
                            self.loop_kind(&arm.value, budget)
                        })();
                        self.leave_scope();
                        if let Some(next) = result? {
                            if kind.as_ref().is_some_and(|previous| *previous != next) {
                                return Ok(Some(None));
                            }
                            kind = Some(next);
                        }
                    }
                    Ok(kind)
                }
                _ => Ok(None), // Structural preparation reports a missing terminal transfer.
            }
        })
    }

    fn local_kind(
        &mut self,
        value: &ValueExpression<Query<C, H>>,
        budget: &mut Budget,
    ) -> Result<Option<Kind<C, H>>, QueryError> {
        budget.within_evaluation(1, Location::Query(value.range.clone()), |budget| {
            budget.charge(1, Location::Query(value.range.clone()))?;
            Ok(match &value.value {
                ValueExpressionKind::Queue { .. }
                | ValueExpressionKind::IdentitySet { .. }
                | ValueExpressionKind::PopFront(_)
                | ValueExpressionKind::PushBackAll { .. }
                | ValueExpressionKind::Insert { .. }
                | ValueExpressionKind::Array(_)
                | ValueExpressionKind::Tuple(_) => match self.value_declaration(value, budget)? {
                    Some(d)
                        if crate::runtime_types::contains_native(
                            &d,
                            budget,
                            &Location::Query(value.range.clone()),
                        )? =>
                    {
                        Some(self.host.declaration_kind(&d, budget, &value.range)?)
                    }
                    _ => None,
                },
                ValueExpressionKind::Call { function, .. } => {
                    let (id, _) = self.function(function, budget)?;
                    Some(self.host.declaration_kind(
                        &self.declarations[id].result.value,
                        budget,
                        &value.range,
                    )?)
                }
                ValueExpressionKind::Fold { step, .. } => {
                    let (id, _) = self.function(step, budget)?;
                    let state = accumulator_state(&self.declarations[id], step, budget)?;
                    Some(self.host.declaration_kind(state, budget, &value.range)?)
                }
                ValueExpressionKind::Scan { step, .. } => {
                    let (id, _) = self.function(step, budget)?;
                    let state = accumulator_state(&self.declarations[id], step, budget)?;
                    let sequence =
                        DeclaredType::Sequence(Box::new(crate::runtime_types::copy_declaration(
                            state,
                            budget,
                            &Location::Query(value.range.clone()),
                        )?));
                    Some(
                        self.host
                            .declaration_kind(&sequence, budget, &value.range)?,
                    )
                }
                ValueExpressionKind::NativeValue(query) => Some(
                    self.prepared
                        .get(&(query.as_ref() as *const _ as usize))
                        .expect("prepared native let")
                        .kind
                        .clone(),
                ),
                ValueExpressionKind::PredicateSubject => self
                    .scope
                    .get(crate::value::PREDICATE_SUBJECT)
                    .or_else(|| self.generator_kinds.get(crate::value::PREDICATE_SUBJECT))
                    .cloned(),
                ValueExpressionKind::Name(name) => self
                    .scope
                    .get(name)
                    .or_else(|| self.generator_kinds.get(name))
                    .cloned(),
                ValueExpressionKind::SubjectScope { subject, argument } => {
                    let kind = self.local_kind(subject, budget)?;
                    self.enter_scope(budget, &value.range)?;
                    let result = (|| {
                        let internal = crate::value::PREDICATE_SUBJECT;
                        self.scope.remove(internal);
                        self.generator_kinds.remove(internal);
                        self.contracts.remove(internal);
                        if let Some(kind) = &kind {
                            budget_name(internal, budget, &subject.range)?;
                            self.scope.insert(internal.to_owned(), kind.clone());
                        }
                        if let Some(pattern) = &argument.argument {
                            self.pattern_kind(PatternRef::Pattern(pattern), kind, None, budget)?;
                        }
                        self.local_kind(&argument.body, budget)
                    })();
                    self.leave_scope();
                    result?
                }
                ValueExpressionKind::Field { value, field } => {
                    match self.local_kind(value, budget)? {
                        Some(kind) => self
                            .host
                            .capture_record_kind(&kind)
                            .map(|record| record.get(field, budget).cloned())
                            .transpose()?,
                        None => None,
                    }
                }
                ValueExpressionKind::Loop { states, body } => {
                    crate::projection::admit_slots::<Option<Kind<C, H>>>(
                        states.len(),
                        budget,
                        &value.range,
                    )?;
                    let mut kinds = Vec::with_capacity(states.len());
                    for (_, value) in states {
                        kinds.push(self.local_kind(value, budget)?);
                    }
                    self.enter_scope(budget, &value.range)?;
                    let result = (|| {
                        for ((name, _), kind) in states.iter().zip(kinds) {
                            if let Some(kind) = kind {
                                budget.charge(
                                    name.value.len() + 1,
                                    Location::Query(name.range.clone()),
                                )?;
                                self.scope.insert(name.value.clone(), kind);
                            }
                        }
                        self.loop_kind(body, budget)
                    })();
                    self.leave_scope();
                    result?.flatten()
                }
                ValueExpressionKind::Break(value) => self.local_kind(value, budget)?,
                ValueExpressionKind::Block { bindings, value } => {
                    self.enter_scope(budget, &value.range)?;
                    let result = (|| {
                        for (pattern, source) in bindings {
                            let kind = self.local_kind(source, budget)?;
                            self.pattern_kind(PatternRef::Pattern(pattern), kind, None, budget)?;
                        }
                        self.local_kind(value, budget)
                    })();
                    self.leave_scope();
                    result?
                }
                ValueExpressionKind::ValueMatch { subject, arms } => {
                    let subject = self.local_kind(subject, budget)?;
                    let mut selected = None;
                    for (index, arm) in arms.iter().enumerate() {
                        self.enter_scope(budget, &arm.pattern.range)?;
                        let result = (|| {
                            self.pattern_kind(
                                PatternRef::Pattern(&arm.pattern),
                                subject.clone(),
                                None,
                                budget,
                            )?;
                            self.local_kind(&arm.value, budget)
                        })();
                        self.leave_scope();
                        let kind = result?;
                        if index > 0 && selected != kind {
                            return Ok(None);
                        }
                        selected = kind;
                    }
                    selected
                }
                ValueExpressionKind::Require { value, .. } => self.local_kind(value, budget)?,
                ValueExpressionKind::Conditional {
                    branches,
                    otherwise,
                } => {
                    let kind = self.local_kind(otherwise, budget)?;
                    for (_, value) in branches {
                        if self.local_kind(value, budget)? != kind {
                            return Ok(None);
                        }
                    }
                    kind
                }
                ValueExpressionKind::Default { value, fallback } => {
                    let right = self.local_kind(fallback, budget)?;
                    if matches!(
                        value.value,
                        ValueExpressionKind::Literal(ConstructedValue::Absent)
                    ) || self.local_kind(value, budget)? == right
                    {
                        right
                    } else {
                        None
                    }
                }
                _ => None,
            })
        })
    }
}

fn no_ambient_input<C, H: ProjectionHost<C>>(
    query: &Query<C, H>,
    host: &H,
    budget: &mut Budget,
) -> Result<(), QueryError> {
    let mut pending = vec![query];
    while let Some(query) = pending.pop() {
        budget.charge(1, Location::Query(query.range.clone()))?;
        let count = match &query.value {
            ExpressionKind::Set { .. } => 2,
            ExpressionKind::Record(fields) => fields.len(),
            ExpressionKind::Binding(_) | ExpressionKind::Input => 0,
            _ => 1,
        };
        crate::projection::admit_slots::<&Query<C, H>>(count, budget, &query.range)?;
        match &query.value {
            ExpressionKind::Input => {
                return Err(QueryError::query(
                    query.range.clone(),
                    "functions require explicit native inputs",
                ));
            }
            ExpressionKind::Group(value) | ExpressionKind::Field { value, .. } => {
                pending.push(value)
            }
            ExpressionKind::Sequence { input, steps } => {
                let explicit = steps.first().is_some_and(|step| match &step.value {
                    crate::ExpressionStep::Stage(stage) => host.is_explicit_source(stage),
                    crate::ExpressionStep::Emit { .. } => false,
                });
                if !explicit {
                    pending.push(input);
                }
            }
            ExpressionKind::Set { left, right, .. } => {
                pending.push(right);
                pending.push(left);
            }
            ExpressionKind::Record(fields) => pending.extend(fields.iter().map(|(_, v)| v)),
            ExpressionKind::Binding(_) => {}
        }
    }
    Ok(())
}
impl<C, H: FunctionHost<C>> ValueQueryHost<Query<C, H>> for Preflight<'_, '_, C, H> {
    type Error = EvaluationError<H::Error>;
    fn prepare_computation(
        &mut self,
        expression: &ValueExpression<Query<C, H>>,
        budget: &mut Budget,
    ) -> Result<(), QueryError> {
        match &expression.value {
            ValueExpressionKind::Call {
                function,
                arguments,
            } => {
                let (id, _) = self.function(function, budget)?;
                for (v, p) in arguments
                    .iter()
                    .zip(self.declarations[id].parameters.iter())
                {
                    self.expect(v, p.declaration, budget)?;
                }
            }
            ValueExpressionKind::Fold { initial, step, .. }
            | ValueExpressionKind::Scan { initial, step, .. } => {
                let (id, _) = self.function(step, budget)?;
                let d = accumulator_state(&self.declarations[id], step, budget)?;
                self.expect(initial, d, budget)?;
            }
            ValueExpressionKind::Loop { states, body } => {
                let mut types = Vec::new();
                for (_, v) in states {
                    crate::projection::admit_slots::<Option<DeclaredType<Kind<C, H>>>>(
                        1,
                        budget,
                        &expression.range,
                    )?;
                    types.push(self.value_declaration(v, budget)?);
                }
                self.expect_next(body, &types, budget)?;
            }
            _ => {}
        }
        Ok(())
    }
    fn worklist_id(
        &mut self,
        expression: &ValueExpression<Query<C, H>>,
        budget: &mut Budget,
    ) -> Result<usize, QueryError> {
        let d = self
            .worklists
            .get(&(expression as *const _ as usize))
            .expect("resolved worklist constructor");
        let d = d
            .as_ref()
            .map(|d| {
                crate::runtime_types::copy_declaration(
                    d,
                    budget,
                    &Location::Query(expression.range.clone()),
                )
            })
            .transpose()?;
        crate::projection::admit_slots::<Option<DeclaredType<Kind<C, H>>>>(
            1,
            budget,
            &expression.range,
        )?;
        let id = self.worklist_contracts.len();
        self.worklist_contracts.push(d);
        Ok(id)
    }
    fn worklist_types(
        &mut self,
        expression: &ValueExpression<Query<C, H>>,
        budget: &mut Budget,
    ) -> Result<Vec<ValueType>, QueryError> {
        let id = expression as *const _ as usize;
        let location = Location::Query(expression.range.clone());
        let declaration = match &expression.value {
            ValueExpressionKind::Queue { items, element } => {
                let explicit = element
                    .as_ref()
                    .map(|t| {
                        t.value.resolve(budget, &t.range, &mut |name, b| {
                            self.host.resolve_type_name(name, b)
                        })
                    })
                    .transpose()?;
                let contextual = match self.worklists.get(&id) {
                    Some(Some(DeclaredType::Queue(d))) => Some(
                        crate::runtime_types::copy_declaration(d, budget, &location)?,
                    ),
                    _ => None,
                };
                if let (Some(a), Some(b)) = (&explicit, &contextual)
                    && !crate::runtime_types::same_declaration(a, b, budget, &location)?
                {
                    return Err(QueryError::query(
                        expression.range.clone(),
                        "incompatible queue element declaration",
                    ));
                }
                let element = match explicit.or(contextual) {
                    Some(d) => Some(d),
                    None => match self.value_declaration(items, budget)? {
                        Some(DeclaredType::Sequence(d) | DeclaredType::Array(d)) => Some(*d),
                        Some(DeclaredType::Native(k))
                            if self.host.scalar_types(&k, budget, &items.range)?.is_none() =>
                        {
                            Some(DeclaredType::Native(self.host.subject_kind(
                                &k,
                                budget,
                                &items.range,
                            )?))
                        }
                        _ => None,
                    },
                };
                if element.is_none()
                    && matches!(&items.value, ValueExpressionKind::Array(v) if v.is_empty())
                {
                    return Err(QueryError::query(
                        expression.range.clone(),
                        "empty queue needs an explicit or contextual element contract",
                    ));
                }
                element.map(|d| DeclaredType::Queue(Box::new(d)))
            }
            ValueExpressionKind::IdentitySet { element } => Some(
                match element
                    .value
                    .resolve(budget, &element.range, &mut |name, b| {
                        self.host.resolve_type_name(name, b)
                    })? {
                    DeclaredType::Native(k) => DeclaredType::IdentitySet(k),
                    _ => {
                        return Err(QueryError::query(
                            element.range.clone(),
                            "identity_set requires a native element type",
                        ));
                    }
                },
            ),
            _ => return Ok(vec![ValueType::Unestablished]),
        };
        if let Some(d) = &declaration {
            crate::runtime_types::validate_declaration(d, budget, &location)?;
        }
        self.host
            .prepare_computational(declaration.as_ref(), budget, &expression.range)?;
        crate::projection::admit_slots::<Option<DeclaredType<Kind<C, H>>>>(
            1,
            budget,
            &expression.range,
        )?;
        self.worklists.insert(id, declaration);
        Ok(vec![ValueType::Unestablished])
    }
    fn function(
        &mut self,
        name: &Located<String>,
        budget: &mut Budget,
    ) -> Result<(usize, usize), QueryError> {
        for (id, d) in self.declarations.iter().enumerate() {
            budget.charge(
                1 + name.value.len().min(d.name.value.len()),
                Location::Query(name.range.clone()),
            )?;
            if name.value == d.name.value {
                return Ok((id, d.parameters.len()));
            }
        }
        Err(QueryError::query(
            name.range.clone(),
            format!("undefined function: {}", name.value),
        ))
    }
    fn function_types(
        &mut self,
        name: &Located<String>,
        budget: &mut Budget,
    ) -> Result<Vec<ValueType>, QueryError> {
        let (id, _) = self.function(name, budget)?;
        crate::value::function_facts(
            &self.declarations[id].result.value,
            budget,
            &Location::Query(name.range.clone()),
        )
    }
    fn accumulator_function(
        &mut self,
        step: &Located<String>,
        budget: &mut Budget,
    ) -> Result<(usize, Vec<ValueType>), QueryError> {
        let (id, _) = self.function(step, budget)?;
        let state = accumulator_state(&self.declarations[id], step, budget)?;
        Ok((
            id,
            crate::value::function_facts(state, budget, &Location::Query(step.range.clone()))?,
        ))
    }
    fn predicate_subject_types(
        &mut self,
        range: &Range<usize>,
        budget: &mut Budget,
    ) -> Result<Vec<ValueType>, QueryError> {
        let kind = self
            .scope
            .get(crate::value::PREDICATE_SUBJECT)
            .ok_or_else(|| {
                QueryError::query(
                    range.clone(),
                    "unnamed argument is only available in a predicate",
                )
            })?;
        Ok(self
            .host
            .scalar_types(kind, budget, range)?
            .unwrap_or_else(|| vec![ValueType::Unestablished]))
    }
    fn query_types(
        &mut self,
        q: &Query<C, H>,
        l: &[(&str, Vec<ValueType>)],
        b: &mut Budget,
        _: &Range<usize>,
    ) -> Result<Vec<ValueType>, QueryError> {
        self.native(q, l, b, true)
    }
    fn native_value_types(
        &mut self,
        q: &Query<C, H>,
        l: &[(&str, Vec<ValueType>)],
        b: &mut Budget,
        _: &Range<usize>,
    ) -> Result<Vec<ValueType>, QueryError> {
        self.native(q, l, b, false)
    }
    fn enter_scope(&mut self, budget: &mut Budget, range: &Range<usize>) -> Result<(), QueryError> {
        let scope = crate::projection::copy_scope::<C, H>(&self.scope, budget, range)?;
        let generators =
            crate::projection::copy_scope::<C, H>(&self.generator_kinds, budget, range)?;
        crate::projection::admit_slots::<LexicalKinds<Kind<C, H>>>(1, budget, range)?;
        let mut contracts = BTreeMap::new();
        for (name, d) in &self.contracts {
            budget_name(name, budget, range)?;
            contracts.insert(
                name.clone(),
                crate::runtime_types::copy_declaration(d, budget, &Location::Query(range.clone()))?,
            );
        }
        self.scopes.push(LexicalKinds {
            scope,
            generators,
            contracts,
        });
        Ok(())
    }
    fn leave_scope(&mut self) {
        let saved = self.scopes.pop().expect("entered lexical scope");
        self.scope = saved.scope;
        self.generator_kinds = saved.generators;
        self.contracts = saved.contracts;
    }
    fn prepare_pattern(
        &mut self,
        pattern: &Pattern,
        source: &ValueExpression<Query<C, H>>,
        budget: &mut Budget,
    ) -> Result<(), QueryError> {
        let kind = self.local_kind(source, budget)?;
        self.pattern_kind(PatternRef::Pattern(pattern), kind, None, budget)
    }
    fn prepare_local(
        &mut self,
        name: &Located<String>,
        value: &ValueExpression<Query<C, H>>,
        types: &[ValueType],
        budget: &mut Budget,
    ) -> Result<(), QueryError> {
        if let Some(d) = self.value_declaration(value, budget)? {
            self.contracts.insert(name.value.clone(), d);
        }
        let kind = match self.local_kind(value, budget)? {
            Some(kind) => kind,
            None => self.host.constructed_kind(copy_value_types(
                types,
                budget,
                Location::Query(name.range.clone()),
            )?),
        };
        budget.charge(name.value.len() + 1, Location::Query(name.range.clone()))?;
        self.scope.insert(name.value.clone(), kind);
        Ok(())
    }
    fn prepare_generator(
        &mut self,
        binder: &Pattern,
        source: &ValueExpression<Query<C, H>>,
        types: &[ValueType],
        element: bool,
        budget: &mut Budget,
    ) -> Result<(), QueryError> {
        let kind = match self.local_kind(source, budget)? {
            Some(kind)
                if element
                    && self
                        .host
                        .scalar_types(&kind, budget, &source.range)?
                        .is_none() =>
            {
                self.host.subject_kind(&kind, budget, &source.range)?
            }
            Some(kind) if !element => kind,
            _ => self.host.constructed_kind(copy_value_types(
                types,
                budget,
                Location::Query(binder.range.clone()),
            )?),
        };
        for name in crate::pattern_names(binder, budget)? {
            self.generator_kinds.remove(&name.value);
        }
        self.pattern_kind(PatternRef::Pattern(binder), Some(kind), None, budget)?;
        for name in crate::pattern_names(binder, budget)? {
            if let Some(kind) = self.scope.remove(&name.value) {
                self.generator_kinds.insert(name.value.clone(), kind);
            }
        }
        Ok(())
    }
    fn prepare_predicate(
        &mut self,
        argument: Option<&Pattern>,
        source: &ValueExpression<Query<C, H>>,
        types: &[ValueType],
        element: bool,
        budget: &mut Budget,
    ) -> Result<(), QueryError> {
        let kind = match self.local_kind(source, budget)? {
            Some(kind)
                if element
                    && self
                        .host
                        .scalar_types(&kind, budget, &source.range)?
                        .is_none() =>
            {
                return Err(QueryError::query(
                    source.range.clone(),
                    "constructed filter needs a positional array; use the host's native filter for native selections",
                ));
            }
            Some(kind) if !element => kind,
            _ => self.host.constructed_kind(copy_value_types(
                types,
                budget,
                Location::Query(source.range.clone()),
            )?),
        };
        let internal = crate::value::PREDICATE_SUBJECT;
        budget_name(internal, budget, &source.range)?;
        self.scope.insert(internal.to_owned(), kind.clone());
        self.generator_kinds
            .insert(internal.to_owned(), kind.clone());
        if let Some(pattern) = argument {
            self.pattern_kind(PatternRef::Pattern(pattern), Some(kind), None, budget)?;
        }
        Ok(())
    }
    fn query_arguments<'q>(
        &self,
        query: &'q Query<C, H>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<Vec<&'q ValueExpression<Query<C, H>>>, QueryError> {
        let arguments = crate::projection::declared_arguments::<C, H>(query, self.host, budget)?;
        crate::projection::admit_slots::<&ValueExpression<Query<C, H>>>(
            arguments.len(),
            budget,
            range,
        )?;
        Ok(arguments.into_iter().map(|(query, _)| query).collect())
    }
    fn evaluate_query(
        &mut self,
        _: &Query<C, H>,
        _: &[(&str, ConstructedValue)],
        _: &mut Budget,
    ) -> Result<ConstructedValue, Self::Error> {
        unreachable!("preflight executes no native operations")
    }
    fn read_binding(
        &mut self,
        _: &str,
        _: &Range<usize>,
        _: &mut Budget,
    ) -> Result<ConstructedValue, Self::Error> {
        unreachable!("preflight reads no values")
    }
}

/// Resolved functions and native operands shared by one submitted program.
/// Preparation borrows immutable source trees and retains no execution results.
/// The host must use this unit only with its current request context.
pub struct PreparedFunctions<'a, 'h, C, H: FunctionHost<C>> {
    bodies: Vec<Body<'a, Query<C, H>, Kind<C, H>>>,
    preflight: Preflight<'h, 'a, C, H>,
    body_prepared: Vec<BTreeMap<usize, Operand<Kind<C, H>>>>,
    identity: std::sync::Arc<()>,
}

/// One written value, resolved once in its exact lexical and relative scope.
/// Execute it through the same [`PreparedFunctions`] that prepared it.
pub struct PreparedFunctionValue<'a, Q, K = ()> {
    source: &'a ValueExpression<Q>,
    kind: K,
    prepared: BTreeMap<usize, Operand<K>>,
    value: crate::value::prepared::PreparedValue<'a, Q>,
    names: Vec<&'a str>,
    identity: std::sync::Arc<()>,
}

/// A prepared initializer and its atomic, ordered public bindings.
pub struct PreparedPatternBinding<'a, Q, K> {
    pattern: &'a Pattern,
    value: PreparedFunctionValue<'a, Q, K>,
    bindings: Vec<(&'a Located<String>, K)>,
}
impl<K, Q> PreparedPatternBinding<'_, Q, K> {
    /// Bound names and host kinds in written pattern order.
    pub fn bindings(&self) -> impl Iterator<Item = (&Located<String>, &K)> {
        self.bindings.iter().map(|(name, kind)| (*name, kind))
    }
}

impl<Q, K> PreparedFunctionValue<'_, Q, K> {
    /// Preflight kind for the written value; runtime whole-type admission still
    /// checks actual arguments and results.
    pub fn kind(&self) -> &K {
        &self.kind
    }
}

impl<'a, 'h, C, H: FunctionHost<C>> PreparedFunctions<'a, 'h, C, H> {
    /// Register signatures and prepare every body, including unused functions.
    ///
    /// # Errors
    /// Invalid declarations, scope, effects and allowances fail before execution.
    pub fn prepare(
        declarations: impl IntoIterator<Item = &'a Declaration<C, H>>,
        host: &'h H,
        budget: &mut Budget,
    ) -> Result<Self, FunctionError<EvaluationError<H::Error>>> {
        Self::prepare_borrowed(
            declarations
                .into_iter()
                .map(FunctionDeclaration::as_borrowed),
            host,
            budget,
        )
    }

    /// Prepare request-resolved headers that borrow existing body trees.
    /// Scope, purity, type and allowance checks are identical to [`Self::prepare`].
    ///
    /// # Errors
    /// Invalid declarations or written bodies fail before execution.
    pub fn prepare_borrowed(
        declarations: impl IntoIterator<Item = FunctionDeclarationRef<'a, Query<C, H>, Kind<C, H>>>,
        host: &'h H,
        budget: &mut Budget,
    ) -> Result<Self, FunctionError<EvaluationError<H::Error>>> {
        Self::prepare_headers(
            declarations.into_iter().map(DeclarationRef::from),
            host,
            budget,
        )
    }

    /// Prepare native functions with destructured whole typed parameters.
    ///
    /// # Errors
    /// Scope, views, purity and contracts are checked before execution.
    pub fn prepare_patterns(
        declarations: impl IntoIterator<Item = &'a PatternFunctionDeclaration<Query<C, H>, Kind<C, H>>>,
        host: &'h H,
        budget: &mut Budget,
    ) -> Result<Self, FunctionError<EvaluationError<H::Error>>> {
        Self::prepare_headers(
            declarations
                .into_iter()
                .map(PatternFunctionDeclaration::as_borrowed),
            host,
            budget,
        )
    }

    /// Prepare request-resolved pattern headers without cloning body trees.
    ///
    /// # Errors
    /// Every declaration and written branch receives the ordinary scope, purity
    /// and allowance checks before execution.
    pub fn prepare_patterns_borrowed(
        declarations: impl IntoIterator<
            Item = PatternFunctionDeclarationRef<'a, Query<C, H>, Kind<C, H>>,
        >,
        host: &'h H,
        budget: &mut Budget,
    ) -> Result<Self, FunctionError<EvaluationError<H::Error>>> {
        Self::prepare_headers(
            declarations.into_iter().map(DeclarationRef::from),
            host,
            budget,
        )
    }

    fn prepare_headers(
        declarations: impl IntoIterator<Item = DeclarationRef<'a, Query<C, H>, Kind<C, H>>>,
        host: &'h H,
        budget: &mut Budget,
    ) -> Result<Self, FunctionError<EvaluationError<H::Error>>> {
        let mut preflight = Preflight::new(declarations, host, budget)?;
        crate::projection::admit_slots::<Body<'_, Query<C, H>, Kind<C, H>>>(
            preflight.declarations.len(),
            budget,
            &(0..0),
        )?;
        let mut bodies = Vec::with_capacity(preflight.declarations.len());
        crate::projection::admit_slots::<BTreeMap<usize, Operand<Kind<C, H>>>>(
            preflight.declarations.len(),
            budget,
            &(0..0),
        )?;
        let mut body_prepared = Vec::with_capacity(preflight.declarations.len());
        for index in 0..preflight.declarations.len() {
            let declaration = preflight.declarations[index];
            preflight.scope.clear();
            preflight.generator_kinds.clear();
            preflight.contracts.clear();
            preflight.worklists.clear();
            for p in declaration.parameters.iter() {
                let kind = host.declaration_kind(p.declaration, budget, p.range)?;
                preflight.pattern_kind(p.pattern, Some(kind), Some(p.declaration), budget)?;
            }
            preflight.expect(declaration.value, &declaration.result.value, budget)?;
            bodies.push(crate::value::prepare_function_body(
                declaration,
                &mut preflight,
                budget,
            )?);
            body_prepared.push(std::mem::take(&mut preflight.prepared));
        }
        preflight.scope.clear();
        preflight.contracts.clear();
        preflight.worklists.clear();
        budget.charge_results(1, Location::Query(0..0))?;
        Ok(Self {
            bodies,
            preflight,
            body_prepared,
            identity: std::sync::Arc::new(()),
        })
    }

    /// Resolve one written value without executing native operations. Call this
    /// for all program values before any statement runs. Functions cannot capture
    /// this entry's scope. Relative native input is explicit and optional.
    ///
    /// # Errors
    /// All written branches and embedded native arguments are checked.
    #[expect(
        clippy::type_complexity,
        reason = "The prepared entry retains the host's existing native expression and kind types"
    )]
    pub fn prepare_value(
        &mut self,
        entry: &'a ValueExpression<Query<C, H>>,
        scope: &BTreeMap<String, Kind<C, H>>,
        relative: Option<Kind<C, H>>,
        budget: &mut Budget,
    ) -> Result<
        PreparedFunctionValue<'a, Query<C, H>, Kind<C, H>>,
        FunctionError<EvaluationError<H::Error>>,
    > {
        let saved = std::mem::take(&mut self.preflight.prepared);
        let saved_worklists = std::mem::take(&mut self.preflight.worklists);
        let result = (|| {
            let kind = self.preflight.entry_kind(entry, scope, relative, budget)?;
            let mut preparation = Preparation::new();
            let value = preparation.resolve(entry, &mut self.preflight, budget)?;
            budget.charge(1, Location::Query(entry.range.clone()))?;
            Ok(PreparedFunctionValue {
                source: entry,
                kind,
                value,
                names: preparation.names,
                prepared: std::mem::take(&mut self.preflight.prepared),
                identity: std::sync::Arc::clone(&self.identity),
            })
        })();
        self.preflight.prepared = saved;
        self.preflight.worklists = saved_worklists;
        result
    }

    /// Discover a value's host kind through the same preflight used by prepared
    /// execution. All written branches, lexical patterns and native arguments
    /// are checked; actual values still require runtime admission.
    ///
    /// # Errors
    /// Invalid scope, effects, host operations and exhausted allowances fail.
    pub fn value_kind(
        &mut self,
        entry: &ValueExpression<Query<C, H>>,
        scope: &BTreeMap<String, Kind<C, H>>,
        relative: Option<Kind<C, H>>,
        budget: &mut Budget,
    ) -> Result<Kind<C, H>, FunctionError<EvaluationError<H::Error>>> {
        let saved = std::mem::take(&mut self.preflight.prepared);
        let saved_worklists = std::mem::take(&mut self.preflight.worklists);
        let result = self.preflight.entry_kind(entry, scope, relative, budget);
        self.preflight.prepared = saved;
        self.preflight.worklists = saved_worklists;
        Ok(result?)
    }

    /// Prepare one atomic pattern binding. The initializer cannot see its new
    /// names. Only selected bindings are materialized by [`Self::evaluate_binding`].
    ///
    /// # Errors
    /// Duplicate/shadowed names, invalid patterns, effects and limits fail.
    #[expect(
        clippy::type_complexity,
        reason = "The binding retains the existing host expression and kind types"
    )]
    pub fn prepare_binding(
        &mut self,
        pattern: &'a Pattern,
        initializer: &'a ValueExpression<Query<C, H>>,
        scope: &BTreeMap<String, Kind<C, H>>,
        relative: Option<Kind<C, H>>,
        budget: &mut Budget,
    ) -> Result<
        PreparedPatternBinding<'a, Query<C, H>, Kind<C, H>>,
        FunctionError<EvaluationError<H::Error>>,
    > {
        let value = self.prepare_value(initializer, scope, relative, budget)?;
        let types = self
            .preflight
            .host
            .scalar_types(value.kind(), budget, &initializer.range)?
            .unwrap_or_else(|| vec![ValueType::Unestablished]);
        let facts = crate::value::pattern::facts(pattern, &types, budget)?;
        let mut names = std::collections::BTreeSet::new();
        for (name, _) in &facts {
            budget_name(&name.value, budget, &name.range)?;
            crate::projection::admit_slots::<&str>(1, budget, &name.range)?;
            if scope.contains_key(&name.value) || !names.insert(name.value.as_str()) {
                return Err(
                    QueryError::query(name.range.clone(), "binding is already defined").into(),
                );
            }
        }
        self.preflight.pattern_kind(
            PatternRef::Pattern(pattern),
            Some(value.kind.clone()),
            None,
            budget,
        )?;
        let mut bindings = Vec::new();
        for (name, types) in facts {
            crate::projection::admit_slots::<(&Located<String>, Kind<C, H>)>(
                1,
                budget,
                &name.range,
            )?;
            let kind = self
                .preflight
                .scope
                .get(&name.value)
                .cloned()
                .unwrap_or_else(|| self.preflight.host.constructed_kind(types));
            bindings.push((name, kind));
        }
        Ok(PreparedPatternBinding {
            pattern,
            value,
            bindings,
        })
    }

    /// Evaluate the initializer once, then match and finish its selected fields.
    /// A mismatch returns no capture; ignored fields are never copied as output.
    ///
    /// # Errors
    /// A mismatch, host failure, invalid ownership, runtime contract or limit
    /// fails before the caller can install any names.
    pub fn evaluate_binding(
        &self,
        entry: &PreparedPatternBinding<'a, Query<C, H>, Kind<C, H>>,
        bindings: &Bindings<H::Value>,
        relative: Option<&H::Value>,
        context: &mut C,
        budget: &mut Budget,
        limits: FunctionLimits,
    ) -> Result<crate::NativeCapture<H::Value>, FunctionError<EvaluationError<H::Error>>> {
        let value = &entry.value;
        if !std::sync::Arc::ptr_eq(&self.identity, &value.identity) {
            return Err(QueryError::query(
                entry.pattern.range.clone(),
                "binding belongs to a different prepared function program",
            )
            .into());
        }
        let mut calls = CallTrace::default();
        let mut runtime = Runtime {
            host: self.preflight.host,
            context,
            bindings,
            contracts: &BTreeMap::new(),
            prepared: &value.prepared,
            body_prepared: &self.body_prepared,
            worklists: &self.preflight.worklist_contracts,
            source_function: None,
            relative,
            limit: limits.active_depth,
            calls: &mut calls,
        };
        let location = Location::Query(entry.pattern.range.clone());
        let result = (|| {
            let value = execution::execute(
                &value.value,
                &value.names,
                &self.bodies,
                &mut runtime,
                budget,
                limits.active_depth,
                0,
            )?;
            execution::Host::inspect_pattern(&mut runtime, &value, budget, &location)?;
            let selected = crate::value::pattern::bind::<Query<C, H>, _>(
                PatternRef::Pattern(entry.pattern),
                value,
                &mut runtime,
                budget,
            )?
            .ok_or_else(|| {
                QueryError::query(entry.pattern.range.clone(), "binding pattern did not match")
            })?;
            crate::projection::admit_slots::<(String, H::Value)>(
                selected.len(),
                budget,
                &entry.pattern.range,
            )?;
            let mut fields = Vec::with_capacity(selected.len());
            for (name, value) in selected {
                budget_name(name, budget, &entry.pattern.range)?;
                fields.push((
                    name.to_owned(),
                    runtime.finish_value(value, budget, &location)?,
                ));
            }
            Ok(crate::NativeCapture { fields })
        })();
        result.map_err(|error| self.function_error(error, calls))
    }

    fn function_error(
        &self,
        error: EvaluationError<H::Error>,
        calls: CallTrace,
    ) -> FunctionError<EvaluationError<H::Error>> {
        FunctionError {
            error,
            omitted_calls: calls.omitted,
            calls: calls
                .frames
                .into_iter()
                .map(|(id, range)| FunctionCall {
                    function: self.preflight.declarations[id]
                        .name
                        .value
                        .chars()
                        .take(64)
                        .collect(),
                    range,
                })
                .collect(),
        }
    }

    /// Execute a projection using its already-prepared fields in written order.
    /// Prepare each field once with the subject name in scope and its singleton
    /// kind as relative input. Pass those entries from this unit in field order.
    /// All fields must admit scalar projection, even when there are no subjects.
    /// Result facts retain the record schema of an empty report.
    ///
    /// # Errors
    /// Shadowing, duplicate labels, mismatched entries, scalar admission and
    /// allowances fail before enumeration. Field failures retain their locations
    /// and active function calls; all work uses the supplied cumulative budget.
    #[expect(
        clippy::type_complexity,
        reason = "The projection borrows existing prepared native field entries"
    )]
    #[expect(
        clippy::too_many_arguments,
        reason = "The bridge keeps the existing projection, prepared entries and execution borrows explicit"
    )]
    pub fn evaluate_projection(
        &self,
        projection: &crate::Projection<Query<C, H>>,
        fields: &[&PreparedFunctionValue<'a, Query<C, H>, Kind<C, H>>],
        input: H::Value,
        bindings: &Bindings<H::Value>,
        context: &mut C,
        budget: &mut Budget,
        limits: FunctionLimits,
    ) -> Result<crate::ConstructedResult, FunctionError<EvaluationError<H::Error>>> {
        let range = &projection.subject.range;
        budget.within_evaluation(1, Location::Query(range.clone()), |budget| {
            if bindings
                .iter()
                .any(|(name, _)| name == projection.subject.value)
            {
                return Err(QueryError::query(
                    range.clone(),
                    "projection subject shadows an existing binding",
                )
                .into());
            }
            if fields.len() != projection.fields.len() {
                return Err(QueryError::query(
                    range.clone(),
                    "projection requires every written prepared field",
                )
                .into());
            }
            let host = self.preflight.host;
            crate::projection::admit_slots::<Vec<ValueType>>(1, budget, range)?;
            let mut positions = vec![Vec::new()];
            for (index, ((_, expression), entry)) in
                projection.fields.iter().zip(fields).enumerate()
            {
                crate::projection::check_projection_label(projection, index, budget)?;
                if !std::sync::Arc::ptr_eq(&self.identity, &entry.identity) {
                    return Err(QueryError::query(
                        expression.range.clone(),
                        "value belongs to a different prepared function program",
                    )
                    .into());
                }
                if !std::ptr::eq(expression, entry.source) {
                    return Err(QueryError::query(
                        expression.range.clone(),
                        "prepared entry does not match the written projection field",
                    )
                    .into());
                }
                let types = host
                    .scalar_types(entry.kind(), budget, &expression.range)?
                    .ok_or_else(|| {
                        QueryError::query(
                            expression.range.clone(),
                            "native handles require an explicit scalar projection",
                        )
                    })?;
                positions = crate::value::extend_type_positions(
                    &positions,
                    &types,
                    budget,
                    &Location::Query(expression.range.clone()),
                )?;
            }
            let types = crate::projection::projection_result_types(projection, positions, budget)?;
            let subjects = host
                .subjects(input, context, budget, range)
                .map_err(|error| self.function_error(error, CallTrace::default()))?;
            let value = crate::projection::projection_rows(
                projection,
                subjects,
                bindings,
                context,
                budget,
                |index, local, context, budget| {
                    let expression = &projection.fields[index].1;
                    let relative = local.get(&projection.subject.value, range.clone())?;
                    let value = self.evaluate(
                        fields[index],
                        local,
                        Some(relative),
                        context,
                        budget,
                        limits,
                    )?;
                    host.project_value(value, context, budget, &expression.range)
                        .map_err(|error| self.function_error(error, CallTrace::default()))
                },
            )?;
            Ok(crate::ConstructedResult { value, types })
        })
    }

    /// Execute a prepared value with current bindings, relative input and one
    /// cumulative allowance. Results retain native ownership through the host.
    ///
    /// # Errors
    /// Runtime contracts, active depth, host failures and allowances retain the
    /// responsible expression and bounded active call context.
    pub fn evaluate(
        &self,
        entry: &PreparedFunctionValue<'a, Query<C, H>, Kind<C, H>>,
        bindings: &Bindings<H::Value>,
        relative: Option<&H::Value>,
        context: &mut C,
        budget: &mut Budget,
        limits: FunctionLimits,
    ) -> Result<H::Value, FunctionError<EvaluationError<H::Error>>> {
        if !std::sync::Arc::ptr_eq(&self.identity, &entry.identity) {
            return Err(QueryError::query(
                entry.value.range.clone(),
                "value belongs to a different prepared function program",
            )
            .into());
        }
        let mut calls = CallTrace::default();
        let mut runtime = Runtime {
            host: self.preflight.host,
            context,
            bindings,
            contracts: &BTreeMap::new(),
            prepared: &entry.prepared,
            body_prepared: &self.body_prepared,
            worklists: &self.preflight.worklist_contracts,
            source_function: None,
            relative,
            limit: limits.active_depth,
            calls: &mut calls,
        };
        let location = Location::Query(entry.value.range.clone());
        let result = execution::execute(
            &entry.value,
            &entry.names,
            &self.bodies,
            &mut runtime,
            budget,
            limits.active_depth,
            0,
        )
        .and_then(|value| runtime.finish_value(value, budget, &location));
        result.map_err(|error| self.function_error(error, calls))
    }
}

/// One-shot facade over [`PreparedFunctions`]. Existing callers retain their
/// context and budget borrowing contract.
pub struct FunctionRequest<'a, 'r, C, H: FunctionHost<C>> {
    functions: PreparedFunctions<'a, 'r, C, H>,
    context: &'r mut C,
    budget: &'r mut Budget,
    limits: FunctionLimits,
}
impl<'a, 'r, C, H: FunctionHost<C>> FunctionRequest<'a, 'r, C, H> {
    /// Prepare every declaration before evaluating the entry.
    ///
    /// # Errors
    /// Invalid declarations, scope, effects and allowances fail before execution.
    pub fn prepare(
        declarations: &'a [Declaration<C, H>],
        host: &'r H,
        context: &'r mut C,
        budget: &'r mut Budget,
        limits: FunctionLimits,
    ) -> Result<Self, FunctionError<EvaluationError<H::Error>>> {
        let functions = PreparedFunctions::prepare(declarations, host, budget)?;
        Ok(Self {
            functions,
            context,
            budget,
            limits,
        })
    }
    /// Prepare pattern-capable functions using the same request runner.
    ///
    /// # Errors
    /// Invalid declarations fail before any operation executes.
    pub fn prepare_patterns(
        declarations: &'a [PatternDeclaration<C, H>],
        host: &'r H,
        context: &'r mut C,
        budget: &'r mut Budget,
        limits: FunctionLimits,
    ) -> Result<Self, FunctionError<EvaluationError<H::Error>>> {
        let functions = PreparedFunctions::prepare_patterns(declarations, host, budget)?;
        Ok(Self {
            functions,
            context,
            budget,
            limits,
        })
    }

    /// Prepare and evaluate one entry with explicit input bindings.
    ///
    /// # Errors
    /// Runtime contracts and limits retain the original failure and bounded calls.
    pub fn evaluate(
        mut self,
        entry: &'a ValueExpression<Query<C, H>>,
        bindings: &Bindings<H::Value>,
    ) -> Result<H::Value, FunctionError<EvaluationError<H::Error>>> {
        let mut scope = BTreeMap::new();
        for (name, value) in bindings.iter() {
            budget_name(name, self.budget, &entry.range)?;
            scope.insert(
                name.to_owned(),
                self.functions
                    .preflight
                    .host
                    .kind(value, self.budget, &entry.range)?,
            );
        }
        let entry = self
            .functions
            .prepare_value(entry, &scope, None, self.budget)?;
        self.functions.evaluate(
            &entry,
            bindings,
            None,
            self.context,
            self.budget,
            self.limits,
        )
    }
}

fn budget_name(name: &str, budget: &mut Budget, range: &Range<usize>) -> Result<(), QueryError> {
    budget.charge(name.len() + 1, Location::Query(range.clone()))
}

struct Runtime<'r, 'a, C, H: FunctionHost<C>> {
    host: &'r H,
    context: &'r mut C,
    bindings: &'r Bindings<H::Value>,
    contracts: &'r BTreeMap<&'a str, &'a DeclaredType<Kind<C, H>>>,
    prepared: &'r BTreeMap<usize, Operand<Kind<C, H>>>,
    body_prepared: &'r [BTreeMap<usize, Operand<Kind<C, H>>>],
    worklists: &'r [Option<DeclaredType<Kind<C, H>>>],
    source_function: Option<usize>,
    relative: Option<&'r H::Value>,
    limit: usize,
    calls: &'r mut CallTrace,
}
impl<'a, C, H: FunctionHost<C>> Runtime<'_, 'a, C, H> {
    fn value_contract(
        &mut self,
        value: &H::Value,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<DeclaredType<Kind<C, H>>, EvaluationError<H::Error>> {
        budget.within_evaluation(1, location.clone(), |budget| {
            budget.charge(1, location.clone())?;
            if let Some(c) = self.host.computational_value(value) {
                return Ok(c.declaration(budget, location)?);
            }
            if let Some(c) = self.host.constructed_value(value)
                && let Some(d) = crate::worklists::scalar_contract(c)
            {
                return Ok(d);
            }
            if let Some(values) = self.host.tuple_view(value) {
                let mut types = Vec::new();
                for v in values {
                    crate::projection::admit_slots::<DeclaredType<Kind<C, H>>>(
                        1,
                        budget,
                        match location {
                            Location::Query(r) | Location::Source(r) => r,
                        },
                    )?;
                    types.push(self.value_contract(v, budget, location)?);
                }
                return Ok(DeclaredType::Tuple(types));
            }
            let range = match location {
                Location::Query(r) | Location::Source(r) => r,
            };
            Ok(DeclaredType::Native(self.host.kind(value, budget, range)?))
        })
    }
    fn infer_queue_element(
        &mut self,
        value: &HostValue<'_, C, H>,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<DeclaredType<Kind<C, H>>, EvaluationError<H::Error>> {
        let range = match location {
            Location::Query(r) | Location::Source(r) => r,
        };
        if let Some(data) = execution::Host::constructed(self, value, budget, location)? {
            let mut actual = constructed_value_type(data.value, budget, location.clone())?;
            if let Some(d) = data.declaration {
                budget.charge_results(1, location.clone())?;
                actual = ValueType::Declared {
                    actual: Box::new(actual),
                    declaration: crate::runtime_types::copy_declaration(d, budget, location)?,
                };
            }
            return match crate::worklists::fact_contract(&actual, budget, location)? {
                Some(DeclaredType::Array(d) | DeclaredType::Sequence(d)) => Ok(*d),
                _ => Err(QueryError::query(
                    range.clone(),
                    "empty queue needs an explicit or contextual element contract",
                )
                .into()),
            };
        }
        match &value.data {
            Data::Constructed(_) => unreachable!("constructed view handled above"),
            Data::Native(view) => {
                budget.charge(view.path.len(), location.clone())?;
                let kind = self
                    .host
                    .kind(native_view::<C, H>(view, self.host), budget, range)?;
                let element = self.host.subject_kind(&kind, budget, range)?;
                if let Some(types) = self.host.scalar_types(&element, budget, range)? {
                    if let [fact] = types.as_slice()
                        && let Some(d) = crate::worklists::fact_contract(fact, budget, location)?
                    {
                        return Ok(d);
                    }
                    return Err(QueryError::query(
                        range.clone(),
                        "queue input needs an established element contract",
                    )
                    .into());
                }
                Ok(DeclaredType::Native(element))
            }
        }
    }
    fn queue_items(
        &mut self,
        value: HostValue<'_, C, H>,
        element: &DeclaredType<Kind<C, H>>,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<Vec<H::Value>, EvaluationError<H::Error>> {
        let value = execution::Host::normalize(self, value, budget, location)?;
        let range = match location {
            Location::Query(r) | Location::Source(r) => r,
        };
        match value.data {
            Data::Native(view) => {
                budget.charge(view.path.len(), location.clone())?;
                self.host.sequence_items(
                    native_view::<C, H>(&view, self.host),
                    element,
                    self.context,
                    budget,
                    range,
                )
            }
            Data::Constructed(data) => {
                let data = data.materialize(budget, location)?;
                let ConstructedValue::Array(values) = data.data() else {
                    return Err(QueryError::query(
                        range.clone(),
                        "queue input needs a positional sequence",
                    )
                    .into());
                };
                crate::projection::admit_slots::<H::Value>(values.len(), budget, range)?;
                let mut output = Vec::with_capacity(values.len());
                for v in values {
                    let v = copy_constructed_value(v, budget, location.clone())?;
                    let facts = vec![constructed_value_type(&v, budget, location.clone())?];
                    output.push(self.host.lift_constructed(
                        v,
                        facts,
                        self.context,
                        budget,
                        range,
                    )?);
                }
                Ok(output)
            }
        }
    }
    fn computational(
        &mut self,
        value: crate::ComputationalValue<H::Value, Kind<C, H>>,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<H::Value, EvaluationError<H::Error>> {
        let range = match location {
            Location::Query(r) | Location::Source(r) => r,
        };
        crate::projection::admit_slots::<H::Value>(1, budget, range)?;
        self.host
            .lift_computational(value, self.context, budget, range)
    }
    fn compute(
        &mut self,
        expression: &'a PreparedValue<'a, Query<C, H>>,
        mut values: Vec<HostValue<'a, C, H>>,
        budget: &mut Budget,
    ) -> Result<HostValue<'a, C, H>, EvaluationError<H::Error>> {
        use crate::ComputationalValue as W;
        let location = Location::Query(expression.range.clone());
        let range = &expression.range;
        let output = match &expression.value {
            PreparedKind::TupleAccess { position, .. }
                if matches!(values[0].data, Data::Native(_)) =>
            {
                let mut value = values.pop().expect("native tuple");
                let len = match execution::Host::constructed(self, &value, budget, &location)? {
                    Some(data) => match data.value.data() {
                        ConstructedValue::Tuple(v) => Some(v.len()),
                        _ => None,
                    },
                    None => {
                        let Data::Native(view) = &value.data else {
                            unreachable!()
                        };
                        self.host
                            .tuple_view(native_view::<C, H>(view, self.host))
                            .map(<[_]>::len)
                    }
                }
                .ok_or_else(|| QueryError::query(range.clone(), "tuple access needs a tuple"))?;
                let index = position
                    .value
                    .checked_sub(1)
                    .filter(|&i| i < len)
                    .ok_or_else(|| {
                        QueryError::query(position.range.clone(), "missing tuple position")
                    })?;
                return crate::value::pattern::select(
                    &mut value,
                    NativeStep::Tuple(index),
                    self,
                    budget,
                    &location,
                );
            }
            PreparedKind::Field { field, .. }
                if matches!(&values[0].data, Data::Native(view)
                    if self.host.capture_record(native_view::<C, H>(view, self.host)).is_some()) =>
            {
                let mut value = values.pop().expect("native capture");
                let Data::Native(view) = &value.data else {
                    unreachable!("native capture view")
                };
                let record = self
                    .host
                    .capture_record(native_view::<C, H>(view, self.host))
                    .expect("native capture view");
                let mut selected = None;
                for (index, (label, _)) in record.fields.iter().enumerate() {
                    budget.charge(1 + label.len().min(field.value.len()), location.clone())?;
                    if label == &field.value {
                        selected = Some(index);
                        break;
                    }
                }
                let index = selected.ok_or_else(|| {
                    QueryError::query(field.range.clone(), "unknown native capture field")
                })?;
                return crate::value::pattern::select(
                    &mut value,
                    NativeStep::Record(index),
                    self,
                    budget,
                    &location,
                );
            }
            PreparedKind::Field { field, .. }
                if matches!(values[0].data, Data::Native(_))
                    && execution::Host::constructed(self, &values[0], budget, &location)?
                        .is_some() =>
            {
                let mut value = values.pop().expect("constructed record view");
                let data = execution::Host::constructed(self, &value, budget, &location)?
                    .expect("constructed view");
                let ConstructedValue::Record(fields) = data.value.data() else {
                    return Err(
                        QueryError::query(range.clone(), "field access needs a record").into(),
                    );
                };
                let mut selected = None;
                for (index, (label, _)) in fields.iter().enumerate() {
                    budget.charge(1 + label.len().min(field.value.len()), location.clone())?;
                    if label == &field.value {
                        selected = Some(index);
                        break;
                    }
                }
                let index = selected.ok_or_else(|| {
                    QueryError::query(field.range.clone(), "missing record field")
                })?;
                return crate::value::pattern::select(
                    &mut value,
                    NativeStep::Record(index),
                    self,
                    budget,
                    &location,
                );
            }
            PreparedKind::Queue { source, .. } => {
                let value = values.pop().expect("queue input");
                let element = match self
                    .worklists
                    .get(*source)
                    .expect("prepared queue contract")
                {
                    Some(DeclaredType::Queue(element)) => {
                        crate::runtime_types::copy_declaration(element, budget, &location)?
                    }
                    None => self.infer_queue_element(&value, budget, &location)?,
                    _ => unreachable!("queue constructor contract"),
                };
                let items = self.queue_items(value, &element, budget, &location)?;
                let q = crate::NativeQueue::new(
                    items,
                    element,
                    self.host,
                    self.context,
                    budget,
                    location.clone(),
                )?;
                self.computational(W::Queue(q), budget, &location)?
            }
            PreparedKind::IdentitySet { source } => {
                let Some(DeclaredType::IdentitySet(kind)) = self
                    .worklists
                    .get(*source)
                    .expect("prepared identity-set contract")
                else {
                    unreachable!()
                };
                let s = crate::NativeIdentitySet::new(
                    kind.clone(),
                    self.host,
                    self.context,
                    budget,
                    location.clone(),
                )?;
                self.computational(W::IdentitySet(s), budget, &location)?
            }
            PreparedKind::PopFront(_) => {
                let value = self.finish_value(values.pop().expect("queue"), budget, &location)?;
                let Some(W::Queue(queue)) = self.host.computational_value(&value) else {
                    return Err(QueryError::query(range.clone(), "pop_front needs a queue").into());
                };
                let element =
                    crate::runtime_types::copy_declaration(queue.element(), budget, &location)?;
                let queue = queue.share(self.host, self.context, budget, location.clone())?;
                match queue.pop_front(self.host, self.context, budget, location.clone())? {
                    None => {
                        return Ok(Value::constructed(RuntimeValue::Owned(
                            ConstructedValue::Absent,
                        )));
                    }
                    Some((item, remaining)) => {
                        let item = match std::sync::Arc::try_unwrap(item) {
                            Ok(v) => v,
                            Err(v) => self.host.copy_value(&v, self.context, budget, range)?,
                        };
                        let remaining =
                            self.computational(W::Queue(remaining), budget, &location)?;
                        crate::projection::admit_slots::<H::Value>(2, budget, range)?;
                        let pair = self.host.construct_tuple(
                            vec![item, remaining],
                            self.context,
                            budget,
                            range,
                        )?;
                        let expected = DeclaredType::Optional(Box::new(DeclaredType::Tuple(vec![
                            crate::runtime_types::copy_declaration(&element, budget, &location)?,
                            DeclaredType::Queue(Box::new(element)),
                        ])));
                        crate::admit_computational(
                            &pair,
                            &expected,
                            self.host,
                            self.context,
                            budget,
                            location.clone(),
                        )?;
                        pair
                    }
                }
            }
            PreparedKind::PushBackAll { .. } => {
                let items = values.pop().expect("appended items");
                let value = self.finish_value(values.pop().expect("queue"), budget, &location)?;
                let Some(W::Queue(queue)) = self.host.computational_value(&value) else {
                    return Err(
                        QueryError::query(range.clone(), "push_back_all needs a queue").into(),
                    );
                };
                let queue = queue.share(self.host, self.context, budget, location.clone())?;
                let items = self.queue_items(items, queue.element(), budget, &location)?;
                let queue = queue.push_back_all(
                    items,
                    self.host,
                    self.context,
                    budget,
                    location.clone(),
                )?;
                self.computational(W::Queue(queue), budget, &location)?
            }
            PreparedKind::Insert { .. } => {
                let item =
                    self.finish_value(values.pop().expect("inserted item"), budget, &location)?;
                let value = self.finish_value(values.pop().expect("set"), budget, &location)?;
                let Some(W::IdentitySet(set)) = self.host.computational_value(&value) else {
                    return Err(QueryError::query(
                        range.clone(),
                        "insert needs a native identity set",
                    )
                    .into());
                };
                let set = set
                    .share(self.host, self.context, budget, location.clone())?
                    .insert(item, self.host, self.context, budget, location.clone())?;
                self.computational(W::IdentitySet(set), budget, &location)?
            }
            PreparedKind::Binary {
                operator: crate::ValueBinaryOperator::In,
                ..
            } if matches!(values[1].data, Data::Native(_))
                && execution::Host::constructed(self, &values[1], budget, &location)?.is_none() =>
            {
                let set = self.finish_value(values.pop().expect("set"), budget, &location)?;
                let item = self.finish_value(values.pop().expect("member"), budget, &location)?;
                let Some(W::IdentitySet(set)) = self.host.computational_value(&set) else {
                    return Err(QueryError::query(
                        range.clone(),
                        "native membership needs an identity set",
                    )
                    .into());
                };
                return Ok(Value::constructed(RuntimeValue::Owned({
                    let found =
                        set.contains(&item, self.host, self.context, budget, location.clone())?;
                    budget.charge(1, location.clone())?;
                    budget.charge_results(1, location.clone())?;
                    ConstructedValue::Boolean(found)
                })));
            }
            PreparedKind::Array(_) | PreparedKind::Tuple(_)
                if values.iter().any(|v| matches!(v.data, Data::Native(_))) =>
            {
                let mut native = false;
                for value in &values {
                    native |= matches!(value.data, Data::Native(_))
                        && execution::Host::constructed(self, value, budget, &location)?.is_none();
                }
                if !native {
                    return execution::apply(expression, values, self, budget);
                }
                crate::projection::admit_slots::<H::Value>(values.len(), budget, range)?;
                let mut output = Vec::with_capacity(values.len());
                for v in values {
                    output.push(self.finish_value(v, budget, &location)?);
                }
                if matches!(expression.value, PreparedKind::Tuple(_)) {
                    self.host
                        .construct_tuple(output, self.context, budget, range)?
                } else {
                    let first = output.first().expect("native array is nonempty");
                    let element = self.value_contract(first, budget, &location)?;
                    for v in &output {
                        if !crate::admit_computational(
                            v,
                            &element,
                            self.host,
                            self.context,
                            budget,
                            location.clone(),
                        )? {
                            admit_value(
                                v,
                                &element,
                                self.host,
                                self.context,
                                budget,
                                location.clone(),
                            )?;
                        }
                    }
                    self.host
                        .construct_sequence(output, &element, self.context, budget, range)?
                }
            }
            _ => return execution::apply(expression, values, self, budget),
        };
        self.retained(std::sync::Arc::new(output), budget, range)
    }
    fn owned_native(
        &mut self,
        value: NativeView<H::Value>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<std::sync::Arc<H::Value>, EvaluationError<H::Error>> {
        let at = Location::Query(range.clone());
        let wrapped = Value {
            data: Data::Native(value),
            contract: None,
        };
        if execution::Host::constructed(self, &wrapped, budget, &at)?.is_some() {
            let value = execution::Host::materialize(self, wrapped, budget, &at)?;
            let types = vec![constructed_value_type(&value, budget, at)?];
            crate::projection::admit_slots::<H::Value>(1, budget, range)?;
            return Ok(std::sync::Arc::new(self.host.lift_constructed(
                value,
                types,
                self.context,
                budget,
                range,
            )?));
        }
        let Data::Native(value) = wrapped.data else {
            unreachable!()
        };
        if value.path.is_empty() {
            Ok(value.owner)
        } else {
            budget.charge(value.path.len(), Location::Query(range.clone()))?;
            let value = native_view::<C, H>(&value, self.host);
            Ok(std::sync::Arc::new(self.host.copy_value(
                value,
                self.context,
                budget,
                range,
            )?))
        }
    }
    fn retained<'v>(
        &mut self,
        value: std::sync::Arc<H::Value>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<HostValue<'v, C, H>, EvaluationError<H::Error>> {
        if let Some(constructed) = self.host.constructed_value(&value) {
            let value = match self
                .host
                .share_constructed(&value, self.context, budget, range)?
            {
                Some(owner) => RuntimeValue::shared(owner),
                None => RuntimeValue::Owned(copy_constructed_value(
                    constructed,
                    budget,
                    Location::Query(range.clone()),
                )?),
            };
            constructed_value_type(value.as_ref(), budget, Location::Query(range.clone()))?;
            Ok(Value::constructed(value))
        } else {
            Ok(Value {
                data: Data::Native(NativeView::new(value)),
                contract: None,
            })
        }
    }
    fn finish_value(
        &mut self,
        value: Value<'a, H::Value, Kind<C, H>>,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<H::Value, EvaluationError<H::Error>> {
        let range = match location {
            Location::Query(r) | Location::Source(r) => r,
        };
        if matches!(value.data, Data::Native(_))
            && execution::Host::constructed(self, &value, budget, location)?.is_some()
        {
            let value = execution::Host::materialize(self, value, budget, location)?;
            let types = vec![constructed_value_type(&value, budget, location.clone())?];
            return self
                .host
                .lift_constructed(value, types, self.context, budget, range);
        }
        match value.data {
            Data::Native(value) => {
                let value = self.owned_native(value, budget, range)?;
                match std::sync::Arc::try_unwrap(value) {
                    Ok(value) => Ok(value),
                    Err(value) => self.host.copy_value(&value, self.context, budget, range),
                }
            }
            Data::Constructed(data) => {
                let value = Value {
                    data: Data::<H::Value>::Constructed(data),
                    contract: value.contract,
                }
                .materialize(budget, location)?;
                let types = vec![constructed_value_type(&value, budget, location.clone())?];
                self.host
                    .lift_constructed(value, types, self.context, budget, range)
            }
        }
    }
}
impl<'a, C, H: FunctionHost<C>> execution::Host<'a, Query<C, H>> for Runtime<'_, 'a, C, H> {
    type Native = H::Value;
    type Kind = Kind<C, H>;
    type Error = EvaluationError<H::Error>;
    fn inspect_pattern(
        &mut self,
        value: &HostValue<'a, C, H>,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<(), Self::Error> {
        if let Some(data) = execution::Host::constructed(self, value, budget, location)? {
            constructed_value_type(data.value, budget, location.clone())?;
            if let Some(d) = data.declaration {
                crate::admit_constructed(data.value, d, budget, location.clone())?;
            }
            return Ok(());
        }
        if value.contract.is_none()
            && let Data::Native(view) = &value.data
        {
            budget.charge(view.path.len(), location.clone())?;
            let value = native_view::<C, H>(view, self.host);
            let declaration = self.value_contract(value, budget, location)?;
            admit_value(
                value,
                &declaration,
                self.host,
                self.context,
                budget,
                location.clone(),
            )?;
        }
        Ok(())
    }
    fn native_constructed<'v>(&self, value: &'v H::Value) -> Option<&'v ConstructedValue> {
        self.host.constructed_value(value)
    }
    fn native_record<'v>(&self, value: &'v H::Value) -> Option<&'v crate::NativeCapture<H::Value>> {
        self.host.capture_record(value)
    }
    fn native_tuple<'v>(&self, value: &'v H::Value) -> Option<&'v [H::Value]> {
        self.host.tuple_view(value)
    }
    fn native_list<'v>(&self, value: &'v H::Value) -> Option<&'v [H::Value]> {
        self.host.positional_view(value)
    }
    fn check_native_context(
        &mut self,
        value: &H::Value,
        expected: &DeclaredType<Kind<C, H>>,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<(), Self::Error> {
        crate::worklists::check_context(value, expected, self.host, self.context, budget, location)
    }
    fn apply(
        &mut self,
        expression: &'a PreparedValue<'a, Query<C, H>>,
        values: Vec<HostValue<'a, C, H>>,
        budget: &mut Budget,
    ) -> Result<HostValue<'a, C, H>, Self::Error> {
        self.compute(expression, values, budget)
    }
    fn retains_native_admission(&self) -> bool {
        self.host.retains_native_admission()
    }
    fn predicate_subject(
        &mut self,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<HostValue<'a, C, H>, Self::Error> {
        self.outer(0, crate::value::PREDICATE_SUBJECT, budget, range)
    }
    fn outer(
        &mut self,
        _: usize,
        name: &str,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<HostValue<'a, C, H>, Self::Error> {
        budget.charge(1, Location::Query(range.clone()))?;
        let mut value = self.retained(self.bindings.shared(name, range.clone())?, budget, range)?;
        value.contract = self.contracts.get(name).copied();
        Ok(value)
    }
    fn native(
        &mut self,
        query: &'a Query<C, H>,
        arguments: &'a [PreparedArgument<'a, Query<C, H>>],
        locals: &mut [(&'a str, HostValue<'a, C, H>)],
        bodies: &'a Bodies<'a, C, H>,
        depth: usize,
        function: Option<usize>,
        projected: bool,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<HostValue<'a, C, H>, Self::Error> {
        let lexical = function.is_some();
        let source_function = function.or(self.source_function);
        let prepared = match source_function {
            Some(id) => &self.body_prepared[id],
            None => self.prepared,
        };
        let operand = prepared
            .get(&(query as *const _ as usize))
            .expect("request native operand");
        let mut values = BTreeMap::new();
        let mut contracts = BTreeMap::new();
        if !lexical {
            crate::projection::admit_slots::<(&str, &DeclaredType<Kind<C, H>>)>(
                self.contracts.len(),
                budget,
                range,
            )?;
            contracts.extend(
                self.contracts
                    .iter()
                    .map(|(&name, &contract)| (name, contract)),
            );
        }
        for (name, value) in locals {
            budget_name(name, budget, range)?;
            if let Some(contract) = value.contract {
                crate::projection::admit_slots::<(&str, &DeclaredType<Kind<C, H>>)>(
                    1, budget, range,
                )?;
                contracts.insert(*name, contract);
            } else {
                contracts.remove(*name);
            }
            let value = match &mut value.data {
                Data::Native(owner) => {
                    let owner = owner.share(budget, &Location::Query(range.clone()))?;
                    self.owned_native(owner, budget, range)?
                }
                Data::Constructed(data) => {
                    let value = data
                        .share(budget, &Location::Query(range.clone()))?
                        .into_shared(budget, &Location::Query(range.clone()))?;
                    let types = vec![constructed_value_type(
                        &value,
                        budget,
                        Location::Query(range.clone()),
                    )?];
                    std::sync::Arc::new(self.host.lift_shared_constructed(
                        value,
                        types,
                        self.context,
                        budget,
                        range,
                    )?)
                }
            };
            values.insert((*name).to_owned(), value);
        }
        let bindings = if lexical {
            Bindings::from_shared(values)
        } else {
            self.bindings.with_shared_values(values, budget, range)?
        };
        let outer = crate::projection::prepared::NativeOuter::Bindings {
            values: &bindings,
            names: &operand.names,
        };
        let input = if lexical {
            None
        } else {
            self.relative
                .map(|value| self.host.copy_value(value, self.context, budget, range))
                .transpose()?
        };
        let host = self.host;
        let prepared = self.prepared;
        let body_prepared = self.body_prepared;
        let worklists = self.worklists;
        let limit = self.limit;
        let calls = &mut *self.calls;
        let value = operand.native.execute(
            query,
            host,
            input,
            self.context,
            &bindings,
            &outer,
            None,
            &[],
            &mut |stage, declared, input, context, bindings, budget, range| {
                let mut arguments = Arguments {
                    host,
                    context,
                    bindings,
                    contracts: &contracts,
                    prepared,
                    body_prepared,
                    worklists,
                    source_function,
                    bodies,
                    arguments,
                    declared,
                    argument_kinds: &operand.argument_kinds,
                    depth,
                    limit,
                    calls,
                };
                // Synchronous host callbacks retain the existing bounded reentry guard.
                budget.within_evaluation(0, Location::Query(range.clone()), |budget| {
                    host.evaluate_stage_with_arguments(stage, input, &mut arguments, budget, range)
                })
            },
            budget,
        )?;
        if projected || host.scalar_types(&operand.kind, budget, range)?.is_some() {
            let value = host.project_value(value, self.context, budget, range)?;
            constructed_value_type(&value, budget, Location::Query(range.clone()))?;
            Ok(Value::constructed(RuntimeValue::Owned(value)))
        } else {
            self.retained(std::sync::Arc::new(value), budget, range)
        }
    }
    fn admit_native(
        &mut self,
        value: &H::Value,
        expected: &DeclaredType<Kind<C, H>>,
        budget: &mut Budget,
        location: Location,
    ) -> Result<(), Self::Error> {
        if crate::admit_computational(
            value,
            expected,
            self.host,
            self.context,
            budget,
            location.clone(),
        )? {
            return Ok(());
        }
        admit_value(value, expected, self.host, self.context, budget, location)
    }
    fn sequence_items(
        &mut self,
        value: NativeView<H::Value>,
        element: &DeclaredType<Kind<C, H>>,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<Vec<HostValue<'a, C, H>>, Self::Error> {
        let range = match location {
            Location::Query(r) | Location::Source(r) => r,
        };
        budget.charge(value.path.len(), location.clone())?;
        let source = native_view::<C, H>(&value, self.host);
        let values = self
            .host
            .sequence_items(source, element, self.context, budget, range)?;
        budget.check_items(values.len(), location.clone())?;
        crate::projection::admit_slots::<HostValue<'a, C, H>>(values.len(), budget, range)?;
        let mut output = Vec::with_capacity(values.len());
        for value in values {
            budget.charge(1, location.clone())?;
            budget.charge_results(1, location.clone())?;
            output.push(self.retained(std::sync::Arc::new(value), budget, range)?);
        }
        Ok(output)
    }
    fn finish_sequence(
        &mut self,
        values: Vec<HostValue<'a, C, H>>,
        element: &'a DeclaredType<Kind<C, H>>,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<HostValue<'a, C, H>, Self::Error> {
        if !crate::runtime_types::contains_native(element, budget, location)? {
            return Ok(execution::constructed_sequence(
                values, element, self, budget, location,
            )?);
        }
        let range = match location {
            Location::Query(r) | Location::Source(r) => r,
        };
        crate::projection::admit_slots::<H::Value>(values.len(), budget, range)?;
        let mut output = Vec::with_capacity(values.len());
        for value in values {
            output.push(self.finish_value(value, budget, location)?);
        }
        let value = self
            .host
            .construct_sequence(output, element, self.context, budget, range)?;
        let expected = DeclaredType::Sequence(Box::new(crate::runtime_types::copy_declaration(
            element, budget, location,
        )?));
        admit_value(
            &value,
            &expected,
            self.host,
            self.context,
            budget,
            location.clone(),
        )?;
        self.retained(std::sync::Arc::new(value), budget, range)
    }
    fn native_contract(
        &mut self,
        value: &H::Value,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<DeclaredType<Kind<C, H>>, Self::Error> {
        self.value_contract(value, budget, location)
    }
    fn subjects(
        &mut self,
        value: NativeView<H::Value>,
        budget: &mut Budget,
        location: &Location,
    ) -> Result<Vec<H::Value>, Self::Error> {
        let range = match location {
            Location::Query(range) | Location::Source(range) => range,
        };
        let value = self.owned_native(value, budget, range)?;
        let value = match std::sync::Arc::try_unwrap(value) {
            Ok(value) => value,
            Err(value) => self.host.copy_value(&value, self.context, budget, range)?,
        };
        self.host.subjects(value, self.context, budget, range)
    }
    fn check(
        &mut self,
        _: &ConstructedValue,
        _: &mut Budget,
        _: &Location,
    ) -> Result<(), QueryError> {
        Ok(())
    }
    fn failure(&mut self, calls: &[(usize, Range<usize>)], omitted: usize) {
        self.calls.append(calls, omitted);
    }
}
fn native_view<'v, C, H: ProgramHost<C>>(
    value: &'v NativeView<H::Value>,
    host: &H,
) -> &'v H::Value {
    value.native(
        |v| host.capture_record(v),
        |v| host.tuple_view(v),
        |v| host.positional_view(v),
    )
}

struct Arguments<'r, 'a, C, H: FunctionHost<C>> {
    host: &'r H,
    context: &'r mut C,
    bindings: &'r Bindings<H::Value>,
    contracts: &'r BTreeMap<&'a str, &'a DeclaredType<Kind<C, H>>>,
    prepared: &'r BTreeMap<usize, Operand<Kind<C, H>>>,
    body_prepared: &'r [BTreeMap<usize, Operand<Kind<C, H>>>],
    worklists: &'r [Option<DeclaredType<Kind<C, H>>>],
    source_function: Option<usize>,
    bodies: &'a Bodies<'a, C, H>,
    arguments: &'a [PreparedArgument<'a, Query<C, H>>],
    declared: &'r [usize],
    argument_kinds: &'r BTreeMap<usize, Kind<C, H>>,
    depth: usize,
    limit: usize,
    calls: &'r mut CallTrace,
}
impl<'a, C, H: FunctionHost<C>> Arguments<'_, 'a, C, H> {
    fn run(
        &mut self,
        expression: &ValueExpression<Query<C, H>>,
        input: &H::Value,
        bindings: Option<&Bindings<H::Value>>,
        budget: &mut Budget,
    ) -> Result<HostValue<'a, C, H>, EvaluationError<H::Error>> {
        let id = expression as *const _ as usize;
        budget.charge(
            self.declared.len() + 1,
            Location::Query(expression.range.clone()),
        )?;
        if !self.declared.contains(&id) {
            return Err(QueryError::query(
                expression.range.clone(),
                "argument was not declared by this native stage",
            )
            .into());
        }
        let argument = self
            .arguments
            .iter()
            .find(|a| std::ptr::eq(a.source, expression))
            .ok_or_else(|| {
                QueryError::query(
                    expression.range.clone(),
                    "argument was not prepared in this request",
                )
            })?;
        let mut runtime = Runtime {
            host: self.host,
            context: self.context,
            bindings: bindings.unwrap_or(self.bindings),
            contracts: self.contracts,
            prepared: self.prepared,
            body_prepared: self.body_prepared,
            worklists: self.worklists,
            source_function: self.source_function,
            relative: Some(input),
            limit: self.limit,
            calls: self.calls,
        };
        execution::execute(
            &argument.expression,
            &argument.names,
            self.bodies,
            &mut runtime,
            budget,
            self.limit,
            self.depth,
        )
    }
}
impl<C, H: FunctionHost<C>> NativeArguments<C, H> for Arguments<'_, '_, C, H> {
    fn parts(&mut self) -> (&mut C, &Bindings<H::Value>) {
        (self.context, self.bindings)
    }
    fn evaluate(
        &mut self,
        expression: &ValueExpression<Query<C, H>>,
        input: H::Value,
        budget: &mut Budget,
    ) -> Result<ConstructedRead, EvaluationError<H::Error>> {
        let value = self.run(expression, &input, None, budget)?;
        let location = Location::Query(expression.range.clone());
        let declaration = if let Some(contract) = value.contract {
            if crate::runtime_types::contains_native(contract, budget, &location)? {
                return Err(QueryError::query(
                    expression.range.clone(),
                    "native argument requires an explicit scalar projection",
                )
                .into());
            }
            Some(crate::runtime_types::constructed_declaration(
                contract, budget, &location,
            )?)
        } else {
            None
        };
        let value = match value.data {
            Data::Constructed(value) => value,
            Data::Native(view) => {
                let data = view
                    .constructed(
                        |v| self.host.constructed_value(v),
                        |v| self.host.capture_record(v),
                        |v| self.host.tuple_view(v),
                        |v| self.host.positional_view(v),
                        budget,
                        &location,
                    )?
                    .ok_or_else(|| {
                        QueryError::query(
                            expression.range.clone(),
                            "native argument requires an explicit scalar projection",
                        )
                    })?;
                RuntimeValue::Owned(data.materialize(budget, &location)?)
            }
        };
        Ok(ConstructedRead::from_runtime(value, location, declaration))
    }
    fn evaluate_predicate(
        &mut self,
        expression: &ValueExpression<Query<C, H>>,
        input: H::Value,
        captures: Option<&Bindings<H::Value>>,
        budget: &mut Budget,
    ) -> Result<bool, EvaluationError<H::Error>> {
        let value = self.run(expression, &input, captures, budget)?;
        let Data::Constructed(value) = value.data else {
            return Err(QueryError::query(
                expression.range.clone(),
                "predicate needs a fixed Boolean",
            )
            .into());
        };
        crate::value::boolean(
            value.materialize(budget, &Location::Query(expression.range.clone()))?,
            &Location::Query(expression.range.clone()),
        )
        .map_err(Into::into)
    }
    fn evaluate_native(
        &mut self,
        expression: &ValueExpression<Query<C, H>>,
        input: H::Value,
        budget: &mut Budget,
    ) -> Result<crate::NativeRead<H::Value, Kind<C, H>>, EvaluationError<H::Error>> {
        let value = self.run(expression, &input, None, budget)?;
        self.native_read(value, budget, &expression.range)
    }
    fn evaluate_match_value(
        &mut self,
        expression: &ValueExpression<Query<C, H>>,
        input: H::Value,
        bindings: &Bindings<H::Value>,
        budget: &mut Budget,
    ) -> Result<crate::NativeRead<H::Value, Kind<C, H>>, EvaluationError<H::Error>> {
        let value = self.run(expression, &input, Some(bindings), budget)?;
        self.native_read(value, budget, &expression.range)
    }
    fn evaluate_projection(
        &mut self,
        projection: &crate::Projection<Query<C, H>>,
        input: H::Value,
        budget: &mut Budget,
    ) -> Result<crate::ConstructedResult, EvaluationError<H::Error>> {
        let range = &projection.subject.range;
        budget.within_evaluation(1, Location::Query(range.clone()), |budget| {
            if self
                .bindings
                .iter()
                .any(|(name, _)| name == projection.subject.value)
            {
                return Err(QueryError::query(
                    range.clone(),
                    "projection subject shadows an existing binding",
                )
                .into());
            }
            crate::projection::admit_slots::<Vec<ValueType>>(1, budget, range)?;
            let mut positions = vec![Vec::new()];
            for (index, (_, expression)) in projection.fields.iter().enumerate() {
                crate::projection::check_projection_label(projection, index, budget)?;
                let id = expression as *const _ as usize;
                budget.charge(
                    self.declared.len() + self.arguments.len() + 1,
                    Location::Query(expression.range.clone()),
                )?;
                if !self.declared.contains(&id)
                    || !self
                        .arguments
                        .iter()
                        .any(|argument| std::ptr::eq(argument.source, expression))
                {
                    return Err(QueryError::query(
                        expression.range.clone(),
                        "projection requires every written prepared field",
                    )
                    .into());
                }
                let kind = self.argument_kinds.get(&id).ok_or_else(|| {
                    QueryError::query(
                        expression.range.clone(),
                        "projection field kind was not prepared",
                    )
                })?;
                let types = self
                    .host
                    .scalar_types(kind, budget, &expression.range)?
                    .ok_or_else(|| {
                        QueryError::query(
                            expression.range.clone(),
                            "native handles require an explicit scalar projection",
                        )
                    })?;
                positions = crate::value::extend_type_positions(
                    &positions,
                    &types,
                    budget,
                    &Location::Query(expression.range.clone()),
                )?;
            }
            let types = crate::projection::projection_result_types(projection, positions, budget)?;
            let bindings = self
                .bindings
                .with_shared_values(BTreeMap::new(), budget, range)?;
            let subjects = self.host.subjects(input, self.context, budget, range)?;
            let value = crate::projection::projection_rows(
                projection,
                subjects,
                &bindings,
                self,
                budget,
                |index, local, runner, budget| {
                    let expression = &projection.fields[index].1;
                    let relative = local.get(&projection.subject.value, range.clone())?;
                    let value = runner.run(expression, relative, Some(local), budget)?;
                    let read = runner.native_read(value, budget, &expression.range)?;
                    let value = match std::sync::Arc::try_unwrap(read.into_shared()) {
                        Ok(value) => value,
                        Err(value) => runner.host.copy_value(
                            &value,
                            runner.context,
                            budget,
                            &expression.range,
                        )?,
                    };
                    runner
                        .host
                        .project_value(value, runner.context, budget, &expression.range)
                },
            )?;
            Ok(crate::ConstructedResult { value, types })
        })
    }
}
impl<C, H: FunctionHost<C>> Arguments<'_, '_, C, H> {
    #[expect(
        clippy::type_complexity,
        reason = "The selected argument retains the adapter's native value, kind and error types"
    )]
    fn native_read(
        &mut self,
        value: HostValue<'_, C, H>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<crate::NativeRead<H::Value, Kind<C, H>>, EvaluationError<H::Error>> {
        let location = Location::Query(range.clone());
        let declaration = value
            .contract
            .map(|contract| crate::runtime_types::copy_declaration(contract, budget, &location))
            .transpose()?;
        let value = match value.data {
            Data::Native(owner) => {
                if let Some(data) = owner.constructed(
                    |v| self.host.constructed_value(v),
                    |v| self.host.capture_record(v),
                    |v| self.host.tuple_view(v),
                    |v| self.host.positional_view(v),
                    budget,
                    &location,
                )? {
                    let value = data.materialize(budget, &location)?;
                    let types = vec![constructed_value_type(&value, budget, location.clone())?];
                    crate::projection::admit_slots::<H::Value>(1, budget, range)?;
                    std::sync::Arc::new(self.host.lift_constructed(
                        value,
                        types,
                        self.context,
                        budget,
                        range,
                    )?)
                } else if owner.path.is_empty() {
                    owner.owner
                } else {
                    budget.charge(owner.path.len(), location.clone())?;
                    std::sync::Arc::new(self.host.copy_value(
                        native_view::<C, H>(&owner, self.host),
                        self.context,
                        budget,
                        range,
                    )?)
                }
            }
            Data::Constructed(data) => {
                let value = Value {
                    data: Data::<H::Value>::Constructed(data),
                    contract: value.contract,
                }
                .materialize(budget, &location)?;
                let types = vec![constructed_value_type(&value, budget, location)?];
                crate::projection::admit_slots::<H::Value>(1, budget, range)?;
                std::sync::Arc::new(self.host.lift_constructed(
                    value,
                    types,
                    self.context,
                    budget,
                    range,
                )?)
            }
        };
        Ok(crate::NativeRead { value, declaration })
    }
}

/// Release lowered native function trees without recursively dropping value
/// expression wrappers. Opaque stage payloads retain their host's disposal policy.
pub fn dispose_functions<S, O, E, K>(functions: Vec<FunctionDeclaration<Expression<S, O, E>, K>>) {
    for function in functions {
        for (_, value) in function.bindings {
            dispose_native_value(value);
        }
        dispose_native_value(function.value);
        for parameter in function.parameters {
            dispose_declaration(parameter.value.declaration);
        }
        dispose_declaration(function.result.value);
    }
}
/// Release native pattern-function trees and nested patterns iteratively.
pub fn dispose_pattern_functions<S, O, E, K>(
    functions: Vec<PatternFunctionDeclaration<Expression<S, O, E>, K>>,
) {
    for function in functions {
        dispose_native_value(function.value);
        for parameter in function.parameters {
            crate::dispose_pattern(parameter.value.pattern);
            dispose_declaration(parameter.value.declaration);
        }
        dispose_declaration(function.result.value);
    }
}

pub(crate) fn dispose_declaration<K>(declaration: DeclaredType<K>) {
    let mut pending = vec![declaration];
    while let Some(declaration) = pending.pop() {
        match declaration {
            DeclaredType::Optional(child)
            | DeclaredType::Array(child)
            | DeclaredType::Sequence(child)
            | DeclaredType::Keyed(child)
            | DeclaredType::Queue(child) => pending.push(*child),
            DeclaredType::Tuple(children) => pending.extend(children),
            DeclaredType::Record(fields) => {
                pending.extend(fields.into_iter().map(|(_, value)| value))
            }
            DeclaredType::Boolean
            | DeclaredType::Integer
            | DeclaredType::Float
            | DeclaredType::String
            | DeclaredType::Member(_)
            | DeclaredType::Set(_)
            | DeclaredType::Native(_)
            | DeclaredType::IdentitySet(_) => {}
        }
    }
}